From c2de5c5ff4fa4c07f9c6721b540832d566778b52 Mon Sep 17 00:00:00 2001 From: alexandre Date: Tue, 2 May 2023 07:28:59 +0200 Subject: [PATCH 001/427] 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 002/427] 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 003/427] 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 004/427] 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 005/427] 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 006/427] 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 007/427] 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 008/427] 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 009/427] 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 010/427] 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 6e4d7e8b01682e3327c82213d4b44a0cb12b30ec Mon Sep 17 00:00:00 2001 From: alexandre Date: Tue, 6 Jun 2023 10:31:08 +0200 Subject: [PATCH 011/427] refs #5749 added id --- db/changes/232401/00-zoneIncluded.sql | 27 +++++++++++++++++++ .../back/methods/zone/toggleIsIncluded.js | 15 +++++++---- modules/zone/back/models/zone-included.json | 4 +-- 3 files changed, 39 insertions(+), 7 deletions(-) create mode 100644 db/changes/232401/00-zoneIncluded.sql diff --git a/db/changes/232401/00-zoneIncluded.sql b/db/changes/232401/00-zoneIncluded.sql new file mode 100644 index 000000000..592350629 --- /dev/null +++ b/db/changes/232401/00-zoneIncluded.sql @@ -0,0 +1,27 @@ +ALTER TABLE `vn`.`zoneIncluded` + ADD COLUMN `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT FIRST, + DROP PRIMARY KEY, + DROP FOREIGN KEY `zoneFk2`, + DROP FOREIGN KEY `zoneGeoFk2`, + DROP KEY `geoFk_idx`, + ADD PRIMARY KEY (`id`), + ADD CONSTRAINT `zoneIncluded_FK_1` FOREIGN KEY (zoneFk) REFERENCES `vn`.`zone`(id) ON DELETE CASCADE ON UPDATE CASCADE, + ADD CONSTRAINT `zoneIncluded_FK_2` FOREIGN KEY (geoFk) REFERENCES `vn`.`zoneGeo`(id) ON DELETE CASCADE ON UPDATE CASCADE, + ADD CONSTRAINT `unique_zone_geo` UNIQUE (`zoneFk`, `geoFk`); + +DROP TRIGGER IF EXISTS `vn`.`zoneIncluded_afterDelete`; +USE `vn`; + +DELIMITER $$ +$$ +CREATE DEFINER=`root`@`localhost` TRIGGER `vn`.`zoneIncluded_afterDelete` + AFTER DELETE ON `zoneIncluded` + FOR EACH ROW +BEGIN + INSERT INTO zoneLog + SET `action` = 'delete', + `changedModel` = 'ZoneIncluded', + `changedModelId` = OLD.id, + `userFk` = account.myUser_getId(); +END$$ +DELIMITER ; diff --git a/modules/zone/back/methods/zone/toggleIsIncluded.js b/modules/zone/back/methods/zone/toggleIsIncluded.js index bf8c86f46..06532e5c0 100644 --- a/modules/zone/back/methods/zone/toggleIsIncluded.js +++ b/modules/zone/back/methods/zone/toggleIsIncluded.js @@ -37,11 +37,16 @@ module.exports = Self => { if (isIncluded === undefined) return models.ZoneIncluded.destroyAll({zoneFk: id, geoFk: geoId}, myOptions); else { - return models.ZoneIncluded.upsert({ - zoneFk: id, - geoFk: geoId, - isIncluded: isIncluded - }, myOptions); + const zoneIncluded = await models.ZoneIncluded.findOne({where: {zoneFk: id, geoFk: geoId}}, myOptions); + if (zoneIncluded) + return zoneIncluded.updateAttribute('isIncluded', isIncluded, myOptions); + else { + return models.ZoneIncluded.create({ + zoneFk: id, + geoFk: geoId, + isIncluded: isIncluded + }, myOptions); + } } }; }; diff --git a/modules/zone/back/models/zone-included.json b/modules/zone/back/models/zone-included.json index 61633a3c7..deba73f34 100644 --- a/modules/zone/back/models/zone-included.json +++ b/modules/zone/back/models/zone-included.json @@ -7,8 +7,8 @@ } }, "properties": { - "zoneFk": { - "id": true, + "id": { + "id": true, "type": "number" }, "isIncluded": { From be973138566e555c3e5f54f0ed78cdfa7257d302 Mon Sep 17 00:00:00 2001 From: jgallego Date: Wed, 7 Jun 2023 15:40:25 +0200 Subject: [PATCH 012/427] refs #4059 --- db/changes/232001/00-aclClient.sql | 40 +++++++++++++++++++++++++++++ db/changes/232001/01-aclAccount.sql | 13 ++++++++++ 2 files changed, 53 insertions(+) create mode 100644 db/changes/232001/00-aclClient.sql create mode 100644 db/changes/232001/01-aclAccount.sql diff --git a/db/changes/232001/00-aclClient.sql b/db/changes/232001/00-aclClient.sql new file mode 100644 index 000000000..dec6f6136 --- /dev/null +++ b/db/changes/232001/00-aclClient.sql @@ -0,0 +1,40 @@ +-- No encuentro este back +DELETE FROM salix.ACL WHERE property = 'activeWorkersWithRole'; +DELETE FROM salix.ACL WHERE model = 'Client' AND property = '*'; + +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES ('Client','findOne','READ','ALLOW','ROLE','employee'); +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES ('Client','findById','READ','ALLOW','ROLE','employee'); +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES ('Client','find','READ','ALLOW','ROLE','employee'); +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES ('Client','exists','READ','ALLOW','ROLE','employee'); + +DELETE FROM salix.ACL WHERE model = 'Client' AND accessType = '*' AND property IN ( + 'campaignMetricsEmail', + 'campaignMetricsPdf', + 'clientDebtStatementEmail', + 'clientDebtStatementHtml', + 'clientDebtStatementPdf', + 'clientWelcomeEmail', + 'clientWelcomeHtml', + 'consumptionSendQueued', + 'creditRequestEmail', + 'creditRequestHtml', + 'creditRequestPdf', + 'getClientOrSupplierReference', + 'incotermsAuthorizationEmail', + 'incotermsAuthorizationHtml', + 'incotermsAuthorizationPdf', + 'letterDebtorNdEmail', + 'letterDebtorNdHtml', + 'letterDebtorPdf', + 'letterDebtorStEmail', + 'letterDebtorStHtml', + 'printerSetupEmail', + 'printerSetupHtml', + 'sepaCoreEmail', + 'setPassword', + 'updateUser', + 'uploadFile'); \ No newline at end of file diff --git a/db/changes/232001/01-aclAccount.sql b/db/changes/232001/01-aclAccount.sql new file mode 100644 index 000000000..f618ca842 --- /dev/null +++ b/db/changes/232001/01-aclAccount.sql @@ -0,0 +1,13 @@ +DELETE FROM salix.ACL WHERE model = 'Account' AND property = '*'; + +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES ('Account','findOne','READ','ALLOW','ROLE','employee'); +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES ('Account','findById','READ','ALLOW','ROLE','employee'); +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES ('Account','find','READ','ALLOW','ROLE','employee'); +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES ('Account','exists','READ','ALLOW','ROLE','employee'); + +DELETE FROM salix.ACL WHERE id=529; +-- 529 VnUser changePassword WRITE ALLOW ROLE account \ No newline at end of file From c9c9b64884c5bb05d240378a954052c48cf49119 Mon Sep 17 00:00:00 2001 From: carlossa Date: Mon, 12 Jun 2023 14:57:41 +0200 Subject: [PATCH 013/427] refs #5660 deliveryAssit --- modules/supplier/front/address/create/index.html | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/modules/supplier/front/address/create/index.html b/modules/supplier/front/address/create/index.html index 4d66b70f0..e561501c0 100644 --- a/modules/supplier/front/address/create/index.html +++ b/modules/supplier/front/address/create/index.html @@ -42,7 +42,7 @@ show-field="code" rule> - {{code}} - {{town.name}} ({{town.province.name}}, + {{code}} - {{town.name}} ({{town.province.name}}, {{town.province.country.country}}) @@ -50,12 +50,12 @@ icon="add_circle" vn-tooltip="New postcode" ng-click="postcode.open()" - vn-acl="deliveryBoss" + vn-acl="deliveryAssist" vn-acl-action="remove"> - - \ No newline at end of file + From 908799adeeebc1ce77d4e6bd7bf87b5868f90d17 Mon Sep 17 00:00:00 2001 From: carlossa Date: Mon, 12 Jun 2023 14:58:28 +0200 Subject: [PATCH 014/427] refs #5660 deliveryAssit --- db/changes/232601/00-deliveryAssistantACL.sql | 7 +++++ .../00-useSpecificsAcls.sql | 4 +-- .../01-deliveryAssistantInheritRole.sql | 23 ++++++++++++++++ db/dump/dumpedFixtures.sql | 4 +-- e2e/paths/02-client/01_create_client.spec.js | 2 +- e2e/paths/03-worker/06_create.spec.js | 2 +- e2e/paths/11-zone/01_basic-data.spec.js | 3 ++- e2e/paths/11-zone/02_descriptor.spec.js | 2 +- .../client/front/address/create/index.html | 12 ++++----- modules/client/front/address/edit/index.html | 18 ++++++------- modules/client/front/create/index.html | 12 ++++----- modules/client/front/fiscal-data/index.html | 2 +- modules/client/front/postcode/index.html | 6 ++--- modules/route/front/descriptor/index.html | 16 ++++++------ modules/route/front/tickets/index.html | 8 +++--- .../supplier/front/address/edit/index.html | 12 ++++----- modules/supplier/front/fiscal-data/index.html | 2 +- modules/worker/front/create/index.html | 2 +- modules/zone/front/basic-data/index.html | 26 +++++++++---------- modules/zone/front/index/index.html | 6 ++--- modules/zone/front/location/index.html | 6 ++--- 21 files changed, 103 insertions(+), 72 deletions(-) create mode 100644 db/changes/232601/00-deliveryAssistantACL.sql rename db/changes/{232401 => 232601}/00-useSpecificsAcls.sql (99%) create mode 100644 db/changes/232601/01-deliveryAssistantInheritRole.sql diff --git a/db/changes/232601/00-deliveryAssistantACL.sql b/db/changes/232601/00-deliveryAssistantACL.sql new file mode 100644 index 000000000..6c829867a --- /dev/null +++ b/db/changes/232601/00-deliveryAssistantACL.sql @@ -0,0 +1,7 @@ +-- Auto-generated SQL script #202306121356 +UPDATE `account`.`role` + SET `description` = 'Asistente de envios' + WHERE `name` = 'deliveryAssist'; + + + diff --git a/db/changes/232401/00-useSpecificsAcls.sql b/db/changes/232601/00-useSpecificsAcls.sql similarity index 99% rename from db/changes/232401/00-useSpecificsAcls.sql rename to db/changes/232601/00-useSpecificsAcls.sql index 0d17ca948..cfe60ec9c 100644 --- a/db/changes/232401/00-useSpecificsAcls.sql +++ b/db/changes/232601/00-useSpecificsAcls.sql @@ -3,11 +3,11 @@ INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `pri ('Ticket', 'editDiscount', 'WRITE', 'ALLOW', 'ROLE', 'claimManager'), ('Ticket', 'editDiscount', 'WRITE', 'ALLOW', 'ROLE', 'salesPerson'), ('Ticket', 'isRoleAdvanced', '*', 'ALLOW', 'ROLE', 'salesAssistant'), - ('Ticket', 'isRoleAdvanced', '*', 'ALLOW', 'ROLE', 'deliveryBoss'), + ('Ticket', 'isRoleAdvanced', '*', 'ALLOW', 'ROLE', 'deliveryAssist'), ('Ticket', 'isRoleAdvanced', '*', 'ALLOW', 'ROLE', 'buyer'), ('Ticket', 'isRoleAdvanced', '*', 'ALLOW', 'ROLE', 'claimManager'), ('Ticket', 'deleteTicketWithPartPrepared', 'WRITE', 'ALLOW', 'ROLE', 'salesAssistant'), - ('Ticket', 'editZone', 'WRITE', 'ALLOW', 'ROLE', 'deliveryBoss'), + ('Ticket', 'editZone', 'WRITE', 'ALLOW', 'ROLE', 'deliveryAssist'), ('State', 'editableStates', 'READ', 'ALLOW', 'ROLE', 'employee'), ('State', 'seeEditableStates', 'READ', 'ALLOW', 'ROLE', 'administrative'), ('State', 'seeEditableStates', 'READ', 'ALLOW', 'ROLE', 'production'), diff --git a/db/changes/232601/01-deliveryAssistantInheritRole.sql b/db/changes/232601/01-deliveryAssistantInheritRole.sql new file mode 100644 index 000000000..ad4d7dd1e --- /dev/null +++ b/db/changes/232601/01-deliveryAssistantInheritRole.sql @@ -0,0 +1,23 @@ +-- -- Auto-generated SQL script #202306121403 +-- INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) +-- VALUES (117,1); +-- INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) +-- VALUES (117,2); +-- INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) +-- VALUES (117,3); +-- INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) +-- VALUES (117,6); +-- INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) +-- VALUES (117,11); +-- INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) +-- VALUES (117,13); +-- INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) +-- VALUES (117,33); +-- INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) +-- VALUES (117,56); +-- INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) +-- VALUES (117,57); +-- INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) +-- VALUES (117,70); +-- INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) +-- VALUES (117,76); diff --git a/db/dump/dumpedFixtures.sql b/db/dump/dumpedFixtures.sql index abb5516f7..67b77d587 100644 --- a/db/dump/dumpedFixtures.sql +++ b/db/dump/dumpedFixtures.sql @@ -78,7 +78,7 @@ USE `account`; LOCK TABLES `role` WRITE; /*!40000 ALTER TABLE `role` DISABLE KEYS */; -INSERT INTO `role` VALUES (1,'employee','Empleado básico',1,'2017-05-19 07:04:58','2017-11-29 10:06:31',NULL),(2,'customer','Privilegios básicos de un cliente',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(3,'agency','Consultar tablas de predicciones de bultos',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(5,'administrative','Tareas relacionadas con la contabilidad',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(6,'guest','Privilegios para usuarios sin cuenta',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(9,'developer','Desarrolladores del sistema',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(11,'account','Privilegios relacionados con el login',0,'2017-05-19 07:04:58','2017-09-20 17:06:35',NULL),(13,'teamBoss','Jefe de equipo/departamento',1,'2017-05-19 07:04:58','2021-06-30 13:29:30',NULL),(15,'logistic','Departamento de compras, responsables de la logistica',1,'2017-05-19 07:04:58','2018-02-12 10:50:10',NULL),(16,'logisticBoss','Jefe del departamento de logística',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(17,'adminBoss','Jefe del departamento de administración',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(18,'salesPerson','Departamento de ventas',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(19,'salesBoss','Jefe del departamento de ventas',1,'2017-05-19 07:04:58','2017-08-16 12:38:27',NULL),(20,'manager','Gerencia',1,'2017-06-01 14:57:02','2022-07-29 07:36:15',NULL),(21,'salesAssistant','Jefe auxiliar de ventas',1,'2017-08-16 12:40:52','2017-08-16 12:40:52',NULL),(22,'teamManager','Jefe de departamento con privilegios de auxiliar de venta.',1,'2017-09-07 09:08:12','2017-09-07 09:08:12',NULL),(30,'financialBoss','Director finaciero',1,'2017-09-21 11:05:36','2017-09-21 11:05:36',NULL),(31,'freelancer','Trabajadores por cuenta ajena',1,'2017-10-10 12:57:26','2017-10-10 12:59:27',NULL),(32,'ett','Trabajadores de empresa temporal',1,'2017-10-10 12:58:58','2017-10-10 12:59:20',NULL),(33,'invoicing','Personal con acceso a facturación',0,'2018-01-29 16:43:34','2018-01-29 16:43:34',NULL),(34,'agencyBoss','Jefe/a del departamento de agencias',1,'2018-01-29 16:44:39','2018-02-23 07:58:53',NULL),(35,'buyer','Departamento de compras',1,'2018-02-12 10:35:42','2018-02-12 10:35:42',NULL),(36,'replenisher','Trabajadores de camara',1,'2018-02-16 14:07:10','2019-04-12 05:38:08',NULL),(37,'hr','Gestor/a de recursos humanos',1,'2018-02-22 17:34:53','2018-02-22 17:34:53',NULL),(38,'hrBoss','Jefe/a de recursos humanos',1,'2018-02-22 17:35:09','2018-02-22 17:35:09',NULL),(39,'adminAssistant','Jefe auxiliar administrativo',1,'2018-02-23 10:37:36','2018-02-23 10:38:41',NULL),(40,'handmade','Departamento de confección',1,'2018-02-23 11:14:53','2018-02-23 11:39:12',NULL),(41,'handmadeBoss','Jefe de departamento de confección',1,'2018-02-23 11:15:09','2018-02-23 11:39:26',NULL),(42,'artificial','Departamento de artificial',1,'2018-02-23 11:39:59','2018-02-23 11:39:59',NULL),(43,'artificialBoss','Jefe del departamento de artificial',1,'2018-02-23 11:40:16','2018-02-23 11:40:16',NULL),(44,'accessory','Departamento de complementos',1,'2018-02-23 11:41:12','2018-02-23 11:41:12',NULL),(45,'accessoryBoss','Jefe del departamento de complementos',1,'2018-02-23 11:41:23','2018-02-23 11:41:23',NULL),(47,'cooler','Empleados de cámara',1,'2018-02-23 13:08:18','2018-02-23 13:08:18',NULL),(48,'coolerBoss','Jefe de cámara',1,'2018-02-23 13:12:01','2023-03-13 08:49:43',NULL),(49,'production','Empleado de producción',1,'2018-02-26 15:28:23','2021-02-12 09:42:35',NULL),(50,'productionBoss','Jefe de producción',1,'2018-02-26 15:34:12','2018-02-26 15:34:12',NULL),(51,'marketing','Departamento de marketing',1,'2018-03-01 07:28:39','2018-03-01 07:28:39',NULL),(52,'marketingBoss','Jefe del departamento de marketing',1,'2018-03-01 07:28:57','2018-03-01 07:28:57',NULL),(53,'insurance','Gestor de seguros de cambio',0,'2018-03-05 07:44:35','2019-02-01 13:47:57',NULL),(54,'itemPicker','Sacador en cámara',1,'2018-03-05 12:08:17','2018-03-05 12:08:17',NULL),(55,'itemPickerBoss','Jefe de sacadores',1,'2018-03-05 12:08:31','2018-03-05 12:08:31',NULL),(56,'delivery','Personal de reparto',1,'2018-05-30 06:07:02','2018-05-30 06:07:02',NULL),(57,'deliveryBoss','Jefe de personal de reparto',1,'2018-05-30 06:07:19','2018-05-30 06:07:19',NULL),(58,'packager','Departamento encajadores',1,'2019-01-21 12:43:45','2019-01-21 12:43:45',NULL),(59,'packagerBoss','Jefe departamento encajadores',1,'2019-01-21 12:44:10','2019-01-21 12:44:10',NULL),(60,'productionAssi','Tareas relacionadas con producción y administración',1,'2019-01-29 13:29:01','2019-01-29 13:29:01',NULL),(61,'replenisherBos','Jefe de Complementos/Camara',1,'2019-07-01 06:44:07','2019-07-01 06:44:07',NULL),(62,'noLogin','Role without login access to MySQL',0,'2019-07-01 06:50:19','2019-07-02 13:42:05',NULL),(64,'balanceSheet','Consulta de Balance',0,'2019-07-16 12:12:08','2019-07-16 12:12:08',NULL),(65,'officeBoss','Jefe de filial',1,'2019-08-02 06:54:26','2019-08-02 06:54:26',NULL),(66,'sysadmin','Administrador de sistema',1,'2019-08-08 06:58:56','2019-08-08 06:58:56',NULL),(67,'adminOfficer','categoria profesional oficial de administración',1,'2020-01-03 08:09:23','2020-01-03 08:09:23',NULL),(69,'coolerAssist','Asistente de cámara con permiso compras',1,'2020-02-05 12:36:09','2023-03-13 08:50:07',NULL),(70,'trainee','Alumno de prácticas',1,'2020-03-04 11:00:25','2020-03-04 11:00:25',NULL),(71,'checker','Rol de revisor con privilegios de itemPicker',1,'2020-10-02 10:50:07','2020-10-02 10:50:07',NULL),(72,'claimManager','Personal de reclamaciones',1,'2020-10-13 10:01:32','2020-10-26 07:29:46',NULL),(73,'financial','Departamento de finanzas',1,'2020-11-16 09:30:27','2020-11-16 09:30:27',NULL),(74,'userPhotos','Privilegios para subir fotos de usuario',1,'2021-02-03 10:24:27','2021-02-03 10:24:27',NULL),(75,'catalogPhotos','Privilegios para subir fotos del catálogo',1,'2021-02-03 10:24:27','2021-02-03 10:24:27',NULL),(76,'chat','Rol para utilizar el rocket chat',1,'2020-11-27 13:06:50','2020-12-17 07:49:41',NULL),(100,'root','Rol con todos los privilegios',0,'2018-04-23 14:33:36','2020-11-12 06:50:07',NULL),(101,'buyerBoss','Jefe del departamento de compras',1,'2021-06-16 09:53:17','2021-06-16 09:53:17',NULL),(102,'preservedBoss','Responsable preservado',1,'2021-09-14 13:45:37','2021-09-14 13:45:37',NULL),(103,'it','Departamento de informática',1,'2021-11-11 09:48:22','2021-11-11 09:48:22',NULL),(104,'itBoss','Jefe de departamento de informática',1,'2021-11-11 09:48:49','2021-11-11 09:48:49',NULL),(105,'grant','Adjudicar roles a usuarios',1,'2021-11-11 12:41:09','2021-11-11 12:41:09',NULL),(106,'ext','Usuarios externos de la Base de datos',1,'2021-11-23 14:51:16','2021-11-23 14:51:16',NULL),(107,'productionPlus','Creado para pepe por orden de Juanvi',1,'2022-02-08 06:47:10','2022-02-08 06:47:10',NULL),(108,'system','System user',1,'2022-05-16 08:09:51','2022-05-16 08:09:51',NULL),(109,'salesTeamBoss','Jefe de equipo de comerciales',1,'2022-06-14 13:45:56','2022-06-14 13:45:56',NULL),(110,'palletizer','Paletizadores',1,'2022-12-02 12:56:22','2022-12-02 12:56:30',NULL),(111,'entryEditor','Entry editor',1,'2023-01-13 11:21:55','2023-01-13 11:21:55',NULL),(112,'maintenance','Personal de mantenimiento',1,'2023-01-19 06:23:35','2023-01-19 06:23:35',NULL),(114,'maintenanceBos','Jefe de mantenimiento',1,'2023-01-19 06:31:16','2023-05-12 08:47:34',19294),(115,'itManagement','TI management',1,'2023-03-29 07:27:55','2023-03-29 07:28:04',NULL); +INSERT INTO `role` VALUES (1,'employee','Empleado básico',1,'2017-05-19 07:04:58','2017-11-29 10:06:31',NULL),(2,'customer','Privilegios básicos de un cliente',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(3,'agency','Consultar tablas de predicciones de bultos',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(5,'administrative','Tareas relacionadas con la contabilidad',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(6,'guest','Privilegios para usuarios sin cuenta',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(9,'developer','Desarrolladores del sistema',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(11,'account','Privilegios relacionados con el login',0,'2017-05-19 07:04:58','2017-09-20 17:06:35',NULL),(13,'teamBoss','Jefe de equipo/departamento',1,'2017-05-19 07:04:58','2021-06-30 13:29:30',NULL),(15,'logistic','Departamento de compras, responsables de la logistica',1,'2017-05-19 07:04:58','2018-02-12 10:50:10',NULL),(16,'logisticBoss','Jefe del departamento de logística',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(17,'adminBoss','Jefe del departamento de administración',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(18,'salesPerson','Departamento de ventas',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(19,'salesBoss','Jefe del departamento de ventas',1,'2017-05-19 07:04:58','2017-08-16 12:38:27',NULL),(20,'manager','Gerencia',1,'2017-06-01 14:57:02','2022-07-29 07:36:15',NULL),(21,'salesAssistant','Jefe auxiliar de ventas',1,'2017-08-16 12:40:52','2017-08-16 12:40:52',NULL),(22,'teamManager','Jefe de departamento con privilegios de auxiliar de venta.',1,'2017-09-07 09:08:12','2017-09-07 09:08:12',NULL),(30,'financialBoss','Director finaciero',1,'2017-09-21 11:05:36','2017-09-21 11:05:36',NULL),(31,'freelancer','Trabajadores por cuenta ajena',1,'2017-10-10 12:57:26','2017-10-10 12:59:27',NULL),(32,'ett','Trabajadores de empresa temporal',1,'2017-10-10 12:58:58','2017-10-10 12:59:20',NULL),(33,'invoicing','Personal con acceso a facturación',0,'2018-01-29 16:43:34','2018-01-29 16:43:34',NULL),(34,'agencyBoss','Jefe/a del departamento de agencias',1,'2018-01-29 16:44:39','2018-02-23 07:58:53',NULL),(35,'buyer','Departamento de compras',1,'2018-02-12 10:35:42','2018-02-12 10:35:42',NULL),(36,'replenisher','Trabajadores de camara',1,'2018-02-16 14:07:10','2019-04-12 05:38:08',NULL),(37,'hr','Gestor/a de recursos humanos',1,'2018-02-22 17:34:53','2018-02-22 17:34:53',NULL),(38,'hrBoss','Jefe/a de recursos humanos',1,'2018-02-22 17:35:09','2018-02-22 17:35:09',NULL),(39,'adminAssistant','Jefe auxiliar administrativo',1,'2018-02-23 10:37:36','2018-02-23 10:38:41',NULL),(40,'handmade','Departamento de confección',1,'2018-02-23 11:14:53','2018-02-23 11:39:12',NULL),(41,'handmadeBoss','Jefe de departamento de confección',1,'2018-02-23 11:15:09','2018-02-23 11:39:26',NULL),(42,'artificial','Departamento de artificial',1,'2018-02-23 11:39:59','2018-02-23 11:39:59',NULL),(43,'artificialBoss','Jefe del departamento de artificial',1,'2018-02-23 11:40:16','2018-02-23 11:40:16',NULL),(44,'accessory','Departamento de complementos',1,'2018-02-23 11:41:12','2018-02-23 11:41:12',NULL),(45,'accessoryBoss','Jefe del departamento de complementos',1,'2018-02-23 11:41:23','2018-02-23 11:41:23',NULL),(47,'cooler','Empleados de cámara',1,'2018-02-23 13:08:18','2018-02-23 13:08:18',NULL),(48,'coolerBoss','Jefe de cámara',1,'2018-02-23 13:12:01','2023-03-13 08:49:43',NULL),(49,'production','Empleado de producción',1,'2018-02-26 15:28:23','2021-02-12 09:42:35',NULL),(50,'productionBoss','Jefe de producción',1,'2018-02-26 15:34:12','2018-02-26 15:34:12',NULL),(51,'marketing','Departamento de marketing',1,'2018-03-01 07:28:39','2018-03-01 07:28:39',NULL),(52,'marketingBoss','Jefe del departamento de marketing',1,'2018-03-01 07:28:57','2018-03-01 07:28:57',NULL),(53,'insurance','Gestor de seguros de cambio',0,'2018-03-05 07:44:35','2019-02-01 13:47:57',NULL),(54,'itemPicker','Sacador en cámara',1,'2018-03-05 12:08:17','2018-03-05 12:08:17',NULL),(55,'itemPickerBoss','Jefe de sacadores',1,'2018-03-05 12:08:31','2018-03-05 12:08:31',NULL),(56,'delivery','Personal de reparto',1,'2018-05-30 06:07:02','2018-05-30 06:07:02',NULL),(57,'deliveryAssist','Jefe de personal de reparto',1,'2018-05-30 06:07:19','2018-05-30 06:07:19',NULL),(58,'packager','Departamento encajadores',1,'2019-01-21 12:43:45','2019-01-21 12:43:45',NULL),(59,'packagerBoss','Jefe departamento encajadores',1,'2019-01-21 12:44:10','2019-01-21 12:44:10',NULL),(60,'productionAssi','Tareas relacionadas con producción y administración',1,'2019-01-29 13:29:01','2019-01-29 13:29:01',NULL),(61,'replenisherBos','Jefe de Complementos/Camara',1,'2019-07-01 06:44:07','2019-07-01 06:44:07',NULL),(62,'noLogin','Role without login access to MySQL',0,'2019-07-01 06:50:19','2019-07-02 13:42:05',NULL),(64,'balanceSheet','Consulta de Balance',0,'2019-07-16 12:12:08','2019-07-16 12:12:08',NULL),(65,'officeBoss','Jefe de filial',1,'2019-08-02 06:54:26','2019-08-02 06:54:26',NULL),(66,'sysadmin','Administrador de sistema',1,'2019-08-08 06:58:56','2019-08-08 06:58:56',NULL),(67,'adminOfficer','categoria profesional oficial de administración',1,'2020-01-03 08:09:23','2020-01-03 08:09:23',NULL),(69,'coolerAssist','Asistente de cámara con permiso compras',1,'2020-02-05 12:36:09','2023-03-13 08:50:07',NULL),(70,'trainee','Alumno de prácticas',1,'2020-03-04 11:00:25','2020-03-04 11:00:25',NULL),(71,'checker','Rol de revisor con privilegios de itemPicker',1,'2020-10-02 10:50:07','2020-10-02 10:50:07',NULL),(72,'claimManager','Personal de reclamaciones',1,'2020-10-13 10:01:32','2020-10-26 07:29:46',NULL),(73,'financial','Departamento de finanzas',1,'2020-11-16 09:30:27','2020-11-16 09:30:27',NULL),(74,'userPhotos','Privilegios para subir fotos de usuario',1,'2021-02-03 10:24:27','2021-02-03 10:24:27',NULL),(75,'catalogPhotos','Privilegios para subir fotos del catálogo',1,'2021-02-03 10:24:27','2021-02-03 10:24:27',NULL),(76,'chat','Rol para utilizar el rocket chat',1,'2020-11-27 13:06:50','2020-12-17 07:49:41',NULL),(100,'root','Rol con todos los privilegios',0,'2018-04-23 14:33:36','2020-11-12 06:50:07',NULL),(101,'buyerBoss','Jefe del departamento de compras',1,'2021-06-16 09:53:17','2021-06-16 09:53:17',NULL),(102,'preservedBoss','Responsable preservado',1,'2021-09-14 13:45:37','2021-09-14 13:45:37',NULL),(103,'it','Departamento de informática',1,'2021-11-11 09:48:22','2021-11-11 09:48:22',NULL),(104,'itBoss','Jefe de departamento de informática',1,'2021-11-11 09:48:49','2021-11-11 09:48:49',NULL),(105,'grant','Adjudicar roles a usuarios',1,'2021-11-11 12:41:09','2021-11-11 12:41:09',NULL),(106,'ext','Usuarios externos de la Base de datos',1,'2021-11-23 14:51:16','2021-11-23 14:51:16',NULL),(107,'productionPlus','Creado para pepe por orden de Juanvi',1,'2022-02-08 06:47:10','2022-02-08 06:47:10',NULL),(108,'system','System user',1,'2022-05-16 08:09:51','2022-05-16 08:09:51',NULL),(109,'salesTeamBoss','Jefe de equipo de comerciales',1,'2022-06-14 13:45:56','2022-06-14 13:45:56',NULL),(110,'palletizer','Paletizadores',1,'2022-12-02 12:56:22','2022-12-02 12:56:30',NULL),(111,'entryEditor','Entry editor',1,'2023-01-13 11:21:55','2023-01-13 11:21:55',NULL),(112,'maintenance','Personal de mantenimiento',1,'2023-01-19 06:23:35','2023-01-19 06:23:35',NULL),(114,'maintenanceBos','Jefe de mantenimiento',1,'2023-01-19 06:31:16','2023-05-12 08:47:34',19294),(115,'itManagement','TI management',1,'2023-03-29 07:27:55','2023-03-29 07:28:04',NULL); /*!40000 ALTER TABLE `role` ENABLE KEYS */; UNLOCK TABLES; @@ -164,7 +164,7 @@ USE `salix`; LOCK TABLES `ACL` WRITE; /*!40000 ALTER TABLE `ACL` DISABLE KEYS */; -INSERT INTO `ACL` VALUES (1,'Account','*','*','ALLOW','ROLE','employee'),(3,'Address','*','*','ALLOW','ROLE','employee'),(5,'AgencyService','*','READ','ALLOW','ROLE','employee'),(9,'ClientObservation','*','*','ALLOW','ROLE','employee'),(11,'ContactChannel','*','READ','ALLOW','ROLE','trainee'),(13,'Employee','*','READ','ALLOW','ROLE','employee'),(14,'PayMethod','*','READ','ALLOW','ROLE','trainee'),(16,'FakeProduction','*','READ','ALLOW','ROLE','employee'),(17,'Warehouse','* ','READ','ALLOW','ROLE','trainee'),(18,'State','*','READ','ALLOW','ROLE','employee'),(20,'TicketState','*','*','ALLOW','ROLE','employee'),(24,'Delivery','*','READ','ALLOW','ROLE','employee'),(25,'Zone','*','READ','ALLOW','ROLE','employee'),(26,'ClientCredit','*','*','ALLOW','ROLE','employee'),(27,'ClientCreditLimit','*','READ','ALLOW','ROLE','trainee'),(30,'GreugeType','*','READ','ALLOW','ROLE','trainee'),(31,'Mandate','*','READ','ALLOW','ROLE','trainee'),(32,'MandateType','*','READ','ALLOW','ROLE','trainee'),(33,'Company','*','READ','ALLOW','ROLE','trainee'),(34,'Greuge','*','READ','ALLOW','ROLE','trainee'),(35,'AddressObservation','*','*','ALLOW','ROLE','employee'),(36,'ObservationType','*','*','ALLOW','ROLE','employee'),(37,'Greuge','*','WRITE','ALLOW','ROLE','employee'),(38,'AgencyMode','*','READ','ALLOW','ROLE','employee'),(39,'ItemTag','*','WRITE','ALLOW','ROLE','buyer'),(40,'ItemBotanical','*','WRITE','ALLOW','ROLE','buyer'),(41,'ItemBotanical','*','READ','ALLOW','ROLE','employee'),(42,'ItemPlacement','*','WRITE','ALLOW','ROLE','buyer'),(43,'ItemPlacement','*','WRITE','ALLOW','ROLE','replenisher'),(44,'ItemPlacement','*','READ','ALLOW','ROLE','employee'),(45,'ItemBarcode','*','READ','ALLOW','ROLE','employee'),(46,'ItemBarcode','*','WRITE','ALLOW','ROLE','buyer'),(47,'ItemBarcode','*','WRITE','ALLOW','ROLE','replenisher'),(51,'ItemTag','*','READ','ALLOW','ROLE','employee'),(53,'Item','*','READ','ALLOW','ROLE','employee'),(54,'Item','*','WRITE','ALLOW','ROLE','buyer'),(55,'Recovery','*','READ','ALLOW','ROLE','trainee'),(56,'Recovery','*','WRITE','ALLOW','ROLE','administrative'),(58,'CreditClassification','*','*','ALLOW','ROLE','insurance'),(60,'CreditInsurance','*','*','ALLOW','ROLE','insurance'),(61,'InvoiceOut','*','READ','ALLOW','ROLE','employee'),(62,'Ticket','*','*','ALLOW','ROLE','employee'),(63,'TicketObservation','*','*','ALLOW','ROLE','employee'),(64,'Route','*','READ','ALLOW','ROLE','employee'),(65,'Sale','*','READ','ALLOW','ROLE','employee'),(66,'TicketTracking','*','READ','ALLOW','ROLE','employee'),(68,'TicketPackaging','*','*','ALLOW','ROLE','employee'),(69,'Packaging','*','READ','ALLOW','ROLE','employee'),(70,'Packaging','*','WRITE','ALLOW','ROLE','logistic'),(72,'SaleComponent','*','READ','ALLOW','ROLE','employee'),(73,'Expedition','*','READ','ALLOW','ROLE','employee'),(74,'Expedition','*','WRITE','ALLOW','ROLE','deliveryBoss'),(75,'Expedition','*','WRITE','ALLOW','ROLE','production'),(76,'AnnualAverageInvoiced','*','READ','ALLOW','ROLE','employee'),(77,'WorkerMana','*','READ','ALLOW','ROLE','employee'),(78,'TicketTracking','*','WRITE','ALLOW','ROLE','production'),(79,'TicketTracking','changeState','*','ALLOW','ROLE','employee'),(80,'Sale','deleteSales','*','ALLOW','ROLE','employee'),(81,'Sale','moveToTicket','*','ALLOW','ROLE','employee'),(82,'Sale','updateQuantity','*','ALLOW','ROLE','employee'),(83,'Sale','updatePrice','*','ALLOW','ROLE','employee'),(84,'Sale','updateDiscount','*','ALLOW','ROLE','employee'),(85,'SaleTracking','*','READ','ALLOW','ROLE','employee'),(86,'Order','*','*','ALLOW','ROLE','employee'),(87,'OrderRow','*','*','ALLOW','ROLE','employee'),(88,'ClientContact','*','*','ALLOW','ROLE','employee'),(89,'Sale','moveToNewTicket','*','ALLOW','ROLE','employee'),(90,'Sale','reserve','*','ALLOW','ROLE','employee'),(91,'TicketWeekly','*','READ','ALLOW','ROLE','employee'),(94,'Agency','landsThatDay','*','ALLOW','ROLE','employee'),(96,'ClaimEnd','*','READ','ALLOW','ROLE','employee'),(97,'ClaimEnd','*','WRITE','ALLOW','ROLE','claimManager'),(98,'ClaimBeginning','*','*','ALLOW','ROLE','employee'),(99,'ClaimDevelopment','*','READ','ALLOW','ROLE','employee'),(100,'ClaimDevelopment','*','WRITE','ALLOW','ROLE','claimManager'),(101,'Claim','*','*','ALLOW','ROLE','employee'),(102,'Claim','createFromSales','*','ALLOW','ROLE','employee'),(104,'Item','*','WRITE','ALLOW','ROLE','marketingBoss'),(105,'ItemBarcode','*','WRITE','ALLOW','ROLE','marketingBoss'),(106,'ItemBotanical','*','WRITE','ALLOW','ROLE','marketingBoss'),(108,'ItemPlacement','*','WRITE','ALLOW','ROLE','marketingBoss'),(109,'UserConfig','*','*','ALLOW','ROLE','employee'),(110,'Bank','*','READ','ALLOW','ROLE','trainee'),(111,'ClientLog','*','READ','ALLOW','ROLE','trainee'),(112,'Defaulter','*','READ','ALLOW','ROLE','employee'),(113,'ClientRisk','*','READ','ALLOW','ROLE','trainee'),(114,'Receipt','*','READ','ALLOW','ROLE','trainee'),(115,'Receipt','*','WRITE','ALLOW','ROLE','administrative'),(116,'BankEntity','*','*','ALLOW','ROLE','employee'),(117,'ClientSample','*','*','ALLOW','ROLE','employee'),(118,'WorkerTeam','*','*','ALLOW','ROLE','salesPerson'),(119,'Travel','*','READ','ALLOW','ROLE','employee'),(120,'Travel','*','WRITE','ALLOW','ROLE','buyer'),(121,'Item','regularize','*','ALLOW','ROLE','employee'),(122,'TicketRequest','*','*','ALLOW','ROLE','employee'),(123,'Worker','*','READ','ALLOW','ROLE','employee'),(124,'Client','confirmTransaction','WRITE','ALLOW','ROLE','administrative'),(125,'Agency','getAgenciesWithWarehouse','*','ALLOW','ROLE','employee'),(126,'Client','activeWorkersWithRole','*','ALLOW','ROLE','employee'),(127,'TicketLog','*','READ','ALLOW','ROLE','employee'),(129,'TicketService','*','*','ALLOW','ROLE','employee'),(130,'Expedition','*','WRITE','ALLOW','ROLE','packager'),(131,'CreditInsurance','*','READ','ALLOW','ROLE','trainee'),(132,'CreditClassification','*','READ','ALLOW','ROLE','trainee'),(133,'ItemTag','*','WRITE','ALLOW','ROLE','marketingBoss'),(135,'ZoneGeo','*','READ','ALLOW','ROLE','employee'),(136,'ZoneCalendar','*','READ','ALLOW','ROLE','employee'),(137,'ZoneIncluded','*','READ','ALLOW','ROLE','employee'),(138,'LabourHoliday','*','READ','ALLOW','ROLE','employee'),(139,'LabourHolidayLegend','*','READ','ALLOW','ROLE','employee'),(140,'LabourHolidayType','*','READ','ALLOW','ROLE','employee'),(141,'Zone','*','*','ALLOW','ROLE','logisticBoss'),(142,'ZoneCalendar','*','WRITE','ALLOW','ROLE','deliveryBoss'),(143,'ZoneIncluded','*','*','ALLOW','ROLE','deliveryBoss'),(144,'Stowaway','*','*','ALLOW','ROLE','employee'),(145,'Ticket','getPossibleStowaways','READ','ALLOW','ROLE','employee'),(147,'UserConfigView','*','*','ALLOW','ROLE','employee'),(148,'UserConfigView','*','*','ALLOW','ROLE','employee'),(149,'Sip','*','READ','ALLOW','ROLE','employee'),(150,'Sip','*','WRITE','ALLOW','ROLE','hr'),(151,'Department','*','READ','ALLOW','ROLE','employee'),(152,'Department','*','WRITE','ALLOW','ROLE','hr'),(153,'Route','*','READ','ALLOW','ROLE','employee'),(154,'Route','*','WRITE','ALLOW','ROLE','delivery'),(155,'Calendar','*','READ','ALLOW','ROLE','hr'),(156,'WorkerLabour','*','READ','ALLOW','ROLE','hr'),(157,'Calendar','absences','READ','ALLOW','ROLE','employee'),(158,'ItemTag','*','WRITE','ALLOW','ROLE','accessory'),(160,'TicketServiceType','*','READ','ALLOW','ROLE','employee'),(161,'TicketConfig','*','READ','ALLOW','ROLE','employee'),(162,'InvoiceOut','delete','WRITE','ALLOW','ROLE','invoicing'),(163,'InvoiceOut','book','WRITE','ALLOW','ROLE','invoicing'),(165,'TicketDms','*','*','ALLOW','ROLE','employee'),(167,'Worker','isSubordinate','READ','ALLOW','ROLE','employee'),(168,'Worker','mySubordinates','READ','ALLOW','ROLE','employee'),(169,'WorkerTimeControl','filter','READ','ALLOW','ROLE','employee'),(170,'WorkerTimeControl','addTime','WRITE','ALLOW','ROLE','employee'),(171,'TicketServiceType','*','WRITE','ALLOW','ROLE','administrative'),(172,'Sms','*','READ','ALLOW','ROLE','employee'),(173,'Sms','send','WRITE','ALLOW','ROLE','employee'),(174,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(175,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(176,'Device','*','*','ALLOW','ROLE','employee'),(177,'Device','*','*','ALLOW','ROLE','employee'),(178,'WorkerTimeControl','*','*','ALLOW','ROLE','employee'),(179,'ItemLog','*','READ','ALLOW','ROLE','employee'),(180,'RouteLog','*','READ','ALLOW','ROLE','employee'),(181,'Dms','removeFile','WRITE','ALLOW','ROLE','employee'),(182,'Dms','uploadFile','WRITE','ALLOW','ROLE','employee'),(183,'Dms','downloadFile','READ','ALLOW','ROLE','employee'),(184,'Client','uploadFile','WRITE','ALLOW','ROLE','employee'),(185,'ClientDms','removeFile','WRITE','ALLOW','ROLE','employee'),(186,'ClientDms','*','READ','ALLOW','ROLE','trainee'),(187,'Ticket','uploadFile','WRITE','ALLOW','ROLE','employee'),(190,'Route','updateVolume','WRITE','ALLOW','ROLE','deliveryBoss'),(191,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(192,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(194,'Postcode','*','WRITE','ALLOW','ROLE','deliveryBoss'),(195,'Ticket','addSale','WRITE','ALLOW','ROLE','employee'),(196,'Dms','updateFile','WRITE','ALLOW','ROLE','employee'),(197,'Dms','*','READ','ALLOW','ROLE','trainee'),(198,'ClaimDms','removeFile','WRITE','ALLOW','ROLE','employee'),(199,'ClaimDms','*','READ','ALLOW','ROLE','employee'),(200,'Claim','uploadFile','WRITE','ALLOW','ROLE','employee'),(201,'Sale','updateConcept','WRITE','ALLOW','ROLE','employee'),(202,'Claim','updateClaimAction','WRITE','ALLOW','ROLE','claimManager'),(203,'UserPhone','*','*','ALLOW','ROLE','employee'),(204,'WorkerDms','removeFile','WRITE','ALLOW','ROLE','hr'),(205,'WorkerDms','*','READ','ALLOW','ROLE','hr'),(206,'Chat','*','*','ALLOW','ROLE','employee'),(207,'Chat','sendMessage','*','ALLOW','ROLE','employee'),(208,'Sale','recalculatePrice','WRITE','ALLOW','ROLE','employee'),(209,'Ticket','recalculateComponents','WRITE','ALLOW','ROLE','employee'),(211,'TravelLog','*','READ','ALLOW','ROLE','buyer'),(212,'Thermograph','*','*','ALLOW','ROLE','buyer'),(213,'TravelThermograph','*','WRITE','ALLOW','ROLE','buyer'),(214,'Entry','*','*','ALLOW','ROLE','buyer'),(215,'TicketWeekly','*','WRITE','ALLOW','ROLE','buyer'),(216,'TravelThermograph','*','READ','ALLOW','ROLE','employee'),(218,'Intrastat','*','*','ALLOW','ROLE','buyer'),(221,'UserConfig','getUserConfig','READ','ALLOW','ROLE','account'),(222,'Client','*','READ','ALLOW','ROLE','trainee'),(226,'ClientObservation','*','READ','ALLOW','ROLE','trainee'),(227,'Address','*','READ','ALLOW','ROLE','trainee'),(228,'AddressObservation','*','READ','ALLOW','ROLE','trainee'),(230,'ClientCredit','*','READ','ALLOW','ROLE','trainee'),(231,'ClientContact','*','READ','ALLOW','ROLE','trainee'),(232,'ClientSample','*','READ','ALLOW','ROLE','trainee'),(233,'EntryLog','*','READ','ALLOW','ROLE','buyer'),(234,'WorkerLog','*','READ','ALLOW','ROLE','salesAssistant'),(235,'CustomsAgent','*','*','ALLOW','ROLE','employee'),(236,'Buy','*','*','ALLOW','ROLE','buyer'),(237,'WorkerDms','filter','*','ALLOW','ROLE','employee'),(238,'Town','*','WRITE','ALLOW','ROLE','deliveryBoss'),(239,'Province','*','WRITE','ALLOW','ROLE','deliveryBoss'),(240,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(241,'SupplierContact','*','WRITE','ALLOW','ROLE','administrative'),(242,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(244,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(248,'RoleMapping','*','READ','ALLOW','ROLE','account'),(249,'UserPassword','*','READ','ALLOW','ROLE','account'),(250,'Town','*','WRITE','ALLOW','ROLE','deliveryBoss'),(251,'Province','*','WRITE','ALLOW','ROLE','deliveryBoss'),(252,'Supplier','*','READ','ALLOW','ROLE','employee'),(253,'Supplier','*','WRITE','ALLOW','ROLE','administrative'),(254,'SupplierLog','*','READ','ALLOW','ROLE','employee'),(256,'Image','*','WRITE','ALLOW','ROLE','employee'),(257,'FixedPrice','*','*','ALLOW','ROLE','buyer'),(258,'PayDem','*','READ','ALLOW','ROLE','employee'),(259,'Client','createReceipt','*','ALLOW','ROLE','salesAssistant'),(260,'PrintServerQueue','*','WRITE','ALLOW','ROLE','employee'),(261,'SupplierAccount','*','*','ALLOW','ROLE','administrative'),(262,'Entry','*','*','ALLOW','ROLE','administrative'),(263,'InvoiceIn','*','*','ALLOW','ROLE','administrative'),(264,'StarredModule','*','*','ALLOW','ROLE','employee'),(265,'ItemBotanical','*','WRITE','ALLOW','ROLE','logisticBoss'),(266,'ZoneLog','*','READ','ALLOW','ROLE','employee'),(267,'Genus','*','WRITE','ALLOW','ROLE','logisticBoss'),(268,'Specie','*','WRITE','ALLOW','ROLE','logisticBoss'),(269,'InvoiceOut','createPdf','WRITE','ALLOW','ROLE','employee'),(270,'SupplierAddress','*','*','ALLOW','ROLE','employee'),(271,'SalesMonitor','*','*','ALLOW','ROLE','employee'),(272,'InvoiceInLog','*','READ','ALLOW','ROLE','employee'),(273,'InvoiceInTax','*','*','ALLOW','ROLE','administrative'),(274,'InvoiceInLog','*','READ','ALLOW','ROLE','administrative'),(275,'InvoiceOut','createManualInvoice','WRITE','ALLOW','ROLE','invoicing'),(276,'InvoiceOut','globalInvoicing','WRITE','ALLOW','ROLE','invoicing'),(277,'Role','*','*','ALLOW','ROLE','it'),(278,'RoleInherit','*','WRITE','ALLOW','ROLE','grant'),(279,'MailAlias','*','*','ALLOW','ROLE','marketing'),(283,'EntryObservation','*','*','ALLOW','ROLE','buyer'),(284,'LdapConfig','*','*','ALLOW','ROLE','sysadmin'),(285,'SambaConfig','*','*','ALLOW','ROLE','sysadmin'),(286,'ACL','*','*','ALLOW','ROLE','developer'),(287,'AccessToken','*','*','ALLOW','ROLE','developer'),(288,'MailAliasAccount','*','*','ALLOW','ROLE','marketing'),(289,'MailAliasAccount','*','*','ALLOW','ROLE','hr'),(290,'MailAlias','*','*','ALLOW','ROLE','hr'),(291,'MailForward','*','*','ALLOW','ROLE','marketing'),(292,'MailForward','*','*','ALLOW','ROLE','hr'),(293,'RoleInherit','*','*','ALLOW','ROLE','it'),(294,'RoleRole','*','*','ALLOW','ROLE','it'),(295,'AccountConfig','*','*','ALLOW','ROLE','sysadmin'),(296,'Collection','*','READ','ALLOW','ROLE','employee'),(297,'Sale','refund','WRITE','ALLOW','ROLE','invoicing'),(298,'InvoiceInDueDay','*','*','ALLOW','ROLE','administrative'),(299,'Collection','setSaleQuantity','*','ALLOW','ROLE','employee'),(300,'Docuware','*','*','ALLOW','ROLE','employee'),(301,'Agency','*','READ','ALLOW','ROLE','employee'),(302,'AgencyTerm','*','*','ALLOW','ROLE','administrative'),(303,'ClaimLog','*','READ','ALLOW','ROLE','claimManager'),(304,'Edi','updateData','WRITE','ALLOW','ROLE','employee'),(305,'EducationLevel','*','*','ALLOW','ROLE','employee'),(306,'InvoiceInIntrastat','*','*','ALLOW','ROLE','employee'),(307,'SupplierAgencyTerm','*','*','ALLOW','ROLE','administrative'),(308,'InvoiceInIntrastat','*','*','ALLOW','ROLE','employee'),(309,'Zone','getZoneClosing','*','ALLOW','ROLE','employee'),(310,'ExpeditionState','*','READ','ALLOW','ROLE','employee'),(311,'Expense','*','READ','ALLOW','ROLE','employee'),(312,'Expense','*','WRITE','ALLOW','ROLE','administrative'),(314,'SupplierActivity','*','READ','ALLOW','ROLE','employee'),(315,'SupplierActivity','*','WRITE','ALLOW','ROLE','administrative'),(316,'Dms','deleteTrashFiles','WRITE','ALLOW','ROLE','employee'),(317,'ClientUnpaid','*','*','ALLOW','ROLE','administrative'),(318,'MdbVersion','*','*','ALLOW','ROLE','developer'),(319,'ItemType','*','READ','ALLOW','ROLE','employee'),(320,'ItemType','*','WRITE','ALLOW','ROLE','buyer'),(321,'InvoiceOut','refund','WRITE','ALLOW','ROLE','invoicing'),(322,'InvoiceOut','refund','WRITE','ALLOW','ROLE','salesAssistant'),(323,'InvoiceOut','refund','WRITE','ALLOW','ROLE','claimManager'),(324,'Ticket','refund','WRITE','ALLOW','ROLE','invoicing'),(325,'Ticket','refund','WRITE','ALLOW','ROLE','salesAssistant'),(326,'Ticket','refund','WRITE','ALLOW','ROLE','claimManager'),(327,'Sale','refund','WRITE','ALLOW','ROLE','salesAssistant'),(328,'Sale','refund','WRITE','ALLOW','ROLE','claimManager'),(329,'TicketRefund','*','WRITE','ALLOW','ROLE','invoicing'),(330,'ClaimObservation','*','WRITE','ALLOW','ROLE','salesPerson'),(331,'ClaimObservation','*','READ','ALLOW','ROLE','salesPerson'),(332,'Client','setPassword','WRITE','ALLOW','ROLE','salesPerson'),(333,'Client','updateUser','WRITE','ALLOW','ROLE','salesPerson'),(334,'ShelvingLog','*','READ','ALLOW','ROLE','employee'),(335,'ZoneExclusionGeo','*','READ','ALLOW','ROLE','employee'),(336,'ZoneExclusionGeo','*','WRITE','ALLOW','ROLE','deliveryBoss'),(337,'Parking','*','*','ALLOW','ROLE','employee'),(338,'Shelving','*','*','ALLOW','ROLE','employee'),(339,'OsTicket','*','*','ALLOW','ROLE','employee'),(340,'OsTicketConfig','*','*','ALLOW','ROLE','it'),(341,'ClientConsumptionQueue','*','WRITE','ALLOW','ROLE','employee'),(342,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','employee'),(343,'Ticket','deliveryNoteEmail','WRITE','ALLOW','ROLE','employee'),(344,'Ticket','deliveryNoteCsvPdf','READ','ALLOW','ROLE','employee'),(345,'Ticket','deliveryNoteCsvEmail','WRITE','ALLOW','ROLE','employee'),(346,'Client','campaignMetricsPdf','READ','ALLOW','ROLE','employee'),(347,'Client','campaignMetricsEmail','WRITE','ALLOW','ROLE','employee'),(348,'Client','clientWelcomeHtml','READ','ALLOW','ROLE','employee'),(349,'Client','clientWelcomeEmail','WRITE','ALLOW','ROLE','employee'),(350,'Client','creditRequestPdf','READ','ALLOW','ROLE','employee'),(351,'Client','creditRequestHtml','READ','ALLOW','ROLE','employee'),(352,'Client','creditRequestEmail','WRITE','ALLOW','ROLE','employee'),(353,'Client','printerSetupHtml','READ','ALLOW','ROLE','employee'),(354,'Client','printerSetupEmail','WRITE','ALLOW','ROLE','employee'),(355,'Client','sepaCoreEmail','WRITE','ALLOW','ROLE','employee'),(356,'Client','letterDebtorPdf','READ','ALLOW','ROLE','employee'),(357,'Client','letterDebtorStHtml','READ','ALLOW','ROLE','employee'),(358,'Client','letterDebtorStEmail','WRITE','ALLOW','ROLE','employee'),(359,'Client','letterDebtorNdHtml','READ','ALLOW','ROLE','employee'),(360,'Client','letterDebtorNdEmail','WRITE','ALLOW','ROLE','employee'),(361,'Client','clientDebtStatementPdf','READ','ALLOW','ROLE','employee'),(362,'Client','clientDebtStatementHtml','READ','ALLOW','ROLE','employee'),(363,'Client','clientDebtStatementEmail','WRITE','ALLOW','ROLE','employee'),(364,'Client','incotermsAuthorizationPdf','READ','ALLOW','ROLE','employee'),(365,'Client','incotermsAuthorizationHtml','READ','ALLOW','ROLE','employee'),(366,'Client','incotermsAuthorizationEmail','WRITE','ALLOW','ROLE','employee'),(367,'Client','consumptionSendQueued','WRITE','ALLOW','ROLE','system'),(368,'InvoiceOut','invoiceEmail','WRITE','ALLOW','ROLE','employee'),(369,'InvoiceOut','exportationPdf','READ','ALLOW','ROLE','employee'),(370,'InvoiceOut','sendQueued','WRITE','ALLOW','ROLE','system'),(371,'Ticket','invoiceCsvPdf','READ','ALLOW','ROLE','employee'),(372,'Ticket','invoiceCsvEmail','WRITE','ALLOW','ROLE','employee'),(373,'Supplier','campaignMetricsPdf','READ','ALLOW','ROLE','employee'),(374,'Supplier','campaignMetricsEmail','WRITE','ALLOW','ROLE','employee'),(375,'Travel','extraCommunityPdf','READ','ALLOW','ROLE','employee'),(376,'Travel','extraCommunityEmail','WRITE','ALLOW','ROLE','employee'),(377,'Entry','entryOrderPdf','READ','ALLOW','ROLE','employee'),(378,'OsTicket','osTicketReportEmail','WRITE','ALLOW','ROLE','system'),(379,'Item','buyerWasteEmail','WRITE','ALLOW','ROLE','system'),(380,'Claim','claimPickupPdf','READ','ALLOW','ROLE','employee'),(381,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','claimManager'),(382,'Item','labelPdf','READ','ALLOW','ROLE','employee'),(383,'Sector','*','READ','ALLOW','ROLE','employee'),(384,'Sector','*','WRITE','ALLOW','ROLE','employee'),(385,'Route','driverRoutePdf','READ','ALLOW','ROLE','employee'),(386,'Route','driverRouteEmail','WRITE','ALLOW','ROLE','employee'),(387,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','customer'),(388,'Supplier','newSupplier','WRITE','ALLOW','ROLE','administrative'),(389,'ClaimRma','*','READ','ALLOW','ROLE','claimManager'),(390,'ClaimRma','*','WRITE','ALLOW','ROLE','claimManager'),(391,'Notification','*','WRITE','ALLOW','ROLE','system'),(392,'Boxing','*','*','ALLOW','ROLE','employee'),(393,'Url','*','READ','ALLOW','ROLE','employee'),(394,'Url','*','WRITE','ALLOW','ROLE','it'),(395,'ItemShelving','*','READ','ALLOW','ROLE','employee'),(396,'ItemShelving','*','WRITE','ALLOW','ROLE','production'),(397,'ItemShelvingPlacementSupplyStock','*','READ','ALLOW','ROLE','employee'),(398,'NotificationQueue','*','*','ALLOW','ROLE','employee'),(399,'InvoiceOut','clientsToInvoice','WRITE','ALLOW','ROLE','invoicing'),(400,'InvoiceOut','invoiceClient','WRITE','ALLOW','ROLE','invoicing'),(401,'Sale','editTracked','WRITE','ALLOW','ROLE','production'),(402,'Sale','editFloramondo','WRITE','ALLOW','ROLE','salesAssistant'),(403,'Receipt','balanceCompensationEmail','WRITE','ALLOW','ROLE','employee'),(404,'Receipt','balanceCompensationPdf','READ','ALLOW','ROLE','employee'),(405,'Ticket','getTicketsFuture','READ','ALLOW','ROLE','employee'),(406,'Ticket','merge','WRITE','ALLOW','ROLE','employee'),(407,'Sale','editFloramondo','WRITE','ALLOW','ROLE','logistic'),(408,'ZipConfig','*','*','ALLOW','ROLE','employee'),(409,'Item','*','WRITE','ALLOW','ROLE','administrative'),(410,'Sale','editCloned','WRITE','ALLOW','ROLE','buyer'),(411,'Sale','editCloned','WRITE','ALLOW','ROLE','salesAssistant'),(414,'MdbVersion','*','READ','ALLOW','ROLE','$everyone'),(416,'TicketLog','getChanges','READ','ALLOW','ROLE','employee'),(417,'Ticket','getTicketsAdvance','READ','ALLOW','ROLE','employee'),(418,'EntryLog','*','READ','ALLOW','ROLE','administrative'),(419,'Sale','editTracked','WRITE','ALLOW','ROLE','buyer'),(420,'MdbBranch','*','READ','ALLOW','ROLE','$everyone'),(421,'ItemShelvingSale','*','*','ALLOW','ROLE','employee'),(422,'Docuware','checkFile','READ','ALLOW','ROLE','employee'),(423,'Docuware','download','READ','ALLOW','ROLE','salesPerson'),(424,'Docuware','upload','WRITE','ALLOW','ROLE','productionAssi'),(425,'Docuware','deliveryNoteEmail','WRITE','ALLOW','ROLE','salesPerson'),(426,'TpvTransaction','confirm','WRITE','ALLOW','ROLE','$everyone'),(427,'TpvTransaction','start','WRITE','ALLOW','ROLE','$authenticated'),(428,'TpvTransaction','end','WRITE','ALLOW','ROLE','$authenticated'),(429,'ItemConfig','*','READ','ALLOW','ROLE','employee'),(431,'Tag','onSubmit','WRITE','ALLOW','ROLE','employee'),(432,'Worker','updateAttributes','WRITE','ALLOW','ROLE','hr'),(433,'Worker','createAbsence','*','ALLOW','ROLE','employee'),(434,'Worker','updateAbsence','WRITE','ALLOW','ROLE','employee'),(435,'Worker','deleteAbsence','*','ALLOW','ROLE','employee'),(436,'Worker','new','WRITE','ALLOW','ROLE','hr'),(437,'Role','*','READ','ALLOW','ROLE','hr'),(438,'Client','getClientOrSupplierReference','READ','ALLOW','ROLE','employee'),(439,'NotificationSubscription','*','*','ALLOW','ROLE','employee'),(440,'NotificationAcl','*','READ','ALLOW','ROLE','employee'),(441,'MdbApp','*','READ','ALLOW','ROLE','$everyone'),(442,'MdbApp','*','*','ALLOW','ROLE','developer'),(443,'ItemConfig','*','*','ALLOW','ROLE','employee'),(444,'DeviceProduction','*','*','ALLOW','ROLE','hr'),(445,'DeviceProductionModels','*','*','ALLOW','ROLE','hr'),(446,'DeviceProductionState','*','*','ALLOW','ROLE','hr'),(447,'DeviceProductionUser','*','*','ALLOW','ROLE','hr'),(448,'DeviceProduction','*','*','ALLOW','ROLE','productionAssi'),(449,'DeviceProductionModels','*','*','ALLOW','ROLE','productionAssi'),(450,'DeviceProductionState','*','*','ALLOW','ROLE','productionAssi'),(451,'DeviceProductionUser','*','*','ALLOW','ROLE','productionAssi'),(452,'Worker','deallocatePDA','*','ALLOW','ROLE','hr'),(453,'Worker','allocatePDA','*','ALLOW','ROLE','hr'),(454,'Worker','deallocatePDA','*','ALLOW','ROLE','productionAssi'),(455,'Worker','allocatePDA','*','ALLOW','ROLE','productionAssi'),(456,'Zone','*','*','ALLOW','ROLE','deliveryBoss'),(457,'Account','setPassword','WRITE','ALLOW','ROLE','itManagement'),(458,'Operator','*','READ','ALLOW','ROLE','employee'),(459,'Operator','*','WRITE','ALLOW','ROLE','employee'),(460,'InvoiceIn','getSerial','READ','ALLOW','ROLE','administrative'),(461,'Ticket','saveSign','WRITE','ALLOW','ROLE','employee'),(462,'InvoiceOut','negativeBases','READ','ALLOW','ROLE','administrative'),(463,'InvoiceOut','negativeBasesCsv','READ','ALLOW','ROLE','administrative'),(464,'WorkerObservation','*','*','ALLOW','ROLE','hr'),(465,'ClientInforma','*','READ','ALLOW','ROLE','employee'),(466,'ClientInforma','*','WRITE','ALLOW','ROLE','financial'),(467,'Receipt','receiptEmail','*','ALLOW','ROLE','salesAssistant'),(468,'Client','setRating','WRITE','ALLOW','ROLE','financial'),(469,'Client','*','READ','ALLOW','ROLE','employee'),(470,'Client','addressesPropagateRe','*','ALLOW','ROLE','employee'),(471,'Client','canBeInvoiced','*','ALLOW','ROLE','employee'),(472,'Client','canCreateTicket','*','ALLOW','ROLE','employee'),(473,'Client','consumption','*','ALLOW','ROLE','employee'),(474,'Client','createAddress','*','ALLOW','ROLE','employee'),(475,'Client','createWithUser','*','ALLOW','ROLE','employee'),(476,'Client','extendedListFilter','*','ALLOW','ROLE','employee'),(477,'Client','getAverageInvoiced','*','ALLOW','ROLE','employee'),(478,'Client','getCard','*','ALLOW','ROLE','employee'),(479,'Client','getDebt','*','ALLOW','ROLE','employee'),(480,'Client','getMana','*','ALLOW','ROLE','employee'),(481,'Client','transactions','*','ALLOW','ROLE','employee'),(482,'Client','hasCustomerRole','*','ALLOW','ROLE','employee'),(483,'Client','isValidClient','*','ALLOW','ROLE','employee'),(484,'Client','lastActiveTickets','*','ALLOW','ROLE','employee'),(485,'Client','sendSms','*','ALLOW','ROLE','employee'),(486,'Client','setPassword','*','ALLOW','ROLE','employee'),(487,'Client','summary','*','ALLOW','ROLE','employee'),(488,'Client','updateAddress','*','ALLOW','ROLE','employee'),(489,'Client','updateFiscalData','*','ALLOW','ROLE','employee'),(490,'Client','updateUser','*','ALLOW','ROLE','employee'),(491,'Client','uploadFile','*','ALLOW','ROLE','employee'),(492,'Client','campaignMetricsPdf','*','ALLOW','ROLE','employee'),(493,'Client','campaignMetricsEmail','*','ALLOW','ROLE','employee'),(494,'Client','clientWelcomeHtml','*','ALLOW','ROLE','employee'),(495,'Client','clientWelcomeEmail','*','ALLOW','ROLE','employee'),(496,'Client','printerSetupHtml','*','ALLOW','ROLE','employee'),(497,'Client','printerSetupEmail','*','ALLOW','ROLE','employee'),(498,'Client','sepaCoreEmail','*','ALLOW','ROLE','employee'),(499,'Client','letterDebtorPdf','*','ALLOW','ROLE','employee'),(500,'Client','letterDebtorStHtml','*','ALLOW','ROLE','employee'),(501,'Client','letterDebtorStEmail','*','ALLOW','ROLE','employee'),(502,'Client','letterDebtorNdHtml','*','ALLOW','ROLE','employee'),(503,'Client','letterDebtorNdEmail','*','ALLOW','ROLE','employee'),(504,'Client','clientDebtStatementPdf','*','ALLOW','ROLE','employee'),(505,'Client','clientDebtStatementHtml','*','ALLOW','ROLE','employee'),(506,'Client','clientDebtStatementEmail','*','ALLOW','ROLE','employee'),(507,'Client','creditRequestPdf','*','ALLOW','ROLE','employee'),(508,'Client','creditRequestHtml','*','ALLOW','ROLE','employee'),(509,'Client','creditRequestEmail','*','ALLOW','ROLE','employee'),(510,'Client','incotermsAuthorizationPdf','*','ALLOW','ROLE','employee'),(511,'Client','incotermsAuthorizationHtml','*','ALLOW','ROLE','employee'),(512,'Client','incotermsAuthorizationEmail','*','ALLOW','ROLE','employee'),(513,'Client','consumptionSendQueued','*','ALLOW','ROLE','employee'),(514,'Client','filter','*','ALLOW','ROLE','employee'),(515,'Client','getClientOrSupplierReference','*','ALLOW','ROLE','employee'),(516,'Client','upsert','*','ALLOW','ROLE','employee'),(517,'Client','create','*','ALLOW','ROLE','employee'),(518,'Client','replaceById','*','ALLOW','ROLE','employee'),(519,'Client','updateAttributes','*','ALLOW','ROLE','employee'),(520,'Client','updateAttributes','*','ALLOW','ROLE','employee'),(521,'Client','deleteById','*','ALLOW','ROLE','employee'),(522,'Client','replaceOrCreate','*','ALLOW','ROLE','employee'),(523,'Client','updateAll','*','ALLOW','ROLE','employee'),(524,'Client','upsertWithWhere','*','ALLOW','ROLE','employee'),(525,'Defaulter','observationEmail','WRITE','ALLOW','ROLE','employee'),(526,'VnUser','*','*','ALLOW','ROLE','employee'),(527,'VnUser','acl','READ','ALLOW','ROLE','account'),(528,'VnUser','getCurrentUserData','READ','ALLOW','ROLE','account'),(529,'VnUser','changePassword','WRITE','ALLOW','ROLE','account'),(530,'Account','exists','READ','ALLOW','ROLE','account'),(531,'Account','exists','READ','ALLOW','ROLE','account'),(532,'UserLog','*','READ','ALLOW','ROLE','employee'),(533,'RoleLog','*','READ','ALLOW','ROLE','employee'); +INSERT INTO `ACL` VALUES (1,'Account','*','*','ALLOW','ROLE','employee'),(3,'Address','*','*','ALLOW','ROLE','employee'),(5,'AgencyService','*','READ','ALLOW','ROLE','employee'),(9,'ClientObservation','*','*','ALLOW','ROLE','employee'),(11,'ContactChannel','*','READ','ALLOW','ROLE','trainee'),(13,'Employee','*','READ','ALLOW','ROLE','employee'),(14,'PayMethod','*','READ','ALLOW','ROLE','trainee'),(16,'FakeProduction','*','READ','ALLOW','ROLE','employee'),(17,'Warehouse','* ','READ','ALLOW','ROLE','trainee'),(18,'State','*','READ','ALLOW','ROLE','employee'),(20,'TicketState','*','*','ALLOW','ROLE','employee'),(24,'Delivery','*','READ','ALLOW','ROLE','employee'),(25,'Zone','*','READ','ALLOW','ROLE','employee'),(26,'ClientCredit','*','*','ALLOW','ROLE','employee'),(27,'ClientCreditLimit','*','READ','ALLOW','ROLE','trainee'),(30,'GreugeType','*','READ','ALLOW','ROLE','trainee'),(31,'Mandate','*','READ','ALLOW','ROLE','trainee'),(32,'MandateType','*','READ','ALLOW','ROLE','trainee'),(33,'Company','*','READ','ALLOW','ROLE','trainee'),(34,'Greuge','*','READ','ALLOW','ROLE','trainee'),(35,'AddressObservation','*','*','ALLOW','ROLE','employee'),(36,'ObservationType','*','*','ALLOW','ROLE','employee'),(37,'Greuge','*','WRITE','ALLOW','ROLE','employee'),(38,'AgencyMode','*','READ','ALLOW','ROLE','employee'),(39,'ItemTag','*','WRITE','ALLOW','ROLE','buyer'),(40,'ItemBotanical','*','WRITE','ALLOW','ROLE','buyer'),(41,'ItemBotanical','*','READ','ALLOW','ROLE','employee'),(42,'ItemPlacement','*','WRITE','ALLOW','ROLE','buyer'),(43,'ItemPlacement','*','WRITE','ALLOW','ROLE','replenisher'),(44,'ItemPlacement','*','READ','ALLOW','ROLE','employee'),(45,'ItemBarcode','*','READ','ALLOW','ROLE','employee'),(46,'ItemBarcode','*','WRITE','ALLOW','ROLE','buyer'),(47,'ItemBarcode','*','WRITE','ALLOW','ROLE','replenisher'),(51,'ItemTag','*','READ','ALLOW','ROLE','employee'),(53,'Item','*','READ','ALLOW','ROLE','employee'),(54,'Item','*','WRITE','ALLOW','ROLE','buyer'),(55,'Recovery','*','READ','ALLOW','ROLE','trainee'),(56,'Recovery','*','WRITE','ALLOW','ROLE','administrative'),(58,'CreditClassification','*','*','ALLOW','ROLE','insurance'),(60,'CreditInsurance','*','*','ALLOW','ROLE','insurance'),(61,'InvoiceOut','*','READ','ALLOW','ROLE','employee'),(62,'Ticket','*','*','ALLOW','ROLE','employee'),(63,'TicketObservation','*','*','ALLOW','ROLE','employee'),(64,'Route','*','READ','ALLOW','ROLE','employee'),(65,'Sale','*','READ','ALLOW','ROLE','employee'),(66,'TicketTracking','*','READ','ALLOW','ROLE','employee'),(68,'TicketPackaging','*','*','ALLOW','ROLE','employee'),(69,'Packaging','*','READ','ALLOW','ROLE','employee'),(70,'Packaging','*','WRITE','ALLOW','ROLE','logistic'),(72,'SaleComponent','*','READ','ALLOW','ROLE','employee'),(73,'Expedition','*','READ','ALLOW','ROLE','employee'),(74,'Expedition','*','WRITE','ALLOW','ROLE','deliveryAssist'),(75,'Expedition','*','WRITE','ALLOW','ROLE','production'),(76,'AnnualAverageInvoiced','*','READ','ALLOW','ROLE','employee'),(77,'WorkerMana','*','READ','ALLOW','ROLE','employee'),(78,'TicketTracking','*','WRITE','ALLOW','ROLE','production'),(79,'TicketTracking','changeState','*','ALLOW','ROLE','employee'),(80,'Sale','deleteSales','*','ALLOW','ROLE','employee'),(81,'Sale','moveToTicket','*','ALLOW','ROLE','employee'),(82,'Sale','updateQuantity','*','ALLOW','ROLE','employee'),(83,'Sale','updatePrice','*','ALLOW','ROLE','employee'),(84,'Sale','updateDiscount','*','ALLOW','ROLE','employee'),(85,'SaleTracking','*','READ','ALLOW','ROLE','employee'),(86,'Order','*','*','ALLOW','ROLE','employee'),(87,'OrderRow','*','*','ALLOW','ROLE','employee'),(88,'ClientContact','*','*','ALLOW','ROLE','employee'),(89,'Sale','moveToNewTicket','*','ALLOW','ROLE','employee'),(90,'Sale','reserve','*','ALLOW','ROLE','employee'),(91,'TicketWeekly','*','READ','ALLOW','ROLE','employee'),(94,'Agency','landsThatDay','*','ALLOW','ROLE','employee'),(96,'ClaimEnd','*','READ','ALLOW','ROLE','employee'),(97,'ClaimEnd','*','WRITE','ALLOW','ROLE','claimManager'),(98,'ClaimBeginning','*','*','ALLOW','ROLE','employee'),(99,'ClaimDevelopment','*','READ','ALLOW','ROLE','employee'),(100,'ClaimDevelopment','*','WRITE','ALLOW','ROLE','claimManager'),(101,'Claim','*','*','ALLOW','ROLE','employee'),(102,'Claim','createFromSales','*','ALLOW','ROLE','employee'),(104,'Item','*','WRITE','ALLOW','ROLE','marketingBoss'),(105,'ItemBarcode','*','WRITE','ALLOW','ROLE','marketingBoss'),(106,'ItemBotanical','*','WRITE','ALLOW','ROLE','marketingBoss'),(108,'ItemPlacement','*','WRITE','ALLOW','ROLE','marketingBoss'),(109,'UserConfig','*','*','ALLOW','ROLE','employee'),(110,'Bank','*','READ','ALLOW','ROLE','trainee'),(111,'ClientLog','*','READ','ALLOW','ROLE','trainee'),(112,'Defaulter','*','READ','ALLOW','ROLE','employee'),(113,'ClientRisk','*','READ','ALLOW','ROLE','trainee'),(114,'Receipt','*','READ','ALLOW','ROLE','trainee'),(115,'Receipt','*','WRITE','ALLOW','ROLE','administrative'),(116,'BankEntity','*','*','ALLOW','ROLE','employee'),(117,'ClientSample','*','*','ALLOW','ROLE','employee'),(118,'WorkerTeam','*','*','ALLOW','ROLE','salesPerson'),(119,'Travel','*','READ','ALLOW','ROLE','employee'),(120,'Travel','*','WRITE','ALLOW','ROLE','buyer'),(121,'Item','regularize','*','ALLOW','ROLE','employee'),(122,'TicketRequest','*','*','ALLOW','ROLE','employee'),(123,'Worker','*','READ','ALLOW','ROLE','employee'),(124,'Client','confirmTransaction','WRITE','ALLOW','ROLE','administrative'),(125,'Agency','getAgenciesWithWarehouse','*','ALLOW','ROLE','employee'),(126,'Client','activeWorkersWithRole','*','ALLOW','ROLE','employee'),(127,'TicketLog','*','READ','ALLOW','ROLE','employee'),(129,'TicketService','*','*','ALLOW','ROLE','employee'),(130,'Expedition','*','WRITE','ALLOW','ROLE','packager'),(131,'CreditInsurance','*','READ','ALLOW','ROLE','trainee'),(132,'CreditClassification','*','READ','ALLOW','ROLE','trainee'),(133,'ItemTag','*','WRITE','ALLOW','ROLE','marketingBoss'),(135,'ZoneGeo','*','READ','ALLOW','ROLE','employee'),(136,'ZoneCalendar','*','READ','ALLOW','ROLE','employee'),(137,'ZoneIncluded','*','READ','ALLOW','ROLE','employee'),(138,'LabourHoliday','*','READ','ALLOW','ROLE','employee'),(139,'LabourHolidayLegend','*','READ','ALLOW','ROLE','employee'),(140,'LabourHolidayType','*','READ','ALLOW','ROLE','employee'),(141,'Zone','*','*','ALLOW','ROLE','logisticBoss'),(142,'ZoneCalendar','*','WRITE','ALLOW','ROLE','deliveryAssist'),(143,'ZoneIncluded','*','*','ALLOW','ROLE','deliveryAssist'),(144,'Stowaway','*','*','ALLOW','ROLE','employee'),(145,'Ticket','getPossibleStowaways','READ','ALLOW','ROLE','employee'),(147,'UserConfigView','*','*','ALLOW','ROLE','employee'),(148,'UserConfigView','*','*','ALLOW','ROLE','employee'),(149,'Sip','*','READ','ALLOW','ROLE','employee'),(150,'Sip','*','WRITE','ALLOW','ROLE','hr'),(151,'Department','*','READ','ALLOW','ROLE','employee'),(152,'Department','*','WRITE','ALLOW','ROLE','hr'),(153,'Route','*','READ','ALLOW','ROLE','employee'),(154,'Route','*','WRITE','ALLOW','ROLE','delivery'),(155,'Calendar','*','READ','ALLOW','ROLE','hr'),(156,'WorkerLabour','*','READ','ALLOW','ROLE','hr'),(157,'Calendar','absences','READ','ALLOW','ROLE','employee'),(158,'ItemTag','*','WRITE','ALLOW','ROLE','accessory'),(160,'TicketServiceType','*','READ','ALLOW','ROLE','employee'),(161,'TicketConfig','*','READ','ALLOW','ROLE','employee'),(162,'InvoiceOut','delete','WRITE','ALLOW','ROLE','invoicing'),(163,'InvoiceOut','book','WRITE','ALLOW','ROLE','invoicing'),(165,'TicketDms','*','*','ALLOW','ROLE','employee'),(167,'Worker','isSubordinate','READ','ALLOW','ROLE','employee'),(168,'Worker','mySubordinates','READ','ALLOW','ROLE','employee'),(169,'WorkerTimeControl','filter','READ','ALLOW','ROLE','employee'),(170,'WorkerTimeControl','addTime','WRITE','ALLOW','ROLE','employee'),(171,'TicketServiceType','*','WRITE','ALLOW','ROLE','administrative'),(172,'Sms','*','READ','ALLOW','ROLE','employee'),(173,'Sms','send','WRITE','ALLOW','ROLE','employee'),(174,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(175,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(176,'Device','*','*','ALLOW','ROLE','employee'),(177,'Device','*','*','ALLOW','ROLE','employee'),(178,'WorkerTimeControl','*','*','ALLOW','ROLE','employee'),(179,'ItemLog','*','READ','ALLOW','ROLE','employee'),(180,'RouteLog','*','READ','ALLOW','ROLE','employee'),(181,'Dms','removeFile','WRITE','ALLOW','ROLE','employee'),(182,'Dms','uploadFile','WRITE','ALLOW','ROLE','employee'),(183,'Dms','downloadFile','READ','ALLOW','ROLE','employee'),(184,'Client','uploadFile','WRITE','ALLOW','ROLE','employee'),(185,'ClientDms','removeFile','WRITE','ALLOW','ROLE','employee'),(186,'ClientDms','*','READ','ALLOW','ROLE','trainee'),(187,'Ticket','uploadFile','WRITE','ALLOW','ROLE','employee'),(190,'Route','updateVolume','WRITE','ALLOW','ROLE','deliveryAssist'),(191,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(192,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(194,'Postcode','*','WRITE','ALLOW','ROLE','deliveryAssist'),(195,'Ticket','addSale','WRITE','ALLOW','ROLE','employee'),(196,'Dms','updateFile','WRITE','ALLOW','ROLE','employee'),(197,'Dms','*','READ','ALLOW','ROLE','trainee'),(198,'ClaimDms','removeFile','WRITE','ALLOW','ROLE','employee'),(199,'ClaimDms','*','READ','ALLOW','ROLE','employee'),(200,'Claim','uploadFile','WRITE','ALLOW','ROLE','employee'),(201,'Sale','updateConcept','WRITE','ALLOW','ROLE','employee'),(202,'Claim','updateClaimAction','WRITE','ALLOW','ROLE','claimManager'),(203,'UserPhone','*','*','ALLOW','ROLE','employee'),(204,'WorkerDms','removeFile','WRITE','ALLOW','ROLE','hr'),(205,'WorkerDms','*','READ','ALLOW','ROLE','hr'),(206,'Chat','*','*','ALLOW','ROLE','employee'),(207,'Chat','sendMessage','*','ALLOW','ROLE','employee'),(208,'Sale','recalculatePrice','WRITE','ALLOW','ROLE','employee'),(209,'Ticket','recalculateComponents','WRITE','ALLOW','ROLE','employee'),(211,'TravelLog','*','READ','ALLOW','ROLE','buyer'),(212,'Thermograph','*','*','ALLOW','ROLE','buyer'),(213,'TravelThermograph','*','WRITE','ALLOW','ROLE','buyer'),(214,'Entry','*','*','ALLOW','ROLE','buyer'),(215,'TicketWeekly','*','WRITE','ALLOW','ROLE','buyer'),(216,'TravelThermograph','*','READ','ALLOW','ROLE','employee'),(218,'Intrastat','*','*','ALLOW','ROLE','buyer'),(221,'UserConfig','getUserConfig','READ','ALLOW','ROLE','account'),(222,'Client','*','READ','ALLOW','ROLE','trainee'),(226,'ClientObservation','*','READ','ALLOW','ROLE','trainee'),(227,'Address','*','READ','ALLOW','ROLE','trainee'),(228,'AddressObservation','*','READ','ALLOW','ROLE','trainee'),(230,'ClientCredit','*','READ','ALLOW','ROLE','trainee'),(231,'ClientContact','*','READ','ALLOW','ROLE','trainee'),(232,'ClientSample','*','READ','ALLOW','ROLE','trainee'),(233,'EntryLog','*','READ','ALLOW','ROLE','buyer'),(234,'WorkerLog','*','READ','ALLOW','ROLE','salesAssistant'),(235,'CustomsAgent','*','*','ALLOW','ROLE','employee'),(236,'Buy','*','*','ALLOW','ROLE','buyer'),(237,'WorkerDms','filter','*','ALLOW','ROLE','employee'),(238,'Town','*','WRITE','ALLOW','ROLE','deliveryAssist'),(239,'Province','*','WRITE','ALLOW','ROLE','deliveryAssist'),(240,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(241,'SupplierContact','*','WRITE','ALLOW','ROLE','administrative'),(242,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(244,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(248,'RoleMapping','*','READ','ALLOW','ROLE','account'),(249,'UserPassword','*','READ','ALLOW','ROLE','account'),(250,'Town','*','WRITE','ALLOW','ROLE','deliveryAssist'),(251,'Province','*','WRITE','ALLOW','ROLE','deliveryAssist'),(252,'Supplier','*','READ','ALLOW','ROLE','employee'),(253,'Supplier','*','WRITE','ALLOW','ROLE','administrative'),(254,'SupplierLog','*','READ','ALLOW','ROLE','employee'),(256,'Image','*','WRITE','ALLOW','ROLE','employee'),(257,'FixedPrice','*','*','ALLOW','ROLE','buyer'),(258,'PayDem','*','READ','ALLOW','ROLE','employee'),(259,'Client','createReceipt','*','ALLOW','ROLE','salesAssistant'),(260,'PrintServerQueue','*','WRITE','ALLOW','ROLE','employee'),(261,'SupplierAccount','*','*','ALLOW','ROLE','administrative'),(262,'Entry','*','*','ALLOW','ROLE','administrative'),(263,'InvoiceIn','*','*','ALLOW','ROLE','administrative'),(264,'StarredModule','*','*','ALLOW','ROLE','employee'),(265,'ItemBotanical','*','WRITE','ALLOW','ROLE','logisticBoss'),(266,'ZoneLog','*','READ','ALLOW','ROLE','employee'),(267,'Genus','*','WRITE','ALLOW','ROLE','logisticBoss'),(268,'Specie','*','WRITE','ALLOW','ROLE','logisticBoss'),(269,'InvoiceOut','createPdf','WRITE','ALLOW','ROLE','employee'),(270,'SupplierAddress','*','*','ALLOW','ROLE','employee'),(271,'SalesMonitor','*','*','ALLOW','ROLE','employee'),(272,'InvoiceInLog','*','READ','ALLOW','ROLE','employee'),(273,'InvoiceInTax','*','*','ALLOW','ROLE','administrative'),(274,'InvoiceInLog','*','READ','ALLOW','ROLE','administrative'),(275,'InvoiceOut','createManualInvoice','WRITE','ALLOW','ROLE','invoicing'),(276,'InvoiceOut','globalInvoicing','WRITE','ALLOW','ROLE','invoicing'),(277,'Role','*','*','ALLOW','ROLE','it'),(278,'RoleInherit','*','WRITE','ALLOW','ROLE','grant'),(279,'MailAlias','*','*','ALLOW','ROLE','marketing'),(283,'EntryObservation','*','*','ALLOW','ROLE','buyer'),(284,'LdapConfig','*','*','ALLOW','ROLE','sysadmin'),(285,'SambaConfig','*','*','ALLOW','ROLE','sysadmin'),(286,'ACL','*','*','ALLOW','ROLE','developer'),(287,'AccessToken','*','*','ALLOW','ROLE','developer'),(288,'MailAliasAccount','*','*','ALLOW','ROLE','marketing'),(289,'MailAliasAccount','*','*','ALLOW','ROLE','hr'),(290,'MailAlias','*','*','ALLOW','ROLE','hr'),(291,'MailForward','*','*','ALLOW','ROLE','marketing'),(292,'MailForward','*','*','ALLOW','ROLE','hr'),(293,'RoleInherit','*','*','ALLOW','ROLE','it'),(294,'RoleRole','*','*','ALLOW','ROLE','it'),(295,'AccountConfig','*','*','ALLOW','ROLE','sysadmin'),(296,'Collection','*','READ','ALLOW','ROLE','employee'),(297,'Sale','refund','WRITE','ALLOW','ROLE','invoicing'),(298,'InvoiceInDueDay','*','*','ALLOW','ROLE','administrative'),(299,'Collection','setSaleQuantity','*','ALLOW','ROLE','employee'),(300,'Docuware','*','*','ALLOW','ROLE','employee'),(301,'Agency','*','READ','ALLOW','ROLE','employee'),(302,'AgencyTerm','*','*','ALLOW','ROLE','administrative'),(303,'ClaimLog','*','READ','ALLOW','ROLE','claimManager'),(304,'Edi','updateData','WRITE','ALLOW','ROLE','employee'),(305,'EducationLevel','*','*','ALLOW','ROLE','employee'),(306,'InvoiceInIntrastat','*','*','ALLOW','ROLE','employee'),(307,'SupplierAgencyTerm','*','*','ALLOW','ROLE','administrative'),(308,'InvoiceInIntrastat','*','*','ALLOW','ROLE','employee'),(309,'Zone','getZoneClosing','*','ALLOW','ROLE','employee'),(310,'ExpeditionState','*','READ','ALLOW','ROLE','employee'),(311,'Expense','*','READ','ALLOW','ROLE','employee'),(312,'Expense','*','WRITE','ALLOW','ROLE','administrative'),(314,'SupplierActivity','*','READ','ALLOW','ROLE','employee'),(315,'SupplierActivity','*','WRITE','ALLOW','ROLE','administrative'),(316,'Dms','deleteTrashFiles','WRITE','ALLOW','ROLE','employee'),(317,'ClientUnpaid','*','*','ALLOW','ROLE','administrative'),(318,'MdbVersion','*','*','ALLOW','ROLE','developer'),(319,'ItemType','*','READ','ALLOW','ROLE','employee'),(320,'ItemType','*','WRITE','ALLOW','ROLE','buyer'),(321,'InvoiceOut','refund','WRITE','ALLOW','ROLE','invoicing'),(322,'InvoiceOut','refund','WRITE','ALLOW','ROLE','salesAssistant'),(323,'InvoiceOut','refund','WRITE','ALLOW','ROLE','claimManager'),(324,'Ticket','refund','WRITE','ALLOW','ROLE','invoicing'),(325,'Ticket','refund','WRITE','ALLOW','ROLE','salesAssistant'),(326,'Ticket','refund','WRITE','ALLOW','ROLE','claimManager'),(327,'Sale','refund','WRITE','ALLOW','ROLE','salesAssistant'),(328,'Sale','refund','WRITE','ALLOW','ROLE','claimManager'),(329,'TicketRefund','*','WRITE','ALLOW','ROLE','invoicing'),(330,'ClaimObservation','*','WRITE','ALLOW','ROLE','salesPerson'),(331,'ClaimObservation','*','READ','ALLOW','ROLE','salesPerson'),(332,'Client','setPassword','WRITE','ALLOW','ROLE','salesPerson'),(333,'Client','updateUser','WRITE','ALLOW','ROLE','salesPerson'),(334,'ShelvingLog','*','READ','ALLOW','ROLE','employee'),(335,'ZoneExclusionGeo','*','READ','ALLOW','ROLE','employee'),(336,'ZoneExclusionGeo','*','WRITE','ALLOW','ROLE','deliveryAssist'),(337,'Parking','*','*','ALLOW','ROLE','employee'),(338,'Shelving','*','*','ALLOW','ROLE','employee'),(339,'OsTicket','*','*','ALLOW','ROLE','employee'),(340,'OsTicketConfig','*','*','ALLOW','ROLE','it'),(341,'ClientConsumptionQueue','*','WRITE','ALLOW','ROLE','employee'),(342,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','employee'),(343,'Ticket','deliveryNoteEmail','WRITE','ALLOW','ROLE','employee'),(344,'Ticket','deliveryNoteCsvPdf','READ','ALLOW','ROLE','employee'),(345,'Ticket','deliveryNoteCsvEmail','WRITE','ALLOW','ROLE','employee'),(346,'Client','campaignMetricsPdf','READ','ALLOW','ROLE','employee'),(347,'Client','campaignMetricsEmail','WRITE','ALLOW','ROLE','employee'),(348,'Client','clientWelcomeHtml','READ','ALLOW','ROLE','employee'),(349,'Client','clientWelcomeEmail','WRITE','ALLOW','ROLE','employee'),(350,'Client','creditRequestPdf','READ','ALLOW','ROLE','employee'),(351,'Client','creditRequestHtml','READ','ALLOW','ROLE','employee'),(352,'Client','creditRequestEmail','WRITE','ALLOW','ROLE','employee'),(353,'Client','printerSetupHtml','READ','ALLOW','ROLE','employee'),(354,'Client','printerSetupEmail','WRITE','ALLOW','ROLE','employee'),(355,'Client','sepaCoreEmail','WRITE','ALLOW','ROLE','employee'),(356,'Client','letterDebtorPdf','READ','ALLOW','ROLE','employee'),(357,'Client','letterDebtorStHtml','READ','ALLOW','ROLE','employee'),(358,'Client','letterDebtorStEmail','WRITE','ALLOW','ROLE','employee'),(359,'Client','letterDebtorNdHtml','READ','ALLOW','ROLE','employee'),(360,'Client','letterDebtorNdEmail','WRITE','ALLOW','ROLE','employee'),(361,'Client','clientDebtStatementPdf','READ','ALLOW','ROLE','employee'),(362,'Client','clientDebtStatementHtml','READ','ALLOW','ROLE','employee'),(363,'Client','clientDebtStatementEmail','WRITE','ALLOW','ROLE','employee'),(364,'Client','incotermsAuthorizationPdf','READ','ALLOW','ROLE','employee'),(365,'Client','incotermsAuthorizationHtml','READ','ALLOW','ROLE','employee'),(366,'Client','incotermsAuthorizationEmail','WRITE','ALLOW','ROLE','employee'),(367,'Client','consumptionSendQueued','WRITE','ALLOW','ROLE','system'),(368,'InvoiceOut','invoiceEmail','WRITE','ALLOW','ROLE','employee'),(369,'InvoiceOut','exportationPdf','READ','ALLOW','ROLE','employee'),(370,'InvoiceOut','sendQueued','WRITE','ALLOW','ROLE','system'),(371,'Ticket','invoiceCsvPdf','READ','ALLOW','ROLE','employee'),(372,'Ticket','invoiceCsvEmail','WRITE','ALLOW','ROLE','employee'),(373,'Supplier','campaignMetricsPdf','READ','ALLOW','ROLE','employee'),(374,'Supplier','campaignMetricsEmail','WRITE','ALLOW','ROLE','employee'),(375,'Travel','extraCommunityPdf','READ','ALLOW','ROLE','employee'),(376,'Travel','extraCommunityEmail','WRITE','ALLOW','ROLE','employee'),(377,'Entry','entryOrderPdf','READ','ALLOW','ROLE','employee'),(378,'OsTicket','osTicketReportEmail','WRITE','ALLOW','ROLE','system'),(379,'Item','buyerWasteEmail','WRITE','ALLOW','ROLE','system'),(380,'Claim','claimPickupPdf','READ','ALLOW','ROLE','employee'),(381,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','claimManager'),(382,'Item','labelPdf','READ','ALLOW','ROLE','employee'),(383,'Sector','*','READ','ALLOW','ROLE','employee'),(384,'Sector','*','WRITE','ALLOW','ROLE','employee'),(385,'Route','driverRoutePdf','READ','ALLOW','ROLE','employee'),(386,'Route','driverRouteEmail','WRITE','ALLOW','ROLE','employee'),(387,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','customer'),(388,'Supplier','newSupplier','WRITE','ALLOW','ROLE','administrative'),(389,'ClaimRma','*','READ','ALLOW','ROLE','claimManager'),(390,'ClaimRma','*','WRITE','ALLOW','ROLE','claimManager'),(391,'Notification','*','WRITE','ALLOW','ROLE','system'),(392,'Boxing','*','*','ALLOW','ROLE','employee'),(393,'Url','*','READ','ALLOW','ROLE','employee'),(394,'Url','*','WRITE','ALLOW','ROLE','it'),(395,'ItemShelving','*','READ','ALLOW','ROLE','employee'),(396,'ItemShelving','*','WRITE','ALLOW','ROLE','production'),(397,'ItemShelvingPlacementSupplyStock','*','READ','ALLOW','ROLE','employee'),(398,'NotificationQueue','*','*','ALLOW','ROLE','employee'),(399,'InvoiceOut','clientsToInvoice','WRITE','ALLOW','ROLE','invoicing'),(400,'InvoiceOut','invoiceClient','WRITE','ALLOW','ROLE','invoicing'),(401,'Sale','editTracked','WRITE','ALLOW','ROLE','production'),(402,'Sale','editFloramondo','WRITE','ALLOW','ROLE','salesAssistant'),(403,'Receipt','balanceCompensationEmail','WRITE','ALLOW','ROLE','employee'),(404,'Receipt','balanceCompensationPdf','READ','ALLOW','ROLE','employee'),(405,'Ticket','getTicketsFuture','READ','ALLOW','ROLE','employee'),(406,'Ticket','merge','WRITE','ALLOW','ROLE','employee'),(407,'Sale','editFloramondo','WRITE','ALLOW','ROLE','logistic'),(408,'ZipConfig','*','*','ALLOW','ROLE','employee'),(409,'Item','*','WRITE','ALLOW','ROLE','administrative'),(410,'Sale','editCloned','WRITE','ALLOW','ROLE','buyer'),(411,'Sale','editCloned','WRITE','ALLOW','ROLE','salesAssistant'),(414,'MdbVersion','*','READ','ALLOW','ROLE','$everyone'),(416,'TicketLog','getChanges','READ','ALLOW','ROLE','employee'),(417,'Ticket','getTicketsAdvance','READ','ALLOW','ROLE','employee'),(418,'EntryLog','*','READ','ALLOW','ROLE','administrative'),(419,'Sale','editTracked','WRITE','ALLOW','ROLE','buyer'),(420,'MdbBranch','*','READ','ALLOW','ROLE','$everyone'),(421,'ItemShelvingSale','*','*','ALLOW','ROLE','employee'),(422,'Docuware','checkFile','READ','ALLOW','ROLE','employee'),(423,'Docuware','download','READ','ALLOW','ROLE','salesPerson'),(424,'Docuware','upload','WRITE','ALLOW','ROLE','productionAssi'),(425,'Docuware','deliveryNoteEmail','WRITE','ALLOW','ROLE','salesPerson'),(426,'TpvTransaction','confirm','WRITE','ALLOW','ROLE','$everyone'),(427,'TpvTransaction','start','WRITE','ALLOW','ROLE','$authenticated'),(428,'TpvTransaction','end','WRITE','ALLOW','ROLE','$authenticated'),(429,'ItemConfig','*','READ','ALLOW','ROLE','employee'),(431,'Tag','onSubmit','WRITE','ALLOW','ROLE','employee'),(432,'Worker','updateAttributes','WRITE','ALLOW','ROLE','hr'),(433,'Worker','createAbsence','*','ALLOW','ROLE','employee'),(434,'Worker','updateAbsence','WRITE','ALLOW','ROLE','employee'),(435,'Worker','deleteAbsence','*','ALLOW','ROLE','employee'),(436,'Worker','new','WRITE','ALLOW','ROLE','hr'),(437,'Role','*','READ','ALLOW','ROLE','hr'),(438,'Client','getClientOrSupplierReference','READ','ALLOW','ROLE','employee'),(439,'NotificationSubscription','*','*','ALLOW','ROLE','employee'),(440,'NotificationAcl','*','READ','ALLOW','ROLE','employee'),(441,'MdbApp','*','READ','ALLOW','ROLE','$everyone'),(442,'MdbApp','*','*','ALLOW','ROLE','developer'),(443,'ItemConfig','*','*','ALLOW','ROLE','employee'),(444,'DeviceProduction','*','*','ALLOW','ROLE','hr'),(445,'DeviceProductionModels','*','*','ALLOW','ROLE','hr'),(446,'DeviceProductionState','*','*','ALLOW','ROLE','hr'),(447,'DeviceProductionUser','*','*','ALLOW','ROLE','hr'),(448,'DeviceProduction','*','*','ALLOW','ROLE','productionAssi'),(449,'DeviceProductionModels','*','*','ALLOW','ROLE','productionAssi'),(450,'DeviceProductionState','*','*','ALLOW','ROLE','productionAssi'),(451,'DeviceProductionUser','*','*','ALLOW','ROLE','productionAssi'),(452,'Worker','deallocatePDA','*','ALLOW','ROLE','hr'),(453,'Worker','allocatePDA','*','ALLOW','ROLE','hr'),(454,'Worker','deallocatePDA','*','ALLOW','ROLE','productionAssi'),(455,'Worker','allocatePDA','*','ALLOW','ROLE','productionAssi'),(456,'Zone','*','*','ALLOW','ROLE','deliveryAssist'),(457,'Account','setPassword','WRITE','ALLOW','ROLE','itManagement'),(458,'Operator','*','READ','ALLOW','ROLE','employee'),(459,'Operator','*','WRITE','ALLOW','ROLE','employee'),(460,'InvoiceIn','getSerial','READ','ALLOW','ROLE','administrative'),(461,'Ticket','saveSign','WRITE','ALLOW','ROLE','employee'),(462,'InvoiceOut','negativeBases','READ','ALLOW','ROLE','administrative'),(463,'InvoiceOut','negativeBasesCsv','READ','ALLOW','ROLE','administrative'),(464,'WorkerObservation','*','*','ALLOW','ROLE','hr'),(465,'ClientInforma','*','READ','ALLOW','ROLE','employee'),(466,'ClientInforma','*','WRITE','ALLOW','ROLE','financial'),(467,'Receipt','receiptEmail','*','ALLOW','ROLE','salesAssistant'),(468,'Client','setRating','WRITE','ALLOW','ROLE','financial'),(469,'Client','*','READ','ALLOW','ROLE','employee'),(470,'Client','addressesPropagateRe','*','ALLOW','ROLE','employee'),(471,'Client','canBeInvoiced','*','ALLOW','ROLE','employee'),(472,'Client','canCreateTicket','*','ALLOW','ROLE','employee'),(473,'Client','consumption','*','ALLOW','ROLE','employee'),(474,'Client','createAddress','*','ALLOW','ROLE','employee'),(475,'Client','createWithUser','*','ALLOW','ROLE','employee'),(476,'Client','extendedListFilter','*','ALLOW','ROLE','employee'),(477,'Client','getAverageInvoiced','*','ALLOW','ROLE','employee'),(478,'Client','getCard','*','ALLOW','ROLE','employee'),(479,'Client','getDebt','*','ALLOW','ROLE','employee'),(480,'Client','getMana','*','ALLOW','ROLE','employee'),(481,'Client','transactions','*','ALLOW','ROLE','employee'),(482,'Client','hasCustomerRole','*','ALLOW','ROLE','employee'),(483,'Client','isValidClient','*','ALLOW','ROLE','employee'),(484,'Client','lastActiveTickets','*','ALLOW','ROLE','employee'),(485,'Client','sendSms','*','ALLOW','ROLE','employee'),(486,'Client','setPassword','*','ALLOW','ROLE','employee'),(487,'Client','summary','*','ALLOW','ROLE','employee'),(488,'Client','updateAddress','*','ALLOW','ROLE','employee'),(489,'Client','updateFiscalData','*','ALLOW','ROLE','employee'),(490,'Client','updateUser','*','ALLOW','ROLE','employee'),(491,'Client','uploadFile','*','ALLOW','ROLE','employee'),(492,'Client','campaignMetricsPdf','*','ALLOW','ROLE','employee'),(493,'Client','campaignMetricsEmail','*','ALLOW','ROLE','employee'),(494,'Client','clientWelcomeHtml','*','ALLOW','ROLE','employee'),(495,'Client','clientWelcomeEmail','*','ALLOW','ROLE','employee'),(496,'Client','printerSetupHtml','*','ALLOW','ROLE','employee'),(497,'Client','printerSetupEmail','*','ALLOW','ROLE','employee'),(498,'Client','sepaCoreEmail','*','ALLOW','ROLE','employee'),(499,'Client','letterDebtorPdf','*','ALLOW','ROLE','employee'),(500,'Client','letterDebtorStHtml','*','ALLOW','ROLE','employee'),(501,'Client','letterDebtorStEmail','*','ALLOW','ROLE','employee'),(502,'Client','letterDebtorNdHtml','*','ALLOW','ROLE','employee'),(503,'Client','letterDebtorNdEmail','*','ALLOW','ROLE','employee'),(504,'Client','clientDebtStatementPdf','*','ALLOW','ROLE','employee'),(505,'Client','clientDebtStatementHtml','*','ALLOW','ROLE','employee'),(506,'Client','clientDebtStatementEmail','*','ALLOW','ROLE','employee'),(507,'Client','creditRequestPdf','*','ALLOW','ROLE','employee'),(508,'Client','creditRequestHtml','*','ALLOW','ROLE','employee'),(509,'Client','creditRequestEmail','*','ALLOW','ROLE','employee'),(510,'Client','incotermsAuthorizationPdf','*','ALLOW','ROLE','employee'),(511,'Client','incotermsAuthorizationHtml','*','ALLOW','ROLE','employee'),(512,'Client','incotermsAuthorizationEmail','*','ALLOW','ROLE','employee'),(513,'Client','consumptionSendQueued','*','ALLOW','ROLE','employee'),(514,'Client','filter','*','ALLOW','ROLE','employee'),(515,'Client','getClientOrSupplierReference','*','ALLOW','ROLE','employee'),(516,'Client','upsert','*','ALLOW','ROLE','employee'),(517,'Client','create','*','ALLOW','ROLE','employee'),(518,'Client','replaceById','*','ALLOW','ROLE','employee'),(519,'Client','updateAttributes','*','ALLOW','ROLE','employee'),(520,'Client','updateAttributes','*','ALLOW','ROLE','employee'),(521,'Client','deleteById','*','ALLOW','ROLE','employee'),(522,'Client','replaceOrCreate','*','ALLOW','ROLE','employee'),(523,'Client','updateAll','*','ALLOW','ROLE','employee'),(524,'Client','upsertWithWhere','*','ALLOW','ROLE','employee'),(525,'Defaulter','observationEmail','WRITE','ALLOW','ROLE','employee'),(526,'VnUser','*','*','ALLOW','ROLE','employee'),(527,'VnUser','acl','READ','ALLOW','ROLE','account'),(528,'VnUser','getCurrentUserData','READ','ALLOW','ROLE','account'),(529,'VnUser','changePassword','WRITE','ALLOW','ROLE','account'),(530,'Account','exists','READ','ALLOW','ROLE','account'),(531,'Account','exists','READ','ALLOW','ROLE','account'),(532,'UserLog','*','READ','ALLOW','ROLE','employee'),(533,'RoleLog','*','READ','ALLOW','ROLE','employee'); /*!40000 ALTER TABLE `ACL` ENABLE KEYS */; UNLOCK TABLES; diff --git a/e2e/paths/02-client/01_create_client.spec.js b/e2e/paths/02-client/01_create_client.spec.js index ff2aac6b9..9be9a5915 100644 --- a/e2e/paths/02-client/01_create_client.spec.js +++ b/e2e/paths/02-client/01_create_client.spec.js @@ -8,7 +8,7 @@ describe('Client create path', () => { beforeAll(async() => { browser = await getBrowser(); page = browser.page; - await page.loginAndModule(' deliveryBoss', 'client'); + await page.loginAndModule(' deliveryAssist', 'client'); }); afterAll(async() => { diff --git a/e2e/paths/03-worker/06_create.spec.js b/e2e/paths/03-worker/06_create.spec.js index 98e67edbf..3257f170f 100644 --- a/e2e/paths/03-worker/06_create.spec.js +++ b/e2e/paths/03-worker/06_create.spec.js @@ -45,7 +45,7 @@ describe('Worker create path', () => { // should create a new worker and go to worker basic data' await page.pickDate(selectors.workerCreate.birth, new Date(1962, 8, 5)); - await page.autocompleteSearch(selectors.workerCreate.boss, 'deliveryBoss'); + await page.autocompleteSearch(selectors.workerCreate.boss, 'deliveryAssist'); await page.waitToClick(selectors.workerCreate.createButton); message = await page.waitForSnackbar(); await page.waitForState('worker.card.basicData'); diff --git a/e2e/paths/11-zone/01_basic-data.spec.js b/e2e/paths/11-zone/01_basic-data.spec.js index ded40579d..be83ed565 100644 --- a/e2e/paths/11-zone/01_basic-data.spec.js +++ b/e2e/paths/11-zone/01_basic-data.spec.js @@ -8,7 +8,8 @@ describe('Zone basic data path', () => { beforeAll(async() => { browser = await getBrowser(); page = browser.page; - await page.loginAndModule('deliveryBoss', 'zone'); // turns up the zone module name and route aint the same lol + // eslint-disable-next-line max-len + await page.loginAndModule('deliveryAssist', 'zone'); // turns up the zone module name and route aint the same lol await page.accessToSearchResult('10'); await page.accessToSection('zone.card.basicData'); }); diff --git a/e2e/paths/11-zone/02_descriptor.spec.js b/e2e/paths/11-zone/02_descriptor.spec.js index f3c0e7740..56340efe7 100644 --- a/e2e/paths/11-zone/02_descriptor.spec.js +++ b/e2e/paths/11-zone/02_descriptor.spec.js @@ -8,7 +8,7 @@ describe('Zone descriptor path', () => { beforeAll(async() => { browser = await getBrowser(); page = browser.page; - await page.loginAndModule('deliveryBoss', 'zone'); + await page.loginAndModule('deliveryAssist', 'zone'); await page.accessToSearchResult('13'); }); diff --git a/modules/client/front/address/create/index.html b/modules/client/front/address/create/index.html index 96bd8f114..1e2bf1470 100644 --- a/modules/client/front/address/create/index.html +++ b/modules/client/front/address/create/index.html @@ -31,7 +31,7 @@ - + - {{code}} - {{town.name}} ({{town.province.name}}, + {{code}} - {{town.name}} ({{town.province.name}}, {{town.province.country.country}}) @@ -68,12 +68,12 @@ icon="add_circle" vn-tooltip="New postcode" ng-click="postcode.open()" - vn-acl="deliveryBoss" + vn-acl="deliveryAssist" vn-acl-action="remove"> - - @@ -190,4 +190,4 @@ - \ No newline at end of file + diff --git a/modules/client/front/address/edit/index.html b/modules/client/front/address/edit/index.html index 1f0b7d30a..0ba780ef8 100644 --- a/modules/client/front/address/edit/index.html +++ b/modules/client/front/address/edit/index.html @@ -73,20 +73,20 @@ show-field="code" rule> - {{code}} - {{town.name}} ({{town.province.name}}, + {{code}} - {{town.name}} ({{town.province.name}}, {{town.province.country.country}}) - - - + @@ -197,12 +197,12 @@ - - @@ -234,4 +234,4 @@ - \ No newline at end of file + diff --git a/modules/client/front/create/index.html b/modules/client/front/create/index.html index 3e7fdd949..dd13e7a10 100644 --- a/modules/client/front/create/index.html +++ b/modules/client/front/create/index.html @@ -26,7 +26,7 @@ - - {{code}} - {{town.name}} ({{town.province.name}}, + {{code}} - {{town.name}} ({{town.province.name}}, {{town.province.country.country}}) @@ -76,13 +76,13 @@ icon="add_circle" vn-tooltip="New postcode" ng-click="postcode.open()" - vn-acl="deliveryBoss" + vn-acl="deliveryAssist" vn-acl-action="remove"> - {{name}}, {{province.name}} + {{name}}, {{province.name}} ({{province.country.country}}) @@ -150,4 +150,4 @@ - \ No newline at end of file + diff --git a/modules/client/front/fiscal-data/index.html b/modules/client/front/fiscal-data/index.html index d232d6dab..8dffcf4ca 100644 --- a/modules/client/front/fiscal-data/index.html +++ b/modules/client/front/fiscal-data/index.html @@ -92,7 +92,7 @@ icon="add_circle" vn-tooltip="New postcode" ng-click="postcode.open()" - vn-acl="deliveryBoss" + vn-acl="deliveryAssist" vn-acl-action="remove"> diff --git a/modules/client/front/postcode/index.html b/modules/client/front/postcode/index.html index 8f9f35eb8..ad1580945 100644 --- a/modules/client/front/postcode/index.html +++ b/modules/client/front/postcode/index.html @@ -27,7 +27,7 @@ icon="add_circle" vn-tooltip="New city" ng-click="city.open($event)" - vn-acl="deliveryBoss" + vn-acl="deliveryAssist" vn-acl-action="remove"> @@ -45,7 +45,7 @@ icon="add_circle" vn-tooltip="New province" ng-click="province.open($event)" - vn-acl="deliveryBoss" + vn-acl="deliveryAssist" vn-acl-action="remove"> @@ -73,4 +73,4 @@ - \ No newline at end of file + diff --git a/modules/route/front/descriptor/index.html b/modules/route/front/descriptor/index.html index 6d6fb082e..8b6cf6535 100644 --- a/modules/route/front/descriptor/index.html +++ b/modules/route/front/descriptor/index.html @@ -15,14 +15,14 @@ Update volume Delete route @@ -31,23 +31,23 @@
@@ -72,4 +72,4 @@ - \ No newline at end of file + diff --git a/modules/route/front/tickets/index.html b/modules/route/front/tickets/index.html index 32a4a2d7c..5723b118f 100644 --- a/modules/route/front/tickets/index.html +++ b/modules/route/front/tickets/index.html @@ -37,7 +37,7 @@ icon="format_list_numbered"> {{::ticket.street}} - diff --git a/modules/supplier/front/address/edit/index.html b/modules/supplier/front/address/edit/index.html index dd4cbb4d2..2dbb34f15 100644 --- a/modules/supplier/front/address/edit/index.html +++ b/modules/supplier/front/address/edit/index.html @@ -40,20 +40,20 @@ show-field="code" rule> - {{code}} - {{town.name}} ({{town.province.name}}, + {{code}} - {{town.name}} ({{town.province.name}}, {{town.province.country.country}}) - - - - \ No newline at end of file + diff --git a/modules/supplier/front/fiscal-data/index.html b/modules/supplier/front/fiscal-data/index.html index 218fe284d..ed6798c3c 100644 --- a/modules/supplier/front/fiscal-data/index.html +++ b/modules/supplier/front/fiscal-data/index.html @@ -150,7 +150,7 @@ icon="add_circle" vn-tooltip="New postcode" ng-click="postcode.open()" - vn-acl="deliveryBoss" + vn-acl="deliveryAssist" vn-acl-action="remove"> diff --git a/modules/worker/front/create/index.html b/modules/worker/front/create/index.html index eb45704a7..24f719a68 100644 --- a/modules/worker/front/create/index.html +++ b/modules/worker/front/create/index.html @@ -72,7 +72,7 @@ icon="add_circle" vn-tooltip="New postcode" ng-click="postcode.open()" - vn-acl="deliveryBoss" + vn-acl="deliveryAssist" vn-acl-action="remove"> diff --git a/modules/zone/front/basic-data/index.html b/modules/zone/front/basic-data/index.html index 8d8fc6c56..39fb25fae 100644 --- a/modules/zone/front/basic-data/index.html +++ b/modules/zone/front/basic-data/index.html @@ -12,9 +12,9 @@ @@ -26,7 +26,7 @@ show-field="name" value-field="id" label="Agency" - vn-acl="deliveryBoss" + vn-acl="deliveryAssist" rule> @@ -52,13 +52,13 @@ ng-model="$ctrl.zone.travelingDays" min="0" step="1" - vn-acl="deliveryBoss" + vn-acl="deliveryAssist" rule> @@ -68,16 +68,16 @@ ng-model="$ctrl.zone.price" min="0" step="0.01" - vn-acl="deliveryBoss" + vn-acl="deliveryAssist" rule> - + @@ -101,7 +101,7 @@ - diff --git a/modules/zone/front/location/index.html b/modules/zone/front/location/index.html index a9e9261a8..caace6660 100644 --- a/modules/zone/front/location/index.html +++ b/modules/zone/front/location/index.html @@ -16,12 +16,12 @@ root-label="Locations" fetch-func="$ctrl.onFetch($item)" sort-func="$ctrl.onSort($a, $b)"> - + label="{{::item.name}}"> From ee5677ecb60ec030d10bd4e8a311572a3563f871 Mon Sep 17 00:00:00 2001 From: carlossa Date: Fri, 16 Jun 2023 09:28:56 +0200 Subject: [PATCH 015/427] refs #5660 fix line --- e2e/paths/11-zone/01_basic-data.spec.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/e2e/paths/11-zone/01_basic-data.spec.js b/e2e/paths/11-zone/01_basic-data.spec.js index be83ed565..c06f955c6 100644 --- a/e2e/paths/11-zone/01_basic-data.spec.js +++ b/e2e/paths/11-zone/01_basic-data.spec.js @@ -8,8 +8,9 @@ describe('Zone basic data path', () => { beforeAll(async() => { browser = await getBrowser(); page = browser.page; - // eslint-disable-next-line max-len - await page.loginAndModule('deliveryAssist', 'zone'); // turns up the zone module name and route aint the same lol + + await page.loginAndModule('deliveryAssist', + 'zone'); // turns up the zone module name and route aint the same lol await page.accessToSearchResult('10'); await page.accessToSection('zone.card.basicData'); }); From 9870cc7b14c290af7e1d922e257d1f15f76ba5ff Mon Sep 17 00:00:00 2001 From: carlossa Date: Wed, 21 Jun 2023 13:34:27 +0200 Subject: [PATCH 016/427] refs #5660 change assist --- db/changes/232601/00-deliveryAssistantACL.sql | 2 +- db/changes/232601/00-useSpecificsAcls.sql | 4 ++-- db/dump/dumpedFixtures.sql | 4 ++-- e2e/paths/02-client/01_create_client.spec.js | 2 +- e2e/paths/03-worker/06_create.spec.js | 2 +- e2e/paths/11-zone/01_basic-data.spec.js | 2 +- e2e/paths/11-zone/02_descriptor.spec.js | 2 +- .../client/front/address/create/index.html | 2 +- modules/client/front/address/edit/index.html | 2 +- modules/client/front/create/index.html | 2 +- modules/client/front/fiscal-data/index.html | 2 +- modules/client/front/postcode/index.html | 4 ++-- modules/route/front/descriptor/index.html | 4 ++-- modules/route/front/tickets/index.html | 2 +- .../supplier/front/address/create/index.html | 2 +- .../supplier/front/address/edit/index.html | 2 +- modules/supplier/front/fiscal-data/index.html | 2 +- modules/worker/front/create/index.html | 2 +- modules/zone/front/basic-data/index.html | 22 +++++++++---------- modules/zone/front/index/index.html | 4 ++-- modules/zone/front/location/index.html | 2 +- 21 files changed, 36 insertions(+), 36 deletions(-) diff --git a/db/changes/232601/00-deliveryAssistantACL.sql b/db/changes/232601/00-deliveryAssistantACL.sql index 6c829867a..e5152087e 100644 --- a/db/changes/232601/00-deliveryAssistantACL.sql +++ b/db/changes/232601/00-deliveryAssistantACL.sql @@ -1,7 +1,7 @@ -- Auto-generated SQL script #202306121356 UPDATE `account`.`role` SET `description` = 'Asistente de envios' - WHERE `name` = 'deliveryAssist'; + WHERE `name` = 'deliveryAssistant'; diff --git a/db/changes/232601/00-useSpecificsAcls.sql b/db/changes/232601/00-useSpecificsAcls.sql index cfe60ec9c..d124786f6 100644 --- a/db/changes/232601/00-useSpecificsAcls.sql +++ b/db/changes/232601/00-useSpecificsAcls.sql @@ -3,11 +3,11 @@ INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `pri ('Ticket', 'editDiscount', 'WRITE', 'ALLOW', 'ROLE', 'claimManager'), ('Ticket', 'editDiscount', 'WRITE', 'ALLOW', 'ROLE', 'salesPerson'), ('Ticket', 'isRoleAdvanced', '*', 'ALLOW', 'ROLE', 'salesAssistant'), - ('Ticket', 'isRoleAdvanced', '*', 'ALLOW', 'ROLE', 'deliveryAssist'), + ('Ticket', 'isRoleAdvanced', '*', 'ALLOW', 'ROLE', 'deliveryAssistant'), ('Ticket', 'isRoleAdvanced', '*', 'ALLOW', 'ROLE', 'buyer'), ('Ticket', 'isRoleAdvanced', '*', 'ALLOW', 'ROLE', 'claimManager'), ('Ticket', 'deleteTicketWithPartPrepared', 'WRITE', 'ALLOW', 'ROLE', 'salesAssistant'), - ('Ticket', 'editZone', 'WRITE', 'ALLOW', 'ROLE', 'deliveryAssist'), + ('Ticket', 'editZone', 'WRITE', 'ALLOW', 'ROLE', 'deliveryAssistant'), ('State', 'editableStates', 'READ', 'ALLOW', 'ROLE', 'employee'), ('State', 'seeEditableStates', 'READ', 'ALLOW', 'ROLE', 'administrative'), ('State', 'seeEditableStates', 'READ', 'ALLOW', 'ROLE', 'production'), diff --git a/db/dump/dumpedFixtures.sql b/db/dump/dumpedFixtures.sql index 52c6e1073..3403ffaf3 100644 --- a/db/dump/dumpedFixtures.sql +++ b/db/dump/dumpedFixtures.sql @@ -78,7 +78,7 @@ USE `account`; LOCK TABLES `role` WRITE; /*!40000 ALTER TABLE `role` DISABLE KEYS */; -INSERT INTO `role` VALUES (1,'employee','Empleado básico',1,'2017-05-19 07:04:58','2017-11-29 10:06:31',NULL),(2,'customer','Privilegios básicos de un cliente',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(3,'agency','Consultar tablas de predicciones de bultos',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(5,'administrative','Tareas relacionadas con la contabilidad',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(6,'guest','Privilegios para usuarios sin cuenta',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(9,'developer','Desarrolladores del sistema',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(11,'account','Privilegios relacionados con el login',0,'2017-05-19 07:04:58','2017-09-20 17:06:35',NULL),(13,'teamBoss','Jefe de equipo/departamento',1,'2017-05-19 07:04:58','2021-06-30 13:29:30',NULL),(15,'logistic','Departamento de compras, responsables de la logistica',1,'2017-05-19 07:04:58','2018-02-12 10:50:10',NULL),(16,'logisticBoss','Jefe del departamento de logística',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(17,'adminBoss','Jefe del departamento de administración',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(18,'salesPerson','Departamento de ventas',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(19,'salesBoss','Jefe del departamento de ventas',1,'2017-05-19 07:04:58','2017-08-16 12:38:27',NULL),(20,'manager','Gerencia',1,'2017-06-01 14:57:02','2022-07-29 07:36:15',NULL),(21,'salesAssistant','Jefe auxiliar de ventas',1,'2017-08-16 12:40:52','2017-08-16 12:40:52',NULL),(22,'teamManager','Jefe de departamento con privilegios de auxiliar de venta.',1,'2017-09-07 09:08:12','2017-09-07 09:08:12',NULL),(30,'financialBoss','Director finaciero',1,'2017-09-21 11:05:36','2017-09-21 11:05:36',NULL),(31,'freelancer','Trabajadores por cuenta ajena',1,'2017-10-10 12:57:26','2017-10-10 12:59:27',NULL),(32,'ett','Trabajadores de empresa temporal',1,'2017-10-10 12:58:58','2017-10-10 12:59:20',NULL),(33,'invoicing','Personal con acceso a facturación',0,'2018-01-29 16:43:34','2018-01-29 16:43:34',NULL),(34,'agencyBoss','Jefe/a del departamento de agencias',1,'2018-01-29 16:44:39','2018-02-23 07:58:53',NULL),(35,'buyer','Departamento de compras',1,'2018-02-12 10:35:42','2018-02-12 10:35:42',NULL),(36,'replenisher','Trabajadores de camara',1,'2018-02-16 14:07:10','2019-04-12 05:38:08',NULL),(37,'hr','Gestor/a de recursos humanos',1,'2018-02-22 17:34:53','2018-02-22 17:34:53',NULL),(38,'hrBoss','Jefe/a de recursos humanos',1,'2018-02-22 17:35:09','2018-02-22 17:35:09',NULL),(39,'adminAssistant','Jefe auxiliar administrativo',1,'2018-02-23 10:37:36','2018-02-23 10:38:41',NULL),(40,'handmade','Departamento de confección',1,'2018-02-23 11:14:53','2018-02-23 11:39:12',NULL),(41,'handmadeBoss','Jefe de departamento de confección',1,'2018-02-23 11:15:09','2018-02-23 11:39:26',NULL),(42,'artificial','Departamento de artificial',1,'2018-02-23 11:39:59','2018-02-23 11:39:59',NULL),(43,'artificialBoss','Jefe del departamento de artificial',1,'2018-02-23 11:40:16','2018-02-23 11:40:16',NULL),(44,'accessory','Departamento de complementos',1,'2018-02-23 11:41:12','2018-02-23 11:41:12',NULL),(45,'accessoryBoss','Jefe del departamento de complementos',1,'2018-02-23 11:41:23','2018-02-23 11:41:23',NULL),(47,'cooler','Empleados de cámara',1,'2018-02-23 13:08:18','2018-02-23 13:08:18',NULL),(48,'coolerBoss','Jefe de cámara',1,'2018-02-23 13:12:01','2023-03-13 08:49:43',NULL),(49,'production','Empleado de producción',1,'2018-02-26 15:28:23','2021-02-12 09:42:35',NULL),(50,'productionBoss','Jefe de producción',1,'2018-02-26 15:34:12','2018-02-26 15:34:12',NULL),(51,'marketing','Departamento de marketing',1,'2018-03-01 07:28:39','2018-03-01 07:28:39',NULL),(52,'marketingBoss','Jefe del departamento de marketing',1,'2018-03-01 07:28:57','2018-03-01 07:28:57',NULL),(53,'insurance','Gestor de seguros de cambio',0,'2018-03-05 07:44:35','2019-02-01 13:47:57',NULL),(54,'itemPicker','Sacador en cámara',1,'2018-03-05 12:08:17','2018-03-05 12:08:17',NULL),(55,'itemPickerBoss','Jefe de sacadores',1,'2018-03-05 12:08:31','2018-03-05 12:08:31',NULL),(56,'delivery','Personal de reparto',1,'2018-05-30 06:07:02','2018-05-30 06:07:02',NULL),(57,'deliveryAssist','Jefe de personal de reparto',1,'2018-05-30 06:07:19','2018-05-30 06:07:19',NULL),(58,'packager','Departamento encajadores',1,'2019-01-21 12:43:45','2019-01-21 12:43:45',NULL),(59,'packagerBoss','Jefe departamento encajadores',1,'2019-01-21 12:44:10','2019-01-21 12:44:10',NULL),(60,'productionAssi','Tareas relacionadas con producción y administración',1,'2019-01-29 13:29:01','2019-01-29 13:29:01',NULL),(61,'replenisherBos','Jefe de Complementos/Camara',1,'2019-07-01 06:44:07','2019-07-01 06:44:07',NULL),(62,'noLogin','Role without login access to MySQL',0,'2019-07-01 06:50:19','2019-07-02 13:42:05',NULL),(64,'balanceSheet','Consulta de Balance',0,'2019-07-16 12:12:08','2019-07-16 12:12:08',NULL),(65,'officeBoss','Jefe de filial',1,'2019-08-02 06:54:26','2019-08-02 06:54:26',NULL),(66,'sysadmin','Administrador de sistema',1,'2019-08-08 06:58:56','2019-08-08 06:58:56',NULL),(67,'adminOfficer','categoria profesional oficial de administración',1,'2020-01-03 08:09:23','2020-01-03 08:09:23',NULL),(69,'coolerAssist','Asistente de cámara con permiso compras',1,'2020-02-05 12:36:09','2023-03-13 08:50:07',NULL),(70,'trainee','Alumno de prácticas',1,'2020-03-04 11:00:25','2020-03-04 11:00:25',NULL),(71,'checker','Rol de revisor con privilegios de itemPicker',1,'2020-10-02 10:50:07','2020-10-02 10:50:07',NULL),(72,'claimManager','Personal de reclamaciones',1,'2020-10-13 10:01:32','2020-10-26 07:29:46',NULL),(73,'financial','Departamento de finanzas',1,'2020-11-16 09:30:27','2020-11-16 09:30:27',NULL),(74,'userPhotos','Privilegios para subir fotos de usuario',1,'2021-02-03 10:24:27','2021-02-03 10:24:27',NULL),(75,'catalogPhotos','Privilegios para subir fotos del catálogo',1,'2021-02-03 10:24:27','2021-02-03 10:24:27',NULL),(76,'chat','Rol para utilizar el rocket chat',1,'2020-11-27 13:06:50','2020-12-17 07:49:41',NULL),(100,'root','Rol con todos los privilegios',0,'2018-04-23 14:33:36','2020-11-12 06:50:07',NULL),(101,'buyerBoss','Jefe del departamento de compras',1,'2021-06-16 09:53:17','2021-06-16 09:53:17',NULL),(102,'preservedBoss','Responsable preservado',1,'2021-09-14 13:45:37','2021-09-14 13:45:37',NULL),(103,'it','Departamento de informática',1,'2021-11-11 09:48:22','2021-11-11 09:48:22',NULL),(104,'itBoss','Jefe de departamento de informática',1,'2021-11-11 09:48:49','2021-11-11 09:48:49',NULL),(105,'grant','Adjudicar roles a usuarios',1,'2021-11-11 12:41:09','2021-11-11 12:41:09',NULL),(106,'ext','Usuarios externos de la Base de datos',1,'2021-11-23 14:51:16','2021-11-23 14:51:16',NULL),(107,'productionPlus','Creado para pepe por orden de Juanvi',1,'2022-02-08 06:47:10','2022-02-08 06:47:10',NULL),(108,'system','System user',1,'2022-05-16 08:09:51','2022-05-16 08:09:51',NULL),(109,'salesTeamBoss','Jefe de equipo de comerciales',1,'2022-06-14 13:45:56','2022-06-14 13:45:56',NULL),(110,'palletizer','Paletizadores',1,'2022-12-02 12:56:22','2022-12-02 12:56:30',NULL),(111,'entryEditor','Entry editor',1,'2023-01-13 11:21:55','2023-01-13 11:21:55',NULL),(112,'maintenance','Personal de mantenimiento',1,'2023-01-19 06:23:35','2023-01-19 06:23:35',NULL),(114,'maintenanceBos','Jefe de mantenimiento',1,'2023-01-19 06:31:16','2023-05-12 08:47:34',19294),(115,'itManagement','TI management',1,'2023-03-29 07:27:55','2023-03-29 07:28:04',NULL); +INSERT INTO `role` VALUES (1,'employee','Empleado básico',1,'2017-05-19 07:04:58','2017-11-29 10:06:31',NULL),(2,'customer','Privilegios básicos de un cliente',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(3,'agency','Consultar tablas de predicciones de bultos',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(5,'administrative','Tareas relacionadas con la contabilidad',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(6,'guest','Privilegios para usuarios sin cuenta',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(9,'developer','Desarrolladores del sistema',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(11,'account','Privilegios relacionados con el login',0,'2017-05-19 07:04:58','2017-09-20 17:06:35',NULL),(13,'teamBoss','Jefe de equipo/departamento',1,'2017-05-19 07:04:58','2021-06-30 13:29:30',NULL),(15,'logistic','Departamento de compras, responsables de la logistica',1,'2017-05-19 07:04:58','2018-02-12 10:50:10',NULL),(16,'logisticBoss','Jefe del departamento de logística',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(17,'adminBoss','Jefe del departamento de administración',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(18,'salesPerson','Departamento de ventas',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(19,'salesBoss','Jefe del departamento de ventas',1,'2017-05-19 07:04:58','2017-08-16 12:38:27',NULL),(20,'manager','Gerencia',1,'2017-06-01 14:57:02','2022-07-29 07:36:15',NULL),(21,'salesAssistant','Jefe auxiliar de ventas',1,'2017-08-16 12:40:52','2017-08-16 12:40:52',NULL),(22,'teamManager','Jefe de departamento con privilegios de auxiliar de venta.',1,'2017-09-07 09:08:12','2017-09-07 09:08:12',NULL),(30,'financialBoss','Director finaciero',1,'2017-09-21 11:05:36','2017-09-21 11:05:36',NULL),(31,'freelancer','Trabajadores por cuenta ajena',1,'2017-10-10 12:57:26','2017-10-10 12:59:27',NULL),(32,'ett','Trabajadores de empresa temporal',1,'2017-10-10 12:58:58','2017-10-10 12:59:20',NULL),(33,'invoicing','Personal con acceso a facturación',0,'2018-01-29 16:43:34','2018-01-29 16:43:34',NULL),(34,'agencyBoss','Jefe/a del departamento de agencias',1,'2018-01-29 16:44:39','2018-02-23 07:58:53',NULL),(35,'buyer','Departamento de compras',1,'2018-02-12 10:35:42','2018-02-12 10:35:42',NULL),(36,'replenisher','Trabajadores de camara',1,'2018-02-16 14:07:10','2019-04-12 05:38:08',NULL),(37,'hr','Gestor/a de recursos humanos',1,'2018-02-22 17:34:53','2018-02-22 17:34:53',NULL),(38,'hrBoss','Jefe/a de recursos humanos',1,'2018-02-22 17:35:09','2018-02-22 17:35:09',NULL),(39,'adminAssistant','Jefe auxiliar administrativo',1,'2018-02-23 10:37:36','2018-02-23 10:38:41',NULL),(40,'handmade','Departamento de confección',1,'2018-02-23 11:14:53','2018-02-23 11:39:12',NULL),(41,'handmadeBoss','Jefe de departamento de confección',1,'2018-02-23 11:15:09','2018-02-23 11:39:26',NULL),(42,'artificial','Departamento de artificial',1,'2018-02-23 11:39:59','2018-02-23 11:39:59',NULL),(43,'artificialBoss','Jefe del departamento de artificial',1,'2018-02-23 11:40:16','2018-02-23 11:40:16',NULL),(44,'accessory','Departamento de complementos',1,'2018-02-23 11:41:12','2018-02-23 11:41:12',NULL),(45,'accessoryBoss','Jefe del departamento de complementos',1,'2018-02-23 11:41:23','2018-02-23 11:41:23',NULL),(47,'cooler','Empleados de cámara',1,'2018-02-23 13:08:18','2018-02-23 13:08:18',NULL),(48,'coolerBoss','Jefe de cámara',1,'2018-02-23 13:12:01','2023-03-13 08:49:43',NULL),(49,'production','Empleado de producción',1,'2018-02-26 15:28:23','2021-02-12 09:42:35',NULL),(50,'productionBoss','Jefe de producción',1,'2018-02-26 15:34:12','2018-02-26 15:34:12',NULL),(51,'marketing','Departamento de marketing',1,'2018-03-01 07:28:39','2018-03-01 07:28:39',NULL),(52,'marketingBoss','Jefe del departamento de marketing',1,'2018-03-01 07:28:57','2018-03-01 07:28:57',NULL),(53,'insurance','Gestor de seguros de cambio',0,'2018-03-05 07:44:35','2019-02-01 13:47:57',NULL),(54,'itemPicker','Sacador en cámara',1,'2018-03-05 12:08:17','2018-03-05 12:08:17',NULL),(55,'itemPickerBoss','Jefe de sacadores',1,'2018-03-05 12:08:31','2018-03-05 12:08:31',NULL),(56,'delivery','Personal de reparto',1,'2018-05-30 06:07:02','2018-05-30 06:07:02',NULL),(57,'deliveryAssistantant','Jefe de personal de reparto',1,'2018-05-30 06:07:19','2018-05-30 06:07:19',NULL),(58,'packager','Departamento encajadores',1,'2019-01-21 12:43:45','2019-01-21 12:43:45',NULL),(59,'packagerBoss','Jefe departamento encajadores',1,'2019-01-21 12:44:10','2019-01-21 12:44:10',NULL),(60,'productionAssi','Tareas relacionadas con producción y administración',1,'2019-01-29 13:29:01','2019-01-29 13:29:01',NULL),(61,'replenisherBos','Jefe de Complementos/Camara',1,'2019-07-01 06:44:07','2019-07-01 06:44:07',NULL),(62,'noLogin','Role without login access to MySQL',0,'2019-07-01 06:50:19','2019-07-02 13:42:05',NULL),(64,'balanceSheet','Consulta de Balance',0,'2019-07-16 12:12:08','2019-07-16 12:12:08',NULL),(65,'officeBoss','Jefe de filial',1,'2019-08-02 06:54:26','2019-08-02 06:54:26',NULL),(66,'sysadmin','Administrador de sistema',1,'2019-08-08 06:58:56','2019-08-08 06:58:56',NULL),(67,'adminOfficer','categoria profesional oficial de administración',1,'2020-01-03 08:09:23','2020-01-03 08:09:23',NULL),(69,'coolerAssist','Asistente de cámara con permiso compras',1,'2020-02-05 12:36:09','2023-03-13 08:50:07',NULL),(70,'trainee','Alumno de prácticas',1,'2020-03-04 11:00:25','2020-03-04 11:00:25',NULL),(71,'checker','Rol de revisor con privilegios de itemPicker',1,'2020-10-02 10:50:07','2020-10-02 10:50:07',NULL),(72,'claimManager','Personal de reclamaciones',1,'2020-10-13 10:01:32','2020-10-26 07:29:46',NULL),(73,'financial','Departamento de finanzas',1,'2020-11-16 09:30:27','2020-11-16 09:30:27',NULL),(74,'userPhotos','Privilegios para subir fotos de usuario',1,'2021-02-03 10:24:27','2021-02-03 10:24:27',NULL),(75,'catalogPhotos','Privilegios para subir fotos del catálogo',1,'2021-02-03 10:24:27','2021-02-03 10:24:27',NULL),(76,'chat','Rol para utilizar el rocket chat',1,'2020-11-27 13:06:50','2020-12-17 07:49:41',NULL),(100,'root','Rol con todos los privilegios',0,'2018-04-23 14:33:36','2020-11-12 06:50:07',NULL),(101,'buyerBoss','Jefe del departamento de compras',1,'2021-06-16 09:53:17','2021-06-16 09:53:17',NULL),(102,'preservedBoss','Responsable preservado',1,'2021-09-14 13:45:37','2021-09-14 13:45:37',NULL),(103,'it','Departamento de informática',1,'2021-11-11 09:48:22','2021-11-11 09:48:22',NULL),(104,'itBoss','Jefe de departamento de informática',1,'2021-11-11 09:48:49','2021-11-11 09:48:49',NULL),(105,'grant','Adjudicar roles a usuarios',1,'2021-11-11 12:41:09','2021-11-11 12:41:09',NULL),(106,'ext','Usuarios externos de la Base de datos',1,'2021-11-23 14:51:16','2021-11-23 14:51:16',NULL),(107,'productionPlus','Creado para pepe por orden de Juanvi',1,'2022-02-08 06:47:10','2022-02-08 06:47:10',NULL),(108,'system','System user',1,'2022-05-16 08:09:51','2022-05-16 08:09:51',NULL),(109,'salesTeamBoss','Jefe de equipo de comerciales',1,'2022-06-14 13:45:56','2022-06-14 13:45:56',NULL),(110,'palletizer','Paletizadores',1,'2022-12-02 12:56:22','2022-12-02 12:56:30',NULL),(111,'entryEditor','Entry editor',1,'2023-01-13 11:21:55','2023-01-13 11:21:55',NULL),(112,'maintenance','Personal de mantenimiento',1,'2023-01-19 06:23:35','2023-01-19 06:23:35',NULL),(114,'maintenanceBos','Jefe de mantenimiento',1,'2023-01-19 06:31:16','2023-05-12 08:47:34',19294),(115,'itManagement','TI management',1,'2023-03-29 07:27:55','2023-03-29 07:28:04',NULL); /*!40000 ALTER TABLE `role` ENABLE KEYS */; UNLOCK TABLES; @@ -164,7 +164,7 @@ USE `salix`; LOCK TABLES `ACL` WRITE; /*!40000 ALTER TABLE `ACL` DISABLE KEYS */; -INSERT INTO `ACL` VALUES (1,'Account','*','*','ALLOW','ROLE','employee'),(3,'Address','*','*','ALLOW','ROLE','employee'),(5,'AgencyService','*','READ','ALLOW','ROLE','employee'),(9,'ClientObservation','*','*','ALLOW','ROLE','employee'),(11,'ContactChannel','*','READ','ALLOW','ROLE','trainee'),(13,'Employee','*','READ','ALLOW','ROLE','employee'),(14,'PayMethod','*','READ','ALLOW','ROLE','trainee'),(16,'FakeProduction','*','READ','ALLOW','ROLE','employee'),(17,'Warehouse','* ','READ','ALLOW','ROLE','trainee'),(18,'State','*','READ','ALLOW','ROLE','employee'),(20,'TicketState','*','*','ALLOW','ROLE','employee'),(24,'Delivery','*','READ','ALLOW','ROLE','employee'),(25,'Zone','*','READ','ALLOW','ROLE','employee'),(26,'ClientCredit','*','*','ALLOW','ROLE','employee'),(27,'ClientCreditLimit','*','READ','ALLOW','ROLE','trainee'),(30,'GreugeType','*','READ','ALLOW','ROLE','trainee'),(31,'Mandate','*','READ','ALLOW','ROLE','trainee'),(32,'MandateType','*','READ','ALLOW','ROLE','trainee'),(33,'Company','*','READ','ALLOW','ROLE','trainee'),(34,'Greuge','*','READ','ALLOW','ROLE','trainee'),(35,'AddressObservation','*','*','ALLOW','ROLE','employee'),(36,'ObservationType','*','*','ALLOW','ROLE','employee'),(37,'Greuge','*','WRITE','ALLOW','ROLE','employee'),(38,'AgencyMode','*','READ','ALLOW','ROLE','employee'),(39,'ItemTag','*','WRITE','ALLOW','ROLE','buyer'),(40,'ItemBotanical','*','WRITE','ALLOW','ROLE','buyer'),(41,'ItemBotanical','*','READ','ALLOW','ROLE','employee'),(42,'ItemPlacement','*','WRITE','ALLOW','ROLE','buyer'),(43,'ItemPlacement','*','WRITE','ALLOW','ROLE','replenisher'),(44,'ItemPlacement','*','READ','ALLOW','ROLE','employee'),(45,'ItemBarcode','*','READ','ALLOW','ROLE','employee'),(46,'ItemBarcode','*','WRITE','ALLOW','ROLE','buyer'),(47,'ItemBarcode','*','WRITE','ALLOW','ROLE','replenisher'),(51,'ItemTag','*','READ','ALLOW','ROLE','employee'),(53,'Item','*','READ','ALLOW','ROLE','employee'),(54,'Item','*','WRITE','ALLOW','ROLE','buyer'),(55,'Recovery','*','READ','ALLOW','ROLE','trainee'),(56,'Recovery','*','WRITE','ALLOW','ROLE','administrative'),(58,'CreditClassification','*','*','ALLOW','ROLE','insurance'),(60,'CreditInsurance','*','*','ALLOW','ROLE','insurance'),(61,'InvoiceOut','*','READ','ALLOW','ROLE','employee'),(62,'Ticket','*','*','ALLOW','ROLE','employee'),(63,'TicketObservation','*','*','ALLOW','ROLE','employee'),(64,'Route','*','READ','ALLOW','ROLE','employee'),(65,'Sale','*','READ','ALLOW','ROLE','employee'),(66,'TicketTracking','*','READ','ALLOW','ROLE','employee'),(68,'TicketPackaging','*','*','ALLOW','ROLE','employee'),(69,'Packaging','*','READ','ALLOW','ROLE','employee'),(70,'Packaging','*','WRITE','ALLOW','ROLE','logistic'),(72,'SaleComponent','*','READ','ALLOW','ROLE','employee'),(73,'Expedition','*','READ','ALLOW','ROLE','employee'),(74,'Expedition','*','WRITE','ALLOW','ROLE','deliveryAssist'),(75,'Expedition','*','WRITE','ALLOW','ROLE','production'),(76,'AnnualAverageInvoiced','*','READ','ALLOW','ROLE','employee'),(77,'WorkerMana','*','READ','ALLOW','ROLE','employee'),(78,'TicketTracking','*','WRITE','ALLOW','ROLE','production'),(79,'TicketTracking','changeState','*','ALLOW','ROLE','employee'),(80,'Sale','deleteSales','*','ALLOW','ROLE','employee'),(81,'Sale','moveToTicket','*','ALLOW','ROLE','employee'),(82,'Sale','updateQuantity','*','ALLOW','ROLE','employee'),(83,'Sale','updatePrice','*','ALLOW','ROLE','employee'),(84,'Sale','updateDiscount','*','ALLOW','ROLE','employee'),(85,'SaleTracking','*','READ','ALLOW','ROLE','employee'),(86,'Order','*','*','ALLOW','ROLE','employee'),(87,'OrderRow','*','*','ALLOW','ROLE','employee'),(88,'ClientContact','*','*','ALLOW','ROLE','employee'),(89,'Sale','moveToNewTicket','*','ALLOW','ROLE','employee'),(90,'Sale','reserve','*','ALLOW','ROLE','employee'),(91,'TicketWeekly','*','READ','ALLOW','ROLE','employee'),(94,'Agency','landsThatDay','*','ALLOW','ROLE','employee'),(96,'ClaimEnd','*','READ','ALLOW','ROLE','employee'),(97,'ClaimEnd','*','WRITE','ALLOW','ROLE','claimManager'),(98,'ClaimBeginning','*','*','ALLOW','ROLE','employee'),(99,'ClaimDevelopment','*','READ','ALLOW','ROLE','employee'),(100,'ClaimDevelopment','*','WRITE','ALLOW','ROLE','claimManager'),(101,'Claim','*','*','ALLOW','ROLE','employee'),(102,'Claim','createFromSales','*','ALLOW','ROLE','employee'),(104,'Item','*','WRITE','ALLOW','ROLE','marketingBoss'),(105,'ItemBarcode','*','WRITE','ALLOW','ROLE','marketingBoss'),(106,'ItemBotanical','*','WRITE','ALLOW','ROLE','marketingBoss'),(108,'ItemPlacement','*','WRITE','ALLOW','ROLE','marketingBoss'),(109,'UserConfig','*','*','ALLOW','ROLE','employee'),(110,'Bank','*','READ','ALLOW','ROLE','trainee'),(111,'ClientLog','*','READ','ALLOW','ROLE','trainee'),(112,'Defaulter','*','READ','ALLOW','ROLE','employee'),(113,'ClientRisk','*','READ','ALLOW','ROLE','trainee'),(114,'Receipt','*','READ','ALLOW','ROLE','trainee'),(115,'Receipt','*','WRITE','ALLOW','ROLE','administrative'),(116,'BankEntity','*','*','ALLOW','ROLE','employee'),(117,'ClientSample','*','*','ALLOW','ROLE','employee'),(118,'WorkerTeam','*','*','ALLOW','ROLE','salesPerson'),(119,'Travel','*','READ','ALLOW','ROLE','employee'),(120,'Travel','*','WRITE','ALLOW','ROLE','buyer'),(121,'Item','regularize','*','ALLOW','ROLE','employee'),(122,'TicketRequest','*','*','ALLOW','ROLE','employee'),(123,'Worker','*','READ','ALLOW','ROLE','employee'),(124,'Client','confirmTransaction','WRITE','ALLOW','ROLE','administrative'),(125,'Agency','getAgenciesWithWarehouse','*','ALLOW','ROLE','employee'),(126,'Client','activeWorkersWithRole','*','ALLOW','ROLE','employee'),(127,'TicketLog','*','READ','ALLOW','ROLE','employee'),(129,'TicketService','*','*','ALLOW','ROLE','employee'),(130,'Expedition','*','WRITE','ALLOW','ROLE','packager'),(131,'CreditInsurance','*','READ','ALLOW','ROLE','trainee'),(132,'CreditClassification','*','READ','ALLOW','ROLE','trainee'),(133,'ItemTag','*','WRITE','ALLOW','ROLE','marketingBoss'),(135,'ZoneGeo','*','READ','ALLOW','ROLE','employee'),(136,'ZoneCalendar','*','READ','ALLOW','ROLE','employee'),(137,'ZoneIncluded','*','READ','ALLOW','ROLE','employee'),(138,'LabourHoliday','*','READ','ALLOW','ROLE','employee'),(139,'LabourHolidayLegend','*','READ','ALLOW','ROLE','employee'),(140,'LabourHolidayType','*','READ','ALLOW','ROLE','employee'),(141,'Zone','*','*','ALLOW','ROLE','logisticBoss'),(142,'ZoneCalendar','*','WRITE','ALLOW','ROLE','deliveryAssist'),(143,'ZoneIncluded','*','*','ALLOW','ROLE','deliveryAssist'),(144,'Stowaway','*','*','ALLOW','ROLE','employee'),(145,'Ticket','getPossibleStowaways','READ','ALLOW','ROLE','employee'),(147,'UserConfigView','*','*','ALLOW','ROLE','employee'),(148,'UserConfigView','*','*','ALLOW','ROLE','employee'),(149,'Sip','*','READ','ALLOW','ROLE','employee'),(150,'Sip','*','WRITE','ALLOW','ROLE','hr'),(151,'Department','*','READ','ALLOW','ROLE','employee'),(152,'Department','*','WRITE','ALLOW','ROLE','hr'),(153,'Route','*','READ','ALLOW','ROLE','employee'),(154,'Route','*','WRITE','ALLOW','ROLE','delivery'),(155,'Calendar','*','READ','ALLOW','ROLE','hr'),(156,'WorkerLabour','*','READ','ALLOW','ROLE','hr'),(157,'Calendar','absences','READ','ALLOW','ROLE','employee'),(158,'ItemTag','*','WRITE','ALLOW','ROLE','accessory'),(160,'TicketServiceType','*','READ','ALLOW','ROLE','employee'),(161,'TicketConfig','*','READ','ALLOW','ROLE','employee'),(162,'InvoiceOut','delete','WRITE','ALLOW','ROLE','invoicing'),(163,'InvoiceOut','book','WRITE','ALLOW','ROLE','invoicing'),(165,'TicketDms','*','*','ALLOW','ROLE','employee'),(167,'Worker','isSubordinate','READ','ALLOW','ROLE','employee'),(168,'Worker','mySubordinates','READ','ALLOW','ROLE','employee'),(169,'WorkerTimeControl','filter','READ','ALLOW','ROLE','employee'),(170,'WorkerTimeControl','addTime','WRITE','ALLOW','ROLE','employee'),(171,'TicketServiceType','*','WRITE','ALLOW','ROLE','administrative'),(172,'Sms','*','READ','ALLOW','ROLE','employee'),(173,'Sms','send','WRITE','ALLOW','ROLE','employee'),(174,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(175,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(176,'Device','*','*','ALLOW','ROLE','employee'),(177,'Device','*','*','ALLOW','ROLE','employee'),(178,'WorkerTimeControl','*','*','ALLOW','ROLE','employee'),(179,'ItemLog','*','READ','ALLOW','ROLE','employee'),(180,'RouteLog','*','READ','ALLOW','ROLE','employee'),(181,'Dms','removeFile','WRITE','ALLOW','ROLE','employee'),(182,'Dms','uploadFile','WRITE','ALLOW','ROLE','employee'),(183,'Dms','downloadFile','READ','ALLOW','ROLE','employee'),(184,'Client','uploadFile','WRITE','ALLOW','ROLE','employee'),(185,'ClientDms','removeFile','WRITE','ALLOW','ROLE','employee'),(186,'ClientDms','*','READ','ALLOW','ROLE','trainee'),(187,'Ticket','uploadFile','WRITE','ALLOW','ROLE','employee'),(190,'Route','updateVolume','WRITE','ALLOW','ROLE','deliveryAssist'),(191,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(192,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(194,'Postcode','*','WRITE','ALLOW','ROLE','deliveryAssist'),(195,'Ticket','addSale','WRITE','ALLOW','ROLE','employee'),(196,'Dms','updateFile','WRITE','ALLOW','ROLE','employee'),(197,'Dms','*','READ','ALLOW','ROLE','trainee'),(198,'ClaimDms','removeFile','WRITE','ALLOW','ROLE','employee'),(199,'ClaimDms','*','READ','ALLOW','ROLE','employee'),(200,'Claim','uploadFile','WRITE','ALLOW','ROLE','employee'),(201,'Sale','updateConcept','WRITE','ALLOW','ROLE','employee'),(202,'Claim','updateClaimAction','WRITE','ALLOW','ROLE','claimManager'),(203,'UserPhone','*','*','ALLOW','ROLE','employee'),(204,'WorkerDms','removeFile','WRITE','ALLOW','ROLE','hr'),(205,'WorkerDms','*','READ','ALLOW','ROLE','hr'),(206,'Chat','*','*','ALLOW','ROLE','employee'),(207,'Chat','sendMessage','*','ALLOW','ROLE','employee'),(208,'Sale','recalculatePrice','WRITE','ALLOW','ROLE','employee'),(209,'Ticket','recalculateComponents','WRITE','ALLOW','ROLE','employee'),(211,'TravelLog','*','READ','ALLOW','ROLE','buyer'),(212,'Thermograph','*','*','ALLOW','ROLE','buyer'),(213,'TravelThermograph','*','WRITE','ALLOW','ROLE','buyer'),(214,'Entry','*','*','ALLOW','ROLE','buyer'),(215,'TicketWeekly','*','WRITE','ALLOW','ROLE','buyer'),(216,'TravelThermograph','*','READ','ALLOW','ROLE','employee'),(218,'Intrastat','*','*','ALLOW','ROLE','buyer'),(221,'UserConfig','getUserConfig','READ','ALLOW','ROLE','account'),(222,'Client','*','READ','ALLOW','ROLE','trainee'),(226,'ClientObservation','*','READ','ALLOW','ROLE','trainee'),(227,'Address','*','READ','ALLOW','ROLE','trainee'),(228,'AddressObservation','*','READ','ALLOW','ROLE','trainee'),(230,'ClientCredit','*','READ','ALLOW','ROLE','trainee'),(231,'ClientContact','*','READ','ALLOW','ROLE','trainee'),(232,'ClientSample','*','READ','ALLOW','ROLE','trainee'),(233,'EntryLog','*','READ','ALLOW','ROLE','buyer'),(234,'WorkerLog','*','READ','ALLOW','ROLE','salesAssistant'),(235,'CustomsAgent','*','*','ALLOW','ROLE','employee'),(236,'Buy','*','*','ALLOW','ROLE','buyer'),(237,'WorkerDms','filter','*','ALLOW','ROLE','employee'),(238,'Town','*','WRITE','ALLOW','ROLE','deliveryAssist'),(239,'Province','*','WRITE','ALLOW','ROLE','deliveryAssist'),(240,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(241,'SupplierContact','*','WRITE','ALLOW','ROLE','administrative'),(242,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(244,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(248,'RoleMapping','*','READ','ALLOW','ROLE','account'),(249,'UserPassword','*','READ','ALLOW','ROLE','account'),(250,'Town','*','WRITE','ALLOW','ROLE','deliveryAssist'),(251,'Province','*','WRITE','ALLOW','ROLE','deliveryAssist'),(252,'Supplier','*','READ','ALLOW','ROLE','employee'),(253,'Supplier','*','WRITE','ALLOW','ROLE','administrative'),(254,'SupplierLog','*','READ','ALLOW','ROLE','employee'),(256,'Image','*','WRITE','ALLOW','ROLE','employee'),(257,'FixedPrice','*','*','ALLOW','ROLE','buyer'),(258,'PayDem','*','READ','ALLOW','ROLE','employee'),(259,'Client','createReceipt','*','ALLOW','ROLE','salesAssistant'),(260,'PrintServerQueue','*','WRITE','ALLOW','ROLE','employee'),(261,'SupplierAccount','*','*','ALLOW','ROLE','administrative'),(262,'Entry','*','*','ALLOW','ROLE','administrative'),(263,'InvoiceIn','*','*','ALLOW','ROLE','administrative'),(264,'StarredModule','*','*','ALLOW','ROLE','employee'),(265,'ItemBotanical','*','WRITE','ALLOW','ROLE','logisticBoss'),(266,'ZoneLog','*','READ','ALLOW','ROLE','employee'),(267,'Genus','*','WRITE','ALLOW','ROLE','logisticBoss'),(268,'Specie','*','WRITE','ALLOW','ROLE','logisticBoss'),(269,'InvoiceOut','createPdf','WRITE','ALLOW','ROLE','employee'),(270,'SupplierAddress','*','*','ALLOW','ROLE','employee'),(271,'SalesMonitor','*','*','ALLOW','ROLE','employee'),(272,'InvoiceInLog','*','READ','ALLOW','ROLE','employee'),(273,'InvoiceInTax','*','*','ALLOW','ROLE','administrative'),(274,'InvoiceInLog','*','READ','ALLOW','ROLE','administrative'),(275,'InvoiceOut','createManualInvoice','WRITE','ALLOW','ROLE','invoicing'),(276,'InvoiceOut','globalInvoicing','WRITE','ALLOW','ROLE','invoicing'),(277,'Role','*','*','ALLOW','ROLE','it'),(278,'RoleInherit','*','WRITE','ALLOW','ROLE','grant'),(279,'MailAlias','*','*','ALLOW','ROLE','marketing'),(283,'EntryObservation','*','*','ALLOW','ROLE','buyer'),(284,'LdapConfig','*','*','ALLOW','ROLE','sysadmin'),(285,'SambaConfig','*','*','ALLOW','ROLE','sysadmin'),(286,'ACL','*','*','ALLOW','ROLE','developer'),(287,'AccessToken','*','*','ALLOW','ROLE','developer'),(288,'MailAliasAccount','*','*','ALLOW','ROLE','marketing'),(289,'MailAliasAccount','*','*','ALLOW','ROLE','hr'),(290,'MailAlias','*','*','ALLOW','ROLE','hr'),(291,'MailForward','*','*','ALLOW','ROLE','marketing'),(292,'MailForward','*','*','ALLOW','ROLE','hr'),(293,'RoleInherit','*','*','ALLOW','ROLE','it'),(294,'RoleRole','*','*','ALLOW','ROLE','it'),(295,'AccountConfig','*','*','ALLOW','ROLE','sysadmin'),(296,'Collection','*','READ','ALLOW','ROLE','employee'),(297,'Sale','refund','WRITE','ALLOW','ROLE','invoicing'),(298,'InvoiceInDueDay','*','*','ALLOW','ROLE','administrative'),(299,'Collection','setSaleQuantity','*','ALLOW','ROLE','employee'),(300,'Docuware','*','*','ALLOW','ROLE','employee'),(301,'Agency','*','READ','ALLOW','ROLE','employee'),(302,'AgencyTerm','*','*','ALLOW','ROLE','administrative'),(303,'ClaimLog','*','READ','ALLOW','ROLE','claimManager'),(304,'Edi','updateData','WRITE','ALLOW','ROLE','employee'),(305,'EducationLevel','*','*','ALLOW','ROLE','employee'),(306,'InvoiceInIntrastat','*','*','ALLOW','ROLE','employee'),(307,'SupplierAgencyTerm','*','*','ALLOW','ROLE','administrative'),(308,'InvoiceInIntrastat','*','*','ALLOW','ROLE','employee'),(309,'Zone','getZoneClosing','*','ALLOW','ROLE','employee'),(310,'ExpeditionState','*','READ','ALLOW','ROLE','employee'),(311,'Expense','*','READ','ALLOW','ROLE','employee'),(312,'Expense','*','WRITE','ALLOW','ROLE','administrative'),(314,'SupplierActivity','*','READ','ALLOW','ROLE','employee'),(315,'SupplierActivity','*','WRITE','ALLOW','ROLE','administrative'),(316,'Dms','deleteTrashFiles','WRITE','ALLOW','ROLE','employee'),(317,'ClientUnpaid','*','*','ALLOW','ROLE','administrative'),(318,'MdbVersion','*','*','ALLOW','ROLE','developer'),(319,'ItemType','*','READ','ALLOW','ROLE','employee'),(320,'ItemType','*','WRITE','ALLOW','ROLE','buyer'),(321,'InvoiceOut','refund','WRITE','ALLOW','ROLE','invoicing'),(322,'InvoiceOut','refund','WRITE','ALLOW','ROLE','salesAssistant'),(323,'InvoiceOut','refund','WRITE','ALLOW','ROLE','claimManager'),(324,'Ticket','refund','WRITE','ALLOW','ROLE','invoicing'),(325,'Ticket','refund','WRITE','ALLOW','ROLE','salesAssistant'),(326,'Ticket','refund','WRITE','ALLOW','ROLE','claimManager'),(327,'Sale','refund','WRITE','ALLOW','ROLE','salesAssistant'),(328,'Sale','refund','WRITE','ALLOW','ROLE','claimManager'),(329,'TicketRefund','*','WRITE','ALLOW','ROLE','invoicing'),(330,'ClaimObservation','*','WRITE','ALLOW','ROLE','salesPerson'),(331,'ClaimObservation','*','READ','ALLOW','ROLE','salesPerson'),(332,'Client','setPassword','WRITE','ALLOW','ROLE','salesPerson'),(333,'Client','updateUser','WRITE','ALLOW','ROLE','salesPerson'),(334,'ShelvingLog','*','READ','ALLOW','ROLE','employee'),(335,'ZoneExclusionGeo','*','READ','ALLOW','ROLE','employee'),(336,'ZoneExclusionGeo','*','WRITE','ALLOW','ROLE','deliveryAssist'),(337,'Parking','*','*','ALLOW','ROLE','employee'),(338,'Shelving','*','*','ALLOW','ROLE','employee'),(339,'OsTicket','*','*','ALLOW','ROLE','employee'),(340,'OsTicketConfig','*','*','ALLOW','ROLE','it'),(341,'ClientConsumptionQueue','*','WRITE','ALLOW','ROLE','employee'),(342,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','employee'),(343,'Ticket','deliveryNoteEmail','WRITE','ALLOW','ROLE','employee'),(344,'Ticket','deliveryNoteCsvPdf','READ','ALLOW','ROLE','employee'),(345,'Ticket','deliveryNoteCsvEmail','WRITE','ALLOW','ROLE','employee'),(346,'Client','campaignMetricsPdf','READ','ALLOW','ROLE','employee'),(347,'Client','campaignMetricsEmail','WRITE','ALLOW','ROLE','employee'),(348,'Client','clientWelcomeHtml','READ','ALLOW','ROLE','employee'),(349,'Client','clientWelcomeEmail','WRITE','ALLOW','ROLE','employee'),(350,'Client','creditRequestPdf','READ','ALLOW','ROLE','employee'),(351,'Client','creditRequestHtml','READ','ALLOW','ROLE','employee'),(352,'Client','creditRequestEmail','WRITE','ALLOW','ROLE','employee'),(353,'Client','printerSetupHtml','READ','ALLOW','ROLE','employee'),(354,'Client','printerSetupEmail','WRITE','ALLOW','ROLE','employee'),(355,'Client','sepaCoreEmail','WRITE','ALLOW','ROLE','employee'),(356,'Client','letterDebtorPdf','READ','ALLOW','ROLE','employee'),(357,'Client','letterDebtorStHtml','READ','ALLOW','ROLE','employee'),(358,'Client','letterDebtorStEmail','WRITE','ALLOW','ROLE','employee'),(359,'Client','letterDebtorNdHtml','READ','ALLOW','ROLE','employee'),(360,'Client','letterDebtorNdEmail','WRITE','ALLOW','ROLE','employee'),(361,'Client','clientDebtStatementPdf','READ','ALLOW','ROLE','employee'),(362,'Client','clientDebtStatementHtml','READ','ALLOW','ROLE','employee'),(363,'Client','clientDebtStatementEmail','WRITE','ALLOW','ROLE','employee'),(364,'Client','incotermsAuthorizationPdf','READ','ALLOW','ROLE','employee'),(365,'Client','incotermsAuthorizationHtml','READ','ALLOW','ROLE','employee'),(366,'Client','incotermsAuthorizationEmail','WRITE','ALLOW','ROLE','employee'),(367,'Client','consumptionSendQueued','WRITE','ALLOW','ROLE','system'),(368,'InvoiceOut','invoiceEmail','WRITE','ALLOW','ROLE','employee'),(369,'InvoiceOut','exportationPdf','READ','ALLOW','ROLE','employee'),(370,'InvoiceOut','sendQueued','WRITE','ALLOW','ROLE','system'),(371,'Ticket','invoiceCsvPdf','READ','ALLOW','ROLE','employee'),(372,'Ticket','invoiceCsvEmail','WRITE','ALLOW','ROLE','employee'),(373,'Supplier','campaignMetricsPdf','READ','ALLOW','ROLE','employee'),(374,'Supplier','campaignMetricsEmail','WRITE','ALLOW','ROLE','employee'),(375,'Travel','extraCommunityPdf','READ','ALLOW','ROLE','employee'),(376,'Travel','extraCommunityEmail','WRITE','ALLOW','ROLE','employee'),(377,'Entry','entryOrderPdf','READ','ALLOW','ROLE','employee'),(378,'OsTicket','osTicketReportEmail','WRITE','ALLOW','ROLE','system'),(379,'Item','buyerWasteEmail','WRITE','ALLOW','ROLE','system'),(380,'Claim','claimPickupPdf','READ','ALLOW','ROLE','employee'),(381,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','claimManager'),(382,'Item','labelPdf','READ','ALLOW','ROLE','employee'),(383,'Sector','*','READ','ALLOW','ROLE','employee'),(384,'Sector','*','WRITE','ALLOW','ROLE','employee'),(385,'Route','driverRoutePdf','READ','ALLOW','ROLE','employee'),(386,'Route','driverRouteEmail','WRITE','ALLOW','ROLE','employee'),(387,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','customer'),(388,'Supplier','newSupplier','WRITE','ALLOW','ROLE','administrative'),(389,'ClaimRma','*','READ','ALLOW','ROLE','claimManager'),(390,'ClaimRma','*','WRITE','ALLOW','ROLE','claimManager'),(391,'Notification','*','WRITE','ALLOW','ROLE','system'),(392,'Boxing','*','*','ALLOW','ROLE','employee'),(393,'Url','*','READ','ALLOW','ROLE','employee'),(394,'Url','*','WRITE','ALLOW','ROLE','it'),(395,'ItemShelving','*','READ','ALLOW','ROLE','employee'),(396,'ItemShelving','*','WRITE','ALLOW','ROLE','production'),(397,'ItemShelvingPlacementSupplyStock','*','READ','ALLOW','ROLE','employee'),(398,'NotificationQueue','*','*','ALLOW','ROLE','employee'),(399,'InvoiceOut','clientsToInvoice','WRITE','ALLOW','ROLE','invoicing'),(400,'InvoiceOut','invoiceClient','WRITE','ALLOW','ROLE','invoicing'),(401,'Sale','editTracked','WRITE','ALLOW','ROLE','production'),(402,'Sale','editFloramondo','WRITE','ALLOW','ROLE','salesAssistant'),(403,'Receipt','balanceCompensationEmail','WRITE','ALLOW','ROLE','employee'),(404,'Receipt','balanceCompensationPdf','READ','ALLOW','ROLE','employee'),(405,'Ticket','getTicketsFuture','READ','ALLOW','ROLE','employee'),(406,'Ticket','merge','WRITE','ALLOW','ROLE','employee'),(407,'Sale','editFloramondo','WRITE','ALLOW','ROLE','logistic'),(408,'ZipConfig','*','*','ALLOW','ROLE','employee'),(409,'Item','*','WRITE','ALLOW','ROLE','administrative'),(410,'Sale','editCloned','WRITE','ALLOW','ROLE','buyer'),(411,'Sale','editCloned','WRITE','ALLOW','ROLE','salesAssistant'),(414,'MdbVersion','*','READ','ALLOW','ROLE','$everyone'),(416,'TicketLog','getChanges','READ','ALLOW','ROLE','employee'),(417,'Ticket','getTicketsAdvance','READ','ALLOW','ROLE','employee'),(418,'EntryLog','*','READ','ALLOW','ROLE','administrative'),(419,'Sale','editTracked','WRITE','ALLOW','ROLE','buyer'),(420,'MdbBranch','*','READ','ALLOW','ROLE','$everyone'),(421,'ItemShelvingSale','*','*','ALLOW','ROLE','employee'),(422,'Docuware','checkFile','READ','ALLOW','ROLE','employee'),(423,'Docuware','download','READ','ALLOW','ROLE','salesPerson'),(424,'Docuware','upload','WRITE','ALLOW','ROLE','productionAssi'),(425,'Docuware','deliveryNoteEmail','WRITE','ALLOW','ROLE','salesPerson'),(426,'TpvTransaction','confirm','WRITE','ALLOW','ROLE','$everyone'),(427,'TpvTransaction','start','WRITE','ALLOW','ROLE','$authenticated'),(428,'TpvTransaction','end','WRITE','ALLOW','ROLE','$authenticated'),(429,'ItemConfig','*','READ','ALLOW','ROLE','employee'),(431,'Tag','onSubmit','WRITE','ALLOW','ROLE','employee'),(432,'Worker','updateAttributes','WRITE','ALLOW','ROLE','hr'),(433,'Worker','createAbsence','*','ALLOW','ROLE','employee'),(434,'Worker','updateAbsence','WRITE','ALLOW','ROLE','employee'),(435,'Worker','deleteAbsence','*','ALLOW','ROLE','employee'),(436,'Worker','new','WRITE','ALLOW','ROLE','hr'),(437,'Role','*','READ','ALLOW','ROLE','hr'),(438,'Client','getClientOrSupplierReference','READ','ALLOW','ROLE','employee'),(439,'NotificationSubscription','*','*','ALLOW','ROLE','employee'),(440,'NotificationAcl','*','READ','ALLOW','ROLE','employee'),(441,'MdbApp','*','READ','ALLOW','ROLE','$everyone'),(442,'MdbApp','*','*','ALLOW','ROLE','developer'),(443,'ItemConfig','*','*','ALLOW','ROLE','employee'),(444,'DeviceProduction','*','*','ALLOW','ROLE','hr'),(445,'DeviceProductionModels','*','*','ALLOW','ROLE','hr'),(446,'DeviceProductionState','*','*','ALLOW','ROLE','hr'),(447,'DeviceProductionUser','*','*','ALLOW','ROLE','hr'),(448,'DeviceProduction','*','*','ALLOW','ROLE','productionAssi'),(449,'DeviceProductionModels','*','*','ALLOW','ROLE','productionAssi'),(450,'DeviceProductionState','*','*','ALLOW','ROLE','productionAssi'),(451,'DeviceProductionUser','*','*','ALLOW','ROLE','productionAssi'),(452,'Worker','deallocatePDA','*','ALLOW','ROLE','hr'),(453,'Worker','allocatePDA','*','ALLOW','ROLE','hr'),(454,'Worker','deallocatePDA','*','ALLOW','ROLE','productionAssi'),(455,'Worker','allocatePDA','*','ALLOW','ROLE','productionAssi'),(456,'Zone','*','*','ALLOW','ROLE','deliveryAssist'),(457,'Account','setPassword','WRITE','ALLOW','ROLE','itManagement'),(458,'Operator','*','READ','ALLOW','ROLE','employee'),(459,'Operator','*','WRITE','ALLOW','ROLE','employee'),(460,'InvoiceIn','getSerial','READ','ALLOW','ROLE','administrative'),(461,'Ticket','saveSign','WRITE','ALLOW','ROLE','employee'),(462,'InvoiceOut','negativeBases','READ','ALLOW','ROLE','administrative'),(463,'InvoiceOut','negativeBasesCsv','READ','ALLOW','ROLE','administrative'),(464,'WorkerObservation','*','*','ALLOW','ROLE','hr'),(465,'ClientInforma','*','READ','ALLOW','ROLE','employee'),(466,'ClientInforma','*','WRITE','ALLOW','ROLE','financial'),(467,'Receipt','receiptEmail','*','ALLOW','ROLE','salesAssistant'),(468,'Client','setRating','WRITE','ALLOW','ROLE','financial'),(469,'Client','*','READ','ALLOW','ROLE','employee'),(470,'Client','addressesPropagateRe','*','ALLOW','ROLE','employee'),(471,'Client','canBeInvoiced','*','ALLOW','ROLE','employee'),(472,'Client','canCreateTicket','*','ALLOW','ROLE','employee'),(473,'Client','consumption','*','ALLOW','ROLE','employee'),(474,'Client','createAddress','*','ALLOW','ROLE','employee'),(475,'Client','createWithUser','*','ALLOW','ROLE','employee'),(476,'Client','extendedListFilter','*','ALLOW','ROLE','employee'),(477,'Client','getAverageInvoiced','*','ALLOW','ROLE','employee'),(478,'Client','getCard','*','ALLOW','ROLE','employee'),(479,'Client','getDebt','*','ALLOW','ROLE','employee'),(480,'Client','getMana','*','ALLOW','ROLE','employee'),(481,'Client','transactions','*','ALLOW','ROLE','employee'),(482,'Client','hasCustomerRole','*','ALLOW','ROLE','employee'),(483,'Client','isValidClient','*','ALLOW','ROLE','employee'),(484,'Client','lastActiveTickets','*','ALLOW','ROLE','employee'),(485,'Client','sendSms','*','ALLOW','ROLE','employee'),(486,'Client','setPassword','*','ALLOW','ROLE','employee'),(487,'Client','summary','*','ALLOW','ROLE','employee'),(488,'Client','updateAddress','*','ALLOW','ROLE','employee'),(489,'Client','updateFiscalData','*','ALLOW','ROLE','employee'),(490,'Client','updateUser','*','ALLOW','ROLE','employee'),(491,'Client','uploadFile','*','ALLOW','ROLE','employee'),(492,'Client','campaignMetricsPdf','*','ALLOW','ROLE','employee'),(493,'Client','campaignMetricsEmail','*','ALLOW','ROLE','employee'),(494,'Client','clientWelcomeHtml','*','ALLOW','ROLE','employee'),(495,'Client','clientWelcomeEmail','*','ALLOW','ROLE','employee'),(496,'Client','printerSetupHtml','*','ALLOW','ROLE','employee'),(497,'Client','printerSetupEmail','*','ALLOW','ROLE','employee'),(498,'Client','sepaCoreEmail','*','ALLOW','ROLE','employee'),(499,'Client','letterDebtorPdf','*','ALLOW','ROLE','employee'),(500,'Client','letterDebtorStHtml','*','ALLOW','ROLE','employee'),(501,'Client','letterDebtorStEmail','*','ALLOW','ROLE','employee'),(502,'Client','letterDebtorNdHtml','*','ALLOW','ROLE','employee'),(503,'Client','letterDebtorNdEmail','*','ALLOW','ROLE','employee'),(504,'Client','clientDebtStatementPdf','*','ALLOW','ROLE','employee'),(505,'Client','clientDebtStatementHtml','*','ALLOW','ROLE','employee'),(506,'Client','clientDebtStatementEmail','*','ALLOW','ROLE','employee'),(507,'Client','creditRequestPdf','*','ALLOW','ROLE','employee'),(508,'Client','creditRequestHtml','*','ALLOW','ROLE','employee'),(509,'Client','creditRequestEmail','*','ALLOW','ROLE','employee'),(510,'Client','incotermsAuthorizationPdf','*','ALLOW','ROLE','employee'),(511,'Client','incotermsAuthorizationHtml','*','ALLOW','ROLE','employee'),(512,'Client','incotermsAuthorizationEmail','*','ALLOW','ROLE','employee'),(513,'Client','consumptionSendQueued','*','ALLOW','ROLE','employee'),(514,'Client','filter','*','ALLOW','ROLE','employee'),(515,'Client','getClientOrSupplierReference','*','ALLOW','ROLE','employee'),(516,'Client','upsert','*','ALLOW','ROLE','employee'),(517,'Client','create','*','ALLOW','ROLE','employee'),(518,'Client','replaceById','*','ALLOW','ROLE','employee'),(519,'Client','updateAttributes','*','ALLOW','ROLE','employee'),(520,'Client','updateAttributes','*','ALLOW','ROLE','employee'),(521,'Client','deleteById','*','ALLOW','ROLE','employee'),(522,'Client','replaceOrCreate','*','ALLOW','ROLE','employee'),(523,'Client','updateAll','*','ALLOW','ROLE','employee'),(524,'Client','upsertWithWhere','*','ALLOW','ROLE','employee'),(525,'Defaulter','observationEmail','WRITE','ALLOW','ROLE','employee'),(526,'VnUser','*','*','ALLOW','ROLE','employee'),(527,'VnUser','acl','READ','ALLOW','ROLE','account'),(528,'VnUser','getCurrentUserData','READ','ALLOW','ROLE','account'),(529,'VnUser','changePassword','WRITE','ALLOW','ROLE','account'),(530,'Account','exists','READ','ALLOW','ROLE','account'),(531,'Account','exists','READ','ALLOW','ROLE','account'),(532,'UserLog','*','READ','ALLOW','ROLE','employee'),(533,'RoleLog','*','READ','ALLOW','ROLE','employee'); +INSERT INTO `ACL` VALUES (1,'Account','*','*','ALLOW','ROLE','employee'),(3,'Address','*','*','ALLOW','ROLE','employee'),(5,'AgencyService','*','READ','ALLOW','ROLE','employee'),(9,'ClientObservation','*','*','ALLOW','ROLE','employee'),(11,'ContactChannel','*','READ','ALLOW','ROLE','trainee'),(13,'Employee','*','READ','ALLOW','ROLE','employee'),(14,'PayMethod','*','READ','ALLOW','ROLE','trainee'),(16,'FakeProduction','*','READ','ALLOW','ROLE','employee'),(17,'Warehouse','* ','READ','ALLOW','ROLE','trainee'),(18,'State','*','READ','ALLOW','ROLE','employee'),(20,'TicketState','*','*','ALLOW','ROLE','employee'),(24,'Delivery','*','READ','ALLOW','ROLE','employee'),(25,'Zone','*','READ','ALLOW','ROLE','employee'),(26,'ClientCredit','*','*','ALLOW','ROLE','employee'),(27,'ClientCreditLimit','*','READ','ALLOW','ROLE','trainee'),(30,'GreugeType','*','READ','ALLOW','ROLE','trainee'),(31,'Mandate','*','READ','ALLOW','ROLE','trainee'),(32,'MandateType','*','READ','ALLOW','ROLE','trainee'),(33,'Company','*','READ','ALLOW','ROLE','trainee'),(34,'Greuge','*','READ','ALLOW','ROLE','trainee'),(35,'AddressObservation','*','*','ALLOW','ROLE','employee'),(36,'ObservationType','*','*','ALLOW','ROLE','employee'),(37,'Greuge','*','WRITE','ALLOW','ROLE','employee'),(38,'AgencyMode','*','READ','ALLOW','ROLE','employee'),(39,'ItemTag','*','WRITE','ALLOW','ROLE','buyer'),(40,'ItemBotanical','*','WRITE','ALLOW','ROLE','buyer'),(41,'ItemBotanical','*','READ','ALLOW','ROLE','employee'),(42,'ItemPlacement','*','WRITE','ALLOW','ROLE','buyer'),(43,'ItemPlacement','*','WRITE','ALLOW','ROLE','replenisher'),(44,'ItemPlacement','*','READ','ALLOW','ROLE','employee'),(45,'ItemBarcode','*','READ','ALLOW','ROLE','employee'),(46,'ItemBarcode','*','WRITE','ALLOW','ROLE','buyer'),(47,'ItemBarcode','*','WRITE','ALLOW','ROLE','replenisher'),(51,'ItemTag','*','READ','ALLOW','ROLE','employee'),(53,'Item','*','READ','ALLOW','ROLE','employee'),(54,'Item','*','WRITE','ALLOW','ROLE','buyer'),(55,'Recovery','*','READ','ALLOW','ROLE','trainee'),(56,'Recovery','*','WRITE','ALLOW','ROLE','administrative'),(58,'CreditClassification','*','*','ALLOW','ROLE','insurance'),(60,'CreditInsurance','*','*','ALLOW','ROLE','insurance'),(61,'InvoiceOut','*','READ','ALLOW','ROLE','employee'),(62,'Ticket','*','*','ALLOW','ROLE','employee'),(63,'TicketObservation','*','*','ALLOW','ROLE','employee'),(64,'Route','*','READ','ALLOW','ROLE','employee'),(65,'Sale','*','READ','ALLOW','ROLE','employee'),(66,'TicketTracking','*','READ','ALLOW','ROLE','employee'),(68,'TicketPackaging','*','*','ALLOW','ROLE','employee'),(69,'Packaging','*','READ','ALLOW','ROLE','employee'),(70,'Packaging','*','WRITE','ALLOW','ROLE','logistic'),(72,'SaleComponent','*','READ','ALLOW','ROLE','employee'),(73,'Expedition','*','READ','ALLOW','ROLE','employee'),(74,'Expedition','*','WRITE','ALLOW','ROLE','deliveryAssistantant'),(75,'Expedition','*','WRITE','ALLOW','ROLE','production'),(76,'AnnualAverageInvoiced','*','READ','ALLOW','ROLE','employee'),(77,'WorkerMana','*','READ','ALLOW','ROLE','employee'),(78,'TicketTracking','*','WRITE','ALLOW','ROLE','production'),(79,'TicketTracking','changeState','*','ALLOW','ROLE','employee'),(80,'Sale','deleteSales','*','ALLOW','ROLE','employee'),(81,'Sale','moveToTicket','*','ALLOW','ROLE','employee'),(82,'Sale','updateQuantity','*','ALLOW','ROLE','employee'),(83,'Sale','updatePrice','*','ALLOW','ROLE','employee'),(84,'Sale','updateDiscount','*','ALLOW','ROLE','employee'),(85,'SaleTracking','*','READ','ALLOW','ROLE','employee'),(86,'Order','*','*','ALLOW','ROLE','employee'),(87,'OrderRow','*','*','ALLOW','ROLE','employee'),(88,'ClientContact','*','*','ALLOW','ROLE','employee'),(89,'Sale','moveToNewTicket','*','ALLOW','ROLE','employee'),(90,'Sale','reserve','*','ALLOW','ROLE','employee'),(91,'TicketWeekly','*','READ','ALLOW','ROLE','employee'),(94,'Agency','landsThatDay','*','ALLOW','ROLE','employee'),(96,'ClaimEnd','*','READ','ALLOW','ROLE','employee'),(97,'ClaimEnd','*','WRITE','ALLOW','ROLE','claimManager'),(98,'ClaimBeginning','*','*','ALLOW','ROLE','employee'),(99,'ClaimDevelopment','*','READ','ALLOW','ROLE','employee'),(100,'ClaimDevelopment','*','WRITE','ALLOW','ROLE','claimManager'),(101,'Claim','*','*','ALLOW','ROLE','employee'),(102,'Claim','createFromSales','*','ALLOW','ROLE','employee'),(104,'Item','*','WRITE','ALLOW','ROLE','marketingBoss'),(105,'ItemBarcode','*','WRITE','ALLOW','ROLE','marketingBoss'),(106,'ItemBotanical','*','WRITE','ALLOW','ROLE','marketingBoss'),(108,'ItemPlacement','*','WRITE','ALLOW','ROLE','marketingBoss'),(109,'UserConfig','*','*','ALLOW','ROLE','employee'),(110,'Bank','*','READ','ALLOW','ROLE','trainee'),(111,'ClientLog','*','READ','ALLOW','ROLE','trainee'),(112,'Defaulter','*','READ','ALLOW','ROLE','employee'),(113,'ClientRisk','*','READ','ALLOW','ROLE','trainee'),(114,'Receipt','*','READ','ALLOW','ROLE','trainee'),(115,'Receipt','*','WRITE','ALLOW','ROLE','administrative'),(116,'BankEntity','*','*','ALLOW','ROLE','employee'),(117,'ClientSample','*','*','ALLOW','ROLE','employee'),(118,'WorkerTeam','*','*','ALLOW','ROLE','salesPerson'),(119,'Travel','*','READ','ALLOW','ROLE','employee'),(120,'Travel','*','WRITE','ALLOW','ROLE','buyer'),(121,'Item','regularize','*','ALLOW','ROLE','employee'),(122,'TicketRequest','*','*','ALLOW','ROLE','employee'),(123,'Worker','*','READ','ALLOW','ROLE','employee'),(124,'Client','confirmTransaction','WRITE','ALLOW','ROLE','administrative'),(125,'Agency','getAgenciesWithWarehouse','*','ALLOW','ROLE','employee'),(126,'Client','activeWorkersWithRole','*','ALLOW','ROLE','employee'),(127,'TicketLog','*','READ','ALLOW','ROLE','employee'),(129,'TicketService','*','*','ALLOW','ROLE','employee'),(130,'Expedition','*','WRITE','ALLOW','ROLE','packager'),(131,'CreditInsurance','*','READ','ALLOW','ROLE','trainee'),(132,'CreditClassification','*','READ','ALLOW','ROLE','trainee'),(133,'ItemTag','*','WRITE','ALLOW','ROLE','marketingBoss'),(135,'ZoneGeo','*','READ','ALLOW','ROLE','employee'),(136,'ZoneCalendar','*','READ','ALLOW','ROLE','employee'),(137,'ZoneIncluded','*','READ','ALLOW','ROLE','employee'),(138,'LabourHoliday','*','READ','ALLOW','ROLE','employee'),(139,'LabourHolidayLegend','*','READ','ALLOW','ROLE','employee'),(140,'LabourHolidayType','*','READ','ALLOW','ROLE','employee'),(141,'Zone','*','*','ALLOW','ROLE','logisticBoss'),(142,'ZoneCalendar','*','WRITE','ALLOW','ROLE','deliveryAssistant'),(143,'ZoneIncluded','*','*','ALLOW','ROLE','deliveryAssistant'),(144,'Stowaway','*','*','ALLOW','ROLE','employee'),(145,'Ticket','getPossibleStowaways','READ','ALLOW','ROLE','employee'),(147,'UserConfigView','*','*','ALLOW','ROLE','employee'),(148,'UserConfigView','*','*','ALLOW','ROLE','employee'),(149,'Sip','*','READ','ALLOW','ROLE','employee'),(150,'Sip','*','WRITE','ALLOW','ROLE','hr'),(151,'Department','*','READ','ALLOW','ROLE','employee'),(152,'Department','*','WRITE','ALLOW','ROLE','hr'),(153,'Route','*','READ','ALLOW','ROLE','employee'),(154,'Route','*','WRITE','ALLOW','ROLE','delivery'),(155,'Calendar','*','READ','ALLOW','ROLE','hr'),(156,'WorkerLabour','*','READ','ALLOW','ROLE','hr'),(157,'Calendar','absences','READ','ALLOW','ROLE','employee'),(158,'ItemTag','*','WRITE','ALLOW','ROLE','accessory'),(160,'TicketServiceType','*','READ','ALLOW','ROLE','employee'),(161,'TicketConfig','*','READ','ALLOW','ROLE','employee'),(162,'InvoiceOut','delete','WRITE','ALLOW','ROLE','invoicing'),(163,'InvoiceOut','book','WRITE','ALLOW','ROLE','invoicing'),(165,'TicketDms','*','*','ALLOW','ROLE','employee'),(167,'Worker','isSubordinate','READ','ALLOW','ROLE','employee'),(168,'Worker','mySubordinates','READ','ALLOW','ROLE','employee'),(169,'WorkerTimeControl','filter','READ','ALLOW','ROLE','employee'),(170,'WorkerTimeControl','addTime','WRITE','ALLOW','ROLE','employee'),(171,'TicketServiceType','*','WRITE','ALLOW','ROLE','administrative'),(172,'Sms','*','READ','ALLOW','ROLE','employee'),(173,'Sms','send','WRITE','ALLOW','ROLE','employee'),(174,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(175,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(176,'Device','*','*','ALLOW','ROLE','employee'),(177,'Device','*','*','ALLOW','ROLE','employee'),(178,'WorkerTimeControl','*','*','ALLOW','ROLE','employee'),(179,'ItemLog','*','READ','ALLOW','ROLE','employee'),(180,'RouteLog','*','READ','ALLOW','ROLE','employee'),(181,'Dms','removeFile','WRITE','ALLOW','ROLE','employee'),(182,'Dms','uploadFile','WRITE','ALLOW','ROLE','employee'),(183,'Dms','downloadFile','READ','ALLOW','ROLE','employee'),(184,'Client','uploadFile','WRITE','ALLOW','ROLE','employee'),(185,'ClientDms','removeFile','WRITE','ALLOW','ROLE','employee'),(186,'ClientDms','*','READ','ALLOW','ROLE','trainee'),(187,'Ticket','uploadFile','WRITE','ALLOW','ROLE','employee'),(190,'Route','updateVolume','WRITE','ALLOW','ROLE','deliveryAssistant'),(191,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(192,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(194,'Postcode','*','WRITE','ALLOW','ROLE','deliveryAssistant'),(195,'Ticket','addSale','WRITE','ALLOW','ROLE','employee'),(196,'Dms','updateFile','WRITE','ALLOW','ROLE','employee'),(197,'Dms','*','READ','ALLOW','ROLE','trainee'),(198,'ClaimDms','removeFile','WRITE','ALLOW','ROLE','employee'),(199,'ClaimDms','*','READ','ALLOW','ROLE','employee'),(200,'Claim','uploadFile','WRITE','ALLOW','ROLE','employee'),(201,'Sale','updateConcept','WRITE','ALLOW','ROLE','employee'),(202,'Claim','updateClaimAction','WRITE','ALLOW','ROLE','claimManager'),(203,'UserPhone','*','*','ALLOW','ROLE','employee'),(204,'WorkerDms','removeFile','WRITE','ALLOW','ROLE','hr'),(205,'WorkerDms','*','READ','ALLOW','ROLE','hr'),(206,'Chat','*','*','ALLOW','ROLE','employee'),(207,'Chat','sendMessage','*','ALLOW','ROLE','employee'),(208,'Sale','recalculatePrice','WRITE','ALLOW','ROLE','employee'),(209,'Ticket','recalculateComponents','WRITE','ALLOW','ROLE','employee'),(211,'TravelLog','*','READ','ALLOW','ROLE','buyer'),(212,'Thermograph','*','*','ALLOW','ROLE','buyer'),(213,'TravelThermograph','*','WRITE','ALLOW','ROLE','buyer'),(214,'Entry','*','*','ALLOW','ROLE','buyer'),(215,'TicketWeekly','*','WRITE','ALLOW','ROLE','buyer'),(216,'TravelThermograph','*','READ','ALLOW','ROLE','employee'),(218,'Intrastat','*','*','ALLOW','ROLE','buyer'),(221,'UserConfig','getUserConfig','READ','ALLOW','ROLE','account'),(222,'Client','*','READ','ALLOW','ROLE','trainee'),(226,'ClientObservation','*','READ','ALLOW','ROLE','trainee'),(227,'Address','*','READ','ALLOW','ROLE','trainee'),(228,'AddressObservation','*','READ','ALLOW','ROLE','trainee'),(230,'ClientCredit','*','READ','ALLOW','ROLE','trainee'),(231,'ClientContact','*','READ','ALLOW','ROLE','trainee'),(232,'ClientSample','*','READ','ALLOW','ROLE','trainee'),(233,'EntryLog','*','READ','ALLOW','ROLE','buyer'),(234,'WorkerLog','*','READ','ALLOW','ROLE','salesAssistant'),(235,'CustomsAgent','*','*','ALLOW','ROLE','employee'),(236,'Buy','*','*','ALLOW','ROLE','buyer'),(237,'WorkerDms','filter','*','ALLOW','ROLE','employee'),(238,'Town','*','WRITE','ALLOW','ROLE','deliveryAssistant'),(239,'Province','*','WRITE','ALLOW','ROLE','deliveryAssistant'),(240,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(241,'SupplierContact','*','WRITE','ALLOW','ROLE','administrative'),(242,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(244,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(248,'RoleMapping','*','READ','ALLOW','ROLE','account'),(249,'UserPassword','*','READ','ALLOW','ROLE','account'),(250,'Town','*','WRITE','ALLOW','ROLE','deliveryAssistant'),(251,'Province','*','WRITE','ALLOW','ROLE','deliveryAssistant'),(252,'Supplier','*','READ','ALLOW','ROLE','employee'),(253,'Supplier','*','WRITE','ALLOW','ROLE','administrative'),(254,'SupplierLog','*','READ','ALLOW','ROLE','employee'),(256,'Image','*','WRITE','ALLOW','ROLE','employee'),(257,'FixedPrice','*','*','ALLOW','ROLE','buyer'),(258,'PayDem','*','READ','ALLOW','ROLE','employee'),(259,'Client','createReceipt','*','ALLOW','ROLE','salesAssistant'),(260,'PrintServerQueue','*','WRITE','ALLOW','ROLE','employee'),(261,'SupplierAccount','*','*','ALLOW','ROLE','administrative'),(262,'Entry','*','*','ALLOW','ROLE','administrative'),(263,'InvoiceIn','*','*','ALLOW','ROLE','administrative'),(264,'StarredModule','*','*','ALLOW','ROLE','employee'),(265,'ItemBotanical','*','WRITE','ALLOW','ROLE','logisticBoss'),(266,'ZoneLog','*','READ','ALLOW','ROLE','employee'),(267,'Genus','*','WRITE','ALLOW','ROLE','logisticBoss'),(268,'Specie','*','WRITE','ALLOW','ROLE','logisticBoss'),(269,'InvoiceOut','createPdf','WRITE','ALLOW','ROLE','employee'),(270,'SupplierAddress','*','*','ALLOW','ROLE','employee'),(271,'SalesMonitor','*','*','ALLOW','ROLE','employee'),(272,'InvoiceInLog','*','READ','ALLOW','ROLE','employee'),(273,'InvoiceInTax','*','*','ALLOW','ROLE','administrative'),(274,'InvoiceInLog','*','READ','ALLOW','ROLE','administrative'),(275,'InvoiceOut','createManualInvoice','WRITE','ALLOW','ROLE','invoicing'),(276,'InvoiceOut','globalInvoicing','WRITE','ALLOW','ROLE','invoicing'),(277,'Role','*','*','ALLOW','ROLE','it'),(278,'RoleInherit','*','WRITE','ALLOW','ROLE','grant'),(279,'MailAlias','*','*','ALLOW','ROLE','marketing'),(283,'EntryObservation','*','*','ALLOW','ROLE','buyer'),(284,'LdapConfig','*','*','ALLOW','ROLE','sysadmin'),(285,'SambaConfig','*','*','ALLOW','ROLE','sysadmin'),(286,'ACL','*','*','ALLOW','ROLE','developer'),(287,'AccessToken','*','*','ALLOW','ROLE','developer'),(288,'MailAliasAccount','*','*','ALLOW','ROLE','marketing'),(289,'MailAliasAccount','*','*','ALLOW','ROLE','hr'),(290,'MailAlias','*','*','ALLOW','ROLE','hr'),(291,'MailForward','*','*','ALLOW','ROLE','marketing'),(292,'MailForward','*','*','ALLOW','ROLE','hr'),(293,'RoleInherit','*','*','ALLOW','ROLE','it'),(294,'RoleRole','*','*','ALLOW','ROLE','it'),(295,'AccountConfig','*','*','ALLOW','ROLE','sysadmin'),(296,'Collection','*','READ','ALLOW','ROLE','employee'),(297,'Sale','refund','WRITE','ALLOW','ROLE','invoicing'),(298,'InvoiceInDueDay','*','*','ALLOW','ROLE','administrative'),(299,'Collection','setSaleQuantity','*','ALLOW','ROLE','employee'),(300,'Docuware','*','*','ALLOW','ROLE','employee'),(301,'Agency','*','READ','ALLOW','ROLE','employee'),(302,'AgencyTerm','*','*','ALLOW','ROLE','administrative'),(303,'ClaimLog','*','READ','ALLOW','ROLE','claimManager'),(304,'Edi','updateData','WRITE','ALLOW','ROLE','employee'),(305,'EducationLevel','*','*','ALLOW','ROLE','employee'),(306,'InvoiceInIntrastat','*','*','ALLOW','ROLE','employee'),(307,'SupplierAgencyTerm','*','*','ALLOW','ROLE','administrative'),(308,'InvoiceInIntrastat','*','*','ALLOW','ROLE','employee'),(309,'Zone','getZoneClosing','*','ALLOW','ROLE','employee'),(310,'ExpeditionState','*','READ','ALLOW','ROLE','employee'),(311,'Expense','*','READ','ALLOW','ROLE','employee'),(312,'Expense','*','WRITE','ALLOW','ROLE','administrative'),(314,'SupplierActivity','*','READ','ALLOW','ROLE','employee'),(315,'SupplierActivity','*','WRITE','ALLOW','ROLE','administrative'),(316,'Dms','deleteTrashFiles','WRITE','ALLOW','ROLE','employee'),(317,'ClientUnpaid','*','*','ALLOW','ROLE','administrative'),(318,'MdbVersion','*','*','ALLOW','ROLE','developer'),(319,'ItemType','*','READ','ALLOW','ROLE','employee'),(320,'ItemType','*','WRITE','ALLOW','ROLE','buyer'),(321,'InvoiceOut','refund','WRITE','ALLOW','ROLE','invoicing'),(322,'InvoiceOut','refund','WRITE','ALLOW','ROLE','salesAssistant'),(323,'InvoiceOut','refund','WRITE','ALLOW','ROLE','claimManager'),(324,'Ticket','refund','WRITE','ALLOW','ROLE','invoicing'),(325,'Ticket','refund','WRITE','ALLOW','ROLE','salesAssistant'),(326,'Ticket','refund','WRITE','ALLOW','ROLE','claimManager'),(327,'Sale','refund','WRITE','ALLOW','ROLE','salesAssistant'),(328,'Sale','refund','WRITE','ALLOW','ROLE','claimManager'),(329,'TicketRefund','*','WRITE','ALLOW','ROLE','invoicing'),(330,'ClaimObservation','*','WRITE','ALLOW','ROLE','salesPerson'),(331,'ClaimObservation','*','READ','ALLOW','ROLE','salesPerson'),(332,'Client','setPassword','WRITE','ALLOW','ROLE','salesPerson'),(333,'Client','updateUser','WRITE','ALLOW','ROLE','salesPerson'),(334,'ShelvingLog','*','READ','ALLOW','ROLE','employee'),(335,'ZoneExclusionGeo','*','READ','ALLOW','ROLE','employee'),(336,'ZoneExclusionGeo','*','WRITE','ALLOW','ROLE','deliveryAssistant'),(337,'Parking','*','*','ALLOW','ROLE','employee'),(338,'Shelving','*','*','ALLOW','ROLE','employee'),(339,'OsTicket','*','*','ALLOW','ROLE','employee'),(340,'OsTicketConfig','*','*','ALLOW','ROLE','it'),(341,'ClientConsumptionQueue','*','WRITE','ALLOW','ROLE','employee'),(342,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','employee'),(343,'Ticket','deliveryNoteEmail','WRITE','ALLOW','ROLE','employee'),(344,'Ticket','deliveryNoteCsvPdf','READ','ALLOW','ROLE','employee'),(345,'Ticket','deliveryNoteCsvEmail','WRITE','ALLOW','ROLE','employee'),(346,'Client','campaignMetricsPdf','READ','ALLOW','ROLE','employee'),(347,'Client','campaignMetricsEmail','WRITE','ALLOW','ROLE','employee'),(348,'Client','clientWelcomeHtml','READ','ALLOW','ROLE','employee'),(349,'Client','clientWelcomeEmail','WRITE','ALLOW','ROLE','employee'),(350,'Client','creditRequestPdf','READ','ALLOW','ROLE','employee'),(351,'Client','creditRequestHtml','READ','ALLOW','ROLE','employee'),(352,'Client','creditRequestEmail','WRITE','ALLOW','ROLE','employee'),(353,'Client','printerSetupHtml','READ','ALLOW','ROLE','employee'),(354,'Client','printerSetupEmail','WRITE','ALLOW','ROLE','employee'),(355,'Client','sepaCoreEmail','WRITE','ALLOW','ROLE','employee'),(356,'Client','letterDebtorPdf','READ','ALLOW','ROLE','employee'),(357,'Client','letterDebtorStHtml','READ','ALLOW','ROLE','employee'),(358,'Client','letterDebtorStEmail','WRITE','ALLOW','ROLE','employee'),(359,'Client','letterDebtorNdHtml','READ','ALLOW','ROLE','employee'),(360,'Client','letterDebtorNdEmail','WRITE','ALLOW','ROLE','employee'),(361,'Client','clientDebtStatementPdf','READ','ALLOW','ROLE','employee'),(362,'Client','clientDebtStatementHtml','READ','ALLOW','ROLE','employee'),(363,'Client','clientDebtStatementEmail','WRITE','ALLOW','ROLE','employee'),(364,'Client','incotermsAuthorizationPdf','READ','ALLOW','ROLE','employee'),(365,'Client','incotermsAuthorizationHtml','READ','ALLOW','ROLE','employee'),(366,'Client','incotermsAuthorizationEmail','WRITE','ALLOW','ROLE','employee'),(367,'Client','consumptionSendQueued','WRITE','ALLOW','ROLE','system'),(368,'InvoiceOut','invoiceEmail','WRITE','ALLOW','ROLE','employee'),(369,'InvoiceOut','exportationPdf','READ','ALLOW','ROLE','employee'),(370,'InvoiceOut','sendQueued','WRITE','ALLOW','ROLE','system'),(371,'Ticket','invoiceCsvPdf','READ','ALLOW','ROLE','employee'),(372,'Ticket','invoiceCsvEmail','WRITE','ALLOW','ROLE','employee'),(373,'Supplier','campaignMetricsPdf','READ','ALLOW','ROLE','employee'),(374,'Supplier','campaignMetricsEmail','WRITE','ALLOW','ROLE','employee'),(375,'Travel','extraCommunityPdf','READ','ALLOW','ROLE','employee'),(376,'Travel','extraCommunityEmail','WRITE','ALLOW','ROLE','employee'),(377,'Entry','entryOrderPdf','READ','ALLOW','ROLE','employee'),(378,'OsTicket','osTicketReportEmail','WRITE','ALLOW','ROLE','system'),(379,'Item','buyerWasteEmail','WRITE','ALLOW','ROLE','system'),(380,'Claim','claimPickupPdf','READ','ALLOW','ROLE','employee'),(381,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','claimManager'),(382,'Item','labelPdf','READ','ALLOW','ROLE','employee'),(383,'Sector','*','READ','ALLOW','ROLE','employee'),(384,'Sector','*','WRITE','ALLOW','ROLE','employee'),(385,'Route','driverRoutePdf','READ','ALLOW','ROLE','employee'),(386,'Route','driverRouteEmail','WRITE','ALLOW','ROLE','employee'),(387,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','customer'),(388,'Supplier','newSupplier','WRITE','ALLOW','ROLE','administrative'),(389,'ClaimRma','*','READ','ALLOW','ROLE','claimManager'),(390,'ClaimRma','*','WRITE','ALLOW','ROLE','claimManager'),(391,'Notification','*','WRITE','ALLOW','ROLE','system'),(392,'Boxing','*','*','ALLOW','ROLE','employee'),(393,'Url','*','READ','ALLOW','ROLE','employee'),(394,'Url','*','WRITE','ALLOW','ROLE','it'),(395,'ItemShelving','*','READ','ALLOW','ROLE','employee'),(396,'ItemShelving','*','WRITE','ALLOW','ROLE','production'),(397,'ItemShelvingPlacementSupplyStock','*','READ','ALLOW','ROLE','employee'),(398,'NotificationQueue','*','*','ALLOW','ROLE','employee'),(399,'InvoiceOut','clientsToInvoice','WRITE','ALLOW','ROLE','invoicing'),(400,'InvoiceOut','invoiceClient','WRITE','ALLOW','ROLE','invoicing'),(401,'Sale','editTracked','WRITE','ALLOW','ROLE','production'),(402,'Sale','editFloramondo','WRITE','ALLOW','ROLE','salesAssistant'),(403,'Receipt','balanceCompensationEmail','WRITE','ALLOW','ROLE','employee'),(404,'Receipt','balanceCompensationPdf','READ','ALLOW','ROLE','employee'),(405,'Ticket','getTicketsFuture','READ','ALLOW','ROLE','employee'),(406,'Ticket','merge','WRITE','ALLOW','ROLE','employee'),(407,'Sale','editFloramondo','WRITE','ALLOW','ROLE','logistic'),(408,'ZipConfig','*','*','ALLOW','ROLE','employee'),(409,'Item','*','WRITE','ALLOW','ROLE','administrative'),(410,'Sale','editCloned','WRITE','ALLOW','ROLE','buyer'),(411,'Sale','editCloned','WRITE','ALLOW','ROLE','salesAssistant'),(414,'MdbVersion','*','READ','ALLOW','ROLE','$everyone'),(416,'TicketLog','getChanges','READ','ALLOW','ROLE','employee'),(417,'Ticket','getTicketsAdvance','READ','ALLOW','ROLE','employee'),(418,'EntryLog','*','READ','ALLOW','ROLE','administrative'),(419,'Sale','editTracked','WRITE','ALLOW','ROLE','buyer'),(420,'MdbBranch','*','READ','ALLOW','ROLE','$everyone'),(421,'ItemShelvingSale','*','*','ALLOW','ROLE','employee'),(422,'Docuware','checkFile','READ','ALLOW','ROLE','employee'),(423,'Docuware','download','READ','ALLOW','ROLE','salesPerson'),(424,'Docuware','upload','WRITE','ALLOW','ROLE','productionAssi'),(425,'Docuware','deliveryNoteEmail','WRITE','ALLOW','ROLE','salesPerson'),(426,'TpvTransaction','confirm','WRITE','ALLOW','ROLE','$everyone'),(427,'TpvTransaction','start','WRITE','ALLOW','ROLE','$authenticated'),(428,'TpvTransaction','end','WRITE','ALLOW','ROLE','$authenticated'),(429,'ItemConfig','*','READ','ALLOW','ROLE','employee'),(431,'Tag','onSubmit','WRITE','ALLOW','ROLE','employee'),(432,'Worker','updateAttributes','WRITE','ALLOW','ROLE','hr'),(433,'Worker','createAbsence','*','ALLOW','ROLE','employee'),(434,'Worker','updateAbsence','WRITE','ALLOW','ROLE','employee'),(435,'Worker','deleteAbsence','*','ALLOW','ROLE','employee'),(436,'Worker','new','WRITE','ALLOW','ROLE','hr'),(437,'Role','*','READ','ALLOW','ROLE','hr'),(438,'Client','getClientOrSupplierReference','READ','ALLOW','ROLE','employee'),(439,'NotificationSubscription','*','*','ALLOW','ROLE','employee'),(440,'NotificationAcl','*','READ','ALLOW','ROLE','employee'),(441,'MdbApp','*','READ','ALLOW','ROLE','$everyone'),(442,'MdbApp','*','*','ALLOW','ROLE','developer'),(443,'ItemConfig','*','*','ALLOW','ROLE','employee'),(444,'DeviceProduction','*','*','ALLOW','ROLE','hr'),(445,'DeviceProductionModels','*','*','ALLOW','ROLE','hr'),(446,'DeviceProductionState','*','*','ALLOW','ROLE','hr'),(447,'DeviceProductionUser','*','*','ALLOW','ROLE','hr'),(448,'DeviceProduction','*','*','ALLOW','ROLE','productionAssi'),(449,'DeviceProductionModels','*','*','ALLOW','ROLE','productionAssi'),(450,'DeviceProductionState','*','*','ALLOW','ROLE','productionAssi'),(451,'DeviceProductionUser','*','*','ALLOW','ROLE','productionAssi'),(452,'Worker','deallocatePDA','*','ALLOW','ROLE','hr'),(453,'Worker','allocatePDA','*','ALLOW','ROLE','hr'),(454,'Worker','deallocatePDA','*','ALLOW','ROLE','productionAssi'),(455,'Worker','allocatePDA','*','ALLOW','ROLE','productionAssi'),(456,'Zone','*','*','ALLOW','ROLE','deliveryAssistant'),(457,'Account','setPassword','WRITE','ALLOW','ROLE','itManagement'),(458,'Operator','*','READ','ALLOW','ROLE','employee'),(459,'Operator','*','WRITE','ALLOW','ROLE','employee'),(460,'InvoiceIn','getSerial','READ','ALLOW','ROLE','administrative'),(461,'Ticket','saveSign','WRITE','ALLOW','ROLE','employee'),(462,'InvoiceOut','negativeBases','READ','ALLOW','ROLE','administrative'),(463,'InvoiceOut','negativeBasesCsv','READ','ALLOW','ROLE','administrative'),(464,'WorkerObservation','*','*','ALLOW','ROLE','hr'),(465,'ClientInforma','*','READ','ALLOW','ROLE','employee'),(466,'ClientInforma','*','WRITE','ALLOW','ROLE','financial'),(467,'Receipt','receiptEmail','*','ALLOW','ROLE','salesAssistant'),(468,'Client','setRating','WRITE','ALLOW','ROLE','financial'),(469,'Client','*','READ','ALLOW','ROLE','employee'),(470,'Client','addressesPropagateRe','*','ALLOW','ROLE','employee'),(471,'Client','canBeInvoiced','*','ALLOW','ROLE','employee'),(472,'Client','canCreateTicket','*','ALLOW','ROLE','employee'),(473,'Client','consumption','*','ALLOW','ROLE','employee'),(474,'Client','createAddress','*','ALLOW','ROLE','employee'),(475,'Client','createWithUser','*','ALLOW','ROLE','employee'),(476,'Client','extendedListFilter','*','ALLOW','ROLE','employee'),(477,'Client','getAverageInvoiced','*','ALLOW','ROLE','employee'),(478,'Client','getCard','*','ALLOW','ROLE','employee'),(479,'Client','getDebt','*','ALLOW','ROLE','employee'),(480,'Client','getMana','*','ALLOW','ROLE','employee'),(481,'Client','transactions','*','ALLOW','ROLE','employee'),(482,'Client','hasCustomerRole','*','ALLOW','ROLE','employee'),(483,'Client','isValidClient','*','ALLOW','ROLE','employee'),(484,'Client','lastActiveTickets','*','ALLOW','ROLE','employee'),(485,'Client','sendSms','*','ALLOW','ROLE','employee'),(486,'Client','setPassword','*','ALLOW','ROLE','employee'),(487,'Client','summary','*','ALLOW','ROLE','employee'),(488,'Client','updateAddress','*','ALLOW','ROLE','employee'),(489,'Client','updateFiscalData','*','ALLOW','ROLE','employee'),(490,'Client','updateUser','*','ALLOW','ROLE','employee'),(491,'Client','uploadFile','*','ALLOW','ROLE','employee'),(492,'Client','campaignMetricsPdf','*','ALLOW','ROLE','employee'),(493,'Client','campaignMetricsEmail','*','ALLOW','ROLE','employee'),(494,'Client','clientWelcomeHtml','*','ALLOW','ROLE','employee'),(495,'Client','clientWelcomeEmail','*','ALLOW','ROLE','employee'),(496,'Client','printerSetupHtml','*','ALLOW','ROLE','employee'),(497,'Client','printerSetupEmail','*','ALLOW','ROLE','employee'),(498,'Client','sepaCoreEmail','*','ALLOW','ROLE','employee'),(499,'Client','letterDebtorPdf','*','ALLOW','ROLE','employee'),(500,'Client','letterDebtorStHtml','*','ALLOW','ROLE','employee'),(501,'Client','letterDebtorStEmail','*','ALLOW','ROLE','employee'),(502,'Client','letterDebtorNdHtml','*','ALLOW','ROLE','employee'),(503,'Client','letterDebtorNdEmail','*','ALLOW','ROLE','employee'),(504,'Client','clientDebtStatementPdf','*','ALLOW','ROLE','employee'),(505,'Client','clientDebtStatementHtml','*','ALLOW','ROLE','employee'),(506,'Client','clientDebtStatementEmail','*','ALLOW','ROLE','employee'),(507,'Client','creditRequestPdf','*','ALLOW','ROLE','employee'),(508,'Client','creditRequestHtml','*','ALLOW','ROLE','employee'),(509,'Client','creditRequestEmail','*','ALLOW','ROLE','employee'),(510,'Client','incotermsAuthorizationPdf','*','ALLOW','ROLE','employee'),(511,'Client','incotermsAuthorizationHtml','*','ALLOW','ROLE','employee'),(512,'Client','incotermsAuthorizationEmail','*','ALLOW','ROLE','employee'),(513,'Client','consumptionSendQueued','*','ALLOW','ROLE','employee'),(514,'Client','filter','*','ALLOW','ROLE','employee'),(515,'Client','getClientOrSupplierReference','*','ALLOW','ROLE','employee'),(516,'Client','upsert','*','ALLOW','ROLE','employee'),(517,'Client','create','*','ALLOW','ROLE','employee'),(518,'Client','replaceById','*','ALLOW','ROLE','employee'),(519,'Client','updateAttributes','*','ALLOW','ROLE','employee'),(520,'Client','updateAttributes','*','ALLOW','ROLE','employee'),(521,'Client','deleteById','*','ALLOW','ROLE','employee'),(522,'Client','replaceOrCreate','*','ALLOW','ROLE','employee'),(523,'Client','updateAll','*','ALLOW','ROLE','employee'),(524,'Client','upsertWithWhere','*','ALLOW','ROLE','employee'),(525,'Defaulter','observationEmail','WRITE','ALLOW','ROLE','employee'),(526,'VnUser','*','*','ALLOW','ROLE','employee'),(527,'VnUser','acl','READ','ALLOW','ROLE','account'),(528,'VnUser','getCurrentUserData','READ','ALLOW','ROLE','account'),(529,'VnUser','changePassword','WRITE','ALLOW','ROLE','account'),(530,'Account','exists','READ','ALLOW','ROLE','account'),(531,'Account','exists','READ','ALLOW','ROLE','account'),(532,'UserLog','*','READ','ALLOW','ROLE','employee'),(533,'RoleLog','*','READ','ALLOW','ROLE','employee'); /*!40000 ALTER TABLE `ACL` ENABLE KEYS */; UNLOCK TABLES; diff --git a/e2e/paths/02-client/01_create_client.spec.js b/e2e/paths/02-client/01_create_client.spec.js index 9be9a5915..889f7c058 100644 --- a/e2e/paths/02-client/01_create_client.spec.js +++ b/e2e/paths/02-client/01_create_client.spec.js @@ -8,7 +8,7 @@ describe('Client create path', () => { beforeAll(async() => { browser = await getBrowser(); page = browser.page; - await page.loginAndModule(' deliveryAssist', 'client'); + await page.loginAndModule(' deliveryAssistant', 'client'); }); afterAll(async() => { diff --git a/e2e/paths/03-worker/06_create.spec.js b/e2e/paths/03-worker/06_create.spec.js index 3257f170f..0c0822c51 100644 --- a/e2e/paths/03-worker/06_create.spec.js +++ b/e2e/paths/03-worker/06_create.spec.js @@ -45,7 +45,7 @@ describe('Worker create path', () => { // should create a new worker and go to worker basic data' await page.pickDate(selectors.workerCreate.birth, new Date(1962, 8, 5)); - await page.autocompleteSearch(selectors.workerCreate.boss, 'deliveryAssist'); + await page.autocompleteSearch(selectors.workerCreate.boss, 'deliveryAssistant'); await page.waitToClick(selectors.workerCreate.createButton); message = await page.waitForSnackbar(); await page.waitForState('worker.card.basicData'); diff --git a/e2e/paths/11-zone/01_basic-data.spec.js b/e2e/paths/11-zone/01_basic-data.spec.js index c06f955c6..34d08c57f 100644 --- a/e2e/paths/11-zone/01_basic-data.spec.js +++ b/e2e/paths/11-zone/01_basic-data.spec.js @@ -9,7 +9,7 @@ describe('Zone basic data path', () => { browser = await getBrowser(); page = browser.page; - await page.loginAndModule('deliveryAssist', + await page.loginAndModule('deliveryAssistant', 'zone'); // turns up the zone module name and route aint the same lol await page.accessToSearchResult('10'); await page.accessToSection('zone.card.basicData'); diff --git a/e2e/paths/11-zone/02_descriptor.spec.js b/e2e/paths/11-zone/02_descriptor.spec.js index 56340efe7..baccc910f 100644 --- a/e2e/paths/11-zone/02_descriptor.spec.js +++ b/e2e/paths/11-zone/02_descriptor.spec.js @@ -8,7 +8,7 @@ describe('Zone descriptor path', () => { beforeAll(async() => { browser = await getBrowser(); page = browser.page; - await page.loginAndModule('deliveryAssist', 'zone'); + await page.loginAndModule('deliveryAssistant', 'zone'); await page.accessToSearchResult('13'); }); diff --git a/modules/client/front/address/create/index.html b/modules/client/front/address/create/index.html index 1e2bf1470..20e7b38e1 100644 --- a/modules/client/front/address/create/index.html +++ b/modules/client/front/address/create/index.html @@ -68,7 +68,7 @@ icon="add_circle" vn-tooltip="New postcode" ng-click="postcode.open()" - vn-acl="deliveryAssist" + vn-acl="deliveryAssistant" vn-acl-action="remove"> diff --git a/modules/client/front/address/edit/index.html b/modules/client/front/address/edit/index.html index 0ba780ef8..e6b1dc71e 100644 --- a/modules/client/front/address/edit/index.html +++ b/modules/client/front/address/edit/index.html @@ -81,7 +81,7 @@ icon="add_circle" vn-tooltip="New postcode" ng-click="postcode.open()" - vn-acl="deliveryAssist" + vn-acl="deliveryAssistant" vn-acl-action="remove"> diff --git a/modules/client/front/create/index.html b/modules/client/front/create/index.html index dd13e7a10..b2f1236b7 100644 --- a/modules/client/front/create/index.html +++ b/modules/client/front/create/index.html @@ -76,7 +76,7 @@ icon="add_circle" vn-tooltip="New postcode" ng-click="postcode.open()" - vn-acl="deliveryAssist" + vn-acl="deliveryAssistant" vn-acl-action="remove"> diff --git a/modules/client/front/fiscal-data/index.html b/modules/client/front/fiscal-data/index.html index 8dffcf4ca..18127db6a 100644 --- a/modules/client/front/fiscal-data/index.html +++ b/modules/client/front/fiscal-data/index.html @@ -92,7 +92,7 @@ icon="add_circle" vn-tooltip="New postcode" ng-click="postcode.open()" - vn-acl="deliveryAssist" + vn-acl="deliveryAssistant" vn-acl-action="remove"> diff --git a/modules/client/front/postcode/index.html b/modules/client/front/postcode/index.html index ad1580945..b3dbb74d8 100644 --- a/modules/client/front/postcode/index.html +++ b/modules/client/front/postcode/index.html @@ -27,7 +27,7 @@ icon="add_circle" vn-tooltip="New city" ng-click="city.open($event)" - vn-acl="deliveryAssist" + vn-acl="deliveryAssistant" vn-acl-action="remove"> @@ -45,7 +45,7 @@ icon="add_circle" vn-tooltip="New province" ng-click="province.open($event)" - vn-acl="deliveryAssist" + vn-acl="deliveryAssistant" vn-acl-action="remove"> diff --git a/modules/route/front/descriptor/index.html b/modules/route/front/descriptor/index.html index 8b6cf6535..4e7e99f1a 100644 --- a/modules/route/front/descriptor/index.html +++ b/modules/route/front/descriptor/index.html @@ -15,14 +15,14 @@
Update volume Delete route diff --git a/modules/route/front/tickets/index.html b/modules/route/front/tickets/index.html index 5723b118f..5c6f8bee5 100644 --- a/modules/route/front/tickets/index.html +++ b/modules/route/front/tickets/index.html @@ -37,7 +37,7 @@ icon="format_list_numbered"> diff --git a/modules/supplier/front/address/edit/index.html b/modules/supplier/front/address/edit/index.html index 2dbb34f15..b6f90134b 100644 --- a/modules/supplier/front/address/edit/index.html +++ b/modules/supplier/front/address/edit/index.html @@ -48,7 +48,7 @@ icon="add_circle" vn-tooltip="New postcode" ng-click="postcode.open()" - vn-acl="deliveryAssist" + vn-acl="deliveryAssistant" vn-acl-action="remove"> diff --git a/modules/supplier/front/fiscal-data/index.html b/modules/supplier/front/fiscal-data/index.html index ed6798c3c..3fe67762f 100644 --- a/modules/supplier/front/fiscal-data/index.html +++ b/modules/supplier/front/fiscal-data/index.html @@ -150,7 +150,7 @@ icon="add_circle" vn-tooltip="New postcode" ng-click="postcode.open()" - vn-acl="deliveryAssist" + vn-acl="deliveryAssistant" vn-acl-action="remove"> diff --git a/modules/worker/front/create/index.html b/modules/worker/front/create/index.html index 24f719a68..50daacb7d 100644 --- a/modules/worker/front/create/index.html +++ b/modules/worker/front/create/index.html @@ -72,7 +72,7 @@ icon="add_circle" vn-tooltip="New postcode" ng-click="postcode.open()" - vn-acl="deliveryAssist" + vn-acl="deliveryAssistant" vn-acl-action="remove"> diff --git a/modules/zone/front/basic-data/index.html b/modules/zone/front/basic-data/index.html index 39fb25fae..5070a3aea 100644 --- a/modules/zone/front/basic-data/index.html +++ b/modules/zone/front/basic-data/index.html @@ -14,7 +14,7 @@ @@ -26,7 +26,7 @@ show-field="name" value-field="id" label="Agency" - vn-acl="deliveryAssist" + vn-acl="deliveryAssistant" rule> @@ -52,13 +52,13 @@ ng-model="$ctrl.zone.travelingDays" min="0" step="1" - vn-acl="deliveryAssist" + vn-acl="deliveryAssistant" rule> @@ -68,14 +68,14 @@ ng-model="$ctrl.zone.price" min="0" step="0.01" - vn-acl="deliveryAssist" + vn-acl="deliveryAssistant" rule> @@ -86,14 +86,14 @@ ng-model="$ctrl.zone.inflation" min="0" step="0.01" - vn-acl="deliveryAssist" + vn-acl="deliveryAssistant" rule> @@ -101,7 +101,7 @@ diff --git a/modules/zone/front/location/index.html b/modules/zone/front/location/index.html index caace6660..b86c618b7 100644 --- a/modules/zone/front/location/index.html +++ b/modules/zone/front/location/index.html @@ -16,7 +16,7 @@ root-label="Locations" fetch-func="$ctrl.onFetch($item)" sort-func="$ctrl.onSort($a, $b)"> - Date: Tue, 27 Jun 2023 13:17:00 +0200 Subject: [PATCH 017/427] refs #5660 change sql --- .../01-deliveryAssistantInheritRole.sql | 23 ------------------- .../00-deliveryAssistantACL.sql | 0 .../01-deliveryAssistantInheritRole.sql | 23 +++++++++++++++++++ e2e/paths/02-client/01_create_client.spec.js | 2 +- 4 files changed, 24 insertions(+), 24 deletions(-) delete mode 100644 db/changes/232601/01-deliveryAssistantInheritRole.sql rename db/changes/{232601 => 232801}/00-deliveryAssistantACL.sql (100%) create mode 100644 db/changes/232801/01-deliveryAssistantInheritRole.sql diff --git a/db/changes/232601/01-deliveryAssistantInheritRole.sql b/db/changes/232601/01-deliveryAssistantInheritRole.sql deleted file mode 100644 index ad4d7dd1e..000000000 --- a/db/changes/232601/01-deliveryAssistantInheritRole.sql +++ /dev/null @@ -1,23 +0,0 @@ --- -- Auto-generated SQL script #202306121403 --- INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) --- VALUES (117,1); --- INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) --- VALUES (117,2); --- INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) --- VALUES (117,3); --- INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) --- VALUES (117,6); --- INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) --- VALUES (117,11); --- INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) --- VALUES (117,13); --- INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) --- VALUES (117,33); --- INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) --- VALUES (117,56); --- INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) --- VALUES (117,57); --- INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) --- VALUES (117,70); --- INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) --- VALUES (117,76); diff --git a/db/changes/232601/00-deliveryAssistantACL.sql b/db/changes/232801/00-deliveryAssistantACL.sql similarity index 100% rename from db/changes/232601/00-deliveryAssistantACL.sql rename to db/changes/232801/00-deliveryAssistantACL.sql diff --git a/db/changes/232801/01-deliveryAssistantInheritRole.sql b/db/changes/232801/01-deliveryAssistantInheritRole.sql new file mode 100644 index 000000000..5b3806fa2 --- /dev/null +++ b/db/changes/232801/01-deliveryAssistantInheritRole.sql @@ -0,0 +1,23 @@ +-- Auto-generated SQL script #202306121403 +INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) + VALUES (117,1); +INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) + VALUES (117,2); +INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) + VALUES (117,3); +INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) + VALUES (117,6); +INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) + VALUES (117,11); +INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) + VALUES (117,13); +INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) + VALUES (117,33); +INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) + VALUES (117,56); +INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) + VALUES (117,57); +INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) + VALUES (117,70); +INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) + VALUES (117,76); diff --git a/e2e/paths/02-client/01_create_client.spec.js b/e2e/paths/02-client/01_create_client.spec.js index 889f7c058..0fd06402a 100644 --- a/e2e/paths/02-client/01_create_client.spec.js +++ b/e2e/paths/02-client/01_create_client.spec.js @@ -8,7 +8,7 @@ describe('Client create path', () => { beforeAll(async() => { browser = await getBrowser(); page = browser.page; - await page.loginAndModule(' deliveryAssistant', 'client'); + await page.loginAndModule('deliveryAssistant', 'client'); }); afterAll(async() => { From 68b65105fdb5026e5ecec3eb0ae3d5fe7d8ef19c Mon Sep 17 00:00:00 2001 From: carlossa Date: Wed, 28 Jun 2023 08:02:31 +0200 Subject: [PATCH 018/427] refs #5660 role mod --- db/changes/232801/00-deliveryAssistantACL.sql | 8 +++--- .../01-deliveryAssistantInheritRole.sql | 28 ++++--------------- 2 files changed, 9 insertions(+), 27 deletions(-) diff --git a/db/changes/232801/00-deliveryAssistantACL.sql b/db/changes/232801/00-deliveryAssistantACL.sql index e5152087e..94873aece 100644 --- a/db/changes/232801/00-deliveryAssistantACL.sql +++ b/db/changes/232801/00-deliveryAssistantACL.sql @@ -1,7 +1,7 @@ --- Auto-generated SQL script #202306121356 -UPDATE `account`.`role` - SET `description` = 'Asistente de envios' - WHERE `name` = 'deliveryAssistant'; +-- Auto-generated SQL script. Actual values for binary/complex data types may differ - what you see is the default string representation of values. +INSERT INTO `account`.`role` (name,description) + VALUES ('deliveryAssistant','Asistencia de envios'); + diff --git a/db/changes/232801/01-deliveryAssistantInheritRole.sql b/db/changes/232801/01-deliveryAssistantInheritRole.sql index 5b3806fa2..e8146e806 100644 --- a/db/changes/232801/01-deliveryAssistantInheritRole.sql +++ b/db/changes/232801/01-deliveryAssistantInheritRole.sql @@ -1,23 +1,5 @@ --- Auto-generated SQL script #202306121403 -INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) - VALUES (117,1); -INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) - VALUES (117,2); -INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) - VALUES (117,3); -INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) - VALUES (117,6); -INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) - VALUES (117,11); -INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) - VALUES (117,13); -INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) - VALUES (117,33); -INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) - VALUES (117,56); -INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) - VALUES (117,57); -INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) - VALUES (117,70); -INSERT INTO `account`.`roleInherit` (`role`,inheritsFrom) - VALUES (117,76); +INSERT INTO account.roleInherit + SELECT (SELECT id FROM account.role r WHERE r.name = 'deliveryAssistant'), ri.inheritsFrom + FROM account.roleInherit ri + JOIN account.role r ON r.id = ri.`role` + WHERE r.name = 'deliveryBoss'; \ No newline at end of file From d32563eec7dcca90e86c8327c2a9c1a98ca07e42 Mon Sep 17 00:00:00 2001 From: carlossa Date: Wed, 28 Jun 2023 08:37:30 +0200 Subject: [PATCH 019/427] refs #5660 delivery --- db/changes/232801/00-changeRole.sql | 1 + .../{00-deliveryAssistantACL.sql => 01-deliveryAssistantACL.sql} | 0 ...istantInheritRole.sql => 02-deliveryAssistantInheritRole.sql} | 0 3 files changed, 1 insertion(+) create mode 100644 db/changes/232801/00-changeRole.sql rename db/changes/232801/{00-deliveryAssistantACL.sql => 01-deliveryAssistantACL.sql} (100%) rename db/changes/232801/{01-deliveryAssistantInheritRole.sql => 02-deliveryAssistantInheritRole.sql} (100%) diff --git a/db/changes/232801/00-changeRole.sql b/db/changes/232801/00-changeRole.sql new file mode 100644 index 000000000..3c8c81edb --- /dev/null +++ b/db/changes/232801/00-changeRole.sql @@ -0,0 +1 @@ +ALTER TABLE account.`role` MODIFY COLUMN name varchar(79) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL COMMENT 'MySQL doesn''t support more than 14 chars for proxied user names'; diff --git a/db/changes/232801/00-deliveryAssistantACL.sql b/db/changes/232801/01-deliveryAssistantACL.sql similarity index 100% rename from db/changes/232801/00-deliveryAssistantACL.sql rename to db/changes/232801/01-deliveryAssistantACL.sql diff --git a/db/changes/232801/01-deliveryAssistantInheritRole.sql b/db/changes/232801/02-deliveryAssistantInheritRole.sql similarity index 100% rename from db/changes/232801/01-deliveryAssistantInheritRole.sql rename to db/changes/232801/02-deliveryAssistantInheritRole.sql From 39f821252927c5e81987e937569f965bde1c0a16 Mon Sep 17 00:00:00 2001 From: carlossa Date: Wed, 28 Jun 2023 11:30:22 +0200 Subject: [PATCH 020/427] refs #5660 fixtures acls --- db/changes/232801/01-deliveryAssistantACL.sql | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/db/changes/232801/01-deliveryAssistantACL.sql b/db/changes/232801/01-deliveryAssistantACL.sql index 94873aece..5ee8a566f 100644 --- a/db/changes/232801/01-deliveryAssistantACL.sql +++ b/db/changes/232801/01-deliveryAssistantACL.sql @@ -2,6 +2,22 @@ INSERT INTO `account`.`role` (name,description) VALUES ('deliveryAssistant','Asistencia de envios'); +INSERT INTO `account`.`roleInherit` + SELECT (SELECT id FROM account.role r WHERE r.name = 'deliveryAssistant'), ri.inheritsFrom + FROM account.roleInherit ri + JOIN account.role r ON r.id = ri.`role` + WHERE r.name = 'deliveryBoss'; + + +DELETE FROM roleInherit WHERE role = 57; + +INSERT INTO `account`.`roleInherit` + SELECT (SELECT id FROM account.role r WHERE r.name = 'deliveryBoss'), ri.inheritsFrom + FROM account.roleInherit ri + JOIN account.role r ON r.id = ri.`role` + WHERE + + From 3bea23c52a0116652217893223389065b6555319 Mon Sep 17 00:00:00 2001 From: carlossa Date: Wed, 28 Jun 2023 11:30:45 +0200 Subject: [PATCH 021/427] refs #5660 delivery acls --- db/changes/232801/02-deliveryAssistantInheritRole.sql | 4 ++-- db/dump/dumpedFixtures.sql | 2 +- db/dump/structure.sql | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/db/changes/232801/02-deliveryAssistantInheritRole.sql b/db/changes/232801/02-deliveryAssistantInheritRole.sql index e8146e806..403ea5cdc 100644 --- a/db/changes/232801/02-deliveryAssistantInheritRole.sql +++ b/db/changes/232801/02-deliveryAssistantInheritRole.sql @@ -1,5 +1,5 @@ -INSERT INTO account.roleInherit - SELECT (SELECT id FROM account.role r WHERE r.name = 'deliveryAssistant'), ri.inheritsFrom +INSERT INTO account.roleInherit(role,inheritsFrom) + SELECT (SELECT id FROM account.role r WHERE r.name = 'deliveryAssistant') role, ri.inheritsFrom FROM account.roleInherit ri JOIN account.role r ON r.id = ri.`role` WHERE r.name = 'deliveryBoss'; \ No newline at end of file diff --git a/db/dump/dumpedFixtures.sql b/db/dump/dumpedFixtures.sql index 3403ffaf3..23aa619e7 100644 --- a/db/dump/dumpedFixtures.sql +++ b/db/dump/dumpedFixtures.sql @@ -78,7 +78,7 @@ USE `account`; LOCK TABLES `role` WRITE; /*!40000 ALTER TABLE `role` DISABLE KEYS */; -INSERT INTO `role` VALUES (1,'employee','Empleado básico',1,'2017-05-19 07:04:58','2017-11-29 10:06:31',NULL),(2,'customer','Privilegios básicos de un cliente',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(3,'agency','Consultar tablas de predicciones de bultos',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(5,'administrative','Tareas relacionadas con la contabilidad',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(6,'guest','Privilegios para usuarios sin cuenta',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(9,'developer','Desarrolladores del sistema',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(11,'account','Privilegios relacionados con el login',0,'2017-05-19 07:04:58','2017-09-20 17:06:35',NULL),(13,'teamBoss','Jefe de equipo/departamento',1,'2017-05-19 07:04:58','2021-06-30 13:29:30',NULL),(15,'logistic','Departamento de compras, responsables de la logistica',1,'2017-05-19 07:04:58','2018-02-12 10:50:10',NULL),(16,'logisticBoss','Jefe del departamento de logística',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(17,'adminBoss','Jefe del departamento de administración',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(18,'salesPerson','Departamento de ventas',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(19,'salesBoss','Jefe del departamento de ventas',1,'2017-05-19 07:04:58','2017-08-16 12:38:27',NULL),(20,'manager','Gerencia',1,'2017-06-01 14:57:02','2022-07-29 07:36:15',NULL),(21,'salesAssistant','Jefe auxiliar de ventas',1,'2017-08-16 12:40:52','2017-08-16 12:40:52',NULL),(22,'teamManager','Jefe de departamento con privilegios de auxiliar de venta.',1,'2017-09-07 09:08:12','2017-09-07 09:08:12',NULL),(30,'financialBoss','Director finaciero',1,'2017-09-21 11:05:36','2017-09-21 11:05:36',NULL),(31,'freelancer','Trabajadores por cuenta ajena',1,'2017-10-10 12:57:26','2017-10-10 12:59:27',NULL),(32,'ett','Trabajadores de empresa temporal',1,'2017-10-10 12:58:58','2017-10-10 12:59:20',NULL),(33,'invoicing','Personal con acceso a facturación',0,'2018-01-29 16:43:34','2018-01-29 16:43:34',NULL),(34,'agencyBoss','Jefe/a del departamento de agencias',1,'2018-01-29 16:44:39','2018-02-23 07:58:53',NULL),(35,'buyer','Departamento de compras',1,'2018-02-12 10:35:42','2018-02-12 10:35:42',NULL),(36,'replenisher','Trabajadores de camara',1,'2018-02-16 14:07:10','2019-04-12 05:38:08',NULL),(37,'hr','Gestor/a de recursos humanos',1,'2018-02-22 17:34:53','2018-02-22 17:34:53',NULL),(38,'hrBoss','Jefe/a de recursos humanos',1,'2018-02-22 17:35:09','2018-02-22 17:35:09',NULL),(39,'adminAssistant','Jefe auxiliar administrativo',1,'2018-02-23 10:37:36','2018-02-23 10:38:41',NULL),(40,'handmade','Departamento de confección',1,'2018-02-23 11:14:53','2018-02-23 11:39:12',NULL),(41,'handmadeBoss','Jefe de departamento de confección',1,'2018-02-23 11:15:09','2018-02-23 11:39:26',NULL),(42,'artificial','Departamento de artificial',1,'2018-02-23 11:39:59','2018-02-23 11:39:59',NULL),(43,'artificialBoss','Jefe del departamento de artificial',1,'2018-02-23 11:40:16','2018-02-23 11:40:16',NULL),(44,'accessory','Departamento de complementos',1,'2018-02-23 11:41:12','2018-02-23 11:41:12',NULL),(45,'accessoryBoss','Jefe del departamento de complementos',1,'2018-02-23 11:41:23','2018-02-23 11:41:23',NULL),(47,'cooler','Empleados de cámara',1,'2018-02-23 13:08:18','2018-02-23 13:08:18',NULL),(48,'coolerBoss','Jefe de cámara',1,'2018-02-23 13:12:01','2023-03-13 08:49:43',NULL),(49,'production','Empleado de producción',1,'2018-02-26 15:28:23','2021-02-12 09:42:35',NULL),(50,'productionBoss','Jefe de producción',1,'2018-02-26 15:34:12','2018-02-26 15:34:12',NULL),(51,'marketing','Departamento de marketing',1,'2018-03-01 07:28:39','2018-03-01 07:28:39',NULL),(52,'marketingBoss','Jefe del departamento de marketing',1,'2018-03-01 07:28:57','2018-03-01 07:28:57',NULL),(53,'insurance','Gestor de seguros de cambio',0,'2018-03-05 07:44:35','2019-02-01 13:47:57',NULL),(54,'itemPicker','Sacador en cámara',1,'2018-03-05 12:08:17','2018-03-05 12:08:17',NULL),(55,'itemPickerBoss','Jefe de sacadores',1,'2018-03-05 12:08:31','2018-03-05 12:08:31',NULL),(56,'delivery','Personal de reparto',1,'2018-05-30 06:07:02','2018-05-30 06:07:02',NULL),(57,'deliveryAssistantant','Jefe de personal de reparto',1,'2018-05-30 06:07:19','2018-05-30 06:07:19',NULL),(58,'packager','Departamento encajadores',1,'2019-01-21 12:43:45','2019-01-21 12:43:45',NULL),(59,'packagerBoss','Jefe departamento encajadores',1,'2019-01-21 12:44:10','2019-01-21 12:44:10',NULL),(60,'productionAssi','Tareas relacionadas con producción y administración',1,'2019-01-29 13:29:01','2019-01-29 13:29:01',NULL),(61,'replenisherBos','Jefe de Complementos/Camara',1,'2019-07-01 06:44:07','2019-07-01 06:44:07',NULL),(62,'noLogin','Role without login access to MySQL',0,'2019-07-01 06:50:19','2019-07-02 13:42:05',NULL),(64,'balanceSheet','Consulta de Balance',0,'2019-07-16 12:12:08','2019-07-16 12:12:08',NULL),(65,'officeBoss','Jefe de filial',1,'2019-08-02 06:54:26','2019-08-02 06:54:26',NULL),(66,'sysadmin','Administrador de sistema',1,'2019-08-08 06:58:56','2019-08-08 06:58:56',NULL),(67,'adminOfficer','categoria profesional oficial de administración',1,'2020-01-03 08:09:23','2020-01-03 08:09:23',NULL),(69,'coolerAssist','Asistente de cámara con permiso compras',1,'2020-02-05 12:36:09','2023-03-13 08:50:07',NULL),(70,'trainee','Alumno de prácticas',1,'2020-03-04 11:00:25','2020-03-04 11:00:25',NULL),(71,'checker','Rol de revisor con privilegios de itemPicker',1,'2020-10-02 10:50:07','2020-10-02 10:50:07',NULL),(72,'claimManager','Personal de reclamaciones',1,'2020-10-13 10:01:32','2020-10-26 07:29:46',NULL),(73,'financial','Departamento de finanzas',1,'2020-11-16 09:30:27','2020-11-16 09:30:27',NULL),(74,'userPhotos','Privilegios para subir fotos de usuario',1,'2021-02-03 10:24:27','2021-02-03 10:24:27',NULL),(75,'catalogPhotos','Privilegios para subir fotos del catálogo',1,'2021-02-03 10:24:27','2021-02-03 10:24:27',NULL),(76,'chat','Rol para utilizar el rocket chat',1,'2020-11-27 13:06:50','2020-12-17 07:49:41',NULL),(100,'root','Rol con todos los privilegios',0,'2018-04-23 14:33:36','2020-11-12 06:50:07',NULL),(101,'buyerBoss','Jefe del departamento de compras',1,'2021-06-16 09:53:17','2021-06-16 09:53:17',NULL),(102,'preservedBoss','Responsable preservado',1,'2021-09-14 13:45:37','2021-09-14 13:45:37',NULL),(103,'it','Departamento de informática',1,'2021-11-11 09:48:22','2021-11-11 09:48:22',NULL),(104,'itBoss','Jefe de departamento de informática',1,'2021-11-11 09:48:49','2021-11-11 09:48:49',NULL),(105,'grant','Adjudicar roles a usuarios',1,'2021-11-11 12:41:09','2021-11-11 12:41:09',NULL),(106,'ext','Usuarios externos de la Base de datos',1,'2021-11-23 14:51:16','2021-11-23 14:51:16',NULL),(107,'productionPlus','Creado para pepe por orden de Juanvi',1,'2022-02-08 06:47:10','2022-02-08 06:47:10',NULL),(108,'system','System user',1,'2022-05-16 08:09:51','2022-05-16 08:09:51',NULL),(109,'salesTeamBoss','Jefe de equipo de comerciales',1,'2022-06-14 13:45:56','2022-06-14 13:45:56',NULL),(110,'palletizer','Paletizadores',1,'2022-12-02 12:56:22','2022-12-02 12:56:30',NULL),(111,'entryEditor','Entry editor',1,'2023-01-13 11:21:55','2023-01-13 11:21:55',NULL),(112,'maintenance','Personal de mantenimiento',1,'2023-01-19 06:23:35','2023-01-19 06:23:35',NULL),(114,'maintenanceBos','Jefe de mantenimiento',1,'2023-01-19 06:31:16','2023-05-12 08:47:34',19294),(115,'itManagement','TI management',1,'2023-03-29 07:27:55','2023-03-29 07:28:04',NULL); +INSERT INTO `role` VALUES (1,'employee','Empleado básico',1,'2017-05-19 07:04:58','2017-11-29 10:06:31',NULL),(2,'customer','Privilegios básicos de un cliente',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(3,'agency','Consultar tablas de predicciones de bultos',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(5,'administrative','Tareas relacionadas con la contabilidad',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(6,'guest','Privilegios para usuarios sin cuenta',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(9,'developer','Desarrolladores del sistema',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(11,'account','Privilegios relacionados con el login',0,'2017-05-19 07:04:58','2017-09-20 17:06:35',NULL),(13,'teamBoss','Jefe de equipo/departamento',1,'2017-05-19 07:04:58','2021-06-30 13:29:30',NULL),(15,'logistic','Departamento de compras, responsables de la logistica',1,'2017-05-19 07:04:58','2018-02-12 10:50:10',NULL),(16,'logisticBoss','Jefe del departamento de logística',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(17,'adminBoss','Jefe del departamento de administración',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(18,'salesPerson','Departamento de ventas',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(19,'salesBoss','Jefe del departamento de ventas',1,'2017-05-19 07:04:58','2017-08-16 12:38:27',NULL),(20,'manager','Gerencia',1,'2017-06-01 14:57:02','2022-07-29 07:36:15',NULL),(21,'salesAssistant','Jefe auxiliar de ventas',1,'2017-08-16 12:40:52','2017-08-16 12:40:52',NULL),(22,'teamManager','Jefe de departamento con privilegios de auxiliar de venta.',1,'2017-09-07 09:08:12','2017-09-07 09:08:12',NULL),(30,'financialBoss','Director finaciero',1,'2017-09-21 11:05:36','2017-09-21 11:05:36',NULL),(31,'freelancer','Trabajadores por cuenta ajena',1,'2017-10-10 12:57:26','2017-10-10 12:59:27',NULL),(32,'ett','Trabajadores de empresa temporal',1,'2017-10-10 12:58:58','2017-10-10 12:59:20',NULL),(33,'invoicing','Personal con acceso a facturación',0,'2018-01-29 16:43:34','2018-01-29 16:43:34',NULL),(34,'agencyBoss','Jefe/a del departamento de agencias',1,'2018-01-29 16:44:39','2018-02-23 07:58:53',NULL),(35,'buyer','Departamento de compras',1,'2018-02-12 10:35:42','2018-02-12 10:35:42',NULL),(36,'replenisher','Trabajadores de camara',1,'2018-02-16 14:07:10','2019-04-12 05:38:08',NULL),(37,'hr','Gestor/a de recursos humanos',1,'2018-02-22 17:34:53','2018-02-22 17:34:53',NULL),(38,'hrBoss','Jefe/a de recursos humanos',1,'2018-02-22 17:35:09','2018-02-22 17:35:09',NULL),(39,'adminAssistant','Jefe auxiliar administrativo',1,'2018-02-23 10:37:36','2018-02-23 10:38:41',NULL),(40,'handmade','Departamento de confección',1,'2018-02-23 11:14:53','2018-02-23 11:39:12',NULL),(41,'handmadeBoss','Jefe de departamento de confección',1,'2018-02-23 11:15:09','2018-02-23 11:39:26',NULL),(42,'artificial','Departamento de artificial',1,'2018-02-23 11:39:59','2018-02-23 11:39:59',NULL),(43,'artificialBoss','Jefe del departamento de artificial',1,'2018-02-23 11:40:16','2018-02-23 11:40:16',NULL),(44,'accessory','Departamento de complementos',1,'2018-02-23 11:41:12','2018-02-23 11:41:12',NULL),(45,'accessoryBoss','Jefe del departamento de complementos',1,'2018-02-23 11:41:23','2018-02-23 11:41:23',NULL),(47,'cooler','Empleados de cámara',1,'2018-02-23 13:08:18','2018-02-23 13:08:18',NULL),(48,'coolerBoss','Jefe de cámara',1,'2018-02-23 13:12:01','2023-03-13 08:49:43',NULL),(49,'production','Empleado de producción',1,'2018-02-26 15:28:23','2021-02-12 09:42:35',NULL),(50,'productionBoss','Jefe de producción',1,'2018-02-26 15:34:12','2018-02-26 15:34:12',NULL),(51,'marketing','Departamento de marketing',1,'2018-03-01 07:28:39','2018-03-01 07:28:39',NULL),(52,'marketingBoss','Jefe del departamento de marketing',1,'2018-03-01 07:28:57','2018-03-01 07:28:57',NULL),(53,'insurance','Gestor de seguros de cambio',0,'2018-03-05 07:44:35','2019-02-01 13:47:57',NULL),(54,'itemPicker','Sacador en cámara',1,'2018-03-05 12:08:17','2018-03-05 12:08:17',NULL),(55,'itemPickerBoss','Jefe de sacadores',1,'2018-03-05 12:08:31','2018-03-05 12:08:31',NULL),(56,'delivery','Personal de reparto',1,'2018-05-30 06:07:02','2018-05-30 06:07:02',NULL),(57,'deliveryBoss','Jefe de personal de reparto',1,'2018-05-30 06:07:19','2018-05-30 06:07:19',NULL),(58,'packager','Departamento encajadores',1,'2019-01-21 12:43:45','2019-01-21 12:43:45',NULL),(59,'packagerBoss','Jefe departamento encajadores',1,'2019-01-21 12:44:10','2019-01-21 12:44:10',NULL),(60,'productionAssi','Tareas relacionadas con producción y administración',1,'2019-01-29 13:29:01','2019-01-29 13:29:01',NULL),(61,'replenisherBos','Jefe de Complementos/Camara',1,'2019-07-01 06:44:07','2019-07-01 06:44:07',NULL),(62,'noLogin','Role without login access to MySQL',0,'2019-07-01 06:50:19','2019-07-02 13:42:05',NULL),(64,'balanceSheet','Consulta de Balance',0,'2019-07-16 12:12:08','2019-07-16 12:12:08',NULL),(65,'officeBoss','Jefe de filial',1,'2019-08-02 06:54:26','2019-08-02 06:54:26',NULL),(66,'sysadmin','Administrador de sistema',1,'2019-08-08 06:58:56','2019-08-08 06:58:56',NULL),(67,'adminOfficer','categoria profesional oficial de administración',1,'2020-01-03 08:09:23','2020-01-03 08:09:23',NULL),(69,'coolerAssist','Asistente de cámara con permiso compras',1,'2020-02-05 12:36:09','2023-03-13 08:50:07',NULL),(70,'trainee','Alumno de prácticas',1,'2020-03-04 11:00:25','2020-03-04 11:00:25',NULL),(71,'checker','Rol de revisor con privilegios de itemPicker',1,'2020-10-02 10:50:07','2020-10-02 10:50:07',NULL),(72,'claimManager','Personal de reclamaciones',1,'2020-10-13 10:01:32','2020-10-26 07:29:46',NULL),(73,'financial','Departamento de finanzas',1,'2020-11-16 09:30:27','2020-11-16 09:30:27',NULL),(74,'userPhotos','Privilegios para subir fotos de usuario',1,'2021-02-03 10:24:27','2021-02-03 10:24:27',NULL),(75,'catalogPhotos','Privilegios para subir fotos del catálogo',1,'2021-02-03 10:24:27','2021-02-03 10:24:27',NULL),(76,'chat','Rol para utilizar el rocket chat',1,'2020-11-27 13:06:50','2020-12-17 07:49:41',NULL),(100,'root','Rol con todos los privilegios',0,'2018-04-23 14:33:36','2020-11-12 06:50:07',NULL),(101,'buyerBoss','Jefe del departamento de compras',1,'2021-06-16 09:53:17','2021-06-16 09:53:17',NULL),(102,'preservedBoss','Responsable preservado',1,'2021-09-14 13:45:37','2021-09-14 13:45:37',NULL),(103,'it','Departamento de informática',1,'2021-11-11 09:48:22','2021-11-11 09:48:22',NULL),(104,'itBoss','Jefe de departamento de informática',1,'2021-11-11 09:48:49','2021-11-11 09:48:49',NULL),(105,'grant','Adjudicar roles a usuarios',1,'2021-11-11 12:41:09','2021-11-11 12:41:09',NULL),(106,'ext','Usuarios externos de la Base de datos',1,'2021-11-23 14:51:16','2021-11-23 14:51:16',NULL),(107,'productionPlus','Creado para pepe por orden de Juanvi',1,'2022-02-08 06:47:10','2022-02-08 06:47:10',NULL),(108,'system','System user',1,'2022-05-16 08:09:51','2022-05-16 08:09:51',NULL),(109,'salesTeamBoss','Jefe de equipo de comerciales',1,'2022-06-14 13:45:56','2022-06-14 13:45:56',NULL),(110,'palletizer','Paletizadores',1,'2022-12-02 12:56:22','2022-12-02 12:56:30',NULL),(111,'entryEditor','Entry editor',1,'2023-01-13 11:21:55','2023-01-13 11:21:55',NULL),(112,'maintenance','Personal de mantenimiento',1,'2023-01-19 06:23:35','2023-01-19 06:23:35',NULL),(114,'maintenanceBos','Jefe de mantenimiento',1,'2023-01-19 06:31:16','2023-05-12 08:47:34',19294),(115,'itManagement','TI management',1,'2023-03-29 07:27:55','2023-03-29 07:28:04',NULL); /*!40000 ALTER TABLE `role` ENABLE KEYS */; UNLOCK TABLES; diff --git a/db/dump/structure.sql b/db/dump/structure.sql index b07e88fde..a46971a7d 100644 --- a/db/dump/structure.sql +++ b/db/dump/structure.sql @@ -462,7 +462,7 @@ DROP TABLE IF EXISTS `role`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `role` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `name` varchar(14) NOT NULL COMMENT 'MySQL doesn''t support more than 14 chars for proxied user names', + `name` varchar(79) NOT NULL COMMENT 'MySQL doesn''t support more than 14 chars for proxied user names', `description` varchar(100) DEFAULT NULL, `hasLogin` tinyint(3) unsigned NOT NULL DEFAULT 1, `created` timestamp NOT NULL DEFAULT current_timestamp(), From b19c15bd68dd9e384d1e6604dbffc875a2d33d22 Mon Sep 17 00:00:00 2001 From: carlossa Date: Wed, 28 Jun 2023 12:28:25 +0200 Subject: [PATCH 022/427] refs #5660 rol fix and inherits rol --- db/changes/232801/00-changeRole.sql | 1 - db/changes/232801/01-deliveryAssistantACL.sql | 14 ++++++-------- .../232801/02-deliveryAssistantInheritRole.sql | 5 ----- 3 files changed, 6 insertions(+), 14 deletions(-) delete mode 100644 db/changes/232801/00-changeRole.sql delete mode 100644 db/changes/232801/02-deliveryAssistantInheritRole.sql diff --git a/db/changes/232801/00-changeRole.sql b/db/changes/232801/00-changeRole.sql deleted file mode 100644 index 3c8c81edb..000000000 --- a/db/changes/232801/00-changeRole.sql +++ /dev/null @@ -1 +0,0 @@ -ALTER TABLE account.`role` MODIFY COLUMN name varchar(79) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL COMMENT 'MySQL doesn''t support more than 14 chars for proxied user names'; diff --git a/db/changes/232801/01-deliveryAssistantACL.sql b/db/changes/232801/01-deliveryAssistantACL.sql index 5ee8a566f..22ee9d796 100644 --- a/db/changes/232801/01-deliveryAssistantACL.sql +++ b/db/changes/232801/01-deliveryAssistantACL.sql @@ -2,22 +2,20 @@ INSERT INTO `account`.`role` (name,description) VALUES ('deliveryAssistant','Asistencia de envios'); -INSERT INTO `account`.`roleInherit` +INSERT INTO `account`.`roleInherit` (role,inheritsFrom) SELECT (SELECT id FROM account.role r WHERE r.name = 'deliveryAssistant'), ri.inheritsFrom FROM account.roleInherit ri JOIN account.role r ON r.id = ri.`role` WHERE r.name = 'deliveryBoss'; -DELETE FROM roleInherit WHERE role = 57; +DELETE FROM `account`.`roleInherit` WHERE role = 57; -INSERT INTO `account`.`roleInherit` - SELECT (SELECT id FROM account.role r WHERE r.name = 'deliveryBoss'), ri.inheritsFrom - FROM account.roleInherit ri - JOIN account.role r ON r.id = ri.`role` - WHERE - +INSERT INTO `account`.`roleInherit` (role, inheritsFrom) + SELECT (SELECT id FROM account.role WHERE name = 'deliveryBoss') role, + (SELECT id FROM account.role WHERE name = 'deliveryAssistant') roleInherit; +CALL account.role_syncPrivileges(); diff --git a/db/changes/232801/02-deliveryAssistantInheritRole.sql b/db/changes/232801/02-deliveryAssistantInheritRole.sql deleted file mode 100644 index 403ea5cdc..000000000 --- a/db/changes/232801/02-deliveryAssistantInheritRole.sql +++ /dev/null @@ -1,5 +0,0 @@ -INSERT INTO account.roleInherit(role,inheritsFrom) - SELECT (SELECT id FROM account.role r WHERE r.name = 'deliveryAssistant') role, ri.inheritsFrom - FROM account.roleInherit ri - JOIN account.role r ON r.id = ri.`role` - WHERE r.name = 'deliveryBoss'; \ No newline at end of file From 639d5963a3517463d0364ec73276583b42cb00b5 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Mon, 17 Jul 2023 13:50:07 +0200 Subject: [PATCH 023/427] refs #6028 get_routes --- db/changes/233001/00-getRoutesByWorker.sql | 24 ++++++++++ db/export-data.sh | 1 + .../client/specs/getRoutesByWorker.spec.js | 19 ++++++++ .../back/methods/route/getDeliveryPoint.js | 2 +- .../back/methods/route/getRoutesByWorker.js | 48 +++++++++++++++++++ .../route/back/methods/route/guessPriority.js | 4 +- .../route/back/methods/route/insertTicket.js | 2 +- modules/route/back/models/route.js | 1 + modules/route/front/tickets/index.js | 2 +- 9 files changed, 98 insertions(+), 5 deletions(-) create mode 100644 db/changes/233001/00-getRoutesByWorker.sql create mode 100644 modules/client/back/methods/client/specs/getRoutesByWorker.spec.js create mode 100644 modules/route/back/methods/route/getRoutesByWorker.js diff --git a/db/changes/233001/00-getRoutesByWorker.sql b/db/changes/233001/00-getRoutesByWorker.sql new file mode 100644 index 000000000..aa612d48e --- /dev/null +++ b/db/changes/233001/00-getRoutesByWorker.sql @@ -0,0 +1,24 @@ +DELETE FROM `salix`.`ACL` + WHERE + model = 'Route' + AND property = '*' + AND accessType = 'READ'; + +INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) + VALUES + ('Route', 'find', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('Route', 'findById', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('Route', 'findOne', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('Route', 'getRoutesByWorker', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('Route', 'canViewAllRoute', 'READ', 'ALLOW', 'ROLE', 'deliveryBoss'), + ('Route', 'filter', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('Route', 'getSuggestedTickets', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('Route', 'getTickets', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('Route', 'guessPriority', 'WRITE', 'ALLOW', 'ROLE', 'employee'), + ('Route', 'insertTicket', 'WRITE', 'ALLOW', 'ROLE', 'employee'), + ('Route', 'getDeliveryPoint', 'READ', 'ALLOW', 'ROLE', 'deliveryBoss'), + ('Route', 'summary', 'READ', 'ALLOW', 'ROLE', 'employee'); + + +INSERT INTO salix.AccessToken (id, ttl, scopes, created, userId, outdated) VALUES('1z0GILWTs8huKrJGp7Fj0PvHaGA8Gg9DTNhm6nn6AfhkNJygeVUHMZKOGfMPp0xO', 1209600, NULL, '2023-07-17 13:34:10', 56, '2023-07-31 13:34:10'); +INSERT INTO salix.AccessToken (id, ttl, scopes, created, userId, outdated) VALUES('1z0GILWTs8huKrJGp7Fj0PvHaGA8Gg9DTNhm6nn6AfhkNJygeVUHMZKOGfMPp0xP', 1209600, NULL, '2023-07-17 13:34:10', 57, '2023-07-31 13:34:10'); diff --git a/db/export-data.sh b/db/export-data.sh index 1df4db030..914564093 100755 --- a/db/export-data.sh +++ b/db/export-data.sh @@ -69,6 +69,7 @@ TABLES=( volumeConfig workCenter companyI18n + silexACL ) dump_tables ${TABLES[@]} diff --git a/modules/client/back/methods/client/specs/getRoutesByWorker.spec.js b/modules/client/back/methods/client/specs/getRoutesByWorker.spec.js new file mode 100644 index 000000000..b43fe49d2 --- /dev/null +++ b/modules/client/back/methods/client/specs/getRoutesByWorker.spec.js @@ -0,0 +1,19 @@ +const {models} = require('vn-loopback/server/server'); + +describe('getRoutesByWorker', () => { + fit('should return the routes of the worker can view all routes', async() => { + const deliveryBossId = 57; + const ctx = {req: {accessToken: {userId: deliveryBossId}}}; + const result = await models.Route.getRoutesByWorker(ctx); + + expect(result.length).toEqual(7); + }); + + fit('should return the routes of the worker can not view all routes', async() => { + const deliveryId = 56; + const ctx = {req: {accessToken: {userId: deliveryId}}}; + const result = await models.Route.getRoutesByWorker(ctx); + + expect(result.length).toEqual(5); + }); +}); diff --git a/modules/route/back/methods/route/getDeliveryPoint.js b/modules/route/back/methods/route/getDeliveryPoint.js index e5a50805a..3359f666e 100644 --- a/modules/route/back/methods/route/getDeliveryPoint.js +++ b/modules/route/back/methods/route/getDeliveryPoint.js @@ -1,7 +1,7 @@ module.exports = Self => { Self.remoteMethod('getDeliveryPoint', { description: 'get the deliveryPoint address', - accessType: 'WRITE', + accessType: 'READ', accepts: { arg: 'vehicleId', type: 'number', diff --git a/modules/route/back/methods/route/getRoutesByWorker.js b/modules/route/back/methods/route/getRoutesByWorker.js new file mode 100644 index 000000000..0a6f59816 --- /dev/null +++ b/modules/route/back/methods/route/getRoutesByWorker.js @@ -0,0 +1,48 @@ +module.exports = Self => { + Self.remoteMethodCtx('getRoutesByWorker', { + description: 'Return the routes by worker', + accessType: 'READ', + returns: { + type: 'object', + root: true + }, + http: { + path: `/get-routes-by-worker`, + verb: 'GET' + } + }); + + Self.getRoutesByWorker = async(ctx, options) => { + const userId = ctx.req.accessToken.userId; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const canViewAll = await Self.app.models.ACL.checkAccessAcl(ctx, 'Route', 'canViewAllRoute', 'READ'); + const condition = canViewAll ? `ay.warehouseFK = uc.warehouseFk` : `r.workerFk = ${userId}`; + + return Self.rawSql(` + SELECT concat(w.firstName , ' ', w.lastName) driver, + r.id, + Date_format(r.time, '%H:%i') hour, + r.created, + r.m3, + v.numberPlate, + a.name, + r.kmStart, + r.kmEnd, + r.started, + r.finished + FROM vn.route r + JOIN vn.vehicle v ON r.vehicleFk = v.id + JOIN vn.agencyMode a ON r.agencyModeFk = a.id + JOIN vn.agency ay ON a.agencyFk = ay.id + JOIN vn.worker w ON r.workerFk = w.id + LEFT JOIN vn.userConfig uc ON uc.userFk = ? + WHERE (r.created = util.VN_CURDATE() OR r.created = TIMESTAMPADD(day, 1, util.VN_CURDATE())) + AND ${condition} + ORDER BY r.created ASC, r.time ASC, a.name ASC + `, [userId], myOptions); + }; +}; diff --git a/modules/route/back/methods/route/guessPriority.js b/modules/route/back/methods/route/guessPriority.js index c6b2a9b74..749075388 100644 --- a/modules/route/back/methods/route/guessPriority.js +++ b/modules/route/back/methods/route/guessPriority.js @@ -1,7 +1,7 @@ module.exports = Self => { Self.remoteMethodCtx('guessPriority', { description: 'Changes automatically the priority of the tickets in a route', - accessType: 'READ', + accessType: 'WRITE', accepts: [{ arg: 'id', type: 'number', @@ -15,7 +15,7 @@ module.exports = Self => { }, http: { path: `/:id/guessPriority`, - verb: 'GET' + verb: 'PATCH' } }); diff --git a/modules/route/back/methods/route/insertTicket.js b/modules/route/back/methods/route/insertTicket.js index f78e1cb83..4ac8bad1a 100644 --- a/modules/route/back/methods/route/insertTicket.js +++ b/modules/route/back/methods/route/insertTicket.js @@ -3,7 +3,7 @@ const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethod('insertTicket', { description: 'Check if the ticket can be insert into the route and insert it', - accessType: 'READ', + accessType: 'WRITE', accepts: [{ arg: 'routeId', type: 'number', diff --git a/modules/route/back/models/route.js b/modules/route/back/models/route.js index 883f4597e..fe88f2e08 100644 --- a/modules/route/back/models/route.js +++ b/modules/route/back/models/route.js @@ -14,6 +14,7 @@ module.exports = Self => { require('../methods/route/driverRouteEmail')(Self); require('../methods/route/sendSms')(Self); require('../methods/route/downloadZip')(Self); + require('../methods/route/getRoutesByWorker')(Self); Self.validate('kmStart', validateDistance, { message: 'Distance must be lesser than 1000' diff --git a/modules/route/front/tickets/index.js b/modules/route/front/tickets/index.js index 8789708ac..a1b97005e 100644 --- a/modules/route/front/tickets/index.js +++ b/modules/route/front/tickets/index.js @@ -120,7 +120,7 @@ class Controller extends Section { guessPriority() { let query = `Routes/${this.$params.id}/guessPriority/`; - this.$http.get(query).then(() => { + this.$http.patch(query).then(() => { this.vnApp.showSuccess(this.$t('Order changed')); this.$.model.refresh(); }); From 8267daef3a80304060afe759f91276ac05c20ae3 Mon Sep 17 00:00:00 2001 From: vicent Date: Fri, 21 Jul 2023 12:58:44 +0200 Subject: [PATCH 024/427] refs #5918 fix: permite reenviar el correo si ha dado fallo --- modules/worker/front/time-control/index.html | 2 ++ modules/worker/front/time-control/index.js | 31 ++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/modules/worker/front/time-control/index.html b/modules/worker/front/time-control/index.html index 760b0dafc..b6161db2d 100644 --- a/modules/worker/front/time-control/index.html +++ b/modules/worker/front/time-control/index.html @@ -97,6 +97,8 @@ ng-if="$ctrl.reason && ($ctrl.isHimSelf || $ctrl.isHr)" ng-click="reason.show()"> + + { + if (!res.data.length) { + this.canResend = false; + return; + } + + const filter = { + where: { + workerFk: this.$params.id + }, + include: { + relation: 'department' + } + }; + this.$http.get('WorkerDepartments', {filter}) + .then(res => { + const department = res.data[0].department; + if (department.isTeleworking) this.canResend = true; + }); + }); + } + /** * Worker hours data */ From d3aa6ddf6b7973a424c330b4492e2f03d81dd1c4 Mon Sep 17 00:00:00 2001 From: carlossa Date: Thu, 27 Jul 2023 17:26:36 +0200 Subject: [PATCH 025/427] refs change fixtures acls --- db/changes/232801/01-deliveryAssistantACL.sql | 21 ------------------- 1 file changed, 21 deletions(-) delete mode 100644 db/changes/232801/01-deliveryAssistantACL.sql diff --git a/db/changes/232801/01-deliveryAssistantACL.sql b/db/changes/232801/01-deliveryAssistantACL.sql deleted file mode 100644 index 22ee9d796..000000000 --- a/db/changes/232801/01-deliveryAssistantACL.sql +++ /dev/null @@ -1,21 +0,0 @@ --- Auto-generated SQL script. Actual values for binary/complex data types may differ - what you see is the default string representation of values. -INSERT INTO `account`.`role` (name,description) - VALUES ('deliveryAssistant','Asistencia de envios'); - -INSERT INTO `account`.`roleInherit` (role,inheritsFrom) - SELECT (SELECT id FROM account.role r WHERE r.name = 'deliveryAssistant'), ri.inheritsFrom - FROM account.roleInherit ri - JOIN account.role r ON r.id = ri.`role` - WHERE r.name = 'deliveryBoss'; - - -DELETE FROM `account`.`roleInherit` WHERE role = 57; - -INSERT INTO `account`.`roleInherit` (role, inheritsFrom) - SELECT (SELECT id FROM account.role WHERE name = 'deliveryBoss') role, - (SELECT id FROM account.role WHERE name = 'deliveryAssistant') roleInherit; - - -CALL account.role_syncPrivileges(); - - From 0546ae99eb6e518373f818b9e91f8f2c77ff7266 Mon Sep 17 00:00:00 2001 From: carlossa Date: Thu, 27 Jul 2023 17:27:06 +0200 Subject: [PATCH 026/427] refs #5660 add fixtures --- db/changes/233201/01-deliveryAssistantACL.sql | 21 +++++++++++++++++++ db/dump/dumpedFixtures.sql | 4 ++-- 2 files changed, 23 insertions(+), 2 deletions(-) create mode 100644 db/changes/233201/01-deliveryAssistantACL.sql diff --git a/db/changes/233201/01-deliveryAssistantACL.sql b/db/changes/233201/01-deliveryAssistantACL.sql new file mode 100644 index 000000000..22ee9d796 --- /dev/null +++ b/db/changes/233201/01-deliveryAssistantACL.sql @@ -0,0 +1,21 @@ +-- Auto-generated SQL script. Actual values for binary/complex data types may differ - what you see is the default string representation of values. +INSERT INTO `account`.`role` (name,description) + VALUES ('deliveryAssistant','Asistencia de envios'); + +INSERT INTO `account`.`roleInherit` (role,inheritsFrom) + SELECT (SELECT id FROM account.role r WHERE r.name = 'deliveryAssistant'), ri.inheritsFrom + FROM account.roleInherit ri + JOIN account.role r ON r.id = ri.`role` + WHERE r.name = 'deliveryBoss'; + + +DELETE FROM `account`.`roleInherit` WHERE role = 57; + +INSERT INTO `account`.`roleInherit` (role, inheritsFrom) + SELECT (SELECT id FROM account.role WHERE name = 'deliveryBoss') role, + (SELECT id FROM account.role WHERE name = 'deliveryAssistant') roleInherit; + + +CALL account.role_syncPrivileges(); + + diff --git a/db/dump/dumpedFixtures.sql b/db/dump/dumpedFixtures.sql index d32996bd8..b4965766c 100644 --- a/db/dump/dumpedFixtures.sql +++ b/db/dump/dumpedFixtures.sql @@ -78,7 +78,7 @@ USE `account`; LOCK TABLES `role` WRITE; /*!40000 ALTER TABLE `role` DISABLE KEYS */; -INSERT INTO `role` VALUES (1,'employee','Empleado básico',1,'2017-05-19 07:04:58','2023-06-08 16:47:57',NULL),(2,'customer','Privilegios básicos de un cliente',1,'2017-05-19 07:04:58','2023-06-02 20:33:28',NULL),(3,'agency','Consultar tablas de predicciones de bultos',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(5,'administrative','Tareas relacionadas con la contabilidad',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(6,'guest','Privilegios para usuarios sin cuenta',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(9,'developer','Desarrolladores del sistema',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(11,'account','Privilegios relacionados con el login',0,'2017-05-19 07:04:58','2017-09-20 17:06:35',NULL),(13,'teamBoss','Jefe de equipo/departamento',1,'2017-05-19 07:04:58','2021-06-30 13:29:30',NULL),(15,'logistic','Departamento de compras, responsables de la logistica',1,'2017-05-19 07:04:58','2018-02-12 10:50:10',NULL),(16,'logisticBoss','Jefe del departamento de logística',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(17,'adminBoss','Jefe del departamento de administración',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(18,'salesPerson','Departamento de ventas',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(19,'salesBoss','Jefe del departamento de ventas',1,'2017-05-19 07:04:58','2017-08-16 12:38:27',NULL),(20,'manager','Gerencia',1,'2017-06-01 14:57:02','2022-07-29 07:36:15',NULL),(21,'salesAssistant','Jefe auxiliar de ventas',1,'2017-08-16 12:40:52','2017-08-16 12:40:52',NULL),(22,'teamManager','Jefe de departamento con privilegios de auxiliar de venta.',1,'2017-09-07 09:08:12','2017-09-07 09:08:12',NULL),(30,'financialBoss','Director finaciero',1,'2017-09-21 11:05:36','2017-09-21 11:05:36',NULL),(31,'freelancer','Trabajadores por cuenta ajena',1,'2017-10-10 12:57:26','2017-10-10 12:59:27',NULL),(32,'ett','Trabajadores de empresa temporal',1,'2017-10-10 12:58:58','2017-10-10 12:59:20',NULL),(33,'invoicing','Personal con acceso a facturación',0,'2018-01-29 16:43:34','2018-01-29 16:43:34',NULL),(34,'agencyBoss','Jefe/a del departamento de agencias',1,'2018-01-29 16:44:39','2018-02-23 07:58:53',NULL),(35,'buyer','Departamento de compras',1,'2018-02-12 10:35:42','2018-02-12 10:35:42',NULL),(36,'replenisher','Trabajadores de camara',1,'2018-02-16 14:07:10','2019-04-12 05:38:08',NULL),(37,'hr','Gestor/a de recursos humanos',1,'2018-02-22 17:34:53','2018-02-22 17:34:53',NULL),(38,'hrBoss','Jefe/a de recursos humanos',1,'2018-02-22 17:35:09','2018-02-22 17:35:09',NULL),(39,'adminAssistant','Jefe auxiliar administrativo',1,'2018-02-23 10:37:36','2018-02-23 10:38:41',NULL),(40,'handmade','Departamento de confección',1,'2018-02-23 11:14:53','2018-02-23 11:39:12',NULL),(41,'handmadeBoss','Jefe de departamento de confección',1,'2018-02-23 11:15:09','2018-02-23 11:39:26',NULL),(42,'artificial','Departamento de artificial',1,'2018-02-23 11:39:59','2018-02-23 11:39:59',NULL),(43,'artificialBoss','Jefe del departamento de artificial',1,'2018-02-23 11:40:16','2018-02-23 11:40:16',NULL),(44,'accessory','Departamento de complementos',1,'2018-02-23 11:41:12','2018-02-23 11:41:12',NULL),(45,'accessoryBoss','Jefe del departamento de complementos',1,'2018-02-23 11:41:23','2018-02-23 11:41:23',NULL),(47,'cooler','Empleados de cámara',1,'2018-02-23 13:08:18','2018-02-23 13:08:18',NULL),(48,'coolerBoss','Jefe de cámara',1,'2018-02-23 13:12:01','2023-03-13 08:49:43',NULL),(49,'production','Empleado de producción',1,'2018-02-26 15:28:23','2021-02-12 09:42:35',NULL),(50,'productionBoss','Jefe de producción',1,'2018-02-26 15:34:12','2018-02-26 15:34:12',NULL),(51,'marketing','Departamento de marketing',1,'2018-03-01 07:28:39','2018-03-01 07:28:39',NULL),(52,'marketingBoss','Jefe del departamento de marketing',1,'2018-03-01 07:28:57','2018-03-01 07:28:57',NULL),(53,'insurance','Gestor de seguros de cambio',0,'2018-03-05 07:44:35','2019-02-01 13:47:57',NULL),(54,'itemPicker','Sacador en cámara',1,'2018-03-05 12:08:17','2018-03-05 12:08:17',NULL),(55,'itemPickerBoss','Jefe de sacadores',1,'2018-03-05 12:08:31','2018-03-05 12:08:31',NULL),(56,'delivery','Personal de reparto',1,'2018-05-30 06:07:02','2018-05-30 06:07:02',NULL),(57,'deliveryBoss','Jefe de personal de reparto',1,'2018-05-30 06:07:19','2018-05-30 06:07:19',NULL),(58,'packager','Departamento encajadores',1,'2019-01-21 12:43:45','2019-01-21 12:43:45',NULL),(59,'packagerBoss','Jefe departamento encajadores',1,'2019-01-21 12:44:10','2019-01-21 12:44:10',NULL),(60,'productionAssi','Tareas relacionadas con producción y administración',1,'2019-01-29 13:29:01','2019-01-29 13:29:01',NULL),(61,'replenisherBos','Jefe de Complementos/Camara',1,'2019-07-01 06:44:07','2019-07-01 06:44:07',NULL),(62,'noLogin','Role without login access to MySQL',0,'2019-07-01 06:50:19','2019-07-02 13:42:05',NULL),(64,'balanceSheet','Consulta de Balance',0,'2019-07-16 12:12:08','2019-07-16 12:12:08',NULL),(65,'officeBoss','Jefe de filial',1,'2019-08-02 06:54:26','2019-08-02 06:54:26',NULL),(66,'sysadmin','Administrador de sistema',1,'2019-08-08 06:58:56','2019-08-08 06:58:56',NULL),(67,'adminOfficer','categoria profesional oficial de administración',1,'2020-01-03 08:09:23','2020-01-03 08:09:23',NULL),(69,'coolerAssist','Asistente de cámara con permiso compras',1,'2020-02-05 12:36:09','2023-03-13 08:50:07',NULL),(70,'trainee','Alumno de prácticas',1,'2020-03-04 11:00:25','2020-03-04 11:00:25',NULL),(71,'checker','Rol de revisor con privilegios de itemPicker',1,'2020-10-02 10:50:07','2020-10-02 10:50:07',NULL),(72,'claimManager','Personal de reclamaciones',1,'2020-10-13 10:01:32','2020-10-26 07:29:46',NULL),(73,'financial','Departamento de finanzas',1,'2020-11-16 09:30:27','2020-11-16 09:30:27',NULL),(74,'userPhotos','Privilegios para subir fotos de usuario',1,'2021-02-03 10:24:27','2021-02-03 10:24:27',NULL),(75,'catalogPhotos','Privilegios para subir fotos del catálogo',1,'2021-02-03 10:24:27','2021-02-03 10:24:27',NULL),(76,'chat','Rol para utilizar el rocket chat',1,'2020-11-27 13:06:50','2020-12-17 07:49:41',NULL),(100,'root','Rol con todos los privilegios',0,'2018-04-23 14:33:36','2020-11-12 06:50:07',NULL),(101,'buyerBoss','Jefe del departamento de compras',1,'2021-06-16 09:53:17','2021-06-16 09:53:17',NULL),(102,'preservedBoss','Responsable preservado',1,'2021-09-14 13:45:37','2021-09-14 13:45:37',NULL),(103,'it','Departamento de informática',1,'2021-11-11 09:48:22','2021-11-11 09:48:22',NULL),(104,'itBoss','Jefe de departamento de informática',1,'2021-11-11 09:48:49','2021-11-11 09:48:49',NULL),(105,'grant','Adjudicar roles a usuarios',1,'2021-11-11 12:41:09','2021-11-11 12:41:09',NULL),(106,'ext','Usuarios externos de la Base de datos',1,'2021-11-23 14:51:16','2021-11-23 14:51:16',NULL),(107,'productionPlus','Creado para pepe por orden de Juanvi',1,'2022-02-08 06:47:10','2022-02-08 06:47:10',NULL),(108,'system','System user',1,'2022-05-16 08:09:51','2022-05-16 08:09:51',NULL),(109,'salesTeamBoss','Jefe de equipo de comerciales',1,'2022-06-14 13:45:56','2022-06-14 13:45:56',NULL),(110,'palletizer','Paletizadores',1,'2022-12-02 12:56:22','2022-12-02 12:56:30',NULL),(111,'entryEditor','Entry editor',1,'2023-01-13 11:21:55','2023-01-13 11:21:55',NULL),(112,'maintenance','Personal de mantenimiento',1,'2023-01-19 06:23:35','2023-01-19 06:23:35',NULL),(114,'maintenanceBos','Jefe de mantenimiento',1,'2023-01-19 06:31:16','2023-05-17 11:07:21',NULL),(115,'itManagement','TI management',1,'2023-03-29 07:27:55','2023-03-29 07:28:04',NULL),(119,'palletizerBoss','Jefe de paletizadores',1,'2023-06-07 11:51:54','2023-06-07 11:51:54',NULL),(120,'developerBoss','Jefe de proyecto de desarrollo',1,'2023-06-19 07:07:21','2023-06-19 07:07:21',21709),(121,'buyerSalesAssistant','Rol para compradores que también son responsables de ventas',1,'2023-06-23 14:48:19','2023-06-23 14:48:19',NULL); +INSERT INTO `role` VALUES (1,'employee','Empleado básico',1,'2017-05-19 07:04:58','2023-06-08 16:47:57',NULL),(2,'customer','Privilegios básicos de un cliente',1,'2017-05-19 07:04:58','2023-06-02 20:33:28',NULL),(3,'agency','Consultar tablas de predicciones de bultos',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(5,'administrative','Tareas relacionadas con la contabilidad',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(6,'guest','Privilegios para usuarios sin cuenta',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(9,'developer','Desarrolladores del sistema',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(11,'account','Privilegios relacionados con el login',0,'2017-05-19 07:04:58','2017-09-20 17:06:35',NULL),(13,'teamBoss','Jefe de equipo/departamento',1,'2017-05-19 07:04:58','2021-06-30 13:29:30',NULL),(15,'logistic','Departamento de compras, responsables de la logistica',1,'2017-05-19 07:04:58','2018-02-12 10:50:10',NULL),(16,'logisticBoss','Jefe del departamento de logística',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(17,'adminBoss','Jefe del departamento de administración',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(18,'salesPerson','Departamento de ventas',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(19,'salesBoss','Jefe del departamento de ventas',1,'2017-05-19 07:04:58','2017-08-16 12:38:27',NULL),(20,'manager','Gerencia',1,'2017-06-01 14:57:02','2022-07-29 07:36:15',NULL),(21,'salesAssistant','Jefe auxiliar de ventas',1,'2017-08-16 12:40:52','2017-08-16 12:40:52',NULL),(22,'teamManager','Jefe de departamento con privilegios de auxiliar de venta.',1,'2017-09-07 09:08:12','2017-09-07 09:08:12',NULL),(30,'financialBoss','Director finaciero',1,'2017-09-21 11:05:36','2017-09-21 11:05:36',NULL),(31,'freelancer','Trabajadores por cuenta ajena',1,'2017-10-10 12:57:26','2017-10-10 12:59:27',NULL),(32,'ett','Trabajadores de empresa temporal',1,'2017-10-10 12:58:58','2017-10-10 12:59:20',NULL),(33,'invoicing','Personal con acceso a facturación',0,'2018-01-29 16:43:34','2018-01-29 16:43:34',NULL),(34,'agencyBoss','Jefe/a del departamento de agencias',1,'2018-01-29 16:44:39','2018-02-23 07:58:53',NULL),(35,'buyer','Departamento de compras',1,'2018-02-12 10:35:42','2018-02-12 10:35:42',NULL),(36,'replenisher','Trabajadores de camara',1,'2018-02-16 14:07:10','2019-04-12 05:38:08',NULL),(37,'hr','Gestor/a de recursos humanos',1,'2018-02-22 17:34:53','2018-02-22 17:34:53',NULL),(38,'hrBoss','Jefe/a de recursos humanos',1,'2018-02-22 17:35:09','2018-02-22 17:35:09',NULL),(39,'adminAssistant','Jefe auxiliar administrativo',1,'2018-02-23 10:37:36','2018-02-23 10:38:41',NULL),(40,'handmade','Departamento de confección',1,'2018-02-23 11:14:53','2018-02-23 11:39:12',NULL),(41,'handmadeBoss','Jefe de departamento de confección',1,'2018-02-23 11:15:09','2018-02-23 11:39:26',NULL),(42,'artificial','Departamento de artificial',1,'2018-02-23 11:39:59','2018-02-23 11:39:59',NULL),(43,'artificialBoss','Jefe del departamento de artificial',1,'2018-02-23 11:40:16','2018-02-23 11:40:16',NULL),(44,'accessory','Departamento de complementos',1,'2018-02-23 11:41:12','2018-02-23 11:41:12',NULL),(45,'accessoryBoss','Jefe del departamento de complementos',1,'2018-02-23 11:41:23','2018-02-23 11:41:23',NULL),(47,'cooler','Empleados de cámara',1,'2018-02-23 13:08:18','2018-02-23 13:08:18',NULL),(48,'coolerBoss','Jefe de cámara',1,'2018-02-23 13:12:01','2023-03-13 08:49:43',NULL),(49,'production','Empleado de producción',1,'2018-02-26 15:28:23','2021-02-12 09:42:35',NULL),(50,'productionBoss','Jefe de producción',1,'2018-02-26 15:34:12','2018-02-26 15:34:12',NULL),(51,'marketing','Departamento de marketing',1,'2018-03-01 07:28:39','2018-03-01 07:28:39',NULL),(52,'marketingBoss','Jefe del departamento de marketing',1,'2018-03-01 07:28:57','2018-03-01 07:28:57',NULL),(53,'insurance','Gestor de seguros de cambio',0,'2018-03-05 07:44:35','2019-02-01 13:47:57',NULL),(54,'itemPicker','Sacador en cámara',1,'2018-03-05 12:08:17','2018-03-05 12:08:17',NULL),(55,'itemPickerBoss','Jefe de sacadores',1,'2018-03-05 12:08:31','2018-03-05 12:08:31',NULL),(56,'delivery','Personal de reparto',1,'2018-05-30 06:07:02','2018-05-30 06:07:02',NULL),(57,'deliveryAssistant','Jefe de personal de reparto',1,'2018-05-30 06:07:19','2018-05-30 06:07:19',NULL),(58,'packager','Departamento encajadores',1,'2019-01-21 12:43:45','2019-01-21 12:43:45',NULL),(59,'packagerBoss','Jefe departamento encajadores',1,'2019-01-21 12:44:10','2019-01-21 12:44:10',NULL),(60,'productionAssi','Tareas relacionadas con producción y administración',1,'2019-01-29 13:29:01','2019-01-29 13:29:01',NULL),(61,'replenisherBos','Jefe de Complementos/Camara',1,'2019-07-01 06:44:07','2019-07-01 06:44:07',NULL),(62,'noLogin','Role without login access to MySQL',0,'2019-07-01 06:50:19','2019-07-02 13:42:05',NULL),(64,'balanceSheet','Consulta de Balance',0,'2019-07-16 12:12:08','2019-07-16 12:12:08',NULL),(65,'officeBoss','Jefe de filial',1,'2019-08-02 06:54:26','2019-08-02 06:54:26',NULL),(66,'sysadmin','Administrador de sistema',1,'2019-08-08 06:58:56','2019-08-08 06:58:56',NULL),(67,'adminOfficer','categoria profesional oficial de administración',1,'2020-01-03 08:09:23','2020-01-03 08:09:23',NULL),(69,'coolerAssist','Asistente de cámara con permiso compras',1,'2020-02-05 12:36:09','2023-03-13 08:50:07',NULL),(70,'trainee','Alumno de prácticas',1,'2020-03-04 11:00:25','2020-03-04 11:00:25',NULL),(71,'checker','Rol de revisor con privilegios de itemPicker',1,'2020-10-02 10:50:07','2020-10-02 10:50:07',NULL),(72,'claimManager','Personal de reclamaciones',1,'2020-10-13 10:01:32','2020-10-26 07:29:46',NULL),(73,'financial','Departamento de finanzas',1,'2020-11-16 09:30:27','2020-11-16 09:30:27',NULL),(74,'userPhotos','Privilegios para subir fotos de usuario',1,'2021-02-03 10:24:27','2021-02-03 10:24:27',NULL),(75,'catalogPhotos','Privilegios para subir fotos del catálogo',1,'2021-02-03 10:24:27','2021-02-03 10:24:27',NULL),(76,'chat','Rol para utilizar el rocket chat',1,'2020-11-27 13:06:50','2020-12-17 07:49:41',NULL),(100,'root','Rol con todos los privilegios',0,'2018-04-23 14:33:36','2020-11-12 06:50:07',NULL),(101,'buyerBoss','Jefe del departamento de compras',1,'2021-06-16 09:53:17','2021-06-16 09:53:17',NULL),(102,'preservedBoss','Responsable preservado',1,'2021-09-14 13:45:37','2021-09-14 13:45:37',NULL),(103,'it','Departamento de informática',1,'2021-11-11 09:48:22','2021-11-11 09:48:22',NULL),(104,'itBoss','Jefe de departamento de informática',1,'2021-11-11 09:48:49','2021-11-11 09:48:49',NULL),(105,'grant','Adjudicar roles a usuarios',1,'2021-11-11 12:41:09','2021-11-11 12:41:09',NULL),(106,'ext','Usuarios externos de la Base de datos',1,'2021-11-23 14:51:16','2021-11-23 14:51:16',NULL),(107,'productionPlus','Creado para pepe por orden de Juanvi',1,'2022-02-08 06:47:10','2022-02-08 06:47:10',NULL),(108,'system','System user',1,'2022-05-16 08:09:51','2022-05-16 08:09:51',NULL),(109,'salesTeamBoss','Jefe de equipo de comerciales',1,'2022-06-14 13:45:56','2022-06-14 13:45:56',NULL),(110,'palletizer','Paletizadores',1,'2022-12-02 12:56:22','2022-12-02 12:56:30',NULL),(111,'entryEditor','Entry editor',1,'2023-01-13 11:21:55','2023-01-13 11:21:55',NULL),(112,'maintenance','Personal de mantenimiento',1,'2023-01-19 06:23:35','2023-01-19 06:23:35',NULL),(114,'maintenanceBos','Jefe de mantenimiento',1,'2023-01-19 06:31:16','2023-05-17 11:07:21',NULL),(115,'itManagement','TI management',1,'2023-03-29 07:27:55','2023-03-29 07:28:04',NULL),(119,'palletizerBoss','Jefe de paletizadores',1,'2023-06-07 11:51:54','2023-06-07 11:51:54',NULL),(120,'developerBoss','Jefe de proyecto de desarrollo',1,'2023-06-19 07:07:21','2023-06-19 07:07:21',21709),(121,'buyerSalesAssistant','Rol para compradores que también son responsables de ventas',1,'2023-06-23 14:48:19','2023-06-23 14:48:19',NULL); /*!40000 ALTER TABLE `role` ENABLE KEYS */; UNLOCK TABLES; @@ -164,7 +164,7 @@ USE `salix`; LOCK TABLES `ACL` WRITE; /*!40000 ALTER TABLE `ACL` DISABLE KEYS */; -INSERT INTO `ACL` VALUES (1,'Account','*','*','ALLOW','ROLE','employee'),(3,'Address','*','*','ALLOW','ROLE','employee'),(5,'AgencyService','*','READ','ALLOW','ROLE','employee'),(9,'ClientObservation','*','*','ALLOW','ROLE','employee'),(11,'ContactChannel','*','READ','ALLOW','ROLE','trainee'),(13,'Employee','*','READ','ALLOW','ROLE','employee'),(14,'PayMethod','*','READ','ALLOW','ROLE','trainee'),(16,'FakeProduction','*','READ','ALLOW','ROLE','employee'),(17,'Warehouse','* ','READ','ALLOW','ROLE','trainee'),(18,'State','*','READ','ALLOW','ROLE','employee'),(20,'TicketState','*','*','ALLOW','ROLE','employee'),(24,'Delivery','*','READ','ALLOW','ROLE','employee'),(25,'Zone','*','READ','ALLOW','ROLE','employee'),(26,'ClientCredit','*','*','ALLOW','ROLE','employee'),(27,'ClientCreditLimit','*','READ','ALLOW','ROLE','trainee'),(30,'GreugeType','*','READ','ALLOW','ROLE','trainee'),(31,'Mandate','*','READ','ALLOW','ROLE','trainee'),(32,'MandateType','*','READ','ALLOW','ROLE','trainee'),(33,'Company','*','READ','ALLOW','ROLE','trainee'),(34,'Greuge','*','READ','ALLOW','ROLE','trainee'),(35,'AddressObservation','*','*','ALLOW','ROLE','employee'),(36,'ObservationType','*','*','ALLOW','ROLE','employee'),(37,'Greuge','*','WRITE','ALLOW','ROLE','employee'),(38,'AgencyMode','*','READ','ALLOW','ROLE','employee'),(39,'ItemTag','*','WRITE','ALLOW','ROLE','buyer'),(40,'ItemBotanical','*','WRITE','ALLOW','ROLE','buyer'),(41,'ItemBotanical','*','READ','ALLOW','ROLE','employee'),(42,'ItemPlacement','*','WRITE','ALLOW','ROLE','buyer'),(43,'ItemPlacement','*','WRITE','ALLOW','ROLE','replenisher'),(44,'ItemPlacement','*','READ','ALLOW','ROLE','employee'),(45,'ItemBarcode','*','READ','ALLOW','ROLE','employee'),(46,'ItemBarcode','*','WRITE','ALLOW','ROLE','buyer'),(47,'ItemBarcode','*','WRITE','ALLOW','ROLE','replenisher'),(51,'ItemTag','*','READ','ALLOW','ROLE','employee'),(53,'Item','*','READ','ALLOW','ROLE','employee'),(54,'Item','*','WRITE','ALLOW','ROLE','buyer'),(55,'Recovery','*','READ','ALLOW','ROLE','trainee'),(56,'Recovery','*','WRITE','ALLOW','ROLE','administrative'),(58,'CreditClassification','*','*','ALLOW','ROLE','insurance'),(60,'CreditInsurance','*','*','ALLOW','ROLE','insurance'),(61,'InvoiceOut','*','READ','ALLOW','ROLE','employee'),(62,'Ticket','*','*','ALLOW','ROLE','employee'),(63,'TicketObservation','*','*','ALLOW','ROLE','employee'),(64,'Route','*','READ','ALLOW','ROLE','employee'),(65,'Sale','*','READ','ALLOW','ROLE','employee'),(66,'TicketTracking','*','READ','ALLOW','ROLE','employee'),(68,'TicketPackaging','*','*','ALLOW','ROLE','employee'),(69,'Packaging','*','READ','ALLOW','ROLE','employee'),(70,'Packaging','*','WRITE','ALLOW','ROLE','logistic'),(72,'SaleComponent','*','READ','ALLOW','ROLE','employee'),(73,'Expedition','*','READ','ALLOW','ROLE','employee'),(74,'Expedition','*','WRITE','ALLOW','ROLE','deliveryBoss'),(75,'Expedition','*','WRITE','ALLOW','ROLE','production'),(76,'AnnualAverageInvoiced','*','READ','ALLOW','ROLE','employee'),(77,'WorkerMana','*','READ','ALLOW','ROLE','employee'),(78,'TicketTracking','*','WRITE','ALLOW','ROLE','production'),(79,'TicketTracking','changeState','*','ALLOW','ROLE','employee'),(80,'Sale','deleteSales','*','ALLOW','ROLE','employee'),(81,'Sale','moveToTicket','*','ALLOW','ROLE','employee'),(82,'Sale','updateQuantity','*','ALLOW','ROLE','employee'),(83,'Sale','updatePrice','*','ALLOW','ROLE','employee'),(84,'Sale','updateDiscount','*','ALLOW','ROLE','employee'),(85,'SaleTracking','*','READ','ALLOW','ROLE','employee'),(86,'Order','*','*','ALLOW','ROLE','employee'),(87,'OrderRow','*','*','ALLOW','ROLE','employee'),(88,'ClientContact','*','*','ALLOW','ROLE','employee'),(89,'Sale','moveToNewTicket','*','ALLOW','ROLE','employee'),(90,'Sale','reserve','*','ALLOW','ROLE','employee'),(91,'TicketWeekly','*','READ','ALLOW','ROLE','employee'),(94,'Agency','landsThatDay','*','ALLOW','ROLE','employee'),(96,'ClaimEnd','*','READ','ALLOW','ROLE','employee'),(97,'ClaimEnd','*','WRITE','ALLOW','ROLE','claimManager'),(98,'ClaimBeginning','*','*','ALLOW','ROLE','employee'),(99,'ClaimDevelopment','*','READ','ALLOW','ROLE','employee'),(100,'ClaimDevelopment','*','WRITE','ALLOW','ROLE','claimManager'),(101,'Claim','*','*','ALLOW','ROLE','employee'),(102,'Claim','createFromSales','*','ALLOW','ROLE','employee'),(104,'Item','*','WRITE','ALLOW','ROLE','marketingBoss'),(105,'ItemBarcode','*','WRITE','ALLOW','ROLE','marketingBoss'),(106,'ItemBotanical','*','WRITE','ALLOW','ROLE','marketingBoss'),(108,'ItemPlacement','*','WRITE','ALLOW','ROLE','marketingBoss'),(109,'UserConfig','*','*','ALLOW','ROLE','employee'),(110,'Bank','*','READ','ALLOW','ROLE','trainee'),(111,'ClientLog','*','READ','ALLOW','ROLE','trainee'),(112,'Defaulter','*','READ','ALLOW','ROLE','employee'),(113,'ClientRisk','*','READ','ALLOW','ROLE','trainee'),(114,'Receipt','*','READ','ALLOW','ROLE','trainee'),(115,'Receipt','*','WRITE','ALLOW','ROLE','administrative'),(116,'BankEntity','*','*','ALLOW','ROLE','employee'),(117,'ClientSample','*','*','ALLOW','ROLE','employee'),(118,'WorkerTeam','*','*','ALLOW','ROLE','salesPerson'),(119,'Travel','*','READ','ALLOW','ROLE','employee'),(120,'Travel','*','WRITE','ALLOW','ROLE','buyer'),(121,'Item','regularize','*','ALLOW','ROLE','employee'),(122,'TicketRequest','*','*','ALLOW','ROLE','employee'),(123,'Worker','*','READ','ALLOW','ROLE','employee'),(124,'Client','confirmTransaction','WRITE','ALLOW','ROLE','administrative'),(125,'Agency','getAgenciesWithWarehouse','*','ALLOW','ROLE','employee'),(126,'Client','activeWorkersWithRole','*','ALLOW','ROLE','employee'),(127,'TicketLog','*','READ','ALLOW','ROLE','employee'),(129,'TicketService','*','*','ALLOW','ROLE','employee'),(130,'Expedition','*','WRITE','ALLOW','ROLE','packager'),(131,'CreditInsurance','*','READ','ALLOW','ROLE','trainee'),(132,'CreditClassification','*','READ','ALLOW','ROLE','trainee'),(133,'ItemTag','*','WRITE','ALLOW','ROLE','marketingBoss'),(135,'ZoneGeo','*','READ','ALLOW','ROLE','employee'),(136,'ZoneCalendar','*','READ','ALLOW','ROLE','employee'),(137,'ZoneIncluded','*','READ','ALLOW','ROLE','employee'),(138,'LabourHoliday','*','READ','ALLOW','ROLE','employee'),(139,'LabourHolidayLegend','*','READ','ALLOW','ROLE','employee'),(140,'LabourHolidayType','*','READ','ALLOW','ROLE','employee'),(141,'Zone','*','*','ALLOW','ROLE','logisticBoss'),(142,'ZoneCalendar','*','WRITE','ALLOW','ROLE','deliveryBoss'),(143,'ZoneIncluded','*','*','ALLOW','ROLE','deliveryBoss'),(144,'Stowaway','*','*','ALLOW','ROLE','employee'),(145,'Ticket','getPossibleStowaways','READ','ALLOW','ROLE','employee'),(147,'UserConfigView','*','*','ALLOW','ROLE','employee'),(148,'UserConfigView','*','*','ALLOW','ROLE','employee'),(149,'Sip','*','READ','ALLOW','ROLE','employee'),(150,'Sip','*','WRITE','ALLOW','ROLE','hr'),(151,'Department','*','READ','ALLOW','ROLE','employee'),(152,'Department','*','WRITE','ALLOW','ROLE','hr'),(153,'Route','*','READ','ALLOW','ROLE','employee'),(154,'Route','*','WRITE','ALLOW','ROLE','delivery'),(155,'Calendar','*','READ','ALLOW','ROLE','hr'),(156,'WorkerLabour','*','READ','ALLOW','ROLE','hr'),(157,'Calendar','absences','READ','ALLOW','ROLE','employee'),(158,'ItemTag','*','WRITE','ALLOW','ROLE','accessory'),(160,'TicketServiceType','*','READ','ALLOW','ROLE','employee'),(161,'TicketConfig','*','READ','ALLOW','ROLE','employee'),(162,'InvoiceOut','delete','WRITE','ALLOW','ROLE','invoicing'),(163,'InvoiceOut','book','WRITE','ALLOW','ROLE','invoicing'),(165,'TicketDms','*','*','ALLOW','ROLE','employee'),(167,'Worker','isSubordinate','READ','ALLOW','ROLE','employee'),(168,'Worker','mySubordinates','READ','ALLOW','ROLE','employee'),(169,'WorkerTimeControl','filter','READ','ALLOW','ROLE','employee'),(170,'WorkerTimeControl','addTime','WRITE','ALLOW','ROLE','employee'),(171,'TicketServiceType','*','WRITE','ALLOW','ROLE','administrative'),(172,'Sms','*','READ','ALLOW','ROLE','employee'),(173,'Sms','send','WRITE','ALLOW','ROLE','employee'),(174,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(175,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(176,'Device','*','*','ALLOW','ROLE','employee'),(177,'Device','*','*','ALLOW','ROLE','employee'),(178,'WorkerTimeControl','*','*','ALLOW','ROLE','employee'),(179,'ItemLog','*','READ','ALLOW','ROLE','employee'),(180,'RouteLog','*','READ','ALLOW','ROLE','employee'),(181,'Dms','removeFile','WRITE','ALLOW','ROLE','employee'),(182,'Dms','uploadFile','WRITE','ALLOW','ROLE','employee'),(183,'Dms','downloadFile','READ','ALLOW','ROLE','employee'),(184,'Client','uploadFile','WRITE','ALLOW','ROLE','employee'),(185,'ClientDms','removeFile','WRITE','ALLOW','ROLE','employee'),(186,'ClientDms','*','READ','ALLOW','ROLE','trainee'),(187,'Ticket','uploadFile','WRITE','ALLOW','ROLE','employee'),(190,'Route','updateVolume','WRITE','ALLOW','ROLE','deliveryBoss'),(191,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(192,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(194,'Postcode','*','WRITE','ALLOW','ROLE','deliveryBoss'),(195,'Ticket','addSale','WRITE','ALLOW','ROLE','employee'),(196,'Dms','updateFile','WRITE','ALLOW','ROLE','employee'),(197,'Dms','*','READ','ALLOW','ROLE','trainee'),(198,'ClaimDms','removeFile','WRITE','ALLOW','ROLE','employee'),(199,'ClaimDms','*','READ','ALLOW','ROLE','employee'),(200,'Claim','uploadFile','WRITE','ALLOW','ROLE','employee'),(201,'Sale','updateConcept','WRITE','ALLOW','ROLE','employee'),(202,'Claim','updateClaimAction','WRITE','ALLOW','ROLE','claimManager'),(203,'UserPhone','*','*','ALLOW','ROLE','employee'),(204,'WorkerDms','removeFile','WRITE','ALLOW','ROLE','hr'),(205,'WorkerDms','*','READ','ALLOW','ROLE','hr'),(206,'Chat','*','*','ALLOW','ROLE','employee'),(207,'Chat','sendMessage','*','ALLOW','ROLE','employee'),(208,'Sale','recalculatePrice','WRITE','ALLOW','ROLE','employee'),(209,'Ticket','recalculateComponents','WRITE','ALLOW','ROLE','employee'),(211,'TravelLog','*','READ','ALLOW','ROLE','buyer'),(212,'Thermograph','*','*','ALLOW','ROLE','buyer'),(213,'TravelThermograph','*','WRITE','ALLOW','ROLE','buyer'),(214,'Entry','*','*','ALLOW','ROLE','buyer'),(215,'TicketWeekly','*','WRITE','ALLOW','ROLE','buyer'),(216,'TravelThermograph','*','READ','ALLOW','ROLE','employee'),(218,'Intrastat','*','*','ALLOW','ROLE','buyer'),(221,'UserConfig','getUserConfig','READ','ALLOW','ROLE','account'),(222,'Client','*','READ','ALLOW','ROLE','trainee'),(226,'ClientObservation','*','READ','ALLOW','ROLE','trainee'),(227,'Address','*','READ','ALLOW','ROLE','trainee'),(228,'AddressObservation','*','READ','ALLOW','ROLE','trainee'),(230,'ClientCredit','*','READ','ALLOW','ROLE','trainee'),(231,'ClientContact','*','READ','ALLOW','ROLE','trainee'),(232,'ClientSample','*','READ','ALLOW','ROLE','trainee'),(233,'EntryLog','*','READ','ALLOW','ROLE','buyer'),(234,'WorkerLog','*','READ','ALLOW','ROLE','salesAssistant'),(235,'CustomsAgent','*','*','ALLOW','ROLE','employee'),(236,'Buy','*','*','ALLOW','ROLE','buyer'),(237,'WorkerDms','filter','*','ALLOW','ROLE','employee'),(238,'Town','*','WRITE','ALLOW','ROLE','deliveryBoss'),(239,'Province','*','WRITE','ALLOW','ROLE','deliveryBoss'),(240,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(241,'SupplierContact','*','WRITE','ALLOW','ROLE','administrative'),(242,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(244,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(248,'RoleMapping','*','READ','ALLOW','ROLE','account'),(249,'UserPassword','*','READ','ALLOW','ROLE','account'),(250,'Town','*','WRITE','ALLOW','ROLE','deliveryBoss'),(251,'Province','*','WRITE','ALLOW','ROLE','deliveryBoss'),(252,'Supplier','*','READ','ALLOW','ROLE','employee'),(253,'Supplier','*','WRITE','ALLOW','ROLE','administrative'),(254,'SupplierLog','*','READ','ALLOW','ROLE','employee'),(256,'Image','*','WRITE','ALLOW','ROLE','employee'),(257,'FixedPrice','*','*','ALLOW','ROLE','buyer'),(258,'PayDem','*','READ','ALLOW','ROLE','employee'),(259,'Client','createReceipt','*','ALLOW','ROLE','salesAssistant'),(260,'PrintServerQueue','*','WRITE','ALLOW','ROLE','employee'),(261,'SupplierAccount','*','*','ALLOW','ROLE','administrative'),(262,'Entry','*','*','ALLOW','ROLE','administrative'),(263,'InvoiceIn','*','*','ALLOW','ROLE','administrative'),(264,'StarredModule','*','*','ALLOW','ROLE','employee'),(265,'ItemBotanical','*','WRITE','ALLOW','ROLE','logisticBoss'),(266,'ZoneLog','*','READ','ALLOW','ROLE','employee'),(267,'Genus','*','WRITE','ALLOW','ROLE','logisticBoss'),(268,'Specie','*','WRITE','ALLOW','ROLE','logisticBoss'),(269,'InvoiceOut','createPdf','WRITE','ALLOW','ROLE','employee'),(270,'SupplierAddress','*','*','ALLOW','ROLE','employee'),(271,'SalesMonitor','*','*','ALLOW','ROLE','employee'),(272,'InvoiceInLog','*','READ','ALLOW','ROLE','employee'),(273,'InvoiceInTax','*','*','ALLOW','ROLE','administrative'),(274,'InvoiceInLog','*','READ','ALLOW','ROLE','administrative'),(275,'InvoiceOut','createManualInvoice','WRITE','ALLOW','ROLE','invoicing'),(276,'InvoiceOut','globalInvoicing','WRITE','ALLOW','ROLE','invoicing'),(277,'Role','*','*','ALLOW','ROLE','it'),(278,'RoleInherit','*','WRITE','ALLOW','ROLE','grant'),(279,'MailAlias','*','*','ALLOW','ROLE','marketing'),(283,'EntryObservation','*','*','ALLOW','ROLE','buyer'),(284,'LdapConfig','*','*','ALLOW','ROLE','sysadmin'),(285,'SambaConfig','*','*','ALLOW','ROLE','sysadmin'),(286,'ACL','*','*','ALLOW','ROLE','developer'),(287,'AccessToken','*','*','ALLOW','ROLE','developer'),(288,'MailAliasAccount','*','*','ALLOW','ROLE','marketing'),(289,'MailAliasAccount','*','*','ALLOW','ROLE','hr'),(290,'MailAlias','*','*','ALLOW','ROLE','hr'),(291,'MailForward','*','*','ALLOW','ROLE','marketing'),(292,'MailForward','*','*','ALLOW','ROLE','hr'),(293,'RoleInherit','*','*','ALLOW','ROLE','it'),(294,'RoleRole','*','*','ALLOW','ROLE','it'),(295,'AccountConfig','*','*','ALLOW','ROLE','sysadmin'),(296,'Collection','*','READ','ALLOW','ROLE','employee'),(297,'Sale','refund','WRITE','ALLOW','ROLE','invoicing'),(298,'InvoiceInDueDay','*','*','ALLOW','ROLE','administrative'),(299,'Collection','setSaleQuantity','*','ALLOW','ROLE','employee'),(300,'Docuware','*','*','ALLOW','ROLE','employee'),(301,'Agency','*','READ','ALLOW','ROLE','employee'),(302,'AgencyTerm','*','*','ALLOW','ROLE','administrative'),(303,'ClaimLog','*','READ','ALLOW','ROLE','claimManager'),(304,'Edi','updateData','WRITE','ALLOW','ROLE','employee'),(305,'EducationLevel','*','*','ALLOW','ROLE','employee'),(306,'InvoiceInIntrastat','*','*','ALLOW','ROLE','employee'),(307,'SupplierAgencyTerm','*','*','ALLOW','ROLE','administrative'),(308,'InvoiceInIntrastat','*','*','ALLOW','ROLE','employee'),(309,'Zone','getZoneClosing','*','ALLOW','ROLE','employee'),(310,'ExpeditionState','*','READ','ALLOW','ROLE','employee'),(311,'Expense','*','READ','ALLOW','ROLE','employee'),(312,'Expense','*','WRITE','ALLOW','ROLE','administrative'),(314,'SupplierActivity','*','READ','ALLOW','ROLE','employee'),(315,'SupplierActivity','*','WRITE','ALLOW','ROLE','administrative'),(316,'Dms','deleteTrashFiles','WRITE','ALLOW','ROLE','employee'),(317,'ClientUnpaid','*','*','ALLOW','ROLE','administrative'),(318,'MdbVersion','*','*','ALLOW','ROLE','developer'),(319,'ItemType','*','READ','ALLOW','ROLE','employee'),(320,'ItemType','*','WRITE','ALLOW','ROLE','buyer'),(321,'InvoiceOut','refund','WRITE','ALLOW','ROLE','invoicing'),(322,'InvoiceOut','refund','WRITE','ALLOW','ROLE','salesAssistant'),(323,'InvoiceOut','refund','WRITE','ALLOW','ROLE','claimManager'),(324,'Ticket','refund','WRITE','ALLOW','ROLE','invoicing'),(325,'Ticket','refund','WRITE','ALLOW','ROLE','salesAssistant'),(326,'Ticket','refund','WRITE','ALLOW','ROLE','claimManager'),(327,'Sale','refund','WRITE','ALLOW','ROLE','salesAssistant'),(328,'Sale','refund','WRITE','ALLOW','ROLE','claimManager'),(329,'TicketRefund','*','WRITE','ALLOW','ROLE','invoicing'),(330,'ClaimObservation','*','WRITE','ALLOW','ROLE','salesPerson'),(331,'ClaimObservation','*','READ','ALLOW','ROLE','salesPerson'),(332,'Client','setPassword','WRITE','ALLOW','ROLE','salesPerson'),(333,'Client','updateUser','WRITE','ALLOW','ROLE','salesPerson'),(334,'ShelvingLog','*','READ','ALLOW','ROLE','employee'),(335,'ZoneExclusionGeo','*','READ','ALLOW','ROLE','employee'),(336,'ZoneExclusionGeo','*','WRITE','ALLOW','ROLE','deliveryBoss'),(337,'Parking','*','*','ALLOW','ROLE','employee'),(338,'Shelving','*','*','ALLOW','ROLE','employee'),(339,'OsTicket','*','*','ALLOW','ROLE','employee'),(340,'OsTicketConfig','*','*','ALLOW','ROLE','it'),(341,'ClientConsumptionQueue','*','WRITE','ALLOW','ROLE','employee'),(342,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','employee'),(343,'Ticket','deliveryNoteEmail','WRITE','ALLOW','ROLE','employee'),(344,'Ticket','deliveryNoteCsvPdf','READ','ALLOW','ROLE','employee'),(345,'Ticket','deliveryNoteCsvEmail','WRITE','ALLOW','ROLE','employee'),(346,'Client','campaignMetricsPdf','READ','ALLOW','ROLE','employee'),(347,'Client','campaignMetricsEmail','WRITE','ALLOW','ROLE','employee'),(348,'Client','clientWelcomeHtml','READ','ALLOW','ROLE','employee'),(349,'Client','clientWelcomeEmail','WRITE','ALLOW','ROLE','employee'),(350,'Client','creditRequestPdf','READ','ALLOW','ROLE','employee'),(351,'Client','creditRequestHtml','READ','ALLOW','ROLE','employee'),(352,'Client','creditRequestEmail','WRITE','ALLOW','ROLE','employee'),(353,'Client','printerSetupHtml','READ','ALLOW','ROLE','employee'),(354,'Client','printerSetupEmail','WRITE','ALLOW','ROLE','employee'),(355,'Client','sepaCoreEmail','WRITE','ALLOW','ROLE','employee'),(356,'Client','letterDebtorPdf','READ','ALLOW','ROLE','employee'),(357,'Client','letterDebtorStHtml','READ','ALLOW','ROLE','employee'),(358,'Client','letterDebtorStEmail','WRITE','ALLOW','ROLE','employee'),(359,'Client','letterDebtorNdHtml','READ','ALLOW','ROLE','employee'),(360,'Client','letterDebtorNdEmail','WRITE','ALLOW','ROLE','employee'),(361,'Client','clientDebtStatementPdf','READ','ALLOW','ROLE','employee'),(362,'Client','clientDebtStatementHtml','READ','ALLOW','ROLE','employee'),(363,'Client','clientDebtStatementEmail','WRITE','ALLOW','ROLE','employee'),(364,'Client','incotermsAuthorizationPdf','READ','ALLOW','ROLE','employee'),(365,'Client','incotermsAuthorizationHtml','READ','ALLOW','ROLE','employee'),(366,'Client','incotermsAuthorizationEmail','WRITE','ALLOW','ROLE','employee'),(367,'Client','consumptionSendQueued','WRITE','ALLOW','ROLE','system'),(368,'InvoiceOut','invoiceEmail','WRITE','ALLOW','ROLE','employee'),(369,'InvoiceOut','exportationPdf','READ','ALLOW','ROLE','employee'),(370,'InvoiceOut','sendQueued','WRITE','ALLOW','ROLE','system'),(371,'Ticket','invoiceCsvPdf','READ','ALLOW','ROLE','employee'),(372,'Ticket','invoiceCsvEmail','WRITE','ALLOW','ROLE','employee'),(373,'Supplier','campaignMetricsPdf','READ','ALLOW','ROLE','employee'),(374,'Supplier','campaignMetricsEmail','WRITE','ALLOW','ROLE','employee'),(375,'Travel','extraCommunityPdf','READ','ALLOW','ROLE','employee'),(376,'Travel','extraCommunityEmail','WRITE','ALLOW','ROLE','employee'),(377,'Entry','entryOrderPdf','READ','ALLOW','ROLE','employee'),(378,'OsTicket','osTicketReportEmail','WRITE','ALLOW','ROLE','system'),(379,'Item','buyerWasteEmail','WRITE','ALLOW','ROLE','system'),(380,'Claim','claimPickupPdf','READ','ALLOW','ROLE','employee'),(381,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','claimManager'),(382,'Item','labelPdf','READ','ALLOW','ROLE','employee'),(383,'Sector','*','READ','ALLOW','ROLE','employee'),(384,'Sector','*','WRITE','ALLOW','ROLE','employee'),(385,'Route','driverRoutePdf','READ','ALLOW','ROLE','employee'),(386,'Route','driverRouteEmail','WRITE','ALLOW','ROLE','employee'),(387,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','customer'),(388,'Supplier','newSupplier','WRITE','ALLOW','ROLE','administrative'),(389,'ClaimRma','*','READ','ALLOW','ROLE','claimManager'),(390,'ClaimRma','*','WRITE','ALLOW','ROLE','claimManager'),(391,'Notification','*','WRITE','ALLOW','ROLE','system'),(392,'Boxing','*','*','ALLOW','ROLE','employee'),(393,'Url','*','READ','ALLOW','ROLE','employee'),(394,'Url','*','WRITE','ALLOW','ROLE','it'),(395,'ItemShelving','*','READ','ALLOW','ROLE','employee'),(396,'ItemShelving','*','WRITE','ALLOW','ROLE','production'),(397,'ItemShelvingPlacementSupplyStock','*','READ','ALLOW','ROLE','employee'),(398,'NotificationQueue','*','*','ALLOW','ROLE','employee'),(399,'InvoiceOut','clientsToInvoice','WRITE','ALLOW','ROLE','invoicing'),(400,'InvoiceOut','invoiceClient','WRITE','ALLOW','ROLE','invoicing'),(401,'Sale','editTracked','WRITE','ALLOW','ROLE','production'),(402,'Sale','editFloramondo','WRITE','ALLOW','ROLE','salesAssistant'),(403,'Receipt','balanceCompensationEmail','WRITE','ALLOW','ROLE','employee'),(404,'Receipt','balanceCompensationPdf','READ','ALLOW','ROLE','employee'),(405,'Ticket','getTicketsFuture','READ','ALLOW','ROLE','employee'),(406,'Ticket','merge','WRITE','ALLOW','ROLE','employee'),(407,'Sale','editFloramondo','WRITE','ALLOW','ROLE','logistic'),(408,'ZipConfig','*','*','ALLOW','ROLE','employee'),(409,'Item','*','WRITE','ALLOW','ROLE','administrative'),(410,'Sale','editCloned','WRITE','ALLOW','ROLE','buyer'),(411,'Sale','editCloned','WRITE','ALLOW','ROLE','salesAssistant'),(414,'MdbVersion','*','READ','ALLOW','ROLE','$everyone'),(416,'TicketLog','getChanges','READ','ALLOW','ROLE','employee'),(417,'Ticket','getTicketsAdvance','READ','ALLOW','ROLE','employee'),(418,'EntryLog','*','READ','ALLOW','ROLE','administrative'),(419,'Sale','editTracked','WRITE','ALLOW','ROLE','buyer'),(420,'MdbBranch','*','READ','ALLOW','ROLE','$everyone'),(421,'ItemShelvingSale','*','*','ALLOW','ROLE','employee'),(422,'Docuware','checkFile','READ','ALLOW','ROLE','employee'),(423,'Docuware','download','READ','ALLOW','ROLE','salesPerson'),(424,'Docuware','upload','WRITE','ALLOW','ROLE','productionAssi'),(425,'Docuware','deliveryNoteEmail','WRITE','ALLOW','ROLE','salesPerson'),(426,'TpvTransaction','confirm','WRITE','ALLOW','ROLE','$everyone'),(427,'TpvTransaction','start','WRITE','ALLOW','ROLE','$authenticated'),(428,'TpvTransaction','end','WRITE','ALLOW','ROLE','$authenticated'),(429,'ItemConfig','*','READ','ALLOW','ROLE','employee'),(431,'Tag','onSubmit','WRITE','ALLOW','ROLE','employee'),(432,'Worker','updateAttributes','WRITE','ALLOW','ROLE','hr'),(433,'Worker','createAbsence','*','ALLOW','ROLE','employee'),(434,'Worker','updateAbsence','WRITE','ALLOW','ROLE','employee'),(435,'Worker','deleteAbsence','*','ALLOW','ROLE','employee'),(436,'Worker','new','WRITE','ALLOW','ROLE','hr'),(437,'Role','*','READ','ALLOW','ROLE','hr'),(438,'Client','getClientOrSupplierReference','READ','ALLOW','ROLE','employee'),(439,'NotificationSubscription','*','*','ALLOW','ROLE','employee'),(440,'NotificationAcl','*','READ','ALLOW','ROLE','employee'),(441,'MdbApp','*','READ','ALLOW','ROLE','$everyone'),(442,'MdbApp','*','*','ALLOW','ROLE','developer'),(443,'ItemConfig','*','*','ALLOW','ROLE','employee'),(444,'DeviceProduction','*','*','ALLOW','ROLE','hr'),(445,'DeviceProductionModels','*','*','ALLOW','ROLE','hr'),(446,'DeviceProductionState','*','*','ALLOW','ROLE','hr'),(447,'DeviceProductionUser','*','*','ALLOW','ROLE','hr'),(448,'DeviceProduction','*','*','ALLOW','ROLE','productionAssi'),(449,'DeviceProductionModels','*','*','ALLOW','ROLE','productionAssi'),(450,'DeviceProductionState','*','*','ALLOW','ROLE','productionAssi'),(451,'DeviceProductionUser','*','*','ALLOW','ROLE','productionAssi'),(452,'Worker','deallocatePDA','*','ALLOW','ROLE','hr'),(453,'Worker','allocatePDA','*','ALLOW','ROLE','hr'),(454,'Worker','deallocatePDA','*','ALLOW','ROLE','productionAssi'),(455,'Worker','allocatePDA','*','ALLOW','ROLE','productionAssi'),(456,'Zone','*','*','ALLOW','ROLE','deliveryBoss'),(457,'Account','setPassword','WRITE','ALLOW','ROLE','itManagement'),(458,'Operator','*','READ','ALLOW','ROLE','employee'),(459,'Operator','*','WRITE','ALLOW','ROLE','employee'),(460,'InvoiceIn','getSerial','READ','ALLOW','ROLE','administrative'),(461,'Ticket','saveSign','WRITE','ALLOW','ROLE','employee'),(462,'InvoiceOut','negativeBases','READ','ALLOW','ROLE','administrative'),(463,'InvoiceOut','negativeBasesCsv','READ','ALLOW','ROLE','administrative'),(464,'WorkerObservation','*','*','ALLOW','ROLE','hr'),(465,'ClientInforma','*','READ','ALLOW','ROLE','employee'),(466,'ClientInforma','*','WRITE','ALLOW','ROLE','financial'),(467,'Receipt','receiptEmail','*','ALLOW','ROLE','salesAssistant'),(468,'Client','setRating','WRITE','ALLOW','ROLE','financial'),(469,'Client','*','READ','ALLOW','ROLE','employee'),(470,'Client','addressesPropagateRe','*','ALLOW','ROLE','employee'),(471,'Client','canBeInvoiced','*','ALLOW','ROLE','employee'),(472,'Client','canCreateTicket','*','ALLOW','ROLE','employee'),(473,'Client','consumption','*','ALLOW','ROLE','employee'),(474,'Client','createAddress','*','ALLOW','ROLE','employee'),(475,'Client','createWithUser','*','ALLOW','ROLE','employee'),(476,'Client','extendedListFilter','*','ALLOW','ROLE','employee'),(477,'Client','getAverageInvoiced','*','ALLOW','ROLE','employee'),(478,'Client','getCard','*','ALLOW','ROLE','employee'),(479,'Client','getDebt','*','ALLOW','ROLE','employee'),(480,'Client','getMana','*','ALLOW','ROLE','employee'),(481,'Client','transactions','*','ALLOW','ROLE','employee'),(482,'Client','hasCustomerRole','*','ALLOW','ROLE','employee'),(483,'Client','isValidClient','*','ALLOW','ROLE','employee'),(484,'Client','lastActiveTickets','*','ALLOW','ROLE','employee'),(485,'Client','sendSms','*','ALLOW','ROLE','employee'),(486,'Client','setPassword','*','ALLOW','ROLE','employee'),(487,'Client','summary','*','ALLOW','ROLE','employee'),(488,'Client','updateAddress','*','ALLOW','ROLE','employee'),(489,'Client','updateFiscalData','*','ALLOW','ROLE','employee'),(490,'Client','updateUser','*','ALLOW','ROLE','employee'),(491,'Client','uploadFile','*','ALLOW','ROLE','employee'),(492,'Client','campaignMetricsPdf','*','ALLOW','ROLE','employee'),(493,'Client','campaignMetricsEmail','*','ALLOW','ROLE','employee'),(494,'Client','clientWelcomeHtml','*','ALLOW','ROLE','employee'),(495,'Client','clientWelcomeEmail','*','ALLOW','ROLE','employee'),(496,'Client','printerSetupHtml','*','ALLOW','ROLE','employee'),(497,'Client','printerSetupEmail','*','ALLOW','ROLE','employee'),(498,'Client','sepaCoreEmail','*','ALLOW','ROLE','employee'),(499,'Client','letterDebtorPdf','*','ALLOW','ROLE','employee'),(500,'Client','letterDebtorStHtml','*','ALLOW','ROLE','employee'),(501,'Client','letterDebtorStEmail','*','ALLOW','ROLE','employee'),(502,'Client','letterDebtorNdHtml','*','ALLOW','ROLE','employee'),(503,'Client','letterDebtorNdEmail','*','ALLOW','ROLE','employee'),(504,'Client','clientDebtStatementPdf','*','ALLOW','ROLE','employee'),(505,'Client','clientDebtStatementHtml','*','ALLOW','ROLE','employee'),(506,'Client','clientDebtStatementEmail','*','ALLOW','ROLE','employee'),(507,'Client','creditRequestPdf','*','ALLOW','ROLE','employee'),(508,'Client','creditRequestHtml','*','ALLOW','ROLE','employee'),(509,'Client','creditRequestEmail','*','ALLOW','ROLE','employee'),(510,'Client','incotermsAuthorizationPdf','*','ALLOW','ROLE','employee'),(511,'Client','incotermsAuthorizationHtml','*','ALLOW','ROLE','employee'),(512,'Client','incotermsAuthorizationEmail','*','ALLOW','ROLE','employee'),(513,'Client','consumptionSendQueued','*','ALLOW','ROLE','employee'),(514,'Client','filter','*','ALLOW','ROLE','employee'),(515,'Client','getClientOrSupplierReference','*','ALLOW','ROLE','employee'),(516,'Client','upsert','*','ALLOW','ROLE','employee'),(517,'Client','create','*','ALLOW','ROLE','employee'),(518,'Client','replaceById','*','ALLOW','ROLE','employee'),(519,'Client','updateAttributes','*','ALLOW','ROLE','employee'),(520,'Client','updateAttributes','*','ALLOW','ROLE','employee'),(521,'Client','deleteById','*','ALLOW','ROLE','employee'),(522,'Client','replaceOrCreate','*','ALLOW','ROLE','employee'),(523,'Client','updateAll','*','ALLOW','ROLE','employee'),(524,'Client','upsertWithWhere','*','ALLOW','ROLE','employee'),(525,'Defaulter','observationEmail','WRITE','ALLOW','ROLE','employee'),(526,'VnUser','*','*','ALLOW','ROLE','employee'),(527,'VnUser','acl','READ','ALLOW','ROLE','account'),(528,'VnUser','getCurrentUserData','READ','ALLOW','ROLE','account'),(529,'VnUser','changePassword','WRITE','ALLOW','ROLE','account'),(530,'Account','exists','READ','ALLOW','ROLE','account'),(531,'Account','exists','READ','ALLOW','ROLE','account'),(532,'UserLog','*','READ','ALLOW','ROLE','employee'),(533,'RoleLog','*','READ','ALLOW','ROLE','employee'); +INSERT INTO `ACL` VALUES (1,'Account','*','*','ALLOW','ROLE','employee'),(3,'Address','*','*','ALLOW','ROLE','employee'),(5,'AgencyService','*','READ','ALLOW','ROLE','employee'),(9,'ClientObservation','*','*','ALLOW','ROLE','employee'),(11,'ContactChannel','*','READ','ALLOW','ROLE','trainee'),(13,'Employee','*','READ','ALLOW','ROLE','employee'),(14,'PayMethod','*','READ','ALLOW','ROLE','trainee'),(16,'FakeProduction','*','READ','ALLOW','ROLE','employee'),(17,'Warehouse','* ','READ','ALLOW','ROLE','trainee'),(18,'State','*','READ','ALLOW','ROLE','employee'),(20,'TicketState','*','*','ALLOW','ROLE','employee'),(24,'Delivery','*','READ','ALLOW','ROLE','employee'),(25,'Zone','*','READ','ALLOW','ROLE','employee'),(26,'ClientCredit','*','*','ALLOW','ROLE','employee'),(27,'ClientCreditLimit','*','READ','ALLOW','ROLE','trainee'),(30,'GreugeType','*','READ','ALLOW','ROLE','trainee'),(31,'Mandate','*','READ','ALLOW','ROLE','trainee'),(32,'MandateType','*','READ','ALLOW','ROLE','trainee'),(33,'Company','*','READ','ALLOW','ROLE','trainee'),(34,'Greuge','*','READ','ALLOW','ROLE','trainee'),(35,'AddressObservation','*','*','ALLOW','ROLE','employee'),(36,'ObservationType','*','*','ALLOW','ROLE','employee'),(37,'Greuge','*','WRITE','ALLOW','ROLE','employee'),(38,'AgencyMode','*','READ','ALLOW','ROLE','employee'),(39,'ItemTag','*','WRITE','ALLOW','ROLE','buyer'),(40,'ItemBotanical','*','WRITE','ALLOW','ROLE','buyer'),(41,'ItemBotanical','*','READ','ALLOW','ROLE','employee'),(42,'ItemPlacement','*','WRITE','ALLOW','ROLE','buyer'),(43,'ItemPlacement','*','WRITE','ALLOW','ROLE','replenisher'),(44,'ItemPlacement','*','READ','ALLOW','ROLE','employee'),(45,'ItemBarcode','*','READ','ALLOW','ROLE','employee'),(46,'ItemBarcode','*','WRITE','ALLOW','ROLE','buyer'),(47,'ItemBarcode','*','WRITE','ALLOW','ROLE','replenisher'),(51,'ItemTag','*','READ','ALLOW','ROLE','employee'),(53,'Item','*','READ','ALLOW','ROLE','employee'),(54,'Item','*','WRITE','ALLOW','ROLE','buyer'),(55,'Recovery','*','READ','ALLOW','ROLE','trainee'),(56,'Recovery','*','WRITE','ALLOW','ROLE','administrative'),(58,'CreditClassification','*','*','ALLOW','ROLE','insurance'),(60,'CreditInsurance','*','*','ALLOW','ROLE','insurance'),(61,'InvoiceOut','*','READ','ALLOW','ROLE','employee'),(62,'Ticket','*','*','ALLOW','ROLE','employee'),(63,'TicketObservation','*','*','ALLOW','ROLE','employee'),(64,'Route','*','READ','ALLOW','ROLE','employee'),(65,'Sale','*','READ','ALLOW','ROLE','employee'),(66,'TicketTracking','*','READ','ALLOW','ROLE','employee'),(68,'TicketPackaging','*','*','ALLOW','ROLE','employee'),(69,'Packaging','*','READ','ALLOW','ROLE','employee'),(70,'Packaging','*','WRITE','ALLOW','ROLE','logistic'),(72,'SaleComponent','*','READ','ALLOW','ROLE','employee'),(73,'Expedition','*','READ','ALLOW','ROLE','employee'),(74,'Expedition','*','WRITE','ALLOW','ROLE','deliveryAssistant'),(75,'Expedition','*','WRITE','ALLOW','ROLE','production'),(76,'AnnualAverageInvoiced','*','READ','ALLOW','ROLE','employee'),(77,'WorkerMana','*','READ','ALLOW','ROLE','employee'),(78,'TicketTracking','*','WRITE','ALLOW','ROLE','production'),(79,'TicketTracking','changeState','*','ALLOW','ROLE','employee'),(80,'Sale','deleteSales','*','ALLOW','ROLE','employee'),(81,'Sale','moveToTicket','*','ALLOW','ROLE','employee'),(82,'Sale','updateQuantity','*','ALLOW','ROLE','employee'),(83,'Sale','updatePrice','*','ALLOW','ROLE','employee'),(84,'Sale','updateDiscount','*','ALLOW','ROLE','employee'),(85,'SaleTracking','*','READ','ALLOW','ROLE','employee'),(86,'Order','*','*','ALLOW','ROLE','employee'),(87,'OrderRow','*','*','ALLOW','ROLE','employee'),(88,'ClientContact','*','*','ALLOW','ROLE','employee'),(89,'Sale','moveToNewTicket','*','ALLOW','ROLE','employee'),(90,'Sale','reserve','*','ALLOW','ROLE','employee'),(91,'TicketWeekly','*','READ','ALLOW','ROLE','employee'),(94,'Agency','landsThatDay','*','ALLOW','ROLE','employee'),(96,'ClaimEnd','*','READ','ALLOW','ROLE','employee'),(97,'ClaimEnd','*','WRITE','ALLOW','ROLE','claimManager'),(98,'ClaimBeginning','*','*','ALLOW','ROLE','employee'),(99,'ClaimDevelopment','*','READ','ALLOW','ROLE','employee'),(100,'ClaimDevelopment','*','WRITE','ALLOW','ROLE','claimManager'),(101,'Claim','*','*','ALLOW','ROLE','employee'),(102,'Claim','createFromSales','*','ALLOW','ROLE','employee'),(104,'Item','*','WRITE','ALLOW','ROLE','marketingBoss'),(105,'ItemBarcode','*','WRITE','ALLOW','ROLE','marketingBoss'),(106,'ItemBotanical','*','WRITE','ALLOW','ROLE','marketingBoss'),(108,'ItemPlacement','*','WRITE','ALLOW','ROLE','marketingBoss'),(109,'UserConfig','*','*','ALLOW','ROLE','employee'),(110,'Bank','*','READ','ALLOW','ROLE','trainee'),(111,'ClientLog','*','READ','ALLOW','ROLE','trainee'),(112,'Defaulter','*','READ','ALLOW','ROLE','employee'),(113,'ClientRisk','*','READ','ALLOW','ROLE','trainee'),(114,'Receipt','*','READ','ALLOW','ROLE','trainee'),(115,'Receipt','*','WRITE','ALLOW','ROLE','administrative'),(116,'BankEntity','*','*','ALLOW','ROLE','employee'),(117,'ClientSample','*','*','ALLOW','ROLE','employee'),(118,'WorkerTeam','*','*','ALLOW','ROLE','salesPerson'),(119,'Travel','*','READ','ALLOW','ROLE','employee'),(120,'Travel','*','WRITE','ALLOW','ROLE','buyer'),(121,'Item','regularize','*','ALLOW','ROLE','employee'),(122,'TicketRequest','*','*','ALLOW','ROLE','employee'),(123,'Worker','*','READ','ALLOW','ROLE','employee'),(124,'Client','confirmTransaction','WRITE','ALLOW','ROLE','administrative'),(125,'Agency','getAgenciesWithWarehouse','*','ALLOW','ROLE','employee'),(126,'Client','activeWorkersWithRole','*','ALLOW','ROLE','employee'),(127,'TicketLog','*','READ','ALLOW','ROLE','employee'),(129,'TicketService','*','*','ALLOW','ROLE','employee'),(130,'Expedition','*','WRITE','ALLOW','ROLE','packager'),(131,'CreditInsurance','*','READ','ALLOW','ROLE','trainee'),(132,'CreditClassification','*','READ','ALLOW','ROLE','trainee'),(133,'ItemTag','*','WRITE','ALLOW','ROLE','marketingBoss'),(135,'ZoneGeo','*','READ','ALLOW','ROLE','employee'),(136,'ZoneCalendar','*','READ','ALLOW','ROLE','employee'),(137,'ZoneIncluded','*','READ','ALLOW','ROLE','employee'),(138,'LabourHoliday','*','READ','ALLOW','ROLE','employee'),(139,'LabourHolidayLegend','*','READ','ALLOW','ROLE','employee'),(140,'LabourHolidayType','*','READ','ALLOW','ROLE','employee'),(141,'Zone','*','*','ALLOW','ROLE','logisticBoss'),(142,'ZoneCalendar','*','WRITE','ALLOW','ROLE','deliveryAssistant'),(143,'ZoneIncluded','*','*','ALLOW','ROLE','deliveryAssistant'),(144,'Stowaway','*','*','ALLOW','ROLE','employee'),(145,'Ticket','getPossibleStowaways','READ','ALLOW','ROLE','employee'),(147,'UserConfigView','*','*','ALLOW','ROLE','employee'),(148,'UserConfigView','*','*','ALLOW','ROLE','employee'),(149,'Sip','*','READ','ALLOW','ROLE','employee'),(150,'Sip','*','WRITE','ALLOW','ROLE','hr'),(151,'Department','*','READ','ALLOW','ROLE','employee'),(152,'Department','*','WRITE','ALLOW','ROLE','hr'),(153,'Route','*','READ','ALLOW','ROLE','employee'),(154,'Route','*','WRITE','ALLOW','ROLE','delivery'),(155,'Calendar','*','READ','ALLOW','ROLE','hr'),(156,'WorkerLabour','*','READ','ALLOW','ROLE','hr'),(157,'Calendar','absences','READ','ALLOW','ROLE','employee'),(158,'ItemTag','*','WRITE','ALLOW','ROLE','accessory'),(160,'TicketServiceType','*','READ','ALLOW','ROLE','employee'),(161,'TicketConfig','*','READ','ALLOW','ROLE','employee'),(162,'InvoiceOut','delete','WRITE','ALLOW','ROLE','invoicing'),(163,'InvoiceOut','book','WRITE','ALLOW','ROLE','invoicing'),(165,'TicketDms','*','*','ALLOW','ROLE','employee'),(167,'Worker','isSubordinate','READ','ALLOW','ROLE','employee'),(168,'Worker','mySubordinates','READ','ALLOW','ROLE','employee'),(169,'WorkerTimeControl','filter','READ','ALLOW','ROLE','employee'),(170,'WorkerTimeControl','addTime','WRITE','ALLOW','ROLE','employee'),(171,'TicketServiceType','*','WRITE','ALLOW','ROLE','administrative'),(172,'Sms','*','READ','ALLOW','ROLE','employee'),(173,'Sms','send','WRITE','ALLOW','ROLE','employee'),(174,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(175,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(176,'Device','*','*','ALLOW','ROLE','employee'),(177,'Device','*','*','ALLOW','ROLE','employee'),(178,'WorkerTimeControl','*','*','ALLOW','ROLE','employee'),(179,'ItemLog','*','READ','ALLOW','ROLE','employee'),(180,'RouteLog','*','READ','ALLOW','ROLE','employee'),(181,'Dms','removeFile','WRITE','ALLOW','ROLE','employee'),(182,'Dms','uploadFile','WRITE','ALLOW','ROLE','employee'),(183,'Dms','downloadFile','READ','ALLOW','ROLE','employee'),(184,'Client','uploadFile','WRITE','ALLOW','ROLE','employee'),(185,'ClientDms','removeFile','WRITE','ALLOW','ROLE','employee'),(186,'ClientDms','*','READ','ALLOW','ROLE','trainee'),(187,'Ticket','uploadFile','WRITE','ALLOW','ROLE','employee'),(190,'Route','updateVolume','WRITE','ALLOW','ROLE','deliveryAssistant'),(191,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(192,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(194,'Postcode','*','WRITE','ALLOW','ROLE','deliveryAssistant'),(195,'Ticket','addSale','WRITE','ALLOW','ROLE','employee'),(196,'Dms','updateFile','WRITE','ALLOW','ROLE','employee'),(197,'Dms','*','READ','ALLOW','ROLE','trainee'),(198,'ClaimDms','removeFile','WRITE','ALLOW','ROLE','employee'),(199,'ClaimDms','*','READ','ALLOW','ROLE','employee'),(200,'Claim','uploadFile','WRITE','ALLOW','ROLE','employee'),(201,'Sale','updateConcept','WRITE','ALLOW','ROLE','employee'),(202,'Claim','updateClaimAction','WRITE','ALLOW','ROLE','claimManager'),(203,'UserPhone','*','*','ALLOW','ROLE','employee'),(204,'WorkerDms','removeFile','WRITE','ALLOW','ROLE','hr'),(205,'WorkerDms','*','READ','ALLOW','ROLE','hr'),(206,'Chat','*','*','ALLOW','ROLE','employee'),(207,'Chat','sendMessage','*','ALLOW','ROLE','employee'),(208,'Sale','recalculatePrice','WRITE','ALLOW','ROLE','employee'),(209,'Ticket','recalculateComponents','WRITE','ALLOW','ROLE','employee'),(211,'TravelLog','*','READ','ALLOW','ROLE','buyer'),(212,'Thermograph','*','*','ALLOW','ROLE','buyer'),(213,'TravelThermograph','*','WRITE','ALLOW','ROLE','buyer'),(214,'Entry','*','*','ALLOW','ROLE','buyer'),(215,'TicketWeekly','*','WRITE','ALLOW','ROLE','buyer'),(216,'TravelThermograph','*','READ','ALLOW','ROLE','employee'),(218,'Intrastat','*','*','ALLOW','ROLE','buyer'),(221,'UserConfig','getUserConfig','READ','ALLOW','ROLE','account'),(222,'Client','*','READ','ALLOW','ROLE','trainee'),(226,'ClientObservation','*','READ','ALLOW','ROLE','trainee'),(227,'Address','*','READ','ALLOW','ROLE','trainee'),(228,'AddressObservation','*','READ','ALLOW','ROLE','trainee'),(230,'ClientCredit','*','READ','ALLOW','ROLE','trainee'),(231,'ClientContact','*','READ','ALLOW','ROLE','trainee'),(232,'ClientSample','*','READ','ALLOW','ROLE','trainee'),(233,'EntryLog','*','READ','ALLOW','ROLE','buyer'),(234,'WorkerLog','*','READ','ALLOW','ROLE','salesAssistant'),(235,'CustomsAgent','*','*','ALLOW','ROLE','employee'),(236,'Buy','*','*','ALLOW','ROLE','buyer'),(237,'WorkerDms','filter','*','ALLOW','ROLE','employee'),(238,'Town','*','WRITE','ALLOW','ROLE','deliveryAssistant'),(239,'Province','*','WRITE','ALLOW','ROLE','deliveryAssistant'),(240,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(241,'SupplierContact','*','WRITE','ALLOW','ROLE','administrative'),(242,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(244,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(248,'RoleMapping','*','READ','ALLOW','ROLE','account'),(249,'UserPassword','*','READ','ALLOW','ROLE','account'),(250,'Town','*','WRITE','ALLOW','ROLE','deliveryAssistant'),(251,'Province','*','WRITE','ALLOW','ROLE','deliveryAssistant'),(252,'Supplier','*','READ','ALLOW','ROLE','employee'),(253,'Supplier','*','WRITE','ALLOW','ROLE','administrative'),(254,'SupplierLog','*','READ','ALLOW','ROLE','employee'),(256,'Image','*','WRITE','ALLOW','ROLE','employee'),(257,'FixedPrice','*','*','ALLOW','ROLE','buyer'),(258,'PayDem','*','READ','ALLOW','ROLE','employee'),(259,'Client','createReceipt','*','ALLOW','ROLE','salesAssistant'),(260,'PrintServerQueue','*','WRITE','ALLOW','ROLE','employee'),(261,'SupplierAccount','*','*','ALLOW','ROLE','administrative'),(262,'Entry','*','*','ALLOW','ROLE','administrative'),(263,'InvoiceIn','*','*','ALLOW','ROLE','administrative'),(264,'StarredModule','*','*','ALLOW','ROLE','employee'),(265,'ItemBotanical','*','WRITE','ALLOW','ROLE','logisticBoss'),(266,'ZoneLog','*','READ','ALLOW','ROLE','employee'),(267,'Genus','*','WRITE','ALLOW','ROLE','logisticBoss'),(268,'Specie','*','WRITE','ALLOW','ROLE','logisticBoss'),(269,'InvoiceOut','createPdf','WRITE','ALLOW','ROLE','employee'),(270,'SupplierAddress','*','*','ALLOW','ROLE','employee'),(271,'SalesMonitor','*','*','ALLOW','ROLE','employee'),(272,'InvoiceInLog','*','READ','ALLOW','ROLE','employee'),(273,'InvoiceInTax','*','*','ALLOW','ROLE','administrative'),(274,'InvoiceInLog','*','READ','ALLOW','ROLE','administrative'),(275,'InvoiceOut','createManualInvoice','WRITE','ALLOW','ROLE','invoicing'),(276,'InvoiceOut','globalInvoicing','WRITE','ALLOW','ROLE','invoicing'),(277,'Role','*','*','ALLOW','ROLE','it'),(278,'RoleInherit','*','WRITE','ALLOW','ROLE','grant'),(279,'MailAlias','*','*','ALLOW','ROLE','marketing'),(283,'EntryObservation','*','*','ALLOW','ROLE','buyer'),(284,'LdapConfig','*','*','ALLOW','ROLE','sysadmin'),(285,'SambaConfig','*','*','ALLOW','ROLE','sysadmin'),(286,'ACL','*','*','ALLOW','ROLE','developer'),(287,'AccessToken','*','*','ALLOW','ROLE','developer'),(288,'MailAliasAccount','*','*','ALLOW','ROLE','marketing'),(289,'MailAliasAccount','*','*','ALLOW','ROLE','hr'),(290,'MailAlias','*','*','ALLOW','ROLE','hr'),(291,'MailForward','*','*','ALLOW','ROLE','marketing'),(292,'MailForward','*','*','ALLOW','ROLE','hr'),(293,'RoleInherit','*','*','ALLOW','ROLE','it'),(294,'RoleRole','*','*','ALLOW','ROLE','it'),(295,'AccountConfig','*','*','ALLOW','ROLE','sysadmin'),(296,'Collection','*','READ','ALLOW','ROLE','employee'),(297,'Sale','refund','WRITE','ALLOW','ROLE','invoicing'),(298,'InvoiceInDueDay','*','*','ALLOW','ROLE','administrative'),(299,'Collection','setSaleQuantity','*','ALLOW','ROLE','employee'),(300,'Docuware','*','*','ALLOW','ROLE','employee'),(301,'Agency','*','READ','ALLOW','ROLE','employee'),(302,'AgencyTerm','*','*','ALLOW','ROLE','administrative'),(303,'ClaimLog','*','READ','ALLOW','ROLE','claimManager'),(304,'Edi','updateData','WRITE','ALLOW','ROLE','employee'),(305,'EducationLevel','*','*','ALLOW','ROLE','employee'),(306,'InvoiceInIntrastat','*','*','ALLOW','ROLE','employee'),(307,'SupplierAgencyTerm','*','*','ALLOW','ROLE','administrative'),(308,'InvoiceInIntrastat','*','*','ALLOW','ROLE','employee'),(309,'Zone','getZoneClosing','*','ALLOW','ROLE','employee'),(310,'ExpeditionState','*','READ','ALLOW','ROLE','employee'),(311,'Expense','*','READ','ALLOW','ROLE','employee'),(312,'Expense','*','WRITE','ALLOW','ROLE','administrative'),(314,'SupplierActivity','*','READ','ALLOW','ROLE','employee'),(315,'SupplierActivity','*','WRITE','ALLOW','ROLE','administrative'),(316,'Dms','deleteTrashFiles','WRITE','ALLOW','ROLE','employee'),(317,'ClientUnpaid','*','*','ALLOW','ROLE','administrative'),(318,'MdbVersion','*','*','ALLOW','ROLE','developer'),(319,'ItemType','*','READ','ALLOW','ROLE','employee'),(320,'ItemType','*','WRITE','ALLOW','ROLE','buyer'),(321,'InvoiceOut','refund','WRITE','ALLOW','ROLE','invoicing'),(322,'InvoiceOut','refund','WRITE','ALLOW','ROLE','salesAssistant'),(323,'InvoiceOut','refund','WRITE','ALLOW','ROLE','claimManager'),(324,'Ticket','refund','WRITE','ALLOW','ROLE','invoicing'),(325,'Ticket','refund','WRITE','ALLOW','ROLE','salesAssistant'),(326,'Ticket','refund','WRITE','ALLOW','ROLE','claimManager'),(327,'Sale','refund','WRITE','ALLOW','ROLE','salesAssistant'),(328,'Sale','refund','WRITE','ALLOW','ROLE','claimManager'),(329,'TicketRefund','*','WRITE','ALLOW','ROLE','invoicing'),(330,'ClaimObservation','*','WRITE','ALLOW','ROLE','salesPerson'),(331,'ClaimObservation','*','READ','ALLOW','ROLE','salesPerson'),(332,'Client','setPassword','WRITE','ALLOW','ROLE','salesPerson'),(333,'Client','updateUser','WRITE','ALLOW','ROLE','salesPerson'),(334,'ShelvingLog','*','READ','ALLOW','ROLE','employee'),(335,'ZoneExclusionGeo','*','READ','ALLOW','ROLE','employee'),(336,'ZoneExclusionGeo','*','WRITE','ALLOW','ROLE','deliveryAssistant'),(337,'Parking','*','*','ALLOW','ROLE','employee'),(338,'Shelving','*','*','ALLOW','ROLE','employee'),(339,'OsTicket','*','*','ALLOW','ROLE','employee'),(340,'OsTicketConfig','*','*','ALLOW','ROLE','it'),(341,'ClientConsumptionQueue','*','WRITE','ALLOW','ROLE','employee'),(342,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','employee'),(343,'Ticket','deliveryNoteEmail','WRITE','ALLOW','ROLE','employee'),(344,'Ticket','deliveryNoteCsvPdf','READ','ALLOW','ROLE','employee'),(345,'Ticket','deliveryNoteCsvEmail','WRITE','ALLOW','ROLE','employee'),(346,'Client','campaignMetricsPdf','READ','ALLOW','ROLE','employee'),(347,'Client','campaignMetricsEmail','WRITE','ALLOW','ROLE','employee'),(348,'Client','clientWelcomeHtml','READ','ALLOW','ROLE','employee'),(349,'Client','clientWelcomeEmail','WRITE','ALLOW','ROLE','employee'),(350,'Client','creditRequestPdf','READ','ALLOW','ROLE','employee'),(351,'Client','creditRequestHtml','READ','ALLOW','ROLE','employee'),(352,'Client','creditRequestEmail','WRITE','ALLOW','ROLE','employee'),(353,'Client','printerSetupHtml','READ','ALLOW','ROLE','employee'),(354,'Client','printerSetupEmail','WRITE','ALLOW','ROLE','employee'),(355,'Client','sepaCoreEmail','WRITE','ALLOW','ROLE','employee'),(356,'Client','letterDebtorPdf','READ','ALLOW','ROLE','employee'),(357,'Client','letterDebtorStHtml','READ','ALLOW','ROLE','employee'),(358,'Client','letterDebtorStEmail','WRITE','ALLOW','ROLE','employee'),(359,'Client','letterDebtorNdHtml','READ','ALLOW','ROLE','employee'),(360,'Client','letterDebtorNdEmail','WRITE','ALLOW','ROLE','employee'),(361,'Client','clientDebtStatementPdf','READ','ALLOW','ROLE','employee'),(362,'Client','clientDebtStatementHtml','READ','ALLOW','ROLE','employee'),(363,'Client','clientDebtStatementEmail','WRITE','ALLOW','ROLE','employee'),(364,'Client','incotermsAuthorizationPdf','READ','ALLOW','ROLE','employee'),(365,'Client','incotermsAuthorizationHtml','READ','ALLOW','ROLE','employee'),(366,'Client','incotermsAuthorizationEmail','WRITE','ALLOW','ROLE','employee'),(367,'Client','consumptionSendQueued','WRITE','ALLOW','ROLE','system'),(368,'InvoiceOut','invoiceEmail','WRITE','ALLOW','ROLE','employee'),(369,'InvoiceOut','exportationPdf','READ','ALLOW','ROLE','employee'),(370,'InvoiceOut','sendQueued','WRITE','ALLOW','ROLE','system'),(371,'Ticket','invoiceCsvPdf','READ','ALLOW','ROLE','employee'),(372,'Ticket','invoiceCsvEmail','WRITE','ALLOW','ROLE','employee'),(373,'Supplier','campaignMetricsPdf','READ','ALLOW','ROLE','employee'),(374,'Supplier','campaignMetricsEmail','WRITE','ALLOW','ROLE','employee'),(375,'Travel','extraCommunityPdf','READ','ALLOW','ROLE','employee'),(376,'Travel','extraCommunityEmail','WRITE','ALLOW','ROLE','employee'),(377,'Entry','entryOrderPdf','READ','ALLOW','ROLE','employee'),(378,'OsTicket','osTicketReportEmail','WRITE','ALLOW','ROLE','system'),(379,'Item','buyerWasteEmail','WRITE','ALLOW','ROLE','system'),(380,'Claim','claimPickupPdf','READ','ALLOW','ROLE','employee'),(381,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','claimManager'),(382,'Item','labelPdf','READ','ALLOW','ROLE','employee'),(383,'Sector','*','READ','ALLOW','ROLE','employee'),(384,'Sector','*','WRITE','ALLOW','ROLE','employee'),(385,'Route','driverRoutePdf','READ','ALLOW','ROLE','employee'),(386,'Route','driverRouteEmail','WRITE','ALLOW','ROLE','employee'),(387,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','customer'),(388,'Supplier','newSupplier','WRITE','ALLOW','ROLE','administrative'),(389,'ClaimRma','*','READ','ALLOW','ROLE','claimManager'),(390,'ClaimRma','*','WRITE','ALLOW','ROLE','claimManager'),(391,'Notification','*','WRITE','ALLOW','ROLE','system'),(392,'Boxing','*','*','ALLOW','ROLE','employee'),(393,'Url','*','READ','ALLOW','ROLE','employee'),(394,'Url','*','WRITE','ALLOW','ROLE','it'),(395,'ItemShelving','*','READ','ALLOW','ROLE','employee'),(396,'ItemShelving','*','WRITE','ALLOW','ROLE','production'),(397,'ItemShelvingPlacementSupplyStock','*','READ','ALLOW','ROLE','employee'),(398,'NotificationQueue','*','*','ALLOW','ROLE','employee'),(399,'InvoiceOut','clientsToInvoice','WRITE','ALLOW','ROLE','invoicing'),(400,'InvoiceOut','invoiceClient','WRITE','ALLOW','ROLE','invoicing'),(401,'Sale','editTracked','WRITE','ALLOW','ROLE','production'),(402,'Sale','editFloramondo','WRITE','ALLOW','ROLE','salesAssistant'),(403,'Receipt','balanceCompensationEmail','WRITE','ALLOW','ROLE','employee'),(404,'Receipt','balanceCompensationPdf','READ','ALLOW','ROLE','employee'),(405,'Ticket','getTicketsFuture','READ','ALLOW','ROLE','employee'),(406,'Ticket','merge','WRITE','ALLOW','ROLE','employee'),(407,'Sale','editFloramondo','WRITE','ALLOW','ROLE','logistic'),(408,'ZipConfig','*','*','ALLOW','ROLE','employee'),(409,'Item','*','WRITE','ALLOW','ROLE','administrative'),(410,'Sale','editCloned','WRITE','ALLOW','ROLE','buyer'),(411,'Sale','editCloned','WRITE','ALLOW','ROLE','salesAssistant'),(414,'MdbVersion','*','READ','ALLOW','ROLE','$everyone'),(416,'TicketLog','getChanges','READ','ALLOW','ROLE','employee'),(417,'Ticket','getTicketsAdvance','READ','ALLOW','ROLE','employee'),(418,'EntryLog','*','READ','ALLOW','ROLE','administrative'),(419,'Sale','editTracked','WRITE','ALLOW','ROLE','buyer'),(420,'MdbBranch','*','READ','ALLOW','ROLE','$everyone'),(421,'ItemShelvingSale','*','*','ALLOW','ROLE','employee'),(422,'Docuware','checkFile','READ','ALLOW','ROLE','employee'),(423,'Docuware','download','READ','ALLOW','ROLE','salesPerson'),(424,'Docuware','upload','WRITE','ALLOW','ROLE','productionAssi'),(425,'Docuware','deliveryNoteEmail','WRITE','ALLOW','ROLE','salesPerson'),(426,'TpvTransaction','confirm','WRITE','ALLOW','ROLE','$everyone'),(427,'TpvTransaction','start','WRITE','ALLOW','ROLE','$authenticated'),(428,'TpvTransaction','end','WRITE','ALLOW','ROLE','$authenticated'),(429,'ItemConfig','*','READ','ALLOW','ROLE','employee'),(431,'Tag','onSubmit','WRITE','ALLOW','ROLE','employee'),(432,'Worker','updateAttributes','WRITE','ALLOW','ROLE','hr'),(433,'Worker','createAbsence','*','ALLOW','ROLE','employee'),(434,'Worker','updateAbsence','WRITE','ALLOW','ROLE','employee'),(435,'Worker','deleteAbsence','*','ALLOW','ROLE','employee'),(436,'Worker','new','WRITE','ALLOW','ROLE','hr'),(437,'Role','*','READ','ALLOW','ROLE','hr'),(438,'Client','getClientOrSupplierReference','READ','ALLOW','ROLE','employee'),(439,'NotificationSubscription','*','*','ALLOW','ROLE','employee'),(440,'NotificationAcl','*','READ','ALLOW','ROLE','employee'),(441,'MdbApp','*','READ','ALLOW','ROLE','$everyone'),(442,'MdbApp','*','*','ALLOW','ROLE','developer'),(443,'ItemConfig','*','*','ALLOW','ROLE','employee'),(444,'DeviceProduction','*','*','ALLOW','ROLE','hr'),(445,'DeviceProductionModels','*','*','ALLOW','ROLE','hr'),(446,'DeviceProductionState','*','*','ALLOW','ROLE','hr'),(447,'DeviceProductionUser','*','*','ALLOW','ROLE','hr'),(448,'DeviceProduction','*','*','ALLOW','ROLE','productionAssi'),(449,'DeviceProductionModels','*','*','ALLOW','ROLE','productionAssi'),(450,'DeviceProductionState','*','*','ALLOW','ROLE','productionAssi'),(451,'DeviceProductionUser','*','*','ALLOW','ROLE','productionAssi'),(452,'Worker','deallocatePDA','*','ALLOW','ROLE','hr'),(453,'Worker','allocatePDA','*','ALLOW','ROLE','hr'),(454,'Worker','deallocatePDA','*','ALLOW','ROLE','productionAssi'),(455,'Worker','allocatePDA','*','ALLOW','ROLE','productionAssi'),(456,'Zone','*','*','ALLOW','ROLE','deliveryAssistant'),(457,'Account','setPassword','WRITE','ALLOW','ROLE','itManagement'),(458,'Operator','*','READ','ALLOW','ROLE','employee'),(459,'Operator','*','WRITE','ALLOW','ROLE','employee'),(460,'InvoiceIn','getSerial','READ','ALLOW','ROLE','administrative'),(461,'Ticket','saveSign','WRITE','ALLOW','ROLE','employee'),(462,'InvoiceOut','negativeBases','READ','ALLOW','ROLE','administrative'),(463,'InvoiceOut','negativeBasesCsv','READ','ALLOW','ROLE','administrative'),(464,'WorkerObservation','*','*','ALLOW','ROLE','hr'),(465,'ClientInforma','*','READ','ALLOW','ROLE','employee'),(466,'ClientInforma','*','WRITE','ALLOW','ROLE','financial'),(467,'Receipt','receiptEmail','*','ALLOW','ROLE','salesAssistant'),(468,'Client','setRating','WRITE','ALLOW','ROLE','financial'),(469,'Client','*','READ','ALLOW','ROLE','employee'),(470,'Client','addressesPropagateRe','*','ALLOW','ROLE','employee'),(471,'Client','canBeInvoiced','*','ALLOW','ROLE','employee'),(472,'Client','canCreateTicket','*','ALLOW','ROLE','employee'),(473,'Client','consumption','*','ALLOW','ROLE','employee'),(474,'Client','createAddress','*','ALLOW','ROLE','employee'),(475,'Client','createWithUser','*','ALLOW','ROLE','employee'),(476,'Client','extendedListFilter','*','ALLOW','ROLE','employee'),(477,'Client','getAverageInvoiced','*','ALLOW','ROLE','employee'),(478,'Client','getCard','*','ALLOW','ROLE','employee'),(479,'Client','getDebt','*','ALLOW','ROLE','employee'),(480,'Client','getMana','*','ALLOW','ROLE','employee'),(481,'Client','transactions','*','ALLOW','ROLE','employee'),(482,'Client','hasCustomerRole','*','ALLOW','ROLE','employee'),(483,'Client','isValidClient','*','ALLOW','ROLE','employee'),(484,'Client','lastActiveTickets','*','ALLOW','ROLE','employee'),(485,'Client','sendSms','*','ALLOW','ROLE','employee'),(486,'Client','setPassword','*','ALLOW','ROLE','employee'),(487,'Client','summary','*','ALLOW','ROLE','employee'),(488,'Client','updateAddress','*','ALLOW','ROLE','employee'),(489,'Client','updateFiscalData','*','ALLOW','ROLE','employee'),(490,'Client','updateUser','*','ALLOW','ROLE','employee'),(491,'Client','uploadFile','*','ALLOW','ROLE','employee'),(492,'Client','campaignMetricsPdf','*','ALLOW','ROLE','employee'),(493,'Client','campaignMetricsEmail','*','ALLOW','ROLE','employee'),(494,'Client','clientWelcomeHtml','*','ALLOW','ROLE','employee'),(495,'Client','clientWelcomeEmail','*','ALLOW','ROLE','employee'),(496,'Client','printerSetupHtml','*','ALLOW','ROLE','employee'),(497,'Client','printerSetupEmail','*','ALLOW','ROLE','employee'),(498,'Client','sepaCoreEmail','*','ALLOW','ROLE','employee'),(499,'Client','letterDebtorPdf','*','ALLOW','ROLE','employee'),(500,'Client','letterDebtorStHtml','*','ALLOW','ROLE','employee'),(501,'Client','letterDebtorStEmail','*','ALLOW','ROLE','employee'),(502,'Client','letterDebtorNdHtml','*','ALLOW','ROLE','employee'),(503,'Client','letterDebtorNdEmail','*','ALLOW','ROLE','employee'),(504,'Client','clientDebtStatementPdf','*','ALLOW','ROLE','employee'),(505,'Client','clientDebtStatementHtml','*','ALLOW','ROLE','employee'),(506,'Client','clientDebtStatementEmail','*','ALLOW','ROLE','employee'),(507,'Client','creditRequestPdf','*','ALLOW','ROLE','employee'),(508,'Client','creditRequestHtml','*','ALLOW','ROLE','employee'),(509,'Client','creditRequestEmail','*','ALLOW','ROLE','employee'),(510,'Client','incotermsAuthorizationPdf','*','ALLOW','ROLE','employee'),(511,'Client','incotermsAuthorizationHtml','*','ALLOW','ROLE','employee'),(512,'Client','incotermsAuthorizationEmail','*','ALLOW','ROLE','employee'),(513,'Client','consumptionSendQueued','*','ALLOW','ROLE','employee'),(514,'Client','filter','*','ALLOW','ROLE','employee'),(515,'Client','getClientOrSupplierReference','*','ALLOW','ROLE','employee'),(516,'Client','upsert','*','ALLOW','ROLE','employee'),(517,'Client','create','*','ALLOW','ROLE','employee'),(518,'Client','replaceById','*','ALLOW','ROLE','employee'),(519,'Client','updateAttributes','*','ALLOW','ROLE','employee'),(520,'Client','updateAttributes','*','ALLOW','ROLE','employee'),(521,'Client','deleteById','*','ALLOW','ROLE','employee'),(522,'Client','replaceOrCreate','*','ALLOW','ROLE','employee'),(523,'Client','updateAll','*','ALLOW','ROLE','employee'),(524,'Client','upsertWithWhere','*','ALLOW','ROLE','employee'),(525,'Defaulter','observationEmail','WRITE','ALLOW','ROLE','employee'),(526,'VnUser','*','*','ALLOW','ROLE','employee'),(527,'VnUser','acl','READ','ALLOW','ROLE','account'),(528,'VnUser','getCurrentUserData','READ','ALLOW','ROLE','account'),(529,'VnUser','changePassword','WRITE','ALLOW','ROLE','account'),(530,'Account','exists','READ','ALLOW','ROLE','account'),(531,'Account','exists','READ','ALLOW','ROLE','account'),(532,'UserLog','*','READ','ALLOW','ROLE','employee'),(533,'RoleLog','*','READ','ALLOW','ROLE','employee'); /*!40000 ALTER TABLE `ACL` ENABLE KEYS */; UNLOCK TABLES; From 50155cea8d5e3669b5293764f7666f0223a35c9c Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 28 Jul 2023 15:21:43 +0200 Subject: [PATCH 027/427] refs #5914 WIP transfer invoiceOut --- .../233201/00-transferInvoiceOutACL.sql | 6 + db/dump/fixtures.sql | 13 ++ loopback/locale/es.json | 3 +- .../methods/invoiceOut/transferInvoiceOut.js | 81 +++++++++++ modules/invoiceOut/back/model-config.json | 12 ++ .../back/models/cplus-correcting-type.json | 19 +++ .../back/models/cplus-rectification-type.json | 19 +++ .../back/models/invoice-correction-type.json | 19 +++ modules/invoiceOut/back/models/invoice-out.js | 1 + .../back/models/invoiceCorrection.json | 28 ++++ .../front/descriptor-menu/index.html | 89 ++++++++++++ .../invoiceOut/front/descriptor-menu/index.js | 13 ++ .../front/descriptor-menu/locale/en.yml | 2 + .../front/descriptor-menu/locale/es.yml | 2 + modules/ticket/back/methods/sale/clone.js | 76 ++++++++++ .../back/methods/sale/createTicketRefund.js | 25 ++++ modules/ticket/back/methods/sale/refund.js | 137 +++++++++++++++++- 17 files changed, 543 insertions(+), 2 deletions(-) create mode 100644 db/changes/233201/00-transferInvoiceOutACL.sql create mode 100644 modules/invoiceOut/back/methods/invoiceOut/transferInvoiceOut.js create mode 100644 modules/invoiceOut/back/models/cplus-correcting-type.json create mode 100644 modules/invoiceOut/back/models/cplus-rectification-type.json create mode 100644 modules/invoiceOut/back/models/invoice-correction-type.json create mode 100644 modules/invoiceOut/back/models/invoiceCorrection.json create mode 100644 modules/ticket/back/methods/sale/clone.js create mode 100644 modules/ticket/back/methods/sale/createTicketRefund.js diff --git a/db/changes/233201/00-transferInvoiceOutACL.sql b/db/changes/233201/00-transferInvoiceOutACL.sql new file mode 100644 index 000000000..b549e52a8 --- /dev/null +++ b/db/changes/233201/00-transferInvoiceOutACL.sql @@ -0,0 +1,6 @@ +INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) + VALUES + ('CplusRectificationType', '*', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('CplusCorrectingType', '*', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('InvoiceCorrectionType', '*', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('InvoiceOut', 'transferInvoiceOut', 'WRITE', 'ALLOW', 'ROLE', 'employee'); \ No newline at end of file diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index eaa00a3de..0a17e2e42 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -2958,3 +2958,16 @@ INSERT INTO `vn`.`invoiceInSerial` (`code`, `description`, `cplusTerIdNifFk`, `t INSERT INTO `hedera`.`imageConfig` (`id`, `maxSize`, `useXsendfile`, `url`) VALUES (1, 0, 0, 'marvel.com'); + +INSERT INTO `vn`.`cplusCorrectingType` (`description`) + VALUES + ('Embalajes'), + ('Anulación'), + ('Impagado'), + ('Moroso'); + +INSERT INTO `vn`.`invoiceCorrectionType` (`description`) + VALUES + ('Error en el cálculo del IVA'), + ('Error en el detalle de las ventas'), + ('Error en los datos del cliente'); diff --git a/loopback/locale/es.json b/loopback/locale/es.json index ac62d62e1..3439adcde 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -311,5 +311,6 @@ "You don't have enough privileges.": "No tienes suficientes permisos.", "This ticket is locked.": "Este ticket está bloqueado.", "This ticket is not editable.": "Este ticket no es editable.", - "The ticket doesn't exist.": "No existe el ticket." + "The ticket doesn't exist.": "No existe el ticket.", + "There are missing fields.": "There are missing fields." } \ No newline at end of file diff --git a/modules/invoiceOut/back/methods/invoiceOut/transferInvoiceOut.js b/modules/invoiceOut/back/methods/invoiceOut/transferInvoiceOut.js new file mode 100644 index 000000000..b50e4b1a7 --- /dev/null +++ b/modules/invoiceOut/back/methods/invoiceOut/transferInvoiceOut.js @@ -0,0 +1,81 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('transferInvoiceOut', { + description: 'Transfer an invoice out to another client', + accessType: 'WRITE', + accepts: [ + { + arg: 'data', + type: 'Object', + required: true + } + ], + returns: { + type: 'boolean', + root: true + }, + http: { + path: '/transferInvoice', + verb: 'post' + } + }); + + Self.transferInvoiceOut = async(ctx, params, options) => { + const models = Self.app.models; + const myOptions = {}; + let tx; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + try { + const {ref, newClientFk, cplusRectificationId, cplusCorrectingTypeId, invoiceCorrectionTypeId} = params; + if (!ref || !newClientFk || !cplusRectificationId || !cplusCorrectingTypeId || !invoiceCorrectionTypeId) + throw new UserError(`There are missing fields.`); + + const filter = {where: {refFk: ref}}; + const tickets = await models.Ticket.find(filter, myOptions); + const ticketsIds = tickets.map(ticket => ticket.id); + const refundTicket = await models.Ticket.refund(ctx, ticketsIds, null, myOptions); + // Clonar tickets + const refundAgencyMode = await models.AgencyMode.findOne({ + include: { + relation: 'zones', + scope: { + limit: 1, + field: ['id', 'name'] + } + }, + where: {code: 'refund'} + }, myOptions); + const refoundZoneId = refundAgencyMode.zones()[0].id; + const services = await models.TicketService.find(filter, myOptions); + const servicesIds = services.map(service => service.id); + const salesFilter = { + where: {id: {inq: salesIds}}, + include: { + relation: 'components', + scope: { + fields: ['saleFk', 'componentFk', 'value'] + } + } + }; + const sales = await models.Sale.find(salesFilter, myOptions); + // Actualizar cliente + + // Invoice Ticket - Factura rápida ?? + + // Insert InvoiceCorrection + if (tx) await tx.commit(); + } catch (e) { + if (tx) await tx.rollback(); + throw e; + } + return true; + }; +}; diff --git a/modules/invoiceOut/back/model-config.json b/modules/invoiceOut/back/model-config.json index 9e8b119ab..995ea976b 100644 --- a/modules/invoiceOut/back/model-config.json +++ b/modules/invoiceOut/back/model-config.json @@ -31,5 +31,17 @@ }, "ZipConfig": { "dataSource": "vn" + }, + "CplusRectificationType": { + "dataSource": "vn" + }, + "CplusCorrectingType": { + "dataSource": "vn" + }, + "InvoiceCorrectionType": { + "dataSource": "vn" + }, + "InvoiceCorrection": { + "dataSource": "vn" } } diff --git a/modules/invoiceOut/back/models/cplus-correcting-type.json b/modules/invoiceOut/back/models/cplus-correcting-type.json new file mode 100644 index 000000000..660f60008 --- /dev/null +++ b/modules/invoiceOut/back/models/cplus-correcting-type.json @@ -0,0 +1,19 @@ +{ + "name": "CplusCorrectingType", + "base": "VnModel", + "options": { + "mysql": { + "table": "cplusCorrectingType" + } + }, + "properties": { + "id": { + "id": true, + "type": "number", + "description": "Identifier" + }, + "description": { + "type": "string" + } + } +} \ No newline at end of file diff --git a/modules/invoiceOut/back/models/cplus-rectification-type.json b/modules/invoiceOut/back/models/cplus-rectification-type.json new file mode 100644 index 000000000..e7bfb957f --- /dev/null +++ b/modules/invoiceOut/back/models/cplus-rectification-type.json @@ -0,0 +1,19 @@ +{ + "name": "CplusRectificationType", + "base": "VnModel", + "options": { + "mysql": { + "table": "cplusRectificationType" + } + }, + "properties": { + "id": { + "id": true, + "type": "number", + "description": "Identifier" + }, + "description": { + "type": "string" + } + } +} \ No newline at end of file diff --git a/modules/invoiceOut/back/models/invoice-correction-type.json b/modules/invoiceOut/back/models/invoice-correction-type.json new file mode 100644 index 000000000..ad3f034ea --- /dev/null +++ b/modules/invoiceOut/back/models/invoice-correction-type.json @@ -0,0 +1,19 @@ +{ + "name": "InvoiceCorrectionType", + "base": "VnModel", + "options": { + "mysql": { + "table": "invoiceCorrectionType" + } + }, + "properties": { + "id": { + "id": true, + "type": "number", + "description": "Identifier" + }, + "description": { + "type": "string" + } + } +} \ No newline at end of file diff --git a/modules/invoiceOut/back/models/invoice-out.js b/modules/invoiceOut/back/models/invoice-out.js index d3aaf3b3d..0bb31ce12 100644 --- a/modules/invoiceOut/back/models/invoice-out.js +++ b/modules/invoiceOut/back/models/invoice-out.js @@ -23,6 +23,7 @@ module.exports = Self => { require('../methods/invoiceOut/getInvoiceDate')(Self); require('../methods/invoiceOut/negativeBases')(Self); require('../methods/invoiceOut/negativeBasesCsv')(Self); + require('../methods/invoiceOut/transferInvoiceOut')(Self); Self.filePath = async function(id, options) { const fields = ['ref', 'issued']; diff --git a/modules/invoiceOut/back/models/invoiceCorrection.json b/modules/invoiceOut/back/models/invoiceCorrection.json new file mode 100644 index 000000000..48bd172a6 --- /dev/null +++ b/modules/invoiceOut/back/models/invoiceCorrection.json @@ -0,0 +1,28 @@ +{ + "name": "InvoiceCorrection", + "base": "VnModel", + "options": { + "mysql": { + "table": "invoiceCorrection" + } + }, + "properties": { + "correctingFk": { + "id": true, + "type": "number", + "description": "Identifier" + }, + "correctedFk": { + "type": "number" + }, + "cplusRectificationTypeFk": { + "type": "number" + }, + "cplusInvoiceType477Fk": { + "type": "number" + }, + "invoiceCorrectionTypeFk": { + "type": "number" + } + } +} \ No newline at end of file diff --git a/modules/invoiceOut/front/descriptor-menu/index.html b/modules/invoiceOut/front/descriptor-menu/index.html index 106f8e3cc..d6eaa1cc7 100644 --- a/modules/invoiceOut/front/descriptor-menu/index.html +++ b/modules/invoiceOut/front/descriptor-menu/index.html @@ -1,3 +1,19 @@ + + + + + + + + Transfer invoice to... + Confirm + + + + + + + #{{id}} - {{::name}} + + + + + {{::description}} + + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/invoiceOut/front/descriptor-menu/index.js b/modules/invoiceOut/front/descriptor-menu/index.js index 38c3c9434..0b43b73a7 100644 --- a/modules/invoiceOut/front/descriptor-menu/index.js +++ b/modules/invoiceOut/front/descriptor-menu/index.js @@ -125,6 +125,19 @@ class Controller extends Section { this.$state.go('ticket.card.sale', {id: refundTicket.id}); }); } + + transferInvoice() { + const params = { + data: { + ref: this.invoiceOut.ref, + newClientFk: this.invoiceOut.client.id, + cplusRectificationId: this.cplusRectificationType, + cplusCorrectingTypeId: this.cplusCorrectingType, + invoiceCorrectionTypeId: this.invoiceCorrectionType + } + }; + this.$http.post(`InvoiceOuts/transferInvoice`, params).then(res => console.log(res.data)); + } } Controller.$inject = ['$element', '$scope', 'vnReport', 'vnEmail']; diff --git a/modules/invoiceOut/front/descriptor-menu/locale/en.yml b/modules/invoiceOut/front/descriptor-menu/locale/en.yml index d299155d7..8fad5f25e 100644 --- a/modules/invoiceOut/front/descriptor-menu/locale/en.yml +++ b/modules/invoiceOut/front/descriptor-menu/locale/en.yml @@ -1 +1,3 @@ The following refund tickets have been created: "The following refund tickets have been created: {{ticketIds}}" +Transfer invoice to...: Transfer invoice to... +Cplus Type: Cplus Type \ No newline at end of file diff --git a/modules/invoiceOut/front/descriptor-menu/locale/es.yml b/modules/invoiceOut/front/descriptor-menu/locale/es.yml index 393efd58c..0f74b5fec 100644 --- a/modules/invoiceOut/front/descriptor-menu/locale/es.yml +++ b/modules/invoiceOut/front/descriptor-menu/locale/es.yml @@ -21,3 +21,5 @@ The invoice PDF document has been regenerated: El documento PDF de la factura ha The email can't be empty: El correo no puede estar vacío The following refund tickets have been created: "Se han creado los siguientes tickets de abono: {{ticketIds}}" Refund...: Abono... +Transfer invoice to...: Transferir factura a... +Cplus Type: Cplus Tipo diff --git a/modules/ticket/back/methods/sale/clone.js b/modules/ticket/back/methods/sale/clone.js new file mode 100644 index 000000000..1d69ca158 --- /dev/null +++ b/modules/ticket/back/methods/sale/clone.js @@ -0,0 +1,76 @@ +module.exports = async function clone(ctx, Self, sales, refundAgencyMode, refoundZoneId, servicesIds, withWarehouse, group, isRefund, myOptions) { + const models = Self.app.models; + const ticketsIds = [...new Set(sales.map(sale => sale.ticketFk))]; + const [firstTicketId] = ticketsIds; + + const now = Date.vnNew(); + let refundTickets = []; + let refundTicket; + + if (!group) { + for (const ticketId of ticketsIds) { + refundTicket = await createTicketRefund( + ticketId, + now, + refundAgencyMode, + refoundZoneId, + null, + myOptions + ); + refundTickets.push(refundTicket); + } + } else { + refundTicket = await createTicketRefund( + firstTicketId, + now, + refundAgencyMode, + refoundZoneId, + withWarehouse, + myOptions + ); + } + + for (const sale of sales) { + const createdSale = await models.Sale.create({ + ticketFk: (group) ? refundTicket.id : sale.ticketFk, + itemFk: sale.itemFk, + quantity: (isRefund) ? - sale.quantity : sale.quantity, + concept: sale.concept, + price: sale.price, + discount: sale.discount, + }, myOptions); + + const components = sale.components(); + for (const component of components) + component.saleFk = createdSale.id; + + await models.SaleComponent.create(components, myOptions); + } + + if (servicesIds && servicesIds.length > 0) { + const servicesFilter = { + where: {id: {inq: servicesIds}} + }; + const services = await models.TicketService.find(servicesFilter, myOptions); + for (const service of services) { + await models.TicketService.create({ + description: service.description, + quantity: (isRefund) ? - service.quantity : service.quantity, + price: service.price, + taxClassFk: service.taxClassFk, + ticketFk: (group) ? refundTicket.id : service.ticketFk, + ticketServiceTypeFk: service.ticketServiceTypeFk, + }, myOptions); + } + } + + const query = `CALL vn.ticket_recalc(?, NULL)`; + if (refundTickets.length > 0) { + for (const refundTicket of refundTickets) + await Self.rawSql(query, [refundTicket.id], myOptions); + return refundTickets.map(refundTicket => refundTicket.id); + } else { + await Self.rawSql(query, [refundTicket.id], myOptions); + return refundTicket; + } +}; diff --git a/modules/ticket/back/methods/sale/createTicketRefund.js b/modules/ticket/back/methods/sale/createTicketRefund.js new file mode 100644 index 000000000..0ecc62e0c --- /dev/null +++ b/modules/ticket/back/methods/sale/createTicketRefund.js @@ -0,0 +1,25 @@ +module.exports = async function createTicketRefund(models, ticketId, now, refundAgencyMode, refoundZoneId, withWarehouse, myOptions) { + // const models = Self.app.models; + + const filter = {include: {relation: 'address'}}; + const ticket = await models.Ticket.findById(ticketId, filter, myOptions); + + const refundTicket = await models.Ticket.create({ + clientFk: ticket.clientFk, + shipped: now, + addressFk: ticket.address().id, + agencyModeFk: refundAgencyMode.id, + nickname: ticket.address().nickname, + warehouseFk: withWarehouse ? ticket.warehouseFk : null, + companyFk: ticket.companyFk, + landed: now, + zoneFk: refoundZoneId + }, myOptions); + + await models.TicketRefund.create({ + refundTicketFk: refundTicket.id, + originalTicketFk: ticket.id, + }, myOptions); + + return refundTicket; +}; diff --git a/modules/ticket/back/methods/sale/refund.js b/modules/ticket/back/methods/sale/refund.js index a8191610a..fc6d8bbc2 100644 --- a/modules/ticket/back/methods/sale/refund.js +++ b/modules/ticket/back/methods/sale/refund.js @@ -28,7 +28,7 @@ module.exports = Self => { } }); - Self.refund = async(ctx, salesIds, servicesIds, withWarehouse, options) => { + /* Self.refund = async(ctx, salesIds, servicesIds, withWarehouse, options) => { const models = Self.app.models; const myOptions = {userId: ctx.req.accessToken.userId}; let tx; @@ -111,6 +111,64 @@ module.exports = Self => { if (tx) await tx.commit(); + return refundTicket; + } catch (e) { + if (tx) await tx.rollback(); + throw e; + } + }; */ + + Self.refund = async(ctx, salesIds, servicesIds, withWarehouse, options) => { + const models = Self.app.models; + const myOptions = {userId: ctx.req.accessToken.userId}; + let tx; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + try { + const refundAgencyMode = await models.AgencyMode.findOne({ + include: { + relation: 'zones', + scope: { + limit: 1, + field: ['id', 'name'] + } + }, + where: {code: 'refund'} + }, myOptions); + + const refoundZoneId = refundAgencyMode.zones()[0].id; + + const salesFilter = { + where: {id: {inq: salesIds}}, + include: { + relation: 'components', + scope: { + fields: ['saleFk', 'componentFk', 'value'] + } + } + }; + const sales = await models.Sale.find(salesFilter, myOptions); + const group = true; + const isRefund = true; + + const refundTicket = await clone( + sales, + refundAgencyMode, + refoundZoneId, servicesIds, + withWarehouse, + group, + isRefund, + myOptions + ); + if (tx) await tx.commit(); + return refundTicket; } catch (e) { if (tx) await tx.rollback(); @@ -118,6 +176,83 @@ module.exports = Self => { } }; + async function clone(sales, refundAgencyMode, refoundZoneId, servicesIds, withWarehouse, group, isRefund, myOptions) { + const models = Self.app.models; + const ticketsIds = [...new Set(sales.map(sale => sale.ticketFk))]; + const [firstTicketId] = ticketsIds; + + const now = Date.vnNew(); + let refundTickets = []; + let refundTicket; + + if (!group) { + for (const ticketId of ticketsIds) { + refundTicket = await createTicketRefund( + ticketId, + now, + refundAgencyMode, + refoundZoneId, + null, + myOptions + ); + refundTickets.push(refundTicket); + } + } else { + refundTicket = await createTicketRefund( + firstTicketId, + now, + refundAgencyMode, + refoundZoneId, + withWarehouse, + myOptions + ); + } + + for (const sale of sales) { + const createdSale = await models.Sale.create({ + ticketFk: (group) ? refundTicket.id : sale.ticketFk, + itemFk: sale.itemFk, + quantity: (isRefund) ? - sale.quantity : sale.quantity, + concept: sale.concept, + price: sale.price, + discount: sale.discount, + }, myOptions); + + const components = sale.components(); + for (const component of components) + component.saleFk = createdSale.id; + + await models.SaleComponent.create(components, myOptions); + } + + if (servicesIds && servicesIds.length > 0) { + const servicesFilter = { + where: {id: {inq: servicesIds}} + }; + const services = await models.TicketService.find(servicesFilter, myOptions); + for (const service of services) { + await models.TicketService.create({ + description: service.description, + quantity: (isRefund) ? - service.quantity : service.quantity, + price: service.price, + taxClassFk: service.taxClassFk, + ticketFk: (group) ? refundTicket.id : service.ticketFk, + ticketServiceTypeFk: service.ticketServiceTypeFk, + }, myOptions); + } + } + + const query = `CALL vn.ticket_recalc(?, NULL)`; + if (refundTickets.length > 0) { + for (const refundTicket of refundTickets) + await Self.rawSql(query, [refundTicket.id], myOptions); + return refundTickets.map(refundTicket => refundTicket.id); + } else { + await Self.rawSql(query, [refundTicket.id], myOptions); + return refundTicket; + } + } + async function createTicketRefund(ticketId, now, refundAgencyMode, refoundZoneId, withWarehouse, myOptions) { const models = Self.app.models; From 22f76ec6a943282c8e870e54f17b2cebe79f1d5a Mon Sep 17 00:00:00 2001 From: jorgep Date: Mon, 31 Jul 2023 10:33:51 +0200 Subject: [PATCH 028/427] refs #5914 WIP clone method created --- .../233201/00-transferInvoiceOutACL.sql | 2 +- .../methods/invoiceOut/transferInvoiceOut.js | 31 ++++- modules/invoiceOut/back/model-config.json | 6 +- ...-type.json => cplus-invoice-type-477.json} | 4 +- .../front/descriptor-menu/index.html | 10 +- .../invoiceOut/front/descriptor-menu/index.js | 3 +- modules/ticket/back/methods/sale/clone.js | 127 ++++++++---------- .../back/methods/sale/createTicketRefund.js | 25 ---- modules/ticket/back/methods/sale/refund.js | 71 +++++----- modules/ticket/back/models/sale.js | 1 + 10 files changed, 129 insertions(+), 151 deletions(-) rename modules/invoiceOut/back/models/{cplus-correcting-type.json => cplus-invoice-type-477.json} (78%) delete mode 100644 modules/ticket/back/methods/sale/createTicketRefund.js diff --git a/db/changes/233201/00-transferInvoiceOutACL.sql b/db/changes/233201/00-transferInvoiceOutACL.sql index b549e52a8..6e8d88c5d 100644 --- a/db/changes/233201/00-transferInvoiceOutACL.sql +++ b/db/changes/233201/00-transferInvoiceOutACL.sql @@ -1,6 +1,6 @@ INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) VALUES ('CplusRectificationType', '*', 'READ', 'ALLOW', 'ROLE', 'employee'), - ('CplusCorrectingType', '*', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('CplusInvoiceType477', '*', 'READ', 'ALLOW', 'ROLE', 'employee'), ('InvoiceCorrectionType', '*', 'READ', 'ALLOW', 'ROLE', 'employee'), ('InvoiceOut', 'transferInvoiceOut', 'WRITE', 'ALLOW', 'ROLE', 'employee'); \ No newline at end of file diff --git a/modules/invoiceOut/back/methods/invoiceOut/transferInvoiceOut.js b/modules/invoiceOut/back/methods/invoiceOut/transferInvoiceOut.js index b50e4b1a7..d53581ac6 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/transferInvoiceOut.js +++ b/modules/invoiceOut/back/methods/invoiceOut/transferInvoiceOut.js @@ -34,15 +34,17 @@ module.exports = Self => { myOptions.transaction = tx; } try { - const {ref, newClientFk, cplusRectificationId, cplusCorrectingTypeId, invoiceCorrectionTypeId} = params; - if (!ref || !newClientFk || !cplusRectificationId || !cplusCorrectingTypeId || !invoiceCorrectionTypeId) + const {id, ref, newClientFk, cplusRectificationId, cplusInvoiceType477FkId, invoiceCorrectionTypeId} = params; + if (!id || !ref || !newClientFk || !cplusRectificationId || !cplusInvoiceType477FkId || !invoiceCorrectionTypeId) throw new UserError(`There are missing fields.`); + // Refund tickets and group const filter = {where: {refFk: ref}}; const tickets = await models.Ticket.find(filter, myOptions); const ticketsIds = tickets.map(ticket => ticket.id); - const refundTicket = await models.Ticket.refund(ctx, ticketsIds, null, myOptions); - // Clonar tickets + await models.Ticket.refund(ctx, ticketsIds, null, myOptions); + + // Clone tickets const refundAgencyMode = await models.AgencyMode.findOne({ include: { relation: 'zones', @@ -66,11 +68,28 @@ module.exports = Self => { } }; const sales = await models.Sale.find(salesFilter, myOptions); - // Actualizar cliente + const isRefund = false; + const clonedTicketIds = await models.Sale.clone(sales, refundAgencyMode, refoundZoneId, servicesIds, null, isRefund, myOptions); - // Invoice Ticket - Factura rápida ?? + // Update client + for (const clonedTicketId of clonedTicketIds) { + const ticket = await models.Ticket.findById(clonedTicketId, myOptions); + await ticket.updateAttributes({clientFk: newClientFk}); + } + // Quick invoice + const invoiceIds = await models.Ticket.invoiceTickets(ctx, clonedTicketIds, myOptions); // Insert InvoiceCorrection + for (const invoiceId of invoiceIds) { + await models.invoiceCorrection.create({ + correctingFk: invoiceId, + correctedFk: id, + cplusRectificationTypeFk: cplusRectificationId, + cplusInvoiceType477Fk: cplusInvoiceType477FkId, + invoiceCorrectionType: invoiceCorrectionTypeId + }); + } + if (tx) await tx.commit(); } catch (e) { if (tx) await tx.rollback(); diff --git a/modules/invoiceOut/back/model-config.json b/modules/invoiceOut/back/model-config.json index 995ea976b..23246893b 100644 --- a/modules/invoiceOut/back/model-config.json +++ b/modules/invoiceOut/back/model-config.json @@ -35,13 +35,13 @@ "CplusRectificationType": { "dataSource": "vn" }, - "CplusCorrectingType": { - "dataSource": "vn" - }, "InvoiceCorrectionType": { "dataSource": "vn" }, "InvoiceCorrection": { "dataSource": "vn" + }, + "CplusInvoiceType477": { + "dataSource": "vn" } } diff --git a/modules/invoiceOut/back/models/cplus-correcting-type.json b/modules/invoiceOut/back/models/cplus-invoice-type-477.json similarity index 78% rename from modules/invoiceOut/back/models/cplus-correcting-type.json rename to modules/invoiceOut/back/models/cplus-invoice-type-477.json index 660f60008..840a9a7e4 100644 --- a/modules/invoiceOut/back/models/cplus-correcting-type.json +++ b/modules/invoiceOut/back/models/cplus-invoice-type-477.json @@ -1,9 +1,9 @@ { - "name": "CplusCorrectingType", + "name": "CplusInvoiceType477", "base": "VnModel", "options": { "mysql": { - "table": "cplusCorrectingType" + "table": "cplusInvoiceType477" } }, "properties": { diff --git a/modules/invoiceOut/front/descriptor-menu/index.html b/modules/invoiceOut/front/descriptor-menu/index.html index d6eaa1cc7..1655290f4 100644 --- a/modules/invoiceOut/front/descriptor-menu/index.html +++ b/modules/invoiceOut/front/descriptor-menu/index.html @@ -6,8 +6,8 @@ + url="CplusInvoiceType477s" + data="cplusInvoiceType477"> sale.ticketFk))]; - const [firstTicketId] = ticketsIds; +module.exports = Self => { + Self.clone = async(sales, refundAgencyMode, refoundZoneId, servicesIds, withWarehouse, isRefund, myOptions) => { + const models = Self.app.models; + const ticketsIds = [...new Set(sales.map(sale => sale.ticketFk))]; - const now = Date.vnNew(); - let refundTickets = []; - let refundTicket; + const now = Date.vnNew(); + let updatedTickets = []; - if (!group) { for (const ticketId of ticketsIds) { - refundTicket = await createTicketRefund( - ticketId, - now, - refundAgencyMode, - refoundZoneId, - null, - myOptions - ); - refundTickets.push(refundTicket); - } - } else { - refundTicket = await createTicketRefund( - firstTicketId, - now, - refundAgencyMode, - refoundZoneId, - withWarehouse, - myOptions - ); - } + const filter = {include: {relation: 'address'}}; + const ticket = await models.Ticket.findById(ticketId, filter, myOptions); - for (const sale of sales) { - const createdSale = await models.Sale.create({ - ticketFk: (group) ? refundTicket.id : sale.ticketFk, - itemFk: sale.itemFk, - quantity: (isRefund) ? - sale.quantity : sale.quantity, - concept: sale.concept, - price: sale.price, - discount: sale.discount, - }, myOptions); - - const components = sale.components(); - for (const component of components) - component.saleFk = createdSale.id; - - await models.SaleComponent.create(components, myOptions); - } - - if (servicesIds && servicesIds.length > 0) { - const servicesFilter = { - where: {id: {inq: servicesIds}} - }; - const services = await models.TicketService.find(servicesFilter, myOptions); - for (const service of services) { - await models.TicketService.create({ - description: service.description, - quantity: (isRefund) ? - service.quantity : service.quantity, - price: service.price, - taxClassFk: service.taxClassFk, - ticketFk: (group) ? refundTicket.id : service.ticketFk, - ticketServiceTypeFk: service.ticketServiceTypeFk, + const ticketUpdated = await models.Ticket.create({ + clientFk: ticket.clientFk, + shipped: now, + addressFk: ticket.address().id, + agencyModeFk: refundAgencyMode.id, + nickname: ticket.address().nickname, + warehouseFk: withWarehouse ? ticket.warehouseFk : null, + companyFk: ticket.companyFk, + landed: now, + zoneFk: refoundZoneId }, myOptions); + updatedTickets.push(ticketUpdated); } - } - const query = `CALL vn.ticket_recalc(?, NULL)`; - if (refundTickets.length > 0) { - for (const refundTicket of refundTickets) - await Self.rawSql(query, [refundTicket.id], myOptions); - return refundTickets.map(refundTicket => refundTicket.id); - } else { - await Self.rawSql(query, [refundTicket.id], myOptions); - return refundTicket; - } + for (const sale of sales) { + const createdSale = await models.Sale.create({ + ticketFk: sale.ticketFk, + itemFk: sale.itemFk, + quantity: (isRefund) ? - sale.quantity : sale.quantity, + concept: sale.concept, + price: sale.price, + discount: sale.discount, + }, myOptions); + + const components = sale.components(); + for (const component of components) + component.saleFk = createdSale.id; + + await models.SaleComponent.create(components, myOptions); + } + + if (servicesIds && servicesIds.length > 0) { + const servicesFilter = { + where: {id: {inq: servicesIds}} + }; + const services = await models.TicketService.find(servicesFilter, myOptions); + for (const service of services) { + await models.TicketService.create({ + description: service.description, + quantity: (isRefund) ? - service.quantity : service.quantity, + price: service.price, + taxClassFk: service.taxClassFk, + ticketFk: service.ticketFk, + ticketServiceTypeFk: service.ticketServiceTypeFk, + }, myOptions); + } + } + + const query = `CALL vn.ticket_recalc(?, NULL)`; + + for (const updatedTicket of updatedTickets) + await Self.rawSql(query, [updatedTicket.id], myOptions); + return updatedTickets.map(updatedTicket => updatedTicket.id); + }; }; diff --git a/modules/ticket/back/methods/sale/createTicketRefund.js b/modules/ticket/back/methods/sale/createTicketRefund.js deleted file mode 100644 index 0ecc62e0c..000000000 --- a/modules/ticket/back/methods/sale/createTicketRefund.js +++ /dev/null @@ -1,25 +0,0 @@ -module.exports = async function createTicketRefund(models, ticketId, now, refundAgencyMode, refoundZoneId, withWarehouse, myOptions) { - // const models = Self.app.models; - - const filter = {include: {relation: 'address'}}; - const ticket = await models.Ticket.findById(ticketId, filter, myOptions); - - const refundTicket = await models.Ticket.create({ - clientFk: ticket.clientFk, - shipped: now, - addressFk: ticket.address().id, - agencyModeFk: refundAgencyMode.id, - nickname: ticket.address().nickname, - warehouseFk: withWarehouse ? ticket.warehouseFk : null, - companyFk: ticket.companyFk, - landed: now, - zoneFk: refoundZoneId - }, myOptions); - - await models.TicketRefund.create({ - refundTicketFk: refundTicket.id, - originalTicketFk: ticket.id, - }, myOptions); - - return refundTicket; -}; diff --git a/modules/ticket/back/methods/sale/refund.js b/modules/ticket/back/methods/sale/refund.js index fc6d8bbc2..6bb131e4d 100644 --- a/modules/ticket/back/methods/sale/refund.js +++ b/modules/ticket/back/methods/sale/refund.js @@ -158,10 +158,11 @@ module.exports = Self => { const group = true; const isRefund = true; - const refundTicket = await clone( + const refundTicket = await cloneAndGroup( sales, refundAgencyMode, - refoundZoneId, servicesIds, + refoundZoneId, + servicesIds, withWarehouse, group, isRefund, @@ -176,41 +177,37 @@ module.exports = Self => { } }; - async function clone(sales, refundAgencyMode, refoundZoneId, servicesIds, withWarehouse, group, isRefund, myOptions) { - const models = Self.app.models; + async function cloneAndGroup(sales, refundAgencyMode, refoundZoneId, servicesIds, withWarehouse, group, isRefund, myOptions) { + if (!group) { + const tickets = await models.Sale.clone(sales, + refundAgencyMode, + refoundZoneId, servicesIds, + withWarehouse, + isRefund, + myOptions); + return tickets; + } + const ticketsIds = [...new Set(sales.map(sale => sale.ticketFk))]; const [firstTicketId] = ticketsIds; + const filter = {include: {relation: 'address'}}; + const ticket = await models.Ticket.findById(firstTicketId, filter, myOptions); - const now = Date.vnNew(); - let refundTickets = []; - let refundTicket; - - if (!group) { - for (const ticketId of ticketsIds) { - refundTicket = await createTicketRefund( - ticketId, - now, - refundAgencyMode, - refoundZoneId, - null, - myOptions - ); - refundTickets.push(refundTicket); - } - } else { - refundTicket = await createTicketRefund( - firstTicketId, - now, - refundAgencyMode, - refoundZoneId, - withWarehouse, - myOptions - ); - } + const ticketUpdated = await models.Ticket.create({ + clientFk: ticket.clientFk, + shipped: now, + addressFk: ticket.address().id, + agencyModeFk: refundAgencyMode.id, + nickname: ticket.address().nickname, + warehouseFk: withWarehouse ? ticket.warehouseFk : null, + companyFk: ticket.companyFk, + landed: now, + zoneFk: refoundZoneId + }, myOptions); for (const sale of sales) { const createdSale = await models.Sale.create({ - ticketFk: (group) ? refundTicket.id : sale.ticketFk, + ticketFk: ticketUpdated.id, itemFk: sale.itemFk, quantity: (isRefund) ? - sale.quantity : sale.quantity, concept: sale.concept, @@ -236,21 +233,15 @@ module.exports = Self => { quantity: (isRefund) ? - service.quantity : service.quantity, price: service.price, taxClassFk: service.taxClassFk, - ticketFk: (group) ? refundTicket.id : service.ticketFk, + ticketFk: ticketUpdated.id, ticketServiceTypeFk: service.ticketServiceTypeFk, }, myOptions); } } const query = `CALL vn.ticket_recalc(?, NULL)`; - if (refundTickets.length > 0) { - for (const refundTicket of refundTickets) - await Self.rawSql(query, [refundTicket.id], myOptions); - return refundTickets.map(refundTicket => refundTicket.id); - } else { - await Self.rawSql(query, [refundTicket.id], myOptions); - return refundTicket; - } + await Self.rawSql(query, [refundTicket.id], myOptions); + return ticketUpdated; } async function createTicketRefund(ticketId, now, refundAgencyMode, refoundZoneId, withWarehouse, myOptions) { diff --git a/modules/ticket/back/models/sale.js b/modules/ticket/back/models/sale.js index bab201fdd..e65c98fea 100644 --- a/modules/ticket/back/models/sale.js +++ b/modules/ticket/back/models/sale.js @@ -10,6 +10,7 @@ module.exports = Self => { require('../methods/sale/refund')(Self); require('../methods/sale/canEdit')(Self); require('../methods/sale/usesMana')(Self); + require('../methods/sale/clone')(Self); Self.validatesPresenceOf('concept', { message: `Concept cannot be blank` From 3ef74cab5c00ee70ebc8ad78e15a5b0f40145f59 Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 1 Aug 2023 12:45:57 +0200 Subject: [PATCH 029/427] refs #5914 WIP created transferInvoiceOut --- .../methods/invoiceOut/transferInvoiceOut.js | 66 +++++--- .../front/descriptor-menu/index.html | 3 +- .../invoiceOut/front/descriptor-menu/index.js | 14 +- modules/ticket/back/methods/sale/clone.js | 151 +++++++++++------- modules/ticket/back/methods/sale/refund.js | 87 ++-------- .../back/methods/sale/specs/refund.spec.js | 2 +- modules/ticket/back/methods/ticket/refund.js | 1 - modules/ticket/back/models/ticket.json | 5 + 8 files changed, 161 insertions(+), 168 deletions(-) diff --git a/modules/invoiceOut/back/methods/invoiceOut/transferInvoiceOut.js b/modules/invoiceOut/back/methods/invoiceOut/transferInvoiceOut.js index d53581ac6..86de59e9d 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/transferInvoiceOut.js +++ b/modules/invoiceOut/back/methods/invoiceOut/transferInvoiceOut.js @@ -6,10 +6,35 @@ module.exports = Self => { accessType: 'WRITE', accepts: [ { - arg: 'data', - type: 'Object', + arg: 'id', + type: 'number', required: true - } + }, + { + arg: 'ref', + type: 'string', + required: true + }, + { + arg: 'newClientFk', + type: 'number', + required: true + }, + { + arg: 'cplusRectificationId', + type: 'number', + required: true + }, + { + arg: 'cplusInvoiceType477Id', + type: 'number', + required: true + }, + { + arg: 'invoiceCorrectionTypeId', + type: 'number', + required: true + }, ], returns: { type: 'boolean', @@ -21,7 +46,7 @@ module.exports = Self => { } }); - Self.transferInvoiceOut = async(ctx, params, options) => { + Self.transferInvoiceOut = async(ctx, id, ref, newClientFk, cplusRectificationId, cplusInvoiceType477Id, invoiceCorrectionTypeId, options) => { const models = Self.app.models; const myOptions = {}; let tx; @@ -34,16 +59,12 @@ module.exports = Self => { myOptions.transaction = tx; } try { - const {id, ref, newClientFk, cplusRectificationId, cplusInvoiceType477FkId, invoiceCorrectionTypeId} = params; - if (!id || !ref || !newClientFk || !cplusRectificationId || !cplusInvoiceType477FkId || !invoiceCorrectionTypeId) - throw new UserError(`There are missing fields.`); - // Refund tickets and group const filter = {where: {refFk: ref}}; const tickets = await models.Ticket.find(filter, myOptions); const ticketsIds = tickets.map(ticket => ticket.id); await models.Ticket.refund(ctx, ticketsIds, null, myOptions); - + console.log('Ticket refunded'); // Clone tickets const refundAgencyMode = await models.AgencyMode.findOne({ include: { @@ -58,25 +79,20 @@ module.exports = Self => { const refoundZoneId = refundAgencyMode.zones()[0].id; const services = await models.TicketService.find(filter, myOptions); const servicesIds = services.map(service => service.id); - const salesFilter = { - where: {id: {inq: salesIds}}, - include: { - relation: 'components', - scope: { - fields: ['saleFk', 'componentFk', 'value'] - } - } - }; + const salesFilter = {where: {ticketFk: {inq: ticketsIds}}}; const sales = await models.Sale.find(salesFilter, myOptions); - const isRefund = false; - const clonedTicketIds = await models.Sale.clone(sales, refundAgencyMode, refoundZoneId, servicesIds, null, isRefund, myOptions); - + const clonedTickets = await models.Sale.clone(sales, refundAgencyMode, refoundZoneId, servicesIds, null, false, false, myOptions); + console.log('cloned tickets'); // Update client - for (const clonedTicketId of clonedTicketIds) { - const ticket = await models.Ticket.findById(clonedTicketId, myOptions); - await ticket.updateAttributes({clientFk: newClientFk}); + for (const clonedTicket of clonedTickets) { + // const ticket = await models.Ticket.findById(clonedTicketId, myOptions); + console.log(clonedTicket); + await clonedTicket.updateAttributes({clientFk: newClientFk}, myOptions); + console.log(clonedTicket); } // Quick invoice + const clonedTicketIds = clonedTickets.map(clonedTicket => clonedTicket.id); + console.log(clonedTicketIds); const invoiceIds = await models.Ticket.invoiceTickets(ctx, clonedTicketIds, myOptions); // Insert InvoiceCorrection @@ -85,7 +101,7 @@ module.exports = Self => { correctingFk: invoiceId, correctedFk: id, cplusRectificationTypeFk: cplusRectificationId, - cplusInvoiceType477Fk: cplusInvoiceType477FkId, + cplusInvoiceType477Fk: cplusInvoiceType477Id, invoiceCorrectionType: invoiceCorrectionTypeId }); } diff --git a/modules/invoiceOut/front/descriptor-menu/index.html b/modules/invoiceOut/front/descriptor-menu/index.html index 1655290f4..dc5c2a8e9 100644 --- a/modules/invoiceOut/front/descriptor-menu/index.html +++ b/modules/invoiceOut/front/descriptor-menu/index.html @@ -222,12 +222,13 @@ console.log(res.data)); } diff --git a/modules/ticket/back/methods/sale/clone.js b/modules/ticket/back/methods/sale/clone.js index 96e66de2c..e1793d088 100644 --- a/modules/ticket/back/methods/sale/clone.js +++ b/modules/ticket/back/methods/sale/clone.js @@ -1,67 +1,104 @@ module.exports = Self => { - Self.clone = async(sales, refundAgencyMode, refoundZoneId, servicesIds, withWarehouse, isRefund, myOptions) => { + Self.clone = async(sales, refundAgencyMode, refoundZoneId, servicesIds, withWarehouse, group, negative, myOptions) => { const models = Self.app.models; - const ticketsIds = [...new Set(sales.map(sale => sale.ticketFk))]; + let tx; + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + const ticketsIds = [...new Set(sales.map(sale => sale.ticketFk))]; + const [firstTicketId] = ticketsIds; const now = Date.vnNew(); let updatedTickets = []; + let newTicket; + const filter = { + include: [ + {relation: 'address'}, + { + relation: 'sale', + inq: sales, + }, + ] + }; + try { + for (const [index, ticketId] of ticketsIds.entries()) { + const ticket = await models.Ticket.findById(ticketId, filter, myOptions); + if (!group || !index) { + newTicket = await models.Ticket.create({ + clientFk: ticket.clientFk, + shipped: now, + addressFk: ticket.address().id, + agencyModeFk: refundAgencyMode.id, + nickname: ticket.address().nickname, + warehouseFk: withWarehouse ? ticket.warehouseFk : null, + companyFk: ticket.companyFk, + landed: now, + zoneFk: refoundZoneId + }, myOptions); + updatedTickets.push(newTicket); + } + const sales = ticket.sale(); + const saleIds = sales.map(sale => sale.id); + const saleComponentsFilter = { + where: {saleFk: {inq: saleIds}}, + scope: { + fields: ['saleFk', 'componentFk', 'value'] + } + }; + for (const sale of sales) { + const createdSale = await models.Sale.create({ + ticketFk: newTicket.id, + itemFk: sale.itemFk, + quantity: (negative) ? - sale.quantity : sale.quantity, + concept: sale.concept, + price: sale.price, + discount: sale.discount, + }, myOptions); + const components = await models.SaleComponent.find(saleComponentsFilter, myOptions); + // const components = sale.components(); + for (const component of components) + component.saleFk = createdSale.id; - for (const ticketId of ticketsIds) { - const filter = {include: {relation: 'address'}}; - const ticket = await models.Ticket.findById(ticketId, filter, myOptions); - - const ticketUpdated = await models.Ticket.create({ - clientFk: ticket.clientFk, - shipped: now, - addressFk: ticket.address().id, - agencyModeFk: refundAgencyMode.id, - nickname: ticket.address().nickname, - warehouseFk: withWarehouse ? ticket.warehouseFk : null, - companyFk: ticket.companyFk, - landed: now, - zoneFk: refoundZoneId - }, myOptions); - updatedTickets.push(ticketUpdated); - } - - for (const sale of sales) { - const createdSale = await models.Sale.create({ - ticketFk: sale.ticketFk, - itemFk: sale.itemFk, - quantity: (isRefund) ? - sale.quantity : sale.quantity, - concept: sale.concept, - price: sale.price, - discount: sale.discount, - }, myOptions); - - const components = sale.components(); - for (const component of components) - component.saleFk = createdSale.id; - - await models.SaleComponent.create(components, myOptions); - } - - if (servicesIds && servicesIds.length > 0) { - const servicesFilter = { - where: {id: {inq: servicesIds}} - }; - const services = await models.TicketService.find(servicesFilter, myOptions); - for (const service of services) { - await models.TicketService.create({ - description: service.description, - quantity: (isRefund) ? - service.quantity : service.quantity, - price: service.price, - taxClassFk: service.taxClassFk, - ticketFk: service.ticketFk, - ticketServiceTypeFk: service.ticketServiceTypeFk, - }, myOptions); + await models.SaleComponent.create(components, myOptions); + } } + if (servicesIds && servicesIds.length > 0) { + const servicesFilter = { + where: {id: {inq: servicesIds}} + }; + const services = await models.TicketService.find(servicesFilter, myOptions); + for (const service of services) { + await models.TicketService.create({ + description: service.description, + quantity: (negative) ? - service.quantity : service.quantity, + price: service.price, + taxClassFk: service.taxClassFk, + ticketFk: service.ticketFk, + ticketServiceTypeFk: service.ticketServiceTypeFk, + }, myOptions); + } + } + + const query = `CALL vn.ticket_recalc(?, NULL)`; + + if (group) { + await Self.rawSql(query, [newTicket.id], myOptions); + if (tx) await tx.commit(); + return { + refundTicket: newTicket, + originalTicketFk: firstTicketId + }; + } else { + for (const updatedTicket of updatedTickets) + await Self.rawSql(query, [updatedTicket.id], myOptions); + if (tx) await tx.commit(); + return updatedTickets/* updatedTickets.map(updatedTicket => updatedTicket.id) */; + } + } catch (e) { + if (tx) await tx.rollback(); + throw e; } - - const query = `CALL vn.ticket_recalc(?, NULL)`; - - for (const updatedTicket of updatedTickets) - await Self.rawSql(query, [updatedTicket.id], myOptions); - return updatedTickets.map(updatedTicket => updatedTicket.id); }; }; diff --git a/modules/ticket/back/methods/sale/refund.js b/modules/ticket/back/methods/sale/refund.js index 6bb131e4d..c85bcd834 100644 --- a/modules/ticket/back/methods/sale/refund.js +++ b/modules/ticket/back/methods/sale/refund.js @@ -155,19 +155,23 @@ module.exports = Self => { } }; const sales = await models.Sale.find(salesFilter, myOptions); - const group = true; - const isRefund = true; - - const refundTicket = await cloneAndGroup( + const clonedTicket = await models.Sale.clone( sales, refundAgencyMode, refoundZoneId, servicesIds, withWarehouse, - group, - isRefund, + true, + true, myOptions ); + + const refundTicket = clonedTicket.refundTicket; + + await models.TicketRefund.create({ + refundTicketFk: refundTicket.id, + originalTicketFk: clonedTicket.originalTicketFk, + }, myOptions); if (tx) await tx.commit(); return refundTicket; @@ -177,74 +181,7 @@ module.exports = Self => { } }; - async function cloneAndGroup(sales, refundAgencyMode, refoundZoneId, servicesIds, withWarehouse, group, isRefund, myOptions) { - if (!group) { - const tickets = await models.Sale.clone(sales, - refundAgencyMode, - refoundZoneId, servicesIds, - withWarehouse, - isRefund, - myOptions); - return tickets; - } - - const ticketsIds = [...new Set(sales.map(sale => sale.ticketFk))]; - const [firstTicketId] = ticketsIds; - const filter = {include: {relation: 'address'}}; - const ticket = await models.Ticket.findById(firstTicketId, filter, myOptions); - - const ticketUpdated = await models.Ticket.create({ - clientFk: ticket.clientFk, - shipped: now, - addressFk: ticket.address().id, - agencyModeFk: refundAgencyMode.id, - nickname: ticket.address().nickname, - warehouseFk: withWarehouse ? ticket.warehouseFk : null, - companyFk: ticket.companyFk, - landed: now, - zoneFk: refoundZoneId - }, myOptions); - - for (const sale of sales) { - const createdSale = await models.Sale.create({ - ticketFk: ticketUpdated.id, - itemFk: sale.itemFk, - quantity: (isRefund) ? - sale.quantity : sale.quantity, - concept: sale.concept, - price: sale.price, - discount: sale.discount, - }, myOptions); - - const components = sale.components(); - for (const component of components) - component.saleFk = createdSale.id; - - await models.SaleComponent.create(components, myOptions); - } - - if (servicesIds && servicesIds.length > 0) { - const servicesFilter = { - where: {id: {inq: servicesIds}} - }; - const services = await models.TicketService.find(servicesFilter, myOptions); - for (const service of services) { - await models.TicketService.create({ - description: service.description, - quantity: (isRefund) ? - service.quantity : service.quantity, - price: service.price, - taxClassFk: service.taxClassFk, - ticketFk: ticketUpdated.id, - ticketServiceTypeFk: service.ticketServiceTypeFk, - }, myOptions); - } - } - - const query = `CALL vn.ticket_recalc(?, NULL)`; - await Self.rawSql(query, [refundTicket.id], myOptions); - return ticketUpdated; - } - - async function createTicketRefund(ticketId, now, refundAgencyMode, refoundZoneId, withWarehouse, myOptions) { + /* async function createTicketRefund(ticketId, now, refundAgencyMode, refoundZoneId, withWarehouse, myOptions) { const models = Self.app.models; const filter = {include: {relation: 'address'}}; @@ -268,5 +205,5 @@ module.exports = Self => { }, myOptions); return refundTicket; - } + } */ }; diff --git a/modules/ticket/back/methods/sale/specs/refund.spec.js b/modules/ticket/back/methods/sale/specs/refund.spec.js index b81f7f84d..727ce2fac 100644 --- a/modules/ticket/back/methods/sale/specs/refund.spec.js +++ b/modules/ticket/back/methods/sale/specs/refund.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); -describe('Sale refund()', () => { +fdescribe('Sale refund()', () => { const userId = 5; const ctx = {req: {accessToken: userId}}; const activeCtx = { diff --git a/modules/ticket/back/methods/ticket/refund.js b/modules/ticket/back/methods/ticket/refund.js index c99b6aa83..758384ae2 100644 --- a/modules/ticket/back/methods/ticket/refund.js +++ b/modules/ticket/back/methods/ticket/refund.js @@ -39,7 +39,6 @@ module.exports = Self => { try { const filter = {where: {ticketFk: {inq: ticketsIds}}}; - const sales = await models.Sale.find(filter, myOptions); const salesIds = sales.map(sale => sale.id); diff --git a/modules/ticket/back/models/ticket.json b/modules/ticket/back/models/ticket.json index ec4193bed..1c5610a2a 100644 --- a/modules/ticket/back/models/ticket.json +++ b/modules/ticket/back/models/ticket.json @@ -136,6 +136,11 @@ "type": "belongsTo", "model": "Zone", "foreignKey": "zoneFk" + }, + "sale": { + "type": "hasMany", + "model": "Sale", + "foreignKey": "ticketFk" } } } From bd122e6327024b2ad885cfcd340d9bcb2f5e42e5 Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 1 Aug 2023 16:13:24 +0200 Subject: [PATCH 030/427] refs #5014 WIP trasactions added --- .../methods/invoiceOut/transferInvoiceOut.js | 17 +++++------------ ...orrection.json => invoice-correction.json} | 0 modules/ticket/back/methods/sale/clone.js | 19 ++++++++++--------- modules/ticket/back/methods/sale/refund.js | 14 ++++++++------ 4 files changed, 23 insertions(+), 27 deletions(-) rename modules/invoiceOut/back/models/{invoiceCorrection.json => invoice-correction.json} (100%) diff --git a/modules/invoiceOut/back/methods/invoiceOut/transferInvoiceOut.js b/modules/invoiceOut/back/methods/invoiceOut/transferInvoiceOut.js index 86de59e9d..e059aa431 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/transferInvoiceOut.js +++ b/modules/invoiceOut/back/methods/invoiceOut/transferInvoiceOut.js @@ -48,7 +48,7 @@ module.exports = Self => { Self.transferInvoiceOut = async(ctx, id, ref, newClientFk, cplusRectificationId, cplusInvoiceType477Id, invoiceCorrectionTypeId, options) => { const models = Self.app.models; - const myOptions = {}; + const myOptions = {userId: ctx.req.accessToken.userId}; let tx; if (typeof options == 'object') @@ -64,7 +64,6 @@ module.exports = Self => { const tickets = await models.Ticket.find(filter, myOptions); const ticketsIds = tickets.map(ticket => ticket.id); await models.Ticket.refund(ctx, ticketsIds, null, myOptions); - console.log('Ticket refunded'); // Clone tickets const refundAgencyMode = await models.AgencyMode.findOne({ include: { @@ -82,22 +81,17 @@ module.exports = Self => { const salesFilter = {where: {ticketFk: {inq: ticketsIds}}}; const sales = await models.Sale.find(salesFilter, myOptions); const clonedTickets = await models.Sale.clone(sales, refundAgencyMode, refoundZoneId, servicesIds, null, false, false, myOptions); - console.log('cloned tickets'); // Update client - for (const clonedTicket of clonedTickets) { - // const ticket = await models.Ticket.findById(clonedTicketId, myOptions); - console.log(clonedTicket); + for (const clonedTicket of clonedTickets) await clonedTicket.updateAttributes({clientFk: newClientFk}, myOptions); - console.log(clonedTicket); - } + // Quick invoice const clonedTicketIds = clonedTickets.map(clonedTicket => clonedTicket.id); - console.log(clonedTicketIds); const invoiceIds = await models.Ticket.invoiceTickets(ctx, clonedTicketIds, myOptions); // Insert InvoiceCorrection for (const invoiceId of invoiceIds) { - await models.invoiceCorrection.create({ + await models.InvoiceCorrection.create({ correctingFk: invoiceId, correctedFk: id, cplusRectificationTypeFk: cplusRectificationId, @@ -105,12 +99,11 @@ module.exports = Self => { invoiceCorrectionType: invoiceCorrectionTypeId }); } - if (tx) await tx.commit(); + return true; } catch (e) { if (tx) await tx.rollback(); throw e; } - return true; }; }; diff --git a/modules/invoiceOut/back/models/invoiceCorrection.json b/modules/invoiceOut/back/models/invoice-correction.json similarity index 100% rename from modules/invoiceOut/back/models/invoiceCorrection.json rename to modules/invoiceOut/back/models/invoice-correction.json diff --git a/modules/ticket/back/methods/sale/clone.js b/modules/ticket/back/methods/sale/clone.js index e1793d088..dae15d7df 100644 --- a/modules/ticket/back/methods/sale/clone.js +++ b/modules/ticket/back/methods/sale/clone.js @@ -1,8 +1,12 @@ module.exports = Self => { - Self.clone = async(sales, refundAgencyMode, refoundZoneId, servicesIds, withWarehouse, group, negative, myOptions) => { + Self.clone = async(sales, refundAgencyMode, refoundZoneId, servicesIds, withWarehouse, group, negative, options) => { const models = Self.app.models; + const myOptions = {}; let tx; + if (typeof options == 'object') + Object.assign(myOptions, options); + if (!myOptions.transaction) { tx = await Self.beginTransaction({}); myOptions.transaction = tx; @@ -39,15 +43,15 @@ module.exports = Self => { }, myOptions); updatedTickets.push(newTicket); } - const sales = ticket.sale(); - const saleIds = sales.map(sale => sale.id); + const salesByTicket = ticket.sale(); + const saleIds = salesByTicket.map(sale => sale.id); const saleComponentsFilter = { where: {saleFk: {inq: saleIds}}, scope: { fields: ['saleFk', 'componentFk', 'value'] } }; - for (const sale of sales) { + for (const sale of salesByTicket) { const createdSale = await models.Sale.create({ ticketFk: newTicket.id, itemFk: sale.itemFk, @@ -56,7 +60,7 @@ module.exports = Self => { price: sale.price, discount: sale.discount, }, myOptions); - const components = await models.SaleComponent.find(saleComponentsFilter, myOptions); + const components = await models.SaleComponent.find(saleComponentsFilter, myOptions); // Revisar con Alex // const components = sale.components(); for (const component of components) component.saleFk = createdSale.id; @@ -86,10 +90,7 @@ module.exports = Self => { if (group) { await Self.rawSql(query, [newTicket.id], myOptions); if (tx) await tx.commit(); - return { - refundTicket: newTicket, - originalTicketFk: firstTicketId - }; + return newTicket; } else { for (const updatedTicket of updatedTickets) await Self.rawSql(query, [updatedTicket.id], myOptions); diff --git a/modules/ticket/back/methods/sale/refund.js b/modules/ticket/back/methods/sale/refund.js index c85bcd834..a69c05f36 100644 --- a/modules/ticket/back/methods/sale/refund.js +++ b/modules/ticket/back/methods/sale/refund.js @@ -155,7 +155,7 @@ module.exports = Self => { } }; const sales = await models.Sale.find(salesFilter, myOptions); - const clonedTicket = await models.Sale.clone( + const refundTicket = await models.Sale.clone( sales, refundAgencyMode, refoundZoneId, @@ -166,12 +166,14 @@ module.exports = Self => { myOptions ); - const refundTicket = clonedTicket.refundTicket; + const ticketsIds = [...new Set(sales.map(sale => sale.ticketFk))]; + for (const ticketId of ticketsIds) { + await models.TicketRefund.create({ + refundTicketFk: refundTicket.id, + originalTicketFk: ticketId, + }, myOptions); + } - await models.TicketRefund.create({ - refundTicketFk: refundTicket.id, - originalTicketFk: clonedTicket.originalTicketFk, - }, myOptions); if (tx) await tx.commit(); return refundTicket; From 725fe674c0babb414a7ea7f7b99763c8f066bcce Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 3 Aug 2023 14:01:50 +0200 Subject: [PATCH 031/427] refs #5914 WIP fixing transacticions --- .../methods/invoiceOut/transferInvoiceOut.js | 47 ++++------ .../invoiceOut/front/descriptor-menu/index.js | 6 +- modules/ticket/back/methods/sale/clone.js | 9 +- modules/ticket/back/methods/sale/refund.js | 90 ------------------- 4 files changed, 27 insertions(+), 125 deletions(-) diff --git a/modules/invoiceOut/back/methods/invoiceOut/transferInvoiceOut.js b/modules/invoiceOut/back/methods/invoiceOut/transferInvoiceOut.js index e059aa431..fbb40061d 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/transferInvoiceOut.js +++ b/modules/invoiceOut/back/methods/invoiceOut/transferInvoiceOut.js @@ -1,5 +1,3 @@ -const UserError = require('vn-loopback/util/user-error'); - module.exports = Self => { Self.remoteMethodCtx('transferInvoiceOut', { description: 'Transfer an invoice out to another client', @@ -48,7 +46,7 @@ module.exports = Self => { Self.transferInvoiceOut = async(ctx, id, ref, newClientFk, cplusRectificationId, cplusInvoiceType477Id, invoiceCorrectionTypeId, options) => { const models = Self.app.models; - const myOptions = {userId: ctx.req.accessToken.userId}; + const myOptions = {}; let tx; if (typeof options == 'object') @@ -65,42 +63,35 @@ module.exports = Self => { const ticketsIds = tickets.map(ticket => ticket.id); await models.Ticket.refund(ctx, ticketsIds, null, myOptions); // Clone tickets - const refundAgencyMode = await models.AgencyMode.findOne({ - include: { - relation: 'zones', - scope: { - limit: 1, - field: ['id', 'name'] - } - }, - where: {code: 'refund'} - }, myOptions); - const refoundZoneId = refundAgencyMode.zones()[0].id; const services = await models.TicketService.find(filter, myOptions); const servicesIds = services.map(service => service.id); const salesFilter = {where: {ticketFk: {inq: ticketsIds}}}; const sales = await models.Sale.find(salesFilter, myOptions); - const clonedTickets = await models.Sale.clone(sales, refundAgencyMode, refoundZoneId, servicesIds, null, false, false, myOptions); + const clonedTickets = await models.Sale.clone(sales, servicesIds, null, false, false, myOptions); + console.log('cloned tickets', clonedTickets); // Update client - for (const clonedTicket of clonedTickets) - await clonedTicket.updateAttributes({clientFk: newClientFk}, myOptions); + for (const clonedTicket of clonedTickets) { + const ticket = await models.Ticket.findById(clonedTicket); + console.log(ticket); + await ticket.updateAttributes({clientFk: newClientFk}, myOptions); + // await clonedTicket.updateAttributes({clientFk: newClientFk}, myOptions); + } // Quick invoice const clonedTicketIds = clonedTickets.map(clonedTicket => clonedTicket.id); - const invoiceIds = await models.Ticket.invoiceTickets(ctx, clonedTicketIds, myOptions); + const invoiceId = await models.Ticket.invoiceTickets(ctx, clonedTicketIds, myOptions); // Insert InvoiceCorrection - for (const invoiceId of invoiceIds) { - await models.InvoiceCorrection.create({ - correctingFk: invoiceId, - correctedFk: id, - cplusRectificationTypeFk: cplusRectificationId, - cplusInvoiceType477Fk: cplusInvoiceType477Id, - invoiceCorrectionType: invoiceCorrectionTypeId - }); - } + await models.InvoiceCorrection.create({ + correctingFk: invoiceId, + correctedFk: id, + cplusRectificationTypeFk: cplusRectificationId, + cplusInvoiceType477Fk: cplusInvoiceType477Id, + invoiceCorrectionType: invoiceCorrectionTypeId + }); + if (tx) await tx.commit(); - return true; + return invoiceId; } catch (e) { if (tx) await tx.rollback(); throw e; diff --git a/modules/invoiceOut/front/descriptor-menu/index.js b/modules/invoiceOut/front/descriptor-menu/index.js index 8ec5de3e6..ef69098c4 100644 --- a/modules/invoiceOut/front/descriptor-menu/index.js +++ b/modules/invoiceOut/front/descriptor-menu/index.js @@ -135,7 +135,11 @@ class Controller extends Section { cplusInvoiceType477Id: this.cplusInvoiceType477, invoiceCorrectionTypeId: this.invoiceCorrectionType }; - this.$http.post(`InvoiceOuts/transferInvoice`, params).then(res => console.log(res.data)); + this.$http.post(`InvoiceOuts/transferInvoice`, params).then(res => { + newInvoice = res.data;// id de la nueva factura + this.vnApp.showSucces(this.$t('Invoice trasfered!')); + this.$state.go('invoiceOut.index', {id: newInvoice}); + }); } } diff --git a/modules/ticket/back/methods/sale/clone.js b/modules/ticket/back/methods/sale/clone.js index dae15d7df..c168f4b3c 100644 --- a/modules/ticket/back/methods/sale/clone.js +++ b/modules/ticket/back/methods/sale/clone.js @@ -1,5 +1,5 @@ module.exports = Self => { - Self.clone = async(sales, refundAgencyMode, refoundZoneId, servicesIds, withWarehouse, group, negative, options) => { + Self.clone = async(sales, servicesIds, withWarehouse, group, negative, options) => { const models = Self.app.models; const myOptions = {}; let tx; @@ -13,7 +13,6 @@ module.exports = Self => { } const ticketsIds = [...new Set(sales.map(sale => sale.ticketFk))]; - const [firstTicketId] = ticketsIds; const now = Date.vnNew(); let updatedTickets = []; let newTicket; @@ -22,7 +21,7 @@ module.exports = Self => { {relation: 'address'}, { relation: 'sale', - inq: sales, + where: {saleFk: {inq: sales}}, }, ] }; @@ -34,12 +33,10 @@ module.exports = Self => { clientFk: ticket.clientFk, shipped: now, addressFk: ticket.address().id, - agencyModeFk: refundAgencyMode.id, nickname: ticket.address().nickname, warehouseFk: withWarehouse ? ticket.warehouseFk : null, companyFk: ticket.companyFk, landed: now, - zoneFk: refoundZoneId }, myOptions); updatedTickets.push(newTicket); } @@ -95,7 +92,7 @@ module.exports = Self => { for (const updatedTicket of updatedTickets) await Self.rawSql(query, [updatedTicket.id], myOptions); if (tx) await tx.commit(); - return updatedTickets/* updatedTickets.map(updatedTicket => updatedTicket.id) */; + return /* updatedTickets */updatedTickets.map(updatedTicket => updatedTicket.id); } } catch (e) { if (tx) await tx.rollback(); diff --git a/modules/ticket/back/methods/sale/refund.js b/modules/ticket/back/methods/sale/refund.js index a69c05f36..dabafb469 100644 --- a/modules/ticket/back/methods/sale/refund.js +++ b/modules/ticket/back/methods/sale/refund.js @@ -28,96 +28,6 @@ module.exports = Self => { } }); - /* Self.refund = async(ctx, salesIds, servicesIds, withWarehouse, options) => { - const models = Self.app.models; - const myOptions = {userId: ctx.req.accessToken.userId}; - let tx; - - if (typeof options == 'object') - Object.assign(myOptions, options); - - if (!myOptions.transaction) { - tx = await Self.beginTransaction({}); - myOptions.transaction = tx; - } - - try { - const refundAgencyMode = await models.AgencyMode.findOne({ - include: { - relation: 'zones', - scope: { - limit: 1, - field: ['id', 'name'] - } - }, - where: {code: 'refund'} - }, myOptions); - - const refoundZoneId = refundAgencyMode.zones()[0].id; - - const salesFilter = { - where: {id: {inq: salesIds}}, - include: { - relation: 'components', - scope: { - fields: ['saleFk', 'componentFk', 'value'] - } - } - }; - const sales = await models.Sale.find(salesFilter, myOptions); - const ticketsIds = [...new Set(sales.map(sale => sale.ticketFk))]; - - const now = Date.vnNew(); - const [firstTicketId] = ticketsIds; - - const refundTicket = await createTicketRefund(firstTicketId, now, refundAgencyMode, refoundZoneId, withWarehouse, myOptions); - - for (const sale of sales) { - const createdSale = await models.Sale.create({ - ticketFk: refundTicket.id, - itemFk: sale.itemFk, - quantity: - sale.quantity, - concept: sale.concept, - price: sale.price, - discount: sale.discount, - }, myOptions); - - const components = sale.components(); - for (const component of components) - component.saleFk = createdSale.id; - - await models.SaleComponent.create(components, myOptions); - } - - if (servicesIds && servicesIds.length > 0) { - const servicesFilter = { - where: {id: {inq: servicesIds}} - }; - const services = await models.TicketService.find(servicesFilter, myOptions); - for (const service of services) { - await models.TicketService.create({ - description: service.description, - quantity: - service.quantity, - price: service.price, - taxClassFk: service.taxClassFk, - ticketFk: refundTicket.id, - ticketServiceTypeFk: service.ticketServiceTypeFk, - }, myOptions); - } - } - - const query = `CALL vn.ticket_recalc(?, NULL)`; - await Self.rawSql(query, [refundTicket.id], myOptions); - - if (tx) await tx.commit(); - - return refundTicket; - } catch (e) { - if (tx) await tx.rollback(); - throw e; - } - }; */ - Self.refund = async(ctx, salesIds, servicesIds, withWarehouse, options) => { const models = Self.app.models; const myOptions = {userId: ctx.req.accessToken.userId}; From 700ba4a7b1fce37f7575b3308ead22163687a14b Mon Sep 17 00:00:00 2001 From: alexm Date: Fri, 4 Aug 2023 08:22:43 +0200 Subject: [PATCH 032/427] refs #5914 feat(transferInvoiceOut): optimization --- .../methods/invoiceOut/transferInvoiceOut.js | 18 ++++++++---------- modules/ticket/back/methods/sale/clone.js | 2 +- .../back/methods/ticket/invoiceTickets.js | 7 +++++-- 3 files changed, 14 insertions(+), 13 deletions(-) diff --git a/modules/invoiceOut/back/methods/invoiceOut/transferInvoiceOut.js b/modules/invoiceOut/back/methods/invoiceOut/transferInvoiceOut.js index fbb40061d..440ebe4d3 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/transferInvoiceOut.js +++ b/modules/invoiceOut/back/methods/invoiceOut/transferInvoiceOut.js @@ -46,7 +46,8 @@ module.exports = Self => { Self.transferInvoiceOut = async(ctx, id, ref, newClientFk, cplusRectificationId, cplusInvoiceType477Id, invoiceCorrectionTypeId, options) => { const models = Self.app.models; - const myOptions = {}; + const myOptions = {userId: ctx.req.accessToken.userId}; + let tx; if (typeof options == 'object') @@ -65,20 +66,17 @@ module.exports = Self => { // Clone tickets const services = await models.TicketService.find(filter, myOptions); const servicesIds = services.map(service => service.id); - const salesFilter = {where: {ticketFk: {inq: ticketsIds}}}; - const sales = await models.Sale.find(salesFilter, myOptions); + const sales = await models.Sale.find({where: {ticketFk: {inq: ticketsIds}}}, myOptions); const clonedTickets = await models.Sale.clone(sales, servicesIds, null, false, false, myOptions); - console.log('cloned tickets', clonedTickets); + const clonedTicketIds = []; + // Update client for (const clonedTicket of clonedTickets) { - const ticket = await models.Ticket.findById(clonedTicket); - console.log(ticket); - await ticket.updateAttributes({clientFk: newClientFk}, myOptions); - // await clonedTicket.updateAttributes({clientFk: newClientFk}, myOptions); + await clonedTicket.updateAttribute('clientFk', newClientFk, myOptions); + clonedTicketIds.push(clonedTicket.id); } // Quick invoice - const clonedTicketIds = clonedTickets.map(clonedTicket => clonedTicket.id); const invoiceId = await models.Ticket.invoiceTickets(ctx, clonedTicketIds, myOptions); // Insert InvoiceCorrection @@ -88,7 +86,7 @@ module.exports = Self => { cplusRectificationTypeFk: cplusRectificationId, cplusInvoiceType477Fk: cplusInvoiceType477Id, invoiceCorrectionType: invoiceCorrectionTypeId - }); + }, myOptions); if (tx) await tx.commit(); return invoiceId; diff --git a/modules/ticket/back/methods/sale/clone.js b/modules/ticket/back/methods/sale/clone.js index c168f4b3c..7d52fd0e6 100644 --- a/modules/ticket/back/methods/sale/clone.js +++ b/modules/ticket/back/methods/sale/clone.js @@ -92,7 +92,7 @@ module.exports = Self => { for (const updatedTicket of updatedTickets) await Self.rawSql(query, [updatedTicket.id], myOptions); if (tx) await tx.commit(); - return /* updatedTickets */updatedTickets.map(updatedTicket => updatedTicket.id); + return /* updatedTickets */updatedTickets; } } catch (e) { if (tx) await tx.rollback(); diff --git a/modules/ticket/back/methods/ticket/invoiceTickets.js b/modules/ticket/back/methods/ticket/invoiceTickets.js index ca1bf15fb..7baee133d 100644 --- a/modules/ticket/back/methods/ticket/invoiceTickets.js +++ b/modules/ticket/back/methods/ticket/invoiceTickets.js @@ -77,9 +77,11 @@ module.exports = function(Self) { if (tx) await tx.rollback(); throw e; } - - for (const invoiceId of invoicesIds) + console.log(invoicesIds, 'invoicesIds'); + for (const invoiceId of invoicesIds) { + console.log(await models.InvoiceOut.find()); await models.InvoiceOut.makePdfAndNotify(ctx, invoiceId, null); + } return invoicesIds; }; @@ -98,6 +100,7 @@ module.exports = function(Self) { `, [ticketsIds], myOptions); const invoiceId = await models.Ticket.makeInvoice(ctx, 'R', companyId, Date.vnNew(), myOptions); + console.log(await models.InvoiceOut.find(null, myOptions)); invoicesIds.push(invoiceId); } }; From 6eb88f8ab7f7923af915791f9adb4934bd708ee6 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Fri, 11 Aug 2023 11:58:30 +0200 Subject: [PATCH 033/427] refs #5134 feat: models --- modules/ticket/back/models/saleMistake.json | 49 +++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 modules/ticket/back/models/saleMistake.json diff --git a/modules/ticket/back/models/saleMistake.json b/modules/ticket/back/models/saleMistake.json new file mode 100644 index 000000000..b48e6088d --- /dev/null +++ b/modules/ticket/back/models/saleMistake.json @@ -0,0 +1,49 @@ +{ // A REVISAR QUE NOFA INSERT EN + "name": "SaleMistake", + "base": "VnModel", + "options": { + "mysql": { + "table": "saleMistake" + } + }, + "properties": { + "id": { + "id": true, + "type": "number", + "description": "Identifier" + }, + "created": { + "type": "date" + }, + "saleFk": { + "type": "number" + }, + "userFk": { + "type": "number" + }, + "typeFk": { + "type": "number" + } + }, + "relations": { + "sale": { + "type": "belongsTo", + "model": "Sale", + "foreignKey": "saleFk", + "required": true + }, + "worker": { + "type": "belongsTo", + "model": "Worker", + "foreignKey": "userFk", + "required": true + }, + "mistakeType": { + "type": "belongsTo", + "model": "MistakeType", + "foreignKey": "typeFk", + "required": true + } + + } +} From 9ef4ba9befa6dcf1de94d6d0b7b167e6a049c3ac Mon Sep 17 00:00:00 2001 From: alexm Date: Fri, 11 Aug 2023 12:32:49 +0200 Subject: [PATCH 034/427] refs #5134 feat: add saleMistake model --- db/changes/233401/00-acl_saleMistake.sql | 3 +++ db/dump/fixtures.sql | 6 ++++- modules/ticket/back/model-config.json | 3 +++ .../{saleMistake.json => sale-mistake.json} | 22 +++++++++---------- 4 files changed, 22 insertions(+), 12 deletions(-) create mode 100644 db/changes/233401/00-acl_saleMistake.sql rename modules/ticket/back/models/{saleMistake.json => sale-mistake.json} (75%) diff --git a/db/changes/233401/00-acl_saleMistake.sql b/db/changes/233401/00-acl_saleMistake.sql new file mode 100644 index 000000000..219669c17 --- /dev/null +++ b/db/changes/233401/00-acl_saleMistake.sql @@ -0,0 +1,3 @@ +INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) + VALUES + ('SaleMistake', 'create', 'WRITE', 'ALLOW', 'ROLE', 'employee'); diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 7a572fb04..630b6fb6c 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -2955,6 +2955,10 @@ INSERT INTO `vn`.`invoiceInSerial` (`code`, `description`, `cplusTerIdNifFk`, `t ('W', 'Vanaheim', 1, 'WORLD'); -INSERT INTO `hedera`.`imageConfig` (`id`, `maxSize`, `useXsendfile`, `url`) +INSERT INTO `hedera`.`imageConfig` (`id`, `maxSize`, `useXsendfile`, `url`) VALUES (1, 0, 0, 'marvel.com'); + +INSERT INTO `vn`.`mistakeType` (`id`, `description`) + VALUES + (1, 'Incorrect quantity'); diff --git a/modules/ticket/back/model-config.json b/modules/ticket/back/model-config.json index 3c7e12eea..ef2a14dfe 100644 --- a/modules/ticket/back/model-config.json +++ b/modules/ticket/back/model-config.json @@ -44,6 +44,9 @@ "SaleGroup": { "dataSource": "vn" }, + "SaleMistake": { + "dataSource": "vn" + }, "SaleGroupDetail": { "dataSource": "vn" }, diff --git a/modules/ticket/back/models/saleMistake.json b/modules/ticket/back/models/sale-mistake.json similarity index 75% rename from modules/ticket/back/models/saleMistake.json rename to modules/ticket/back/models/sale-mistake.json index b48e6088d..390e45404 100644 --- a/modules/ticket/back/models/saleMistake.json +++ b/modules/ticket/back/models/sale-mistake.json @@ -1,4 +1,4 @@ -{ // A REVISAR QUE NOFA INSERT EN +{ "name": "SaleMistake", "base": "VnModel", "options": { @@ -16,34 +16,34 @@ "type": "date" }, "saleFk": { - "type": "number" + "type": "number", + "required": true }, "userFk": { - "type": "number" + "type": "number", + "required": true }, "typeFk": { - "type": "number" + "type": "number", + "required": true } }, "relations": { "sale": { "type": "belongsTo", "model": "Sale", - "foreignKey": "saleFk", - "required": true + "foreignKey": "saleFk" }, "worker": { "type": "belongsTo", "model": "Worker", - "foreignKey": "userFk", - "required": true + "foreignKey": "userFk" }, "mistakeType": { "type": "belongsTo", "model": "MistakeType", - "foreignKey": "typeFk", - "required": true + "foreignKey": "typeFk" } - + } } From a6047d257b9c118e971767f45baf62208c13f50e Mon Sep 17 00:00:00 2001 From: sergiodt Date: Fri, 11 Aug 2023 12:45:18 +0200 Subject: [PATCH 035/427] refs #5134 feat:modelsSalix --- db/changes/233401/00-models.sql | 29 +++++++++++++++++++ modules/invoiceOut/back/models/printer.json | 7 +++++ modules/shelving/back/model-config.json | 3 ++ modules/shelving/back/models/train.json | 19 ++++++++++++ modules/ticket/back/model-config.json | 6 ++++ .../ticket/back/models/expeditionMistake.json | 2 +- .../back/models/expeditionMistakeType.json | 20 +++++++++++++ modules/ticket/back/models/sale-mistake.json | 2 +- modules/worker/back/model-config.json | 9 ++++++ modules/worker/back/models/mistakeType.json | 20 +++++++++++++ modules/worker/back/models/workerMistake.json | 25 ++++++++++++++++ .../worker/back/models/workerMistakeType.json | 27 +++++++++++++++++ 12 files changed, 167 insertions(+), 2 deletions(-) create mode 100644 db/changes/233401/00-models.sql create mode 100644 modules/shelving/back/models/train.json create mode 100644 modules/ticket/back/models/expeditionMistakeType.json create mode 100644 modules/worker/back/models/mistakeType.json create mode 100644 modules/worker/back/models/workerMistake.json create mode 100644 modules/worker/back/models/workerMistakeType.json diff --git a/db/changes/233401/00-models.sql b/db/changes/233401/00-models.sql new file mode 100644 index 000000000..648824287 --- /dev/null +++ b/db/changes/233401/00-models.sql @@ -0,0 +1,29 @@ +INSERT INTO salix.ACL ( model, property, accessType, permission, principalType, principalId) + VALUES('ExpeditionMistakeType', '*', 'READ', 'ALLOW', 'ROLE', 'employee'); + +INSERT INTO salix.ACL (id, model, property, accessType, permission, principalType, principalId) + VALUES('WorkerMistakeType', '*', 'READ', 'ALLOW', 'ROLE', 'employee'); + +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES ('ExpeditionMistake','*','WRITE','ALLOW','ROLE','employee'); + +INSERT INTO salix.ACL (model, property, accessType, permission, principalType, principalId) + VALUES('WorkerMistake', '*', 'WRITE', 'ALLOW', 'ROLE', 'coolerBoss'); + +INSERT INTO salix.ACL (model, property, accessType, permission, principalType, principalId) + VALUES('WorkerMistake', '*', 'WRITE', 'ALLOW', 'ROLE', 'coolerBoss'); + +INSERT INTO salix.ACL ( model, property, accessType, permission, principalType, principalId) + VALUES('MistakesTypes', '*', 'WRITE', 'ALLOW', 'ROLE', 'coolerBoss'); + +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES ('MistakeType','*','READ','ALLOW','ROLE','employee'); + +INSERT INTO salix.ACL (id, model, property, accessType, permission, principalType, principalId) + VALUES(698, 'MachineWorker', '*', 'READ', 'ALLOW', 'ROLE', 'coolerAssist'); + +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES ('Printer','*','READ','ALLOW','ROLE','employee'); + +INSERT INTO salix.ACL (model, property, accessType, permission, principalType, principalId) +VALUES( 'SaleMistake', '*', 'WRITE', 'ALLOW', 'ROLE', 'production'); diff --git a/modules/invoiceOut/back/models/printer.json b/modules/invoiceOut/back/models/printer.json index 99003560d..46a031f65 100644 --- a/modules/invoiceOut/back/models/printer.json +++ b/modules/invoiceOut/back/models/printer.json @@ -18,6 +18,13 @@ "isLabeler": { "type": "boolean" } + }, + "relations": { + "sector": { + "type": "belongsTo", + "model": "Sector", + "foreignKey": "sectorFk" + } }, "acls": [{ "accessType": "READ", diff --git a/modules/shelving/back/model-config.json b/modules/shelving/back/model-config.json index c26c39d38..89a0832b0 100644 --- a/modules/shelving/back/model-config.json +++ b/modules/shelving/back/model-config.json @@ -10,5 +10,8 @@ }, "Sector": { "dataSource": "vn" + }, + "Train": { + "dataSource": "vn" } } \ No newline at end of file diff --git a/modules/shelving/back/models/train.json b/modules/shelving/back/models/train.json new file mode 100644 index 000000000..cc819664b --- /dev/null +++ b/modules/shelving/back/models/train.json @@ -0,0 +1,19 @@ +{ + "name": "Train", + "options": { + "mysql": { + "table": "train" + } + }, + "properties": { + "id": { + "type": "number", + "id": true + }, + "name": { + "type": "string", + "required": true + } + + } +} diff --git a/modules/ticket/back/model-config.json b/modules/ticket/back/model-config.json index ef2a14dfe..456bb73d3 100644 --- a/modules/ticket/back/model-config.json +++ b/modules/ticket/back/model-config.json @@ -29,6 +29,9 @@ "ExpeditionMistake": { "dataSource": "vn" }, + "ExpeditionMistakeType": { + "dataSource": "vn" + }, "PrintServerQueue": { "dataSource": "vn" }, @@ -50,6 +53,9 @@ "SaleGroupDetail": { "dataSource": "vn" }, + "SaleMistake": { + "dataSource": "vn" + }, "SaleTracking": { "dataSource": "vn" }, diff --git a/modules/ticket/back/models/expeditionMistake.json b/modules/ticket/back/models/expeditionMistake.json index 43033194a..aeed2aa3a 100644 --- a/modules/ticket/back/models/expeditionMistake.json +++ b/modules/ticket/back/models/expeditionMistake.json @@ -24,7 +24,7 @@ }, "type": { "type": "belongsTo", - "model": "MistakeType", + "model": "ExpeditionMistakeType", "foreignKey": "typeFk" } } diff --git a/modules/ticket/back/models/expeditionMistakeType.json b/modules/ticket/back/models/expeditionMistakeType.json new file mode 100644 index 000000000..cf997a963 --- /dev/null +++ b/modules/ticket/back/models/expeditionMistakeType.json @@ -0,0 +1,20 @@ +{ + "name": "ExpeditionMistakeType", + "base": "VnModel", + "options": { + "mysql": { + "table": "expeditionMistakeType" + } + }, + "properties": { + "code": { + "id":true, + "type": "string" + + }, + "description": { + "type": "string" + } + } + } + \ No newline at end of file diff --git a/modules/ticket/back/models/sale-mistake.json b/modules/ticket/back/models/sale-mistake.json index 390e45404..b1cd989e0 100644 --- a/modules/ticket/back/models/sale-mistake.json +++ b/modules/ticket/back/models/sale-mistake.json @@ -46,4 +46,4 @@ } } -} +} \ No newline at end of file diff --git a/modules/worker/back/model-config.json b/modules/worker/back/model-config.json index 60ec273a5..ca47afaf6 100644 --- a/modules/worker/back/model-config.json +++ b/modules/worker/back/model-config.json @@ -40,6 +40,9 @@ }, "EducationLevel": { "dataSource": "vn" + }, + "MistakeType": { + "dataSource": "vn" }, "ProfileType":{ "dataSource": "vn" @@ -80,6 +83,12 @@ "WorkerMana": { "dataSource": "vn" }, + "WorkerMistake": { + "dataSource": "vn" + }, + "WorkerMistakeType": { + "dataSource": "vn" + }, "WorkerMedia": { "dataSource": "vn" }, diff --git a/modules/worker/back/models/mistakeType.json b/modules/worker/back/models/mistakeType.json new file mode 100644 index 000000000..71d9e4744 --- /dev/null +++ b/modules/worker/back/models/mistakeType.json @@ -0,0 +1,20 @@ +{ + "name": "MistakeType", + "base": "VnModel", + "options": { + "mysql": { + "table": "mistakeType" + } + }, + "properties": { + "id": { + "id":true, + "type": "number" + }, + "description": { + "type": "string" + } + + } + } + \ No newline at end of file diff --git a/modules/worker/back/models/workerMistake.json b/modules/worker/back/models/workerMistake.json new file mode 100644 index 000000000..47ed95f80 --- /dev/null +++ b/modules/worker/back/models/workerMistake.json @@ -0,0 +1,25 @@ +{ + "name": "WorkerMistake", + "base": "VnModel", + "options": { + "mysql": { + "table": "workerMistake" + } + }, + "properties": { + "id": { + "id":true, + "type": "number" + }, + "userFk": { + "type": "number" + }, + "workerMistakeTypeFk": { + "type": "string" + }, + "created": { + "type": "date" + } + } + } + \ No newline at end of file diff --git a/modules/worker/back/models/workerMistakeType.json b/modules/worker/back/models/workerMistakeType.json new file mode 100644 index 000000000..3c808f24c --- /dev/null +++ b/modules/worker/back/models/workerMistakeType.json @@ -0,0 +1,27 @@ +{ + "name": "WorkerMistakeType", + "base": "VnModel", + "options": { + "mysql": { + "table": "workerMistakeType" + } + }, + "properties": { + "code": { + "id":true, + "type": "string" + + }, + "description": { + "type": "string" + } + }, + "relations": { + "type": { + "type": "belongsTo", + "model": "WorkerMistakeType", + "foreignKey": "code" + } + } + } + \ No newline at end of file From 1ec51d94cf497df1ed51dc0043d66091583430d8 Mon Sep 17 00:00:00 2001 From: alexm Date: Fri, 11 Aug 2023 12:53:43 +0200 Subject: [PATCH 036/427] refs #5134 feat: correct sql --- db/changes/233401/00-acl_saleMistake.sql | 3 --- db/changes/233401/00-models.sql | 24 ++++++++++++------------ modules/ticket/back/model-config.json | 3 --- 3 files changed, 12 insertions(+), 18 deletions(-) delete mode 100644 db/changes/233401/00-acl_saleMistake.sql diff --git a/db/changes/233401/00-acl_saleMistake.sql b/db/changes/233401/00-acl_saleMistake.sql deleted file mode 100644 index 219669c17..000000000 --- a/db/changes/233401/00-acl_saleMistake.sql +++ /dev/null @@ -1,3 +0,0 @@ -INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) - VALUES - ('SaleMistake', 'create', 'WRITE', 'ALLOW', 'ROLE', 'employee'); diff --git a/db/changes/233401/00-models.sql b/db/changes/233401/00-models.sql index 648824287..c06965b3f 100644 --- a/db/changes/233401/00-models.sql +++ b/db/changes/233401/00-models.sql @@ -1,29 +1,29 @@ -INSERT INTO salix.ACL ( model, property, accessType, permission, principalType, principalId) +INSERT INTO `salix`.`ACL` ( model, property, accessType, permission, principalType, principalId) VALUES('ExpeditionMistakeType', '*', 'READ', 'ALLOW', 'ROLE', 'employee'); -INSERT INTO salix.ACL (id, model, property, accessType, permission, principalType, principalId) +INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) VALUES('WorkerMistakeType', '*', 'READ', 'ALLOW', 'ROLE', 'employee'); -INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) +INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId) VALUES ('ExpeditionMistake','*','WRITE','ALLOW','ROLE','employee'); -INSERT INTO salix.ACL (model, property, accessType, permission, principalType, principalId) +INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) VALUES('WorkerMistake', '*', 'WRITE', 'ALLOW', 'ROLE', 'coolerBoss'); -INSERT INTO salix.ACL (model, property, accessType, permission, principalType, principalId) +INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) VALUES('WorkerMistake', '*', 'WRITE', 'ALLOW', 'ROLE', 'coolerBoss'); -INSERT INTO salix.ACL ( model, property, accessType, permission, principalType, principalId) +INSERT INTO `salix`.`ACL` ( model, property, accessType, permission, principalType, principalId) VALUES('MistakesTypes', '*', 'WRITE', 'ALLOW', 'ROLE', 'coolerBoss'); -INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) +INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId) VALUES ('MistakeType','*','READ','ALLOW','ROLE','employee'); -INSERT INTO salix.ACL (id, model, property, accessType, permission, principalType, principalId) - VALUES(698, 'MachineWorker', '*', 'READ', 'ALLOW', 'ROLE', 'coolerAssist'); +INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) + VALUES('MachineWorker', '*', 'READ', 'ALLOW', 'ROLE', 'coolerAssist'); -INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) +INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId) VALUES ('Printer','*','READ','ALLOW','ROLE','employee'); -INSERT INTO salix.ACL (model, property, accessType, permission, principalType, principalId) -VALUES( 'SaleMistake', '*', 'WRITE', 'ALLOW', 'ROLE', 'production'); +INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) + VALUES( 'SaleMistake', '*', 'WRITE', 'ALLOW', 'ROLE', 'production'); diff --git a/modules/ticket/back/model-config.json b/modules/ticket/back/model-config.json index 456bb73d3..e90d0409f 100644 --- a/modules/ticket/back/model-config.json +++ b/modules/ticket/back/model-config.json @@ -53,9 +53,6 @@ "SaleGroupDetail": { "dataSource": "vn" }, - "SaleMistake": { - "dataSource": "vn" - }, "SaleTracking": { "dataSource": "vn" }, From b1b6bd13ea73fe7860eef2548f1ffeb4f21f12e7 Mon Sep 17 00:00:00 2001 From: carlossa Date: Tue, 22 Aug 2023 10:45:41 +0200 Subject: [PATCH 037/427] refs #5843 change userFk --- modules/claim/front/descriptor/index.html | 2 +- modules/client/back/methods/receipt/filter.js | 2 +- modules/client/front/credit/index/index.html | 10 +++++----- modules/item/back/methods/item/filter.js | 2 +- modules/item/front/descriptor/index.html | 6 +++--- modules/item/front/summary/index.html | 2 +- .../monitor/back/methods/sales-monitor/salesFilter.js | 2 +- modules/order/back/methods/order/filter.js | 2 +- modules/route/back/methods/route/filter.js | 4 ++-- .../back/methods/sale-tracking/listSaleTracking.js | 2 +- modules/ticket/back/methods/ticket-request/filter.js | 4 ++-- modules/ticket/back/methods/ticket/filter.js | 2 +- modules/worker/back/methods/worker/getWorkedHours.js | 6 +++--- modules/worker/back/models/worker.json | 7 ++----- modules/worker/front/pbx/index.js | 2 +- modules/worker/front/summary/index.html | 2 +- print/templates/email/client-welcome/sql/client.sql | 4 ++-- print/templates/email/printer-setup/sql/client.sql | 4 ++-- print/templates/reports/driver-route/sql/routes.sql | 6 +++--- 19 files changed, 34 insertions(+), 37 deletions(-) diff --git a/modules/claim/front/descriptor/index.html b/modules/claim/front/descriptor/index.html index 5fd198440..8ff1fd791 100644 --- a/modules/claim/front/descriptor/index.html +++ b/modules/claim/front/descriptor/index.html @@ -45,7 +45,7 @@ {{$ctrl.claim.worker.user.name}} diff --git a/modules/client/back/methods/receipt/filter.js b/modules/client/back/methods/receipt/filter.js index 6df5e73f8..7b5d73dae 100644 --- a/modules/client/back/methods/receipt/filter.js +++ b/modules/client/back/methods/receipt/filter.js @@ -60,7 +60,7 @@ module.exports = Self => { at2.id IS NOT NULL as isCompensation FROM vn.receipt r LEFT JOIN vn.worker w ON w.id = r.workerFk - LEFT JOIN account.user u ON u.id = w.userFk + LEFT JOIN account.user u ON u.id = w.id JOIN vn.company c ON c.id = r.companyFk LEFT JOIN vn.accounting a ON a.id = r.bankFk LEFT JOIN vn.accountingType at2 ON at2.id = a.accountingTypeFk AND at2.code = 'compensation' diff --git a/modules/client/front/credit/index/index.html b/modules/client/front/credit/index/index.html index 989a0129f..d11449268 100644 --- a/modules/client/front/credit/index/index.html +++ b/modules/client/front/credit/index/index.html @@ -24,8 +24,8 @@ {{::credit.created | date:'dd/MM/yyyy HH:mm'}} - {{::credit.worker.user.name}} @@ -41,10 +41,10 @@ ui-sref="client.card.credit.create" vn-acl="teamBoss" vn-acl-action="remove" - vn-tooltip="New credit" + vn-tooltip="New credit" vn-bind="+" fixed-bottom-right> - - \ No newline at end of file + diff --git a/modules/item/back/methods/item/filter.js b/modules/item/back/methods/item/filter.js index d5de6a954..909b3dff8 100644 --- a/modules/item/back/methods/item/filter.js +++ b/modules/item/back/methods/item/filter.js @@ -180,7 +180,7 @@ module.exports = Self => { LEFT JOIN itemType it ON it.id = i.typeFk LEFT JOIN itemCategory ic ON ic.id = it.categoryFk LEFT JOIN worker w ON w.id = it.workerFk - LEFT JOIN account.user u ON u.id = w.userFk + LEFT JOIN account.user u ON u.id = w.id LEFT JOIN intrastat intr ON intr.id = i.intrastatFk LEFT JOIN producer pr ON pr.id = i.producerFk LEFT JOIN origin ori ON ori.id = i.originFk diff --git a/modules/item/front/descriptor/index.html b/modules/item/front/descriptor/index.html index 7c442d364..82dfa3c9f 100644 --- a/modules/item/front/descriptor/index.html +++ b/modules/item/front/descriptor/index.html @@ -1,6 +1,6 @@ {{$ctrl.item.itemType.worker.user.name}} diff --git a/modules/item/front/summary/index.html b/modules/item/front/summary/index.html index fcc267b4d..6ec738c7e 100644 --- a/modules/item/front/summary/index.html +++ b/modules/item/front/summary/index.html @@ -70,7 +70,7 @@ {{$ctrl.summary.item.itemType.worker.user.name}} diff --git a/modules/monitor/back/methods/sales-monitor/salesFilter.js b/modules/monitor/back/methods/sales-monitor/salesFilter.js index 4f9edd11c..693ae122f 100644 --- a/modules/monitor/back/methods/sales-monitor/salesFilter.js +++ b/modules/monitor/back/methods/sales-monitor/salesFilter.js @@ -215,7 +215,7 @@ module.exports = Self => { LEFT JOIN state st ON st.id = ts.stateFk LEFT JOIN client c ON c.id = t.clientFk LEFT JOIN worker wk ON wk.id = c.salesPersonFk - LEFT JOIN account.user u ON u.id = wk.userFk + LEFT JOIN account.user u ON u.id = wk.id LEFT JOIN zoneEstimatedDelivery zed ON zed.zoneFk = t.zoneFk`); if (args.orderFk) { diff --git a/modules/order/back/methods/order/filter.js b/modules/order/back/methods/order/filter.js index 10185af7e..44d8ccb10 100644 --- a/modules/order/back/methods/order/filter.js +++ b/modules/order/back/methods/order/filter.js @@ -169,7 +169,7 @@ module.exports = Self => { LEFT JOIN agencyMode am ON am.id = o.agency_id LEFT JOIN client c ON c.id = o.customer_id LEFT JOIN worker wk ON wk.id = c.salesPersonFk - LEFT JOIN account.user u ON u.id = wk.userFk + LEFT JOIN account.user u ON u.id = wk.id LEFT JOIN company co ON co.id = o.company_id LEFT JOIN orderTicket ot ON ot.orderFk = o.id LEFT JOIN ticket t ON t.id = ot.ticketFk diff --git a/modules/route/back/methods/route/filter.js b/modules/route/back/methods/route/filter.js index fdec84d4d..fc35e979f 100644 --- a/modules/route/back/methods/route/filter.js +++ b/modules/route/back/methods/route/filter.js @@ -111,7 +111,7 @@ module.exports = Self => { let stmt; stmt = new ParameterizedSQL( - `SELECT + `SELECT r.id, r.workerFk, r.created, @@ -134,7 +134,7 @@ module.exports = Self => { LEFT JOIN agencyMode am ON am.id = r.agencyModeFk LEFT JOIN vehicle v ON v.id = r.vehicleFk LEFT JOIN worker w ON w.id = r.workerFk - LEFT JOIN account.user u ON u.id = w.userFk` + LEFT JOIN account.user u ON u.id = w.id` ); stmt.merge(conn.makeSuffix(filter)); diff --git a/modules/ticket/back/methods/sale-tracking/listSaleTracking.js b/modules/ticket/back/methods/sale-tracking/listSaleTracking.js index 98743d8cc..fbc855501 100644 --- a/modules/ticket/back/methods/sale-tracking/listSaleTracking.js +++ b/modules/ticket/back/methods/sale-tracking/listSaleTracking.js @@ -41,7 +41,7 @@ module.exports = Self => { FROM saleTracking st JOIN sale s ON s.id = st.saleFk JOIN worker w ON w.id = st.workerFk - JOIN account.user u ON u.id = w.userFk + JOIN account.user u ON u.id = w.id JOIN state ste ON ste.id = st.stateFk`); stmt.merge(Self.makeSuffix(filter)); diff --git a/modules/ticket/back/methods/ticket-request/filter.js b/modules/ticket/back/methods/ticket-request/filter.js index 921598b57..f27ea5018 100644 --- a/modules/ticket/back/methods/ticket-request/filter.js +++ b/modules/ticket/back/methods/ticket-request/filter.js @@ -153,9 +153,9 @@ module.exports = Self => { LEFT JOIN item i ON i.id = tr.itemFk LEFT JOIN sale s ON s.id = tr.saleFk LEFT JOIN worker wk ON wk.id = c.salesPersonFk - LEFT JOIN account.user u ON u.id = wk.userFk + LEFT JOIN account.user u ON u.id = wk.id LEFT JOIN worker wka ON wka.id = tr.attenderFk - LEFT JOIN account.user ua ON ua.id = wka.userFk`); + LEFT JOIN account.user ua ON ua.id = wka.id`); stmt.merge(conn.makeSuffix(filter)); return conn.executeStmt(stmt, myOptions); diff --git a/modules/ticket/back/methods/ticket/filter.js b/modules/ticket/back/methods/ticket/filter.js index eb3da39af..899fe05cd 100644 --- a/modules/ticket/back/methods/ticket/filter.js +++ b/modules/ticket/back/methods/ticket/filter.js @@ -272,7 +272,7 @@ module.exports = Self => { LEFT JOIN state st ON st.id = ts.stateFk LEFT JOIN client c ON c.id = t.clientFk LEFT JOIN worker wk ON wk.id = c.salesPersonFk - LEFT JOIN account.user u ON u.id = wk.userFk + LEFT JOIN account.user u ON u.id = wk.id LEFT JOIN route r ON r.id = t.routeFk`); if (args.orderFk) { diff --git a/modules/worker/back/methods/worker/getWorkedHours.js b/modules/worker/back/methods/worker/getWorkedHours.js index 44f3eca3a..cac74a416 100644 --- a/modules/worker/back/methods/worker/getWorkedHours.js +++ b/modules/worker/back/methods/worker/getWorkedHours.js @@ -38,12 +38,12 @@ module.exports = Self => { const conn = Self.dataSource.connector; const worker = await models.Worker.findById(id); - const userId = worker.userFk; + const userId = worker.id; const stmts = []; stmts.push(` - DROP TEMPORARY TABLE IF EXISTS + DROP TEMPORARY TABLE IF EXISTS tmp.timeControlCalculate, tmp.timeBusinessCalculate `); @@ -54,7 +54,7 @@ module.exports = Self => { const resultIndex = stmts.push(new ParameterizedSQL(` SELECT tcc.dated, tbc.timeWorkSeconds expectedHours, tcc.timeWorkSeconds workedHours - FROM tmp.timeControlCalculate tcc + FROM tmp.timeControlCalculate tcc LEFT JOIN tmp.timeBusinessCalculate tbc ON tcc.dated = tbc.dated WHERE tcc.dated BETWEEN DATE(?) AND DATE(?) `, [started, ended])) - 1; diff --git a/modules/worker/back/models/worker.json b/modules/worker/back/models/worker.json index 6e1371055..dbb3ed23f 100644 --- a/modules/worker/back/models/worker.json +++ b/modules/worker/back/models/worker.json @@ -24,9 +24,6 @@ "phone": { "type" : "string" }, - "userFk": { - "type" : "number" - }, "bossFk": { "type" : "number" }, @@ -66,12 +63,12 @@ "client": { "type": "belongsTo", "model": "Client", - "foreignKey": "userFk" + "foreignKey": "id" }, "sip": { "type": "belongsTo", "model": "Sip", - "foreignKey": "userFk" + "foreignKey": "id" }, "department": { "type": "belongsTo", diff --git a/modules/worker/front/pbx/index.js b/modules/worker/front/pbx/index.js index d37f6f7d8..3b6443d3c 100644 --- a/modules/worker/front/pbx/index.js +++ b/modules/worker/front/pbx/index.js @@ -5,7 +5,7 @@ class Controller extends Section { onSubmit() { const sip = this.worker.sip; const params = { - userFk: this.worker.userFk, + userFk: this.worker.id, extension: sip.extension }; this.$.watcher.check(); diff --git a/modules/worker/front/summary/index.html b/modules/worker/front/summary/index.html index 2607d9b2f..6604ef6ca 100644 --- a/modules/worker/front/summary/index.html +++ b/modules/worker/front/summary/index.html @@ -58,7 +58,7 @@

User data

+ value="{{worker.id}}"> diff --git a/print/templates/email/client-welcome/sql/client.sql b/print/templates/email/client-welcome/sql/client.sql index 49e1d4bf6..59bdeae4a 100644 --- a/print/templates/email/client-welcome/sql/client.sql +++ b/print/templates/email/client-welcome/sql/client.sql @@ -7,5 +7,5 @@ SELECT FROM client c JOIN account.user u ON u.id = c.id LEFT JOIN worker w ON w.id = c.salesPersonFk - LEFT JOIN account.user wu ON wu.id = w.userFk -WHERE c.id = ? \ No newline at end of file + LEFT JOIN account.user wu ON wu.id = w.id +WHERE c.id = ? diff --git a/print/templates/email/printer-setup/sql/client.sql b/print/templates/email/printer-setup/sql/client.sql index 2a8a751e0..31454408f 100644 --- a/print/templates/email/printer-setup/sql/client.sql +++ b/print/templates/email/printer-setup/sql/client.sql @@ -8,5 +8,5 @@ SELECT FROM client c JOIN account.user u ON u.id = c.id LEFT JOIN worker w ON w.id = c.salesPersonFk - LEFT JOIN account.user wu ON wu.id = w.userFk -WHERE c.id = ? \ No newline at end of file + LEFT JOIN account.user wu ON wu.id = w.id +WHERE c.id = ? diff --git a/print/templates/reports/driver-route/sql/routes.sql b/print/templates/reports/driver-route/sql/routes.sql index 4b6f6a318..79bede5b2 100644 --- a/print/templates/reports/driver-route/sql/routes.sql +++ b/print/templates/reports/driver-route/sql/routes.sql @@ -1,4 +1,4 @@ -SELECT +SELECT r.id, r.m3, r.created, @@ -11,9 +11,9 @@ SELECT FROM route r LEFT JOIN vehicle v ON v.id = r.vehicleFk LEFT JOIN worker w ON w.id = r.workerFk - LEFT JOIN account.user u ON u.id = w.userFk + LEFT JOIN account.user u ON u.id = w.id LEFT JOIN agencyMode am ON am.id = r.agencyModeFk LEFT JOIN agency a ON a.id = am.agencyFk LEFT JOIN supplierAgencyTerm sa ON sa.agencyFk = a.id LEFT JOIN supplier s ON s.id = sa.supplierFk -WHERE r.id IN(?) \ No newline at end of file +WHERE r.id IN(?) From 91c6ab9e440be19346a24d10eba3b507cefcb9be Mon Sep 17 00:00:00 2001 From: carlossa Date: Tue, 22 Aug 2023 12:50:27 +0200 Subject: [PATCH 038/427] refs #5843 edit structure --- db/changes/233601/00-dropUserFk.sql | 5 ++ db/dump/fixtures.sql | 16 ++--- db/dump/structure.sql | 105 +++++++++++++--------------- 3 files changed, 60 insertions(+), 66 deletions(-) create mode 100644 db/changes/233601/00-dropUserFk.sql diff --git a/db/changes/233601/00-dropUserFk.sql b/db/changes/233601/00-dropUserFk.sql new file mode 100644 index 000000000..ad4db3110 --- /dev/null +++ b/db/changes/233601/00-dropUserFk.sql @@ -0,0 +1,5 @@ +ALTER TABLE `vn`.`workerDocument` DROP FOREIGN KEY `workerDocument_ibfk_1`; + +ALTER TABLE `vn`.`worker` DROP KEY `user_id_UNIQUE`; + +ALTER TABLE `vn`.`worker` DROP COLUMN `userFk`; diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index b01c07461..e6e10b8ff 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -87,8 +87,8 @@ INSERT INTO `vn`.`educationLevel` (`id`, `name`) (1, 'ESTUDIOS PRIMARIOS COMPLETOS'), (2, 'ENSEÑANZAS DE BACHILLERATO'); -INSERT INTO `vn`.`worker`(`id`,`code`, `firstName`, `lastName`, `userFk`, `bossFk`) - SELECT id,UPPER(LPAD(role, 3, '0')), name, name, id, 9 +INSERT INTO `vn`.`worker`(`id`,`code`, `firstName`, `lastName`, `bossFk`) + SELECT id,UPPER(LPAD(role, 3, '0')), name, name, 9 FROM `account`.`user`; UPDATE `vn`.`worker` SET bossFk = NULL WHERE id = 20; @@ -188,13 +188,13 @@ INSERT INTO `vn`.`printer` (`id`, `name`, `path`, `isLabeler`, `sectorFk`, `ipAd UPDATE `vn`.`sector` SET mainPrinterFk = 1 WHERE id = 1; -INSERT INTO `vn`.`worker`(`id`, `code`, `firstName`, `lastName`, `userFk`,`bossFk`, `phone`) +INSERT INTO `vn`.`worker`(`id`, `code`, `firstName`, `lastName`,`bossFk`, `phone`) VALUES - (1106, 'LGN', 'David Charles', 'Haller', 1106, 19, 432978106), - (1107, 'ANT', 'Hank' , 'Pym' , 1107, 19, 432978107), - (1108, 'DCX', 'Charles' , 'Xavier', 1108, 19, 432978108), - (1109, 'HLK', 'Bruce' , 'Banner', 1109, 19, 432978109), - (1110, 'JJJ', 'Jessica' , 'Jones' , 1110, 19, 432978110); + (1106, 'LGN', 'David Charles', 'Haller', 19, 432978106), + (1107, 'ANT', 'Hank' , 'Pym' , 19, 432978107), + (1108, 'DCX', 'Charles' , 'Xavier', 19, 432978108), + (1109, 'HLK', 'Bruce' , 'Banner', 19, 432978109), + (1110, 'JJJ', 'Jessica' , 'Jones' , 19, 432978110); INSERT INTO `vn`.`parking` (`id`, `column`, `row`, `sectorFk`, `code`, `pickingOrder`) VALUES diff --git a/db/dump/structure.sql b/db/dump/structure.sql index 4e7127310..2d66d456c 100644 --- a/db/dump/structure.sql +++ b/db/dump/structure.sql @@ -24465,7 +24465,7 @@ BEGIN CONCAT('Cliente ', NEW.id), CONCAT('Recibida la documentación: ', vText) FROM worker w - LEFT JOIN account.user u ON w.userFk = u.id AND u.active + 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; @@ -45621,7 +45621,7 @@ BEGIN SELECT code INTO vUserCode FROM worker - WHERE userFk = account.myUser_getId(); + WHERE id = account.myUser_getId(); RETURN vUserCode; END ;; @@ -48037,22 +48037,22 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` FUNCTION `workerIsBoss`(vUserId INT) RETURNS int(11) +CREATE DEFINER=`root`@`localhost` FUNCTION `workerIsBoss`(vSelf INT) RETURNS int(11) DETERMINISTIC BEGIN /** * Comprueba por jerarquía si el trabajador actual es jefe * de un trabajador en concreto. * - * @param vUserId Id del trabajador que se desea comprobar. + * @param vSelf Id del trabajador que se desea comprobar. * @return Revuelve verdadero si es jefe del empleado por escala jerárquica. */ DECLARE vWorkerId INT; DECLARE vBossId INT; SELECT id INTO vWorkerId - FROM vn.worker - WHERE userFk = vUserId; + FROM worker + WHERE id = vSelf; IF vWorkerId IS NULL THEN CALL util.throw('USER_NOT_FOUND'); END IF; @@ -48064,7 +48064,7 @@ BEGIN SELECT id workerFk FROM worker LIMIT 0; LOOP SELECT bossFk INTO vBossId - FROM vn.worker + FROM worker WHERE id = vWorkerId; IF (SELECT COUNT(*) FROM tCheckedWorker WHERE workerFk = vBossId) THEN CALL util.throw('INFINITE_LOOP'); @@ -64369,7 +64369,7 @@ proc: BEGIN SELECT isTodayRelative INTO vIsTodayRelative FROM worker - WHERE userFk = getUser(); + WHERE id = getUser(); CALL prepareTicketList( util.VN_CURDATE() - INTERVAL 1 DAY, vEndingDate); @@ -70656,7 +70656,7 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_cloneWeekly`(IN vWeek INT) +CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_cloneWeekly`(vWeek INT) BEGIN DECLARE vIsDone BOOL; DECLARE vLanding DATE; @@ -70742,8 +70742,7 @@ BEGIN SELECT e.email INTO vSalesPersonEmail FROM vn.client c - JOIN vn.worker sp ON sp.id = c.salesPersonFk - JOIN account.emailUser e ON e.userFk = sp.userFk + JOIN account.emailUser e ON e.userFk = c.salesPersonFk WHERE c.id = vClientFk; SET vSubject = CONCAT('Turnos - No se ha podido clonar correctamente el ticket ', vTicketFk, @@ -72839,7 +72838,7 @@ BEGIN isAllowedToWork FROM(SELECT t.dated, b.id businessFk, - w.userFk, + w.id, b.departmentFk, IF(bs.started = NULL, NULL, GROUP_CONCAT(DISTINCT LEFT(bs.started,5) ORDER BY bs.started ASC SEPARATOR ' - ')) hourStart , IF(bs.started = NULL, NULL, GROUP_CONCAT(DISTINCT LEFT(bs.ended,5) ORDER BY bs.ended ASC SEPARATOR ' - ')) hourEnd, @@ -72849,18 +72848,19 @@ BEGIN at2.permissionRate, at2.discountRate, ct.hoursWeek hoursWeek, - at2.isAllowedToWork + at2.isAllowedToWork, + u.userFk FROM time t LEFT JOIN business b ON t.dated BETWEEN b.started AND IFNULL(b.ended, vDatedTo) LEFT JOIN worker w ON w.id = b.workerFk - JOIN tmp.`user` u ON u.userFK = w.userFK + JOIN tmp.`user` u ON u.userFK = w.id LEFT JOIN workCenter wc ON wc.id = b.workcenterFK LEFT JOIN calendarType ct ON ct.id = b.calendarTypeFk LEFT JOIN businessSchedule bs ON bs.businessFk = b.id AND bs.weekday = WEEKDAY(t.dated) + 1 LEFT JOIN calendar c ON c.businessFk = b.id AND c.dated = t.dated LEFT JOIN absenceType at2 ON at2.id = c.dayOffTypeFk WHERE t.dated BETWEEN vDatedFrom AND vDatedTo - GROUP BY w.userFk, t.dated + GROUP BY w.id, t.dated )sub; UPDATE tmp.timeBusinessCalculate t @@ -72913,13 +72913,9 @@ BEGIN * @param vDatedTo workerTimeControl */ - DROP TEMPORARY TABLE IF EXISTS tmp.`user`; - - CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` - SELECT userFk - FROM vn.worker w - JOIN account.`user` u ON u.id = w.userFk - WHERE userFk IS NOT NULL; + CREATE OR REPLACE TEMPORARY TABLE tmp.`user` + SELECT w.id userFk + FROM vn.worker w; CALL vn.timeBusiness_calculate(vDatedFrom, vDatedTo); @@ -73023,15 +73019,12 @@ BEGIN * @param vDatedTo workerTimeControl */ - DROP TEMPORARY TABLE IF EXISTS tmp.`user`; + CREATE OR REPLACE TEMPORARY TABLE tmp.`user` + SELECT w.id userFk + FROM worker w + WHERE w.id = vWorkerFk; - CREATE TEMPORARY TABLE tmp.`user` - SELECT u.id userFk - FROM account.user u - JOIN vn.worker w ON w.userFk = u.id - WHERE w.id = vWorkerFk; - - CALL vn.timeBusiness_calculate(vDatedFrom, vDatedTo); + CALL timeBusiness_calculate(vDatedFrom, vDatedTo); DROP TEMPORARY TABLE tmp.`user`; @@ -73273,13 +73266,9 @@ BEGIN * @param vDatedTo workerTimeControl */ - DROP TEMPORARY TABLE IF EXISTS tmp.`user`; - - CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` - SELECT userFk - FROM vn.worker w - JOIN account.`user` u ON u.id = w.userFk - WHERE userFk IS NOT NULL; + CREATE OR REPLACE TEMPORARY TABLE tmp.`user` + SELECT w.id userFk + FROM vn.worker w; CALL vn.timeControl_calculate(vDatedFrom, vDatedTo); @@ -74723,8 +74712,8 @@ BEGIN * Create new worker * */ - INSERT INTO worker(id, code, firstName, lastName, userFk, bossFk, fi, birth) - VALUES (vUserFk, vCode, vFirstname, vLastName, vUserFk, vBossFk, vFi, vBirth); + INSERT INTO worker(id, code, firstName, lastName, bossFk, fi, birth) + VALUES (vUserFk, vCode, vFirstname, vLastName, vBossFk, vFi, vBirth); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -74765,8 +74754,8 @@ BEGIN SET vSurnames = CONCAT(vSurname1, ' ', vSurname2); END IF; - INSERT INTO worker(id, firstName, lastName, code, userFk, isFreelance) - SELECT vUserId, vFirstName, vSurnames, vWorkerCode, vUserId, true; + INSERT INTO worker(id, firstName, lastName, code, isFreelance) + SELECT vUserId, vFirstName, vSurnames, vWorkerCode, true; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -74789,7 +74778,7 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.workerDepartmentByDate; CREATE TEMPORARY TABLE tmp.workerDepartmentByDate ENGINE = MEMORY - SELECT w.userFk, + SELECT w.id, w.lastName name, w.firstName firstname, d.name department, @@ -75490,7 +75479,7 @@ BEGIN LIMIT 10000000000000000000)sub GROUP BY cont HAVING cont2 MOD 2 = 1 - )sub2 + )sub2; JOIN worker w ON w.userFk = sub2.userFk; END ;; DELIMITER ; @@ -76550,10 +76539,10 @@ BEGIN w.lastName, w.firstname, c.fi, - w.id, + w.id userFk, MONTHNAME(t.dated) mes, YEAR(t.dated) año, - w.userFk, + w.id, tm.hoursWeek, tm.type, b.started, @@ -78136,7 +78125,7 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`zone_getLeaves`( vSearch VARCHAR(255), vHasInsert BOOL ) -BEGIN +BEGIN /** * Devuelve las ubicaciones incluidas en la ruta y que sean hijos de parentFk. * @param vSelf Id de la zona @@ -78151,23 +78140,23 @@ BEGIN CREATE OR REPLACE TEMPORARY TABLE tNodes (UNIQUE (id)) ENGINE = MEMORY - SELECT id - FROM zoneGeo + SELECT id + FROM zoneGeo LIMIT 0; IF vIsSearch THEN SET vIsNumber = vSearch REGEXP '^[0-9]+$'; - + INSERT INTO tNodes - SELECT id + SELECT id FROM zoneGeo WHERE (vIsNumber AND `name` = vSearch) OR (!vIsNumber AND `name` LIKE CONCAT('%', vSearch, '%')) LIMIT 1000; - + ELSEIF vParentFk IS NULL THEN INSERT INTO tNodes - SELECT geoFk + SELECT geoFk FROM zoneIncluded WHERE zoneFk = vSelf; END IF; @@ -78190,25 +78179,25 @@ BEGIN FROM zoneGeo g JOIN tChilds c ON c.id = g.id WHERE g.parentFk IS NOT NULL; - + INSERT IGNORE INTO tNodes SELECT id FROM tParents; - + IF NOT ROW_COUNT() THEN LEAVE myLoop; END IF; - + DELETE FROM tChilds; INSERT INTO tChilds SELECT id FROM tParents; END LOOP; - + DROP TEMPORARY TABLE tChilds, tParents; END IF; IF NOT vIsSearch THEN INSERT IGNORE INTO tNodes - SELECT id + SELECT id FROM zoneGeo WHERE parentFk <=> vParentFk; END IF; @@ -81824,7 +81813,7 @@ USE `vn`; /*!50001 SET collation_connection = utf8mb3_general_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `workerTimeControlUserInfo` AS select `u`.`id` AS `userFk`,`w`.`firstName` AS `name`,`w`.`lastName` AS `surname`,`u`.`name` AS `user`,`u`.`password` AS `password`,`wd`.`departmentFk` AS `departmentFk`,left(`c`.`fi`,8) AS `dni` from (((`account`.`user` `u` join `vn`.`worker` `w` on(`w`.`userFk` = `u`.`id`)) join `vn`.`client` `c` on(`c`.`id` = `u`.`id`)) left join `vn`.`workerDepartment` `wd` on(`wd`.`workerFk` = `w`.`id`)) */; +/*!50001 VIEW `workerTimeControlUserInfo` AS select `u`.`id` AS `userFk`,`w`.`firstName` AS `name`,`w`.`lastName` AS `surname`,`u`.`name` AS `user`,`u`.`password` AS `password`,`wd`.`departmentFk` AS `departmentFk`,left(`c`.`fi`,8) AS `dni` from (((`account`.`user` `u` join `vn`.`worker` `w` on(`w`.`id` = `u`.`id`)) join `vn`.`client` `c` on(`c`.`id` = `u`.`id`)) left join `vn`.`workerDepartment` `wd` on(`wd`.`workerFk` = `w`.`id`)) */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; From 1f63648697d585ef03cc18ba77108c14f744ba57 Mon Sep 17 00:00:00 2001 From: vicent Date: Thu, 24 Aug 2023 09:10:04 +0200 Subject: [PATCH 039/427] =?UTF-8?q?refs=20#5918=20fix:=20muestra=20los=20b?= =?UTF-8?q?otones=20en=20una=20l=C3=ADnea=20y=20no=20carga=20todos=20los?= =?UTF-8?q?=20datos=20de=20workerTimeControlMail=20de=20la=20semana?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- db/changes/233601/00-ACL_workerDepartment.sql | 3 +++ modules/worker/front/time-control/index.html | 12 +++++------- modules/worker/front/time-control/index.js | 3 ++- 3 files changed, 10 insertions(+), 8 deletions(-) create mode 100644 db/changes/233601/00-ACL_workerDepartment.sql diff --git a/db/changes/233601/00-ACL_workerDepartment.sql b/db/changes/233601/00-ACL_workerDepartment.sql new file mode 100644 index 000000000..ceb8d5d75 --- /dev/null +++ b/db/changes/233601/00-ACL_workerDepartment.sql @@ -0,0 +1,3 @@ +INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) + VALUES + ('WorkerDepartment', '*', '*', 'ALLOW', 'ROLE', 'employee'); diff --git a/modules/worker/front/time-control/index.html b/modules/worker/front/time-control/index.html index 307d9a50f..847eb9505 100644 --- a/modules/worker/front/time-control/index.html +++ b/modules/worker/front/time-control/index.html @@ -79,32 +79,30 @@ - + - - + ng-show="$ctrl.isHr && $ctrl.canResend"> diff --git a/modules/worker/front/time-control/index.js b/modules/worker/front/time-control/index.js index f63a766e8..91f095334 100644 --- a/modules/worker/front/time-control/index.js +++ b/modules/worker/front/time-control/index.js @@ -117,7 +117,8 @@ class Controller extends Section { where: { year: this._date.getFullYear(), week: this.getWeekNumber(this._date) - } + }, + limit: 1 }; this.$http.get('WorkerTimeControlMails', {filter}) .then(res => { From 3d4a99b07e0024d4161bbc91d65e5cd97c560973 Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 24 Aug 2023 10:51:34 +0200 Subject: [PATCH 040/427] refs 5914 transferInvoice created --- loopback/locale/es.json | 346 ++---------------- .../methods/invoiceOut/makePdfAndNotify.js | 2 +- ...ansferInvoiceOut.js => transferInvoice.js} | 28 +- .../front/descriptor-menu/index.html | 3 +- .../invoiceOut/front/descriptor-menu/index.js | 6 +- .../front/descriptor-menu/style.scss | 8 +- modules/ticket/back/methods/sale/clone.js | 171 ++++++--- modules/ticket/back/methods/sale/refund.js | 18 +- .../back/methods/ticket/invoiceTickets.js | 8 +- .../methods/ticket/invoiceTicketsWithPdf.js | 0 print/templates/reports/invoice/invoice.js | 3 + 11 files changed, 178 insertions(+), 415 deletions(-) rename modules/invoiceOut/back/methods/invoiceOut/{transferInvoiceOut.js => transferInvoice.js} (76%) create mode 100644 modules/ticket/back/methods/ticket/invoiceTicketsWithPdf.js diff --git a/loopback/locale/es.json b/loopback/locale/es.json index d196f99fa..627ab9a46 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -1,324 +1,26 @@ { - "Phone format is invalid": "El formato del teléfono no es correcto", - "You are not allowed to change the credit": "No tienes privilegios para modificar el crédito", - "Unable to mark the equivalence surcharge": "No se puede marcar el recargo de equivalencia", - "The default consignee can not be unchecked": "No se puede desmarcar el consignatario predeterminado", - "Unable to default a disabled consignee": "No se puede poner predeterminado un consignatario desactivado", - "Can't be blank": "No puede estar en blanco", - "Invalid TIN": "NIF/CIF invalido", - "TIN must be unique": "El NIF/CIF debe ser único", - "A client with that Web User name already exists": "Ya existe un cliente con ese Usuario Web", - "Is invalid": "Is invalid", - "Quantity cannot be zero": "La cantidad no puede ser cero", - "Enter an integer different to zero": "Introduce un entero distinto de cero", - "Package cannot be blank": "El embalaje no puede estar en blanco", - "The company name must be unique": "La razón social debe ser única", - "Invalid email": "Correo electrónico inválido", - "The IBAN does not have the correct format": "El IBAN no tiene el formato correcto", - "That payment method requires an IBAN": "El método de pago seleccionado requiere un IBAN", - "That payment method requires a BIC": "El método de pago seleccionado requiere un BIC", - "State cannot be blank": "El estado no puede estar en blanco", - "Worker cannot be blank": "El trabajador no puede estar en blanco", - "Cannot change the payment method if no salesperson": "No se puede cambiar la forma de pago si no hay comercial asignado", - "can't be blank": "El campo no puede estar vacío", - "Observation type must be unique": "El tipo de observación no puede repetirse", + "Name cannot be blank": "Name cannot be blank", + "Swift / BIC cannot be empty": "Swift / BIC cannot be empty", + "Social name should be uppercase": "Social name should be uppercase", + "Street cannot be empty": "Street cannot be empty", + "Street should be uppercase": "Street should be uppercase", + "City cannot be empty": "City cannot be empty", + "Invalid email": "Invalid email", + "Phone cannot be blank": "Phone cannot be blank", "The credit must be an integer greater than or equal to zero": "The credit must be an integer greater than or equal to zero", - "The grade must be similar to the last one": "El grade debe ser similar al último", - "Only manager can change the credit": "Solo el gerente puede cambiar el credito de este cliente", - "Name cannot be blank": "El nombre no puede estar en blanco", - "Phone cannot be blank": "El teléfono no puede estar en blanco", - "Period cannot be blank": "El periodo no puede estar en blanco", - "Choose a company": "Selecciona una empresa", - "Se debe rellenar el campo de texto": "Se debe rellenar el campo de texto", - "Description should have maximum of 45 characters": "La descripción debe tener maximo 45 caracteres", - "Cannot be blank": "El campo no puede estar en blanco", - "The grade must be an integer greater than or equal to zero": "El grade debe ser un entero mayor o igual a cero", - "Sample type cannot be blank": "El tipo de plantilla no puede quedar en blanco", - "Description cannot be blank": "Se debe rellenar el campo de texto", - "The new quantity should be smaller than the old one": "La nueva cantidad debe de ser menor que la anterior", - "The value should not be greater than 100%": "El valor no debe de ser mayor de 100%", - "The value should be a number": "El valor debe ser un numero", - "This order is not editable": "Esta orden no se puede modificar", - "You can't create an order for a frozen client": "No puedes crear una orden para un cliente congelado", - "You can't create an order for a client that has a debt": "No puedes crear una orden para un cliente con deuda", - "is not a valid date": "No es una fecha valida", - "Barcode must be unique": "El código de barras debe ser único", - "The warehouse can't be repeated": "El almacén no puede repetirse", - "The tag or priority can't be repeated for an item": "El tag o prioridad no puede repetirse para un item", - "The observation type can't be repeated": "El tipo de observación no puede repetirse", - "A claim with that sale already exists": "Ya existe una reclamación para esta línea", - "You don't have enough privileges to change that field": "No tienes permisos para cambiar ese campo", - "Warehouse cannot be blank": "El almacén no puede quedar en blanco", - "Agency cannot be blank": "La agencia no puede quedar en blanco", - "Not enough privileges to edit a client with verified data": "No tienes permisos para hacer cambios en un cliente con datos comprobados", - "This address doesn't exist": "Este consignatario no existe", - "You must delete the claim id %d first": "Antes debes borrar la reclamación %d", - "You don't have enough privileges": "No tienes suficientes permisos", - "Cannot check Equalization Tax in this NIF/CIF": "No se puede marcar RE en este NIF/CIF", - "You can't make changes on the basic data of an confirmed order or with rows": "No puedes cambiar los datos basicos de una orden con artículos", - "INVALID_USER_NAME": "El nombre de usuario solo debe contener letras minúsculas o, a partir del segundo carácter, números o subguiones, no esta permitido el uso de la letra ñ", - "You can't create a ticket for a frozen client": "No puedes crear un ticket para un cliente congelado", - "You can't create a ticket for a inactive client": "No puedes crear un ticket para un cliente inactivo", - "Tag value cannot be blank": "El valor del tag no puede quedar en blanco", - "ORDER_EMPTY": "Cesta vacía", - "You don't have enough privileges to do that": "No tienes permisos para cambiar esto", - "NO SE PUEDE DESACTIVAR EL CONSIGNAT": "NO SE PUEDE DESACTIVAR EL CONSIGNAT", - "Error. El NIF/CIF está repetido": "Error. El NIF/CIF está repetido", - "Street cannot be empty": "Dirección no puede estar en blanco", - "City cannot be empty": "Cuidad no puede estar en blanco", - "Code cannot be blank": "Código no puede estar en blanco", - "You cannot remove this department": "No puedes eliminar este departamento", - "The extension must be unique": "La extensión debe ser unica", - "The secret can't be blank": "La contraseña no puede estar en blanco", - "We weren't able to send this SMS": "No hemos podido enviar el SMS", - "This client can't be invoiced": "Este cliente no puede ser facturado", - "This ticket can't be invoiced": "Este ticket no puede ser facturado", - "You cannot add or modify services to an invoiced ticket": "No puedes añadir o modificar servicios a un ticket facturado", - "This ticket can not be modified": "Este ticket no puede ser modificado", - "The introduced hour already exists": "Esta hora ya ha sido introducida", - "INFINITE_LOOP": "Existe una dependencia entre dos Jefes", - "The sales of the receiver ticket can't be modified": "Las lineas del ticket al que envias no pueden ser modificadas", - "NO_AGENCY_AVAILABLE": "No hay una zona de reparto disponible con estos parámetros", - "ERROR_PAST_SHIPMENT": "No puedes seleccionar una fecha de envío en pasado", - "The current ticket can't be modified": "El ticket actual no puede ser modificado", - "The current claim can't be modified": "La reclamación actual no puede ser modificada", - "The sales of this ticket can't be modified": "Las lineas de este ticket no pueden ser modificadas", - "The sales do not exists": "La(s) línea(s) seleccionada(s) no existe(n)", - "Please select at least one sale": "Por favor selecciona al menos una linea", - "All sales must belong to the same ticket": "Todas las lineas deben pertenecer al mismo ticket", - "NO_ZONE_FOR_THIS_PARAMETERS": "Para este día no hay ninguna zona configurada", - "This item doesn't exists": "El artículo no existe", - "NOT_ZONE_WITH_THIS_PARAMETERS": "Para este día no hay ninguna zona configurada", - "Extension format is invalid": "El formato de la extensión es inválido", - "Invalid parameters to create a new ticket": "Parámetros inválidos para crear un nuevo ticket", - "This item is not available": "Este artículo no está disponible", - "This postcode already exists": "Este código postal ya existe", - "Concept cannot be blank": "El concepto no puede quedar en blanco", - "File doesn't exists": "El archivo no existe", - "You don't have privileges to change the zone": "No tienes permisos para cambiar la zona o para esos parámetros hay más de una opción de envío, hable con las agencias", - "This ticket is already on weekly tickets": "Este ticket ya está en tickets programados", - "Ticket id cannot be blank": "El id de ticket no puede quedar en blanco", - "Weekday cannot be blank": "El día de la semana no puede quedar en blanco", - "You can't delete a confirmed order": "No puedes borrar un pedido confirmado", - "The social name has an invalid format": "El nombre fiscal tiene un formato incorrecto", - "Invalid quantity": "Cantidad invalida", - "This postal code is not valid": "This postal code is not valid", - "is invalid": "is invalid", - "The postcode doesn't exist. Please enter a correct one": "El código postal no existe. Por favor, introduce uno correcto", - "The department name can't be repeated": "El nombre del departamento no puede repetirse", - "This phone already exists": "Este teléfono ya existe", - "You cannot move a parent to its own sons": "No puedes mover un elemento padre a uno de sus hijos", - "You can't create a claim for a removed ticket": "No puedes crear una reclamación para un ticket eliminado", - "You cannot delete a ticket that part of it is being prepared": "No puedes eliminar un ticket en el que una parte que está siendo preparada", - "You must delete all the buy requests first": "Debes eliminar todas las peticiones de compra primero", - "You should specify a date": "Debes especificar una fecha", - "You should specify at least a start or end date": "Debes especificar al menos una fecha de inicio o de fín", - "Start date should be lower than end date": "La fecha de inicio debe ser menor que la fecha de fín", - "You should mark at least one week day": "Debes marcar al menos un día de la semana", - "Swift / BIC can't be empty": "Swift / BIC no puede estar vacío", - "Customs agent is required for a non UEE member": "El agente de aduanas es requerido para los clientes extracomunitarios", - "Incoterms is required for a non UEE member": "El incoterms es requerido para los clientes extracomunitarios", - "Deleted sales from ticket": "He eliminado las siguientes lineas del ticket [{{ticketId}}]({{{ticketUrl}}}): {{{deletions}}}", - "Added sale to ticket": "He añadido la siguiente linea al ticket [{{ticketId}}]({{{ticketUrl}}}): {{{addition}}}", - "Changed sale discount": "He cambiado el descuento de las siguientes lineas al ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}", - "Created claim": "He creado la reclamación [{{claimId}}]({{{claimUrl}}}) de las siguientes lineas del ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}", - "Changed sale price": "He cambiado el precio de [{{itemId}} {{concept}}]({{{itemUrl}}}) ({{quantity}}) de {{oldPrice}}€ ➔ *{{newPrice}}€* del ticket [{{ticketId}}]({{{ticketUrl}}})", - "Changed sale quantity": "He cambiado la cantidad de [{{itemId}} {{concept}}]({{{itemUrl}}}) de {{oldQuantity}} ➔ *{{newQuantity}}* del ticket [{{ticketId}}]({{{ticketUrl}}})", - "State": "Estado", - "regular": "normal", - "reserved": "reservado", - "Changed sale reserved state": "He cambiado el estado reservado de las siguientes lineas al ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}", - "Bought units from buy request": "Se ha comprado {{quantity}} unidades de [{{itemId}} {{concept}}]({{{urlItem}}}) para el ticket id [{{ticketId}}]({{{url}}})", - "Deny buy request": "Se ha rechazado la petición de compra para el ticket id [{{ticketId}}]({{{url}}}). Motivo: {{observation}}", - "MESSAGE_INSURANCE_CHANGE": "He cambiado el crédito asegurado del cliente [{{clientName}} ({{clientId}})]({{{url}}}) a *{{credit}} €*", - "Changed client paymethod": "He cambiado la forma de pago del cliente [{{clientName}} ({{clientId}})]({{{url}}})", - "Sent units from ticket": "Envio *{{quantity}}* unidades de [{{concept}} ({{itemId}})]({{{itemUrl}}}) a *\"{{nickname}}\"* provenientes del ticket id [{{ticketId}}]({{{ticketUrl}}})", - "Change quantity": "{{concept}} cambia de {{oldQuantity}} a {{newQuantity}}", - "Claim will be picked": "Se recogerá el género de la reclamación [({{claimId}})]({{{claimUrl}}}) del cliente *{{clientName}}*", - "Claim state has changed to incomplete": "Se ha cambiado el estado de la reclamación [({{claimId}})]({{{claimUrl}}}) del cliente *{{clientName}}* a *incompleta*", - "Claim state has changed to canceled": "Se ha cambiado el estado de la reclamación [({{claimId}})]({{{claimUrl}}}) del cliente *{{clientName}}* a *anulado*", - "Client checked as validated despite of duplication": "Cliente comprobado a pesar de que existe el cliente id {{clientId}}", - "ORDER_ROW_UNAVAILABLE": "No hay disponibilidad de este producto", - "Distance must be lesser than 1000": "La distancia debe ser inferior a 1000", - "This ticket is deleted": "Este ticket está eliminado", - "Unable to clone this travel": "No ha sido posible clonar este travel", - "This thermograph id already exists": "La id del termógrafo ya existe", - "Choose a date range or days forward": "Selecciona un rango de fechas o días en adelante", - "ORDER_ALREADY_CONFIRMED": "ORDER_ALREADY_CONFIRMED", - "Invalid password": "Invalid password", - "Password does not meet requirements": "La contraseña no cumple los requisitos", - "Role already assigned": "Role already assigned", - "Invalid role name": "Invalid role name", - "Role name must be written in camelCase": "Role name must be written in camelCase", - "Email already exists": "Email already exists", - "User already exists": "User already exists", - "Absence change notification on the labour calendar": "Notificacion de cambio de ausencia en el calendario laboral", - "Record of hours week": "Registro de horas semana {{week}} año {{year}} ", - "Created absence": "El empleado {{author}} ha añadido una ausencia de tipo '{{absenceType}}' a {{employee}} para el día {{dated}}.", - "Deleted absence": "El empleado {{author}} ha eliminado una ausencia de tipo '{{absenceType}}' a {{employee}} del día {{dated}}.", - "I have deleted the ticket id": "He eliminado el ticket id [{{id}}]({{{url}}})", - "I have restored the ticket id": "He restaurado el ticket id [{{id}}]({{{url}}})", - "You can only restore a ticket within the first hour after deletion": "Únicamente puedes restaurar el ticket dentro de la primera hora después de su eliminación", - "Changed this data from the ticket": "He cambiado estos datos del ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}", - "agencyModeFk": "Agencia", - "clientFk": "Cliente", - "zoneFk": "Zona", - "warehouseFk": "Almacén", - "shipped": "F. envío", - "landed": "F. entrega", - "addressFk": "Consignatario", - "companyFk": "Empresa", - "The social name cannot be empty": "La razón social no puede quedar en blanco", - "The nif cannot be empty": "El NIF no puede quedar en blanco", - "You need to fill sage information before you check verified data": "Debes rellenar la información de sage antes de marcar datos comprobados", - "ASSIGN_ZONE_FIRST": "Asigna una zona primero", - "Amount cannot be zero": "El importe no puede ser cero", - "Company has to be official": "Empresa inválida", - "You can not select this payment method without a registered bankery account": "No se puede utilizar este método de pago si no has registrado una cuenta bancaria", - "Action not allowed on the test environment": "Esta acción no está permitida en el entorno de pruebas", - "The selected ticket is not suitable for this route": "El ticket seleccionado no es apto para esta ruta", - "New ticket request has been created with price": "Se ha creado una nueva petición de compra '{{description}}' para el día *{{shipped}}*, con una cantidad de *{{quantity}}* y un precio de *{{price}} €*", - "New ticket request has been created": "Se ha creado una nueva petición de compra '{{description}}' para el día *{{shipped}}*, con una cantidad de *{{quantity}}*", - "Swift / BIC cannot be empty": "Swift / BIC no puede estar vacío", - "This BIC already exist.": "Este BIC ya existe.", - "That item doesn't exists": "Ese artículo no existe", - "There's a new urgent ticket:": "Hay un nuevo ticket urgente:", - "Invalid account": "Cuenta inválida", - "Compensation account is empty": "La cuenta para compensar está vacia", - "This genus already exist": "Este genus ya existe", - "This specie already exist": "Esta especie ya existe", - "Client assignment has changed": "He cambiado el comercial ~*\"<{{previousWorkerName}}>\"*~ por *\"<{{currentWorkerName}}>\"* del cliente [{{clientName}} ({{clientId}})]({{{url}}})", - "None": "Ninguno", - "The contract was not active during the selected date": "El contrato no estaba activo durante la fecha seleccionada", - "Cannot add more than one '1/2 day vacation'": "No puedes añadir más de un 'Vacaciones 1/2 dia'", - "This document already exists on this ticket": "Este documento ya existe en el ticket", - "Some of the selected tickets are not billable": "Algunos de los tickets seleccionados no son facturables", - "You can't invoice tickets from multiple clients": "No puedes facturar tickets de multiples clientes", - "nickname": "nickname", - "INACTIVE_PROVIDER": "Proveedor inactivo", - "This client is not invoiceable": "Este cliente no es facturable", - "serial non editable": "Esta serie no permite asignar la referencia", - "Max shipped required": "La fecha límite es requerida", - "Can't invoice to future": "No se puede facturar a futuro", - "Can't invoice to past": "No se puede facturar a pasado", - "This ticket is already invoiced": "Este ticket ya está facturado", - "A ticket with an amount of zero can't be invoiced": "No se puede facturar un ticket con importe cero", - "A ticket with a negative base can't be invoiced": "No se puede facturar un ticket con una base negativa", - "Global invoicing failed": "[Facturación global] No se han podido facturar algunos clientes", - "Wasn't able to invoice the following clients": "No se han podido facturar los siguientes clientes", - "Can't verify data unless the client has a business type": "No se puede verificar datos de un cliente que no tiene tipo de negocio", - "You don't have enough privileges to set this credit amount": "No tienes suficientes privilegios para establecer esta cantidad de crédito", - "You can't change the credit set to zero from a financialBoss": "No puedes cambiar el cŕedito establecido a cero por un jefe de finanzas", - "Amounts do not match": "Las cantidades no coinciden", - "The PDF document does not exist": "El documento PDF no existe. Prueba a regenerarlo desde la opción 'Regenerar PDF factura'", - "The type of business must be filled in basic data": "El tipo de negocio debe estar rellenado en datos básicos", - "You can't create a claim from a ticket delivered more than seven days ago": "No puedes crear una reclamación de un ticket entregado hace más de siete días", - "The worker has hours recorded that day": "El trabajador tiene horas fichadas ese día", - "The worker has a marked absence that day": "El trabajador tiene marcada una ausencia ese día", - "You can not modify is pay method checked": "No se puede modificar el campo método de pago validado", - "Can't transfer claimed sales": "No puedes transferir lineas reclamadas", - "You don't have privileges to create refund": "No tienes permisos para crear un abono", - "The item is required": "El artículo es requerido", - "The agency is already assigned to another autonomous": "La agencia ya está asignada a otro autónomo", - "date in the future": "Fecha en el futuro", - "reference duplicated": "Referencia duplicada", - "This ticket is already a refund": "Este ticket ya es un abono", - "isWithoutNegatives": "isWithoutNegatives", - "routeFk": "routeFk", - "Can't change the password of another worker": "No se puede cambiar la contraseña de otro trabajador", - "No hay un contrato en vigor": "No hay un contrato en vigor", - "No se permite fichar a futuro": "No se permite fichar a futuro", - "No está permitido trabajar": "No está permitido trabajar", - "Fichadas impares": "Fichadas impares", - "Descanso diario 12h.": "Descanso diario 12h.", - "Descanso semanal 36h. / 72h.": "Descanso semanal 36h. / 72h.", - "Dirección incorrecta": "Dirección incorrecta", - "Modifiable user details only by an administrator": "Detalles de usuario modificables solo por un administrador", - "Modifiable password only via recovery or by an administrator": "Contraseña modificable solo a través de la recuperación o por un administrador", - "Not enough privileges to edit a client": "No tienes suficientes privilegios para editar un cliente", - "This route does not exists": "Esta ruta no existe", - "Claim pickup order sent": "Reclamación Orden de recogida enviada [{{claimId}}]({{{claimUrl}}}) al cliente *{{clientName}}*", - "You don't have grant privilege": "No tienes privilegios para dar privilegios", - "You don't own the role and you can't assign it to another user": "No eres el propietario del rol y no puedes asignarlo a otro usuario", - "Ticket merged": "Ticket [{{originId}}]({{{originFullPath}}}) ({{{originDated}}}) fusionado con [{{destinationId}}]({{{destinationFullPath}}}) ({{{destinationDated}}})", - "Already has this status": "Ya tiene este estado", - "There aren't records for this week": "No existen registros para esta semana", - "Empty data source": "Origen de datos vacio", - "App locked": "Aplicación bloqueada por el usuario {{userId}}", - "Email verify": "Correo de verificación", - "Landing cannot be lesser than shipment": "Landing cannot be lesser than shipment", - "Receipt's bank was not found": "No se encontró el banco del recibo", - "This receipt was not compensated": "Este recibo no ha sido compensado", - "Client's email was not found": "No se encontró el email del cliente", - "Negative basis": "Base negativa", - "This worker code already exists": "Este codigo de trabajador ya existe", - "This personal mail already exists": "Este correo personal ya existe", - "This worker already exists": "Este trabajador ya existe", - "App name does not exist": "El nombre de aplicación no es válido", - "Try again": "Vuelve a intentarlo", - "Aplicación bloqueada por el usuario 9": "Aplicación bloqueada por el usuario 9", - "Failed to upload delivery note": "Error al subir albarán {{id}}", - "The DOCUWARE PDF document does not exists": "El documento PDF Docuware no existe", - "It is not possible to modify tracked sales": "No es posible modificar líneas de pedido que se hayan empezado a preparar", - "It is not possible to modify sales that their articles are from Floramondo": "No es posible modificar líneas de pedido cuyos artículos sean de Floramondo", - "It is not possible to modify cloned sales": "No es posible modificar líneas de pedido clonadas", - "A supplier with the same name already exists. Change the country.": "Un proveedor con el mismo nombre ya existe. Cambie el país.", - "There is no assigned email for this client": "No hay correo asignado para este cliente", - "Exists an invoice with a future date": "Existe una factura con fecha posterior", - "Invoice date can't be less than max date": "La fecha de factura no puede ser inferior a la fecha límite", - "Warehouse inventory not set": "El almacén inventario no está establecido", - "This locker has already been assigned": "Esta taquilla ya ha sido asignada", - "Tickets with associated refunds": "No se pueden borrar tickets con abonos asociados. Este ticket está asociado al abono Nº %d", - "Not exist this branch": "La rama no existe", - "This ticket cannot be signed because it has not been boxed": "Este ticket no puede firmarse porque no ha sido encajado", - "Collection does not exist": "La colección no existe", - "Cannot obtain exclusive lock": "No se puede obtener un bloqueo exclusivo", - "Insert a date range": "Inserte un rango de fechas", - "Added observation": "{{user}} añadió esta observacion: {{text}}", - "Comment added to client": "Observación añadida al cliente {{clientFk}}", - "Invalid auth code": "Código de verificación incorrecto", - "Invalid or expired verification code": "Código de verificación incorrecto o expirado", - "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", - "Pass expired": "La contraseña ha caducado, cambiela desde Salix", - "Invalid NIF for VIES": "Invalid NIF for VIES", - "Ticket does not exist": "Este ticket no existe", - "Ticket is already signed": "Este ticket ya ha sido firmado", - "Authentication failed": "Autenticación fallida", - "You can't use the same password": "No puedes usar la misma contraseña", - "You can only add negative amounts in refund tickets": "Solo se puede añadir cantidades negativas en tickets abono", - "Fecha fuera de rango": "Fecha fuera de rango", - "Error while generating PDF": "Error al generar PDF", - "Error when sending mail to client": "Error al enviar el correo al cliente", - "Mail not sent": "Se ha producido un fallo al enviar la factura al cliente [{{clientId}}]({{{clientUrl}}}), por favor revisa la dirección de correo electrónico", - "The renew period has not been exceeded": "El periodo de renovación no ha sido superado", - "Valid priorities": "Prioridades válidas: %d", - "Negative basis of tickets": "Base negativa para los tickets: {{ticketsIds}}", - "You cannot assign an alias that you are not assigned to": "No puede asignar un alias que no tenga asignado", - "This ticket cannot be left empty.": "Este ticket no se puede dejar vacío. %s", - "The company has not informed the supplier account for bank transfers": "La empresa no tiene informado la cuenta de proveedor para transferencias bancarias", - "You cannot assign/remove an alias that you are not assigned to": "No puede asignar/eliminar un alias que no tenga asignado", - "This invoice has a linked vehicle.": "Esta factura tiene un vehiculo vinculado", - "You don't have enough privileges.": "No tienes suficientes permisos.", - "This ticket is locked.": "Este ticket está bloqueado.", - "This ticket is not editable.": "Este ticket no es editable.", - "The ticket doesn't exist.": "No existe el ticket.", -<<<<<<< HEAD - "There are missing fields.": "There are missing fields." -} -======= - "Social name should be uppercase": "La razón social debe ir en mayúscula", - "Street should be uppercase": "La dirección fiscal debe ir en mayúscula" -} ->>>>>>> ce78fc8e5dd383b3c6457fe5f78a45b21b246858 + "The grade must be an integer greater than or equal to zero": "The grade must be an integer greater than or equal to zero", + "Description should have maximum of 45 characters": "Description should have maximum of 45 characters", + "Amount cannot be zero": "Amount cannot be zero", + "Period cannot be blank": "Period cannot be blank", + "Sample type cannot be blank": "Sample type cannot be blank", + "Cannot be blank": "Cannot be blank", + "The social name cannot be empty": "The social name cannot be empty", + "Concept cannot be blank": "Concept cannot be blank", + "Enter an integer different to zero": "Enter an integer different to zero", + "Package cannot be blank": "Package cannot be blank", + "State cannot be blank": "State cannot be blank", + "Worker cannot be blank": "Worker cannot be blank", + "Description cannot be blank": "Description cannot be blank", + "Agency cannot be blank": "Agency cannot be blank", + "The renew period has not been exceeded": "The renew period has not been exceeded" +} \ No newline at end of file diff --git a/modules/invoiceOut/back/methods/invoiceOut/makePdfAndNotify.js b/modules/invoiceOut/back/methods/invoiceOut/makePdfAndNotify.js index a48664b30..e13ec0255 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/makePdfAndNotify.js +++ b/modules/invoiceOut/back/methods/invoiceOut/makePdfAndNotify.js @@ -23,7 +23,7 @@ module.exports = Self => { } }); - Self.makePdfAndNotify = async function(ctx, id, printerFk) { + Self.makePdfAndNotify = async function(ctx, id, printerFk, options) { const models = Self.app.models; options = typeof options == 'object' diff --git a/modules/invoiceOut/back/methods/invoiceOut/transferInvoiceOut.js b/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js similarity index 76% rename from modules/invoiceOut/back/methods/invoiceOut/transferInvoiceOut.js rename to modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js index 440ebe4d3..c590ff9ea 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/transferInvoiceOut.js +++ b/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js @@ -1,6 +1,6 @@ module.exports = Self => { - Self.remoteMethodCtx('transferInvoiceOut', { - description: 'Transfer an invoice out to another client', + Self.remoteMethodCtx('transferInvoice', { + description: 'Transfer an issued invoice to another client', accessType: 'WRITE', accepts: [ { @@ -49,7 +49,6 @@ module.exports = Self => { const myOptions = {userId: ctx.req.accessToken.userId}; let tx; - if (typeof options == 'object') Object.assign(myOptions, options); @@ -59,15 +58,21 @@ module.exports = Self => { } try { // Refund tickets and group - const filter = {where: {refFk: ref}}; - const tickets = await models.Ticket.find(filter, myOptions); + const filterRef = {where: {refFk: ref}}; + const tickets = await models.Ticket.find(filterRef, myOptions); const ticketsIds = tickets.map(ticket => ticket.id); await models.Ticket.refund(ctx, ticketsIds, null, myOptions); + // Clone tickets - const services = await models.TicketService.find(filter, myOptions); + const filterTicket = {where: {ticketFk: {inq: ticketsIds}}}; + + const services = await models.TicketService.find(filterTicket, myOptions); const servicesIds = services.map(service => service.id); - const sales = await models.Sale.find({where: {ticketFk: {inq: ticketsIds}}}, myOptions); - const clonedTickets = await models.Sale.clone(sales, servicesIds, null, false, false, myOptions); + + const sales = await models.Sale.find(filterTicket, myOptions); + const salesIds = sales.map(sale => sale.id); + + const clonedTickets = await models.Sale.clone(salesIds, servicesIds, null, false, false, myOptions); const clonedTicketIds = []; // Update client @@ -77,7 +82,8 @@ module.exports = Self => { } // Quick invoice - const invoiceId = await models.Ticket.invoiceTickets(ctx, clonedTicketIds, myOptions); + const invoiceIds = await models.Ticket.invoiceTickets(ctx, clonedTicketIds, myOptions); + const [invoiceId] = invoiceIds; // Insert InvoiceCorrection await models.InvoiceCorrection.create({ @@ -89,6 +95,10 @@ module.exports = Self => { }, myOptions); if (tx) await tx.commit(); + + // Crear PDF + await models.InvoiceOut.makePdfAndNotify(ctx, invoiceId, null); + return invoiceId; } catch (e) { if (tx) await tx.rollback(); diff --git a/modules/invoiceOut/front/descriptor-menu/index.html b/modules/invoiceOut/front/descriptor-menu/index.html index dc5c2a8e9..7d465f4ea 100644 --- a/modules/invoiceOut/front/descriptor-menu/index.html +++ b/modules/invoiceOut/front/descriptor-menu/index.html @@ -184,9 +184,9 @@ +
+
diff --git a/modules/invoiceOut/front/descriptor-menu/index.js b/modules/invoiceOut/front/descriptor-menu/index.js index ef69098c4..7d2644158 100644 --- a/modules/invoiceOut/front/descriptor-menu/index.js +++ b/modules/invoiceOut/front/descriptor-menu/index.js @@ -136,9 +136,9 @@ class Controller extends Section { invoiceCorrectionTypeId: this.invoiceCorrectionType }; this.$http.post(`InvoiceOuts/transferInvoice`, params).then(res => { - newInvoice = res.data;// id de la nueva factura - this.vnApp.showSucces(this.$t('Invoice trasfered!')); - this.$state.go('invoiceOut.index', {id: newInvoice}); + const invoiceId = res.data; + this.vnApp.showSuccess(this.$t('Invoice trasfered!')); + this.$state.go('invoiceOut.card.summary', {id: invoiceId}); }); } } diff --git a/modules/invoiceOut/front/descriptor-menu/style.scss b/modules/invoiceOut/front/descriptor-menu/style.scss index b68301961..25c02c80c 100644 --- a/modules/invoiceOut/front/descriptor-menu/style.scss +++ b/modules/invoiceOut/front/descriptor-menu/style.scss @@ -21,4 +21,10 @@ vn-invoice-out-descriptor-menu { font-size: 1.75rem; } } -} \ No newline at end of file + +} +@media screen and (min-width: 1000px) { + .transferInvoice { + min-width: 900px; + } +} diff --git a/modules/ticket/back/methods/sale/clone.js b/modules/ticket/back/methods/sale/clone.js index 7d52fd0e6..9a3b5fedc 100644 --- a/modules/ticket/back/methods/sale/clone.js +++ b/modules/ticket/back/methods/sale/clone.js @@ -1,5 +1,5 @@ module.exports = Self => { - Self.clone = async(sales, servicesIds, withWarehouse, group, negative, options) => { + Self.clone = async(salesIds, servicesIds, withWarehouse, group, negative, options) => { const models = Self.app.models; const myOptions = {}; let tx; @@ -12,91 +12,142 @@ module.exports = Self => { myOptions.transaction = tx; } - const ticketsIds = [...new Set(sales.map(sale => sale.ticketFk))]; - const now = Date.vnNew(); - let updatedTickets = []; - let newTicket; - const filter = { - include: [ - {relation: 'address'}, - { - relation: 'sale', - where: {saleFk: {inq: sales}}, - }, - ] - }; try { - for (const [index, ticketId] of ticketsIds.entries()) { - const ticket = await models.Ticket.findById(ticketId, filter, myOptions); - if (!group || !index) { - newTicket = await models.Ticket.create({ - clientFk: ticket.clientFk, - shipped: now, - addressFk: ticket.address().id, - nickname: ticket.address().nickname, - warehouseFk: withWarehouse ? ticket.warehouseFk : null, - companyFk: ticket.companyFk, - landed: now, - }, myOptions); - updatedTickets.push(newTicket); - } - const salesByTicket = ticket.sale(); - const saleIds = salesByTicket.map(sale => sale.id); - const saleComponentsFilter = { - where: {saleFk: {inq: saleIds}}, + const salesFilter = { + where: {id: {inq: salesIds}}, + include: { + relation: 'components', scope: { fields: ['saleFk', 'componentFk', 'value'] } - }; - for (const sale of salesByTicket) { - const createdSale = await models.Sale.create({ - ticketFk: newTicket.id, - itemFk: sale.itemFk, - quantity: (negative) ? - sale.quantity : sale.quantity, - concept: sale.concept, - price: sale.price, - discount: sale.discount, - }, myOptions); - const components = await models.SaleComponent.find(saleComponentsFilter, myOptions); // Revisar con Alex - // const components = sale.components(); - for (const component of components) - component.saleFk = createdSale.id; + } + }; + const sales = await models.Sale.find(salesFilter, myOptions); + const ticketsIds = [...new Set(sales.map(sale => sale.ticketFk))]; - await models.SaleComponent.create(components, myOptions); + const refundTickets = []; + const mappedTickets = new Map(); + const now = Date.vnNew(); + + const [firstTicketId] = ticketsIds; + if (group) { + await createTicketRefund( + firstTicketId, + withWarehouse, + refundTickets, + mappedTickets, + now, + myOptions + ); + } else { + for (let ticketId of ticketsIds) { + await createTicketRefund( + ticketId, + withWarehouse, + refundTickets, + mappedTickets, + now, + myOptions + ); } } + + for (const sale of sales) { + const refundTicketId = await getTicketRefundId(group, sale.ticketFk, refundTickets, mappedTickets); + + const createdSale = await models.Sale.create({ + ticketFk: refundTicketId, + itemFk: sale.itemFk, + quantity: negative ? - sale.quantity : sale.quantity, + concept: sale.concept, + price: sale.price, + discount: sale.discount, + }, myOptions); + + const components = sale.components(); + for (const component of components) + component.saleFk = createdSale.id; + + await models.SaleComponent.create(components, myOptions); + } + if (servicesIds && servicesIds.length > 0) { const servicesFilter = { where: {id: {inq: servicesIds}} }; const services = await models.TicketService.find(servicesFilter, myOptions); + for (const service of services) { + const refundTicketId = await getTicketRefundId(group, service.ticketFk, refundTickets, mappedTickets); + await models.TicketService.create({ description: service.description, - quantity: (negative) ? - service.quantity : service.quantity, + quantity: negative ? - service.quantity : service.quantity, price: service.price, taxClassFk: service.taxClassFk, - ticketFk: service.ticketFk, + ticketFk: refundTicketId, ticketServiceTypeFk: service.ticketServiceTypeFk, }, myOptions); } } - const query = `CALL vn.ticket_recalc(?, NULL)`; + if (tx) await tx.commit(); - if (group) { - await Self.rawSql(query, [newTicket.id], myOptions); - if (tx) await tx.commit(); - return newTicket; - } else { - for (const updatedTicket of updatedTickets) - await Self.rawSql(query, [updatedTicket.id], myOptions); - if (tx) await tx.commit(); - return /* updatedTickets */updatedTickets; - } + return refundTickets; } catch (e) { if (tx) await tx.rollback(); throw e; } }; + + async function createTicketRefund( + ticketId, + withWarehouse, + refundTickets, + mappedTickets, + now, + myOptions + ) { + const models = Self.app.models; + + const filter = { + include: [ + { + relation: 'address' + }, + { + relation: 'agencyMode' + }, + { + relation: 'zone' + } + ] + }; + const ticket = await models.Ticket.findById(ticketId, filter, myOptions); + const refundTicket = await models.Ticket.create({ + clientFk: ticket.clientFk, + shipped: now, + addressFk: ticket.address().id, + agencyModeFk: ticket.agencyMode().id, + nickname: ticket.address().nickname, + warehouseFk: withWarehouse ? ticket.warehouseFk : null, + companyFk: ticket.companyFk, + zonePrice: ticket.zonePrice, + zoneBonus: ticket.zoneBonus, + weight: ticket.weight, + landed: now, + zoneFk: ticket.zone().id, + }, myOptions); + + refundTickets.push(refundTicket); + + mappedTickets.set(ticketId, refundTicket.id); + } + + async function getTicketRefundId(group, ticketId, refundTickets, mappedTickets) { + if (group) { + const [firstRefundTicket] = refundTickets; + return firstRefundTicket.id; + } else return mappedTickets.get(ticketId); + } }; diff --git a/modules/ticket/back/methods/sale/refund.js b/modules/ticket/back/methods/sale/refund.js index dabafb469..3f7e1cd21 100644 --- a/modules/ticket/back/methods/sale/refund.js +++ b/modules/ticket/back/methods/sale/refund.js @@ -64,27 +64,19 @@ module.exports = Self => { } } }; - const sales = await models.Sale.find(salesFilter, myOptions); + // const sales = await models.Sale.find(salesFilter, myOptions); const refundTicket = await models.Sale.clone( - sales, - refundAgencyMode, - refoundZoneId, + salesIds, servicesIds, withWarehouse, + // refundAgencyMode, + // refoundZoneId, true, true, myOptions ); - const ticketsIds = [...new Set(sales.map(sale => sale.ticketFk))]; - for (const ticketId of ticketsIds) { - await models.TicketRefund.create({ - refundTicketFk: refundTicket.id, - originalTicketFk: ticketId, - }, myOptions); - } - - if (tx) await tx.commit(); + if (tx && !options) await tx.commit(); return refundTicket; } catch (e) { diff --git a/modules/ticket/back/methods/ticket/invoiceTickets.js b/modules/ticket/back/methods/ticket/invoiceTickets.js index 7baee133d..e65c14e9a 100644 --- a/modules/ticket/back/methods/ticket/invoiceTickets.js +++ b/modules/ticket/back/methods/ticket/invoiceTickets.js @@ -77,10 +77,9 @@ module.exports = function(Self) { if (tx) await tx.rollback(); throw e; } - console.log(invoicesIds, 'invoicesIds'); - for (const invoiceId of invoicesIds) { - console.log(await models.InvoiceOut.find()); - await models.InvoiceOut.makePdfAndNotify(ctx, invoiceId, null); + if (tx) { + for (const invoiceId of invoicesIds) + await models.InvoiceOut.makePdfAndNotify(ctx, invoiceId, null, myOptions); } return invoicesIds; @@ -100,7 +99,6 @@ module.exports = function(Self) { `, [ticketsIds], myOptions); const invoiceId = await models.Ticket.makeInvoice(ctx, 'R', companyId, Date.vnNew(), myOptions); - console.log(await models.InvoiceOut.find(null, myOptions)); invoicesIds.push(invoiceId); } }; diff --git a/modules/ticket/back/methods/ticket/invoiceTicketsWithPdf.js b/modules/ticket/back/methods/ticket/invoiceTicketsWithPdf.js new file mode 100644 index 000000000..e69de29bb diff --git a/print/templates/reports/invoice/invoice.js b/print/templates/reports/invoice/invoice.js index 1c9965d3b..4424c8ea3 100755 --- a/print/templates/reports/invoice/invoice.js +++ b/print/templates/reports/invoice/invoice.js @@ -6,7 +6,10 @@ module.exports = { name: 'invoice', mixins: [vnReport], async serverPrefetch() { + console.log(this.reference); this.invoice = await this.findOneFromDef('invoice', [this.reference]); + console.log(this.invoice); + this.checkMainEntity(this.invoice); this.client = await this.findOneFromDef('client', [this.reference]); this.taxes = await this.rawSqlFromDef(`taxes`, [this.reference]); From f3e43686a3db0f7a1e43434fd8e3396f5436b657 Mon Sep 17 00:00:00 2001 From: vicent Date: Thu, 24 Aug 2023 14:59:28 +0200 Subject: [PATCH 041/427] refs #5811 feat: al borrar expedicion borrar tmb de viaexpress --- .../viaexpress-config/deleteShipment.ejs | 11 +++++ .../viaexpress-config/deleteShipment.js | 45 +++++++++++++++++++ .../deleteShipmentRenderer.js | 44 ++++++++++++++++++ modules/ticket/back/models/expedition.json | 3 ++ 4 files changed, 103 insertions(+) create mode 100644 back/methods/viaexpress-config/deleteShipment.ejs create mode 100644 back/methods/viaexpress-config/deleteShipment.js create mode 100644 back/methods/viaexpress-config/deleteShipmentRenderer.js diff --git a/back/methods/viaexpress-config/deleteShipment.ejs b/back/methods/viaexpress-config/deleteShipment.ejs new file mode 100644 index 000000000..3be459a8d --- /dev/null +++ b/back/methods/viaexpress-config/deleteShipment.ejs @@ -0,0 +1,11 @@ + + + + + <%= viaexpressConfig.client %> + <%= viaexpressConfig.user %> + <%= viaexpressConfig.password %> + <%= externalId %> + + + diff --git a/back/methods/viaexpress-config/deleteShipment.js b/back/methods/viaexpress-config/deleteShipment.js new file mode 100644 index 000000000..40509899b --- /dev/null +++ b/back/methods/viaexpress-config/deleteShipment.js @@ -0,0 +1,45 @@ +const axios = require('axios'); +const {DOMParser} = require('xmldom'); + +module.exports = Self => { + Self.remoteMethod('deleteShipment', { + description: 'Create an expedition and return a label', + accessType: 'WRITE', + accepts: [{ + arg: 'expeditionFk', + type: 'number', + required: true + }], + returns: { + type: ['object'], + root: true + }, + http: { + path: `/deleteShipment`, + verb: 'POST' + } + }); + + Self.deleteShipment = async expeditionFk => { + const models = Self.app.models; + + const viaexpressConfig = await models.ViaexpressConfig.findOne({ + fields: ['url'] + }); + + const renderedXml = await models.ViaexpressConfig.deleteShipmentRenderer(expeditionFk); + const response = await axios.post(`${viaexpressConfig.url}ServicioVxClientes.asmx`, renderedXml, { + headers: { + 'Content-Type': 'application/soap+xml; charset=utf-8' + } + }); + + const xmlString = response.data; + const parser = new DOMParser(); + const xmlDoc = parser.parseFromString(xmlString, 'text/xml'); + const resultElement = xmlDoc.getElementsByTagName('DeleteEnvioResult')[0]; + const result = resultElement.textContent; + + return result; + }; +}; diff --git a/back/methods/viaexpress-config/deleteShipmentRenderer.js b/back/methods/viaexpress-config/deleteShipmentRenderer.js new file mode 100644 index 000000000..d9106a9ec --- /dev/null +++ b/back/methods/viaexpress-config/deleteShipmentRenderer.js @@ -0,0 +1,44 @@ +const fs = require('fs'); +const ejs = require('ejs'); + +module.exports = Self => { + Self.remoteMethod('deleteShipmentRenderer', { + description: 'Renders the data from an XML', + accessType: 'READ', + accepts: [{ + arg: 'expeditionFk', + type: 'number', + required: true + }], + returns: { + type: ['object'], + root: true + }, + http: { + path: `/deleteShipmentRenderer`, + verb: 'GET' + } + }); + + Self.deleteShipmentRenderer = async expeditionFk => { + const models = Self.app.models; + + const viaexpressConfig = await models.ViaexpressConfig.findOne({ + fields: ['client', 'user', 'password'] + }); + + const expedition = await models.Expedition.findOne({ + fields: ['id', 'externalId'], + where: {id: expeditionFk} + }); + + const data = { + viaexpressConfig, + externalId: expedition.externalId + }; + + const template = fs.readFileSync(__dirname + '/deleteShipment.ejs', 'utf-8'); + const renderedXml = ejs.render(template, data); + return renderedXml; + }; +}; diff --git a/modules/ticket/back/models/expedition.json b/modules/ticket/back/models/expedition.json index e32a3b23d..1ad083ce3 100644 --- a/modules/ticket/back/models/expedition.json +++ b/modules/ticket/back/models/expedition.json @@ -20,6 +20,9 @@ }, "counter": { "type": "number" + }, + "externalId": { + "type": "string" } }, "relations": { From 4ae06d4b6b22a846bf5ad422898c0fb29d0a6bc4 Mon Sep 17 00:00:00 2001 From: pablone Date: Fri, 25 Aug 2023 07:36:52 +0200 Subject: [PATCH 042/427] refs #6159 fixBusinessAfterInsert --- .../233601/00-updateAfterBusinnesInsert.sql | 42 +++++++++++++++++++ db/dump/fixtures.sql | 5 +++ 2 files changed, 47 insertions(+) create mode 100644 db/changes/233601/00-updateAfterBusinnesInsert.sql diff --git a/db/changes/233601/00-updateAfterBusinnesInsert.sql b/db/changes/233601/00-updateAfterBusinnesInsert.sql new file mode 100644 index 000000000..f2b5dc753 --- /dev/null +++ b/db/changes/233601/00-updateAfterBusinnesInsert.sql @@ -0,0 +1,42 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`business_afterInsert` + AFTER INSERT ON `business` + FOR EACH ROW +BEGIN + CALL worker_updateBusiness(NEW.workerFk); + + IF ( + SELECT NOT active + FROM account.user + WHERE id = NEW.workerFk + ) THEN + UPDATE account.user + SET active = TRUE + WHERE id = NEW.workerFk; + END IF; + + IF ( + SELECT NOT COUNT(aa.id) + FROM account.mailAliasAccount aa + JOIN account.mailAlias ma ON ma.id = aa.mailAlias + WHERE aa.account = NEW.workerFk + AND ma.alias = 'general' + ) THEN + INSERT INTO account.mailAliasAccount (mailAlias, account) + SELECT id, NEW.workerFk + FROM account.mailAlias + WHERE alias = 'general'; + END IF; + + IF ( + SELECT NOT COUNT(account) + FROM account.mailForward + WHERE account = NEW.workerFk + ) THEN + INSERT INTO account.mailForward (account, forwardTo) + SELECT NEW.workerFk, email + FROM account.user + WHERE id = NEW.workerFk; + END IF; +END$$ +DELIMITER ; diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index b01c07461..a3d76015f 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -1965,6 +1965,11 @@ INSERT INTO `vn`.`calendarType` (`id`, `description`, `hoursWeek`, `isPartial`) VALUES (1, 'General schedule', 40, 0); +INSERT INTO `account`.`account`(id) + SELECT u.id + FROM account.user u + LEFT JOIN account.account a ON a.id = u.id + WHERE a.id IS NULL; DROP TEMPORARY TABLE IF EXISTS tmp.worker; CREATE TEMPORARY TABLE tmp.worker From 9da5c4c1db4d9bff39b578d943406333d33a7625 Mon Sep 17 00:00:00 2001 From: vicent Date: Fri, 25 Aug 2023 10:04:27 +0200 Subject: [PATCH 043/427] refs #5918 refacotr: cambiado nombre variable --- modules/worker/front/time-control/index.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/modules/worker/front/time-control/index.js b/modules/worker/front/time-control/index.js index 91f095334..88bd2e92a 100644 --- a/modules/worker/front/time-control/index.js +++ b/modules/worker/front/time-control/index.js @@ -113,21 +113,21 @@ class Controller extends Section { } isMailSended() { - const filter = { + const filterTimeControl = { where: { year: this._date.getFullYear(), week: this.getWeekNumber(this._date) }, limit: 1 }; - this.$http.get('WorkerTimeControlMails', {filter}) + this.$http.get('WorkerTimeControlMails', {filterTimeControl}) .then(res => { if (!res.data.length) { this.canResend = false; return; } - const filter = { + const filterDepartment = { where: { workerFk: this.$params.id }, @@ -135,7 +135,7 @@ class Controller extends Section { relation: 'department' } }; - this.$http.get('WorkerDepartments', {filter}) + this.$http.get('WorkerDepartments', {filterDepartment}) .then(res => { const department = res.data[0].department; if (department.isTeleworking) this.canResend = true; From c06ee9c5b039e1048a72db7d80027474dd84e987 Mon Sep 17 00:00:00 2001 From: pablone Date: Fri, 25 Aug 2023 10:55:10 +0200 Subject: [PATCH 044/427] refs #6159 fixUserNoActiveOnNewBusiness --- db/dump/fixtures.sql | 3 +++ 1 file changed, 3 insertions(+) diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index a3d76015f..5ac355ea4 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -1994,6 +1994,9 @@ INSERT INTO `vn`.`business` (`id`, `workerFk`, `companyCodeFk`, `started`, `ende DROP TEMPORARY TABLE IF EXISTS tmp.worker; +DELETE FROM `account`.`account` + WHERE id = 1105; + UPDATE `vn`.`business` SET `payedHolidays`= 8 WHERE `id`= 1106; From 2ecc464046493b4ae2c21a8a8e8ae6bd00b6902a Mon Sep 17 00:00:00 2001 From: alexm Date: Fri, 25 Aug 2023 14:26:17 +0200 Subject: [PATCH 045/427] refs #5673 feat(claim_development): redirect to lilium --- modules/claim/front/development/index.html | 118 +----------------- modules/claim/front/development/index.js | 15 +-- modules/claim/front/development/index.spec.js | 31 ----- modules/claim/front/development/locale/es.yml | 8 -- modules/claim/front/development/style.scss | 0 5 files changed, 8 insertions(+), 164 deletions(-) delete mode 100644 modules/claim/front/development/index.spec.js delete mode 100644 modules/claim/front/development/locale/es.yml delete mode 100644 modules/claim/front/development/style.scss diff --git a/modules/claim/front/development/index.html b/modules/claim/front/development/index.html index 1684541ea..7fb3b870e 100644 --- a/modules/claim/front/development/index.html +++ b/modules/claim/front/development/index.html @@ -1,116 +1,2 @@ - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - -
- - - - -
-
- - - - - - -
+ + diff --git a/modules/claim/front/development/index.js b/modules/claim/front/development/index.js index 04569f0aa..7b31bd17f 100644 --- a/modules/claim/front/development/index.js +++ b/modules/claim/front/development/index.js @@ -1,17 +1,14 @@ import ngModule from '../module'; import Section from 'salix/components/section'; -import './style.scss'; class Controller extends Section { - onSubmit() { - this.$.watcher.check(); - this.$.model.save().then(() => { - this.$.watcher.notifySaved(); - this.$.watcher.updateOriginalData(); + constructor($element, $) { + super($element, $); + } - if (this.aclService.hasAny(['claimManager'])) - this.$state.go('claim.card.action'); - }); + async $onInit() { + this.$state.go('claim.card.summary', {id: this.$params.id}); + window.location.href = await this.vnApp.getUrl(`claim/${this.$params.id}/development`); } } diff --git a/modules/claim/front/development/index.spec.js b/modules/claim/front/development/index.spec.js deleted file mode 100644 index e2574ccb9..000000000 --- a/modules/claim/front/development/index.spec.js +++ /dev/null @@ -1,31 +0,0 @@ -import './index.js'; -import watcher from 'core/mocks/watcher'; -import crudModel from 'core/mocks/crud-model'; - -describe('Claim', () => { - describe('Component vnClaimDevelopment', () => { - let controller; - let $scope; - - beforeEach(ngModule('claim')); - - beforeEach(inject(($componentController, $rootScope) => { - $scope = $rootScope.$new(); - $scope.watcher = watcher; - $scope.model = crudModel; - const $element = angular.element(''); - controller = $componentController('vnClaimDevelopment', {$element, $scope}); - })); - - describe('onSubmit()', () => { - it(`should redirect to 'claim.card.action' state`, () => { - jest.spyOn(controller.aclService, 'hasAny').mockReturnValue(true); - jest.spyOn(controller.$state, 'go'); - - controller.onSubmit(); - - expect(controller.$state.go).toHaveBeenCalledWith('claim.card.action'); - }); - }); - }); -}); diff --git a/modules/claim/front/development/locale/es.yml b/modules/claim/front/development/locale/es.yml deleted file mode 100644 index c0c4ed184..000000000 --- a/modules/claim/front/development/locale/es.yml +++ /dev/null @@ -1,8 +0,0 @@ -Destination: Destino -Development: Trazabilidad -Reason: Motivo -Result: Consecuencia -Responsible: Responsable -Worker: Trabajador -Redelivery: Devolución -Add line: Añadir Linea \ No newline at end of file diff --git a/modules/claim/front/development/style.scss b/modules/claim/front/development/style.scss deleted file mode 100644 index e69de29bb..000000000 From d1df8009a620138e1a53de2c19ab952d725590d8 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 29 Aug 2023 10:52:05 +0200 Subject: [PATCH 046/427] refs #6023 Fix change rol bug --- back/methods/vn-user/privileges.js | 66 ++++++++++++-------- modules/account/back/methods/account/sync.js | 5 ++ 2 files changed, 44 insertions(+), 27 deletions(-) diff --git a/back/methods/vn-user/privileges.js b/back/methods/vn-user/privileges.js index 08cfaaae8..05ad4481c 100644 --- a/back/methods/vn-user/privileges.js +++ b/back/methods/vn-user/privileges.js @@ -40,44 +40,56 @@ module.exports = Self => { const userId = ctx.req.accessToken.userId; const myOptions = {}; + let tx; if (typeof options == 'object') Object.assign(myOptions, options); - const user = await Self.findById(userId, {fields: ['hasGrant']}, myOptions); + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + }; - const userToUpdate = await Self.findById(id, { - fields: ['id', 'name', 'hasGrant', 'roleFk', 'password', 'email'], - include: { - relation: 'role', - scope: { - fields: ['name'] + try { + const user = await Self.findById(userId, {fields: ['hasGrant']}, myOptions); + + const userToUpdate = await Self.findById(id, { + fields: ['id', 'name', 'hasGrant', 'roleFk', 'password', 'email'], + include: { + relation: 'role', + scope: { + fields: ['name'] + } } - } - }, myOptions); + }, myOptions); - if (!user.hasGrant) - throw new UserError(`You don't have grant privilege`); + if (!user.hasGrant) + throw new UserError(`You don't have grant privilege`); - const hasRoleFromUser = await Self.hasRole(userId, userToUpdate.role().name, myOptions); + const hasRoleFromUser = await Self.hasRole(userId, userToUpdate.role().name, myOptions); - if (!hasRoleFromUser) - throw new UserError(`You don't own the role and you can't assign it to another user`); - - if (hasGrant != null) - userToUpdate.hasGrant = hasGrant; - - if (roleFk) { - const role = await models.Role.findById(roleFk, {fields: ['name']}, myOptions); - const hasRole = await Self.hasRole(userId, role.name, myOptions); - - if (!hasRole) + if (!hasRoleFromUser) throw new UserError(`You don't own the role and you can't assign it to another user`); - userToUpdate.roleFk = roleFk; - } + if (hasGrant != null) + userToUpdate.hasGrant = hasGrant; - await userToUpdate.save(userToUpdate); - await models.Account.sync(userToUpdate.name); + if (roleFk) { + const role = await models.Role.findById(roleFk, {fields: ['name']}, myOptions); + const hasRole = await Self.hasRole(userId, role.name, myOptions); + + if (!hasRole) + throw new UserError(`You don't own the role and you can't assign it to another user`); + + userToUpdate.roleFk = roleFk; + } + + await userToUpdate.save(myOptions); + await models.Account.sync(userToUpdate.name, null, null, myOptions); + await tx.commit(); + } catch (err) { + await tx.rollback(); + throw err; + }; }; }; diff --git a/modules/account/back/methods/account/sync.js b/modules/account/back/methods/account/sync.js index a5befc22c..3ab19eed5 100644 --- a/modules/account/back/methods/account/sync.js +++ b/modules/account/back/methods/account/sync.js @@ -30,6 +30,11 @@ module.exports = Self => { if (typeof options == 'object') Object.assign(myOptions, options); + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + }; + const models = Self.app.models; const user = await models.VnUser.findOne({ fields: ['id'], From 9f6d034f9cf044f9ab688bb860bf4277d1df7bec Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 29 Aug 2023 13:45:20 +0200 Subject: [PATCH 047/427] refs #6023 Minor changes --- back/methods/vn-user/privileges.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/back/methods/vn-user/privileges.js b/back/methods/vn-user/privileges.js index 05ad4481c..0520fd5c2 100644 --- a/back/methods/vn-user/privileges.js +++ b/back/methods/vn-user/privileges.js @@ -86,9 +86,9 @@ module.exports = Self => { await userToUpdate.save(myOptions); await models.Account.sync(userToUpdate.name, null, null, myOptions); - await tx.commit(); + if (tx) await tx.commit(); } catch (err) { - await tx.rollback(); + if (tx) await tx.rollback(); throw err; }; }; From 0b9199688e786f3da556966fe6ec97dd6a82ad51 Mon Sep 17 00:00:00 2001 From: carlossa Date: Wed, 30 Aug 2023 12:48:57 +0200 Subject: [PATCH 048/427] refs #5843 userFk remove and vchange --- .../224903/00-timeBusiness_calculate.sql | 6 +-- db/changes/231401/00-clientBeforeUpdate.sql | 2 +- db/dump/structure.sql | 5 +- .../claim/back/methods/claim/getSummary.js | 4 +- modules/claim/back/methods/claim/logs.js | 46 +++++++++---------- modules/claim/front/card/index.js | 2 +- .../client/front/credit-management/index.js | 2 +- modules/client/front/credit/index/index.js | 2 +- modules/client/front/dms/index/index.js | 2 +- modules/item/back/methods/item/getCard.js | 2 +- modules/item/back/methods/item/getSummary.js | 2 +- modules/route/back/methods/route/summary.js | 2 +- modules/route/front/card/index.js | 2 +- modules/route/front/descriptor/index.js | 2 +- .../back/methods/shelving/getSummary.js | 2 +- modules/shelving/front/card/index.js | 2 +- modules/shelving/front/summary/index.js | 2 +- .../back/methods/supplier/getSummary.js | 2 +- modules/ticket/front/dms/index/index.js | 2 +- modules/ticket/front/tracking/index/index.js | 2 +- .../methods/worker-time-control/sendMail.js | 2 +- .../methods/worker/activeWithInheritedRole.js | 4 +- modules/worker/back/methods/worker/filter.js | 7 ++- 23 files changed, 53 insertions(+), 53 deletions(-) diff --git a/db/.archive/224903/00-timeBusiness_calculate.sql b/db/.archive/224903/00-timeBusiness_calculate.sql index ea13c4a8a..6345475dd 100644 --- a/db/.archive/224903/00-timeBusiness_calculate.sql +++ b/db/.archive/224903/00-timeBusiness_calculate.sql @@ -34,7 +34,7 @@ BEGIN isAllowedToWork FROM(SELECT t.dated, b.id businessFk, - w.userFk, + w.id, b.departmentFk, IF(j.start = NULL, NULL, GROUP_CONCAT(DISTINCT LEFT(j.start,5) ORDER BY j.start ASC SEPARATOR ' - ')) hourStart , IF(j.start = NULL, NULL, GROUP_CONCAT(DISTINCT LEFT(j.end,5) ORDER BY j.end ASC SEPARATOR ' - ')) hourEnd, @@ -48,14 +48,14 @@ BEGIN FROM time t LEFT JOIN business b ON t.dated BETWEEN b.started AND IFNULL(b.ended, vDatedTo) LEFT JOIN worker w ON w.id = b.workerFk - JOIN tmp.`user` u ON u.userFK = w.userFK + JOIN tmp.`user` u ON u.userFK = w.id LEFT JOIN workCenter wc ON wc.id = b.workcenterFK LEFT JOIN postgresql.calendar_labour_type cl ON cl.calendar_labour_type_id = b.calendarTypeFk LEFT JOIN postgresql.journey j ON j.business_id = b.id AND j.day_id = WEEKDAY(t.dated) + 1 LEFT JOIN postgresql.calendar_employee ce ON ce.businessFk = b.id AND ce.date = t.dated LEFT JOIN absenceType at2 ON at2.id = ce.calendar_state_id WHERE t.dated BETWEEN vDatedFrom AND vDatedTo - GROUP BY w.userFk, t.dated + GROUP BY w.id, t.dated )sub; UPDATE tmp.timeBusinessCalculate t diff --git a/db/changes/231401/00-clientBeforeUpdate.sql b/db/changes/231401/00-clientBeforeUpdate.sql index 8f9f70dd5..6bae98f61 100644 --- a/db/changes/231401/00-clientBeforeUpdate.sql +++ b/db/changes/231401/00-clientBeforeUpdate.sql @@ -46,7 +46,7 @@ BEGIN CONCAT('Cliente ', NEW.id), CONCAT('Recibida la documentación: ', vText) FROM worker w - LEFT JOIN account.user u ON w.userFk = u.id AND u.active + 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; diff --git a/db/dump/structure.sql b/db/dump/structure.sql index 2d66d456c..c47d0debc 100644 --- a/db/dump/structure.sql +++ b/db/dump/structure.sql @@ -73377,7 +73377,7 @@ BEGIN CREATE TEMPORARY TABLE tmp.`user` SELECT u.id userFk FROM account.user u - JOIN vn.worker w ON w.userFk = u.id + JOIN vn.worker w ON w.id = u.id WHERE w.id = vWorkerFk; CALL vn.timeControl_calculate(vDatedFrom, vDatedTo); @@ -75480,7 +75480,7 @@ BEGIN GROUP BY cont HAVING cont2 MOD 2 = 1 )sub2; - JOIN worker w ON w.userFk = sub2.userFk; + JOIN worker w ON w.id = sub2.userFk; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -81818,6 +81818,7 @@ USE `vn`; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; + -- -- Final view structure for view `workerTimeJourneyNG` -- diff --git a/modules/claim/back/methods/claim/getSummary.js b/modules/claim/back/methods/claim/getSummary.js index d384f7ebb..2731f1e8f 100644 --- a/modules/claim/back/methods/claim/getSummary.js +++ b/modules/claim/back/methods/claim/getSummary.js @@ -35,7 +35,7 @@ module.exports = Self => { { relation: 'worker', scope: { - fields: ['userFk'], + fields: ['id'], include: { relation: 'user', scope: { @@ -109,7 +109,7 @@ module.exports = Self => { { relation: 'worker', scope: { - fields: ['userFk'], + fields: ['id'], include: { relation: 'user', scope: { diff --git a/modules/claim/back/methods/claim/logs.js b/modules/claim/back/methods/claim/logs.js index f47513e9e..4d1b37822 100644 --- a/modules/claim/back/methods/claim/logs.js +++ b/modules/claim/back/methods/claim/logs.js @@ -1,7 +1,7 @@ const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; const buildFilter = require('vn-loopback/util/filter').buildFilter; -const { mergeFilters, mergeWhere } = require('vn-loopback/util/filter'); +const {mergeFilters, mergeWhere} = require('vn-loopback/util/filter'); module.exports = Self => { Self.remoteMethodCtx('logs', { @@ -12,27 +12,27 @@ module.exports = Self => { arg: 'id', type: 'Number', description: 'The claim id', - http: { source: 'path' } + http: {source: 'path'} }, { arg: 'filter', type: 'object', - http: { source: 'query' } + http: {source: 'query'} }, { arg: 'search', type: 'string', - http: { source: 'query' } + http: {source: 'query'} }, { arg: 'userFk', type: 'number', - http: { source: 'query' } + http: {source: 'query'} }, { arg: 'created', type: 'date', - http: { source: 'query' } + http: {source: 'query'} }, ], returns: { @@ -45,7 +45,7 @@ module.exports = Self => { } }); - Self.logs = async (ctx, id, filter, options) => { + Self.logs = async(ctx, id, filter, options) => { const conn = Self.dataSource.connector; const args = ctx.args; const myOptions = {}; @@ -56,25 +56,25 @@ module.exports = Self => { let where = buildFilter(args, (param, value) => { switch (param) { - case 'search': - return { - or: [ - { changedModel: { like: `%${value}%` } }, - { oldInstance: { like: `%${value}%` } } - ] - }; - case 'userFk': - return { 'cl.userFk': value }; - case 'created': - value.setHours(0, 0, 0, 0); - to = new Date(value); - to.setHours(23, 59, 59, 999); + case 'search': + return { + or: [ + {changedModel: {like: `%${value}%`}}, + {oldInstance: {like: `%${value}%`}} + ] + }; + case 'userFk': + return {'cl.userFk': value}; + case 'created': + value.setHours(0, 0, 0, 0); + to = new Date(value); + to.setHours(23, 59, 59, 999); - return { creationDate: { between: [value, to] } }; + return {creationDate: {between: [value, to]}}; } }); - where = mergeWhere(where, { ['cl.originFk']: id }); - filter = mergeFilters(args.filter, { where }); + where = mergeWhere(where, {['cl.originFk']: id}); + filter = mergeFilters(args.filter, {where}); const stmts = []; diff --git a/modules/claim/front/card/index.js b/modules/claim/front/card/index.js index 4a8677c90..5dad0dfc2 100644 --- a/modules/claim/front/card/index.js +++ b/modules/claim/front/card/index.js @@ -8,7 +8,7 @@ class Controller extends ModuleCard { { relation: 'worker', scope: { - fields: ['userFk'], + fields: ['id'], include: { relation: 'user', scope: { diff --git a/modules/client/front/credit-management/index.js b/modules/client/front/credit-management/index.js index 856acd27b..7733319e8 100644 --- a/modules/client/front/credit-management/index.js +++ b/modules/client/front/credit-management/index.js @@ -9,7 +9,7 @@ export default class Controller extends Section { include: [{ relation: 'worker', scope: { - fields: ['userFk'], + fields: ['id'], include: { relation: 'user', scope: { diff --git a/modules/client/front/credit/index/index.js b/modules/client/front/credit/index/index.js index 28160dfeb..3083ac598 100644 --- a/modules/client/front/credit/index/index.js +++ b/modules/client/front/credit/index/index.js @@ -9,7 +9,7 @@ class Controller extends Section { { relation: 'worker', scope: { - fields: ['userFk'], + fields: ['id'], include: { relation: 'user', scope: { diff --git a/modules/client/front/dms/index/index.js b/modules/client/front/dms/index/index.js index a18f195bb..aff64aa4f 100644 --- a/modules/client/front/dms/index/index.js +++ b/modules/client/front/dms/index/index.js @@ -28,7 +28,7 @@ class Controller extends Section { }, { relation: 'worker', scope: { - fields: ['userFk'], + fields: ['id'], include: { relation: 'user', scope: { diff --git a/modules/item/back/methods/item/getCard.js b/modules/item/back/methods/item/getCard.js index c4ee09d95..49ce3636f 100644 --- a/modules/item/back/methods/item/getCard.js +++ b/modules/item/back/methods/item/getCard.js @@ -34,7 +34,7 @@ module.exports = Self => { include: [{ relation: 'worker', scope: { - fields: ['userFk'], + fields: ['id'], include: { relation: 'user', scope: { diff --git a/modules/item/back/methods/item/getSummary.js b/modules/item/back/methods/item/getSummary.js index 6cd9d9511..17a38cf07 100644 --- a/modules/item/back/methods/item/getSummary.js +++ b/modules/item/back/methods/item/getSummary.js @@ -38,7 +38,7 @@ module.exports = Self => { include: [{ relation: 'worker', scope: { - fields: ['userFk'], + fields: ['id'], include: { relation: 'user', scope: { diff --git a/modules/route/back/methods/route/summary.js b/modules/route/back/methods/route/summary.js index 10cfe38ee..acd17759d 100644 --- a/modules/route/back/methods/route/summary.js +++ b/modules/route/back/methods/route/summary.js @@ -33,7 +33,7 @@ module.exports = Self => { }, { relation: 'worker', scope: { - fields: ['id', 'userFk'], + fields: ['id'], include: [ { relation: 'user', diff --git a/modules/route/front/card/index.js b/modules/route/front/card/index.js index 6bf233c0a..07b5a547c 100644 --- a/modules/route/front/card/index.js +++ b/modules/route/front/card/index.js @@ -41,7 +41,7 @@ class Controller extends ModuleCard { { relation: 'worker', scope: { - fields: ['userFk'], + fields: ['id'], include: { relation: 'user', scope: { diff --git a/modules/route/front/descriptor/index.js b/modules/route/front/descriptor/index.js index aa47044b1..4377ac617 100644 --- a/modules/route/front/descriptor/index.js +++ b/modules/route/front/descriptor/index.js @@ -79,7 +79,7 @@ class Controller extends Descriptor { }, { relation: 'worker', scope: { - fields: ['userFk'], + fields: ['id'], include: { relation: 'user', scope: { diff --git a/modules/shelving/back/methods/shelving/getSummary.js b/modules/shelving/back/methods/shelving/getSummary.js index da357c7bf..7488511d0 100644 --- a/modules/shelving/back/methods/shelving/getSummary.js +++ b/modules/shelving/back/methods/shelving/getSummary.js @@ -35,7 +35,7 @@ module.exports = Self => { { relation: 'worker', scope: { - fields: ['id', 'userFk'], + fields: ['id'], include: { relation: 'user', scope: { diff --git a/modules/shelving/front/card/index.js b/modules/shelving/front/card/index.js index 5e2ea9b12..4f571d876 100644 --- a/modules/shelving/front/card/index.js +++ b/modules/shelving/front/card/index.js @@ -7,7 +7,7 @@ class Controller extends ModuleCard { include: [ {relation: 'worker', scope: { - fields: ['userFk'], + fields: ['id'], include: { relation: 'user', scope: { diff --git a/modules/shelving/front/summary/index.js b/modules/shelving/front/summary/index.js index 10a905f1d..91f8e2aa7 100644 --- a/modules/shelving/front/summary/index.js +++ b/modules/shelving/front/summary/index.js @@ -12,7 +12,7 @@ class Controller extends Summary { include: [ {relation: 'worker', scope: { - fields: ['userFk'], + fields: ['id'], include: { relation: 'user', scope: { diff --git a/modules/supplier/back/methods/supplier/getSummary.js b/modules/supplier/back/methods/supplier/getSummary.js index bf3fa56f5..bc869725c 100644 --- a/modules/supplier/back/methods/supplier/getSummary.js +++ b/modules/supplier/back/methods/supplier/getSummary.js @@ -91,7 +91,7 @@ module.exports = Self => { { relation: 'worker', scope: { - fields: ['userFk'], + fields: ['id'], include: { relation: 'user', scope: { diff --git a/modules/ticket/front/dms/index/index.js b/modules/ticket/front/dms/index/index.js index 2ec7e03c0..676a28db8 100644 --- a/modules/ticket/front/dms/index/index.js +++ b/modules/ticket/front/dms/index/index.js @@ -29,7 +29,7 @@ class Controller extends Section { { relation: 'worker', scope: { - fields: ['userFk'], + fields: ['id'], include: { relation: 'user', scope: { diff --git a/modules/ticket/front/tracking/index/index.js b/modules/ticket/front/tracking/index/index.js index 38abcd8ab..95665b071 100644 --- a/modules/ticket/front/tracking/index/index.js +++ b/modules/ticket/front/tracking/index/index.js @@ -9,7 +9,7 @@ class Controller extends Section { { relation: 'worker', scope: { - fields: ['userFk'], + fields: ['id'], include: { relation: 'user', scope: { diff --git a/modules/worker/back/methods/worker-time-control/sendMail.js b/modules/worker/back/methods/worker-time-control/sendMail.js index ab5e56a77..331c81512 100644 --- a/modules/worker/back/methods/worker-time-control/sendMail.js +++ b/modules/worker/back/methods/worker-time-control/sendMail.js @@ -102,7 +102,7 @@ module.exports = Self => { stmt = new ParameterizedSQL('DROP TEMPORARY TABLE IF EXISTS tmp.`user`'); stmts.push(stmt); - stmt = new ParameterizedSQL('CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` SELECT userFk FROM vn.worker w JOIN account.`user` u ON u.id = w.userFk WHERE userFk IS NOT NULL'); + stmt = new ParameterizedSQL('CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` SELECT id as userFk FROM vn.worker w JOIN account.`user` u ON u.id = w.id WHERE id IS NOT NULL'); stmts.push(stmt); } diff --git a/modules/worker/back/methods/worker/activeWithInheritedRole.js b/modules/worker/back/methods/worker/activeWithInheritedRole.js index 9536b0f29..2b75a939e 100644 --- a/modules/worker/back/methods/worker/activeWithInheritedRole.js +++ b/modules/worker/back/methods/worker/activeWithInheritedRole.js @@ -23,8 +23,8 @@ module.exports = Self => { const query = `SELECT DISTINCT w.id, w.firstName, w.lastName, u.name, u.nickname FROM worker w - JOIN account.user u ON u.id = w.userFk - JOIN account.roleRole i ON i.role = u.role + JOIN account.user u ON u.id = w.id + JOIN account.roleRole i ON i.role = u.role JOIN account.role r ON r.id = i.inheritsFrom`; return Self.activeWorkers(query, filter); diff --git a/modules/worker/back/methods/worker/filter.js b/modules/worker/back/methods/worker/filter.js index 71a8da96f..15a56949f 100644 --- a/modules/worker/back/methods/worker/filter.js +++ b/modules/worker/back/methods/worker/filter.js @@ -94,9 +94,8 @@ module.exports = Self => { {'u.nickname': {like: `%${value}%`}} ]}; case 'id': - return {'w.id': value}; case 'userFk': - return {'w.userFk': value}; + return {'w.id': value}; case 'firstName': return {'w.firstName': {like: `%${value}%`}}; case 'lastName': @@ -123,8 +122,8 @@ module.exports = Self => { FROM worker w LEFT JOIN workerDepartment wd ON wd.workerFk = w.id LEFT JOIN department d ON d.id = wd.departmentFk - LEFT JOIN client c ON c.id = w.userFk - LEFT JOIN account.user u ON u.id = w.userFk + LEFT JOIN client c ON c.id = w.id + LEFT JOIN account.user u ON u.id = w.id LEFT JOIN pbx.sip p ON p.user_id = u.id LEFT JOIN account.emailUser mu ON mu.userFk = u.id` ); From 05f0f72c739a6c668c7c73c0370644e3906c143e Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 30 Aug 2023 14:14:48 +0200 Subject: [PATCH 049/427] refs #6119 microsip link added --- modules/client/front/summary/index.html | 23 ++++++++-- modules/client/front/summary/style.scss | 4 ++ modules/order/front/summary/index.html | 11 ++++- modules/order/front/summary/style.scss | 4 ++ .../route/front/roadmap/summary/index.html | 11 ++++- .../route/front/roadmap/summary/style.scss | 6 ++- modules/ticket/front/summary/index.html | 42 ++++++++++++++++--- modules/ticket/front/summary/style.scss | 5 +++ modules/worker/front/descriptor/index.html | 30 +++++++++++-- modules/worker/front/descriptor/index.js | 2 +- modules/worker/front/descriptor/style.scss | 6 +++ modules/worker/front/summary/index.html | 41 +++++++++++++++--- modules/worker/front/summary/index.js | 2 +- modules/worker/front/summary/style.scss | 6 +++ 14 files changed, 169 insertions(+), 24 deletions(-) create mode 100644 modules/worker/front/descriptor/style.scss create mode 100644 modules/worker/front/summary/style.scss diff --git a/modules/client/front/summary/index.html b/modules/client/front/summary/index.html index 15a55ec8c..6f7c915c1 100644 --- a/modules/client/front/summary/index.html +++ b/modules/client/front/summary/index.html @@ -45,11 +45,26 @@ - + + {{$ctrl.summary.phone}} + + + + - + + {{$ctrl.summary.mobile}} + + + diff --git a/modules/client/front/summary/style.scss b/modules/client/front/summary/style.scss index 7dc1cc928..dd30edaa0 100644 --- a/modules/client/front/summary/style.scss +++ b/modules/client/front/summary/style.scss @@ -11,4 +11,8 @@ vn-client-summary .summary { font-family: 'salixfont' !important; content: "\e965"; } + vn-icon.tel { + font-size: 1.1em; + vertical-align: bottom; + } } diff --git a/modules/order/front/summary/index.html b/modules/order/front/summary/index.html index 3622ae932..52a1afd6d 100644 --- a/modules/order/front/summary/index.html +++ b/modules/order/front/summary/index.html @@ -49,7 +49,16 @@ value="{{$ctrl.summary.landed | date: 'dd/MM/yyyy HH:mm'}}"> + > + {{$ctrl.summary.address.phone}} + + + + diff --git a/modules/order/front/summary/style.scss b/modules/order/front/summary/style.scss index a2537c58f..7abcd889b 100644 --- a/modules/order/front/summary/style.scss +++ b/modules/order/front/summary/style.scss @@ -17,4 +17,8 @@ vn-order-summary .summary{ } } } + vn-icon.tel { + font-size: 1.1em; + vertical-align: bottom; + } } \ No newline at end of file diff --git a/modules/route/front/roadmap/summary/index.html b/modules/route/front/roadmap/summary/index.html index e6b50601e..c8ba85456 100644 --- a/modules/route/front/roadmap/summary/index.html +++ b/modules/route/front/roadmap/summary/index.html @@ -25,7 +25,16 @@ + > + {{summary.phone}} + + + + + > + {{$ctrl.summary.address.phone}} + + + + + > + {{$ctrl.summary.address.mobile}} + + + + + ng-if="$ctrl.summary.client.phone != null"> + {{$ctrl.summary.client.phone}} + + + + ng-if="$ctrl.summary.client.mobile != null"> + {{$ctrl.summary.client.mobile}} + + + diff --git a/modules/ticket/front/summary/style.scss b/modules/ticket/front/summary/style.scss index e92ff0d42..2f52de65e 100644 --- a/modules/ticket/front/summary/style.scss +++ b/modules/ticket/front/summary/style.scss @@ -47,4 +47,9 @@ vn-ticket-summary .summary { } } } + + vn-icon.tel { + font-size: 1.1em; + vertical-align: bottom; + } } \ No newline at end of file diff --git a/modules/worker/front/descriptor/index.html b/modules/worker/front/descriptor/index.html index ea005e1a2..ce318540f 100644 --- a/modules/worker/front/descriptor/index.html +++ b/modules/worker/front/descriptor/index.html @@ -36,12 +36,34 @@ value="{{$ctrl.worker.department.department.name}}"> + label="Phone"> + - + + {{$ctrl.worker.phone}} + + + + + label="Extension"> + - + + {{$ctrl.worker.sip.extension}} + + + +
diff --git a/modules/worker/front/descriptor/index.js b/modules/worker/front/descriptor/index.js index a53528ef2..446f8167c 100644 --- a/modules/worker/front/descriptor/index.js +++ b/modules/worker/front/descriptor/index.js @@ -1,6 +1,6 @@ import ngModule from '../module'; import Descriptor from 'salix/components/descriptor'; - +import './style.scss'; class Controller extends Descriptor { constructor($element, $, $rootScope) { super($element, $); diff --git a/modules/worker/front/descriptor/style.scss b/modules/worker/front/descriptor/style.scss new file mode 100644 index 000000000..6db663ae3 --- /dev/null +++ b/modules/worker/front/descriptor/style.scss @@ -0,0 +1,6 @@ +vn-worker-descriptor { + vn-icon.tel { + font-size: 1.1em; + vertical-align: bottom; + } +} \ No newline at end of file diff --git a/modules/worker/front/summary/index.html b/modules/worker/front/summary/index.html index 2607d9b2f..13924fe8d 100644 --- a/modules/worker/front/summary/index.html +++ b/modules/worker/front/summary/index.html @@ -42,14 +42,45 @@ {{::worker.boss.name}} - + + - + + {{worker.mobileExtension}} + + + + - + + - + + {{worker.phone}} + + + + + > + - + + {{worker.client.phone}} + + + + diff --git a/modules/worker/front/summary/index.js b/modules/worker/front/summary/index.js index 2bb1f0853..1e64527cf 100644 --- a/modules/worker/front/summary/index.js +++ b/modules/worker/front/summary/index.js @@ -1,6 +1,6 @@ import ngModule from '../module'; import Summary from 'salix/components/summary'; - +import './style.scss'; class Controller extends Summary { get worker() { return this._worker; diff --git a/modules/worker/front/summary/style.scss b/modules/worker/front/summary/style.scss new file mode 100644 index 000000000..2bde27129 --- /dev/null +++ b/modules/worker/front/summary/style.scss @@ -0,0 +1,6 @@ +vn-worker-summary { + vn-icon.tel { + font-size: 1.1em; + vertical-align: bottom; + } +} \ No newline at end of file From 0dbb77fc646f625df5432ba655c7a9da0357034e Mon Sep 17 00:00:00 2001 From: guillermo Date: Thu, 31 Aug 2023 09:20:33 +0200 Subject: [PATCH 050/427] refs #6023 Transactioned sync --- modules/account/back/methods/account/sync.js | 31 +++++++++++++------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/modules/account/back/methods/account/sync.js b/modules/account/back/methods/account/sync.js index 3ab19eed5..c4f9cb181 100644 --- a/modules/account/back/methods/account/sync.js +++ b/modules/account/back/methods/account/sync.js @@ -25,8 +25,10 @@ module.exports = Self => { }); Self.sync = async function(userName, password, force, options) { + const models = Self.app.models; const myOptions = {}; - + let tx; + if (typeof options == 'object') Object.assign(myOptions, options); @@ -35,16 +37,23 @@ module.exports = Self => { myOptions.transaction = tx; }; - const models = Self.app.models; - const user = await models.VnUser.findOne({ - fields: ['id'], - where: {name: userName} - }, myOptions); - const isSync = !await models.UserSync.exists(userName, myOptions); + try { + const user = await models.VnUser.findOne({ + fields: ['id'], + where: {name: userName} + }, myOptions); + const isSync = !await models.UserSync.exists(userName, myOptions); - if (!force && isSync && user) return; - await models.AccountConfig.syncUser(userName, password); - await models.UserSync.destroyById(userName, myOptions); + if (!force && isSync && user) { + if (tx) await tx.rollback(); + return; + } + await models.AccountConfig.syncUser(userName, password); + await models.UserSync.destroyById(userName, myOptions); + if (tx) await tx.commit(); + } catch (err) { + if (tx) await tx.rollback(); + throw err; + } }; }; - From c2a54b8c6590458094ec6cdc512bc00d556dccf4 Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 31 Aug 2023 13:02:56 +0200 Subject: [PATCH 051/427] ref #6119 vnLinkPhone created --- front/core/components/index.js | 1 + front/core/components/link-phone/index.html | 21 +++++++++ front/core/components/link-phone/index.js | 21 +++++++++ front/core/components/link-phone/style.scss | 7 +++ modules/client/front/summary/index.html | 24 +++------- modules/client/front/summary/style.scss | 4 -- modules/order/front/summary/index.html | 15 ++----- modules/order/front/summary/style.scss | 4 -- .../route/front/roadmap/summary/index.html | 12 ++--- .../route/front/roadmap/summary/style.scss | 7 +-- modules/ticket/front/summary/index.html | 44 +++++-------------- modules/worker/front/descriptor/index.html | 36 +++++---------- modules/worker/front/descriptor/index.js | 1 - modules/worker/front/descriptor/style.scss | 6 --- modules/worker/front/summary/index.html | 42 ++++-------------- modules/worker/front/summary/index.js | 1 - modules/worker/front/summary/style.scss | 6 --- 17 files changed, 96 insertions(+), 156 deletions(-) create mode 100644 front/core/components/link-phone/index.html create mode 100644 front/core/components/link-phone/index.js create mode 100644 front/core/components/link-phone/style.scss delete mode 100644 modules/worker/front/descriptor/style.scss delete mode 100644 modules/worker/front/summary/style.scss diff --git a/front/core/components/index.js b/front/core/components/index.js index eb40d5e1f..cfa46f0cb 100644 --- a/front/core/components/index.js +++ b/front/core/components/index.js @@ -39,6 +39,7 @@ import './range'; import './input-time'; import './input-file'; import './label'; +import './link-phone'; import './list'; import './popover'; import './popup'; diff --git a/front/core/components/link-phone/index.html b/front/core/components/link-phone/index.html new file mode 100644 index 000000000..2e2e2338a --- /dev/null +++ b/front/core/components/link-phone/index.html @@ -0,0 +1,21 @@ + + + + {{ $ctrl.phoneNumber }} + + + + + + + + {{ $ctrl.phoneNumber }} + + +- \ No newline at end of file diff --git a/front/core/components/link-phone/index.js b/front/core/components/link-phone/index.js new file mode 100644 index 000000000..7731487eb --- /dev/null +++ b/front/core/components/link-phone/index.js @@ -0,0 +1,21 @@ +import ngModule from '../../module'; +import './style.scss'; +class Controller { + constructor() { + this.phoneNumber = null; + this.icon = true; + this.showNumber = true; + this.schemeUrl = 'tel'; + } +} + +ngModule.vnComponent('vnLinkPhone', { + template: require('./index.html'), + controller: Controller, + bindings: { + phoneNumber: '<', + icon: ' - {{$ctrl.summary.phone}} - - - - + + - {{$ctrl.summary.mobile}} - - - + diff --git a/modules/client/front/summary/style.scss b/modules/client/front/summary/style.scss index dd30edaa0..7dc1cc928 100644 --- a/modules/client/front/summary/style.scss +++ b/modules/client/front/summary/style.scss @@ -11,8 +11,4 @@ vn-client-summary .summary { font-family: 'salixfont' !important; content: "\e965"; } - vn-icon.tel { - font-size: 1.1em; - vertical-align: bottom; - } } diff --git a/modules/order/front/summary/index.html b/modules/order/front/summary/index.html index 52a1afd6d..218359992 100644 --- a/modules/order/front/summary/index.html +++ b/modules/order/front/summary/index.html @@ -48,17 +48,10 @@ - - {{$ctrl.summary.address.phone}} - - - - + + diff --git a/modules/order/front/summary/style.scss b/modules/order/front/summary/style.scss index 7abcd889b..a2537c58f 100644 --- a/modules/order/front/summary/style.scss +++ b/modules/order/front/summary/style.scss @@ -17,8 +17,4 @@ vn-order-summary .summary{ } } } - vn-icon.tel { - font-size: 1.1em; - vertical-align: bottom; - } } \ No newline at end of file diff --git a/modules/route/front/roadmap/summary/index.html b/modules/route/front/roadmap/summary/index.html index c8ba85456..9fab0bf87 100644 --- a/modules/route/front/roadmap/summary/index.html +++ b/modules/route/front/roadmap/summary/index.html @@ -26,15 +26,9 @@ - {{summary.phone}} - - - - + - {{$ctrl.summary.address.phone}} - - - - + - {{$ctrl.summary.address.mobile}} - - - - + - {{$ctrl.summary.client.phone}} - - - + - {{$ctrl.summary.client.mobile}} - - - + diff --git a/modules/worker/front/descriptor/index.html b/modules/worker/front/descriptor/index.html index ce318540f..1131d3d6c 100644 --- a/modules/worker/front/descriptor/index.html +++ b/modules/worker/front/descriptor/index.html @@ -36,34 +36,18 @@ value="{{$ctrl.worker.department.department.name}}"> - - - - {{$ctrl.worker.phone}} - - - - + label="Phone" + > + - - - - {{$ctrl.worker.sip.extension}} - - - - + label="Extension" + > +
diff --git a/modules/worker/front/descriptor/index.js b/modules/worker/front/descriptor/index.js index 446f8167c..a2aadf3b3 100644 --- a/modules/worker/front/descriptor/index.js +++ b/modules/worker/front/descriptor/index.js @@ -1,6 +1,5 @@ import ngModule from '../module'; import Descriptor from 'salix/components/descriptor'; -import './style.scss'; class Controller extends Descriptor { constructor($element, $, $rootScope) { super($element, $); diff --git a/modules/worker/front/descriptor/style.scss b/modules/worker/front/descriptor/style.scss deleted file mode 100644 index 6db663ae3..000000000 --- a/modules/worker/front/descriptor/style.scss +++ /dev/null @@ -1,6 +0,0 @@ -vn-worker-descriptor { - vn-icon.tel { - font-size: 1.1em; - vertical-align: bottom; - } -} \ No newline at end of file diff --git a/modules/worker/front/summary/index.html b/modules/worker/front/summary/index.html index 13924fe8d..0d9aef7f8 100644 --- a/modules/worker/front/summary/index.html +++ b/modules/worker/front/summary/index.html @@ -43,44 +43,20 @@ - - - - {{worker.mobileExtension}} - - - - + - - - - {{worker.phone}} - - - - + - - - - {{worker.client.phone}} - - - - + diff --git a/modules/worker/front/summary/index.js b/modules/worker/front/summary/index.js index 1e64527cf..212609f58 100644 --- a/modules/worker/front/summary/index.js +++ b/modules/worker/front/summary/index.js @@ -1,6 +1,5 @@ import ngModule from '../module'; import Summary from 'salix/components/summary'; -import './style.scss'; class Controller extends Summary { get worker() { return this._worker; diff --git a/modules/worker/front/summary/style.scss b/modules/worker/front/summary/style.scss deleted file mode 100644 index 2bde27129..000000000 --- a/modules/worker/front/summary/style.scss +++ /dev/null @@ -1,6 +0,0 @@ -vn-worker-summary { - vn-icon.tel { - font-size: 1.1em; - vertical-align: bottom; - } -} \ No newline at end of file From 979315aa5e5fcbf3bfc6a52e64259f52d1210c9e Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 1 Sep 2023 12:10:39 +0200 Subject: [PATCH 052/427] refs #5995 Implemented downloadCmrsZip --- .../back/methods/route/downloadCmrsZip.js | 75 +++++++++++++++++++ .../back/methods/route/getExternalCmrs.js | 70 +++++++++-------- modules/route/back/models/route.js | 1 + 3 files changed, 115 insertions(+), 31 deletions(-) create mode 100644 modules/route/back/methods/route/downloadCmrsZip.js diff --git a/modules/route/back/methods/route/downloadCmrsZip.js b/modules/route/back/methods/route/downloadCmrsZip.js new file mode 100644 index 000000000..61f9701b5 --- /dev/null +++ b/modules/route/back/methods/route/downloadCmrsZip.js @@ -0,0 +1,75 @@ +const JSZip = require('jszip'); +const axios = require('axios'); +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('downloadCmrsZip', { + description: 'Download a zip file with multiple cmrs pdfs', + accessType: 'READ', + accepts: [ + { + arg: 'ids', + type: 'string', + description: 'The cmrs ids', + } + ], + returns: [ + { + arg: 'body', + type: 'file', + root: true + }, { + arg: 'Content-Type', + type: 'string', + http: {target: 'header'} + }, { + arg: 'Content-Disposition', + type: 'string', + http: {target: 'header'} + } + ], + http: { + path: '/downloadCmrsZip', + verb: 'GET' + } + }); + + Self.downloadCmrsZip = async function(ctx, ids, options) { + const models = Self.app.models; + const myOptions = {}; + const token = ctx.req.accessToken; + const zip = new JSZip(); + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const zipConfig = await models.ZipConfig.findOne(null, myOptions); + let totalSize = 0; + ids = ids.split(','); + try { + for (let id of ids) { + if (zipConfig && totalSize > zipConfig.maxSize) throw new UserError('Files are too large'); + const response = await axios.get( + `${ctx.req.headers.referer}api/Routes/${id}/cmr?access_token=${token.id}`, { + ...myOptions, + responseType: 'arraybuffer', + }); + + if (response.headers['content-type'] !== 'application/pdf') { + throw new UserError(`The response for cmr id ${id} is not a PDF.`); + } + + const pdfData = response.data; + const fileName = `${id}.pdf`; + + zip.file(fileName, pdfData, { binary: true }); + } + + const zipStream = zip.generateNodeStream({ streamFiles: true }); + + return [zipStream, 'application/zip', `filename="cmrs.zip"`]; + } catch (e) { + throw e; + } + }; +}; diff --git a/modules/route/back/methods/route/getExternalCmrs.js b/modules/route/back/methods/route/getExternalCmrs.js index 7b3772c9e..4750e53a1 100644 --- a/modules/route/back/methods/route/getExternalCmrs.js +++ b/modules/route/back/methods/route/getExternalCmrs.js @@ -22,6 +22,11 @@ module.exports = Self => { type: 'integer', description: 'The worker id', }, + { + arg: 'routeFk', + type: 'integer', + description: 'The route id', + }, { arg: 'country', type: 'string', @@ -57,6 +62,7 @@ module.exports = Self => { filter, cmrFk, ticketFk, + routeFk, country, clientFk, hasCmrDms, @@ -66,6 +72,7 @@ module.exports = Self => { const params = { cmrFk, ticketFk, + routeFk, country, clientFk, hasCmrDms, @@ -89,37 +96,38 @@ module.exports = Self => { let stmts = []; const stmt = new ParameterizedSQL(` - SELECT * - FROM ( - SELECT t.cmrFk, - t.id ticketFk, - co.country, - t.clientFk, - IF(sub.id, TRUE, FALSE) hasCmrDms, - DATE(t.shipped) shipped - FROM ticket t - JOIN ticketState ts ON ts.ticketFk = t.id - JOIN state s ON s.id = ts.stateFk - JOIN alertLevel al ON al.id = s.alertLevel - JOIN client c ON c.id = t.clientFk - JOIN address a ON a.id = t.addressFk - JOIN province p ON p.id = a.provinceFk - JOIN country co ON co.id = p.countryFk - JOIN agencyMode am ON am.id = t.agencyModeFk - JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk - JOIN warehouse w ON w.id = t.warehouseFk - LEFT JOIN ( - SELECT td.ticketFk, d.id - FROM ticketDms td - JOIN dms d ON d.id = td.dmsFk - JOIN dmsType dt ON dt.id = d.dmsTypeFk - WHERE dt.name = 'cmr' - ) sub ON sub.ticketFk = t.id - WHERE co.code <> 'ES' - AND am.name <> 'ABONO' - AND w.code = 'ALG' - AND dm.code = 'DELIVERY' - AND t.cmrFk + SELECT * + FROM ( + SELECT t.cmrFk, + t.id ticketFk, + t.routeFk, + co.country, + t.clientFk, + IF(sub.id, TRUE, FALSE) hasCmrDms, + DATE(t.shipped) shipped + FROM ticket t + JOIN ticketState ts ON ts.ticketFk = t.id + JOIN state s ON s.id = ts.stateFk + JOIN alertLevel al ON al.id = s.alertLevel + JOIN client c ON c.id = t.clientFk + JOIN address a ON a.id = t.addressFk + JOIN province p ON p.id = a.provinceFk + JOIN country co ON co.id = p.countryFk + JOIN agencyMode am ON am.id = t.agencyModeFk + JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk + JOIN warehouse w ON w.id = t.warehouseFk + LEFT JOIN ( + SELECT td.ticketFk, d.id + FROM ticketDms td + JOIN dms d ON d.id = td.dmsFk + JOIN dmsType dt ON dt.id = d.dmsTypeFk + WHERE dt.name = 'cmr' + ) sub ON sub.ticketFk = t.id + WHERE co.code <> 'ES' + AND am.name <> 'ABONO' + AND w.code = 'ALG' + AND dm.code = 'DELIVERY' + AND t.cmrFk ) sub `); diff --git a/modules/route/back/models/route.js b/modules/route/back/models/route.js index 7e61acf25..65fa43ab5 100644 --- a/modules/route/back/models/route.js +++ b/modules/route/back/models/route.js @@ -16,6 +16,7 @@ module.exports = Self => { require('../methods/route/downloadZip')(Self); require('../methods/route/cmr')(Self); require('../methods/route/getExternalCmrs')(Self); + require('../methods/route/downloadCmrsZip')(Self); Self.validate('kmStart', validateDistance, { message: 'Distance must be lesser than 1000' From 022d3d08e689c224595dff149e47c1e8b79102df Mon Sep 17 00:00:00 2001 From: sergiodt Date: Fri, 1 Sep 2023 12:34:33 +0200 Subject: [PATCH 053/427] refs #5652 feat:itemTrash_new --- back/methods/collection/getAddress.js | 20 ++++++ .../collection/spec/getAddress.spec.js | 10 +++ back/models/collection.js | 1 + .../233801/00-address_getLosesLastYear.sql | 15 +++++ .../233801/00-item_setVisibleDiscard.sql | 65 +++++++++++++++++++ db/changes/233801/00-ticketConfig.sql | 13 ++++ db/dump/fixtures.sql | 9 +++ .../back/methods/item/setVisibleDiscard.js | 37 +++++++++++ modules/item/back/models/item.js | 1 + 9 files changed, 171 insertions(+) create mode 100644 back/methods/collection/getAddress.js create mode 100644 back/methods/collection/spec/getAddress.spec.js create mode 100644 db/changes/233801/00-address_getLosesLastYear.sql create mode 100644 db/changes/233801/00-item_setVisibleDiscard.sql create mode 100644 db/changes/233801/00-ticketConfig.sql create mode 100644 modules/item/back/methods/item/setVisibleDiscard.js diff --git a/back/methods/collection/getAddress.js b/back/methods/collection/getAddress.js new file mode 100644 index 000000000..3fd4b9e6e --- /dev/null +++ b/back/methods/collection/getAddress.js @@ -0,0 +1,20 @@ +module.exports = Self => { + Self.remoteMethod('getAddress', { + description: 'Get all activated address last year ', + accessType: 'READ', + returns: { + type: 'Object', + root: true + }, + http: { + path: `/getAddress`, + verb: 'GET' + } + }); + + Self.getAddress = async() => { + const query = `CALL vn.address_getLosesLastYear()`; + const [result] = await Self.rawSql(query); + return result; + }; +}; diff --git a/back/methods/collection/spec/getAddress.spec.js b/back/methods/collection/spec/getAddress.spec.js new file mode 100644 index 000000000..aac769aa3 --- /dev/null +++ b/back/methods/collection/spec/getAddress.spec.js @@ -0,0 +1,10 @@ +const {models} = require('vn-loopback/server/server'); + +describe('getAddress()', () => { + fit('return list of address last year', async() => { + let response = await models.Collection.getAddress(); + + expect(response.length).toBeGreaterThan(0); + expect(response[0].addressFk).toEqual(1); + }); +}); diff --git a/back/models/collection.js b/back/models/collection.js index a41742ee7..75cdb1174 100644 --- a/back/models/collection.js +++ b/back/models/collection.js @@ -4,4 +4,5 @@ module.exports = Self => { require('../methods/collection/getSectors')(Self); require('../methods/collection/setSaleQuantity')(Self); require('../methods/collection/previousLabel')(Self); + require('../methods/collection/getAddress')(Self); }; diff --git a/db/changes/233801/00-address_getLosesLastYear.sql b/db/changes/233801/00-address_getLosesLastYear.sql new file mode 100644 index 000000000..3b8fa209b --- /dev/null +++ b/db/changes/233801/00-address_getLosesLastYear.sql @@ -0,0 +1,15 @@ + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`address_getLosesLastYear`() +BEGIN + SELECT t.addressFk , a.nickname, c.name + FROM ticket t + JOIN address a ON a.id = t.addressFk + JOIN client c ON a.clientFk = c.id + WHERE c.typeFk = 'loses' + AND a.isactive = 1 + AND t.created >= (CURRENT_DATE() - INTERVAL 1 YEAR) + GROUP BY t.addressFk; +END$$ +DELIMITER ; + diff --git a/db/changes/233801/00-item_setVisibleDiscard.sql b/db/changes/233801/00-item_setVisibleDiscard.sql new file mode 100644 index 000000000..1b9bf0ffb --- /dev/null +++ b/db/changes/233801/00-item_setVisibleDiscard.sql @@ -0,0 +1,65 @@ + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_setVisibleDiscard`( + vItemFk INT, + vWarehouseFk INT, + vQuantity INT, + vAddressFk INT) + +BEGIN + DECLARE vTicketFk INT; + DECLARE vClientFk INT; + DECLARE vCompanyVnlFk INT; + DECLARE vCalc INT; + + SELECT barcodeToItem(vItemFk) INTO vItemFk; + + SELECT companyDefaultFk INTO vCompanyVnlFk + FROM ticketConfig ; + + SELECT c.id INTO vClientFk + FROM client c + JOIN address a ON a.clientFk = c.id + WHERE a.id = vAddressFk; + + SELECT t.id INTO vTicketFk + FROM ticket t + JOIN address a ON a.id = t.addressFk + WHERE t.warehouseFk = vWarehouseFk + AND t.clientFk = vClientFk + AND DATE(t.shipped) = util.VN_CURDATE() + AND a.isDefaultAddress + LIMIT 1; + + CALL cache.visible_refresh(vCalc, TRUE, vWarehouseFk); + + IF vTicketFk IS NULL THEN + CALL ticket_add( + vClientFk, + util.VN_CURDATE(), + vWarehouseFk, + vCompanyVnlFk, + NULL, + NULL, + NULL, + util.VN_CURDATE(), + account.myUser_getId(), + FALSE, + vTicketFk); + END IF; + + INSERT INTO sale(ticketFk, itemFk, concept, quantity) + SELECT vTicketFk, + vItemFk, + CONCAT(longName,' ', getWorkerCode(), ' ', 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/db/changes/233801/00-ticketConfig.sql b/db/changes/233801/00-ticketConfig.sql new file mode 100644 index 000000000..d80dcd7ab --- /dev/null +++ b/db/changes/233801/00-ticketConfig.sql @@ -0,0 +1,13 @@ + +ALTER TABLE `vn`.`ticketConfig` ADD companyDefaultFk int(10) unsigned DEFAULT 442 NOT NULL COMMENT 'Compañía por defecto para crear ticket'; + +ALTER TABLE `vn`.`ticketConfig` ADD CONSTRAINT ticketConfig_FK FOREIGN KEY (companyDefaultFk) REFERENCES vn.company(id) ON DELETE CASCADE ON UPDATE CASCADE; + +-- Se desactivan por utilizarse muy poco + +UPDATE vn.address + SET isDefaultAddress = 0, + isActive = 0 + WHERE id IN (6,47); + + INSERT INTO `salix`.`ACL` (id, model, property, accessType, permission, principalType, principalId) VALUES(698, 'Item', 'setVisibleDiscard', 'WRITE', 'ALLOW', 'ROLE', 'employee'); diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index b01c07461..7ce39287e 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -2958,3 +2958,12 @@ INSERT INTO `vn`.`invoiceInSerial` (`code`, `description`, `cplusTerIdNifFk`, `t INSERT INTO `hedera`.`imageConfig` (`id`, `maxSize`, `useXsendfile`, `url`) VALUES (1, 0, 0, 'marvel.com'); + +--fixtures for getaddressLastYear +UPDATE vn.client + SET typeFk='loses' + WHERE id=1101; + +UPDATE vn.ticket + SET created='2023-08-01 00:00:00' + WHERE id=6; \ No newline at end of file diff --git a/modules/item/back/methods/item/setVisibleDiscard.js b/modules/item/back/methods/item/setVisibleDiscard.js new file mode 100644 index 000000000..bcdda1ced --- /dev/null +++ b/modules/item/back/methods/item/setVisibleDiscard.js @@ -0,0 +1,37 @@ +module.exports = Self => { + Self.remoteMethodCtx('setVisibleDiscard', { + description: 'Change visible for item', + accessType: 'WRITE', + accepts: [{ + arg: 'itemFk', + type: 'Number', + required: false, + description: 'The item id' + }, { + arg: 'warehouseFk', + type: 'Number', + required: true, + description: 'The warehouse of item' + }, { + arg: 'quantity', + type: 'Number', + required: true, + description: 'The quantity to modify' + }, + { + arg: 'addressFk', + type: 'Number', + required: true, + description: 'The address id' + }], + http: { + path: `/setVisibleDiscard`, + verb: 'POST' + } + }); + + Self.setVisibleDiscard = async(ctx, itemFk, warehouseFk, quantity, addressFk) => { + const query = `CALL vn.item_setVisibleDiscard(?, ?, ?, ?)`; + await Self.rawSql(query, [itemFk, warehouseFk, quantity, addressFk]); + }; +}; diff --git a/modules/item/back/models/item.js b/modules/item/back/models/item.js index 61c5c2588..eac1ecb7d 100644 --- a/modules/item/back/models/item.js +++ b/modules/item/back/models/item.js @@ -16,6 +16,7 @@ module.exports = Self => { require('../methods/item/createIntrastat')(Self); require('../methods/item/buyerWasteEmail')(Self); require('../methods/item/labelPdf')(Self); + require('../methods/item/setVisibleDiscard')(Self); Self.validatesPresenceOf('originFk', {message: 'Cannot be blank'}); From 52d698b0ebdd622b24337c370e75ed932d5266e8 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 1 Sep 2023 12:38:35 +0200 Subject: [PATCH 054/427] ref#6119 link fixed --- modules/worker/front/descriptor/index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/worker/front/descriptor/index.html b/modules/worker/front/descriptor/index.html index 1131d3d6c..69271db23 100644 --- a/modules/worker/front/descriptor/index.html +++ b/modules/worker/front/descriptor/index.html @@ -39,7 +39,7 @@ label="Phone" > Date: Mon, 4 Sep 2023 13:08:01 +0200 Subject: [PATCH 055/427] refs #6194 change link --- print/templates/email/printer-setup/locale/es.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/print/templates/email/printer-setup/locale/es.yml b/print/templates/email/printer-setup/locale/es.yml index b96d6d5f4..1884493ca 100644 --- a/print/templates/email/printer-setup/locale/es.yml +++ b/print/templates/email/printer-setup/locale/es.yml @@ -8,8 +8,8 @@ description: https://www.youtube.com/watch?v=qhb0kgQF3o8. También necesitarás el GoLabel, el programa para imprimir las cintas. - downloadFrom: Puedes descargarlo desde este enlace https://godex.s3-accelerate.amazonaws.com/_6f5glRrVhQAEBGhdUsqJA.file?v01 + downloadFrom: Puedes descargarlo desde este enlace https://godex.s3-accelerate.amazonaws.com/bF8ttaXcClv24092,4vQCQ.file?v01 downloadDriver: En este enlace puedes descargar el driver de la impresora https://es.seagullscientific.com/support/downloads/drivers/godex/download/ sections: @@ -40,4 +40,4 @@ help: Cualquier duda que te surja, no dudes en consultarla, ¡estamos pa atenderte! salesPersonName: Soy tu comercial y mi nombre es salesPersonPhone: Teléfono y whatsapp -salesPersonEmail: Dirección de e-mail \ No newline at end of file +salesPersonEmail: Dirección de e-mail From d14c49519e6ddb750cde49a68fa41e75c8bee01b Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 4 Sep 2023 13:16:35 +0200 Subject: [PATCH 056/427] refs #6159 fixSpec --- modules/client/back/methods/client/specs/setPassword.spec.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/client/back/methods/client/specs/setPassword.spec.js b/modules/client/back/methods/client/specs/setPassword.spec.js index 590172a02..6df527e70 100644 --- a/modules/client/back/methods/client/specs/setPassword.spec.js +++ b/modules/client/back/methods/client/specs/setPassword.spec.js @@ -13,11 +13,11 @@ describe('Client setPassword', () => { expect(error.message).toEqual(`Modifiable password only via recovery or by an administrator`); }); - it('should change the password of the client', async() => { + fit('should change the password of the client', async() => { let error; try { - await models.Client.setPassword(1101, 't0pl3v3l.p455w0rd!'); + await models.Client.setPassword(1105, 't0pl3v3l.p455w0rd!'); } catch (e) { error = e; } From 05a73247a11b416470972e2740a437fa67d62346 Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 4 Sep 2023 13:19:01 +0200 Subject: [PATCH 057/427] refs #6159 fix --- modules/client/back/methods/client/specs/setPassword.spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/client/back/methods/client/specs/setPassword.spec.js b/modules/client/back/methods/client/specs/setPassword.spec.js index 6df527e70..841f173bd 100644 --- a/modules/client/back/methods/client/specs/setPassword.spec.js +++ b/modules/client/back/methods/client/specs/setPassword.spec.js @@ -13,7 +13,7 @@ describe('Client setPassword', () => { expect(error.message).toEqual(`Modifiable password only via recovery or by an administrator`); }); - fit('should change the password of the client', async() => { + it('should change the password of the client', async() => { let error; try { From 2711ed579cca76ef9d8ebb7d142cbe80c0c9151c Mon Sep 17 00:00:00 2001 From: carlossa Date: Mon, 4 Sep 2023 13:26:08 +0200 Subject: [PATCH 058/427] refs #6194 generical url --- print/templates/email/printer-setup/locale/es.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/print/templates/email/printer-setup/locale/es.yml b/print/templates/email/printer-setup/locale/es.yml index 1884493ca..b07b88ffc 100644 --- a/print/templates/email/printer-setup/locale/es.yml +++ b/print/templates/email/printer-setup/locale/es.yml @@ -8,8 +8,8 @@ description: https://www.youtube.com/watch?v=qhb0kgQF3o8. También necesitarás el GoLabel, el programa para imprimir las cintas. - downloadFrom: Puedes descargarlo desde este enlace https://godex.s3-accelerate.amazonaws.com/bF8ttaXcClv24092,4vQCQ.file?v01 + downloadFrom: Puedes descargarlo desde este enlace, una vez dentro, abajo a la derecha podrás encontrar la sección de "Downloads", donde pulsando el icono de descarga, se iniciará la descarga automáticamente https://www.godexintl.com/product/16681379086423723?locale=en downloadDriver: En este enlace puedes descargar el driver de la impresora https://es.seagullscientific.com/support/downloads/drivers/godex/download/ sections: From b81dd1a9e81656dbae31e8401a0d5a1c8677e080 Mon Sep 17 00:00:00 2001 From: carlossa Date: Mon, 4 Sep 2023 14:01:36 +0200 Subject: [PATCH 059/427] refs #6194 new url verdnatura --- print/templates/email/printer-setup/locale/es.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/print/templates/email/printer-setup/locale/es.yml b/print/templates/email/printer-setup/locale/es.yml index b07b88ffc..00795b34b 100644 --- a/print/templates/email/printer-setup/locale/es.yml +++ b/print/templates/email/printer-setup/locale/es.yml @@ -8,8 +8,8 @@ description: https://www.youtube.com/watch?v=qhb0kgQF3o8. También necesitarás el GoLabel, el programa para imprimir las cintas. - downloadFrom: Puedes descargarlo desde este enlace, una vez dentro, abajo a la derecha podrás encontrar la sección de "Downloads", donde pulsando el icono de descarga, se iniciará la descarga automáticamente https://www.godexintl.com/product/16681379086423723?locale=en + downloadFrom: Puedes descargarlo desde este enlace https://cdn.verdnatura.es/public/GoLabel_II.zip downloadDriver: En este enlace puedes descargar el driver de la impresora https://es.seagullscientific.com/support/downloads/drivers/godex/download/ sections: From 8141cd7834c0dbb503ea9579d2c0a3b98976573e Mon Sep 17 00:00:00 2001 From: carlossa Date: Mon, 4 Sep 2023 14:08:17 +0200 Subject: [PATCH 060/427] refs #6194 url verdnatura --- print/templates/email/printer-setup/locale/es.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/print/templates/email/printer-setup/locale/es.yml b/print/templates/email/printer-setup/locale/es.yml index 00795b34b..39e83b1a8 100644 --- a/print/templates/email/printer-setup/locale/es.yml +++ b/print/templates/email/printer-setup/locale/es.yml @@ -8,8 +8,8 @@ description: https://www.youtube.com/watch?v=qhb0kgQF3o8. También necesitarás el GoLabel, el programa para imprimir las cintas. - downloadFrom: Puedes descargarlo desde este enlace https://cdn.verdnatura.es/public/GoLabel_II.zip + downloadFrom: Puedes descargarlo desde este enlace https://cdn.verdnatura.es/public/GoLabel.zip downloadDriver: En este enlace puedes descargar el driver de la impresora https://es.seagullscientific.com/support/downloads/drivers/godex/download/ sections: From 2fffa56d703ab2945895b19d72e05add031c6c95 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Wed, 6 Sep 2023 09:18:28 +0200 Subject: [PATCH 061/427] refs #5652 feat:itemTrash_new --- .../client/back/methods/address/getAddress.js | 21 +++++++++++++++++++ .../methods/address/specs}/getAddress.spec.js | 4 ++-- modules/client/back/models/address.js | 2 ++ 3 files changed, 25 insertions(+), 2 deletions(-) create mode 100644 modules/client/back/methods/address/getAddress.js rename {back/methods/collection/spec => modules/client/back/methods/address/specs}/getAddress.spec.js (70%) diff --git a/modules/client/back/methods/address/getAddress.js b/modules/client/back/methods/address/getAddress.js new file mode 100644 index 000000000..94e0439da --- /dev/null +++ b/modules/client/back/methods/address/getAddress.js @@ -0,0 +1,21 @@ +module.exports = Self => { + Self.remoteMethod('getAddress', { + description: 'Get all activated address last year ', + accessType: 'READ', + accepts: [], + returns: { + type: ['object'], + root: true + }, + http: { + path: `/getAddress`, + verb: 'GET' + } + }); + + Self.getAddress = async() => { + const query = `CALL vn.address_getLosesLastYear()`; + const [result] = await Self.rawSql(query); + return result; + }; +}; diff --git a/back/methods/collection/spec/getAddress.spec.js b/modules/client/back/methods/address/specs/getAddress.spec.js similarity index 70% rename from back/methods/collection/spec/getAddress.spec.js rename to modules/client/back/methods/address/specs/getAddress.spec.js index aac769aa3..707d7360b 100644 --- a/back/methods/collection/spec/getAddress.spec.js +++ b/modules/client/back/methods/address/specs/getAddress.spec.js @@ -1,8 +1,8 @@ const {models} = require('vn-loopback/server/server'); -describe('getAddress()', () => { +describe('getAddressa()', () => { fit('return list of address last year', async() => { - let response = await models.Collection.getAddress(); + let response = await models.Addressa.getAddress(); expect(response.length).toBeGreaterThan(0); expect(response[0].addressFk).toEqual(1); diff --git a/modules/client/back/models/address.js b/modules/client/back/models/address.js index 3a1157add..4a93b5d5c 100644 --- a/modules/client/back/models/address.js +++ b/modules/client/back/models/address.js @@ -3,6 +3,8 @@ let getFinalState = require('vn-loopback/util/hook').getFinalState; let isMultiple = require('vn-loopback/util/hook').isMultiple; module.exports = Self => { + require('../methods/address/getAddress')(Self); + Self.validateAsync('isEqualizated', cannotHaveET, { message: 'Cannot check Equalization Tax in this NIF/CIF' }); From 9d367b82999c5e296c9eabc53007632903288322 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Wed, 6 Sep 2023 09:22:29 +0200 Subject: [PATCH 062/427] refs #5652 feat:itemTrash_new --- back/methods/collection/getAddress.js | 20 -------------------- back/models/collection.js | 1 - 2 files changed, 21 deletions(-) delete mode 100644 back/methods/collection/getAddress.js diff --git a/back/methods/collection/getAddress.js b/back/methods/collection/getAddress.js deleted file mode 100644 index 3fd4b9e6e..000000000 --- a/back/methods/collection/getAddress.js +++ /dev/null @@ -1,20 +0,0 @@ -module.exports = Self => { - Self.remoteMethod('getAddress', { - description: 'Get all activated address last year ', - accessType: 'READ', - returns: { - type: 'Object', - root: true - }, - http: { - path: `/getAddress`, - verb: 'GET' - } - }); - - Self.getAddress = async() => { - const query = `CALL vn.address_getLosesLastYear()`; - const [result] = await Self.rawSql(query); - return result; - }; -}; diff --git a/back/models/collection.js b/back/models/collection.js index 75cdb1174..a41742ee7 100644 --- a/back/models/collection.js +++ b/back/models/collection.js @@ -4,5 +4,4 @@ module.exports = Self => { require('../methods/collection/getSectors')(Self); require('../methods/collection/setSaleQuantity')(Self); require('../methods/collection/previousLabel')(Self); - require('../methods/collection/getAddress')(Self); }; From dd1f759e209750481a4b8a2cd15fd54c205f4930 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Wed, 6 Sep 2023 09:35:43 +0200 Subject: [PATCH 063/427] refs #5652 feat:itemTrash_new --- db/changes/233801/00-ticketConfig.sql | 7 ++++++- .../client/back/methods/address/specs/getAddress.spec.js | 4 ++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/db/changes/233801/00-ticketConfig.sql b/db/changes/233801/00-ticketConfig.sql index d80dcd7ab..5cef1ba5f 100644 --- a/db/changes/233801/00-ticketConfig.sql +++ b/db/changes/233801/00-ticketConfig.sql @@ -10,4 +10,9 @@ UPDATE vn.address isActive = 0 WHERE id IN (6,47); - INSERT INTO `salix`.`ACL` (id, model, property, accessType, permission, principalType, principalId) VALUES(698, 'Item', 'setVisibleDiscard', 'WRITE', 'ALLOW', 'ROLE', 'employee'); + INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) + VALUES('Item', 'setVisibleDiscard', 'WRITE', 'ALLOW', 'ROLE', 'employee'); + + INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) + VALUES('Address', 'getAddress', 'READ', 'ALLOW', 'ROLE', 'employee'); + diff --git a/modules/client/back/methods/address/specs/getAddress.spec.js b/modules/client/back/methods/address/specs/getAddress.spec.js index 707d7360b..2c84769e6 100644 --- a/modules/client/back/methods/address/specs/getAddress.spec.js +++ b/modules/client/back/methods/address/specs/getAddress.spec.js @@ -1,8 +1,8 @@ const {models} = require('vn-loopback/server/server'); -describe('getAddressa()', () => { +describe('getAddress()', () => { fit('return list of address last year', async() => { - let response = await models.Addressa.getAddress(); + let response = await models.Address.getAddress(); expect(response.length).toBeGreaterThan(0); expect(response[0].addressFk).toEqual(1); From 8218eb2a6b12c1a15e2b9725d61dc891423317c7 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Wed, 6 Sep 2023 09:37:41 +0200 Subject: [PATCH 064/427] refs #5652 feat:itemTrash_new --- modules/client/back/methods/address/specs/getAddress.spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/client/back/methods/address/specs/getAddress.spec.js b/modules/client/back/methods/address/specs/getAddress.spec.js index 2c84769e6..d2b219495 100644 --- a/modules/client/back/methods/address/specs/getAddress.spec.js +++ b/modules/client/back/methods/address/specs/getAddress.spec.js @@ -1,7 +1,7 @@ const {models} = require('vn-loopback/server/server'); describe('getAddress()', () => { - fit('return list of address last year', async() => { + it('return list of address last year', async() => { let response = await models.Address.getAddress(); expect(response.length).toBeGreaterThan(0); From 04d04e6598a37c424400c9855ad55c252e5cf9de Mon Sep 17 00:00:00 2001 From: pablone Date: Wed, 6 Sep 2023 13:59:28 +0200 Subject: [PATCH 065/427] refs #6159 fixtrigger --- .../233601/00-updateAfterBusinnesInsert.sql | 42 ------------------- .../233801/00-updateAfterBusinnesInsert.sql | 21 ++++++++++ db/dump/fixtures.sql | 9 ---- .../methods/client/specs/setPassword.spec.js | 2 +- 4 files changed, 22 insertions(+), 52 deletions(-) delete mode 100644 db/changes/233601/00-updateAfterBusinnesInsert.sql create mode 100644 db/changes/233801/00-updateAfterBusinnesInsert.sql diff --git a/db/changes/233601/00-updateAfterBusinnesInsert.sql b/db/changes/233601/00-updateAfterBusinnesInsert.sql deleted file mode 100644 index f2b5dc753..000000000 --- a/db/changes/233601/00-updateAfterBusinnesInsert.sql +++ /dev/null @@ -1,42 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`business_afterInsert` - AFTER INSERT ON `business` - FOR EACH ROW -BEGIN - CALL worker_updateBusiness(NEW.workerFk); - - IF ( - SELECT NOT active - FROM account.user - WHERE id = NEW.workerFk - ) THEN - UPDATE account.user - SET active = TRUE - WHERE id = NEW.workerFk; - END IF; - - IF ( - SELECT NOT COUNT(aa.id) - FROM account.mailAliasAccount aa - JOIN account.mailAlias ma ON ma.id = aa.mailAlias - WHERE aa.account = NEW.workerFk - AND ma.alias = 'general' - ) THEN - INSERT INTO account.mailAliasAccount (mailAlias, account) - SELECT id, NEW.workerFk - FROM account.mailAlias - WHERE alias = 'general'; - END IF; - - IF ( - SELECT NOT COUNT(account) - FROM account.mailForward - WHERE account = NEW.workerFk - ) THEN - INSERT INTO account.mailForward (account, forwardTo) - SELECT NEW.workerFk, email - FROM account.user - WHERE id = NEW.workerFk; - END IF; -END$$ -DELIMITER ; diff --git a/db/changes/233801/00-updateAfterBusinnesInsert.sql b/db/changes/233801/00-updateAfterBusinnesInsert.sql new file mode 100644 index 000000000..82c71507c --- /dev/null +++ b/db/changes/233801/00-updateAfterBusinnesInsert.sql @@ -0,0 +1,21 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`business_afterInsert` + AFTER INSERT ON `business` + FOR EACH ROW +BEGIN + CALL worker_updateBusiness(NEW.workerFk); + UPDATE account.user + SET active = TRUE + WHERE id = NEW.workerFk; + + INSERT IGNORE INTO account.mailAliasAccount (mailAlias, account) + SELECT id, NEW.workerFk + FROM account.mailAlias + WHERE alias = 'general'; + + INSERT IGNORE INTO account.mailForward (account, forwardTo) + SELECT NEW.workerFk, email + FROM account.user + WHERE id = NEW.workerFk; +END$$ +DELIMITER ; diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 5ac355ea4..68922d176 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -1965,12 +1965,6 @@ INSERT INTO `vn`.`calendarType` (`id`, `description`, `hoursWeek`, `isPartial`) VALUES (1, 'General schedule', 40, 0); -INSERT INTO `account`.`account`(id) - SELECT u.id - FROM account.user u - LEFT JOIN account.account a ON a.id = u.id - WHERE a.id IS NULL; - DROP TEMPORARY TABLE IF EXISTS tmp.worker; CREATE TEMPORARY TABLE tmp.worker (PRIMARY KEY (id)) @@ -1994,9 +1988,6 @@ INSERT INTO `vn`.`business` (`id`, `workerFk`, `companyCodeFk`, `started`, `ende DROP TEMPORARY TABLE IF EXISTS tmp.worker; -DELETE FROM `account`.`account` - WHERE id = 1105; - UPDATE `vn`.`business` SET `payedHolidays`= 8 WHERE `id`= 1106; diff --git a/modules/client/back/methods/client/specs/setPassword.spec.js b/modules/client/back/methods/client/specs/setPassword.spec.js index 841f173bd..590172a02 100644 --- a/modules/client/back/methods/client/specs/setPassword.spec.js +++ b/modules/client/back/methods/client/specs/setPassword.spec.js @@ -17,7 +17,7 @@ describe('Client setPassword', () => { let error; try { - await models.Client.setPassword(1105, 't0pl3v3l.p455w0rd!'); + await models.Client.setPassword(1101, 't0pl3v3l.p455w0rd!'); } catch (e) { error = e; } From 86ecaedb0e12e5b1f95a498e37e75cfa2a6d1d8e Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 6 Sep 2023 14:33:31 +0200 Subject: [PATCH 066/427] ref #6119 scheme url removed --- front/core/components/link-phone/index.html | 4 ++-- front/core/components/link-phone/index.js | 2 -- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/front/core/components/link-phone/index.html b/front/core/components/link-phone/index.html index 2e2e2338a..54bcc1e9f 100644 --- a/front/core/components/link-phone/index.html +++ b/front/core/components/link-phone/index.html @@ -3,7 +3,7 @@ {{ $ctrl.phoneNumber }} - + - + {{ $ctrl.phoneNumber }} diff --git a/front/core/components/link-phone/index.js b/front/core/components/link-phone/index.js index 7731487eb..d5c828f21 100644 --- a/front/core/components/link-phone/index.js +++ b/front/core/components/link-phone/index.js @@ -5,7 +5,6 @@ class Controller { this.phoneNumber = null; this.icon = true; this.showNumber = true; - this.schemeUrl = 'tel'; } } @@ -16,6 +15,5 @@ ngModule.vnComponent('vnLinkPhone', { phoneNumber: '<', icon: ' Date: Thu, 7 Sep 2023 09:03:25 +0200 Subject: [PATCH 067/427] refs #4059 acls --- db/changes/233801/00-aclClient.sql | 40 +++++++++++++++++++++++++++++ db/changes/233801/01-aclAccount.sql | 10 ++++++++ 2 files changed, 50 insertions(+) create mode 100644 db/changes/233801/00-aclClient.sql create mode 100644 db/changes/233801/01-aclAccount.sql diff --git a/db/changes/233801/00-aclClient.sql b/db/changes/233801/00-aclClient.sql new file mode 100644 index 000000000..5308dbbe2 --- /dev/null +++ b/db/changes/233801/00-aclClient.sql @@ -0,0 +1,40 @@ +-- No encuentro este back +DELETE FROM salix.ACL WHERE property = 'activeWorkersWithRole'; +DELETE FROM salix.ACL WHERE model = 'Client' AND property = '*'; + +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES ('Client','findOne','READ','ALLOW','ROLE','employee'); +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES ('Client','findById','READ','ALLOW','ROLE','employee'); +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES ('Client','find','READ','ALLOW','ROLE','employee'); +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES ('Client','exists','READ','ALLOW','ROLE','employee'); + +DELETE FROM salix.ACL WHERE model = 'Client' AND property = '*' AND accessType IN ( + 'campaignMetricsEmail', + 'campaignMetricsPdf', + 'clientDebtStatementEmail', + 'clientDebtStatementHtml', + 'clientDebtStatementPdf', + 'clientWelcomeEmail', + 'clientWelcomeHtml', + 'consumptionSendQueued', + 'creditRequestEmail', + 'creditRequestHtml', + 'creditRequestPdf', + 'getClientOrSupplierReference', + 'incotermsAuthorizationEmail', + 'incotermsAuthorizationHtml', + 'incotermsAuthorizationPdf', + 'letterDebtorNdEmail', + 'letterDebtorNdHtml', + 'letterDebtorPdf', + 'letterDebtorStEmail', + 'letterDebtorStHtml', + 'printerSetupEmail', + 'printerSetupHtml', + 'sepaCoreEmail', + 'setPassword', + 'updateUser', + 'uploadFile'); diff --git a/db/changes/233801/01-aclAccount.sql b/db/changes/233801/01-aclAccount.sql new file mode 100644 index 000000000..0f2d6d48c --- /dev/null +++ b/db/changes/233801/01-aclAccount.sql @@ -0,0 +1,10 @@ +DELETE FROM salix.ACL WHERE model = 'Account' AND property = '*' AND principalId = 'employee'; + +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES ('Account','findOne','READ','ALLOW','ROLE','employee'); +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES ('Account','findById','READ','ALLOW','ROLE','employee'); +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES ('Account','find','READ','ALLOW','ROLE','employee'); +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES ('Account','exists','READ','ALLOW','ROLE','employee'); From 427425a750f7fba0acb0dcd07a6624f14bb1ceec Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 7 Sep 2023 09:50:13 +0200 Subject: [PATCH 068/427] ref #6119 simplifiy component --- front/core/components/link-phone/index.html | 34 +++++++------------ modules/client/front/summary/index.html | 2 ++ modules/order/front/summary/index.html | 1 + .../route/front/roadmap/summary/index.html | 1 + modules/ticket/front/summary/index.html | 4 +++ modules/worker/front/descriptor/index.html | 4 ++- modules/worker/front/summary/index.html | 3 ++ 7 files changed, 27 insertions(+), 22 deletions(-) diff --git a/front/core/components/link-phone/index.html b/front/core/components/link-phone/index.html index 54bcc1e9f..fc520cefd 100644 --- a/front/core/components/link-phone/index.html +++ b/front/core/components/link-phone/index.html @@ -1,21 +1,13 @@ - - - - {{ $ctrl.phoneNumber }} - - - - - - - - {{ $ctrl.phoneNumber }} - - -- \ No newline at end of file + + + + \ No newline at end of file diff --git a/modules/client/front/summary/index.html b/modules/client/front/summary/index.html index 8bec03d8b..a0c83ded1 100644 --- a/modules/client/front/summary/index.html +++ b/modules/client/front/summary/index.html @@ -46,12 +46,14 @@ value="{{$ctrl.summary.contact}}"> + {{$ctrl.summary.phone | dashIfEmpty}} + {{$ctrl.summary.mobile | dashIfEmpty}} diff --git a/modules/order/front/summary/index.html b/modules/order/front/summary/index.html index 218359992..e9bdf33b2 100644 --- a/modules/order/front/summary/index.html +++ b/modules/order/front/summary/index.html @@ -49,6 +49,7 @@ value="{{$ctrl.summary.landed | date: 'dd/MM/yyyy HH:mm'}}"> + {{$ctrl.summary.address.phone | dashIfEmpty}} diff --git a/modules/route/front/roadmap/summary/index.html b/modules/route/front/roadmap/summary/index.html index 9fab0bf87..aea7e717b 100644 --- a/modules/route/front/roadmap/summary/index.html +++ b/modules/route/front/roadmap/summary/index.html @@ -26,6 +26,7 @@ + {{summary.phone | dashIfEmpty}} diff --git a/modules/ticket/front/summary/index.html b/modules/ticket/front/summary/index.html index 3c60352a7..4a92daa39 100644 --- a/modules/ticket/front/summary/index.html +++ b/modules/ticket/front/summary/index.html @@ -84,6 +84,7 @@ + {{$ctrl.summary.address.phone | dashIfEmpty}} @@ -91,18 +92,21 @@ + {{$ctrl.summary.address.mobile | dashIfEmpty}} + {{$ctrl.summary.client.phone | dashIfEmpty}} + {{$ctrl.summary.client.mobile | dashIfEmpty}} diff --git a/modules/worker/front/descriptor/index.html b/modules/worker/front/descriptor/index.html index 69271db23..4a5fb894e 100644 --- a/modules/worker/front/descriptor/index.html +++ b/modules/worker/front/descriptor/index.html @@ -38,13 +38,15 @@ + {{$ctrl.worker.phone | dashIfEmpty}} + > + {{$ctrl.worker.sip.extension | dashIfEmpty}} diff --git a/modules/worker/front/summary/index.html b/modules/worker/front/summary/index.html index 0d9aef7f8..a95b96c5e 100644 --- a/modules/worker/front/summary/index.html +++ b/modules/worker/front/summary/index.html @@ -43,17 +43,20 @@ + {{worker.mobileExtension | dashIfEmpty}} + {{worker.phone | dashIfEmpty}} + {{worker.client.phone | dashIfEmpty}} From da9182783d1a5f0a584a0826cc379e951addac97 Mon Sep 17 00:00:00 2001 From: pablone Date: Thu, 7 Sep 2023 11:02:47 +0200 Subject: [PATCH 069/427] refs #5881 changes --- db/changes/233601/00-createClaimReader.sql | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/db/changes/233601/00-createClaimReader.sql b/db/changes/233601/00-createClaimReader.sql index 666bf232e..e913c0ed9 100644 --- a/db/changes/233601/00-createClaimReader.sql +++ b/db/changes/233601/00-createClaimReader.sql @@ -1,4 +1,4 @@ -INSERT INTO `account`.`role` (`id`, `name`, `description`, `hasLogin`) +INSERT INTO `account`.`role` (`name`, `description`, `hasLogin`) VALUES ('claimViewer','Trabajadores que consulta las reclamaciones ',1); INSERT INTO `account`.`roleInherit` (`role`,`inheritsFrom`) @@ -10,7 +10,7 @@ INSERT INTO `account`.`roleInherit` (`role`,`inheritsFrom`) 'buyer', 'deliveryBoss', 'handmadeBoss' - ) + ); DELETE FROM `salix`.`ACL` WHERE `model`= 'claim' @@ -28,5 +28,4 @@ INSERT INTO `salix`.`ACL` (`model`,`property`,`accessType`,`permission`,`princip 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'); - + VALUES ('Claim','getSummary','READ','ALLOW','ROLE','claimViewer'); \ No newline at end of file From e20a8d215ddbb365621db07b3e7028723a2e3e31 Mon Sep 17 00:00:00 2001 From: guillermo Date: Thu, 7 Sep 2023 11:47:33 +0200 Subject: [PATCH 070/427] refs #5662 Add email modified-collection-volumetry --- .../assets/css/import.js | 12 +++++++++ .../assets/css/style.css | 8 ++++++ .../locale/en.yml | 3 +++ .../locale/es.yml | 3 +++ .../modified-collection-volumetry.html | 15 +++++++++++ .../modified-collection-volumetry.js | 25 +++++++++++++++++++ 6 files changed, 66 insertions(+) create mode 100644 print/templates/email/modified-collection-volumetry/assets/css/import.js create mode 100644 print/templates/email/modified-collection-volumetry/assets/css/style.css create mode 100644 print/templates/email/modified-collection-volumetry/locale/en.yml create mode 100644 print/templates/email/modified-collection-volumetry/locale/es.yml create mode 100644 print/templates/email/modified-collection-volumetry/modified-collection-volumetry.html create mode 100755 print/templates/email/modified-collection-volumetry/modified-collection-volumetry.js diff --git a/print/templates/email/modified-collection-volumetry/assets/css/import.js b/print/templates/email/modified-collection-volumetry/assets/css/import.js new file mode 100644 index 000000000..fec23d870 --- /dev/null +++ b/print/templates/email/modified-collection-volumetry/assets/css/import.js @@ -0,0 +1,12 @@ +const Stylesheet = require(`vn-print/core/stylesheet`); + +const path = require('path'); +const vnPrintPath = path.resolve('print'); + +module.exports = new Stylesheet([ + `${vnPrintPath}/common/css/spacing.css`, + `${vnPrintPath}/common/css/misc.css`, + `${vnPrintPath}/common/css/layout.css`, + `${vnPrintPath}/common/css/email.css`, + `${__dirname}/style.css`]) + .mergeStyles(); diff --git a/print/templates/email/modified-collection-volumetry/assets/css/style.css b/print/templates/email/modified-collection-volumetry/assets/css/style.css new file mode 100644 index 000000000..5e006baa2 --- /dev/null +++ b/print/templates/email/modified-collection-volumetry/assets/css/style.css @@ -0,0 +1,8 @@ +.jsonSection { + text-align: left; + background-color: #e4e4e4; + padding: 25px; + margin-left: 60px; + margin-right: 60px; + border-radius: 25px; +} \ No newline at end of file diff --git a/print/templates/email/modified-collection-volumetry/locale/en.yml b/print/templates/email/modified-collection-volumetry/locale/en.yml new file mode 100644 index 000000000..d29b5b8de --- /dev/null +++ b/print/templates/email/modified-collection-volumetry/locale/en.yml @@ -0,0 +1,3 @@ +subject: Modified collection volumetry +title: Modified collection volumetry +description: Action performed \ No newline at end of file diff --git a/print/templates/email/modified-collection-volumetry/locale/es.yml b/print/templates/email/modified-collection-volumetry/locale/es.yml new file mode 100644 index 000000000..c271183b5 --- /dev/null +++ b/print/templates/email/modified-collection-volumetry/locale/es.yml @@ -0,0 +1,3 @@ +subject: Volumetría de colección modificada +title: Volumetría de colección modificada +description: Acción realizada \ No newline at end of file diff --git a/print/templates/email/modified-collection-volumetry/modified-collection-volumetry.html b/print/templates/email/modified-collection-volumetry/modified-collection-volumetry.html new file mode 100644 index 000000000..32ad19fd4 --- /dev/null +++ b/print/templates/email/modified-collection-volumetry/modified-collection-volumetry.html @@ -0,0 +1,15 @@ + +
+
+
+

{{ $t('title') }}

+

{{ $t('description') }}: {{ data.action }} {{ `(${this.username})` }}

+
+ + {{ `${key}:` }} {{ value }}
+
+
+
+
+
+
diff --git a/print/templates/email/modified-collection-volumetry/modified-collection-volumetry.js b/print/templates/email/modified-collection-volumetry/modified-collection-volumetry.js new file mode 100755 index 000000000..4345ead47 --- /dev/null +++ b/print/templates/email/modified-collection-volumetry/modified-collection-volumetry.js @@ -0,0 +1,25 @@ +const Component = require(`vn-print/core/component`); +const emailBody = new Component('email-body'); +const models = require('vn-loopback/server/server').models; + +module.exports = { + name: 'modified-collection-volumetry', + components: { + 'email-body': emailBody.build(), + }, + async serverPrefetch() { + this.username = (this.data.userFk) ? await this.getUsername(this.data.userFk) : 'system'; + }, + methods: { + async getUsername(id) { + const account = await models.VnUser.findById(id); + return account.name; + } + }, + props: { + data: { + type: Object, + required: true + } + } +}; From d6027096799301eb9ccf2399b3cb0c107cbab967 Mon Sep 17 00:00:00 2001 From: jgallego Date: Mon, 11 Sep 2023 08:46:26 +0200 Subject: [PATCH 071/427] refs #4059 changes en la carpeta actual --- db/changes/232001/00-aclClient.sql | 40 ----------------------------- db/changes/232001/01-aclAccount.sql | 13 ---------- 2 files changed, 53 deletions(-) delete mode 100644 db/changes/232001/00-aclClient.sql delete mode 100644 db/changes/232001/01-aclAccount.sql diff --git a/db/changes/232001/00-aclClient.sql b/db/changes/232001/00-aclClient.sql deleted file mode 100644 index dec6f6136..000000000 --- a/db/changes/232001/00-aclClient.sql +++ /dev/null @@ -1,40 +0,0 @@ --- No encuentro este back -DELETE FROM salix.ACL WHERE property = 'activeWorkersWithRole'; -DELETE FROM salix.ACL WHERE model = 'Client' AND property = '*'; - -INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) - VALUES ('Client','findOne','READ','ALLOW','ROLE','employee'); -INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) - VALUES ('Client','findById','READ','ALLOW','ROLE','employee'); -INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) - VALUES ('Client','find','READ','ALLOW','ROLE','employee'); -INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) - VALUES ('Client','exists','READ','ALLOW','ROLE','employee'); - -DELETE FROM salix.ACL WHERE model = 'Client' AND accessType = '*' AND property IN ( - 'campaignMetricsEmail', - 'campaignMetricsPdf', - 'clientDebtStatementEmail', - 'clientDebtStatementHtml', - 'clientDebtStatementPdf', - 'clientWelcomeEmail', - 'clientWelcomeHtml', - 'consumptionSendQueued', - 'creditRequestEmail', - 'creditRequestHtml', - 'creditRequestPdf', - 'getClientOrSupplierReference', - 'incotermsAuthorizationEmail', - 'incotermsAuthorizationHtml', - 'incotermsAuthorizationPdf', - 'letterDebtorNdEmail', - 'letterDebtorNdHtml', - 'letterDebtorPdf', - 'letterDebtorStEmail', - 'letterDebtorStHtml', - 'printerSetupEmail', - 'printerSetupHtml', - 'sepaCoreEmail', - 'setPassword', - 'updateUser', - 'uploadFile'); \ No newline at end of file diff --git a/db/changes/232001/01-aclAccount.sql b/db/changes/232001/01-aclAccount.sql deleted file mode 100644 index f618ca842..000000000 --- a/db/changes/232001/01-aclAccount.sql +++ /dev/null @@ -1,13 +0,0 @@ -DELETE FROM salix.ACL WHERE model = 'Account' AND property = '*'; - -INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) - VALUES ('Account','findOne','READ','ALLOW','ROLE','employee'); -INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) - VALUES ('Account','findById','READ','ALLOW','ROLE','employee'); -INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) - VALUES ('Account','find','READ','ALLOW','ROLE','employee'); -INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) - VALUES ('Account','exists','READ','ALLOW','ROLE','employee'); - -DELETE FROM salix.ACL WHERE id=529; --- 529 VnUser changePassword WRITE ALLOW ROLE account \ No newline at end of file From 9d0e4e7558d2583e7e1863d2fdc69af37d21460c Mon Sep 17 00:00:00 2001 From: carlossa Date: Mon, 11 Sep 2023 10:47:39 +0200 Subject: [PATCH 072/427] refs #5660 change sql --- db/changes/{233201 => 233801}/01-deliveryAssistantACL.sql | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename db/changes/{233201 => 233801}/01-deliveryAssistantACL.sql (100%) diff --git a/db/changes/233201/01-deliveryAssistantACL.sql b/db/changes/233801/01-deliveryAssistantACL.sql similarity index 100% rename from db/changes/233201/01-deliveryAssistantACL.sql rename to db/changes/233801/01-deliveryAssistantACL.sql From 62a4469803ae0d01195a5bd06280349f16f3e5fb Mon Sep 17 00:00:00 2001 From: carlossa Date: Mon, 11 Sep 2023 11:34:23 +0200 Subject: [PATCH 073/427] refs #5660 cambios structure --- db/dump/structure.sql | 10171 ++++++++++++++++++++-------------------- 1 file changed, 5027 insertions(+), 5144 deletions(-) diff --git a/db/dump/structure.sql b/db/dump/structure.sql index b7fb40485..73f6e92cb 100644 --- a/db/dump/structure.sql +++ b/db/dump/structure.sql @@ -787,7 +787,7 @@ DELIMITER ;; FOR EACH ROW BEGIN SET NEW.editorFk = account.myUser_getId(); - + CALL user_checkName(NEW.`name`); IF NEW.nickname = '' THEN @@ -1018,7 +1018,7 @@ BEGIN SET vSignature = util.hmacSha2(256, CONCAT_WS('/', @userId, @userName), vKey); RETURN vSignature = @userSignature; END IF; - + RETURN FALSE; END ;; @@ -1047,7 +1047,7 @@ BEGIN * @return The user id */ DECLARE vUser INT DEFAULT NULL; - + IF myUser_checkLogin() THEN SET vUser = @userId; @@ -1055,7 +1055,7 @@ BEGIN SELECT id INTO vUser FROM user WHERE name = LEFT(USER(), INSTR(USER(), '@') - 1); END IF; - + RETURN vUser; END ;; DELIMITER ; @@ -1090,7 +1090,7 @@ BEGIN ELSE SET vUser = LEFT(USER(), INSTR(USER(), '@') - 1); END IF; - + RETURN vUser; END ;; DELIMITER ; @@ -1185,10 +1185,10 @@ BEGIN DECLARE vDigitChars TEXT DEFAULT '1234567890'; DECLARE vPunctChars TEXT DEFAULT '!$%&()=.'; - SELECT length, nAlpha, nUpper, nDigits, nPunct + SELECT length, nAlpha, nUpper, nDigits, nPunct INTO vMinLength, vMinAlpha, vMinUpper, vMinDigits, vMinPunct FROM userPassword; - WHILE LENGTH(vPwd) < vMinLength OR vAlpha < vMinAlpha + WHILE LENGTH(vPwd) < vMinLength OR vAlpha < vMinAlpha OR vUpper < vMinUpper OR vDigits < vMinDigits OR vPunct < vMinPunct DO SET vRandIndex = FLOOR((RAND() * 4) + 1); @@ -1263,7 +1263,7 @@ BEGIN DECLARE vRole VARCHAR(255); SELECT CONCAT(IF(r.hasLogin, c.rolePrefix, ''), r.name) INTO vRole - FROM role r + FROM role r JOIN user u ON u.role = r.id JOIN roleConfig c WHERE u.name = vUserName; @@ -1290,16 +1290,16 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `user_getNameFromId`(vSelf INT) RETUR BEGIN /** * Gets user name from it's id. - * + * * @param vSelf The user id * @return The user name */ DECLARE vName VARCHAR(30); - - SELECT `name` INTO vName - FROM user + + SELECT `name` INTO vName + FROM user WHERE id = vSelf; - + RETURN vName; END ;; DELIMITER ; @@ -1371,7 +1371,7 @@ BEGIN JOIN role r ON r.id = rr.inheritsFrom WHERE u.`name` = vUser AND r.id = vRoleId; - + RETURN vHasRole; END ;; DELIMITER ; @@ -1405,7 +1405,7 @@ BEGIN AND password = MD5(vPassword) AND active; - IF vAuthIsOk + IF vAuthIsOk THEN CALL myUser_loginWithName (vUserName); ELSE @@ -1466,7 +1466,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `myUser_loginWithName`(vUserName VAR BEGIN /** * Logs in using only the user name. This procedure is intended to be executed - * by users with a high level of privileges so that normal users should not have + * by users with a high level of privileges so that normal users should not have * execute permissions on it. * * @param vUserName The user name @@ -1502,7 +1502,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `myUser_logout`() BEGIN /** * Logouts the user. - */ + */ SET @userId = NULL; SET @userName = NULL; SET @userSignature = NULL; @@ -1600,9 +1600,9 @@ BEGIN SELECT COUNT(*) > 0 INTO vIsRoot FROM tmp.role t - JOIN role r ON r.id = t.id + JOIN role r ON r.id = t.id WHERE r.`name` = 'root'; - + IF vIsRoot THEN INSERT IGNORE INTO tmp.role (id) SELECT id FROM role; @@ -2321,7 +2321,7 @@ BEGIN IF vChr REGEXP '[[:alpha:]]' THEN SET vNAlpha = vNAlpha+1; - + IF vChr REGEXP '[A-Z]' THEN SET vNUpper = vNUpper+1; @@ -2792,7 +2792,7 @@ BEGIN IF NOT (NEW.`schema`REGEXP '^[0-9a-zA-Z_]+$') OR NOT (NEW.`procedure`REGEXP '^[0-9a-zA-Z_]+$') THEN CALL util.throw('ONLY_ALPHANUMERICS_ALLOWED'); - + END IF; END */;; @@ -2818,7 +2818,7 @@ BEGIN IF NOT (NEW.`schema`REGEXP '^[0-9a-zA-Z_]+$') OR NOT (NEW.`procedure`REGEXP '^[0-9a-zA-Z_]+$') THEN CALL util.throw('ONLY_ALPHANUMERICS_ALLOWED'); - + END IF; END */;; @@ -3341,11 +3341,11 @@ BEGIN DECLARE vTramo VARCHAR(20); DECLARE vHour INT; - + SET vHour = HOUR(vDateTime) ; - + SET vTramo = - CASE + CASE WHEN vHour BETWEEN 0 AND 14 THEN 'Mañana' WHEN vHour BETWEEN 15 AND 24 THEN 'Tarde' END ; @@ -3373,7 +3373,7 @@ BEGIN * Inserta en la tabla bancos_evolution los saldos acumulados de cada banco * * @param vStartingDate Fecha desde la cual se recalculan la tabla bs.bancos_evolution - */ + */ DECLARE vCurrentDate DATE; DECLARE vMaxDate DATE DEFAULT TIMESTAMPADD(MONTH, 7, util.VN_CURDATE()); IF IFNULL(vStartingDate,0) < TIMESTAMPADD(YEAR, -5, util.VN_CURDATE()) THEN @@ -3387,49 +3387,49 @@ BEGIN SELECT vCurrentDate, Id_Banco, deuda FROM bs.bancos_evolution WHERE Fecha = TIMESTAMPADD(DAY,-1,vCurrentDate); - + WHILE vCurrentDate < vMaxDate DO -- insertar solo el dia de ayer INSERT INTO bs.bancos_evolution(Fecha ,Id_Banco, saldo) - SELECT vCurrentDate, Id_Banco, SUM(saldo) + SELECT vCurrentDate, Id_Banco, SUM(saldo) FROM ( SELECT Id_Banco ,saldo FROM bs.bancos_evolution WHERE Fecha = TIMESTAMPADD(DAY,-1,vCurrentDate) -- los saldos acumulados del dia anterior UNION ALL - + SELECT c.Id_Banco, IFNULL(SUM(Entrada),0) - IFNULL(SUM(Salida),0) as saldo FROM vn2008.Cajas c JOIN vn2008.Bancos b using(Id_Banco) -- saldos de las cajas - JOIN vn.accountingType at2 ON at2.id = b.cash + JOIN vn.accountingType at2 ON at2.id = b.cash WHERE at2.code IN ('wireTransfer','fundingLine') AND Cajafecha = vCurrentDate AND (Serie = 'MB' OR at2.code = 'fundingLine') GROUP BY Id_Banco - )sub + )sub GROUP BY Id_Banco ON DUPLICATE KEY UPDATE saldo = saldo + VALUES(saldo); - + SET vCurrentDate = TIMESTAMPADD(DAY,1,vCurrentDate); END WHILE; - -- Ahora actualizamos la quilla + -- Ahora actualizamos la quilla UPDATE bs.bancos_evolution be JOIN ( SELECT bp.Id_Banco, - sum(bp.importe) as quilla, t.dated - FROM vn.time t + FROM vn.time t JOIN vn2008.Bancos_poliza bp ON t.dated between apertura AND IFNULL(cierre, t.dated) WHERE t.dated BETWEEN vStartingDate AND vMaxDate GROUP BY Id_Banco, t.dated ) sub ON be.Id_Banco = sub.Id_Banco AND sub.dated = be.Fecha - SET be.quilla = sub.quilla; + SET be.quilla = sub.quilla; -- pagos futuros no concilidados INSERT INTO bs.bancos_evolution(Fecha, Id_Banco, saldo) SELECT t.dated, p.id_banco, - importe - FROM vn.time t + FROM vn.time t join vn2008.pago p ON p.fecha <= t.dated WHERE t.dated BETWEEN util.VN_CURDATE() AND vMaxDate AND p.fecha BETWEEN util.VN_CURDATE() AND vMaxDate @@ -3439,7 +3439,7 @@ BEGIN -- cobros futuros INSERT INTO bs.bancos_evolution(Fecha, Id_Banco, saldo) SELECT t.dated, r.Id_Banco, SUM(Entregado) - FROM vn.time t + FROM vn.time t JOIN vn2008.Recibos r ON r.Fechacobro <= t.dated WHERE r.Fechacobro > util.VN_CURDATE() AND r.Fechacobro <= vMaxDate AND t.dated BETWEEN util.VN_CURDATE() AND vMaxDate @@ -3449,10 +3449,10 @@ BEGIN -- saldos de la tabla prevision INSERT INTO bs.bancos_evolution(Fecha, Id_Banco, saldo) SELECT t.dated, sp.Id_Banco, SUM(Importe) - FROM vn.time t + FROM vn.time t JOIN vn2008.Saldos_Prevision sp ON sp.Fecha <= t.dated JOIN vn2008.Bancos b ON sp.Id_Banco = b.Id_Banco - JOIN vn.accountingType at2 ON at2.id = b.cash + JOIN vn.accountingType at2 ON at2.id = b.cash WHERE at2.code IN ('wireTransfer','fundingLine') AND t.dated BETWEEN vStartingDate AND vMaxDate GROUP BY t.dated, sp.Id_Banco @@ -3466,12 +3466,12 @@ BEGIN -- Deuda UPDATE bs.bancos_evolution be JOIN vn2008.Bancos b using(Id_Banco) - JOIN vn.accountingType at2 ON at2.id = b.cash + JOIN vn.accountingType at2 ON at2.id = b.cash SET be.deuda = IF(at2.code = 'fundingLine', be.saldo_aux, 0) , be.saldo = IF(at2.code = 'fundingLine', 0, be.saldo_aux) WHERE Fecha >= vStartingDate; - -- Liquidez + -- Liquidez update bs.bancos_evolution set liquidez = saldo - quilla + deuda WHERE Fecha >= vStartingDate; -- Disponibilidad update bs.bancos_evolution set `disponibilidad ajena` = - quilla + deuda WHERE Fecha >= vStartingDate; @@ -3494,14 +3494,14 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `campaignComparative`(vDateFrom DATE, vDateTo DATE) BEGIN - SELECT - workerName, - id, - name, - CAST(SUM(previousAmmount) AS DECIMAL(10, 0)) AS previousAmmount, - CAST(SUM(currentAmmount) AS DECIMAL(10, 0)) AS currentAmmount + SELECT + workerName, + id, + name, + CAST(SUM(previousAmmount) AS DECIMAL(10, 0)) AS previousAmmount, + CAST(SUM(currentAmmount) AS DECIMAL(10, 0)) AS currentAmmount FROM ( - (SELECT + (SELECT CONCAT(w.firstname, ' ', w.lastName) AS workerName, c.id, c.name, @@ -3510,11 +3510,11 @@ BEGIN FROM bs.ventas v INNER JOIN vn.`client` c ON v.Id_Cliente = c.id INNER JOIN vn.worker w ON c.salesPersonFk = w.id - WHERE v.fecha BETWEEN DATE_ADD(vDateFrom, INTERVAL - 1 YEAR) + WHERE v.fecha BETWEEN DATE_ADD(vDateFrom, INTERVAL - 1 YEAR) AND DATE_ADD(vDateTo, INTERVAL - 1 YEAR) GROUP BY w.id, v.Id_Cliente) UNION ALL - (SELECT + (SELECT CONCAT(w.firstname, ' ', w.lastName) AS workerName, c.id, c.name, @@ -3548,21 +3548,21 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `carteras_add`() -BEGIN -/** - * Inserta en @bs.carteras. - */ - DELETE FROM bs.carteras - WHERE Año >= YEAR(util.VN_CURDATE()) - 1; - - INSERT INTO bs.carteras(Año,Mes,CodigoTrabajador,Peso) - SELECT t.year AS Año, t.month AS Mes, w.code AS CodigoTrabajador, SUM(v.importe) AS Peso - FROM vn.time t - JOIN bs.ventas v on t.dated = v.fecha - JOIN vn.client c on c.id = v.Id_Cliente - JOIN vn.worker w ON w.id = c.salesPersonFk - WHERE t.year >= YEAR(util.VN_CURDATE()) - 1 - GROUP BY w.code, t.year , t.month; +BEGIN +/** + * Inserta en @bs.carteras. + */ + DELETE FROM bs.carteras + WHERE Año >= YEAR(util.VN_CURDATE()) - 1; + + INSERT INTO bs.carteras(Año,Mes,CodigoTrabajador,Peso) + SELECT t.year AS Año, t.month AS Mes, w.code AS CodigoTrabajador, SUM(v.importe) AS Peso + FROM vn.time t + JOIN bs.ventas v on t.dated = v.fecha + JOIN vn.client c on c.id = v.Id_Cliente + JOIN vn.worker w ON w.id = c.salesPersonFk + WHERE t.year >= YEAR(util.VN_CURDATE()) - 1 + GROUP BY w.code, t.year , t.month; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -3594,24 +3594,24 @@ BEGIN DELETE FROM bs.clientNewBorn WHERE lastShipped < vOneYearAgo; - + DELETE FROM ventas WHERE fecha < vFourYearsAgo; - + DELETE FROM payMethodClient WHERE dated < vOneYearAgo; DELETE FROM payMethodClientEvolution WHERE dated < vFourYearsAgo; - DELETE FROM bs.salesByclientSalesPerson + DELETE FROM bs.salesByclientSalesPerson WHERE dated < vFourYearsAgo; - - DELETE FROM bs.m3 + + DELETE FROM bs.m3 WHERE fecha < vTwoYearAgo; DELETE FROM salesByItemTypeDay - WHERE dated < vThreeYearAgo; + WHERE dated < vThreeYearAgo; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -3710,16 +3710,16 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `clientNewBorn_recalc`() BLOCK1: BEGIN DECLARE vClientFk INT; - DECLARE vShipped DATE; + DECLARE vShipped DATE; DECLARE vPreviousShipped DATE; - DECLARE vDone boolean; - DECLARE cur cursor for - - SELECT clientFk, firstShipped - FROM bs.clientNewBorn; - - DECLARE continue HANDLER FOR NOT FOUND SET vDone = TRUE; - SET vDone := FALSE; + DECLARE vDone boolean; + DECLARE cur cursor for + + SELECT clientFk, firstShipped + FROM bs.clientNewBorn; + + DECLARE continue HANDLER FOR NOT FOUND SET vDone = TRUE; + SET vDone := FALSE; DELETE FROM bs.clientNewBorn WHERE isModified = FALSE; @@ -3731,7 +3731,7 @@ BLOCK1: BEGIN WHERE t.shipped BETWEEN TIMESTAMPADD(YEAR, -1, util.VN_CURDATE()) AND util.VN_CURDATE() AND cb.isModified is null GROUP BY c.id; OPEN cur; - + LOOP1: LOOP SET vDone := FALSE; FETCH cur INTO vClientFk, vShipped; @@ -3742,37 +3742,37 @@ BLOCK1: BEGIN END IF; BLOCK2: BEGIN - DECLARE vCurrentShipped DATE; - DECLARE vDone2 boolean; + DECLARE vCurrentShipped DATE; + DECLARE vDone2 boolean; DECLARE cur2 CURSOR FOR - SELECT shipped - FROM vn.ticket + SELECT shipped + FROM vn.ticket WHERE clientFk = vClientFk AND shipped <= util.VN_CURDATE() ORDER BY shipped DESC; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone2 = TRUE; SET vDone2 := FALSE; OPEN cur2; - + SET vPreviousShipped := vShipped; LOOP2: LOOP SET vDone2 := FALSE; FETCH cur2 INTO vCurrentShipped; - + IF DATEDIFF(vPreviousShipped,vCurrentShipped) > 365 THEN - UPDATE bs.clientNewBorn - SET firstShipped = vPreviousShipped + UPDATE bs.clientNewBorn + SET firstShipped = vPreviousShipped WHERE clientFk= vClientFk; - + CLOSE cur2; - LEAVE LOOP2; + LEAVE LOOP2; END IF; - + SET vPreviousShipped := vCurrentShipped; IF vDone2 THEN - UPDATE bs.clientNewBorn - SET firstShipped = vCurrentShipped + UPDATE bs.clientNewBorn + SET firstShipped = vCurrentShipped WHERE clientFk= vClientFk; CLOSE cur2; LEAVE LOOP2; @@ -3782,14 +3782,14 @@ BLOCK1: BEGIN END BLOCK2; END LOOP LOOP1; - UPDATE bs.clientNewBorn cnb + UPDATE bs.clientNewBorn cnb LEFT JOIN (SELECT DISTINCT t.clientFk FROM vn.ticket t JOIN vn.productionConfig pc WHERE t.shipped BETWEEN util.VN_CURDATE() + INTERVAL -(`notBuyingMonths`) MONTH AND util.VN_CURDATE() + INTERVAL -(`pc`.`rookieDays`) DAY) notRookie ON notRookie.clientFk = cnb.clientFk - SET cnb.isRookie = ISNULL(notRookie.clientFk); - + SET cnb.isRookie = ISNULL(notRookie.clientFk); + END BLOCK1 ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -3810,16 +3810,16 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `comercialesCompleto`(IN vWorker INT BEGIN DECLARE vAYearAgoStarted DATE DEFAULT DATE_FORMAT(TIMESTAMPADD(YEAR, - 1, vDate), '%Y-%m-01'); DECLARE vAYearAgoEnded DATE DEFAULT TIMESTAMPADD(YEAR, - 1, LAST_DAY(vDate)); - + CALL vn.worker_GetHierarchy(vWorker); - + INSERT IGNORE INTO tmp.workerHierarchyList (workerFk) SELECT wd2.workerFk FROM vn.workerDepartment wd2 WHERE wd2.workerFk = vWorker; - + -- Falta que en algunos casos solo tenga en cuenta los tipos afectados. - SELECT + SELECT c.Id_Cliente id_cliente, c.Cliente cliente, cr.recobro * 100 tarifa, @@ -3844,7 +3844,7 @@ BEGIN FROM vn2008.Clientes c LEFT JOIN - (SELECT g.Id_Cliente, CAST( SUM(Importe) as DECIMAL(12,2)) AS Greuge + (SELECT g.Id_Cliente, CAST( SUM(Importe) as DECIMAL(12,2)) AS Greuge FROM vn2008.Greuges g JOIN vn.`client` c ON c.id = g.Id_Cliente LEFT JOIN vn.worker w ON c.salesPersonFk = w.id @@ -3866,14 +3866,14 @@ BEGIN WHERE v.fecha BETWEEN TIMESTAMPADD(YEAR, - 1, vDate) AND vDate GROUP BY v.Id_Cliente) c365 ON c365.Id_Cliente = c.Id_Cliente LEFT JOIN - (SELECT + (SELECT Id_Cliente, SUM(importe) consumo FROM bs.ventas v INNER JOIN vn2008.Clientes c USING (Id_Cliente) LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador WHERE - (c.Id_Trabajador = vWorker OR tr.boss = vWorker) + (c.Id_Trabajador = vWorker OR tr.boss = vWorker) AND (v.fecha BETWEEN TIMESTAMPADD(DAY, - DAY(vDate) + 1, vDate) AND TIMESTAMPADD(DAY, - 1, vDate)) GROUP BY Id_Cliente) mes_actual ON mes_actual.Id_Cliente = c.Id_Cliente LEFT JOIN @@ -3934,17 +3934,17 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `compradores_add`(IN vYear INT, IN v BEGIN /** * Sustituye los registros de "bs.compradores". - * + * * @param vYear: año ventas * @param vWeekFrom: semana desde * @param vWeekTo: semana hasta */ REPLACE bs.compradores - SELECT it.workerFk AS Id_Trabajador, vYear AS año, tm.week AS semana, SUM(importe) AS importe, 0 AS comision + SELECT it.workerFk AS Id_Trabajador, vYear AS año, tm.week AS semana, SUM(importe) AS importe, 0 AS comision FROM bs.ventas v JOIN vn.time tm ON tm.dated = v.fecha - JOIN vn.itemType it ON it.id = v.tipo_id - WHERE tm.year = vYear + JOIN vn.itemType it ON it.id = v.tipo_id + WHERE tm.year = vYear AND tm.week BETWEEN vWeekFrom AND vWeekTo AND it.categoryFk != 6 GROUP BY it.workerFk, tm.week; @@ -3970,22 +3970,22 @@ BEGIN DECLARE vYear INT; DECLARE vWeek INT; DECLARE done BOOL DEFAULT FALSE; - + DECLARE rs CURSOR FOR SELECT year, week FROM vn.time - WHERE dated <= util.VN_CURDATE() - AND year = vYear + WHERE dated <= util.VN_CURDATE() + AND year = vYear AND week >= vWeek; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - - SELECT MAX(año) INTO vYear + + SELECT MAX(año) INTO vYear FROM compradores; - + SELECT MAX(semana) INTO vWeek - FROM compradores - WHERE año = vYear; + FROM compradores + WHERE año = vYear; OPEN rs; @@ -3994,7 +3994,7 @@ BEGIN WHILE NOT done DO CALL compradores_add(vYear, vWeek, vWeek); - + FETCH rs INTO vYear, vWeek; END WHILE; @@ -4002,7 +4002,7 @@ BEGIN CLOSE rs; CALL compradores_evolution_add; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -4023,17 +4023,17 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `compradores_evolution_add`() BEGIN /** * Inserta en la tabla compradores_evolution las ventas acumuladas en los ultimos 365 dias - * + * */ DECLARE vDated DATE; DECLARE vCount INT DEFAULT 1; - SELECT MAX(fecha) + INTERVAL 1 DAY INTO vDated + SELECT MAX(fecha) + INTERVAL 1 DAY INTO vDated FROM compradores_evolution; IF vDated IS NULL THEN - - SELECT MIN(dated) INTO vDated + + SELECT MIN(dated) INTO vDated FROM sale; INSERT INTO compradores_evolution( @@ -4054,7 +4054,7 @@ BEGIN WHILE vDated < util.VN_CURDATE() DO SET vCount = vCount + 1; - + REPLACE compradores_evolution( Id_Trabajador, fecha, @@ -4066,18 +4066,18 @@ BEGIN SELECT Id_Trabajador, importe FROM compradores_evolution JOIN ( - SELECT DISTINCT it.workerFk - FROM vn.itemType it + SELECT DISTINCT it.workerFk + FROM vn.itemType it )sub2 ON sub2.workerFk = Id_Trabajador - WHERE fecha = vDated - INTERVAL 1 DAY + WHERE fecha = vDated - INTERVAL 1 DAY UNION ALL - SELECT it.workerFk, s.amount * IF(s.dated < vDated, -1, 1) + SELECT it.workerFk, s.amount * IF(s.dated < vDated, -1, 1) FROM sale s JOIN vn.itemType it ON it.id = s.typeFk JOIN vn.itemCategory ic ON ic.id = it.categoryFk WHERE s.dated IN (vDated, vDated - INTERVAL 1 YEAR) AND ic.merchandise - )sub + )sub GROUP BY Id_Trabajador; SET vDated = vDated + INTERVAL 1 DAY; @@ -4104,49 +4104,49 @@ BEGIN * Inserta en la tabla fondo_maniobra los saldos acumulados en los ultimos 365 dias */ DECLARE datFEC DATE DEFAULT '2015-01-01'; - - SELECT TIMESTAMPADD(DAY,1,MAX(fecha)) - INTO datFEC + + SELECT TIMESTAMPADD(DAY,1,MAX(fecha)) + INTO datFEC FROM bs.fondo_maniobra; - + WHILE datFEC < util.VN_CURDATE() DO - + IF DAY(datFEC) MOD 28 = 0 THEN -- esto solo sirve para no aburrirse mientras esperamos... SELECT datFEC; END IF; - + REPLACE bs.fondo_maniobra(Fecha, clientes_facturas, clientes_cobros,proveedores_facturas,proveedores_pagos, fondo) SELECT datFEC AS Fecha, Facturas, Cobros,Recibidas,Pagos, Facturas + Cobros + Recibidas + Pagos FROM ( SELECT SUM(io.amount) AS Facturas FROM vn.invoiceOut io - JOIN vn.client c ON io.clientFk = c.id + JOIN vn.client c ON io.clientFk = c.id WHERE c.isRelevant - AND io.companyFk <> 1381 + AND io.companyFk <> 1381 AND io.issued BETWEEN '2011-01-01' AND datFEC ) fac JOIN ( SELECT - SUM(r.amountPaid) AS Cobros - FROM vn.receipt r - JOIN vn.client c ON r.clientFk = c.id - WHERE c.isRelevant + FROM vn.receipt r + JOIN vn.client c ON r.clientFk = c.id + WHERE c.isRelevant AND r.companyFk <> 1381 AND r.payed BETWEEN '2011-01-01' AND datFEC ) cob JOIN ( SELECT - SUM(id.amount) AS Recibidas - FROM vn.invoiceIn ii - JOIN vn.invoiceInDueDay id ON ii.id = id.invoiceInFk + FROM vn.invoiceIn ii + JOIN vn.invoiceInDueDay id ON ii.id = id.invoiceInFk WHERE ii.companyFk <> 1381 AND ii.issued BETWEEN '2015-01-01' AND datFEC ) rec JOIN ( SELECT SUM(p.amount) AS Pagos - FROM vn.payment p - WHERE p.companyFk <>1381 + FROM vn.payment p + WHERE p.companyFk <>1381 AND p.received BETWEEN '2015-01-01' AND datFEC ) pag; - + UPDATE bs.fondo_maniobra JOIN ( SELECT AVG(fondo) AS media @@ -4154,7 +4154,7 @@ BEGIN WHERE fecha <= datFEC ) sub SET fondo_medio = media WHERE fecha = datFEC; - + SET datFEC = TIMESTAMPADD(DAY,1,datFEC); END WHILE; @@ -4178,7 +4178,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `fruitsEvolution`() BEGIN -select Id_Cliente, +select Id_Cliente, Cliente, count(semana) as semanas, (w.code IS NOT NULL) isWorker from ( select distinct v.Id_Cliente, c.name as Cliente, week(fecha, 3) as semana @@ -4219,40 +4219,40 @@ BEGIN -- Ventas totales del ultimo año UPDATE indicators - SET lastYearSales = + SET lastYearSales = (SELECT SUM(importe + recargo) FROM ventas v JOIN vn2008.empresa e ON e.id = v.empresa_id JOIN vn2008.empresa_grupo eg ON eg.empresa_grupo_id = e.empresa_grupo WHERE fecha BETWEEN oneYearBefore AND vDated AND eg.grupo = 'Verdnatura' - ) + ) WHERE updated = vDated; - + -- Greuge total acumulado UPDATE indicators - SET totalGreuge = + SET totalGreuge = (SELECT SUM(amount) FROM vn.greuge WHERE shipped <= vDated - ) + ) WHERE updated = vDated; -- Tasa de morosidad con respecto a las ventas del último mes UPDATE indicators - SET latePaymentRate = - (SELECT SUM(amount) - FROM bi.defaulters + SET latePaymentRate = + (SELECT SUM(amount) + FROM bi.defaulters WHERE date = vDated AND amount > 0) / - (SELECT SUM(importe + recargo) - FROM ventas + (SELECT SUM(importe + recargo) + FROM ventas WHERE fecha BETWEEN oneMonthBefore AND vDated) WHERE updated = vDated; -- Número de trabajadores activos UPDATE indicators - SET countEmployee = + SET countEmployee = (SELECT CAST(SUM(ct.hoursWeek) / 40 AS DECIMAL (10, 2)) FROM vn.business b JOIN vn.calendarType ct ON ct.id = b.calendarTypeFk @@ -4271,7 +4271,7 @@ BEGIN -- Número de clientes que han comprado en los últimos 30 dias UPDATE indicators - SET lastMonthActiveClients = + SET lastMonthActiveClients = (SELECT COUNT(DISTINCT t.clientFk) FROM vn.ticket t WHERE t.shipped BETWEEN oneMonthBefore AND vDated @@ -4280,9 +4280,9 @@ BEGIN -- Número de clientes que no han comprado en los últimos 30 dias, pero compraron en los 30 anteriores UPDATE indicators - SET lastMonthLostClients = + SET lastMonthLostClients = (SELECT COUNT(lm.clientFk) - FROM + FROM (SELECT DISTINCT t.clientFk FROM vn.ticket t WHERE t.shipped BETWEEN oneMonthBefore AND vDated @@ -4299,9 +4299,9 @@ BEGIN -- Número de clientes que han comprado en los últimos 30 dias, pero no compraron en los 30 anteriores UPDATE indicators - SET lastMonthNewClients = + SET lastMonthNewClients = (SELECT COUNT(cm.clientFk) - FROM + FROM (SELECT DISTINCT t.clientFk FROM vn.ticket t WHERE t.shipped BETWEEN oneMonthBefore AND vDated @@ -4327,7 +4327,7 @@ BEGIN -- Cálculo de las ventas agrupado por semanas SELECT week INTO vWeek - FROM vn.time + FROM vn.time WHERE dated = vDated; TRUNCATE salesByWeek; @@ -4341,12 +4341,12 @@ BEGIN -- Indicador Ventas semana actual UPDATE indicators i - JOIN salesByWeek s ON s.week= vWeek + JOIN salesByWeek s ON s.week= vWeek AND s.year = YEAR(vDated) SET i.thisWeekSales = s.sales WHERE updated = vDated; - -- Indicador ventas semana actual en el año pasado + -- Indicador ventas semana actual en el año pasado UPDATE indicators i JOIN salesByWeek s ON s.week = vWeek AND s.year = YEAR(vDated)-1 @@ -4377,15 +4377,15 @@ BEGIN SELECT IFNULL(TIMESTAMPADD(DAY,1,MAX(updated)), '2018-04-01') INTO vDated FROM bs.indicators; - + WHILE vDated < util.VN_CURDATE() DO - + CALL indicatorsUpdate(vDated); - + SELECT TIMESTAMPADD(DAY,1,MAX(updated)) INTO vDated FROM bs.indicators; - + END WHILE; END ;; @@ -4414,7 +4414,7 @@ BEGIN DECLARE vCalc INT; DECLARE vWarehouseFk INT; - DECLARE cWarehouses CURSOR FOR + DECLARE cWarehouses CURSOR FOR SELECT id FROM vn.warehouse WHERE isInventory; @@ -4427,13 +4427,13 @@ BEGIN read_loop: LOOP SET vDone = FALSE; FETCH cWarehouses INTO vWarehouseFk; - + IF vDone THEN LEAVE read_loop; END IF; - + CALL cache.visible_refresh(vCalc, FALSE, vWarehouseFk); - + CREATE OR REPLACE TEMPORARY TABLE tVisible SELECT itemFk, SUM(visible) totalVisible FROM vn.itemShelving ish @@ -4442,7 +4442,7 @@ BEGIN JOIN vn.sector sc ON sc.id = p.sectorFk WHERE sc.warehouseFk = vWarehouseFk GROUP BY itemFk; - + INSERT INTO inventoryDiscrepancyDetail( warehouseFk, itemFk, @@ -4514,15 +4514,15 @@ BEGIN DECLARE datSTART DATE; DECLARE datEND DATE; - + SELECT TIMESTAMPADD(WEEK, -1,MAX(fecha)) INTO datSTART FROM bs.m3; - + SET datEND = TIMESTAMPADD(DAY,-1,util.VN_CURDATE()); - - DELETE FROM bs.m3 + + DELETE FROM bs.m3 WHERE fecha >= datSTART; - + INSERT INTO bs.m3 (fecha, provinceFk, warehouseFk, m3, year, month, week, day, dayName, euros) SELECT v.fecha, a.provinceFk, t.warehouseFk, sum(s.quantity * ic.cm3delivery) / 1000000 AS m3, tm.year, tm.month, tm.week, tm.day, dayname(v.fecha), sum(importe) @@ -4565,51 +4565,51 @@ BEGIN DECLARE vManaBankId INT; DECLARE vManaGreugeTypeId INT; - SELECT id INTO vManaId + SELECT id INTO vManaId FROM vn.component WHERE code = 'mana'; - - SELECT id INTO vManaAutoId + + SELECT id INTO vManaAutoId FROM vn.component WHERE code = 'autoMana'; - + SELECT id INTO vClaimManaId FROM vn.component WHERE code = 'manaClaim'; - - SELECT id INTO vManaBankId + + SELECT id INTO vManaBankId FROM vn.bank WHERE code = 'mana'; - - SELECT id INTO vManaGreugeTypeId + + SELECT id INTO vManaGreugeTypeId FROM vn.greugeType WHERE code = 'mana'; SELECT IFNULL(MAX(dated), '2016-01-01') - INTO vFromDated + INTO vFromDated FROM vn.clientManaCache; - + DELETE FROM vn.clientManaCache WHERE dated = vFromDated; SELECT IFNULL(MAX(dated), '2016-01-01') - INTO vFromDated + INTO vFromDated FROM vn.clientManaCache; WHILE timestampadd(DAY,30,vFromDated) < util.VN_CURDATE() DO SELECT timestampadd(DAY,30,vFromDated), - timestampadd(DAY,-90,vFromDated) - INTO + timestampadd(DAY,-90,vFromDated) + INTO vToDated, vForDeleteDated; - + DELETE FROM vn.clientManaCache WHERE dated <= vForDeleteDated; INSERT INTO vn.clientManaCache(clientFk, mana, dated) - SELECT + SELECT Id_Cliente, cast(sum(mana) as decimal(10,2)) as mana, - vToDated as dated - FROM + vToDated as dated + FROM ( SELECT cs.Id_Cliente, Cantidad * Valor as mana FROM vn2008.Tickets t @@ -4617,20 +4617,20 @@ BEGIN JOIN vn2008.Movimientos m on m.Id_Ticket = t.Id_Ticket JOIN vn2008.Movimientos_componentes mc on mc.Id_Movimiento = m.Id_Movimiento WHERE Id_Componente IN (vManaAutoId, vManaId, vClaimManaId) - AND t.Fecha > vFromDated + AND t.Fecha > vFromDated AND date(t.Fecha) <= vToDated UNION ALL SELECT r.Id_Cliente, - Entregado FROM vn2008.Recibos r WHERE Id_Banco = vManaBankId - AND Fechacobro > vFromDated + AND Fechacobro > vFromDated AND Fechacobro <= vToDated - + UNION ALL SELECT g.Id_Cliente, g.Importe FROM vn2008.Greuges g WHERE Greuges_type_id = vManaGreugeTypeId - AND Fecha > vFromDated + AND Fecha > vFromDated AND Fecha <= vToDated UNION ALL SELECT clientFk, mana @@ -4641,7 +4641,7 @@ BEGIN HAVING Id_Cliente; SET vFromDated = vToDated; - + END WHILE; END ;; @@ -4662,22 +4662,22 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `manaSpellers_actualize`() BEGIN -/** - * Recalcula el valor del campo con el modificador de precio +/** + * Recalcula el valor del campo con el modificador de precio * para el componente de maná automático. */ - UPDATE vn.workerMana wm + UPDATE vn.workerMana wm JOIN ( - SELECT c.lastSalesPersonFk, + SELECT c.lastSalesPersonFk, FLOOR(SUM(s.amount) / 12) amount FROM salesByclientSalesPerson s JOIN vn.client c ON c.id = s.clientFk WHERE s.dated BETWEEN util.VN_CURDATE() - INTERVAL 1 YEAR AND util.VN_CURDATE() GROUP BY c.lastSalesPersonFk - )avgPortfolioWeight ON avgPortfolioWeight.lastSalesPersonFk = wm.workerFk + )avgPortfolioWeight ON avgPortfolioWeight.lastSalesPersonFk = wm.workerFk JOIN vn.salespersonConfig spc SET wm.pricesModifierRate = GREATEST( - spc.manaMinRate, + spc.manaMinRate, LEAST(spc.manaMaxRate, ROUND( - wm.amount / avgPortfolioWeight.amount))); END ;; DELIMITER ; @@ -4710,8 +4710,8 @@ BEGIN DECLARE vId INT; DECLARE rs CURSOR FOR - SELECT id, `schema`, `procedure` - FROM nightTask + SELECT id, `schema`, `procedure` + FROM nightTask WHERE finished <= util.VN_CURDATE() OR finished IS NULL ORDER BY `order`; @@ -4744,7 +4744,7 @@ BEGIN vError, vErrorCode ); - + IF vError IS NOT NULL THEN SET vNErrors = vNErrors + 1; @@ -4814,7 +4814,7 @@ BEGIN vError = MESSAGE_TEXT, vErrorCode = RETURNED_SQLSTATE; - CALL util.exec(CONCAT('CALL `', vSchema ,'`.`', vProcedure ,'`')); + CALL util.exec(CONCAT('CALL `', vSchema ,'`.`', vProcedure ,'`')); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -4833,22 +4833,22 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `payMethodClientAdd`() BEGIN - INSERT IGNORE INTO `bs`.`payMethodClient` (dated, payMethodFk, clientFk) + INSERT IGNORE INTO `bs`.`payMethodClient` (dated, payMethodFk, clientFk) SELECT util.VN_CURDATE(), c.payMethodFk, c.id - FROM vn.client c + FROM vn.client c JOIN vn.payMethod p ON c.payMethodFk = p.id; - + TRUNCATE `bs`.`payMethodClientEvolution` ; - + INSERT INTO `bs`.`payMethodClientEvolution` (dated, payMethodName, amountClient, amount, equalizationTax) - SELECT p.dated, pm.name, COUNT(p.clientFk), SUM(sub.importe) , SUM(sub.recargo) + SELECT p.dated, pm.name, COUNT(p.clientFk), SUM(sub.importe) , SUM(sub.recargo) FROM bs.payMethodClient p - JOIN (SELECT SUM(v.importe) AS importe, SUM(v.recargo) as recargo, v.fecha, v.Id_cliente + JOIN (SELECT SUM(v.importe) AS importe, SUM(v.recargo) as recargo, v.fecha, v.Id_cliente FROM bs.ventas v WHERE v.fecha>= (SELECT MIN(dated) FROM bs. payMethodClient) GROUP BY v.Id_cliente, v.fecha) sub ON sub.fecha = p.dated AND sub.Id_cliente = p.ClientFk JOIN vn.payMethod pm ON p.payMethodFk = pm.id - GROUP BY dated,payMethodFk; + GROUP BY dated,payMethodFk; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -4868,12 +4868,12 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `saleGraphic`(IN vItemFk INT, IN vTypeFk INT, IN vCategoryFk INT, IN vFromDate DATE, IN vToDate DATE, IN vProducerFk INT) BEGIN - + DECLARE vFromDateLastYear DATE; DECLARE vToDateLastYear DATE; DECLARE vFromDateTwoYearsAgo DATE; DECLARE vToDateTwoYearsAgo DATE; - + SET vItemFk = IFNULL(vItemFk,0); SET vTypeFk = IFNULL(vTypeFk, 0); SET vCategoryFk = IFNULL(vCategoryFk,0); @@ -4888,19 +4888,19 @@ BEGIN SELECT s.quantity, CAST(v.importe AS DECIMAL(10,0)) importe, v.fecha FROM bs.ventas v - JOIN vn.sale s ON s.id = v.Id_Movimiento - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.itemType it ON it.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk + JOIN vn.sale s ON s.id = v.Id_Movimiento + JOIN vn.item i ON i.id = s.itemFk + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk WHERE vItemFk IN (i.id, 0) AND vTypeFk IN (i.typeFk, 0) AND vCategoryFk IN (it.categoryFk, 0) AND vProducerFk IN (i.producerFk, 0) AND (v.fecha BETWEEN vFromDate AND vToDate OR v.fecha BETWEEN vFromDateLastYear AND vToDateLastYear - OR v.fecha BETWEEN vFromDateTwoYearsAgo AND vToDateTwoYearsAgo + OR v.fecha BETWEEN vFromDateTwoYearsAgo AND vToDateTwoYearsAgo ); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -4919,21 +4919,21 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `salePersonEvolutionAdd`(IN vDateStart DATETIME) BEGIN - DELETE FROM bs.salePersonEvolution + DELETE FROM bs.salePersonEvolution WHERE dated <= DATE_SUB(util.VN_CURDATE(), INTERVAL 1 YEAR); - - + + INSERT INTO bs.salePersonEvolution (dated, amount, equalizationTax, salesPersonFk) - SELECT fecha dated, - CAST(SUM(importe) AS DECIMAL(10,2) ) amount, + SELECT fecha dated, + CAST(SUM(importe) AS DECIMAL(10,2) ) amount, CAST(SUM(recargo) AS DECIMAL(10,2) ) equalizationTax , IFNULL(salesPersonFk,0) salesPersonFk FROM bs.ventas v - JOIN vn.client c ON v.Id_Cliente = c.id + JOIN vn.client c ON v.Id_Cliente = c.id JOIN vn.company co ON co.id = v.empresa_id WHERE co.code = "VNL" AND fecha >= vDateStart GROUP BY v.fecha,c.salesPersonFk - ORDER BY salesPersonFk,dated ASC; + ORDER BY salesPersonFk,dated ASC; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -4955,7 +4955,7 @@ BEGIN /** * Agrupa las ventas por cliente/comercial/fecha en la tabla bs.salesByclientSalesPerson * El asociación cliente/comercial/fecha, se mantiene correcta en el tiempo - * + * * @param vDatedFrom el cálculo se realizará desde la fecha introducida hasta ayer */ @@ -4963,17 +4963,17 @@ BEGIN SET vDatedFrom = util.VN_CURDATE() - INTERVAL 1 MONTH; END IF; - UPDATE salesByclientSalesPerson + UPDATE salesByclientSalesPerson SET amount = 0, equalizationTax = 0, amountNewBorn = 0 WHERE dated BETWEEN vDatedFrom AND util.yesterday(); - - INSERT INTO salesByclientSalesPerson( - dated, - salesPersonFk, - clientFk, - amount, + + INSERT INTO salesByclientSalesPerson( + dated, + salesPersonFk, + clientFk, + amount, equalizationTax) SELECT s.dated, c.salesPersonFk, @@ -4982,7 +4982,7 @@ BEGIN SUM(s.surcharge) FROM sale s JOIN vn.client c on s.clientFk = c.id - WHERE s.dated BETWEEN vDatedFrom AND util.yesterday() + WHERE s.dated BETWEEN vDatedFrom AND util.yesterday() GROUP BY s.dated, c.salesPersonFk, s.clientFk ON DUPLICATE KEY UPDATE amount= VALUES(amount), equalizationTax= VALUES(equalizationTax); @@ -5156,8 +5156,8 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `salesByItemTypeDay_addLauncher`() -BEGIN - CALL bs.salesByItemTypeDay_add(util.VN_CURDATE() - INTERVAL 30 DAY, util.VN_CURDATE()); +BEGIN + CALL bs.salesByItemTypeDay_add(util.VN_CURDATE() - INTERVAL 30 DAY, util.VN_CURDATE()); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -5177,35 +5177,35 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `salesPersonEvolution_add`() BEGIN /** - * Calcula los datos para los gráficos de evolución agrupado por salesPersonFk y día. + * Calcula los datos para los gráficos de evolución agrupado por salesPersonFk y día. * Recalcula automáticamente los 3 últimos meses para comprobar si hay algún cambio. */ DECLARE vDated DATE; DECLARE vCont INT DEFAULT 1; - SELECT MAX(dated) - INTERVAL 3 MONTH INTO vDated + SELECT MAX(dated) - INTERVAL 3 MONTH INTO vDated FROM salesPersonEvolution; - DELETE FROM salesPersonEvolution + DELETE FROM salesPersonEvolution WHERE dated >= vDated; IF ISNULL(vDated) THEN - SELECT MIN(dated) INTO vDated + SELECT MIN(dated) INTO vDated FROM salesByclientSalesPerson; - + INSERT INTO salesPersonEvolution( - salesPersonFk, - dated, - amount, - equalizationTax, + salesPersonFk, + dated, + amount, + equalizationTax, amountNewBorn ) - SELECT salesPersonFk, - dated, - amount, - equalizationTax, + SELECT salesPersonFk, + dated, + amount, + equalizationTax, amountNewBorn - FROM salesByclientSalesPerson + FROM salesByclientSalesPerson WHERE dated = vDated GROUP BY salesPersonFk; @@ -5213,21 +5213,21 @@ BEGIN END IF; WHILE vDated < util.VN_CURDATE() DO - + SET vCont = vCont + 1; REPLACE salesPersonEvolution(salesPersonFk, dated, amount) SELECT salesPersonFk, vDated, amount FROM(SELECT salesPersonFk, SUM(amount) amount FROM(SELECT salesPersonFk, amount - FROM salesPersonEvolution + FROM salesPersonEvolution WHERE dated = vDated - INTERVAL 1 DAY UNION ALL - SELECT salesPersonFk, amount - FROM salesByclientSalesPerson + SELECT salesPersonFk, amount + FROM salesByclientSalesPerson WHERE dated = vDated UNION ALL SELECT salesPersonFk, - amount - FROM salesByclientSalesPerson + FROM salesByclientSalesPerson WHERE dated = vDated - INTERVAL 1 YEAR )sub GROUP BY salesPersonFk @@ -5256,7 +5256,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `vendedores_add_launcher`() BEGIN CALL bs.salesByclientSalesPerson_add(util.VN_CURDATE()- INTERVAL 45 DAY); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -5280,7 +5280,7 @@ BEGIN /** * Añade las ventas que se realizaron entre * vStarted y vEnded -* +* * @param vStarted Fecha de inicio * @param vEnded Fecha de finalizacion * @@ -5288,7 +5288,7 @@ BEGIN DECLARE vStartingDate DATETIME; DECLARE vEndingDate DATETIME; - IF vStarted < TIMESTAMPADD(YEAR,-5,util.VN_CURDATE()) + IF vStarted < TIMESTAMPADD(YEAR,-5,util.VN_CURDATE()) OR vEnded < TIMESTAMPADD(YEAR,-5,util.VN_CURDATE()) THEN CALL util.throw('fechaDemasiadoAntigua'); END IF; @@ -5297,8 +5297,8 @@ BEGIN SET vStartingDate = vStarted ; SET vEndingDate = util.dayEnd(vStartingDate); - DELETE - FROM sale + DELETE + FROM sale WHERE dated BETWEEN vStartingDate AND vEnded; WHILE vEndingDate <= vEnded DO @@ -5319,28 +5319,28 @@ BEGIN JOIN vn.itemType it ON it.id = i.typeFk JOIN vn.itemCategory ic ON ic.id = it.categoryFk JOIN vn.ticket t ON t.id = s.ticketFk - JOIN vn.address a ON a.id = t.addressFk + JOIN vn.address a ON a.id = t.addressFk JOIN vn.client cl ON cl.id = a.clientFk WHERE t.shipped BETWEEN vStartingDate AND vEndingDate AND s.quantity <> 0 AND s.discount <> 100 - AND ic.merchandise + AND ic.merchandise GROUP BY sc.saleFk HAVING IFNULL(importe,0) <> 0 OR IFNULL(recargo,0) <> 0; UPDATE sale s JOIN ( - SELECT s.id, + SELECT s.id, SUM(s.quantity * sc.value ) margen, s.quantity * s.price * (100 - s.discount ) / 100 pvp FROM vn.sale s - JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.ticket t ON t.id = s.ticketFk JOIN vn.saleComponent sc ON sc.saleFk = s.id - JOIN vn.component c ON c.id = sc.componentFk - JOIN vn.componentType ct ON ct.id = c.typeFk + JOIN vn.component c ON c.id = sc.componentFk + JOIN vn.componentType ct ON ct.id = c.typeFk WHERE t.shipped BETWEEN vStartingDate AND vEndingDate AND ct.isMargin = TRUE - GROUP BY s.id) sub ON sub.id = s.saleFk + GROUP BY s.id) sub ON sub.id = s.saleFk SET s.margin = sub.margen + s.amount + s.surcharge - sub.pvp; SET vStartingDate = TIMESTAMPADD(DAY,1, vStartingDate); @@ -5368,7 +5368,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `ventas_add_launcher`() BEGIN /** * Añade las ventas a la tabla bs.sale que se realizaron desde hace un mes hasta hoy - * + * */ DECLARE vCurDate DATE DEFAULT util.VN_CURDATE(); @@ -5392,7 +5392,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ventas_contables_add`(IN vYear INT, IN vMonth INT) BEGIN - + /** * Reemplaza las ventas contables del último año. * Es el origen de datos para el balance de Entradas @@ -5404,8 +5404,8 @@ BEGIN DECLARE TIPO_PATRIMONIAL INT DEFAULT 188; - DELETE FROM bs.ventas_contables - WHERE year = vYear + DELETE FROM bs.ventas_contables + WHERE year = vYear AND month = vMonth; DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; @@ -5416,7 +5416,7 @@ BEGIN FROM vn2008.Tickets t JOIN vn2008.Facturas f ON f.Id_Factura = t.Factura WHERE year(f.Fecha) = vYear - AND month(f.Fecha) = vMonth; + AND month(f.Fecha) = vMonth; INSERT INTO bs.ventas_contables(year , month @@ -5426,7 +5426,7 @@ BEGIN , tipo_id , empresa_id , gasto) - + SELECT vYear , vMonth , round(sum(Cantidad * Preu * (100 - m.Descuento)/100)) @@ -5438,13 +5438,13 @@ BEGIN , tp.reino_id , a.tipo_id , t.empresa_id - , 7000000000 + , 7000000000 + IF(e.empresa_grupo = e2.empresa_grupo ,1 ,IF(e2.empresa_grupo,2,0) - ) * 1000000 + ) * 1000000 + tp.reino_id * 10000 as Gasto - FROM vn2008.Movimientos m + FROM vn2008.Movimientos m JOIN vn2008.Tickets t on t.Id_Ticket = m.Id_Ticket JOIN vn2008.Consignatarios cs on cs.Id_Consigna = t.Id_Consigna JOIN vn2008.Clientes c on c.Id_Cliente = cs.Id_Cliente @@ -5458,7 +5458,7 @@ BEGIN AND m.Descuento <> 100 AND a.tipo_id != TIPO_PATRIMONIAL GROUP BY grupo, reino_id, tipo_id, empresa_id, Gasto; - + INSERT INTO bs.ventas_contables(year , month , venta @@ -5477,17 +5477,17 @@ BEGIN ) as grupo , NULL , NULL - , t.companyFk + , t.companyFk , 7050000000 - FROM vn.ticketService ts + FROM vn.ticketService ts JOIN vn.ticket t ON ts.ticketFk = t.id - JOIN vn.address a on a.id = t.addressFk - JOIN vn.client cl on cl.id = a.clientFk + JOIN vn.address a on a.id = t.addressFk + JOIN vn.client cl on cl.id = a.clientFk JOIN tmp.ticket_list tt on tt.Id_Ticket = t.id - JOIN vn.company c on c.id = t.companyFk + JOIN vn.company c on c.id = t.companyFk LEFT JOIN vn.company c2 on c2.clientFk = cl.id - GROUP BY grupo, t.companyFk ; - + GROUP BY grupo, t.companyFk ; + DROP TEMPORARY TABLE tmp.ticket_list; END ;; DELIMITER ; @@ -5507,13 +5507,13 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ventas_contables_add_launcher`() BEGIN - + /** * Reemplaza las ventas contables del último año. * Es el origen de datos para el balance de Entradas * **/ - + CALL bs.ventas_contables_add(YEAR(TIMESTAMPADD(MONTH,-1,util.VN_CURDATE())), MONTH(TIMESTAMPADD(MONTH,-1,util.VN_CURDATE()))); END ;; @@ -5534,12 +5534,12 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ventas_contables_por_cliente`(IN vYear INT, IN vMonth INT) BEGIN - + /** * Muestra las ventas (€) de cada cliente * dependiendo del año */ - + DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; CREATE TEMPORARY TABLE tmp.ticket_list @@ -5548,8 +5548,8 @@ BEGIN FROM vn2008.Tickets t JOIN vn2008.Facturas f ON f.Id_Factura = t.Factura WHERE year(f.Fecha) = vYear - AND month(f.Fecha) = vMonth; - + AND month(f.Fecha) = vMonth; + SELECT vYear Año, vMonth Mes, t.Id_Cliente, @@ -5559,7 +5559,7 @@ BEGIN IF(e2.empresa_grupo,2,0)) AS grupo, t.empresa_id empresa - FROM vn2008.Movimientos m + FROM vn2008.Movimientos m JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket JOIN vn2008.Consignatarios cs ON cs.Id_Consigna = t.Id_Consigna JOIN vn2008.Clientes c ON c.Id_Cliente = cs.Id_Cliente @@ -5573,9 +5573,9 @@ BEGIN AND m.Descuento <> 100 AND a.tipo_id != 188 GROUP BY t.Id_Cliente, grupo,t.empresa_id; - + DROP TEMPORARY TABLE tmp.ticket_list; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -5594,7 +5594,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `vivosMuertos`() BEGIN - + /** * Devuelve el número de clientes nuevos y muertos, * dependiendo de la fecha actual. @@ -5605,9 +5605,9 @@ BEGIN SET @datSTART = TIMESTAMPADD(YEAR,-2,util.VN_CURDATE()); SET @datEND = TIMESTAMPADD(DAY,-DAY(util.VN_CURDATE()),util.VN_CURDATE()); - + DROP TEMPORARY TABLE IF EXISTS tmp.VivosMuertos; - + CREATE TEMPORARY TABLE tmp.VivosMuertos SELECT c.Id_Cliente, tm.yearMonth, f.Compra, 0 as Nuevo, 0 as Muerto FROM vn2008.Clientes c @@ -5623,10 +5623,10 @@ BEGIN WHERE Fecha BETWEEN @datSTART AND @datEND) f ON f.yearMonth = tm.yearMonth AND f.Id_Cliente = c.Id_Cliente; - + UPDATE tmp.VivosMuertos vm JOIN - (SELECT MIN(tm.yearMonth) firstMonth, f.Id_Cliente + (SELECT MIN(tm.yearMonth) firstMonth, f.Id_Cliente FROM vn2008.Facturas f JOIN vn2008.time tm ON tm.date = f.Fecha WHERE Fecha BETWEEN @datSTART AND @datEND @@ -5634,9 +5634,9 @@ BEGIN AND fm.Id_Cliente = vm.Id_Cliente SET Nuevo = 1; - + SELECT max(yearMonth) INTO @lastYearMonth FROM tmp.VivosMuertos; - + UPDATE tmp.VivosMuertos vm JOIN ( SELECT MAX(tm.yearMonth) firstMonth, f.Id_Cliente @@ -5677,23 +5677,23 @@ BEGIN INTO vWeek, vYear FROM vn.time WHERE dated = util.VN_CURDATE(); - + REPLACE bs.waste SELECT *, 100 * mermas / total as porcentaje FROM ( - SELECT buyer, - year, + SELECT buyer, + year, week, family, itemFk, itemTypeFk, - floor(sum(value)) as total, + floor(sum(value)) as total, floor(sum(IF(clientTypeFk = 'loses', value, 0))) as mermas - FROM vn.saleValue + FROM vn.saleValue where year = vYear and week = vWeek - + GROUP BY family, itemFk - + ) sub ORDER BY mermas DESC; END ;; @@ -5725,56 +5725,56 @@ BEGIN DECLARE vDateEnded DATE; DECLARE vCursor CURSOR FOR - SELECT util.firstDayOfMonth(t.dated), LAST_DAY(t.dated) + SELECT util.firstDayOfMonth(t.dated), LAST_DAY(t.dated) FROM vn.time t WHERE t.dated BETWEEN vDateStarted AND vDateEnded - GROUP BY year,month; + GROUP BY year,month; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + IF DAY(util.VN_CURDATE()) = 21 THEN - + SELECT util.firstDayOfMonth(DATE_SUB(util.VN_CURDATE(), INTERVAL 12 MONTH)), LAST_DAY(DATE_SUB(util.VN_CURDATE(), INTERVAL 1 MONTH)) - INTO vDateStarted, + INTO vDateStarted, vDateEnded; - - DELETE FROM workerLabourDataByMonth + + DELETE FROM workerLabourDataByMonth WHERE CONCAT(`year`, '-',`month`, '-01') BETWEEN vDateStarted AND vDateEnded; OPEN vCursor; l: LOOP SET vDone = FALSE; - + FETCH vCursor INTO vFristDay, vLastDay; - + IF vDone THEN LEAVE l; END IF; - + -- Altas periodo - INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent) - SELECT 'hiring', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent) + INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent) + SELECT 'hiring', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent) FROM vn.business b JOIN vn.workCenter wc ON wc.id = b.workCenterFk JOIN vn.worker w ON w.id = b.workerFk LEFT JOIN vn.workerBusinessType wbt ON wbt.id = b.workerBusinessTypeFk LEFT JOIN (SELECT b.id, b.workerFk FROM vn.business b - LEFT JOIN (SELECT ended, workerFk FROM vn.business) wl + LEFT JOIN (SELECT ended, workerFk FROM vn.business) wl ON wl.ended = DATE_SUB(b.started, INTERVAL 1 DAY) AND wl.workerFk = b.workerFk - WHERE b.started BETWEEN vFristDay AND vLastDay AND wl.ended + WHERE b.started BETWEEN vFristDay AND vLastDay AND wl.ended )sub ON sub.workerFk = b.workerFk WHERE wc.payrollCenterFk IS NOT NULL AND b.workCenterFk IS NOT NULL AND b.started BETWEEN vFristDay AND vLastDay AND sub.workerFk IS NULL - AND NOT w.isFreelance; + AND NOT w.isFreelance; -- Bajas periodo - INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent) - SELECT 'layoffs', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent) + INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent) + SELECT 'layoffs', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent) FROM vn.business b JOIN vn.worker w ON w.id = b.workerFk JOIN vn.workCenter wc ON wc.id = b.workCenterFk @@ -5785,12 +5785,12 @@ BEGIN AND b.ended BETWEEN vFristDay AND vLastDay AND wl.started IS NULL AND NOT w.isFreelance; - + -- Anterior al periodo SET vLastDay = LAST_DAY(DATE_SUB(vFristDay, INTERVAL 1 DAY)); - INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent) - SELECT 'staff', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent) + INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent) + SELECT 'staff', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent) FROM vn.business b JOIN vn.worker w ON w.id = b.workerFk JOIN vn.workCenter wc ON wc.id = b.workCenterFk @@ -5800,8 +5800,8 @@ BEGIN AND NOT w.isFreelance; -- Discapacidad - INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent) - SELECT 'disabled', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent) + INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent) + SELECT 'disabled', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent) FROM vn.business b JOIN vn.worker w ON w.id = b.workerFk JOIN vn.workCenter wc ON wc.id = b.workCenterFk @@ -6210,7 +6210,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `addressFriendship_Update`() BEGIN - REPLACE cache.addressFriendship + REPLACE cache.addressFriendship SELECT addressFk1, addressFk2, count(*) friendship FROM ( @@ -6221,7 +6221,7 @@ BEGIN AND t2.shipped >= TIMESTAMPADD(MONTH,-3,util.VN_CURDATE()) AND t.addressFk != t2.addressFk) sub GROUP BY addressFk1, addressFk2; - + REPLACE cache.zoneAgencyFriendship SELECT r.agencyModeFk, t.zoneFk, count(*) friendship FROM vn.route r @@ -6395,12 +6395,12 @@ BEGIN FROM available a LEFT JOIN tCalc c ON c.id = a.calc_id WHERE c.id IS NULL; - + DELETE a FROM availableNoRaids a LEFT JOIN tCalc c ON c.id = a.calc_id WHERE c.id IS NULL; - + DROP TEMPORARY TABLE tCalc; END ;; DELIMITER ; @@ -6579,27 +6579,27 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `cache_calc_end`(IN `v_calc` INT) -BEGIN - DECLARE v_cache_name VARCHAR(255); - DECLARE v_params VARCHAR(255); - - -- Libera el bloqueo y actualiza la fecha de ultimo refresco. - - UPDATE cache_calc cc JOIN cache c ON c.id = cc.cache_id - SET - cc.last_refresh = NOW(), - cc.expires = ADDTIME(NOW(), c.lifetime), - cc.connection_id = NULL - WHERE cc.id = v_calc; - - SELECT c.name, ca.params INTO v_cache_name, v_params - FROM cache c - JOIN cache_calc ca ON c.id = ca.cache_id - WHERE ca.id = v_calc; - - IF v_cache_name IS NOT NULL THEN - DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, ''))); - END IF; +BEGIN + DECLARE v_cache_name VARCHAR(255); + DECLARE v_params VARCHAR(255); + + -- Libera el bloqueo y actualiza la fecha de ultimo refresco. + + UPDATE cache_calc cc JOIN cache c ON c.id = cc.cache_id + SET + cc.last_refresh = NOW(), + cc.expires = ADDTIME(NOW(), c.lifetime), + cc.connection_id = NULL + WHERE cc.id = v_calc; + + SELECT c.name, ca.params INTO v_cache_name, v_params + FROM cache c + JOIN cache_calc ca ON c.id = ca.cache_id + WHERE ca.id = v_calc; + + IF v_cache_name IS NOT NULL THEN + DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, ''))); + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -6617,89 +6617,89 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `cache_calc_start`(OUT `v_calc` INT, INOUT `v_refresh` INT, IN `v_cache_name` VARCHAR(50), IN `v_params` VARCHAR(100)) -proc: BEGIN - DECLARE v_valid BOOL; - DECLARE v_lock_id VARCHAR(100); - DECLARE v_cache_id INT; - DECLARE v_expires DATETIME; - DECLARE v_clean_time DATETIME; - DECLARE vLastRefresh DATETIME; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - IF v_lock_id IS NOT NULL THEN - DO RELEASE_LOCK(v_lock_id); - END IF; - - RESIGNAL; - END; - - SET v_params = IFNULL(v_params, ''); - - -- Si el servidor se ha reiniciado invalida todos los calculos. - - SELECT COUNT(*) > 0 INTO v_valid FROM cache_valid; - - IF !v_valid - THEN - DELETE FROM cache_calc; - INSERT INTO cache_valid (valid) VALUES (TRUE); - END IF; - - -- Obtiene un bloqueo exclusivo para que no haya problemas de concurrencia. - - SET v_lock_id = CONCAT_WS('/', v_cache_name, v_params); - - IF !GET_LOCK(v_lock_id, 30) - THEN - SET v_calc = NULL; - SET v_refresh = FALSE; - LEAVE proc; - END IF; - - -- Comprueba si el calculo solicitado existe y esta actualizado. - - SELECT c.id, ca.id, ca.expires, ca.last_refresh - INTO v_cache_id, v_calc, v_expires, vLastRefresh - FROM cache c - LEFT JOIN cache_calc ca - ON ca.cache_id = c.id AND ca.params = v_params COLLATE 'utf8_general_ci' - WHERE c.name = v_cache_name COLLATE 'utf8_general_ci'; - - -- Si existe una calculo valido libera el bloqueo y devuelve su identificador. - - IF !v_refresh AND NOW() < v_expires AND vLastRefresh >= CURDATE() - THEN - DO RELEASE_LOCK(v_lock_id); - SET v_refresh = FALSE; - LEAVE proc; - END IF; - - -- Si el calculo no existe le crea una entrada en la tabla de calculos. - - IF v_calc IS NULL - THEN - INSERT INTO cache_calc SET - cache_id = v_cache_id, - cacheName = v_cache_name, - params = v_params, - last_refresh = NULL, - expires = NULL, - connection_id = CONNECTION_ID(); - - SET v_calc = LAST_INSERT_ID(); - ELSE - UPDATE cache_calc - SET - last_refresh = NULL, - expires = NULL, - connection_id = CONNECTION_ID() - WHERE id = v_calc; - END IF; - - -- Si se debe recalcular mantiene el bloqueo y devuelve su identificador. - - SET v_refresh = TRUE; +proc: BEGIN + DECLARE v_valid BOOL; + DECLARE v_lock_id VARCHAR(100); + DECLARE v_cache_id INT; + DECLARE v_expires DATETIME; + DECLARE v_clean_time DATETIME; + DECLARE vLastRefresh DATETIME; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + IF v_lock_id IS NOT NULL THEN + DO RELEASE_LOCK(v_lock_id); + END IF; + + RESIGNAL; + END; + + SET v_params = IFNULL(v_params, ''); + + -- Si el servidor se ha reiniciado invalida todos los calculos. + + SELECT COUNT(*) > 0 INTO v_valid FROM cache_valid; + + IF !v_valid + THEN + DELETE FROM cache_calc; + INSERT INTO cache_valid (valid) VALUES (TRUE); + END IF; + + -- Obtiene un bloqueo exclusivo para que no haya problemas de concurrencia. + + SET v_lock_id = CONCAT_WS('/', v_cache_name, v_params); + + IF !GET_LOCK(v_lock_id, 30) + THEN + SET v_calc = NULL; + SET v_refresh = FALSE; + LEAVE proc; + END IF; + + -- Comprueba si el calculo solicitado existe y esta actualizado. + + SELECT c.id, ca.id, ca.expires, ca.last_refresh + INTO v_cache_id, v_calc, v_expires, vLastRefresh + FROM cache c + LEFT JOIN cache_calc ca + ON ca.cache_id = c.id AND ca.params = v_params COLLATE 'utf8_general_ci' + WHERE c.name = v_cache_name COLLATE 'utf8_general_ci'; + + -- Si existe una calculo valido libera el bloqueo y devuelve su identificador. + + IF !v_refresh AND NOW() < v_expires AND vLastRefresh >= CURDATE() + THEN + DO RELEASE_LOCK(v_lock_id); + SET v_refresh = FALSE; + LEAVE proc; + END IF; + + -- Si el calculo no existe le crea una entrada en la tabla de calculos. + + IF v_calc IS NULL + THEN + INSERT INTO cache_calc SET + cache_id = v_cache_id, + cacheName = v_cache_name, + params = v_params, + last_refresh = NULL, + expires = NULL, + connection_id = CONNECTION_ID(); + + SET v_calc = LAST_INSERT_ID(); + ELSE + UPDATE cache_calc + SET + last_refresh = NULL, + expires = NULL, + connection_id = CONNECTION_ID() + WHERE id = v_calc; + END IF; + + -- Si se debe recalcular mantiene el bloqueo y devuelve su identificador. + + SET v_refresh = TRUE; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -6729,7 +6729,7 @@ proc: BEGIN FROM cache c JOIN cache_calc ca ON c.id = ca.cache_id WHERE ca.id = v_calc; - + DELETE FROM cache_calc WHERE id = v_calc; IF v_cache_name IS NOT NULL THEN @@ -6825,7 +6825,7 @@ DECLARE rs CURSOR FOR DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - SET myTime = HOUR(util.VN_NOW()) + MINUTE(util.VN_NOW()) / 60; + SET myTime = HOUR(util.VN_NOW()) + MINUTE(util.VN_NOW()) / 60; OPEN rs; @@ -6834,23 +6834,23 @@ DECLARE rs CURSOR FOR WHILE NOT done DO SET resto = IF(inicioProd < rsDeparture, rsDeparture - inicioProd,0); - + SET inicioProd = rsDeparture - rsHoras; - + IF inicioProd - resto < myTime THEN - + SET done = TRUE; - + ELSE - + SET departureLimit = rsDeparture; - + FETCH rs INTO rsDeparture, rsHoras , rsInicio; - + -- SELECT rsDeparture, rsHoras , rsInicio; - + END IF; - + END WHILE; SET departureLimit = IFNULL(departureLimit,24); @@ -6895,7 +6895,7 @@ proc: BEGIN DECLARE started DATE; DECLARE ended DATE; DECLARE vLastRefresh DATE; - + DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN CALL cache_calc_unlock (vCalc); @@ -6945,14 +6945,14 @@ proc: BEGIN DECLARE datEQ DATETIME; DECLARE timDIF TIME; DECLARE v_calc INT; - + CALL cache_calc_start (v_calc, v_refresh, 'prod_graphic', wh_id); - + IF !v_refresh THEN LEAVE proc; END IF; - + CALL vn2008.production_control_source(wh_id, 0); DELETE FROM prod_graphic_source; @@ -6970,8 +6970,8 @@ proc: BEGIN WHERE Fecha = util.VN_CURDATE() GROUP BY wh_id, graphCategory ; - - + + CALL cache_calc_end (v_calc); END ;; DELIMITER ; @@ -6992,7 +6992,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `stock_refresh`(v_refresh BOOL) proc: BEGIN /** - * Crea o actualiza la cache con el disponible hasta el día de + * Crea o actualiza la cache con el disponible hasta el día de * ayer. Esta cache es usada como base para otros procedimientos * como el cáculo del visible o del ATP. * @@ -7018,21 +7018,21 @@ proc: BEGIN SET v_date_inv = (SELECT inventoried FROM vn.config LIMIT 1); SET vCURDATE = util.VN_CURDATE(); - + DELETE FROM stock; - + INSERT INTO stock (item_id, warehouse_id, amount) SELECT item_id, warehouse_id, SUM(amount) amount FROM ( - SELECT itemFk AS item_id, warehouseFk AS warehouse_id, quantity AS amount + SELECT itemFk AS item_id, warehouseFk AS warehouse_id, quantity AS amount FROM vn.itemTicketOut WHERE shipped >= v_date_inv AND shipped < vCURDATE UNION ALL - SELECT itemFk ASitem_id, warehouseInFk AS warehouse_id, quantity AS amount + SELECT itemFk ASitem_id, warehouseInFk AS warehouse_id, quantity AS amount FROM vn.itemEntryIn WHERE landed >= v_date_inv AND landed < vCURDATE AND isVirtualStock is FALSE UNION ALL - SELECT itemFk AS item_id ,warehouseOutFk AS warehouse_id, quantity AS amount + SELECT itemFk AS item_id ,warehouseOutFk AS warehouse_id, quantity AS amount FROM vn.itemEntryOut WHERE shipped >= v_date_inv AND shipped < vCURDATE ) t @@ -7062,12 +7062,12 @@ BEGIN (INDEX (id)) ENGINE = MEMORY SELECT id FROM cache_calc; - + DELETE v FROM visible v LEFT JOIN tCalc c ON c.id = v.calc_id WHERE c.id IS NULL; - + DROP TEMPORARY TABLE tCalc; END ;; DELIMITER ; @@ -7991,9 +7991,9 @@ DELIMITER ;; BEGIN DECLARE nextID INT; - + SELECT 1 + MAX(id) INTO nextID FROM putOrder ; - + SET NEW.orderTradelineItemID = nextID; END */;; @@ -8015,36 +8015,36 @@ DELIMITER ;; BEFORE UPDATE ON `putOrder` FOR EACH ROW BEGIN - + DECLARE vError VARCHAR(100) DEFAULT 'Orderregel niet meer teruggevonden op basis van de orderps'; DECLARE vVmpIdError INT DEFAULT 7; DECLARE vVmpFk INT; DECLARE vSupplyResponseNumberOfUnits INT; - - SELECT sr.vmpID INTO vVmpFk - FROM edi.supplyResponse sr + + SELECT sr.vmpID INTO vVmpFk + FROM edi.supplyResponse sr WHERE sr.id = NEW.supplyResponseID; - - IF NEW.OrderStatus = 3 - AND NOT (NEW.OrderStatus <=> OLD.OrderStatus) - AND NEW.error = vError - AND vVmpFk = vVmpIdError - - THEN - + + IF NEW.OrderStatus = 3 + AND NOT (NEW.OrderStatus <=> OLD.OrderStatus) + AND NEW.error = vError + AND vVmpFk = vVmpIdError + + THEN + SET NEW.OrderStatus = 2; - + END IF; - + -- Error de disponible menor de lo solicitado IF NEW.error LIKE 'error2602%' THEN - + SELECT NumberOfUnits INTO vSupplyResponseNumberOfUnits - FROM edi.supplyResponse sr + FROM edi.supplyResponse sr WHERE sr.ID = NEW.supplyResponseID; - + SET NEW.error = CONCAT('(',vSupplyResponseNumberOfUnits,') ', NEW.error); - + END IF; END */;; DELIMITER ; @@ -8071,16 +8071,16 @@ BEGIN DECLARE vIsEktSender BOOLEAN; IF NEW.OrderStatus = vOrderStatusDenied AND NOT (NEW.OrderStatus <=> OLD.OrderStatus) THEN - + SELECT s.id INTO vSaleFk - FROM vn.sale s + FROM vn.sale s JOIN vn.ticket t ON s.ticketFk = t.id JOIN vn.item i ON i.id = s.itemFk JOIN deliveryInformation di ON di.ID = NEW.deliveryInformationID WHERE t.clientFk = NEW.EndUserPartyGLN AND t.shipped >= util.VN_CURDATE() AND i.supplyResponseFk = NEW.supplyResponseID LIMIT 1; - + UPDATE vn.sale s JOIN vn.ticket t ON s.ticketFk = t.id JOIN vn.item i ON i.id = s.itemFk @@ -8088,7 +8088,7 @@ BEGIN SET s.quantity = 0 WHERE t.clientFk = NEW.EndUserPartyGLN AND t.shipped >= util.VN_CURDATE() AND i.supplyResponseFk = NEW.supplyResponseID; - + INSERT INTO vn.mail (sender, `subject`, body) SELECT IF(u.id IS NOT NULL AND c.email IS NOT NULL, c.email, @@ -8100,26 +8100,26 @@ BEGIN IF (u.id IS NOT NULL AND c.email IS NOT NULL , CONCAT('https://shop.verdnatura.es/#!form=ecomerce%2Fticket&ticket=', t.id ), CONCAT('https://salix.verdnatura.es/#!/ticket/', t.id ,'/summary'))) - FROM vn.sale s + FROM vn.sale s JOIN vn.ticket t ON t.id = s.ticketFk JOIN vn.`client` c ON c.id = t.clientFk LEFT JOIN account.user u ON u.id= c.salesPersonFk AND u.name IN ('ruben', 'ismaelalcolea') WHERE s.id = vSaleFk; - + END IF; IF NEW.OrderStatus = vOrderStatusOK AND NOT (NEW.OrderStatus <=> OLD.OrderStatus) THEN - SELECT v.isEktSender INTO vIsEktSender + SELECT v.isEktSender INTO vIsEktSender FROM edi.VMPSettings v - JOIN edi.supplyResponse sr ON sr.vmpID = v.VMPID + JOIN edi.supplyResponse sr ON sr.vmpID = v.VMPID WHERE sr.id = NEW.supplyResponseID; - + IF NOT vIsEktSender THEN CALL edi.ekt_add(NEW.id); - + END IF; IF NEW.barcode THEN @@ -8128,7 +8128,7 @@ BEGIN SELECT i.id, NEW.barcode FROM vn.item i WHERE i.supplyResponseFk = NEW.supplyResponseID; - + END IF; END IF; @@ -8326,8 +8326,8 @@ BEGIN UPDATE vn.buy b JOIN vn.entry e ON e.id = b.entryFk - JOIN vn.travel tr ON tr.id = e.travelFk - JOIN vn.agencyMode am ON am.id = tr.agencyModeFk + JOIN vn.travel tr ON tr.id = e.travelFk + JOIN vn.agencyMode am ON am.id = tr.agencyModeFk JOIN vn.item i ON i.id = b.itemFk JOIN edi.supplyResponse sr ON i.supplyResponseFk = sr.ID SET b.quantity = NEW.NumberOfItemsPerCask * NEW.NumberOfUnits, @@ -8336,7 +8336,7 @@ BEGIN AND am.name = 'LOGIFLORA' AND e.isRaid AND tr.landed >= util.VN_CURDATE(); - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -8478,7 +8478,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `imageName`(vPictureReference VARCHAR(255)) RETURNS varchar(255) CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci DETERMINISTIC BEGIN - + SET vPictureReference = REPLACE(vPictureReference,'.',''); SET vPictureReference = REPLACE(vPictureReference,'/',''); @@ -8490,7 +8490,7 @@ BEGIN SET vPictureReference = REPLACE(vPictureReference,'?',''); SET vPictureReference = REPLACE(vPictureReference,'=',''); - + RETURN vPictureReference; END ;; @@ -8546,27 +8546,27 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `deliveryInformation_Delete`() BEGIN - + DECLARE vID INT; DECLARE vGap INT DEFAULT 100; DECLARE vTope INT; - - SELECT MIN(ID), MAX(ID) + + SELECT MIN(ID), MAX(ID) INTO vID, vTope FROM edi.deliveryInformation; - WHILE vID <= vTope DO - + WHILE vID <= vTope DO + SET vID = vID + vGap; - - DELETE - FROM edi.deliveryInformation + + DELETE + FROM edi.deliveryInformation WHERE ID < vID AND EarliestDespatchDateTime IS NULL; - + END WHILE; - - + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -8585,15 +8585,15 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ekt_add`(vPutOrderFk INT) BEGIN - + /** * Añade ekt para las ordenes de compra de proveedores que no envian el ekt por email - * + * * @param vPutOrderFk PutOrderId de donde coger los datos **/ - - INSERT INTO edi.ekt(entryYear, - deliveryNumber, + + INSERT INTO edi.ekt(entryYear, + deliveryNumber, fec, hor, item, @@ -8633,17 +8633,17 @@ BEGIN i.value10 s6, p.id putOrderFk, sr.Item_ArticleCode, - sr.vmpID + sr.vmpID FROM edi.putOrder p - JOIN edi.supplyResponse sr ON sr.ID = p.supplyResponseID - JOIN edi.deliveryInformation di ON di.id = p.deliveryInformationID - JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID - JOIN vn.item i ON i.supplyResponseFk = sr.ID - JOIN vn.origin o ON o.id = i.originFk + JOIN edi.supplyResponse sr ON sr.ID = p.supplyResponseID + JOIN edi.deliveryInformation di ON di.id = p.deliveryInformationID + JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID + JOIN vn.item i ON i.supplyResponseFk = sr.ID + JOIN vn.origin o ON o.id = i.originFk WHERE p.id = vPutOrderFk; - + CALL edi.ekt_load(LAST_INSERT_ID()); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -8662,7 +8662,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ekt_load`(IN `vSelf` INT) proc:BEGIN - + DECLARE vRef INT; DECLARE vBuy INT; DECLARE vItem INT; @@ -8687,51 +8687,51 @@ proc:BEGIN FROM edi.ekt e LEFT JOIN edi.item i ON e.ref = i.id LEFT JOIN edi.putOrder po ON po.id = e.putOrderFk - LEFT JOIN vn.item i2 ON i2.supplyResponseFk = po.supplyResponseID + LEFT JOIN vn.item i2 ON i2.supplyResponseFk = po.supplyResponseID LEFT JOIN vn.ektEntryAssign eea ON eea.sub = e.sub LEFT JOIN edi.item_groupToOffer igto ON igto.group_code = i.group_id WHERE e.id = vSelf LIMIT 1; - + IF NOT vHasItemGroup THEN - + CALL vn.mail_insert('logistica@verdnatura.es', 'nocontestar@verdnatura.es', 'Nuevo grupo en Floramondo', vDescription); - + CALL vn.mail_insert('pako@verdnatura.es', 'nocontestar@verdnatura.es', CONCAT('Nuevo grupo en Floramondo: ', vDescription), vDescription); - + LEAVE proc; - + END IF; - + -- Asigna la entrada SELECT vn.ekt_getEntry(vSelf) INTO vEntryFk; - + -- Inserta el cubo si no existe IF vPackage = 800 THEN - + SET vHasToChangePackagingFk = TRUE; - + IF vItem THEN - + SELECT vn.item_getPackage(vItem) INTO vPackage ; - + ELSE - + SET vPackage = 8000 + vQty; INSERT IGNORE INTO vn.packaging(id, width, `depth`) SELECT vPackage, vc.ccLength / vQty, vc.ccWidth FROM vn.volumeConfig vc; - + END IF; - + ELSE - + INSERT IGNORE INTO vn2008.Cubos (Id_Cubo, X, Y, Z) SELECT bucket_id, ROUND(x_size/10), ROUND(y_size/10), ROUND(z_size/10) FROM bucket WHERE bucket_id = vPackage; - + IF ROW_COUNT() > 0 THEN INSERT INTO vn2008.mail SET @@ -8740,27 +8740,27 @@ proc:BEGIN `to` = 'ekt@verdnatura.es'; END IF; END IF; - + -- Si es una compra de Logiflora obtiene el articulo IF vPutOrderFk THEN - + SELECT i.id INTO vItem FROM edi.putOrder po JOIN vn.item i ON i.supplyResponseFk = po.supplyResponseID WHERE po.id = vPutOrderFk LIMIT 1; - + END IF; INSERT IGNORE INTO item_track SET item_id = vRef; - + IF IFNULL(vItem,0) = 0 THEN - + -- Intenta obtener el artículo en base a los atributos holandeses - + SELECT b.id, IFNULL(b.itemOriginalFk ,b.itemFk) INTO vBuy, vItem - FROM edi.ekt e + FROM edi.ekt e JOIN edi.item_track t ON t.item_id = e.ref LEFT JOIN edi.ekt l ON l.ref = e.ref LEFT JOIN vn.buy b ON b.ektFk = l.id @@ -8781,19 +8781,19 @@ proc:BEGIN AND IF(t.pro, l.pro = e.pro, TRUE) AND IF(t.package, l.package = e.package, TRUE) AND IF(t.item, l.item = e.item, TRUE) - AND i.isFloramondo = vIsFloramondoDirect - ORDER BY l.now DESC, b.id ASC + AND i.isFloramondo = vIsFloramondoDirect + ORDER BY l.now DESC, b.id ASC LIMIT 1; END IF; - + -- Si no encuentra el articulo lo crea en el caso de las compras directas en Floramondo IF ISNULL(vItem) AND vIsFloramondoDirect THEN - + CALL edi.item_getNewByEkt(vSelf, vItem); - + END IF; - + INSERT INTO vn.buy ( entryFk @@ -8816,15 +8816,15 @@ proc:BEGIN ,e.qty stickers ,@pac := IFNULL(i.stemMultiplier, 1) * e.pac / @t packing ,IFNULL(b.`grouping`, e.pac) - ,@pac * e.qty + ,@pac * e.qty ,vForceToPacking ,IF(vHasToChangePackagingFk OR ISNULL(b.packageFk), vPackage, b.packageFk) ,(IFNULL(i.weightByPiece,0) * @pac)/1000 - FROM edi.ekt e + FROM edi.ekt e LEFT JOIN vn.buy b ON b.id = vBuy LEFT JOIN vn.item i ON i.id = b.itemFk LEFT JOIN vn.supplier s ON e.pro = s.id - JOIN vn2008.config cfg + JOIN vn2008.config cfg WHERE e.id = vSelf LIMIT 1; @@ -8832,36 +8832,36 @@ proc:BEGIN CREATE TEMPORARY TABLE tmp.buyRecalc SELECT buy.id - FROM vn.buy + FROM vn.buy WHERE ektFk = vSelf; CALL vn.buy_recalcPrices(); -- Si es una compra de Logiflora hay que informar la tabla vn.saleBuy IF vPutOrderFk THEN - + REPLACE vn.saleBuy(saleFk, buyFk, workerFk) SELECT po.saleFk, b.id, account.myUser_getId() FROM edi.putOrder po JOIN vn.buy b ON b.ektFk = vSelf WHERE po.id = vPutOrderFk; - + END IF; - -- Si es una compra directa en Floramondo hay que añadirlo al ticket + -- Si es una compra directa en Floramondo hay que añadirlo al ticket IF vIsFloramondoDirect THEN SELECT t.id INTO vTicketFk FROM vn.ticket t - JOIN vn.ektEntryAssign eea - ON eea.addressFk = t.addressFk + JOIN vn.ektEntryAssign eea + ON eea.addressFk = t.addressFk AND t.warehouseFk = eea.warehouseInFk - JOIN edi.ekt e - ON e.sub = eea.sub + JOIN edi.ekt e + ON e.sub = eea.sub AND e.id = vSelf WHERE e.fec = t.shipped LIMIT 1; - + IF ISNULL(vTicketFk) THEN INSERT INTO vn.ticket ( @@ -8889,8 +8889,8 @@ proc:BEGIN z.id, z.price, z.bonus - FROM edi.ekt e - JOIN vn.ektEntryAssign eea ON eea.sub = e.sub + FROM edi.ekt e + JOIN vn.ektEntryAssign eea ON eea.sub = e.sub JOIN vn.address a ON a.id = eea.addressFk JOIN vn.company c ON c.code = 'VNL' JOIN vn.`zone` z ON z.code = 'FLORAMONDO' @@ -8898,11 +8898,11 @@ proc:BEGIN LIMIT 1; SET vTicketFk = LAST_INSERT_ID(); - + INSERT INTO vn.ticketLog - SET originFk = vTicketFk, - userFk = account.myUser_getId(), - `action` = 'insert', + SET originFk = vTicketFk, + userFk = account.myUser_getId(), + `action` = 'insert', description = CONCAT('EktLoad ha creado el ticket:', ' ', vTicketFk); END IF; @@ -8912,9 +8912,9 @@ proc:BEGIN FROM edi.ekt e JOIN edi.floraHollandConfig fhc WHERE e.id = vSelf; - + SELECT LAST_INSERT_ID() INTO vSaleFk; - + REPLACE vn.saleBuy(saleFk, buyFk, workerFk) SELECT vSaleFk, b.id, account.myUser_getId() FROM vn.buy b @@ -8925,9 +8925,9 @@ proc:BEGIN FROM edi.ekt e JOIN vn.component c ON c.code = 'purchaseValue' WHERE e.id = vSelf; - + INSERT INTO vn.saleComponent(saleFk, componentFk, value) - SELECT vSaleFk, c.id, e.pri * fhc.floramondoMargin + SELECT vSaleFk, c.id, e.pri * fhc.floramondoMargin FROM edi.ekt e JOIN edi.floraHollandConfig fhc JOIN vn.component c ON c.code = 'margin' @@ -9068,7 +9068,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `ekt_scan`(vBarcode VARCHAR(512)) BEGIN /** * Busca transaciones a partir de un código de barras, las marca como escaneadas - * y las devuelve. + * y las devuelve. * Ver https://wiki.verdnatura.es/index.php/Ekt#Algoritmos_de_lectura * * @param vBarcode Código de compra de una etiqueta de subasta @@ -9107,19 +9107,19 @@ BEGIN ENGINE = MEMORY SELECT id ektFk FROM ekt LIMIT 0; - CASE + CASE WHEN LENGTH(vBarcode) <= vFloridayBarcodeLength THEN INSERT INTO tmp.ekt - SELECT id + SELECT id FROM edi.ektRecent e WHERE e.cps = vBarcode OR e.batchNumber = vBarcode; WHEN LENGTH(vBarcode) = vFloramondoBarcodeLength THEN INSERT INTO tmp.ekt - SELECT e.id + SELECT e.id FROM edi.ektRecent e - WHERE e.pro = MID(vBarcode,2,6) + WHERE e.pro = MID(vBarcode,2,6) AND CAST(e.ptd AS SIGNED) = MID(vBarcode,8,5); ELSE @@ -9134,7 +9134,7 @@ BEGIN -- Clásico de subasta -- Trade standard -- Trade que construye como la subasta - -- Trade como el anterior pero sin trade code + -- Trade como el anterior pero sin trade code INSERT INTO tmp.ekt SELECT id FROM ekt @@ -9155,9 +9155,9 @@ BEGIN -- BatchNumber largo IF NOT vIsFound THEN INSERT INTO tmp.ekt - SELECT id + SELECT id FROM edi.ektRecent e - WHERE e.batchNumber + WHERE e.batchNumber = LEFT(vBarcode,vUsefulAuctionLeftSegmentLength) AND e.batchNumber > 0; @@ -9167,7 +9167,7 @@ BEGIN -- Order Number IF NOT vIsFound THEN INSERT INTO tmp.ekt - SELECT id + SELECT id FROM edi.ektRecent e WHERE e.putOrderFk = vBarcode; @@ -9177,7 +9177,7 @@ BEGIN -- deliveryNumber incrustado IF NOT vIsFound THEN INSERT INTO tmp.ekt - SELECT id + SELECT id FROM edi.ektRecent e WHERE e.deliveryNumber = MID(vBarcode, 4, 13) @@ -9188,7 +9188,7 @@ BEGIN END CASE; IF vIsFound THEN - UPDATE ekt e + UPDATE ekt e JOIN tmp.ekt t ON t.ektFk = e.id SET e.scanned = TRUE; END IF; @@ -9209,524 +9209,524 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `floramondo_offerRefresh`() -proc: BEGIN - DECLARE vLanded DATETIME; - DECLARE vDone INT DEFAULT FALSE; - DECLARE vFreeId INT; - DECLARE vSupplyResponseFk INT; - DECLARE vLastInserted DATETIME; - DECLARE vIsAuctionDay BOOLEAN; - DECLARE vMaxNewItems INT DEFAULT 10000; - DECLARE vStartingTime DATETIME; - DECLARE vAalsmeerMarketPlaceID VARCHAR(13) DEFAULT '8713783439043'; - DECLARE vDayRange INT; - - DECLARE cur1 CURSOR FOR - SELECT id - FROM edi.item_free; - - DECLARE cur2 CURSOR FOR - SELECT srId - FROM itemToInsert; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - DECLARE EXIT HANDLER FOR SQLSTATE '45000' - BEGIN - ROLLBACK; - RESIGNAL; - END; - - DECLARE CONTINUE HANDLER FOR SQLEXCEPTION - BEGIN - DO RELEASE_LOCK('edi.floramondo_offerRefresh'); - SET @isTriggerDisabled = FALSE; - RESIGNAL; - END; - - IF 'test' = (SELECT environment FROM util.config) THEN - LEAVE proc; - END IF; - - IF !GET_LOCK('edi.floramondo_offerRefresh', 0) THEN - LEAVE proc; - END IF; - - SELECT dayRange INTO vDayRange - FROM offerRefreshConfig; - - IF vDayRange IS NULL THEN - CALL util.throw("Variable vDayRange not declared"); - END IF; - - SET vStartingTime = util.VN_NOW(); - - TRUNCATE edi.offerList; - - INSERT INTO edi.offerList(supplier, total) - SELECT v.name, COUNT(DISTINCT sr.ID) total - FROM edi.supplyResponse sr - JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID - WHERE sr.NumberOfUnits > 0 - AND sr.EmbalageCode != 999 - GROUP BY sr.vmpID; - - UPDATE edi.offerList o - JOIN (SELECT v.name, COUNT(*) total - FROM edi.supplyOffer sr - JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID - GROUP BY sr.vmpID) sub ON o.supplier = sub.name - SET o.`filter` = sub.total; - - -- Elimina de la lista de items libres aquellos que ya existen - DELETE itf.* - FROM edi.item_free itf - JOIN vn.item i ON i.id = itf.id; - - CREATE OR REPLACE TEMPORARY TABLE tmp - (INDEX (`Item_ArticleCode`)) - ENGINE = MEMORY - SELECT t.* - FROM ( - SELECT * - FROM edi.supplyOffer - ORDER BY (MarketPlaceID = vAalsmeerMarketPlaceID) DESC, - NumberOfUnits DESC LIMIT 10000000000000000000) t - GROUP BY t.srId; - - CREATE OR REPLACE TEMPORARY TABLE edi.offer (INDEX (`srID`), INDEX (`EmbalageCode`), - INDEX (`ef1`), INDEX (`ef2`), INDEX (`ef3`), INDEX (`ef4`),INDEX (`ef5`), INDEX (`ef6`), - INDEX (`s1Value`), INDEX (`s2Value`), INDEX (`s3Value`), INDEX (`s4Value`),INDEX (`s5Value`), INDEX (`s6Value`)) - ENGINE = MEMORY - SELECT so.*, - ev1.type_description s1Value, - ev2.type_description s2Value, - ev3.type_description s3Value, - ev4.type_description s4Value, - ev5.type_description s5Value, - ev6.type_description s6Value, - eif1.feature ef1, - eif2.feature ef2, - eif3.feature ef3, - eif4.feature ef4, - eif5.feature ef5, - eif6.feature ef6 - FROM tmp so - LEFT JOIN edi.item_feature eif1 ON eif1.item_id = so.Item_ArticleCode - AND eif1.presentation_order = 1 - AND eif1.expiry_date IS NULL - LEFT JOIN edi.item_feature eif2 ON eif2.item_id = so.Item_ArticleCode - AND eif2.presentation_order = 2 - AND eif2.expiry_date IS NULL - LEFT JOIN edi.item_feature eif3 ON eif3.item_id = so.Item_ArticleCode - AND eif3.presentation_order = 3 - AND eif3.expiry_date IS NULL - LEFT JOIN edi.item_feature eif4 ON eif4.item_id = so.Item_ArticleCode - AND eif4.presentation_order = 4 - AND eif4.expiry_date IS NULL - LEFT JOIN edi.item_feature eif5 ON eif5.item_id = so.Item_ArticleCode - AND eif5.presentation_order = 5 - AND eif5.expiry_date IS NULL - LEFT JOIN edi.item_feature eif6 ON eif6.item_id = so.Item_ArticleCode - AND eif6.presentation_order = 6 - AND eif6.expiry_date IS NULL - LEFT JOIN edi.`value` ev1 ON ev1.type_id = eif1.feature - AND so.s1 = ev1.type_value - LEFT JOIN edi.`value` ev2 ON ev2.type_id = eif2.feature - AND so.s2 = ev2.type_value - LEFT JOIN edi.`value` ev3 ON ev3.type_id = eif3.feature - AND so.s3 = ev3.type_value - LEFT JOIN edi.`value` ev4 ON ev4.type_id = eif4.feature - AND so.s4 = ev4.type_value - LEFT JOIN edi.`value` ev5 ON ev5.type_id = eif5.feature - AND so.s5 = ev5.type_value - LEFT JOIN edi.`value` ev6 ON ev6.type_id = eif6.feature - AND so.s6 = ev6.type_value - ORDER BY Price; - - DROP TEMPORARY TABLE tmp; - - DELETE o - FROM edi.offer o - LEFT JOIN vn.tag t1 ON t1.ediTypeFk = o.ef1 AND t1.overwrite = 'size' - LEFT JOIN vn.tag t2 ON t2.ediTypeFk = o.ef2 AND t2.overwrite = 'size' - LEFT JOIN vn.tag t3 ON t3.ediTypeFk = o.ef3 AND t3.overwrite = 'size' - LEFT JOIN vn.tag t4 ON t4.ediTypeFk = o.ef4 AND t4.overwrite = 'size' - LEFT JOIN vn.tag t5 ON t5.ediTypeFk = o.ef5 AND t5.overwrite = 'size' - LEFT JOIN vn.tag t6 ON t6.ediTypeFk = o.ef6 AND t6.overwrite = 'size' - JOIN vn.floramondoConfig fc ON TRUE - WHERE (t1.id IS NOT NULL AND CONVERT(s1Value, UNSIGNED) > fc.itemMaxSize) - OR (t2.id IS NOT NULL AND CONVERT(s2Value, UNSIGNED) > fc.itemMaxSize) - OR (t3.id IS NOT NULL AND CONVERT(s3Value, UNSIGNED) > fc.itemMaxSize) - OR (t4.id IS NOT NULL AND CONVERT(s4Value, UNSIGNED) > fc.itemMaxSize) - OR (t5.id IS NOT NULL AND CONVERT(s5Value, UNSIGNED) > fc.itemMaxSize) - OR (t6.id IS NOT NULL AND CONVERT(s6Value, UNSIGNED) > fc.itemMaxSize); - - START TRANSACTION; - - -- Actualizamos el campo supplyResponseFk para aquellos articulos que ya estan creados y reutilizamos - UPDATE IGNORE edi.offer o - JOIN vn.item i - ON i.name = o.product_name - AND i.subname <=> o.company_name - AND i.value5 <=> o.s1Value - AND i.value6 <=> o.s2Value - AND i.value7 <=> o.s3Value - AND i.value8 <=> o.s4Value - AND i.value9 <=> o.s5Value - AND i.value10 <=> o.s6Value - AND i.NumberOfItemsPerCask <=> o.NumberOfItemsPerCask - AND i.EmbalageCode <=> o.EmbalageCode - AND i.quality <=> o.Quality - JOIN vn.itemType it ON it.id = i.typeFk - LEFT JOIN vn.sale s ON s.itemFk = i.id - LEFT JOIN vn.ticket t ON t.id = s.ticketFk - AND t.shipped > (util.VN_CURDATE() - INTERVAL 1 WEEK) - LEFT JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk - LEFT JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID - LEFT JOIN edi.putOrder po ON po.supplyResponseID = i.supplyResponseFk - AND po.OrderTradeLineDateTime > (util.VN_CURDATE() - INTERVAL 1 WEEK) - SET i.supplyResponseFk = o.srID - WHERE (sr.ID IS NULL - OR sr.NumberOfUnits = 0 - OR di.LatestOrderDateTime < util.VN_NOW() - OR di.ID IS NULL) - AND it.isInventory - AND t.id IS NULL - AND po.id IS NULL; - - CREATE OR REPLACE TEMPORARY TABLE itemToInsert - ENGINE = MEMORY - SELECT o.*, CAST(NULL AS DECIMAL(6,0)) itemFk - FROM edi.offer o - LEFT JOIN vn.item i ON i.supplyResponseFk = o.srId - WHERE i.id IS NULL - LIMIT vMaxNewItems; - - -- Reciclado de nº de item - OPEN cur1; - OPEN cur2; - - read_loop: LOOP - - FETCH cur2 INTO vSupplyResponseFk; - FETCH cur1 INTO vFreeId; - - IF vDone THEN - LEAVE read_loop; - END IF; - - UPDATE itemToInsert - SET itemFk = vFreeId - WHERE srId = vSupplyResponseFk; - - END LOOP; - - CLOSE cur1; - CLOSE cur2; - - -- Insertamos todos los items en Articles de la oferta - INSERT INTO vn.item(id, - `name`, - longName, - subName, - expenceFk, - typeFk, - intrastatFk, - originFk, - supplyResponseFk, - numberOfItemsPerCask, - embalageCode, - quality, - isFloramondo) - SELECT iti.itemFk, - iti.product_name, - iti.product_name, - iti.company_name, - iti.expenseFk, - iti.itemTypeFk, - iti.intrastatFk, - iti.originFk, - iti.`srId`, - iti.NumberOfItemsPerCask, - iti.EmbalageCode, - iti.Quality, - TRUE - FROM itemToInsert iti; - - -- Inserta la foto de los articulos nuevos (prioridad alta) - INSERT IGNORE INTO vn.itemImageQueue(itemFk, url) - SELECT i.id, PictureReference - FROM itemToInsert ii - JOIN vn.item i ON i.supplyResponseFk = ii.srId - WHERE PictureReference IS NOT NULL - AND i.image IS NULL; - - INSERT INTO edi.`log`(tableName, fieldName,fieldValue) - SELECT 'itemImageQueue','NumImagenesPtes', COUNT(*) - FROM vn.itemImageQueue - WHERE attempts = 0; - - -- Inserta si se añadiesen tags nuevos - INSERT IGNORE INTO vn.tag (name, ediTypeFk) - SELECT description, type_id FROM edi.type; - - -- Desabilita el trigger para recalcular los tags al final - SET @isTriggerDisabled = TRUE; - - -- Inserta los tags sólo en los articulos nuevos - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , ii.product_name, 1 - FROM itemToInsert ii - JOIN vn.tag t ON t.`name` = 'Producto' - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT ii.product_name IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , ii.Quality, 3 - FROM itemToInsert ii - JOIN vn.tag t ON t.`name` = 'Calidad' - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT ii.Quality IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , ii.company_name, 4 - FROM itemToInsert ii - JOIN vn.tag t ON t.`name` = 'Productor' - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT ii.company_name IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s1Value, 5 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef1 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s1Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s2Value, 6 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef2 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s2Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s3Value, 7 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef3 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s3Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s4Value, 8 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef4 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s4Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s5Value, 9 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef5 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s5Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s6Value, 10 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef6 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s6Value IS NULL; - - INSERT IGNORE INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id, IFNULL(ink.name, ik.color), 11 - FROM itemToInsert ii - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - JOIN vn.tag t ON t.`name` = 'Color' - LEFT JOIN edi.feature f ON f.item_id = ii.Item_ArticleCode - LEFT JOIN edi.`type` tp ON tp.type_id = f.feature_type_id - AND tp.`description` = 'Hoofdkleur 1' - LEFT JOIN vn.ink ON ink.dutchCode = f.feature_value - LEFT JOIN vn.itemInk ik ON ik.longName = i.longName - WHERE ink.name IS NOT NULL - OR ik.color IS NOT NULL; - - CREATE OR REPLACE TABLE tmp.item - (PRIMARY KEY (id)) - SELECT i.id FROM vn.item i - JOIN itemToInsert ii ON i.supplyResponseFk = ii.`srId`; - - CALL vn.item_refreshTags(); - - DROP TABLE tmp.item; - - SELECT MIN(LatestDeliveryDateTime) INTO vLanded - FROM edi.supplyResponse sr - JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID - JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID - JOIN vn.floramondoConfig fc - WHERE mp.isLatestOrderDateTimeRelevant - AND di.LatestOrderDateTime > IF( - fc.MaxLatestOrderHour > HOUR(util.VN_NOW()), - util.VN_CURDATE(), - util.VN_CURDATE() + INTERVAL 1 DAY); - - UPDATE vn.floramondoConfig - SET nextLanded = vLanded - WHERE vLanded IS NOT NULL; - - -- Elimina la oferta obsoleta - UPDATE vn.buy b - JOIN vn.entry e ON e.id = b.entryFk - JOIN vn.travel tr ON tr.id = e.travelFk - JOIN vn.agencyMode am ON am.id = tr.agencyModeFk - JOIN vn.item i ON i.id = b.itemFk - LEFT JOIN edi.supplyResponse sr ON i.supplyResponseFk = sr.ID - LEFT JOIN edi.deliveryInformation di ON di.ID = b.deliveryFk - SET b.quantity = 0 - WHERE (IFNULL(di.LatestOrderDateTime,util.VN_NOW()) <= util.VN_NOW() - OR i.supplyResponseFk IS NULL - OR sr.NumberOfUnits = 0) - AND am.name = 'LOGIFLORA' - AND e.isRaid; - - -- Localiza las entradas de cada almacen - UPDATE edi.warehouseFloramondo - SET entryFk = vn.entry_getForLogiflora(vLanded + INTERVAL travellingDays DAY, warehouseFk); - - IF vLanded IS NOT NULL THEN - -- Actualiza la oferta existente - UPDATE vn.buy b - JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk - JOIN vn.item i ON i.id = b.itemFk - JOIN edi.offer o ON i.supplyResponseFk = o.`srId` - SET b.quantity = o.NumberOfUnits * o.NumberOfItemsPerCask, - b.buyingValue = o.price - WHERE (b.quantity <> o.NumberOfUnits * o.NumberOfItemsPerCask - OR b.buyingValue <> o.price); - - -- Inserta el resto - SET vLastInserted := util.VN_NOW(); - - -- Inserta la oferta - INSERT INTO vn.buy ( - entryFk, - itemFk, - quantity, - buyingValue, - stickers, - packing, - `grouping`, - groupingMode, - packageFk, - deliveryFk) - SELECT wf.entryFk, - i.id, - o.NumberOfUnits * o.NumberOfItemsPerCask quantity, - o.Price, - o.NumberOfUnits etiquetas, - o.NumberOfItemsPerCask packing, - GREATEST(1, IFNULL(o.MinimumQuantity,0)) * o.NumberOfItemsPerCask `grouping`, - 2, -- Obliga al Packing - o.embalageCode, - o.diId - FROM edi.offer o - JOIN vn.item i ON i.supplyResponseFk = o.srId - JOIN edi.warehouseFloramondo wf - JOIN vn.packaging p ON p.id - LIKE o.embalageCode - LEFT JOIN vn.buy b ON b.itemFk = i.id - AND b.entryFk = wf.entryFk - WHERE b.id IS NULL; -- Quitar esta linea y mirar de crear los packages a tiempo REAL - - INSERT INTO vn.itemCost( - itemFk, - warehouseFk, - cm3, - cm3delivery) - SELECT b.itemFk, - wf.warehouseFk, - @cm3 := vn.buy_getUnitVolume(b.id), - IFNULL((vc.standardFlowerBox * 1000) / i.packingOut, @cm3) - FROM warehouseFloramondo wf - JOIN vn.volumeConfig vc - JOIN vn.buy b ON b.entryFk = wf.entryFk - JOIN vn.item i ON i.id = b.itemFk - LEFT JOIN vn.itemCost ic ON ic.itemFk = b.itemFk - AND ic.warehouseFk = wf.warehouseFk - WHERE (ic.cm3 IS NULL OR ic.cm3 = 0) - ON DUPLICATE KEY UPDATE cm3 = @cm3, cm3delivery = IFNULL((vc.standardFlowerBox * 1000) / i.packingOut, @cm3); - - CREATE OR REPLACE TEMPORARY TABLE tmp.buyRecalc - SELECT b.id - FROM vn.buy b - JOIN warehouseFloramondo wf ON wf.entryFk = b.entryFk - WHERE b.created >= vLastInserted; - - CALL vn.buy_recalcPrices(); - - UPDATE edi.offerList o - JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total - FROM vn.buy b - JOIN vn.item i ON i.id = b.itemFk - JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk - JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID - JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk - JOIN vn.warehouse w ON w.id = wf.warehouseFk - WHERE w.name = 'VNH' - AND b.quantity > 0 - GROUP BY sr.vmpID) sub ON o.supplier = sub.name - SET o.vnh = sub.total; - - UPDATE edi.offerList o - JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total - FROM vn.buy b - JOIN vn.item i ON i.id = b.itemFk - JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk - JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID - JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk - JOIN vn.warehouse w ON w.id = wf.warehouseFk - WHERE w.name = 'ALGEMESI' - AND b.quantity > 0 - GROUP BY sr.vmpID) sub ON o.supplier = sub.name - SET o.algemesi = sub.total; - END IF; - - DROP TEMPORARY TABLE - edi.offer, - itemToInsert; - - SET @isTriggerDisabled = FALSE; - - COMMIT; - - -- Esto habria que pasarlo a procesos programados o trabajar con tags y dejar las familias - UPDATE vn.item i - SET typeFk = 121 - WHERE i.longName LIKE 'Rosa Garden %' - AND typeFk = 17; - - UPDATE vn.item i - SET typeFk = 156 - WHERE i.longName LIKE 'Rosa ec %' - AND typeFk = 17; - - -- Refresca las fotos de los items existentes que mostramos (prioridad baja) - INSERT IGNORE INTO vn.itemImageQueue(itemFk, url, priority) - SELECT i.id, sr.PictureReference, 100 - FROM edi.supplyResponse sr - JOIN vn.item i ON i.supplyResponseFk = sr.ID - JOIN edi.supplyOffer so ON so.srId = sr.ID - JOIN hedera.image i2 ON i2.name = i.image - AND i2.collectionFk = 'catalog' - WHERE i2.updated <= (UNIX_TIMESTAMP(util.VN_NOW()) - vDayRange) - AND sr.NumberOfUnits; - - INSERT INTO edi.`log` - SET tableName = 'floramondo_offerRefresh', - fieldName = 'Tiempo de proceso', - fieldValue = TIMEDIFF(util.VN_NOW(), vStartingTime); - - DO RELEASE_LOCK('edi.floramondo_offerRefresh'); +proc: BEGIN + DECLARE vLanded DATETIME; + DECLARE vDone INT DEFAULT FALSE; + DECLARE vFreeId INT; + DECLARE vSupplyResponseFk INT; + DECLARE vLastInserted DATETIME; + DECLARE vIsAuctionDay BOOLEAN; + DECLARE vMaxNewItems INT DEFAULT 10000; + DECLARE vStartingTime DATETIME; + DECLARE vAalsmeerMarketPlaceID VARCHAR(13) DEFAULT '8713783439043'; + DECLARE vDayRange INT; + + DECLARE cur1 CURSOR FOR + SELECT id + FROM edi.item_free; + + DECLARE cur2 CURSOR FOR + SELECT srId + FROM itemToInsert; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + DECLARE EXIT HANDLER FOR SQLSTATE '45000' + BEGIN + ROLLBACK; + RESIGNAL; + END; + + DECLARE CONTINUE HANDLER FOR SQLEXCEPTION + BEGIN + DO RELEASE_LOCK('edi.floramondo_offerRefresh'); + SET @isTriggerDisabled = FALSE; + RESIGNAL; + END; + + IF 'test' = (SELECT environment FROM util.config) THEN + LEAVE proc; + END IF; + + IF !GET_LOCK('edi.floramondo_offerRefresh', 0) THEN + LEAVE proc; + END IF; + + SELECT dayRange INTO vDayRange + FROM offerRefreshConfig; + + IF vDayRange IS NULL THEN + CALL util.throw("Variable vDayRange not declared"); + END IF; + + SET vStartingTime = util.VN_NOW(); + + TRUNCATE edi.offerList; + + INSERT INTO edi.offerList(supplier, total) + SELECT v.name, COUNT(DISTINCT sr.ID) total + FROM edi.supplyResponse sr + JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID + WHERE sr.NumberOfUnits > 0 + AND sr.EmbalageCode != 999 + GROUP BY sr.vmpID; + + UPDATE edi.offerList o + JOIN (SELECT v.name, COUNT(*) total + FROM edi.supplyOffer sr + JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID + GROUP BY sr.vmpID) sub ON o.supplier = sub.name + SET o.`filter` = sub.total; + + -- Elimina de la lista de items libres aquellos que ya existen + DELETE itf.* + FROM edi.item_free itf + JOIN vn.item i ON i.id = itf.id; + + CREATE OR REPLACE TEMPORARY TABLE tmp + (INDEX (`Item_ArticleCode`)) + ENGINE = MEMORY + SELECT t.* + FROM ( + SELECT * + FROM edi.supplyOffer + ORDER BY (MarketPlaceID = vAalsmeerMarketPlaceID) DESC, + NumberOfUnits DESC LIMIT 10000000000000000000) t + GROUP BY t.srId; + + CREATE OR REPLACE TEMPORARY TABLE edi.offer (INDEX (`srID`), INDEX (`EmbalageCode`), + INDEX (`ef1`), INDEX (`ef2`), INDEX (`ef3`), INDEX (`ef4`),INDEX (`ef5`), INDEX (`ef6`), + INDEX (`s1Value`), INDEX (`s2Value`), INDEX (`s3Value`), INDEX (`s4Value`),INDEX (`s5Value`), INDEX (`s6Value`)) + ENGINE = MEMORY + SELECT so.*, + ev1.type_description s1Value, + ev2.type_description s2Value, + ev3.type_description s3Value, + ev4.type_description s4Value, + ev5.type_description s5Value, + ev6.type_description s6Value, + eif1.feature ef1, + eif2.feature ef2, + eif3.feature ef3, + eif4.feature ef4, + eif5.feature ef5, + eif6.feature ef6 + FROM tmp so + LEFT JOIN edi.item_feature eif1 ON eif1.item_id = so.Item_ArticleCode + AND eif1.presentation_order = 1 + AND eif1.expiry_date IS NULL + LEFT JOIN edi.item_feature eif2 ON eif2.item_id = so.Item_ArticleCode + AND eif2.presentation_order = 2 + AND eif2.expiry_date IS NULL + LEFT JOIN edi.item_feature eif3 ON eif3.item_id = so.Item_ArticleCode + AND eif3.presentation_order = 3 + AND eif3.expiry_date IS NULL + LEFT JOIN edi.item_feature eif4 ON eif4.item_id = so.Item_ArticleCode + AND eif4.presentation_order = 4 + AND eif4.expiry_date IS NULL + LEFT JOIN edi.item_feature eif5 ON eif5.item_id = so.Item_ArticleCode + AND eif5.presentation_order = 5 + AND eif5.expiry_date IS NULL + LEFT JOIN edi.item_feature eif6 ON eif6.item_id = so.Item_ArticleCode + AND eif6.presentation_order = 6 + AND eif6.expiry_date IS NULL + LEFT JOIN edi.`value` ev1 ON ev1.type_id = eif1.feature + AND so.s1 = ev1.type_value + LEFT JOIN edi.`value` ev2 ON ev2.type_id = eif2.feature + AND so.s2 = ev2.type_value + LEFT JOIN edi.`value` ev3 ON ev3.type_id = eif3.feature + AND so.s3 = ev3.type_value + LEFT JOIN edi.`value` ev4 ON ev4.type_id = eif4.feature + AND so.s4 = ev4.type_value + LEFT JOIN edi.`value` ev5 ON ev5.type_id = eif5.feature + AND so.s5 = ev5.type_value + LEFT JOIN edi.`value` ev6 ON ev6.type_id = eif6.feature + AND so.s6 = ev6.type_value + ORDER BY Price; + + DROP TEMPORARY TABLE tmp; + + DELETE o + FROM edi.offer o + LEFT JOIN vn.tag t1 ON t1.ediTypeFk = o.ef1 AND t1.overwrite = 'size' + LEFT JOIN vn.tag t2 ON t2.ediTypeFk = o.ef2 AND t2.overwrite = 'size' + LEFT JOIN vn.tag t3 ON t3.ediTypeFk = o.ef3 AND t3.overwrite = 'size' + LEFT JOIN vn.tag t4 ON t4.ediTypeFk = o.ef4 AND t4.overwrite = 'size' + LEFT JOIN vn.tag t5 ON t5.ediTypeFk = o.ef5 AND t5.overwrite = 'size' + LEFT JOIN vn.tag t6 ON t6.ediTypeFk = o.ef6 AND t6.overwrite = 'size' + JOIN vn.floramondoConfig fc ON TRUE + WHERE (t1.id IS NOT NULL AND CONVERT(s1Value, UNSIGNED) > fc.itemMaxSize) + OR (t2.id IS NOT NULL AND CONVERT(s2Value, UNSIGNED) > fc.itemMaxSize) + OR (t3.id IS NOT NULL AND CONVERT(s3Value, UNSIGNED) > fc.itemMaxSize) + OR (t4.id IS NOT NULL AND CONVERT(s4Value, UNSIGNED) > fc.itemMaxSize) + OR (t5.id IS NOT NULL AND CONVERT(s5Value, UNSIGNED) > fc.itemMaxSize) + OR (t6.id IS NOT NULL AND CONVERT(s6Value, UNSIGNED) > fc.itemMaxSize); + + START TRANSACTION; + + -- Actualizamos el campo supplyResponseFk para aquellos articulos que ya estan creados y reutilizamos + UPDATE IGNORE edi.offer o + JOIN vn.item i + ON i.name = o.product_name + AND i.subname <=> o.company_name + AND i.value5 <=> o.s1Value + AND i.value6 <=> o.s2Value + AND i.value7 <=> o.s3Value + AND i.value8 <=> o.s4Value + AND i.value9 <=> o.s5Value + AND i.value10 <=> o.s6Value + AND i.NumberOfItemsPerCask <=> o.NumberOfItemsPerCask + AND i.EmbalageCode <=> o.EmbalageCode + AND i.quality <=> o.Quality + JOIN vn.itemType it ON it.id = i.typeFk + LEFT JOIN vn.sale s ON s.itemFk = i.id + LEFT JOIN vn.ticket t ON t.id = s.ticketFk + AND t.shipped > (util.VN_CURDATE() - INTERVAL 1 WEEK) + LEFT JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk + LEFT JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID + LEFT JOIN edi.putOrder po ON po.supplyResponseID = i.supplyResponseFk + AND po.OrderTradeLineDateTime > (util.VN_CURDATE() - INTERVAL 1 WEEK) + SET i.supplyResponseFk = o.srID + WHERE (sr.ID IS NULL + OR sr.NumberOfUnits = 0 + OR di.LatestOrderDateTime < util.VN_NOW() + OR di.ID IS NULL) + AND it.isInventory + AND t.id IS NULL + AND po.id IS NULL; + + CREATE OR REPLACE TEMPORARY TABLE itemToInsert + ENGINE = MEMORY + SELECT o.*, CAST(NULL AS DECIMAL(6,0)) itemFk + FROM edi.offer o + LEFT JOIN vn.item i ON i.supplyResponseFk = o.srId + WHERE i.id IS NULL + LIMIT vMaxNewItems; + + -- Reciclado de nº de item + OPEN cur1; + OPEN cur2; + + read_loop: LOOP + + FETCH cur2 INTO vSupplyResponseFk; + FETCH cur1 INTO vFreeId; + + IF vDone THEN + LEAVE read_loop; + END IF; + + UPDATE itemToInsert + SET itemFk = vFreeId + WHERE srId = vSupplyResponseFk; + + END LOOP; + + CLOSE cur1; + CLOSE cur2; + + -- Insertamos todos los items en Articles de la oferta + INSERT INTO vn.item(id, + `name`, + longName, + subName, + expenceFk, + typeFk, + intrastatFk, + originFk, + supplyResponseFk, + numberOfItemsPerCask, + embalageCode, + quality, + isFloramondo) + SELECT iti.itemFk, + iti.product_name, + iti.product_name, + iti.company_name, + iti.expenseFk, + iti.itemTypeFk, + iti.intrastatFk, + iti.originFk, + iti.`srId`, + iti.NumberOfItemsPerCask, + iti.EmbalageCode, + iti.Quality, + TRUE + FROM itemToInsert iti; + + -- Inserta la foto de los articulos nuevos (prioridad alta) + INSERT IGNORE INTO vn.itemImageQueue(itemFk, url) + SELECT i.id, PictureReference + FROM itemToInsert ii + JOIN vn.item i ON i.supplyResponseFk = ii.srId + WHERE PictureReference IS NOT NULL + AND i.image IS NULL; + + INSERT INTO edi.`log`(tableName, fieldName,fieldValue) + SELECT 'itemImageQueue','NumImagenesPtes', COUNT(*) + FROM vn.itemImageQueue + WHERE attempts = 0; + + -- Inserta si se añadiesen tags nuevos + INSERT IGNORE INTO vn.tag (name, ediTypeFk) + SELECT description, type_id FROM edi.type; + + -- Desabilita el trigger para recalcular los tags al final + SET @isTriggerDisabled = TRUE; + + -- Inserta los tags sólo en los articulos nuevos + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , ii.product_name, 1 + FROM itemToInsert ii + JOIN vn.tag t ON t.`name` = 'Producto' + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT ii.product_name IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , ii.Quality, 3 + FROM itemToInsert ii + JOIN vn.tag t ON t.`name` = 'Calidad' + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT ii.Quality IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , ii.company_name, 4 + FROM itemToInsert ii + JOIN vn.tag t ON t.`name` = 'Productor' + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT ii.company_name IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s1Value, 5 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef1 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s1Value IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s2Value, 6 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef2 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s2Value IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s3Value, 7 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef3 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s3Value IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s4Value, 8 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef4 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s4Value IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s5Value, 9 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef5 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s5Value IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s6Value, 10 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef6 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s6Value IS NULL; + + INSERT IGNORE INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id, IFNULL(ink.name, ik.color), 11 + FROM itemToInsert ii + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + JOIN vn.tag t ON t.`name` = 'Color' + LEFT JOIN edi.feature f ON f.item_id = ii.Item_ArticleCode + LEFT JOIN edi.`type` tp ON tp.type_id = f.feature_type_id + AND tp.`description` = 'Hoofdkleur 1' + LEFT JOIN vn.ink ON ink.dutchCode = f.feature_value + LEFT JOIN vn.itemInk ik ON ik.longName = i.longName + WHERE ink.name IS NOT NULL + OR ik.color IS NOT NULL; + + CREATE OR REPLACE TABLE tmp.item + (PRIMARY KEY (id)) + SELECT i.id FROM vn.item i + JOIN itemToInsert ii ON i.supplyResponseFk = ii.`srId`; + + CALL vn.item_refreshTags(); + + DROP TABLE tmp.item; + + SELECT MIN(LatestDeliveryDateTime) INTO vLanded + FROM edi.supplyResponse sr + JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID + JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID + JOIN vn.floramondoConfig fc + WHERE mp.isLatestOrderDateTimeRelevant + AND di.LatestOrderDateTime > IF( + fc.MaxLatestOrderHour > HOUR(util.VN_NOW()), + util.VN_CURDATE(), + util.VN_CURDATE() + INTERVAL 1 DAY); + + UPDATE vn.floramondoConfig + SET nextLanded = vLanded + WHERE vLanded IS NOT NULL; + + -- Elimina la oferta obsoleta + UPDATE vn.buy b + JOIN vn.entry e ON e.id = b.entryFk + JOIN vn.travel tr ON tr.id = e.travelFk + JOIN vn.agencyMode am ON am.id = tr.agencyModeFk + JOIN vn.item i ON i.id = b.itemFk + LEFT JOIN edi.supplyResponse sr ON i.supplyResponseFk = sr.ID + LEFT JOIN edi.deliveryInformation di ON di.ID = b.deliveryFk + SET b.quantity = 0 + WHERE (IFNULL(di.LatestOrderDateTime,util.VN_NOW()) <= util.VN_NOW() + OR i.supplyResponseFk IS NULL + OR sr.NumberOfUnits = 0) + AND am.name = 'LOGIFLORA' + AND e.isRaid; + + -- Localiza las entradas de cada almacen + UPDATE edi.warehouseFloramondo + SET entryFk = vn.entry_getForLogiflora(vLanded + INTERVAL travellingDays DAY, warehouseFk); + + IF vLanded IS NOT NULL THEN + -- Actualiza la oferta existente + UPDATE vn.buy b + JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk + JOIN vn.item i ON i.id = b.itemFk + JOIN edi.offer o ON i.supplyResponseFk = o.`srId` + SET b.quantity = o.NumberOfUnits * o.NumberOfItemsPerCask, + b.buyingValue = o.price + WHERE (b.quantity <> o.NumberOfUnits * o.NumberOfItemsPerCask + OR b.buyingValue <> o.price); + + -- Inserta el resto + SET vLastInserted := util.VN_NOW(); + + -- Inserta la oferta + INSERT INTO vn.buy ( + entryFk, + itemFk, + quantity, + buyingValue, + stickers, + packing, + `grouping`, + groupingMode, + packageFk, + deliveryFk) + SELECT wf.entryFk, + i.id, + o.NumberOfUnits * o.NumberOfItemsPerCask quantity, + o.Price, + o.NumberOfUnits etiquetas, + o.NumberOfItemsPerCask packing, + GREATEST(1, IFNULL(o.MinimumQuantity,0)) * o.NumberOfItemsPerCask `grouping`, + 2, -- Obliga al Packing + o.embalageCode, + o.diId + FROM edi.offer o + JOIN vn.item i ON i.supplyResponseFk = o.srId + JOIN edi.warehouseFloramondo wf + JOIN vn.packaging p ON p.id + LIKE o.embalageCode + LEFT JOIN vn.buy b ON b.itemFk = i.id + AND b.entryFk = wf.entryFk + WHERE b.id IS NULL; -- Quitar esta linea y mirar de crear los packages a tiempo REAL + + INSERT INTO vn.itemCost( + itemFk, + warehouseFk, + cm3, + cm3delivery) + SELECT b.itemFk, + wf.warehouseFk, + @cm3 := vn.buy_getUnitVolume(b.id), + IFNULL((vc.standardFlowerBox * 1000) / i.packingOut, @cm3) + FROM warehouseFloramondo wf + JOIN vn.volumeConfig vc + JOIN vn.buy b ON b.entryFk = wf.entryFk + JOIN vn.item i ON i.id = b.itemFk + LEFT JOIN vn.itemCost ic ON ic.itemFk = b.itemFk + AND ic.warehouseFk = wf.warehouseFk + WHERE (ic.cm3 IS NULL OR ic.cm3 = 0) + ON DUPLICATE KEY UPDATE cm3 = @cm3, cm3delivery = IFNULL((vc.standardFlowerBox * 1000) / i.packingOut, @cm3); + + CREATE OR REPLACE TEMPORARY TABLE tmp.buyRecalc + SELECT b.id + FROM vn.buy b + JOIN warehouseFloramondo wf ON wf.entryFk = b.entryFk + WHERE b.created >= vLastInserted; + + CALL vn.buy_recalcPrices(); + + UPDATE edi.offerList o + JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total + FROM vn.buy b + JOIN vn.item i ON i.id = b.itemFk + JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk + JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID + JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk + JOIN vn.warehouse w ON w.id = wf.warehouseFk + WHERE w.name = 'VNH' + AND b.quantity > 0 + GROUP BY sr.vmpID) sub ON o.supplier = sub.name + SET o.vnh = sub.total; + + UPDATE edi.offerList o + JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total + FROM vn.buy b + JOIN vn.item i ON i.id = b.itemFk + JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk + JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID + JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk + JOIN vn.warehouse w ON w.id = wf.warehouseFk + WHERE w.name = 'ALGEMESI' + AND b.quantity > 0 + GROUP BY sr.vmpID) sub ON o.supplier = sub.name + SET o.algemesi = sub.total; + END IF; + + DROP TEMPORARY TABLE + edi.offer, + itemToInsert; + + SET @isTriggerDisabled = FALSE; + + COMMIT; + + -- Esto habria que pasarlo a procesos programados o trabajar con tags y dejar las familias + UPDATE vn.item i + SET typeFk = 121 + WHERE i.longName LIKE 'Rosa Garden %' + AND typeFk = 17; + + UPDATE vn.item i + SET typeFk = 156 + WHERE i.longName LIKE 'Rosa ec %' + AND typeFk = 17; + + -- Refresca las fotos de los items existentes que mostramos (prioridad baja) + INSERT IGNORE INTO vn.itemImageQueue(itemFk, url, priority) + SELECT i.id, sr.PictureReference, 100 + FROM edi.supplyResponse sr + JOIN vn.item i ON i.supplyResponseFk = sr.ID + JOIN edi.supplyOffer so ON so.srId = sr.ID + JOIN hedera.image i2 ON i2.name = i.image + AND i2.collectionFk = 'catalog' + WHERE i2.updated <= (UNIX_TIMESTAMP(util.VN_NOW()) - vDayRange) + AND sr.NumberOfUnits; + + INSERT INTO edi.`log` + SET tableName = 'floramondo_offerRefresh', + fieldName = 'Tiempo de proceso', + fieldValue = TIMEDIFF(util.VN_NOW(), vStartingTime); + + DO RELEASE_LOCK('edi.floramondo_offerRefresh'); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -9793,7 +9793,7 @@ BEGIN /** * Devuelve un número nuevo de item a partir de un registro de la tabla edi.ekt - * + * * @param vEktFk Identificador de la tabla edi.ekt */ @@ -9802,17 +9802,17 @@ BEGIN SELECT MIN(id) id INTO vItemFk FROM edi.item_free; - DELETE FROM edi.item_free + DELETE FROM edi.item_free WHERE id = vItemFk; - + COMMIT; - + IF ISNULL(vItemFk) THEN SELECT MAX(i.id) + 1 INTO vItemFk FROM vn.item i; END IF; - + INSERT INTO vn.item(id, `name`, longName, @@ -9838,118 +9838,118 @@ BEGIN least(IF((e.package = 800),((e.package * 10) + e.pac), e.package), IFNULL(idt.bucket_id, '999')) packageFk, e.cat, TRUE - FROM edi.ekt e - JOIN edi.item i ON i.id = e.`ref` - JOIN edi.item_groupToOffer igto ON igto.group_code = i.group_id - LEFT JOIN edi.item_defaultType idt ON idt.item_id = e.`ref` + FROM edi.ekt e + JOIN edi.item i ON i.id = e.`ref` + JOIN edi.item_groupToOffer igto ON igto.group_code = i.group_id + LEFT JOIN edi.item_defaultType idt ON idt.item_id = e.`ref` WHERE e.id = vEktFk; SET @isTriggerDisabled = TRUE; - + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id , e.item , 1 - FROM edi.ekt e + SELECT vItemFk, t.id , e.item , 1 + FROM edi.ekt e JOIN vn.tag t ON t.`name` = 'Producto' WHERE e.id = vEktFk AND NOT ISNULL(e.item); INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id , e.cat , 3 - FROM edi.ekt e + SELECT vItemFk, t.id , e.cat , 3 + FROM edi.ekt e JOIN vn.tag t ON t.`name` = 'Calidad' WHERE e.id = vEktFk AND NOT ISNULL(e.cat); - + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id , s.company_name , 4 - FROM edi.ekt e + SELECT vItemFk, t.id , s.company_name , 4 + FROM edi.ekt e JOIN edi.supplier s ON s.supplier_id = e.pro JOIN vn.tag t ON t.`name` = 'Productor' WHERE e.id = vEktFk AND NOT ISNULL(s.company_name); INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id , e.s1, 5 + SELECT vItemFk, t.id , e.s1, 5 FROM edi.ekt e - LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` - AND eif.presentation_order = 1 + LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` + AND eif.presentation_order = 1 AND eif.expiry_date IS NULL - LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature + LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature AND e.s1 = ev.type_value JOIN vn.tag t ON t.ediTypeFk = eif.feature WHERE e.id = vEktFk AND NOT ISNULL(e.s1); - + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id , e.s2, 6 + SELECT vItemFk, t.id , e.s2, 6 FROM edi.ekt e - LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` - AND eif.presentation_order = 2 + LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` + AND eif.presentation_order = 2 AND eif.expiry_date IS NULL - LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature + LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature AND e.s2 = ev.type_value JOIN vn.tag t ON t.ediTypeFk = eif.feature WHERE e.id = vEktFk AND NOT ISNULL(e.s2); - + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id , e.s3, 7 + SELECT vItemFk, t.id , e.s3, 7 FROM edi.ekt e - LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` - AND eif.presentation_order = 3 + LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` + AND eif.presentation_order = 3 AND eif.expiry_date IS NULL - LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature + LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature AND e.s3 = ev.type_value JOIN vn.tag t ON t.ediTypeFk = eif.feature WHERE e.id = vEktFk AND NOT ISNULL(e.s3); - + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id , e.s4, 8 + SELECT vItemFk, t.id , e.s4, 8 FROM edi.ekt e - LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` + LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` AND eif.presentation_order = 4 AND eif.expiry_date IS NULL - LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature + LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature AND e.s4 = ev.type_value JOIN vn.tag t ON t.ediTypeFk = eif.feature WHERE e.id = vEktFk AND NOT ISNULL(e.s4); - + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id , e.s5, 9 + SELECT vItemFk, t.id , e.s5, 9 FROM edi.ekt e - LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` + LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` AND eif.presentation_order = 5 AND eif.expiry_date IS NULL - LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature + LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature AND e.s5 = ev.type_value JOIN vn.tag t ON t.ediTypeFk = eif.feature WHERE e.id = vEktFk AND NOT ISNULL(e.s5); INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id , e.s6, 10 + SELECT vItemFk, t.id , e.s6, 10 FROM edi.ekt e - LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` + LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` AND eif.presentation_order = 6 AND eif.expiry_date IS NULL - LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature + LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature AND e.s6 = ev.type_value JOIN vn.tag t ON t.ediTypeFk = eif.feature WHERE e.id = vEktFk AND NOT ISNULL(e.s6); INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id, IFNULL(ink.name, ik.color), 11 - FROM edi.ekt e + SELECT vItemFk, t.id, IFNULL(ink.name, ik.color), 11 + FROM edi.ekt e JOIN vn.tag t ON t.`name` = 'Color' - LEFT JOIN edi.feature f ON f.item_id = e.`ref` + LEFT JOIN edi.feature f ON f.item_id = e.`ref` LEFT JOIN edi.`type` tp ON tp.type_id = f.feature_type_id AND tp.`description` = 'Hoofdkleur 1' LEFT JOIN vn.ink ON ink.dutchCode = f.feature_value LEFT JOIN vn.itemInk ik ON ik.longName = e.item WHERE e.id = vEktFk - AND ( ink.name IS NOT NULL + AND ( ink.name IS NOT NULL OR ik.color IS NOT NULL) LIMIT 1; @@ -10016,7 +10016,7 @@ BEGIN sender = vSender, senderFk = vSenderId, messageId = vMessageId; - + IF vIsDuplicated THEN SELECT id INTO vSelf FROM mail @@ -10838,7 +10838,7 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `hedera`.`order_afterInsert` AFTER INSERT ON `order` FOR EACH ROW -BEGIN +BEGIN IF NEW.address_id = 2850 THEN -- Fallo que se insertan no se sabe como tickets en este cliente CALL vn.mail_insert( @@ -10847,7 +10847,7 @@ BEGIN 'Creada order al address 2850', CONCAT(account.myUser_getName(), ' ha creado la order ',NEW.id) ); - + END IF; END */;; DELIMITER ; @@ -10864,27 +10864,27 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `hedera`.`order_afterUpdate` - AFTER UPDATE ON `order` - FOR EACH ROW -BEGIN - CALL stock.log_add('order', NEW.id, OLD.id); - - IF !(OLD.address_id <=> NEW.address_id) - OR !(OLD.company_id <=> NEW.company_id) - OR !(OLD.customer_id <=> NEW.customer_id) THEN - CALL order_requestRecalc(NEW.id); - END IF; - - IF !(OLD.address_id <=> NEW.address_id) AND NEW.address_id = 2850 THEN - -- Fallo que se actualiza no se sabe como tickets en este cliente - CALL vn.mail_insert( - 'jgallego@verdnatura.es', - 'noreply@verdnatura.es', - 'Actualizada order al address 2850', - CONCAT(account.myUser_getName(), ' ha creado la order ',NEW.id) - ); - END IF; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `hedera`.`order_afterUpdate` + AFTER UPDATE ON `order` + FOR EACH ROW +BEGIN + CALL stock.log_add('order', NEW.id, OLD.id); + + IF !(OLD.address_id <=> NEW.address_id) + OR !(OLD.company_id <=> NEW.company_id) + OR !(OLD.customer_id <=> NEW.customer_id) THEN + CALL order_requestRecalc(NEW.id); + END IF; + + IF !(OLD.address_id <=> NEW.address_id) AND NEW.address_id = 2850 THEN + -- Fallo que se actualiza no se sabe como tickets en este cliente + CALL vn.mail_insert( + 'jgallego@verdnatura.es', + 'noreply@verdnatura.es', + 'Actualizada order al address 2850', + CONCAT(account.myUser_getName(), ' ha creado la order ',NEW.id) + ); + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -10999,12 +10999,12 @@ DELIMITER ;; BEGIN DECLARE vIsFirst BOOL; - SELECT (first_row_stamp IS NULL) INTO vIsFirst - FROM `order` + SELECT (first_row_stamp IS NULL) INTO vIsFirst + FROM `order` WHERE id = NEW.orderFk; IF vIsFirst THEN - UPDATE `order` SET first_row_stamp = util.VN_NOW() + UPDATE `order` SET first_row_stamp = util.VN_NOW() WHERE id = NEW.orderFk; END IF; END */;; @@ -11593,7 +11593,7 @@ BEGIN IF vCount = 0 THEN RETURN FALSE; - END IF; + END IF; SELECT COUNT(*) > 0 INTO vHasRole @@ -11674,14 +11674,14 @@ BEGIN * @return tmp.ticketComponent * @return tmp.ticketLot * @return tmp.zoneGetShipped - */ + */ DECLARE vAgencyMode INT; - + SELECT a.agencyModeFk INTO vAgencyMode FROM myClient c JOIN vn.address a ON a.clientFk = c.id - WHERE a.id = vAddress; + WHERE a.id = vAddress; CALL vn.available_calc(vDelivery, vAddress, vAgencyMode); @@ -11694,7 +11694,7 @@ BEGIN JOIN tmp.availableCalc a ON a.calcFk = c.calc_id WHERE c.available > 0 GROUP BY c.item_id; - + CALL vn.catalog_calculate(vDelivery, vAddress, vAgencyMode); DROP TEMPORARY TABLE tmp.item; @@ -11796,7 +11796,7 @@ BEGIN */ DROP TEMPORARY TABLE IF EXISTS tmp.item; CREATE TEMPORARY TABLE tmp.item - ENGINE = MEMORY + ENGINE = MEMORY SELECT vSelf itemFk; CALL vn.catalog_calculate(vLanded, vAddressFk, vAgencyModeFk); @@ -11836,7 +11836,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getVisible`( vType INT, vPrefix VARCHAR(255)) BEGIN - + /** * Gets visible items of the specified type at specified date. * @@ -11845,7 +11845,7 @@ BEGIN * @param vType The type id * @param vPrefix The article prefix to filter or %NULL for all * @return tmp.itemVisible Visible items - */ + */ DECLARE vPrefixLen SMALLINT; DECLARE vFilter VARCHAR(255) DEFAULT NULL; DECLARE vDateInv DATE DEFAULT vn2008.date_inv(); @@ -11854,13 +11854,13 @@ BEGIN GET DIAGNOSTICS CONDITION 1 @message = MESSAGE_TEXT; CALL vn.mail_insert( - 'cau@verdnatura.es', - NULL, + 'cau@verdnatura.es', + NULL, CONCAT('hedera.item_getVisible error: ', @message), CONCAT( - 'warehouse: ', IFNULL(vWarehouse, ''), - ', Fecha:', IFNULL(vDate, ''), - ', tipo: ', IFNULL(vType,''), + 'warehouse: ', IFNULL(vWarehouse, ''), + ', Fecha:', IFNULL(vDate, ''), + ', tipo: ', IFNULL(vType,''), ', prefijo: ', IFNULL(vPrefix,''))); RESIGNAL; END; @@ -11939,7 +11939,7 @@ BEGIN IF(p.depth > 0, p.depth, 0) depth, p.width, p.height, CEIL(s.quantity / t.packing) etiquetas FROM vn.item i - JOIN `filter` f ON f.itemFk = i.id + JOIN `filter` f ON f.itemFk = i.id JOIN currentStock s ON s.itemFk = i.id LEFT JOIN tmp t ON t.itemFk = i.id LEFT JOIN vn.packaging p ON p.id = t.packageFk @@ -12416,15 +12416,15 @@ BEGIN START TRANSACTION; - SELECT a.agencyModeFk, a.id + SELECT a.agencyModeFk, a.id INTO vAgencyMode, vAddressFk - FROM vn.address a + FROM vn.address a WHERE a.id = vAddressFk; - + SELECT deliveryMethodFk INTO vDeliveryMethodId FROM vn.agencyMode am WHERE am.id = vAgencyMode; - + IF vCompany IS NULL THEN SELECT defaultCompanyFk INTO vCompany @@ -12442,7 +12442,7 @@ BEGIN company_id = vCompany; SET vSelf = LAST_INSERT_ID(); - + CALL order_checkConfig(vSelf); COMMIT; @@ -12488,15 +12488,15 @@ BEGIN START TRANSACTION; - SELECT a.agencyModeFk, a.id + SELECT a.agencyModeFk, a.id INTO vAgencyMode, vAddress FROM myClient c JOIN vn.address a ON a.id = c.defaultAddressFk; - + SELECT deliveryMethodFk INTO vDeliveryMethodId FROM vn.agencyMode am WHERE am.id = vAgencyMode; - + IF vCompany IS NULL THEN SELECT defaultCompanyFk INTO vCompany @@ -12514,7 +12514,7 @@ BEGIN company_id = vCompany; SET vSelf = LAST_INSERT_ID(); - + CALL order_checkConfig(vSelf); COMMIT; @@ -12697,7 +12697,7 @@ BEGIN SELECT t.id ticketFk FROM myTicket t WHERE shipped BETWEEN TIMESTAMP(vFrom) AND TIMESTAMP(vTo, '23:59:59'); - + CALL vn.ticketGetTotal(NULL); SELECT v.id, IFNULL(v.landed, v.shipped) landed, @@ -12962,10 +12962,10 @@ BEGIN CREATE TEMPORARY TABLE tmp.item (PRIMARY KEY (itemFk)) ENGINE = MEMORY - SELECT itemFk FROM orderRow + SELECT itemFk FROM orderRow WHERE orderFk = vSelf GROUP BY itemFk; - + CALL vn.catalog_calculate(vDate, vAddress, vAgencyMode); DROP TEMPORARY TABLE tmp.item; @@ -13340,7 +13340,7 @@ BEGIN END; -- Carga los datos del pedido - SELECT o.date_send, o.address_id, o.note, a.clientFk, + SELECT o.date_send, o.address_id, o.note, a.clientFk, o.company_id, o.agency_id, c.isTaxDataChecked INTO vDelivery, vAddress, vNotes, vClientId, vCompanyId, vAgencyModeId, vIsTaxDataChecked @@ -13661,7 +13661,7 @@ BEGIN INTO vDelivery, vAddress, vAgencyMode FROM `order` WHERE id = vSelf; - + CALL vn.available_calc(vDelivery, vAddress, vAgencyMode); DROP TEMPORARY TABLE IF EXISTS tmp.itemAvailable; @@ -13703,7 +13703,7 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.addressCompany; CREATE TEMPORARY TABLE tmp.addressCompany (INDEX (addressFk, companyFk)) - ENGINE = MEMORY + ENGINE = MEMORY SELECT DISTINCT o.address_id addressFk, o.company_id companyFk FROM tmp.`order` tmpOrder JOIN hedera.`order` o ON o.id = tmpOrder.orderFk; @@ -13738,7 +13738,7 @@ BEGIN JOIN vn.taxClass tc ON tc.id = bp.taxClassFk GROUP BY tmpOrder.orderFk, pgc.`code`, pgc.rate HAVING taxableBase != 0; - + DROP TEMPORARY TABLE IF EXISTS tmp.orderAmount; CREATE TEMPORARY TABLE tmp.orderAmount (INDEX (orderFk)) @@ -13747,7 +13747,7 @@ BEGIN SUM(CAST(taxableBase * rate / 100 AS DECIMAL(10, 2))) tax FROM tmp.orderTax GROUP BY orderFk, `code`; - + DROP TEMPORARY TABLE tmp.addressTaxArea; END ;; DELIMITER ; @@ -13817,7 +13817,7 @@ BEGIN CREATE TEMPORARY TABLE tmp.`order` ENGINE = MEMORY SELECT vSelf orderFk; - + CALL order_getTax; SELECT IFNULL(SUM(taxableBase), 0.0), IFNULL(SUM(tax), 0.0) @@ -13908,7 +13908,7 @@ proc: BEGIN FROM orderRow r JOIN orderRowComponent c ON c.rowFk = r.id WHERE r.orderFk = vSelf; - + UPDATE orderRow r LEFT JOIN tmp.ticketComponentPrice p ON p.warehouseFk = r.warehouseFk @@ -13933,7 +13933,7 @@ proc: BEGIN ON t.id = c.componentFk AND (t.classRate IS NULL OR t.classRate = r.rate) WHERE r.orderFk = vSelf; - + CALL vn.ticketCalculatePurge; END IF; @@ -14461,13 +14461,13 @@ p: BEGIN AND DATE(FECHA) = vDate AND EURODEBE = vAmount LIMIT 1; - + -- Actualiza la transaccion UPDATE tpvTransaction SET response = NULL, status = 'started' WHERE id = vSelf; - + COMMIT; END ;; DELIMITER ; @@ -14500,7 +14500,7 @@ BEGIN UPDATE userSession SET userVisitFk = vUserVisit WHERE ssid = vSsid; - + DELETE FROM userSession WHERE lastUpdate < TIMESTAMPADD(HOUR, -1, util.VN_NOW()); END ;; @@ -14624,7 +14624,7 @@ BEGIN UPDATE visitAgent SET firstAccessFk = vAccessId WHERE id = vAgentId; END IF; - + -- Returns the visit info SELECT vVisit visit, vAccessId access; @@ -15333,7 +15333,7 @@ BEGIN WHILE vI < vLen DO SET vChr = SUBSTR(vPhone, vI + 1, 1); - + IF vChr REGEXP '^[0-9]$' THEN SET vNewPhone = CONCAT(vNewPhone, vChr); @@ -15341,7 +15341,7 @@ BEGIN THEN SET vNewPhone = CONCAT(vNewPhone, '00'); END IF; - + SET vI = vI + 1; END WHILE; @@ -15440,18 +15440,18 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sip_getExtension`(vUserId INT(10)) BEGIN - + /* * Devuelve la extensión pbx del usuario - * - * @param vUserId Id del usuario - * + * + * @param vUserId Id del usuario + * */ SELECT extension - FROM sip s + FROM sip s WHERE s.user_id = vUserId; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -16239,22 +16239,22 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `company_getCode`(vCompanyFk INT) RET READS SQL DATA BEGIN /** - * Devuelve la correspondencía del código de empresa de sage. + * Devuelve la correspondencía del código de empresa de sage. * Tiene en cuenta el entorno - * + * * @param vSelf Id de empresa de verdnatura * @return Código de empresa sage */ DECLARE vCompanySageFk INT(2); - - SELECT IF(c.environment = 'production', - co.companyCode, + + SELECT IF(c.environment = 'production', + co.companyCode, co.companyCodeTest ) INTO vCompanySageFk FROM util.config c JOIN vn.company co WHERE co.id = vCompanyFk; - + RETURN vCompanySageFk; END ;; DELIMITER ; @@ -16273,12 +16273,12 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `accountingMovements_add`( - vYear INT, + vYear INT, vCompanyFk INT ) BEGIN /** - * Traslada la info de contabilidad generada en base a vn.XDiario a la tabla sage.movConta + * Traslada la info de contabilidad generada en base a vn.XDiario a la tabla sage.movConta * para poder ejecutar posteriormente el proceso de importación de datos de SQL Server * Solo traladará los asientos marcados con el campo vn.XDiario.enlazadoSage = FALSE * @vYear Año contable del que se quiere trasladar la información @@ -16594,8 +16594,8 @@ BEGIN mci.FechaFacturaOriginal = x.FECHA_EX, mci.SuFacturaNo = x.FACTURAEX, mci.FechaOperacion = x.FECHA_OP, - mci.ImporteFactura = mci.ImporteFactura + - x.BASEEURO + + mci.ImporteFactura = mci.ImporteFactura + + x.BASEEURO + CAST((x.IVA / 100) * x.BASEEURO AS DECIMAL(10, 2)) WHERE pm.description = 'HP Iva pendiente' AND mci.enlazadoSage = FALSE @@ -16614,7 +16614,7 @@ BEGIN mci.CodigoIva2 = vTaxImportFk, mci.IvaDeducible2 = TRUE, mci.ImporteFactura = mci.ImporteFactura + - x.BASEEURO + + x.BASEEURO + CAST((x.IVA / 100) * x.BASEEURO AS DECIMAL(10, 2)) WHERE pm.description = 'HP Iva pendiente' AND mci.enlazadoSage = FALSE @@ -16632,8 +16632,8 @@ BEGIN mci.CodigoTransaccion3 = vDuaTransactionFk , mci.CodigoIva3 = vTaxImportSuperReducedFk, mci.IvaDeducible3 = TRUE, - mci.ImporteFactura = mci.ImporteFactura + - x.BASEEURO + + mci.ImporteFactura = mci.ImporteFactura + + x.BASEEURO + CAST((x.IVA / 100) * x.BASEEURO AS DECIMAL(10, 2)) WHERE pm.description = 'HP Iva pendiente' AND mci.enlazadoSage = FALSE @@ -16667,14 +16667,14 @@ BEGIN OR CodigoTransaccion2 = vTransactionExportFk OR CodigoTransaccion3 = vTransactionExportFk OR CodigoTransaccion4 = vTransactionExportFk) - AND SiglaNacion IN (vCountryCanariasCode COLLATE utf8mb3_unicode_ci, + AND SiglaNacion IN (vCountryCanariasCode COLLATE utf8mb3_unicode_ci, vCountryCeutaMelillaCode COLLATE utf8mb3_unicode_ci); UPDATE movConta mc SET CodigoDivisa = 'USD', FactorCambio = TRUE, - ImporteCambio = ABS( CAST( IF( ImporteDivisa <> 0 AND ImporteCambio = 0, - ImporteAsiento / ImporteDivisa, + ImporteCambio = ABS( CAST( IF( ImporteDivisa <> 0 AND ImporteCambio = 0, + ImporteAsiento / ImporteDivisa, ImporteCambio) AS DECIMAL( 10, 2))) WHERE enlazadoSage = FALSE AND (ImporteCambio <> 0 OR ImporteDivisa <> 0 OR FactorCambio); @@ -16716,8 +16716,8 @@ BEGIN AND sub.amountTaxableBase/2 <> sub2.amountTaxableBase) sub; IF vBookEntries IS NOT NULL THEN - SELECT util.notification_send ("book-entries-imported-incorrectly", - CONCAT('{"bookEntries":"', vBookEntries,'"}'), + SELECT util.notification_send ("book-entries-imported-incorrectly", + CONCAT('{"bookEntries":"', vBookEntries,'"}'), null); END IF; END ;; @@ -16798,8 +16798,8 @@ BEGIN IF(n.SiglaNacion = vCountryCanariasCode COLLATE utf8mb3_unicode_ci, IF(@isCeutaMelilla := IF(pr.Provincia IN ('CEUTA', 'MELILLA'), TRUE, FALSE), vCountryCeutaMelillaFk, IF (@isCanarias, vCountryCanariasCode, n.CodigoNacion)), n.CodigoNacion), IF(n.SiglaNacion = vCountryCanariasCode COLLATE utf8mb3_unicode_ci, IF(@isCeutaMelilla, vCountryCeutaMelillaCode, IF (@isCanarias, vCountryCanariasCode, n.SiglaNacion)), n.SiglaNacion), IF((c.fi REGEXP '^([[:blank:]]|[[:digit:]])'), 'J','F'), - IF(cu.code = 'ES', - 1, + IF(cu.code = 'ES', + 1, IF((cu.isUeeMember AND c.isVies), 2, 4)), IFNULL(c.taxTypeSageFk,0), IF(n.SiglaNacion = vCountryCanariasCode COLLATE utf8mb3_unicode_ci, @@ -16877,10 +16877,10 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceIn_add`(vInvoiceInFk INT, vX BEGIN /** * Traslada la info de contabilidad relacionada con las facturas recibidas - * + * * @vInvoiceInFk Factura recibida * @vXDiarioFk Id tabla XDiario - */ + */ DECLARE vDone BOOL DEFAULT FALSE; DECLARE vBase DOUBLE; DECLARE vVat DOUBLE; @@ -16897,25 +16897,25 @@ BEGIN DECLARE vInvoiceTypeInformative VARCHAR(1); DECLARE vIsInformativeExportation BOOL DEFAULT FALSE; - DECLARE vCursor CURSOR FOR + DECLARE vCursor CURSOR FOR SELECT it.taxableBase, CAST((( it.taxableBase / 100) * t.PorcentajeIva) AS DECIMAL (10,2)), t.PorcentajeIva, it.transactionTypeSageFk, it.taxTypeSageFk, tty.isIntracommunity, - tt.ClaveOperacionDefecto + tt.ClaveOperacionDefecto FROM vn.invoiceIn i JOIN vn.invoiceInTax it ON it.InvoiceInFk = i.id JOIN TiposIva t ON t.CodigoIva = it.taxTypeSageFk JOIN taxType tty ON tty.id = t.CodigoIva JOIN TiposTransacciones tt ON tt.CodigoTransaccion = it.transactionTypeSageFk LEFT JOIN vn.dua d ON d.id = vInvoiceInFk - WHERE i.id = vInvoiceInFk + WHERE i.id = vInvoiceInFk AND d.id IS NULL; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + DELETE FROM movContaIVA WHERE id = vXDiarioFk; @@ -16938,22 +16938,22 @@ BEGIN vTaxCode, vIsIntracommunity, vOperationCode; - - IF vDone THEN + + IF vDone THEN LEAVE l; END IF; - SET vTransactionCodeOld = vTransactionCode; - SET vTaxCodeOld = vTaxCode; + SET vTransactionCodeOld = vTransactionCode; + SET vTaxCodeOld = vTaxCode; - IF vOperationCode IS NOT NULL THEN + IF vOperationCode IS NOT NULL THEN UPDATE movContaIVA SET ClaveOperacionFactura = vOperationCode WHERE id = vXDiarioFk; END IF; - + SET vCounter = vCounter + 1; - CASE vCounter + CASE vCounter WHEN 1 THEN UPDATE movContaIVA SET BaseIva1 = vBase, @@ -16989,31 +16989,31 @@ BEGIN WHERE id = vXDiarioFk; ELSE SELECT vXDiarioFk INTO vXDiarioFk; - END CASE; + END CASE; IF vIsIntracommunity THEN UPDATE movContaIVA SET Intracomunitaria = TRUE WHERE id = vXDiarioFk; END IF; - - SET vTransactionCodeOld = vTransactionCode; - SET vTaxCodeOld = vTaxCode; - + + SET vTransactionCodeOld = vTransactionCode; + SET vTaxCodeOld = vTaxCode; + END LOOP; CLOSE vCursor; SELECT d.ASIEN AND x.ASIEN IS NULL INTO vIsInformativeExportation FROM vn.dua d - LEFT JOIN vn.XDiario x ON x.ASIEN = d.ASIEN + LEFT JOIN vn.XDiario x ON x.ASIEN = d.ASIEN AND x.SERIE = vSerialDua COLLATE utf8mb3_unicode_ci WHERE d.ASIEN = ( SELECT ASIEN - FROM vn.XDiario + FROM vn.XDiario WHERE id = vXDiarioFk) LIMIT 1; - + UPDATE movContaIVA mci JOIN tmp.invoiceIn ii ON ii.id = vInvoiceInFk JOIN vn.XDiario x ON x.id = mci.id @@ -17025,13 +17025,13 @@ BEGIN mci.Serie = ii.serial, mci.Factura = ii.id, mci.FechaFactura = ii.issued, - mci.ImporteFactura = IFNULL(mci.BaseIva1, 0) + IFNULL(mci.CuotaIva1, 0) + - IFNULL(mci.BaseIva2, 0) + IFNULL(mci.CuotaIva2, 0) + - IFNULL(mci.BaseIva3, 0) + IFNULL(mci.CuotaIva3, 0) + + mci.ImporteFactura = IFNULL(mci.BaseIva1, 0) + IFNULL(mci.CuotaIva1, 0) + + IFNULL(mci.BaseIva2, 0) + IFNULL(mci.CuotaIva2, 0) + + IFNULL(mci.BaseIva3, 0) + IFNULL(mci.CuotaIva3, 0) + IFNULL(mci.BaseIva4, 0) + IFNULL(mci.CuotaIva4, 0), - mci.TipoFactura = IF(id.id, - IF( ii.serial = vSerialDua COLLATE utf8mb3_unicode_ci, vInvoiceTypeReceived, vInvoiceTypeInformative), - IF(vIsInformativeExportation,vInvoiceTypeInformative, vInvoiceTypeReceived)), + mci.TipoFactura = IF(id.id, + IF( ii.serial = vSerialDua COLLATE utf8mb3_unicode_ci, vInvoiceTypeReceived, vInvoiceTypeInformative), + IF(vIsInformativeExportation,vInvoiceTypeInformative, vInvoiceTypeReceived)), mci.CodigoCuentaFactura = x.SUBCTA, mci.CifDni = IF(LEFT(TRIM(s.nif), 2) = n.SiglaNacion, SUBSTRING(TRIM(s.nif), 3), s.nif), mci.Nombre = s.name, @@ -17059,7 +17059,7 @@ BEGIN JOIN (SELECT SUM(x2.BASEEURO) taxableBase, SUM(x2.EURODEBE) taxBase FROM vn.XDiario x1 JOIN vn.XDiario x2 ON x1.ASIEN = x2.ASIEN - WHERE x2.BASEEURO <> 0 + WHERE x2.BASEEURO <> 0 AND x1.id = vXDiarioFk )sub JOIN ClavesOperacion co ON co.Descripcion = 'Arrendamiento de locales de negocio' @@ -17067,8 +17067,8 @@ BEGIN mci.ClaveOperacionFactura = IF( t.Retencion = 'ARRENDAMIENTO Y SUBARRENDAMIENTO', co.ClaveOperacionFactura_, mci.ClaveOperacionFactura), mci.BaseRetencion = IF (t.Retencion = 'ACTIVIDADES AGRICOLAS O GANADERAS', sub.taxableBase + sub.taxBase, sub.taxableBase), mci.PorRetencion = t.PorcentajeRetencion, - mci.ImporteRetencion = iit.taxableBase * - 1 - WHERE mci.id = vXDiarioFk + mci.ImporteRetencion = iit.taxableBase * - 1 + WHERE mci.id = vXDiarioFk AND e.name = 'Retenciones' AND id.id IS NULL; @@ -17091,10 +17091,10 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceIn_manager`(vYear INT, vCompanyFk INT) BEGIN /** - * Traslada la info de contabilidad relacionada con las facturas recibidas - * + * Traslada la info de contabilidad relacionada con las facturas recibidas + * * @vYear Año contable del que se quiere trasladar la información - * @vCompany Empresa de la que se quiere trasladar datos + * @vCompany Empresa de la que se quiere trasladar datos */ DECLARE vDone BOOL DEFAULT FALSE; DECLARE vInvoiceFk INT; @@ -17106,22 +17106,22 @@ BEGIN DECLARE vAccountTaxOutstanding VARCHAR(10); DECLARE vInvoiceTypeSended VARCHAR(1); DECLARE vCursor CURSOR FOR - SELECT IFNULL(x.CLAVE, x.FACTURA) invoiceInFk, + SELECT IFNULL(x.CLAVE, x.FACTURA) invoiceInFk, x.id XDiarioFk - FROM vn.XDiario x + FROM vn.XDiario x JOIN(SELECT DISTINCT(x.ASIEN) FROM vn.XDiario x LEFT JOIN vn.invoiceIn ii ON x.CLAVE = ii.id LEFT JOIN vn.invoiceInTax it ON it.invoiceInFk = ii.id - WHERE(it.taxTypeSageFk IS NOT NULL OR x.SERIE = vSerialDua COLLATE utf8mb3_unicode_ci) - AND x.enlazadoSage = FALSE + WHERE(it.taxTypeSageFk IS NOT NULL OR x.SERIE = vSerialDua COLLATE utf8mb3_unicode_ci) + AND x.enlazadoSage = FALSE AND x.FECHA BETWEEN vDatedFrom AND vDatedTo - AND x.empresa_id = vCompanyFk + AND x.empresa_id = vCompanyFk ) sub ON sub.ASIEN = x.ASIEN WHERE x.CLAVE IS NOT NULL; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + SELECT CAST(CONCAT(vYear, '-01-01') AS DATETIME), util.dayEnd(CAST(CONCAT(vYear, '-12-31') AS DATE)) INTO vDatedFrom, vDatedTo; @@ -17135,15 +17135,15 @@ BEGIN SELECT codeSage INTO vInvoiceTypeSended FROM invoiceType WHERE `code` ='sended'; - + DROP TEMPORARY TABLE IF EXISTS tmp.invoiceDua; CREATE TEMPORARY TABLE tmp.invoiceDua - SELECT x.id + SELECT x.id FROM vn.XDiario x JOIN vn.company c ON c.id = x.empresa_id JOIN (SELECT ASIEN - FROM vn.XDiario x - WHERE x.enlazadoSage = FALSE + FROM vn.XDiario x + WHERE x.enlazadoSage = FALSE AND x.SUBCTA = vAccountTaxOutstanding COLLATE utf8mb3_unicode_ci AND x.FECHA BETWEEN vDatedFrom AND vDatedTo )sub ON sub.ASIEN = x.ASIEN @@ -17161,7 +17161,7 @@ BEGIN FROM vn.invoiceIn i JOIN vn.currency c ON c.id = i.currencyFk WHERE i.bookEntried BETWEEN vDatedFrom AND vDatedTo - UNION ALL + UNION ALL SELECT d.id, d.code, vSerialDua COLLATE utf8mb3_unicode_ci, @@ -17169,8 +17169,8 @@ BEGIN d.issued, FALSE, '' -- EUROS - FROM vn.dua d - WHERE d.issued IS NOT NULL + FROM vn.dua d + WHERE d.issued IS NOT NULL AND code IS NOT NULL; OPEN vCursor; @@ -17178,7 +17178,7 @@ BEGIN l: LOOP FETCH vCursor INTO vInvoiceFk, vXDiarioFk; - IF vDone THEN + IF vDone THEN LEAVE l; END IF; CALL invoiceIn_add(vInvoiceFk, vXDiarioFk); @@ -17266,21 +17266,21 @@ BEGIN JOIN (SELECT x.ASIEN, x.id FROM vn.XDiario x JOIN(SELECT DISTINCT(x.ASIEN) ASIEN - FROM vn.XDiario x + FROM vn.XDiario x JOIN (SELECT DISTINCT(ASIEN) FROM vn.XDiario x - WHERE SUBCTA LIKE '472%' + WHERE SUBCTA LIKE '472%' AND x.enlazadoSage = FALSE AND x.empresa_id = vCompanyFk AND x.FECHA BETWEEN vDatedFrom AND vDatedTo ) sub ON sub.ASIEN = x.ASIEN WHERE x.SUBCTA LIKE '477%' )sub2 ON sub2.ASIEN = x.ASIEN - WHERE x.CONTRA IS NOT NULL + WHERE x.CONTRA IS NOT NULL AND x.SUBCTA LIKE '477%' GROUP BY x.ASIEN )sub3 ON sub3.ASIEN = x.ASIEN; - + INSERT INTO movContaIVA (`id`, `CodigoDivisa`, @@ -17351,9 +17351,9 @@ BEGIN `FechaGrabacion`, `Intracomunitaria`, `moveData`) - SELECT * + SELECT * FROM tmp.movContaIVA; - + DROP TEMPORARY TABLE tmp.movContaIVA; END ;; @@ -17375,10 +17375,10 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOut_add`(IN vInvoiceOutFk INT, IN vXDiarioFk INT) BEGIN /** - * Traslada la info de contabilidad relacionada con las facturas emitidas - * + * Traslada la info de contabilidad relacionada con las facturas emitidas + * * @vYear Año contable del que se quiere trasladar la información - * @vCompany Empresa de la que se quiere trasladar datos + * @vCompany Empresa de la que se quiere trasladar datos */ DECLARE vDone BOOL DEFAULT FALSE; DECLARE vMaxLengthName INT DEFAULT 35; @@ -17398,12 +17398,12 @@ BEGIN DECLARE vHasCustomsAccountingNote BOOL; DECLARE vCursor CURSOR FOR - SELECT oit.taxableBase, - oit.vat, - pgc.rate, - pgc.mod347, - pgcRE.rate, - oitRE.vat, + SELECT oit.taxableBase, + oit.vat, + pgc.rate, + pgc.mod347, + pgcRE.rate, + oitRE.vat, tc.transactionCode, tc.taxCode, tc.isIntracommunity, @@ -17412,7 +17412,7 @@ BEGIN JOIN vn.pgc ON pgc.code = oit.pgcFk LEFT JOIN vn.pgcEqu e ON e.vatFk = oit.pgcFk LEFT JOIN vn.pgcEqu eRE ON eRE.equFk = oit.pgcFk - LEFT JOIN vn.invoiceOutTax oitRE ON oitRE.invoiceOutFk = oit.invoiceOutFk + LEFT JOIN vn.invoiceOutTax oitRE ON oitRE.invoiceOutFk = oit.invoiceOutFk AND oitRE.pgcFk = e.equFk LEFT JOIN vn.pgc pgcRE ON pgcRE.code = oitRE.pgcFk LEFT JOIN vn.taxCode tc ON tc.code = pgc.code COLLATE 'utf8mb3_unicode_ci' @@ -17428,12 +17428,12 @@ BEGIN WHERE ASIEN = (SELECT ASIEN FROM vn.XDiario WHERE id = vXDiarioFk); SELECT codeSage INTO vInvoiceTypeSended - FROM invoiceType + FROM invoiceType WHERE code = IF(vHasCustomsAccountingNote, 'informative', 'sended'); - + DELETE FROM movContaIVA WHERE id = vXDiarioFk; - + INSERT INTO movContaIVA(id) VALUES (vXDiarioFk); OPEN vCursor; @@ -17450,13 +17450,13 @@ BEGIN vIsIntracommunity, vOperationCode; - IF vDone THEN + IF vDone THEN LEAVE l; END IF; SET vCounter = vCounter + 1; - - CASE vCounter + + CASE vCounter WHEN 1 THEN UPDATE movContaIVA SET BaseIva1 = vBase, @@ -17497,7 +17497,7 @@ BEGIN CodigoTransaccion4 = vTransactionCode, CodigoIva4 = vTaxCode WHERE id = vXDiarioFk; - END CASE; + END CASE; UPDATE movContaIVA SET Exclusion347 = NOT vMod347, @@ -17508,7 +17508,7 @@ BEGIN END LOOP; CLOSE vCursor; - + UPDATE movContaIVA mci JOIN vn.invoiceOut i ON i.id = vInvoiceOutFk LEFT JOIN vn.invoiceCorrection ic ON ic.correctedFk = vInvoiceOutFk @@ -17533,25 +17533,25 @@ BEGIN mci.MantenerAsiento = TRUE, mci.FechaFacturaOriginal = x.FECHA_EX WHERE mci.id = vXDiarioFk; - + SELECT correctedFk INTO vInvoiceOutCorrectedFk FROM vn.invoiceCorrection WHERE correctingFk = vInvoiceOutFk; - - IF vInvoiceOutCorrectedFk THEN + + IF vInvoiceOutCorrectedFk THEN UPDATE movContaIVA mci JOIN vn.invoiceOut i ON i.id = vInvoiceOutCorrectedFk JOIN vn.invoiceCorrection ic ON ic.correctedFk = vInvoiceOutCorrectedFk - JOIN (SELECT SUM(IF(IFNULL(e.vatFk, TRUE), iot.taxableBase, 0)) taxableBase, + JOIN (SELECT SUM(IF(IFNULL(e.vatFk, TRUE), iot.taxableBase, 0)) taxableBase, SUM(IF(IFNULL(e.vatFk, TRUE), iot.vat, 0)) vat, SUM(IF(IFNULL(e.vatFk, TRUE), 0, iot.vat)) equ FROM vn.invoiceOutTax iot - LEFT JOIN vn.pgcEqu e ON e.vatFk = iot.pgcFk + LEFT JOIN vn.pgcEqu e ON e.vatFk = iot.pgcFk WHERE iot.invoiceOutFk = vInvoiceOutCorrectedFk ) tax JOIN ClavesOperacion co ON co.Descripcion = 'Factura rectificativa' SET mci.TipoRectificativa = 2, - mci.ClaseAbonoRectificativas = 1, + mci.ClaseAbonoRectificativas = 1, mci.FechaFacturaOriginal = i.issued, mci.FechaOperacion = i.issued, mci.BaseImponibleOriginal = tax.taxableBase, @@ -17582,10 +17582,10 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOut_manager`(vYear INT, vCompanyFk INT) BEGIN /** - * Traslada la info de contabilidad relacionada con las facturas emitidas - * + * Traslada la info de contabilidad relacionada con las facturas emitidas + * * @vYear Año contable del que se quiere trasladar la información - * @vCompany Empresa de la que se quiere trasladar datos + * @vCompany Empresa de la que se quiere trasladar datos */ DECLARE vDone BOOL DEFAULT FALSE; DECLARE vInvoiceFk INT; @@ -17602,7 +17602,7 @@ BEGIN JOIN (SELECT x.ASIEN, CONCAT(x.SERIE, x.FACTURA) refFk FROM vn.XDiario x WHERE x.enlazadoSage = FALSE - AND x.FACTURA + AND x.FACTURA AND x.empresa_id = vCompanyFk AND x.FECHA BETWEEN vDatedFrom AND vDatedTo GROUP BY refFk @@ -17611,19 +17611,19 @@ BEGIN )sub2 ON sub2.refFk = i.ref; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + SELECT CAST(CONCAT(vYear, '-01-01') AS DATETIME), util.dayEnd(CAST(CONCAT(vYear, '-12-31') AS DATE)) INTO vDatedFrom, vDatedTo; - + OPEN vCursor; l: LOOP FETCH vCursor INTO vInvoiceFk, vXDiarioFk; - IF vDone THEN + IF vDone THEN LEAVE l; END IF; - + CALL invoiceOut_add(vInvoiceFk, vXDiarioFk); END LOOP; @@ -17649,7 +17649,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `pgc_add`(vCompanyFk INT) BEGIN /** - * Añade cuentas del plan general contable para exportarlos a Sage + * Añade cuentas del plan general contable para exportarlos a Sage * @vCompanyFk Empresa de la que se quiere trasladar datos */ TRUNCATE TABLE planCuentasPGC; @@ -17659,25 +17659,25 @@ BEGIN CodigoCuenta, Cuenta, ClienteOProveedor) - SELECT * + SELECT * FROM (SELECT company_getCode(vCompanyFk) companyFk, e.id accountFk, UCASE(e.name), '' FROM vn.expence e - UNION + UNION SELECT company_getCode(vCompanyFk), - b.account, + b.account, UCASE(b.bank), - '' + '' FROM vn.bank b WHERE b.isActive AND b.`account` - UNION + UNION SELECT CodigoEmpresa, CodigoCuenta, Nombre, - ClienteOProveedor + ClienteOProveedor FROM clientesProveedores)sub GROUP BY companyFk, accountFk; END ;; @@ -18026,7 +18026,7 @@ DELIMITER ;; FOR EACH ROW BEGIN SET NEW.isPicked = NEW.isPicked OR NEW.dated < util.VN_CURDATE(); - + CALL visible_log( NEW.isPicked, NEW.warehouseFk, @@ -18150,7 +18150,7 @@ DELIMITER ;; BEGIN SET NEW.lack = NEW.quantity; SET NEW.isPicked = NEW.isPicked OR NEW.dated < util.VN_CURDATE(); - + CALL visible_log( NEW.isPicked, NEW.warehouseFk, @@ -18361,7 +18361,7 @@ BEGIN DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + SET vSupplied = 0; OPEN vPicks; @@ -18377,7 +18377,7 @@ BEGIN SET vPickGranted = LEAST(vRequested - vSupplied, vPickQuantity); SET vSupplied = vSupplied + vPickGranted; CALL inbound_removePick(vSelf, vOutboundFk, vPickGranted, vPickQuantity); - + UPDATE outbound SET isSync = FALSE, lack = lack + vPickGranted @@ -18457,7 +18457,7 @@ BEGIN END IF; SET vSupplied = LEAST(vAvailable, vLack); - + IF vSupplied > 0 THEN SET vAvailable = vAvailable - vSupplied; UPDATE outbound @@ -18470,7 +18470,7 @@ BEGIN SET vSupplied = vSupplied + vSuppliedFromRequest; SET vAvailable = vAvailable - vSuppliedFromRequest; END IF; - + IF vSupplied > 0 THEN CALL inbound_addPick(vSelf, vOutboundFk, vSupplied); END IF; @@ -18599,7 +18599,7 @@ BEGIN DO RELEASE_LOCK('stock.log_sync'); RESIGNAL; END; - + IF !GET_LOCK('stock.log_sync', 30) THEN CALL util.throw('Lock timeout exceeded'); END IF; @@ -19070,7 +19070,7 @@ BEGIN SET vPickGranted = LEAST(vRequested - vSupplied, vPickQuantity); SET vSupplied = vSupplied + vPickGranted; CALL inbound_removePick(vInboundFk, vSelf, vPickGranted, vPickQuantity); - + UPDATE inbound SET isSync = FALSE, available = available + vPickGranted @@ -19510,11 +19510,11 @@ BEGIN WHILE vI < vLen DO SET vSpaceIni = vI; - + WHILE MID(vString, vI, 1) REGEXP '[[:space:]]' DO SET vI = vI + 1; END WHILE; - + SET vWordIni = vI; SET vI = vWordIni + 1; @@ -19551,11 +19551,11 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `crypt`(vText VARCHAR(255), vKey VARC BEGIN DECLARE vResult VARCHAR(255); - + CALL vn.crypt(vText, vKey, vResult); RETURN vResult; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -19577,11 +19577,11 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `cryptOff`(vText VARCHAR(255), vKey V BEGIN DECLARE vResult VARCHAR(255); - + CALL vn.cryptOff(vText, vKey, vResult); RETURN vResult; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -19749,7 +19749,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `hasDateOverlapped`(vSarted1 DATE, vEnded1 DATE, vSarted2 DATE, vEnded2 DATE) RETURNS tinyint(1) DETERMINISTIC -BEGIN +BEGIN RETURN GREATEST(vSarted1, vSarted2) <= LEAST(vEnded1,vEnded2); @@ -19778,7 +19778,7 @@ BEGIN */ DECLARE vHashlen INT UNSIGNED; DECLARE vOpad, vIpad TINYBLOB; - + CASE vAlg WHEN 224 THEN SET vHashlen = 64; WHEN 256 THEN SET vHashlen = 64; @@ -19786,16 +19786,16 @@ BEGIN WHEN 512 THEN SET vHashlen = 128; ELSE CALL throw ('WRONG_ALGORYTHM_IDENTIFICATOR_USED'); END CASE; - + IF LENGTH(vKey) > vHashlen THEN SET vKey = UNHEX(SHA2(vKey, vAlg)); END IF; - + SET vKey = RPAD(vKey, vHashlen, 0x00); - + SET vIpad = stringXor(vKey, 0x36); SET vOpad = stringXor(vKey, 0x5C); - + RETURN SHA2(CONCAT(vOpad, UNHEX(SHA2(CONCAT(vIpad, vMsg), vAlg))), vAlg); END ;; DELIMITER ; @@ -19818,7 +19818,7 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `isLeapYear`(vYear INT) RETURNS tinyi BEGIN RETURN (DAYOFYEAR(CONCAT(vYear, "-02-29")) IS NOT NULL); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -19977,7 +19977,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `midnight`() RETURNS datetime READS SQL DATA BEGIN - + RETURN TIMESTAMP(util.VN_CURDATE(), '23:59:59'); END ;; @@ -20105,7 +20105,7 @@ BEGIN * modo 3. */ DECLARE vYear INT DEFAULT FLOOR(vYearWeek / 100); - + IF vYearWeek < YEARWEEK(CONCAT(vYear, '-12-31'), 3) THEN RETURN vYearWeek + 1; ELSE @@ -20211,16 +20211,16 @@ BEGIN */ DECLARE vLen, vPos INT UNSIGNED; DECLARE vResult MEDIUMBLOB; - + SET vLen = LENGTH(vString); SET vPos = 1; SET vResult = ''; - + WHILE vPos <= vLen DO SET vResult = CONCAT(vResult, LPAD(HEX( ORD(SUBSTR(vString, vPos, 1)) ^ vConst), 2, '0')); SET vPos = vPos + 1; END WHILE; - + RETURN UNHEX(vResult); END ;; DELIMITER ; @@ -20491,11 +20491,11 @@ BEGIN IF vYear = vCurYear THEN RETURN 'curYear'; END IF; - + IF vYear = vCurYear - 1 THEN RETURN 'lastYear'; END IF; - + IF vYear = vCurYear - 2 THEN RETURN 'twoYearsAgo'; END IF; @@ -20578,7 +20578,7 @@ BEGIN * @param vValue Valor de la variable */ DECLARE vIndex INT DEFAULT INSTR(USER(), '@'); - + INSERT INTO debug SET `connectionId` = CONNECTION_ID(), `user` = LEFT(USER(), vIndex - 1), @@ -20981,7 +20981,7 @@ BEGIN INSERT INTO tmp.time (dated) VALUES (vCurrentDate); SET vCurrentDate = DATE_ADD(vCurrentDate, INTERVAL 1 DAY); END WHILE; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -21375,11 +21375,11 @@ BEGIN END IF; IF NEW.isEqualizated IS NULL THEN - SELECT isEqualizated + SELECT isEqualizated INTO vIsEqualizated FROM client WHERE id = NEW.clientFk; - + SET NEW.isEqualizated = vIsEqualizated; END IF; END */;; @@ -21401,7 +21401,7 @@ DELIMITER ;; BEFORE UPDATE ON `address` FOR EACH ROW BEGIN - + SET NEW.editorFk = account.myUser_getId(); IF !(NEW.phone <=> OLD.phone) AND (NEW.phone <> '') THEN @@ -21433,16 +21433,16 @@ DELIMITER ;; BEGIN -- Recargos de equivalencia distintos implican facturacion por consignatario IF NEW.isEqualizated != OLD.isEqualizated THEN - IF + IF (SELECT COUNT(*) FROM ( SELECT DISTINCT (isEqualizated = FALSE) as Equ - FROM address + FROM address WHERE clientFk = NEW.clientFk ) t1 ) > 1 - THEN - UPDATE client + THEN + UPDATE client SET hasToInvoiceByAddress = TRUE WHERE id = NEW.clientFk; END IF; @@ -21450,10 +21450,10 @@ BEGIN IF NEW.isDefaultAddress AND NEW.isActive = FALSE THEN CALL util.throw ('Cannot desactivate the default address'); END IF; - + IF NOT (NEW.isEqualizated <=> OLD.isEqualizated) THEN INSERT IGNORE INTO ticketRecalc (ticketFk) - SELECT id FROM ticket t + SELECT id FROM ticket t WHERE t.addressFk = NEW.id AND t.refFk IS NULL; END IF; @@ -21870,8 +21870,8 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`autonomy_BI` BEFORE INSERT ON `autonomy` FOR EACH ROW -BEGIN - +BEGIN + SET NEW.geoFk = zoneGeo_new('autonomy', NEW.`name`, (SELECT geoFk FROM country WHERE id = NEW.countryFk)); END */;; @@ -21921,7 +21921,7 @@ DELIMITER ;; AFTER DELETE ON `autonomy` FOR EACH ROW BEGIN - CALL zoneGeo_delete(OLD.geoFk); + CALL zoneGeo_delete(OLD.geoFk); END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -21996,7 +21996,7 @@ DELIMITER ;; BEFORE INSERT ON `awb` FOR EACH ROW BEGIN - + SET NEW.year= year(util.VN_CURDATE()); @@ -22370,11 +22370,11 @@ DELIMITER ;; BEFORE INSERT ON `budgetNotes` FOR EACH ROW BEGIN - + IF ISNULL(NEW.userFk) THEN - + SET NEW.userFk = account.myUser_getId(); - + END IF; END */;; @@ -22468,7 +22468,7 @@ DELIMITER ;; FOR EACH ROW BEGIN SET NEW.editorFk = account.myUser_getId(); - + IF NEW.ended IS NULL THEN SET NEW.payedHolidays = 0; END IF; @@ -22514,25 +22514,25 @@ BEGIN DECLARE isOverlapping BOOL; SET NEW.editorFk = account.myUser_getId(); - + IF NEW.ended IS NULL THEN SET NEW.payedHolidays = 0; END IF; IF !(OLD.started <=> NEW.started AND OLD.ended <=> NEW.ended) THEN - + SELECT COUNT(*) > 0 INTO isOverlapping FROM business b WHERE (util.hasDateOverlapped( - NEW.started, + NEW.started, IFNULL(NEW.ended, b.started), b.started, IFNULL(b.ended, NEW.started)) OR (NEW.ended <=> NULL AND b.ended <=> NULL)) AND b.id <> OLD.id AND workerFk = OLD.workerFk; - - IF isOverlapping THEN + + IF isOverlapping THEN CALL util.throw ('IS_OVERLAPPING'); END IF; @@ -22793,7 +22793,7 @@ trig: BEGIN END IF; END IF; IF NEW.quantity < 0 THEN - SET NEW.isIgnored = TRUE; + SET NEW.isIgnored = TRUE; END IF; END */;; DELIMITER ; @@ -22988,7 +22988,7 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`buy_beforeDelete` BEFORE DELETE ON buy FOR EACH ROW -BEGIN +BEGIN IF OLD.printedStickers <> 0 THEN CALL util.throw("it is not possible to delete buys with printed labels "); END IF; @@ -24192,7 +24192,7 @@ BEGIN END IF; SET NEW.accountingAccount = 4300000000 + NEW.id; - + SET NEW.lastSalesPersonFk = NEW.salesPersonFk; END */;; DELIMITER ; @@ -24217,7 +24217,7 @@ BEGIN DECLARE vPayMethodFk INT; SET NEW.editorFk = account.myUser_getId(); - + -- Comprueba que el formato de los teléfonos es válido IF !(NEW.phone <=> OLD.phone) AND (NEW.phone <> '') THEN @@ -24299,18 +24299,18 @@ BEGIN IF !(NEW.defaultAddressFk <=> OLD.defaultAddressFk) THEN UPDATE `address` SET isDefaultAddress = 0 WHERE clientFk = NEW.id; - + UPDATE `address` SET isDefaultAddress = 1 - WHERE id = NEW.defaultAddressFk; + WHERE id = NEW.defaultAddressFk; END IF; IF NOT (NEW.provinceFk <=> OLD.provinceFk) OR NOT (NEW.isVies <=> OLD.isVies) THEN INSERT IGNORE INTO ticketRecalc (ticketFk) - SELECT id FROM ticket t + SELECT id FROM ticket t WHERE t.clientFk = NEW.id AND t.refFk IS NULL; END IF; - + IF NOT NEW.isActive THEN UPDATE account.`user` SET active = FALSE @@ -24506,15 +24506,15 @@ DELIMITER ;; AFTER INSERT ON clientCredit FOR EACH ROW BEGIN - + DECLARE vSender VARCHAR(50); SELECT u.name INTO vSender FROM account.`user` u WHERE u.id = NEW.workerFk; - + IF vSender IN ('juanvi','pepe') THEN - + CALL `vn`.`mail_insert`('pako@verdnatura.es', NULL, CONCAT('ClientCredit ',vSender, ' ', NEW.clientFk, ' ' , NEW.amount, ' €'), @@ -25095,7 +25095,7 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`cmr_beforeDelete` BEFORE DELETE ON `cmr` FOR EACH ROW -BEGIN +BEGIN IF NOT (OLD.companyFk <=> NULL AND OLD.addressFromFk <=> NULL AND OLD.packagesList <=> NULL) THEN CALL util.throw("Can not delete cmr, fields required not empty"); END IF; @@ -25226,39 +25226,39 @@ CREATE TABLE `collection` ( /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`collection_BEFORE_UPDATE` - BEFORE UPDATE ON `collection` - FOR EACH ROW -BEGIN - - DECLARE vStateFk INT; - DECLARE vTotalLines INT; - DECLARE vPickedLines INT; - - IF NEW.saleTotalCount <= NEW.salePickedCount - AND (NEW.saleTotalCount != OLD.saleTotalCount - OR NEW.salePickedCount != OLD.salePickedCount) - THEN - - SELECT id INTO vStateFk - FROM vn.state - WHERE code = 'PREPARED'; - - SET NEW.stateFk = vStateFk; - - END IF; - - IF NEW.saleTotalCount > NEW.salePickedCount - AND (NEW.saleTotalCount != OLD.saleTotalCount OR NEW.salePickedCount != OLD.salePickedCount) THEN - - SELECT id INTO vStateFk - FROM vn.state - WHERE code = 'ON_PREPARATION'; - - SET NEW.stateFk = vStateFk; - - END IF; - +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`collection_BEFORE_UPDATE` + BEFORE UPDATE ON `collection` + FOR EACH ROW +BEGIN + + DECLARE vStateFk INT; + DECLARE vTotalLines INT; + DECLARE vPickedLines INT; + + IF NEW.saleTotalCount <= NEW.salePickedCount + AND (NEW.saleTotalCount != OLD.saleTotalCount + OR NEW.salePickedCount != OLD.salePickedCount) + THEN + + SELECT id INTO vStateFk + FROM vn.state + WHERE code = 'PREPARED'; + + SET NEW.stateFk = vStateFk; + + END IF; + + IF NEW.saleTotalCount > NEW.salePickedCount + AND (NEW.saleTotalCount != OLD.saleTotalCount OR NEW.salePickedCount != OLD.salePickedCount) THEN + + SELECT id INTO vStateFk + FROM vn.state + WHERE code = 'ON_PREPARATION'; + + SET NEW.stateFk = vStateFk; + + END IF; + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -26194,7 +26194,7 @@ BEGIN UPDATE `client` c JOIN vn.creditClassification cc ON cc.client = c.id SET creditInsurance = NEW.credit WHERE cc.id = NEW.creditClassification; - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -26463,7 +26463,7 @@ BEGIN JOIN vn.department d ON d.id = b.departmentFk SET b.departmentFk = d.parentFk WHERE b.departmentFk = OLD.id; - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -26483,9 +26483,9 @@ DELIMITER ;; AFTER DELETE ON `department` FOR EACH ROW BEGIN - + UPDATE vn.department_recalc SET isChanged = TRUE; - + UPDATE vn.business b JOIN vn.department d ON d.id = b.departmentFk SET b.departmentFk = d.parentFk @@ -26988,20 +26988,20 @@ DELIMITER ;; BEGIN DECLARE vHardCopyNumber INT; DECLARE vDmsTypeCode INT; - + IF (SELECT NOT hasDms FROM warehouse WHERE id = NEW.warehouseFk) THEN CALL util.throw('this warehouse has not dms'); END IF; IF NEW.hasFile THEN - SELECT 1 + MAX(hardCopyNumber) INTO vHardCopyNumber - FROM dms + SELECT 1 + MAX(hardCopyNumber) INTO vHardCopyNumber + FROM dms WHERE warehouseFk = NEW.warehouseFk; - + SET NEW.hardCopyNumber = IFNULL(vHardCopyNumber,1); END IF; - - SELECT code INTO vDmsTypeCode + + SELECT code INTO vDmsTypeCode FROM dmsType WHERE NEW.dmsTypeFk = id; IF (vDmsTypeCode ='ticket') THEN UPDATE ticket SET isSigned = 1 WHERE id = NEW.reference; @@ -27021,31 +27021,31 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`dms_beforeUpdate` - BEFORE UPDATE ON `dms` - FOR EACH ROW -BEGIN - DECLARE vHardCopyNumber INT; - - IF (NEW.hasFile <> 0) AND (OLD.hasFile = 0) AND (NEW.hardCopyNumber IS NULL) - OR - (NEW.hardCopyNumber = OLD.hardCopyNumber AND OLD.warehouseFk <> NEW.warehouseFk) THEN - - IF (SELECT NOT hasDms FROM warehouse WHERE id = NEW.warehouseFk) THEN - SET NEW.warehouseFk = (SELECT id FROM warehouse WHERE name = 'Algemesi'); - END IF; - - SELECT 1 + MAX(hardCopyNumber) INTO vHardCopyNumber - FROM dms - WHERE warehouseFk = NEW.warehouseFk; - - SET NEW.hardCopyNumber = IFNULL(vHardCopyNumber,1); - END IF; - - IF ((NEW.hardCopyNumber = 0) OR NEW.hardCopyNumber IS NULL) AND (OLD.hardCopyNumber <> 0) THEN - - SET NEW.hasFile = 0; - END IF; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`dms_beforeUpdate` + BEFORE UPDATE ON `dms` + FOR EACH ROW +BEGIN + DECLARE vHardCopyNumber INT; + + IF (NEW.hasFile <> 0) AND (OLD.hasFile = 0) AND (NEW.hardCopyNumber IS NULL) + OR + (NEW.hardCopyNumber = OLD.hardCopyNumber AND OLD.warehouseFk <> NEW.warehouseFk) THEN + + IF (SELECT NOT hasDms FROM warehouse WHERE id = NEW.warehouseFk) THEN + SET NEW.warehouseFk = (SELECT id FROM warehouse WHERE name = 'Algemesi'); + END IF; + + SELECT 1 + MAX(hardCopyNumber) INTO vHardCopyNumber + FROM dms + WHERE warehouseFk = NEW.warehouseFk; + + SET NEW.hardCopyNumber = IFNULL(vHardCopyNumber,1); + END IF; + + IF ((NEW.hardCopyNumber = 0) OR NEW.hardCopyNumber IS NULL) AND (OLD.hardCopyNumber <> 0) THEN + + SET NEW.hasFile = 0; + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -27064,14 +27064,14 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`dms_beforeDelete` BEFORE DELETE ON `dms` FOR EACH ROW -BEGIN +BEGIN DECLARE vCanNotBeDeleted INT; - SELECT COUNT(*) INTO vCanNotBeDeleted - FROM dmsType dt - WHERE NOT (code <=> 'trash') + SELECT COUNT(*) INTO vCanNotBeDeleted + FROM dmsType dt + WHERE NOT (code <=> 'trash') AND dt.id = OLD.dmsTypeFk; - - IF vCanNotBeDeleted THEN + + IF vCanNotBeDeleted THEN CALL util.throw('A dms can not be deleted'); END IF; END */;; @@ -27649,7 +27649,7 @@ BEGIN END IF; IF NOT (NEW.travelFk <=> OLD.travelFk) - OR NOT (NEW.currencyFk <=> OLD.currencyFk) THEN + OR NOT (NEW.currencyFk <=> OLD.currencyFk) THEN SET NEW.commission = entry_getCommission(NEW.travelFk, NEW.currencyFk,NEW.supplierFk); END IF; END */;; @@ -28149,17 +28149,17 @@ BEGIN SET NEW.editorFk = account.myUser_getId(); - IF NEW.freightItemFk IS NOT NULL THEN + IF NEW.freightItemFk IS NOT NULL THEN UPDATE ticket SET packages = nz(packages) + 1 WHERE id = NEW.ticketFk; - SELECT IFNULL(MAX(counter),0) +1 INTO intcounter - FROM expedition e - INNER JOIN ticket t1 ON e.ticketFk = t1.id + SELECT IFNULL(MAX(counter),0) +1 INTO intcounter + FROM expedition e + INNER JOIN ticket t1 ON e.ticketFk = t1.id LEFT JOIN ticketState ts ON ts.ticket = t1.id - INNER JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped) + INNER JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped) AND t1.warehouseFk = t2.warehouseFk - WHERE t2.id = NEW.ticketFk AND ts.alertLevel < 3 AND t1.companyFk = t2.companyFk + WHERE t2.id = NEW.ticketFk AND ts.alertLevel < 3 AND t1.companyFk = t2.companyFk AND t1.agencyModeFk = t2.agencyModeFk; SET NEW.`counter` = intcounter; @@ -28186,9 +28186,9 @@ BEGIN SET NEW.editorFk = account.myUser_getId(); IF NEW.counter <> OLD.counter THEN - IF (SELECT COUNT(*) FROM expedition e + IF (SELECT COUNT(*) FROM expedition e INNER JOIN ticket t1 ON e.ticketFk = t1.id - INNER JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped) + INNER JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped) WHERE t1.id = NEW.ticketFk AND counter = NEW.counter) > 0 THEN SET NEW.id = NULL; END IF; @@ -28212,11 +28212,11 @@ DELIMITER ;; BEFORE DELETE ON `expedition` FOR EACH ROW BEGIN - UPDATE ticket t - SET packages = (SELECT COUNT(counter)-1 + UPDATE ticket t + SET packages = (SELECT COUNT(counter)-1 FROM expedition e WHERE e.ticketFk = OLD.ticketFk and e.freightItemFk) - WHERE t.id = OLD.ticketFk; - + WHERE t.id = OLD.ticketFk; + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -28355,13 +28355,13 @@ DELIMITER ;; BEGIN DECLARE vNewPosition INT; - + SELECT MAX(position) + 1 INTO vNewPosition FROM vn.expeditionPallet WHERE truckFk = NEW.truckFk; - + SET NEW.position = IFNULL(vNewPosition,1); - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -28460,7 +28460,7 @@ DELIMITER ;; BEGIN SET NEW.workerFk = vn.getUser(); - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -28521,9 +28521,9 @@ DELIMITER ;; BEFORE INSERT ON expeditionState FOR EACH ROW BEGIN - + SET NEW.userFk = account.myUser_getId(); - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -28547,7 +28547,7 @@ BEGIN UPDATE vn.expedition e SET e.stateTypeFk = NEW.typeFk WHERE e.id = NEW.expeditionFk; - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -29578,42 +29578,42 @@ BEGIN DECLARE vWithholdingSageFk INT; SET NEW.editorFk = account.myUser_getId(); - - SELECT withholdingSageFk INTO vWithholdingSageFk - FROM vn.supplier + + SELECT withholdingSageFk INTO vWithholdingSageFk + FROM vn.supplier WHERE id = NEW.supplierFk; - SET NEW.withholdingSageFk = vWithholdingSageFk; - - SELECT countryFk, isActive INTO vIssuingCountry, vActive - FROM vn.supplier + SET NEW.withholdingSageFk = vWithholdingSageFk; + + SELECT countryFk, isActive INTO vIssuingCountry, vActive + FROM vn.supplier WHERE id = NEW.supplierFk; - - SELECT countryFk INTO vhostCountry - FROM vn.supplier + + SELECT countryFk INTO vhostCountry + FROM vn.supplier WHERE id = NEW.companyFk; IF vActive = 0 THEN CALL util.throw('INACTIVE_PROVIDER'); END IF; - - IF (SELECT COUNT(*) FROM vn.invoiceIn - WHERE supplierRef = NEW.supplierRef - AND supplierFk = NEW.supplierFk + + IF (SELECT COUNT(*) FROM vn.invoiceIn + WHERE supplierRef = NEW.supplierRef + AND supplierFk = NEW.supplierFk AND YEAR(issued) = YEAR(NEW.issued) ) THEN CALL util.throw('reference duplicated'); END IF; - + SELECT CASE WHEN (SELECT account FROM vn.supplier where id = NEW.supplierFk) LIKE '___3______' THEN 'C' - WHEN (SELECT vIssuingCountry=vhostCountry from vn.country p1 join vn.country p2 ON p2.id = vhostCountry AND p1.id = vIssuingCountry + WHEN (SELECT vIssuingCountry=vhostCountry from vn.country p1 join vn.country p2 ON p2.id = vhostCountry AND p1.id = vIssuingCountry where p1.CEE < 2 and p2.CEE < 2) = 1 THEN 'R' - WHEN (SELECT vIssuingCountry <> vhostCountry from vn.country p1 join vn.country p2 ON p2.id = vhostCountry AND p1.id = vIssuingCountry - where p1.CEE < 2 and p2.CEE < 2) = 1 THEN 'E' + WHEN (SELECT vIssuingCountry <> vhostCountry from vn.country p1 join vn.country p2 ON p2.id = vhostCountry AND p1.id = vIssuingCountry + where p1.CEE < 2 and p2.CEE < 2) = 1 THEN 'E' WHEN (SELECT vIssuingCountry<>vhostCountry from vn.country p1 join vn.country p2 ON p2.id = vhostCountry AND p1.id = vIssuingCountry - where NOT p1.CEE < 2 AND not p1.id = 1) = 1 THEN 'W' + where NOT p1.CEE < 2 AND not p1.id = 1) = 1 THEN 'W' END INTO vSerie; - + SET NEW.serial = IFNULL(vSerie,'R'); END */;; @@ -29640,9 +29640,9 @@ BEGIN SET NEW.editorFk = account.myUser_getId(); - IF (SELECT COUNT(*) FROM vn.invoiceIn - WHERE supplierRef = NEW.supplierRef - AND supplierFk = NEW.supplierFk + IF (SELECT COUNT(*) FROM vn.invoiceIn + WHERE supplierRef = NEW.supplierRef + AND supplierFk = NEW.supplierFk AND YEAR(issued) = YEAR(NEW.issued) AND id <> NEW.id ) THEN @@ -29652,7 +29652,7 @@ BEGIN IF NEW.supplierFk != OLD.supplierFk THEN CALL supplier_checkIsActive(NEW.supplierFk); SELECT withholdingSageFk INTO vWithholdingSageFk - FROM vn.supplier + FROM vn.supplier WHERE id = NEW.supplierFk; SET NEW.withholdingSageFk = vWithholdingSageFk; END IF; @@ -29677,23 +29677,23 @@ DELIMITER ;; FOR EACH ROW BEGIN - IF NEW.issued != OLD.issued + IF NEW.issued != OLD.issued OR NEW.currencyFk != OLD.currencyFk THEN UPDATE invoiceInTax iit JOIN invoiceIn ii ON ii.id = iit.invoiceInFk LEFT JOIN referenceRate rr ON rr.dated = ii.issued - AND rr.currencyFk = ii.currencyFk + AND rr.currencyFk = ii.currencyFk SET iit.taxableBase = IF(iit.foreignValue IS NULL, iit.taxableBase, iit.foreignValue / rr.value) WHERE ii.id = NEW.id; - + UPDATE invoiceInDueDay iidd JOIN invoiceIn ii ON ii.id = iidd.invoiceInFk LEFT JOIN referenceRate rr ON rr.dated = ii.issued - AND rr.currencyFk = ii.currencyFk + AND rr.currencyFk = ii.currencyFk SET iidd.amount = IF(iidd.foreignValue IS NULL, iidd.amount, iidd.foreignValue / rr.value) - WHERE ii.id = NEW.id; - + WHERE ii.id = NEW.id; + END IF; END */;; @@ -29787,13 +29787,13 @@ BEGIN DECLARE vIsNotified BOOLEAN; SET NEW.editorFk = account.myUser_getId(); - - SELECT isNotified INTO vIsNotified - FROM vn.invoiceIn ii + + SELECT isNotified INTO vIsNotified + FROM vn.invoiceIn ii JOIN vn.supplier s ON s.id = ii.supplierFk JOIN vn.payMethod pm ON pm.id = s.payMethodFk WHERE ii.id = NEW.invoiceInFk; - + IF (NEW.dueDated <= util.VN_CURDATE() AND vIsNotified) THEN CALL mail_insert( @@ -29801,12 +29801,12 @@ BEGIN 'begonya@verdnatura.es', 'Añadido vencimiento en el pasado', CONCAT( - account.myUser_getName(), ' ha añadido un vencimiento de ', + account.myUser_getName(), ' ha añadido un vencimiento de ', NEW.amount, '€ en una fecha pasada en la recibida ', NEW.invoiceInFk ) ); END IF; - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -29829,13 +29829,13 @@ BEGIN DECLARE vIsNotified BOOLEAN; SET NEW.editorFk = account.myUser_getId(); - - SELECT isNotified INTO vIsNotified - FROM vn.invoiceIn ii + + SELECT isNotified INTO vIsNotified + FROM vn.invoiceIn ii JOIN vn.supplier s ON s.id = ii.supplierFk JOIN vn.payMethod pm ON pm.id = s.payMethodFk WHERE ii.id = NEW.invoiceInFk; - + IF (NEW.dueDated <= util.VN_CURDATE() AND vIsNotified) THEN CALL mail_insert( @@ -29843,12 +29843,12 @@ BEGIN 'begonya@verdnatura.es', 'Añadido vencimiento en el pasado', CONCAT( - account.myUser_getName(), ' ha añadido un vencimiento de ', + account.myUser_getName(), ' ha añadido un vencimiento de ', NEW.amount,'€ en una fecha pasada en la recibida ',NEW.invoiceInFk ) ); END IF; - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -30984,15 +30984,15 @@ BEGIN IF NEW.itemFk IN (95, 98) THEN SET NEW.cm3 = 0; END IF; - + IF !(NEW.cm3delivery <=> OLD.cm3delivery) THEN INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) - SELECT r.id + SELECT r.id FROM vn.itemCost ic JOIN vn.sale s ON s.itemFk = ic.itemFk - JOIN vn.ticket t ON t.id = s.ticketFk AND t.warehouseFk = ic.warehouseFk + JOIN vn.ticket t ON t.id = s.ticketFk AND t.warehouseFk = ic.warehouseFk JOIN vn.route r ON r.id = t.routeFk - WHERE r.isOk = FALSE + WHERE r.isOk = FALSE AND ic.itemFk = NEW.itemFk AND r.created >= util.VN_CURDATE() GROUP BY r.id; @@ -31312,10 +31312,10 @@ DELIMITER ;; BEFORE INSERT ON `itemShelving` FOR EACH ROW BEGIN - + SET NEW.userFk = account.myUser_getId(); - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -31424,8 +31424,8 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemShelving_BEFORE_DELETE` BEFORE DELETE ON `itemShelving` FOR EACH ROW -INSERT INTO vn.itemShelvingLog(itemShelvingFk, - workerFk, +INSERT INTO vn.itemShelvingLog(itemShelvingFk, + workerFk, accion, shelvingFk, itemFk) @@ -31609,7 +31609,7 @@ DELIMITER ;; BEGIN UPDATE vn.sale - SET isPicked = TRUE + SET isPicked = TRUE WHERE id = NEW.saleFk; END */;; @@ -31799,9 +31799,9 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemTag_beforeUpdate` BEFORE UPDATE ON `itemTag` FOR EACH ROW -BEGIN +BEGIN SET NEW.editorFk = account.myUser_getId(); - + IF !(OLD.`value` <=> NEW.`value`) OR !(OLD.intValue <=> NEW.intValue) THEN SET NEW.intValue = itemTag_getIntValue(NEW.`value`); @@ -31834,7 +31834,7 @@ trig: BEGIN IF @isTriggerDisabled OR visTriggerDisabled THEN LEAVE trig; END IF; - + SET vItemFk = NEW.itemFk; DROP TEMPORARY TABLE IF EXISTS tmp.item; CREATE TEMPORARY TABLE tmp.item @@ -32341,7 +32341,7 @@ DELIMITER ;; BEFORE INSERT ON `machine` FOR EACH ROW BEGIN - + SET NEW.workerFk = vn.getUser(); END */;; @@ -32475,9 +32475,9 @@ DELIMITER ;; BEGIN IF NEW.sender IS NOT NULL THEN - + SET NEW.receiver = NEW.sender; - + END IF; END */;; @@ -32540,8 +32540,8 @@ DELIMITER ;; FOR EACH ROW BEGIN IF (NEW.code IS NULL) THEN - SET NEW.code=CONCAT(NEW.clientFk,'-',(SELECT AUTO_INCREMENT - FROM information_schema.TABLES + SET NEW.code=CONCAT(NEW.clientFk,'-',(SELECT AUTO_INCREMENT + FROM information_schema.TABLES WHERE TABLE_SCHEMA='vn' and TABLE_NAME='mandate')); END IF; END */;; @@ -33535,7 +33535,7 @@ DELIMITER ;; BEGIN -- SET new.`code` = CONCAT(new.`column`,' - ',new.`row`) ; - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -33660,13 +33660,13 @@ BEGIN SELECT account INTO cuenta_banco FROM bank WHERE id = NEW.bankFk; - + SELECT account INTO cuenta_proveedor FROM supplier WHERE id = NEW.supplierFk; - + CALL vn.ledger_next(vNewBookEntry); - + INSERT INTO XDiario ( ASIEN, FECHA, SUBCTA, @@ -33692,7 +33692,7 @@ BEGIN cuenta_banco CONTRA, NEW.amount EURODEBE, 0 EUROHABER) gf; - + IF NEW.bankingFees <> 0 THEN INSERT INTO XDiario ( ASIEN, FECHA, @@ -33714,7 +33714,7 @@ BEGIN FROM supplier s JOIN country c ON s.countryFk = c.id WHERE s.id = NEW.supplierFk; - END IF; + END IF; END IF; SET NEW.dueDated = IFNULL(NEW.dueDated, NEW.received); @@ -33722,15 +33722,15 @@ BEGIN SELECT isActive INTO isSupplierActive FROM supplier WHERE id = NEW.supplierFk; - + IF isSupplierActive = FALSE THEN CALL util.throw('SUPPLIER_INACTIVE'); END IF; - + IF ISNULL(NEW.workerFk) THEN SET NEW.workerFk = account.myUser_getId(); END IF; - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -33752,12 +33752,12 @@ DELIMITER ;; BEGIN DECLARE vIsPayMethodChecked BOOLEAN; DECLARE vEmail VARCHAR(150); - + SELECT isPayMethodChecked INTO vIsPayMethodChecked FROM supplier WHERE id = NEW.supplierFk; - - + + IF vIsPayMethodChecked = FALSE THEN SELECT notificationEmail INTO vEmail @@ -34639,11 +34639,11 @@ DELIMITER ;; BEFORE INSERT ON projectNotes FOR EACH ROW BEGIN - + IF ISNULL(NEW.userFk) THEN - + SET NEW.userFk = account.myUser_getId(); - + END IF; END */;; @@ -34804,10 +34804,10 @@ DELIMITER ;; BEFORE INSERT ON `province` FOR EACH ROW BEGIN - + SET NEW.geoFk = zoneGeo_new('province', NEW.`name`, (SELECT geoFk FROM autonomy WHERE id = NEW.autonomyFk)); - + SET NEW.countryFk = (SELECT a.countryFk FROM vn.autonomy a WHERE a.id = NEW.autonomyFk); END */;; @@ -34828,14 +34828,14 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`province_beforeUpdate` BEFORE UPDATE ON `province` FOR EACH ROW -BEGIN - +BEGIN + IF !(OLD.autonomyFk <=> NEW.autonomyFk) THEN - + SET NEW.countryFk = (SELECT a.countryFk FROM vn.autonomy a WHERE a.id = NEW.autonomyFk); END IF; - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -34851,19 +34851,19 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`province_afterUpdate` - AFTER UPDATE ON `province` - FOR EACH ROW -BEGIN - IF !(OLD.autonomyFk <=> NEW.autonomyFk) THEN - CALL zoneGeo_setParent(NEW.geoFk, - (SELECT geoFk FROM autonomy WHERE id = NEW.autonomyFk)); - END IF; - - IF !(OLD.`name` <=> NEW.`name`) THEN - UPDATE zoneGeo SET `name` = NEW.`name` - WHERE id = NEW.geoFk; - END IF; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`province_afterUpdate` + AFTER UPDATE ON `province` + FOR EACH ROW +BEGIN + IF !(OLD.autonomyFk <=> NEW.autonomyFk) THEN + CALL zoneGeo_setParent(NEW.geoFk, + (SELECT geoFk FROM autonomy WHERE id = NEW.autonomyFk)); + END IF; + + IF !(OLD.`name` <=> NEW.`name`) THEN + UPDATE zoneGeo SET `name` = NEW.`name` + WHERE id = NEW.geoFk; + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -34883,7 +34883,7 @@ DELIMITER ;; AFTER DELETE ON `province` FOR EACH ROW BEGIN - CALL zoneGeo_delete(OLD.geoFk); + CALL zoneGeo_delete(OLD.geoFk); END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -35107,20 +35107,20 @@ CREATE TABLE `receipt` ( /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`receipt_beforeInsert` - BEFORE INSERT ON `receipt` - FOR EACH ROW -BEGIN - DECLARE vIsAutoConciliated BOOLEAN; - - IF NEW.isConciliate = FALSE THEN - SELECT isAutoConciliated INTO vIsAutoConciliated - FROM accounting a - JOIN accountingType at2 ON at2.id = a.accountingTypeFk - WHERE a.id = NEW.bankFk; - - SET NEW.isConciliate = vIsAutoConciliated; - END IF; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`receipt_beforeInsert` + BEFORE INSERT ON `receipt` + FOR EACH ROW +BEGIN + DECLARE vIsAutoConciliated BOOLEAN; + + IF NEW.isConciliate = FALSE THEN + SELECT isAutoConciliated INTO vIsAutoConciliated + FROM accounting a + JOIN accountingType at2 ON at2.id = a.accountingTypeFk + WHERE a.id = NEW.bankFk; + + SET NEW.isConciliate = vIsAutoConciliated; + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -35176,18 +35176,18 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`receipt_afterUpdate` - AFTER UPDATE ON `receipt` - FOR EACH ROW -BEGIN - IF NEW.isConciliate = FALSE AND NEW.payed > OLD.payed THEN - CALL mail_insert( - 'finanzas@verdnatura.es', - NULL, - CONCAT('Cambios de recibos del cliente: ', NEW.clientFk), - CONCAT('Se ha cambiado el recibo: ', NEW.Id, ' de ', OLD.payed, ' a ', NEW.payed) - ); - END IF; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`receipt_afterUpdate` + AFTER UPDATE ON `receipt` + FOR EACH ROW +BEGIN + IF NEW.isConciliate = FALSE AND NEW.payed > OLD.payed THEN + CALL mail_insert( + 'finanzas@verdnatura.es', + NULL, + CONCAT('Cambios de recibos del cliente: ', NEW.clientFk), + CONCAT('Se ha cambiado el recibo: ', NEW.Id, ' de ', OLD.payed, ' a ', NEW.payed) + ); + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -35535,7 +35535,7 @@ BEGIN DECLARE vDefaultAgencyModeFk INT; SET NEW.editorFk = account.myUser_getId(); - + SET NEW.commissionWorkCenterFk = ( SELECT IFNULL(b.workCenterFK, r.defaultWorkCenterFk) FROM vn.routeConfig r @@ -35569,7 +35569,7 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`route_afterInsert` AFTER INSERT ON `route` FOR EACH ROW -BEGIN +BEGIN CALL route_calcCommission(NEW.id); END */;; DELIMITER ; @@ -35591,16 +35591,16 @@ DELIMITER ;; FOR EACH ROW BEGIN DECLARE vKmMax INT; - + SET NEW.editorFk = account.myUser_getId(); - + IF NEW.isOk <> FALSE AND OLD.isOk = FALSE THEN - SET NEW.m3 = ( SELECT SUM(litros)/1000 - FROM vn.saleVolume s - JOIN vn.ticket t ON s.ticketFk = t.id + SET NEW.m3 = ( SELECT SUM(litros)/1000 + FROM vn.saleVolume s + JOIN vn.ticket t ON s.ticketFk = t.id WHERE t.routeFk = NEW.id); END IF; - + IF NEW.kmEnd < NEW.kmStart AND NEW.kmEnd <> 0 THEN CALL util.throw ('KmEnd menor que kmStart'); END IF; @@ -35630,18 +35630,18 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`route_afterUpdate` AFTER UPDATE ON `route` FOR EACH ROW -BEGIN +BEGIN IF IFNULL(NEW.gestdocFk,0) <> IFNULL(OLD.gestdocFk,0) AND NEW.gestdocFk > 0 THEN -- JGF 09/09/14 cuando se añade un gestdoc a una ruta, se le asigna automagicamente a todos sus Tickets - + -- Inserta el gestdoc en todos los tickets de la ruta INSERT INTO ticketDms(ticketFk,dmsFk) SELECT id, NEW.gestdocFk FROM ticket WHERE routeFk = NEW.id ON DUPLICATE KEY UPDATE dmsFk = NEW.gestdocFk; - -- Update del firmado - UPDATE ticket t - JOIN ticketDms tg ON t.id = tg.ticketFk + -- Update del firmado + UPDATE ticket t + JOIN ticketDms tg ON t.id = tg.ticketFk SET isSigned = 1 WHERE t.routeFk = NEW.id; END IF; @@ -36099,20 +36099,20 @@ DELIMITER ;; BEFORE UPDATE ON `sale` FOR EACH ROW BEGIN -/* +/* IF (SELECT COUNT(*) from item i WHERE id = NEW.itemFk AND family = 'SER') THEN CALL util.throw('Cannot insert a service item into a ticket'); END IF; */ SET NEW.editorFk = account.myUser_getId(); - + IF NEW.discount > 100 THEN SET NEW.discount = 0; END IF; IF old.discount > 0 AND NEW.discount = 0 THEN INSERT INTO ticketLog - SET originFk = NEW.ticketFk, userFk = account.myUser_getId(), `action` = 'insert', + SET originFk = NEW.ticketFk, userFk = account.myUser_getId(), `action` = 'insert', description = CONCAT('Cambio de descuento del item :', ' ', new.itemFk, ' de ', old.discount ,' a 0 '); END IF; END */;; @@ -36244,11 +36244,11 @@ DELIMITER ;; BEGIN IF OLD.quantity > 0 THEN INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) - SELECT r.id + SELECT r.id FROM vn.sale s JOIN vn.ticket t ON t.id = s.ticketFk JOIN vn.route r ON r.id = t.routeFk - WHERE r.isOk = FALSE + WHERE r.isOk = FALSE AND s.id = OLD.id AND r.created >= util.VN_CURDATE() GROUP BY r.id; @@ -36350,10 +36350,10 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`BEFORE_INSERT` BEFORE INSERT ON `saleBuy` FOR EACH ROW -BEGIN - +BEGIN + SET NEW.workerFk = vn.getUser(); - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -36372,13 +36372,13 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`saleBuy_AI` AFTER INSERT ON `saleBuy` FOR EACH ROW -BEGIN +BEGIN /* Activar de nuevo cuando volvamos a vender fruta y verdura - * + * UPDATE vn.sale s SET s.concept = CONCAT(s.concept, ' Lote: ', NEW.buyFk) WHERE s.id = NEW.saleFk; -*/ +*/ END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -36644,14 +36644,14 @@ DELIMITER ;; AFTER INSERT ON `saleTracking` FOR EACH ROW BEGIN - - IF NEW.isChecked THEN - + + IF NEW.isChecked THEN + UPDATE vn.sale s - SET s.isPicked = TRUE + SET s.isPicked = TRUE WHERE s.id = NEW.saleFk AND s.isPicked = 0; - + END IF; END */;; @@ -37037,9 +37037,9 @@ BEGIN IF NEW.workerFk = NEW.workerSubstitute THEN CALL util.throw ('worker and workerSubstitute must be different'); ELSE - INSERT IGNORE INTO sharingCartDaily (ownerFk, substituteFk, dated) - SELECT NEW.workerFk, NEW.workerSubstitute, dated - FROM time + INSERT IGNORE INTO sharingCartDaily (ownerFk, substituteFk, dated) + SELECT NEW.workerFk, NEW.workerSubstitute, dated + FROM time WHERE dated BETWEEN NEW.started AND NEW.ended; END IF; END */;; @@ -37064,14 +37064,14 @@ BEGIN IF NEW.workerFk = NEW.workerSubstitute THEN CALL util.throw ('worker and workerSubstitute must be different'); ELSE - DELETE sc FROM sharingCartDaily sc - WHERE sc.dated BETWEEN OLD.started AND OLD.ended AND - sc.ownerFk = OLD.workerFk AND + DELETE sc FROM sharingCartDaily sc + WHERE sc.dated BETWEEN OLD.started AND OLD.ended AND + sc.ownerFk = OLD.workerFk AND sc.substituteFk = OLD.workerSubstitute; - - INSERT IGNORE INTO sharingCartDaily (ownerFk, substituteFk, dated) - SELECT NEW.workerFk, NEW.workerSubstitute, dated - FROM time + + INSERT IGNORE INTO sharingCartDaily (ownerFk, substituteFk, dated) + SELECT NEW.workerFk, NEW.workerSubstitute, dated + FROM time WHERE dated BETWEEN NEW.started AND NEW.ended; END IF; @@ -37094,9 +37094,9 @@ DELIMITER ;; BEFORE DELETE ON `sharingCart` FOR EACH ROW BEGIN - DELETE sc FROM sharingCartDaily sc - WHERE sc.dated BETWEEN OLD.started AND OLD.ended AND - sc.ownerFk = OLD.workerFk AND + DELETE sc FROM sharingCartDaily sc + WHERE sc.dated BETWEEN OLD.started AND OLD.ended AND + sc.ownerFk = OLD.workerFk AND sc.substituteFk = OLD.workerSubstitute; END */;; DELIMITER ; @@ -37478,7 +37478,7 @@ DELIMITER ;; FOR EACH ROW BEGIN UPDATE vn2008.Clientes c - JOIN creditClassification cc ON c.Id_Cliente = cc.client + JOIN creditClassification cc ON c.Id_Cliente = cc.client JOIN creditInsurance ci ON ci.creditClassification = cc.id SET creditInsurance = ci.credit * 2 WHERE ci.id = NEW.creditInsurance; END */;; @@ -37502,12 +37502,12 @@ DELIMITER ;; BEGIN IF NEW.dateLeaving IS NOT NULL THEN UPDATE vn2008.Clientes c - JOIN creditClassification cc ON c.Id_Cliente = cc.client + JOIN creditClassification cc ON c.Id_Cliente = cc.client JOIN creditInsurance ci ON ci.creditClassification = cc.id SET creditInsurance = ci.credit WHERE ci.id = OLD.creditInsurance; ELSE UPDATE vn2008.Clientes c - JOIN creditClassification cc ON c.Id_Cliente = cc.client + JOIN creditClassification cc ON c.Id_Cliente = cc.client JOIN creditInsurance ci ON ci.creditClassification = cc.id SET creditInsurance = ci.credit * 2 WHERE ci.id = OLD.creditInsurance; END IF; @@ -37531,7 +37531,7 @@ DELIMITER ;; FOR EACH ROW BEGIN UPDATE vn2008.Clientes c - JOIN creditClassification cc ON c.Id_Cliente = cc.client + JOIN creditClassification cc ON c.Id_Cliente = cc.client JOIN creditInsurance ci ON ci.creditClassification = cc.id SET creditInsurance = ci.credit WHERE ci.id = OLD.creditInsurance; END */;; @@ -38743,7 +38743,7 @@ DELIMITER ;; AFTER INSERT ON `ticket` FOR EACH ROW BEGIN - + DECLARE vClientType VARCHAR(255); DECLARE vStateCode VARCHAR(255); DECLARE vTransferorFirstShipped DATE; @@ -38771,7 +38771,7 @@ BEGIN 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 */;; @@ -38798,10 +38798,10 @@ BEGIN SET NEW.editorFk = account.myUser_getId(); IF !(NEW.routeFk <=> OLD.routeFk) THEN - INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) - SELECT r.id + INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) + SELECT r.id FROM vn.route r - WHERE r.isOk = FALSE + WHERE r.isOk = FALSE AND r.id IN (OLD.routeFk,NEW.routeFk) AND r.created >= util.VN_CURDATE() GROUP BY r.id; @@ -38818,13 +38818,13 @@ BEGIN END IF; END IF; - + IF !(NEW.isDeleted <=> OLD.isDeleted) AND NEW.isDeleted THEN - INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) - SELECT r.id + INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) + SELECT r.id FROM vn.ticket t JOIN vn.route r ON r.id = t.routeFk - WHERE r.isOk = FALSE + WHERE r.isOk = FALSE AND t.id = NEW.id AND r.created >= util.VN_CURDATE() GROUP BY r.id; @@ -38834,7 +38834,7 @@ BEGIN SET NEW.zoneFk = NULL; END IF; - IF NEW.routeFk AND NEW.isDeleted THEN + IF NEW.routeFk AND NEW.isDeleted THEN CALL util.throw ('This ticket is deleted'); END IF; @@ -38843,12 +38843,12 @@ BEGIN FROM vn.ticket WHERE routeFk = NEW.routeFk HAVING MAX(TIME(shipped)) > TIME(NEW.shipped); - + IF vNewTime THEN SET NEW.shipped = TIMESTAMP(DATE(NEW.shipped), vNewTime); END IF; INSERT IGNORE INTO zoneAgencyMode (agencyModeFk,zoneFk) - SELECT r.agencyModeFk, NEW.zoneFk FROM route r + SELECT r.agencyModeFk, NEW.zoneFk FROM route r WHERE r.id = NEW.routeFk; CALL vn.routeUpdateM3(NEW.routeFk); @@ -38886,7 +38886,7 @@ BEGIN END IF; IF NEW.routeFk <> OLD.routeFk THEN - UPDATE expedition + UPDATE expedition SET hasNewRoute = TRUE WHERE ticketFk = NEW.id; END IF; @@ -38909,11 +38909,11 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`ticket_beforeDelete` BEFORE DELETE ON `ticket` FOR EACH ROW -BEGIN - INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) - SELECT r.id +BEGIN + INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) + SELECT r.id FROM vn.route r - WHERE r.isOk = FALSE + WHERE r.isOk = FALSE AND r.id = OLD.routeFk AND r.created >= util.VN_CURDATE() GROUP BY r.id; @@ -38990,31 +38990,31 @@ CREATE TABLE `ticketCollection` ( /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER ticketCollection_afterDelete -AFTER DELETE -ON ticketCollection FOR EACH ROW -BEGIN - - DECLARE vSalesRemaining INT; - - SELECT count(*) INTO vSalesRemaining - FROM vn.ticketCollection tc - JOIN sale s ON s.ticketFk = tc.ticketFk - WHERE collectionFk = OLD.collectionFk - AND tc.id != OLD.id; - - IF NOT vSalesRemaining THEN - - DELETE FROM vn.collection WHERE id = OLD.collectionFk; - - ELSE - - UPDATE vn.collection - SET saleTotalCount = vSalesRemaining - WHERE id = OLD.collectionFk; - - END IF; - +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER ticketCollection_afterDelete +AFTER DELETE +ON ticketCollection FOR EACH ROW +BEGIN + + DECLARE vSalesRemaining INT; + + SELECT count(*) INTO vSalesRemaining + FROM vn.ticketCollection tc + JOIN sale s ON s.ticketFk = tc.ticketFk + WHERE collectionFk = OLD.collectionFk + AND tc.id != OLD.id; + + IF NOT vSalesRemaining THEN + + DELETE FROM vn.collection WHERE id = OLD.collectionFk; + + ELSE + + UPDATE vn.collection + SET saleTotalCount = vSalesRemaining + WHERE id = OLD.collectionFk; + + END IF; + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -39112,13 +39112,13 @@ DELIMITER ;; BEFORE DELETE ON `ticketDms` FOR EACH ROW BEGIN - UPDATE dms - SET dmsTypeFk = (SELECT id - FROM dmsType + UPDATE dms + SET dmsTypeFk = (SELECT id + FROM dmsType WHERE `code` = 'trash' ) - WHERE id = OLD.dmsFk AND ( SELECT IF(COUNT(*) > 0, FALSE, TRUE) - FROM ticketDms + WHERE id = OLD.dmsFk AND ( SELECT IF(COUNT(*) > 0, FALSE, TRUE) + FROM ticketDms WHERE dmsFk = OLD.dmsFk ) ; END */;; @@ -39594,7 +39594,7 @@ DELIMITER ;; BEGIN SET NEW.workerFk = vn.getUser(); - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -39922,7 +39922,7 @@ DELIMITER ;; BEGIN CALL ticket_requestRecalc(NEW.ticketFk); - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -39992,7 +39992,7 @@ BEGIN `changedModel` = 'TicketService', `changedModelId` = OLD.id, `userFk` = account.myUser_getId(); - + CALL ticket_requestRecalc(OLD.ticketFk); END */;; @@ -40143,11 +40143,11 @@ DELIMITER ;; FOR EACH ROW BEGIN DECLARE vNumTicketsPrepared INT; - + REPLACE vn.ticketLastState(ticketFk, ticketTrackingFk, name) SELECT NEW.ticketFk, NEW.id, `name` FROM state - WHERE id = NEW.stateFk; + WHERE id = NEW.stateFk; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -40190,21 +40190,21 @@ BEGIN DECLARE vTicketFk INT; DECLARE vTicketTrackingFk INT; DECLARE vStateName VARCHAR(15); - + IF NEW.stateFk <> OLD.stateFk THEN REPLACE vn.ticketLastState(ticketFk, ticketTrackingFk, name) SELECT NEW.ticketFk, NEW.id, `name` FROM state WHERE id = NEW.stateFk; END IF; - + IF NEW.ticketFk <> OLD.ticketFk THEN SELECT i.ticketFk, i.id, s.`name` - INTO vTicketFk, vTicketTrackingFk, vStateName - FROM ticketTracking i - JOIN state s ON i.stateFk = s.id - WHERE ticketFk = NEW.ticketFk - ORDER BY created DESC + INTO vTicketFk, vTicketTrackingFk, vStateName + FROM ticketTracking i + JOIN state s ON i.stateFk = s.id + WHERE ticketFk = NEW.ticketFk + ORDER BY created DESC LIMIT 1; IF vTicketFk > 0 THEN @@ -40246,18 +40246,18 @@ BEGIN `changedModel` = 'TicketTracking', `changedModelId` = OLD.id, `userFk` = account.myUser_getId(); - + CALL util.debugAdd('deletedState', CONCAT('interFk: ', OLD.id, ' ticketFk: ', OLD.ticketFk, ' stateFk: ', OLD.stateFk)); SELECT i.ticketFk, i.id, s.`name` - INTO vTicketFk, vTicketTrackingFk, vStateName - FROM ticketTracking i - JOIN state s ON i.stateFk = s.id - WHERE ticketFk = OLD.ticketFk - ORDER BY created DESC + INTO vTicketFk, vTicketTrackingFk, vStateName + FROM ticketTracking i + JOIN state s ON i.stateFk = s.id + WHERE ticketFk = OLD.ticketFk + ORDER BY created DESC LIMIT 1; IF vTicketFk > 0 THEN @@ -40449,13 +40449,13 @@ CREATE TABLE `till` ( /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`till_beforeInsert` - BEFORE INSERT ON `till` - FOR EACH ROW -BEGIN - IF NEW.concept IS NULL OR NEW.concept REGEXP '^[[:space:]]*$' THEN - SET NEW.concept = 'SIN DETALLE'; - END IF; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`till_beforeInsert` + BEFORE INSERT ON `till` + FOR EACH ROW +BEGIN + IF NEW.concept IS NULL OR NEW.concept REGEXP '^[[:space:]]*$' THEN + SET NEW.concept = 'SIN DETALLE'; + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -40878,7 +40878,7 @@ DELIMITER ;; FOR EACH ROW BEGIN SET NEW.editorFk = account.myUser_getId(); - + IF NOT (NEW.landed <=> OLD.landed) OR NOT (NEW.shipped <=> OLD.shipped) THEN CALL travel_checkDates(NEW.shipped, NEW.landed); @@ -40920,7 +40920,7 @@ BEGIN CALL stock.log_add('travel', NEW.id, OLD.id); IF !(NEW.shipped <=> OLD.shipped) THEN - UPDATE entry + UPDATE entry SET commission = entry_getCommission(travelFk, currencyFk,supplierFk) WHERE travelFk = NEW.id; END IF; @@ -42634,9 +42634,9 @@ DELIMITER ;; AFTER INSERT ON `workerTimeControl` FOR EACH ROW BEGIN - IF NEW.timed > DATE_ADD(util.VN_NOW(), INTERVAL 1 DAY) THEN + IF NEW.timed > DATE_ADD(util.VN_NOW(), INTERVAL 1 DAY) THEN CALL util.throw('date in the future'); - END IF; + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -43168,10 +43168,10 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`zoneExclusion_BI` BEFORE INSERT ON `zoneExclusion` FOR EACH ROW -BEGIN +BEGIN SET NEW.editorFk = account.myUser_getId(); SET NEW.userFk = account.myUser_getId(); - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -43190,10 +43190,10 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`zoneExclusion_BU` BEFORE UPDATE ON `zoneExclusion` FOR EACH ROW -BEGIN +BEGIN SET NEW.editorFk = account.myUser_getId(); SET NEW.userFk = account.myUser_getId(); - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -43590,8 +43590,8 @@ DELIMITER ;; FROM client c LEFT JOIN ticket t ON t.clientFk = c.id WHERE c.salesPersonFk IS NOT NULL - OR t.created > util.VN_CURDATE() - INTERVAL 2 MONTH - OR shipped > util.VN_CURDATE() - INTERVAL 2 MONTH + OR t.created > util.VN_CURDATE() - INTERVAL 2 MONTH + OR shipped > util.VN_CURDATE() - INTERVAL 2 MONTH ); END */ ;; /*!50003 SET time_zone = @saved_time_zone */ ;; @@ -44057,7 +44057,7 @@ BEGIN DECLARE vGeoFk INT; SELECT p.geoFk INTO vGeoFk - FROM address a + FROM address a JOIN town t ON t.provinceFk = a.provinceFk JOIN postCode p ON p.townFk = t.id AND p.`code` = a.postalCode WHERE a.id = vSelf @@ -44084,12 +44084,12 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `barcodeToItem`(vBarcode VARCHAR(22)) RETURNS int(11) DETERMINISTIC BEGIN - + /** * Obtiene el id del artículo * * @param vBarcode código de barras - * + * * return id del item */ @@ -44099,35 +44099,35 @@ BEGIN FROM vn.item WHERE id = vBarcode OR comment = vBarcode LIMIT 1; - - IF vItemFk THEN + + IF vItemFk THEN RETURN vItemFk; END IF; - SELECT itemFk INTO vItemFk - FROM buy + SELECT itemFk INTO vItemFk + FROM buy WHERE id = vBarcode; - - IF vItemFk THEN - RETURN vItemFk; - END IF; - - SELECT itemFk INTO vItemFk - FROM itemBarcode - WHERE code = vBarcode; - - IF vItemFk THEN + + IF vItemFk THEN RETURN vItemFk; END IF; - SELECT i.id INTO vItemFk + SELECT itemFk INTO vItemFk + FROM itemBarcode + WHERE code = vBarcode; + + IF vItemFk THEN + RETURN vItemFk; + END IF; + + SELECT i.id INTO vItemFk FROM vn.item i WHERE i.name LIKE CONCAT('%',vBarcode,'%') ORDER BY i.id ASC LIMIT 1; - + RETURN vItemFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -44150,9 +44150,9 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `botanicExport_isUpdatable`(vEdiGenus DETERMINISTIC BEGIN DECLARE vIsUpdatable INTEGER; - SELECT COUNT(*) INTO vIsUpdatable - FROM botanicExport - WHERE ediGenusFk = vEdiGenusFk + SELECT COUNT(*) INTO vIsUpdatable + FROM botanicExport + WHERE ediGenusFk = vEdiGenusFk AND (vEdiSpecieFk = ediSpecieFk OR IFNULL(vEdiSpecieFk,ediSpecieFk) IS NULL) AND vRestriction = restriction; RETURN vIsUpdatable; @@ -44248,16 +44248,16 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `catalog_componentReverse`(vWarehouse DETERMINISTIC BEGIN /* Calcula los componentes para un cliente a partir de un coste y volumen - * @param vWarehouse + * @param vWarehouse * @param vCost Valor de coste del articulo * @param vM3 m3 del articulo - * @param vAddressFk + * @param vAddressFk * @param vZoneFk - * @return vRetailedPrice precio de venta sin iva + * @return vRetailedPrice precio de venta sin iva * @return tmp.catalog_component (warehouseFk, itemFk, componentFk, cost) */ - - DECLARE vBoxVolume BIGINT; + + DECLARE vBoxVolume BIGINT; DECLARE vCustomer INT; DECLARE vComponentRecovery INT DEFAULT 17; DECLARE vComponentMana INT DEFAULT 39; @@ -44266,11 +44266,11 @@ BEGIN DECLARE vComponentCost INT DEFAULT 28; DECLARE vRetailedPrice DECIMAL(10,2); DECLARE vItem INT DEFAULT 98; - + SELECT volume INTO vBoxVolume FROM vn.packaging WHERE id = '94'; - + SELECT clientFk INTO vCustomer FROM address WHERE id = vAddressFk; DROP TEMPORARY TABLE IF EXISTS tmp.catalog_component; @@ -44294,7 +44294,7 @@ BEGIN -- Margen -- No se aplica margen, cau 12589 /* INSERT INTO tmp.catalog_component (warehouseFk, itemFk, componentFk, cost) - SELECT vWarehouse, vItem, vComponentMargin, (vCost / ((100 - rate2) / 100)) - vCost + SELECT vWarehouse, vItem, vComponentMargin, (vCost / ((100 - rate2) / 100)) - vCost FROM vn.rate WHERE dated <= util.VN_CURDATE() AND warehouseFk = vWarehouse @@ -44303,7 +44303,7 @@ BEGIN */ -- Recobro INSERT INTO tmp.catalog_component (warehouseFk, itemFk, componentFk, cost) - SELECT vWarehouse, vItem, vComponentRecovery, ROUND(LEAST(recobro,0.25), 3) + SELECT vWarehouse, vItem, vComponentRecovery, ROUND(LEAST(recobro,0.25), 3) FROM bi.claims_ratio WHERE Id_Cliente = vCustomer AND recobro > 0.009; @@ -44320,7 +44320,7 @@ BEGIN ROUND( vM3 * (z.price - z.bonus) - * z.inflation + * z.inflation / vBoxVolume, 4 ) FROM zone z @@ -44363,30 +44363,30 @@ BEGIN DECLARE vAutoManaComponent INT; DECLARE vManaBank INT; DECLARE vManaGreugeType INT; - + SELECT id INTO vManaGreugeType FROM greugeType WHERE code = 'mana'; SELECT id INTO vManaBank FROM bank WHERE code = 'mana'; SELECT id INTO vManaComponent FROM component WHERE code = 'mana'; SELECT id INTO vAutoManaComponent FROM component WHERE code = 'autoMana'; - + SELECT COUNT(*) INTO vHasMana FROM `client` c WHERE c.id = vClient AND c.typeFk = 'normal'; - + IF NOT vHasMana THEN RETURN 0; END IF; - + SELECT max(dated) INTO vFromDated FROM clientManaCache; SELECT sum(mana) INTO vMana - FROM + FROM ( SELECT mana FROM clientManaCache WHERE clientFk = vClient - AND dated = vFromDated + AND dated = vFromDated UNION ALL SELECT s.quantity * value FROM ticket t @@ -44394,7 +44394,7 @@ BEGIN JOIN sale s on s.ticketFk = t.id JOIN saleComponent sc on sc.saleFk = s.id WHERE sc.componentFk IN (vManaComponent, vAutoManaComponent) - AND t.shipped > vFromDated + AND t.shipped > vFromDated AND t.shipped < TIMESTAMPADD(DAY,1,util.VN_CURDATE()) AND a.clientFk = vClient UNION ALL @@ -44458,7 +44458,7 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `clientTaxArea`(vClientId INT, vCompa READS SQL DATA BEGIN /** -* Devuelve el area de un cliente, +* Devuelve el area de un cliente, * intracomunitario, extracomunitario o nacional. * * @param vClient Id del cliente @@ -44505,7 +44505,7 @@ BEGIN SELECT COUNT(*) INTO vHasDebt FROM `client` c WHERE c.id = vClient AND c.typeFk = 'normal'; - + IF NOT vHasDebt THEN RETURN 0; END IF; @@ -44593,8 +44593,8 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `client_getSalesPerson`(vClientFk INT DETERMINISTIC BEGIN /** - * Dado un id cliente y una fecha, devuelve su comercial para ese dia, teniendo - * en cuenta la jerarquía de las tablas: 1º la de sharingclient, 2º la de + * Dado un id cliente y una fecha, devuelve su comercial para ese dia, teniendo + * en cuenta la jerarquía de las tablas: 1º la de sharingclient, 2º la de * sharingcart y tercero la de clientes. * * @param vClientFk El id del cliente @@ -44632,29 +44632,29 @@ BEGIN l: LOOP SELECT workerSubstitute INTO vWorkerSubstituteFk - FROM sharingCart + FROM sharingCart WHERE util.VN_CURDATE() BETWEEN started AND ended AND workerFk = vSalesPersonFk ORDER BY id LIMIT 1; - + IF vWorkerSubstituteFk IS NULL THEN LEAVE l; END IF; - + SELECT COUNT(*) > 0 INTO vLoop FROM tmp.stack WHERE substitute = vWorkerSubstituteFk; IF vLoop THEN LEAVE l; END IF; - + INSERT INTO tmp.stack SET substitute = vWorkerSubstituteFk; - + SET vSalesPersonFk = vWorkerSubstituteFk; END LOOP; - + DROP TEMPORARY TABLE tmp.stack; END IF; @@ -44688,11 +44688,11 @@ BEGIN **/ DECLARE vClientFk INT; DECLARE vDated DATE; - + SELECT clientFk, shipped INTO vClientFk, vDated FROM ticket WHERE id = vTicketFk; - + RETURN client_getSalesPerson(vClientFk, vDated); END ;; DELIMITER ; @@ -44723,12 +44723,12 @@ BEGIN **/ DECLARE vWorkerCode CHAR(3); DECLARE vSalesPersonFk INT; - + SET vSalesPersonFk = client_getSalesPerson(vClientFk, vDated); SELECT code INTO vWorkerCode - FROM worker + FROM worker WHERE id = vSalesPersonFk; RETURN vWorkerCode; @@ -44761,11 +44761,11 @@ BEGIN **/ DECLARE vClientFk INT; DECLARE vDated DATE; - + SELECT clientFk, shipped INTO vClientFk, vDated FROM ticket WHERE id = vTicketFk; - + RETURN client_getSalesPersonCode(vClientFk, vDated); END ;; DELIMITER ; @@ -44857,7 +44857,7 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `currentRate`(vCurrencyFk INT, vDated BEGIN DECLARE curRate DECIMAL(10,4); - + SELECT value INTO curRate FROM referenceRate WHERE dated <= vDated @@ -44888,23 +44888,23 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `deviceProductionUser_accessGranted`( BEGIN /* * Comprueba si el usuario puede entrar en la aplicacion de almacen con ese movil - * + * * */ - + /*DECLARE vIsGranted BOOLEAN; DECLARE vDeviceProductionFk INT(11) DEFAULT NULL; - SELECT dp.id INTO vDeviceProductionFk - FROM vn.deviceProduction dp + SELECT dp.id INTO vDeviceProductionFk + FROM vn.deviceProduction dp WHERE dp.android_id = android_id; IF vDeviceProductionFk THEN - - SELECT COUNT(*) INTO vIsGranted - FROM vn.deviceProductionUser dpu - WHERE dpu.userFk = vUserFK + + SELECT COUNT(*) INTO vIsGranted + FROM vn.deviceProductionUser dpu + WHERE dpu.userFk = vUserFK AND dpu.deviceProductionFk = vDeviceProductionFk; - + RETURN vIsGranted; END IF;*/ RETURN TRUE; @@ -44928,16 +44928,16 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `duaTax_getRate`(vDua INT, vTaxClass DETERMINISTIC BEGIN DECLARE vCountryFk INTEGER; - + SELECT s.countryFk INTO vCountryFk FROM dua d JOIN supplier s ON s.id = d.companyFk WHERE d.id = vDua; - + RETURN (SELECT rate FROM (SELECT taxClassFk, rate - FROM invoiceInTaxBookingAccount + FROM invoiceInTaxBookingAccount WHERE effectived <= util.VN_CURDATE() AND countryFk = vCountryFk AND taxClassFk = vTaxClass @@ -44965,24 +44965,24 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `ekt_getEntry`(vEktFk INT) RETURNS in READS SQL DATA BEGIN /** - * Devuelve el numero de entrada para el ekt - * + * Devuelve el numero de entrada para el ekt + * * @param vEktFk Identificador de edi.ekt - */ + */ DECLARE vTravelFk INT; DECLARE vEntryFk INT DEFAULT 0; DECLARE vEntryAssignFk INT; - SELECT ea.id + SELECT ea.id INTO vEntryAssignFk FROM edi.ekt e - JOIN vn.ektEntryAssign ea ON + JOIN vn.ektEntryAssign ea ON IFNULL(ea.sub, e.sub) <=> e.sub AND IFNULL(ea.kop, e.kop) <=> e.kop AND IFNULL(ea.pro, e.pro) <=> e.pro AND IFNULL(ea.auction, e.auction) <=> e.auction WHERE e.id = vEktFk - ORDER BY + ORDER BY IF(ea.sub,1,0) * 1000 + IF(ea.kop,1,0) * 100 + IF(ea.pro,1,0) * 10 + @@ -44993,7 +44993,7 @@ BEGIN IF vTravelFk THEN - SELECT MAX(e.id) + SELECT MAX(e.id) INTO vEntryFk FROM vn.entry e JOIN vn.ektEntryAssign ea ON ea.id = vEntryAssignFk @@ -45008,13 +45008,13 @@ BEGIN INSERT INTO vn.entry(travelFk, supplierFk, companyFk, currencyFk, kop, sub, reference, pro, auction) SELECT vTravelFk, ea.supplierFk, ea.companyFk, cu.id, ea.kop, ea.sub, ea.ref, ea.pro, ea.auction FROM vn.ektEntryAssign ea - JOIN vn.currency cu ON cu.code = 'EUR' + JOIN vn.currency cu ON cu.code = 'EUR' WHERE ea.id = vEntryAssignFk; SET vEntryFk = LAST_INSERT_ID(); END IF; - UPDATE vn.ektEntryAssign + UPDATE vn.ektEntryAssign SET entryFk = vEntryFk WHERE id = vEntryAssignFk; @@ -45048,7 +45048,7 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `ekt_getTravel`(vEntryAssignFk INT, v BEGIN /** * Devuelve un vn.travel.id - * + * * @param vEntryAssignFk Identificador de vn.entryAssign */ DECLARE vTravelFk INT; @@ -45109,36 +45109,36 @@ BEGIN DECLARE vCurrentCommission INT; DECLARE vIsCurrencyUsd INT; DECLARE vLastEntryFk INT; - + SELECT count(*) INTO vIsCurrencyUsd FROM currency c WHERE c.code = 'USD' AND id = vCurrencyFk; - + IF NOT vIsCurrencyUsd THEN - + SELECT e.id INTO vLastEntryFk FROM vn.entry e JOIN vn.travel tr ON tr.id = e.travelFk WHERE e.supplierFk = vSupplierFk ORDER BY tr.landed DESC LIMIT 1; - + IF vLastEntryFk THEN - + SELECT commission INTO vCurrentCommission FROM vn.entry WHERE id = vLastEntryFk; - + ELSE - + SELECT commission INTO vCurrentCommission FROM supplier s WHERE s.id = vSupplierFk; - + END IF; - + RETURN vCurrentCommission; - + ELSE SELECT ROUND(-100 * (1 - (1 / r.value))) INTO vCommission @@ -45147,11 +45147,11 @@ BEGIN WHERE t.id = vTravelFk ORDER BY r.`dated` DESC LIMIT 1; - + RETURN IFNULL(vCommission, 0); - + END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -45202,10 +45202,10 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `entry_getForLogiflora`(vLanded DATE, vWarehouseFk INT) RETURNS int(11) READS SQL DATA BEGIN - + /** * Devuelve una entrada para Logiflora. Si no existe la crea. - * + * * @param vLanded Fecha de llegada al almacén * @param vWarehouseFk Identificador de vn.warehouse */ @@ -45213,51 +45213,51 @@ BEGIN DECLARE vTravelFk INT; DECLARE vEntryFk INT; DECLARE previousEntryFk INT; - + SET vTravelFk = vn.travel_getForLogiflora(vLanded, vWarehouseFk); - + IF vLanded THEN - - SELECT IFNULL(MAX(id),0) INTO vEntryFk + + SELECT IFNULL(MAX(id),0) INTO vEntryFk FROM vn.entry - WHERE travelFk = vTravelFk + WHERE travelFk = vTravelFk AND isRaid; IF NOT vEntryFk THEN - + INSERT INTO vn.entry(travelFk, supplierFk, commission, companyFk, currencyFk, isRaid) SELECT vTravelFk, s.id, 4, c.id, cu.id, TRUE FROM vn.supplier s JOIN vn.company c ON c.code = 'VNL' JOIN vn.currency cu ON cu.code = 'EUR' WHERE s.name = 'KONINKLIJE COOPERATIEVE BLOEMENVEILING FLORAHOLLAN'; - - SELECT MAX(id) INTO vEntryFk + + SELECT MAX(id) INTO vEntryFk FROM vn.entry WHERE travelFk = vTravelFk; - - END IF; - - END IF; - SELECT entryFk INTO previousEntryFk + END IF; + + END IF; + + SELECT entryFk INTO previousEntryFk FROM edi.warehouseFloramondo wf WHERE wf.warehouseFk = vWarehouseFk; - + IF IFNULL(previousEntryFk,0) != vEntryFk THEN - - UPDATE buy b - SET b.printedStickers = 0 + + UPDATE buy b + SET b.printedStickers = 0 WHERE entryFk = previousEntryFk; DELETE FROM buy WHERE entryFk = previousEntryFk; - + DELETE FROM entry WHERE id = previousEntryFk; - + END IF; - + RETURN vEntryFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -45290,21 +45290,21 @@ BEGIN SELECT IFNULL(a.isUeeMember, c.isUeeMember), c.id INTO vIsUeeSupplier, vSupplierCountry - FROM entry e - JOIN supplier s ON s.id = e.supplierFk - JOIN country c ON c.id = s.countryFk + FROM entry e + JOIN supplier s ON s.id = e.supplierFk + JOIN country c ON c.id = s.countryFk LEFT JOIN province p ON p.id = s.provinceFk LEFT JOIN autonomy a ON a.id = p.autonomyFk WHERE e.id = vSelf; - + SELECT IFNULL(a.isUeeMember, c.isUeeMember), c.id INTO vIsUeeCompany, vCompanyCountry - FROM entry e - JOIN supplier s ON s.id = e.companyFk - JOIN country c ON c.id = s.countryFk + FROM entry e + JOIN supplier s ON s.id = e.companyFk + JOIN country c ON c.id = s.countryFk LEFT JOIN province p ON p.id = s.provinceFk LEFT JOIN autonomy a ON a.id = p.autonomyFk - WHERE e.id = vSelf; + WHERE e.id = vSelf; RETURN vIsUeeCompany AND vIsUeeSupplier AND (vSupplierCountry <> vCompanyCountry); @@ -45369,17 +45369,17 @@ BEGIN DECLARE vHasDistinctRoutes BOOL; SELECT t.routeFk INTO vRouteFk - FROM vn.expedition e + FROM vn.expedition e JOIN vn.ticket t ON e.ticketFk = t.id WHERE e.id = vExpeditionFk; - + SELECT COUNT(*) > 0 INTO vHasDistinctRoutes FROM vn.expeditionScan es JOIN vn.expedition e ON es.expeditionFk = e.id JOIN vn.ticket t ON e.ticketFk = t.id WHERE es.palletFk = vPalletFk AND t.routeFk <> vRouteFk; - + RETURN vHasDistinctRoutes; END ;; @@ -45440,27 +45440,27 @@ BEGIN DECLARE vDeliveryType INTEGER DEFAULT 0; DECLARE isWaitingForPickUp BOOLEAN DEFAULT FALSE; DECLARE vCode VARCHAR(45); - + SELECT am.deliveryMethodFk - INTO vDeliveryType + INTO vDeliveryType FROM ticket t JOIN agencyMode am ON am.id = t.agencyModeFk WHERE t.id = vTicket; - + CASE vDeliveryType WHEN 1 THEN -- AGENCIAS SET vCode = 'DELIVERED'; - + WHEN 2 THEN -- REPARTO SET vCode = 'ON_DELIVERY'; - + ELSE -- MERCADO, OTROS SELECT MIN(t.warehouseFk <> w.id) INTO isWaitingForPickUp - FROM ticket t + FROM ticket t LEFT JOIN warehouse w ON w.pickUpagencyModeFk = t.agencyModeFk WHERE t.id = vTicket; - + IF isWaitingForPickUp THEN SET vCode = 'WAITING_FOR_PICKUP'; ELSE @@ -45490,28 +45490,28 @@ BEGIN DECLARE vDeliveryType INTEGER DEFAULT 0; DECLARE isWaitingForPickUp BOOLEAN DEFAULT FALSE; DECLARE vCode VARCHAR(45); - - SELECT + + SELECT a.Vista - INTO vDeliveryType + INTO vDeliveryType FROM vn2008.Tickets t JOIN vn2008.Agencias a ON a.Id_Agencia = t.Id_Agencia WHERE Id_Ticket = vTicket; - + CASE vDeliveryType WHEN 1 THEN -- AGENCIAS SET vCode = 'DELIVERED'; - + WHEN 2 THEN -- REPARTO SET vCode = 'ON_DELIVERY'; - + ELSE -- MERCADO, OTROS SELECT t.warehouse_id <> w.warehouse_id INTO isWaitingForPickUp - FROM vn2008.Tickets t - LEFT JOIN vn2008.warehouse_pickup w + FROM vn2008.Tickets t + LEFT JOIN vn2008.warehouse_pickup w ON w.agency_id = t.Id_Agencia AND w.warehouse_id = t.warehouse_id WHERE t.Id_Ticket = vTicket; - + IF isWaitingForPickUp THEN SET vCode = 'WAITING_FOR_PICKUP'; ELSE @@ -45619,16 +45619,16 @@ BEGIN DECLARE vReturn DATE; DECLARE vDuaDate DATE; DECLARE vDuaDateDay INT; - + SELECT TIMESTAMPADD(DAY, vGapDays, vDated) INTO vDuaDate; IF vDuaDate = CONCAT(YEAR(vDuaDate), '-03-01') THEN - SET vDuaDate = TIMESTAMPADD (DAY , -1, vDuaDate); + SET vDuaDate = TIMESTAMPADD (DAY , -1, vDuaDate); ELSEIF vDuaDate = CONCAT(YEAR(vDuaDate), '-02-29') THEN - SET vDuaDate = TIMESTAMPADD (DAY , -2, vDuaDate); + SET vDuaDate = TIMESTAMPADD (DAY , -2, vDuaDate); END IF; - IF MONTH(vDuaDate) = 2 AND vPayDay = 30 THEN + IF MONTH(vDuaDate) = 2 AND vPayDay = 30 THEN IF util.isLeapYear(YEAR(vDuaDate)) THEN SET vPayDay = 29; ELSE @@ -45636,7 +45636,7 @@ BEGIN END IF; END IF; - SELECT DAY(vDuaDate) INTO vDuaDateDay; + SELECT DAY(vDuaDate) INTO vDuaDateDay; RETURN TIMESTAMPADD(MONTH, (vDuaDateDay > vPayDay), DATE_FORMAT(vDuaDate, CONCAT('%y/%m/', vPayDay))); END ;; DELIMITER ; @@ -45658,11 +45658,11 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `getShipmentHour`(vTicket INT) RETURN READS SQL DATA BEGIN DECLARE vShipmentHour INT; - + SELECT HOUR(shipped) INTO vShipmentHour FROM ticket WHERE id = vTicket; - + IF vShipmentHour = 0 THEN DROP TEMPORARY TABLE IF EXISTS tmp.production_buffer; @@ -45677,11 +45677,11 @@ BEGIN JOIN agencyMode am on am.id = t.agencyModeFk JOIN address a on a.id = t.addressFk WHERE t.id = vTicket; - - SELECT Hora INTO vShipmentHour + + SELECT Hora INTO vShipmentHour FROM tmp.production_buffer; END IF; - + RETURN vShipmentHour; END ;; DELIMITER ; @@ -45706,12 +45706,12 @@ BEGIN SELECT rate3 INTO price FROM vn.priceFixed - WHERE itemFk = vItemFk + WHERE itemFk = vItemFk AND util.VN_CURDATE() BETWEEN started AND ended ORDER BY created DESC LIMIT 1; - SELECT `value` INTO price + SELECT `value` INTO price FROM vn.specialPrice - WHERE itemFk = vItemFk + WHERE itemFk = vItemFk AND clientFk = vClientFk ; RETURN price; END ;; @@ -45735,7 +45735,7 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `getTicketTrolleyLabelCount`(vTicket BEGIN DECLARE vLabelCount INT DEFAULT 0; - SELECT labelCount INTO vLabelCount + SELECT labelCount INTO vLabelCount FROM ticketTrolley WHERE ticket = vTicket; @@ -45865,17 +45865,17 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `hasItemsInSector`(vTicketFk INT, vSe BEGIN DECLARE vItemCount INT; - + SELECT count(*) INTO vItemCount - FROM vn.sale s + FROM vn.sale s JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk JOIN vn.shelving sh ON sh.code = ish.shelvingFk JOIN vn.parking p ON p.id = sh.parkingFk WHERE s.ticketFk = vTicketFk AND p.sectorFk = vSectorFk; - + RETURN vItemCount; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -45898,7 +45898,7 @@ BEGIN DECLARE vCountry INT; DECLARE hasSomeNegativeBase BOOLEAN; - SELECT s.countryFk + SELECT s.countryFk INTO vCountry FROM supplier s JOIN ticket t ON t.companyFk = s.id @@ -45907,9 +45907,9 @@ BEGIN SELECT COUNT(*) INTO hasSomeNegativeBase FROM ( SELECT SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2)) taxableBase - FROM sale s + FROM sale s JOIN item i ON i.id = s.itemFk - JOIN itemTaxCountry itc + JOIN itemTaxCountry itc ON itc.itemFk = i.id AND itc.countryFk = vCountry WHERE s.ticketFk = vTicket GROUP BY itc.taxClassFk @@ -45939,12 +45939,12 @@ BEGIN DECLARE totalAmount DECIMAL(10,2); SELECT SUM(vat) INTO totalAmount - FROM ( + FROM ( SELECT iot.vat FROM invoiceOutTax iot JOIN invoiceOut io ON io.id = iot.invoiceOutFk WHERE io.ref = vInvoiceRef - UNION ALL + UNION ALL SELECT ioe.amount FROM invoiceOutExpence ioe JOIN invoiceOut io ON io.id = ioe.invoiceOutFk @@ -45975,23 +45975,23 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `invoiceOut_getMaxIssued`(vSerial VAR READS SQL DATA BEGIN /** - * Retorna la fecha a partir de la cual es válido emitir una factura + * Retorna la fecha a partir de la cual es válido emitir una factura * - * @param vSerial Serie de facturación + * @param vSerial Serie de facturación * @param vCompanyFk Empresa factura emitida * @param vYear Año contable * @return vInvoiceOutIssued fecha factura válida */ DECLARE vInvoiceOutIssued DATE; DECLARE vFirstDayOfYear DATE; - + SET vFirstDayOfYear := MAKEDATE(vYear, 1); - SELECT IFNULL(MAX(io.issued), vFirstDayOfYear) INTO vInvoiceOutIssued + SELECT IFNULL(MAX(io.issued), vFirstDayOfYear) INTO vInvoiceOutIssued FROM invoiceOut io WHERE io.serial = vSerial AND io.companyFk = vCompanyFk - AND io.issued BETWEEN vFirstDayOfYear + AND io.issued BETWEEN vFirstDayOfYear AND util.lastDayOfYear(vFirstDayOfYear); RETURN vInvoiceOutIssued; @@ -46017,7 +46017,7 @@ BEGIN DECLARE vIssued DATE; DECLARE vSerial VARCHAR(15); - SELECT issued, ref + SELECT issued, ref INTO vIssued, vSerial FROM invoiceOut WHERE id = vSelf; @@ -46089,9 +46089,9 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `invoiceSerial`(vClientFk INT, vCompa DETERMINISTIC BEGIN /** - * Obtiene la serie de de una factura + * Obtiene la serie de de una factura * dependiendo del area del cliente. - * + * * @param vClientFk Id del cliente * @param vCompanyFk Id de la empresa * @param vType Tipo de factura ["R", "M", "G"] @@ -46172,18 +46172,18 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `isLogifloraDay`(vShipped DATE, vWarehouse INT) RETURNS tinyint(1) DETERMINISTIC BEGIN - + DECLARE vIsLogifloraDay BOOLEAN; SELECT COUNT(*) INTO vIsLogifloraDay FROM edi.warehouseFloramondo wf - JOIN vn.floramondoConfig fc + JOIN vn.floramondoConfig fc WHERE wf.warehouseFk = vWarehouse AND vShipped BETWEEN DATE(TIMESTAMPADD(DAY, wf.travellingDays , fc.nextLanded)) AND DATE(TIMESTAMPADD(DAY, wf.travellingDays + wf.dayRange , fc.nextLanded)); - + RETURN vIsLogifloraDay; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -46220,7 +46220,7 @@ BEGIN WHERE sl.scan_id = vScanId AND t.Id_Ruta ) t1; - + RETURN vDistinctRoutesInThePallet = 1; END ;; DELIMITER ; @@ -46244,20 +46244,20 @@ BEGIN DECLARE vPacking INTEGER DEFAULT 0; DECLARE vItemFk INTEGER; - + SELECT vn.barcodeToItem(vBarcode) INTO vItemFk; - - SELECT IFNULL(packing,0) INTO vPacking - FROM vn.buy + + SELECT IFNULL(packing,0) INTO vPacking + FROM vn.buy WHERE id = CAST(vBarcode AS DECIMAL(18,0)); - - - - + + + + IF NOT vPacking THEN CALL cache.last_buy_refresh(FALSE); SELECT IFNULL(packing,1) INTO vPacking - FROM + FROM (SELECT packing , created FROM vn.itemShelving WHERE itemFk = vItemFk @@ -46270,11 +46270,11 @@ BEGIN ) packings ORDER BY created desc LIMIT 1; - + END IF; - + RETURN vPacking; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -46299,11 +46299,11 @@ BEGIN DECLARE vColumn INT; DECLARE vClosestParkingFk INT; DECLARE vSectorFk INT; - + SELECT p.column, sectorFk INTO vColumn, vSectorFk FROM vn.parking p WHERE p.id = vParkingFk; - + SELECT itemShelvingFk INTO vClosestParkingFk FROM ( @@ -46313,12 +46313,12 @@ BEGIN JOIN vn.itemPlacementSupplyList ipsl ON ipsl.sectorFk = ispss.sectorFk AND ipsl.itemFk = ispss.itemFk WHERE p.sectorFk = vSectorFk AND ipsl.saldo > 0 - ) sub + ) sub ORDER BY distance LIMIT 1; - + RETURN vClosestParkingFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -46340,17 +46340,17 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `itemsInSector_get`(vTicketFk INT, vS BEGIN DECLARE vItemCount INT; - + SELECT count(*) INTO vItemCount - FROM vn.sale s + FROM vn.sale s JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk JOIN vn.shelving sh ON sh.code = ish.shelvingFk JOIN vn.parking p ON p.id = sh.parkingFk WHERE s.ticketFk = vTicketFk AND p.sectorFk = vSectorFk; - + RETURN vItemCount; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -46423,29 +46423,29 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `item_getPackage`(vItemFk INT) RETURNS varchar(50) CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci DETERMINISTIC BEGIN - + DECLARE vDiameter INT; DECLARE vPackageFk VARCHAR(50); DECLARE vCoeficient DOUBLE DEFAULT 1.08; - + SELECT MAX(LEFT(value,3)) INTO vDiameter - FROM vn.itemTag it + FROM vn.itemTag it JOIN vn.tag t ON t.id = it.tagFk WHERE it.itemFk = vItemFk AND t.overwrite = 'diameter'; - + SELECT 8000 + FLOOR(vc.ccLength * vc.ccWidth / (vCoeficient * PI() * (vDiameter / 2) * (vDiameter / 2))) INTO vPackageFk FROM vn.volumeConfig vc; - + INSERT IGNORE INTO vn.packaging(id, width, `depth`) - SELECT vPackageFk, - FLOOR(vc.ccWidth / FLOOR(vc.ccWidth / vDiameter)), + SELECT vPackageFk, + FLOOR(vc.ccWidth / FLOOR(vc.ccWidth / vDiameter)), FLOOR(vc.ccLength / FLOOR(vc.ccLength / vDiameter)) FROM vn.volumeConfig vc; - + RETURN vPackageFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -46482,7 +46482,7 @@ BEGIN FROM packaging p JOIN item i ON i.id = vSelf WHERE p.id = vPackaging; - + RETURN vVolume; END ;; @@ -46503,7 +46503,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `lastDayOfWeek`(vYear INT, vWeek INT) RETURNS date DETERMINISTIC -BEGIN +BEGIN /** * Returns the date of the last day of the week * @@ -46542,16 +46542,16 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `machine_checkPlate`(vPlate VARCHAR(1 BEGIN /** * Comprueba si existe matrícula - * + * * @param vPlate matrícula del vehículo * @return Devuelve TRUE en caso de que exista - * + * */ - + IF (SELECT COUNT(*) - FROM machine m + FROM machine m WHERE m.plate = vPlate - ) THEN + ) THEN RETURN TRUE; ELSE RETURN FALSE; @@ -46578,9 +46578,9 @@ BEGIN DECLARE result INT; DECLARE vSenderFk INT; - SELECT id INTO vSenderFk + SELECT id INTO vSenderFk FROM account.user WHERE `name` = account.myUser_getName(); - + RETURN (SELECT messageSendWithUser(vSenderFk, vRecipient, vMessage)); END ;; DELIMITER ; @@ -46607,9 +46607,9 @@ BEGIN DECLARE vSendDate DATETIME DEFAULT util.VN_NOW(); DECLARE vSender VARCHAR(255) CHARSET utf8; - SELECT `name` INTO vSender + SELECT `name` INTO vSender FROM account.user WHERE id = vSenderFK; - + SET vRecipient = LOWER(vRecipient); DROP TEMPORARY TABLE IF EXISTS tRecipients; @@ -46630,7 +46630,7 @@ BEGIN IF vCount = 0 THEN RETURN vCount; - END IF; + END IF; SET vUuid = UUID(); @@ -46641,7 +46641,7 @@ BEGIN message = vMessage, sendDate = vSendDate; - INSERT INTO messageInbox (uuid, sender, recipient, finalRecipient, message, sendDate) + INSERT INTO messageInbox (uuid, sender, recipient, finalRecipient, message, sendDate) SELECT vUuid, vSender, vRecipient, finalRecipient, vMessage, vSendDate FROM tRecipients; @@ -46715,7 +46715,7 @@ BEGIN -- Devuelte el volumen total de la orden sumada DECLARE vWarehouseId INTEGER; DECLARE vVolume DECIMAL(10,3); - + SELECT IFNULL(SUM(o.amount * ic.cm3delivery)/1000000,0) INTO vVolume FROM hedera.orderRow o JOIN item i ON i.id = o.itemFk @@ -46792,7 +46792,7 @@ BEGIN WHERE cb.id = packagingReturnFk; SET vValue = IF (vAmount IS NULL, - IFNULL(base,0), + IFNULL(base,0), vAmount / IFNULL(upload, 0) + IFNULL(base, 0)); ELSE SET vValue = IFNULL(price, 0) + IFNULL(base, 0); @@ -46819,7 +46819,7 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `phytoPassport`(vRef VARCHAR(15)) RET DETERMINISTIC BEGIN DECLARE vPhyto TEXT CHARSET utf8 COLLATE utf8_unicode_ci; -SELECT +SELECT GROUP_CONCAT(i.id, ':', ppa.denomination, @@ -46908,20 +46908,20 @@ BEGIN DECLARE vRouteFk INT; DECLARE vAddressFk INT; - + DECLARE vLanded DATE; DECLARE vZoneFk INT; DECLARE vSignificativeFriendship INT DEFAULT 6; DECLARE vVolumeMax DECIMAL(5,1) DEFAULT 10; - + SELECT addressFk, zoneFk, landed INTO vAddressFk, vZoneFk, vLanded - FROM vn.ticket + FROM vn.ticket WHERE id = vTicketFk; - + -- Se inicia la selección de rutas posibles con aquellas cuyas agencias alguna vez han estado asociadas con nuestra zona DROP TEMPORARY TABLE IF EXISTS tmp.route; CREATE TEMPORARY TABLE tmp.route - SELECT r.id routeFk, + SELECT r.id routeFk, zf.friendship zoneFriendship FROM vn.route r JOIN cache.zoneAgencyFriendship zf ON zf.agencyModeFk = r.agencyModeFk @@ -46929,16 +46929,16 @@ BEGIN AND zf.zoneFk = vZoneFk AND r.created = vLanded ORDER BY friendship; - + -- Se eliminan aquellas que superan el volumen máximo DELETE r.* - FROM tmp.route r + FROM tmp.route r JOIN (SELECT routeFk, sum(volume) volume FROM vn.saleVolume WHERE landed = vLanded GROUP BY routeFk) sub ON sub.routeFk = r.routeFk WHERE sub.volume > vVolumeMax; - + -- Se ordenan las que quedan en función con la afinidad del resto de consignatarios de cada ruta SELECT routeFk INTO vRouteFk FROM @@ -46950,7 +46950,7 @@ BEGIN ORDER BY zoneFriendship DESC, friendshipSum DESC ) sub LIMIT 1; - + RETURN vRouteFk; END ;; DELIMITER ; @@ -46975,9 +46975,9 @@ BEGIN DECLARE vRouteFk INT; DECLARE vAddressFk INT; DECLARE vShipped DATETIME; - + SELECT addressFk, date(shipped) INTO vAddressFk, vShipped - FROM vn.ticket + FROM vn.ticket WHERE id = vTicketFk; SELECT routeFk INTO vRouteFk @@ -46991,7 +46991,7 @@ BEGIN ORDER BY friendshipSum DESC ) sub LIMIT 1; - + RETURN vRouteFk; END ;; DELIMITER ; @@ -47015,20 +47015,20 @@ BEGIN DECLARE vRouteFk INT; DECLARE vAddressFk INT; - + DECLARE vLanded DATE; DECLARE vZoneFk INT; DECLARE vSignificativeFriendship INT DEFAULT 6; DECLARE vVolumeMax DECIMAL(5,1) DEFAULT 10; - + SELECT addressFk, zoneFk, landed INTO vAddressFk, vZoneFk, vLanded - FROM vn.ticket + FROM vn.ticket WHERE id = vTicketFk; - + -- Se inicia la selección de rutas posibles con aquellas cuyas agencias alguna vez han estado asociadas con nuestra zona DROP TEMPORARY TABLE IF EXISTS tmp.route; CREATE TEMPORARY TABLE tmp.route - SELECT r.id routeFk, + SELECT r.id routeFk, zf.friendship zoneFriendship FROM vn.route r JOIN cache.zoneAgencyFriendship zf ON zf.agencyModeFk = r.agencyModeFk @@ -47036,16 +47036,16 @@ BEGIN AND zf.zoneFk = vZoneFk AND r.created = vLanded ORDER BY friendship; - + -- Se eliminan aquellas que superan el volumen máximo DELETE r.* - FROM tmp.route r + FROM tmp.route r JOIN (SELECT routeFk, sum(volume) volume FROM vn.saleVolume WHERE landed = vLanded GROUP BY routeFk) sub ON sub.routeFk = r.routeFk WHERE sub.volume > vVolumeMax; - + -- Se ordenan las que quedan en función con la afinidad del resto de consignatarios de cada ruta SELECT routeFk INTO vRouteFk FROM @@ -47057,7 +47057,7 @@ BEGIN ORDER BY zoneFriendship DESC, friendshipSum DESC ) sub LIMIT 1; - + RETURN vRouteFk; END ;; DELIMITER ; @@ -47078,26 +47078,26 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `specie_IsForbidden`(vItemFk INT, vAddressFk INT) RETURNS tinyint(1) READS SQL DATA BEGIN - + DECLARE vIsForbbiden BOOL; DECLARE vLeft INT; SELECT zg.lft INTO vLeft - FROM vn.address a - JOIN vn.zoneGeo zg ON zg.name = a.postalCode + FROM vn.address a + JOIN vn.zoneGeo zg ON zg.name = a.postalCode WHERE a.id = vAddressFk; - + SELECT sgi.isForbidden INTO vIsForbbiden - FROM vn.specieGeoInvasive sgi - JOIN vn.zoneGeo zg ON zg.id = sgi.zoneGeofk + FROM vn.specieGeoInvasive sgi + JOIN vn.zoneGeo zg ON zg.id = sgi.zoneGeofk JOIN vn.itemBotanical ib ON ib.genusFk = sgi.genusFk AND sgi.specieFk IN ('sp.',ib.specieFk) WHERE vLeft BETWEEN zg.lft AND zg.rgt AND ib.itemFk = vItemFk - ORDER BY zg.`depth` DESC + ORDER BY zg.`depth` DESC LIMIT 1; RETURN IFNULL(vIsForbbiden, FALSE); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -47117,7 +47117,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `testCIF`(vCIF VARCHAR(9)) RETURNS varchar(10) CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci DETERMINISTIC BEGIN - + DECLARE vLetraInicial VARCHAR(1); DECLARE vLetraFinal VARCHAR(1); DECLARE vParteNumerica VARCHAR(7); @@ -47129,60 +47129,60 @@ BEGIN SET vLetraInicial = SUBSTR(vCIF, 1, 1); SET vLetraFinal = SUBSTR(vCIF, 9, 1); SET vParteNumerica = SUBSTR(vCIF, 2, 7); - - WHILE i < 7 DO - + + WHILE i < 7 DO + SET i = i + 1; - + SET vNumero = CAST(SUBSTR(vParteNumerica, i, 1) AS DECIMAL(1,0)); - + IF i MOD 2 THEN - + SET vNumero = vNumero * 2; SET vNumero = vNumero MOD 10 + FLOOR(vNumero/10); - + END IF; - + SET vSuma = vSuma + vNumero; - + END WHILE; - + SET vSuma = vSuma MOD 10; - + IF vSuma > 0 THEN - + SET vSuma = 10 - vSuma; - + END IF; - + -- Comprobación de dígito de control IF CAST(vLetraFinal AS DECIMAL(1,0)) = vSuma THEN - + SET vResult = TRUE; - + END IF; - + IF vSuma = 0 THEN - + SET vSuma = 10; - + END IF; - + IF CHAR(64 + vSuma) = vLetraFinal THEN - + SET vResult = TRUE; - + END IF; - + -- Sólo se aceptan letras como caracter inicial IF ASCII(vLetraInicial) < 65 OR ASCII(vLetraInicial) > 87 THEN -- Ha de ser entre la A y la W - + SET vResult = FALSE; - + END IF; - + RETURN vResult; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -47202,7 +47202,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `testNIE`(vNIE VARCHAR(9)) RETURNS tinyint(1) DETERMINISTIC BEGIN - + DECLARE vIndice INT; DECLARE vNumero VARCHAR(7); DECLARE vOperador VARCHAR(9); @@ -47211,45 +47211,45 @@ BEGIN DECLARE vLetraFinal VARCHAR(1); DECLARE vLetrasFinalesPosibles VARCHAR(24) DEFAULT "TRWAGMYFPDXBNJZSQVHLCKE"; DECLARE vLetraInicialEsIncorrecta BOOL DEFAULT FALSE; - + SET vLetraInicial = SUBSTR(vNIE, 1, 1); SET vLetraFinal = SUBSTR(vNIE, 9, 1); SET vNumero = SUBSTR(vNIE, 2, 7); CASE vLetraInicial - + WHEN 'X' THEN - + SET vOperador = "0"; - + WHEN 'Y' THEN - + SET vOperador = "1"; - + WHEN 'Z' THEN - + SET vOperador = "2"; - + ELSE - + SET vLetraInicialEsIncorrecta = TRUE; - + END CASE; - + SET vOperador = CONCAT(vOperador, vNumero); SET vParteNumerica = CAST(vOperador AS DECIMAL(8,0)); SET vIndice = Round(vParteNumerica Mod 23, 0) + 1; IF SUBSTR(vLetrasFinalesPosibles, vIndice, 1) = vLetraFinal AND vLetraInicialEsIncorrecta = FALSE THEN - + RETURN TRUE; - + ELSE - + RETURN FALSE; - + END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -47274,23 +47274,23 @@ BEGIN DECLARE vParteNumerica DECIMAL(8,0); DECLARE vLetra VARCHAR(1); DECLARE vLetrasPosibles VARCHAR(24) DEFAULT "TRWAGMYFPDXBNJZSQVHLCKE"; - + SET vLetra = SUBSTRING(vNIF, 9, 1); - + SET vParteNumerica = CAST(SUBSTRING(vNIF, 1, 8) AS DECIMAL(8,0)); - + SET vIndice = Round(vParteNumerica MOD 23, 0) + 1; - + If SUBSTRING(vLetrasPosibles, vIndice, 1) = vLetra Then - + RETURN TRUE; - + ELSE - + RETURN FALSE; - + END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -47310,21 +47310,21 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `ticketCollection_getNoPacked`(vCollectionFk INT) RETURNS varchar(100) CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci DETERMINISTIC BEGIN - + /* * return message with tickets and collection if there is tickets of a collection without expeditions - * + * * @param vCollectionFk the collection to check * @return an array with collection and tickets without expeditions - * + * */ - + DECLARE vAnswer VARCHAR(100) DEFAULT ''; IF collection_isPacked(vCollectionFk) = FALSE THEN SELECT CONCAT('Colección: ',tc.collectionFk,' Tickets: ' , GROUP_CONCAT(tc.ticketFk) ) INTO vAnswer FROM vn.ticketCollection tc - LEFT JOIN vn.expedition e ON e.ticketFk = tc.ticketFk + LEFT JOIN vn.expedition e ON e.ticketFk = tc.ticketFk WHERE tc.collectionFk = vCollectionFk AND ISNULL(e.id); END IF; @@ -47370,9 +47370,9 @@ BEGIN DROP TEMPORARY TABLE tmp.ticket, tmp.ticketTotal; - + RETURN vTotal; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -47392,7 +47392,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `ticketPositionInPath`(vTicketId INT) RETURNS varchar(10) CHARSET utf8mb3 COLLATE utf8mb3_general_ci DETERMINISTIC BEGIN - + DECLARE vRestTicketsMaxOrder INT; DECLARE vRestTicketsMinOrder INT; DECLARE vRestTicketsPacking INT; @@ -47404,7 +47404,7 @@ BEGIN DECLARE vExpeditionsCount INT; DECLARE vIsValenciaPath BOOLEAN DEFAULT FALSE; -SELECT `order` +SELECT `order` INTO PACKING_ORDER FROM state WHERE code = 'PACKING'; @@ -47415,7 +47415,7 @@ SELECT t.routeFk, t.warehouseFk, IFNULL(ts.productionOrder,0) LEFT JOIN ticketState ts on ts.ticket = t.id WHERE t.id = vTicketId; -SELECT (ag.`name` = 'VN_VALENCIA') +SELECT (ag.`name` = 'VN_VALENCIA') INTO vIsValenciaPath FROM vn2008.Rutas r JOIN vn2008.Agencias a on a.Id_Agencia = r.Id_Agencia @@ -47429,7 +47429,7 @@ IF vIsValenciaPath THEN -- Rutas Valencia FROM expedition e JOIN ticket t ON t.id = e.ticketFk WHERE t.routeFk = vMyPath; - + SELECT MAX(ts.productionOrder), MIN(ts.productionOrder) INTO vRestTicketsMaxOrder, vRestTicketsMinOrder FROM ticket t @@ -47438,7 +47438,7 @@ IF vIsValenciaPath THEN -- Rutas Valencia AND t.warehouseFk = vMyWarehouse AND t.id != vTicketid; - SELECT COUNT(*) + SELECT COUNT(*) INTO vRestTicketsPacking FROM ticket t LEFT JOIN ticketState ts on t.id = ts.ticket @@ -47493,9 +47493,9 @@ BEGIN LEFT JOIN vn2008.movement_label l ON l.Id_Movimiento = s.id WHERE ticketFk = vTicketFk ) sub; - + RETURN IFNULL(vSplitCounter,'--'); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -47544,21 +47544,21 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `ticketTotalVolumeBoxes`(vTicketId IN DETERMINISTIC BEGIN -/* +/* * Devuelve el volumen estimado del ticket sumado, en cajas * * vTicketId Numero de ticket - * + * */ DECLARE vVolumeBoxM3 DOUBLE; DECLARE vTicketTotalVolumeBoxes DECIMAL(10,1); DECLARE vVnBoxId VARCHAR(10) DEFAULT '94'; - + SELECT volume / 1000000 INTO vVolumeBoxM3 FROM packaging WHERE id = vVnBoxId; - + SET vTicketTotalVolumeBoxes = ticketTotalVolume(vTicketId) / vVolumeBoxM3; - + RETURN vTicketTotalVolumeBoxes; END ;; @@ -47583,7 +47583,7 @@ BEGIN DECLARE vWarehouseFk INT; SELECT warehouseFk INTO vWarehouseFk - FROM ticket + FROM ticket WHERE id = vTicketFk; RETURN vWarehouseFk; @@ -47606,18 +47606,18 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `ticket_CC_volume`(vTicketFk INT) RETURNS decimal(10,1) READS SQL DATA BEGIN - + DECLARE vCC DECIMAL(10,1); SELECT sum(sv.volume * IF(i.itemPackingTypeFk = 'H', vc.dutchCompressionRate, 1)) / (p.volume / 1000000) INTO vCC - FROM vn.saleVolume sv - JOIN vn.sale s ON s.id = sv.saleFk - JOIN vn.item i ON i.id = s.itemFk + FROM vn.saleVolume sv + JOIN vn.sale s ON s.id = sv.saleFk + JOIN vn.item i ON i.id = s.itemFk JOIN vn.packaging p ON p.id = 'CC' - JOIN vn.volumeConfig vc + JOIN vn.volumeConfig vc WHERE sv.ticketFk = vTicketFk; - + RETURN vCC; END ;; @@ -47639,44 +47639,44 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `ticket_get`(vParamFk INT) RETURNS int(11) READS SQL DATA proc:BEGIN - + /* Devuelve el número de ticket o collection consultando en varias tablas posibles - * + * * @param vParamFk Número a validar * @return vValidFk Identificador validado */ - + DECLARE vValidFk INT; -- Tabla vn.saleGroup SELECT s.ticketFk INTO vValidFk FROM vn.sale s JOIN vn.saleGroupDetail sgd ON sgd.saleFk = s.id - JOIN vn.saleGroup sg ON sg.id = sgd.saleGroupFk + JOIN vn.saleGroup sg ON sg.id = sgd.saleGroupFk WHERE sg.id = vParamFk AND sg.created > TIMESTAMPADD(WEEK,-1, util.VN_CURDATE()) LIMIT 1; - + IF vValidFk THEN - + RETURN vValidFk; - + LEAVE proc; - + END IF; -- Tabla vn.collection SELECT c.id INTO vValidFk - FROM vn.collection c + FROM vn.collection c WHERE c.id = vParamFk AND c.created > TIMESTAMPADD(WEEK,-1, util.VN_CURDATE()); - + IF vValidFk THEN - + RETURN vValidFk; - + LEAVE proc; - + END IF; -- Tabla vn.ticket @@ -47684,17 +47684,17 @@ proc:BEGIN FROM vn.ticket t WHERE t.id = vParamFk AND t.shipped > TIMESTAMPADD(WEEK,-1, util.VN_CURDATE()); - + IF vValidFk THEN - + RETURN vValidFk; - + LEAVE proc; - + END IF; RETURN NULL; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -47720,8 +47720,8 @@ BEGIN * @vTicketFk Id del ticket a calcular */ DECLARE deliveryPrice DECIMAL (10,2); - - IF (SELECT isVolumetric FROM ticket t JOIN zone z ON t.zoneFk = z.id + + IF (SELECT isVolumetric FROM ticket t JOIN zone z ON t.zoneFk = z.id WHERE t.id = vTicketFk) THEN SELECT SUM(sv.freight) INTO deliveryPrice FROM vn.saleVolume sv @@ -47732,7 +47732,7 @@ BEGIN LEFT JOIN expedition e ON e.ticketFk = t.id JOIN expeditionBoxVol ebv ON ebv.boxFk = e.freightItemFk WHERE t.id = vTicketFk; - + END IF; RETURN deliveryPrice; END ;; @@ -47756,16 +47756,16 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `ticket_getWeight`(vTicketFk INT) RET BEGIN /** * Devuelve el peso total del ticket - * + * * @return Total peso */ - + DECLARE vWeight DECIMAL(10,3); SELECT sum(weight) INTO vWeight FROM saleVolume WHERE ticketFk = vTicketFk; - + RETURN vWeight; END ;; @@ -47787,15 +47787,15 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `ticket_HasUbication`(vTicketFk INT) RETURNS tinyint(1) READS SQL DATA BEGIN - + DECLARE hasUbication BOOL; SELECT COUNT(*) INTO hasUbication FROM vn.ticket t JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk - WHERE rm.beachFk + WHERE rm.beachFk AND t.id = vTicketFk; - + RETURN hasUbication; END ;; @@ -47944,7 +47944,7 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `timeWorkerControl_getDirection`(vUse READS SQL DATA BEGIN /** - * Verifica la dirección de la fichada + * Verifica la dirección de la fichada * @param vUserFk Identificador del trabajador * @param vTimed Hora de la fichada * @return Retorna sentido de la fichada 'in, out, middle' @@ -47957,40 +47957,40 @@ BEGIN DECLARE vDayStayMax INT; DECLARE vTimedSeconds INT; DECLARE vLastTimeIn INT; - + SELECT UNIX_TIMESTAMP(vTimed) INTO vTimedSeconds; - + SELECT dayStayMax INTO vDayStayMax FROM vn.workerTimeControlParams; SELECT timed, direction INTO vNext,vNextDirection - FROM vn.workerTimeControl - WHERE userFk = vUserFk + FROM vn.workerTimeControl + WHERE userFk = vUserFk AND direction IN ('in','out') AND timed > vTimed ORDER BY timed ASC LIMIT 1; - + SELECT timed, direction INTO vPrevious, vPreviousDirection - FROM vn.workerTimeControl - WHERE userFk = vUserFk + FROM vn.workerTimeControl + WHERE userFk = vUserFk AND direction IN ('in','out') AND timed < vTimed ORDER BY timed DESC - LIMIT 1; - - IF (vTimedSeconds - UNIX_TIMESTAMP(vPrevious) + UNIX_TIMESTAMP(vNext) - vTimedSeconds)<= vDayStayMax AND vPreviousDirection = 'in' AND vNextDirection = 'out' THEN + LIMIT 1; + + IF (vTimedSeconds - UNIX_TIMESTAMP(vPrevious) + UNIX_TIMESTAMP(vNext) - vTimedSeconds)<= vDayStayMax AND vPreviousDirection = 'in' AND vNextDirection = 'out' THEN RETURN 'middle'; END IF; - - + + IF (vTimedSeconds> UNIX_TIMESTAMP(vPrevious)) THEN - IF vPreviousDirection = 'in' THEN + IF vPreviousDirection = 'in' THEN RETURN 'out'; ELSE SELECT UNIX_TIMESTAMP(MAX(timed)) INTO vLastTimeIn - FROM vn.workerTimeControl - WHERE userFk = vUserFk + FROM vn.workerTimeControl + WHERE userFk = vUserFk AND direction ='in' AND timed < vPrevious; IF vTimedSeconds - vLastTimeIn <= vDayStayMax THEN @@ -48044,11 +48044,11 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `travel_getForLogiflora`(vLanded DATE, vWarehouseFk INT) RETURNS int(11) READS SQL DATA BEGIN - + /** * Devuelve un número de travel para compras de Logiflora a partir de la fecha de llegada y del almacén. * Si no existe lo genera. - * + * * @param vLanded Fecha de llegada al almacén * @param vWarehouseFk Identificador de vn.warehouse */ @@ -48056,8 +48056,8 @@ BEGIN DECLARE vTravelFk INT; IF vLanded THEN - - SELECT IFNULL(MAX(tr.id),0) INTO vTravelFk + + SELECT IFNULL(MAX(tr.id),0) INTO vTravelFk FROM vn.travel tr JOIN vn.warehouse wIn ON wIn.id = tr.warehouseInFk JOIN vn.warehouse wOut ON wOut.id = tr.warehouseOutFk @@ -48068,14 +48068,14 @@ BEGIN AND landed = vLanded; IF NOT vTravelFk THEN - + INSERT INTO vn.travel(landed, shipped, warehouseInFk, warehouseOutFk, agencyModeFk) - SELECT vLanded, util.VN_CURDATE(), vWarehouseFk, wOut.id, am.id - FROM vn.warehouse wOut + SELECT vLanded, util.VN_CURDATE(), vWarehouseFk, wOut.id, am.id + FROM vn.warehouse wOut JOIN vn.agencyMode am ON am.name = 'LOGIFLORA' WHERE wOut.name = 'Holanda'; - - SELECT MAX(tr.id) INTO vTravelFk + + SELECT MAX(tr.id) INTO vTravelFk FROM vn.travel tr JOIN vn.warehouse wIn ON wIn.id = tr.warehouseInFk JOIN vn.warehouse wOut ON wOut.id = tr.warehouseOutFk @@ -48083,11 +48083,11 @@ BEGIN AND wOut.name = 'Holanda' AND landed = vLanded; END IF; - + END IF; - + RETURN vTravelFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -48114,21 +48114,21 @@ BEGIN DECLARE vChar INT; SET vLength = length(vString); - + WHILE vLength > 0 DO - + SET vChar = MID(vString,vLength,1); - + SET vSeed = vSeed + ASCII(vChar); - + SET vLength = vLength - 1; - + END WHILE; SET vCode = FLOOR(SQRT(vSeed)*1000000) mod 1000; RETURN vCode; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -48155,21 +48155,21 @@ BEGIN DECLARE vChar INT; SET vLength = length(vString); - + WHILE vLength > 0 DO - + SET vChar = MID(vString,vLength,1); - + SET vSeed = vSeed + ASCII(vChar); - + SET vLength = vLength - 1; - + END WHILE; SET vCode = FLOOR(SQRT(vSeed)*1000000) mod 1000; RETURN vCode; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -48230,15 +48230,15 @@ BEGIN * @param vTimeOut * @return vNigthlyHours */ - DECLARE vNigthlyHours DECIMAL(5,2); + DECLARE vNigthlyHours DECIMAL(5,2); DECLARE vSecondsPerHour INT(4) DEFAULT 3600; - + SELECT GREATEST(0, TIMESTAMPDIFF(SECOND, - IF(TIME(vTimeIn) BETWEEN endNightlyHours AND startNightlyHours, - CONCAT(DATE(vTimeIn), ' ', startNightlyHours), + IF(TIME(vTimeIn) BETWEEN endNightlyHours AND startNightlyHours, + CONCAT(DATE(vTimeIn), ' ', startNightlyHours), vTimeIn), - IF(TIME(vTimeOut) BETWEEN endNightlyHours AND startNightlyHours, - CONCAT(DATE(vTimeOut), ' ', endNightlyHours), + IF(TIME(vTimeOut) BETWEEN endNightlyHours AND startNightlyHours, + CONCAT(DATE(vTimeOut), ' ', endNightlyHours), vTimeOut))) / vSecondsPerHour INTO vNigthlyHours FROM vn.workerTimeControlConfig; @@ -48270,47 +48270,47 @@ BEGIN SELECT dayStayMax INTO vDayStayMax FROM workerTimeControlParams; - + SELECT timeWorkerControl_getDirection(vUserFk,vTimed) INTO vDirection; IF vDirection = 'out' THEN - + SELECT MAX(timed) INTO vLastIn - FROM workerTimeControl - WHERE userFk = vUserFk + FROM workerTimeControl + WHERE userFk = vUserFk AND direction = 'in' AND timed < vTimed; - + UPDATE workerTimeControl wtc SET wtc.direction = 'middle' WHERE userFk = vUserFk AND direction = 'out' AND timed BETWEEN vLastIn AND vTimed; - + ELSE IF vDirection = 'in' THEN - - SELECT COUNT(*) INTO vHasDirectionOut + + SELECT COUNT(*) INTO vHasDirectionOut FROM workerTimeControl wtc - WHERE userFk = vUserFk + WHERE userFk = vUserFk AND direction = 'out' - AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); + AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); UPDATE workerTimeControl wtc SET wtc.direction = IF (vHasDirectionOut,'middle','out') WHERE userFk = vUserFk AND direction = 'in' - AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); + AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); END IF; END IF; - + INSERT INTO workerTimeControl(userFk, timed, warehouseFk, direction, manual) VALUES(vUserFk, vTimed, vWarehouseFk, vDirection, vIsManual); - + SET vLastInsertedId = LAST_INSERT_ID(); - + CALL workerTimeControlSOWP(vUserFk, vTimed); - + RETURN vLastInsertedId; END ;; DELIMITER ; @@ -48339,47 +48339,47 @@ BEGIN SELECT dayStayMax INTO vDayStayMax FROM workerTimeControlParams; - + SELECT timeWorkerControl_getDirection(vUserFk,vTimed) INTO vDirection; IF vDirection = 'out' THEN - + SELECT MAX(timed) INTO vLastIn - FROM workerTimeControl - WHERE userFk = vUserFk + FROM workerTimeControl + WHERE userFk = vUserFk AND direction = 'in' AND timed < vTimed; - + UPDATE workerTimeControl wtc SET wtc.direction = 'middle' WHERE userFk = vUserFk AND direction = 'out' AND timed BETWEEN vLastIn AND vTimed; - + ELSE IF vDirection = 'in' THEN - - SELECT COUNT(*) INTO vHasDirectionOut + + SELECT COUNT(*) INTO vHasDirectionOut FROM workerTimeControl wtc - WHERE userFk = vUserFk + WHERE userFk = vUserFk AND direction = 'out' - AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); + AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); UPDATE workerTimeControl wtc SET wtc.direction = IF (vHasDirectionOut,'middle','out') WHERE userFk = vUserFk AND direction = 'in' - AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); + AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); END IF; END IF; - + INSERT INTO workerTimeControl(userFk, timed, warehouseFk, direction, manual) VALUES(vUserFk, vTimed, vWarehouseFk, vDirection, vIsManual); - + SET vLastInsertedId = LAST_INSERT_ID(); - + CALL workerTimeControlSOWP(vUserFk, vTimed); - + RETURN vLastInsertedId; END ;; DELIMITER ; @@ -48490,17 +48490,17 @@ BEGIN * @return Devuelve TRUE en caso de que este trabajando. Si se encuentra en un descanso devolverá FALSE */ DECLARE vLastIn DATETIME ; - + SELECT MAX(timed) INTO vLastIn - FROM vn.workerTimeControl + FROM vn.workerTimeControl WHERE userFk = vWorkerFk AND direction = 'in'; - IF (SELECT MOD(COUNT(*),2) - FROM vn.workerTimeControl - WHERE userFk = vWorkerFk AND + IF (SELECT MOD(COUNT(*),2) + FROM vn.workerTimeControl + WHERE userFk = vWorkerFk AND timed >= vLastIn - ) THEN + ) THEN RETURN TRUE; ELSE RETURN FALSE; @@ -48594,7 +48594,7 @@ BEGIN SET `type` = vType, `name` = vName, parentFk = vParentFk; - + SET vSelf = LAST_INSERT_ID(); UPDATE zoneGeoRecalc SET isChanged = TRUE; @@ -48618,7 +48618,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `addNoteFromDelivery`(idTicket INT,nota TEXT) BEGIN - + DECLARE observationTypeFk INT DEFAULT 3; /*3 = REPARTIDOR*/ INSERT INTO ticketObservation(ticketFk,observationTypeFk,description) @@ -48646,23 +48646,23 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `addressTaxArea`() READS SQL DATA BEGIN /** - * Devuelve el taxArea para un conjunto de Consignatarios y empresas, + * Devuelve el taxArea para un conjunto de Consignatarios y empresas, * * @table tmp.addressCompany(addressFk, companyFk) valores a calcular * @return tmp.addressTaxArea(addressFk,companyFk) */ - + DROP TEMPORARY TABLE IF EXISTS tmp.addressTaxArea; CREATE TEMPORARY TABLE tmp.addressTaxArea (PRIMARY KEY (addressFk, companyFk)) ENGINE = MEMORY - SELECT CASE - WHEN (NOT IFNULL(auClient.isUeeMember, cClient.isUeeMember) OR NOT cSupplier.isUeeMember) - AND NOT (auSupplier.id <=> auClient.id) THEN + SELECT CASE + WHEN (NOT IFNULL(auClient.isUeeMember, cClient.isUeeMember) OR NOT cSupplier.isUeeMember) + AND NOT (auSupplier.id <=> auClient.id) THEN 'WORLD' - WHEN cClient.isUeeMember AND cSupplier.isUeeMember AND c.countryFk != s.countryFk AND c.isVies THEN + WHEN cClient.isUeeMember AND cSupplier.isUeeMember AND c.countryFk != s.countryFk AND c.isVies THEN 'CEE' - WHEN a.isEqualizated AND cClient.code = 'ES' THEN + WHEN a.isEqualizated AND cClient.code = 'ES' THEN 'EQU' ELSE 'NATIONAL' @@ -48703,27 +48703,27 @@ BEGIN * @param vAddress id de la direccion * @param vWarehouse id del warehouse * @return vShipped la primera fecha disponible y vLanded la fecha de llegada/recojida -*/ +*/ DECLARE vAgency INT; DECLARE vShipped DATE; DECLARE vLanded DATE DEFAULT util.VN_CURDATE(); SELECT agencyFk INTO vAgency FROM agencyMode WHERE id= vAgencyMode; l: LOOP - + CALL agencyHourGetShipped(vLanded,vAddress,vAgency); - SELECT shipped INTO vShipped + SELECT shipped INTO vShipped FROM tmp.agencyHourGetShipped WHERE warehouseFk = vWarehouse LIMIT 1; - + IF vShipped THEN LEAVE l; END IF; - + SET vLanded = DATE_ADD(vLanded, INTERVAL +1 DAY); - + END LOOP; - + SELECT vShipped,vLanded; END ;; DELIMITER ; @@ -48774,7 +48774,7 @@ BEGIN LIMIT 1 ) t WHERE IF(vDated = util.VN_CURDATE(), t.maxHour > HOUR(util.VN_NOW()), TRUE) AND t.substractDay < 225; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -48797,14 +48797,14 @@ BEGIN * DEPRECATED usar zoneGetWarehouse * Devuelve el listado de agencias disponibles para la fecha, * dirección y warehouuse pasadas - * + * * @param vAddress no puede ser NULL * @param vWarehouse warehouse donde comprobaremos las agencias y fecha * @param vDate Fecha de recogida * @table agencyModeWarehouseList Listado de agencias disponibles */ DECLARE vAgency INT; - DECLARE vDone BOOL DEFAULT FALSE; + DECLARE vDone BOOL DEFAULT FALSE; DECLARE vCur CURSOR FOR SELECT DISTINCT a.id FROM agency a @@ -48828,13 +48828,13 @@ BEGIN PRIMARY KEY(id) ) ENGINE = MEMORY; - + OPEN vCur; FETCH vCur INTO vAgency; WHILE NOT vDone DO - + INSERT INTO tmp.agencyModeWarehouseList SELECT am.id, am.name, am.description,am.deliveryMethodFk, TIMESTAMPADD(DAY, -ah.substractDay, vDate), w.name FROM agencyHour ah @@ -48863,7 +48863,7 @@ BEGIN END WHILE; CLOSE vCur; - + SELECT * FROM tmp.agencyModeWarehouseList; DROP TEMPORARY TABLE tmp.agencyModeWarehouseList; END ;; @@ -48889,9 +48889,9 @@ BEGIN CALL vn.agencyHourGetShipped(vDate, vAddress, vAgency); SELECT * FROM tmp.agencyHourGetShipped; - + DROP TEMPORARY TABLE IF EXISTS tmp.agencyHourGetShipped; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -48929,7 +48929,7 @@ BEGIN DECLARE cWarehouses CURSOR FOR SELECT warehouseFk, shipped FROM tmp.zoneGetShipped; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; @@ -48938,7 +48938,7 @@ BEGIN CALL vn.zone_getShipped (vDate, vAddress, vAgencyMode, FALSE); DROP TEMPORARY TABLE IF EXISTS tmp.availableCalc; - CREATE TEMPORARY TABLE tmp.availableCalc( + CREATE TEMPORARY TABLE tmp.availableCalc( calcFk INT UNSIGNED, PRIMARY KEY (calcFk) ) @@ -48949,7 +48949,7 @@ BEGIN l: LOOP SET vDone = FALSE; FETCH cWarehouses INTO vWarehouse, vShipment; - + IF vDone THEN LEAVE l; END IF; @@ -48982,7 +48982,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `bankEntity_checkBic`(vBic VARCHAR(2 BEGIN /** * If the bic length is Incorrect throw exception - * + * * @param vBic bic code */ @@ -48990,7 +48990,7 @@ BEGIN SELECT bicLength INTO vConfigBicLenght FROM vn.bankEntityConfig bec; - + IF LENGTH(vBic) <> vConfigBicLenght THEN CALL util.throw(CONCAT('bic must be of length ', vConfigBicLenght )); END IF; @@ -49017,14 +49017,14 @@ BEGIN * Manda correo cuando caduca un seguro * de los leasing * -*/ +*/ INSERT INTO mail (receiver,replyTo,subject,body) SELECT 'administracion@verdnatura.es' receiver, 'noreply@verdnatura.es' replyTo, CONCAT('El seguro de la poliza ',b.id,' ',b.bank,' ha finalizado.') subject, CONCAT('El seguro de la poliza ',b.id,' ',b.bank,' ha finalizado.') body - FROM vn.bankPolicy bp - LEFT JOIN vn.supplier s + FROM vn.bankPolicy bp + LEFT JOIN vn.supplier s ON s.id = bp.supplierFk LEFT JOIN vn.bank b ON b.id = bp.bankFk @@ -49253,19 +49253,19 @@ BEGIN DECLARE vIsFeedStock BOOL; DECLARE vWeight DECIMAL(10,2); DECLARE vPacking INT; - - SELECT b.entryFk, - b.itemFk, - i.packingOut, - ic.merchandise, + + SELECT b.entryFk, + b.itemFk, + i.packingOut, + ic.merchandise, vc.standardFlowerBox, b.weight, - b.packing - INTO - vEntryFk, - vItemFk, - vPackingOut, - vIsMerchandise, + b.packing + INTO + vEntryFk, + vItemFk, + vPackingOut, + vIsMerchandise, vStandardFlowerBox, vWeight, vPacking @@ -49273,7 +49273,7 @@ BEGIN LEFT JOIN item i ON i.id = b.itemFk LEFT JOIN itemType it ON it.id = i.typeFk LEFT JOIN itemCategory ic ON ic.id = it.categoryFk - LEFT JOIN packaging p ON p.id = b.packageFk AND NOT p.isBox + LEFT JOIN packaging p ON p.id = b.packageFk AND NOT p.isBox JOIN volumeConfig vc ON TRUE WHERE b.id = vSelf; @@ -49290,7 +49290,7 @@ BEGIN warehouseFk = vWarehouse, cm3 = buy_getUnitVolume(vSelf), cm3Delivery = IFNULL((vStandardFlowerBox * 1000) / vPackingOut, buy_getUnitVolume(vSelf)); - + IF vWeight AND vPacking THEN UPDATE itemCost SET grams = vWeight * 1000 / vPacking @@ -49311,7 +49311,7 @@ BEGIN WHERE b.id = vSelf; END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -49358,10 +49358,10 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_getSplit`(vSelf INT, vDated DATE) BEGIN /** - * Devuelve tantos registros como etiquetas se necesitan para cada uno de los cubos o cajas de - * las ventas correspondientes a la compra que se pasa como parámetro, en los almacenes que tienen + * Devuelve tantos registros como etiquetas se necesitan para cada uno de los cubos o cajas de + * las ventas correspondientes a la compra que se pasa como parámetro, en los almacenes que tienen * habilitada la venta de productos con stock virtual, aunque los productos pueden ser de cualquier tipo. - * + * * @param vSelf Identificador de vn.buy * @param vDated Fecha de preparación de las ventas que queremos etiquetar */ @@ -49436,7 +49436,7 @@ BEGIN WHILE vLabels >= vCounter DO INSERT INTO tmp.split SET - id = vSaleFk, + id = vSaleFk, labels = vLabels, counter = vCounter; @@ -49458,11 +49458,11 @@ BEGIN -- Devuelve los splits creados SELECT CONCAT(sp.counter,'/',sp.labels) labels, COALESCE(sfc.nickname, sfa.nickname, a.nickname) destination, - s.itemFk, - i.longName, - i.`size`, - vn.ticketSplitCounter(t.id) counter, - IF(sfa.id OR sfc.id, + s.itemFk, + i.longName, + i.`size`, + vn.ticketSplitCounter(t.id) counter, + IF(sfa.id OR sfc.id, a.nickname, CONCAT(a.id, ' ', p.`name`,' (', c.`code`,')')) destination2 FROM tmp.split sp @@ -49507,12 +49507,12 @@ BEGIN item_getVolume(b.itemFk, b.packageFk)) / vc.trolleyM3 / 1000000 ,1) AS DECIMAL(10,2)) carros , CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) * item_getVolume(b.itemFk, b.packageFk)) / vc.palletM3 / 1000000,1) AS DECIMAL(10,2)) espais - FROM buy b + FROM buy b JOIN tmp.buy tb ON tb.buyFk = b.id JOIN volumeConfig vc JOIN item i ON i.id = b.itemFk JOIN itemType it ON it.id = i.typeFk - LEFT JOIN temperature t ON t.code = it.temperatureFk + LEFT JOIN temperature t ON t.code = it.temperatureFk GROUP BY Temp; END ;; DELIMITER ; @@ -49532,21 +49532,21 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_getVolumeByAgency`(vDated DATE, vAgencyFk INT) BEGIN - + DROP TEMPORARY TABLE IF EXISTS tmp.buy; CREATE TEMPORARY TABLE tmp.buy (buyFk INT NOT NULL, PRIMARY KEY (buyFk)) ENGINE = MEMORY; - INSERT INTO tmp.buy + INSERT INTO tmp.buy SELECT b.id - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk WHERE t.landed = vDated AND t.agencyModeFk IN (0, vAgencyFk); CALL buy_getVolume(); DROP TEMPORARY TABLE tmp.buy; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -49565,19 +49565,19 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_getVolumeByEntry`(vEntryFk INT) BEGIN - + DROP TEMPORARY TABLE IF EXISTS tmp.buy; CREATE TEMPORARY TABLE tmp.buy (buyFk INT NOT NULL, PRIMARY KEY (buyFk)) ENGINE = MEMORY; - - INSERT INTO tmp.buy + + INSERT INTO tmp.buy SELECT b.id - FROM buy b - JOIN entry e ON e.id = b.entryFk + FROM buy b + JOIN entry e ON e.id = b.entryFk WHERE e.id = vEntryFk; CALL buy_getVolume(); DROP TEMPORARY TABLE tmp.buy; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -49665,12 +49665,12 @@ BEGIN * inserta en tmp.buyRecalc las compras de un awb * * @param awbFk - */ + */ DROP TEMPORARY TABLE IF EXISTS tmp.buyRecalc; CREATE TEMPORARY TABLE tmp.buyRecalc SELECT b.id - FROM buy b + FROM buy b JOIN entry e ON e.id = b.entryFk JOIN duaEntry de ON de.entryFk = e.id JOIN dua d ON d.id = de.duaFk @@ -49702,7 +49702,7 @@ BEGIN * Recalcula los precios de una compra * * @param vBuyFk - */ + */ DROP TEMPORARY TABLE IF EXISTS tmp.buyRecalc; CREATE TEMPORARY TABLE tmp.buyRecalc @@ -49733,12 +49733,12 @@ BEGIN * Recalcula los precios de una entrada * * @param vEntryFk - */ + */ DROP TEMPORARY TABLE IF EXISTS tmp.buyRecalc; CREATE TEMPORARY TABLE tmp.buyRecalc SELECT b.id - FROM buy b + FROM buy b WHERE b.entryFk = vEntryFk; CALL buy_recalcPrices(); @@ -49778,12 +49778,12 @@ BEGIN LIMIT 0; INSERT INTO tBuy(buyFk) - SELECT b.id + SELECT b.id FROM buy b JOIN tmp.ekt t ON t.ektFk = b.ektFk JOIN vn.entry en ON en.id = b.entryFk JOIN vn.travel tr ON tr.id = en.travelFk - JOIN vn.warehouse w ON w.id = tr.warehouseInFk + JOIN vn.warehouse w ON w.id = tr.warehouseInFk JOIN vn.country c ON c.id = w.countryFk AND c.code = 'NL'; SELECT b.id buy, i.doPhoto do_photo, b.stickers - CAST(b.printedStickers AS INT) stickersToPrint @@ -49849,7 +49849,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_updatePacking`(vWarehouseFk INT, vItemFk INT, vPacking INT) BEGIN /** - * Actualiza packing + * Actualiza packing * * @param vWarehouseFk warehouse del item * @param vItemFk id del item @@ -49859,8 +49859,8 @@ BEGIN UPDATE buy b JOIN tmp.buyUltimate bu ON b.id = bu.buyFk - SET b.packing = vPacking - WHERE bu.warehouseFk = vWarehouseFk + SET b.packing = vPacking + WHERE bu.warehouseFk = vWarehouseFk AND bu.itemFk = vItemFk; DROP TEMPORARY TABLE tmp.buyUltimate; @@ -49899,7 +49899,7 @@ BEGIN */ DROP TEMPORARY TABLE IF EXISTS tmp.item; CREATE TEMPORARY TABLE tmp.item - ENGINE = MEMORY + ENGINE = MEMORY SELECT vItemFk itemFk; CALL catalog_calculate(vLanded, vAddressFk, vAgencyModeFk); @@ -49921,7 +49921,7 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `catalog_calculate`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT) -BEGIN +BEGIN /** * Calcula los articulos disponibles y sus precios * @@ -49929,7 +49929,7 @@ BEGIN * @param vLanded Fecha de recepcion de mercancia * @param vAddressFk Id del consignatario * @param vAgencyModeFk Id de la agencia - * @return tmp.ticketCalculateItem(itemFk, available, producer, + * @return tmp.ticketCalculateItem(itemFk, available, producer, * item, size, stems, category, inkFk, image, origin, price) * @return tmp.ticketLot(warehouseFk, itemFk, available, buyFk) * @return tmp.ticketComponent @@ -49964,22 +49964,22 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.ticketCalculateItem; CREATE TEMPORARY TABLE tmp.ticketCalculateItem( - itemFk INT(11) NOT NULL, + itemFk INT(11) NOT NULL, available INT(11), - producer VARCHAR(50), - item VARCHAR(50), - size INT(10) UNSIGNED, - stems INT(11), - category VARCHAR(3), - inkFk VARCHAR(3), + producer VARCHAR(50), + item VARCHAR(50), + size INT(10) UNSIGNED, + stems INT(11), + category VARCHAR(3), + inkFk VARCHAR(3), image VARCHAR(50), - origin VARCHAR(3), + origin VARCHAR(3), price DECIMAL(10,2), priceKg DECIMAL(10,2), `grouping` INT(10) UNSIGNED, PRIMARY KEY `itemFk` (`itemFk`) ) ENGINE = MEMORY DEFAULT CHARSET=utf8; - + OPEN cTravelTree; l: LOOP @@ -50001,20 +50001,20 @@ BEGIN bu.buyFk, vZoneFk FROM `cache`.available a - LEFT JOIN cache.availableNoRaids anr ON anr.item_id = a.item_id + LEFT JOIN cache.availableNoRaids anr ON anr.item_id = a.item_id AND anr.calc_id = vAvailableNoRaidsCalc JOIN tmp.item i ON i.itemFk = a.item_id JOIN vn.item it ON it.id = i.itemFk JOIN vn.`zone` z ON z.id = vZoneFk - LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = a.item_id - LEFT JOIN edi.supplyResponse sr ON sr.ID = it.supplyResponseFk - LEFT JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID + LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = a.item_id + LEFT JOIN edi.supplyResponse sr ON sr.ID = it.supplyResponseFk + LEFT JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID LEFT JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID LEFT JOIN (SELECT isVNHSupplier, isEarlyBird, TRUE AS itemAllowed FROM vn.addressFilter af - JOIN (SELECT ad.provinceFk, p.countryFk, ad.isLogifloraAllowed - FROM vn.address ad - JOIN vn.province p ON p.id = ad.provinceFk + JOIN (SELECT ad.provinceFk, p.countryFk, ad.isLogifloraAllowed + FROM vn.address ad + JOIN vn.province p ON p.id = ad.provinceFk WHERE ad.id = vAddressFk ) sub2 ON sub2.provinceFk <=> IFNULL(af.provinceFk, sub2.provinceFk) AND sub2.countryFk <=> IFNULL(af.countryFk, sub2.countryFk) @@ -50031,13 +50031,13 @@ BEGIN JOIN vn.itemType itt ON itt.id = it.typeFk JOIN vn.itemCategory itc on itc.id = itt.categoryFk JOIN vn.address ad ON ad.id = vAddressFk - LEFT JOIN vn.clientItemType cit + LEFT JOIN vn.clientItemType cit ON cit.clientFk = ad.clientFk AND cit.itemTypeFk = itt.id - LEFT JOIN vn.zoneItemType zit + LEFT JOIN vn.zoneItemType zit ON zit.zoneFk = vZoneFk AND zit.itemTypeFk = itt.id - LEFT JOIN vn.agencyModeItemType ait + LEFT JOIN vn.agencyModeItemType ait ON ait.agencyModeFk = vAgencyModeFk AND ait.itemTypeFk = itt.id WHERE a.calc_id = vAvailableCalc @@ -50130,7 +50130,7 @@ BEGIN * Calcula los componentes de los articulos de tmp.ticketLot * * @param vZoneFk para calcular el transporte - * @param vAddressFk Consignatario + * @param vAddressFk Consignatario * @param vShipped dia de salida del pedido * @param vWarehouseFk warehouse de salida del pedido * @table tmp.ticketLot (warehouseFk, available, itemFk, buyFk, zoneFk) @@ -50144,7 +50144,7 @@ BEGIN SELECT clientFk INTO vClientFK FROM address WHERE id = vAddressFk; - + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentCalculate (PRIMARY KEY (itemFk, warehouseFk)) ENGINE = MEMORY @@ -50156,7 +50156,7 @@ BEGIN IFNULL(pf.packing, GREATEST(b.grouping, b.packing)) packing, IFNULL(pf.`grouping`, b.`grouping`) `grouping`, ABS(IFNULL(pf.box, b.groupingMode)) groupingMode, - tl.buyFk, + tl.buyFk, i.typeFk, IF(i.hasKgPrice, b.weight / b.packing, NULL) weightGrouping FROM tmp.ticketLot tl @@ -50164,7 +50164,7 @@ BEGIN JOIN item i ON i.id = tl.itemFk JOIN itemType it ON it.id = i.typeFk JOIN itemCategory ic ON ic.id = it.categoryFk - LEFT JOIN specialPrice sp ON sp.itemFk = i.id + LEFT JOIN specialPrice sp ON sp.itemFk = i.id AND sp.clientFk = vClientFk LEFT JOIN ( SELECT * FROM ( @@ -50183,7 +50183,7 @@ BEGIN LIMIT 10000000000000000000 ) tpf GROUP BY tpf.itemFk, tpf.warehouseFk - ) pf ON pf.itemFk = tl.itemFk + ) pf ON pf.itemFk = tl.itemFk AND pf.warehouseFk = tl.warehouseFk WHERE b.buyingValue + b.freightValue + b.packageValue + b.comissionValue > 0.01 AND ic.merchandise @@ -50215,10 +50215,10 @@ BEGIN FROM tmp.ticketComponent tc JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tc.itemFk AND tcc.warehouseFk = tc.warehouseFk GROUP BY tc.itemFk, warehouseFk; - + -- RECOBRO INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost) - SELECT tcb.warehouseFk, tcb.itemFk, c2.id, + SELECT tcb.warehouseFk, tcb.itemFk, c2.id, ROUND(tcb.base * LEAST( MAX(GREATEST(IFNULL(cr.priceIncreasing,0), @@ -50249,29 +50249,29 @@ BEGIN ROUND(base * (0.01 + wm.pricesModifierRate), 3) manaAuto FROM tmp.ticketComponentBase tcb JOIN `client` c on c.id = vClientFk - JOIN workerMana wm ON c.salesPersonFk = wm.workerFk + JOIN workerMana wm ON c.salesPersonFk = wm.workerFk JOIN vn.component c2 ON c2.code = 'autoMana' WHERE wm.isPricesModifierActivated HAVING manaAuto <> 0; - + -- Precios especiales INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost) SELECT tcb.warehouseFk, tcb.itemFk, c2.id, GREATEST( - IFNULL(ROUND(tcb.base * c2.tax, 4), 0), + IFNULL(ROUND(tcb.base * c2.tax, 4), 0), IF(i.hasMinPrice, i.minPrice,0) - tcc.rate3 ) cost FROM tmp.ticketComponentBase tcb JOIN vn.component c2 ON c2.code = 'lastUnitsDiscount' - JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tcb.itemFk AND tcc.warehouseFk = tcb.warehouseFk + JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tcb.itemFk AND tcc.warehouseFk = tcb.warehouseFk LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk JOIN vn.item i ON i.id = tcb.itemFk WHERE sp.value IS NULL AND i.supplyResponseFk IS NULL; - -- Individual + -- Individual INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost) SELECT tcb.warehouseFk, tcb.itemFk, @@ -50282,10 +50282,10 @@ BEGIN JOIN vn.client c ON c.id = vClientFk JOIN vn.businessType bt ON bt.code = c.businessTypeFk WHERE bt.code = 'individual'; - + -- Venta por paquetes INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost) - SELECT tcc.warehouseFk, tcc.itemFk, c2.id, tcc.rate2 - tcc.rate3 + SELECT tcc.warehouseFk, tcc.itemFk, c2.id, tcc.rate2 - tcc.rate3 FROM tmp.ticketComponentCalculate tcc JOIN vn.component c2 ON c2.code = 'salePerPackage' JOIN buy b ON b.id = tcc.buyFk @@ -50297,7 +50297,7 @@ BEGIN SELECT vZoneFk id; CALL zone_getOptionsForShipment(vShipped, TRUE); - + -- Reparto INSERT INTO tmp.ticketComponent SELECT tcc.warehouseFK, @@ -50311,7 +50311,7 @@ BEGIN JOIN agencyMode am ON am.id = z.agencyModeFk JOIN vn.volumeConfig vc JOIN vn.component c2 ON c2.code = 'delivery' - LEFT JOIN itemCost ic ON ic.warehouseFk = tcc.warehouseFk + LEFT JOIN itemCost ic ON ic.warehouseFk = tcc.warehouseFk AND ic.itemFk = tcc.itemFk HAVING cost <> 0; @@ -50364,9 +50364,9 @@ BEGIN CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) price, CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) / weightGrouping priceKg FROM tmp.ticketComponentCalculate tcc - JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk + JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk AND tcs.warehouseFk = tcc.warehouseFk - WHERE IFNULL(tcs.classRate, 1) = 1 + WHERE IFNULL(tcs.classRate, 1) = 1 AND tcc.groupingMode < 2 AND (tcc.packing > tcc.`grouping` or tcc.groupingMode = 0) GROUP BY tcs.warehouseFk, tcs.itemFk; @@ -50403,7 +50403,7 @@ BEGIN SELECT * FROM tmp.ticketComponentRate ORDER BY price LIMIT 10000000000000000000 ) t GROUP BY itemFk, warehouseFk, `grouping`; - + DROP TEMPORARY TABLE tmp.ticketComponentCalculate, tmp.ticketComponentSum, @@ -50428,7 +50428,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `catalog_componentPrepare`() BEGIN - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent; CREATE TEMPORARY TABLE tmp.ticketComponent ( `warehouseFk` INT UNSIGNED NOT NULL, @@ -50438,9 +50438,9 @@ BEGIN INDEX `itemWarehouse` USING BTREE (`itemFk` ASC, `warehouseFk` ASC), UNIQUE `fkItemWarehouseComponent` (`itemFk` ASC, `warehouseFk` ASC, `componentFk` ASC) )ENGINE=MEMORY DEFAULT CHARSET=utf8; - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentPrice; - CREATE TEMPORARY TABLE tmp.ticketComponentPrice ( + CREATE TEMPORARY TABLE tmp.ticketComponentPrice ( `warehouseFk` INT UNSIGNED NOT NULL, `itemFk` INT NOT NULL, `rate` INT NOT NULL, @@ -50449,7 +50449,7 @@ BEGIN `priceKg` DECIMAL(10,4), INDEX `itemWarehouse` USING BTREE (`itemFk` ASC, `warehouseFk` ASC), UNIQUE `fkItemWarehouseRate` (`itemFk` ASC, `warehouseFk` ASC, `rate` ASC) - )ENGINE=MEMORY DEFAULT CHARSET=utf8; + )ENGINE=MEMORY DEFAULT CHARSET=utf8; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -50468,7 +50468,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `catalog_componentPurge`() BEGIN - DROP TEMPORARY TABLE + DROP TEMPORARY TABLE tmp.ticketComponentPrice, tmp.ticketComponent, tmp.ticketLot; @@ -50523,7 +50523,7 @@ BEGIN DELETE FROM sms WHERE created < v18Month; DELETE FROM saleTracking WHERE created < vOneYearAgo; DELETE FROM ticketTracking WHERE created < v18Month; - DELETE tobs FROM ticketObservation tobs + DELETE tobs FROM ticketObservation tobs JOIN ticket t ON tobs.ticketFk = t.id WHERE t.shipped < TIMESTAMPADD(YEAR,-2,util.VN_CURDATE()); DELETE sc.* FROM saleCloned sc JOIN sale s ON s.id = sc.saleClonedFk JOIN ticket t ON t.id = s.ticketFk WHERE t.shipped < vOneYearAgo; DELETE FROM sharingCart where ended < vDateShort; @@ -50597,12 +50597,12 @@ BEGIN FROM vn.travel t LEFT JOIN vn.entry e ON e.travelFk = t.id WHERE t.shipped < TIMESTAMPADD(MONTH, -3, util.VN_CURDATE()) AND e.travelFk IS NULL; - + UPDATE dms d - JOIN dmsType dt ON dt.id = d.dmsTypeFk - SET d.dmsTypeFk = vTrashId + JOIN dmsType dt ON dt.id = d.dmsTypeFk + SET d.dmsTypeFk = vTrashId WHERE created < TIMESTAMPADD(MONTH, -dt.monthToDelete, util.VN_CURDATE()); - + -- borrar entradas sin compras DROP TEMPORARY TABLE IF EXISTS tmp.entryToDelete; CREATE TEMPORARY TABLE tmp.entryToDelete @@ -50621,7 +50621,7 @@ BEGIN CREATE TEMPORARY TABLE tmp.routeToDelete SELECT * FROM vn.route r - WHERE created < TIMESTAMPADD(YEAR,-4,util.VN_CURDATE()); + WHERE created < TIMESTAMPADD(YEAR,-4,util.VN_CURDATE()); UPDATE tmp.routeToDelete tmp JOIN vn.dms d ON d.id = tmp.gestdocFk @@ -50804,21 +50804,21 @@ BEGIN */ DECLARE vClientDebt DOUBLE; - + SELECT vn.client_getDebt(vClientFk, util.VN_CURDATE()) INTO vClientDebt; - + INSERT INTO vn.greuge(clientFk, description, amount, shipped, greugeTypeFk) VALUES (vClientFk, 'Saldo pendiente', vClientDebt, util.VN_CURDATE(), 5); - + CALL vn.clientGreugeSpray(vClientFk, TRUE, '', TRUE); - + INSERT INTO vn.greuge(clientFk, description, amount, shipped, greugeTypeFk) SELECT vClientFk, 'Liquidación cliente', sum(amount), util.VN_CURDATE(), 5 FROM vn.greuge WHERE clientFk = vClientFk; - - UPDATE vn.client - SET salesPersonFk = NULL + + UPDATE vn.client + SET salesPersonFk = NULL WHERE id = vClientFk; END ;; @@ -50908,33 +50908,33 @@ BEGIN DECLARE vIssued DATETIME; DECLARE vBalance DOUBLE DEFAULT 0.00; DECLARE cur CURSOR FOR - SELECT - created, - issued, + SELECT + created, + issued, ROUND(amount, 2) AS balance FROM invoiceOut - WHERE clientFk = vClientFk AND companyFk = vCompanyFk - UNION ALL - SELECT - created, - payed, + WHERE clientFk = vClientFk AND companyFk = vCompanyFk + UNION ALL + SELECT + created, + payed, ROUND(-1 * amountPaid, 2) AS balance - FROM receipt + FROM receipt WHERE clientFk = vClientFk AND companyFk = vCompanyFk ORDER BY issued, created; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + OPEN cur; - + proc: LOOP SET vDone = FALSE; - + FETCH cur INTO vCreated, vIssued, vBalance; IF vDate IS NULL THEN SET vDate=vIssued; END IF; - + IF vDone THEN LEAVE proc; END IF; @@ -50946,66 +50946,66 @@ BEGIN SET vDone = TRUE; END IF; END LOOP; - + CLOSE cur; - - SELECT - issued, - CAST(debtOut AS DECIMAL(10,2)) debtOut, + + SELECT + issued, + CAST(debtOut AS DECIMAL(10,2)) debtOut, CAST(debtIn AS DECIMAL(10,2)) debtIn, - ref, - companyFk, + ref, + companyFk, priority FROM - (SELECT - NULL AS issued, - SUM(amountUnpaid) AS debtOut, - NULL AS debtIn, - 'Saldo Anterior' AS ref, + (SELECT + NULL AS issued, + SUM(amountUnpaid) AS debtOut, + NULL AS debtIn, + 'Saldo Anterior' AS ref, companyFk, - 0 as priority - FROM - (SELECT SUM(amount) AS amountUnpaid, companyFk, 0 + 0 as priority + FROM + (SELECT SUM(amount) AS amountUnpaid, companyFk, 0 FROM invoiceOut - WHERE clientFk = vClientFK - AND issued < vDate - GROUP BY companyFk - - UNION ALL - - SELECT SUM(-1 * amountPaid), companyFk, 0 - FROM receipt - WHERE clientFk = vClientFK - AND payed < vDate - GROUP BY companyFk) AS transactions - GROUP BY companyFk - - UNION ALL - - SELECT - issued, - amount as debtOut, - NULL AS debtIn, + WHERE clientFk = vClientFK + AND issued < vDate + GROUP BY companyFk + + UNION ALL + + SELECT SUM(-1 * amountPaid), companyFk, 0 + FROM receipt + WHERE clientFk = vClientFK + AND payed < vDate + GROUP BY companyFk) AS transactions + GROUP BY companyFk + + UNION ALL + + SELECT + issued, + amount as debtOut, + NULL AS debtIn, ref, companyFk, - 1 - FROM invoiceOut - WHERE clientFk = vClientFK + 1 + FROM invoiceOut + WHERE clientFk = vClientFK AND issued >= vDate - UNION ALL - - SELECT - r.payed, - NULL as debtOut, - r.amountPaid, - r.invoiceFk, + UNION ALL + + SELECT + r.payed, + NULL as debtOut, + r.amountPaid, + r.invoiceFk, r.companyFk, - 0 + 0 FROM receipt r - WHERE r.clientFk = vClientFK - AND r.payed >= vDate) t - INNER JOIN `client` c ON c.id = vClientFK - HAVING debtOut <> 0 OR debtIn <> 0 + WHERE r.clientFk = vClientFK + AND r.payed >= vDate) t + INNER JOIN `client` c ON c.id = vClientFK + HAVING debtOut <> 0 OR debtIn <> 0 ORDER BY issued, priority DESC, debtIn; END ;; DELIMITER ; @@ -51063,13 +51063,13 @@ BEGIN WHERE id = vClientFk; ELSE - + SELECT id INTO vOwner FROM vn.worker WHERE code = vWorkerCode COLLATE utf8_general_ci; END IF; - + DROP TEMPORARY TABLE IF EXISTS tmp.clientList; CREATE TEMPORARY TABLE tmp.clientList SELECT DISTINCT t.clientFk, floor(cr.yearSale / 12) monthSale @@ -51081,7 +51081,7 @@ BEGIN AND t.shipped >= TIMESTAMPADD(MONTH,-1,util.VN_CURDATE()) AND c.id != vClientFk HAVING monthSale > 100; - + SELECT SUM(monthSale) INTO vTotalSale FROM tmp.clientList; @@ -51092,7 +51092,7 @@ BEGIN SELECT vClientFk, 'Reparto greuge', -vGreuge, util.VN_CURDATE(), vGreugeTypeFk; END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -51287,11 +51287,11 @@ BEGIN LEFT JOIN clientProtected cp ON cp.clientFk = cd.id JOIN client c ON c.id = cd.id JOIN province p ON p.id = c.provinceFk - LEFT JOIN autonomy a ON a.id = p.autonomyFk + LEFT JOIN autonomy a ON a.id = p.autonomyFk JOIN country co ON co.id = p.countryFk WHERE cd.Aviso = 'TERCER AVISO' AND cp.clientFk IS NULL - AND co.code NOT IN ('PT') + AND co.code NOT IN ('PT') AND a.name <> 'Canarias' AND c.salesPersonFk IS NOT NULL; @@ -51402,7 +51402,7 @@ BEGIN JOIN client c ON c.accountingAccount = lc.account WHERE lc.`date` BETWEEN vDateFrom AND vDateTo )sub - GROUP BY companyFk, clientFk + GROUP BY companyFk, clientFk ) sub1 ON sub1.clientFk = c.id JOIN supplier s ON s.id = sub1.companyFk JOIN company co ON co.id = sub1.companyFk @@ -51546,13 +51546,13 @@ BEGIN SET vEnded = TIMESTAMP(IFNULL(vDate, util.VN_CURDATE()), '23:59:59'); DROP TEMPORARY TABLE IF EXISTS tClientRisk; - CREATE TEMPORARY TABLE tClientRisk + CREATE TEMPORARY TABLE tClientRisk ENGINE = MEMORY SELECT cr.clientFk, SUM(cr.amount) amount FROM clientRisk cr JOIN tmp.clientGetDebt c ON c.clientFk = cr.clientFk GROUP BY cr.clientFk; - + INSERT INTO tClientRisk SELECT c.clientFk, SUM(r.amountPaid) FROM receipt r @@ -51567,7 +51567,7 @@ BEGIN WHERE t.receiptFk IS NULL AND t.status = 'ok' GROUP BY t.clientFk; - + INSERT INTO tClientRisk SELECT t.clientFk, totalWithVat FROM ticket t @@ -51583,7 +51583,7 @@ BEGIN FROM client c JOIN tClientRisk cr ON cr.clientFk = c.id GROUP BY c.id; - + DROP TEMPORARY TABLE tClientRisk; END ;; DELIMITER ; @@ -51607,9 +51607,9 @@ BEGIN DECLARE i INT DEFAULT 0; DECLARE c INT DEFAULT 0; DECLARE maxClientFk INT; - + DROP TEMPORARY TABLE IF EXISTS tmp.client; - + CREATE TEMPORARY TABLE tmp.`client` (id INT AUTO_INCREMENT, clientFk INT, @@ -51617,40 +51617,40 @@ BEGIN PRIMARY KEY(id), UNIQUE KEY clientFk (clientFk)) ENGINE = MEMORY; - + INSERT INTO tmp.client(clientFk) SELECT DISTINCT clientFk FROM vn.invoiceOut WHERE issued > TIMESTAMPADD(MONTH, -2, util.VN_CURDATE()); - + SELECT max(id) INTO maxClientFk FROM tmp.client; - - + + WHILE i < vNumber DO - + SET i = i + 1; - + WHILE c = 0 DO - + SELECT id INTO c FROM tmp.client WHERE id = floor(RAND() * maxClientFk) + 1 AND isSelected = FALSE LIMIT 1; - + END WHILE; - + -- SELECT i, maxClientFk, c; - - UPDATE tmp.client - SET isSelected = TRUE + + UPDATE tmp.client + SET isSelected = TRUE WHERE id = c; - + SET c = 0; - + END WHILE; - + SELECT c.id, c.name FROM tmp.client tc JOIN vn.client c ON c.id = tc.clientFk WHERE isSelected @@ -51791,35 +51791,35 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `cmr_getByTicket`(vTicketFk INT) BEGIN DECLARE vLanded DATE; - + SELECT DATE_ADD(util.VN_CURDATE(), INTERVAL landingDays DAY) INTO vLanded FROM vn.cmrConfig; IF vTicketFk THEN - + IF (SELECT count(ticketFk) FROM vn.cmr WHERE ticketFk = vTicketFk) THEN - + SELECT id FROM vn.cmr WHERE ticketFk = vTicketFk; - + ELSE - + INSERT INTO vn.cmr(ticketFk, companyFk, addressFromFk, addressToFk, ead) SELECT vTicketFk, t.companyFk, a.id, t.addressFk, vLanded FROM vn.ticket t - JOIN vn.warehouse w ON w.id = t.warehouseFk - JOIN vn.address a ON a.id = w.addressFk + JOIN vn.warehouse w ON w.id = t.warehouseFk + JOIN vn.address a ON a.id = w.addressFk WHERE t.id = vTicketFk; - + SELECT LAST_INSERT_ID(); - + END IF; - + ELSE - + INSERT INTO vn.cmr(ead) VALUES(vLanded); - + SELECT LAST_INSERT_ID(); - + END IF; END ;; DELIMITER ; @@ -51842,7 +51842,7 @@ BEGIN /** * Insert the monthly CMR summary in vn.mail on the 5th of each month. */ - + SET SESSION group_concat_max_len = 1000000; -- IF (DAY(util.VN_CURDATE()) = 5) THEN INSERT INTO @@ -51870,7 +51870,7 @@ BEGIN CMR Ticket ' - , GROUP_CONCAT(' ', c.id, ' ', c.ticketFk, ' ' ORDER BY c.id SEPARATOR '' ), + , GROUP_CONCAT(' ', c.id, ' ', c.ticketFk, ' ' ORDER BY c.id SEPARATOR '' ), '

@@ -51888,7 +51888,7 @@ BEGIN -- Actualizamos el estado a 'Enviado' UPDATE vn.cmr c SET c.state = 'Sent' - WHERE c.state = 'Pending' + WHERE c.state = 'Pending' AND MONTH(c.created) = MONTH(util.VN_CURDATE() - INTERVAL 1 MONTH) AND YEAR(c.created) = YEAR(util.VN_CURDATE() - INTERVAL 1 MONTH); -- END IF; @@ -52101,15 +52101,15 @@ BEGIN DATE_FORMAT(util.VN_NOW(), '%H:%i' ), ' ', i.name - ) INTO vConcept + ) INTO vConcept FROM item i WHERE i.id = vItemFk; SELECT name INTO vItemName FROM item WHERE id = vBarccodeFk; - SELECT CONCAT('Añadido articulo ', + SELECT CONCAT('Añadido articulo ', vItemName, - ' cantidad:', + ' cantidad:', vQuantity ) INTO vDescription; @@ -52146,7 +52146,7 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_assign`(vUserFk INT, OUT vCollectionFk INT) -proc:BEGIN +proc:BEGIN /* Comprueba si existen colecciones libres que se ajustan al perfil del usuario * y le asigna la más antigua. * Añade un registro al semillero de colecciones @@ -52179,14 +52179,14 @@ proc:BEGIN FROM vn.collection c JOIN vn.ticketCollection tc ON tc.collectionFk = c.id JOIN vn.state s ON s.code = 'PRINTED_AUTO' - JOIN vn.productionConfig pc - WHERE c.workerFk IS NULL + JOIN vn.productionConfig pc + WHERE c.workerFk IS NULL AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; DELETE c.* FROM vn.collection c - JOIN vn.productionConfig pc - WHERE c.workerFk IS NULL + JOIN vn.productionConfig pc + WHERE c.workerFk IS NULL AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; -- Se a�ade registro al semillero @@ -52196,8 +52196,8 @@ proc:BEGIN -- Comprueba si hay colecciones disponibles que se ajustan a su configuracion SELECT MIN(c.id) INTO vCollectionFk - FROM vn.collection c - JOIN vn.operator o + FROM vn.collection c + JOIN vn.operator o ON (o.itemPackingTypeFk = c.itemPackingTypeFk OR c.itemPackingTypeFk IS NULL) AND o.numberOfWagons = c.wagons AND o.trainFk = c.trainFk @@ -52244,18 +52244,18 @@ BEGIN SELECT c.id collectionFk, date(c.created) created, COUNT(DISTINCT tc.ticketFk) ticketTotalCount - FROM collection c - JOIN ticketCollection tc ON tc.collectionFk = c.id - JOIN sale s ON s.ticketFk = tc.ticketFk + FROM collection c + JOIN ticketCollection tc ON tc.collectionFk = c.id + JOIN sale s ON s.ticketFk = tc.ticketFk JOIN ticketState ts ON ts.ticketFk = tc.ticketFk JOIN state s2 ON s2.id = ts.stateFk JOIN productionConfig pc JOIN vn.state ss on ss.code = 'PREPARED' LEFT JOIN vn.saleTracking st on st.saleFk = s.id AND st.stateFk = ss.id - WHERE c.workerFk = vWorkerFk + WHERE c.workerFk = vWorkerFk AND TIMESTAMPDIFF(HOUR, c.created , util.VN_NOW()) < pc.pendingCollectionsAge AND s.quantity != 0 - AND s2.order < pc.pendingCollectionsOrder + AND s2.order < pc.pendingCollectionsOrder GROUP BY c.id HAVING COUNT(*) > COUNT(DISTINCT st.id); @@ -52282,15 +52282,15 @@ BEGIN * Selecciona los tickets de una colección/ticket * @param vParamFk ticketFk/collectionFk * @return Retorna ticketFk, level, agencyName, warehouseFk, salesPersonFk, observaciones - */ + */ DECLARE vItemPackingTypeFk VARCHAR(1); -- Si los sacadores son los de pruebas, pinta los colores SELECT itemPackingTypeFk INTO vItemPackingTypeFk - FROM vn.collection + FROM vn.collection WHERE id = vParamFk; - SELECT t.id ticketFk, + SELECT t.id ticketFk, IF (!(vItemPackingTypeFk <=> 'V'), cc.code,CONCAT(SUBSTRING('ABCDEFGH',tc.wagon, 1),'-',tc.`level` )) `level`, am.name agencyName, t.warehouseFk, @@ -52300,20 +52300,20 @@ BEGIN FROM vn.ticket t LEFT JOIN vn.ticketCollection tc ON t.id = tc.ticketFk LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk -- PAK 23/12/21 - LEFT JOIN vn.collectionColors cc - ON cc.wagon = tc.wagon - AND cc.shelve = tc.`level` + LEFT JOIN vn.collectionColors cc + ON cc.wagon = tc.wagon + AND cc.shelve = tc.`level` AND cc.trainFk = c2.trainFk -- PAK 23/12/21 - LEFT JOIN vn.zone z ON z.id = t.zoneFk + LEFT JOIN vn.zone z ON z.id = t.zoneFk LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk LEFT JOIN vn.client c ON c.id = t.clientFk LEFT JOIN vn.worker w ON w.id = c.salesPersonFk - LEFT JOIN vn.ticketObservation tob ON tob.ticketFk = t.id + LEFT JOIN vn.ticketObservation tob ON tob.ticketFk = t.id AND tob.observationTypeFk = 1 - WHERE t.id = vParamFk + WHERE t.id = vParamFk AND t.shipped >= util.yesterday() UNION ALL - SELECT t.id ticketFk, + SELECT t.id ticketFk, IF(!(vItemPackingTypeFk <=> 'V'), cc.code, CONCAT(SUBSTRING('ABCDEFGH', tc.wagon, 1), '-', tc.`level`)) `level`, am.name agencyName, t.warehouseFk, @@ -52323,15 +52323,15 @@ BEGIN FROM vn.ticket t JOIN vn.ticketCollection tc ON t.id = tc.ticketFk LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk -- PAK 23/12/21 - LEFT JOIN vn.collectionColors cc - ON cc.wagon = tc.wagon - AND cc.shelve = tc.`level` + LEFT JOIN vn.collectionColors cc + ON cc.wagon = tc.wagon + AND cc.shelve = tc.`level` AND cc.trainFk = c2.trainFk -- PAK 23/12/21 - LEFT JOIN vn.zone z ON z.id = t.zoneFk + LEFT JOIN vn.zone z ON z.id = t.zoneFk LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk LEFT JOIN vn.client c ON c.id = t.clientFk LEFT JOIN vn.worker w ON w.id = c.salesPersonFk - LEFT JOIN vn.ticketObservation tob ON tob.ticketFk = t.id + LEFT JOIN vn.ticketObservation tob ON tob.ticketFk = t.id AND tob.observationTypeFk = 1 WHERE tc.collectionFk = vParamFk; @@ -52694,8 +52694,8 @@ proc:BEGIN -- Se anulan el resto de carros libres para que sólo uno lleve un pedido excesivo DELETE tt.* FROM tTrain tt - LEFT JOIN (SELECT DISTINCT wagon - FROM tTrain + LEFT JOIN (SELECT DISTINCT wagon + FROM tTrain WHERE ticketFk IS NOT NULL ) nn ON nn.wagon = tt.wagon WHERE nn.wagon IS NULL; @@ -52863,7 +52863,7 @@ BEGIN DECLARE vDone INT DEFAULT FALSE; DECLARE vCursor CURSOR FOR SELECT DISTINCT ticketFk - FROM ticketCollection tc + FROM ticketCollection tc WHERE tc.collectionFk = vSelf; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; @@ -52910,25 +52910,25 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `company_getFiscaldata`(workerFk INT) BEGIN - + DECLARE vCompanyFk INT; - - SELECT IFNULL(uc.companyFk, rc.defaultCompanyFk) + + SELECT IFNULL(uc.companyFk, rc.defaultCompanyFk) INTO vCompanyFk FROM vn.routeConfig rc LEFT JOIN userConfig uc ON uc.userFk = workerFk; - - + + SELECT s.name AS name , s.NIF AS nif , s.street AS street , s.city AS city , - s.postCode AS postCode - - FROM vn.company c + s.postCode AS postCode + + FROM vn.company c JOIN vn.worker w ON w.id = c.workerManagerFk - JOIN vn.supplier s ON s.id = c.id + JOIN vn.supplier s ON s.id = c.id WHERE c.id = vCompanyFk; END ;; DELIMITER ; @@ -52985,7 +52985,7 @@ BEGIN IF (p.currencyFk = vCurrencyEuroFk, p.amount, p.divisa) AS amount, p.dueDated < vStartingDate isBeforeStarting, p.currencyFk - FROM payment p + FROM payment p WHERE p.received > vStartDate AND p.companyFk = vSelf UNION ALL @@ -52993,9 +52993,9 @@ BEGIN r.companyFk, - IF (r.currencyFk = vCurrencyEuroFk, rv.amount, rv.foreignValue) AS Total, rv.dueDated < vStartingDate isBeforeStarting, - r.currencyFk - FROM invoiceIn r - INNER JOIN invoiceInDueDay rv ON r.id = rv.invoiceInFk + r.currencyFk + FROM invoiceIn r + INNER JOIN invoiceInDueDay rv ON r.id = rv.invoiceInFk WHERE r.issued > vStartDate AND r.isBooked AND r.companyFk = vSelf @@ -53047,11 +53047,11 @@ BEGIN -IF (r.currencyFk = vCurrencyEuroFk, rv.amount, rv.foreignValue), r.currencyFk, FALSE isPayment, - TRUE - FROM invoiceIn r + TRUE + FROM invoiceIn r LEFT JOIN tOpeningBalances si ON r.companyFk = si.companyFk AND r.supplierFk = si.supplierFk - AND r.currencyFk = si.currencyFk + AND r.currencyFk = si.currencyFk JOIN invoiceInDueDay rv ON r.id = rv.invoiceInFk WHERE rv.dueDated >= vStartingDate AND (si.closingBalances IS NULL OR si.closingBalances <> 0) @@ -53106,7 +53106,7 @@ BEGIN FROM tPendingDuedates WHERE balance < vInvalidBalances AND balance > - vInvalidBalances; - + DELETE vp.* FROM tPendingDuedates vp JOIN tRowsToDelete rd ON ( @@ -53134,9 +53134,9 @@ BEGIN FROM tPendingDuedates vp LEFT JOIN supplier s ON s.id = vp.supplierFk LEFT JOIN client c ON c.fi = s.nif - LEFT JOIN clientRisk cr ON cr.clientFk = c.id + LEFT JOIN clientRisk cr ON cr.clientFk = c.id AND cr.companyFk = vp.companyFk; - + DROP TEMPORARY TABLE tOpeningBalances; DROP TEMPORARY TABLE tPendingDuedates; DROP TEMPORARY TABLE tRowsToDelete; @@ -53159,7 +53159,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `conveyorExpedition_Add`(vStarted DATETIME, vEnded DATETIME) BEGIN - + DECLARE startingMinute INT; TRUNCATE vn.conveyorExpedition; @@ -53176,23 +53176,23 @@ BEGIN conveyorBuildingClassFk) SELECT e.id, e.created, - 10 * p.depth as depth, + 10 * p.depth as depth, 10 * p.width as width, 10 * p.height as height, IFNULL(t.routeFk,am.agencyFk) routeFk, hour(e.created) * 60 + minute(e.created), IFNULL(et.description , a.name), IFNULL(t.routeFk,am.agencyFk) criterion, - IFNULL(p.conveyorBuildingClassFk , pc.defaultConveyorBuildingClass) + IFNULL(p.conveyorBuildingClassFk , pc.defaultConveyorBuildingClass) FROM vn.expedition e JOIN vn.ticket t ON t.id = e.ticketFk JOIN vn.packaging p ON p.id = e.packagingFk LEFT JOIN vn.zone z ON z.id = t.zoneFk LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk - LEFT JOIN vn.agency a ON a.id = am.agencyFk - LEFT JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk - LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk - JOIN vn.packagingConfig pc + LEFT JOIN vn.agency a ON a.id = am.agencyFk + LEFT JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk + LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk + JOIN vn.packagingConfig pc WHERE t.warehouseFk IN (60,1,44) AND e.created BETWEEN vStarted AND vEnded AND p.height < 140 @@ -53201,8 +53201,8 @@ BEGIN SELECT MIN(productionMinute) INTO startingMinute FROM vn.conveyorExpedition ce ; - - UPDATE vn.conveyorExpedition + + UPDATE vn.conveyorExpedition SET productionMinute = productionMinute - startingMinute; END ;; @@ -53271,7 +53271,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `createPedidoInterno`(vItemFk INT,vQuantity INT) BEGIN - + UPDATE vn.item SET upToDown = vQuantity WHERE id = vItemFk; END ;; @@ -53294,52 +53294,52 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `crypt`(vText VARCHAR(255), vKey VAR BEGIN DECLARE vEncryptedText VARCHAR(255) DEFAULT ''; - + DECLARE vKeyLength INT; DECLARE vKeyPosition INT DEFAULT 1; DECLARE vKeyChar VARCHAR(1); - + DECLARE vTextLength INT; DECLARE vTextPosition INT DEFAULT 1; DECLARE vTextChar VARCHAR(1); - + DECLARE vEncryptedChar VARCHAR(1); DECLARE vEncryptedCharPosition INT; - + DECLARE vChain VARCHAR(255) DEFAULT '#$.-_0123456789abcdefghijklmnopqrstuvwxyz'; DECLARE vChainTextPosition INT; DECLARE vChainKeyPosition INT; DECLARE vChainLength INT; - + DECLARE vInvalidadChars VARCHAR(255) DEFAULT ''; - - SET vTextLength = LENGTH(vText); + + SET vTextLength = LENGTH(vText); SET vKeyLength = LENGTH(vKey); SET vChainLength = LENGTH(vChain); - + WHILE vTextPosition <= vTextLength DO - + SET vTextChar = MID(vText,vTextPosition,1); SET vKeyChar = MID(vKey,vKeyPosition,1); - + SET vChainTextPosition = LOCATE(vTextChar, vChain); SET vInvalidadChars = IF(vChainTextPosition, vInvalidadChars, CONCAT(vInvalidadChars,vTextChar)); SET vChainKeyPosition = LOCATE(vKeyChar, vChain); SET vEncryptedCharPosition = vChainTextPosition + vChainKeyPosition; - + IF vEncryptedCharPosition > vChainLength THEN - + SET vEncryptedCharPosition = vEncryptedCharPosition - vChainLength; - + END IF; - + SET vEncryptedChar = MID(vChain, vEncryptedCharPosition,1); - + SET vEncryptedText = CONCAT(vEncryptedText, vEncryptedChar); - + SET vKeyPosition = IF(vKeyPosition = vKeyLength, 1,vKeyPosition + 1); SET vTextPosition = vTextPosition + 1; - + END WHILE; SET vResult = IF(LENGTH(vInvalidadChars), CONCAT('Caracteres no válidos: ',vInvalidadChars),vEncryptedText); @@ -53364,49 +53364,49 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `cryptOff`(vText VARCHAR(255), vKey BEGIN DECLARE vUncryptedText VARCHAR(255) DEFAULT ''; - + DECLARE vKeyLength INT; DECLARE vKeyPosition INT DEFAULT 1; DECLARE vKeyChar VARCHAR(1); - + DECLARE vTextLength INT; DECLARE vTextPosition INT DEFAULT 1; DECLARE vTextChar VARCHAR(1); - + DECLARE vUncryptedChar VARCHAR(1); DECLARE vUncryptedCharPosition INT; - + DECLARE vChain VARCHAR(255) DEFAULT '#$.-_0123456789abcdefghijklmnopqrstuvwxyz'; DECLARE vChainTextPosition INT; DECLARE vChainKeyPosition INT; DECLARE vChainLength INT; - - SET vTextLength = LENGTH(vText); + + SET vTextLength = LENGTH(vText); SET vKeyLength = LENGTH(vKey); SET vChainLength = LENGTH(vChain); - + WHILE vTextPosition <= vTextLength DO - + SET vTextChar = MID(vText,vTextPosition,1); SET vKeyChar = MID(vKey,vKeyPosition,1); - + SET vChainTextPosition = LOCATE(vTextChar, vChain); SET vChainKeyPosition = LOCATE(vKeyChar, vChain); SET vUncryptedCharPosition = vChainTextPosition - vChainKeyPosition; - + IF vUncryptedCharPosition < 1 THEN - + SET vUncryptedCharPosition = vUncryptedCharPosition + vChainLength; - + END IF; - + SET vUncryptedChar = MID(vChain, vUncryptedCharPosition,1); - + SET vUncryptedText = CONCAT(vUncryptedText, vUncryptedChar); - + SET vKeyPosition = IF(vKeyPosition = vKeyLength, 1,vKeyPosition + 1); SET vTextPosition = vTextPosition + 1; - + END WHILE; SET vResult = vUncryptedText; @@ -53502,7 +53502,7 @@ BEGIN OR (vSelf IS NOT NULL AND parentFk = vSelf); DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + SET vSons = 0; OPEN vChildren; @@ -53513,11 +53513,11 @@ BEGIN IF vDone THEN LEAVE myLoop; END IF; - + SET vIndex = vIndex + 1; SET vLft = vIndex; SET vSons = vSons + 1; - + CALL department_calcTreeRec( vChildFk, CONCAT(vPath, vChildFk, '/'), @@ -53572,7 +53572,7 @@ proc: BEGIN SELECT isChanged INTO vIsChanged FROM department_recalc; - + IF vIsChanged THEN UPDATE department_recalc SET isChanged = FALSE; CALL vn.department_calcTree; @@ -53597,17 +53597,17 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `department_getHasMistake`() BEGIN - + /** * Obtiene los sectores a los cuales les ponemos errores * */ - + SELECT id, name FROM department WHERE hasToMistake <> FALSE; - - + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -53666,19 +53666,19 @@ BEGIN FROM department g JOIN tChilds c ON c.id = g.id WHERE g.parentFk IS NOT NULL; - + INSERT IGNORE INTO tNodes SELECT id FROM tParents; - + IF ROW_COUNT() = 0 THEN LEAVE myLoop; END IF; - + DELETE FROM tChilds; INSERT INTO tChilds SELECT id FROM tParents; END LOOP; - + DROP TEMPORARY TABLE tChilds, tParents; @@ -53745,12 +53745,12 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `deviceProductionUser_exists`(vUserFk INT) BEGIN - + /* SELECT COUNT(*) AS UserExists - FROM vn.deviceProductionUser dpu + FROM vn.deviceProductionUser dpu WHERE dpu.userFk = vUserFk;*/ SELECT TRUE; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -53822,10 +53822,10 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `device_checkLogin`(vUserFk INT, vAndroidID VARCHAR(50)) BEGIN - + /* * Comprueba si está registrado el dispositivo mediante su androidId - * + * * @param vUSerFk el id del user * @param vAndroidID es el identificador android_id del dispositivo */ @@ -53837,20 +53837,20 @@ BEGIN SELECT dpc.isAllUsersallowed INTO vIsAllUsersAllowed FROM vn.deviceProductionConfig dpc; - IF NOT vIsAllUsersAllowed THEN - + IF NOT vIsAllUsersAllowed THEN + SELECT COUNT(*) INTO vIsDepartment - FROM vn.workerDepartment dp + FROM vn.workerDepartment dp JOIN department d ON d.id = dp.departmentFk WHERE dp.workerFk = vUserFk AND d.hasToCheckLogin; - + IF vIsDepartment THEN SELECT COUNT(*) INTO vIsAuthorized - FROM vn.deviceProductionUser dpu + FROM vn.deviceProductionUser dpu JOIN vn.deviceProduction dp ON dp.id = dpu.deviceProductionFk WHERE dpu.userFk = vUserFk AND dp.android_id = vAndroidID; - + IF NOT vIsAuthorized THEN SET vMessage = 'Usuario no autorizado'; END IF; @@ -53880,15 +53880,15 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `duaEntryValueUpdate`(vDuaFk INT) BEGIN UPDATE duaEntry de - JOIN + JOIN ( SELECT b.entryFk, sum(b.quantity * b.buyingValue) as total FROM buy b JOIN duaEntry de ON de.entryFk = b.entryFk WHERE duaFk = vDuaFk GROUP BY b.entryFk ) sub ON sub.entryFk = de.entryFk - - LEFT JOIN + + LEFT JOIN (SELECT e.id, sum(iit.taxableBase) as euros FROM entry e JOIN invoiceInTax iit ON iit.invoiceInFk = e.invoiceInFk @@ -53896,11 +53896,11 @@ BEGIN WHERE de.duaFk = vDuaFk GROUP BY e.id ) sub2 ON sub2.id = de.entryFk - + SET de.value = sub.total, de.euroValue = sub2.euros WHERE duaFk = vDuaFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -53924,7 +53924,7 @@ BEGIN DECLARE vInvoiceFk INT; DECLARE vASIEN BIGINT DEFAULT 0; DECLARE vCounter INT DEFAULT 0; - + DECLARE rs CURSOR FOR SELECT e.invoiceInFk FROM entry e @@ -53937,7 +53937,7 @@ BEGIN DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; OPEN rs; - + UPDATE invoiceIn ii JOIN entry e ON e.invoiceInFk = ii.id JOIN duaEntry de ON de.entryFk = e.id @@ -53949,41 +53949,41 @@ BEGIN ii.bookEntried = IFNULL(ii.bookEntried,d.bookEntried), e.isConfirmed = TRUE WHERE d.id = vDuaFk; - + SELECT IFNULL(ASIEN,0) INTO vASIEN FROM dua WHERE id = vDuaFk; - + FETCH rs INTO vInvoiceFk; - + WHILE NOT done DO CALL invoiceIn_booking(vInvoiceFk); - + IF vCounter > 0 OR vASIEN > 0 THEN - + UPDATE vn2008.XDiario x JOIN vn.ledgerConfig lc ON lc.lastBookEntry = x.ASIEN SET x.ASIEN = vASIEN; - + ELSE - + SELECT lastBookEntry INTO vASIEN FROM vn.ledgerConfig; - + END IF; - + SET vCounter = vCounter + 1; - + FETCH rs INTO vInvoiceFk; END WHILE; - + CLOSE rs; - - UPDATE dua + + UPDATE dua SET ASIEN = vASIEN WHERE id = vDuaFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -54009,9 +54009,9 @@ BEGIN SELECT awbFk,companyFk FROM dua WHERE id = vDuaFk; - + SELECT LAST_INSERT_ID() INTO vNewDuaFk; - + INSERT INTO duaEntry(duaFk, entryFk, value, customsValue) SELECT vNewDuaFk, entryFk, value, value - customsValue FROM duaEntry @@ -54040,11 +54040,11 @@ BEGIN DECLARE vBookDated DATE; DECLARE vDiff DECIMAL(10,2); DECLARE vApunte BIGINT; - + SELECT ASIEN, IFNULL(bookEntried, util.VN_CURDATE()) INTO vBookNumber, vBookDated - FROM dua + FROM dua WHERE id = vDuaFk; - + IF vBookNumber IS NULL OR NOT vBookNumber THEN CALL ledger_next(vBookNumber); END IF; @@ -54055,14 +54055,14 @@ BEGIN ASIEN, FECHA, SUBCTA, - CONCEPTO, + CONCEPTO, EUROHABER, SERIE, empresa_id, CLAVE, FACTURA) - SELECT + SELECT vBookNumber, d.bookEntried, '4700000999', @@ -54075,20 +54075,20 @@ BEGIN FROM duaTax dt JOIN dua d ON d.id = dt.duaFk WHERE dt.duaFk = vDuaFk; - + -- Apuntes por tipo de IVA y proveedor - + INSERT INTO XDiario( ASIEN, FECHA, SUBCTA, - CONTRA, + CONTRA, EURODEBE, BASEEURO, - CONCEPTO, - FACTURA, + CONCEPTO, + FACTURA, IVA, - AUXILIAR, + AUXILIAR, SERIE, FECHA_EX, FECHA_OP, @@ -54108,17 +54108,17 @@ BEGIN FECREGCON ) - SELECT + SELECT vBookNumber ASIEN, vBookDated FECHA, tr.account SUBCTA, '4330002067' CONTRA, sum(dt.tax) EURODEBE, - sum(dt.base) BASEEURO, + sum(dt.base) BASEEURO, CONCAT('DUA nº',d.code) CONCEPTO, d.id FACTURA, dt.rate IVA, - '*' AUXILIAR, + '*' AUXILIAR, 'D' SERIE, d.issued FECHA_EX, d.operated FECHA_OP, @@ -54145,10 +54145,10 @@ BEGIN WHERE ta.effectived <= vBookDated AND taxAreaFk = 'WORLD' ORDER BY ta.effectived DESC - LIMIT 10000000000000000000 + LIMIT 10000000000000000000 ) tba GROUP BY rate - ) tr ON tr.rate = dt.rate + ) tr ON tr.rate = dt.rate JOIN supplier s ON s.id = d.companyFk JOIN country c ON c.id = s.countryFk WHERE d.id = vDuaFk @@ -54157,16 +54157,16 @@ BEGIN SELECT SUM(EURODEBE) -SUM(EUROHABER), MAX(id) INTO vDiff, vApunte FROM XDiario WHERE ASIEN = vBookNumber; - + UPDATE XDiario SET BASEEURO = 100 * (EURODEBE - vDiff) / IVA, - EURODEBE = EURODEBE - vDiff + EURODEBE = EURODEBE - vDiff WHERE id = vApunte; UPDATE dua SET ASIEN = vBookNumber WHERE id = vDuaFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -54187,21 +54187,21 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `duaTax_doRecalc`(vDuaFk INT) BEGIN /** * Borra los valores de duaTax y los vuelve a crear en base a la tabla duaEntry - * + * * @param vDuaFk Id del dua a recalcular **/ DELETE FROM duaTax WHERE duaFk = vDuaFk; - - INSERT INTO duaTax(duaFk, supplierFk, taxClassFk, base) + + INSERT INTO duaTax(duaFk, supplierFk, taxClassFk, base) SELECT vDuaFk, supplierFk, taxClassFk, sum(sub.Base) as Base FROM intrastat ist JOIN (SELECT - e.supplierFk, + e.supplierFk, i.intrastatFk, CAST(sum(b.quantity * b.buyingValue * de.customsValue / de.value) * di.amount/ tei.Base AS DECIMAL(10,2)) as Base - FROM buy b + FROM buy b JOIN item i ON i.id = b.itemFk JOIN entry e ON e.id = b.entryFk JOIN duaEntry de ON de.entryFk = e.id @@ -54209,15 +54209,15 @@ BEGIN ( SELECT i.intrastatFk, CAST(sum(b.quantity * b.buyingValue * de.customsValue / de.value) AS DECIMAL(10,2)) as Base - FROM buy b + FROM buy b JOIN item i ON i.id = b.itemFk JOIN entry e ON e.id = b.entryFk JOIN duaEntry de ON de.entryFk = e.id WHERE de.duaFk = vDuaFk GROUP BY i.intrastatFk - + ) tei ON tei.intrastatFk = i.intrastatFk - JOIN + JOIN ( SELECT intrastatFk, sum(amount) as amount FROM duaIntrastat @@ -54226,7 +54226,7 @@ BEGIN ) di ON di.intrastatFk = i.intrastatFk WHERE de.duaFk = vDuaFk GROUP BY e.supplierFk, i.intrastatFk - HAVING Base + HAVING Base ) sub ON ist.id = sub.intrastatFk GROUP BY ist.taxClassFk, sub.supplierFk; END ;; @@ -54247,13 +54247,13 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ediTables_Update`() BEGIN - - INSERT IGNORE INTO vn.genus(name) + + INSERT IGNORE INTO vn.genus(name) SELECT latin_genus_name FROM edi.genus ; - INSERT IGNORE INTO vn.specie(name) - SELECT LCASE(latin_species_name) + INSERT IGNORE INTO vn.specie(name) + SELECT LCASE(latin_species_name) FROM edi.specie ; END ;; DELIMITER ; @@ -54293,71 +54293,71 @@ DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; OPEN cur1; read_loop: LOOP - + SET done = FALSE; SET vEntryFk = 0; - + FETCH cur1 INTO vId; - + IF done THEN LEAVE read_loop; END IF; - + SELECT IFNULL(e.id,0) INTO vEntryFk FROM vn.entry e JOIN vn.travel tr ON tr.id = e.travelFk - JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk + JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk AND ea.warehouseInFk = tr.warehouseInFk AND ea.agencyModeFk = tr.agencyModeFk AND ea.supplierFk = e.supplierFk WHERE ea.id = vId AND tr.landed = vLanded LIMIT 1; - + IF NOT vEntryFk THEN - + SELECT IFNULL(e.id,0) INTO vEntryFk FROM vn.entry e JOIN vn.travel tr ON tr.id = e.travelFk - JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk + JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk AND ea.warehouseInFk = tr.warehouseInFk AND ea.agencyModeFk = tr.agencyModeFk WHERE ea.id = vId AND tr.landed = vLanded AND ea.supplierFk IS NULL LIMIT 1; - + END IF; - + IF NOT vEntryFk THEN - + SET vTravelFk = 0; - - SELECT IFNULL(MAX(tr.id),0) INTO vTravelFk + + SELECT IFNULL(MAX(tr.id),0) INTO vTravelFk FROM vn.travel tr - JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk + JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk AND ea.warehouseInFk = tr.warehouseInFk AND ea.agencyModeFk = tr.agencyModeFk WHERE ea.id = vId AND tr.landed = vLanded; - + IF NOT vTravelFk THEN - + INSERT INTO vn.travel(landed, shipped, warehouseInFk, warehouseOutFk, agencyModeFk) SELECT vLanded, vLanded, warehouseInFk, warehouseOutFk, agencyModeFk - FROM vn.ektEntryAssign + FROM vn.ektEntryAssign WHERE id = vId; - - SELECT MAX(tr.id) INTO vTravelFk + + SELECT MAX(tr.id) INTO vTravelFk FROM vn.travel tr - JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk + JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk AND ea.warehouseInFk = tr.warehouseInFk AND ea.agencyModeFk = tr.agencyFk WHERE ea.id = vId AND tr.landed = vLanded; - + END IF; - + INSERT INTO vn.entry(travelFk, supplierFk, companyFk, currencyFk) SELECT vTravelFk, IFNULL(ea.supplierFk,s.id), c.id, cu.id FROM vn.supplier s @@ -54365,13 +54365,13 @@ OPEN cur1; JOIN vn.currency cu ON cu.code = 'EUR' JOIN vn.ektEntryAssign ea ON ea.id = vId WHERE s.name = 'KONINKLIJE COOPERATIEVE BLOEMENVEILING FLORAHOLLAN'; - - SELECT MAX(id) INTO vEntryFk + + SELECT MAX(id) INTO vEntryFk FROM vn.entry WHERE travelFk = vTravelFk; - + END IF; - + UPDATE vn.ektEntryAssign SET entryFk = vEntryFk WHERE id = vId; @@ -54379,7 +54379,7 @@ OPEN cur1; END LOOP; CLOSE cur1; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -54399,18 +54399,18 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `energyMeter_record`(vInput INT, vActiveTime INT) BEGIN DECLARE vConsumption INT; - + SELECT consumption INTO vConsumption FROM energyInput WHERE input = vInput; - INSERT INTO vn.energyMeter - SET - `input` = vInput, - `period` = DATE_FORMAT(util.VN_NOW(), '%Y-%m-%d %H:00:00'), + INSERT INTO vn.energyMeter + SET + `input` = vInput, + `period` = DATE_FORMAT(util.VN_NOW(), '%Y-%m-%d %H:00:00'), `activeTime` = vActiveTime, `consumption` = CAST(IFNULL((vConsumption / 3600) * vActiveTime, 0) AS DECIMAL(10,2)) - ON DUPLICATE KEY UPDATE + ON DUPLICATE KEY UPDATE `activeTime` = `activeTime` + vActiveTime, `consumption` = `consumption` + CAST(VALUES(`consumption`) AS DECIMAL(10,2)); END ;; @@ -54433,28 +54433,28 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `entryDelivered`(vDated DATE, vEntry BEGIN DECLARE vTravelFk INT; - + SELECT travelFk INTO vTravelFk - FROM vn.entry + FROM vn.entry WHERE id = vEntryFk; - + IF (SELECT COUNT(*) FROM vn.entry WHERE travelFk = vTravelFk) = 1 THEN - + UPDATE vn.travel SET shipped = LEAST(shipped, vDated), landed = vDated WHERE id = vTravelFk; - + ELSE - + INSERT INTO vn.travel(shipped, landed, warehouseInFk, warehouseOutFk, agencyModeFk, ref, isDelivered, isReceived) SELECT LEAST(shipped, vDated), vDated, warehouseInFk, warehouseOutFk, agencyModeFk, CONCAT(account.myUser_getName(),' ', vEntryFk), TRUE, TRUE FROM vn.travel WHERE id = vTravelFk; - + SELECT LAST_INSERT_ID() INTO vTravelFk; - - UPDATE vn.entry - SET travelFk = vTravelFk + + UPDATE vn.entry + SET travelFk = vTravelFk WHERE id = vEntryFk; - + END IF; END ;; @@ -54480,29 +54480,29 @@ BEGIN DECLARE vEntry INT; DECLARE vBucket VARCHAR(10); DECLARE vSupplierFk INT; - + SET vSupplierFk = IF (vLandingWarehouse = 1, 850, 963); -- seleccionamos travel SELECT t.id, e.id INTO vTravel, vEntry FROM travel t LEFT JOIN entry e ON t.id = e.travelFk - WHERE t.landed = vInOutDate AND t.shipped = vInOutDate AND t.warehouseOutFk = vShipmentWarehouse + WHERE t.landed = vInOutDate AND t.shipped = vInOutDate AND t.warehouseOutFk = vShipmentWarehouse AND t.warehouseInFk = vLandingWarehouse AND t.agencyModeFk IS NULL AND e.supplierFk = vSupplierFk - LIMIT 1; - + LIMIT 1; + -- creamos el travel si es necesario IF IFNULL(vTravel, FALSE) = FALSE THEN INSERT INTO travel (shipped, landed, warehouseInFk, warehouseOutFk) VALUES (vInOutDate, vInOutDate, vLandingWarehouse, vShipmentWarehouse); SELECT LAST_INSERT_ID() INTO vTravel; END IF; - + -- creamos la Entrada si es necesario IF IFNULL(vEntry, FALSE) = FALSE THEN INSERT INTO entry (supplierFk, travelFk) VALUES (vSupplierFk, vTravel); -- proveedor 'CONFECCION ARTIFICIAL' SELECT LAST_INSERT_ID() INTO vEntry; END IF; - + -- creamos el cubo si es necesario SELECT id INTO vBucket FROM packaging WHERE volume = vVolume LIMIT 1; IF vBucket IS NULL THEN @@ -54512,7 +54512,7 @@ BEGIN SELECT id INTO vBucket FROM packaging WHERE volume = vVolume LIMIT 1; END IF; - INSERT INTO buy(itemFk,quantity, entryFk, packageFk, packing, stickers, buyingValue, price2, price3) + INSERT INTO buy(itemFk,quantity, entryFk, packageFk, packing, stickers, buyingValue, price2, price3) SELECT itemFk, quantity, vEntry, @@ -54544,7 +54544,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_checkPackaging`(vEntryFk INT) BEGIN /** * Comprueba que los campos package y packaging no sean nulos - * + * * @param vEntryFk Id de entrada */ DECLARE vpackageOrPackingNull INT; @@ -54846,7 +54846,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_getRate`(vSelf INT) BEGIN /** - * Prepara una tabla con las tarifas aplicables en funcion de la fecha + * Prepara una tabla con las tarifas aplicables en funcion de la fecha * y el almacén * * @param vSelf Id de la tabla entry @@ -54856,7 +54856,7 @@ BEGIN DECLARE vWarehouseFk INT; SELECT t.landed, t.warehouseInFk INTO vDated, vWarehouseFk - FROM entry e + FROM entry e JOIN travel t ON t.id = e.travelFk WHERE e.id = vSelf; @@ -54986,7 +54986,7 @@ BEGIN FROM buy b WHERE b.entryFk = vSelf AND b.printedStickers != b.stickers; - + IF vChangeEntry THEN UPDATE buy SET stickers = printedStickers, @@ -54998,7 +54998,7 @@ BEGIN FROM item i WHERE i.description = 'MISFIT' LIMIT 1; - + INSERT INTO buy(entryFk, itemFk, quantity, @@ -55065,7 +55065,7 @@ BEGIN UPDATE entry SET gestDocFk = (SELECT gestDocFk FROM entry WHERE id = vSelf LIMIT 1) WHERE id = vNewEntryFk; - + INSERT INTO duaEntry (duaFk, entryFk) SELECT duaFk, vNewEntryFk FROM duaEntry WHERE entryFk = vSelf LIMIT 1; END ;; @@ -55139,12 +55139,12 @@ BEGIN */ DECLARE v_done BOOL DEFAULT FALSE; DECLARE vEntryFk INTEGER; - + DECLARE vCur CURSOR FOR SELECT id FROM tmp.recalcEntryCommision; DECLARE CONTINUE HANDLER FOR NOT FOUND - SET v_done = TRUE; + SET v_done = TRUE; OPEN vCur; @@ -55155,7 +55155,7 @@ BEGIN IF v_done THEN LEAVE l; END IF; - + CALL vn2008.buy_tarifas_entry(vEntryFk); END LOOP; @@ -55180,7 +55180,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_splitByShelving`(vShelvingFk BEGIN /** * Divide las compras entre dos entradas de acuerdo con lo ubicado en una matr�cula - * + * * @param vShelvingFk Identificador de vn.shelving * @param vFromEntryFk Entrada origen * @param vToEntryFk Entrada destino @@ -55190,49 +55190,49 @@ BEGIN DECLARE vBuyStickers INT; DECLARE vDone BOOLEAN DEFAULT FALSE; - DECLARE cur CURSOR FOR + DECLARE cur CURSOR FOR SELECT bb.id buyFk, FLOOR(ish.visible / ish.packing) ishStickers, bb.stickers buyStickers FROM vn.itemShelving ish - JOIN (SELECT b.id, b.itemFk, b.stickers - FROM vn.buy b + JOIN (SELECT b.id, b.itemFk, b.stickers + FROM vn.buy b WHERE b.entryFk = vFromEntryFk ORDER BY b.stickers DESC - LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk + LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk AND bb.stickers >= FLOOR(ish.visible / ish.packing) WHERE shelvingFk = vShelvingFk COLLATE utf8_general_ci GROUP BY ish.id; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - -- Cantidades de la matrícula que exceden la de las entradas - SELECT ish.itemFk, - i.longName, + + -- Cantidades de la matrícula que exceden la de las entradas + SELECT ish.itemFk, + i.longName, FLOOR(ish.visible / ish.packing) AS etiEnMatricula, bb.stickers etiEnEntrada FROM vn.itemShelving ish - JOIN vn.item i ON i.id = ish.itemFk - LEFT JOIN (SELECT b.id, b.itemFk, b.stickers - FROM vn.buy b + JOIN vn.item i ON i.id = ish.itemFk + LEFT JOIN (SELECT b.id, b.itemFk, b.stickers + FROM vn.buy b WHERE b.entryFk = vFromEntryFk ORDER BY b.stickers DESC LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk WHERE shelvingFk = vShelvingFk COLLATE utf8_general_ci AND IFNULL(bb.stickers,0) < FLOOR(ish.visible / ish.packing) GROUP BY ish.id; - + OPEN cur; read_loop: LOOP SET vDone = FALSE; - + FETCH cur INTO vBuyFk, vIshStickers, vBuyStickers; - + IF vDone THEN LEAVE read_loop; END IF; - + IF vIshStickers = vBuyStickers THEN UPDATE vn.buy SET entryFk = vToEntryFk @@ -55240,9 +55240,9 @@ BEGIN ELSE UPDATE vn.buy SET stickers = stickers - vIshStickers, - quantity = stickers * packing + quantity = stickers * packing WHERE id = vBuyFk; - + INSERT INTO vn.buy(entryFk, itemFk, quantity, @@ -55322,16 +55322,16 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_splitMisfit`(vSelf INT) BEGIN - + /* Divide una entrada, pasando los registros que ha insertado vn.entry_fixMisfit de la entrada original * a la nueva */ - + DECLARE vNewEntryFk INT; DECLARE vBuyFk INT; SELECT MAX(b.id) INTO vBuyFk - FROM vn.buy b + FROM vn.buy b JOIN vn.item i ON i.id = b.itemFk WHERE b.entryFk = vSelf AND i.description = 'MISFIT'; @@ -55340,17 +55340,17 @@ BEGIN SELECT supplierFk, dated, travelFk, currencyFk, companyFk FROM vn.entry e WHERE e.id = vSelf; - - SET vNewEntryFk = LAST_INSERT_ID(); - UPDATE vn.buy b + SET vNewEntryFk = LAST_INSERT_ID(); + + UPDATE vn.buy b SET b.entryFk = vNewEntryFk WHERE b.entryFk = vSelf AND b.id > vBuyFk; - + SELECT vNewEntryFk; - - + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -55373,7 +55373,7 @@ BEGIN * Unlock the indicated entry * @vSelf params entry id */ - UPDATE `entry` + UPDATE `entry` SET lockerUserFk = NULL, locked = NULL WHERE id = vSelf; @@ -55404,21 +55404,21 @@ BEGIN DECLARE vComission INT; CREATE OR REPLACE TEMPORARY TABLE tmp.recalcEntryCommision - SELECT e.id + SELECT e.id FROM vn.entry e JOIN vn.travel t ON t.id = e.travelFk - JOIN vn.warehouse w ON w.id = t.warehouseInFk + JOIN vn.warehouse w ON w.id = t.warehouseInFk WHERE t.shipped >= util.VN_CURDATE() AND e.currencyFk = vCurrency; SET vComission = currency_getCommission(vCurrency); - UPDATE vn.entry e + UPDATE vn.entry e JOIN tmp.recalcEntryCommision tmp ON tmp.id = e.id SET e.commission = vComission; - SELECT `name` INTO vCurrencyName - FROM currency + SELECT `name` INTO vCurrencyName + FROM currency WHERE id = vCurrency; CALL entry_recalc(); @@ -55507,7 +55507,7 @@ BEGIN WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo AND cr.description = vDepartment GROUP BY cd.workerFk; - + CREATE OR REPLACE TEMPORARY TABLE volume ENGINE = MEMORY SELECT SUM(w.volume) volume, @@ -55518,15 +55518,15 @@ BEGIN CREATE OR REPLACE TEMPORARY TABLE errorsByChecker ENGINE = MEMORY - SELECT sub1.workerFk, COUNT(id) errors + SELECT sub1.workerFk, COUNT(id) errors FROM ( SELECT st.workerFk, t.id FROM saleMistake sm JOIN saleTracking st ON sm.saleFk = st.saleFk JOIN `state` s2 ON s2.id = st.stateFk - JOIN sale s ON s.id = sm.saleFk - JOIN ticket t on t.id = s.ticketFk + JOIN sale s ON s.id = sm.saleFk + JOIN ticket t on t.id = s.ticketFk WHERE (t.shipped BETWEEN vDatedFrom AND vDatedTo) AND s2.code IN ('OK','PREVIOUS_PREPARATION','PREPARED','CHECKED') ) sub1 @@ -55537,13 +55537,13 @@ BEGIN SELECT COUNT(t.id) errors, e.workerFk FROM vn.expeditionMistake pm - JOIN vn.expedition e ON e.id = pm.expeditionFk + JOIN vn.expedition e ON e.id = pm.expeditionFk JOIN vn.ticket t ON t.id = e.ticketFk WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo GROUP BY e.workerFk; IF (vDepartment = 'Sacadores') THEN - + INSERT INTO errorProduction(userFk, firstname, lastname, @@ -55576,12 +55576,12 @@ BEGIN LEFT JOIN errorsByChecker ec2 ON ec2.workerFk = t.workerFk JOIN (SELECT DISTINCT w.id -- Verificamos que son sacadores FROM vn.collection c - JOIN vn.state s ON s.id = c.stateFk + JOIN vn.state s ON s.id = c.stateFk JOIN vn.train tn ON tn.id = c.trainFk - JOIN vn.worker w ON w.id = c.workerFk + JOIN vn.worker w ON w.id = c.workerFk WHERE c.created BETWEEN vDatedFrom AND vDatedTo) sub ON sub.id = w.id GROUP BY w.id; - + CREATE OR REPLACE TEMPORARY TABLE itemPickerErrors -- Errores de los sacadores, derivadores de los revisadores ENGINE = MEMORY SELECT COUNT(c.ticketFk) errors, @@ -55601,7 +55601,7 @@ BEGIN JOIN itemPickerErrors ipe ON ipe.workerFk = ep.userFk SET ep.error = ep.error + ipe.errors WHERE vDatedFrom = ep.dated AND ep.rol = 'Sacadores'; - + DROP TEMPORARY TABLE itemPickerErrors; ELSE INSERT INTO errorProduction(userFk, @@ -55637,7 +55637,7 @@ BEGIN LEFT JOIN expeditionErrors pe ON pe.workerFk = t.workerFk GROUP BY w.id; END IF; - + DROP TEMPORARY TABLE total, errorsByClaim, volume, @@ -55663,7 +55663,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `errorProduction_addLauncher`() BEGIN DECLARE vDatedFrom DATETIME; DECLARE vDatedTo DATETIME; - + SELECT DATE_SUB(util.VN_CURDATE(),INTERVAL 1 DAY), CONCAT(DATE_SUB(util.VN_CURDATE(),INTERVAL 1 DAY),' 23:59:59') INTO vDatedFrom, vDatedTo; CALL vn.errorProduction_add('SACAR', vDatedFrom, vDatedTo); @@ -55694,7 +55694,7 @@ BEGIN DECLARE vRouteFk INT DEFAULT 0; SELECT t.routeFk INTO vRouteFk - FROM vn.expedition exp + FROM vn.expedition exp INNER JOIN ticket t on t.id = exp.ticketFk WHERE exp.id = vExpeditionFk; @@ -55897,14 +55897,14 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionPallet_printLabel`(vSelf INT) BEGIN /** - * Calls the report_print procedure and passes it + * Calls the report_print procedure and passes it * the necessary parameters for printing. * * @param vSelf expeditioPallet id. */ DECLARE vPrinterFk INT; DECLARE vUserFk INT DEFAULT account.myUser_getId(); - + SELECT o.labelerFk INTO vPrinterFk FROM operator o WHERE o.workerFk = vUserFk; @@ -55971,22 +55971,22 @@ BEGIN DECLARE vTotal INT DEFAULT 0; IF vPalletFk = 0 THEN -- Nuevo pallet - - INSERT INTO vn.expeditionPallet(truckFk) + + INSERT INTO vn.expeditionPallet(truckFk) VALUES(vTruckFk); - + SELECT LAST_INSERT_ID() INTO vPalletFk; - + END IF; - + SELECT COUNT(expeditionFk) INTO vTotal FROM vn.expeditionScan WHERE palletFk = vPalletFk; - + IF vTotal <> 0 THEN - SELECT expeditionFk, + SELECT expeditionFk, palletFk - FROM vn.expeditionScan + FROM vn.expeditionScan WHERE palletFk = vPalletFk; - ELSE + ELSE SELECT 0 expeditionFk,vPalletFk palletFk; END IF; END ;; @@ -56059,12 +56059,12 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionScan_Put`(vPalletFk INT, vExpeditionFk INT) BEGIN - - REPLACE vn.expeditionScan(expeditionFk, palletFk) + + REPLACE vn.expeditionScan(expeditionFk, palletFk) VALUES(vExpeditionFk, vPalletFk); - + SELECT LAST_INSERT_ID() INTO vPalletFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -56083,32 +56083,32 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionState_add`(vParam INT, vStateCode VARCHAR(100)) BEGIN - + /** * Inserta nuevos registros en la tabla vn.expeditionState, segun el parámetro - * + * * @param vParam Identificador de vn.expedition o de vn.route * @param vStateCode Corresponde a vn.expeditionStateType.code */ - + IF (SELECT COUNT(*) FROM vn.route r WHERE r.id = vParam) THEN - + INSERT INTO vn.expeditionState(expeditionFk, typeFk) SELECT e.id, est.id FROM vn.expedition e JOIN vn.ticket t ON t.id = e.ticketFk JOIN vn.expeditionStateType est ON est.code = vStateCode WHERE t.routeFk = vParam; - + ELSE - + INSERT INTO vn.expeditionState(expeditionFk, typeFk) SELECT vParam, est.id FROM vn.expeditionStateType est WHERE est.code = vStateCode; - + END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -56140,7 +56140,7 @@ BEGIN SELECT e.id, est.id FROM vn.expedition e JOIN vn.expeditionStateType est ON est.code = vStateCode - JOIN vn.ticket t ON t.id = e.ticketFk + JOIN vn.ticket t ON t.id = e.ticketFk WHERE t.addressFk = vAdressFk AND t.routeFk = vRouteFk; END ;; @@ -56161,14 +56161,14 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionState_addByExpedition`(vExpeditionFk INT, vStateCode VARCHAR(100)) BEGIN - + /** * Inserta nuevos registros en la tabla vn.expeditionState - * + * * @param vExpeditionFk Identificador de vn.expedition * @param vStateCode Corresponde a vn.expeditionStateType.code */ - + INSERT INTO vn.expeditionState(expeditionFk, typeFk) SELECT vExpeditionFk, est.id FROM vn.expeditionStateType est @@ -56194,7 +56194,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionState_addByPallet`(vPalle BEGIN /** * Inserta nuevos registros en la tabla vn.expeditionState - * + * * @param vPalletFk Identificador de vn.expedition * @param vStateCode Corresponde a vn.expeditionStateType.code */ @@ -56211,7 +56211,7 @@ BEGIN IF NOT hasExpeditions THEN DROP TEMPORARY TABLE tExpeditionScan; - CALL util.throw('palletDoesNotExist'); + CALL util.throw('palletDoesNotExist'); END IF; INSERT INTO vn.expeditionState(expeditionFk, typeFk) @@ -56236,21 +56236,21 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionState_addByRoute`(vRouteFk INT, vStateCode VARCHAR(100)) BEGIN - + /** * Inserta nuevos registros en la tabla vn.expeditionState, por rutas - * + * * @param vRouteFk Identificador de vn.route * @param vStateCode Corresponde a vn.expeditionStateType.code */ - + INSERT INTO vn.expeditionState(expeditionFk, typeFk) SELECT e.id, est.id FROM vn.expedition e JOIN vn.ticket t ON t.id = e.ticketFk JOIN vn.expeditionStateType est ON est.code = vStateCode WHERE t.routeFk = vRouteFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -56292,8 +56292,8 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionTruck_List`() BEGIN - SELECT id truckFk, - eta, + SELECT id truckFk, + eta, description Destino FROM expeditionTruck WHERE eta BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE()) @@ -56337,7 +56337,7 @@ BEGIN JOIN address a ON t.addressFk = a.id JOIN route r ON r.id = t.routeFk LEFT JOIN warehouse w ON t.warehouseFk = w.id - LEFT JOIN (SELECT sub.ticketFk, + LEFT JOIN (SELECT sub.ticketFk, CONCAT('(', GROUP_CONCAT(DISTINCT sub.itemPackingTypeFk ORDER BY sub.items DESC SEPARATOR ','), ') ') itemPackingTypeConcat FROM (SELECT s.ticketFk , i.itemPackingTypeFk, COUNT(*) items FROM ticket t @@ -56368,7 +56368,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_getState`(vExpeditionFk INT) BEGIN - + DECLARE vTicketsPendientes INT; DECLARE vEtiquetasTotales INT; DECLARE vEtiquetasEscaneadas INT; @@ -56378,24 +56378,24 @@ BEGIN FROM vn.ticket t JOIN vn.expedition e ON e.ticketFk = t.id WHERE e.id = vExpeditionFk; - + SELECT COUNT(*) INTO vTicketsPendientes FROM vn.ticket t LEFT JOIN vn.expedition e ON e.ticketFk = t.id WHERE t.routeFk = vRouteFk AND ISNULL(e.id); - + SELECT COUNT(*) INTO vEtiquetasTotales - FROM vn.expedition e + FROM vn.expedition e JOIN vn.ticket t ON t.id = e.ticketFk WHERE t.routeFk = vRouteFk; - + SELECT COUNT(*) INTO vEtiquetasEscaneadas - FROM vn.expeditionScan es + FROM vn.expeditionScan es JOIN vn.expedition e ON e.id = es.expeditionFk - JOIN vn.ticket t ON t.id = e.ticketFk + JOIN vn.ticket t ON t.id = e.ticketFk WHERE t.routeFk = vRouteFk; - + SELECT e.ticketFk ticket, t.nickname cliente, a.city ciudad, @@ -56409,17 +56409,17 @@ BEGIN vTicketsPendientes AS ticketsPendientes, vEtiquetasTotales AS etiquetasTotales, vEtiquetasEscaneadas AS etiquetasEscaneadas - FROM vn.expedition e - JOIN vn.ticket t ON t.id = e.ticketFk - JOIN vn.address a ON a.id = t.addressFk - JOIN vn.province p ON p.id = a.provinceFk - JOIN vn.`zone`z ON z.id = t.zoneFk - LEFT JOIN vn.route r ON r.id = t.routeFk - LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk - LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id - LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk + FROM vn.expedition e + JOIN vn.ticket t ON t.id = e.ticketFk + JOIN vn.address a ON a.id = t.addressFk + JOIN vn.province p ON p.id = a.provinceFk + JOIN vn.`zone`z ON z.id = t.zoneFk + LEFT JOIN vn.route r ON r.id = t.routeFk + LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk + LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id + LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk WHERE e.id = vExpeditionFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -56438,12 +56438,12 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_StateGet`(vExpeditionFk INT) BEGIN - + /* Devuelve una "ficha" con todos los datos relativos a la expedición - * - * param vExpeditionFk + * + * param vExpeditionFk */ - + DECLARE vTicketsPendientes INT; DECLARE vEtiquetasTotales INT; DECLARE vEtiquetasEscaneadas INT; @@ -56454,34 +56454,34 @@ BEGIN FROM vn.ticket t JOIN vn.expedition e ON e.ticketFk = t.id WHERE e.id = vExpeditionFk; - + SELECT COUNT(*) INTO vTicketsPendientes FROM vn.ticket t LEFT JOIN vn.expedition e ON e.ticketFk = t.id WHERE t.routeFk = vRouteFk AND ISNULL(e.id); - + SELECT COUNT(*) INTO vEtiquetasTotales - FROM vn.expedition e + FROM vn.expedition e JOIN vn.ticket t ON t.id = e.ticketFk WHERE t.routeFk = vRouteFk; - + SELECT COUNT(*) INTO vEtiquetasEscaneadas - FROM vn.expeditionScan es + FROM vn.expeditionScan es JOIN vn.expedition e ON e.id = es.expeditionFk - JOIN vn.ticket t ON t.id = e.ticketFk + JOIN vn.ticket t ON t.id = e.ticketFk WHERE t.routeFk = vRouteFk; - + SELECT COUNT(*) INTO vEtiquetasLeidasSorter - FROM srt.expedition e + FROM srt.expedition e JOIN vn.expedition ve ON ve.id = e.id LEFT JOIN vn.expeditionScan es ON es.expeditionFk = e.id - JOIN vn.ticket t ON t.id = ve.ticketFk + JOIN vn.ticket t ON t.id = ve.ticketFk WHERE t.routeFk = vRouteFk AND e.created != e.updated - AND ISNULL(es.expeditionFk); - - + AND ISNULL(es.expeditionFk); + + SELECT e.ticketFk ticket, t.nickname cliente, a.city ciudad, @@ -56496,17 +56496,17 @@ BEGIN vEtiquetasTotales AS etiquetasTotales, vEtiquetasEscaneadas AS etiquetasEscaneadas, vEtiquetasLeidasSorter AS etiquetasSorter - FROM vn.expedition e - JOIN vn.ticket t ON t.id = e.ticketFk - JOIN vn.address a ON a.id = t.addressFk - JOIN vn.province p ON p.id = a.provinceFk - JOIN vn.`zone`z ON z.id = t.zoneFk - LEFT JOIN vn.route r ON r.id = t.routeFk - LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk - LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id - LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk + FROM vn.expedition e + JOIN vn.ticket t ON t.id = e.ticketFk + JOIN vn.address a ON a.id = t.addressFk + JOIN vn.province p ON p.id = a.provinceFk + JOIN vn.`zone`z ON z.id = t.zoneFk + LEFT JOIN vn.route r ON r.id = t.routeFk + LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk + LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id + LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk WHERE e.id = vExpeditionFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -56552,7 +56552,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `fustControl`(vFromDated DATE, vToDated DATE) BEGIN - + DECLARE vSijsnerClientFk INT DEFAULT 19752; DECLARE vDateStart DATETIME; @@ -56561,68 +56561,68 @@ BEGIN SET vDateStart = vFromDated; SET vDateEnd = util.Dayend(vToDated); - SELECT p.id FustCode, - CAST(sent.stucks AS DECIMAL(10,0)) FH, - CAST(tp.stucks AS DECIMAL(10,0)) Tickets, - CAST(-sj.stucks AS DECIMAL(10,0)) Sijsner, + SELECT p.id FustCode, + CAST(sent.stucks AS DECIMAL(10,0)) FH, + CAST(tp.stucks AS DECIMAL(10,0)) Tickets, + CAST(-sj.stucks AS DECIMAL(10,0)) Sijsner, CAST(IFNULL(sent.stucks,0) - IFNULL(tp.stucks,0) + IFNULL(sj.stucks,0) AS DECIMAL(10,0)) saldo FROM vn.packaging p LEFT JOIN ( SELECT FustCode, sum(fustQuantity) stucks FROM ( SELECT IFNULL(pe.equivalentFk ,b.packageFk) FustCode, s.quantity / b.packing AS fustQuantity - FROM vn.sale s - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN vn.warehouse w ON w.id = t.warehouseFk - JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk - JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND lb.warehouse_id = t.warehouseFk - JOIN vn.buy b ON b.id = lb.buy_id - JOIN vn.packaging p ON p.id = b.packageFk + FROM vn.sale s + JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.warehouse w ON w.id = t.warehouseFk + JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk + JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND lb.warehouse_id = t.warehouseFk + JOIN vn.buy b ON b.id = lb.buy_id + JOIN vn.packaging p ON p.id = b.packageFk LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id - JOIN vn.address a ON a.id = t.addressFk - JOIN vn.province p2 ON p2.id = a.provinceFk - JOIN vn.country c ON c.id = p2.countryFk + JOIN vn.address a ON a.id = t.addressFk + JOIN vn.province p2 ON p2.id = a.provinceFk + JOIN vn.country c ON c.id = p2.countryFk WHERE t.shipped BETWEEN vDateStart AND vDateEnd AND wa.name = 'VNH' - AND p.isPackageReturnable - AND c.country = 'FRANCIA') sub + AND p.isPackageReturnable + AND c.country = 'FRANCIA') sub GROUP BY FustCode) sent ON sent.FustCode = p.id LEFT JOIN ( SELECT FustCode, sum(quantity) stucks FROM ( SELECT IFNULL(pe.equivalentFk ,tp.packagingFk) FustCode, tp.quantity - FROM vn.ticketPackaging tp - JOIN vn.ticket t ON t.id = tp.ticketFk - JOIN vn.warehouse w ON w.id = t.warehouseFk - JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk - JOIN vn.packaging p ON p.id = tp.packagingFk + FROM vn.ticketPackaging tp + JOIN vn.ticket t ON t.id = tp.ticketFk + JOIN vn.warehouse w ON w.id = t.warehouseFk + JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk + JOIN vn.packaging p ON p.id = tp.packagingFk LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id - JOIN vn.address a ON a.id = t.addressFk - JOIN vn.province p2 ON p2.id = a.provinceFk - JOIN vn.country c ON c.id = p2.countryFk + JOIN vn.address a ON a.id = t.addressFk + JOIN vn.province p2 ON p2.id = a.provinceFk + JOIN vn.country c ON c.id = p2.countryFk WHERE t.shipped BETWEEN vDateStart AND vDateEnd AND wa.name = 'VNH' - AND p.isPackageReturnable + AND p.isPackageReturnable AND c.country = 'FRANCIA' AND t.clientFk != vSijsnerClientFk - AND tp.quantity > 0) sub + AND tp.quantity > 0) sub GROUP BY FustCode) tp ON tp.FustCode = p.id LEFT JOIN ( SELECT FustCode, sum(quantity) stucks FROM ( SELECT IFNULL(pe.equivalentFk ,tp.packagingFk) FustCode, tp.quantity - FROM vn.ticketPackaging tp - JOIN vn.ticket t ON t.id = tp.ticketFk - JOIN vn.warehouse w ON w.id = t.warehouseFk - JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk - JOIN vn.packaging p ON p.id = tp.packagingFk + FROM vn.ticketPackaging tp + JOIN vn.ticket t ON t.id = tp.ticketFk + JOIN vn.warehouse w ON w.id = t.warehouseFk + JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk + JOIN vn.packaging p ON p.id = tp.packagingFk LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id WHERE t.shipped BETWEEN TIMESTAMPADD(DAY, 1, vDateStart ) AND TIMESTAMPADD(DAY, 1, vDateEnd ) AND wa.name = 'VNH' - AND p.isPackageReturnable - AND t.clientFk = vSijsnerClientFk) sub + AND p.isPackageReturnable + AND t.clientFk = vSijsnerClientFk) sub GROUP BY FustCode) sj ON sj.FustCode = p.id - WHERE sent.stucks + WHERE sent.stucks OR tp.stucks OR sj.stucks; @@ -56644,7 +56644,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `fustControlDetail`(vFromDated DATE, vToDated DATE) BEGIN - + DECLARE vSijsnerClientFk INT DEFAULT 19752; DECLARE vDateStart DATETIME; @@ -56652,29 +56652,29 @@ BEGIN SET vDateStart = vFromDated; SET vDateEnd = util.Dayend(vToDated); - + SELECT a.nickname shopName, - a.city , - IFNULL(pe.equivalentFk ,tp.packagingFk) FustCode, + a.city , + IFNULL(pe.equivalentFk ,tp.packagingFk) FustCode, tp.quantity, tp.ticketFk, CONCAT('From ', vFromDated,' to ', vToDated) AS dateRange - FROM vn.ticketPackaging tp - JOIN vn.ticket t ON t.id = tp.ticketFk - JOIN vn.warehouse w ON w.id = t.warehouseFk - JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk - JOIN vn.packaging p ON p.id = tp.packagingFk + FROM vn.ticketPackaging tp + JOIN vn.ticket t ON t.id = tp.ticketFk + JOIN vn.warehouse w ON w.id = t.warehouseFk + JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk + JOIN vn.packaging p ON p.id = tp.packagingFk LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id - JOIN vn.address a ON a.id = t.addressFk - JOIN vn.province p2 ON p2.id = a.provinceFk - JOIN vn.country c ON c.id = p2.countryFk + JOIN vn.address a ON a.id = t.addressFk + JOIN vn.province p2 ON p2.id = a.provinceFk + JOIN vn.country c ON c.id = p2.countryFk WHERE t.shipped BETWEEN vFromDated AND util.dayend(vToDated) AND wa.name = 'VNH' - AND p.isPackageReturnable + AND p.isPackageReturnable AND c.country = 'FRANCIA' AND t.clientFk != vSijsnerClientFk AND tp.quantity > 0; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -56700,8 +56700,8 @@ DECLARE vTicketFk INT; DECLARE vSaleFk INT; DECLARE vClonTicket INT DEFAULT 0; -DECLARE cur1 CURSOR FOR -SELECT s.ticketFk, s.id +DECLARE cur1 CURSOR FOR +SELECT s.ticketFk, s.id FROM vn.sale s JOIN vn.ticket t ON t.id = s.ticketFk JOIN vn.item i ON i.id = s.itemFk @@ -56717,17 +56717,17 @@ OPEN cur1; FETCH cur1 INTO vTicketFk, vSaleFk; WHILE done = 0 DO - + SELECT t.id INTO vClonTicket FROM vn.ticket t JOIN (SELECT addressFk, shipped FROM vn.ticket WHERE id = vTicketFk) sub USING(addressFk, shipped) WHERE t.warehouseFk = 44 LIMIT 1; - + SELECT vTicketFk, vClonTicket; - + IF vClonTicket = 0 THEN - + INSERT INTO ticket ( clientFk, shipped, @@ -56755,12 +56755,12 @@ FETCH cur1 INTO vTicketFk, vSaleFk; zonePrice, zoneBonus, routeFk - + FROM ticket WHERE id = vTicketFk; SET vClonTicket = LAST_INSERT_ID(); - + SELECT 'lstID', vClonTicket; /* INSERT INTO ticketObservation(ticketFk, observationTypeFk, description) @@ -56770,20 +56770,20 @@ FETCH cur1 INTO vTicketFk, vSaleFk; WHERE t.id = vClonTicket; */ INSERT INTO ticketLog - SET originFk = vTicketFk, userFk = account.myUser_getId(), `action` = 'insert', + SET originFk = vTicketFk, userFk = account.myUser_getId(), `action` = 'insert', description = CONCAT('Ha creado el ticket:', ' ', vClonTicket, ' clonando el ', vTicketFk); - + END IF; - + UPDATE vn.sale SET ticketFk = vClonTicket WHERE id = vSaleFk; SET vClonTicket = 0; - + SET done = 0; FETCH cur1 INTO vTicketFk, vSaleFk; - + END WHILE; CLOSE cur1; @@ -56808,8 +56808,8 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `getDayExpeditions`() BEGIN - SELECT - e.expeditions_id as expeditionFk, + SELECT + e.expeditions_id as expeditionFk, date_format(e.odbc_date,'%Y-%m-%d') as expeditionDate, e.ticket_id as ticketFk, t.routeFk as routeFk @@ -56886,7 +56886,7 @@ BEGIN SELECT DATE_SUB(util.VN_CURDATE(), INTERVAL yearsToDelete YEAR) INTO vDated FROM vn.greugeConfig; - + INSERT INTO vn.greuge(clientFk, description, amount, shipped, created, greugeTypeFk) SELECT clientFk, 'Suma agrupada', SUM(amount), MAX(shipped), MAX(created), greugeTypeFk FROM vn.greuge @@ -57004,8 +57004,8 @@ DECLARE done BOOL DEFAULT FALSE; DECLARE vTicketFk INT; DECLARE rs CURSOR FOR - SELECT id FROM vn.ticket - WHERE shipped = util.yesterday() + SELECT id FROM vn.ticket + WHERE shipped = util.yesterday() AND clientFk = 400 AND warehouseFk IN (1,44); @@ -57016,13 +57016,13 @@ OPEN rs; FETCH rs INTO vTicketFk; WHILE NOT done DO - + INSERT INTO vn.inventoryFailure(dated, itemFk, quantity, value, warehouseFk, throwerFk) - SELECT t.shipped, - s.itemFk, - s.quantity, + SELECT t.shipped, + s.itemFk, + s.quantity, b.buyingValue + b.freightValue + b.packageValue + b.comissionValue, - t.warehouseFk, + t.warehouseFk, w.id FROM vn.ticket t JOIN vn.sale s ON s.ticketFk = t.id @@ -57033,7 +57033,7 @@ WHILE NOT done DO AND s.quantity > 0; FETCH rs INTO vTicketFk; - + END WHILE; @@ -57101,7 +57101,7 @@ proc: BEGIN SELECT inventorySupplierFk INTO vInventorySupplierFk FROM entryConfig; - + SELECT am.id INTO vAgencyModeFkInventory FROM agencyMode am where code = 'inv'; @@ -57198,7 +57198,7 @@ proc: BEGIN JOIN entry e ON e.id = b.entryFk JOIN travel tr ON tr.id = e.travelFk WHERE tr.warehouseInFk = vWh - AND tr.landed BETWEEN vDateLastInventory + AND tr.landed BETWEEN vDateLastInventory AND vDateYesterday AND NOT isRaid GROUP BY b.itemFk; @@ -57252,7 +57252,7 @@ proc: BEGIN inv.price3 = b.price3, inv.minPrice = b.minPrice, inv.producer = p.name; - + INSERT INTO buy( itemFk, quantity, buyingValue, @@ -57286,15 +57286,15 @@ proc: BEGIN FROM tmp.inventory; SELECT vWh, COUNT(*), util.VN_NOW() FROM tmp.inventory; - + -- Actualizamos el campo lastUsed de item UPDATE item i JOIN tmp.inventory i2 ON i2.itemFk = i.id SET i.lastUsed = NOW() WHERE i2.quantity; - + -- DROP TEMPORARY TABLE tmp.inventory; - + END LOOP; CLOSE cWarehouses; @@ -57308,11 +57308,11 @@ proc: BEGIN SELECT e.id as entryId, t.id as travelId FROM travel t - JOIN `entry` e ON e.travelFk = t.id + JOIN `entry` e ON e.travelFk = t.id WHERE e.supplierFk = vInventorySupplierFk AND t.shipped <= util.VN_CURDATE() - INTERVAL 12 DAY AND (DAY(t.shipped) <> 1 OR shipped < util.VN_CURDATE() - INTERVAL 12 DAY); - + DELETE e FROM `entry` e JOIN tmp.entryToDelete tmp ON tmp.entryId = e.id; @@ -57374,7 +57374,7 @@ BEGIN b.id AS buyFk, b.entryFk, b.isIgnored, - b.price2, + b.price2, b.price3, b.stickers, b.packing, @@ -57388,20 +57388,20 @@ BEGIN s.id AS supplierFk, s.name AS supplier FROM itemType it - RIGHT JOIN (entry e + RIGHT JOIN (entry e LEFT JOIN supplier s ON s.id = e.supplierFk RIGHT JOIN buy b ON b.entryFk = e.id LEFT JOIN item i ON i.id = b.itemFk - LEFT JOIN ink ON ink.id = i.inkFk + LEFT JOIN ink ON ink.id = i.inkFk LEFT JOIN travel tr ON tr.id = e.travelFk LEFT JOIN warehouse w ON w.id = tr.warehouseInFk LEFT JOIN origin o ON o.id = i.originFk ) ON it.id = i.typeFk LEFT JOIN edi.ekt ek ON b.ektFk = ek.id WHERE (b.packageFk = "--" OR b.price2 = 0 OR b.packing = 0 OR b.buyingValue = 0) AND tr.landed > util.firstDayOfMonth(TIMESTAMPADD(MONTH,-1,util.VN_CURDATE())) AND s.name = 'INVENTARIO'; - + DROP TEMPORARY TABLE IF EXISTS tmp.lastEntryOk; - CREATE TEMPORARY TABLE tmp.lastEntryOk + CREATE TEMPORARY TABLE tmp.lastEntryOk (PRIMARY KEY (buyFk)) SELECT i.id AS itemFk, @@ -57411,7 +57411,7 @@ BEGIN b.id AS buyFk, b.entryFk, b.isIgnored, - b.price2, + b.price2, b.price3, b.stickers, b.packing, @@ -57425,11 +57425,11 @@ BEGIN s.id AS supplierFk, s.name AS supplier FROM itemType it - RIGHT JOIN (entry e + RIGHT JOIN (entry e LEFT JOIN supplier s ON s.id = e.supplierFk RIGHT JOIN buy b ON b.entryFk = e.id LEFT JOIN item i ON i.id = b.itemFk - LEFT JOIN ink ON ink.id = i.inkFk + LEFT JOIN ink ON ink.id = i.inkFk LEFT JOIN travel tr ON tr.id = e.travelFk LEFT JOIN warehouse w ON w.id = tr.warehouseInFk LEFT JOIN origin o ON o.id = i.originFk @@ -57437,34 +57437,34 @@ BEGIN LEFT JOIN edi.ekt ek ON b.ektFk = ek.id WHERE b.packageFk != "--" AND b.price2 != 0 AND b.packing != 0 AND b.buyingValue > 0 AND tr.landed > util.firstDayOfMonth(TIMESTAMPADD(MONTH,-2,util.VN_CURDATE())) ORDER BY tr.landed DESC; - + DROP TEMPORARY TABLE IF EXISTS tmp.lastEntryOkGroup; - CREATE TEMPORARY TABLE tmp.lastEntryOkGroup + CREATE TEMPORARY TABLE tmp.lastEntryOkGroup (INDEX (warehouseFk,itemFk)) SELECT * FROM tmp.lastEntryOk tmp GROUP BY tmp.itemFk,tmp.warehouseFk; - + UPDATE buy b JOIN tmp.lastEntry lt ON lt.buyFk = b.id JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk SET b.packageFk = eo.packageFk WHERE b.packageFk = "--"; - + UPDATE buy b JOIN tmp.lastEntry lt ON lt.buyFk = b.id JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk SET b.price2 = eo.price2 WHERE b.price2 = 0 ; - + UPDATE buy b JOIN tmp.lastEntry lt ON lt.buyFk = b.id JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk SET b.packing = eo.packing WHERE b.packing = 0; - + UPDATE buy b JOIN tmp.lastEntry lt ON lt.buyFk = b.id JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk SET b.buyingValue = eo.buyingValue WHERE b.buyingValue = 0; - + DROP TEMPORARY TABLE tmp.lastEntry; DROP TEMPORARY TABLE tmp.lastEntryOk; DROP TEMPORARY TABLE tmp.lastEntryOkGroup; @@ -57624,7 +57624,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceInDueDay_calculate`(vInvoiceInFk INT) BEGIN /** - * Calcula los vctos. de una factura recibida + * Calcula los vctos. de una factura recibida * En caso de haberlos informado previamente o que el proveedor sea español, no los recalculará * * @param vInvoiceInFk Factura recibida @@ -57645,46 +57645,46 @@ BEGIN WHERE ii.id = vInvoiceInFk; SELECT COUNT(*) INTO vHasDueDay - FROM invoiceInDueDay iid + FROM invoiceInDueDay iid WHERE iid.invoiceInFk = vInvoiceInFk; IF NOT vHasDueDay AND vCompanyCountryCode = 'ES' THEN SET @cont := 0; INSERT INTO invoiceInDueDay ( - invoiceInFk, - dueDated, - amount, + invoiceInFk, + dueDated, + amount, foreignValue ) SELECT vInvoiceInFk, - IF(payDay, + IF(payDay, IF(getNextDueDate(issued, pdd.detail, payDay) < created, created, - getNextDueDate(issued, pdd.detail, payDay)), + getNextDueDate(issued, pdd.detail, payDay)), GREATEST(created, issued + INTERVAL pdd.detail DAY)), - IF((@cont := @cont + 1) < cont, - TRUNCATE(venc / cont, 2), - venc - (TRUNCATE(venc / cont, 2) * (cont - 1))), - IF(@cont < cont, - TRUNCATE(foreignValue / cont, 2), - foreignValue - (TRUNCATE(foreignValue / cont, 2) * (cont - 1))) - FROM ( - SELECT SUM((1 + (IFNULL(ti.PorcentajeIva, 0) / 100) * vHasDueDayTax) - * iit.taxableBase) / COUNT(DISTINCT(pdd.detail)) venc, + IF((@cont := @cont + 1) < cont, + TRUNCATE(venc / cont, 2), + venc - (TRUNCATE(venc / cont, 2) * (cont - 1))), + IF(@cont < cont, + TRUNCATE(foreignValue / cont, 2), + foreignValue - (TRUNCATE(foreignValue / cont, 2) * (cont - 1))) + FROM ( + SELECT SUM((1 + (IFNULL(ti.PorcentajeIva, 0) / 100) * vHasDueDayTax) + * iit.taxableBase) / COUNT(DISTINCT(pdd.detail)) venc, SUM(iit.foreignValue) / COUNT(DISTINCT(pdd.detail)) foreignValue, - s.payDemFk, + s.payDemFk, ii.companyFk, COUNT(DISTINCT(pdd.detail)) cont, s.payDay, ii.issued, DATE(ii.created) + INTERVAL 2 DAY created - FROM invoiceIn ii - JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id - LEFT JOIN sage.TiposIva ti ON ti.CodigoIva= iit.taxTypeSageFk - JOIN supplier s ON s.id = ii.supplierFk - JOIN payDemDetail pdd ON pdd.id = s.payDemFk - WHERE ii.id = vInvoiceInFk + FROM invoiceIn ii + JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id + LEFT JOIN sage.TiposIva ti ON ti.CodigoIva= iit.taxTypeSageFk + JOIN supplier s ON s.id = ii.supplierFk + JOIN payDemDetail pdd ON pdd.id = s.payDemFk + WHERE ii.id = vInvoiceInFk GROUP BY ii.id )sub JOIN payDemDetail pdd ON pdd.id = sub.payDemFk @@ -57712,9 +57712,9 @@ BEGIN DELETE FROM invoiceInDueDay WHERE invoiceInFk = vInvoiceInFk; - + CALL invoiceInDueDay_calculate(vInvoiceInFk); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -57798,7 +57798,7 @@ BEGIN CALL invoiceInTax_getFromEntries(vInvoiceInFk); CALL invoiceInDueDay_calculate(vInvoiceInFk); - + FETCH rs INTO vInvoiceInFk; END WHILE; @@ -57830,7 +57830,7 @@ BEGIN SELECT MAX(rr.dated) INTO vDated FROM referenceRate rr JOIN invoiceIn ii ON ii.id = vId - WHERE rr.dated <= ii.issued + WHERE rr.dated <= ii.issued AND rr.currencyFk = ii.currencyFk ; IF vDated THEN @@ -57839,13 +57839,13 @@ BEGIN WHERE dated = vDated; END IF; - SELECT id INTO vExpenceFk - FROM vn.expence - WHERE `name` = 'Adquisición mercancia Extracomunitaria' - GROUP BY id + SELECT id INTO vExpenceFk + FROM vn.expence + WHERE `name` = 'Adquisición mercancia Extracomunitaria' + GROUP BY id LIMIT 1; - - DELETE FROM invoiceInTax + + DELETE FROM invoiceInTax WHERE invoiceInFk = vId; INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenceFk, foreignValue, taxTypeSageFk, transactionTypeSageFk) @@ -57859,9 +57859,9 @@ BEGIN JOIN entry e ON e.invoiceInFk = ii.id JOIN supplier s ON s.id = e.supplierFk JOIN buy b ON b.entryFk = e.id - LEFT JOIN referenceRate rr ON rr.currencyFk = ii.currencyFk + LEFT JOIN referenceRate rr ON rr.currencyFk = ii.currencyFk AND rr.dated = ii.issued - WHERE ii.id = vId + WHERE ii.id = vId HAVING taxableBase IS NOT NULL; END ;; DELIMITER ; @@ -57888,7 +57888,7 @@ BEGIN SELECT ii.bookEntried, iit.foreignValue, ii.companyFk, - ii.expenceFkDeductible, + ii.expenceFkDeductible, iit.taxableBase, iit.transactionTypeSageFk, ii.serial, @@ -57927,7 +57927,7 @@ BEGIN JOIN country c ON c.id = s.countryFk JOIN supplier sc ON sc.id = ii.companyFk JOIN country cc ON cc.id = sc.countryFk - JOIN invoiceInSerial iis ON iis.code = ii.serial + JOIN invoiceInSerial iis ON iis.code = ii.serial JOIN cplusInvoiceType472 cit ON cit.id = ii.cplusInvoiceType472Fk LEFT JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id LEFT JOIN sage.TiposTransacciones ttr ON ttr.CodigoTransaccion = iit.transactionTypeSageFk @@ -57950,18 +57950,18 @@ BEGIN NFACTICK, CLAVE, empresa_id) - SELECT + SELECT vBookNumber ASIEN, tii.bookEntried FECHA, tii.supplierAccount SUBCTA, - SUM(tii.taxableBase * - IF(tii.serial= 'R' AND ((tii.taxCode IS NULL OR tii.taxCode <> 'ISP21') - AND tii.taxTypeSageFk IS NOT NULL), - 1 + (tii.PorcentajeIva / 100), - 1)) EUROHABER, - CONCAT('s/fra', - RIGHT(tii.supplierRef, 8), - ':', + SUM(tii.taxableBase * + IF(tii.serial= 'R' AND ((tii.taxCode IS NULL OR tii.taxCode <> 'ISP21') + AND tii.taxTypeSageFk IS NOT NULL), + 1 + (tii.PorcentajeIva / 100), + 1)) EUROHABER, + CONCAT('s/fra', + RIGHT(tii.supplierRef, 8), + ':', LEFT(tii.supplierName, 10)) CONCEPTO, CAST(tii.taxableBase / tii.foreignValue AS DECIMAL (10,4)) CAMBIO, SUM(tii.foreignValue * IF(tii.serial = 'R', 1 + (tii.PorcentajeIva / 100), 1)) HABERME, @@ -57978,7 +57978,7 @@ BEGIN CONTRA, EURODEBE, EUROHABER, - CONCEPTO, + CONCEPTO, CAMBIO, DEBEME, HABERME, @@ -57990,9 +57990,9 @@ BEGIN tii.supplierAccount CONTRA, IF(tii.isWithheld AND tii.taxableBase < 0, NULL, ROUND(SUM(tii.taxableBase),2)) EURODEBE, IF(tii.isWithheld AND tii.taxableBase < 0, ROUND(SUM(-tii.taxableBase), 2), NULL) EUROHABER, - CONCAT('s/fra', - RIGHT(tii.supplierRef, 8), - ':', + CONCAT('s/fra', + RIGHT(tii.supplierRef, 8), + ':', LEFT(tii.supplierName, 10)) CONCEPTO, CAST(tii.taxableBase / tii.foreignValue AS DECIMAL (10, 4)) CAMBIO, IF(tii.isWithheld, NULL,ABS(ROUND(SUM(tii.foreignValue), 2))) DEBEME, @@ -58004,17 +58004,17 @@ BEGIN GROUP BY tii.expenceFk; -- Líneas de IVA - INSERT INTO XDiario( + INSERT INTO XDiario( ASIEN, FECHA, SUBCTA, - CONTRA, + CONTRA, EURODEBE, BASEEURO, CONCEPTO, - FACTURA, + FACTURA, IVA, - AUXILIAR, + AUXILIAR, SERIE, TIPOOPE, FECHA_EX, @@ -58063,28 +58063,28 @@ BEGIN tii.companyFk FROM tInvoiceIn tii LEFT JOIN ( - SELECT e.id + SELECT e.id FROM tInvoiceIn tii - JOIN expence e ON e.id = tii.expenceFk + JOIN expence e ON e.id = tii.expenceFk WHERE e.isWithheld LIMIT 1 - ) eWithheld ON TRUE - WHERE tii.taxTypeSageFk IS NOT NULL - AND (tii.taxCode IS NULL OR tii.taxCode NOT IN ('import10', 'import21')) + ) eWithheld ON TRUE + WHERE tii.taxTypeSageFk IS NOT NULL + AND (tii.taxCode IS NULL OR tii.taxCode NOT IN ('import10', 'import21')) GROUP BY tii.PorcentajeIva, tii.expenceFk; -- Línea iva inversor sujeto pasivo - INSERT INTO XDiario( + INSERT INTO XDiario( ASIEN, FECHA, SUBCTA, - CONTRA, + CONTRA, EUROHABER, BASEEURO, CONCEPTO, - FACTURA, + FACTURA, IVA, - AUXILIAR, + AUXILIAR, SERIE, TIPOOPE, FECHA_EX, @@ -58133,31 +58133,31 @@ BEGIN JOIN sage.config c WHERE tii.taxCode = 'ISP21' OR MID(tii.supplierAccount, 4, 1) = '1' AND tii.taxTypeSageFk IS NOT NULL - AND NOT(tii.isVies - AND c.nontaxableTransactionTypeFk = tii.transactionTypeSageFk + AND NOT(tii.isVies + AND c.nontaxableTransactionTypeFk = tii.transactionTypeSageFk AND tii.taxCode = 'nonTaxable') GROUP BY tii.PorcentajeIva, tii.expenceFk; - - -- Actualización del registro original + + -- Actualización del registro original UPDATE invoiceIn ii SET ii.isBooked = TRUE WHERE ii.id = vSelf; - + -- Problemas derivados de la precisión en los decimales al calcular los impuestos - UPDATE XDiario - SET EURODEBE = EURODEBE - + UPDATE XDiario + SET EURODEBE = EURODEBE - (SELECT IF(ABS(sub.difference) = 0.01, sub.difference, 0) FROM( - SELECT SUM(IFNULL(ROUND(EURODEBE, 2),0)) - SUM(IFNULL(ROUND(EUROHABER, 2), 0)) difference + SELECT SUM(IFNULL(ROUND(EURODEBE, 2),0)) - SUM(IFNULL(ROUND(EUROHABER, 2), 0)) difference FROM XDiario WHERE ASIEN = vBookNumber )sub ) - WHERE ASIEN = vBookNumber + WHERE ASIEN = vBookNumber AND EURODEBE <> 0 ORDER BY id DESC LIMIT 1; - + DROP TEMPORARY TABLE tInvoiceIn; END ;; DELIMITER ; @@ -58272,7 +58272,7 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS rs; CREATE TEMPORARY TABLE rs - SELECT + SELECT c.accountingAccount AS clientBookingAccount, io.amount as totalAmount, CONCAT('n/fra ', io.ref) as simpleConcept, @@ -58306,19 +58306,19 @@ BEGIN WHERE io.id = vInvoice; CALL vn.ledger_next(vBookNumber); - + -- Linea del cliente INSERT INTO XDiario( ASIEN, FECHA, - SUBCTA, + SUBCTA, EURODEBE, - CONCEPTO, + CONCEPTO, FECHA_EX, FECHA_OP, empresa_id ) - SELECT + SELECT vBookNumber AS ASIEN, rs.FECHA, rs.clientBookingAccount AS SUBCTA, @@ -58334,14 +58334,14 @@ BEGIN ASIEN, FECHA, SUBCTA, - CONTRA, + CONTRA, EUROHABER, - CONCEPTO, + CONCEPTO, FECHA_EX, FECHA_OP, empresa_id ) - SELECT + SELECT vBookNumber AS ASIEN, rs.FECHA, ioe.expenceFk AS SUBCTA, @@ -58355,8 +58355,8 @@ BEGIN JOIN invoiceOutExpence ioe WHERE ioe.invoiceOutFk = vInvoice; - SELECT GROUP_CONCAT(`name` SEPARATOR ',') - INTO vExpenceConcept + SELECT GROUP_CONCAT(`name` SEPARATOR ',') + INTO vExpenceConcept FROM expence e JOIN invoiceOutExpence ioe ON ioe.expenceFk = e.id WHERE ioe.invoiceOutFk = vInvoice; @@ -58366,7 +58366,7 @@ BEGIN ASIEN, FECHA, SUBCTA, - CONTRA, + CONTRA, EUROHABER, BASEEURO, CONCEPTO, @@ -58394,7 +58394,7 @@ BEGIN TIPORECTIF, empresa_id ) - SELECT + SELECT vBookNumber AS ASIEN, rs.FECHA, iot.pgcFk AS SUBCTA, @@ -58414,11 +58414,11 @@ BEGIN rs.FECHA_OP, rs.FECHA_EX, rs.TIPOOPE, - rs.NFACTICK, + rs.NFACTICK, rs.TERIDNIF, rs.TERNIF, rs.TERNOM, - pgc.mod340 AS L340, + pgc.mod340 AS L340, pgc.cplusTrascendency477Fk AS TIPOCLAVE, pgc.cplusTaxBreakFk as TIPOEXENCI, rs.TIPONOSUJE, @@ -58426,13 +58426,13 @@ BEGIN rs.TIPORECTIF, rs.companyFk AS empresa_id FROM rs - JOIN invoiceOutTax iot + JOIN invoiceOutTax iot JOIN pgc ON pgc.code = iot.pgcFk LEFT JOIN pgcEqu pe ON pe.vatFk = iot.pgcFk -- --------------- Comprueba si la linea es de iva con rec.equiv. asociado - LEFT JOIN pgc pgce ON pgce.code = pe.equFk + LEFT JOIN pgc pgce ON pgce.code = pe.equFk LEFT JOIN pgcEqu pe2 ON pe2.equFk = iot.pgcFk -- --------------- Comprueba si la linea es de rec.equiv. WHERE iot.invoiceOutFk = vInvoice; - + UPDATE invoiceOut SET booked = util.VN_CURDATE() WHERE id = vInvoice; @@ -58464,7 +58464,7 @@ BEGIN DECLARE done BOOL DEFAULT FALSE; - DECLARE rs CURSOR FOR + DECLARE rs CURSOR FOR SELECT io.id FROM invoiceOut io WHERE RIGHT(ref,7) BETWEEN 1724215 AND 1724224 @@ -58479,15 +58479,15 @@ BEGIN WHILE NOT done DO CALL invoiceOutBooking(vInvoice); - + FETCH rs INTO vInvoice ; - + SET vContador = vContador + 1; - + IF vContador MOD 50 = 0 THEN - + SELECT CONCAT(vContador, ' de momento') AS FACTURAS_ASENTADAS; - + END IF; END WHILE; @@ -58517,14 +58517,14 @@ BEGIN DECLARE vAsien INTEGER; DECLARE vSendMail BOOL; DECLARE vBody TEXT; - + SELECT ASIEN INTO vAsien - FROM XDiario + FROM XDiario WHERE SERIE = SUBSTRING(vRef, 1, 1) AND FACTURA = SUBSTRING(vRef, 2, LENGTH(vRef)-1) LIMIT 1; - SELECT IF(enlazado OR enlazadoSage, TRUE, FALSE), + SELECT IF(enlazado OR enlazadoSage, TRUE, FALSE), CONCAT( ' @@ -58533,7 +58533,7 @@ BEGIN - ', + ', GROUP_CONCAT( CONCAT(' @@ -58546,14 +58546,14 @@ BEGIN ) SEPARATOR ' ' ), '
FECHACONCEPTO EURODEBE EUROHABER
', IFNULL(FECHA,''), '
' - ) + ) INTO vSendMail, vBody - FROM XDiario + FROM XDiario WHERE ASIEN = vAsien; - DELETE FROM XDiario + DELETE FROM XDiario WHERE ASIEN = vAsien; - + IF vSendMail THEN CALL mail_insert( 'administracion@verdnatura.es', @@ -58571,7 +58571,7 @@ BEGIN SET refFk = NULL WHERE refFk = vRef; - DELETE + DELETE FROM invoiceOut WHERE ref = vRef; @@ -58594,7 +58594,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOutListByCompany`(vCompany INT, vStarted DATE, vEnded DATE) BEGIN -SELECT +SELECT c.socialName as RazonSocial, c.fi as NIF, io.ref as Factura, @@ -58606,7 +58606,7 @@ SELECT pgc.rate as Tipo, iot.vat as Cuota, pgc.name as Concepto - + FROM vn.invoiceOut io JOIN vn.invoiceOutTax iot ON iot.invoiceOutFk = io.id JOIN vn.client c ON c.id = io.clientFk @@ -59051,17 +59051,17 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOut_newFromClient`( - IN vClientFk INT, - IN vSerial CHAR(2), + IN vClientFk INT, + IN vSerial CHAR(2), IN vMaxShipped DATE, - IN vCompanyFk INT, + IN vCompanyFk INT, IN vTaxArea VARCHAR(25), - IN vRef VARCHAR(25), + IN vRef VARCHAR(25), OUT vInvoiceId INT) BEGIN /** * Factura los tickets de un cliente hasta una fecha dada - * @param vClientFk Id del cliente a facturar + * @param vClientFk Id del cliente a facturar * @param vSerial Serie de factura * @param vMaxShipped Fecha hasta la cual cogera tickets para facturar * @param vCompanyFk Id de la empresa desde la que se factura @@ -59080,11 +59080,11 @@ BEGIN IF NOT vIsRefEditable THEN CALL util.throw('serial non editable'); END IF; - END IF; + END IF; SELECT COUNT(*) INTO vIsExportation FROM vn.invoiceOutSerial - WHERE taxAreaFk = 'WORLD' + WHERE taxAreaFk = 'WORLD' AND `code` = vSerial; IF vIsExportation THEN @@ -59097,7 +59097,7 @@ BEGIN UPDATE invoiceOut SET `ref` = vRef - WHERE id = vInvoiceId + WHERE id = vInvoiceId AND vRef IS NOT NULL; IF vSerial <> 'R' AND NOT ISNULL(vInvoiceId) AND vInvoiceId <> 0 THEN @@ -59126,7 +59126,7 @@ BEGIN * Factura un ticket * @param vTicketFk Id del ticket * @param vSerial Serie de factura - * @param vTaxArea Area de la factura en caso de querer forzarlo, + * @param vTaxArea Area de la factura en caso de querer forzarlo, * en la mayoria de los casos poner NULL * @return vInvoiceId */ @@ -59141,11 +59141,11 @@ BEGIN IF NOT vIsRefEditable THEN CALL util.throw('serial non editable'); END IF; - - UPDATE invoiceOut + + UPDATE invoiceOut SET `ref` = vRef WHERE id = vInvoiceId; - END IF; + END IF; IF vSerial <> 'R' AND NOT ISNULL(vInvoiceId) AND vInvoiceId <> 0 THEN CALL invoiceOutBooking(vInvoiceId); @@ -59227,7 +59227,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `itemBarcode_update`(vItemFk INT,vCo BEGIN IF vDelete THEN DELETE FROM vn.itemBarcode WHERE itemFk = vItemFk AND code = vCode; -ELSE +ELSE INSERT INTO vn.itemBarcode(itemFk,code) VALUES (vItemFk,vCode); END IF; @@ -59249,8 +59249,8 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemFreight_Show`(vItemFk INT, vWarehouseFk INT) BEGIN - - SELECT cm3 Volumen_Entrada, + + SELECT cm3 Volumen_Entrada, cm3delivery Volumen_Salida, p.volume Volumen_del_embalaje, p.width Ancho_del_embalaje, @@ -59263,11 +59263,11 @@ BEGIN b.id buyFk, b.entryFk, w.name warehouseFk - FROM vn.itemCost ic - JOIN vn.item i ON i.id = ic.itemFk - LEFT JOIN cache.last_buy lb ON lb.item_id = ic.itemFk AND lb.warehouse_id = ic.warehouseFk - LEFT JOIN vn.buy b ON b.id = lb.buy_id - LEFT JOIN vn.packaging p ON p.id = b.packageFk + FROM vn.itemCost ic + JOIN vn.item i ON i.id = ic.itemFk + LEFT JOIN cache.last_buy lb ON lb.item_id = ic.itemFk AND lb.warehouse_id = ic.warehouseFk + LEFT JOIN vn.buy b ON b.id = lb.buy_id + LEFT JOIN vn.packaging p ON p.id = b.packageFk LEFT JOIN vn.warehouse w ON w.id = ic.warehouseFk WHERE ic.itemFk = vItemFk AND ic.warehouseFk = vWarehouseFk; @@ -59291,33 +59291,33 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `itemFuentesBalance`(vDaysInFuture I BEGIN /* Se utiliza para calcular la necesidad de mover mercancia entre el almacén de fuentes y el nuestro - * + * * @param vDaysInFuture Rango de dias para calcular entradas y salidas - * + * */ - + DECLARE vWarehouseFk INT; SELECT s.warehouseFk INTO vWarehouseFk - FROM vn.sector s + FROM vn.sector s WHERE s.code = 'FUENTES_PICASSE'; - + CALL cache.stock_refresh(FALSE); - SELECT i.id itemFk, + SELECT i.id itemFk, i.longName, i.size, i.subName, - v.amount - IFNULL(fue.Fuentes,0) - IFNULL(alb.albenfruit,0) as visible, - fue.Fuentes, + v.amount - IFNULL(fue.Fuentes,0) - IFNULL(alb.albenfruit,0) as visible, + fue.Fuentes, alb.Albenfruit, - sale.venta, - IFNULL(buy.compra,0) + IFNULL(mov.traslado,0) as compra, - IFNULL(v.amount,0) + IFNULL(sale.venta,0) + IFNULL(buy.compra,0) + IFNULL(mov.traslado,0) + sale.venta, + IFNULL(buy.compra,0) + IFNULL(mov.traslado,0) as compra, + IFNULL(v.amount,0) + IFNULL(sale.venta,0) + IFNULL(buy.compra,0) + IFNULL(mov.traslado,0) - IFNULL(fue.Fuentes,0) - IFNULL(alb.albenfruit,0) as saldo - FROM vn.item i - JOIN vn.itemType it ON it.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk + FROM vn.item i + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk LEFT JOIN ( SELECT ish.itemFk, CAST(SUM(ish.visible) AS DECIMAL(10,0)) AS Fuentes FROM vn.itemShelving ish @@ -59325,7 +59325,7 @@ BEGIN JOIN vn.parking p ON p.id = sh.parkingFk JOIN vn.sector s ON s.id = p.sectorFk WHERE s.code = 'FUENTES_PICASSE' - GROUP BY ish.itemFk + GROUP BY ish.itemFk ) fue ON fue.itemFk = i.id LEFT JOIN ( SELECT ish.itemFk, CAST(SUM(ish.visible) AS DECIMAL(10,0)) AS Albenfruit @@ -59334,7 +59334,7 @@ BEGIN JOIN vn.parking p ON p.id = sh.parkingFk JOIN vn.sector s ON s.id = p.sectorFk WHERE s.code = 'ALBENFRUIT' - GROUP BY ish.itemFk + GROUP BY ish.itemFk ) alb ON alb.itemFk = i.id LEFT JOIN cache.stock v ON i.id = v.item_id AND v.warehouse_id = vWarehouseFk LEFT JOIN ( @@ -59359,9 +59359,9 @@ BEGIN AND warehouse_id = vWarehouseFk GROUP BY item_id ) mov ON mov.item_id = i.id - WHERE (v.amount OR fue.Fuentes OR alb.Albenfruit) + WHERE (v.amount OR fue.Fuentes OR alb.Albenfruit) AND i.itemPackingTypeFk = 'H' - AND ic.shortLife + AND ic.shortLife ; END ;; @@ -59383,7 +59383,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemPlacementFromTicket`(vTicket INT) BEGIN /** - * Llama a itemPlacementUpdateVisible + * Llama a itemPlacementUpdateVisible * de los articulos de la tabla temporal tmp.itemPlacement(itemFk) * @treturn tmp.itemPlacement * @param vTicket Id del Ticket @@ -59397,9 +59397,9 @@ BEGIN FROM ticket t JOIN sale s ON s.ticketFk = t.id WHERE t.id = vTicket; - + CALL itemPlacementUpdateVisible(); - + DROP TEMPORARY TABLE tmp.itemPlacement; END ;; DELIMITER ; @@ -59432,7 +59432,7 @@ BEGIN CAST(FLOOR(LEAST(ish.stock,quantity) / ish.packing) AS DECIMAL(10,0)), ' x ', ish.packing, - IF ( + IF ( LEAST(ish.stock,quantity) MOD ish.packing, CONCAT(' + ',CAST(LEAST(ish.stock,quantity) MOD ish.packing AS DECIMAL(10,0))), '' @@ -59463,7 +59463,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemPlacementSupplyCloseOrder`(vId INT, vQuantity INT) BEGIN - UPDATE vn.itemPlacementSupply + UPDATE vn.itemPlacementSupply SET priority = 10 WHERE id = vId; @@ -59489,7 +59489,7 @@ BEGIN DECLARE vId INT; DECLARE vLastParkingFk INT; DECLARE vNextParkingFk INT; - + SELECT sh.parkingFk INTO vLastParkingFk FROM vn.itemShelvingPlacementSupply isps JOIN vn.itemShelving ish ON ish.id = isps.itemShelvingFk @@ -59497,9 +59497,9 @@ BEGIN WHERE isps.userFk = getUser() ORDER BY isps.created DESC LIMIT 1; - + SET vNextParkingFk = vn.itemShelvingPlacementSupply_ClosestGet(vLastParkingFk); - + SELECT ipsl.id INTO vId FROM vn.itemPlacementSupplyList ipsl JOIN vn.itemShelvingPlacementSupplyStock ispss ON ispss.itemFk = ipsl.itemFk @@ -59508,13 +59508,13 @@ BEGIN AND ipsl.sectorFk = vSector ORDER BY ipsl.repoUserFk DESC, ipsl.priority DESC, (ispss.parkingFk = vNextParkingFk) DESC, ispss.parking DESC, ipsl.created LIMIT 1; - + UPDATE vn.itemPlacementSupply SET repoUserFk = getUser() WHERE id = vId; - - SELECT * FROM vn.itemPlacementSupplyList - WHERE id = vId + + SELECT * FROM vn.itemPlacementSupplyList + WHERE id = vId AND sectorFk = vSector; END ;; @@ -59589,20 +59589,20 @@ BEGIN * @param vItemFk item id * @param vTicketFk ticket id * @param vShowType mostrar tipos - */ + */ DECLARE vWarehouseFk INT; DECLARE vShipped DATE; DECLARE vCalcFk INT; DECLARE vTypeFk INT; - - + + DECLARE vTag1 VARCHAR(25); DECLARE vTag5 VARCHAR(25); DECLARE vTag6 VARCHAR(25); DECLARE vTag7 VARCHAR(25); DECLARE vTag8 VARCHAR(25); - + DECLARE vValue1 VARCHAR(50); DECLARE vValue5 VARCHAR(50); DECLARE vValue6 VARCHAR(50); @@ -59612,16 +59612,16 @@ BEGIN SELECT warehouseFk, shipped INTO vWarehouseFk, vShipped FROM vn.ticket WHERE id = vTicketFk; - + SELECT typeFk, tag5, value5, tag6, value6, tag7, value7, tag8, value8, t1.name, it1.value INTO vTypeFk, vTag5, vValue5, vTag6, vValue6, vTag7, vValue7, vTag8, vValue8, vTag1, vValue1 FROM vn.item i LEFT JOIN vn.itemTag it1 ON it1.itemFk = i.id AND it1.priority = 1 LEFT JOIN vn.tag t1 ON t1.id = it1.tagFk WHERE i.id = vItemFk; - + CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, vShipped); - + SELECT i.id itemFk, i.longName, i.subName, @@ -59654,7 +59654,7 @@ BEGIN ORDER BY counter DESC, (t1.name = vTag1 COLLATE utf8_general_ci) DESC, (it1.value = vValue1 COLLATE utf8_general_ci) DESC, - (i.tag6 = vTag6 COLLATE utf8_general_ci) DESC, + (i.tag6 = vTag6 COLLATE utf8_general_ci) DESC, (i.value6 = vValue6 COLLATE utf8_general_ci) DESC, (i.tag5 = vTag5 COLLATE utf8_general_ci) DESC, (i.value5 = vValue5 COLLATE utf8_general_ci) DESC, @@ -59662,7 +59662,7 @@ BEGIN (i.value7 = vValue7 COLLATE utf8_general_ci) DESC, (i.tag8 = vTag8 COLLATE utf8_general_ci) DESC, (i.value8 = vValue8 COLLATE utf8_general_ci) DESC; - + END ;; DELIMITER ; @@ -59688,7 +59688,7 @@ BEGIN * @param vSaleFk id de la tabla sale * @param vMateFk articulo sustituto * @ param vQuantity cantidad que se va a sustituir - */ + */ DECLARE vTicketFk INT; DECLARE vItemFk INT; DECLARE vWarehouseFk SMALLINT; @@ -59697,41 +59697,41 @@ BEGIN DECLARE vBox INT; DECLARE vPacking INT; DECLARE vRoundQuantity INT DEFAULT 1; - + SELECT s.ticketFk, LEAST(s.quantity, vQuantity), s.itemFk,t.shipped,t.warehouseFk INTO vTicketFk, vQuantity, vItemFk,vDate,vWarehouseFk FROM vn.sale s JOIN vn.ticket t ON t.id = s.ticketFk WHERE s.id = vSaleFk; - + UPDATE vn.sale SET quantity = quantity - vQuantity WHERE id = vSaleFk; - + CALL vn.buyUltimate(vWarehouseFk, vDate); - + SELECT `grouping`, groupingMode, packing INTO vGrouping,vBox,vPacking FROM buy b JOIN tmp.buyUltimate tmp ON b.id = tmp.buyFk WHERE tmp.itemFk = vMateFk AND tmp.WarehouseFk = vWarehouseFk; - + IF vBox = 2 AND vPacking > 0 THEN SET vRoundQuantity = vPacking; END IF; IF vBox = 1 AND vGrouping > 0 THEN SET vRoundQuantity = vGrouping; END IF; - + INSERT INTO vn.sale(ticketFk, itemFk, quantity, concept) SELECT vTicketFk, vMateFk, CEIL(vQuantity / vRoundQuantity) * vRoundQuantity, CONCAT('+ ',i.longName) FROM vn.item i WHERE id = vMateFk; - + SELECT LAST_INSERT_ID() INTO vSaleFk; - + CALL vn.sale_calculateComponent(vSaleFk, NULL); - + INSERT INTO vn.itemProposal(itemFk, mateFk, counter) VALUES(vItemFk, vMateFk, 1) ON DUPLICATE KEY UPDATE counter = counter + 1; @@ -59760,13 +59760,13 @@ BEGIN DECLARE vCalcFk INT; DECLARE vTypeFk INT; DECLARE vResultsMax INT DEFAULT 10; - + DECLARE vTag1 VARCHAR(25); DECLARE vTag5 VARCHAR(25); DECLARE vTag6 VARCHAR(25); DECLARE vTag7 VARCHAR(25); DECLARE vTag8 VARCHAR(25); - + DECLARE vValue1 VARCHAR(50); DECLARE vValue5 VARCHAR(50); DECLARE vValue6 VARCHAR(50); @@ -59776,16 +59776,16 @@ BEGIN SELECT warehouseFk, shipped INTO vWarehouseFk, vShipped FROM vn.ticket WHERE id = vTicketFk; - + SELECT typeFk, tag5, value5, tag6, value6, tag7, value7, tag8, value8, t1.name, it1.value INTO vTypeFk, vTag5, vValue5, vTag6, vValue6, vTag7, vValue7, vTag8, vValue8, vTag1, vValue1 - FROM vn.item i + FROM vn.item i LEFT JOIN vn.itemTag it1 ON it1.itemFk = i.id AND it1.priority = 1 LEFT JOIN vn.tag t1 ON t1.id = it1.tagFk WHERE i.id = vItemFk; - + CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, vShipped); - + SELECT i.id itemFk, i.longName, i.subName, @@ -59803,7 +59803,7 @@ BEGIN (i.value8 <=> vValue8 COLLATE utf8_general_ci) match8, a.available, IFNULL(ip.counter,0) counter - FROM vn.item i + FROM vn.item i JOIN cache.available a ON a.item_id = i.id LEFT JOIN vn.itemProposal ip ON ip.mateFk = i.id AND ip.itemFk = vItemFk LEFT JOIN vn.itemTag it1 ON it1.itemFk = i.id AND it1.priority = 1 @@ -59817,7 +59817,7 @@ BEGIN (it1.value = vValue1 COLLATE utf8_general_ci) DESC, (i.tag5 = vTag5 COLLATE utf8_general_ci) DESC, (i.value5 = vValue5 COLLATE utf8_general_ci) DESC, - (i.tag6 = vTag6 COLLATE utf8_general_ci) DESC, + (i.tag6 = vTag6 COLLATE utf8_general_ci) DESC, (i.value6 = vValue6 COLLATE utf8_general_ci) DESC, (i.tag7 = vTag7 COLLATE utf8_general_ci) DESC, (i.value7 = vValue7 COLLATE utf8_general_ci) DESC, @@ -59853,7 +59853,7 @@ BEGIN CREATE TEMPORARY TABLE tmp.item SELECT vItem id; - + CALL item_refreshTags(); DROP TEMPORARY TABLE tmp.item; @@ -59876,23 +59876,23 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemSale_byWeek`(vWeek INT, IN vYear INT, vItemFk INT, vWarehouseFk INT) BEGIN - + DECLARE vStarted DATE; DECLARE vEnded DATETIME; SELECT MIN(dated), util.dayEnd(MAX(dated)) INTO vStarted, vEnded - FROM `time` t + FROM `time` t WHERE CONCAT(vYear, LPAD(vWeek, 2, 0)) = t.period; SELECT t.shipped, w.name warehouse, - s.ticketFk, + s.ticketFk, t.nickname client, - am.name agencyName, + am.name agencyName, wk.code salesPerson, s.itemFk, - IFNULL(CONCAT(ig.longName,' ',ig.`size`,' ',ig.subName), s.concept) AS concept, - s.quantity, + IFNULL(CONCAT(ig.longName,' ',ig.`size`,' ',ig.subName), s.concept) AS concept, + s.quantity, s.price, s.priceFixed, s.discount, @@ -59902,15 +59902,15 @@ BEGIN wk.id salesPersonFk FROM sale s JOIN ticket t ON t.id = s.ticketFk - JOIN warehouse w ON w.id = t.warehouseFk + JOIN warehouse w ON w.id = t.warehouseFk JOIN address a ON a.id = t.addressFk LEFT JOIN agencyMode am ON am.id = t.agencyModeFk JOIN `client` c ON c.id = a.clientFk - LEFT JOIN worker wk ON wk.id = c.salesPersonFk + LEFT JOIN worker wk ON wk.id = c.salesPersonFk LEFT JOIN ticketLastState tls ON tls.ticketFk = t.id - LEFT JOIN saleBuy sb ON sb.saleFk = s.id - LEFT JOIN buy b ON b.id = sb.buyFk - LEFT JOIN item ig ON ig.id = b.itemOriginalFk + LEFT JOIN saleBuy sb ON sb.saleFk = s.id + LEFT JOIN buy b ON b.id = sb.buyFk + LEFT JOIN item ig ON ig.id = b.itemOriginalFk WHERE s.itemFk = vItemFk AND t.shipped BETWEEN vStarted AND vEnded AND IF(vWarehouseFk = 0, w.hasComission , t.warehouseFk = vWarehouseFk) @@ -59937,9 +59937,9 @@ BEGIN DECLARE vItemFk INT; SELECT vn.barcodeToItem(vBarcode) INTO vItemFk; - + UPDATE vn.item SET minimum = min WHERE id = vItemFk; - + END ;; @@ -59961,8 +59961,8 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemSearchShelving`(`vShelvingFk` VARCHAR(3)) BEGIN SELECT p.`column` AS col , p.`row` - FROM vn.shelving s - JOIN parking p ON s.parkingFk = p.id + FROM vn.shelving s + JOIN parking p ON s.parkingFk = p.id WHERE s.`code` = vShelvingFk COLLATE utf8_general_ci; END ;; DELIMITER ; @@ -60003,36 +60003,36 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingLog_get`(vShelvingFk VARCHAR(10) ) BEGIN - + /** * Devuelve el log de los item en cada carro * - * @param vShelvingFk Matrícula del carro - * + * @param vShelvingFk Matrícula del carro + * */ - - SELECT isl.itemShelvingFk, - isl.created, - isl.accion, - isl.itemFk, - isl.shelvingFk, - isl.quantity, + + SELECT isl.itemShelvingFk, + isl.created, + isl.accion, + isl.itemFk, + isl.shelvingFk, + isl.quantity, isl.visible, - isl.available, - isl.grouping, - isl.packing, - isl.stars, - item.longName, - item.size, - item.subName, - worker.code, + isl.available, + isl.grouping, + isl.packing, + isl.stars, + item.longName, + item.size, + item.subName, + worker.code, isl.accion - FROM item - JOIN itemShelvingLog isl ON item.id = isl.itemFk + FROM item + JOIN itemShelvingLog isl ON item.id = isl.itemFk JOIN worker ON isl.workerFk = worker.id WHERE shelvingFk = vShelvingFk OR isl.itemFk = vShelvingFk ORDER BY isl.created DESC; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60051,7 +60051,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingMakeFromDate`(IN `vShelvingFk` VARCHAR(8), IN `vBarcode` VARCHAR(22), IN `vQuantity` INT, IN `vPackagingFk` VARCHAR(10), IN `vGrouping` INT, IN `vPacking` INT, IN `vWarehouseFk` INT, `vCreated` VARCHAR(22)) BEGIN - + DECLARE vItemFk INT; SELECT vn.barcodeToItem(vBarcode) INTO vItemFk; @@ -60070,9 +60070,9 @@ BEGIN END IF; - IF (SELECT COUNT(*) FROM vn.itemShelving - WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk - AND itemFk = vItemFk + IF (SELECT COUNT(*) FROM vn.itemShelving + WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk + AND itemFk = vItemFk AND packing = vPacking) = 1 THEN UPDATE vn.itemShelving @@ -60102,8 +60102,8 @@ BEGIN LEFT JOIN cache.last_buy lb ON i.id = lb.item_id AND lb.warehouse_id = vWarehouseFk LEFT JOIN vn.buy b ON b.id = lb.buy_id WHERE i.id = vItemFk; - END IF; - + END IF; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60124,9 +60124,9 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingMatch`(vEntryFk INT, vA BEGIN DECLARE vTravelFk INT; - - SELECT travelFk INTO vTravelFk - FROM entry + + SELECT travelFk INTO vTravelFk + FROM entry WHERE id = vEntryFk; SELECT i.id, i.longName, i.size, i.subName, b.stickers, ish.etiquetas, b.printed @@ -60139,7 +60139,7 @@ BEGIN GROUP BY itemFk ) b ON b.itemFk = i.id LEFT JOIN ( - SELECT itemFk, sum(cast(visible / packing AS DECIMAL(10,0))) AS etiquetas + SELECT itemFk, sum(cast(visible / packing AS DECIMAL(10,0))) AS etiquetas FROM itemShelving ish JOIN shelving sh ON sh.code = ish.shelvingFk LEFT JOIN parking pk ON pk.id = sh.parkingFk @@ -60179,7 +60179,7 @@ BEGIN UPDATE vn.itemShelving SET visible = visible - vQuantity WHERE id = vItemShelvingFk; - + END ;; DELIMITER ; @@ -60202,47 +60202,47 @@ BEGIN DECLARE vVisibleCache INT; DECLARE vWarehouseFk INT; - + SELECT warehouseFk INTO vWarehouseFk FROM vn.sector WHERE id = vSectorFk; CALL cache.visible_refresh (vVisibleCache, FALSE, vWarehouseFk); - - SELECT t.id as ticketFk, - CAST(s.quantity AS DECIMAL(10,0)) as Cantidad, - s.itemFk, - s.concept, - v.visible - GREATEST(0,iss.visible) + IFNULL(sub3.transit,0) as Nicho, + + SELECT t.id as ticketFk, + CAST(s.quantity AS DECIMAL(10,0)) as Cantidad, + s.itemFk, + s.concept, + v.visible - GREATEST(0,iss.visible) + IFNULL(sub3.transit,0) as Nicho, i.subName, - GREATEST(0,iss.visible - IFNULL(sub3.transit,0)) as Altillo, + GREATEST(0,iss.visible - IFNULL(sub3.transit,0)) as Altillo, s.id as saleFk, IFNULL(sub3.transit,0) transit, v.visible, s.isPicked, s.reserved, t.shipped, tst.productionOrder, mm.Id_Movimiento - FROM vn.ticket t + FROM vn.ticket t JOIN vn.ticketState tst ON tst.ticketFk = t.id JOIN vn.sale s ON s.ticketFk = t.id JOIN vn.item i ON i.id = s.itemFk JOIN cache.visible v ON s.itemFk = v.item_id AND v.calc_id = vVisibleCache LEFT JOIN vn2008.Movimientos_mark mm ON mm.Id_Movimiento = s.id AND mm.stateFk = 26 - JOIN vn.itemShelvingStock iss ON iss.itemFk = v.item_id + JOIN vn.itemShelvingStock iss ON iss.itemFk = v.item_id LEFT JOIN - (SELECT itemFk, sum(saldo) as transit - FROM vn.itemPlacementSupplyList - WHERE saldo > 0 + (SELECT itemFk, sum(saldo) as transit + FROM vn.itemPlacementSupplyList + WHERE saldo > 0 AND sectorFk = vSectorFk GROUP BY itemFk) sub3 ON sub3.itemFk = i.id - WHERE v.visible + IFNULL(sub3.transit,0) - GREATEST(0,iss.visible) < s.quantity + WHERE v.visible + IFNULL(sub3.transit,0) - GREATEST(0,iss.visible) < s.quantity AND IFNULL(sub3.transit,0) < s.quantity - AND s.isPicked = FALSE + AND s.isPicked = FALSE AND s.reserved = FALSE - AND t.shipped BETWEEN util.VN_CURDATE() AND MIDNIGHT(util.VN_CURDATE()) + AND t.shipped BETWEEN util.VN_CURDATE() AND MIDNIGHT(util.VN_CURDATE()) AND tst.isPreviousPreparable = TRUE AND t.warehouseFk = vWarehouseFk AND iss.sectorFk = vSectorFk AND mm.Id_Movimiento IS NULL ORDER BY itemFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60261,7 +60261,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingRadar`(vSectorFk INT) proc:BEGIN - + DECLARE vCalcVisibleFk INT; DECLARE vCalcAvailableFk INT; DECLARE hasFatherSector BOOLEAN; @@ -60269,17 +60269,17 @@ proc:BEGIN DECLARE vWarehouseFk INT DEFAULT 0; DECLARE vSonSectorFk INT; DECLARE vWorkerFk INT; - - SELECT s.workerFk - INTO vWorkerFk + + SELECT s.workerFk + INTO vWorkerFk FROM vn.sector s WHERE s.id = vSectorFk; SELECT w.id, s.warehouseFk INTO vBuyerFk, vWarehouseFk - FROM vn.worker w + FROM vn.worker w JOIN vn.sector s ON s.code = w.code WHERE s.id = vSectorFk; - + SELECT s.id INTO vSectorFk FROM vn.sector s WHERE s.warehouseFk = vWarehouseFk @@ -60289,21 +60289,21 @@ proc:BEGIN SELECT COUNT(*) INTO hasFatherSector FROM vn.sector WHERE sonFk = vSectorFk; - + SELECT warehouseFk, sonFk INTO vWarehouseFk, vSonSectorFk FROM vn.sector WHERE id = vSectorFk; - + CALL cache.visible_refresh(vCalcVisibleFk, TRUE, vWarehouseFk); CALL cache.available_refresh(vCalcAvailableFk, FALSE, vWarehouseFk, util.VN_CURDATE()); - + DROP TEMPORARY TABLE IF EXISTS tmp.itemShelvingRadar; - + IF hasFatherSector THEN CREATE TEMPORARY TABLE tmp.itemShelvingRadar (PRIMARY KEY (itemFk)) - ENGINE = MEMORY + ENGINE = MEMORY SELECT * FROM ( SELECT iss.itemFk, i.longName, @@ -60314,7 +60314,7 @@ proc:BEGIN SUM(IF(iss.sectorFk = vSectorFk, IFNULL(iss.visible,0), 0)) downstairs, IF(it.isPackaging, null, IFNULL(v.visible,0)) as visible, vSectorFk as sectorFk - + FROM vn.itemShelvingStock iss JOIN vn.sector s ON s.id = iss.sectorFk JOIN vn.item i on i.id = iss.itemFk @@ -60323,11 +60323,11 @@ proc:BEGIN LEFT JOIN cache.visible v ON v.item_id = iss.itemFk AND v.calc_id = vCalcVisibleFk WHERE vSectorFk IN (iss.sectorFk, s.sonFk) AND it.workerFk != 3366 - + GROUP BY iss.itemFk - + UNION ALL - + SELECT v.item_id, i.longName, i.size, @@ -60337,7 +60337,7 @@ proc:BEGIN 0 downstairs, IF(it.isPackaging, NULL, v.visible) visible, vSectorFk as sectorFk - FROM cache.visible v + FROM cache.visible v JOIN vn.item i on i.id = v.item_id JOIN vn.itemType it ON it.id = i.typeFk AND vBuyerFk IN (0,it.workerFk) LEFT JOIN vn.itemShelvingStock iss ON iss.itemFk = v.item_id AND iss.warehouseFk = vWarehouseFk @@ -60346,8 +60346,8 @@ proc:BEGIN AND iss.itemFk IS NULL AND it.isInventory ) sub GROUP BY itemFk; - - SELECT ishr.*, + + SELECT ishr.*, CAST(visible - upstairs - downstairs AS DECIMAL(10,0)) AS nicho, CAST(downstairs - IFNULL(notPickedYed,0) AS DECIMAL(10,0)) as pendiente FROM tmp.itemShelvingRadar ishr @@ -60362,13 +60362,13 @@ proc:BEGIN ) sub ON sub.itemFk = ishr.itemFk ORDER BY i.typeFk, i.longName ; - - + + ELSE - + CREATE TEMPORARY TABLE tmp.itemShelvingRadar (PRIMARY KEY (itemFk)) - ENGINE = MEMORY + ENGINE = MEMORY SELECT iss.itemFk, 0 `hour`, 0 `minute`, @@ -60380,7 +60380,7 @@ proc:BEGIN IFNULL(a.available,0) available, IFNULL(v.visible - iss.visible,0) dayEndVisible, IFNULL(v.visible - iss.visible,0) firstNegative, - IFNULL(v.visible - iss.visible,0) itemPlacementVisible, + IFNULL(v.visible - iss.visible,0) itemPlacementVisible, IFNULL(i.minimum * b.packing,0) itemPlacementSize, ips.onTheWay, iss.visible itemShelvingStock, @@ -60394,13 +60394,13 @@ proc:BEGIN LEFT JOIN cache.available a ON a.item_id = iss.itemFk AND a.calc_id = vCalcAvailableFk LEFT JOIN cache.visible v ON v.item_id = iss.itemFk AND v.calc_id = vCalcVisibleFk LEFT JOIN (SELECT itemFk, sum(saldo) as onTheWay - FROM vn.itemPlacementSupplyList - WHERE saldo > 0 + FROM vn.itemPlacementSupplyList + WHERE saldo > 0 GROUP BY itemFk ) ips ON ips.itemFk = i.id - WHERE IFNULL(iss.sectorFk,0) IN (0, vSectorFk) - OR iss.sectorFk = vSectorFk; - /* + WHERE IFNULL(iss.sectorFk,0) IN (0, vSectorFk) + OR iss.sectorFk = vSectorFk; + /* UPDATE tmp.itemShelvingRadar isr JOIN vn.itemShelvingStock iss ON iss.itemFk = isr.itemFk SET isr.dayEndVisible = isr.dayEndVisible + iss.visible, @@ -60411,10 +60411,10 @@ proc:BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.itemOutTime; CREATE TEMPORARY TABLE tmp.itemOutTime SELECT *,SUM(amount) quantity - FROM + FROM (SELECT item_id itemFk, - amount, - IF(HOUR(t.shipped), HOUR(t.shipped), HOUR(z.`hour`)) as hours, + amount, + IF(HOUR(t.shipped), HOUR(t.shipped), HOUR(z.`hour`)) as hours, IF(MINUTE(t.shipped), MINUTE(t.shipped), MINUTE(z.`hour`)) as minutes FROM vn2008.item_out io JOIN tmp.itemShelvingRadar isr ON isr.itemFk = io.item_id @@ -60422,23 +60422,23 @@ proc:BEGIN JOIN vn.ticketState ts on ts.ticketFk = io.ticketFk JOIN vn.state s ON s.id = ts.stateFk LEFT JOIN vn.zone z ON z.id = t.zoneFk - LEFT JOIN (SELECT DISTINCT saleFk - FROM vn.saleTracking st - WHERE st.created > util.VN_CURDATE() + LEFT JOIN (SELECT DISTINCT saleFk + FROM vn.saleTracking st + WHERE st.created > util.VN_CURDATE() AND st.isChecked ) stPrevious ON `stPrevious`.`saleFk` = io.saleFk WHERE t.warehouseFk = vWarehouseFk - AND s.isPicked = 0 - AND NOT io.Reservado + AND s.isPicked = 0 + AND NOT io.Reservado AND stPrevious.saleFk IS NULL - AND io.dat >= util.VN_CURDATE() + AND io.dat >= util.VN_CURDATE() AND io.dat < util.VN_CURDATE() + INTERVAL 1 DAY ) sub GROUP BY itemFk, hours, minutes; - + INSERT INTO tmp.itemShelvingRadar (itemFk) SELECT itemFk FROM tmp.itemOutTime - ON DUPLICATE KEY UPDATE dayEndVisible = dayEndVisible + quantity, + ON DUPLICATE KEY UPDATE dayEndVisible = dayEndVisible + quantity, firstNegative = if (firstNegative < 0, firstNegative, firstNegative + quantity), `hour` = ifnull(if (firstNegative > 0 , `hour`, hours),0), `minute` = ifnull(if (firstNegative > 0, `minute`, minutes),0); @@ -60454,7 +60454,7 @@ proc:BEGIN END IF; DROP TEMPORARY TABLE tmp.itemShelvingRadar; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60478,24 +60478,24 @@ BEGIN DECLARE vCalcVisibleFk INT; DECLARE vCalcAvailableFk INT; DECLARE vTodayDayEnd DATETIME DEFAULT util.dayEnd(util.VN_CURDATE()); - + CALL cache.visible_refresh(vCalcVisibleFk, FALSE, 1); CALL cache.available_refresh(vCalcAvailableFk, FALSE, vWarehouseFk, util.VN_CURDATE()); - + DROP TEMPORARY TABLE IF EXISTS tmp.item; CREATE TEMPORARY TABLE tmp.item ENGINE = MEMORY SELECT DISTINCT itemFk - FROM vn.buy + FROM vn.buy WHERE entryFk = vEntryFk; - + DROP TEMPORARY TABLE IF EXISTS tmp.item2; CREATE TEMPORARY TABLE tmp.item2 ENGINE = MEMORY SELECT * FROM tmp.item; - - SELECT i.id as itemFk, + + SELECT i.id as itemFk, i.minimum, CAST(IFNULL(v.visible,0) - IFNULL(iss.visible,0) AS DECIMAL(10,0)) as enNicho, CAST(IFNULL(a.available,0) AS DECIMAL(10,0)) as disponible, @@ -60515,11 +60515,11 @@ BEGIN AND IFNULL(tst.productionOrder,0) < 5 GROUP BY s.itemFK ) ts ON ts.itemFk = i.id; - - + + DROP TEMPORARY TABLE tmp.item; DROP TEMPORARY TABLE tmp.item2; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60543,34 +60543,34 @@ BEGIN DECLARE vCalcVisibleFk INT; DECLARE vCalcAvailableFk INT; DECLARE vTodayDayEnd DATETIME DEFAULT util.dayEnd(util.VN_CURDATE()); - + CALL cache.visible_refresh(vCalcVisibleFk, FALSE, 1); CALL cache.available_refresh(vCalcAvailableFk, FALSE, vWarehouseFk, util.VN_CURDATE()); - + DROP TEMPORARY TABLE IF EXISTS tmp.item; CREATE TEMPORARY TABLE tmp.item ENGINE = MEMORY SELECT DISTINCT itemFk - FROM vn.buy + FROM vn.buy WHERE entryFk = vEntryFk; - + DROP TEMPORARY TABLE IF EXISTS tmp.item2; CREATE TEMPORARY TABLE tmp.item2 ENGINE = MEMORY SELECT * FROM tmp.item; - - SELECT i.id as itemFk, + + SELECT i.id as itemFk, CAST(IFNULL(iss.visible,0) - IFNULL(v.visible,0) AS DECIMAL(10,0)) as outShelving FROM vn.item i JOIN tmp.item ti ON ti.itemFk = i.id LEFT JOIN cache.visible v ON v.calc_id = vCalcVisibleFk AND v.item_id = i.id LEFT JOIN vn.itemShelvingStock iss ON iss.itemFk = i.id; - - + + DROP TEMPORARY TABLE tmp.item; DROP TEMPORARY TABLE tmp.item2; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60591,10 +60591,10 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_Add`(vItemShelving BEGIN /** * Añade línea a itemShelvingSale y regulariza el carro - * + * * @param vItemShelvingFk Id itemShelving * @param vSaleFk Id de sale - * @param vQuantity cantidad a regularizar + * @param vQuantity cantidad a regularizar */ INSERT INTO itemShelvingSale(itemShelvingFk, saleFk, @@ -60689,7 +60689,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_add`(IN vShelvingFk VARCHAR(8), IN vBarcode VARCHAR(22), IN vQuantity INT, IN vPackagingFk VARCHAR(10), IN vGrouping INT, IN vPacking INT, IN vWarehouseFk INT) BEGIN - + /** * Añade registro o lo actualiza si ya existe. @@ -60701,7 +60701,7 @@ BEGIN * @param vGrouping el grouping del producto en itemShelving, NULL para coger el de la ultima compra * @param vPacking el packing del producto, NULL para coger el de la ultima compra * @param vWarehouseFk indica el sector - * + * **/ DECLARE vItemFk INT; @@ -60711,21 +60711,21 @@ BEGIN IF (SELECT COUNT(*) FROM shelving WHERE code = vShelvingFk COLLATE utf8_unicode_ci) = 0 THEN INSERT IGNORE INTO parking(code) VALUES(vShelvingFk); - INSERT INTO shelving(code, parkingFk) + INSERT INTO shelving(code, parkingFk) SELECT vShelvingFk, id - FROM parking + FROM parking WHERE `code` = vShelvingFk COLLATE utf8_unicode_ci; END IF; - IF (SELECT COUNT(*) FROM itemShelving - WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk - AND itemFk = vItemFk + IF (SELECT COUNT(*) FROM itemShelving + WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk + AND itemFk = vItemFk AND packing = vPacking) = 1 THEN UPDATE itemShelving SET visible = visible+vQuantity - WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk AND itemFk = vItemFk AND packing = vPacking; + WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk AND itemFk = vItemFk AND packing = vPacking; ELSE CALL cache.last_buy_refresh(FALSE); @@ -60870,7 +60870,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_BuyerGet`( ) BEGIN SELECT * FROM vn.buyer; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60897,10 +60897,10 @@ proc:BEGIN * @return Lista de articulos */ DECLARE vCalcVisibleFk INT; - + CALL cache.visible_refresh(vCalcVisibleFk, TRUE, vWarehouseFk); - SELECT * FROM + SELECT * FROM (SELECT sub.itemFk, sub.longName, CONCAT('Hoy saldrán ', CAST(sub2.pendiente AS DECIMAL(10,0)), ' unidades.') `size`, @@ -60917,28 +60917,28 @@ proc:BEGIN 0 upstairs, SUM(IFNULL(iss.visible,0)) downstairs, IF(it.isPackaging, null, IFNULL(v.visible, 0)) visible, - ik.name + ik.name FROM itemShelvingStock iss JOIN sector s ON s.id = iss.sectorFk JOIN item i on i.id = iss.itemFk - LEFT JOIN ink ik ON ik.id = i.inkFk + LEFT JOIN ink ik ON ik.id = i.inkFk JOIN itemType it ON it.id = i.typeFk LEFT JOIN cache.visible v ON v.item_id = iss.itemFk AND v.calc_id = vCalcVisibleFk WHERE s.warehouseFk = vWarehouseFk AND it.workerFk = vBuyerFk - GROUP BY itemFk + GROUP BY itemFk ) sub LEFT JOIN (SELECT s.itemFk, SUM(s.quantity) pendiente FROM sale s LEFT JOIN saleTracking st ON st.saleFk = s.id - JOIN ticket t ON t.id = s.ticketFk + JOIN ticket t ON t.id = s.ticketFk JOIN client c on c.id = t.clientFk JOIN clientType ct ON ct.id = c.clientTypeFk WHERE t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE()) AND st.saleFk IS NULL AND ct.code IN ('normal', 'trust') GROUP BY s.itemFk - ) sub2 ON sub2.itemFk = sub.itemFk - UNION ALL + ) sub2 ON sub2.itemFk = sub.itemFk + UNION ALL SELECT v.item_id , i.longName, CONCAT('Hoy saldrán ', CAST(sub5.pendiente AS DECIMAL(10,0)), ' unidades.') `size`, @@ -60956,7 +60956,7 @@ proc:BEGIN LEFT JOIN (SELECT s.itemFk, SUM(s.quantity) pendiente FROM sale s LEFT JOIN saleTracking st ON st.saleFk = s.id - JOIN ticket t ON t.id = s.ticketFk + JOIN ticket t ON t.id = s.ticketFk JOIN client c on c.id = t.clientFk JOIN clientType ct ON ct.id = c.clientTypeFk WHERE t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE()) @@ -60989,12 +60989,12 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_get`(IN vSelf VARCHAR(8)) BEGIN /** -* Lista artículos de itemshelving +* Lista artículos de itemshelving * * @param vSelf matrícula del carro **/ - SELECT ish.itemFk item, - IFNULL(i.longName, CONCAT(i.name, ' ', i.size)) description, + SELECT ish.itemFk item, + IFNULL(i.longName, CONCAT(i.name, ' ', i.size)) description, ish.visible, CEIL(ish.visible/ish.packing) stickers, ish.packing, @@ -61032,7 +61032,7 @@ BEGIN * * @param vShelvingFk matricula del carro */ - SELECT is2.id,is2.shelvingFk , p.code, is2.itemFk , is2.visible, p.pickingOrder + SELECT is2.id,is2.shelvingFk , p.code, is2.itemFk , is2.visible, p.pickingOrder FROM itemShelving is2 JOIN shelving sh ON sh.code = is2.shelvingFk JOIN parking p ON p.id = sh.parkingFk @@ -61098,35 +61098,35 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_getSaleDate`(vShelvingFk VARCHAR(3)) BEGIN - + /* Devuelve la minima fecha en que se necesita cada producto en esa matricula. - * + * * @param vShelvingFk Matrícula del carro o pallet */ - + DECLARE vWarehouseFk INT; SELECT warehouseFk INTO vWarehouseFk FROM shelving s - JOIN parking p ON s.parkingFk = p.id + JOIN parking p ON s.parkingFk = p.id JOIN sector st ON st.id = p.sectorFk WHERE s.code = vShelvingFk COLLATE utf8_unicode_ci; - + DROP TEMPORARY TABLE IF EXISTS tmp.itemShelvingDistinct; CREATE TEMPORARY TABLE tmp.itemShelvingDistinct (PRIMARY KEY (itemFk)) ENGINE = MEMORY SELECT itemFk, SUM(visible) visible - FROM vn.itemShelving + FROM vn.itemShelving WHERE shelvingFk = vShelvingFk COLLATE utf8_unicode_ci - GROUP BY itemFk; - + GROUP BY itemFk; + DROP TEMPORARY TABLE IF EXISTS tmp.item; CREATE TEMPORARY TABLE tmp.item (PRIMARY KEY (itemFk)) ENGINE = MEMORY SELECT * FROM tmp.itemShelvingDistinct; - + DROP TEMPORARY TABLE IF EXISTS tmp.stockByDay; CREATE TEMPORARY TABLE tmp.stockByDay (index (itemFk, dated)) @@ -61137,16 +61137,16 @@ BEGIN FROM ( SELECT * FROM ( SELECT t2.* FROM ( - SELECT item_id itemFk, amount, util.VN_CURDATE() dated - FROM cache.stock + SELECT item_id itemFk, amount, util.VN_CURDATE() dated + FROM cache.stock WHERE warehouse_id = vWarehouseFk UNION ALL SELECT ish.itemFk, - sum(visible), util.VN_CURDATE() - FROM vn.itemShelving ish - JOIN shelving sh ON sh.code = ish.shelvingFk - JOIN parking p ON sh.parkingFk = p.id + FROM vn.itemShelving ish + JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN parking p ON sh.parkingFk = p.id JOIN sector s ON s.id = p.sectorFk - WHERE s.isReserve + WHERE s.isReserve GROUP BY ish.itemFk UNION ALL SELECT item_id, sum(iei.amount), dat @@ -61155,9 +61155,9 @@ BEGIN AND warehouse_id = vWarehouseFk AND isVirtualStock = FALSE GROUP BY item_id, dat - UNION ALL + UNION ALL SELECT item_id, sum(ieo.amount), dat - FROM vn2008.item_entry_out ieo + FROM vn2008.item_entry_out ieo WHERE dat >= util.VN_CURDATE() AND warehouse_id = vWarehouseFk GROUP BY item_id, dat @@ -61168,11 +61168,11 @@ BEGIN WHERE io.dat >= util.VN_CURDATE() AND io.warehouse_id = vWarehouseFk GROUP BY io.item_id, io.dat - ) t2 + ) t2 JOIN tmp.itemShelvingDistinct ish ON ish.itemFk = t2.itemFk) t order by t.itemFk, DATE(t.dated), t.amount DESC) t3; - - SELECT sbd.itemFk, i.longName, DATE(dated) dated, ish.visible amount, sbd.stock + + SELECT sbd.itemFk, i.longName, DATE(dated) dated, ish.visible amount, sbd.stock FROM tmp.stockByDay sbd JOIN vn.item i ON i.id = sbd.itemFk JOIN tmp.itemShelvingDistinct ish ON ish.itemFk = sbd.itemFk @@ -61275,15 +61275,15 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_selfConsumption`( - vShelvingFk VARCHAR(10) COLLATE utf8_general_ci, - vItemFk INT, + vShelvingFk VARCHAR(10) COLLATE utf8_general_ci, + vItemFk INT, vQuantity INT ) -BEGIN +BEGIN /** - * Leave the indicated amount on the shelf + * Leave the indicated amount on the shelf * and create a ticket with the difference. - * + * * @param vShelvingFk id of the shelf where the item is located. * @param vItemFk article of which the self-consumption ticket is to be created. * @param vQuantity amount that will stay on the shelf @@ -61327,10 +61327,10 @@ BEGIN END IF; SELECT SUM(visible), id INTO vVisible, vItemShelvingFk - FROM itemShelving + FROM itemShelving WHERE shelvingFk = vShelvingFk AND itemFk = vItemFk; - + IF vVisible IS NULL THEN CALL util.throw('The item is not on the shelf.'); END IF; @@ -61383,9 +61383,9 @@ BEGIN * @param vGrouping el grouping del producto en itemShelving */ UPDATE itemShelving - SET visible = vVisible, - packing = vPacking, - grouping = vGrouping + SET visible = vVisible, + packing = vPacking, + grouping = vGrouping WHERE id = vShelf; END ;; @@ -61407,7 +61407,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemTagMake`(vItemFk INT) BEGIN -/* * Crea los tags usando la tabla plantilla itemTag +/* * Crea los tags usando la tabla plantilla itemTag * y si no existe a partir de la ficha del artículo. * @param vItemFk El item al que se le añaden los tags */ @@ -61417,33 +61417,33 @@ BEGIN DECLARE vProducer VARCHAR(50); DECLARE vOrigin VARCHAR(20); DECLARE vTypeFk INTEGER; - - DELETE FROM itemTag + + DELETE FROM itemTag WHERE itemFk = vItemFk; - - SELECT typeFk INTO vTypeFk + + SELECT typeFk INTO vTypeFk FROM item WHERE id = vItemFk; - + INSERT INTO itemTag(itemFk, tagFk, value, priority) SELECT vItemFk, itt.tagFk, NULL, itt.priority FROM itemTag it LEFT JOIN itemTypeTag itt ON itt.itemTypeFk = vTypeFk WHERE it.itemFk = vItemFk; - + IF (SELECT COUNT(*) FROM itemTag WHERE itemFk = vItemFk LIMIT 1) = 0 THEN - SELECT ik.name, i.size, i.category, p.name, o.name + SELECT ik.name, i.size, i.category, p.name, o.name INTO vInk, vSize, vCategory, vProducer, vOrigin FROM item i LEFT JOIN ink ik ON ik.id = i.inkFk LEFT JOIN producer p ON p.id = i.producerFk AND p.isVisible LEFT JOIN origin o ON o.id = i.originFk WHERE i.id = vItemFk; - + INSERT IGNORE INTO itemTag(itemFk, tagFk, value, priority) VALUES(vItemFk, 1, vInk, 1); - + INSERT IGNORE INTO itemTag(itemFk, tagFk, value, priority) VALUES (vItemFk, 8, vSize, 2); @@ -61452,11 +61452,11 @@ BEGIN INSERT IGNORE INTO itemTag(itemFk, tagFk, value, priority) VALUES(vItemFk, 37, vProducer, 4); - + INSERT IGNORE INTO itemTag(itemFk, tagFk, value, priority) VALUES(vItemFk, 35, vOrigin, 5); END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -61477,12 +61477,12 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `itemTagReorder`(itemTypeFk INT) BEGIN SET @isTriggerDisabled = TRUE; - + -- No se puede usar temporary porque da error Error Code: 1137. No puedo reabrir tabla: 'i DROP TABLE IF EXISTS tmp.item; CREATE TABLE tmp.item SELECT DISTINCT i.id - FROM vn.item i + FROM vn.item i WHERE i.typeFk = itemTypeFk; UPDATE itemTag it @@ -61491,8 +61491,8 @@ BEGIN JOIN itemTypeTag itt ON itt.itemTypeFk = item.typeFk AND itt.tagFk = it.tagFk SET it.priority = itt.priority WHERE itt.itemTypeFk = itemTypeFk; - - CALL item_refreshTags(); + + CALL item_refreshTags(); SET @isTriggerDisabled = FALSE; @@ -61517,12 +61517,12 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `itemTagReorderByName`(vName VARCHAR BEGIN SET @isTriggerDisabled = TRUE; - + -- No se puede usar temporary porque da error Error Code: 1137. No puedo reabrir tabla: 'i DROP TABLE IF EXISTS tmp.item; CREATE TABLE tmp.item SELECT DISTINCT i.id - FROM vn.item i + FROM vn.item i WHERE i.`name` LIKE CONCAT(vName,'%'); UPDATE itemTag it @@ -61531,8 +61531,8 @@ BEGIN JOIN itemTypeTag itt ON itt.itemTypeFk = item.typeFk AND itt.tagFk = it.tagFk SET it.priority = itt.priority WHERE itt.itemTypeFk = itemTypeFk; - - CALL item_refreshTags(); + + CALL item_refreshTags(); SET @isTriggerDisabled = FALSE; @@ -61555,36 +61555,36 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemTag_replace`(vItemFromFk INT, vItemToFk INT, vPicture VARCHAR(100)) BEGIN - + /* Reemplaza los tags de un artículo por los de otro, así como su imagen - * + * * @param vItemFromFk id de vn.item con el artículo del que se toman los tags * @param vItemToFk id de vn.item con el artículo del que se toman los tags * @param vPicture imagen del artículo. Opcional. Si no se especifica, hereada la del vItemFromFk */ - DELETE FROM vn.itemTag + DELETE FROM vn.itemTag WHERE itemFk = vItemToFk; - + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) SELECT vItemToFk, tagFk, value, priority - FROM vn.itemTag + FROM vn.itemTag WHERE itemFk = vItemFromFk; - + IF ISNULL(vPicture) THEN - - SELECT image INTO vPicture - FROM vn.item + + SELECT image INTO vPicture + FROM vn.item WHERE id = vItemFromFk; - + END IF; - UPDATE vn.item i + UPDATE vn.item i SET i.image = vPicture WHERE i.id = vItemToFk; - + CALL vn.itemRefreshTags(vItemToFk); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -61609,9 +61609,9 @@ BEGIN SELECT DISTINCT id FROM vn.itemCategory WHERE merchandise <> FALSE; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN + DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN RESIGNAL; END; @@ -61622,45 +61622,45 @@ BEGIN INNER JOIN bs.ventas v ON v.Id_Movimiento = s.id WHERE v.fecha BETWEEN TIMESTAMPADD(DAY, - 7, util.VN_CURDATE()) AND util.VN_CURDATE() GROUP BY s.itemFk; - + DROP TABLE IF EXISTS tmp.topSeller; - CREATE TEMPORARY TABLE tmp.topSeller - ( + CREATE TEMPORARY TABLE tmp.topSeller + ( `id` int(11) NOT NULL DEFAULT '0', `typeFk` smallint(5) unsigned NOT NULL, `itemCategoryFk` int(10) unsigned NOT NULL, `total` bigint(21) NOT NULL DEFAULT '0' ) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; - + OPEN rs; read_loop: LOOP FETCH rs INTO vCategoryFk; - + IF vDone THEN LEAVE read_loop; END IF; - + INSERT INTO tmp.topSeller SELECT tsm.itemFk, tsm.typeFk, it.categoryFk, tsm.total FROM tmp.topSellerMin tsm INNER JOIN vn.itemType it ON it.id = tsm.typeFk WHERE it.categoryFk = vCategoryFk ORDER BY tsm.itemFk ,tsm.total DESC - LIMIT 5; + LIMIT 5; END LOOP; CLOSE rs; - + SELECT i.name ,i.id, i.image, i.typeFk, it.categoryFk AS itemCategoryFk, ic.name AS itemCategoryName, it.name AS itemTypeName, ts.total FROM tmp.topSeller ts INNER JOIN vn.item i ON i.id = ts.id INNER JOIN vn.itemType it ON it.id = ts.typeFk INNER JOIN vn.itemCategory ic ON ic.id = it.categoryFk; - + DROP TABLE IF EXISTS topSellerMin; DROP TABLE IF EXISTS tmp.topSeller; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -61770,7 +61770,7 @@ SET tag6 = t.name, value6 = it.value WHERE it.priority = 2 AND (vItem IS NULL OR vItem = it.itemFk); -UPDATE item i +UPDATE item i JOIN itemTag it ON it.itemFk = i.id JOIN tag t ON t.id = it.tagFk SET tag7 = t.name, value7 = it.value @@ -61803,7 +61803,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `item_cleanFloramondo`() BEGIN /** -* Elimina todos los items repetidos de floramondo +* Elimina todos los items repetidos de floramondo * y los sustituye por el que tiene menor id */ DECLARE vItemFrom INT; @@ -61869,7 +61869,7 @@ BEGIN AND i2.EmbalageCode <=> i.EmbalageCode AND i2.quality <=> i.quality JOIN ( - SELECT DISTINCT b.itemFk + SELECT DISTINCT b.itemFk FROM buy b JOIN item i ON i.id = b.itemFk WHERE i.isFloramondo @@ -61877,7 +61877,7 @@ BEGIN )sub2 ON sub2.itemFk = GREATEST(i.id, i2.id) WHERE i.isFloramondo AND i.id <> i2.id; - + DECLARE EXIT HANDLER FOR SQLEXCEPTION SET vDone = TRUE; BEGIN SET vDone = TRUE; @@ -62131,13 +62131,13 @@ BEGIN /** * @vItemFk item a buscar * @vWarehouseFk almacen donde buscar - * @vDate Si la fecha es null, muestra el histórico desde el inventario. + * @vDate Si la fecha es null, muestra el histórico desde el inventario. * Si la fecha no es null, muestra histórico desde la fecha pasada. */ DECLARE vDateInventory DATETIME; IF vDate IS NULL THEN - SELECT inventoried INTO vDateInventory + SELECT inventoried INTO vDateInventory FROM config; ELSE SELECT mockUtcTime INTO vDateInventory @@ -62163,7 +62163,7 @@ BEGIN inventorySupplierFk INT(10) ); - INSERT INTO tItemDiary + INSERT INTO tItemDiary SELECT tr.landed shipped, b.quantity `in`, NULL `out`, @@ -62184,14 +62184,14 @@ BEGIN JOIN entry e ON e.id = b.entryFk JOIN travel tr ON tr.id = e.travelFk JOIN supplier s ON s.id = e.supplierFk - JOIN state st ON st.`code` = IF( tr.landed < util.VN_CURDATE() + JOIN state st ON st.`code` = IF( tr.landed < util.VN_CURDATE() OR (util.VN_CURDATE() AND tr.isReceived), - 'DELIVERED', + 'DELIVERED', 'FREE') JOIN entryConfig ec WHERE tr.landed >= vDateInventory AND vWarehouseFk = tr.warehouseInFk - AND (s.id <> ec.inventorySupplierFk OR vDate IS NULL) + AND (s.id <> ec.inventorySupplierFk OR vDate IS NULL) AND b.itemFk = vItemFk AND e.isExcludedFromAvailable = FALSE AND e.isRaid = FALSE @@ -62217,14 +62217,14 @@ BEGIN JOIN travel tr ON tr.id = e.travelFk JOIN warehouse w ON w.id = tr.warehouseOutFk JOIN supplier s ON s.id = e.supplierFk - JOIN state st ON st.`code` = IF(tr.shipped < util.VN_CURDATE() + JOIN state st ON st.`code` = IF(tr.shipped < util.VN_CURDATE() OR (tr.shipped = util.VN_CURDATE() AND tr.isReceived), - 'DELIVERED', + 'DELIVERED', 'FREE') JOIN entryConfig ec WHERE tr.shipped >= vDateInventory AND vWarehouseFk = tr.warehouseOutFk - AND (s.id <> ec.inventorySupplierFk OR vDate IS NULL) + AND (s.id <> ec.inventorySupplierFk OR vDate IS NULL) AND b.itemFk = vItemFk AND e.isExcludedFromAvailable = FALSE AND w.isFeedStock = FALSE @@ -62253,12 +62253,12 @@ BEGIN JOIN client c ON c.id = t.clientFk JOIN clientType ct ON ct.id = c.clientTypeFk JOIN state st2 ON st2.`code` = IF(t.shipped < util.VN_CURDATE(), - 'DELIVERED', + 'DELIVERED', IF (t.shipped > util.dayEnd(util.VN_CURDATE()), 'FREE', IFNULL(ts.code, 'FREE'))) LEFT JOIN state stPrep ON stPrep.`code` = 'PREPARED' - LEFT JOIN saleTracking stk ON stk.saleFk = s.id + LEFT JOIN saleTracking stk ON stk.saleFk = s.id AND stk.stateFk = stPrep.id LEFT JOIN claimBeginning cb ON s.id = cb.saleFk WHERE t.shipped >= vDateInventory @@ -62274,7 +62274,7 @@ BEGIN `out` DESC; IF vDate IS NULL THEN - + SET @a := 0; SET @currentLineFk := 0; SET @shipped := ''; @@ -62289,9 +62289,9 @@ BEGIN `in` invalue, `out`, @a := @a + IFNULL(`in`, 0) - IFNULL(`out`, 0) balance, - @currentLineFk := IF (@shipped < util.VN_CURDATE() + @currentLineFk := IF (@shipped < util.VN_CURDATE() OR (@shipped = util.VN_CURDATE() AND (isPicked OR a.`code` >= 'ON_PREPARATION')), - lineFk, + lineFk, @currentLineFk) lastPreparedLineFk, isTicket, lineFk, @@ -62323,25 +62323,25 @@ BEGIN 0 clientType, 0 claimFk UNION ALL - SELECT shipped, - alertlevel, - stateName, - origin, - reference, - clientFk, - name, `in`, - `out`, - @a := @a + IFNULL(`in`, 0) - IFNULL(`out`, 0), - 0, - isTicket, - lineFk, - isPicked, - clientType, + SELECT shipped, + alertlevel, + stateName, + origin, + reference, + clientFk, + name, `in`, + `out`, + @a := @a + IFNULL(`in`, 0) - IFNULL(`out`, 0), + 0, + isTicket, + lineFk, + isPicked, + clientType, claimFk FROM tItemDiary WHERE shipped >= vDate; END IF; - + DROP TEMPORARY TABLE tItemDiary; END ;; DELIMITER ; @@ -62448,7 +62448,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getLack`(IN vForce BOOLEAN, IN BEGIN /** * Calcula una tabla con el máximo negativo visible para cada producto y almacen - * + * * @param vForce Fuerza el recalculo del stock * @param vDays Numero de dias a considerar **/ @@ -62457,31 +62457,31 @@ BEGIN CALL item_getMinacum(NULL, util.VN_CURDATE(), vDays, NULL); CALL item_getMinETD(); - SELECT i.id itemFk, + SELECT i.id itemFk, i.longName, w.id warehouseFk, - p.`name` producer, + p.`name` producer, i.`size`, i.category, - w.name warehouse, + w.name warehouse, SUM(IFNULL(sub.amount,0)) lack, i.inkFk, - IFNULL(im.timed, util.midnight()) timed - FROM (SELECT item_id, - warehouse_id, + IFNULL(im.timed, util.midnight()) timed + FROM (SELECT item_id, + warehouse_id, amount FROM cache.stock WHERE amount > 0 UNION ALL - SELECT itemFk, - warehouseFk, + SELECT itemFk, + warehouseFk, amount FROM tmp.itemMinacum ) sub JOIN warehouse w ON w.id = sub.warehouse_id JOIN item i ON i.id = sub.item_id - LEFT JOIN producer p ON p.id = i.producerFk - JOIN itemType it ON it.id = i.typeFk + LEFT JOIN producer p ON p.id = i.producerFk + JOIN itemType it ON it.id = i.typeFk JOIN itemCategory ic ON ic.id = it.categoryFk LEFT JOIN tmp.itemMinETD im ON im.itemFk = i.id WHERE w.isForTicket @@ -62602,12 +62602,12 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getMinETD`() BEGIN - + /* Devuelve una tabla temporal con la primera ETD, para todos los artículos con salida hoy. - * + * * @return tmp.itemMinETD(itemFk, timed) */ - + DECLARE vMidnight DATETIME DEFAULT util.midnight(); DROP TEMPORARY TABLE IF EXISTS tmp.itemMinETD; @@ -62618,7 +62618,7 @@ BEGIN SELECT s.itemFk, MIN(TIME(IFNULL(z.`hour`,vMidnight))) timed FROM ticket t JOIN sale s ON s.ticketFk = t.id - LEFT JOIN `zone` z ON z.id = t.zoneFk + LEFT JOIN `zone` z ON z.id = t.zoneFk WHERE t.shipped BETWEEN util.VN_CURDATE() AND vMidnight GROUP BY s.itemFk; END ;; @@ -62648,33 +62648,33 @@ BEGIN * @param vWarehouseFk warehouse id * @param vDate fecha para revisar disponible * @param vIsShowedByType para mostrar solo artículos de ese tipo - */ + */ DECLARE vCalcFk INT; DECLARE vTypeFk INT; - + DECLARE vTag1 VARCHAR(25) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; DECLARE vTag5 VARCHAR(25) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; DECLARE vTag6 VARCHAR(25) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; DECLARE vTag7 VARCHAR(25) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; DECLARE vTag8 VARCHAR(25) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; - + DECLARE vValue1 VARCHAR(50) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; DECLARE vValue5 VARCHAR(50) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; DECLARE vValue6 VARCHAR(50) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; DECLARE vValue7 VARCHAR(50) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; DECLARE vValue8 VARCHAR(50) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; - + SELECT typeFk, tag5, value5, tag6, value6, tag7, value7, tag8, value8, t1.name, it1.value INTO vTypeFk, vTag5, vValue5, vTag6, vValue6, vTag7, vValue7, vTag8, vValue8, vTag1, vValue1 FROM vn.item i LEFT JOIN vn.itemTag it1 ON it1.itemFk = i.id AND it1.priority = 1 LEFT JOIN vn.tag t1 ON t1.id = it1.tagFk WHERE i.id = vItemFk; - + CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, vDate); - + SELECT i.id itemFk, i.longName, i.subName, @@ -62707,7 +62707,7 @@ BEGIN ORDER BY counter DESC, (t1.name = vTag1) DESC, (it1.value = vValue1) DESC, - (i.tag6 = vTag6) DESC, + (i.tag6 = vTag6) DESC, (i.value6 = vValue6) DESC, (i.tag5 = vTag5) DESC, (i.value5 = vValue5) DESC, @@ -62716,7 +62716,7 @@ BEGIN (i.tag8 = vTag8) DESC, (i.value8 = vValue8) DESC LIMIT 30; - + END ;; DELIMITER ; @@ -63001,11 +63001,11 @@ BEGIN * @param vBarcode del item * @param vReference referencia a actualizar */ - + DECLARE vItemFk INT; SELECT barcodeToItem(vBarcode) INTO vItemFk; - + UPDATE item SET comment = vReference WHERE id = vItemFk; END ;; @@ -63028,7 +63028,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `item_setGeneric`(vSelf INT) BEGIN /** * Asigna el código genérico a un item, salvo que sea un código de item genérico. - * + * * @param vSelf identificador de vn.item */ DECLARE vGenericFk INT; @@ -63038,7 +63038,7 @@ BEGIN SELECT itemFk, SUM(matches) = maxMatches `match` FROM ( SELECT ga.id gaid, ga.itemFk, - CASE + CASE WHEN t.code = 'nflowers' THEN it.value <=> ga.numFlores WHEN t.code = 'origin' THEN @@ -63069,13 +63069,13 @@ BEGIN AND (i.`size` = ga.`size` OR ga.`size` IS NULL) AND i.id != ga.itemFk WHERE i.id = vSelf - AND NOT i.isFloramondo) sub + AND NOT i.isFloramondo) sub GROUP BY gaid HAVING `match`) sub2 LIMIT 1; - UPDATE vn.item - SET genericFk = vGenericFk + UPDATE vn.item + SET genericFk = vGenericFk WHERE id = vSelf; END ;; DELIMITER ; @@ -63095,18 +63095,18 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `item_updatePackingShelve`(vSelf INT, vPacking INT) BEGIN - + /** * Actualiza el valor de item.packingShelve - * + * * @param vSelf Identificador de vn.item * @param vPacking Cantidad de unidades de venta que caben en una bandeja */ - - UPDATE vn.item i + + UPDATE vn.item i SET i.packingShelve = vPacking WHERE i.id = vSelf; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -63156,9 +63156,9 @@ BEGIN DECLARE vHasNotInventory BOOLEAN DEFAULT FALSE; DECLARE vInventoried2 DATE; DECLARE vDateDayEnd DATETIME; - + SET vDateDayEnd = util.dayEnd(vDated); - + SELECT landed INTO vInventoried FROM travel tr JOIN entry E ON E.travelFk = tr.id @@ -63168,7 +63168,7 @@ BEGIN LIMIT 1; SET vHasNotInventory = IF (vInventoried is null, TRUE, FALSE); - + IF vHasNotInventory THEN SELECT landed INTO vInventoried2 @@ -63189,13 +63189,13 @@ BEGIN CREATE TEMPORARY TABLE inv (warehouseFk SMALLINT, Id_Article BIGINT, - cantidad INT, + cantidad INT, coste DOUBLE DEFAULT 0, total DOUBLE DEFAULT 0, Almacen VARCHAR(20), PRIMARY KEY (Almacen, Id_Article) USING HASH) ENGINE = MEMORY; - + IF vHasNotInventory = TRUE THEN INSERT INTO inv(warehouseFk, Id_Article, cantidad, Almacen) @@ -63272,7 +63272,7 @@ BEGIN AND it.isInventory ON DUPLICATE KEY UPDATE inv.cantidad = inv.cantidad + s.quantity * IF(vHasNotInventory,0,1); - END IF; + END IF; -- Mercancia en transito INSERT INTO inv(warehouseFk, Id_Article, cantidad, Almacen) @@ -63290,7 +63290,7 @@ BEGIN AND t.isInventory AND e.isConfirmed ON DUPLICATE KEY UPDATE inv.cantidad = inv.cantidad + (b.quantity); - + CALL vn.buyUltimate(NULL,vDateDayEnd); UPDATE inv i @@ -63305,20 +63305,20 @@ BEGIN IF vIsDetailed THEN SELECT inv.warehouseFk, - i.id itemFk, - i.longName , - i.size, - inv.Cantidad, + i.id itemFk, + i.longName , + i.size, + inv.Cantidad, tp.name Tipo, - ic.name Reino, - inv.coste, + ic.name Reino, + inv.coste, cast(inv.total as decimal(10,2)) total, almacen FROM inv JOIN warehouse w on w.id = warehouseFk JOIN item i ON i.id = inv.Id_Article JOIN itemType tp ON tp.id = i.typeFk - JOIN itemCategory ic ON ic.id = tp.categoryFk + JOIN itemCategory ic ON ic.id = tp.categoryFk WHERE w.valuatedInventory and inv.total > 0 order by inv.total desc; @@ -63365,37 +63365,37 @@ BEGIN * @param vConcept descripcion * @param vAmount cantidad que se compensa * @param vCompany empresa - * @param vOriginalAccount cuenta contable desde la cual se compensa - * - */ + * @param vOriginalAccount cuenta contable desde la cual se compensa + * + */ DECLARE vNewBookEntry INT; DECLARE vIsClientCompensation INT; DECLARE vClientFk INT; DECLARE vSupplierFk INT; DECLARE vIsOriginalAClient BOOL; DECLARE vPayMethodCompensation INT; - + CALL ledger_next(vNewBookEntry); SELECT COUNT(id) INTO vIsOriginalAClient FROM client WHERE accountingAccount LIKE vOriginalAccount COLLATE utf8_general_ci; - SELECT id, COUNT(id) INTO vClientFk, vIsClientCompensation - FROM client + SELECT id, COUNT(id) INTO vClientFk, vIsClientCompensation + FROM client WHERE accountingAccount LIKE vCompensationAccount COLLATE utf8_general_ci; - + SET @vAmount1:= 0.0; SET @vAmount2:= 0.0; - INSERT INTO XDiario (ASIEN, FECHA, SUBCTA, CONTRA, CONCEPTO, EURODEBE, EUROHABER, empresa_id) - VALUES ( vNewBookEntry, - vDated, - vOriginalAccount, - vCompensationAccount, - vConcept, + INSERT INTO XDiario (ASIEN, FECHA, SUBCTA, CONTRA, CONCEPTO, EURODEBE, EUROHABER, empresa_id) + VALUES ( vNewBookEntry, + vDated, + vOriginalAccount, + vCompensationAccount, + vConcept, @vAmount1:= IF( - (vIsOriginalAClient AND vAmount > 0) OR - (NOT vIsOriginalAClient AND vAmount < 0), - 0, + (vIsOriginalAClient AND vAmount > 0) OR + (NOT vIsOriginalAClient AND vAmount < 0), + 0, ABS(vAmount) ), @vAmount2:= IF(@vAmount1, @@ -63404,20 +63404,20 @@ BEGIN ), vCompanyFk ), - ( vNewBookEntry, - vDated, - vCompensationAccount, - vOriginalAccount, - vConcept, + ( vNewBookEntry, + vDated, + vCompensationAccount, + vOriginalAccount, + vConcept, @vAmount2, @vAmount1, vCompanyFk); - + IF vIsClientCompensation THEN IF vIsOriginalAClient THEN SET vAmount = -vAmount; END IF; - INSERT INTO receipt(invoiceFk, amountPaid, payed, bankFk, companyFk, clientFk, isConciliate) + INSERT INTO receipt(invoiceFk, amountPaid, payed, bankFk, companyFk, clientFk, isConciliate) VALUES (vConcept, vAmount, vDated, vBankFk, vCompanyFk, vClientFk, TRUE); ELSE IF NOT vIsOriginalAClient THEN @@ -63425,7 +63425,7 @@ BEGIN END IF; SELECT id INTO vSupplierFk FROM supplier WHERE `account` LIKE vCompensationAccount COLLATE utf8_general_ci; SELECT id INTO vPayMethodCompensation FROM payMethod WHERE `code` = 'compensation'; - + INSERT INTO payment (received, dueDated, supplierFk, amount, bankFk, payMethodFk, concept, companyFk, isConciliated) VALUES(vDated, vDated, vSupplierFk, vAmount, vBankFk, vPayMethodCompensation, vConcept, vCompanyFk, TRUE); END IF; @@ -63447,10 +63447,10 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ledger_next`(OUT vNewBookEntry INT) BEGIN - + UPDATE vn.ledgerConfig SET lastBookEntry = LAST_INSERT_ID(lastBookEntry + 1); SET vNewBookEntry = LAST_INSERT_ID(); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -63476,15 +63476,15 @@ BEGIN * @param vEntity Nombre que hace referencia a la tabla. */ DECLARE vTableName VARCHAR(45); - + SET vTableName = CONCAT(vEntity, 'Log'); - + SET @qryLog := CONCAT( 'SELECT ot.id, ot.originFk, ot.userFk, u.name, ot.action, ot.creationDate, ot.description FROM ', vTableName, ' AS ot', ' INNER JOIN account.user u ON u.id = ot.userFk', ' WHERE ot.originFk = ', vOriginFk, ' ORDER BY ot.creationDate DESC' ); - + PREPARE stmt FROM @qryLog; EXECUTE stmt; END ;; @@ -63509,9 +63509,9 @@ BEGIN SET @buildingOrder := 0; SET @route := 0; set @cajas := 0; - + UPDATE tmp.sorter - SET buildingOrder = @buildingOrder := IF(@route = @route := routeFk, @buildingOrder, 0) + 1 + SET buildingOrder = @buildingOrder := IF(@route = @route := routeFk, @buildingOrder, 0) + 1 where date(created) = vDate order by routeFk, created, weight DESC; @@ -63529,23 +63529,23 @@ set @cajas := 0; UPDATE tmp.sorter SET lungGrow = IF(palletOrder = 0, -13, lungGrow); - + DELETE FROM tmp.lungSize WHERE dia = vDate; - + INSERT INTO tmp.lungSize(dia, hora,size) select vDate,hora, @cajas := @cajas + cajas as size from ( select IF(lungGrow BETWEEN -12 AND -1, ETD,time_format(created,"%H:%i")) as hora, sum(if(lungGrow <= 0, lungGrow, 1)) as cajas, @cajas := 0 - from tmp.sorter + from tmp.sorter where date(created) = vDate group by hora ) sub; - + SELECT * FROM tmp.lungSize WHERE dia = vDate; - - + + END ;; @@ -63566,23 +63566,23 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `machineWorker_add`(vPlate VARCHAR(10), vWorkerFk INT) BEGIN - + /** * Inserta registro si el vWorkerFk no ha registrado nada en las últimas 12 horas * @param vPlate número de matrícula - * @param vWorkerFk id del worker - * -*/ - UPDATE vn.machineWorker mw - JOIN vn.machine m ON m.id = mw.machineFk + * @param vWorkerFk id del worker + * +*/ + UPDATE vn.machineWorker mw + JOIN vn.machine m ON m.id = mw.machineFk SET mw.outTimed = util.VN_NOW() WHERE (mw.workerFk = vWorkerFk OR m.plate = vPlate) AND ISNULL(mw.outTimed); - + INSERT INTO machineWorker (machineFk, workerFk) SELECT m.id, vWorkerFk FROM machine m - WHERE m.plate= vPlate; + WHERE m.plate= vPlate; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -63602,21 +63602,21 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `machineWorker_getHistorical`(vPlate VARCHAR(20), vWorkerFk INT) BEGIN /** - * Obtiene historial de la matrícula vPlate que el trabajador vWorkerFk escanea, + * Obtiene historial de la matrícula vPlate que el trabajador vWorkerFk escanea, * si es jefe de producción muestra el historial completo. - * + * * @param vPlate número de matrícula - * @param vWorkerFk id del trabajador - * + * @param vWorkerFk id del trabajador + * */ DECLARE vWorkerName VARCHAR(255) DEFAULT account.user_getNameFromId(vWorkerFk); - SELECT mw.inTimed,account.user_getNameFromId(mw.workerFk) as workerName, mw.outTimed + SELECT mw.inTimed,account.user_getNameFromId(mw.workerFk) as workerName, mw.outTimed FROM machineWorker mw JOIN machine m ON m.plate = vPlate WHERE mw.machineFk = m.id AND mw.workerFk = IF(account.user_hasRole(vWorkerName, 'coolerAssist'), mw.workerFk, vWorkerFk) - ORDER BY mw.inTimed DESC; + ORDER BY mw.inTimed DESC; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -63635,13 +63635,13 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `machineWorker_update`(vPlate VARCHAR(10), vWorkerFk INT) BEGIN - + /** - * Actualiza el registro correspondiente si el vWorkerFk se ha registrado en las últimas horas (campo maxHours de machineWorkerConfig) con vPlate, - * + * Actualiza el registro correspondiente si el vWorkerFk se ha registrado en las últimas horas (campo maxHours de machineWorkerConfig) con vPlate, + * * @param vPlate número de matrícula - * @param vWorkerFk id del trabajador - * + * @param vWorkerFk id del trabajador + * */ DECLARE vMachineFk INT(10); @@ -63650,24 +63650,24 @@ BEGIN SELECT m.id INTO vMachineFk FROM machine m WHERE m.plate = vPlate; - + SELECT maxHours INTO vMaxHours FROM machineWorkerConfig; - IF (SELECT COUNT(*) + IF (SELECT COUNT(*) FROM machineWorker m WHERE m.workerFk = vWorkerFk - AND m.inTimed >= TIMESTAMPADD(HOUR , -vMaxHours, util.VN_NOW()) AND ISNULL(m.outTimed)) THEN - + AND m.inTimed >= TIMESTAMPADD(HOUR , -vMaxHours, util.VN_NOW()) AND ISNULL(m.outTimed)) THEN + UPDATE machineWorker m SET m.outTimed = CURRENT_TIMESTAMP() - WHERE m.workerFk = vWorkerFk - AND m.inTimed >= TIMESTAMPADD(HOUR , -vMaxHours, util.VN_NOW()) + WHERE m.workerFk = vWorkerFk + AND m.inTimed >= TIMESTAMPADD(HOUR , -vMaxHours, util.VN_NOW()) AND ISNULL(m.outTimed) AND m.machineFk = vMachineFk; - + END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -63722,12 +63722,12 @@ BEGIN /** * Inserta en la tabla vn.mail * - * @param vReceiver Receptor del correo + * @param vReceiver Receptor del correo * @param vReplyTo A quién contestar el correo * @param vSubject Título del correo * @param vBody Cuerpo del correo */ - + DECLARE vIsRepeated BOOLEAN; SELECT COUNT(*) INTO vIsRepeated @@ -63768,12 +63768,12 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `makeNewItem`() BEGIN DECLARE newItemFk INT; - + SELECT getNewItemId() INTO newItemFk; - + INSERT INTO item(id,name,typeFk,originFk) SELECT newItemFk, 'Nuevo artículo', 78,39; - + SELECT newItemFk; @@ -63801,34 +63801,34 @@ BEGIN DECLARE vMinute INT DEFAULT 0; DECLARE vBoxes INT; - + DROP TEMPORARY TABLE IF EXISTS vn.pcsDay; CREATE TEMPORARY TABLE vn.pcsDay SELECT 0 as hh, 0 as mm, 0 as boxes; - + -- Creamos una tabla soporte para acumular las cajas a lo largo del dia WHILE vHour < 24 DO - + WHILE vMinute < 59 DO - + SET vMinute = vMinute + 1; - + INSERT INTO vn.pcsDay(hh,mm) VALUES(vHour, vMinute); - + END WHILE; - + SET vMinute = -1; SET vHour = vHour + 1; - + END WHILE; - + -- Acumulamos UPDATE vn.pcsDay pd LEFT JOIN (SELECT * FROM vn.pcs_graf WHERE dia = vDated) pg USING(hh,mm) SET pd.boxes = pd.boxes + pg.box; - + SELECT * FROM vn.pcsDay; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -63851,7 +63851,7 @@ BEGIN * Recalcula el mana consumido por un trabajador * * @param vWorkerFk Id Trabajador - */ + */ DECLARE vWorkerIsExcluded BOOLEAN; DECLARE vFromDated DATE; DECLARE vToDated DATE DEFAULT TIMESTAMPADD(DAY,1,util.VN_CURDATE()); @@ -63860,32 +63860,32 @@ BEGIN DECLARE vClaimMana INT; DECLARE vManaBank INT; DECLARE vManaGreugeType INT; - + SELECT COUNT(*) INTO vWorkerIsExcluded FROM workerManaExcluded WHERE workerFk = vWorkerFk; - + IF NOT vWorkerIsExcluded THEN - SELECT id INTO vMana + SELECT id INTO vMana FROM `component` WHERE code = 'mana'; - - SELECT id INTO vAutoMana + + SELECT id INTO vAutoMana FROM `component` WHERE code = 'autoMana'; - - SELECT id INTO vClaimMana + + SELECT id INTO vClaimMana FROM `component` WHERE code = 'manaClaim'; - - SELECT id INTO vManaBank + + SELECT id INTO vManaBank FROM `bank` WHERE code = 'mana'; - - SELECT id INTO vManaGreugeType + + SELECT id INTO vManaGreugeType FROM `greugeType` WHERE code = 'mana'; - SELECT max(dated) INTO vFromDated + SELECT max(dated) INTO vFromDated FROM clientManaCache; - + REPLACE workerMana (workerFk, amount) - SELECT vWorkerFk, sum(mana) FROM + SELECT vWorkerFk, sum(mana) FROM ( SELECT s.quantity * sc.value as mana FROM ticket t @@ -63906,8 +63906,8 @@ BEGIN FROM greuge g JOIN client c ON c.id = g.clientFk WHERE c.salesPersonFk = vWorkerFk AND g.greugeTypeFk = vManaGreugeType - AND g.shipped > vFromDated and g.shipped < util.VN_CURDATE() - UNION ALL + AND g.shipped > vFromDated and g.shipped < util.VN_CURDATE() + UNION ALL SELECT cc.mana FROM clientManaCache cc JOIN client c ON c.id = cc.clientFk @@ -63934,20 +63934,20 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `mysqlConnectionsSorter_kill`() BEGIN /** - * Elimina conexiones del usuario sorter con tiempo >= 30seg. Asociado al evento con el mismo nombre - */ - + * Elimina conexiones del usuario sorter con tiempo >= 30seg. Asociado al evento con el mismo nombre + */ + DECLARE vDone INT DEFAULT 0; DECLARE vProcesId INT; DECLARE vCursor CURSOR FOR - SELECT p.id + SELECT p.id FROM information_schema.processlist p - WHERE USER = 'sorter' + WHERE USER = 'sorter' AND TIME >= 30; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + OPEN vCursor; l: LOOP @@ -63984,7 +63984,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `mysqlPreparedCount_check`() BEGIN DECLARE vPreparedCount INTEGER; - SELECT VARIABLE_VALUE INTO vPreparedCount + SELECT VARIABLE_VALUE INTO vPreparedCount FROM INFORMATION_SCHEMA.GLOBAL_STATUS WHERE VARIABLE_NAME LIKE '%prepared_stmt_count%'; @@ -63992,7 +63992,7 @@ BEGIN CALL `vn`.`mail_insert`('cau@verdnatura.es', NULL, 'Problemas BBDD prepared_stmt_count', - CONCAT('Existen problemas con el servicio de Logiflora, prepared_stmt_count con valor: ', + CONCAT('Existen problemas con el servicio de Logiflora, prepared_stmt_count con valor: ', vPreparedCount, ', está próximo a exceder su límite. \r\n Hay que reiniciar el servicio LF.VMP.Service del servidor a3.') ); @@ -64019,37 +64019,37 @@ BEGIN DECLARE newShelving VARCHAR(3); DECLARE vCode VARCHAR(3); - + SELECT MAX(code) INTO vCode FROM vn.shelving WHERE isPrinted = FALSE; - + SET @a1 := ASCII(MID(vCode,1,1)); SET @a2 := ASCII(MID(vCode,2,1)); SET @a3 := ASCII(MID(vCode,3,1)) + 1; - + IF @a3 > 90 THEN - + SET @a3 = 65; SET @a2 = @a2 + 1; - + IF @a2 > 90 THEN - + SET @a2 = 65; SET @a1 = @a1 + 1; - + IF @a1 > 90 THEN - + SET @a1 = 65; - + END IF; - + END IF; - + END IF; SET newShelving = CHAR(@a1,@a2,@a3 USING utf8); - + INSERT INTO vn.shelving(code) VALUES(newShelving); END ;; @@ -64078,18 +64078,18 @@ BEGIN * @param descripcion Texto de la observacion */ DECLARE vTableName VARCHAR(45); - + SET vTableName = CONCAT(vTableCode,'Observation'); - + IF ISNULL(vTableName) THEN CALL util.throw('CODE_NOT_FOUND'); END IF; - + SET @qryLog := CONCAT( 'INSERT INTO ', vTableName, ' (originFk, userFk, description)', ' VALUES (', vOriginFk, ', ', account.myUser_getId(), ', "', vDescription, '")' ); - + PREPARE stmt FROM @qryLog; EXECUTE stmt; DEALLOCATE PREPARE stmt; @@ -64119,15 +64119,15 @@ BEGIN DECLARE vDeliveryMethod INT; DECLARE vClient INT; - + SELECT deliveryMethodFk INTO vDeliveryMethod - FROM vn.agencyMode + FROM vn.agencyMode WHERE id = vAgencyMode; - + SELECT clientFk INTO vClient FROM vn.address WHERE id = vAddress; - + INSERT INTO hedera.order(date_send,customer_id,delivery_method_id,agency_id,address_id,source_app) VALUES( vLanded,vClient ,vDeliveryMethod,vAgencyMode ,vAddress ,vSourceApp); @@ -64153,7 +64153,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `orderDelete`(IN vId INT) BEGIN DELETE FROM hedera.`order` where id = vId; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -64180,7 +64180,7 @@ BEGIN DECLARE vOrderId INT; CALL vn.orderCreate(vLanded,vAgencyMode,vAddress,vSourceApp,vOrderId); SELECT vOrderId; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -64200,7 +64200,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `orderListVolume`(IN vOrderId INT) BEGIN - SELECT + SELECT o.id, o.itemFk, i.description, @@ -64226,7 +64226,7 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `packageInvoicing`( +CREATE DEFINER=`root`@`localhost` PROCEDURE `packageInvoicing`( IN vClient INT, IN vDate DATE, IN vCompany INT, @@ -64245,20 +64245,20 @@ BEGIN SET vGraceDays = IF(vIsAllInvoiceable ,0, 30); SET vGraceDate = TIMESTAMPADD(DAY, - vGraceDays, vDate); - - /* Clientes especiales: + + /* Clientes especiales: 3240 MADEFLOR 992 JAVIER FELIU 4 TONI VENDRELL */ - + IF vClient IN (992, 3240, 4) THEN - + SET vGraceDays = 365; - + END IF; /* Fin clientes especiales */ - + SET vDateEnd = DATE_ADD(vDate, INTERVAL 1 DAY); DROP TEMPORARY TABLE IF EXISTS tmp.packageToInvoice; @@ -64282,22 +64282,22 @@ BEGIN FROM tmp.packageToInvoice GROUP BY itemFk HAVING totalQuantity > 0; - + SELECT COUNT(*) INTO vIsInvoiceable FROM tmp.packageToInvoicePositives; IF vIsInvoiceable THEN - CALL ticket_add(vClient, + CALL ticket_add(vClient, vDateEnd, - vWarehouse, - vCompany, - NULL, - NULL, - NULL, - vDateEnd, - account.myUser_getId(), + vWarehouse, + vCompany, + NULL, + NULL, + NULL, + vDateEnd, + account.myUser_getId(), TRUE, vNewTicket); @@ -64306,44 +64306,44 @@ BEGIN packagingFk, quantity, pvp) - SELECT vNewTicket, - pti.packagingFk, - - SUM(pti.quantity) AS totalQuantity, + SELECT vNewTicket, + pti.packagingFk, + - SUM(pti.quantity) AS totalQuantity, pti.price FROM tmp.packageToInvoice pti - LEFT JOIN tmp.packageToInvoicePositives ptip ON pti.itemFk = ptip.itemFk - WHERE ptip.itemFK IS NOT NULL + LEFT JOIN tmp.packageToInvoicePositives ptip ON pti.itemFk = ptip.itemFk + WHERE ptip.itemFK IS NOT NULL OR vIsAllInvoiceable GROUP BY packagingFk HAVING totalQuantity; INSERT INTO sale( ticketFk, - itemFk, - concept, - quantity, + itemFk, + concept, + quantity, price ) - SELECT vNewTicket, - pti.itemFk, - i.name as concept, - sum(pti.quantity) as totalQuantity, + SELECT vNewTicket, + pti.itemFk, + i.name as concept, + sum(pti.quantity) as totalQuantity, pti.price FROM tmp.packageToInvoice pti JOIN item i ON i.id = pti.itemFk LEFT JOIN tmp.packageToInvoicePositives ptip ON pti.itemFk = ptip.itemFk - WHERE ptip.itemFK IS NOT NULL + WHERE ptip.itemFK IS NOT NULL OR vIsAllInvoiceable GROUP BY pti.itemFk HAVING totalQuantity; - + INSERT INTO saleComponent(saleFk, componentFk, value) SELECT id, vComponentCost, price FROM sale WHERE ticketFk = vNewTicket; - + END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -64369,7 +64369,7 @@ BEGIN WHERE mm.valor = 1 -- Listo para imprimir AND mm.stateFk = 9 -- Encajando AND m.Id_Ticket = ticketFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -64391,15 +64391,15 @@ BEGIN DECLARE valueFk INT; DECLARE encajando INT DEFAULT 9; - - SELECT valor INTO valueFk - FROM vn2008.Movimientos_mark - WHERE Id_Movimiento = saleFk + + SELECT valor INTO valueFk + FROM vn2008.Movimientos_mark + WHERE Id_Movimiento = saleFk AND stateFk = encajando; - + SET valueFk = (IFNULL(valueFk,0) + 1) MOD 3; - - REPLACE vn2008.Movimientos_mark(Id_Movimiento, valor, Id_Trabajador, stateFk) + + REPLACE vn2008.Movimientos_mark(Id_Movimiento, valor, Id_Trabajador, stateFk) VALUES(saleFk,valueFk,account.myUser_getId(),encajando); @@ -64491,34 +64491,34 @@ BEGIN DECLARE vLetters VARCHAR(26) DEFAULT 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; DECLARE vMaxId INT; DECLARE vCode VARCHAR(8); - + SET vColumn = vFromColumn; SET vRow = vFromRow; SET vCode = CONCAT(LPAD(vColumn,3,'0'),'-',IF(vIsLetterMode, MID(vLetters, vRow, 1), LPAD(vRow, 2,'0'))); - + SELECT MAX(id) INTO vMaxId FROM vn.parking; WHILE vColumn <= vToColumn DO - + WHILE vRow <= vToRow DO - + INSERT IGNORE INTO vn.parking(`column`, `row`, sectorFk, `code`, pickingOrder) VALUES (vColumn, vRow, vSectorFk, vCode, vColumn * 100 + vRow ) ON DUPLICATE KEY UPDATE `code` = vCode; - + SET vRow = vRow + 1; SET vCode = CONCAT(LPAD(vColumn,3,'0'),'-',IF(vIsLetterMode, MID(vLetters, vRow, 1), LPAD(vRow, 2,'0'))); - + END WHILE; - + SET vRow = vFromRow; SET vColumn = vColumn + 1; - + SET vCode = CONCAT(LPAD(vColumn,3,'0'),'-',IF(vIsLetterMode, MID(vLetters, vRow, 1), LPAD(vRow, 2,'0'))); - + END WHILE; - + SELECT * FROM vn.parking WHERE `column` BETWEEN vFromColumn AND vToColumn; END ;; @@ -64543,59 +64543,59 @@ BEGIN DECLARE vRow INT; DECLARE vCode VARCHAR(8); DECLARE i INT; - + IF vToRow < vFromRow THEN - + SET vRow = vFromRow; - + WHILE vRow >= vToRow DO - + SET i = 1; - + WHILE i <= vTrolleysByLine DO - + SET vCode = CONCAT(vLetter,'-', LPAD(vRow,2,'0'),'-', i); - + INSERT IGNORE INTO vn.parking( sectorFk, `code`, pickingOrder) VALUES (vSectorFk, vCode, vPickingOrder + (i * 10)) ON DUPLICATE KEY UPDATE `code` = vCode; - + SET i = i + 1; - + END WHILE; - + SET vRow = vRow - 1; - + END WHILE; ELSE - + SET vRow = vFromRow; - + WHILE vRow <= vToRow DO - + SET i = 1; - + WHILE i <= vTrolleysByLine DO - + SET vCode = CONCAT(vLetter,'-', LPAD(vRow,2,'0'),'-', i); - + INSERT IGNORE INTO vn.parking( sectorFk, `code`, pickingOrder) VALUES (vSectorFk, vCode, vPickingOrder + (i * 10) ) ON DUPLICATE KEY UPDATE `code` = vCode; - + SET i = i + 1; - + END WHILE; - + SET vRow = vRow + 1; - + END WHILE; - - + + END IF; - - + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -64619,28 +64619,28 @@ BEGIN DECLARE vColumn INT; DECLARE vLetters VARCHAR(200); DECLARE vLettersLength INT; - + SET vColumn = vStart; SET vRow = 1; SET vLetters = 'ABCDEF'; SET vLettersLength = LENGTH(vLetters); - + WHILE vColumn <= vEnd DO - + REPLACE vn.parking(`column`, `row`, `code`, sectorFk) VALUES(vColumn, vRow, CONCAT(vColumn,MID(vLetters,vRow,1)), vSectorFk); - + SET vRow = vRow + 1; - + IF vRow > vLettersLength THEN - + SET vRow = 1; SET vColumn = vColumn + 1; - + END IF; - + END WHILE; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -64659,11 +64659,11 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `parking_setOrder`(vWarehouseFk INT) BEGIN - + /* * Ordena el orden de preparacion de los parking de acuerdo con la tabla vn.corridor */ - + UPDATE vn.parking p JOIN ( SELECT code, @@ -64672,15 +64672,15 @@ BEGIN SELECT c.prepOrder, p.code, @orden := 0, - IF(c.isAscendent, 1,-1) * CAST(SUBSTRING(p.code,3,2) AS DECIMAL(2,0)) subCorridor , - CAST(IF(LENGTH(p.code) > 5, SUBSTRING(p.code,6,2), 0) AS DECIMAL(2,0)) ubication + IF(c.isAscendent, 1,-1) * CAST(SUBSTRING(p.code,3,2) AS DECIMAL(2,0)) subCorridor , + CAST(IF(LENGTH(p.code) > 5, SUBSTRING(p.code,6,2), 0) AS DECIMAL(2,0)) ubication FROM vn.parking p - JOIN vn.sector s ON s.id = p.sectorFk + JOIN vn.sector s ON s.id = p.sectorFk JOIN vn.corridor c ON c.code = LEFT(p.code,1) COLLATE utf8_general_ci - WHERE s.warehouseFk = vWarehouseFk) sub - ORDER BY sub.prepOrder, subCorridor, ubication) sub2 ON sub2.code = p.code + WHERE s.warehouseFk = vWarehouseFk) sub + ORDER BY sub.prepOrder, subCorridor, ubication) sub2 ON sub2.code = p.code SET p.pickingOrder = sub2.po; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -64699,17 +64699,17 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `prepareClientList`() BEGIN - + /* * Require la tabla tmp.ticket(id,clientFk) */ - + DROP TEMPORARY TABLE IF EXISTS tmp.client; CREATE TEMPORARY TABLE tmp.client (PRIMARY KEY (id)) ENGINE = MEMORY SELECT DISTINCT clientFk id - FROM tmp.ticket; + FROM tmp.ticket; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -64837,14 +64837,14 @@ BEGIN /** * Comprueba si la impresora pertenece al sector * - * @param vLabelerFk id de la impresora + * @param vLabelerFk id de la impresora * @param vSector sector a comprobar */ DECLARE isPrinterInNewSector BOOL; IF vLabelerFk IS NOT NULL THEN SELECT COUNT(sectorFK) INTO isPrinterInNewSector - FROM vn.printer p + FROM vn.printer p WHERE id = vLabelerFk AND sectorFk = vSector; IF !isPrinterInNewSector THEN @@ -64868,7 +64868,7 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `productionControl`( - vWarehouseFk INT, + vWarehouseFk INT, vScopeDays INT ) proc: BEGIN @@ -64969,7 +64969,7 @@ proc: BEGIN LEFT JOIN parking pk ON pk.id = tp.parkingFk WHERE t.warehouseFk = vWarehouseFk AND dm.code IN ('AGENCY', 'DELIVERY', 'PICKUP'); - + UPDATE tmp.productionBuffer pb JOIN ( SELECT pb.ticketFk, GROUP_CONCAT(p.code) previaParking @@ -64977,12 +64977,12 @@ proc: BEGIN JOIN sale s ON s.ticketFk = pb.ticketFk JOIN saleGroupDetail sgd ON sgd.saleFk = s.id JOIN saleGroup sg ON sg.id = sgd.saleGroupFk - JOIN parking p ON p.id = sg.parkingFk + JOIN parking p ON p.id = sg.parkingFk GROUP BY pb.ticketFk ) t ON t.ticketFk = pb.ticketFk SET pb.previaParking = t.previaParking; - -- Problemas por ticket + -- Problemas por ticket ALTER TABLE tmp.productionBuffer CHANGE COLUMN `problem` `problem` VARCHAR(255), ADD COLUMN `collectionH` INT, @@ -65263,7 +65263,7 @@ BEGIN `yearMonth` INT ) ENGINE = MEMORY; - + WHILE vDated <= vEnded DO INSERT INTO tmp.rangeDate SET `dated` = vDated, @@ -65273,7 +65273,7 @@ BEGIN `day` = DAY(vDated), `week` = WEEK(vDated, 1), `yearMonth` = YEAR(vDated) * 100 + MONTH(vDated); - + SET vDated = DATE_ADD(vDated, INTERVAL 1 DAY); END WHILE; END ;; @@ -65362,7 +65362,7 @@ BEGIN CALL cache.available_refresh(vCalc, FALSE, vWarehouseFk, vDate); DROP TEMPORARY TABLE IF EXISTS tmp.recipeCook; - + CREATE TEMPORARY TABLE tmp.recipeCook SELECT *, @counter := IF(@element = element COLLATE utf8_general_ci , @counter + 1, 1) as counter, @@ -65380,22 +65380,22 @@ BEGIN IFNULL((i.inkFk = r.inkFk ) ,0) + IFNULL((i.size = r.size) ,0) + IFNULL((i.name LIKE CONCAT('%',r.name,'%')) ,0) - + IFNULL((i.longName LIKE CONCAT('%',r.longName,'%')),0) + + IFNULL((i.longName LIKE CONCAT('%',r.longName,'%')),0) + IFNULL((i.typeFk = r.typeFk),0) as matches, i.typeFk, rl.previousSelected - FROM vn.recipe r + FROM vn.recipe r JOIN vn.item i ON (IFNULL(i.name LIKE CONCAT('%',r.name,'%'), 0) OR IFNULL(i.longName LIKE CONCAT('%',r.longName,'%'),0)) OR i.typeFk <=> r.typeFk JOIN cache.available a ON a.item_id = i.id AND a.calc_id = vCalc LEFT JOIN (SELECT recipe_ItemFk, element as log_element, selected_ItemFk, count(*) as previousSelected FROM vn.recipe_log - GROUP BY recipe_ItemFk, element, selected_ItemFk) rl ON rl.recipe_ItemFk = r.itemFk + GROUP BY recipe_ItemFk, element, selected_ItemFk) rl ON rl.recipe_ItemFk = r.itemFk AND rl.log_element = r.element AND rl.selected_ItemFk = i.id WHERE r.itemFk = vItemFk - AND a.available > vBunchesQuantity * r.quantity + AND a.available > vBunchesQuantity * r.quantity UNION ALL SELECT 100 itemFk, CONCAT('? ',r.element,' ',IFNULL(r.size,''),' ',IFNULL(r.inkFk,'')) as longName, @@ -65412,15 +65412,15 @@ BEGIN WHERE r.itemFk = vItemFk GROUP BY r.element ) sub - + ORDER BY element, matches DESC, previousSelected DESC; - - SELECT * + + SELECT * FROM tmp.recipeCook WHERE counter < 6 - OR itemFk = 100 + OR itemFk = 100 ; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -65445,71 +65445,71 @@ BEGIN DECLARE vShipped DATE; DECLARE vEntryFk INT; DECLARE vTravelFk INT; - + CALL cache.last_buy_refresh(FALSE); - - SELECT warehouseFk, shipped + + SELECT warehouseFk, shipped INTO vWarehouseFk, vShipped - FROM vn.ticket + FROM vn.ticket WHERE id = vTicketFk; UPDATE vn.ticket t JOIN vn.item i ON i.id = vItemFk SET t.nickname = CONCAT(vQuantity,' ',i.longName) WHERE t.id = vTicketFk; - + SELECT b.buyingValue INTO vLastCost FROM vn.buy b JOIN cache.last_buy lb ON lb.buy_id = b.id WHERE lb.item_id = vItemFk ORDER BY (lb.warehouse_id = vWarehouseFk) DESC LIMIT 1; - + INSERT INTO vn.sale(ticketFk, itemFk, quantity, concept, price) SELECT vTicketFk, 98, - vQuantity, i.longName, vLastCost FROM vn.item i WHERE i.id = vItemFk; - /* + /* SELECT tr.id INTO vTravelFk FROM vn.travel tr JOIN vn.warehouse w ON w.id = tr.warehouseOutFk WHERE tr.warehouseInFk = vWarehouseFk AND tr.landed = vShipped AND w.name = 'Confeccion'; - + IF IFNULL(vTravelFk,0) = 0 THEN - + INSERT INTO vn.travel(shipped, landed, warehouseInFk, warehouseOutFk, agencyFk) SELECT vShipped, vShipped, vWarehouseFk, w.id, am.id - FROM vn.warehouse w - JOIN vn.agencyMode am + FROM vn.warehouse w + JOIN vn.agencyMode am WHERE w.name = 'Confeccion' AND am.name = 'DIRECTO PROVEEDOR'; - + SET vTravelFk = LAST_INSERT_ID(); - - END IF; - + + END IF; + SELECT e.id INTO vEntryFk FROM vn.entry e JOIN vn.supplier s ON s.id = supplierFk WHERE e.travelFk = vTravelFk AND s.name = 'Confeccion Natural' AND e.isRaid = FALSE; - + IF IFNULL(vEntryFk,0) = 0 THEN - + INSERT INTO vn.entry(supplierFk, evaNotes, travelFk, companyFk) SELECT s.id, t.nickname, vTravelFk, c.id FROM vn.supplier s JOIN vn.ticket t ON t.id = vTicketFk - JOIN vn.company c ON c.code = 'VNL' + JOIN vn.company c ON c.code = 'VNL' WHERE s.name = 'Confeccion Natural'; - + SET vEntryFk = LAST_INSERT_ID(); - + END IF; - + INSERT INTO vn.buy(entryFk, itemFk, quantity, buyingValue, packageFk, packing, grouping) SELECT vEntryFk, b.itemFk, vQuantity, b.buyingValue, b.packageFk, b.packing, b.grouping FROM cache.last_buy lb @@ -65611,7 +65611,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `report_print`( ) BEGIN /** - * Inserts in the print queue the report to be printed and the necessary parameters for this + * Inserts in the print queue the report to be printed and the necessary parameters for this * one taking into account the paper size of both the printer and the report. * * @param vReportName the report to be printed. @@ -65654,11 +65654,11 @@ BEGIN END IF; IF vReportFk IS NULL THEN - CALL util.throw('reportNotExists'); + CALL util.throw('reportNotExists'); END IF; IF vReportSize <> vPrinteSize THEN - CALL util.throw('incorrectSize'); + CALL util.throw('incorrectSize'); END IF; START TRANSACTION; @@ -65667,7 +65667,7 @@ BEGIN priorityFk = vPriorityFk, reportFk = vReportFk, workerFk = vUserFk; - + SET vPrintQueueFk = LAST_INSERT_ID(); WHILE vI < vLength DO @@ -65700,16 +65700,16 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `riskAllClients`(maxRiskDate DATE) BEGIN - + DROP TEMPORARY TABLE IF EXISTS tmp.client_list; CREATE TEMPORARY TABLE tmp.client_list (PRIMARY KEY (Id_Cliente)) ENGINE = MEMORY SELECT id Id_Cliente, null grade FROM vn.client; - + CALL vn2008.risk_vs_client_list(maxRiskDate); - - SELECT + + SELECT c.RazonSocial, c.Id_Cliente, c.Credito, @@ -65721,7 +65721,7 @@ BEGIN JOIN tmp.risk r ON r.Id_Cliente = c.Id_Cliente JOIN tmp.client_list ci ON c.Id_Cliente = ci.Id_Cliente GROUP BY c.Id_cliente; - + DROP TEMPORARY TABLE IF EXISTS tmp.risk; DROP TEMPORARY TABLE IF EXISTS tmp.client_list; END ;; @@ -65780,25 +65780,25 @@ BEGIN DECLARE vM3 INT; DECLARE vKg INT; DECLARE vMatricula varchar(50); - + SELECT sum(packages) as bultos INTO vPackages - FROM vn.ticket t + FROM vn.ticket t WHERE routeFk = vRouteFk; - + SELECT SUM(sv.physicalVolume), SUM(sv.physicalWeight) INTO vM3, vKg FROM vn.saleVolume sv WHERE sv.routeFk = vRouteFk; - + SELECT v.numberPlate as matricula INTO vMatricula - FROM vn.route r + FROM vn.route r JOIN vn.vehicle v ON r.vehicleFk = v.id WHERE r.id = vRouteFk; - + SELECT vRouteFk as Ruta, - vPackages as Bultos, + vPackages as Bultos, vM3 as m3, vKg as Kg, vMatricula as Matricula; @@ -65863,7 +65863,7 @@ BEGIN ) sub ON sub.routeFk = rm.routeFk SET rm.ticketFree = sub.ticketFree; - UPDATE routesMonitor rm + UPDATE routesMonitor rm JOIN( SELECT t.routeFk, COUNT(*) AS ticketPacked FROM vn.ticket t @@ -65949,11 +65949,11 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `routeSetOk`( vRouteFk INT) BEGIN - + UPDATE vn.route r SET r.isOk = 1 WHERE r.id = vRouteFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -66018,17 +66018,17 @@ proc: BEGIN IF vIsFreelance THEN INSERT INTO routeCommission ( - routeFk, - workCenterFk, - freelanceYearlyM3, - cat4m3, + routeFk, + workCenterFk, + freelanceYearlyM3, + cat4m3, cat5m3 ) SELECT vSelf, r.commissionWorkCenterFk, rc.freelanceM3 * IF( - IFNULL(r.m3, 0) >= rc.freelanceMinM3, - IFNULL(r.m3, 0), + IFNULL(r.m3, 0) >= rc.freelanceMinM3, + IFNULL(r.m3, 0), 0), rc.distributionCat4M3 * IFNULL(r.m3, 0), rc.distributionCat5M3 * IFNULL(r.m3, 0) @@ -66040,20 +66040,20 @@ proc: BEGIN AND r.commissionWorkCenterFk; ELSE INSERT INTO routeCommission ( - routeFk, - workCenterFk, - km, - m3, - yearlyKm, - yearlyM3, - cat4m3, + routeFk, + workCenterFk, + km, + m3, + yearlyKm, + yearlyM3, + cat4m3, cat5m3 ) SELECT vSelf, r.commissionWorkCenterFk, - (r.kmEnd - r.kmStart) * + (r.kmEnd - r.kmStart) * IF(v.isKmTruckRate, rc.kmHeavy, rc.kmLight), - IFNULL(r.m3, 0) * + IFNULL(r.m3, 0) * IF(v.isKmTruckRate, rc.deliveryM3Cat5, rc.deliveryM3Cat4), (r.kmEnd - r.kmStart) * rc.kmYearly, IFNULL(r.m3, 0) * rc.m3Yearly, @@ -66090,7 +66090,7 @@ proc: BEGIN /** * Recalculates modified route. */ - + DECLARE vDone BOOL; DECLARE vRouteFk INT; @@ -66099,7 +66099,7 @@ proc: BEGIN DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + DECLARE CONTINUE HANDLER FOR SQLEXCEPTION BEGIN DO RELEASE_LOCK('vn.route_doRecalc'); @@ -66257,27 +66257,27 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `saleBuy_Add`(vSaleFk INT, vBuyFk INT) BEGIN - + /* Añade un registro a la tabla saleBuy en el caso de que sea posible mantener la trazabilidad - * + * * @param vSaleFk clave primaria de vn.sale * @param vBuyFk clave primaria de vn.buy */ - /*IF (SELECT COUNT(*) + /*IF (SELECT COUNT(*) FROM vn.sale s JOIN vn.item i ON i.id = s.itemFk - JOIN vn.itemType it ON it.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk WHERE s.id = vSaleFk AND ic.code = 'fruit') THEN */ - - IF (SELECT COUNT(*) FROM vn.buy WHERE id = vBuyFk AND itemOriginalFk) THEN - + + IF (SELECT COUNT(*) FROM vn.buy WHERE id = vBuyFk AND itemOriginalFk) THEN + INSERT INTO vn.saleBuy (saleFk, buyFk) VALUES(vSaleFk, vBuyFk); - + END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -66301,7 +66301,7 @@ BEGIN * * @param vSectorFk Identificador de vn.sector */ - INSERT INTO vn.saleGroup(userFk, sectorFk) + INSERT INTO vn.saleGroup(userFk, sectorFk) VALUES (account.myUser_getId(), vSectorFk); SELECT LAST_INSERT_ID(); @@ -66433,41 +66433,41 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sales_merge`(vTicketFk INT) -BEGIN - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - CREATE OR REPLACE TEMPORARY TABLE tSalesToPreserve - SELECT s.id, s.itemFk, SUM(s.quantity) newQuantity - FROM sale s - JOIN item i ON i.id = s.itemFk - JOIN itemType it ON it.id = i.typeFk - WHERE s.ticketFk = vTicketFk - AND it.isMergeable - GROUP BY s.itemFk, s.price, s.discount; - - START TRANSACTION; - - UPDATE sale s - JOIN tSalesToPreserve stp ON stp.id = s.id - SET quantity = newQuantity - WHERE s.ticketFk = vTicketFk; - - DELETE s.* - FROM sale s - LEFT JOIN tSalesToPreserve stp ON stp.id = s.id - JOIN item i ON i.id = s.itemFk - JOIN itemType it ON it.id = i.typeFk - WHERE s.ticketFk = vTicketFk - AND stp.id IS NULL - AND it.isMergeable; - - COMMIT; - - DROP TEMPORARY TABLE tSalesToPreserve; +BEGIN + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + CREATE OR REPLACE TEMPORARY TABLE tSalesToPreserve + SELECT s.id, s.itemFk, SUM(s.quantity) newQuantity + FROM sale s + JOIN item i ON i.id = s.itemFk + JOIN itemType it ON it.id = i.typeFk + WHERE s.ticketFk = vTicketFk + AND it.isMergeable + GROUP BY s.itemFk, s.price, s.discount; + + START TRANSACTION; + + UPDATE sale s + JOIN tSalesToPreserve stp ON stp.id = s.id + SET quantity = newQuantity + WHERE s.ticketFk = vTicketFk; + + DELETE s.* + FROM sale s + LEFT JOIN tSalesToPreserve stp ON stp.id = s.id + JOIN item i ON i.id = s.itemFk + JOIN itemType it ON it.id = i.typeFk + WHERE s.ticketFk = vTicketFk + AND stp.id IS NULL + AND it.isMergeable; + + COMMIT; + + DROP TEMPORARY TABLE tSalesToPreserve; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -66502,17 +66502,17 @@ BEGIN OPEN cCur; myLoop: LOOP - + SET vDone = FALSE; - + FETCH cCur INTO vTicketFk; IF vDone THEN LEAVE myLoop; END IF; - + CALL vn.sales_merge(vTicketFk); - + END LOOP; CLOSE cCur; @@ -66643,9 +66643,9 @@ BEGIN DELETE st.* FROM vn.saleTracking st JOIN vn.state s ON s.id = st.stateFk - WHERE st.saleFk = vSaleFk + WHERE st.saleFk = vSaleFk AND s.code = vState COLLATE utf8_unicode_ci; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -66662,12 +66662,12 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `saleTracking_new`( - vSaleFK INT, - vIsChecked BOOLEAN, - vOriginalQuantity INT, - vWorkerFk INT, - vAction VARCHAR(50), +CREATE DEFINER=`root`@`localhost` PROCEDURE `saleTracking_new`( + vSaleFK INT, + vIsChecked BOOLEAN, + vOriginalQuantity INT, + vWorkerFk INT, + vAction VARCHAR(50), vState VARCHAR(50), vIsScanned BOOLEAN) BEGIN @@ -66683,12 +66683,12 @@ BEGIN * @param vIsScanned Identificador si se ha escaneado automáticamente o manual */ - REPLACE vn.saleTracking(saleFk, - isChecked, - originalQuantity, - workerFk, + REPLACE vn.saleTracking(saleFk, + isChecked, + originalQuantity, + workerFk, stateFk, - isScanned) + isScanned) SELECT vSaleFK, vIsChecked, vOriginalQuantity, @@ -66715,27 +66715,27 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `saleTracking_updateIsChecked`(vSaleFK INT, vIsChecked BOOL, vIsScanned BOOL) BEGIN - + /** * Actualiza el estado del campo vn.saleTracking.isChecked y elimina las lineas de vn.itemShelving * si procede, en el caso de las preparaciones previas, por usuario - * + * * @param vSaleFk Identificador de vn.sale * @param vIsChecked Estado del registro */ - + UPDATE vn.saleTracking st JOIN vn.state s ON s.id = st.stateFk AND s.code = 'PREVIOUS_PREPARATION' SET st.isChecked = vIsChecked, st.isScanned = vIsScanned WHERE st.saleFk = vSaleFK AND st.workerFk = account.myUser_getId(); - + IF vIsChecked = FALSE THEN - - DELETE FROM vn.itemShelvingSale + + DELETE FROM vn.itemShelvingSale WHERE saleFk = vSaleFK; - + END IF; END ;; @@ -66761,14 +66761,14 @@ proc: BEGIN * * @param vSelf Id de la venta * @param vOption indica en que componente pone el descuadre, NULL en casos habituales - */ + */ CREATE OR REPLACE TEMPORARY TABLE tmp.recalculateSales SELECT s.id FROM sale s WHERE s.id = vSelf; - + CALL sale_recalcComponent(vOption); - + DROP TEMPORARY TABLE tmp.recalculateSales; END ;; DELIMITER ; @@ -66815,7 +66815,7 @@ BEGIN GROUP BY s.id; DECLARE CONTINUE HANDLER FOR NOT FOUND - SET v_done = TRUE; + SET v_done = TRUE; DROP TEMPORARY TABLE IF EXISTS tmp.coste; @@ -66823,7 +66823,7 @@ BEGIN CREATE TEMPORARY TABLE tmp.coste (PRIMARY KEY (id)) ENGINE = MEMORY SELECT s.id - FROM sale s + FROM sale s JOIN item i ON i.id = s.itemFk JOIN itemType tp ON tp.id = i.typeFk JOIN itemCategory ic ON ic.id = tp.categoryFk @@ -66842,17 +66842,17 @@ BEGIN IF v_done THEN LEAVE l; END IF; - + SELECT ticketFk, concept INTO vTicketFk, vConcept FROM sale WHERE id = vSaleFk; - + CALL sale_calculateComponent(vSaleFk, 1); END LOOP; CLOSE vCur; - DROP TEMPORARY TABLE tmp.coste; + DROP TEMPORARY TABLE tmp.coste; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -66938,7 +66938,7 @@ DECLARE vIsCollection BOOL; TRIM(CONCAT(LPAD(s.concept,30,' '), ' ', RPAD(IFNULL(i.size,''),5,' '))) line1, '' cel1, - TRIM(CONCAT(LPAD(IFNULL(ip.productor,''),30,' '), ' ',LPAD(IFNULL(o.code,''),4,' '))) line2, + TRIM(CONCAT(LPAD(IFNULL(ip.productor,''),30,' '), ' ',LPAD(IFNULL(o.code,''),4,' '))) line2, IF(s.quantity MOD IFNULL(b.packing,s.quantity + 1), CONCAT(CAST(s.quantity/IFNULL(b.`grouping`,1) AS DECIMAL(10,0)),' x ',IFNULL(b.`grouping`,1)), CONCAT(CAST(s.quantity / IFNULL(b.packing,1) AS DECIMAL(10,0)),' pack de ',IFNULL(b.packing,1))) cel2, @@ -66955,12 +66955,12 @@ DECLARE vIsCollection BOOL; JOIN sale s ON s.ticketFk = t.id JOIN ticket tt ON tt.id = t.id LEFT JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND lb.warehouse_id = tt.warehouseFk - LEFT JOIN buy b ON b.id = lb.buy_id + LEFT JOIN buy b ON b.id = lb.buy_id JOIN item i ON i.id = s.itemFk LEFT JOIN ticketCollection tc ON tc.ticketFk = t.id LEFT JOIN collection c ON c.id = tc.collectionFk - LEFT JOIN (SELECT sub.saleFk, sub.isChecked, sub.stateFk, sub.originalQuantity - FROM (SELECT DISTINCT st.id, st.saleFk, st.isChecked, st.stateFk, st.originalQuantity + LEFT JOIN (SELECT sub.saleFk, sub.isChecked, sub.stateFk, sub.originalQuantity + FROM (SELECT DISTINCT st.id, st.saleFk, st.isChecked, st.stateFk, st.originalQuantity FROM tmp.ticket2 t JOIN sale s ON s.ticketFk = t.id JOIN saleTracking st ON st.saleFk = s.id @@ -66972,7 +66972,7 @@ DECLARE vIsCollection BOOL; LEFT JOIN itemColor ic ON ic.itemFk = s.itemFk LEFT JOIN itemProductor ip ON ip.itemFk = s.itemFk LEFT JOIN origin o ON o.id = i.originFk - LEFT JOIN saleGroupDetail sgd ON sgd.saleFk = s.id + LEFT JOIN saleGroupDetail sgd ON sgd.saleFk = s.id LEFT JOIN saleGroup sg ON sg.id = sgd.saleGroupFk LEFT JOIN parking p ON p.id = sg.parkingFk LEFT JOIN saleMistake sm ON sm.saleFk = s.id @@ -67024,8 +67024,8 @@ BEGIN DELETE tt.* FROM tmp.sale_getProblems tt JOIN vn.ticketObservation tto ON tto.ticketFk = tt.ticketFk - JOIN vn.observationType ot ON ot.id = tto.observationTypeFk - WHERE ot.code = 'administrative' + JOIN vn.observationType ot ON ot.id = tto.observationTypeFk + WHERE ot.code = 'administrative' AND tto.description = 'Miriam'; CREATE OR REPLACE TEMPORARY TABLE tmp.sale_problems ( @@ -67057,7 +67057,7 @@ BEGIN -- Too Little INSERT INTO tmp.sale_problems(ticketFk, isTooLittle) - SELECT tp.ticketFk, TRUE + SELECT tp.ticketFk, TRUE FROM tmp.sale_getProblems tp JOIN vn.ticket t ON t.id = tp.ticketFk JOIN (SELECT t.addressFk, SUM(sv.litros) litros, t.totalWithoutVat @@ -67144,25 +67144,25 @@ BEGIN -- Disponible: no va a haber suficiente producto para preparar todos los pedidos CALL cache.available_refresh(vAvailableCache, FALSE, vWarehouseFk, vDate); - - -- Faltas: visible, disponible y ubicado son menores que la cantidad vendida + + -- Faltas: visible, disponible y ubicado son menores que la cantidad vendida CALL cache.visible_refresh(vVisibleCache, FALSE, vWarehouseFk); INSERT INTO tmp.sale_problems(ticketFk, itemShortage, saleFk) SELECT ticketFk, problem, saleFk FROM ( - SELECT tl.ticketFk, - LEFT(CONCAT('F: ',GROUP_CONCAT(i.id, ' ', i.longName, ' ')),250) problem, + SELECT tl.ticketFk, + LEFT(CONCAT('F: ',GROUP_CONCAT(i.id, ' ', i.longName, ' ')),250) problem, s.id AS saleFk FROM tmp.ticket_list tl JOIN vn.ticket t ON t.id = tl.ticketFk JOIN vn.sale s ON s.ticketFk = t.id JOIN vn.item i ON i.id = s.itemFk JOIN vn.itemType it on it.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk LEFT JOIN cache.visible v ON v.item_id = i.id AND v.calc_id = vVisibleCache LEFT JOIN cache.available av ON av.item_id = i.id AND av.calc_id = vAvailableCache - LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk + LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk WHERE IFNULL(v.visible,0) < s.quantity AND IFNULL(av.available ,0) < s.quantity AND IFNULL(issw.visible, 0) < s.quantity @@ -67175,7 +67175,7 @@ BEGIN AND t.warehouseFk = vWarehouseFk GROUP BY tl.ticketFk) sub ON DUPLICATE KEY UPDATE itemShortage = sub.problem, saleFk = sub.saleFk; - + -- Inventario: Visible suficiente, pero ubicado menor a la cantidad vendida INSERT INTO tmp.sale_problems(ticketFk, itemLost, saleFk) SELECT ticketFk, problem, saleFk @@ -67188,7 +67188,7 @@ BEGIN JOIN vn.itemType it on it.id = i.typeFk JOIN vn.itemCategory ic ON ic.id = it.categoryFk LEFT JOIN cache.visible v ON v.item_id = s.itemFk AND v.calc_id = vVisibleCache - LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk + LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk WHERE IFNULL(v.visible,0) >= s.quantity AND IFNULL(issw.visible, 0) < s.quantity AND s.quantity > 0 @@ -67201,7 +67201,7 @@ BEGIN AND t.warehouseFk = vWarehouseFk GROUP BY tl.ticketFk) sub ON DUPLICATE KEY UPDATE itemDelay = sub.problem, saleFk = sub.saleFk; - + -- Retraso: Disponible suficiente, pero no visible ni ubicado INSERT INTO tmp.sale_problems(ticketFk, itemDelay, saleFk) SELECT ticketFk, problem, saleFk @@ -67215,7 +67215,7 @@ BEGIN JOIN vn.itemCategory ic ON ic.id = it.categoryFk LEFT JOIN cache.visible v ON v.item_id = s.itemFk AND v.calc_id = vVisibleCache LEFT JOIN cache.available av ON av.item_id = i.id AND av.calc_id = vAvailableCache - LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk + LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk WHERE IFNULL(v.visible,0) < s.quantity AND IFNULL(av.available ,0) >= s.quantity AND IFNULL(issw.visible, 0) < s.quantity @@ -67235,13 +67235,13 @@ BEGIN INSERT INTO tmp.sale_problems(ticketFk, hasRounding, saleFk) SELECT ticketFk, problem, saleFk FROM ( - SELECT - tl.ticketFk, + SELECT + tl.ticketFk, s.id saleFk , - LEFT(GROUP_CONCAT('RE: ',i.id, ' ', IFNULL(i.longName,''), ' '), 250) problem, + LEFT(GROUP_CONCAT('RE: ',i.id, ' ', IFNULL(i.longName,''), ' '), 250) problem, MOD(s.quantity, b.`grouping`) hasRounding FROM tmp.ticket_list tl - JOIN ticket t ON t.id = tl.ticketFk + JOIN ticket t ON t.id = tl.ticketFk AND t.warehouseFk = vWarehouseFk JOIN sale s ON s.ticketFk = tl.ticketFk JOIN item i ON i.id = s.itemFk @@ -67249,12 +67249,12 @@ BEGIN JOIN buy b ON b.id = bu.buyFk GROUP BY tl.ticketFk HAVING hasRounding - ) sub + ) sub ON DUPLICATE KEY UPDATE hasRounding = sub.problem, saleFk = sub.saleFk; END LOOP; CLOSE vCursor; - + INSERT INTO tmp.sale_problems(ticketFk, isTaxDataChecked) SELECT DISTINCT tl.ticketFk, FALSE FROM tmp.ticket_list tl @@ -67284,16 +67284,16 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_getProblemsByTicket`(IN vTicketFk INT, IN vIsTodayRelative TINYINT(1)) BEGIN /** - * Calcula los problemas de cada venta + * Calcula los problemas de cada venta * para un conjunto de tickets. * * @return Problems result */ DROP TEMPORARY TABLE IF EXISTS tmp.sale_getProblems; - CREATE TEMPORARY TABLE tmp.sale_getProblems + CREATE TEMPORARY TABLE tmp.sale_getProblems (INDEX (ticketFk)) ENGINE = MEMORY - SELECT t.id ticketFk, t.clientFk, t.warehouseFk, t.shipped + SELECT t.id ticketFk, t.clientFk, t.warehouseFk, t.shipped FROM ticket t WHERE t.id = vTicketFk; @@ -67322,7 +67322,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_PriceFix`(vTicketFk INT) BEGIN - + DELETE sc.* FROM vn.saleComponent sc JOIN vn.sale s ON s.id = sc.saleFk @@ -67358,52 +67358,52 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_recalcComponent`(vOption INT) proc: BEGIN /** - * Este procedimiento recalcula los componentes de un conjunto de sales, + * Este procedimiento recalcula los componentes de un conjunto de sales, * eliminando los componentes existentes e insertandolos de nuevo * * @param vOption si no se quiere forzar llamar con NULL * @table tmp.recalculateSales (id) - */ - DECLARE vShipped DATE; + */ + DECLARE vShipped DATE; DECLARE vWarehouseFk SMALLINT; DECLARE vAgencyModeFk INT; DECLARE vAddressFk INT; DECLARE vTicketFk INT; - DECLARE vLanded DATE; + DECLARE vLanded DATE; DECLARE vIsEditable BOOLEAN; DECLARE vZoneFk INTEGER; DECLARE vDone BOOL DEFAULT FALSE; - + DECLARE vCur CURSOR FOR SELECT DISTINCT s.ticketFk FROM tmp.recalculateSales rs JOIN vn.sale s ON s.id = rs.id; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + OPEN vCur; l: LOOP SET vDone = FALSE; - FETCH vCur INTO vTicketFk; - + FETCH vCur INTO vTicketFk; + IF vDone THEN LEAVE l; END IF; - SELECT (hasToRecalcPrice OR ts.alertLevel IS NULL) AND t.refFk IS NULL, - t.zoneFk, - t.warehouseFk, - t.shipped, - t.addressFk, - t.agencyModeFk, + SELECT (hasToRecalcPrice OR ts.alertLevel IS NULL) AND t.refFk IS NULL, + t.zoneFk, + t.warehouseFk, + t.shipped, + t.addressFk, + t.agencyModeFk, t.landed - INTO vIsEditable, - vZoneFk, - vWarehouseFk, - vShipped, - vAddressFk, - vAgencyModeFk, + INTO vIsEditable, + vZoneFk, + vWarehouseFk, + vShipped, + vAddressFk, + vAgencyModeFk, vLanded FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket @@ -67411,31 +67411,31 @@ proc: BEGIN WHERE t.id = vTicketFk; CALL zone_getLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk, TRUE); - + IF NOT EXISTS (SELECT TRUE FROM tmp.zoneGetLanded LIMIT 1) THEN CALL util.throw(CONCAT('There is no zone for these parameters ', vTicketFk)); END IF; - + IF vLanded IS NULL OR vZoneFk IS NULL THEN - + UPDATE ticket t - SET t.landed = (SELECT landed FROM tmp.zoneGetLanded LIMIT 1) + SET t.landed = (SELECT landed FROM tmp.zoneGetLanded LIMIT 1) WHERE t.id = vTicketFk AND t.landed IS NULL; - + IF vZoneFk IS NULL THEN SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetLanded LIMIT 1; UPDATE ticket t SET t.zoneFk = vZoneFk WHERE t.id = vTicketFk AND t.zoneFk IS NULL; END IF; - + END IF; - + DROP TEMPORARY TABLE tmp.zoneGetLanded; - - -- rellena la tabla buyUltimate con la ultima compra - CALL buyUltimate (vWarehouseFk, vShipped); - + + -- rellena la tabla buyUltimate con la ultima compra + CALL buyUltimate (vWarehouseFk, vShipped); + CREATE OR REPLACE TEMPORARY TABLE tmp.sale (PRIMARY KEY (saleFk)) ENGINE = MEMORY SELECT s.id saleFk, vWarehouseFk warehouseFk @@ -67443,7 +67443,7 @@ proc: BEGIN JOIN tmp.recalculateSales rs ON s.id = rs.id WHERE s.ticketFk = vTicketFk; - CREATE OR REPLACE TEMPORARY TABLE tmp.ticketLot + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketLot SELECT vWarehouseFk warehouseFk, NULL available, s.itemFk, bu.buyFk, vZoneFk zoneFk FROM sale s JOIN tmp.recalculateSales rs ON s.id = rs.id @@ -67457,15 +67457,15 @@ proc: BEGIN IF vOption IS NULL THEN SET vOption = IF(vIsEditable, 1, 6); END IF; - - CALL ticketComponentUpdateSale(vOption); + + CALL ticketComponentUpdateSale(vOption); CALL catalog_componentPurge(); - + DROP TEMPORARY TABLE tmp.buyUltimate; DROP TEMPORARY TABLE tmp.sale; - + END LOOP; - CLOSE vCur; + CLOSE vCur; END ;; DELIMITER ; @@ -67486,22 +67486,22 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sectorCollectionSaleGroup_add`(vSaleGroupFk INT, vSectorCollectionFk INT) BEGIN /** - * Inserta un nuevo registro en vn.sectorCollectionSaleGroup + * Inserta un nuevo registro en vn.sectorCollectionSaleGroup * Actualiza el usuario en vn.saleGroup y reemplaza los registros de vn.saleTracking - * + * * @param vSaleGroupFk Identificador de vn.saleGroup * @param vSectorCollectionFk Identificador de vn.sectorCollection */ REPLACE sectorCollectionSaleGroup - SET sectorCollectionFk = vSectorCollectionFk, + SET sectorCollectionFk = vSectorCollectionFk, saleGroupFk = vSaleGroupFk; - + UPDATE saleGroup sg JOIN sectorCollectionSaleGroup scsg ON scsg.saleGroupFk = sg.id JOIN sectorCollection sc ON sc.id = scsg.sectorCollectionFk - SET sg.userFk = sc.userFk + SET sg.userFk = sc.userFk WHERE sg.id = vSaleGroupFk; - + INSERT IGNORE saleTracking( saleFk, isChecked, @@ -67513,8 +67513,8 @@ BEGIN sc.userFk, s.id FROM saleGroupDetail sgd - JOIN sectorCollectionSaleGroup scsg - ON scsg.saleGroupFk = sgd.saleGroupFk + JOIN sectorCollectionSaleGroup scsg + ON scsg.saleGroupFk = sgd.saleGroupFk JOIN sectorCollection sc ON sc.id = scsg.sectorCollectionFk JOIN state s ON s.code = 'PREVIOUS_PREPARATION' WHERE sgd.saleGroupFk = vSaleGroupFk; @@ -67615,30 +67615,30 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sectorCollection_new`(vSectorFk INT) -BEGIN -/** - * Inserta una nueva colección, si el usuario no tiene ninguna vacia. - * Esto se hace para evitar que por error se generen colecciones sin sentido. - * - * @param vSectorFk Identificador de #vn.sector - */ - DECLARE hasEmptyCollections BOOL; - DECLARE vUserFk INT; - - SET vUserFk = account.myUser_getId(); - - SELECT (COUNT(sc.id) > 0) INTO hasEmptyCollections - FROM vn.sectorCollection sc - LEFT JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id - WHERE ISNULL(scsg.id) - AND sc.userFk = vUserFk - AND sc.sectorFk = vSectorFk - AND sc.created >= util.VN_CURDATE(); - - IF NOT hasEmptyCollections THEN - INSERT INTO vn.sectorCollection(userFk, sectorFk) - VALUES(vUserFk, vSectorFk); - END IF; +BEGIN +/** + * Inserta una nueva colección, si el usuario no tiene ninguna vacia. + * Esto se hace para evitar que por error se generen colecciones sin sentido. + * + * @param vSectorFk Identificador de #vn.sector + */ + DECLARE hasEmptyCollections BOOL; + DECLARE vUserFk INT; + + SET vUserFk = account.myUser_getId(); + + SELECT (COUNT(sc.id) > 0) INTO hasEmptyCollections + FROM vn.sectorCollection sc + LEFT JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id + WHERE ISNULL(scsg.id) + AND sc.userFk = vUserFk + AND sc.sectorFk = vSectorFk + AND sc.created >= util.VN_CURDATE(); + + IF NOT hasEmptyCollections THEN + INSERT INTO vn.sectorCollection(userFk, sectorFk) + VALUES(vUserFk, vSectorFk); + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -67774,7 +67774,7 @@ BEGIN SELECT s.warehouseFk FROM vn.sector s WHERE s.id = vSectorFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -67869,10 +67869,10 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `shelvingChange`(IN `vShelvingO` VAR BEGIN UPDATE vn.itemShelving - SET shelvingFk = vShelvingD COLLATE utf8_unicode_ci - WHERE shelvingFk = vShelvingO COLLATE utf8_unicode_ci; - - + SET shelvingFk = vShelvingD COLLATE utf8_unicode_ci + WHERE shelvingFk = vShelvingO COLLATE utf8_unicode_ci; + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -67891,16 +67891,16 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `shelvingLog_get`(shelvingFk VARCHAR(10)) BEGIN - + /* Lista el log de un carro - * + * * @param shelvingFk matrícula del carro - * + * */ - + SELECT originFk, name, creationDate, description FROM shelvingLog sl - JOIN account.user u ON u.id = sl.userFk + JOIN account.user u ON u.id = sl.userFk WHERE sl.originFk = shelvingFk COLLATE utf8_general_ci ORDER BY creationDate DESC; @@ -67923,22 +67923,22 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `shelvingParking_get`(vShelvingFk VARCHAR(10), vWarehouseFk INT, vDayRange INT) BEGIN - -SELECT s.itemFk, + +SELECT s.itemFk, s.concept, - CAST(SUM(s.quantity) AS DECIMAL(10,0)) as sinServir, - CAST(IFNULL(ist.visible,0) AS DECIMAL(10,0)) as aparcado + CAST(SUM(s.quantity) AS DECIMAL(10,0)) as sinServir, + CAST(IFNULL(ist.visible,0) AS DECIMAL(10,0)) as aparcado FROM vn.sale s LEFT JOIN vn.itemShelvingSale iss ON iss.saleFk = s.id JOIN vn.ticket t ON t.id = s.ticketFk LEFT JOIN vn.itemShelvingStock ist ON ist.itemFk = s.itemFk AND ist.warehouseFk = vWarehouseFk JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk AND ish.shelvingFk = vShelvingFk COLLATE utf8_general_ci - WHERE t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(TIMESTAMPADD(DAY, GREATEST(0,vDayRange), util.VN_CURDATE())) + WHERE t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(TIMESTAMPADD(DAY, GREATEST(0,vDayRange), util.VN_CURDATE())) AND iss.saleFk IS NULL AND t.warehouseFk = vWarehouseFk GROUP BY s.itemFk HAVING sinServir > aparcado; - + END ;; DELIMITER ; @@ -67983,12 +67983,12 @@ BEGIN DELETE FROM vn.shelving WHERE length(code) > 3 AND parked < TIMESTAMPADD(WEEK,-1,util.VN_CURDATE()); - + DELETE FROM vn.itemShelving WHERE visible <= 0 AND created < TIMESTAMPADD(MONTH,-1,util.VN_CURDATE()); - DELETE ish.* + DELETE ish.* FROM vn.itemShelving ish JOIN vn.shelving sh ON sh.code = ish.shelvingFk WHERE sh.parkingFk IS NULL @@ -67996,12 +67996,12 @@ BEGIN UPDATE vn.shelving sh LEFT JOIN vn.itemShelving its ON its.shelvingFk = sh.`code` - SET isPrinted = 0, + SET isPrinted = 0, parkingFk = NULL WHERE its.id IS NULL - AND sh.isRecyclable - AND ( sh.parked IS NULL - OR + AND sh.isRecyclable + AND ( sh.parked IS NULL + OR sh.parked < TIMESTAMPADD(MONTH,-1,util.VN_CURDATE()) ); @@ -68178,20 +68178,20 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `solunionRiskRequest`() BEGIN - + DROP TEMPORARY TABLE IF EXISTS tmp.client_list; CREATE TEMPORARY TABLE tmp.client_list (PRIMARY KEY (Id_Cliente)) ENGINE = MEMORY - SELECT * FROM (SELECT cc.client Id_Cliente, ci.grade FROM vn.creditClassification cc + SELECT * FROM (SELECT cc.client Id_Cliente, ci.grade FROM vn.creditClassification cc JOIN vn.creditInsurance ci ON cc.id = ci.creditClassification WHERE dateEnd IS NULL ORDER BY ci.creationDate DESC LIMIT 10000000000000000000) t1 GROUP BY Id_Cliente; - + CALL vn2008.risk_vs_client_list(util.VN_CURDATE()); - - SELECT + + SELECT c.Id_Cliente, c.Cliente, c.Credito credito_vn, c.creditInsurance solunion, cast(r.risk as DECIMAL(10,0)) riesgo_vivo, cast(c.creditInsurance - r.risk as decimal(10,0)) margen_vivo, f.Consumo consumo_anual, c.Vencimiento, ci.grade @@ -68201,7 +68201,7 @@ BEGIN JOIN tmp.client_list ci ON c.Id_Cliente = ci.Id_Cliente JOIN bi.facturacion_media_anual f ON c.Id_Cliente = f.Id_Cliente GROUP BY Id_cliente; - + DROP TEMPORARY TABLE IF EXISTS tmp.risk; DROP TEMPORARY TABLE IF EXISTS tmp.client_list; END ;; @@ -68416,10 +68416,10 @@ BEGIN DECLARE vBossId INT; DECLARE vDone BOOL; DECLARE workerCur CURSOR FOR - SELECT workerFk - FROM tmp.subordinate + SELECT workerFk + FROM tmp.subordinate WHERE NOT isChecked; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; DECLARE EXIT HANDLER FOR 1062 BEGIN @@ -68427,29 +68427,29 @@ BEGIN END; DROP TEMPORARY TABLE IF EXISTS tmp.subordinate; - + CREATE TEMPORARY TABLE tmp.subordinate (PRIMARY KEY (workerFk)) ENGINE = MEMORY SELECT vBossFk AS workerFk, 0 AS isChecked; - + WHILE (SELECT COUNT(*) FROM tmp.subordinate WHERE NOT isChecked) > 0 DO OPEN workerCur; workerLoop: LOOP SET vDone = FALSE; FETCH workerCur INTO vBossId; - + IF vDone THEN LEAVE workerLoop; END IF; - - INSERT INTO tmp.subordinate - SELECT id, 0 - FROM worker + + INSERT INTO tmp.subordinate + SELECT id, 0 + FROM worker WHERE bossFk = vBossId; - - UPDATE tmp.subordinate + + UPDATE tmp.subordinate SET isChecked = 1 WHERE workerFk = vBossId; END LOOP; @@ -68489,13 +68489,13 @@ BEGIN -- Calcula el balance inicial y final de cada proveedor INSERT INTO openingBalance SELECT MAX(dueDated), - supplierFk, - companyFk, + supplierFk, + companyFk, sum(amount) eurAmount, sum(divisa) foreignAmount FROM ( SELECT p.dueDated, - p.supplierFk, + p.supplierFk, p.companyFk, p.amount, p.divisa @@ -68511,7 +68511,7 @@ BEGIN SELECT iidd.dueDated, ii.supplierFk, ii.companyFk, - - iidd.amount, + - iidd.amount, - iidd.foreignValue FROM invoiceIn ii JOIN invoiceInDueDay iidd ON ii.id = iidd.invoiceInFk @@ -68519,14 +68519,14 @@ BEGIN JOIN company co ON co.id = ii.companyFk WHERE iidd.dueDated > '2014-12-31' AND iidd.dueDated <= vEnded - AND ii.isBooked AND co.`code` = 'VNL' + AND ii.isBooked AND co.`code` = 'VNL' AND c.`code` <> 'EUR' UNION ALL SELECT se.dueDated, se.supplierFk, se.companyFk, - - se.amount, + - se.amount, 0 FROM supplierExpense se JOIN currency c ON c.id = se.currencyFk @@ -68536,7 +68536,7 @@ BEGIN AND co.`code` = 'VNL' AND c.`code` <> 'EUR' ) sub GROUP BY companyFk, supplierFk; - + SELECT ob.dueDated , ob.supplierFk , ob.companyFk @@ -68750,7 +68750,7 @@ BEGIN - SUM(iid.amount) mysql, 0 sage FROM invoiceInDueDay iid - JOIN invoiceIn ii ON ii.id = iid.invoiceInFk + JOIN invoiceIn ii ON ii.id = iid.invoiceInFk WHERE IFNULL(ii.bookEntried, ii.issued) BETWEEN vDateFrom AND vDateTo AND ii.isBooked GROUP BY ii.id @@ -68889,15 +68889,15 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketBoxesView`(IN vTicketFk INT) BEGIN - - SELECT s.id, - s.itemFk, - s.concept, - floor(s.quantity / b.packing) as Cajas, - b.packing, - s.isPicked, + + SELECT s.id, + s.itemFk, + s.concept, + floor(s.quantity / b.packing) as Cajas, + b.packing, + s.isPicked, i.size - FROM ticket t + FROM ticket t JOIN sale s ON s.ticketFk = t.id JOIN item i ON i.id = s.itemFk JOIN cache.last_buy lb on lb.warehouse_id = t.warehouseFk AND lb.item_id = s.itemFk @@ -68908,7 +68908,7 @@ BEGIN AND p.isBox GROUP BY s.itemFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -68930,7 +68930,7 @@ BEGIN DECLARE vDateStart DATETIME DEFAULT DATE(vDate); DECLARE vDateEnd DATETIME DEFAULT util.dayEnd(vDate); - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketBuiltTime; CREATE TEMPORARY TABLE tmp.ticketBuiltTime @@ -68943,7 +68943,7 @@ BEGIN SELECT ticketFk, builtTime FROM ( - SELECT + SELECT ticketFk, created as builtTime FROM @@ -68951,13 +68951,13 @@ BEGIN WHERE created BETWEEN vDateStart AND vDateEnd ORDER BY ticketFk, created DESC LIMIT 10000000000000000000 - ) sub + ) sub GROUP BY ticketFk ) sub2 ON sub2.ticketFk = t.id WHERE t.shipped BETWEEN vDate AND util.dayEnd(vDate) AND t.clientFk NOT IN (50,400,200) AND t.companyFk = 442 - + ; END ;; @@ -68986,30 +68986,30 @@ BEGIN */ REPLACE INTO orderTicket(orderFk,ticketFk) - SELECT orderFk, vTicketNew - FROM orderTicket + SELECT orderFk, vTicketNew + FROM orderTicket WHERE ticketFk = vTicketOld; - + -- Bionizamos lineas con Preu = 0 CREATE OR REPLACE TEMPORARY TABLE tmp.recalculateSales (PRIMARY KEY (id)) ENGINE = MEMORY - SELECT id + SELECT id FROM sale WHERE ticketFk = vTicketNew AND price = 0; - + CALL sale_recalcComponent(1); -- Bionizamos lineas con Preu > 0 CREATE OR REPLACE TEMPORARY TABLE tmp.recalculateSales (PRIMARY KEY (id)) ENGINE = MEMORY - SELECT id + SELECT id FROM sale WHERE ticketFk = vTicketNew AND price > 0; - + CALL sale_recalcComponent(6); DROP TEMPORARY TABLE IF EXISTS tmp.recalculateSales; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -69032,12 +69032,12 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketCalculateFromType`( vLanded D vTypeFk INT) BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.item; - CREATE TEMPORARY TABLE tmp.item - (INDEX (itemFk)) - ENGINE = MEMORY + CREATE TEMPORARY TABLE tmp.item + (INDEX (itemFk)) + ENGINE = MEMORY SELECT id itemFk FROM vn.item WHERE typeFk = vTypeFk; - + CALL catalog_calculate(vLanded, vAddressFk, vAgencyModeFk); DROP TEMPORARY TABLE tmp.item; DROP TEMPORARY TABLE tmp.ticketLot; @@ -69059,7 +69059,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketCalculatePurge`() BEGIN - DROP TEMPORARY TABLE + DROP TEMPORARY TABLE tmp.ticketCalculateItem, tmp.ticketComponentPrice, tmp.ticketComponent, @@ -69083,56 +69083,56 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketClon`(vTicketFk INT, vNewShipped DATE) BEGIN - + DECLARE done INT DEFAULT FALSE; - DECLARE vNewTicketFk INT; + DECLARE vNewTicketFk INT; DECLARE vOldSaleFk INT; DECLARE vNewSaleFk INT; - + DECLARE cur1 CURSOR FOR SELECT id FROM vn.sale WHERE ticketFk = vTicketFk; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - + SET vNewShipped = IFNULL(vNewShipped, util.VN_CURDATE()); - + CALL vn.ticket_Clone(vTicketFk, vNewTicketFk); - - UPDATE vn.ticket + + UPDATE vn.ticket SET landed = TIMESTAMPADD(DAY, DATEDIFF(vNewShipped, shipped), landed), shipped = vNewShipped WHERE id = vNewTicketFk; - + OPEN cur1; - + read_loop: LOOP - + FETCH cur1 INTO vOldSaleFk; - + IF done THEN LEAVE read_loop; END IF; - + INSERT INTO vn.sale(ticketFk, itemFk, quantity, concept, price, discount, priceFixed, isPriceFixed) SELECT vNewTicketFk, itemFk, quantity, concept, price, discount, priceFixed, isPriceFixed FROM vn.sale WHERE id = vOldSaleFk; - + SELECT max(id) INTO vNewSaleFk FROM vn.sale WHERE ticketFk = vNewTicketFk; - + INSERT INTO vn.saleComponent(saleFk, componentFk, value, isGreuge) SELECT vNewSaleFk, componentFk, value, isGreuge FROM vn.saleComponent WHERE saleFk = vOldSaleFk; - + END LOOP; CLOSE cur1; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -69154,18 +69154,18 @@ BEGIN DECLARE vShipped DATE; DECLARE vMaxDated DATE; - - SELECT shipped, TIMESTAMPADD(YEAR,1,shipped) + + SELECT shipped, TIMESTAMPADD(YEAR,1,shipped) INTO vShipped, vMaxDated FROM vn.ticket WHERE id = vTicketFk; - + WHILE vShipped <= vMaxDated DO - + SET vShipped = TIMESTAMPADD(WEEK, 1, vShipped); - + CALL vn.ticketClon(vTicketFk, vShipped); - + END WHILE; END ;; @@ -69187,10 +69187,10 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketCollection_get`(vTicketFk INT) BEGIN - SELECT tc.collectionFk + SELECT tc.collectionFk FROM vn.ticketCollection tc WHERE ticketFk = vTicketFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -69209,18 +69209,18 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketCollection_setUsedShelves`(vTicketFk INT, vUsedShelves INT) BEGIN - + /* * Inserta número de baldas que ocupa un ticket - * + * * @param vTicketFk Identificador de ticket * @param vUsedShelves Número de baldas */ - + UPDATE ticketCollection tc SET tc.usedShelves = vUsedShelves WHERE tc.ticketFk = vTicketFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -69258,18 +69258,18 @@ BEGIN END; START TRANSACTION; - + IF (SELECT addressFk FROM ticket WHERE id = vTicketFk) <> vAddressFk THEN - - UPDATE ticket t + + UPDATE ticket t JOIN address a ON a.id = vAddressFk SET t.nickname = a.nickname WHERE t.id = vTicketFk; - + END IF; - + UPDATE ticket t - SET + SET t.clientFk = vClientFk, t.agencyModeFk = vAgencyModeFk, t.addressFk = vAddressFk, @@ -69280,12 +69280,12 @@ BEGIN t.isDeleted = vIsDeleted WHERE t.id = vTicketFk; - + IF vHasToBeUnrouted THEN UPDATE ticket t SET t.routeFk = NULL WHERE t.id = vTicketFk; END IF; - + IF vOption <> 8 THEN DROP TEMPORARY TABLE IF EXISTS tmp.sale; CREATE TEMPORARY TABLE tmp.sale @@ -69327,104 +69327,104 @@ BEGIN DECLARE vComponentFk INT; DECLARE vRenewComponents BOOLEAN; DECLARE vKeepPrices BOOLEAN; - + CASE vOption - WHEN 1 THEN + WHEN 1 THEN SET vRenewComponents = TRUE; SET vKeepPrices = FALSE; WHEN 2 THEN - SELECT id INTO vComponentFk FROM component WHERE `code` = 'debtCollection'; + SELECT id INTO vComponentFk FROM component WHERE `code` = 'debtCollection'; SET vRenewComponents = TRUE; SET vKeepPrices = TRUE; - WHEN 3 THEN - SELECT id INTO vComponentFk FROM component WHERE `code` = 'mana'; - SET vRenewComponents = TRUE; - SET vKeepPrices = TRUE; - WHEN 4 THEN - SELECT id INTO vComponentFk FROM component WHERE `code` = 'buyerDiscount'; + WHEN 3 THEN + SELECT id INTO vComponentFk FROM component WHERE `code` = 'mana'; SET vRenewComponents = TRUE; SET vKeepPrices = TRUE; - /* WHEN 5 THEN + WHEN 4 THEN + SELECT id INTO vComponentFk FROM component WHERE `code` = 'buyerDiscount'; + SET vRenewComponents = TRUE; + SET vKeepPrices = TRUE; + /* WHEN 5 THEN SET vComponentFk = 35; SET vRenewComponents = TRUE; SET vKeepPrices = TRUE;*/ - WHEN 6 THEN + WHEN 6 THEN SELECT id INTO vComponentFk FROM component WHERE `code` = 'imbalance'; SET vRenewComponents = TRUE; SET vKeepPrices = TRUE; WHEN 7 THEN REPLACE INTO saleComponent(saleFk, componentFk, value) - SELECT s.id, 28, ROUND(((s.price * (100 - s.discount) / 100) - SUM(IFNULL(sc.value, 0))) * 0.8, 3) + SELECT s.id, 28, ROUND(((s.price * (100 - s.discount) / 100) - SUM(IFNULL(sc.value, 0))) * 0.8, 3) FROM sale s JOIN tmp.sale tmps ON tmps.saleFk = s.id - LEFT JOIN saleComponent sc ON sc.saleFk = s.id + LEFT JOIN saleComponent sc ON sc.saleFk = s.id AND sc.componentFk NOT IN (28, 29) GROUP BY s.id; - + REPLACE INTO saleComponent(saleFk, componentFk, value) - SELECT s.id, 29, ROUND(((s.price * (100 - s.discount) / 100) - SUM(IFNULL(sc.value, 0))) * 0.2, 3) + SELECT s.id, 29, ROUND(((s.price * (100 - s.discount) / 100) - SUM(IFNULL(sc.value, 0))) * 0.2, 3) FROM sale s JOIN tmp.sale tmps ON tmps.saleFk = s.id - LEFT JOIN saleComponent sc ON sc.saleFk = s.id + LEFT JOIN saleComponent sc ON sc.saleFk = s.id AND sc.componentFk NOT IN (28, 29) GROUP BY s.id; - + SET vRenewComponents = FALSE; SET vKeepPrices = FALSE; WHEN 8 THEN - DELETE sc.* + DELETE sc.* FROM tmp.sale tmps JOIN saleComponent sc ON sc.saleFk = tmps.saleFk; - + REPLACE INTO saleComponent(saleFk, componentFk, value) - SELECT s.id, 28, ROUND(((s.price * (100 - s.discount) / 100)), 3) + SELECT s.id, 28, ROUND(((s.price * (100 - s.discount) / 100)), 3) FROM sale s JOIN tmp.sale tmps ON tmps.saleFk = s.id; - + SET vRenewComponents = FALSE; SET vKeepPrices = FALSE; - WHEN 9 THEN + WHEN 9 THEN SET vRenewComponents = TRUE; SET vKeepPrices = TRUE; END CASE; IF vRenewComponents THEN - DELETE sc.* - FROM tmp.sale tmps + DELETE sc.* + FROM tmp.sale tmps JOIN saleComponent sc ON sc.saleFk = tmps.saleFk JOIN `component` c ON c.id = sc.componentFk WHERE c.isRenewable; - + REPLACE INTO saleComponent(saleFk, componentFk, value) SELECT s.id, tc.componentFk, tc.cost - FROM sale s + FROM sale s JOIN tmp.sale tmps ON tmps.saleFk = s.id JOIN tmp.ticketComponent tc ON tc.itemFk = s.itemFk AND tc.warehouseFk = tmps.warehouseFk - LEFT JOIN saleComponent sc ON sc.saleFk = s.id - AND sc.componentFk = tc.componentFk - LEFT JOIN `component` c ON c.id = tc.componentFk + LEFT JOIN saleComponent sc ON sc.saleFk = s.id + AND sc.componentFk = tc.componentFk + LEFT JOIN `component` c ON c.id = tc.componentFk WHERE IF(sc.componentFk IS NULL AND NOT c.isRenewable, FALSE, TRUE); - - -- Añadir componente venta por paquete + + -- Añadir componente venta por paquete DROP TEMPORARY TABLE IF EXISTS tmp.sale2; CREATE TEMPORARY TABLE tmp.sale2 (PRIMARY KEY (saleFk)) - ENGINE = MEMORY + ENGINE = MEMORY SELECT * FROM tmp.sale; - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent2; CREATE TEMPORARY TABLE tmp.ticketComponent2 - SELECT * FROM tmp.ticketComponent; - - REPLACE INTO saleComponent(saleFk, componentFk, value) + SELECT * FROM tmp.ticketComponent; + + REPLACE INTO saleComponent(saleFk, componentFk, value) SELECT t.id, t.componentFk, t.cost FROM ( SELECT s.id, tc.componentFk, tc.cost, MOD(s.quantity, b.packing) as resto FROM vn.sale s JOIN tmp.sale tmps ON tmps.saleFk = s.id - JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND tmps.warehouseFk = lb.warehouse_id + JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND tmps.warehouseFk = lb.warehouse_id JOIN vn.buy b ON b.id = buy_id JOIN tmp.ticketComponent tc ON tc.itemFk = s.itemFk AND tc.warehouseFk = tmps.warehouseFk - JOIN `component` c ON c.id = tc.componentFk AND c.code = 'salePerPackage' + JOIN `component` c ON c.id = tc.componentFk AND c.code = 'salePerPackage' LEFT JOIN ( SELECT s.id FROM vn.sale s @@ -69435,8 +69435,8 @@ BEGIN ) tp ON tp.id = s.id WHERE tp.id IS NULL HAVING resto <> 0) t; - - DROP TEMPORARY TABLE IF EXISTS + + DROP TEMPORARY TABLE IF EXISTS tmp.sale2, tmp.ticketComponent2; END IF; @@ -69454,26 +69454,26 @@ BEGIN UPDATE sale s JOIN item i on i.id = s.itemFk JOIN itemType it on it.id = i.typeFk - JOIN (SELECT SUM(sc.value) sumValue, sc.saleFk + JOIN (SELECT SUM(sc.value) sumValue, sc.saleFk FROM saleComponent sc JOIN tmp.sale tmps ON tmps.saleFk = sc.saleFk GROUP BY sc.saleFk) sc ON sc.saleFk = s.id SET s.price = sumValue / ((100 - s.discount) / 100) - WHERE it.code != 'PRT' ; - + WHERE it.code != 'PRT' ; + REPLACE INTO saleComponent(saleFk, componentFk, value) SELECT s.id, 21, ROUND((s.price * (100 - s.discount) / 100) - SUM(value), 3) saleValue FROM sale s JOIN tmp.sale tmps ON tmps.saleFk = s.id LEFT JOIN saleComponent sc ON sc.saleFk = s.id WHERE sc.componentFk != 21 - GROUP BY s.id + GROUP BY s.id HAVING ROUND(saleValue, 4) <> 0; END IF; - + UPDATE sale s JOIN ( - SELECT SUM(sc.value) sumValue, sc.saleFk + SELECT SUM(sc.value) sumValue, sc.saleFk FROM saleComponent sc JOIN tmp.sale tmps ON tmps.saleFk = sc.saleFk JOIN `component` c ON c.id = sc.componentFk @@ -69487,10 +69487,10 @@ BEGIN JOIN sale s on s.id = sc.saleFk JOIN item i ON i.id = s.itemFk JOIN itemType it ON it.id = i.typeFk - WHERE it.code = 'PRT'; - + WHERE it.code = 'PRT'; + INSERT INTO saleComponent(saleFk, componentFk, value) - SELECT s.id, 15, s.price + SELECT s.id, 15, s.price FROM sale s JOIN tmp.sale tmps ON tmps.saleFk = s.id JOIN item i ON i.id = s.itemFK @@ -69557,24 +69557,24 @@ BEGIN CREATE TEMPORARY TABLE tmp.ticket ENGINE = MEMORY SELECT vTicketFk ticketFk; - + CALL vn.ticket_getTax(NULL); - SELECT + SELECT tt.ticketFk, CAST(tt.taxableBase AS DECIMAL(10, 2)) AS taxableBase, CAST(tt.rate * tt.taxableBase / 100 AS DECIMAL(10, 2)) AS tax, - pgc.*, + pgc.*, CAST(IF(pe.equFk IS NULL, taxableBase, 0) AS DECIMAL(10, 2)) AS Base, pgc.rate / 100 as vatPercent FROM tmp.ticketTax tt JOIN vn.pgc ON pgc.code = tt.pgcFk LEFT JOIN vn.pgcEqu pe ON pe.equFk = pgc.code; - + DROP TEMPORARY TABLE tmp.ticket; DROP TEMPORARY TABLE tmp.ticketTax; DROP TEMPORARY TABLE tmp.ticketAmount; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -69612,29 +69612,29 @@ BEGIN JOIN ticket t ON t.id = tmpTicket.ticketFk; CALL addressTaxArea (); - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketTax; CREATE TEMPORARY TABLE tmp.ticketTax (INDEX (ticketFk)) ENGINE = MEMORY SELECT tmpTicket.ticketFk, bp.pgcFk, - SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2) + SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2) ) AS taxableBase, SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2) ) * pgc.rate / 100 AS tax, tc.code - + FROM tmp.ticket tmpTicket JOIN sale s ON s.ticketFk = tmpTicket.ticketFk JOIN item i ON i.id = s.itemFk JOIN ticket t ON t.id = tmpTicket.ticketFk JOIN supplier su ON su.id = t.companyFk - JOIN tmp.addressTaxArea ata + JOIN tmp.addressTaxArea ata ON ata.addressFk = t.addressFk AND ata.companyFk = t.companyFk - JOIN itemTaxCountry itc + JOIN itemTaxCountry itc ON itc.itemFk = i.id AND itc.countryFk = su.countryFk - JOIN bookingPlanner bp + JOIN bookingPlanner bp ON bp.countryFk = su.countryFk AND bp.taxAreaFk = ata.areaFk AND bp.taxClassFk = itc.taxClassFk @@ -69642,7 +69642,7 @@ BEGIN JOIN taxClass tc ON tc.id = bp.taxClassFk GROUP BY tmpTicket.ticketFk, pgc.code HAVING taxableBase != 0; - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketAmount; CREATE TEMPORARY TABLE tmp.ticketAmount (INDEX (ticketFk)) @@ -69653,7 +69653,7 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.addressCompany; DROP TEMPORARY TABLE IF EXISTS tmp.addressTaxArea; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -69674,7 +69674,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketGetTotal`(vTaxArea VARCHAR(25 BEGIN /** * Calcula el total con IVA para un conjunto de tickets. - * + * * @param vTaxArea * @table tmp.ticket(ticketFk) Identificadores de los tickets a calcular * @return tmp.ticketTotal Total para cada ticket @@ -69691,7 +69691,7 @@ BEGIN FROM tmp.ticket t LEFT JOIN tmp.ticketAmount ta ON t.ticketFk = ta.ticketFk GROUP BY ticketFk; - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketAmount; DROP TEMPORARY TABLE IF EXISTS tmp.ticketTax; END ;; @@ -69763,18 +69763,18 @@ BEGIN DECLARE vParked DATETIME; DECLARE vLevel INT; DECLARE vCollectionFk INT; - - SELECT IFNULL(`level`,0), IFNULL(collectionFk,0) + + SELECT IFNULL(`level`,0), IFNULL(collectionFk,0) INTO vLevel, vCollectionFk FROM vn.ticketCollection WHERE ticketFk = vTicketFk LIMIT 1; - - SELECT created, parkingFk + + SELECT created, parkingFk INTO vParked, vParkingFk FROM vn.ticketParking WHERE ticketFk = vTicketFk; - + SELECT tp.ticketFk, CONCAT(tc.collectionFk, ' - ', tc.level) coleccion, tp.created, p.code, am.name as Agencia FROM vn.ticketParking tp JOIN vn.parking p ON p.id = tp.parkingFk @@ -69801,7 +69801,7 @@ BEGIN AND sc.isPackagingArea AND tp.created < vParked AND t.packages <=> 0); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -69822,7 +69822,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketNotInvoicedByClient`(vClientF BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.ticket; - + CREATE TEMPORARY TABLE tmp.ticket SELECT id ticketFk FROM ticket @@ -69832,7 +69832,7 @@ BEGIN CALL vn.ticketGetTotal(NULL); - SELECT c.id, + SELECT c.id, c.name as Cliente, t.shipped as Fecha, t.id as Id_Ticket, @@ -69843,7 +69843,7 @@ BEGIN DROP TEMPORARY TABLE tmp.ticket, - tmp.ticketTotal; + tmp.ticketTotal; END ;; DELIMITER ; @@ -69863,21 +69863,21 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketObservation_addNewBorn`(vTicketFk INT) BEGIN - + /** * Inserta observaciones para los tickets con clientes nuevos o recuperados - * + * * @param vTicketFk Identificador de vn.ticket */ - + DECLARE vDescription VARCHAR(20) DEFAULT '¡Cliente NUEVO! '; INSERT INTO vn.ticketObservation(ticketFk, observationTypeFk, description) SELECT vTicketFk, ot.id, vDescription FROM vn.observationType ot WHERE ot.hasNewBornMessage - ON DUPLICATE KEY UPDATE description = CONCAT(vDescription, ticketObservation.description); - + ON DUPLICATE KEY UPDATE description = CONCAT(vDescription, ticketObservation.description); + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -69917,7 +69917,7 @@ BEGIN DECLARE vComponentCost INT; DECLARE vDone INT DEFAULT FALSE; DECLARE vClientId INT; - + DECLARE vCursor CURSOR FOR SELECT DISTINCT clientFk FROM ( @@ -69934,31 +69934,31 @@ BEGIN RESIGNAL; END; - SELECT id INTO vWarehouseInventory - FROM warehouse + SELECT id INTO vWarehouseInventory + FROM warehouse WHERE `code`= 'inv'; - - SELECT id INTO vComponentCost - FROM component + + SELECT id INTO vComponentCost + FROM component WHERE `code`= 'purchaseValue'; - - SELECT packagingInvoicingDated INTO vDateStart - FROM ticketConfig; - + + SELECT packagingInvoicingDated INTO vDateStart + FROM ticketConfig; + IF vWarehouseInventory IS NULL THEN CALL util.throw('Warehouse inventory not set'); END IF; IF vComponentCost IS NULL THEN CALL util.throw('Component cost not set'); - END IF; + END IF; SET vDateEnd = vDated + INTERVAL 1 DAY; - + IF NOT vWithoutPeriodGrace THEN SET vGraceDate = vGraceDate -INTERVAL 1 MONTH; END IF; - + DROP TEMPORARY TABLE IF EXISTS tmp.packagingToInvoice; CREATE TEMPORARY TABLE tmp.packagingToInvoice (INDEX (clientFk)) @@ -69971,7 +69971,7 @@ BEGIN t.clientFk FROM ticketPackaging tp JOIN packaging p ON p.id = tp.packagingFk - JOIN ticket t ON t.id = tp.ticketFk + JOIN ticket t ON t.id = tp.ticketFk JOIN client c ON c.id = t.clientFk WHERE c.isActive AND (vClientFk IS NULL OR t.clientFk = vClientFk) @@ -69979,7 +69979,7 @@ BEGIN AND (tp.quantity < 0 OR (tp.quantity > 0 AND t.shipped < vGraceDate)) AND tp.quantity AND p.itemFk; - + OPEN vCursor; l: LOOP @@ -69992,25 +69992,25 @@ BEGIN START TRANSACTION; CALL ticket_add( - vClientId, + vClientId, vDateEnd, - vWarehouseInventory, - vCompanyFk, - NULL, - NULL, - NULL, - vDateEnd, - account.myUser_getId(), + vWarehouseInventory, + vCompanyFk, + NULL, + NULL, + NULL, + vDateEnd, + account.myUser_getId(), TRUE, vNewTicket); - + INSERT INTO ticketPackaging(ticketFk, packagingFk, quantity, pvp) SELECT vNewTicket, packagingFk, - SUM(quantity) totalQuantity, price - FROM tmp.packagingToInvoice + FROM tmp.packagingToInvoice WHERE clientFk = vClientId GROUP BY packagingFk HAVING IF(vWithoutPeriodGrace, totalQuantity <> 0, totalQuantity < 0); - + INSERT INTO sale(ticketFk, itemFk, concept, quantity, price) SELECT vNewTicket, pti.itemFk, i.name, SUM(pti.quantity) totalQuantity, pti.price FROM tmp.packagingToInvoice pti @@ -70018,12 +70018,12 @@ BEGIN WHERE pti.clientFk = vClientId GROUP BY pti.itemFk HAVING IF(vWithoutPeriodGrace, totalQuantity <> 0, totalQuantity > 0); - + INSERT INTO saleComponent(saleFk, componentFk, value) SELECT id, vComponentCost, price FROM sale WHERE ticketFk = vNewTicket; - + COMMIT; END LOOP; CLOSE vCursor; @@ -70047,37 +70047,37 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketParking_findSkipped`(vTicketFk INT, vItemPackingTypeFk VARCHAR(1)) BEGIN - + /** * Averigua los tickets que se han saltado por un error en el proceso encajado * @param vTicketFk Ticket * @param vItemPackingTypeFk Modo de encajado * @return un select con los tickets afectados - */ + */ DECLARE vParkingFk INT; DECLARE vParked DATETIME; DECLARE vLevel INT; DECLARE vWagon INT; DECLARE vCollectionFk INT; - - SELECT IFNULL(`level`,0), IFNULL(`wagon`,0),IFNULL(collectionFk,0) + + SELECT IFNULL(`level`,0), IFNULL(`wagon`,0),IFNULL(collectionFk,0) INTO vLevel, vWagon, vCollectionFk FROM vn.ticketCollection tc JOIN vn.collection c ON c.id = tc.collectionFk AND c.itemPackingTypeFk = vItemPackingTypeFk WHERE ticketFk = vTicketFk ORDER BY c.id DESC LIMIT 1; - - SELECT created, parkingFk + + SELECT created, parkingFk INTO vParked, vParkingFk FROM vn.ticketParking tp - JOIN vn.parking p ON p.id = tp.parkingFk - JOIN vn.sector s ON s.id = p.sectorFk + JOIN vn.parking p ON p.id = tp.parkingFk + JOIN vn.sector s ON s.id = p.sectorFk WHERE ticketFk = vTicketFk AND s.itemPackingTypeFk = vItemPackingTypeFk AND s.isPackagingArea ; - + SELECT tp.ticketFk, CONCAT(tc.collectionFk, ' ', tc.wagon, ' - ', tc.level) coleccion, tp.created, p.code, am.name as Agencia FROM vn.ticketParking tp JOIN vn.parking p ON p.id = tp.parkingFk @@ -70094,9 +70094,9 @@ BEGIN AND ( ( IFNULL(tc.collectionFk,-1) != IFNULL(@vCollectionFk,0) AND tp.created < vParked ) OR - ( tc.collectionFk = vCollectionFk + ( tc.collectionFk = vCollectionFk AND (LEFT(tc.wagon,1) < LEFT(vWagon,1) - OR (LEFT(tc.wagon,1) = LEFT(vWagon,1) AND LEFT(tc.level,1) < LEFT(vLevel,1))) + OR (LEFT(tc.wagon,1) = LEFT(vWagon,1) AND LEFT(tc.level,1) < LEFT(vLevel,1))) ) ) ) -- Etiquetas que no se han escaneado y ya estamos con una posterior @@ -70104,7 +70104,7 @@ BEGIN (s.alertLevel > 1 AND tp.parkingFk = vParkingFk AND sc.isPackagingArea - AND tp.created < vParked + AND tp.created < vParked AND t.packages <=> 0); END ;; DELIMITER ; @@ -70156,11 +70156,11 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketRequest_Add`(vDescription VARCHAR(255), vQuantity INT, vPrice DOUBLE, vTicketFk INT, vBuyerCode VARCHAR(3)) BEGIN - INSERT INTO vn.ticketRequest(description, - quantity, - price, - ticketFk, - buyerCode, + INSERT INTO vn.ticketRequest(description, + quantity, + price, + ticketFk, + buyerCode, requesterFk) VALUES(vDescription, vQuantity, @@ -70168,7 +70168,7 @@ BEGIN vTicketFk, vBuyerCode, vn.getUser()); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -70187,26 +70187,26 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketStateToday_setState`(vTicketFk INT, vStateCode VARCHAR(45)) BEGIN - + /* Modifica el estado de un ticket de hoy - * + * * @param vTicketFk el id del ticket * @param vStateCode estado a modificar del ticket - * + * */ - + DECLARE vAlertLevel INT; - - SELECT s.alertLevel INTO vAlertLevel - FROM state s - JOIN ticketStateToday tst ON tst.state = s.id + + SELECT s.alertLevel INTO vAlertLevel + FROM state s + JOIN ticketStateToday tst ON tst.state = s.id WHERE tst.ticket = vTicketFk LIMIT 1; - + IF vAlertLevel < 2 THEN - + CALL vn.ticket_setState(vTicketFk, vStateCode); - + END IF; END ;; @@ -70227,23 +70227,23 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketStateUpdate`(vTicketFk INT, vStateCode VARCHAR(45)) BEGIN - + /* * @deprecated:utilizar ticket_setState */ - + DECLARE vAlertLevel INT; - SELECT s.alertLevel INTO vAlertLevel + SELECT s.alertLevel INTO vAlertLevel FROM vn.state s JOIN vn.ticketState ts ON ts.stateFk = s.id WHERE ts.ticketFk = vTicketFk; - - IF !(vStateCode = 'ON_CHECKING' AND vAlertLevel > 1) THEN - + + IF !(vStateCode = 'ON_CHECKING' AND vAlertLevel > 1) THEN + INSERT INTO ticketTracking(stateFk, ticketFk, workerFk) SELECT id, vTicketFk, account.myUser_getId() - FROM vn.state + FROM vn.state WHERE `code` = vStateCode collate utf8_unicode_ci; END IF; @@ -70523,20 +70523,20 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_administrativeCopy`(vOriginalTicket INT, OUT vNewTicket INT) BEGIN - + INSERT INTO vn.ticket(clientFk, addressFk, shipped, warehouseFk, companyFk, landed) - SELECT t.clientFk , t.addressFk , t.shipped ,w.id, t.companyFk , t.landed + SELECT t.clientFk , t.addressFk , t.shipped ,w.id, t.companyFk , t.landed FROM vn.ticket t JOIN vn.warehouse w ON w.name = 'INVENTARIO' WHERE t.id = vOriginalTicket; - + SELECT LAST_INSERT_ID() INTO vNewTicket; INSERT INTO vn.sale(ticketFk, itemFk, concept, quantity, price, discount) - SELECT vNewTicket, s.itemFk , s.concept , s.quantity , s.price , s.discount + SELECT vNewTicket, s.itemFk , s.concept , s.quantity , s.price , s.discount FROM vn.sale s WHERE s.ticketFk = vOriginalTicket; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -70780,7 +70780,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_canMerge`(vDated DATE, vScop BEGIN /** * Devuelve un listado de tickets susceptibles de fusionarse con otros tickets en el futuro - * + * * @param vDated Fecha en cuestión * @param vScopeDays Dias en el futuro a sondear * @param vLitersMax Volumen máximo de los tickets a catapultar @@ -70861,10 +70861,10 @@ BEGIN * Comprueba que los tickets entre un rango de fechas tienen componentes * y recalcula sus componentes * - * @param vShippedFrom rango inicial de fecha + * @param vShippedFrom rango inicial de fecha * @param vShippedTo rango final de fecha */ - + CREATE OR REPLACE TEMPORARY TABLE tmp.coste (primary key (id)) ENGINE = MEMORY SELECT s.id @@ -70893,9 +70893,9 @@ BEGIN AND ic.merchandise; CALL vn.sale_recalcComponent(1); - + DROP TEMPORARY TABLE tmp.recalculateSales; - DROP TEMPORARY TABLE tmp.coste; + DROP TEMPORARY TABLE tmp.coste; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -71011,7 +71011,7 @@ BEGIN t.companyFk, t.addressFk, tt.agencyModeFk - FROM ticketWeekly tt + FROM ticketWeekly tt JOIN ticket t ON tt.ticketFk = t.id; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vIsDone = TRUE; @@ -71025,15 +71025,15 @@ BEGIN DECLARE vIsDuplicateMail BOOL; DECLARE vSubject VARCHAR(150); DECLARE vMessage TEXT; - + SET vIsDone = FALSE; FETCH rsTicket INTO vTicketFk, vWeekDay, vClientFk, vWarehouseFk, vCompanyFk, vAddressFk, vAgencyModeFk; IF vIsDone THEN LEAVE myLoop; END IF; - - SELECT dated INTO vShipment + + SELECT dated INTO vShipment FROM `time` WHERE `year` = vYear AND `week` = vWeek AND WEEKDAY(dated) = vWeekDay; @@ -71044,17 +71044,17 @@ BEGIN JOIN saleCloned sc ON sc.saleOriginalFk = saleOrig.id JOIN sale saleClon ON saleClon.id = sc.saleClonedFk JOIN ticket tClon ON tClon.id = saleClon.ticketFk - WHERE tOrig.id = vTicketFk - AND tClon.isDeleted = FALSE + WHERE tOrig.id = vTicketFk + AND tClon.isDeleted = FALSE AND DATE(tClon.shipped) = vShipment) THEN ITERATE myLoop; END IF; IF vAgencyModeFk IS NULL THEN - SELECT agencyModeFk INTO vAgencyModeFk + SELECT agencyModeFk INTO vAgencyModeFk FROM address - WHERE clientFk = vClientFk + WHERE clientFk = vClientFk AND isDefaultAddress; END IF; @@ -71075,8 +71075,8 @@ BEGIN FALSE, vNewTicket); - UPDATE ticket - SET clonedFrom = vTicketFk + UPDATE ticket + SET clonedFrom = vTicketFk WHERE id = vNewTicket; INSERT INTO sale (ticketFk, itemFk, concept, quantity, price, @@ -71095,7 +71095,7 @@ BEGIN INSERT IGNORE INTO saleCloned(saleOriginalFk, saleClonedFk) SELECT saleOriginal.id, saleClon.id FROM sale saleOriginal - JOIN sale saleClon ON saleOriginal.itemFk = saleClon.itemFk + JOIN sale saleClon ON saleOriginal.itemFk = saleClon.itemFk AND saleOriginal.quantity = saleClon.quantity WHERE saleOriginal.ticketFk = vTicketFk AND saleClon.ticketFk = vNewTicket; @@ -71125,7 +71125,7 @@ BEGIN buyed, requesterFk, attenderFk, - vNewTicket + vNewTicket FROM ticketRequest WHERE ticketFk =vTicketFk; @@ -71140,26 +71140,26 @@ BEGIN INSERT INTO ticketObservation( ticketFk, observationTypeFk, - description) + description) VALUES( vNewTicket, vSalesPersonFK, CONCAT('turno desde ticket: ',vTicketFk)) - ON DUPLICATE KEY UPDATE description = + ON DUPLICATE KEY UPDATE description = CONCAT(ticketObservation.description,VALUES(description),' '); INSERT INTO ticketObservation(ticketFk, observationTypeFk, - description) + description) VALUES( vNewTicket, vItemPicker, 'ATENCION: Contiene lineas de TURNO') - ON DUPLICATE KEY UPDATE description = + ON DUPLICATE KEY UPDATE description = CONCAT(ticketObservation.description,VALUES(description),' '); IF (vLanding IS NULL) THEN - + SELECT e.email INTO vSalesPersonEmail FROM client c JOIN account.emailUser e ON e.userFk = c.salesPersonFk @@ -71167,8 +71167,8 @@ BEGIN SET vSubject = CONCAT('Turnos - No se ha podido clonar correctamente el ticket ', vTicketFk,' para el dia: ', vShipment); - SET vMessage = CONCAT('No se ha podido clonar el ticket ', vTicketFk, - ' para el dia: ', vShipment, + SET vMessage = CONCAT('No se ha podido clonar el ticket ', vTicketFk, + ' para el dia: ', vShipment, ' porque no hay una zona de envío disponible. Se ha creado el ticket: ', vNewTicket, ' pero ha que revisar las fechas y la agencia'); @@ -71207,7 +71207,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_close`() BEGIN /** - * Realiza el cierre de todos los + * Realiza el cierre de todos los * tickets de la tabla tmp.ticket_close. * * @table tmp.ticket_close(ticketFk) Identificadores de los tickets a cerrar @@ -71225,7 +71225,7 @@ BEGIN DECLARE cur CURSOR FOR SELECT ticketFk FROM tmp.ticket_close; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN RESIGNAL; @@ -71235,7 +71235,7 @@ BEGIN proc: LOOP SET vDone = FALSE; - + FETCH cur INTO vCurTicketFk; IF vDone THEN @@ -71252,12 +71252,12 @@ BEGIN c.hasToInvoice INTO vClientFk, vIsTaxDataChecked, - vCompanyFk, + vCompanyFk, vShipped, vHasDailyInvoice, vWithPackage, vHasToInvoice - FROM ticket t + FROM ticket t JOIN `client` c ON c.id = t.clientFk JOIN province p ON p.id = c.provinceFk LEFT JOIN autonomy a ON a.id = p.autonomyFk @@ -71267,22 +71267,22 @@ BEGIN INSERT INTO ticketPackaging (ticketFk, packagingFk, quantity) (SELECT vCurTicketFk, p.id, COUNT(*) - FROM expedition e + FROM expedition e JOIN packaging p ON p.itemFk = e.freightItemFk WHERE e.ticketFk = vCurTicketFk AND p.isPackageReturnable AND vWithPackage GROUP BY p.itemFk); -- No retornables o no catalogados - INSERT INTO sale (itemFk, ticketFk, concept, quantity, price, isPriceFixed) + INSERT INTO sale (itemFk, ticketFk, concept, quantity, price, isPriceFixed) (SELECT e.freightItemFk, vCurTicketFk, i.name, COUNT(*) AS amount, getSpecialPrice(e.freightItemFk, vClientFk), 1 - FROM expedition e + FROM expedition e JOIN item i ON i.id = e.freightItemFk LEFT JOIN packaging p ON p.itemFk = i.id WHERE e.ticketFk = vCurTicketFk AND IFNULL(p.isPackageReturnable, 0) = 0 AND getSpecialPrice(e.freightItemFk, vClientFk) > 0 GROUP BY e.freightItemFk); - + IF(vHasDailyInvoice) AND vHasToInvoice THEN -- Facturacion rapida @@ -71290,10 +71290,10 @@ BEGIN -- Facturar si está contabilizado IF vIsTaxDataChecked THEN CALL invoiceOut_newFromClient( - vClientFk, - (SELECT invoiceSerial(vClientFk, vCompanyFk, 'M')), - vShipped, - vCompanyFk, + vClientFk, + (SELECT invoiceSerial(vClientFk, vCompanyFk, 'M')), + vShipped, + vCompanyFk, NULL, NULL, vNewInvoiceId); @@ -71361,25 +71361,25 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_componentMakeUpdate`( - vTicketFk INT, + vTicketFk INT, vClientFk INT, - vNickname VARCHAR(50), + vNickname VARCHAR(50), vAgencyModeFk INT, - vAddressFk INT, - vZoneFk INT, + vAddressFk INT, + vZoneFk INT, vWarehouseFk INT, - vCompanyFk INT, + vCompanyFk INT, vShipped DATETIME, - vLanded DATE, + vLanded DATE, vIsDeleted BOOLEAN, - vHasToBeUnrouted BOOLEAN, + vHasToBeUnrouted BOOLEAN, vOption INT) BEGIN - + /** * Modifica en el ticket los campos que se le pasan por parámetro * y cambia sus componentes - * + * * @param vTicketFk Id del ticket a modificar * @param vClientFk nuevo cliente * @param vNickname nuevo alias @@ -71394,29 +71394,29 @@ BEGIN * @param vHasToBeUnrouted si se le elimina la ruta al ticket * @param vOption opcion para el case del proc ticketComponentUpdateSale */ - + DECLARE vPrice DECIMAL(10,2); DECLARE vBonus DECIMAL(10,2); CALL ticket_componentPreview (vTicketFk, vLanded, vAddressFk, vZoneFk, vWarehouseFk); IF (SELECT addressFk FROM ticket WHERE id = vTicketFk) <> vAddressFk THEN - - UPDATE ticket t + + UPDATE ticket t JOIN address a ON a.id = vAddressFk SET t.nickname = a.nickname WHERE t.id = vTicketFk; - + END IF; CALL zone_getShipped(vLanded, vAddressFk, vAgencyModeFk, TRUE); - SELECT zoneFk, price, bonus INTO vZoneFk, vPrice, vBonus + SELECT zoneFk, price, bonus INTO vZoneFk, vPrice, vBonus FROM tmp.zoneGetShipped WHERE shipped BETWEEN DATE(vShipped) AND util.dayEnd(vShipped) AND warehouseFk = vWarehouseFk LIMIT 1; - + UPDATE ticket t - SET + SET t.clientFk = vClientFk, t.nickname = vNickname, t.agencyModeFk = vAgencyModeFk, @@ -71431,12 +71431,12 @@ BEGIN t.isDeleted = vIsDeleted WHERE t.id = vTicketFk; - + IF vHasToBeUnrouted THEN UPDATE ticket t SET t.routeFk = NULL WHERE t.id = vTicketFk; END IF; - + IF vOption <> 8 THEN DROP TEMPORARY TABLE IF EXISTS tmp.sale; CREATE TEMPORARY TABLE tmp.sale @@ -71474,7 +71474,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_componentPreview`( vTicketFk INT, - vLanded DATE, + vLanded DATE, vAddressFk INT, vZoneFk INT, vWarehouseFk SMALLINT) @@ -71490,7 +71490,7 @@ BEGIN * * @return tmp.ticketComponentPreview (warehouseFk, itemFk, componentFk, cost) */ - DECLARE vHasDataChanged BOOL DEFAULT FALSE; + DECLARE vHasDataChanged BOOL DEFAULT FALSE; DECLARE vHasAddressChanged BOOL; DECLARE vHasZoneChanged BOOL DEFAULT FALSE; DECLARE vHasWarehouseChanged BOOL DEFAULT FALSE; @@ -71501,8 +71501,8 @@ BEGIN DECLARE vHasChangeAll BOOL DEFAULT FALSE; - SELECT DATE(landed) <> vLanded, - addressFk <> vAddressFk, + SELECT DATE(landed) <> vLanded, + addressFk <> vAddressFk, zoneFk <> vZoneFk, warehouseFk <> vWarehouseFk INTO @@ -71525,15 +71525,15 @@ BEGIN SET vAgencyModeTypeRateFk = 6; END IF; - SELECT TIMESTAMPADD(DAY, -travelingDays, vLanded) INTO vShipped + SELECT TIMESTAMPADD(DAY, -travelingDays, vLanded) INTO vShipped FROM zone WHERE id = vZoneFk; - + CALL buyUltimate(vWarehouseFk, vShipped); - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; - CREATE TEMPORARY TABLE tmp.ticketLot ENGINE = MEMORY ( - SELECT + CREATE TEMPORARY TABLE tmp.ticketLot ENGINE = MEMORY ( + SELECT vWarehouseFk AS warehouseFk, NULL AS available, s.itemFk, @@ -71553,9 +71553,9 @@ BEGIN JOIN sale s ON s.id = sc.saleFk JOIN ticket t ON t.id = s.ticketFk JOIN `component` c ON c.id = sc.componentFk - WHERE s.ticketFk = vTicketFk - AND (c.isRenewable = FALSE - OR + WHERE s.ticketFk = vTicketFk + AND (c.isRenewable = FALSE + OR (NOT vHasChangeAll AND (NOT (c.typeFk <=> vAddressTypeRateFk OR c.typeFk <=> vAgencyModeTypeRateFk)))); @@ -71635,52 +71635,52 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_DelayTruckSplit`(vTicketFk INT) BEGIN - + /* * Splita las lineas de ticket que no estan ubicadas - * + * */ - + DECLARE vNewTicketFk INT; DECLARE vTotalLines INT; DECLARE vLinesToSplit INT; DROP TEMPORARY TABLE IF EXISTS tmp.SalesToSplit; - + SELECT COUNT(*) INTO vTotalLines - FROM vn.sale + FROM vn.sale WHERE ticketFk = vTicketFk; - + CREATE TEMPORARY TABLE tmp.SalesToSplit SELECT s.id saleFk FROM vn.ticket t - JOIN vn.sale s ON t.id = s.ticketFk - LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = s.itemFk AND issw.warehouseFk = t.warehouseFk + JOIN vn.sale s ON t.id = s.ticketFk + LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = s.itemFk AND issw.warehouseFk = t.warehouseFk WHERE s.quantity > IFNULL(issw.visible, 0) AND s.quantity > 0 AND s.isPicked = FALSE AND s.reserved = FALSE AND t.id = vTicketFk; - + SELECT COUNT(*) INTO vLinesToSplit FROM tmp.SalesToSplit; - + IF vLinesToSplit = vTotalLines AND vLinesToSplit > 0 THEN - + SET vNewTicketFk = vTicketFk; - + ELSE - + CALL vn.ticket_Clone(vTicketFk, vNewTicketFk); - - UPDATE vn.sale s - JOIN tmp.SalesToSplit sts ON sts.saleFk = s.id + + UPDATE vn.sale s + JOIN tmp.SalesToSplit sts ON sts.saleFk = s.id SET s.ticketFk = vNewTicketFk; - + END IF; - + CALL vn.ticketStateUpdate(vNewTicketFk, 'FIXING'); - + DROP TEMPORARY TABLE tmp.SalesToSplit; END ;; @@ -71700,91 +71700,91 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_doCmr`(vSelf INT) -BEGIN -/** -* Crea u actualiza la información del CMR asociado con -* un ticket específico en caso de que sea necesario. -* -* @param vSelf El id del ticket -*/ - DECLARE vCmrFk, vPreviousCmrFk, vCurrentCmrFk INT; - SELECT cmrFk INTO vCmrFk - FROM ticket - WHERE id = vSelf; - - CREATE OR REPLACE TEMPORARY TABLE tTicket - SELECT wo.firstName, - v.numberPlate, - com.id companyFk, - a.id addressFk, - c2.defaultAddressFk, - su.id supplierFk, - t.landed - FROM ticket t - JOIN ticketState ts ON ts.ticketFk = t.id - JOIN `state` s ON s.id = ts.stateFk - JOIN alertLevel al ON al.id = s.alertLevel - JOIN client c ON c.id = t.clientFk - JOIN `address` a ON a.id = t.addressFk - JOIN province p ON p.id = a.provinceFk - JOIN country co ON co.id = p.countryFk - JOIN agencyMode am ON am.id = t.agencyModeFk - JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk - JOIN warehouse w ON w.id = t.warehouseFk - JOIN company com ON com.id = t.companyFk - JOIN client c2 ON c2.id = com.clientFk - JOIN supplierAccount sa ON sa.id = com.supplierAccountFk - JOIN supplier su ON su.id = sa.supplierFk - LEFT JOIN route r ON r.id = t.routeFk - LEFT JOIN worker wo ON wo.id = r.workerFk - LEFT JOIN vehicle v ON v.id = r.vehicleFk - WHERE t.shipped BETWEEN util.yesterday() AND util.dayEnd(util.VN_CURDATE()) - AND al.code IN ('PACKED', 'DELIVERED') - AND co.code <> 'ES' - AND am.name <> 'ABONO' - AND w.code = 'ALG' - AND dm.code = 'DELIVERY' - AND t.id = vSelf - GROUP BY t.id; - - START TRANSACTION; - - IF vCmrFk THEN - UPDATE cmr c - JOIN tTicket t - SET c.senderInstruccions = t.firstName, - c.truckPlate = t.numberPlate, - c.companyFk = t.companyFk, - c.addressToFk = t.addressFk, - c.addressFromFk = t.defaultAddressFk, - c.supplierFk = t.supplierFk, - c.ead = t.landed - WHERE id = vCmrFk; - ELSE - SELECT MAX(id) INTO vPreviousCmrFk FROM cmr; - - INSERT INTO cmr ( - senderInstruccions, - truckPlate, - companyFk, - addressToFk, - addressFromFk, - supplierFk, - ead - ) - SELECT * FROM tTicket; - - SELECT MAX(id) INTO vCurrentCmrFk FROM cmr; - - IF vPreviousCmrFk <> vCurrentCmrFk THEN - UPDATE ticket - SET cmrFk = vCurrentCmrFk - WHERE id = vSelf; - END IF; - END IF; - - COMMIT; - DROP TEMPORARY TABLE tTicket; +BEGIN +/** +* Crea u actualiza la información del CMR asociado con +* un ticket específico en caso de que sea necesario. +* +* @param vSelf El id del ticket +*/ + DECLARE vCmrFk, vPreviousCmrFk, vCurrentCmrFk INT; + SELECT cmrFk INTO vCmrFk + FROM ticket + WHERE id = vSelf; + + CREATE OR REPLACE TEMPORARY TABLE tTicket + SELECT wo.firstName, + v.numberPlate, + com.id companyFk, + a.id addressFk, + c2.defaultAddressFk, + su.id supplierFk, + t.landed + FROM ticket t + JOIN ticketState ts ON ts.ticketFk = t.id + JOIN `state` s ON s.id = ts.stateFk + JOIN alertLevel al ON al.id = s.alertLevel + JOIN client c ON c.id = t.clientFk + JOIN `address` a ON a.id = t.addressFk + JOIN province p ON p.id = a.provinceFk + JOIN country co ON co.id = p.countryFk + JOIN agencyMode am ON am.id = t.agencyModeFk + JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk + JOIN warehouse w ON w.id = t.warehouseFk + JOIN company com ON com.id = t.companyFk + JOIN client c2 ON c2.id = com.clientFk + JOIN supplierAccount sa ON sa.id = com.supplierAccountFk + JOIN supplier su ON su.id = sa.supplierFk + LEFT JOIN route r ON r.id = t.routeFk + LEFT JOIN worker wo ON wo.id = r.workerFk + LEFT JOIN vehicle v ON v.id = r.vehicleFk + WHERE t.shipped BETWEEN util.yesterday() AND util.dayEnd(util.VN_CURDATE()) + AND al.code IN ('PACKED', 'DELIVERED') + AND co.code <> 'ES' + AND am.name <> 'ABONO' + AND w.code = 'ALG' + AND dm.code = 'DELIVERY' + AND t.id = vSelf + GROUP BY t.id; + + START TRANSACTION; + + IF vCmrFk THEN + UPDATE cmr c + JOIN tTicket t + SET c.senderInstruccions = t.firstName, + c.truckPlate = t.numberPlate, + c.companyFk = t.companyFk, + c.addressToFk = t.addressFk, + c.addressFromFk = t.defaultAddressFk, + c.supplierFk = t.supplierFk, + c.ead = t.landed + WHERE id = vCmrFk; + ELSE + SELECT MAX(id) INTO vPreviousCmrFk FROM cmr; + + INSERT INTO cmr ( + senderInstruccions, + truckPlate, + companyFk, + addressToFk, + addressFromFk, + supplierFk, + ead + ) + SELECT * FROM tTicket; + + SELECT MAX(id) INTO vCurrentCmrFk FROM cmr; + + IF vPreviousCmrFk <> vCurrentCmrFk THEN + UPDATE ticket + SET cmrFk = vCurrentCmrFk + WHERE id = vSelf; + END IF; + END IF; + + COMMIT; + DROP TEMPORARY TABLE tTicket; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -72017,37 +72017,37 @@ BEGIN * @param vTicketFk -> Ticket * @param vDatedNew -> Nueva fecha * @return Sales con Movible -*/ +*/ DECLARE vDatedOld DATETIME; SET vDatedNew = DATE_ADD(vDatedNew, INTERVAL 1 DAY); SELECT t.shipped INTO vDatedOld - FROM ticket t + FROM ticket t WHERE t.id = vTicketFk; - CALL item_getStock(vWarehouseFk, vDatedNew, NULL); + CALL item_getStock(vWarehouseFk, vDatedNew, NULL); CALL item_getMinacum(vWarehouseFk, vDatedNew, DATEDIFF(DATE_SUB(vDatedOld, INTERVAL 1 DAY), vDatedNew), NULL); - - SELECT s.id, - s.itemFk, - s.quantity, - s.concept, - s.price, + + SELECT s.id, + s.itemFk, + s.quantity, + s.concept, + s.price, s.reserved, - s.discount, - i.image, - i.subName, + s.discount, + i.image, + i.subName, il.stock + IFNULL(im.amount, 0) AS movable FROM ticket t JOIN sale s ON s.ticketFk = t.id - JOIN item i ON i.id = s.itemFk + JOIN item i ON i.id = s.itemFk LEFT JOIN tmp.itemMinacum im ON im.itemFk = s.itemFk AND im.warehouseFk = vWarehouseFk LEFT JOIN tmp.itemList il ON il.itemFk = s.itemFk WHERE t.id = vTicketFk; DROP TEMPORARY TABLE IF EXISTS tmp.itemList; - DROP TEMPORARY TABLE IF EXISTS tmp.itemMinacum; - + DROP TEMPORARY TABLE IF EXISTS tmp.itemMinacum; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -72076,10 +72076,10 @@ BEGIN CALL sale_getProblems(vIsTodayRelative); DROP TEMPORARY TABLE IF EXISTS tmp.ticket_problems; - CREATE TEMPORARY TABLE tmp.ticket_problems + CREATE TEMPORARY TABLE tmp.ticket_problems (PRIMARY KEY (ticketFk)) ENGINE = MEMORY - SELECT + SELECT ticketFk, MAX(p.isFreezed) isFreezed, MAX(p.risk) risk, @@ -72097,7 +72097,7 @@ BEGIN GROUP BY ticketFk; UPDATE tmp.ticket_problems tp - SET tp.totalProblems = + SET tp.totalProblems = ( (tp.isFreezed) + IF(tp.risk, TRUE, FALSE) + @@ -72151,17 +72151,17 @@ BEGIN (saleFk INT PRIMARY KEY, ticketFk INT, problem VARCHAR(1)) ENGINE = MEMORY; - + INSERT INTO tmp.salesToSplit(saleFk, ticketFk, problem) SELECT s.id, s.ticketFk, 'F' FROM vn.ticket t JOIN vn.sale s ON s.ticketFk = t.id JOIN vn.item i ON i.id = s.itemFk JOIN vn.itemType it on it.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk LEFT JOIN cache.visible v ON v.item_id = i.id AND v.calc_id = vVisibleCache LEFT JOIN cache.available av ON av.item_id = i.id AND av.calc_id = vAvailableCache - LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk + LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk WHERE IFNULL(v.visible,0) < s.quantity AND IFNULL(av.available ,0) < s.quantity AND IFNULL(issw.visible, 0) < s.quantity @@ -72171,16 +72171,16 @@ BEGIN AND t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE()) AND NOT i.generic AND t.warehouseFk = vWarehouseFk; - + INSERT IGNORE INTO tmp.salesToSplit(saleFk, ticketFk, problem) SELECT s.id, s.ticketFk, 'I' - FROM vn.ticket t + FROM vn.ticket t JOIN vn.sale s ON s.ticketFk = t.id JOIN vn.item i ON i.id = s.itemFk JOIN vn.itemType it on it.id = i.typeFk JOIN vn.itemCategory ic ON ic.id = it.categoryFk LEFT JOIN cache.visible v ON v.item_id = s.itemFk AND v.calc_id = vVisibleCache - LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk + LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk WHERE IFNULL(v.visible,0) >= s.quantity AND IFNULL(issw.visible, 0) < s.quantity AND s.quantity > 0 @@ -72190,7 +72190,7 @@ BEGIN AND t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE()) AND NOT i.generic AND t.warehouseFk = vWarehouseFk; - + INSERT IGNORE INTO tmp.salesToSplit(saleFk, ticketFk, problem) SELECT s.id, s.ticketFk, 'R' FROM vn.ticket t @@ -72200,7 +72200,7 @@ BEGIN JOIN vn.itemCategory ic ON ic.id = it.categoryFk LEFT JOIN cache.visible v ON v.item_id = s.itemFk AND v.calc_id = vVisibleCache LEFT JOIN cache.available av ON av.item_id = i.id AND av.calc_id = vAvailableCache - LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk + LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk WHERE IFNULL(v.visible,0) < s.quantity AND IFNULL(av.available ,0) >= s.quantity AND IFNULL(issw.visible, 0) < s.quantity @@ -72211,7 +72211,7 @@ BEGIN AND t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE()) AND NOT i.generic AND t.warehouseFk = vWarehouseFk; - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketsToSplit; CREATE TEMPORARY TABLE tmp.ticketsToSplit @@ -72232,11 +72232,11 @@ BEGIN JOIN vn.ticket t ON t.id = ss.ticketFk JOIN vn.sale s ON s.id = ss.saleFk JOIN vn.item i ON i.id = s.itemFk - LEFT JOIN vn.zoneClosure zc ON zc.zoneFk = t.zoneFk + LEFT JOIN vn.zoneClosure zc ON zc.zoneFk = t.zoneFk GROUP BY ss.ticketFk; - - SELECT - ts.*, + + SELECT + ts.*, t.id ticketFuture, st.name state, zc.`hour` tfEtd, @@ -72245,23 +72245,23 @@ BEGIN FROM tmp.ticketsToSplit ts LEFT JOIN vn.ticketState ts2 ON ts2.ticketFk = ts.ticketFk LEFT JOIN vn.state st ON st.id = ts2.stateFk - LEFT JOIN vn.ticket t - ON t.id != ts.ticketFk + LEFT JOIN vn.ticket t + ON t.id != ts.ticketFk AND t.addressFk = ts.addressFk AND t.shipped BETWEEN vDated AND util.dayend(vDated) LEFT JOIN vn.zoneClosure zc ON zc.zoneFk = t.zoneFk AND zc.dated = vDated LEFT JOIN vn.sale s ON s.ticketFk = t.id LEFT JOIN vn.item i ON i.id = s.itemFk - LEFT JOIN vn.ticketState tst ON tst.ticketFk = t.id + LEFT JOIN vn.ticketState tst ON tst.ticketFk = t.id LEFT JOIN vn.state st2 ON st2.id = tst.stateFk - WHERE (t.id IS NULL + WHERE (t.id IS NULL OR (vDated > util.VN_CURDATE()) OR (vDated = util.VN_CURDATE() AND vHour >= zc.`hour`)) AND ts.etd <= vHour GROUP BY ts.ticketFk, t.id ORDER BY ts.etd, ts.ticketFk; - - DROP TEMPORARY TABLE + + DROP TEMPORARY TABLE tmp.ticketsToSplit; END ;; DELIMITER ; @@ -72298,7 +72298,7 @@ BEGIN JOIN ticket t ON t.id = tmpTicket.ticketFk; CALL addressTaxArea (); - + IF vTaxArea IS NOT NULL THEN UPDATE tmp.addressTaxArea SET areaFk = vTaxArea; @@ -72370,8 +72370,8 @@ BEGIN CREATE TEMPORARY TABLE tmp.ticketAmount (INDEX (ticketFk)) ENGINE = MEMORY - SELECT ticketFk, - taxableBase, + SELECT ticketFk, + taxableBase, SUM(CAST(taxableBase * rate / 100 AS DECIMAL(10, 2))) tax, code FROM tmp.ticketTax @@ -72451,11 +72451,11 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_getWithParameters`( - vClientFk INT, + vClientFk INT, vWarehouseFk INT, - vShipped DATE, - vAddressFk INT, - vCompanyFk INT, + vShipped DATE, + vAddressFk INT, + vCompanyFk INT, vAgencyModeFk INT, OUT vTicketFk INT ) @@ -72469,8 +72469,8 @@ BEGIN * @param vAddressFk Consignatario * @param vCompanyFk Empresa * @param vAgencyModeFk agencia - */ - + */ + SELECT t.id INTO vTicketFk FROM vn.ticket t WHERE t.clientFk <=> vClientFk @@ -72480,7 +72480,7 @@ BEGIN AND (t.companyFk <=> vCompanyFk OR vCompanyFk IS NULL) AND (t.agencyModeFk <=> vAgencyModeFk OR vAgencyModeFk IS NULL) LIMIT 1; - + IF vTicketFk IS NULL THEN CALL vn.ticket_add( vClientFk, @@ -72520,24 +72520,24 @@ BEGIN DECLARE vAddressFk INT; DECLARE vAgencyModeFk INT; DECLARE vWarehouseFk INT; - DECLARE vCursor CURSOR FOR + DECLARE vCursor CURSOR FOR SELECT id, landed, addressFk, agencyModeFk, warehouseFk FROM vn.ticket WHERE shipped > '2020-01-01' AND zoneFk is null; DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET vDone = 1; - + OPEN vCursor; REPEAT FETCH vCursor INTO vFechedTicket, vLanded, vAddressFk, vAgencyModeFk, vWarehouseFk; CALL vn.zone_getShipped (vlanded, vAddressFk, vAgencyModeFk, TRUE); - + UPDATE vn.ticket t JOIN tmp.zoneGetShipped zgs ON zgs.warehouseFk = vWarehouseFk SET t.zoneFk = zgs.zoneFk WHERE t.id = vFechedTicket; - + UNTIL vDone END REPEAT; DROP TEMPORARY TABLE tmp.zoneGetShipped; - + CLOSE vCursor; END ;; DELIMITER ; @@ -72557,14 +72557,14 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_priceDifference`( vTicketFk INT, - vLanded DATE, + vLanded DATE, vAddressFk INT, vZoneFk INT, vWarehouseFk INT) BEGIN /** * Devuelve las diferencias de precio de los movimientos de un ticket. - * + * * @param vTicketFk Id del ticket * @param vLanded Fecha de recepcion * @param vAddressFk Id del consignatario @@ -72573,26 +72573,26 @@ BEGIN */ CALL vn.ticket_componentPreview(vTicketFk, vLanded, vAddressFk, vZoneFk, vWarehouseFk); - SELECT s.itemFk, - i.name, - i.size, - i.category, - IFNULL(s.quantity, 0) AS quantity, - IFNULL(s.price, 0) AS price, + SELECT s.itemFk, + i.name, + i.size, + i.category, + IFNULL(s.quantity, 0) AS quantity, + IFNULL(s.price, 0) AS price, ROUND(SUM(tc.cost), 2) AS newPrice, s.quantity * (s.price - ROUND(SUM(tc.cost), 2)) difference, s.id AS saleFk FROM sale s - JOIN item i ON i.id = s.itemFk - JOIN ticket t ON t.id = s.ticketFk - LEFT JOIN tmp.ticketComponentPreview tc ON tc.itemFk = s.itemFk + JOIN item i ON i.id = s.itemFk + JOIN ticket t ON t.id = s.ticketFk + LEFT JOIN tmp.ticketComponentPreview tc ON tc.itemFk = s.itemFk AND tc.warehouseFk = vWarehouseFk - LEFT JOIN saleComponent sc ON sc.saleFk = s.id + LEFT JOIN saleComponent sc ON sc.saleFk = s.id AND sc.componentFk = tc.componentFk - LEFT JOIN `component` c ON c.id = tc.componentFk - WHERE t.id = vTicketFk - AND IF(sc.componentFk IS NULL - AND c.classRate IS NOT NULL, FALSE, TRUE) + LEFT JOIN `component` c ON c.id = tc.componentFk + WHERE t.id = vTicketFk + AND IF(sc.componentFk IS NULL + AND c.classRate IS NOT NULL, FALSE, TRUE) GROUP BY s.id ORDER BY s.id; DROP TEMPORARY TABLE tmp.ticketComponentPreview; @@ -72615,7 +72615,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_printLabelPrevious`(vTicketFk INT) BEGIN /** - * Calls the report_print procedure and passes it + * Calls the report_print procedure and passes it * the necessary parameters for printing. * * @param vTicketFk id ticket to print. @@ -72623,18 +72623,18 @@ BEGIN DECLARE vPrinterFk INT; DECLARE vSaleGroup INT; DECLARE vUserFk INT DEFAULT account.myUser_getId(); - + SELECT sg.id, o.labelerFk INTO vSaleGroup, vPrinterFk FROM saleGroup sg JOIN sector sc ON sc.id = sg.sectorFk - JOIN saleGroupDetail sgd ON sg.id = sgd.saleGroupFk + JOIN saleGroupDetail sgd ON sg.id = sgd.saleGroupFk JOIN sale s ON sgd.saleFk = s.id JOIN ticket t ON s.ticketFk = t.id JOIN operator o ON o.workerFk = vUserFk - WHERE sc.id = o.sectorFk + WHERE sc.id = o.sectorFk AND t.id = vTicketFk LIMIT 1; - + CALL report_print( 'LabelPrevia', vPrinterFk, @@ -72668,12 +72668,12 @@ proc:BEGIN */ DECLARE hasInvoice BOOL; - SELECT COUNT(*) INTO hasInvoice - FROM ticket + SELECT COUNT(*) INTO hasInvoice + FROM ticket WHERE id = vSelf AND refFk IS NOT NULL; - - IF hasInvoice THEN + + IF hasInvoice THEN LEAVE proc; END IF; @@ -72907,62 +72907,62 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_setState`(vSelf INT, vStateCode VARCHAR(255) COLLATE utf8_general_ci) -BEGIN -/** - * Modifica el estado de un ticket si se cumplen las condiciones necesarias. - * - * @param vSelf el id del ticket - * @param vStateCode estado a modificar del ticket - */ - DECLARE vticketAlertLevel INT; - DECLARE vTicketStateCode VARCHAR(255); - DECLARE vCanChangeState BOOL; - DECLARE vPackedAlertLevel INT; - DECLARE vOnPreparationAlertLevel INT; - DECLARE vNextAlertLevel INT; - DECLARE vZoneFk INT; - - SELECT s.alertLevel, s.`code`, s2.alertLevel, t.zoneFk - INTO vticketAlertLevel, vTicketStateCode, vNextAlertLevel , vZoneFk - FROM state s - JOIN ticketTracking tt ON tt.stateFk = s.id - JOIN state s2 ON s2.code = vStateCode - JOIN ticket t ON t.id = tt.ticketFk - WHERE tt.ticketFk = vSelf - ORDER BY tt.created DESC - LIMIT 1; - - SELECT id INTO vPackedAlertLevel FROM alertLevel WHERE code = 'PACKED'; - SELECT id INTO vOnPreparationAlertLevel FROM alertLevel WHERE code = 'ON_PREPARATION'; - - IF vStateCode = 'OK' AND vZoneFk IS NULL THEN - CALL util.throw('ASSIGN_ZONE_FIRST'); - END IF; - - IF vNextAlertLevel > vticketAlertLevel && vticketAlertLevel < vOnPreparationAlertLevel THEN - UPDATE sale - SET originalQuantity = quantity - WHERE ticketFk = vSelf; - END IF; - - SET vCanChangeState = (vStateCode <> 'ON_CHECKING' OR vticketAlertLevel < vPackedAlertLevel) - AND NOT ( - vTicketStateCode IN ('CHECKED', 'CHECKING') - AND vStateCode IN ('PREPARED', 'ON_PREPARATION') - ); - - IF vCanChangeState THEN - INSERT INTO ticketTracking (stateFk, ticketFk, workerFk) - SELECT id, vSelf, account.myUser_getId() - FROM state - WHERE `code` = vStateCode COLLATE utf8_unicode_ci; - - IF vStateCode = 'PACKED' THEN - CALL ticket_doCmr(vSelf); - END IF; - ELSE - CALL util.throw('INCORRECT_TICKET_STATE'); - END IF; +BEGIN +/** + * Modifica el estado de un ticket si se cumplen las condiciones necesarias. + * + * @param vSelf el id del ticket + * @param vStateCode estado a modificar del ticket + */ + DECLARE vticketAlertLevel INT; + DECLARE vTicketStateCode VARCHAR(255); + DECLARE vCanChangeState BOOL; + DECLARE vPackedAlertLevel INT; + DECLARE vOnPreparationAlertLevel INT; + DECLARE vNextAlertLevel INT; + DECLARE vZoneFk INT; + + SELECT s.alertLevel, s.`code`, s2.alertLevel, t.zoneFk + INTO vticketAlertLevel, vTicketStateCode, vNextAlertLevel , vZoneFk + FROM state s + JOIN ticketTracking tt ON tt.stateFk = s.id + JOIN state s2 ON s2.code = vStateCode + JOIN ticket t ON t.id = tt.ticketFk + WHERE tt.ticketFk = vSelf + ORDER BY tt.created DESC + LIMIT 1; + + SELECT id INTO vPackedAlertLevel FROM alertLevel WHERE code = 'PACKED'; + SELECT id INTO vOnPreparationAlertLevel FROM alertLevel WHERE code = 'ON_PREPARATION'; + + IF vStateCode = 'OK' AND vZoneFk IS NULL THEN + CALL util.throw('ASSIGN_ZONE_FIRST'); + END IF; + + IF vNextAlertLevel > vticketAlertLevel && vticketAlertLevel < vOnPreparationAlertLevel THEN + UPDATE sale + SET originalQuantity = quantity + WHERE ticketFk = vSelf; + END IF; + + SET vCanChangeState = (vStateCode <> 'ON_CHECKING' OR vticketAlertLevel < vPackedAlertLevel) + AND NOT ( + vTicketStateCode IN ('CHECKED', 'CHECKING') + AND vStateCode IN ('PREPARED', 'ON_PREPARATION') + ); + + IF vCanChangeState THEN + INSERT INTO ticketTracking (stateFk, ticketFk, workerFk) + SELECT id, vSelf, account.myUser_getId() + FROM state + WHERE `code` = vStateCode COLLATE utf8_unicode_ci; + + IF vStateCode = 'PACKED' THEN + CALL ticket_doCmr(vSelf); + END IF; + ELSE + CALL util.throw('INCORRECT_TICKET_STATE'); + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -72996,40 +72996,40 @@ proc:BEGIN SELECT COUNT(*) INTO vProblemLines FROM tmp.salesToSplit WHERE ticketFk = vTicketFk; - + SELECT count(*) INTO vTotalLines - FROM vn.sale s + FROM vn.sale s WHERE s.ticketFk = vTicketFk; - + SET vHasFullProblem = (vTotalLines = vProblemLines); -- Ticket completo IF vHasFullProblem THEN - + UPDATE vn.ticket SET landed = vDated + INTERVAL 1 DAY, shipped = vDated, nickname = CONCAT('(',DAY(util.VN_CURDATE()),') ', nickname ) WHERE id = vTicketFk; - + SELECT CONCAT("Se ha cambiado el ticket ", vTicketFk, " al dia ", vDated); LEAVE proc; - + END IF; -- Ticket a futuro existe IF vTicketFutureFk THEN - - UPDATE vn.sale s + + UPDATE vn.sale s JOIN tmp.salesToSplit ss ON s.id = ss.saleFk SET s.ticketFk = vTicketFutureFk, s.concept = CONCAT('(s) ', s.concept) WHERE ss.ticketFk = vTicketFk; - - SELECT CONCAT("Se han movido lineas del ticket ", vTicketFk, + + SELECT CONCAT("Se han movido lineas del ticket ", vTicketFk, " al ticket existente ", vTicketFutureFk,"(", vDated,")"); LEAVE proc; - + END IF; -- Ticket nuevo @@ -73041,18 +73041,18 @@ proc:BEGIN t.landed = vDated + INTERVAL 1 DAY, t.shipped = vDated, t.agencyModeFk = pc.defautlAgencyMode, - t.zoneFk = pc.defaultZone + t.zoneFk = pc.defaultZone WHERE t.id = vTicketFutureFk; - - UPDATE vn.sale s - JOIN tmp.salesToSplit sts ON sts.saleFk = s.id + + UPDATE vn.sale s + JOIN tmp.salesToSplit sts ON sts.saleFk = s.id SET s.ticketFk = vTicketFutureFk, s.concept = CONCAT('(s) ', s.concept) WHERE sts.ticketFk = vTicketFk; CALL vn.ticketStateUpdate(vTicketFutureFk, 'FIXING'); - SELECT CONCAT("Se han movido lineas del ticket ", vTicketFk, + SELECT CONCAT("Se han movido lineas del ticket ", vTicketFk, " al nuevo ticket ", vTicketFutureFk,"(", vDated,")"); END ;; DELIMITER ; @@ -73191,43 +73191,43 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_splitPackingComplete`(vTicketFk INT, vSectorFk INT) BEGIN - + DECLARE vNeedToSplit BOOLEAN; DECLARE vNewTicketFk INT; - + DROP TEMPORARY TABLE IF EXISTS tmpSale; - + CREATE TEMPORARY TABLE tmpSale SELECT DISTINCT s.id - FROM vn.ticket t + FROM vn.ticket t JOIN vn.sale s ON s.ticketFk = t.id - JOIN vn.item i ON i.id = s.itemFk + JOIN vn.item i ON i.id = s.itemFk LEFT JOIN vn.itemShelvingStock iss ON iss.itemFk = s.itemFk AND iss.sectorFk = vSectorFk - JOIN vn.packagingConfig pc + JOIN vn.packagingConfig pc WHERE t.id = vTicketFk AND ( s.quantity MOD IFNULL(iss.packing,1) != 0 - OR + OR IFNULL(iss.packing,1) = 1 - OR + OR i.`size` <= pc.previousPreparationMinimumSize ); - - SELECT COUNT(*) + + SELECT COUNT(*) INTO vNeedToSplit - FROM tmpSale; - + FROM tmpSale; + IF vNeedToSplit THEN - + CALL vn.ticket_Clone(vTicketFk, vNewTicketFk); - + UPDATE vn.sale s - JOIN vn.tmpSale ts ON ts.id = s.id + JOIN vn.tmpSale ts ON ts.id = s.id SET s.ticketFk = vNewTicketFk; - + END IF; - + DROP TEMPORARY TABLE tmpSale; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -73258,7 +73258,7 @@ BEGIN WHERE ot.description = 'Peso Aduana' AND t.clientFk = vClientFk AND t.shipped BETWEEN vDated AND util.dayend(vDated); - + SELECT sum(IF(sv.physicalWeight = 0, sv.weight, sv.physicalWeight)) INTO vTheorycalWeight FROM vn.ticket t JOIN vn.sale s ON s.ticketFk = t.id @@ -73267,9 +73267,9 @@ BEGIN JOIN vn.itemCost ic ON ic.itemFk = i.id AND ic.warehouseFk = t.warehouseFk WHERE t.clientFk = vClientFk AND t.shipped BETWEEN vDated AND util.dayend(vDated); - + SET vRatio = vRealWeight / vTheorycalWeight; - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketWeight; CREATE TEMPORARY TABLE tmp.ticketWeight @@ -73290,7 +73290,7 @@ BEGIN AND t.shipped BETWEEN vDated AND util.dayend(vDated) GROUP BY ib.ediBotanic, o.code; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -73410,18 +73410,18 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `timeBusiness_calculateAll`(vDatedFr BEGIN /** - * @param vDatedFrom Fecha desde + * @param vDatedFrom Fecha desde * @param vDatedTo Fecha hasta */ - CREATE OR REPLACE TEMPORARY TABLE tmp.`user` + CREATE OR REPLACE TEMPORARY TABLE tmp.`user` SELECT w.id userFk FROM vn.worker w; - + CALL vn.timeBusiness_calculate(vDatedFrom, vDatedTo); DROP TEMPORARY TABLE tmp.`user`; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -73441,21 +73441,21 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `timeBusiness_calculateByDepartment`(vDepartmentFk INT, vDatedFrom DATETIME, vDatedTo DATETIME) BEGIN /** - * @param vDepartmentFk + * @param vDepartmentFk * @param vDatedFrom workerTimeControl * @param vDatedTo workerTimeControl */ DROP TEMPORARY TABLE IF EXISTS tmp.`user`; - + CREATE TEMPORARY TABLE tmp.`user` SELECT DISTINCT b.workerFk userFk - FROM business AS b - WHERE (b.started BETWEEN vDatedFrom AND vDatedTo + FROM business AS b + WHERE (b.started BETWEEN vDatedFrom AND vDatedTo OR IFNULL(b.ended, vDatedTo) BETWEEN vDatedFrom AND vDatedTo OR (b.started <= vDatedFrom AND b.ended >= vDatedTo) ) AND b.departmentFk = vDepartmentFk ORDER BY b.ended DESC; - + CALL timeBusiness_calculate(vDatedFrom, vDatedTo); DROP TEMPORARY TABLE tmp.`user`; @@ -73480,19 +73480,19 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `timeBusiness_calculateByUser`(vUser BEGIN /** - * @param vUserFk + * @param vUserFk * @param vDatedFrom workerTimeControl * @param vDatedTo workerTimeControl */ - + DROP TEMPORARY TABLE IF EXISTS tmp.`user`; - + CREATE TEMPORARY TABLE tmp.`user` SELECT id userFk - FROM account.user - WHERE id = vUserFk; + FROM account.user + WHERE id = vUserFk; CALL vn.timeBusiness_calculate(vDatedFrom, vDatedTo); - + DROP TEMPORARY TABLE tmp.`user`; END ;; @@ -73519,14 +73519,14 @@ BEGIN * @param vDatedFrom Fecha desde * @param vDatedTo Fecha hasta */ - - CREATE OR REPLACE TEMPORARY TABLE tmp.`user` + + CREATE OR REPLACE TEMPORARY TABLE tmp.`user` SELECT w.id userFk FROM worker w WHERE w.id = vWorkerFk; - + CALL timeBusiness_calculate(vDatedFrom, vDatedTo); - + DROP TEMPORARY TABLE tmp.`user`; END ;; @@ -73546,30 +73546,30 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `timeControl_calculate`( - vDatedFrom DATETIME, + vDatedFrom DATETIME, vDatedTo DATETIME) BEGIN /* * @param vDatedFrom - * @param vDatedTo - * Cálculo de horas trabajadas por empleado y día, + * @param vDatedTo + * Cálculo de horas trabajadas por empleado y día, * sin tener en cuenta los días con fichadas incorrectas (tabla tmp.timeControlError) - * En el caso de haber hecho descanso y trabajado un mínimo de tiempo (vTimeToBreakTime), + * En el caso de haber hecho descanso y trabajado un mínimo de tiempo (vTimeToBreakTime), * se añade al tiempo de trabajo efectivo el descanso (vBreakTime) - * @return tmp.timeControlCalculate + * @return tmp.timeControlCalculate * (workerFk, dated, timeWorkSeconds, timeWorkSexagesimal, timeWorkDecimal, timed) */ DECLARE vHourToSeconds INTEGER; DECLARE vDatedFromYesterday DATETIME; - DECLARE vDatedToTomorrow DATETIME; + DECLARE vDatedToTomorrow DATETIME; DECLARE vTimeToBreakTime INT; DECLARE vBreakTime INT; - - SELECT DATE_SUB(vDatedFrom, INTERVAL 1 DAY), DATE_ADD(vDatedTo, INTERVAL 1 DAY) + + SELECT DATE_SUB(vDatedFrom, INTERVAL 1 DAY), DATE_ADD(vDatedTo, INTERVAL 1 DAY) INTO vDatedFromYesterday, vDatedToTomorrow; - + SELECT timeToBreakTime, breakTime INTO vTimeToBreakTime, vBreakTime - FROM workerTimeControlConfig + FROM workerTimeControlConfig LIMIT 1; CALL timeControl_getError(vDatedFrom, vDatedTo); @@ -73578,9 +73578,9 @@ BEGIN CREATE TEMPORARY TABLE tmp.workerTimeControl (INDEX (userFk), INDEX (timed)) ENGINE = MEMORY - SELECT DISTINCT(wtc.id), - wtc.userFk, - wtc.timed, + SELECT DISTINCT(wtc.id), + wtc.userFk, + wtc.timed, wtc.direction, TRUE isReal FROM workerTimeControl wtc @@ -73590,10 +73590,10 @@ BEGIN AND tce.id IS NULL ORDER BY wtc.userFk, wtc.timed ASC; - SELECT MAX(id) INTO @vCont + SELECT MAX(id) INTO @vCont FROM tmp.workerTimeControl; - DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControlAux; + DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControlAux; CREATE TEMPORARY TABLE tmp.workerTimeControlAux ( `id` int(11) , `userFk` int(10) unsigned , @@ -73606,14 +73606,14 @@ BEGIN -- Cambio de dia en medio de un descanso INSERT INTO tmp.workerTimeControlAux (id, userFk, timed, direction) - SELECT @vCont:= @vCont + 1 id, - userFk, - util.dayEnd(dated) timed, + SELECT @vCont:= @vCont + 1 id, + userFk, + util.dayEnd(dated) timed, 'middle' direction FROM(SELECT wtc.userFk, DATE(@lastTimed) dated, (@vIsOdd := NOT @vIsOdd) isOdd, - IF(@vIsOdd AND wtc.direction = 'middle' + IF(@vIsOdd AND wtc.direction = 'middle' AND DATE(timed) <> DATE(@lastTimed), TRUE, FALSE) hasBreak, @lastTimed := wtc.timed FROM tmp.workerTimeControl wtc @@ -73626,14 +73626,14 @@ BEGIN SET @vIsOdd := FALSE; INSERT INTO tmp.workerTimeControlAux (id, userFk, timed, direction) - SELECT @vCont:= @vCont + 1, - userFk, - DATE_ADD(sub.dated, INTERVAL 1 DAY), + SELECT @vCont:= @vCont + 1, + userFk, + DATE_ADD(sub.dated, INTERVAL 1 DAY), 'middle' FROM(SELECT wtc.userFk, DATE(@lastTimed) dated, (@vIsOdd := NOT @vIsOdd) isOdd, - IF(@vIsOdd AND wtc.direction = 'middle' + IF(@vIsOdd AND wtc.direction = 'middle' AND DATE(timed) <> DATE(@lastTimed), TRUE, FALSE) hasBreak, @lastTimed := wtc.timed FROM tmp.workerTimeControl wtc @@ -73644,9 +73644,9 @@ BEGIN -- Cambio de dia INSERT INTO tmp.workerTimeControlAux (id, userFk, timed, direction) - SELECT @vCont:= @vCont + 1 id, - sub.userFk, - util.dayEnd(sub.dated) timed, + SELECT @vCont:= @vCont + 1 id, + sub.userFk, + util.dayEnd(sub.dated) timed, 'out' direction FROM (SELECT MAX(wtc.timed) timed, wtc.userFk, date(wtc.timed) dated FROM workerTimeControl wtc @@ -73656,7 +73656,7 @@ BEGIN AND tce.id IS NULL GROUP BY wtc.userFk, DATE(wtc.timed) ) sub - JOIN tmp.workerTimeControl wtc ON wtc.timed = sub.timed + JOIN tmp.workerTimeControl wtc ON wtc.timed = sub.timed AND wtc.userFk = sub.userFk WHERE wtc.direction <> 'out'; @@ -73670,7 +73670,7 @@ BEGIN AND tce.id IS NULL GROUP BY wtc.userFk, DATE(wtc.timed) ) sub - JOIN tmp.workerTimeControl wtc ON wtc.timed = sub.timed + JOIN tmp.workerTimeControl wtc ON wtc.timed = sub.timed AND wtc.userFk = sub.userFk WHERE wtc.direction <> 'out'; @@ -73687,7 +73687,7 @@ BEGIN CREATE TEMPORARY TABLE tmp.workerBreakDays (INDEX (userFk), INDEX (dated)) ENGINE = MEMORY - SELECT sub.userFk, + SELECT sub.userFk, sub.dated FROM (SELECT (@vIsOdd := NOT @vIsOdd), IF(wtc.direction = 'in', @vIsOdd := TRUE, NULL), @@ -73696,7 +73696,7 @@ BEGIN IF(direction='in', @vDated := DATE(wtc.timed), @vDated) dated, wtc.userFk FROM tmp.workerTimeControl wtc - ORDER BY wtc.userFk, wtc.timed, wtc.id + ORDER BY wtc.userFk, wtc.timed, wtc.id LIMIT 10000000000000000000 )sub GROUP BY sub.userFk, sub.dated @@ -73707,9 +73707,9 @@ BEGIN SET @vLastTimed := 0; DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControlAux2; - CREATE TEMPORARY TABLE tmp.workerTimeControlAux2 + CREATE TEMPORARY TABLE tmp.workerTimeControlAux2 SELECT * - FROM tmp.workerTimeControl + FROM tmp.workerTimeControl WHERE timed BETWEEN vDatedFromYesterday AND vDatedTo ORDER BY userFk, timed, id; @@ -73722,7 +73722,7 @@ BEGIN IF(wb.userFk, vBreakTime, 0) + SUM(sub.timeWork) timeWorkSeconds, SEC_TO_TIME(IF(wb.userFk, vBreakTime, 0) + SUM(sub.timeWork)) timeWorkSexagesimal, (IF(wb.userFk, vBreakTime, 0) + SUM(sub.timeWork)) / vHourToSeconds timeWorkDecimal, - CAST(GROUP_CONCAT(DATE_FORMAT(sub.realTimed, "%H:%i") + CAST(GROUP_CONCAT(DATE_FORMAT(sub.realTimed, "%H:%i") ORDER BY sub.timed ASC SEPARATOR ' - ') AS CHAR(256)) timed FROM (SELECT (@vIsOdd := NOT @vIsOdd), IF(direction='in', @vIsOdd := TRUE, 0), @@ -73767,14 +73767,14 @@ BEGIN * @param vDatedTo Fecha hasta */ - CREATE OR REPLACE TEMPORARY TABLE tmp.`user` + CREATE OR REPLACE TEMPORARY TABLE tmp.`user` SELECT w.id userFk FROM vn.worker w; - + CALL vn.timeControl_calculate(vDatedFrom, vDatedTo); DROP TEMPORARY TABLE tmp.`user`; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -73794,21 +73794,21 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `timeControl_calculateByDepartment`(vDepartmentFk INT, vDatedFrom DATETIME, vDatedTo DATETIME) BEGIN /** - * @param vDepartmentFk + * @param vDepartmentFk * @param vDatedFrom workerTimeControl * @param vDatedTo workerTimeControl */ DROP TEMPORARY TABLE IF EXISTS tmp.`user`; - + CREATE TEMPORARY TABLE tmp.`user` SELECT DISTINCT b.workerFk userFk - FROM business AS b - WHERE (b.started BETWEEN vDatedFrom AND vDatedTo + FROM business AS b + WHERE (b.started BETWEEN vDatedFrom AND vDatedTo OR IFNULL(b.ended, vDatedTo) BETWEEN vDatedFrom AND vDatedTo OR (b.started <= vDatedFrom AND b.ended >= vDatedTo) ) AND b.departmentFk = vDepartmentFk ORDER BY b.ended DESC; - + CALL timeControl_calculate(vDatedFrom, vDatedTo); DROP TEMPORARY TABLE tmp.`user`; @@ -73833,19 +73833,19 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `timeControl_calculateByUser`(vUserF BEGIN /** - * @param vUserFk + * @param vUserFk * @param vDatedFrom workerTimeControl * @param vDatedTo workerTimeControl */ - + DROP TEMPORARY TABLE IF EXISTS tmp.`user`; - + CREATE TEMPORARY TABLE tmp.`user` SELECT id userFk - FROM account.user - WHERE id = vUserFk; + FROM account.user + WHERE id = vUserFk; CALL vn.timeControl_calculate(vDatedFrom, vDatedTo); - + DROP TEMPORARY TABLE tmp.`user`; END ;; @@ -73868,21 +73868,21 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `timeControl_calculateByWorker`(vWor BEGIN /** - * @param vWorkerFk + * @param vWorkerFk * @param vDatedFrom workerTimeControl * @param vDatedTo workerTimeControl */ - + DROP TEMPORARY TABLE IF EXISTS tmp.`user`; - + CREATE TEMPORARY TABLE tmp.`user` SELECT u.id userFk FROM account.user u JOIN vn.worker w ON w.userFk = u.id WHERE w.id = vWorkerFk; - + CALL vn.timeControl_calculate(vDatedFrom, vDatedTo); - + DROP TEMPORARY TABLE tmp.`user`; END ;; @@ -73905,12 +73905,12 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `timeControl_getError`(vDatedFrom DA BEGIN /* * @param vDatedFrom - * @param vDatedTo + * @param vDatedTo * @table tmp.`user`(userFk) * Fichadas incorrectas de las cuales no se puede calcular horas trabajadas * @return tmp.timeControlError (id) */ - DECLARE vDayMaxTime INTEGER; + DECLARE vDayMaxTime INTEGER; SET @journeyCounter := 0; SET @lastUserFk := NULL; @@ -73918,16 +73918,16 @@ BEGIN SELECT dayMaxTime INTO vDayMaxTime FROM workerTimeControlConfig LIMIT 1; - DROP TEMPORARY TABLE IF EXISTS tmp.timeControl; - CREATE TEMPORARY TABLE tmp.timeControl + DROP TEMPORARY TABLE IF EXISTS tmp.timeControl; + CREATE TEMPORARY TABLE tmp.timeControl (INDEX(id), INDEX(journeyCounter)) ENGINE = MEMORY SELECT sub.id, - sub.direction, + sub.direction, sub.timed, IF(sub.direction = 'in' OR @hasOut OR sub.userFk <> @lastUserFk, @journeyCounter := @journeyCounter + 1, @journeyCounter) journeyCounter, - @lastUserFk := sub.userFk workerFk, - IF(sub.direction = 'out', @hasOut:= TRUE, @hasOut:= FALSE) + @lastUserFk := sub.userFk workerFk, + IF(sub.direction = 'out', @hasOut:= TRUE, @hasOut:= FALSE) FROM ( SELECT DISTINCT wtc.id, wtc.direction, @@ -73938,36 +73938,36 @@ BEGIN WHERE wtc.timed BETWEEN DATE_SUB(vDatedFrom, INTERVAL 1 DAY) AND DATE_ADD(vDatedTo, INTERVAL 1 DAY) ORDER BY wtc.userFk, wtc.timed ) sub; - - DROP TEMPORARY TABLE IF EXISTS tmp.timeControlAux; + + DROP TEMPORARY TABLE IF EXISTS tmp.timeControlAux; CREATE TEMPORARY TABLE tmp.timeControlAux (INDEX(id), INDEX(journeyCounter)) ENGINE = MEMORY SELECT * FROM tmp.timeControl; - DROP TEMPORARY TABLE IF EXISTS tmp.timeControlError; - CREATE TEMPORARY TABLE tmp.timeControlError + DROP TEMPORARY TABLE IF EXISTS tmp.timeControlError; + CREATE TEMPORARY TABLE tmp.timeControlError (INDEX(id)) ENGINE = MEMORY - SELECT id + SELECT id FROM tmp.timeControlAux tca JOIN ( - SELECT journeyCounter, + SELECT journeyCounter, UNIX_TIMESTAMP(MAX(timed)) - UNIX_TIMESTAMP(MIN(timed)) timeWork, - SUM(direction = 'in') totalIn, + SUM(direction = 'in') totalIn, SUM(direction = 'out') totalOut, timed FROM tmp.timeControl GROUP BY journeyCounter - HAVING COUNT(*) MOD 2 = 1 - OR totalIn <> 1 - OR totalOut <> 1 + HAVING COUNT(*) MOD 2 = 1 + OR totalIn <> 1 + OR totalOut <> 1 OR timeWork >= vDayMaxTime )sub ON sub.journeyCounter = tca.journeyCounter WHERE sub.timed BETWEEN vDatedFrom AND vDatedTo; - DROP TEMPORARY TABLE IF EXISTS tmp.timeControl; - DROP TEMPORARY TABLE IF EXISTS tmp.timeControlAux; + DROP TEMPORARY TABLE IF EXISTS tmp.timeControl; + DROP TEMPORARY TABLE IF EXISTS tmp.timeControlAux; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -73990,7 +73990,7 @@ proc: BEGIN * deprecated call workerTimeControl_check */ CALL vn.workerTimeControl_check(vUserFk,vDated,vTabletFk); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -74046,12 +74046,12 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `travelVolume`(vTravelFk INT) BEGIN - - SELECT w1.name AS ORI, - w2.name AS DES, + + SELECT w1.name AS ORI, + w2.name AS DES, tr.shipped shipment, tr.landed landing, - a.name Agencia, + a.name Agencia, s.name Proveedor, e.id Id_Entrada, e.invoiceNumber Referencia, @@ -74059,18 +74059,18 @@ BEGIN vn.item_getVolume(b.itemFk ,b.packageFk)) / vc.trolleyM3 / 1000000 ,1) AS DECIMAL(10,2)) AS CC, CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) * vn.item_getVolume(b.itemFk ,b.packageFk)) / vc.palletM3 / 1000000,1) AS DECIMAL(10,2)) AS espais - FROM vn.buy b - JOIN vn.entry e ON e.id = b.entryFk - JOIN vn.supplier s ON s.id = e.supplierFk - JOIN vn.travel tr ON tr.id = e.travelFk + FROM vn.buy b + JOIN vn.entry e ON e.id = b.entryFk + JOIN vn.supplier s ON s.id = e.supplierFk + JOIN vn.travel tr ON tr.id = e.travelFk JOIN vn.agencyMode a ON a.id = tr.agencyModeFk - JOIN vn.warehouse w1 ON w1.id = tr.warehouseInFk - JOIN vn.warehouse w2 ON w2.id = tr.warehouseOutFk - JOIN vn.volumeConfig vc - JOIN vn.item i ON i.id = b.itemFk + JOIN vn.warehouse w1 ON w1.id = tr.warehouseInFk + JOIN vn.warehouse w2 ON w2.id = tr.warehouseOutFk + JOIN vn.volumeConfig vc + JOIN vn.item i ON i.id = b.itemFk JOIN vn.itemType it ON it.id = i.typeFk WHERE tr.id = vTravelFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -74126,11 +74126,11 @@ BEGIN * @param vShipped The shipment date * @param vLanded The landing date */ - + IF vLanded < vShipped THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Landing cannot be lesser than shipment'; - END IF; + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -74194,7 +74194,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `travel_checkWarehouseIsFeedStock`(v proc: BEGIN /* * Check that the warehouse is not Feed Stock - * + * * @vWarehouseFk param warehouse id */ IF vWarehouseFk IS NULL THEN @@ -74282,13 +74282,13 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `travel_cloneWithEntries`( - IN vTravelFk INT, - IN vDateStart DATE, + IN vTravelFk INT, + IN vDateStart DATE, IN vDateEnd DATE, IN vWarehouseOutFk INT, - IN vWarehouseInFk INT, - IN vRef VARCHAR(255), - IN vAgencyModeFk INT, + IN vWarehouseInFk INT, + IN vRef VARCHAR(255), + IN vAgencyModeFk INT, OUT vNewTravelFk INT) BEGIN /** @@ -74312,29 +74312,29 @@ BEGIN FROM entry e JOIN travel t ON t.id = e.travelFk WHERE e.travelFk = vTravelFk; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN + BEGIN ROLLBACK; RESIGNAL; END; - + START TRANSACTION; INSERT INTO travel (shipped, landed, warehouseInFk, warehouseOutFk, agencyModeFk, `ref`, isDelivered, isReceived, m3, cargoSupplierFk, kg,clonedFrom) SELECT vDateStart, vDateEnd, vWarehouseInFk, vWarehouseOutFk, vAgencyModeFk, vRef, isDelivered, isReceived, m3,cargoSupplierFk, kg,vTravelFk FROM travel WHERE id = vTravelFk; - + SET vNewTravelFk = LAST_INSERT_ID(); SET vDone = FALSE; SET @isModeInventory = TRUE; OPEN vRsEntry; - + l: LOOP SET vDone = FALSE; FETCH vRsEntry INTO vAuxEntryFk; @@ -74403,11 +74403,11 @@ BEGIN SELECT COUNT(*) INTO vTotalEntries FROM entry WHERE travelFk = vTravelFk; - + UPDATE travel SET totalEntries = vTotalEntries WHERE id = vTravelFk; - + DELETE FROM travelRecalc WHERE travelFk = vTravelFk; END LOOP; @@ -74438,10 +74438,10 @@ BEGIN WHERE id = vSelf; SELECT e.id entryFk - FROM travel t - JOIN entry e ON e.travelFk = t.id - JOIN buy b ON b.entryFk = e.id - WHERE t.id = vTravelFk + FROM travel t + JOIN entry e ON e.travelFk = t.id + JOIN buy b ON b.entryFk = e.id + WHERE t.id = vTravelFk AND (b.packing IS NULL OR b.packageFk IS NULL); END ;; DELIMITER ; @@ -74464,7 +74464,7 @@ BEGIN /* * Desplaza al dia siguiente los travels que contengan redadas y avisa a los compradores - * + * */ DECLARE vDone BOOL DEFAULT FALSE; DECLARE vWorkerName VARCHAR(50); @@ -74476,7 +74476,7 @@ BEGIN SELECT GROUP_CONCAT( DISTINCT CONCAT('https://salix.verdnatura.es/#!/travel/', ttr.id, '/summary ') ORDER BY ttr.id SEPARATOR '\n\r'), u.name FROM tmp.travel ttr - JOIN entry e ON e.travelFk = ttr.id + JOIN entry e ON e.travelFk = ttr.id JOIN buy b ON b.entryFk = e.id JOIN item i ON i.id = b.itemFk JOIN itemType it ON it.id = i.typeFk @@ -74484,19 +74484,19 @@ BEGIN GROUP BY u.name; DECLARE CONTINUE HANDLER FOR NOT FOUND - SET vDone = TRUE; + SET vDone = TRUE; DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN ROLLBACK; RESIGNAL; END; - + DROP TEMPORARY TABLE IF EXISTS tmp.travel; CREATE TEMPORARY TABLE tmp.travel SELECT tr.id,tr.landed FROM travel tr - JOIN entry e ON e.travelFk = tr.id + JOIN entry e ON e.travelFk = tr.id WHERE tr.landed = util.tomorrow() AND e.isRaid GROUP BY tr.id; @@ -74554,7 +74554,7 @@ proc: BEGIN IF vSelf IS NULL THEN LEAVE proc; END IF; - + INSERT IGNORE INTO travelRecalc SET travelFk = vSelf; END ;; DELIMITER ; @@ -74580,10 +74580,10 @@ BEGIN * @param vItemFk id del item * @param vPacking nuevo packing */ - + DECLARE vAuctionWarehouseFk INT; DECLARE vMainWarehouseFk INT; - + SELECT warehouseFk INTO vAuctionWarehouseFk FROM auctionConfig; @@ -74643,7 +74643,7 @@ BEGIN FROM travelClonedWeekly WHERE travelFk; - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; SET vCounter = vSinceWeek; @@ -74705,12 +74705,12 @@ BEGIN /* * Plantilla para modificar reemplazar todos los tags * por los valores que tienen los articulos - * + * * @param vTypeFk tipo a modificar - * + * */ - DELETE it.* - FROM itemTag it + DELETE it.* + FROM itemTag it JOIN item i ON i.id = it.itemFk WHERE i.typeFk = vTypeFk; @@ -74719,40 +74719,40 @@ BEGIN FROM item i JOIN tag t ON t.name = 'Longitud' COLLATE utf8_general_ci WHERE i.typeFk = vTypeFk; - + INSERT INTO itemTag(itemFk, tagFk, value, priority) SELECT i.id, t.id, i.category, 5 FROM item i JOIN tag t ON t.name = 'Categoria' COLLATE utf8_general_ci WHERE i.typeFk = vTypeFk; - + INSERT INTO itemTag(itemFk, tagFk, value, priority) SELECT i.id, t.id, ink.name, 2 FROM item i JOIN tag t ON t.name = 'Color' COLLATE utf8_general_ci JOIN ink ON ink.id = i.inkFk WHERE i.typeFk = vTypeFk; - + INSERT INTO itemTag(itemFk, tagFk, value, priority) SELECT i.id, t.id, p.name, 3 FROM item i JOIN tag t ON t.name = 'Productor' COLLATE utf8_general_ci JOIN producer p ON p.id = i.producerFk - WHERE i.typeFk = vTypeFk; - + WHERE i.typeFk = vTypeFk; + INSERT INTO itemTag(itemFk, tagFk, value, priority) SELECT i.id, t.id, o.name, 4 FROM item i JOIN tag t ON t.name = 'Origen' COLLATE utf8_general_ci JOIN origin o ON o.id = i.originFk WHERE i.typeFk = vTypeFk; - /* + /* INSERT INTO itemTag(itemFk, tagFk, value, priority) SELECT i.id, t.id, i.stems, 6 FROM item i JOIN tag t ON t.name = 'Tallos' COLLATE utf8_general_ci - WHERE i.typeFk = vTypeFk; - */ + WHERE i.typeFk = vTypeFk; + */ -- CALL itemTagArrangedUpdate(NULL); END ;; @@ -74775,7 +74775,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `updatePedidosInternos`(vItemFk INT) BEGIN UPDATE vn.item SET upToDown = 0 WHERE item.id = vItemFk; - + END ;; DELIMITER ; @@ -74803,7 +74803,7 @@ BEGIN SELECT vp.regex INTO vRegex FROM vehiclePlateRegex vp WHERE vp.countryCodeFk = vCountryCodeFk; - + IF NOT vNumberPlate REGEXP BINARY (vRegex)THEN CALL util.throw(CONCAT('Error: la matricula ', vNumberPlate, ' no es valida para ',vCountryCodeFk)); END IF; @@ -74836,7 +74836,7 @@ proc:BEGIN ROLLBACK; RESIGNAL; END; - + SELECT eventEarlyDays INTO vEventEarlyDays FROM vehicleConfig; @@ -74854,7 +74854,7 @@ proc:BEGIN IF NOT vHasEvents THEN LEAVE proc; END IF; - + START TRANSACTION; SELECT util.notification_send('vehicle-event-expired', @@ -74889,21 +74889,21 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `visible_getMisfit`(vSectorFk INT) BEGIN - + /* Devuelve una tabla temporal con los descuadres entre el visible teórico y lo ubicado en la práctica - * + * * @param vSectorFk Identificador de vn.sector - * + * * @return tmp.stockMisfit(itemFk, visible, parked) */ - + DECLARE vCalcVisibleFk INT; DECLARE vWarehouseFk INT; SELECT warehouseFk INTO vWarehouseFk - FROM vn.sector s + FROM vn.sector s WHERE s.id = vSectorFk; - + CALL cache.visible_refresh(vCalcVisibleFk, FALSE, vWarehouseFk); DROP TEMPORARY TABLE IF EXISTS tmp.stockMisfit; @@ -74916,17 +74916,17 @@ BEGIN INSERT INTO tmp.stockMisfit(itemFk, parked) SELECT iss.itemFk , sum(iss.visible ) - FROM vn.itemShelvingStock iss - JOIN vn.sector s ON s.id = iss.sectorFk + FROM vn.itemShelvingStock iss + JOIN vn.sector s ON s.id = iss.sectorFk WHERE vSectorFk IN (s.id, s.sonFk) GROUP BY iss.itemFk; - + INSERT INTO tmp.stockMisfit(itemFk, visible) - SELECT v.item_id , v.visible - FROM cache.visible v - WHERE v.calc_id = vCalcVisibleFk + SELECT v.item_id , v.visible + FROM cache.visible v + WHERE v.calc_id = vCalcVisibleFk ON DUPLICATE KEY UPDATE visible = v.visible; - + DELETE FROM tmp.stockMisfit WHERE visible = parked; @@ -74950,17 +74950,17 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `warehouseFitting`(IN vWhOrigin INT BEGIN DECLARE vCacheVisibleOriginFk INT; DECLARE vCacheVisibleDestinyFk INT; - + CALL cache.visible_refresh(vCacheVisibleOriginFk, FALSE, vWhOrigin); CALL cache.visible_refresh(vCacheVisibleDestinyFk, FALSE, vWhDestiny); - + SELECT i.id itemFk, i.longName, i.size, i.subName, vOrigin.visible AS Origen, vDestiny.visible Destino - + FROM vn.item i JOIN vn.itemType it ON it.id = i.typeFk LEFT JOIN cache.visible vOrigin ON vOrigin.calc_id = vCacheVisibleOriginFk AND vOrigin.item_id = i.id @@ -74989,13 +74989,13 @@ BEGIN DECLARE vWhOrigin INT; DECLARE vWhDestiny INT; - + SELECT warehouseInFk, warehouseOutFk INTO vWhDestiny, vWhOrigin FROM vn.travel WHERE id = vTravelFk; - + CALL vn.warehouseFitting(vWhOrigin, vWhDestiny); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -75059,7 +75059,7 @@ BEGIN * Calcula los días y horas de vacaciones en función de un contrato y año * * @param vYear - * @param vBusinessFk + * @param vBusinessFk * @return tmp.workerCalendarCalculateBusiness (days, hours, daysEnjoyed, hoursEnjoyed) */ DECLARE vStarted DATE; @@ -75071,17 +75071,17 @@ BEGIN DECLARE vPayedHolidays DECIMAL(5,2); DECLARE vDifDays INT; - SELECT IF(b.started < CONCAT(vYear,"-01-01"), CONCAT(vYear,"-01-01"),b.started), - IF(b.ended IS NULL OR YEAR(b.ended)>vYear , CONCAT(vYear,"-12-31"), b.ended), + SELECT IF(b.started < CONCAT(vYear,"-01-01"), CONCAT(vYear,"-01-01"),b.started), + IF(b.ended IS NULL OR YEAR(b.ended)>vYear , CONCAT(vYear,"-12-31"), b.ended), IF(wbt.hasHolidayEntitlement, w.days, 0), c.hoursWeek, IF(YEAR(b.ended) = vYear, b.payedHolidays, 0) payedHolidays - INTO vStarted, - vEnded, - vDaysHoliday, + INTO vStarted, + vEnded, + vDaysHoliday, vHoursWeek, vPayedHolidays - FROM business b + FROM business b JOIN workerBusinessType wbt ON wbt.id = b.workerBusinessTypeFk JOIN workCenterHoliday w ON w.workcenterFk = b.workcenterFk LEFT JOIN calendarType c ON c.id = b.calendarTypeFk @@ -75089,23 +75089,23 @@ BEGIN AND w.year = vYear; DROP TEMPORARY TABLE IF EXISTS tmp.workerCalendarCalculateBusiness; - + IF vStarted < vEnded THEN SET vDifDays = DAYOFYEAR(vEnded) - DAYOFYEAR(vStarted) + 1; - SELECT IFNULL(SUM(a.holidayEntitlementRate), 0), + SELECT IFNULL(SUM(a.holidayEntitlementRate), 0), SUM(-(a.discountRate - 1)) + vPayedHolidays - INTO vDaysToSubtract, - vDaysHolidayEnjoyed + INTO vDaysToSubtract, + vDaysHolidayEnjoyed FROM calendar c JOIN absenceType a ON a.id = c.dayOffTypeFk JOIN business b ON b.id = c.businessFk - WHERE b.id = vBusinessFk + WHERE b.id = vBusinessFk AND YEAR(c.dated) = vYear; END IF; - CREATE TEMPORARY TABLE tmp.workerCalendarCalculateBusiness + CREATE TEMPORARY TABLE tmp.workerCalendarCalculateBusiness ENGINE = MEMORY SELECT @days := IFNULL(ROUND((vDaysHoliday * (vDifDays - vDaysToSubtract) / IF(util.isLeapYear(vYear) , 366, 365)), 1), 0) days, @days * (vHoursWeek / 5) hours, @@ -75133,32 +75133,32 @@ BEGIN /** * Calcula los días y horas de vacaciones en función de un trabajador y año * - * @param vYear - * @param vWorkerFk + * @param vYear + * @param vWorkerFk * @return tmp.workerCalendarCalculateYear (days, hours, daysEnjoyed, hoursEnjoyed) - */ + */ DECLARE vDone BOOL; DECLARE vBusinessFk INT; DECLARE cur CURSOR FOR - SELECT b.id + SELECT b.id FROM business b - WHERE vYear BETWEEN YEAR(b.started) AND IFNULL(YEAR(b.ended), vYear) + WHERE vYear BETWEEN YEAR(b.started) AND IFNULL(YEAR(b.ended), vYear) AND b.workerFk = vWorkerFk; DECLARE CONTINUE HANDLER FOR NOT FOUND - SET vDone = TRUE; - + SET vDone = TRUE; + DROP TEMPORARY TABLE IF EXISTS tmp.workerCalendarCalculateYear; CREATE TEMPORARY TABLE tmp.workerCalendarCalculateYear - (days DEC(5,2), + (days DEC(5,2), hours DEC(5,2), - daysEnjoyed DEC(5,2), - hoursEnjoyed DEC(5,2)) + daysEnjoyed DEC(5,2), + hoursEnjoyed DEC(5,2)) ENGINE = MEMORY; INSERT INTO tmp.workerCalendarCalculateYear VALUES(0, 0, 0, 0); - + OPEN cur; l: LOOP @@ -75171,12 +75171,12 @@ BEGIN CALL workerCalendar_calculateBusiness(vYear, vBusinessFk); UPDATE tmp.workerCalendarCalculateYear w - JOIN tmp.workerCalendarCalculateBusiness wc + JOIN tmp.workerCalendarCalculateBusiness wc SET w.days = w.days + wc.days, w.hours = w.hours + wc.hours, w.daysEnjoyed = w.daysEnjoyed + wc.daysEnjoyed, w.hoursEnjoyed = w.hoursEnjoyed + wc.hoursEnjoyed; - + DROP TEMPORARY TABLE tmp.workerCalendarCalculateBusiness; END LOOP; @@ -75201,7 +75201,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerCreate`( vFirstname VARCHAR(50), - vLastName VARCHAR(50), + vLastName VARCHAR(50), vCode CHAR(3), vBossFk INT, vUserFk INT, @@ -75213,7 +75213,7 @@ BEGIN * Create new worker * */ - INSERT INTO worker(id, code, firstName, lastName, bossFk, fi, birth,userFk) + INSERT INTO worker(id, code, firstName, lastName, bossFk, fi, birth,userFk) VALUES (vUserFk, vCode, vFirstname, vLastName, vBossFk, vFi, vBirth,vUserFk); END ;; DELIMITER ; @@ -75279,20 +75279,20 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.workerDepartmentByDate; CREATE TEMPORARY TABLE tmp.workerDepartmentByDate ENGINE = MEMORY - SELECT w.id userFk, - w.lastName name, - w.firstName firstname, - d.name department, + SELECT w.id userFk, + w.lastName name, + w.firstName firstname, + d.name department, d.id departmentFk, - b.started, - d.isProduction, + b.started, + d.isProduction, CAST(12 * b.amount / ct.hoursWeek / 52 AS DECIMAL(10,2)) costeHora, w.fi nif FROM business b JOIN calendarType ct ON ct.id = b.calendarTypeFk JOIN department d ON d.id = b.departmentFk JOIN worker w ON w.id = b.workerFk - WHERE b.started <= vDate + WHERE b.started <= vDate AND (b.ended > vDate OR b.ended IS NULL); END ;; DELIMITER ; @@ -75319,18 +75319,18 @@ mainLabel:BEGIN DELETE FROM account.account WHERE id = vUserId; - UPDATE account.user + UPDATE account.user SET role = 2 - WHERE id = vUserId; + WHERE id = vUserId; - DELETE FROM pbx.sip - WHERE user_id = vUserId; + DELETE FROM pbx.sip + WHERE user_id = vUserId; UPDATE `client` c JOIN payMethod p ON p.name = 'CONTADO' SET c.credit = 0, c.payMethodFk = p.id, hasCoreVnl = FALSE WHERE c.id = vUserId; - + UPDATE `client` c SET c.salesPersonFk = null WHERE c.salesPersonFk = vUserId; @@ -75359,12 +75359,12 @@ BEGIN SELECT b.workerFk FROM business b JOIN vn.worker w ON w.id = b.workerFk - JOIN account.account a ON a.id = b.workerFk - LEFT JOIN (SELECT b.workerFk + JOIN account.account a ON a.id = b.workerFk + LEFT JOIN (SELECT b.workerFk FROM business b WHERE (ended IS NULL OR ended >=util.VN_CURDATE()) )sub ON sub.workerFk = a.id - LEFT JOIN vn.workerDisableExcluded wd ON wd.workerFk = b.workerFk + LEFT JOIN vn.workerDisableExcluded wd ON wd.workerFk = b.workerFk WHERE sub.workerFk IS NULL AND wd.workerFk IS NULL GROUP BY w.id; @@ -75382,7 +75382,7 @@ BEGIN END WHILE; CLOSE rs; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -75446,19 +75446,19 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerJourney_replace`( - vDatedFrom DATE, - vDatedTo DATE, + vDatedFrom DATE, + vDatedTo DATE, vWorkerFk INT) BEGIN /** - * Actualiza la tabla workerJourney para que actue como caché permanente revisable + * Actualiza la tabla workerJourney para que actue como caché permanente revisable * de las jornadas laborales. * @param vDatedFrom workerTimeControl * @param vDatedTo workerTimeControl * @param vWorkerFk, en caso de pasar 0 ó NULL se aplica a todos - */ + */ DECLARE vDatedTimeTo DATETIME; - DECLARE vMaxTimePerDay INT; + DECLARE vMaxTimePerDay INT; DECLARE vMinHoursToBreak DECIMAL(10,2); DECLARE vBreakHours DECIMAL(10,2); DECLARE vMonthByYear INT; @@ -75466,57 +75466,57 @@ BEGIN DECLARE vMonthsByYear INT DEFAULT 12; DECLARE vDaysByWeek INT DEFAULT 5; DECLARE vDatedFromYesterday DATETIME; - DECLARE vDatedToTomorrow DATETIME; - - SELECT DATE_SUB(vDatedFrom, INTERVAL 1 DAY), DATE_ADD(vDatedTo, INTERVAL 1 DAY) + DECLARE vDatedToTomorrow DATETIME; + + SELECT DATE_SUB(vDatedFrom, INTERVAL 1 DAY), DATE_ADD(vDatedTo, INTERVAL 1 DAY) INTO vDatedFromYesterday, vDatedToTomorrow; SET vDatedTimeTo = util.dayEnd(vDatedTo); - - SELECT minHoursToBreak, breakHours, maxTimePerDay + + SELECT minHoursToBreak, breakHours, maxTimePerDay INTO vMinHoursToBreak, vBreakHours, vMaxTimePerDay FROM workerTimeControlConfig; DELETE FROM workerJourney - WHERE dated BETWEEN vDatedFrom AND vDatedTo + WHERE dated BETWEEN vDatedFrom AND vDatedTo AND NOT isPaid AND NOT isUpdated - AND (vWorkerFk IS NULL OR userFK = vWorkerFk); + AND (vWorkerFk IS NULL OR userFK = vWorkerFk); - -- Se inserta todos los días del periodo por worker y business en el rango de fechas. + -- Se inserta todos los días del periodo por worker y business en el rango de fechas. INSERT IGNORE INTO workerJourney(userFk, dated, businessFk) SELECT b.workerFk, t.dated, b.id - FROM business b + FROM business b JOIN time t ON t.dated BETWEEN b.started AND IFNULL(b.ended,util.VN_CURDATE()) WHERE t.dated BETWEEN vDatedFrom AND vDatedTo AND (vWorkerFk IS NULL OR b.workerFk = vWorkerFk) ORDER BY b.workerFk, t.dated, b.id; - + DROP TEMPORARY TABLE IF EXISTS tmp.`user`; IF vWorkerFk THEN CALL timeControl_calculateByUser(vWorkerFk, vDatedFrom , vDatedTimeTo); - CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` - SELECT vWorkerFk userFk; + CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` + SELECT vWorkerFk userFk; ELSE CALL timeControl_calculateAll(vDatedFrom, vDatedTimeTo); - CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` + CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` SELECT id userFk FROM worker w; - END IF; + END IF; UPDATE workerJourney wj JOIN tmp.timeControlCalculate t ON wj.dated = t.dated AND wj.userFk = t.userFk - SET wj.total = CAST(IF(t.timeWorkDecimal >= vMinHoursToBreak, - t.timeWorkDecimal - vBreakHours, + SET wj.total = CAST(IF(t.timeWorkDecimal >= vMinHoursToBreak, + t.timeWorkDecimal - vBreakHours, t.timeWorkDecimal) AS DECIMAL (10,2)), wj.lunch = IF(t.timeWorkDecimal >= vMinHoursToBreak , vBreakHours , 0) WHERE wj.dated BETWEEN vDatedFrom AND vDatedTo AND NOT wj.isPaid AND NOT wj.isUpdated AND (vWorkerFk IS NULL OR wj.userFk = vWorkerFk); - - -- NOCTURNIDAD + + -- NOCTURNIDAD CALL timeControl_getError(vDatedFrom, vDatedTimeTo); SET @vIsOdd := TRUE; @@ -75526,9 +75526,9 @@ BEGIN CREATE TEMPORARY TABLE tmp.workerTimeControl (INDEX (userFk), INDEX (timed)) ENGINE = MEMORY - SELECT DISTINCT(wtc.id), - wtc.userFk, - wtc.timed, + SELECT DISTINCT(wtc.id), + wtc.userFk, + wtc.timed, wtc.direction FROM workerTimeControl wtc JOIN tmp.`user` w ON w.userFk = wtc.userFk @@ -75538,10 +75538,10 @@ BEGIN AND (vWorkerFk IS NULL OR wtc.userFk = vWorkerFk) ORDER BY wtc.userFk, wtc.timed ASC; - SELECT MAX(id) INTO @vCont + SELECT MAX(id) INTO @vCont FROM tmp.workerTimeControl; - DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControlAux; + DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControlAux; CREATE TEMPORARY TABLE tmp.workerTimeControlAux ( `id` int(11) , `userFk` int(10) unsigned , @@ -75563,9 +75563,9 @@ BEGIN DATE(@lastTimed) dated, @lastUserFk lastUserFk, IF(direction ='middle', @vIsOdd := NOT @vIsOdd, FALSE) isOdd, - IF(@vIsOdd - AND @lastDirection = 'middle' - AND (DATE(@lastTimed) <> date(timed) + IF(@vIsOdd + AND @lastDirection = 'middle' + AND (DATE(@lastTimed) <> date(timed) OR @lastUserFk <> userFk), TRUE, FALSE) hasBreak, @lastTimed := wtc.timed, @lastUserFk := userFk, @@ -75579,16 +75579,16 @@ BEGIN SET @lastDirection := NULL; INSERT INTO tmp.workerTimeControlAux (id, userFk, timed, direction) - SELECT @vCont:= @vCont + 1, - lastUserFk, - DATE_ADD(sub.dated, INTERVAL 1 DAY), + SELECT @vCont:= @vCont + 1, + lastUserFk, + DATE_ADD(sub.dated, INTERVAL 1 DAY), 'middle' FROM (SELECT IF(@lastUserFk <> userFk, @vIsOdd := TRUE, NULL), DATE(@lastTimed) dated, @lastUserFk lastUserFk, IF(direction ='middle', @vIsOdd := NOT @vIsOdd, FALSE) isOdd, - IF(@vIsOdd - AND @lastDirection = 'middle' + IF(@vIsOdd + AND @lastDirection = 'middle' AND (DATE(@lastTimed)<>date(timed) OR @lastUserFk<>userFk), TRUE, FALSE) hasBreak, @lastTimed := wtc.timed, @@ -75601,7 +75601,7 @@ BEGIN -- Cambio de dia INSERT INTO tmp.workerTimeControlAux (id, userFk, timed, direction) SELECT @vCont:= @vCont + 1, - wtc.userFk, + wtc.userFk, util.dayEnd(date(wtc.timed)), 'out' FROM workerTimeControl wtc @@ -75612,8 +75612,8 @@ BEGIN GROUP BY wtc.userFk, DATE(wtc.timed); INSERT INTO tmp.workerTimeControlAux (id, userFk, timed, direction) - SELECT @vCont:= @vCont + 1, - wtc.userFk, + SELECT @vCont:= @vCont + 1, + wtc.userFk, DATE_ADD(date(wtc.timed), INTERVAL 1 DAY), 'in' FROM workerTimeControl wtc @@ -75639,8 +75639,8 @@ BEGIN IF(@vIsOdd, @vLastTimed:=UNIX_TIMESTAMP(timed),@vLastTimed), IF(direction='in', @vDated := DATE(wtc.timed), @vDated ) dated, wtc.userFk, - IF(UNIX_TIMESTAMP(timed)- @vLastTimed < vMaxTimePerDay, - workerNigthlyHours_calculate(FROM_UNIXTIME(@vLastTimed), wtc.timed), + IF(UNIX_TIMESTAMP(timed)- @vLastTimed < vMaxTimePerDay, + workerNigthlyHours_calculate(FROM_UNIXTIME(@vLastTimed), wtc.timed), 0) NigthlyHours, @lastUserFk := userFk FROM (SELECT DISTINCT(wtc.id), wtc.userFk, wtc.timed, wtc.direction @@ -75653,7 +75653,7 @@ BEGIN ) wtc ORDER BY wtc.userFk, wtc.timed )sub - WHERE sub.dated BETWEEN vDatedFrom AND vDatedTo + WHERE sub.dated BETWEEN vDatedFrom AND vDatedTo GROUP BY userFk, sub.dated )night ON night.userFk = wj.userFk AND night.dated = wj.dated SET wj.nocturn = night.NigthlyHours @@ -75665,8 +75665,8 @@ BEGIN UPDATE workerJourney wj JOIN business b ON b.id = wj.businessFk JOIN calendarType ct ON ct.id = b.calendarTypeFk - SET wj.priceOrdinaryHour = - (vMonthsByYear * b.amount) / + SET wj.priceOrdinaryHour = + (vMonthsByYear * b.amount) / (vWeeksByYear * ct.hoursWeek), wj.contractJourney = ct.hoursWeek / vDaysByWeek WHERE wj.dated BETWEEN vDatedFrom AND vDatedTo @@ -75674,7 +75674,7 @@ BEGIN AND NOT wj.isPaid AND NOT isUpdated; - -- Precio Extras, Vacaciones y Nocturnas + -- Precio Extras, Vacaciones y Nocturnas UPDATE workerJourney wj JOIN(SELECT MAX(w.dated), t.dated, w.holidayInc, w.nightInc, w.extraInc FROM time t @@ -75698,12 +75698,12 @@ BEGIN WHERE ct.isPartial AND wj.dated BETWEEN vDatedFrom AND vDatedTo AND (vWorkerFk IS NULL OR wj.userFk = vWorkerFk) - AND NOT wj.isPaid + AND NOT wj.isPaid AND NOT wj.isUpdated; -- Ausencias UPDATE workerJourney wj - JOIN businessCalendar bc ON bc.businessFk = wj.businessFk + JOIN businessCalendar bc ON bc.businessFk = wj.businessFk AND bc.dated = wj.dated JOIN absenceType ab ON ab.id = bc.absenceTypeFk SET wj.permission = ab.permissionRate * wj.contractJourney, @@ -75718,7 +75718,7 @@ BEGIN UPDATE workerJourney SET holiday = IF(DAYNAME(dated)='sábado', 0, total), contractJourney = 0 - WHERE DAYNAME(dated) IN ('sábado', 'domingo') + WHERE DAYNAME(dated) IN ('sábado', 'domingo') AND dated BETWEEN vDatedFrom AND vDatedTo AND (vWorkerFk IS NULL OR userFk = vWorkerFk) AND NOT isPaid @@ -75727,8 +75727,8 @@ BEGIN -- Festivos por centro de trabajo UPDATE workerJourney wj JOIN calendarHolidays ch ON ch.dated = wj.dated - JOIN business b ON b.id = wj.businessFk - AND b.workcenterFk = ch.workcenterFk + JOIN business b ON b.id = wj.businessFk + AND b.workcenterFk = ch.workcenterFk SET wj.holiday = wj.total, wj.permission = wj.contractJourney, wj.contractJourney = 0 @@ -75738,7 +75738,7 @@ BEGIN AND NOT wj.isUpdated; -- Horas extras - UPDATE workerJourney + UPDATE workerJourney SET extra = lunch + total - contractJourney WHERE dated BETWEEN vDatedFrom AND vDatedTo AND (vWorkerFk IS NULL OR userFk = vWorkerFk) @@ -75768,15 +75768,15 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerMistakeType_get`() BEGIN - + /** * Obtiene los tipos de error para los trabajadores */ - - SELECT code, description - FROM workerMistakeType + + SELECT code, description + FROM workerMistakeType ORDER BY description; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -75803,7 +75803,7 @@ BEGIN * */ INSERT INTO vn.workerMistake(userFk, workerMistakeTypeFk) - VALUES(vWorkerFk, vWorkerMistakeTypeFk); + VALUES(vWorkerFk, vWorkerMistakeTypeFk); END ;; DELIMITER ; @@ -75826,11 +75826,11 @@ BEGIN /*INSERT INTO workerTimeControl(userFk, timed, manual, warehouseFk) VALUES(vUserFk, vDated, FALSE, vWarehouseFk); - + CALL vn.workerTimeControlSOWP(vUserFk , vDated);*/ - + CALL vn.workerTimeControl_add(vUserFk,vWarehouseFk,util.VN_NOW(),FALSE); - + END ;; DELIMITER ; @@ -75856,8 +75856,8 @@ BEGIN * */ - - + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -75906,13 +75906,13 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControlSOWP`(IN vUserFk INT, IN vDated DATE) BEGIN SET @order := 0; - - UPDATE workerTimeControl - SET `order` = @order := @order + 1 - WHERE vUserFk =userFk + + UPDATE workerTimeControl + SET `order` = @order := @order + 1 + WHERE vUserFk =userFk AND vDated = DATE(timed) ORDER BY timed; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -75931,8 +75931,8 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControl_add`(IN vUserFk INT, IN vWarehouseFk INT, IN vTimed DATETIME, IN vIsManual BOOL) BEGIN - - + + SELECT workerTimeControl_add(vUserFk,vWarehouseFk,vTimed,vIsManual); END ;; DELIMITER ; @@ -76020,73 +76020,73 @@ proc: BEGIN DECLARE vTo VARCHAR(50) DEFAULT NULL; DECLARE vUserName VARCHAR(50) DEFAULT NULL; DECLARE vBody VARCHAR(255) DEFAULT NULL; - - SELECT dayBreak, weekBreak, weekScope, dayWorkMax, dayStayMax + + SELECT dayBreak, weekBreak, weekScope, dayWorkMax, dayStayMax INTO vDayBreak, vWeekBreak, vWeekScope, vDayWorkMax, vDayStayMax FROM workerTimeControlParams; SELECT MAX(timed) INTO vLastIn - FROM workerTimeControl - WHERE userFk = vUserFk + FROM workerTimeControl + WHERE userFk = vUserFk AND direction = 'in'; - + SELECT MAX(timed) INTO vLastOut - FROM workerTimeControl - WHERE userFk = vUserFk - AND direction = 'out'; + FROM workerTimeControl + WHERE userFk = vUserFk + AND direction = 'out'; SELECT CONCAT(u.name,'@verdnatura.es') INTO vTo FROM account.user u - WHERE u.id = (SELECT bossFk FROM worker WHERE id = vUserFk); - + WHERE u.id = (SELECT bossFk FROM worker WHERE id = vUserFk); + SELECT CONCAT(firstName,' ',lastName) INTO vUserName FROM worker w WHERE w.id = vUserFk; IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastIn) > vDayStayMax THEN -- NUEVA JORNADA - - -- VERIFICAR DESCANSO DIARIO - IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastOut) < vDayBreak THEN + + -- VERIFICAR DESCANSO DIARIO + IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastOut) < vDayBreak THEN SELECT "Descansos 12 h" AS problem; -- ENVIAMOS CORREO AL BOSSFK SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Descansos 12 h") INTO vBody; CALL mail_insert(vTo,vTo,'error al fichar',vBody); LEAVE proc; - END IF; - + END IF; + -- VERIFICAR FICHADAS IMPARES DEL ÚLTIMO DÍA QUE SE FICHÓ - IF (SELECT MOD(COUNT(*),2) -- <>0 - FROM workerTimeControl + IF (SELECT MOD(COUNT(*),2) -- <>0 + FROM workerTimeControl WHERE userFk = vUserFk AND timed >= vLastIn - ) THEN + ) THEN SELECT "Dias con fichadas impares" AS problem; -- ENVIAMOS CORREO AL BOSSFK SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Dias con fichadas impares") INTO vBody; CALL mail_insert(vTo,vTo,'error al fichar',vBody); - LEAVE proc; + LEAVE proc; END IF; - + -- VERIFICAR VACACIONES SELECT at2.name INTO vCalendarStateType - FROM calendar c + FROM calendar c JOIN business b ON b.id = c.businessFk JOIN absenceType at2 ON at2.id = c.dayOffTypeFk WHERE c.dated = util.VN_CURDATE() AND at2.isAllowedToWork = FALSE AND b.workerFk = vUserFk LIMIT 1; - + IF(LENGTH(vCalendarStateType)) THEN SELECT vCalendarStateType AS problem; -- ENVIAMOS CORREO AL BOSSFK SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Vacaciones") INTO vBody; CALL mail_insert(vTo,vTo,'error al fichar',vBody); - LEAVE proc; - + LEAVE proc; + END IF; - + -- VERIFICAR CONTRATO EN VIGOR IF (SELECT COUNT(*) FROM business b @@ -76098,44 +76098,44 @@ proc: BEGIN -- ENVIAMOS CORREO AL BOSSFK SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"No hay un contrato en vigor") INTO vBody; CALL mail_insert(vTo,vTo,'error al fichar',vBody); - LEAVE proc; - + LEAVE proc; + END IF; -- VERIFICAR DESCANSO SEMANAL SET @vHasBreakWeek:= FALSE; - SET @vLastTimed:= UNIX_TIMESTAMP((util.VN_NOW() - INTERVAL vWeekScope SECOND)); - + SET @vLastTimed:= UNIX_TIMESTAMP((util.VN_NOW() - INTERVAL vWeekScope SECOND)); + DROP TEMPORARY TABLE IF EXISTS tmp.trash; CREATE TEMPORARY TABLE tmp.trash SELECT IF(vWeekBreak-(UNIX_TIMESTAMP(timed)-@vLastTimed) <= 0, @vHasBreakWeek:=TRUE, TRUE) alias, @vLastTimed:= UNIX_TIMESTAMP(timed) - FROM workerTimeControl + FROM workerTimeControl WHERE timed>= (util.VN_NOW() - INTERVAL vWeekScope SECOND) AND userFk= vUserFk AND direction IN ('in','out') - ORDER BY timed ASC; - - IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastOut) < vWeekBreak AND @vHasBreakWeek = FALSE THEN -- REVISA SI EL DESCANSO SE HA REALIZADO DESPUÉS DE LA ÚLTIMA FICHADA + ORDER BY timed ASC; + + IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastOut) < vWeekBreak AND @vHasBreakWeek = FALSE THEN -- REVISA SI EL DESCANSO SE HA REALIZADO DESPUÉS DE LA ÚLTIMA FICHADA SELECT "Descansos 36 h" AS problem; -- ENVIAMOS CORREO AL BOSSFK SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Descansos 36 h") INTO vBody; CALL mail_insert(vTo,vTo,'error al fichar',vBody); LEAVE proc; END IF; - - DROP TEMPORARY TABLE tmp.trash; - ELSE -- DIA ACTUAL - + DROP TEMPORARY TABLE tmp.trash; + + ELSE -- DIA ACTUAL + -- VERIFICA QUE EL TIEMPO EFECTIVO NO SUPERE EL MÁXIMO - SELECT IFNULL(SUM(if( mod(wtc.order,2)=1, -UNIX_TIMESTAMP(timed), UNIX_TIMESTAMP(timed))),0) - IF( MOD(COUNT(*),2), UNIX_TIMESTAMP(util.VN_NOW()), 0) INTO vTimedWorked + SELECT IFNULL(SUM(if( mod(wtc.order,2)=1, -UNIX_TIMESTAMP(timed), UNIX_TIMESTAMP(timed))),0) - IF( MOD(COUNT(*),2), UNIX_TIMESTAMP(util.VN_NOW()), 0) INTO vTimedWorked FROM workerTimeControl wtc - WHERE userFk = vUserFk + WHERE userFk = vUserFk AND timed >= vLastIn ORDER BY timed; - IF vTimedWorked > vDayWorkMax THEN + IF vTimedWorked > vDayWorkMax THEN SELECT "Jornadas" AS problem; -- ENVIAMOS CORREO AL BOSSFK SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Jornadas") INTO vBody; @@ -76158,10 +76158,10 @@ proc: BEGIN -- ENVIAMOS CORREO AL BOSSFK SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"No perteneces a este departamento.") INTO vBody; CALL mail_insert(vTo,vTo,'error al fichar',vBody); - LEAVE proc; + LEAVE proc; END IF; END IF;*/ - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -76181,7 +76181,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControl_checkBreak`(vStarted DATE) BEGIN /** - * Retorna los trabajadores que no han respetado el descanso semanal de 36/72 horas + * Retorna los trabajadores que no han respetado el descanso semanal de 36/72 horas * El sistema verificará el descanso corto en la siguiente semana * o el largo en las 2 siguientes semanas a partir de la fecha dada * @param vStarted día inicio de la semana en el que se quiere verificar @@ -76192,27 +76192,27 @@ BEGIN DECLARE vShortWeekBreak INT; DECLARE vLongWeekBreak INT; - SELECT util.dayEnd(DATE_ADD(vStarted, INTERVAL shortWeekDays DAY)), + SELECT util.dayEnd(DATE_ADD(vStarted, INTERVAL shortWeekDays DAY)), util.dayEnd(DATE_ADD(vStarted, INTERVAL longWeekDays DAY)), - shortWeekBreak, + shortWeekBreak, longWeekBreak INTO vShortEnded, vLongEnded, vShortWeekBreak, vLongWeekBreak FROM workerTimeControlConfig; - + SET @previousTimed:= UNIX_TIMESTAMP(vStarted); SET @lastUserFk := NULL; - + -- Descanso corto en la semana - + DROP TEMPORARY TABLE IF EXISTS tmp.worker; CREATE TEMPORARY TABLE tmp.worker (PRIMARY KEY(workerFk)) ENGINE = MEMORY SELECT DISTINCT userFk workerFk - FROM workerTimeControl + FROM workerTimeControl WHERE timed BETWEEN vStarted AND vShortEnded AND direction IN ('in', 'out'); - + DROP TEMPORARY TABLE IF EXISTS tmp.worker2; CREATE TEMPORARY TABLE tmp.worker2 (PRIMARY KEY(workerFk)) @@ -76225,28 +76225,28 @@ BEGIN SELECT sub2.userFk workerFk FROM(SELECT sub.userFk, IF(sub.userFk <> @lastUserFk, - @previousTimed:= sub.timed, + @previousTimed:= sub.timed, FALSE), - IF(sub.timed - @previousTimed >= vShortWeekBreak, - TRUE, + IF(sub.timed - @previousTimed >= vShortWeekBreak, + TRUE, FALSE) hasShortWeekBreak, @previousTimed:= sub.timed, @lastUserFk:= sub.userFk FROM ( SELECT userFk, UNIX_TIMESTAMP(timed) timed - FROM workerTimeControl + FROM workerTimeControl WHERE timed BETWEEN vStarted AND vShortEnded AND direction IN ('in', 'out') - UNION + UNION SELECT w.workerFk, UNIX_TIMESTAMP(IFNULL( - MIN(wtc.timed), + MIN(wtc.timed), DATE_ADD(vShortEnded, INTERVAL vShortWeekBreak SECOND))) FROM tmp.worker w - LEFT JOIN workerTimeControl wtc - ON wtc.userFk = w.workerFk - AND wtc.timed BETWEEN vShortEnded - AND DATE_ADD(vShortEnded, INTERVAL vShortWeekBreak SECOND) + LEFT JOIN workerTimeControl wtc + ON wtc.userFk = w.workerFk + AND wtc.timed BETWEEN vShortEnded + AND DATE_ADD(vShortEnded, INTERVAL vShortWeekBreak SECOND) GROUP BY w.workerFk UNION SELECT w.workerFk, @@ -76254,10 +76254,10 @@ BEGIN MAX(wtc.timed), DATE_SUB(vStarted, INTERVAL vShortWeekBreak SECOND))) FROM tmp.worker2 w - LEFT JOIN workerTimeControl wtc - ON wtc.userFk = w.workerFk - AND wtc.timed BETWEEN - DATE_SUB(vStarted, INTERVAL vShortWeekBreak SECOND) + LEFT JOIN workerTimeControl wtc + ON wtc.userFk = w.workerFk + AND wtc.timed BETWEEN + DATE_SUB(vStarted, INTERVAL vShortWeekBreak SECOND) AND vStarted GROUP BY w.workerFk ORDER BY userFk, timed @@ -76267,7 +76267,7 @@ BEGIN GROUP BY sub2.userFk HAVING NOT SUM(hasShortWeekBreak); - -- Descanso largo en las 2 siguientes semanas + -- Descanso largo en las 2 siguientes semanas DROP TEMPORARY TABLE tmp.worker; CREATE TEMPORARY TABLE tmp.worker (PRIMARY KEY(workerFk)) @@ -76287,12 +76287,12 @@ BEGIN (PRIMARY KEY(workerFk)) ENGINE = MEMORY SELECT sub2.userFk workerFk - FROM(SELECT userFk, + FROM(SELECT userFk, IF(userFk <> @lastUserFk, - @previousTimed:= timed, + @previousTimed:= timed, TRUE), - IF(timed - @previousTimed >= vLongWeekBreak, - TRUE, + IF(timed - @previousTimed >= vLongWeekBreak, + TRUE, FALSE) hasLongWeekBreak, @previousTimed:= timed, @lastUserFk:= userFk @@ -76301,24 +76301,24 @@ BEGIN JOIN tmp.workerWithoutShortWeekBreak wws ON wws.workerFk = wtc.userFk WHERE timed BETWEEN vStarted AND vLongEnded AND direction IN ('in', 'out') - UNION + UNION SELECT w.workerFk, - UNIX_TIMESTAMP(IFNULL(MIN(wtc.timed), + UNIX_TIMESTAMP(IFNULL(MIN(wtc.timed), DATE_ADD(vLongEnded, INTERVAL vLongWeekBreak SECOND))) FROM tmp.worker w - LEFT JOIN workerTimeControl wtc - ON wtc.userFk = w.workerFk - AND timed BETWEEN vLongEnded - AND DATE_ADD(vLongEnded, INTERVAL vLongWeekBreak SECOND) + LEFT JOIN workerTimeControl wtc + ON wtc.userFk = w.workerFk + AND timed BETWEEN vLongEnded + AND DATE_ADD(vLongEnded, INTERVAL vLongWeekBreak SECOND) GROUP BY w.workerFk UNION - SELECT w.workerFk, - UNIX_TIMESTAMP(IFNULL(MAX(wtc.timed), + SELECT w.workerFk, + UNIX_TIMESTAMP(IFNULL(MAX(wtc.timed), DATE_SUB(vStarted, INTERVAL vLongWeekBreak SECOND))) FROM tmp.worker2 w - LEFT JOIN workerTimeControl wtc - ON wtc.userFk = w.workerFk - AND timed BETWEEN DATE_SUB(vStarted, INTERVAL vLongWeekBreak SECOND) + LEFT JOIN workerTimeControl wtc + ON wtc.userFk = w.workerFk + AND timed BETWEEN DATE_SUB(vStarted, INTERVAL vLongWeekBreak SECOND) AND vStarted GROUP BY w.workerFk ORDER BY userFk, timed @@ -76695,27 +76695,27 @@ BEGIN * Devuelve que direcciones de fichadas son lógicas a partir de la anterior fichada * @param vWorkerFk Identificador del trabajador * @return (option1, option2) - * Los valores posibles de retorno son ('in', 'inMiddle', 'outMiddle', 'out') + * Los valores posibles de retorno son ('in', 'inMiddle', 'outMiddle', 'out') */ DECLARE vLastIn DATETIME ; DECLARE vIsMiddleOdd BOOLEAN ; - IF (vTimed IS NULL) THEN + IF (vTimed IS NULL) THEN SET vTimed = util.VN_NOW(); END IF; - + SELECT timed INTO vLastIn - FROM workerTimeControl + FROM workerTimeControl WHERE userFk = vWorkerFk - AND direction = 'in' + AND direction = 'in' AND timed < vTimed ORDER BY timed DESC LIMIT 1; - + SELECT (COUNT(*)mod 2 = 1) INTO vIsMiddleOdd - FROM workerTimeControl + FROM workerTimeControl WHERE userFk = vWorkerFk - AND direction = 'middle' + AND direction = 'middle' AND timed BETWEEN vLastIn AND util.VN_NOW(); DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControlDirection; @@ -76764,7 +76764,7 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControl_getClockIn`( - vUserFk INT, + vUserFk INT, vDated DATE) BEGIN /** @@ -76774,9 +76774,9 @@ BEGIN * @param vDated Fecha proporcionada */ CALL timeControl_calculateByWorker( - vUserFk, + vUserFk, DATE_SUB(vDated, INTERVAL 6 DAY), util.dayEnd(vDated)); - + SET @position := 0; SET @lastDated := NULL; @@ -76793,7 +76793,7 @@ BEGIN MAX(2daysAgoDirection) 2daysAgoDirection, MAX(1daysAgo) 1daysAgo, MAX(1daysAgoDirection) 1daysAgoDirection, - MAX(0daysAgo) 0daysAgo, + MAX(0daysAgo) 0daysAgo, MAX(0daysAgoDirection) 0daysAgoDirection FROM(SELECT IF(daysAgo = 6, timed, '') 6daysAgo, IF(daysAgo = 5, timed, '') 5daysAgo, @@ -76813,7 +76813,7 @@ BEGIN direction, position FROM(SELECT DATEDIFF(vDated, timed) daysAgo, - TIME_FORMAT(timed,'%H:%i') timed, + TIME_FORMAT(timed,'%H:%i') timed, IF(DATE(timed) <> @lastDated, @position := 0, NULL), @position := @position+1 position, @lastDated := DATE(timed), @@ -76825,18 +76825,18 @@ BEGIN LIMIT 10000000000000000000 )sub )sub2 - GROUP BY position) sub3 + GROUP BY position) sub3 JOIN (SELECT MAX(IF(daysAgo = 6, timeWorkSeconds, 0)) 6daysAgoTotal, MAX(IF(daysAgo = 5, timeWorkSeconds, 0)) 5daysAgoTotal, MAX(IF(daysAgo = 4, timeWorkSeconds, 0)) 4daysAgoTotal, MAX(IF(daysAgo = 3, timeWorkSeconds, 0)) 3daysAgoTotal, MAX(IF(daysAgo = 2, timeWorkSeconds, 0)) 2daysAgoTotal, MAX(IF(daysAgo = 1, timeWorkSeconds, 0)) 1daysAgoTotal, - MAX(IF(daysAgo = 0, timeWorkSeconds, 0)) 0daysAgoTotal + MAX(IF(daysAgo = 0, timeWorkSeconds, 0)) 0daysAgoTotal FROM (SELECT DATEDIFF(vDated, dated) daysAgo, timeWorkSeconds FROM tmp.timeControlCalculate) sub4)sub5 ON TRUE; - + DROP TEMPORARY TABLE tmp.timeControlCalculate; END ;; DELIMITER ; @@ -76900,45 +76900,45 @@ BEGIN DECLARE vDirectionPrevious VARCHAR(6); DECLARE vTimedPrevious DATETIME; - SELECT direction INTO vDirectionRemove - FROM vn.workerTimeControl - WHERE userFk = vUserFk + SELECT direction INTO vDirectionRemove + FROM vn.workerTimeControl + WHERE userFk = vUserFk AND timed = vTimed ; IF vDirectionRemove = 'out' THEN - + SELECT timed, direction INTO vTimedPrevious, vDirectionPrevious - FROM vn.workerTimeControl - WHERE userFk = vUserFk + FROM vn.workerTimeControl + WHERE userFk = vUserFk AND timed < vTimed ORDER BY timed DESC - LIMIT 1; - + LIMIT 1; + IF vDirectionPrevious = "middle" THEN - UPDATE vn.workerTimeControl + UPDATE vn.workerTimeControl SET direction = "out" WHERE userFk = vUserFk AND timed = vTimedPrevious; END IF; - + ELSE IF vDirectionRemove = 'in' THEN - UPDATE vn.workerTimeControl + UPDATE vn.workerTimeControl SET direction = "in" WHERE userFk = vUserFk AND timed > vTimed ORDER BY timed ASC - LIMIT 1; + LIMIT 1; END IF; - + END IF; - + DELETE FROM vn.workerTimeControl - WHERE userFk = vUserFk + WHERE userFk = vUserFk AND timed = vTimed; - + CALL vn.workerTimeControlSOWP(vUserFk, vTimed); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -76966,31 +76966,31 @@ proc: BEGIN UPDATE vn.workerTimeControl SET direction = 'middle'; /*2- poner los out*/ -UPDATE vn.workerTimeControl wtc - JOIN +UPDATE vn.workerTimeControl wtc + JOIN (SELECT userFk,MAX(timed) maxTimed FROM (SELECT id, userFk, timed, date(timed) dated - FROM vn.workerTimeControl - ) sub + FROM vn.workerTimeControl + ) sub GROUP BY userFk,dated )sub SET direction = "out" - WHERE wtc.userFk = sub.userFk + WHERE wtc.userFk = sub.userFk AND wtc.timed = sub.maxTimed; - - /*3- poner los in*/ -UPDATE vn.workerTimeControl wtc - JOIN + + /*3- poner los in*/ +UPDATE vn.workerTimeControl wtc + JOIN (SELECT userFk,MIN(timed) maxTimed FROM (SELECT id, userFk, timed, date(timed) dated - FROM vn.workerTimeControl - ) sub + FROM vn.workerTimeControl + ) sub GROUP BY userFk,dated )sub SET direction = "in" - WHERE wtc.userFk = sub.userFk - AND wtc.timed = sub.maxTimed ; - + WHERE wtc.userFk = sub.userFk + AND wtc.timed = sub.maxTimed ; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -77063,7 +77063,7 @@ BEGIN AND w.businessFk GROUP BY tm.userFk,t.dated ORDER BY tm.userFk,t.dated; - + INSERT INTO vn.mail (receiver, replyTo, subject, body) SELECT eu.email, 'laboral@verdnatura.es', CONCAT('Registro de horas semana ', WEEK(vDatedFrom), ' año ', YEAR(vDatedFrom)) , CONCAT(' @@ -77155,7 +77155,7 @@ BEGIN IF (DAYNAME(util.VN_CURDATE()) = 'miércoles') THEN SELECT DATE_SUB(util.VN_CURDATE(), INTERVAL 9 DAY), CONCAT(DATE_SUB(util.VN_CURDATE(), INTERVAL 3 DAY), ' 23:59:59') INTO vDatedFrom, vDatedTo; - + CALL vn.workerTimeControl_sendMailByDepartment(vDatedFrom, vDatedTo, NULL); END IF; END ;; @@ -77205,9 +77205,9 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControl_weekCheckBreak`(vStarted DATE, vEnded DATE) BEGIN /** - * Retorna los trabajadores que no han respetado el descanso semanal de 36/72 horas - * El sistema verificará el descanso corto en la siguiente semana - * o el largo en las 2 siguientes semanas a partir de las fechas dadas + * Retorna los trabajadores que no han respetado el descanso semanal de 36/72 horas + * El sistema verificará el descanso corto en la siguiente semana + * o el largo en las 2 siguientes semanas a partir de las fechas dadas * @param vStarted día inicio para verificar * @param vEnded día final para verificar * @return tmp.workerWithoutWeekBreak (workerFk) @@ -77229,10 +77229,10 @@ BEGIN CALL workerTimeControl_checkBreak(vStarted); INSERT IGNORE INTO tmp.workerWithoutWeekBreakInWeek - SELECT workerFk + SELECT workerFk FROM tmp.workerWithoutWeekBreak; DROP TEMPORARY TABLE IF EXISTS tmp.workerWithoutWeekBreak; - SET vStarted = DATE_ADD(vStarted, INTERVAL 1 DAY); + SET vStarted = DATE_ADD(vStarted, INTERVAL 1 DAY); END WHILE; END ;; @@ -77270,7 +77270,7 @@ BEGIN DECLARE vDepartmentFk INT; DECLARE isEnabled BOOLEAN DEFAULT TRUE; - SELECT COUNT(*) INTO vHasSignedToday + SELECT COUNT(*) INTO vHasSignedToday FROM workerTimeControl WHERE timed >= vDated AND userFk = vUserFk; SET @day := 0; @@ -77283,16 +77283,16 @@ BEGIN SELECT fichada_anterior, fichada_actual, interval_in_minutes, jornadas FROM ( - SELECT @lastTimed fichada_anterior, + SELECT @lastTimed fichada_anterior, timed, CAST(time_to_sec(timediff(timed,@lastTimed )) / 60 AS UNSIGNED) as interval_in_minutes, IF(day(timed) != @day, 1, 0) as jornadas, @day := day(timed) dia_del_mes, - @lastTimed := timed fichada_actual + @lastTimed := timed fichada_actual FROM ( SELECT day(timed) as dayNumber, dayname(timed) as dayName, timed - FROM + FROM (SELECT TIMESTAMPADD(DAY, -11, util.VN_NOW()) as timed, vUserFk as userFk -- Fichada virtual para los en los que no se ha trabajado la semana anterior UNION ALL SELECT timed, userFk @@ -77300,18 +77300,18 @@ BEGIN WHERE userFk = vUserFk AND timed >= TIMESTAMPADD(DAY, -10,vDated) UNION ALL - SELECT IF(vHasSignedToday, '2000-01-01 00:00', util.VN_NOW()) as timed, vUserFk + SELECT IF(vHasSignedToday, '2000-01-01 00:00', util.VN_NOW()) as timed, vUserFk ) sub4 ORDER BY timed ) sub - + ) sub2 WHERE fichada_actual >= TIMESTAMPADD(WEEK, -1, vDated) ) sub3 ; SELECT IFNULL(SUM(impar),0) into vImpares FROM ( - SELECT day(timed) as dayNumber, + SELECT day(timed) as dayNumber, count(*) mod 2 as impar FROM vn.workerTimeControl wtc WHERE userFk = vUserFk @@ -77328,29 +77328,29 @@ BEGIN AND at2.isAllowedToWork = FALSE AND b.workerFk = vUserFk LIMIT 1; - + -- Contrato en vigor SELECT IF(COUNT(*),vCantWork,'Sin contrato') INTO vCantWork FROM business b WHERE b.workerFk = vUserFk AND b.started <= vDated AND IFNULL(b.ended, vDated) >= vDated; - + -- Departamento si vTabletFk es 0 no hacemos comprobacion (Madrid y Vilassar) IF vTabletFk <> '0' THEN -- 1 Obtener el departamento del usuario SELECT wtcu.departmentFk INTO vDepartmentFk FROM workerTimeControlUserInfo wtcu WHERE wtcu.userFk = vUserFk; - -- 2 Comprobar si la tablet pertenece al departamento + -- 2 Comprobar si la tablet pertenece al departamento SELECT COUNT(td.tabletFk) INTO isEnabled FROM tabletDepartment td WHERE td.tabletFk = vTabletFk AND td.departmentFk = vDepartmentFk; - + END IF; - + IF vJornadas IS NOT NULL THEN - + SELECT 'Jornadas' as Item, vJornadas as Cantidad, 'Correcto' AS Análisis UNION ALL SELECT 'Descansos 12 h' as Item, vDescansos12h as Cantidad, IF(vDescansos12h >= vJornadas, 'Correcto','Error: 1 por jornada') as Análisis @@ -77359,9 +77359,9 @@ BEGIN UNION ALL SELECT 'Dias con fichadas impares' as Item, vImpares as Cantidad, IF(vImpares = 0, 'Correcto','Error') as Análisis UNION ALL - SELECT IF (LENGTH(vCantWork),CONCAT('Dia no laborable: ', vCantWork),'Dia laborable') as Item, - '' as Cantidad, - IF(LENGTH(vCantWork),'Error', 'Correcto') as Análisis + SELECT IF (LENGTH(vCantWork),CONCAT('Dia no laborable: ', vCantWork),'Dia laborable') as Item, + '' as Cantidad, + IF(LENGTH(vCantWork),'Error', 'Correcto') as Análisis UNION ALL SELECT 'El fichador no pertenece a tu departamento.' as Item, '' as Cantidad, IF(isEnabled, 'Correcto','Error') as Análisis; @@ -77375,7 +77375,7 @@ BEGIN UNION ALL SELECT 'Dias con fichadas impares' as Item, vImpares as Cantidad, 'Correcto' as Análisis UNION ALL - SELECT IF (LENGTH(vCantWork),CONCAT('Dia no laborable: ', vCantWork),'Dia laborable') as Item, + SELECT IF (LENGTH(vCantWork),CONCAT('Dia no laborable: ', vCantWork),'Dia laborable') as Item, '' as Cantidad, IF(LENGTH(vCantWork),'Error', 'Correcto') as Análisis UNION ALL SELECT 'El fichador no pertenece a tu departamento.' as Item, '' as Cantidad, IF(isEnabled, 'Correcto','Error') as Análisis; @@ -77405,11 +77405,11 @@ BEGIN * @param vDepartmentFk id del departamento * */ - - SELECT w.id,w.firstName, w.lastName,d.name - FROM worker w - JOIN workerDepartment wd ON wd.workerFk = w.id - JOIN department d ON d.id = wd.departmentFk + + SELECT w.id,w.firstName, w.lastName,d.name + FROM worker w + JOIN workerDepartment wd ON wd.workerFk = w.id + JOIN department d ON d.id = wd.departmentFk WHERE d.id = vDepartmentFk ORDER BY firstName; @@ -77440,7 +77440,7 @@ BEGIN (PRIMARY KEY (workerFk)) ENGINE = MEMORY SELECT vBoss AS workerFk; - + DROP TEMPORARY TABLE IF EXISTS tmp.workerHierarchyList; CREATE TEMPORARY TABLE tmp.workerHierarchyList (PRIMARY KEY (workerFk)) @@ -77451,7 +77451,7 @@ BEGIN WHILE (SELECT COUNT(*) FROM tmp.workerHierarchyList WHERE NOT isChecked) > 0 DO INSERT INTO tmp.workerHierarchyList - SELECT w.id, 0 + SELECT w.id, 0 FROM worker w JOIN workerHierarchy wh ON wh.workerFk = w.bossFk; @@ -77462,12 +77462,12 @@ BEGIN TRUNCATE workerHierarchy; INSERT INTO workerHierarchy - SELECT workerFk + SELECT workerFk FROM tmp.workerHierarchyList WHERE NOT isChecked; END WHILE; - + DROP TEMPORARY TABLE IF EXISTS workerHierarchy; END ;; DELIMITER ; @@ -77494,7 +77494,7 @@ BEGIN SELECT s.id,s.description,s.warehouseFk FROM sector s - JOIN operator o ON o.sectorFk = s.id + JOIN operator o ON o.sectorFk = s.id WHERE o.workerFk = account.myUser_getId(); END ;; @@ -77579,8 +77579,8 @@ BEGIN DECLARE vDone BOOL; DECLARE vCursor CURSOR FOR - SELECT DISTINCT b.workerFk - FROM business b + SELECT DISTINCT b.workerFk + FROM business b WHERE b.started > vBusinessUpdated AND b.started <= vCurdate OR b.ended >= vBusinessUpdated AND b.ended < vCurdate; @@ -77623,10 +77623,10 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workingHours`(username varchar(255), logon boolean) BEGIN DECLARE userid int(11); - + SELECT vn.getUserId(username) INTO userid; SELECT username, userid; - IF userid IS NOT NULL THEN + IF userid IS NOT NULL THEN IF (logon) THEN CALL vn.workingHoursTimeIn(userid); ELSE @@ -77695,17 +77695,17 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `wrongEqualizatedClient`() BEGIN SELECT clientFk, c.name, c.isActive, c.isTaxDataChecked, count(ie) as num FROM vn.client c - JOIN + JOIN ( - SELECT DISTINCT + SELECT DISTINCT `a`.`clientFk` , a.isEqualizated = 0 as ie - + FROM `vn`.`address` `a` ) sub ON sub.clientFk = c.id WHERE c.hasToInvoiceByAddress = FALSE - + GROUP BY clientFk HAVING num > 1 UNION ALL @@ -77789,27 +77789,27 @@ proc: BEGIN SELECT scope INTO vScope FROM zoneConfig; - + DROP TEMPORARY TABLE IF EXISTS tmp.zone; CREATE TEMPORARY TABLE tmp.zone (INDEX (id)) ENGINE = MEMORY SELECT id FROM zone; - + TRUNCATE TABLE zoneClosure; - + WHILE vCounter <= vScope DO - + CALL zone_getOptionsForShipment(vShipped, TRUE); - + REPLACE zoneClosure(zoneFk, dated, `hour`) - SELECT zoneFk, vShipped, `hour` + SELECT zoneFk, vShipped, `hour` FROM tmp.zoneOption; - + SET vCounter = vCounter + 1; SET vShipped = TIMESTAMPADD(DAY, 1, vShipped); END WHILE; - + -- DROP TEMPORARY TABLE tmp.zone; DO RELEASE_LOCK('vn.zoneClosure_recalc'); END ;; @@ -77903,7 +77903,7 @@ BEGIN OR (vSelf IS NOT NULL AND parentFk = vSelf); DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + SET vSons = 0; OPEN vChildren; @@ -77914,11 +77914,11 @@ BEGIN IF vDone THEN LEAVE myLoop; END IF; - + SET vIndex = vIndex + 1; SET vLft = vIndex; SET vSons = vSons + 1; - + CALL zoneGeo_calcTreeRec( vChildFk, CONCAT(vPath, vChildFk, '/'), @@ -78021,7 +78021,7 @@ proc: BEGIN SELECT isChanged INTO vIsChanged FROM zoneGeoRecalc; - + IF vIsChanged THEN UPDATE zoneGeoRecalc SET isChanged = FALSE; CALL vn.zoneGeo_calcTree; @@ -78209,7 +78209,7 @@ proc:BEGIN * @table tmp.closedZones(zoneFk, warehouseFk); */ DROP TEMPORARY TABLE IF EXISTS tmp.closedZones; - + CREATE TEMPORARY TABLE tmp.closedZones ( `zoneFk` int(11) NOT NULL, `warehouseFk` smallint(6) unsigned NOT NULL, @@ -78251,7 +78251,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getCollisions`() BEGIN /** - * Calcula si para un mismo codigo postal y dia + * Calcula si para un mismo codigo postal y dia * hay mas de una zona configurada y manda correo * */ @@ -78260,16 +78260,16 @@ BEGIN DECLARE vIsDone INT DEFAULT FALSE; DECLARE vTableCollisions TEXT; DECLARE cur1 CURSOR FOR SELECT zoneFk from tmp.zoneOption; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vIsDone = TRUE; DROP TEMPORARY TABLE IF EXISTS tmp.zone; CREATE TEMPORARY TABLE tmp.zone - SELECT z.id + SELECT z.id FROM zone z JOIN agencyMode am ON am.id = z.agencyModeFk JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk - WHERE dm.code IN ('AGENCY','DELIVERY'); + WHERE dm.code IN ('AGENCY','DELIVERY'); CALL zone_getOptionsForShipment(util.VN_CURDATE(),FALSE); @@ -78284,7 +78284,7 @@ BEGIN PRIMARY KEY zoneFkk (zoneFk, geoFk), INDEX(geoFk)) ENGINE = MyISAM; - + OPEN cur1; cur1Loop: LOOP SET vIsDone = FALSE; @@ -78292,40 +78292,40 @@ BEGIN IF vIsDone THEN LEAVE cur1Loop; END IF; - + CALL zone_getLeaves(vZoneFk, NULL, NULL, TRUE); - myLoop: LOOP + myLoop: LOOP SET vGeoFk = NULL; - SELECT geoFk INTO vGeoFk + SELECT geoFk INTO vGeoFk FROM tmp.zoneNodes zn WHERE NOT isChecked LIMIT 1; - + IF vGeoFk IS NULL THEN LEAVE myLoop; END IF; - + CALL zone_getLeaves(vZoneFk, vGeoFk, NULL, TRUE); UPDATE tmp.zoneNodes - SET isChecked = TRUE + SET isChecked = TRUE WHERE geoFk = vGeoFk; END LOOP; END LOOP; CLOSE cur1; - DELETE FROM tmp.zoneNodes + DELETE FROM tmp.zoneNodes WHERE sons > 0; - + DROP TEMPORARY TABLE IF EXISTS geoCollision; CREATE TEMPORARY TABLE geoCollision SELECT z.agencyModeFk, zn.geoFk, zw.warehouseFk FROM tmp.zoneNodes zn JOIN zone z ON z.id = zn.zoneFk - JOIN zoneWarehouse zw ON z.id = zw.zoneFk + JOIN zoneWarehouse zw ON z.id = zw.zoneFk GROUP BY z.agencyModeFk, zn.geoFk, zw.warehouseFk HAVING count(*) > 1; - + SELECT ' @@ -78335,39 +78335,39 @@ BEGIN ' INTO vTableCollisions; - - INSERT INTO mail (receiver,replyTo,subject,body) + + INSERT INTO mail (receiver,replyTo,subject,body) SELECT 'pepe@verdnatura.es' receiver, 'noreply@verdnatura.es' replyTo, CONCAT('Colisiones en zonas ', util.VN_CURDATE()) subject, CONCAT(vTableCollisions, GROUP_CONCAT(sub.td SEPARATOR ''), '
C.PostalAlmacén Salix
') body - FROM(SELECT + FROM(SELECT CONCAT(' ', zn.name, ' ', zoneFk,' ', z.price,' ', z.name,' ', w.name, ' - ', CONCAT('' - 'https://salix.verdnatura.es/#!/zone/', + 'https://salix.verdnatura.es/#!/zone/', zoneFk, '/location?q=%7B%22search%22:%22', - zn.name, + zn.name, '%22%7D'),' ') td FROM tmp.zoneNodes zn JOIN zone z ON z.id = zn.zoneFk JOIN geoCollision gc ON gc.agencyModeFk = z.agencyModeFk AND zn.geoFk = gc.geoFk JOIN warehouse w ON w.id = gc.warehouseFk) sub; - - DROP TEMPORARY TABLE - geoCollision, + + DROP TEMPORARY TABLE + geoCollision, tmp.zone, tmp.zoneNodes; END ;; @@ -78474,18 +78474,18 @@ BEGIN DECLARE vChildFk INT DEFAULT vGeoFk; DECLARE vParentFk INT; DECLARE vLevel INT DEFAULT 1; - + DROP TEMPORARY TABLE IF EXISTS tNodes; CREATE TEMPORARY TABLE tNodes (PRIMARY KEY (id)) ENGINE = MEMORY SELECT vGeoFk id, vLevel `level`; - + myLoop: LOOP SELECT parentFk INTO vParentFk FROM zoneGeo WHERE id = vChildFk; - + SET vChildFk = vParentFk; SET vLevel = vLevel + 1; @@ -78493,7 +78493,7 @@ BEGIN SELECT vChildFk, vLevel FROM DUAL WHERE vChildFk IS NOT NULL; - + IF ROW_COUNT() = 0 THEN LEAVE myLoop; END IF; @@ -78592,13 +78592,12 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getLeaves`( - vSelf INT, - vParentFk INT, - vSearch VARCHAR(255), - vHasInsert BOOL +CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getLeaves`( + vSelf INT, + vParentFk INT, + vSearch VARCHAR(255), + vHasInsert BOOL ) -<<<<<<< HEAD BEGIN /** * Devuelve las ubicaciones incluidas en la ruta y que sean hijos de parentFk. @@ -78713,122 +78712,6 @@ BEGIN END IF; DROP TEMPORARY TABLE tNodes, tZones; -======= -BEGIN -/** - * Devuelve las ubicaciones incluidas en la ruta y que sean hijos de parentFk. - * @param vSelf Id de la zona - * @param vParentFk Id del geo a calcular - * @param vSearch Cadena a buscar - * @param vHasInsert Indica si inserta en tmp.zoneNodes - * Optional @table tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) - */ - DECLARE vIsNumber BOOL; - DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch <> ''; - - CREATE OR REPLACE TEMPORARY TABLE tNodes - (UNIQUE (id)) - ENGINE = MEMORY - SELECT id - FROM zoneGeo - LIMIT 0; - - IF vIsSearch THEN - SET vIsNumber = vSearch REGEXP '^[0-9]+$'; - - INSERT INTO tNodes - SELECT id - FROM zoneGeo - WHERE (vIsNumber AND `name` = vSearch) - OR (!vIsNumber AND `name` LIKE CONCAT('%', vSearch, '%')) - LIMIT 1000; - - ELSEIF vParentFk IS NULL THEN - INSERT INTO tNodes - SELECT geoFk - FROM zoneIncluded - WHERE zoneFk = vSelf; - END IF; - - IF vParentFk IS NULL THEN - CREATE OR REPLACE TEMPORARY TABLE tChilds - (INDEX(id)) - ENGINE = MEMORY - SELECT id FROM tNodes; - - CREATE OR REPLACE TEMPORARY TABLE tParents - (INDEX(id)) - ENGINE = MEMORY - SELECT id FROM zoneGeo LIMIT 0; - - myLoop: LOOP - DELETE FROM tParents; - INSERT INTO tParents - SELECT parentFk id - FROM zoneGeo g - JOIN tChilds c ON c.id = g.id - WHERE g.parentFk IS NOT NULL; - - INSERT IGNORE INTO tNodes - SELECT id FROM tParents; - - IF NOT ROW_COUNT() THEN - LEAVE myLoop; - END IF; - - DELETE FROM tChilds; - INSERT INTO tChilds - SELECT id FROM tParents; - END LOOP; - - DROP TEMPORARY TABLE tChilds, tParents; - END IF; - - IF NOT vIsSearch THEN - INSERT IGNORE INTO tNodes - SELECT id - FROM zoneGeo - WHERE parentFk <=> vParentFk; - END IF; - - CREATE OR REPLACE TEMPORARY TABLE tZones - SELECT g.id, - g.name, - g.parentFk, - g.sons, - NOT g.sons OR `type` = 'country' isChecked, - i.isIncluded selected, - g.`depth`, - vSelf - FROM zoneGeo g - JOIN tNodes n ON n.id = g.id - LEFT JOIN zoneIncluded i ON i.geoFk = g.id - AND i.zoneFk = vSelf - ORDER BY g.`depth`, selected DESC, g.name; - - IF vHasInsert THEN - INSERT IGNORE INTO tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) - SELECT id, - name, - parentFk, - sons, - isChecked, - vSelf - FROM tZones - WHERE selected - OR (selected IS NULL AND vParentFk IS NOT NULL); - ELSE - SELECT id, - name, - parentFk, - sons, - selected - FROM tZones - ORDER BY `depth`, selected DESC, name; - END IF; - - DROP TEMPORARY TABLE tNodes, tZones; ->>>>>>> 08e97b6a19c411bac7301a28ab1e358d4d546af7 END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -78853,7 +78736,7 @@ BEGIN * @table tmp.zone(id) The zones ids * @param vLanded The delivery date * @return tmp.zoneOption The computed options - */ + */ DROP TEMPORARY TABLE IF EXISTS tmp.zoneOption; CREATE TEMPORARY TABLE tmp.zoneOption ENGINE = MEMORY @@ -78894,13 +78777,13 @@ BEGIN END LIMIT 10000000000000000000 ) t - GROUP BY zoneFk; - + GROUP BY zoneFk; + DELETE t FROM tmp.zoneOption t JOIN zoneExclusion e ON e.zoneFk = t.zoneFk AND e.`dated` = t.landed LEFT JOIN zoneExclusionGeo eg ON eg.zoneExclusionFk = e.id WHERE eg.zoneExclusionFk IS NULL; - + IF NOT vShowExpiredZones THEN DELETE FROM tmp.zoneOption WHERE shipped < util.VN_CURDATE() @@ -78932,7 +78815,7 @@ BEGIN * @return tmp.zoneOption(zoneFk, hour, travelingDays, price, bonus, specificity) The computed options */ DECLARE vHour TIME DEFAULT TIME(util.VN_NOW()); - + DROP TEMPORARY TABLE IF EXISTS tLandings; CREATE TEMPORARY TABLE tLandings (INDEX (eventFk)) @@ -79011,53 +78894,53 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getPostalCode`(vSelf INT) -BEGIN -/** - * Devuelve los códigos postales incluidos en una zona - */ - DECLARE vGeoFk INT DEFAULT NULL; - - DROP TEMPORARY TABLE IF EXISTS tmp.zoneNodes; - CREATE TEMPORARY TABLE tmp.zoneNodes ( - geoFk INT, - name VARCHAR(100), - parentFk INT, - sons INT, - isChecked BOOL DEFAULT 0, - zoneFk INT, - PRIMARY KEY zoneNodesPk (zoneFk, geoFk), - INDEX(geoFk)) - ENGINE = MEMORY; - - CALL zone_getLeaves(vSelf, NULL , NULL, TRUE); - - UPDATE tmp.zoneNodes zn - SET isChecked = 0 - WHERE parentFk IS NULL; - - myLoop: LOOP - SET vGeoFk = NULL; - SELECT geoFk INTO vGeoFk - FROM tmp.zoneNodes zn - WHERE NOT isChecked - LIMIT 1; - - CALL zone_getLeaves(vSelf, vGeoFk, NULL, TRUE); - UPDATE tmp.zoneNodes - SET isChecked = TRUE - WHERE geoFk = vGeoFk; - - IF vGeoFk IS NULL THEN - LEAVE myLoop; - END IF; - END LOOP; - - DELETE FROM tmp.zoneNodes - WHERE sons > 0; - - SELECT zn.geoFk, zn.name - FROM tmp.zoneNodes zn - JOIN zone z ON z.id = zn.zoneFk; +BEGIN +/** + * Devuelve los códigos postales incluidos en una zona + */ + DECLARE vGeoFk INT DEFAULT NULL; + + DROP TEMPORARY TABLE IF EXISTS tmp.zoneNodes; + CREATE TEMPORARY TABLE tmp.zoneNodes ( + geoFk INT, + name VARCHAR(100), + parentFk INT, + sons INT, + isChecked BOOL DEFAULT 0, + zoneFk INT, + PRIMARY KEY zoneNodesPk (zoneFk, geoFk), + INDEX(geoFk)) + ENGINE = MEMORY; + + CALL zone_getLeaves(vSelf, NULL , NULL, TRUE); + + UPDATE tmp.zoneNodes zn + SET isChecked = 0 + WHERE parentFk IS NULL; + + myLoop: LOOP + SET vGeoFk = NULL; + SELECT geoFk INTO vGeoFk + FROM tmp.zoneNodes zn + WHERE NOT isChecked + LIMIT 1; + + CALL zone_getLeaves(vSelf, vGeoFk, NULL, TRUE); + UPDATE tmp.zoneNodes + SET isChecked = TRUE + WHERE geoFk = vGeoFk; + + IF vGeoFk IS NULL THEN + LEAVE myLoop; + END IF; + END LOOP; + + DELETE FROM tmp.zoneNodes + WHERE sons > 0; + + SELECT zn.geoFk, zn.name + FROM tmp.zoneNodes zn + JOIN zone z ON z.id = zn.zoneFk; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -79088,7 +78971,7 @@ BEGIN DECLARE vZoneGeo INT; SELECT address_getGeo(vAddressFk) INTO vZoneGeo; - + CALL vn.zone_getFromGeo(vZoneGeo); CALL vn.zone_getOptionsForLanding(vLanded, vShowExpiredZones); CALL vn.zone_excludeFromGeo(vZoneGeo); @@ -79108,7 +78991,7 @@ BEGIN FROM tmp.zoneOption zo JOIN vn.zoneWarehouse zw ON zw.zoneFk = zo.zoneFk JOIN vn.`zone` z ON z.id = zo.zoneFk - LEFT JOIN tmp.closedZones cz + LEFT JOIN tmp.closedZones cz ON cz.warehouseFk = zw.warehouseFk AND cz.zoneFk = zw.zoneFk AND zo.shipped = util.VN_CURDATE() @@ -79142,9 +79025,9 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getState`(vDated DATE) BEGIN /** * Devuelve las zonas y el estado para la fecha solicitada - * + * * @param vDated Fecha en cuestión - */ + */ DROP TEMPORARY TABLE IF EXISTS tmp.zone; CREATE TEMPORARY TABLE tmp.zone ( @@ -79158,7 +79041,7 @@ BEGIN CALL vn.zone_getOptionsForShipment(vDated, TRUE); CALL vn.zone_getClosed(); - + SELECT zo.zoneFk, zo.`hour`etd, (zo.`hour` <= TIME(util.VN_NOW())) isLate, @@ -79168,11 +79051,11 @@ BEGIN FROM tmp.zoneOption zo JOIN vn.zone z ON z.id = zo.zoneFk JOIN vn.zoneWarehouse zw ON zw.zoneFk = z.id - LEFT JOIN tmp.closedZones cz - ON cz.warehouseFk = zw.warehouseFk + LEFT JOIN tmp.closedZones cz + ON cz.warehouseFk = zw.warehouseFk AND cz.zoneFk = zo.zoneFk; - - DROP TEMPORARY TABLE + + DROP TEMPORARY TABLE tmp.closedZones, tmp.zoneOption, tmp.zone; @@ -79198,21 +79081,21 @@ BEGIN /** * Devuelve el listado de agencias disponibles para la fecha, * dirección y almacén pasados. - * + * * @param vAddress * @param vWarehouse warehouse * @param vLanded Fecha de recogida * @select Listado de agencias disponibles */ - + CALL zone_getFromGeo(address_getGeo(vAddress)); CALL zone_getOptionsForLanding(vLanded, FALSE); - - SELECT am.id agencyModeFk, - am.name agencyMode, - am.description, + + SELECT am.id agencyModeFk, + am.name agencyMode, + am.description, am.deliveryMethodFk, - TIMESTAMPADD(DAY, -zo.travelingDays, vLanded) shipped, + TIMESTAMPADD(DAY, -zo.travelingDays, vLanded) shipped, zw.warehouseFk, z.id zoneFk FROM tmp.zoneOption zo @@ -79222,11 +79105,11 @@ BEGIN WHERE zw.warehouseFk = vWarehouse GROUP BY z.agencyModeFk ORDER BY agencyMode; - + DROP TEMPORARY TABLE tmp.zone, tmp.zoneOption; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -79247,7 +79130,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_upcomingDeliveries`() BEGIN DECLARE vForwardDays INT; - + SELECT forwardDays INTO vForwardDays FROM zoneConfig; CALL util.time_createTable(util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL vForwardDays DAY)); @@ -79263,7 +79146,7 @@ BEGIN JOIN zoneEvent e ON e.zoneFk = z.id JOIN tmp.time ti ON ti.dated BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(DAY, vForwardDays, util.VN_CURDATE()); - DROP TEMPORARY TABLE IF EXISTS tmp.zoneOption; + DROP TEMPORARY TABLE IF EXISTS tmp.zoneOption; CREATE TEMPORARY TABLE tmp.zoneOption ENGINE = MEMORY SELECT * @@ -79304,7 +79187,7 @@ BEGIN JOIN zoneExclusion e ON e.zoneFk = t.zoneFk AND e.`dated` = t.landed LEFT JOIN zoneExclusionGeo eg ON eg.zoneExclusionFk = e.id WHERE eg.zoneExclusionFk IS NULL; - + SELECT MAX(zo.`hour`) `hour`, zg.`name`, zo.shipped, zo.zoneFk FROM tmp.zoneOption zo JOIN `zone` z ON z.id = zo.zoneFk @@ -79315,7 +79198,7 @@ BEGIN WHERE dm.code = 'DELIVERY' GROUP BY shipped, zg.`name` ORDER BY shipped, zg.`name`; - + DROP TEMPORARY TABLE tmp.time, tLandings; END ;; DELIMITER ; From ccfd8fad058b0f75deea374a7536a64974495a86 Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 11 Sep 2023 12:32:46 +0200 Subject: [PATCH 074/427] refs #6213 fixCreateError --- .../233801/00-supplierAccountCheckLength.sql | 1 + loopback/locale/es.json | 10 ++++++---- modules/supplier/back/models/supplier.js | 17 +++++++++++++++++ modules/supplier/front/create/index.html | 1 - modules/supplier/front/create/index.js | 1 + 5 files changed, 25 insertions(+), 5 deletions(-) create mode 100644 db/changes/233801/00-supplierAccountCheckLength.sql diff --git a/db/changes/233801/00-supplierAccountCheckLength.sql b/db/changes/233801/00-supplierAccountCheckLength.sql new file mode 100644 index 000000000..99f571ba1 --- /dev/null +++ b/db/changes/233801/00-supplierAccountCheckLength.sql @@ -0,0 +1 @@ +ALTER TABLE vn.supplier ADD CONSTRAINT supplier_CHECK CHECK (LENGTH(account) = 10); diff --git a/loopback/locale/es.json b/loopback/locale/es.json index ccd63e0ff..6388c01a4 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -216,6 +216,7 @@ "The worker has hours recorded that day": "El trabajador tiene horas fichadas ese día", "The worker has a marked absence that day": "El trabajador tiene marcada una ausencia ese día", "You can not modify is pay method checked": "No se puede modificar el campo método de pago validado", + "The account size must be exactly 10 characters": "El tamaño de la cuenta debe ser exactamente de 10 caracteres", "Can't transfer claimed sales": "No puedes transferir lineas reclamadas", "You don't have privileges to create refund": "No tienes permisos para crear un abono", "The item is required": "El artículo es requerido", @@ -307,14 +308,15 @@ "Negative basis of tickets": "Base negativa para los tickets: {{ticketsIds}}", "You cannot assign an alias that you are not assigned to": "No puede asignar un alias que no tenga asignado", "This ticket cannot be left empty.": "Este ticket no se puede dejar vacío. %s", - "The company has not informed the supplier account for bank transfers": "La empresa no tiene informado la cuenta de proveedor para transferencias bancarias", + "The company has not informed the supplier account for bank transfers": "La empresa no tiene informado la cuenta de proveedor para transferencias bancarias", "You cannot assign/remove an alias that you are not assigned to": "No puede asignar/eliminar un alias que no tenga asignado", "This invoice has a linked vehicle.": "Esta factura tiene un vehiculo vinculado", "You don't have enough privileges.": "No tienes suficientes permisos.", "This ticket is locked.": "Este ticket está bloqueado.", "This ticket is not editable.": "Este ticket no es editable.", "The ticket doesn't exist.": "No existe el ticket.", - "Social name should be uppercase": "La razón social debe ir en mayúscula", + "Social name should be uppercase": "La razón social debe ir en mayúscula", "Street should be uppercase": "La dirección fiscal debe ir en mayúscula", - "Ticket without Route": "Ticket sin ruta" -} + "Ticket without Route": "Ticket sin ruta", + "The account size must be exactly 10 characters": "The account size must be exactly 10 characters" +} \ No newline at end of file diff --git a/modules/supplier/back/models/supplier.js b/modules/supplier/back/models/supplier.js index 96042c9a0..28e53e3c5 100644 --- a/modules/supplier/back/models/supplier.js +++ b/modules/supplier/back/models/supplier.js @@ -112,9 +112,26 @@ module.exports = Self => { const hasChanges = orgData && changes; const isPayMethodCheckedChanged = hasChanges && orgData.isPayMethodChecked != isPayMethodChecked; + const isAccountChanged = hasChanges && orgData.account != changes.account; if (!editPayMethodCheck && isPayMethodCheckedChanged) throw new UserError('You can not modify is pay method checked'); + + if (isAccountChanged && !(changes.account.length === 10)) + throw new UserError('The account size must be exactly 10 characters'); + }); + + Self.observe('after save', async function(ctx) { + if (ctx.instance && ctx.isNewInstance) { + const supplierId = ctx.instance.id; + const models = Self.app.models; + + const supplier = await models.Supplier.findById(supplierId); + await supplier.updateAttribute( + 'account', + supplierId.toString().padStart(10, '0') + ); + } }); Self.validateAsync('name', 'countryFk', hasSupplierSameName, { diff --git a/modules/supplier/front/create/index.html b/modules/supplier/front/create/index.html index c3efcf6ae..eb6e7261e 100644 --- a/modules/supplier/front/create/index.html +++ b/modules/supplier/front/create/index.html @@ -18,7 +18,6 @@ Date: Mon, 11 Sep 2023 12:36:42 +0200 Subject: [PATCH 075/427] refs #6213 remove console log --- modules/supplier/front/create/index.js | 1 - 1 file changed, 1 deletion(-) diff --git a/modules/supplier/front/create/index.js b/modules/supplier/front/create/index.js index f11df2884..c33367dac 100644 --- a/modules/supplier/front/create/index.js +++ b/modules/supplier/front/create/index.js @@ -4,7 +4,6 @@ import Section from 'salix/components/section'; class Controller extends Section { constructor($element, $) { super($element, $); - console.log($.name); } onSubmit() { From d3e5e187e100db766701c0ca8504cda9b0707cb3 Mon Sep 17 00:00:00 2001 From: carlossa Date: Mon, 11 Sep 2023 13:46:52 +0200 Subject: [PATCH 076/427] refs #5660 change acl --- e2e/paths/02-client/01_create_client.spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/e2e/paths/02-client/01_create_client.spec.js b/e2e/paths/02-client/01_create_client.spec.js index 744b11a72..cb06d3616 100644 --- a/e2e/paths/02-client/01_create_client.spec.js +++ b/e2e/paths/02-client/01_create_client.spec.js @@ -8,7 +8,7 @@ describe('Client create path', () => { beforeAll(async() => { browser = await getBrowser(); page = browser.page; - await page.loginAndModule('deliveryAssistant', 'client'); + await page.loginAndModule('deliveryBoss', 'client'); }); afterAll(async() => { From 49e635ff4bb5b79db310f5f2a53547786da04eaa Mon Sep 17 00:00:00 2001 From: carlossa Date: Mon, 11 Sep 2023 13:49:18 +0200 Subject: [PATCH 077/427] refs #5660 dump dumpedFixtures --- db/dump/dumpedFixtures.sql | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/db/dump/dumpedFixtures.sql b/db/dump/dumpedFixtures.sql index 683fff77c..2e1511b59 100644 --- a/db/dump/dumpedFixtures.sql +++ b/db/dump/dumpedFixtures.sql @@ -78,7 +78,7 @@ USE `account`; LOCK TABLES `role` WRITE; /*!40000 ALTER TABLE `role` DISABLE KEYS */; -INSERT INTO `role` VALUES (1,'employee','Empleado básico',1,'2017-05-19 07:04:58','2023-06-08 16:47:57',NULL),(2,'customer','Privilegios básicos de un cliente',1,'2017-05-19 07:04:58','2023-06-02 20:33:28',NULL),(3,'agency','Consultar tablas de predicciones de bultos',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(5,'administrative','Tareas relacionadas con la contabilidad',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(6,'guest','Privilegios para usuarios sin cuenta',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(9,'developer','Desarrolladores del sistema',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(11,'account','Privilegios relacionados con el login',0,'2017-05-19 07:04:58','2017-09-20 17:06:35',NULL),(13,'teamBoss','Jefe de equipo/departamento',1,'2017-05-19 07:04:58','2021-06-30 13:29:30',NULL),(15,'logistic','Departamento de compras, responsables de la logistica',1,'2017-05-19 07:04:58','2018-02-12 10:50:10',NULL),(16,'logisticBoss','Jefe del departamento de logística',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(17,'adminBoss','Jefe del departamento de administración',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(18,'salesPerson','Departamento de ventas',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(19,'salesBoss','Jefe del departamento de ventas',1,'2017-05-19 07:04:58','2017-08-16 12:38:27',NULL),(20,'manager','Gerencia',1,'2017-06-01 14:57:02','2022-07-29 07:36:15',NULL),(21,'salesAssistant','Jefe auxiliar de ventas',1,'2017-08-16 12:40:52','2017-08-16 12:40:52',NULL),(22,'teamManager','Jefe de departamento con privilegios de auxiliar de venta.',1,'2017-09-07 09:08:12','2017-09-07 09:08:12',NULL),(30,'financialBoss','Director finaciero',1,'2017-09-21 11:05:36','2017-09-21 11:05:36',NULL),(31,'freelancer','Trabajadores por cuenta ajena',1,'2017-10-10 12:57:26','2017-10-10 12:59:27',NULL),(32,'ett','Trabajadores de empresa temporal',1,'2017-10-10 12:58:58','2017-10-10 12:59:20',NULL),(33,'invoicing','Personal con acceso a facturación',0,'2018-01-29 16:43:34','2018-01-29 16:43:34',NULL),(34,'agencyBoss','Jefe/a del departamento de agencias',1,'2018-01-29 16:44:39','2018-02-23 07:58:53',NULL),(35,'buyer','Departamento de compras',1,'2018-02-12 10:35:42','2018-02-12 10:35:42',NULL),(36,'replenisher','Trabajadores de camara',1,'2018-02-16 14:07:10','2019-04-12 05:38:08',NULL),(37,'hr','Gestor/a de recursos humanos',1,'2018-02-22 17:34:53','2018-02-22 17:34:53',NULL),(38,'hrBoss','Jefe/a de recursos humanos',1,'2018-02-22 17:35:09','2018-02-22 17:35:09',NULL),(39,'adminAssistant','Jefe auxiliar administrativo',1,'2018-02-23 10:37:36','2018-02-23 10:38:41',NULL),(40,'handmade','Departamento de confección',1,'2018-02-23 11:14:53','2018-02-23 11:39:12',NULL),(41,'handmadeBoss','Jefe de departamento de confección',1,'2018-02-23 11:15:09','2018-02-23 11:39:26',NULL),(42,'artificial','Departamento de artificial',1,'2018-02-23 11:39:59','2018-02-23 11:39:59',NULL),(43,'artificialBoss','Jefe del departamento de artificial',1,'2018-02-23 11:40:16','2018-02-23 11:40:16',NULL),(44,'accessory','Departamento de complementos',1,'2018-02-23 11:41:12','2018-02-23 11:41:12',NULL),(45,'accessoryBoss','Jefe del departamento de complementos',1,'2018-02-23 11:41:23','2018-02-23 11:41:23',NULL),(47,'cooler','Empleados de cámara',1,'2018-02-23 13:08:18','2018-02-23 13:08:18',NULL),(48,'coolerBoss','Jefe de cámara',1,'2018-02-23 13:12:01','2023-03-13 08:49:43',NULL),(49,'production','Empleado de producción',1,'2018-02-26 15:28:23','2021-02-12 09:42:35',NULL),(50,'productionBoss','Jefe de producción',1,'2018-02-26 15:34:12','2018-02-26 15:34:12',NULL),(51,'marketing','Departamento de marketing',1,'2018-03-01 07:28:39','2018-03-01 07:28:39',NULL),(52,'marketingBoss','Jefe del departamento de marketing',1,'2018-03-01 07:28:57','2018-03-01 07:28:57',NULL),(53,'insurance','Gestor de seguros de cambio',0,'2018-03-05 07:44:35','2019-02-01 13:47:57',NULL),(54,'itemPicker','Sacador en cámara',1,'2018-03-05 12:08:17','2018-03-05 12:08:17',NULL),(55,'itemPickerBoss','Jefe de sacadores',1,'2018-03-05 12:08:31','2018-03-05 12:08:31',NULL),(56,'delivery','Personal de reparto',1,'2018-05-30 06:07:02','2018-05-30 06:07:02',NULL),(57,'deliveryBoss','Jefe de personal de reparto',1,'2018-05-30 06:07:19','2018-05-30 06:07:19',NULL),(58,'packager','Departamento encajadores',1,'2019-01-21 12:43:45','2019-01-21 12:43:45',NULL),(59,'packagerBoss','Jefe departamento encajadores',1,'2019-01-21 12:44:10','2019-01-21 12:44:10',NULL),(60,'productionAssi','Tareas relacionadas con producción y administración',1,'2019-01-29 13:29:01','2019-01-29 13:29:01',NULL),(61,'replenisherBos','Jefe de Complementos/Camara',1,'2019-07-01 06:44:07','2019-07-01 06:44:07',NULL),(62,'noLogin','Role without login access to MySQL',0,'2019-07-01 06:50:19','2019-07-02 13:42:05',NULL),(64,'balanceSheet','Consulta de Balance',0,'2019-07-16 12:12:08','2019-07-16 12:12:08',NULL),(65,'officeBoss','Jefe de filial',1,'2019-08-02 06:54:26','2019-08-02 06:54:26',NULL),(66,'sysadmin','Administrador de sistema',1,'2019-08-08 06:58:56','2019-08-08 06:58:56',NULL),(67,'adminOfficer','categoria profesional oficial de administración',1,'2020-01-03 08:09:23','2020-01-03 08:09:23',NULL),(69,'coolerAssist','Asistente de cámara con permiso compras',1,'2020-02-05 12:36:09','2023-03-13 08:50:07',NULL),(70,'trainee','Alumno de prácticas',1,'2020-03-04 11:00:25','2020-03-04 11:00:25',NULL),(71,'checker','Rol de revisor con privilegios de itemPicker',1,'2020-10-02 10:50:07','2020-10-02 10:50:07',NULL),(72,'claimManager','Personal de reclamaciones',1,'2020-10-13 10:01:32','2020-10-26 07:29:46',NULL),(73,'financial','Departamento de finanzas',1,'2020-11-16 09:30:27','2020-11-16 09:30:27',NULL),(74,'userPhotos','Privilegios para subir fotos de usuario',1,'2021-02-03 10:24:27','2021-02-03 10:24:27',NULL),(75,'catalogPhotos','Privilegios para subir fotos del catálogo',1,'2021-02-03 10:24:27','2021-02-03 10:24:27',NULL),(76,'chat','Rol para utilizar el rocket chat',1,'2020-11-27 13:06:50','2020-12-17 07:49:41',NULL),(100,'root','Rol con todos los privilegios',0,'2018-04-23 14:33:36','2020-11-12 06:50:07',NULL),(101,'buyerBoss','Jefe del departamento de compras',1,'2021-06-16 09:53:17','2021-06-16 09:53:17',NULL),(102,'preservedBoss','Responsable preservado',1,'2021-09-14 13:45:37','2021-09-14 13:45:37',NULL),(103,'it','Departamento de informática',1,'2021-11-11 09:48:22','2021-11-11 09:48:22',NULL),(104,'itBoss','Jefe de departamento de informática',1,'2021-11-11 09:48:49','2021-11-11 09:48:49',NULL),(105,'grant','Adjudicar roles a usuarios',1,'2021-11-11 12:41:09','2021-11-11 12:41:09',NULL),(106,'ext','Usuarios externos de la Base de datos',1,'2021-11-23 14:51:16','2021-11-23 14:51:16',NULL),(107,'productionPlus','Creado para pepe por orden de Juanvi',1,'2022-02-08 06:47:10','2022-02-08 06:47:10',NULL),(108,'system','System user',1,'2022-05-16 08:09:51','2022-05-16 08:09:51',NULL),(109,'salesTeamBoss','Jefe de equipo de comerciales',1,'2022-06-14 13:45:56','2022-06-14 13:45:56',NULL),(110,'palletizer','Paletizadores',1,'2022-12-02 12:56:22','2022-12-02 12:56:30',NULL),(111,'entryEditor','Entry editor',1,'2023-01-13 11:21:55','2023-01-13 11:21:55',NULL),(112,'maintenance','Personal de mantenimiento',1,'2023-01-19 06:23:35','2023-01-19 06:23:35',NULL),(114,'maintenanceBos','Jefe de mantenimiento',1,'2023-01-19 06:31:16','2023-05-17 11:07:21',NULL),(115,'itManagement','TI management',1,'2023-03-29 07:27:55','2023-03-29 07:28:04',NULL),(119,'palletizerBoss','Jefe de paletizadores',1,'2023-06-07 11:51:54','2023-06-07 11:51:54',NULL),(120,'developerBoss','Jefe de proyecto de desarrollo',1,'2023-06-19 07:07:21','2023-06-19 07:07:21',21709),(121,'buyerSalesAssistant','Rol para compradores que también son responsables de ventas',1,'2023-06-23 14:48:19','2023-06-23 14:48:19',NULL); +INSERT INTO `role` VALUES (1,'employee','Empleado básico',1,'2017-05-19 07:04:58','2023-06-08 16:47:57',NULL),(2,'customer','Privilegios básicos de un cliente',1,'2017-05-19 07:04:58','2023-06-02 20:33:28',NULL),(3,'agency','Consultar tablas de predicciones de bultos',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(5,'administrative','Tareas relacionadas con la contabilidad',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(6,'guest','Privilegios para usuarios sin cuenta',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(9,'developer','Desarrolladores del sistema',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(11,'account','Privilegios relacionados con el login',0,'2017-05-19 07:04:58','2017-09-20 17:06:35',NULL),(13,'teamBoss','Jefe de equipo/departamento',1,'2017-05-19 07:04:58','2021-06-30 13:29:30',NULL),(15,'logistic','Departamento de compras, responsables de la logistica',1,'2017-05-19 07:04:58','2018-02-12 10:50:10',NULL),(16,'logisticBoss','Jefe del departamento de logística',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(17,'adminBoss','Jefe del departamento de administración',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(18,'salesPerson','Departamento de ventas',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(19,'salesBoss','Jefe del departamento de ventas',1,'2017-05-19 07:04:58','2017-08-16 12:38:27',NULL),(20,'manager','Gerencia',1,'2017-06-01 14:57:02','2022-07-29 07:36:15',NULL),(21,'salesAssistant','Jefe auxiliar de ventas',1,'2017-08-16 12:40:52','2017-08-16 12:40:52',NULL),(22,'teamManager','Jefe de departamento con privilegios de auxiliar de venta.',1,'2017-09-07 09:08:12','2017-09-07 09:08:12',NULL),(30,'financialBoss','Director finaciero',1,'2017-09-21 11:05:36','2017-09-21 11:05:36',NULL),(31,'freelancer','Trabajadores por cuenta ajena',1,'2017-10-10 12:57:26','2017-10-10 12:59:27',NULL),(32,'ett','Trabajadores de empresa temporal',1,'2017-10-10 12:58:58','2017-10-10 12:59:20',NULL),(33,'invoicing','Personal con acceso a facturación',0,'2018-01-29 16:43:34','2018-01-29 16:43:34',NULL),(34,'agencyBoss','Jefe/a del departamento de agencias',1,'2018-01-29 16:44:39','2018-02-23 07:58:53',NULL),(35,'buyer','Departamento de compras',1,'2018-02-12 10:35:42','2018-02-12 10:35:42',NULL),(36,'replenisher','Trabajadores de camara',1,'2018-02-16 14:07:10','2019-04-12 05:38:08',NULL),(37,'hr','Gestor/a de recursos humanos',1,'2018-02-22 17:34:53','2018-02-22 17:34:53',NULL),(38,'hrBoss','Jefe/a de recursos humanos',1,'2018-02-22 17:35:09','2018-02-22 17:35:09',NULL),(39,'adminAssistant','Jefe auxiliar administrativo',1,'2018-02-23 10:37:36','2018-02-23 10:38:41',NULL),(40,'handmade','Departamento de confección',1,'2018-02-23 11:14:53','2018-02-23 11:39:12',NULL),(41,'handmadeBoss','Jefe de departamento de confección',1,'2018-02-23 11:15:09','2018-02-23 11:39:26',NULL),(42,'artificial','Departamento de artificial',1,'2018-02-23 11:39:59','2018-02-23 11:39:59',NULL),(43,'artificialBoss','Jefe del departamento de artificial',1,'2018-02-23 11:40:16','2018-02-23 11:40:16',NULL),(44,'accessory','Departamento de complementos',1,'2018-02-23 11:41:12','2018-02-23 11:41:12',NULL),(45,'accessoryBoss','Jefe del departamento de complementos',1,'2018-02-23 11:41:23','2018-02-23 11:41:23',NULL),(47,'cooler','Empleados de cámara',1,'2018-02-23 13:08:18','2018-02-23 13:08:18',NULL),(48,'coolerBoss','Jefe de cámara',1,'2018-02-23 13:12:01','2023-03-13 08:49:43',NULL),(49,'production','Empleado de producción',1,'2018-02-26 15:28:23','2021-02-12 09:42:35',NULL),(50,'productionBoss','Jefe de producción',1,'2018-02-26 15:34:12','2018-02-26 15:34:12',NULL),(51,'marketing','Departamento de marketing',1,'2018-03-01 07:28:39','2018-03-01 07:28:39',NULL),(52,'marketingBoss','Jefe del departamento de marketing',1,'2018-03-01 07:28:57','2018-03-01 07:28:57',NULL),(53,'insurance','Gestor de seguros de cambio',0,'2018-03-05 07:44:35','2019-02-01 13:47:57',NULL),(54,'itemPicker','Sacador en cámara',1,'2018-03-05 12:08:17','2018-03-05 12:08:17',NULL),(55,'itemPickerBoss','Jefe de sacadores',1,'2018-03-05 12:08:31','2018-03-05 12:08:31',NULL),(56,'delivery','Personal de reparto',1,'2018-05-30 06:07:02','2018-05-30 06:07:02',NULL),(57,'deliveryBoss','Jefe de personal de reparto',1,'2018-05-30 06:07:19','2018-05-30 06:07:19',NULL),(58,'packager','Departamento encajadores',1,'2019-01-21 12:43:45','2019-01-21 12:43:45',NULL),(59,'packagerBoss','Jefe departamento encajadores',1,'2019-01-21 12:44:10','2019-01-21 12:44:10',NULL),(60,'productionAssi','Tareas relacionadas con producción y administración',1,'2019-01-29 13:29:01','2019-01-29 13:29:01',NULL),(61,'replenisherBos','Jefe de Complementos/Camara',1,'2019-07-01 06:44:07','2019-07-01 06:44:07',NULL),(62,'noLogin','Role without login access to MySQL',0,'2019-07-01 06:50:19','2019-07-02 13:42:05',NULL),(64,'balanceSheet','Consulta de Balance',0,'2019-07-16 12:12:08','2019-07-16 12:12:08',NULL),(65,'officeBoss','Jefe de filial',1,'2019-08-02 06:54:26','2019-08-02 06:54:26',NULL),(66,'sysadmin','Administrador de sistema',1,'2019-08-08 06:58:56','2019-08-08 06:58:56',NULL),(67,'adminOfficer','categoria profesional oficial de administración',1,'2020-01-03 08:09:23','2020-01-03 08:09:23',NULL),(69,'coolerAssist','Asistente de cámara con permiso compras',1,'2020-02-05 12:36:09','2023-03-13 08:50:07',NULL),(70,'trainee','Alumno de prácticas',1,'2020-03-04 11:00:25','2020-03-04 11:00:25',NULL),(71,'checker','Rol de revisor con privilegios de itemPicker',1,'2020-10-02 10:50:07','2020-10-02 10:50:07',NULL),(72,'claimManager','Personal de reclamaciones',1,'2020-10-13 10:01:32','2020-10-26 07:29:46',NULL),(73,'financial','Departamento de finanzas',1,'2020-11-16 09:30:27','2020-11-16 09:30:27',NULL),(74,'userPhotos','Privilegios para subir fotos de usuario',1,'2021-02-03 10:24:27','2021-02-03 10:24:27',NULL),(75,'catalogPhotos','Privilegios para subir fotos del catálogo',1,'2021-02-03 10:24:27','2021-02-03 10:24:27',NULL),(76,'chat','Rol para utilizar el rocket chat',1,'2020-11-27 13:06:50','2020-12-17 07:49:41',NULL),(100,'root','Rol con todos los privilegios',0,'2018-04-23 14:33:36','2020-11-12 06:50:07',NULL),(101,'buyerBoss','Jefe del departamento de compras',1,'2021-06-16 09:53:17','2021-06-16 09:53:17',NULL),(102,'preservedBoss','Responsable preservado',1,'2021-09-14 13:45:37','2021-09-14 13:45:37',NULL),(103,'it','Departamento de informática',1,'2021-11-11 09:48:22','2021-11-11 09:48:22',NULL),(104,'itBoss','Jefe de departamento de informática',1,'2021-11-11 09:48:49','2021-11-11 09:48:49',NULL),(105,'grant','Adjudicar roles a usuarios',1,'2021-11-11 12:41:09','2021-11-11 12:41:09',NULL),(106,'ext','Usuarios externos de la Base de datos',1,'2021-11-23 14:51:16','2021-11-23 14:51:16',NULL),(107,'productionPlus','Creado para pepe por orden de Juanvi',1,'2022-02-08 06:47:10','2022-02-08 06:47:10',NULL),(108,'system','System user',1,'2022-05-16 08:09:51','2022-05-16 08:09:51',NULL),(109,'salesTeamBoss','Jefe de equipo de comerciales',1,'2022-06-14 13:45:56','2022-06-14 13:45:56',NULL),(110,'palletizer','Paletizadores',1,'2022-12-02 12:56:22','2022-12-02 12:56:30',NULL),(111,'entryEditor','Entry editor',1,'2023-01-13 11:21:55','2023-01-13 11:21:55',NULL),(112,'maintenance','Personal de mantenimiento',1,'2023-01-19 06:23:35','2023-01-19 06:23:35',NULL),(114,'maintenanceBos','Jefe de mantenimiento',1,'2023-01-19 06:31:16','2023-05-17 11:07:21',NULL),(115,'itManagement','TI management',1,'2023-03-29 07:27:55','2023-03-29 07:28:04',NULL),(119,'palletizerBoss','Jefe de paletizadores',1,'2023-06-07 11:51:54','2023-06-07 11:51:54',NULL),(120,'developerBoss','Jefe de proyecto de desarrollo',1,'2023-06-19 07:07:21','2023-06-19 07:07:21',21709),(121,'buyerSalesAssistant','Rol para compradores que también son responsables de ventas',1,'2023-06-23 14:48:19','2023-06-23 14:48:19',NULL),(122,'logisticAssistant','Jefe auxiliar de logística',1,'2023-06-26 07:21:15','2023-06-26 07:21:15',NULL); /*!40000 ALTER TABLE `role` ENABLE KEYS */; UNLOCK TABLES; @@ -164,7 +164,7 @@ USE `salix`; LOCK TABLES `ACL` WRITE; /*!40000 ALTER TABLE `ACL` DISABLE KEYS */; -INSERT INTO `ACL` VALUES (1,'Account','*','*','ALLOW','ROLE','employee'),(3,'Address','*','*','ALLOW','ROLE','employee'),(5,'AgencyService','*','READ','ALLOW','ROLE','employee'),(9,'ClientObservation','*','*','ALLOW','ROLE','employee'),(11,'ContactChannel','*','READ','ALLOW','ROLE','trainee'),(13,'Employee','*','READ','ALLOW','ROLE','employee'),(14,'PayMethod','*','READ','ALLOW','ROLE','trainee'),(16,'FakeProduction','*','READ','ALLOW','ROLE','employee'),(17,'Warehouse','* ','READ','ALLOW','ROLE','trainee'),(20,'TicketState','*','*','ALLOW','ROLE','employee'),(24,'Delivery','*','READ','ALLOW','ROLE','employee'),(25,'Zone','*','READ','ALLOW','ROLE','employee'),(26,'ClientCredit','*','*','ALLOW','ROLE','employee'),(27,'ClientCreditLimit','*','READ','ALLOW','ROLE','trainee'),(30,'GreugeType','*','READ','ALLOW','ROLE','trainee'),(31,'Mandate','*','READ','ALLOW','ROLE','trainee'),(32,'MandateType','*','READ','ALLOW','ROLE','trainee'),(33,'Company','*','READ','ALLOW','ROLE','trainee'),(34,'Greuge','*','READ','ALLOW','ROLE','trainee'),(35,'AddressObservation','*','*','ALLOW','ROLE','employee'),(36,'ObservationType','*','*','ALLOW','ROLE','employee'),(37,'Greuge','*','WRITE','ALLOW','ROLE','employee'),(38,'AgencyMode','*','READ','ALLOW','ROLE','employee'),(39,'ItemTag','*','WRITE','ALLOW','ROLE','buyer'),(40,'ItemBotanical','*','WRITE','ALLOW','ROLE','buyer'),(41,'ItemBotanical','*','READ','ALLOW','ROLE','employee'),(42,'ItemPlacement','*','WRITE','ALLOW','ROLE','buyer'),(43,'ItemPlacement','*','WRITE','ALLOW','ROLE','replenisher'),(44,'ItemPlacement','*','READ','ALLOW','ROLE','employee'),(45,'ItemBarcode','*','READ','ALLOW','ROLE','employee'),(46,'ItemBarcode','*','WRITE','ALLOW','ROLE','buyer'),(47,'ItemBarcode','*','WRITE','ALLOW','ROLE','replenisher'),(51,'ItemTag','*','READ','ALLOW','ROLE','employee'),(53,'Item','*','READ','ALLOW','ROLE','employee'),(54,'Item','*','WRITE','ALLOW','ROLE','buyer'),(55,'Recovery','*','READ','ALLOW','ROLE','trainee'),(56,'Recovery','*','WRITE','ALLOW','ROLE','administrative'),(58,'CreditClassification','*','*','ALLOW','ROLE','insurance'),(60,'CreditInsurance','*','*','ALLOW','ROLE','insurance'),(61,'InvoiceOut','*','READ','ALLOW','ROLE','employee'),(63,'TicketObservation','*','*','ALLOW','ROLE','employee'),(64,'Route','*','READ','ALLOW','ROLE','employee'),(65,'Sale','*','READ','ALLOW','ROLE','employee'),(66,'TicketTracking','*','READ','ALLOW','ROLE','employee'),(68,'TicketPackaging','*','*','ALLOW','ROLE','employee'),(69,'Packaging','*','READ','ALLOW','ROLE','employee'),(70,'Packaging','*','WRITE','ALLOW','ROLE','logistic'),(72,'SaleComponent','*','READ','ALLOW','ROLE','employee'),(73,'Expedition','*','READ','ALLOW','ROLE','employee'),(74,'Expedition','*','WRITE','ALLOW','ROLE','deliveryBoss'),(75,'Expedition','*','WRITE','ALLOW','ROLE','production'),(76,'AnnualAverageInvoiced','*','READ','ALLOW','ROLE','employee'),(77,'WorkerMana','*','READ','ALLOW','ROLE','employee'),(78,'TicketTracking','*','WRITE','ALLOW','ROLE','production'),(79,'TicketTracking','changeState','*','ALLOW','ROLE','employee'),(80,'Sale','deleteSales','*','ALLOW','ROLE','employee'),(81,'Sale','moveToTicket','*','ALLOW','ROLE','employee'),(82,'Sale','updateQuantity','*','ALLOW','ROLE','employee'),(83,'Sale','updatePrice','*','ALLOW','ROLE','employee'),(84,'Sale','updateDiscount','*','ALLOW','ROLE','employee'),(85,'SaleTracking','*','READ','ALLOW','ROLE','employee'),(86,'Order','*','*','ALLOW','ROLE','employee'),(87,'OrderRow','*','*','ALLOW','ROLE','employee'),(88,'ClientContact','*','*','ALLOW','ROLE','employee'),(89,'Sale','moveToNewTicket','*','ALLOW','ROLE','employee'),(90,'Sale','reserve','*','ALLOW','ROLE','employee'),(91,'TicketWeekly','*','READ','ALLOW','ROLE','employee'),(94,'Agency','landsThatDay','*','ALLOW','ROLE','employee'),(96,'ClaimEnd','*','READ','ALLOW','ROLE','employee'),(97,'ClaimEnd','*','WRITE','ALLOW','ROLE','claimManager'),(98,'ClaimBeginning','*','*','ALLOW','ROLE','employee'),(99,'ClaimDevelopment','*','READ','ALLOW','ROLE','employee'),(100,'ClaimDevelopment','*','WRITE','ALLOW','ROLE','claimManager'),(102,'Claim','createFromSales','*','ALLOW','ROLE','employee'),(104,'Item','*','WRITE','ALLOW','ROLE','marketingBoss'),(105,'ItemBarcode','*','WRITE','ALLOW','ROLE','marketingBoss'),(106,'ItemBotanical','*','WRITE','ALLOW','ROLE','marketingBoss'),(108,'ItemPlacement','*','WRITE','ALLOW','ROLE','marketingBoss'),(109,'UserConfig','*','*','ALLOW','ROLE','employee'),(110,'Bank','*','READ','ALLOW','ROLE','trainee'),(111,'ClientLog','*','READ','ALLOW','ROLE','trainee'),(112,'Defaulter','*','READ','ALLOW','ROLE','employee'),(113,'ClientRisk','*','READ','ALLOW','ROLE','trainee'),(114,'Receipt','*','READ','ALLOW','ROLE','trainee'),(115,'Receipt','*','WRITE','ALLOW','ROLE','administrative'),(116,'BankEntity','*','*','ALLOW','ROLE','employee'),(117,'ClientSample','*','*','ALLOW','ROLE','employee'),(118,'WorkerTeam','*','*','ALLOW','ROLE','salesPerson'),(119,'Travel','*','READ','ALLOW','ROLE','employee'),(120,'Travel','*','WRITE','ALLOW','ROLE','buyer'),(121,'Item','regularize','*','ALLOW','ROLE','employee'),(122,'TicketRequest','*','*','ALLOW','ROLE','employee'),(124,'Client','confirmTransaction','WRITE','ALLOW','ROLE','administrative'),(125,'Agency','getAgenciesWithWarehouse','*','ALLOW','ROLE','employee'),(126,'Client','activeWorkersWithRole','*','ALLOW','ROLE','employee'),(127,'TicketLog','*','READ','ALLOW','ROLE','employee'),(129,'TicketService','*','*','ALLOW','ROLE','employee'),(130,'Expedition','*','WRITE','ALLOW','ROLE','packager'),(131,'CreditInsurance','*','READ','ALLOW','ROLE','trainee'),(132,'CreditClassification','*','READ','ALLOW','ROLE','trainee'),(133,'ItemTag','*','WRITE','ALLOW','ROLE','marketingBoss'),(135,'ZoneGeo','*','READ','ALLOW','ROLE','employee'),(136,'ZoneCalendar','*','READ','ALLOW','ROLE','employee'),(137,'ZoneIncluded','*','READ','ALLOW','ROLE','employee'),(138,'LabourHoliday','*','READ','ALLOW','ROLE','employee'),(139,'LabourHolidayLegend','*','READ','ALLOW','ROLE','employee'),(140,'LabourHolidayType','*','READ','ALLOW','ROLE','employee'),(141,'Zone','*','*','ALLOW','ROLE','logisticBoss'),(142,'ZoneCalendar','*','WRITE','ALLOW','ROLE','deliveryBoss'),(143,'ZoneIncluded','*','*','ALLOW','ROLE','deliveryBoss'),(144,'Stowaway','*','*','ALLOW','ROLE','employee'),(145,'Ticket','getPossibleStowaways','READ','ALLOW','ROLE','employee'),(147,'UserConfigView','*','*','ALLOW','ROLE','employee'),(148,'UserConfigView','*','*','ALLOW','ROLE','employee'),(149,'Sip','*','READ','ALLOW','ROLE','employee'),(150,'Sip','*','WRITE','ALLOW','ROLE','hr'),(151,'Department','*','READ','ALLOW','ROLE','employee'),(152,'Department','*','WRITE','ALLOW','ROLE','hr'),(153,'Route','*','READ','ALLOW','ROLE','employee'),(154,'Route','*','WRITE','ALLOW','ROLE','delivery'),(155,'Calendar','*','READ','ALLOW','ROLE','hr'),(156,'WorkerLabour','*','READ','ALLOW','ROLE','hr'),(157,'Calendar','absences','READ','ALLOW','ROLE','employee'),(158,'ItemTag','*','WRITE','ALLOW','ROLE','accessory'),(160,'TicketServiceType','*','READ','ALLOW','ROLE','employee'),(161,'TicketConfig','*','READ','ALLOW','ROLE','employee'),(162,'InvoiceOut','delete','WRITE','ALLOW','ROLE','invoicing'),(163,'InvoiceOut','book','WRITE','ALLOW','ROLE','invoicing'),(165,'TicketDms','*','*','ALLOW','ROLE','employee'),(167,'Worker','isSubordinate','READ','ALLOW','ROLE','employee'),(168,'Worker','mySubordinates','READ','ALLOW','ROLE','employee'),(169,'WorkerTimeControl','filter','READ','ALLOW','ROLE','employee'),(170,'WorkerTimeControl','addTime','WRITE','ALLOW','ROLE','employee'),(171,'TicketServiceType','*','WRITE','ALLOW','ROLE','administrative'),(172,'Sms','*','READ','ALLOW','ROLE','employee'),(173,'Sms','send','WRITE','ALLOW','ROLE','employee'),(176,'Device','*','*','ALLOW','ROLE','employee'),(177,'Device','*','*','ALLOW','ROLE','employee'),(178,'WorkerTimeControl','*','*','ALLOW','ROLE','employee'),(179,'ItemLog','*','READ','ALLOW','ROLE','employee'),(180,'RouteLog','*','READ','ALLOW','ROLE','employee'),(181,'Dms','removeFile','WRITE','ALLOW','ROLE','employee'),(182,'Dms','uploadFile','WRITE','ALLOW','ROLE','employee'),(183,'Dms','downloadFile','READ','ALLOW','ROLE','employee'),(184,'Client','uploadFile','WRITE','ALLOW','ROLE','employee'),(185,'ClientDms','removeFile','WRITE','ALLOW','ROLE','employee'),(186,'ClientDms','*','READ','ALLOW','ROLE','trainee'),(187,'Ticket','uploadFile','WRITE','ALLOW','ROLE','employee'),(190,'Route','updateVolume','WRITE','ALLOW','ROLE','deliveryBoss'),(191,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(192,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(194,'Postcode','*','WRITE','ALLOW','ROLE','deliveryBoss'),(195,'Ticket','addSale','WRITE','ALLOW','ROLE','employee'),(196,'Dms','updateFile','WRITE','ALLOW','ROLE','employee'),(197,'Dms','*','READ','ALLOW','ROLE','trainee'),(198,'ClaimDms','removeFile','WRITE','ALLOW','ROLE','employee'),(199,'ClaimDms','*','READ','ALLOW','ROLE','employee'),(200,'Claim','uploadFile','WRITE','ALLOW','ROLE','employee'),(201,'Sale','updateConcept','WRITE','ALLOW','ROLE','employee'),(202,'Claim','updateClaimAction','WRITE','ALLOW','ROLE','claimManager'),(203,'UserPhone','*','*','ALLOW','ROLE','employee'),(204,'WorkerDms','removeFile','WRITE','ALLOW','ROLE','hr'),(205,'WorkerDms','*','READ','ALLOW','ROLE','hr'),(206,'Chat','*','*','ALLOW','ROLE','employee'),(207,'Chat','sendMessage','*','ALLOW','ROLE','employee'),(208,'Sale','recalculatePrice','WRITE','ALLOW','ROLE','employee'),(209,'Ticket','recalculateComponents','WRITE','ALLOW','ROLE','employee'),(211,'TravelLog','*','READ','ALLOW','ROLE','buyer'),(212,'Thermograph','*','*','ALLOW','ROLE','buyer'),(213,'TravelThermograph','*','WRITE','ALLOW','ROLE','buyer'),(214,'Entry','*','*','ALLOW','ROLE','buyer'),(215,'TicketWeekly','*','WRITE','ALLOW','ROLE','buyer'),(216,'TravelThermograph','*','READ','ALLOW','ROLE','employee'),(218,'Intrastat','*','*','ALLOW','ROLE','buyer'),(221,'UserConfig','getUserConfig','READ','ALLOW','ROLE','account'),(222,'Client','*','READ','ALLOW','ROLE','trainee'),(226,'ClientObservation','*','READ','ALLOW','ROLE','trainee'),(227,'Address','*','READ','ALLOW','ROLE','trainee'),(228,'AddressObservation','*','READ','ALLOW','ROLE','trainee'),(230,'ClientCredit','*','READ','ALLOW','ROLE','trainee'),(231,'ClientContact','*','READ','ALLOW','ROLE','trainee'),(232,'ClientSample','*','READ','ALLOW','ROLE','trainee'),(233,'EntryLog','*','READ','ALLOW','ROLE','buyer'),(234,'WorkerLog','find','READ','ALLOW','ROLE','hr'),(235,'CustomsAgent','*','*','ALLOW','ROLE','employee'),(236,'Buy','*','*','ALLOW','ROLE','buyer'),(237,'WorkerDms','filter','*','ALLOW','ROLE','employee'),(238,'Town','*','WRITE','ALLOW','ROLE','deliveryBoss'),(239,'Province','*','WRITE','ALLOW','ROLE','deliveryBoss'),(240,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(241,'SupplierContact','*','WRITE','ALLOW','ROLE','administrative'),(242,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(244,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(248,'RoleMapping','*','READ','ALLOW','ROLE','account'),(249,'UserPassword','*','READ','ALLOW','ROLE','account'),(250,'Town','*','WRITE','ALLOW','ROLE','deliveryBoss'),(251,'Province','*','WRITE','ALLOW','ROLE','deliveryBoss'),(252,'Supplier','*','READ','ALLOW','ROLE','employee'),(253,'Supplier','*','WRITE','ALLOW','ROLE','administrative'),(254,'SupplierLog','*','READ','ALLOW','ROLE','employee'),(256,'Image','*','WRITE','ALLOW','ROLE','employee'),(257,'FixedPrice','*','*','ALLOW','ROLE','buyer'),(258,'PayDem','*','READ','ALLOW','ROLE','employee'),(259,'Client','createReceipt','*','ALLOW','ROLE','salesAssistant'),(260,'PrintServerQueue','*','WRITE','ALLOW','ROLE','employee'),(261,'SupplierAccount','*','*','ALLOW','ROLE','administrative'),(262,'Entry','*','*','ALLOW','ROLE','administrative'),(263,'InvoiceIn','*','*','ALLOW','ROLE','administrative'),(264,'StarredModule','*','*','ALLOW','ROLE','employee'),(265,'ItemBotanical','*','WRITE','ALLOW','ROLE','logisticBoss'),(266,'ZoneLog','*','READ','ALLOW','ROLE','employee'),(267,'Genus','*','WRITE','ALLOW','ROLE','logisticBoss'),(268,'Specie','*','WRITE','ALLOW','ROLE','logisticBoss'),(269,'InvoiceOut','createPdf','WRITE','ALLOW','ROLE','employee'),(270,'SupplierAddress','*','*','ALLOW','ROLE','employee'),(271,'SalesMonitor','*','*','ALLOW','ROLE','employee'),(272,'InvoiceInLog','*','READ','ALLOW','ROLE','employee'),(273,'InvoiceInTax','*','*','ALLOW','ROLE','administrative'),(274,'InvoiceInLog','*','READ','ALLOW','ROLE','administrative'),(275,'InvoiceOut','createManualInvoice','WRITE','ALLOW','ROLE','invoicing'),(276,'InvoiceOut','globalInvoicing','WRITE','ALLOW','ROLE','invoicing'),(277,'Role','*','*','ALLOW','ROLE','it'),(278,'RoleInherit','*','WRITE','ALLOW','ROLE','grant'),(279,'MailAlias','*','*','ALLOW','ROLE','marketing'),(283,'EntryObservation','*','*','ALLOW','ROLE','buyer'),(284,'LdapConfig','*','*','ALLOW','ROLE','sysadmin'),(285,'SambaConfig','*','*','ALLOW','ROLE','sysadmin'),(286,'ACL','*','*','ALLOW','ROLE','developer'),(287,'AccessToken','*','*','ALLOW','ROLE','developer'),(288,'MailAliasAccount','*','*','ALLOW','ROLE','marketing'),(289,'MailAliasAccount','*','*','ALLOW','ROLE','hr'),(291,'MailForward','*','*','ALLOW','ROLE','marketing'),(292,'MailForward','*','*','ALLOW','ROLE','hr'),(293,'RoleInherit','*','*','ALLOW','ROLE','it'),(294,'RoleRole','*','*','ALLOW','ROLE','it'),(295,'AccountConfig','*','*','ALLOW','ROLE','sysadmin'),(296,'Collection','*','READ','ALLOW','ROLE','employee'),(297,'Sale','refund','WRITE','ALLOW','ROLE','invoicing'),(298,'InvoiceInDueDay','*','*','ALLOW','ROLE','administrative'),(299,'Collection','setSaleQuantity','*','ALLOW','ROLE','employee'),(302,'AgencyTerm','*','*','ALLOW','ROLE','administrative'),(303,'ClaimLog','*','READ','ALLOW','ROLE','claimManager'),(304,'Edi','updateData','WRITE','ALLOW','ROLE','employee'),(305,'EducationLevel','*','*','ALLOW','ROLE','employee'),(306,'InvoiceInIntrastat','*','*','ALLOW','ROLE','employee'),(307,'SupplierAgencyTerm','*','*','ALLOW','ROLE','administrative'),(308,'InvoiceInIntrastat','*','*','ALLOW','ROLE','employee'),(309,'Zone','getZoneClosing','*','ALLOW','ROLE','employee'),(310,'ExpeditionState','*','READ','ALLOW','ROLE','employee'),(311,'Expense','*','READ','ALLOW','ROLE','employee'),(312,'Expense','*','WRITE','ALLOW','ROLE','administrative'),(314,'SupplierActivity','*','READ','ALLOW','ROLE','employee'),(315,'SupplierActivity','*','WRITE','ALLOW','ROLE','administrative'),(316,'Dms','deleteTrashFiles','WRITE','ALLOW','ROLE','employee'),(317,'ClientUnpaid','*','*','ALLOW','ROLE','administrative'),(318,'MdbVersion','*','*','ALLOW','ROLE','developer'),(319,'ItemType','*','READ','ALLOW','ROLE','employee'),(320,'ItemType','*','WRITE','ALLOW','ROLE','buyer'),(321,'InvoiceOut','refund','WRITE','ALLOW','ROLE','invoicing'),(322,'InvoiceOut','refund','WRITE','ALLOW','ROLE','salesAssistant'),(323,'InvoiceOut','refund','WRITE','ALLOW','ROLE','claimManager'),(324,'Ticket','refund','WRITE','ALLOW','ROLE','invoicing'),(325,'Ticket','refund','WRITE','ALLOW','ROLE','salesAssistant'),(326,'Ticket','refund','WRITE','ALLOW','ROLE','claimManager'),(327,'Sale','refund','WRITE','ALLOW','ROLE','salesAssistant'),(328,'Sale','refund','WRITE','ALLOW','ROLE','claimManager'),(329,'TicketRefund','*','WRITE','ALLOW','ROLE','invoicing'),(330,'ClaimObservation','*','WRITE','ALLOW','ROLE','salesPerson'),(331,'ClaimObservation','*','READ','ALLOW','ROLE','salesPerson'),(332,'Client','setPassword','WRITE','ALLOW','ROLE','salesPerson'),(333,'Client','updateUser','WRITE','ALLOW','ROLE','salesPerson'),(334,'ShelvingLog','*','READ','ALLOW','ROLE','employee'),(335,'ZoneExclusionGeo','*','READ','ALLOW','ROLE','employee'),(336,'ZoneExclusionGeo','*','WRITE','ALLOW','ROLE','deliveryBoss'),(337,'Parking','*','*','ALLOW','ROLE','employee'),(338,'Shelving','*','*','ALLOW','ROLE','employee'),(339,'OsTicket','*','*','ALLOW','ROLE','employee'),(340,'OsTicketConfig','*','*','ALLOW','ROLE','it'),(341,'ClientConsumptionQueue','*','WRITE','ALLOW','ROLE','employee'),(342,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','employee'),(343,'Ticket','deliveryNoteEmail','WRITE','ALLOW','ROLE','employee'),(344,'Ticket','deliveryNoteCsvPdf','READ','ALLOW','ROLE','employee'),(345,'Ticket','deliveryNoteCsvEmail','READ','ALLOW','ROLE','employee'),(346,'Client','campaignMetricsPdf','READ','ALLOW','ROLE','employee'),(347,'Client','campaignMetricsEmail','WRITE','ALLOW','ROLE','employee'),(348,'Client','clientWelcomeHtml','READ','ALLOW','ROLE','employee'),(349,'Client','clientWelcomeEmail','WRITE','ALLOW','ROLE','employee'),(350,'Client','creditRequestPdf','READ','ALLOW','ROLE','employee'),(351,'Client','creditRequestHtml','READ','ALLOW','ROLE','employee'),(352,'Client','creditRequestEmail','WRITE','ALLOW','ROLE','employee'),(353,'Client','printerSetupHtml','READ','ALLOW','ROLE','employee'),(354,'Client','printerSetupEmail','WRITE','ALLOW','ROLE','employee'),(355,'Client','sepaCoreEmail','WRITE','ALLOW','ROLE','employee'),(356,'Client','letterDebtorPdf','READ','ALLOW','ROLE','employee'),(357,'Client','letterDebtorStHtml','READ','ALLOW','ROLE','employee'),(358,'Client','letterDebtorStEmail','WRITE','ALLOW','ROLE','employee'),(359,'Client','letterDebtorNdHtml','READ','ALLOW','ROLE','employee'),(360,'Client','letterDebtorNdEmail','WRITE','ALLOW','ROLE','employee'),(361,'Client','clientDebtStatementPdf','READ','ALLOW','ROLE','employee'),(362,'Client','clientDebtStatementHtml','READ','ALLOW','ROLE','employee'),(363,'Client','clientDebtStatementEmail','WRITE','ALLOW','ROLE','employee'),(364,'Client','incotermsAuthorizationPdf','READ','ALLOW','ROLE','employee'),(365,'Client','incotermsAuthorizationHtml','READ','ALLOW','ROLE','employee'),(366,'Client','incotermsAuthorizationEmail','WRITE','ALLOW','ROLE','employee'),(367,'Client','consumptionSendQueued','WRITE','ALLOW','ROLE','system'),(368,'InvoiceOut','invoiceEmail','WRITE','ALLOW','ROLE','employee'),(369,'InvoiceOut','exportationPdf','READ','ALLOW','ROLE','employee'),(370,'InvoiceOut','sendQueued','WRITE','ALLOW','ROLE','system'),(371,'Ticket','invoiceCsvPdf','READ','ALLOW','ROLE','employee'),(372,'Ticket','invoiceCsvEmail','WRITE','ALLOW','ROLE','employee'),(373,'Supplier','campaignMetricsPdf','READ','ALLOW','ROLE','employee'),(374,'Supplier','campaignMetricsEmail','WRITE','ALLOW','ROLE','employee'),(375,'Travel','extraCommunityPdf','READ','ALLOW','ROLE','employee'),(376,'Travel','extraCommunityEmail','WRITE','ALLOW','ROLE','employee'),(377,'Entry','entryOrderPdf','READ','ALLOW','ROLE','employee'),(378,'OsTicket','osTicketReportEmail','WRITE','ALLOW','ROLE','system'),(379,'Item','buyerWasteEmail','WRITE','ALLOW','ROLE','system'),(380,'Claim','claimPickupPdf','READ','ALLOW','ROLE','employee'),(381,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','claimManager'),(382,'Item','labelPdf','READ','ALLOW','ROLE','employee'),(383,'Sector','*','READ','ALLOW','ROLE','employee'),(384,'Sector','*','WRITE','ALLOW','ROLE','employee'),(385,'Route','driverRoutePdf','READ','ALLOW','ROLE','employee'),(386,'Route','driverRouteEmail','WRITE','ALLOW','ROLE','employee'),(387,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','customer'),(388,'Supplier','newSupplier','WRITE','ALLOW','ROLE','administrative'),(389,'ClaimRma','*','READ','ALLOW','ROLE','claimManager'),(390,'ClaimRma','*','WRITE','ALLOW','ROLE','claimManager'),(391,'Notification','*','WRITE','ALLOW','ROLE','system'),(392,'Boxing','*','*','ALLOW','ROLE','employee'),(393,'Url','*','READ','ALLOW','ROLE','employee'),(394,'Url','*','WRITE','ALLOW','ROLE','it'),(395,'ItemShelving','*','READ','ALLOW','ROLE','employee'),(396,'ItemShelving','*','WRITE','ALLOW','ROLE','production'),(397,'ItemShelvingPlacementSupplyStock','*','READ','ALLOW','ROLE','employee'),(398,'NotificationQueue','*','*','ALLOW','ROLE','employee'),(399,'InvoiceOut','clientsToInvoice','WRITE','ALLOW','ROLE','invoicing'),(400,'InvoiceOut','invoiceClient','WRITE','ALLOW','ROLE','invoicing'),(401,'Sale','editTracked','WRITE','ALLOW','ROLE','production'),(402,'Sale','editFloramondo','WRITE','ALLOW','ROLE','salesAssistant'),(403,'Receipt','balanceCompensationEmail','WRITE','ALLOW','ROLE','employee'),(404,'Receipt','balanceCompensationPdf','READ','ALLOW','ROLE','employee'),(405,'Ticket','getTicketsFuture','READ','ALLOW','ROLE','employee'),(406,'Ticket','merge','WRITE','ALLOW','ROLE','employee'),(407,'Sale','editFloramondo','WRITE','ALLOW','ROLE','logistic'),(408,'ZipConfig','*','*','ALLOW','ROLE','employee'),(409,'Item','*','WRITE','ALLOW','ROLE','administrative'),(410,'Sale','editCloned','WRITE','ALLOW','ROLE','buyer'),(411,'Sale','editCloned','WRITE','ALLOW','ROLE','salesAssistant'),(414,'MdbVersion','*','READ','ALLOW','ROLE','$everyone'),(416,'TicketLog','getChanges','READ','ALLOW','ROLE','employee'),(417,'Ticket','getTicketsAdvance','READ','ALLOW','ROLE','employee'),(418,'EntryLog','*','READ','ALLOW','ROLE','administrative'),(419,'Sale','editTracked','WRITE','ALLOW','ROLE','buyer'),(420,'MdbBranch','*','READ','ALLOW','ROLE','$everyone'),(421,'ItemShelvingSale','*','*','ALLOW','ROLE','employee'),(422,'Docuware','checkFile','READ','ALLOW','ROLE','employee'),(423,'Docuware','download','READ','ALLOW','ROLE','salesPerson'),(424,'Docuware','upload','WRITE','ALLOW','ROLE','productionAssi'),(425,'Docuware','deliveryNoteEmail','WRITE','ALLOW','ROLE','salesPerson'),(426,'TpvTransaction','confirm','WRITE','ALLOW','ROLE','$everyone'),(427,'TpvTransaction','start','WRITE','ALLOW','ROLE','$authenticated'),(428,'TpvTransaction','end','WRITE','ALLOW','ROLE','$authenticated'),(429,'ItemConfig','*','READ','ALLOW','ROLE','employee'),(431,'Tag','onSubmit','WRITE','ALLOW','ROLE','employee'),(432,'Worker','updateAttributes','WRITE','ALLOW','ROLE','hr'),(433,'Worker','createAbsence','*','ALLOW','ROLE','employee'),(434,'Worker','updateAbsence','WRITE','ALLOW','ROLE','employee'),(435,'Worker','deleteAbsence','*','ALLOW','ROLE','employee'),(436,'Worker','new','WRITE','ALLOW','ROLE','hr'),(437,'Role','*','READ','ALLOW','ROLE','hr'),(438,'Client','getClientOrSupplierReference','READ','ALLOW','ROLE','employee'),(439,'NotificationSubscription','*','*','ALLOW','ROLE','employee'),(440,'NotificationAcl','*','READ','ALLOW','ROLE','employee'),(441,'MdbApp','*','READ','ALLOW','ROLE','$everyone'),(442,'MdbApp','*','*','ALLOW','ROLE','developer'),(443,'ItemConfig','*','*','ALLOW','ROLE','employee'),(444,'DeviceProduction','*','*','ALLOW','ROLE','hr'),(445,'DeviceProductionModels','*','*','ALLOW','ROLE','hr'),(446,'DeviceProductionState','*','*','ALLOW','ROLE','hr'),(447,'DeviceProductionUser','*','*','ALLOW','ROLE','hr'),(448,'DeviceProduction','*','*','ALLOW','ROLE','productionAssi'),(449,'DeviceProductionModels','*','*','ALLOW','ROLE','productionAssi'),(450,'DeviceProductionState','*','*','ALLOW','ROLE','productionAssi'),(451,'DeviceProductionUser','*','*','ALLOW','ROLE','productionAssi'),(452,'Worker','deallocatePDA','*','ALLOW','ROLE','hr'),(453,'Worker','allocatePDA','*','ALLOW','ROLE','hr'),(454,'Worker','deallocatePDA','*','ALLOW','ROLE','productionAssi'),(455,'Worker','allocatePDA','*','ALLOW','ROLE','productionAssi'),(456,'Zone','*','*','ALLOW','ROLE','deliveryBoss'),(457,'Account','setPassword','WRITE','ALLOW','ROLE','itManagement'),(458,'Operator','*','READ','ALLOW','ROLE','employee'),(459,'Operator','*','WRITE','ALLOW','ROLE','employee'),(460,'InvoiceIn','getSerial','READ','ALLOW','ROLE','administrative'),(461,'Ticket','saveSign','WRITE','ALLOW','ROLE','employee'),(462,'InvoiceOut','negativeBases','READ','ALLOW','ROLE','administrative'),(463,'InvoiceOut','negativeBasesCsv','READ','ALLOW','ROLE','administrative'),(464,'WorkerObservation','*','*','ALLOW','ROLE','hr'),(465,'ClientInforma','*','READ','ALLOW','ROLE','employee'),(466,'ClientInforma','*','WRITE','ALLOW','ROLE','financial'),(467,'Receipt','receiptEmail','*','ALLOW','ROLE','salesAssistant'),(468,'Client','setRating','WRITE','ALLOW','ROLE','financial'),(469,'Client','*','READ','ALLOW','ROLE','employee'),(470,'Client','addressesPropagateRe','*','ALLOW','ROLE','employee'),(471,'Client','canBeInvoiced','*','ALLOW','ROLE','employee'),(472,'Client','canCreateTicket','*','ALLOW','ROLE','employee'),(473,'Client','consumption','*','ALLOW','ROLE','employee'),(474,'Client','createAddress','*','ALLOW','ROLE','employee'),(475,'Client','createWithUser','*','ALLOW','ROLE','employee'),(476,'Client','extendedListFilter','*','ALLOW','ROLE','employee'),(477,'Client','getAverageInvoiced','*','ALLOW','ROLE','employee'),(478,'Client','getCard','*','ALLOW','ROLE','employee'),(479,'Client','getDebt','*','ALLOW','ROLE','employee'),(480,'Client','getMana','*','ALLOW','ROLE','employee'),(481,'Client','transactions','*','ALLOW','ROLE','employee'),(482,'Client','hasCustomerRole','*','ALLOW','ROLE','employee'),(483,'Client','isValidClient','*','ALLOW','ROLE','employee'),(484,'Client','lastActiveTickets','*','ALLOW','ROLE','employee'),(485,'Client','sendSms','*','ALLOW','ROLE','employee'),(486,'Client','setPassword','*','ALLOW','ROLE','employee'),(487,'Client','summary','*','ALLOW','ROLE','employee'),(488,'Client','updateAddress','*','ALLOW','ROLE','employee'),(489,'Client','updateFiscalData','*','ALLOW','ROLE','employee'),(491,'Client','uploadFile','*','ALLOW','ROLE','employee'),(492,'Client','campaignMetricsPdf','*','ALLOW','ROLE','employee'),(493,'Client','campaignMetricsEmail','*','ALLOW','ROLE','employee'),(494,'Client','clientWelcomeHtml','*','ALLOW','ROLE','employee'),(495,'Client','clientWelcomeEmail','*','ALLOW','ROLE','employee'),(496,'Client','printerSetupHtml','*','ALLOW','ROLE','employee'),(497,'Client','printerSetupEmail','*','ALLOW','ROLE','employee'),(498,'Client','sepaCoreEmail','*','ALLOW','ROLE','employee'),(499,'Client','letterDebtorPdf','*','ALLOW','ROLE','employee'),(500,'Client','letterDebtorStHtml','*','ALLOW','ROLE','employee'),(501,'Client','letterDebtorStEmail','*','ALLOW','ROLE','employee'),(502,'Client','letterDebtorNdHtml','*','ALLOW','ROLE','employee'),(503,'Client','letterDebtorNdEmail','*','ALLOW','ROLE','employee'),(504,'Client','clientDebtStatementPdf','*','ALLOW','ROLE','employee'),(505,'Client','clientDebtStatementHtml','*','ALLOW','ROLE','employee'),(506,'Client','clientDebtStatementEmail','*','ALLOW','ROLE','employee'),(507,'Client','creditRequestPdf','*','ALLOW','ROLE','employee'),(508,'Client','creditRequestHtml','*','ALLOW','ROLE','employee'),(509,'Client','creditRequestEmail','*','ALLOW','ROLE','employee'),(510,'Client','incotermsAuthorizationPdf','*','ALLOW','ROLE','employee'),(511,'Client','incotermsAuthorizationHtml','*','ALLOW','ROLE','employee'),(512,'Client','incotermsAuthorizationEmail','*','ALLOW','ROLE','employee'),(513,'Client','consumptionSendQueued','*','ALLOW','ROLE','employee'),(514,'Client','filter','*','ALLOW','ROLE','employee'),(515,'Client','getClientOrSupplierReference','*','ALLOW','ROLE','employee'),(516,'Client','upsert','*','ALLOW','ROLE','employee'),(517,'Client','create','*','ALLOW','ROLE','employee'),(518,'Client','replaceById','*','ALLOW','ROLE','employee'),(519,'Client','updateAttributes','*','ALLOW','ROLE','employee'),(520,'Client','updateAttributes','*','ALLOW','ROLE','employee'),(521,'Client','deleteById','*','ALLOW','ROLE','employee'),(522,'Client','replaceOrCreate','*','ALLOW','ROLE','employee'),(523,'Client','updateAll','*','ALLOW','ROLE','employee'),(524,'Client','upsertWithWhere','*','ALLOW','ROLE','employee'),(525,'Defaulter','observationEmail','WRITE','ALLOW','ROLE','employee'),(526,'VnUser','*','*','ALLOW','ROLE','employee'),(527,'VnUser','acl','READ','ALLOW','ROLE','account'),(528,'VnUser','getCurrentUserData','READ','ALLOW','ROLE','account'),(529,'VnUser','changePassword','WRITE','ALLOW','ROLE','account'),(530,'Account','exists','READ','ALLOW','ROLE','account'),(531,'Account','exists','READ','ALLOW','ROLE','account'),(532,'UserLog','*','READ','ALLOW','ROLE','employee'),(533,'RoleLog','*','READ','ALLOW','ROLE','employee'),(534,'WagonType','*','*','ALLOW','ROLE','productionAssi'),(535,'WagonTypeColor','*','*','ALLOW','ROLE','productionAssi'),(536,'WagonTypeTray','*','*','ALLOW','ROLE','productionAssi'),(537,'WagonConfig','*','*','ALLOW','ROLE','productionAssi'),(538,'CollectionWagon','*','*','ALLOW','ROLE','productionAssi'),(539,'CollectionWagonTicket','*','*','ALLOW','ROLE','productionAssi'),(540,'Wagon','*','*','ALLOW','ROLE','productionAssi'),(541,'WagonType','createWagonType','*','ALLOW','ROLE','productionAssi'),(542,'WagonType','deleteWagonType','*','ALLOW','ROLE','productionAssi'),(543,'WagonType','editWagonType','*','ALLOW','ROLE','productionAssi'),(544,'Docuware','deliveryNoteEmail','WRITE','ALLOW','ROLE','employee'),(545,'Agency','find','READ','ALLOW','ROLE','employee'),(546,'Agency','seeExpired','READ','ALLOW','ROLE','coolerAssist'),(547,'WorkerLog','models','READ','ALLOW','ROLE','hr'),(548,'Ticket','editDiscount','WRITE','ALLOW','ROLE','claimManager'),(549,'Ticket','editDiscount','WRITE','ALLOW','ROLE','salesPerson'),(550,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','salesAssistant'),(551,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','deliveryBoss'),(552,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','buyer'),(553,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','claimManager'),(554,'Ticket','deleteTicketWithPartPrepared','WRITE','ALLOW','ROLE','salesAssistant'),(555,'Ticket','editZone','WRITE','ALLOW','ROLE','deliveryBoss'),(556,'State','editableStates','READ','ALLOW','ROLE','employee'),(557,'State','seeEditableStates','READ','ALLOW','ROLE','administrative'),(558,'State','seeEditableStates','READ','ALLOW','ROLE','production'),(559,'State','isSomeEditable','READ','ALLOW','ROLE','salesPerson'),(560,'State','isAllEditable','READ','ALLOW','ROLE','production'),(561,'State','isAllEditable','READ','ALLOW','ROLE','administrative'),(562,'Agency','seeExpired','READ','ALLOW','ROLE','administrative'),(563,'Agency','seeExpired','READ','ALLOW','ROLE','productionBoss'),(564,'Claim','createAfterDeadline','WRITE','ALLOW','ROLE','claimManager'),(565,'Client','editAddressLogifloraAllowed','WRITE','ALLOW','ROLE','salesAssistant'),(566,'Client','editFiscalDataWithoutTaxDataCheck','WRITE','ALLOW','ROLE','salesAssistant'),(567,'Client','editVerifiedDataWithoutTaxDataCheck','WRITE','ALLOW','ROLE','salesAssistant'),(568,'Client','editCredit','WRITE','ALLOW','ROLE','employee'),(569,'Client','isNotEditableCredit','WRITE','ALLOW','ROLE','financialBoss'),(570,'InvoiceOut','canCreatePdf','WRITE','ALLOW','ROLE','invoicing'),(571,'Supplier','editPayMethodCheck','WRITE','ALLOW','ROLE','financial'),(572,'Worker','isTeamBoss','WRITE','ALLOW','ROLE','teamBoss'),(573,'Worker','forceIsSubordinate','READ','ALLOW','ROLE','hr'),(574,'Claim','editState','WRITE','ALLOW','ROLE','claimManager'),(575,'Claim','find','READ','ALLOW','ROLE','salesPerson'),(576,'Claim','findById','READ','ALLOW','ROLE','salesPerson'),(577,'Claim','findOne','READ','ALLOW','ROLE','salesPerson'),(578,'Claim','getSummary','READ','ALLOW','ROLE','salesPerson'),(579,'Claim','updateClaim','WRITE','ALLOW','ROLE','salesPerson'),(580,'Claim','regularizeClaim','WRITE','ALLOW','ROLE','claimManager'),(581,'Claim','updateClaimDestination','WRITE','ALLOW','ROLE','claimManager'),(582,'Claim','downloadFile','READ','ALLOW','ROLE','claimManager'),(583,'Claim','deleteById','WRITE','ALLOW','ROLE','claimManager'),(584,'Claim','filter','READ','ALLOW','ROLE','salesPerson'),(585,'Claim','logs','READ','ALLOW','ROLE','claimManager'),(586,'Ticket','find','READ','ALLOW','ROLE','employee'),(587,'Ticket','findById','READ','ALLOW','ROLE','employee'),(588,'Ticket','findOne','READ','ALLOW','ROLE','employee'),(589,'Ticket','getVolume','READ','ALLOW','ROLE','employee'),(590,'Ticket','getTotalVolume','READ','ALLOW','ROLE','employee'),(591,'Ticket','summary','READ','ALLOW','ROLE','employee'),(592,'Ticket','priceDifference','READ','ALLOW','ROLE','employee'),(593,'Ticket','componentUpdate','WRITE','ALLOW','ROLE','employee'),(594,'Ticket','new','WRITE','ALLOW','ROLE','employee'),(595,'Ticket','isEditable','READ','ALLOW','ROLE','employee'),(596,'Ticket','setDeleted','WRITE','ALLOW','ROLE','employee'),(597,'Ticket','restore','WRITE','ALLOW','ROLE','employee'),(598,'Ticket','getSales','READ','ALLOW','ROLE','employee'),(599,'Ticket','getSalesPersonMana','READ','ALLOW','ROLE','employee'),(600,'Ticket','filter','READ','ALLOW','ROLE','employee'),(601,'Ticket','makeInvoice','WRITE','ALLOW','ROLE','employee'),(602,'Ticket','updateEditableTicket','WRITE','ALLOW','ROLE','employee'),(603,'Ticket','updateDiscount','WRITE','ALLOW','ROLE','employee'),(604,'Ticket','transferSales','WRITE','ALLOW','ROLE','employee'),(605,'Ticket','sendSms','WRITE','ALLOW','ROLE','employee'),(606,'Ticket','isLocked','READ','ALLOW','ROLE','employee'),(607,'Ticket','freightCost','READ','ALLOW','ROLE','employee'),(608,'Ticket','getComponentsSum','READ','ALLOW','ROLE','employee'),(609,'Ticket','updateAttributes','WRITE','ALLOW','ROLE','delivery'),(610,'Ticket','deliveryNoteCsv','READ','ALLOW','ROLE','employee'),(611,'State','find','READ','ALLOW','ROLE','employee'),(612,'State','findById','READ','ALLOW','ROLE','employee'),(613,'State','findOne','READ','ALLOW','ROLE','employee'),(614,'Worker','find','READ','ALLOW','ROLE','employee'),(615,'Worker','findById','READ','ALLOW','ROLE','employee'),(616,'Worker','findOne','READ','ALLOW','ROLE','employee'),(617,'Worker','filter','READ','ALLOW','ROLE','employee'),(618,'Worker','getWorkedHours','READ','ALLOW','ROLE','employee'),(619,'Worker','active','READ','ALLOW','ROLE','employee'),(620,'Worker','activeWithRole','READ','ALLOW','ROLE','employee'),(621,'Worker','uploadFile','WRITE','ALLOW','ROLE','hr'),(622,'Worker','contracts','READ','ALLOW','ROLE','employee'),(623,'Worker','holidays','READ','ALLOW','ROLE','employee'),(624,'Worker','activeContract','READ','ALLOW','ROLE','employee'),(625,'Worker','activeWithInheritedRole','READ','ALLOW','ROLE','employee'),(626,'Ticket','collectionLabel','READ','ALLOW','ROLE','employee'),(628,'Ticket','expeditionPalletLabel','READ','ALLOW','ROLE','employee'),(629,'Ticket','editDiscount','WRITE','ALLOW','ROLE','artificialBoss'),(630,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','salesTeamBoss'),(635,'Ticket','updateAttributes','WRITE','ALLOW','ROLE','administrative'),(636,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','salesPerson'),(637,'Claim','downloadFile','READ','ALLOW','ROLE','salesPerson'),(638,'Agency','seeExpired','READ','ALLOW','ROLE','artificialBoss'),(639,'Agency','seeExpired','READ','ALLOW','ROLE','logistic'),(640,'Claim','filter','READ','ALLOW','ROLE','buyer'),(641,'Claim','find','READ','ALLOW','ROLE','buyer'),(642,'Claim','findById','READ','ALLOW','ROLE','buyer'),(643,'Claim','getSummary','READ','ALLOW','ROLE','buyer'),(644,'Claim','filter','READ','ALLOW','ROLE','handmadeBoss'),(645,'Claim','find','READ','ALLOW','ROLE','handmadeBoss'),(646,'Claim','findById','READ','ALLOW','ROLE','handmadeBoss'),(647,'Claim','getSummary','READ','ALLOW','ROLE','handmadeBoss'),(648,'Claim','__get__lines','READ','ALLOW','ROLE','claimManager'),(649,'Claim','__get__lines','READ','ALLOW','ROLE','salesPerson'),(650,'Claim','getSummary','READ','ALLOW','ROLE','deliveryBoss'),(651,'Claim','findById','READ','ALLOW','ROLE','deliveryBoss'),(652,'Claim','find','READ','ALLOW','ROLE','deliveryBoss'),(653,'Claim','filter','READ','ALLOW','ROLE','deliveryBoss'),(654,'Ticket','editZone','WRITE','ALLOW','ROLE','logistic'); +INSERT INTO `ACL` VALUES (3,'Address','*','*','ALLOW','ROLE','employee'),(5,'AgencyService','*','READ','ALLOW','ROLE','employee'),(9,'ClientObservation','*','*','ALLOW','ROLE','employee'),(11,'ContactChannel','*','READ','ALLOW','ROLE','trainee'),(13,'Employee','*','READ','ALLOW','ROLE','employee'),(14,'PayMethod','*','READ','ALLOW','ROLE','trainee'),(16,'FakeProduction','*','READ','ALLOW','ROLE','employee'),(17,'Warehouse','* ','READ','ALLOW','ROLE','trainee'),(20,'TicketState','*','*','ALLOW','ROLE','employee'),(24,'Delivery','*','READ','ALLOW','ROLE','employee'),(25,'Zone','*','READ','ALLOW','ROLE','employee'),(26,'ClientCredit','*','*','ALLOW','ROLE','employee'),(27,'ClientCreditLimit','*','READ','ALLOW','ROLE','trainee'),(30,'GreugeType','*','READ','ALLOW','ROLE','trainee'),(31,'Mandate','*','READ','ALLOW','ROLE','trainee'),(32,'MandateType','*','READ','ALLOW','ROLE','trainee'),(33,'Company','*','READ','ALLOW','ROLE','trainee'),(34,'Greuge','*','READ','ALLOW','ROLE','trainee'),(35,'AddressObservation','*','*','ALLOW','ROLE','employee'),(36,'ObservationType','*','*','ALLOW','ROLE','employee'),(37,'Greuge','*','WRITE','ALLOW','ROLE','employee'),(38,'AgencyMode','*','READ','ALLOW','ROLE','employee'),(39,'ItemTag','*','WRITE','ALLOW','ROLE','buyer'),(40,'ItemBotanical','*','WRITE','ALLOW','ROLE','buyer'),(41,'ItemBotanical','*','READ','ALLOW','ROLE','employee'),(42,'ItemPlacement','*','WRITE','ALLOW','ROLE','buyer'),(43,'ItemPlacement','*','WRITE','ALLOW','ROLE','replenisher'),(44,'ItemPlacement','*','READ','ALLOW','ROLE','employee'),(45,'ItemBarcode','*','READ','ALLOW','ROLE','employee'),(46,'ItemBarcode','*','WRITE','ALLOW','ROLE','buyer'),(47,'ItemBarcode','*','WRITE','ALLOW','ROLE','replenisher'),(51,'ItemTag','*','READ','ALLOW','ROLE','employee'),(53,'Item','*','READ','ALLOW','ROLE','employee'),(54,'Item','*','WRITE','ALLOW','ROLE','buyer'),(55,'Recovery','*','READ','ALLOW','ROLE','trainee'),(56,'Recovery','*','WRITE','ALLOW','ROLE','administrative'),(58,'CreditClassification','*','*','ALLOW','ROLE','insurance'),(60,'CreditInsurance','*','*','ALLOW','ROLE','insurance'),(61,'InvoiceOut','*','READ','ALLOW','ROLE','employee'),(63,'TicketObservation','*','*','ALLOW','ROLE','employee'),(64,'Route','*','READ','ALLOW','ROLE','employee'),(65,'Sale','*','READ','ALLOW','ROLE','employee'),(66,'TicketTracking','*','READ','ALLOW','ROLE','employee'),(68,'TicketPackaging','*','*','ALLOW','ROLE','employee'),(69,'Packaging','*','READ','ALLOW','ROLE','employee'),(70,'Packaging','*','WRITE','ALLOW','ROLE','logistic'),(72,'SaleComponent','*','READ','ALLOW','ROLE','employee'),(73,'Expedition','*','READ','ALLOW','ROLE','employee'),(74,'Expedition','*','WRITE','ALLOW','ROLE','deliveryBoss'),(75,'Expedition','*','WRITE','ALLOW','ROLE','production'),(76,'AnnualAverageInvoiced','*','READ','ALLOW','ROLE','employee'),(77,'WorkerMana','*','READ','ALLOW','ROLE','employee'),(78,'TicketTracking','*','WRITE','ALLOW','ROLE','production'),(79,'TicketTracking','changeState','*','ALLOW','ROLE','employee'),(80,'Sale','deleteSales','*','ALLOW','ROLE','employee'),(81,'Sale','moveToTicket','*','ALLOW','ROLE','employee'),(82,'Sale','updateQuantity','*','ALLOW','ROLE','employee'),(83,'Sale','updatePrice','*','ALLOW','ROLE','employee'),(84,'Sale','updateDiscount','*','ALLOW','ROLE','employee'),(85,'SaleTracking','*','READ','ALLOW','ROLE','employee'),(86,'Order','*','*','ALLOW','ROLE','employee'),(87,'OrderRow','*','*','ALLOW','ROLE','employee'),(88,'ClientContact','*','*','ALLOW','ROLE','employee'),(89,'Sale','moveToNewTicket','*','ALLOW','ROLE','employee'),(90,'Sale','reserve','*','ALLOW','ROLE','employee'),(91,'TicketWeekly','*','READ','ALLOW','ROLE','employee'),(94,'Agency','landsThatDay','*','ALLOW','ROLE','employee'),(96,'ClaimEnd','*','READ','ALLOW','ROLE','employee'),(97,'ClaimEnd','*','WRITE','ALLOW','ROLE','claimManager'),(98,'ClaimBeginning','*','*','ALLOW','ROLE','employee'),(99,'ClaimDevelopment','*','READ','ALLOW','ROLE','employee'),(100,'ClaimDevelopment','*','WRITE','ALLOW','ROLE','claimManager'),(102,'Claim','createFromSales','*','ALLOW','ROLE','employee'),(104,'Item','*','WRITE','ALLOW','ROLE','marketingBoss'),(105,'ItemBarcode','*','WRITE','ALLOW','ROLE','marketingBoss'),(106,'ItemBotanical','*','WRITE','ALLOW','ROLE','marketingBoss'),(108,'ItemPlacement','*','WRITE','ALLOW','ROLE','marketingBoss'),(109,'UserConfig','*','*','ALLOW','ROLE','employee'),(110,'Bank','*','READ','ALLOW','ROLE','trainee'),(111,'ClientLog','*','READ','ALLOW','ROLE','trainee'),(112,'Defaulter','*','READ','ALLOW','ROLE','employee'),(113,'ClientRisk','*','READ','ALLOW','ROLE','trainee'),(114,'Receipt','*','READ','ALLOW','ROLE','trainee'),(115,'Receipt','*','WRITE','ALLOW','ROLE','administrative'),(116,'BankEntity','*','*','ALLOW','ROLE','employee'),(117,'ClientSample','*','*','ALLOW','ROLE','employee'),(118,'WorkerTeam','*','*','ALLOW','ROLE','salesPerson'),(119,'Travel','*','READ','ALLOW','ROLE','employee'),(120,'Travel','*','WRITE','ALLOW','ROLE','buyer'),(121,'Item','regularize','*','ALLOW','ROLE','employee'),(122,'TicketRequest','*','*','ALLOW','ROLE','employee'),(124,'Client','confirmTransaction','WRITE','ALLOW','ROLE','administrative'),(125,'Agency','getAgenciesWithWarehouse','*','ALLOW','ROLE','employee'),(126,'Client','activeWorkersWithRole','*','ALLOW','ROLE','employee'),(127,'TicketLog','*','READ','ALLOW','ROLE','employee'),(129,'TicketService','*','*','ALLOW','ROLE','employee'),(130,'Expedition','*','WRITE','ALLOW','ROLE','packager'),(131,'CreditInsurance','*','READ','ALLOW','ROLE','trainee'),(132,'CreditClassification','*','READ','ALLOW','ROLE','trainee'),(133,'ItemTag','*','WRITE','ALLOW','ROLE','marketingBoss'),(135,'ZoneGeo','*','READ','ALLOW','ROLE','employee'),(136,'ZoneCalendar','*','READ','ALLOW','ROLE','employee'),(137,'ZoneIncluded','*','READ','ALLOW','ROLE','employee'),(138,'LabourHoliday','*','READ','ALLOW','ROLE','employee'),(139,'LabourHolidayLegend','*','READ','ALLOW','ROLE','employee'),(140,'LabourHolidayType','*','READ','ALLOW','ROLE','employee'),(141,'Zone','*','*','ALLOW','ROLE','logisticBoss'),(142,'ZoneCalendar','*','WRITE','ALLOW','ROLE','deliveryBoss'),(143,'ZoneIncluded','*','*','ALLOW','ROLE','deliveryBoss'),(144,'Stowaway','*','*','ALLOW','ROLE','employee'),(145,'Ticket','getPossibleStowaways','READ','ALLOW','ROLE','employee'),(147,'UserConfigView','*','*','ALLOW','ROLE','employee'),(148,'UserConfigView','*','*','ALLOW','ROLE','employee'),(149,'Sip','*','READ','ALLOW','ROLE','employee'),(150,'Sip','*','WRITE','ALLOW','ROLE','hr'),(151,'Department','*','READ','ALLOW','ROLE','employee'),(152,'Department','*','WRITE','ALLOW','ROLE','hr'),(153,'Route','*','READ','ALLOW','ROLE','employee'),(154,'Route','*','WRITE','ALLOW','ROLE','delivery'),(155,'Calendar','*','READ','ALLOW','ROLE','hr'),(156,'WorkerLabour','*','READ','ALLOW','ROLE','hr'),(157,'Calendar','absences','READ','ALLOW','ROLE','employee'),(158,'ItemTag','*','WRITE','ALLOW','ROLE','accessory'),(160,'TicketServiceType','*','READ','ALLOW','ROLE','employee'),(161,'TicketConfig','*','READ','ALLOW','ROLE','employee'),(162,'InvoiceOut','delete','WRITE','ALLOW','ROLE','invoicing'),(163,'InvoiceOut','book','WRITE','ALLOW','ROLE','invoicing'),(165,'TicketDms','*','*','ALLOW','ROLE','employee'),(167,'Worker','isSubordinate','READ','ALLOW','ROLE','employee'),(168,'Worker','mySubordinates','READ','ALLOW','ROLE','employee'),(169,'WorkerTimeControl','filter','READ','ALLOW','ROLE','employee'),(170,'WorkerTimeControl','addTime','WRITE','ALLOW','ROLE','employee'),(171,'TicketServiceType','*','WRITE','ALLOW','ROLE','administrative'),(172,'Sms','*','READ','ALLOW','ROLE','employee'),(173,'Sms','send','WRITE','ALLOW','ROLE','employee'),(176,'Device','*','*','ALLOW','ROLE','employee'),(177,'Device','*','*','ALLOW','ROLE','employee'),(178,'WorkerTimeControl','*','*','ALLOW','ROLE','employee'),(179,'ItemLog','*','READ','ALLOW','ROLE','employee'),(180,'RouteLog','*','READ','ALLOW','ROLE','employee'),(181,'Dms','removeFile','WRITE','ALLOW','ROLE','employee'),(182,'Dms','uploadFile','WRITE','ALLOW','ROLE','employee'),(183,'Dms','downloadFile','READ','ALLOW','ROLE','employee'),(184,'Client','uploadFile','WRITE','ALLOW','ROLE','employee'),(185,'ClientDms','removeFile','WRITE','ALLOW','ROLE','employee'),(186,'ClientDms','*','READ','ALLOW','ROLE','trainee'),(187,'Ticket','uploadFile','WRITE','ALLOW','ROLE','employee'),(190,'Route','updateVolume','WRITE','ALLOW','ROLE','deliveryBoss'),(191,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(192,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(194,'Postcode','*','WRITE','ALLOW','ROLE','deliveryBoss'),(195,'Ticket','addSale','WRITE','ALLOW','ROLE','employee'),(196,'Dms','updateFile','WRITE','ALLOW','ROLE','employee'),(197,'Dms','*','READ','ALLOW','ROLE','trainee'),(198,'ClaimDms','removeFile','WRITE','ALLOW','ROLE','employee'),(199,'ClaimDms','*','READ','ALLOW','ROLE','employee'),(200,'Claim','uploadFile','WRITE','ALLOW','ROLE','employee'),(201,'Sale','updateConcept','WRITE','ALLOW','ROLE','employee'),(202,'Claim','updateClaimAction','WRITE','ALLOW','ROLE','claimManager'),(203,'UserPhone','*','*','ALLOW','ROLE','employee'),(204,'WorkerDms','removeFile','WRITE','ALLOW','ROLE','hr'),(205,'WorkerDms','*','READ','ALLOW','ROLE','hr'),(206,'Chat','*','*','ALLOW','ROLE','employee'),(207,'Chat','sendMessage','*','ALLOW','ROLE','employee'),(208,'Sale','recalculatePrice','WRITE','ALLOW','ROLE','employee'),(209,'Ticket','recalculateComponents','WRITE','ALLOW','ROLE','employee'),(211,'TravelLog','*','READ','ALLOW','ROLE','buyer'),(212,'Thermograph','*','*','ALLOW','ROLE','buyer'),(213,'TravelThermograph','*','WRITE','ALLOW','ROLE','buyer'),(214,'Entry','*','*','ALLOW','ROLE','buyer'),(215,'TicketWeekly','*','WRITE','ALLOW','ROLE','buyer'),(216,'TravelThermograph','*','READ','ALLOW','ROLE','employee'),(218,'Intrastat','*','*','ALLOW','ROLE','buyer'),(221,'UserConfig','getUserConfig','READ','ALLOW','ROLE','account'),(222,'Client','*','READ','ALLOW','ROLE','trainee'),(226,'ClientObservation','*','READ','ALLOW','ROLE','trainee'),(227,'Address','*','READ','ALLOW','ROLE','trainee'),(228,'AddressObservation','*','READ','ALLOW','ROLE','trainee'),(230,'ClientCredit','*','READ','ALLOW','ROLE','trainee'),(231,'ClientContact','*','READ','ALLOW','ROLE','trainee'),(232,'ClientSample','*','READ','ALLOW','ROLE','trainee'),(233,'EntryLog','*','READ','ALLOW','ROLE','buyer'),(234,'WorkerLog','find','READ','ALLOW','ROLE','hr'),(235,'CustomsAgent','*','*','ALLOW','ROLE','employee'),(236,'Buy','*','*','ALLOW','ROLE','buyer'),(237,'WorkerDms','filter','*','ALLOW','ROLE','employee'),(238,'Town','*','WRITE','ALLOW','ROLE','deliveryBoss'),(239,'Province','*','WRITE','ALLOW','ROLE','deliveryBoss'),(240,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(241,'SupplierContact','*','WRITE','ALLOW','ROLE','administrative'),(242,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(244,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(248,'RoleMapping','*','READ','ALLOW','ROLE','account'),(249,'UserPassword','*','READ','ALLOW','ROLE','account'),(250,'Town','*','WRITE','ALLOW','ROLE','deliveryBoss'),(251,'Province','*','WRITE','ALLOW','ROLE','deliveryBoss'),(252,'Supplier','*','READ','ALLOW','ROLE','employee'),(253,'Supplier','*','WRITE','ALLOW','ROLE','administrative'),(254,'SupplierLog','*','READ','ALLOW','ROLE','employee'),(256,'Image','*','WRITE','ALLOW','ROLE','employee'),(257,'FixedPrice','*','*','ALLOW','ROLE','buyer'),(258,'PayDem','*','READ','ALLOW','ROLE','employee'),(259,'Client','createReceipt','*','ALLOW','ROLE','salesAssistant'),(260,'PrintServerQueue','*','WRITE','ALLOW','ROLE','employee'),(261,'SupplierAccount','*','*','ALLOW','ROLE','administrative'),(262,'Entry','*','*','ALLOW','ROLE','administrative'),(263,'InvoiceIn','*','*','ALLOW','ROLE','administrative'),(264,'StarredModule','*','*','ALLOW','ROLE','employee'),(265,'ItemBotanical','*','WRITE','ALLOW','ROLE','logisticBoss'),(266,'ZoneLog','*','READ','ALLOW','ROLE','employee'),(267,'Genus','*','WRITE','ALLOW','ROLE','logisticBoss'),(268,'Specie','*','WRITE','ALLOW','ROLE','logisticBoss'),(269,'InvoiceOut','createPdf','WRITE','ALLOW','ROLE','employee'),(270,'SupplierAddress','*','*','ALLOW','ROLE','employee'),(271,'SalesMonitor','*','*','ALLOW','ROLE','employee'),(272,'InvoiceInLog','*','READ','ALLOW','ROLE','employee'),(273,'InvoiceInTax','*','*','ALLOW','ROLE','administrative'),(274,'InvoiceInLog','*','READ','ALLOW','ROLE','administrative'),(275,'InvoiceOut','createManualInvoice','WRITE','ALLOW','ROLE','invoicing'),(276,'InvoiceOut','globalInvoicing','WRITE','ALLOW','ROLE','invoicing'),(278,'RoleInherit','*','WRITE','ALLOW','ROLE','grant'),(279,'MailAlias','*','*','ALLOW','ROLE','marketing'),(283,'EntryObservation','*','*','ALLOW','ROLE','buyer'),(284,'LdapConfig','*','*','ALLOW','ROLE','sysadmin'),(285,'SambaConfig','*','*','ALLOW','ROLE','sysadmin'),(286,'ACL','*','*','ALLOW','ROLE','developer'),(287,'AccessToken','*','*','ALLOW','ROLE','developer'),(293,'RoleInherit','*','*','ALLOW','ROLE','it'),(294,'RoleRole','*','*','ALLOW','ROLE','it'),(295,'AccountConfig','*','*','ALLOW','ROLE','sysadmin'),(296,'Collection','*','READ','ALLOW','ROLE','employee'),(297,'Sale','refund','WRITE','ALLOW','ROLE','invoicing'),(298,'InvoiceInDueDay','*','*','ALLOW','ROLE','administrative'),(299,'Collection','setSaleQuantity','*','ALLOW','ROLE','employee'),(302,'AgencyTerm','*','*','ALLOW','ROLE','administrative'),(303,'ClaimLog','*','READ','ALLOW','ROLE','claimManager'),(304,'Edi','updateData','WRITE','ALLOW','ROLE','employee'),(305,'EducationLevel','*','*','ALLOW','ROLE','employee'),(306,'InvoiceInIntrastat','*','*','ALLOW','ROLE','employee'),(307,'SupplierAgencyTerm','*','*','ALLOW','ROLE','administrative'),(308,'InvoiceInIntrastat','*','*','ALLOW','ROLE','employee'),(309,'Zone','getZoneClosing','*','ALLOW','ROLE','employee'),(310,'ExpeditionState','*','READ','ALLOW','ROLE','employee'),(311,'Expense','*','READ','ALLOW','ROLE','employee'),(312,'Expense','*','WRITE','ALLOW','ROLE','administrative'),(314,'SupplierActivity','*','READ','ALLOW','ROLE','employee'),(315,'SupplierActivity','*','WRITE','ALLOW','ROLE','administrative'),(316,'Dms','deleteTrashFiles','WRITE','ALLOW','ROLE','employee'),(317,'ClientUnpaid','*','*','ALLOW','ROLE','administrative'),(318,'MdbVersion','*','*','ALLOW','ROLE','developer'),(319,'ItemType','*','READ','ALLOW','ROLE','employee'),(320,'ItemType','*','WRITE','ALLOW','ROLE','buyer'),(321,'InvoiceOut','refund','WRITE','ALLOW','ROLE','invoicing'),(322,'InvoiceOut','refund','WRITE','ALLOW','ROLE','salesAssistant'),(323,'InvoiceOut','refund','WRITE','ALLOW','ROLE','claimManager'),(324,'Ticket','refund','WRITE','ALLOW','ROLE','invoicing'),(325,'Ticket','refund','WRITE','ALLOW','ROLE','salesAssistant'),(326,'Ticket','refund','WRITE','ALLOW','ROLE','claimManager'),(327,'Sale','refund','WRITE','ALLOW','ROLE','salesAssistant'),(328,'Sale','refund','WRITE','ALLOW','ROLE','claimManager'),(329,'TicketRefund','*','WRITE','ALLOW','ROLE','invoicing'),(330,'ClaimObservation','*','WRITE','ALLOW','ROLE','salesPerson'),(331,'ClaimObservation','*','READ','ALLOW','ROLE','salesPerson'),(332,'Client','setPassword','WRITE','ALLOW','ROLE','salesPerson'),(333,'Client','updateUser','WRITE','ALLOW','ROLE','salesPerson'),(334,'ShelvingLog','*','READ','ALLOW','ROLE','employee'),(335,'ZoneExclusionGeo','*','READ','ALLOW','ROLE','employee'),(336,'ZoneExclusionGeo','*','WRITE','ALLOW','ROLE','deliveryBoss'),(337,'Parking','*','*','ALLOW','ROLE','employee'),(338,'Shelving','*','*','ALLOW','ROLE','employee'),(339,'OsTicket','*','*','ALLOW','ROLE','employee'),(340,'OsTicketConfig','*','*','ALLOW','ROLE','it'),(341,'ClientConsumptionQueue','*','WRITE','ALLOW','ROLE','employee'),(342,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','employee'),(343,'Ticket','deliveryNoteEmail','WRITE','ALLOW','ROLE','employee'),(344,'Ticket','deliveryNoteCsvPdf','READ','ALLOW','ROLE','employee'),(345,'Ticket','deliveryNoteCsvEmail','READ','ALLOW','ROLE','employee'),(346,'Client','campaignMetricsPdf','READ','ALLOW','ROLE','employee'),(347,'Client','campaignMetricsEmail','WRITE','ALLOW','ROLE','employee'),(348,'Client','clientWelcomeHtml','READ','ALLOW','ROLE','employee'),(349,'Client','clientWelcomeEmail','WRITE','ALLOW','ROLE','employee'),(350,'Client','creditRequestPdf','READ','ALLOW','ROLE','employee'),(351,'Client','creditRequestHtml','READ','ALLOW','ROLE','employee'),(352,'Client','creditRequestEmail','WRITE','ALLOW','ROLE','employee'),(353,'Client','printerSetupHtml','READ','ALLOW','ROLE','employee'),(354,'Client','printerSetupEmail','WRITE','ALLOW','ROLE','employee'),(355,'Client','sepaCoreEmail','WRITE','ALLOW','ROLE','employee'),(356,'Client','letterDebtorPdf','READ','ALLOW','ROLE','employee'),(357,'Client','letterDebtorStHtml','READ','ALLOW','ROLE','employee'),(358,'Client','letterDebtorStEmail','WRITE','ALLOW','ROLE','employee'),(359,'Client','letterDebtorNdHtml','READ','ALLOW','ROLE','employee'),(360,'Client','letterDebtorNdEmail','WRITE','ALLOW','ROLE','employee'),(361,'Client','clientDebtStatementPdf','READ','ALLOW','ROLE','employee'),(362,'Client','clientDebtStatementHtml','READ','ALLOW','ROLE','employee'),(363,'Client','clientDebtStatementEmail','WRITE','ALLOW','ROLE','employee'),(364,'Client','incotermsAuthorizationPdf','READ','ALLOW','ROLE','employee'),(365,'Client','incotermsAuthorizationHtml','READ','ALLOW','ROLE','employee'),(366,'Client','incotermsAuthorizationEmail','WRITE','ALLOW','ROLE','employee'),(367,'Client','consumptionSendQueued','WRITE','ALLOW','ROLE','system'),(368,'InvoiceOut','invoiceEmail','WRITE','ALLOW','ROLE','employee'),(369,'InvoiceOut','exportationPdf','READ','ALLOW','ROLE','employee'),(370,'InvoiceOut','sendQueued','WRITE','ALLOW','ROLE','system'),(371,'Ticket','invoiceCsvPdf','READ','ALLOW','ROLE','employee'),(372,'Ticket','invoiceCsvEmail','WRITE','ALLOW','ROLE','employee'),(373,'Supplier','campaignMetricsPdf','READ','ALLOW','ROLE','employee'),(374,'Supplier','campaignMetricsEmail','WRITE','ALLOW','ROLE','employee'),(375,'Travel','extraCommunityPdf','READ','ALLOW','ROLE','employee'),(376,'Travel','extraCommunityEmail','WRITE','ALLOW','ROLE','employee'),(377,'Entry','entryOrderPdf','READ','ALLOW','ROLE','employee'),(378,'OsTicket','osTicketReportEmail','WRITE','ALLOW','ROLE','system'),(379,'Item','buyerWasteEmail','WRITE','ALLOW','ROLE','system'),(380,'Claim','claimPickupPdf','READ','ALLOW','ROLE','employee'),(381,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','claimManager'),(382,'Item','labelPdf','READ','ALLOW','ROLE','employee'),(383,'Sector','*','READ','ALLOW','ROLE','employee'),(384,'Sector','*','WRITE','ALLOW','ROLE','employee'),(385,'Route','driverRoutePdf','READ','ALLOW','ROLE','employee'),(386,'Route','driverRouteEmail','WRITE','ALLOW','ROLE','employee'),(387,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','customer'),(388,'Supplier','newSupplier','WRITE','ALLOW','ROLE','administrative'),(389,'ClaimRma','*','READ','ALLOW','ROLE','claimManager'),(390,'ClaimRma','*','WRITE','ALLOW','ROLE','claimManager'),(391,'Notification','*','WRITE','ALLOW','ROLE','system'),(392,'Boxing','*','*','ALLOW','ROLE','employee'),(393,'Url','*','READ','ALLOW','ROLE','employee'),(394,'Url','*','WRITE','ALLOW','ROLE','it'),(395,'ItemShelving','*','READ','ALLOW','ROLE','employee'),(396,'ItemShelving','*','WRITE','ALLOW','ROLE','production'),(397,'ItemShelvingPlacementSupplyStock','*','READ','ALLOW','ROLE','employee'),(398,'NotificationQueue','*','*','ALLOW','ROLE','employee'),(399,'InvoiceOut','clientsToInvoice','WRITE','ALLOW','ROLE','invoicing'),(400,'InvoiceOut','invoiceClient','WRITE','ALLOW','ROLE','invoicing'),(401,'Sale','editTracked','WRITE','ALLOW','ROLE','production'),(402,'Sale','editFloramondo','WRITE','ALLOW','ROLE','salesAssistant'),(403,'Receipt','balanceCompensationEmail','WRITE','ALLOW','ROLE','employee'),(404,'Receipt','balanceCompensationPdf','READ','ALLOW','ROLE','employee'),(405,'Ticket','getTicketsFuture','READ','ALLOW','ROLE','employee'),(406,'Ticket','merge','WRITE','ALLOW','ROLE','employee'),(407,'Sale','editFloramondo','WRITE','ALLOW','ROLE','logistic'),(408,'ZipConfig','*','*','ALLOW','ROLE','employee'),(409,'Item','*','WRITE','ALLOW','ROLE','administrative'),(410,'Sale','editCloned','WRITE','ALLOW','ROLE','buyer'),(411,'Sale','editCloned','WRITE','ALLOW','ROLE','salesAssistant'),(414,'MdbVersion','*','READ','ALLOW','ROLE','$everyone'),(416,'TicketLog','getChanges','READ','ALLOW','ROLE','employee'),(417,'Ticket','getTicketsAdvance','READ','ALLOW','ROLE','employee'),(418,'EntryLog','*','READ','ALLOW','ROLE','administrative'),(419,'Sale','editTracked','WRITE','ALLOW','ROLE','buyer'),(420,'MdbBranch','*','READ','ALLOW','ROLE','$everyone'),(421,'ItemShelvingSale','*','*','ALLOW','ROLE','employee'),(422,'Docuware','checkFile','READ','ALLOW','ROLE','employee'),(423,'Docuware','download','READ','ALLOW','ROLE','salesPerson'),(424,'Docuware','upload','WRITE','ALLOW','ROLE','productionAssi'),(425,'Docuware','deliveryNoteEmail','WRITE','ALLOW','ROLE','salesPerson'),(426,'TpvTransaction','confirm','WRITE','ALLOW','ROLE','$everyone'),(427,'TpvTransaction','start','WRITE','ALLOW','ROLE','$authenticated'),(428,'TpvTransaction','end','WRITE','ALLOW','ROLE','$authenticated'),(429,'ItemConfig','*','READ','ALLOW','ROLE','employee'),(431,'Tag','onSubmit','WRITE','ALLOW','ROLE','employee'),(432,'Worker','updateAttributes','WRITE','ALLOW','ROLE','hr'),(433,'Worker','createAbsence','*','ALLOW','ROLE','employee'),(434,'Worker','updateAbsence','WRITE','ALLOW','ROLE','employee'),(435,'Worker','deleteAbsence','*','ALLOW','ROLE','employee'),(436,'Worker','new','WRITE','ALLOW','ROLE','hr'),(438,'Client','getClientOrSupplierReference','READ','ALLOW','ROLE','employee'),(439,'NotificationSubscription','*','*','ALLOW','ROLE','employee'),(440,'NotificationAcl','*','READ','ALLOW','ROLE','employee'),(441,'MdbApp','*','READ','ALLOW','ROLE','$everyone'),(442,'MdbApp','*','*','ALLOW','ROLE','developer'),(443,'ItemConfig','*','*','ALLOW','ROLE','employee'),(444,'DeviceProduction','*','*','ALLOW','ROLE','hr'),(445,'DeviceProductionModels','*','*','ALLOW','ROLE','hr'),(446,'DeviceProductionState','*','*','ALLOW','ROLE','hr'),(447,'DeviceProductionUser','*','*','ALLOW','ROLE','hr'),(448,'DeviceProduction','*','*','ALLOW','ROLE','productionAssi'),(449,'DeviceProductionModels','*','*','ALLOW','ROLE','productionAssi'),(450,'DeviceProductionState','*','*','ALLOW','ROLE','productionAssi'),(451,'DeviceProductionUser','*','*','ALLOW','ROLE','productionAssi'),(452,'Worker','deallocatePDA','*','ALLOW','ROLE','hr'),(453,'Worker','allocatePDA','*','ALLOW','ROLE','hr'),(454,'Worker','deallocatePDA','*','ALLOW','ROLE','productionAssi'),(455,'Worker','allocatePDA','*','ALLOW','ROLE','productionAssi'),(456,'Zone','*','*','ALLOW','ROLE','deliveryBoss'),(457,'Account','setPassword','WRITE','ALLOW','ROLE','itManagement'),(458,'Operator','*','READ','ALLOW','ROLE','employee'),(459,'Operator','*','WRITE','ALLOW','ROLE','employee'),(460,'InvoiceIn','getSerial','READ','ALLOW','ROLE','administrative'),(461,'Ticket','saveSign','WRITE','ALLOW','ROLE','employee'),(462,'InvoiceOut','negativeBases','READ','ALLOW','ROLE','administrative'),(463,'InvoiceOut','negativeBasesCsv','READ','ALLOW','ROLE','administrative'),(464,'WorkerObservation','*','*','ALLOW','ROLE','hr'),(465,'ClientInforma','*','READ','ALLOW','ROLE','employee'),(466,'ClientInforma','*','WRITE','ALLOW','ROLE','financial'),(467,'Receipt','receiptEmail','*','ALLOW','ROLE','salesAssistant'),(468,'Client','setRating','WRITE','ALLOW','ROLE','financial'),(469,'Client','*','READ','ALLOW','ROLE','employee'),(470,'Client','addressesPropagateRe','*','ALLOW','ROLE','employee'),(471,'Client','canBeInvoiced','*','ALLOW','ROLE','employee'),(472,'Client','canCreateTicket','*','ALLOW','ROLE','employee'),(473,'Client','consumption','*','ALLOW','ROLE','employee'),(474,'Client','createAddress','*','ALLOW','ROLE','employee'),(475,'Client','createWithUser','*','ALLOW','ROLE','employee'),(476,'Client','extendedListFilter','*','ALLOW','ROLE','employee'),(477,'Client','getAverageInvoiced','*','ALLOW','ROLE','employee'),(478,'Client','getCard','*','ALLOW','ROLE','employee'),(479,'Client','getDebt','*','ALLOW','ROLE','employee'),(480,'Client','getMana','*','ALLOW','ROLE','employee'),(481,'Client','transactions','*','ALLOW','ROLE','employee'),(482,'Client','hasCustomerRole','*','ALLOW','ROLE','employee'),(483,'Client','isValidClient','*','ALLOW','ROLE','employee'),(484,'Client','lastActiveTickets','*','ALLOW','ROLE','employee'),(485,'Client','sendSms','*','ALLOW','ROLE','employee'),(486,'Client','setPassword','*','ALLOW','ROLE','employee'),(487,'Client','summary','*','ALLOW','ROLE','employee'),(488,'Client','updateAddress','*','ALLOW','ROLE','employee'),(489,'Client','updateFiscalData','*','ALLOW','ROLE','employee'),(491,'Client','uploadFile','*','ALLOW','ROLE','employee'),(492,'Client','campaignMetricsPdf','*','ALLOW','ROLE','employee'),(493,'Client','campaignMetricsEmail','*','ALLOW','ROLE','employee'),(494,'Client','clientWelcomeHtml','*','ALLOW','ROLE','employee'),(495,'Client','clientWelcomeEmail','*','ALLOW','ROLE','employee'),(496,'Client','printerSetupHtml','*','ALLOW','ROLE','employee'),(497,'Client','printerSetupEmail','*','ALLOW','ROLE','employee'),(498,'Client','sepaCoreEmail','*','ALLOW','ROLE','employee'),(499,'Client','letterDebtorPdf','*','ALLOW','ROLE','employee'),(500,'Client','letterDebtorStHtml','*','ALLOW','ROLE','employee'),(501,'Client','letterDebtorStEmail','*','ALLOW','ROLE','employee'),(502,'Client','letterDebtorNdHtml','*','ALLOW','ROLE','employee'),(503,'Client','letterDebtorNdEmail','*','ALLOW','ROLE','employee'),(504,'Client','clientDebtStatementPdf','*','ALLOW','ROLE','employee'),(505,'Client','clientDebtStatementHtml','*','ALLOW','ROLE','employee'),(506,'Client','clientDebtStatementEmail','*','ALLOW','ROLE','employee'),(507,'Client','creditRequestPdf','*','ALLOW','ROLE','employee'),(508,'Client','creditRequestHtml','*','ALLOW','ROLE','employee'),(509,'Client','creditRequestEmail','*','ALLOW','ROLE','employee'),(510,'Client','incotermsAuthorizationPdf','*','ALLOW','ROLE','employee'),(511,'Client','incotermsAuthorizationHtml','*','ALLOW','ROLE','employee'),(512,'Client','incotermsAuthorizationEmail','*','ALLOW','ROLE','employee'),(513,'Client','consumptionSendQueued','*','ALLOW','ROLE','employee'),(514,'Client','filter','*','ALLOW','ROLE','employee'),(515,'Client','getClientOrSupplierReference','*','ALLOW','ROLE','employee'),(516,'Client','upsert','*','ALLOW','ROLE','employee'),(517,'Client','create','*','ALLOW','ROLE','employee'),(518,'Client','replaceById','*','ALLOW','ROLE','employee'),(519,'Client','updateAttributes','*','ALLOW','ROLE','employee'),(520,'Client','updateAttributes','*','ALLOW','ROLE','employee'),(521,'Client','deleteById','*','ALLOW','ROLE','employee'),(522,'Client','replaceOrCreate','*','ALLOW','ROLE','employee'),(523,'Client','updateAll','*','ALLOW','ROLE','employee'),(524,'Client','upsertWithWhere','*','ALLOW','ROLE','employee'),(525,'Defaulter','observationEmail','WRITE','ALLOW','ROLE','employee'),(527,'VnUser','acl','READ','ALLOW','ROLE','account'),(528,'VnUser','getCurrentUserData','READ','ALLOW','ROLE','account'),(530,'Account','exists','READ','ALLOW','ROLE','account'),(531,'Account','exists','READ','ALLOW','ROLE','account'),(532,'UserLog','*','READ','ALLOW','ROLE','employee'),(533,'RoleLog','*','READ','ALLOW','ROLE','employee'),(534,'WagonType','*','*','ALLOW','ROLE','productionAssi'),(535,'WagonTypeColor','*','*','ALLOW','ROLE','productionAssi'),(536,'WagonTypeTray','*','*','ALLOW','ROLE','productionAssi'),(537,'WagonConfig','*','*','ALLOW','ROLE','productionAssi'),(538,'CollectionWagon','*','*','ALLOW','ROLE','productionAssi'),(539,'CollectionWagonTicket','*','*','ALLOW','ROLE','productionAssi'),(540,'Wagon','*','*','ALLOW','ROLE','productionAssi'),(541,'WagonType','createWagonType','*','ALLOW','ROLE','productionAssi'),(542,'WagonType','deleteWagonType','*','ALLOW','ROLE','productionAssi'),(543,'WagonType','editWagonType','*','ALLOW','ROLE','productionAssi'),(544,'Docuware','deliveryNoteEmail','WRITE','ALLOW','ROLE','employee'),(545,'Agency','find','READ','ALLOW','ROLE','employee'),(546,'Agency','seeExpired','READ','ALLOW','ROLE','coolerAssist'),(547,'WorkerLog','models','READ','ALLOW','ROLE','hr'),(548,'Ticket','editDiscount','WRITE','ALLOW','ROLE','claimManager'),(549,'Ticket','editDiscount','WRITE','ALLOW','ROLE','salesPerson'),(550,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','salesAssistant'),(551,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','deliveryBoss'),(552,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','buyer'),(553,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','claimManager'),(554,'Ticket','deleteTicketWithPartPrepared','WRITE','ALLOW','ROLE','salesAssistant'),(555,'Ticket','editZone','WRITE','ALLOW','ROLE','deliveryBoss'),(556,'State','editableStates','READ','ALLOW','ROLE','employee'),(557,'State','seeEditableStates','READ','ALLOW','ROLE','administrative'),(558,'State','seeEditableStates','READ','ALLOW','ROLE','production'),(559,'State','isSomeEditable','READ','ALLOW','ROLE','salesPerson'),(560,'State','isAllEditable','READ','ALLOW','ROLE','production'),(561,'State','isAllEditable','READ','ALLOW','ROLE','administrative'),(562,'Agency','seeExpired','READ','ALLOW','ROLE','administrative'),(563,'Agency','seeExpired','READ','ALLOW','ROLE','productionBoss'),(564,'Claim','createAfterDeadline','WRITE','ALLOW','ROLE','claimManager'),(565,'Client','editAddressLogifloraAllowed','WRITE','ALLOW','ROLE','salesAssistant'),(566,'Client','editFiscalDataWithoutTaxDataCheck','WRITE','ALLOW','ROLE','salesAssistant'),(567,'Client','editVerifiedDataWithoutTaxDataCheck','WRITE','ALLOW','ROLE','salesAssistant'),(568,'Client','editCredit','WRITE','ALLOW','ROLE','financialBoss'),(569,'Client','zeroCreditEditor','WRITE','ALLOW','ROLE','financialBoss'),(570,'InvoiceOut','canCreatePdf','WRITE','ALLOW','ROLE','invoicing'),(571,'Supplier','editPayMethodCheck','WRITE','ALLOW','ROLE','financial'),(572,'Worker','isTeamBoss','WRITE','ALLOW','ROLE','teamBoss'),(573,'Worker','forceIsSubordinate','READ','ALLOW','ROLE','hr'),(574,'Claim','editState','WRITE','ALLOW','ROLE','claimManager'),(575,'Claim','find','READ','ALLOW','ROLE','salesPerson'),(576,'Claim','findById','READ','ALLOW','ROLE','salesPerson'),(577,'Claim','findOne','READ','ALLOW','ROLE','salesPerson'),(578,'Claim','getSummary','READ','ALLOW','ROLE','salesPerson'),(579,'Claim','updateClaim','WRITE','ALLOW','ROLE','salesPerson'),(580,'Claim','regularizeClaim','WRITE','ALLOW','ROLE','claimManager'),(581,'Claim','updateClaimDestination','WRITE','ALLOW','ROLE','claimManager'),(582,'Claim','downloadFile','READ','ALLOW','ROLE','claimManager'),(583,'Claim','deleteById','WRITE','ALLOW','ROLE','claimManager'),(584,'Claim','filter','READ','ALLOW','ROLE','salesPerson'),(585,'Claim','logs','READ','ALLOW','ROLE','claimManager'),(586,'Ticket','find','READ','ALLOW','ROLE','employee'),(587,'Ticket','findById','READ','ALLOW','ROLE','employee'),(588,'Ticket','findOne','READ','ALLOW','ROLE','employee'),(589,'Ticket','getVolume','READ','ALLOW','ROLE','employee'),(590,'Ticket','getTotalVolume','READ','ALLOW','ROLE','employee'),(591,'Ticket','summary','READ','ALLOW','ROLE','employee'),(592,'Ticket','priceDifference','READ','ALLOW','ROLE','employee'),(593,'Ticket','componentUpdate','WRITE','ALLOW','ROLE','employee'),(594,'Ticket','new','WRITE','ALLOW','ROLE','employee'),(595,'Ticket','isEditable','READ','ALLOW','ROLE','employee'),(596,'Ticket','setDeleted','WRITE','ALLOW','ROLE','salesPerson'),(597,'Ticket','restore','WRITE','ALLOW','ROLE','employee'),(598,'Ticket','getSales','READ','ALLOW','ROLE','employee'),(599,'Ticket','getSalesPersonMana','READ','ALLOW','ROLE','employee'),(600,'Ticket','filter','READ','ALLOW','ROLE','employee'),(601,'Ticket','makeInvoice','WRITE','ALLOW','ROLE','employee'),(602,'Ticket','updateEditableTicket','WRITE','ALLOW','ROLE','employee'),(603,'Ticket','updateDiscount','WRITE','ALLOW','ROLE','employee'),(604,'Ticket','transferSales','WRITE','ALLOW','ROLE','employee'),(605,'Ticket','sendSms','WRITE','ALLOW','ROLE','employee'),(606,'Ticket','isLocked','READ','ALLOW','ROLE','employee'),(607,'Ticket','freightCost','READ','ALLOW','ROLE','employee'),(608,'Ticket','getComponentsSum','READ','ALLOW','ROLE','employee'),(609,'Ticket','updateAttributes','WRITE','ALLOW','ROLE','delivery'),(610,'Ticket','deliveryNoteCsv','READ','ALLOW','ROLE','employee'),(611,'State','find','READ','ALLOW','ROLE','employee'),(612,'State','findById','READ','ALLOW','ROLE','employee'),(613,'State','findOne','READ','ALLOW','ROLE','employee'),(614,'Worker','find','READ','ALLOW','ROLE','employee'),(615,'Worker','findById','READ','ALLOW','ROLE','employee'),(616,'Worker','findOne','READ','ALLOW','ROLE','employee'),(617,'Worker','filter','READ','ALLOW','ROLE','employee'),(618,'Worker','getWorkedHours','READ','ALLOW','ROLE','employee'),(619,'Worker','active','READ','ALLOW','ROLE','employee'),(620,'Worker','activeWithRole','READ','ALLOW','ROLE','employee'),(621,'Worker','uploadFile','WRITE','ALLOW','ROLE','hr'),(622,'Worker','contracts','READ','ALLOW','ROLE','employee'),(623,'Worker','holidays','READ','ALLOW','ROLE','employee'),(624,'Worker','activeContract','READ','ALLOW','ROLE','employee'),(625,'Worker','activeWithInheritedRole','READ','ALLOW','ROLE','employee'),(626,'Ticket','collectionLabel','READ','ALLOW','ROLE','employee'),(628,'Ticket','expeditionPalletLabel','READ','ALLOW','ROLE','employee'),(629,'Ticket','editDiscount','WRITE','ALLOW','ROLE','artificialBoss'),(630,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','salesTeamBoss'),(635,'Ticket','updateAttributes','WRITE','ALLOW','ROLE','administrative'),(636,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','salesPerson'),(637,'Claim','downloadFile','READ','ALLOW','ROLE','salesPerson'),(638,'Agency','seeExpired','READ','ALLOW','ROLE','artificialBoss'),(639,'Agency','seeExpired','READ','ALLOW','ROLE','logisticAssistant'),(640,'Claim','filter','READ','ALLOW','ROLE','buyer'),(641,'Claim','find','READ','ALLOW','ROLE','buyer'),(642,'Claim','findById','READ','ALLOW','ROLE','buyer'),(643,'Claim','getSummary','READ','ALLOW','ROLE','buyer'),(644,'Claim','filter','READ','ALLOW','ROLE','handmadeBoss'),(645,'Claim','find','READ','ALLOW','ROLE','handmadeBoss'),(646,'Claim','findById','READ','ALLOW','ROLE','handmadeBoss'),(647,'Claim','getSummary','READ','ALLOW','ROLE','handmadeBoss'),(648,'Claim','__get__lines','READ','ALLOW','ROLE','claimManager'),(649,'Claim','__get__lines','READ','ALLOW','ROLE','salesPerson'),(650,'Claim','getSummary','READ','ALLOW','ROLE','deliveryBoss'),(651,'Claim','findById','READ','ALLOW','ROLE','deliveryBoss'),(652,'Claim','find','READ','ALLOW','ROLE','deliveryBoss'),(653,'Claim','filter','READ','ALLOW','ROLE','deliveryBoss'),(654,'Ticket','editZone','WRITE','ALLOW','ROLE','logisticAssistant'),(655,'Entry','addFromPackaging','WRITE','ALLOW','ROLE','production'),(656,'Entry','addFromBuy','WRITE','ALLOW','ROLE','production'),(657,'Supplier','getItemsPackaging','READ','ALLOW','ROLE','production'),(658,'Ticket','closeAll','WRITE','ALLOW','ROLE','system'),(659,'Account','*','*','ALLOW','ROLE','itManagement'),(660,'Account','*','READ','ALLOW','ROLE','employee'),(664,'MailForward','*','*','ALLOW','ROLE','itManagement'),(665,'Role','*','READ','ALLOW','ROLE','employee'),(666,'Role','*','WRITE','ALLOW','ROLE','it'),(667,'VnUser','*','*','ALLOW','ROLE','itManagement'),(668,'VnUser','__get__preview','READ','ALLOW','ROLE','employee'),(669,'VnUser','preview','*','ALLOW','ROLE','employee'),(670,'VnUser','create','*','ALLOW','ROLE','itManagement'),(671,'VnUser','renewToken','WRITE','ALLOW','ROLE','employee'),(672,'PackingSiteAdvanced','*','*','ALLOW','ROLE','production'),(673,'InvoiceOut','makePdfAndNotify','WRITE','ALLOW','ROLE','invoicing'),(674,'InvoiceOutConfig','*','READ','ALLOW','ROLE','invoicing'),(676,'Ticket','invoiceTickets','WRITE','ALLOW','ROLE','employee'),(680,'MailAliasAccount','*','READ','ALLOW','ROLE','employee'),(681,'MailAliasAccount','create','WRITE','ALLOW','ROLE','employee'),(682,'MailAliasAccount','deleteById','WRITE','ALLOW','ROLE','employee'),(683,'MailAliasAccount','canEditAlias','WRITE','ALLOW','ROLE','itManagement'),(684,'WorkerDisableExcluded','*','READ','ALLOW','ROLE','itManagement'),(685,'WorkerDisableExcluded','*','WRITE','ALLOW','ROLE','itManagement'),(686,'MailForward','*','*','ALLOW','ROLE','hr'),(687,'ClientSms','find','READ','ALLOW','ROLE','employee'),(688,'ClientSms','create','WRITE','ALLOW','ROLE','employee'),(689,'Vehicle','sorted','WRITE','ALLOW','ROLE','employee'),(690,'Roadmap','*','*','ALLOW','ROLE','palletizerBoss'),(691,'Roadmap','*','*','ALLOW','ROLE','productionBoss'),(692,'ExpeditionTruck','*','*','ALLOW','ROLE','palletizerBoss'),(693,'ExpeditionTruck','*','*','ALLOW','ROLE','productionBoss'),(694,'MailAliasAccount','canEditAlias','WRITE','ALLOW','ROLE','marketingBoss'),(695,'ViaexpressConfig','internationalExpedition','WRITE','ALLOW','ROLE','employee'),(696,'ViaexpressConfig','renderer','READ','ALLOW','ROLE','employee'),(697,'Ticket','transferClient','WRITE','ALLOW','ROLE','administrative'),(698,'Ticket','canEditWeekly','WRITE','ALLOW','ROLE','buyer'),(699,'TicketSms','find','READ','ALLOW','ROLE','salesPerson'),(701,'Docuware','upload','WRITE','ALLOW','ROLE','deliveryBoss'),(702,'Ticket','docuwareDownload','READ','ALLOW','ROLE','salesPerson'); /*!40000 ALTER TABLE `ACL` ENABLE KEYS */; UNLOCK TABLES; From 5f5a0645be9b0c40c0e780566092d62cbe71e4c3 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Mon, 11 Sep 2023 16:16:49 +0200 Subject: [PATCH 078/427] refs #5652 feat:itemTrash_new --- db/changes/233801/00-address_getLosesLastYear.sql | 3 +-- modules/client/back/methods/address/getAddress.js | 4 ++-- modules/client/back/methods/address/specs/getAddress.spec.js | 2 +- 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/db/changes/233801/00-address_getLosesLastYear.sql b/db/changes/233801/00-address_getLosesLastYear.sql index 3b8fa209b..dc75c3121 100644 --- a/db/changes/233801/00-address_getLosesLastYear.sql +++ b/db/changes/233801/00-address_getLosesLastYear.sql @@ -1,6 +1,6 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`address_getLosesLastYear`() +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`address_getLoses`() BEGIN SELECT t.addressFk , a.nickname, c.name FROM ticket t @@ -8,7 +8,6 @@ BEGIN JOIN client c ON a.clientFk = c.id WHERE c.typeFk = 'loses' AND a.isactive = 1 - AND t.created >= (CURRENT_DATE() - INTERVAL 1 YEAR) GROUP BY t.addressFk; END$$ DELIMITER ; diff --git a/modules/client/back/methods/address/getAddress.js b/modules/client/back/methods/address/getAddress.js index 94e0439da..a15fb8aba 100644 --- a/modules/client/back/methods/address/getAddress.js +++ b/modules/client/back/methods/address/getAddress.js @@ -1,6 +1,6 @@ module.exports = Self => { Self.remoteMethod('getAddress', { - description: 'Get all activated address last year ', + description: 'Get all activated address client active', accessType: 'READ', accepts: [], returns: { @@ -14,7 +14,7 @@ module.exports = Self => { }); Self.getAddress = async() => { - const query = `CALL vn.address_getLosesLastYear()`; + const query = `CALL vn.address_getLoses()`; const [result] = await Self.rawSql(query); return result; }; diff --git a/modules/client/back/methods/address/specs/getAddress.spec.js b/modules/client/back/methods/address/specs/getAddress.spec.js index d2b219495..2c84769e6 100644 --- a/modules/client/back/methods/address/specs/getAddress.spec.js +++ b/modules/client/back/methods/address/specs/getAddress.spec.js @@ -1,7 +1,7 @@ const {models} = require('vn-loopback/server/server'); describe('getAddress()', () => { - it('return list of address last year', async() => { + fit('return list of address last year', async() => { let response = await models.Address.getAddress(); expect(response.length).toBeGreaterThan(0); From 705505b931a3398b5406bb993d00c2610ffdb366 Mon Sep 17 00:00:00 2001 From: jgallego Date: Mon, 11 Sep 2023 16:24:47 +0200 Subject: [PATCH 079/427] fixes #4059 acl for address --- db/changes/233801/00-aclClient.sql | 2 ++ 1 file changed, 2 insertions(+) diff --git a/db/changes/233801/00-aclClient.sql b/db/changes/233801/00-aclClient.sql index 5308dbbe2..8e85c027b 100644 --- a/db/changes/233801/00-aclClient.sql +++ b/db/changes/233801/00-aclClient.sql @@ -10,6 +10,8 @@ INSERT INTO salix.ACL (model,property,accessType,permission,principalType,princi VALUES ('Client','find','READ','ALLOW','ROLE','employee'); INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) VALUES ('Client','exists','READ','ALLOW','ROLE','employee'); +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES ('Client','__get__addresses','READ','ALLOW','ROLE','employee'); DELETE FROM salix.ACL WHERE model = 'Client' AND property = '*' AND accessType IN ( 'campaignMetricsEmail', From 6a753d26af5573c910732be2dc1f190f2b56ca8c Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 11 Sep 2023 18:28:47 +0200 Subject: [PATCH 080/427] refs #6213 default account value --- db/changes/233801/00-supplierAccountCheckLength.sql | 8 +++++++- modules/supplier/back/models/supplier.js | 9 +++------ 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/db/changes/233801/00-supplierAccountCheckLength.sql b/db/changes/233801/00-supplierAccountCheckLength.sql index 99f571ba1..30ff739b8 100644 --- a/db/changes/233801/00-supplierAccountCheckLength.sql +++ b/db/changes/233801/00-supplierAccountCheckLength.sql @@ -1 +1,7 @@ -ALTER TABLE vn.supplier ADD CONSTRAINT supplier_CHECK CHECK (LENGTH(account) = 10); + +UPDATE `vn`.`supplier` + SET account = LPAD(id,10,'0') + WHERE account IS NULL; + +ALTER TABLE `vn`.`supplier` ADD CONSTRAINT supplierAccountTooShort CHECK (LENGTH(account) = 10); +ALTER TABLE vn.supplier MODIFY COLUMN account varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT 4100000000 NOT NULL COMMENT 'Default accounting code for suppliers.'; diff --git a/modules/supplier/back/models/supplier.js b/modules/supplier/back/models/supplier.js index 28e53e3c5..6bfec86d1 100644 --- a/modules/supplier/back/models/supplier.js +++ b/modules/supplier/back/models/supplier.js @@ -112,13 +112,9 @@ module.exports = Self => { const hasChanges = orgData && changes; const isPayMethodCheckedChanged = hasChanges && orgData.isPayMethodChecked != isPayMethodChecked; - const isAccountChanged = hasChanges && orgData.account != changes.account; if (!editPayMethodCheck && isPayMethodCheckedChanged) throw new UserError('You can not modify is pay method checked'); - - if (isAccountChanged && !(changes.account.length === 10)) - throw new UserError('The account size must be exactly 10 characters'); }); Self.observe('after save', async function(ctx) { @@ -126,10 +122,11 @@ module.exports = Self => { const supplierId = ctx.instance.id; const models = Self.app.models; - const supplier = await models.Supplier.findById(supplierId); + const supplier = await models.Supplier.findById(supplierId, null, ctx.options); await supplier.updateAttribute( 'account', - supplierId.toString().padStart(10, '0') + supplier.account + supplierId, + ctx.options ); } }); From 1d25355423969b71392b38fb96b18569d23d7e1c Mon Sep 17 00:00:00 2001 From: sergiodt Date: Tue, 12 Sep 2023 08:44:42 +0200 Subject: [PATCH 081/427] refs #5652 fix:without fit --- modules/client/back/methods/address/specs/getAddress.spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/client/back/methods/address/specs/getAddress.spec.js b/modules/client/back/methods/address/specs/getAddress.spec.js index 2c84769e6..d2b219495 100644 --- a/modules/client/back/methods/address/specs/getAddress.spec.js +++ b/modules/client/back/methods/address/specs/getAddress.spec.js @@ -1,7 +1,7 @@ const {models} = require('vn-loopback/server/server'); describe('getAddress()', () => { - fit('return list of address last year', async() => { + it('return list of address last year', async() => { let response = await models.Address.getAddress(); expect(response.length).toBeGreaterThan(0); From 0ddcb57209845852889d1e16874bb1ff873b71a7 Mon Sep 17 00:00:00 2001 From: carlossa Date: Tue, 12 Sep 2023 10:40:10 +0200 Subject: [PATCH 082/427] refs #5660 fix e2e --- db/dump/dumpedFixtures.sql | 4 ++-- e2e/paths/02-client/01_create_client.spec.js | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/db/dump/dumpedFixtures.sql b/db/dump/dumpedFixtures.sql index 2e1511b59..383cc4722 100644 --- a/db/dump/dumpedFixtures.sql +++ b/db/dump/dumpedFixtures.sql @@ -78,7 +78,7 @@ USE `account`; LOCK TABLES `role` WRITE; /*!40000 ALTER TABLE `role` DISABLE KEYS */; -INSERT INTO `role` VALUES (1,'employee','Empleado básico',1,'2017-05-19 07:04:58','2023-06-08 16:47:57',NULL),(2,'customer','Privilegios básicos de un cliente',1,'2017-05-19 07:04:58','2023-06-02 20:33:28',NULL),(3,'agency','Consultar tablas de predicciones de bultos',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(5,'administrative','Tareas relacionadas con la contabilidad',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(6,'guest','Privilegios para usuarios sin cuenta',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(9,'developer','Desarrolladores del sistema',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(11,'account','Privilegios relacionados con el login',0,'2017-05-19 07:04:58','2017-09-20 17:06:35',NULL),(13,'teamBoss','Jefe de equipo/departamento',1,'2017-05-19 07:04:58','2021-06-30 13:29:30',NULL),(15,'logistic','Departamento de compras, responsables de la logistica',1,'2017-05-19 07:04:58','2018-02-12 10:50:10',NULL),(16,'logisticBoss','Jefe del departamento de logística',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(17,'adminBoss','Jefe del departamento de administración',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(18,'salesPerson','Departamento de ventas',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(19,'salesBoss','Jefe del departamento de ventas',1,'2017-05-19 07:04:58','2017-08-16 12:38:27',NULL),(20,'manager','Gerencia',1,'2017-06-01 14:57:02','2022-07-29 07:36:15',NULL),(21,'salesAssistant','Jefe auxiliar de ventas',1,'2017-08-16 12:40:52','2017-08-16 12:40:52',NULL),(22,'teamManager','Jefe de departamento con privilegios de auxiliar de venta.',1,'2017-09-07 09:08:12','2017-09-07 09:08:12',NULL),(30,'financialBoss','Director finaciero',1,'2017-09-21 11:05:36','2017-09-21 11:05:36',NULL),(31,'freelancer','Trabajadores por cuenta ajena',1,'2017-10-10 12:57:26','2017-10-10 12:59:27',NULL),(32,'ett','Trabajadores de empresa temporal',1,'2017-10-10 12:58:58','2017-10-10 12:59:20',NULL),(33,'invoicing','Personal con acceso a facturación',0,'2018-01-29 16:43:34','2018-01-29 16:43:34',NULL),(34,'agencyBoss','Jefe/a del departamento de agencias',1,'2018-01-29 16:44:39','2018-02-23 07:58:53',NULL),(35,'buyer','Departamento de compras',1,'2018-02-12 10:35:42','2018-02-12 10:35:42',NULL),(36,'replenisher','Trabajadores de camara',1,'2018-02-16 14:07:10','2019-04-12 05:38:08',NULL),(37,'hr','Gestor/a de recursos humanos',1,'2018-02-22 17:34:53','2018-02-22 17:34:53',NULL),(38,'hrBoss','Jefe/a de recursos humanos',1,'2018-02-22 17:35:09','2018-02-22 17:35:09',NULL),(39,'adminAssistant','Jefe auxiliar administrativo',1,'2018-02-23 10:37:36','2018-02-23 10:38:41',NULL),(40,'handmade','Departamento de confección',1,'2018-02-23 11:14:53','2018-02-23 11:39:12',NULL),(41,'handmadeBoss','Jefe de departamento de confección',1,'2018-02-23 11:15:09','2018-02-23 11:39:26',NULL),(42,'artificial','Departamento de artificial',1,'2018-02-23 11:39:59','2018-02-23 11:39:59',NULL),(43,'artificialBoss','Jefe del departamento de artificial',1,'2018-02-23 11:40:16','2018-02-23 11:40:16',NULL),(44,'accessory','Departamento de complementos',1,'2018-02-23 11:41:12','2018-02-23 11:41:12',NULL),(45,'accessoryBoss','Jefe del departamento de complementos',1,'2018-02-23 11:41:23','2018-02-23 11:41:23',NULL),(47,'cooler','Empleados de cámara',1,'2018-02-23 13:08:18','2018-02-23 13:08:18',NULL),(48,'coolerBoss','Jefe de cámara',1,'2018-02-23 13:12:01','2023-03-13 08:49:43',NULL),(49,'production','Empleado de producción',1,'2018-02-26 15:28:23','2021-02-12 09:42:35',NULL),(50,'productionBoss','Jefe de producción',1,'2018-02-26 15:34:12','2018-02-26 15:34:12',NULL),(51,'marketing','Departamento de marketing',1,'2018-03-01 07:28:39','2018-03-01 07:28:39',NULL),(52,'marketingBoss','Jefe del departamento de marketing',1,'2018-03-01 07:28:57','2018-03-01 07:28:57',NULL),(53,'insurance','Gestor de seguros de cambio',0,'2018-03-05 07:44:35','2019-02-01 13:47:57',NULL),(54,'itemPicker','Sacador en cámara',1,'2018-03-05 12:08:17','2018-03-05 12:08:17',NULL),(55,'itemPickerBoss','Jefe de sacadores',1,'2018-03-05 12:08:31','2018-03-05 12:08:31',NULL),(56,'delivery','Personal de reparto',1,'2018-05-30 06:07:02','2018-05-30 06:07:02',NULL),(57,'deliveryBoss','Jefe de personal de reparto',1,'2018-05-30 06:07:19','2018-05-30 06:07:19',NULL),(58,'packager','Departamento encajadores',1,'2019-01-21 12:43:45','2019-01-21 12:43:45',NULL),(59,'packagerBoss','Jefe departamento encajadores',1,'2019-01-21 12:44:10','2019-01-21 12:44:10',NULL),(60,'productionAssi','Tareas relacionadas con producción y administración',1,'2019-01-29 13:29:01','2019-01-29 13:29:01',NULL),(61,'replenisherBos','Jefe de Complementos/Camara',1,'2019-07-01 06:44:07','2019-07-01 06:44:07',NULL),(62,'noLogin','Role without login access to MySQL',0,'2019-07-01 06:50:19','2019-07-02 13:42:05',NULL),(64,'balanceSheet','Consulta de Balance',0,'2019-07-16 12:12:08','2019-07-16 12:12:08',NULL),(65,'officeBoss','Jefe de filial',1,'2019-08-02 06:54:26','2019-08-02 06:54:26',NULL),(66,'sysadmin','Administrador de sistema',1,'2019-08-08 06:58:56','2019-08-08 06:58:56',NULL),(67,'adminOfficer','categoria profesional oficial de administración',1,'2020-01-03 08:09:23','2020-01-03 08:09:23',NULL),(69,'coolerAssist','Asistente de cámara con permiso compras',1,'2020-02-05 12:36:09','2023-03-13 08:50:07',NULL),(70,'trainee','Alumno de prácticas',1,'2020-03-04 11:00:25','2020-03-04 11:00:25',NULL),(71,'checker','Rol de revisor con privilegios de itemPicker',1,'2020-10-02 10:50:07','2020-10-02 10:50:07',NULL),(72,'claimManager','Personal de reclamaciones',1,'2020-10-13 10:01:32','2020-10-26 07:29:46',NULL),(73,'financial','Departamento de finanzas',1,'2020-11-16 09:30:27','2020-11-16 09:30:27',NULL),(74,'userPhotos','Privilegios para subir fotos de usuario',1,'2021-02-03 10:24:27','2021-02-03 10:24:27',NULL),(75,'catalogPhotos','Privilegios para subir fotos del catálogo',1,'2021-02-03 10:24:27','2021-02-03 10:24:27',NULL),(76,'chat','Rol para utilizar el rocket chat',1,'2020-11-27 13:06:50','2020-12-17 07:49:41',NULL),(100,'root','Rol con todos los privilegios',0,'2018-04-23 14:33:36','2020-11-12 06:50:07',NULL),(101,'buyerBoss','Jefe del departamento de compras',1,'2021-06-16 09:53:17','2021-06-16 09:53:17',NULL),(102,'preservedBoss','Responsable preservado',1,'2021-09-14 13:45:37','2021-09-14 13:45:37',NULL),(103,'it','Departamento de informática',1,'2021-11-11 09:48:22','2021-11-11 09:48:22',NULL),(104,'itBoss','Jefe de departamento de informática',1,'2021-11-11 09:48:49','2021-11-11 09:48:49',NULL),(105,'grant','Adjudicar roles a usuarios',1,'2021-11-11 12:41:09','2021-11-11 12:41:09',NULL),(106,'ext','Usuarios externos de la Base de datos',1,'2021-11-23 14:51:16','2021-11-23 14:51:16',NULL),(107,'productionPlus','Creado para pepe por orden de Juanvi',1,'2022-02-08 06:47:10','2022-02-08 06:47:10',NULL),(108,'system','System user',1,'2022-05-16 08:09:51','2022-05-16 08:09:51',NULL),(109,'salesTeamBoss','Jefe de equipo de comerciales',1,'2022-06-14 13:45:56','2022-06-14 13:45:56',NULL),(110,'palletizer','Paletizadores',1,'2022-12-02 12:56:22','2022-12-02 12:56:30',NULL),(111,'entryEditor','Entry editor',1,'2023-01-13 11:21:55','2023-01-13 11:21:55',NULL),(112,'maintenance','Personal de mantenimiento',1,'2023-01-19 06:23:35','2023-01-19 06:23:35',NULL),(114,'maintenanceBos','Jefe de mantenimiento',1,'2023-01-19 06:31:16','2023-05-17 11:07:21',NULL),(115,'itManagement','TI management',1,'2023-03-29 07:27:55','2023-03-29 07:28:04',NULL),(119,'palletizerBoss','Jefe de paletizadores',1,'2023-06-07 11:51:54','2023-06-07 11:51:54',NULL),(120,'developerBoss','Jefe de proyecto de desarrollo',1,'2023-06-19 07:07:21','2023-06-19 07:07:21',21709),(121,'buyerSalesAssistant','Rol para compradores que también son responsables de ventas',1,'2023-06-23 14:48:19','2023-06-23 14:48:19',NULL),(122,'logisticAssistant','Jefe auxiliar de logística',1,'2023-06-26 07:21:15','2023-06-26 07:21:15',NULL); +INSERT INTO `role` VALUES (1,'employee','Empleado básico',1,'2017-05-19 07:04:58','2023-06-08 16:47:57',NULL),(2,'customer','Privilegios básicos de un cliente',1,'2017-05-19 07:04:58','2023-06-02 20:33:28',NULL),(3,'agency','Consultar tablas de predicciones de bultos',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(5,'administrative','Tareas relacionadas con la contabilidad',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(6,'guest','Privilegios para usuarios sin cuenta',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(9,'developer','Desarrolladores del sistema',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(11,'account','Privilegios relacionados con el login',0,'2017-05-19 07:04:58','2017-09-20 17:06:35',NULL),(13,'teamBoss','Jefe de equipo/departamento',1,'2017-05-19 07:04:58','2021-06-30 13:29:30',NULL),(15,'logistic','Departamento de compras, responsables de la logistica',1,'2017-05-19 07:04:58','2018-02-12 10:50:10',NULL),(16,'logisticBoss','Jefe del departamento de logística',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(17,'adminBoss','Jefe del departamento de administración',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(18,'salesPerson','Departamento de ventas',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(19,'salesBoss','Jefe del departamento de ventas',1,'2017-05-19 07:04:58','2017-08-16 12:38:27',NULL),(20,'manager','Gerencia',1,'2017-06-01 14:57:02','2022-07-29 07:36:15',NULL),(21,'salesAssistant','Jefe auxiliar de ventas',1,'2017-08-16 12:40:52','2017-08-16 12:40:52',NULL),(22,'teamManager','Jefe de departamento con privilegios de auxiliar de venta.',1,'2017-09-07 09:08:12','2017-09-07 09:08:12',NULL),(30,'financialBoss','Director finaciero',1,'2017-09-21 11:05:36','2017-09-21 11:05:36',NULL),(31,'freelancer','Trabajadores por cuenta ajena',1,'2017-10-10 12:57:26','2017-10-10 12:59:27',NULL),(32,'ett','Trabajadores de empresa temporal',1,'2017-10-10 12:58:58','2017-10-10 12:59:20',NULL),(33,'invoicing','Personal con acceso a facturación',0,'2018-01-29 16:43:34','2018-01-29 16:43:34',NULL),(34,'agencyBoss','Jefe/a del departamento de agencias',1,'2018-01-29 16:44:39','2018-02-23 07:58:53',NULL),(35,'buyer','Departamento de compras',1,'2018-02-12 10:35:42','2018-02-12 10:35:42',NULL),(36,'replenisher','Trabajadores de camara',1,'2018-02-16 14:07:10','2019-04-12 05:38:08',NULL),(37,'hr','Gestor/a de recursos humanos',1,'2018-02-22 17:34:53','2018-02-22 17:34:53',NULL),(38,'hrBoss','Jefe/a de recursos humanos',1,'2018-02-22 17:35:09','2018-02-22 17:35:09',NULL),(39,'adminAssistant','Jefe auxiliar administrativo',1,'2018-02-23 10:37:36','2018-02-23 10:38:41',NULL),(40,'handmade','Departamento de confección',1,'2018-02-23 11:14:53','2018-02-23 11:39:12',NULL),(41,'handmadeBoss','Jefe de departamento de confección',1,'2018-02-23 11:15:09','2018-02-23 11:39:26',NULL),(42,'artificial','Departamento de artificial',1,'2018-02-23 11:39:59','2018-02-23 11:39:59',NULL),(43,'artificialBoss','Jefe del departamento de artificial',1,'2018-02-23 11:40:16','2018-02-23 11:40:16',NULL),(44,'accessory','Departamento de complementos',1,'2018-02-23 11:41:12','2018-02-23 11:41:12',NULL),(45,'accessoryBoss','Jefe del departamento de complementos',1,'2018-02-23 11:41:23','2018-02-23 11:41:23',NULL),(47,'cooler','Empleados de cámara',1,'2018-02-23 13:08:18','2018-02-23 13:08:18',NULL),(48,'coolerBoss','Jefe de cámara',1,'2018-02-23 13:12:01','2023-03-13 08:49:43',NULL),(49,'production','Empleado de producción',1,'2018-02-26 15:28:23','2021-02-12 09:42:35',NULL),(50,'productionBoss','Jefe de producción',1,'2018-02-26 15:34:12','2018-02-26 15:34:12',NULL),(51,'marketing','Departamento de marketing',1,'2018-03-01 07:28:39','2018-03-01 07:28:39',NULL),(52,'marketingBoss','Jefe del departamento de marketing',1,'2018-03-01 07:28:57','2018-03-01 07:28:57',NULL),(53,'insurance','Gestor de seguros de cambio',0,'2018-03-05 07:44:35','2019-02-01 13:47:57',NULL),(54,'itemPicker','Sacador en cámara',1,'2018-03-05 12:08:17','2018-03-05 12:08:17',NULL),(55,'itemPickerBoss','Jefe de sacadores',1,'2018-03-05 12:08:31','2018-03-05 12:08:31',NULL),(56,'delivery','Personal de reparto',1,'2018-05-30 06:07:02','2018-05-30 06:07:02',NULL),(57,'deliveryAssistant','Jefe de personal de reparto',1,'2018-05-30 06:07:19','2018-05-30 06:07:19',NULL),(58,'packager','Departamento encajadores',1,'2019-01-21 12:43:45','2019-01-21 12:43:45',NULL),(59,'packagerBoss','Jefe departamento encajadores',1,'2019-01-21 12:44:10','2019-01-21 12:44:10',NULL),(60,'productionAssi','Tareas relacionadas con producción y administración',1,'2019-01-29 13:29:01','2019-01-29 13:29:01',NULL),(61,'replenisherBos','Jefe de Complementos/Camara',1,'2019-07-01 06:44:07','2019-07-01 06:44:07',NULL),(62,'noLogin','Role without login access to MySQL',0,'2019-07-01 06:50:19','2019-07-02 13:42:05',NULL),(64,'balanceSheet','Consulta de Balance',0,'2019-07-16 12:12:08','2019-07-16 12:12:08',NULL),(65,'officeBoss','Jefe de filial',1,'2019-08-02 06:54:26','2019-08-02 06:54:26',NULL),(66,'sysadmin','Administrador de sistema',1,'2019-08-08 06:58:56','2019-08-08 06:58:56',NULL),(67,'adminOfficer','categoria profesional oficial de administración',1,'2020-01-03 08:09:23','2020-01-03 08:09:23',NULL),(69,'coolerAssist','Asistente de cámara con permiso compras',1,'2020-02-05 12:36:09','2023-03-13 08:50:07',NULL),(70,'trainee','Alumno de prácticas',1,'2020-03-04 11:00:25','2020-03-04 11:00:25',NULL),(71,'checker','Rol de revisor con privilegios de itemPicker',1,'2020-10-02 10:50:07','2020-10-02 10:50:07',NULL),(72,'claimManager','Personal de reclamaciones',1,'2020-10-13 10:01:32','2020-10-26 07:29:46',NULL),(73,'financial','Departamento de finanzas',1,'2020-11-16 09:30:27','2020-11-16 09:30:27',NULL),(74,'userPhotos','Privilegios para subir fotos de usuario',1,'2021-02-03 10:24:27','2021-02-03 10:24:27',NULL),(75,'catalogPhotos','Privilegios para subir fotos del catálogo',1,'2021-02-03 10:24:27','2021-02-03 10:24:27',NULL),(76,'chat','Rol para utilizar el rocket chat',1,'2020-11-27 13:06:50','2020-12-17 07:49:41',NULL),(100,'root','Rol con todos los privilegios',0,'2018-04-23 14:33:36','2020-11-12 06:50:07',NULL),(101,'buyerBoss','Jefe del departamento de compras',1,'2021-06-16 09:53:17','2021-06-16 09:53:17',NULL),(102,'preservedBoss','Responsable preservado',1,'2021-09-14 13:45:37','2021-09-14 13:45:37',NULL),(103,'it','Departamento de informática',1,'2021-11-11 09:48:22','2021-11-11 09:48:22',NULL),(104,'itBoss','Jefe de departamento de informática',1,'2021-11-11 09:48:49','2021-11-11 09:48:49',NULL),(105,'grant','Adjudicar roles a usuarios',1,'2021-11-11 12:41:09','2021-11-11 12:41:09',NULL),(106,'ext','Usuarios externos de la Base de datos',1,'2021-11-23 14:51:16','2021-11-23 14:51:16',NULL),(107,'productionPlus','Creado para pepe por orden de Juanvi',1,'2022-02-08 06:47:10','2022-02-08 06:47:10',NULL),(108,'system','System user',1,'2022-05-16 08:09:51','2022-05-16 08:09:51',NULL),(109,'salesTeamBoss','Jefe de equipo de comerciales',1,'2022-06-14 13:45:56','2022-06-14 13:45:56',NULL),(110,'palletizer','Paletizadores',1,'2022-12-02 12:56:22','2022-12-02 12:56:30',NULL),(111,'entryEditor','Entry editor',1,'2023-01-13 11:21:55','2023-01-13 11:21:55',NULL),(112,'maintenance','Personal de mantenimiento',1,'2023-01-19 06:23:35','2023-01-19 06:23:35',NULL),(114,'maintenanceBos','Jefe de mantenimiento',1,'2023-01-19 06:31:16','2023-05-17 11:07:21',NULL),(115,'itManagement','TI management',1,'2023-03-29 07:27:55','2023-03-29 07:28:04',NULL),(119,'palletizerBoss','Jefe de paletizadores',1,'2023-06-07 11:51:54','2023-06-07 11:51:54',NULL),(120,'developerBoss','Jefe de proyecto de desarrollo',1,'2023-06-19 07:07:21','2023-06-19 07:07:21',21709),(121,'buyerSalesAssistant','Rol para compradores que también son responsables de ventas',1,'2023-06-23 14:48:19','2023-06-23 14:48:19',NULL),(122,'logisticAssistant','Jefe auxiliar de logística',1,'2023-06-26 07:21:15','2023-06-26 07:21:15',NULL); /*!40000 ALTER TABLE `role` ENABLE KEYS */; UNLOCK TABLES; @@ -164,7 +164,7 @@ USE `salix`; LOCK TABLES `ACL` WRITE; /*!40000 ALTER TABLE `ACL` DISABLE KEYS */; -INSERT INTO `ACL` VALUES (3,'Address','*','*','ALLOW','ROLE','employee'),(5,'AgencyService','*','READ','ALLOW','ROLE','employee'),(9,'ClientObservation','*','*','ALLOW','ROLE','employee'),(11,'ContactChannel','*','READ','ALLOW','ROLE','trainee'),(13,'Employee','*','READ','ALLOW','ROLE','employee'),(14,'PayMethod','*','READ','ALLOW','ROLE','trainee'),(16,'FakeProduction','*','READ','ALLOW','ROLE','employee'),(17,'Warehouse','* ','READ','ALLOW','ROLE','trainee'),(20,'TicketState','*','*','ALLOW','ROLE','employee'),(24,'Delivery','*','READ','ALLOW','ROLE','employee'),(25,'Zone','*','READ','ALLOW','ROLE','employee'),(26,'ClientCredit','*','*','ALLOW','ROLE','employee'),(27,'ClientCreditLimit','*','READ','ALLOW','ROLE','trainee'),(30,'GreugeType','*','READ','ALLOW','ROLE','trainee'),(31,'Mandate','*','READ','ALLOW','ROLE','trainee'),(32,'MandateType','*','READ','ALLOW','ROLE','trainee'),(33,'Company','*','READ','ALLOW','ROLE','trainee'),(34,'Greuge','*','READ','ALLOW','ROLE','trainee'),(35,'AddressObservation','*','*','ALLOW','ROLE','employee'),(36,'ObservationType','*','*','ALLOW','ROLE','employee'),(37,'Greuge','*','WRITE','ALLOW','ROLE','employee'),(38,'AgencyMode','*','READ','ALLOW','ROLE','employee'),(39,'ItemTag','*','WRITE','ALLOW','ROLE','buyer'),(40,'ItemBotanical','*','WRITE','ALLOW','ROLE','buyer'),(41,'ItemBotanical','*','READ','ALLOW','ROLE','employee'),(42,'ItemPlacement','*','WRITE','ALLOW','ROLE','buyer'),(43,'ItemPlacement','*','WRITE','ALLOW','ROLE','replenisher'),(44,'ItemPlacement','*','READ','ALLOW','ROLE','employee'),(45,'ItemBarcode','*','READ','ALLOW','ROLE','employee'),(46,'ItemBarcode','*','WRITE','ALLOW','ROLE','buyer'),(47,'ItemBarcode','*','WRITE','ALLOW','ROLE','replenisher'),(51,'ItemTag','*','READ','ALLOW','ROLE','employee'),(53,'Item','*','READ','ALLOW','ROLE','employee'),(54,'Item','*','WRITE','ALLOW','ROLE','buyer'),(55,'Recovery','*','READ','ALLOW','ROLE','trainee'),(56,'Recovery','*','WRITE','ALLOW','ROLE','administrative'),(58,'CreditClassification','*','*','ALLOW','ROLE','insurance'),(60,'CreditInsurance','*','*','ALLOW','ROLE','insurance'),(61,'InvoiceOut','*','READ','ALLOW','ROLE','employee'),(63,'TicketObservation','*','*','ALLOW','ROLE','employee'),(64,'Route','*','READ','ALLOW','ROLE','employee'),(65,'Sale','*','READ','ALLOW','ROLE','employee'),(66,'TicketTracking','*','READ','ALLOW','ROLE','employee'),(68,'TicketPackaging','*','*','ALLOW','ROLE','employee'),(69,'Packaging','*','READ','ALLOW','ROLE','employee'),(70,'Packaging','*','WRITE','ALLOW','ROLE','logistic'),(72,'SaleComponent','*','READ','ALLOW','ROLE','employee'),(73,'Expedition','*','READ','ALLOW','ROLE','employee'),(74,'Expedition','*','WRITE','ALLOW','ROLE','deliveryBoss'),(75,'Expedition','*','WRITE','ALLOW','ROLE','production'),(76,'AnnualAverageInvoiced','*','READ','ALLOW','ROLE','employee'),(77,'WorkerMana','*','READ','ALLOW','ROLE','employee'),(78,'TicketTracking','*','WRITE','ALLOW','ROLE','production'),(79,'TicketTracking','changeState','*','ALLOW','ROLE','employee'),(80,'Sale','deleteSales','*','ALLOW','ROLE','employee'),(81,'Sale','moveToTicket','*','ALLOW','ROLE','employee'),(82,'Sale','updateQuantity','*','ALLOW','ROLE','employee'),(83,'Sale','updatePrice','*','ALLOW','ROLE','employee'),(84,'Sale','updateDiscount','*','ALLOW','ROLE','employee'),(85,'SaleTracking','*','READ','ALLOW','ROLE','employee'),(86,'Order','*','*','ALLOW','ROLE','employee'),(87,'OrderRow','*','*','ALLOW','ROLE','employee'),(88,'ClientContact','*','*','ALLOW','ROLE','employee'),(89,'Sale','moveToNewTicket','*','ALLOW','ROLE','employee'),(90,'Sale','reserve','*','ALLOW','ROLE','employee'),(91,'TicketWeekly','*','READ','ALLOW','ROLE','employee'),(94,'Agency','landsThatDay','*','ALLOW','ROLE','employee'),(96,'ClaimEnd','*','READ','ALLOW','ROLE','employee'),(97,'ClaimEnd','*','WRITE','ALLOW','ROLE','claimManager'),(98,'ClaimBeginning','*','*','ALLOW','ROLE','employee'),(99,'ClaimDevelopment','*','READ','ALLOW','ROLE','employee'),(100,'ClaimDevelopment','*','WRITE','ALLOW','ROLE','claimManager'),(102,'Claim','createFromSales','*','ALLOW','ROLE','employee'),(104,'Item','*','WRITE','ALLOW','ROLE','marketingBoss'),(105,'ItemBarcode','*','WRITE','ALLOW','ROLE','marketingBoss'),(106,'ItemBotanical','*','WRITE','ALLOW','ROLE','marketingBoss'),(108,'ItemPlacement','*','WRITE','ALLOW','ROLE','marketingBoss'),(109,'UserConfig','*','*','ALLOW','ROLE','employee'),(110,'Bank','*','READ','ALLOW','ROLE','trainee'),(111,'ClientLog','*','READ','ALLOW','ROLE','trainee'),(112,'Defaulter','*','READ','ALLOW','ROLE','employee'),(113,'ClientRisk','*','READ','ALLOW','ROLE','trainee'),(114,'Receipt','*','READ','ALLOW','ROLE','trainee'),(115,'Receipt','*','WRITE','ALLOW','ROLE','administrative'),(116,'BankEntity','*','*','ALLOW','ROLE','employee'),(117,'ClientSample','*','*','ALLOW','ROLE','employee'),(118,'WorkerTeam','*','*','ALLOW','ROLE','salesPerson'),(119,'Travel','*','READ','ALLOW','ROLE','employee'),(120,'Travel','*','WRITE','ALLOW','ROLE','buyer'),(121,'Item','regularize','*','ALLOW','ROLE','employee'),(122,'TicketRequest','*','*','ALLOW','ROLE','employee'),(124,'Client','confirmTransaction','WRITE','ALLOW','ROLE','administrative'),(125,'Agency','getAgenciesWithWarehouse','*','ALLOW','ROLE','employee'),(126,'Client','activeWorkersWithRole','*','ALLOW','ROLE','employee'),(127,'TicketLog','*','READ','ALLOW','ROLE','employee'),(129,'TicketService','*','*','ALLOW','ROLE','employee'),(130,'Expedition','*','WRITE','ALLOW','ROLE','packager'),(131,'CreditInsurance','*','READ','ALLOW','ROLE','trainee'),(132,'CreditClassification','*','READ','ALLOW','ROLE','trainee'),(133,'ItemTag','*','WRITE','ALLOW','ROLE','marketingBoss'),(135,'ZoneGeo','*','READ','ALLOW','ROLE','employee'),(136,'ZoneCalendar','*','READ','ALLOW','ROLE','employee'),(137,'ZoneIncluded','*','READ','ALLOW','ROLE','employee'),(138,'LabourHoliday','*','READ','ALLOW','ROLE','employee'),(139,'LabourHolidayLegend','*','READ','ALLOW','ROLE','employee'),(140,'LabourHolidayType','*','READ','ALLOW','ROLE','employee'),(141,'Zone','*','*','ALLOW','ROLE','logisticBoss'),(142,'ZoneCalendar','*','WRITE','ALLOW','ROLE','deliveryBoss'),(143,'ZoneIncluded','*','*','ALLOW','ROLE','deliveryBoss'),(144,'Stowaway','*','*','ALLOW','ROLE','employee'),(145,'Ticket','getPossibleStowaways','READ','ALLOW','ROLE','employee'),(147,'UserConfigView','*','*','ALLOW','ROLE','employee'),(148,'UserConfigView','*','*','ALLOW','ROLE','employee'),(149,'Sip','*','READ','ALLOW','ROLE','employee'),(150,'Sip','*','WRITE','ALLOW','ROLE','hr'),(151,'Department','*','READ','ALLOW','ROLE','employee'),(152,'Department','*','WRITE','ALLOW','ROLE','hr'),(153,'Route','*','READ','ALLOW','ROLE','employee'),(154,'Route','*','WRITE','ALLOW','ROLE','delivery'),(155,'Calendar','*','READ','ALLOW','ROLE','hr'),(156,'WorkerLabour','*','READ','ALLOW','ROLE','hr'),(157,'Calendar','absences','READ','ALLOW','ROLE','employee'),(158,'ItemTag','*','WRITE','ALLOW','ROLE','accessory'),(160,'TicketServiceType','*','READ','ALLOW','ROLE','employee'),(161,'TicketConfig','*','READ','ALLOW','ROLE','employee'),(162,'InvoiceOut','delete','WRITE','ALLOW','ROLE','invoicing'),(163,'InvoiceOut','book','WRITE','ALLOW','ROLE','invoicing'),(165,'TicketDms','*','*','ALLOW','ROLE','employee'),(167,'Worker','isSubordinate','READ','ALLOW','ROLE','employee'),(168,'Worker','mySubordinates','READ','ALLOW','ROLE','employee'),(169,'WorkerTimeControl','filter','READ','ALLOW','ROLE','employee'),(170,'WorkerTimeControl','addTime','WRITE','ALLOW','ROLE','employee'),(171,'TicketServiceType','*','WRITE','ALLOW','ROLE','administrative'),(172,'Sms','*','READ','ALLOW','ROLE','employee'),(173,'Sms','send','WRITE','ALLOW','ROLE','employee'),(176,'Device','*','*','ALLOW','ROLE','employee'),(177,'Device','*','*','ALLOW','ROLE','employee'),(178,'WorkerTimeControl','*','*','ALLOW','ROLE','employee'),(179,'ItemLog','*','READ','ALLOW','ROLE','employee'),(180,'RouteLog','*','READ','ALLOW','ROLE','employee'),(181,'Dms','removeFile','WRITE','ALLOW','ROLE','employee'),(182,'Dms','uploadFile','WRITE','ALLOW','ROLE','employee'),(183,'Dms','downloadFile','READ','ALLOW','ROLE','employee'),(184,'Client','uploadFile','WRITE','ALLOW','ROLE','employee'),(185,'ClientDms','removeFile','WRITE','ALLOW','ROLE','employee'),(186,'ClientDms','*','READ','ALLOW','ROLE','trainee'),(187,'Ticket','uploadFile','WRITE','ALLOW','ROLE','employee'),(190,'Route','updateVolume','WRITE','ALLOW','ROLE','deliveryBoss'),(191,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(192,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(194,'Postcode','*','WRITE','ALLOW','ROLE','deliveryBoss'),(195,'Ticket','addSale','WRITE','ALLOW','ROLE','employee'),(196,'Dms','updateFile','WRITE','ALLOW','ROLE','employee'),(197,'Dms','*','READ','ALLOW','ROLE','trainee'),(198,'ClaimDms','removeFile','WRITE','ALLOW','ROLE','employee'),(199,'ClaimDms','*','READ','ALLOW','ROLE','employee'),(200,'Claim','uploadFile','WRITE','ALLOW','ROLE','employee'),(201,'Sale','updateConcept','WRITE','ALLOW','ROLE','employee'),(202,'Claim','updateClaimAction','WRITE','ALLOW','ROLE','claimManager'),(203,'UserPhone','*','*','ALLOW','ROLE','employee'),(204,'WorkerDms','removeFile','WRITE','ALLOW','ROLE','hr'),(205,'WorkerDms','*','READ','ALLOW','ROLE','hr'),(206,'Chat','*','*','ALLOW','ROLE','employee'),(207,'Chat','sendMessage','*','ALLOW','ROLE','employee'),(208,'Sale','recalculatePrice','WRITE','ALLOW','ROLE','employee'),(209,'Ticket','recalculateComponents','WRITE','ALLOW','ROLE','employee'),(211,'TravelLog','*','READ','ALLOW','ROLE','buyer'),(212,'Thermograph','*','*','ALLOW','ROLE','buyer'),(213,'TravelThermograph','*','WRITE','ALLOW','ROLE','buyer'),(214,'Entry','*','*','ALLOW','ROLE','buyer'),(215,'TicketWeekly','*','WRITE','ALLOW','ROLE','buyer'),(216,'TravelThermograph','*','READ','ALLOW','ROLE','employee'),(218,'Intrastat','*','*','ALLOW','ROLE','buyer'),(221,'UserConfig','getUserConfig','READ','ALLOW','ROLE','account'),(222,'Client','*','READ','ALLOW','ROLE','trainee'),(226,'ClientObservation','*','READ','ALLOW','ROLE','trainee'),(227,'Address','*','READ','ALLOW','ROLE','trainee'),(228,'AddressObservation','*','READ','ALLOW','ROLE','trainee'),(230,'ClientCredit','*','READ','ALLOW','ROLE','trainee'),(231,'ClientContact','*','READ','ALLOW','ROLE','trainee'),(232,'ClientSample','*','READ','ALLOW','ROLE','trainee'),(233,'EntryLog','*','READ','ALLOW','ROLE','buyer'),(234,'WorkerLog','find','READ','ALLOW','ROLE','hr'),(235,'CustomsAgent','*','*','ALLOW','ROLE','employee'),(236,'Buy','*','*','ALLOW','ROLE','buyer'),(237,'WorkerDms','filter','*','ALLOW','ROLE','employee'),(238,'Town','*','WRITE','ALLOW','ROLE','deliveryBoss'),(239,'Province','*','WRITE','ALLOW','ROLE','deliveryBoss'),(240,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(241,'SupplierContact','*','WRITE','ALLOW','ROLE','administrative'),(242,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(244,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(248,'RoleMapping','*','READ','ALLOW','ROLE','account'),(249,'UserPassword','*','READ','ALLOW','ROLE','account'),(250,'Town','*','WRITE','ALLOW','ROLE','deliveryBoss'),(251,'Province','*','WRITE','ALLOW','ROLE','deliveryBoss'),(252,'Supplier','*','READ','ALLOW','ROLE','employee'),(253,'Supplier','*','WRITE','ALLOW','ROLE','administrative'),(254,'SupplierLog','*','READ','ALLOW','ROLE','employee'),(256,'Image','*','WRITE','ALLOW','ROLE','employee'),(257,'FixedPrice','*','*','ALLOW','ROLE','buyer'),(258,'PayDem','*','READ','ALLOW','ROLE','employee'),(259,'Client','createReceipt','*','ALLOW','ROLE','salesAssistant'),(260,'PrintServerQueue','*','WRITE','ALLOW','ROLE','employee'),(261,'SupplierAccount','*','*','ALLOW','ROLE','administrative'),(262,'Entry','*','*','ALLOW','ROLE','administrative'),(263,'InvoiceIn','*','*','ALLOW','ROLE','administrative'),(264,'StarredModule','*','*','ALLOW','ROLE','employee'),(265,'ItemBotanical','*','WRITE','ALLOW','ROLE','logisticBoss'),(266,'ZoneLog','*','READ','ALLOW','ROLE','employee'),(267,'Genus','*','WRITE','ALLOW','ROLE','logisticBoss'),(268,'Specie','*','WRITE','ALLOW','ROLE','logisticBoss'),(269,'InvoiceOut','createPdf','WRITE','ALLOW','ROLE','employee'),(270,'SupplierAddress','*','*','ALLOW','ROLE','employee'),(271,'SalesMonitor','*','*','ALLOW','ROLE','employee'),(272,'InvoiceInLog','*','READ','ALLOW','ROLE','employee'),(273,'InvoiceInTax','*','*','ALLOW','ROLE','administrative'),(274,'InvoiceInLog','*','READ','ALLOW','ROLE','administrative'),(275,'InvoiceOut','createManualInvoice','WRITE','ALLOW','ROLE','invoicing'),(276,'InvoiceOut','globalInvoicing','WRITE','ALLOW','ROLE','invoicing'),(278,'RoleInherit','*','WRITE','ALLOW','ROLE','grant'),(279,'MailAlias','*','*','ALLOW','ROLE','marketing'),(283,'EntryObservation','*','*','ALLOW','ROLE','buyer'),(284,'LdapConfig','*','*','ALLOW','ROLE','sysadmin'),(285,'SambaConfig','*','*','ALLOW','ROLE','sysadmin'),(286,'ACL','*','*','ALLOW','ROLE','developer'),(287,'AccessToken','*','*','ALLOW','ROLE','developer'),(293,'RoleInherit','*','*','ALLOW','ROLE','it'),(294,'RoleRole','*','*','ALLOW','ROLE','it'),(295,'AccountConfig','*','*','ALLOW','ROLE','sysadmin'),(296,'Collection','*','READ','ALLOW','ROLE','employee'),(297,'Sale','refund','WRITE','ALLOW','ROLE','invoicing'),(298,'InvoiceInDueDay','*','*','ALLOW','ROLE','administrative'),(299,'Collection','setSaleQuantity','*','ALLOW','ROLE','employee'),(302,'AgencyTerm','*','*','ALLOW','ROLE','administrative'),(303,'ClaimLog','*','READ','ALLOW','ROLE','claimManager'),(304,'Edi','updateData','WRITE','ALLOW','ROLE','employee'),(305,'EducationLevel','*','*','ALLOW','ROLE','employee'),(306,'InvoiceInIntrastat','*','*','ALLOW','ROLE','employee'),(307,'SupplierAgencyTerm','*','*','ALLOW','ROLE','administrative'),(308,'InvoiceInIntrastat','*','*','ALLOW','ROLE','employee'),(309,'Zone','getZoneClosing','*','ALLOW','ROLE','employee'),(310,'ExpeditionState','*','READ','ALLOW','ROLE','employee'),(311,'Expense','*','READ','ALLOW','ROLE','employee'),(312,'Expense','*','WRITE','ALLOW','ROLE','administrative'),(314,'SupplierActivity','*','READ','ALLOW','ROLE','employee'),(315,'SupplierActivity','*','WRITE','ALLOW','ROLE','administrative'),(316,'Dms','deleteTrashFiles','WRITE','ALLOW','ROLE','employee'),(317,'ClientUnpaid','*','*','ALLOW','ROLE','administrative'),(318,'MdbVersion','*','*','ALLOW','ROLE','developer'),(319,'ItemType','*','READ','ALLOW','ROLE','employee'),(320,'ItemType','*','WRITE','ALLOW','ROLE','buyer'),(321,'InvoiceOut','refund','WRITE','ALLOW','ROLE','invoicing'),(322,'InvoiceOut','refund','WRITE','ALLOW','ROLE','salesAssistant'),(323,'InvoiceOut','refund','WRITE','ALLOW','ROLE','claimManager'),(324,'Ticket','refund','WRITE','ALLOW','ROLE','invoicing'),(325,'Ticket','refund','WRITE','ALLOW','ROLE','salesAssistant'),(326,'Ticket','refund','WRITE','ALLOW','ROLE','claimManager'),(327,'Sale','refund','WRITE','ALLOW','ROLE','salesAssistant'),(328,'Sale','refund','WRITE','ALLOW','ROLE','claimManager'),(329,'TicketRefund','*','WRITE','ALLOW','ROLE','invoicing'),(330,'ClaimObservation','*','WRITE','ALLOW','ROLE','salesPerson'),(331,'ClaimObservation','*','READ','ALLOW','ROLE','salesPerson'),(332,'Client','setPassword','WRITE','ALLOW','ROLE','salesPerson'),(333,'Client','updateUser','WRITE','ALLOW','ROLE','salesPerson'),(334,'ShelvingLog','*','READ','ALLOW','ROLE','employee'),(335,'ZoneExclusionGeo','*','READ','ALLOW','ROLE','employee'),(336,'ZoneExclusionGeo','*','WRITE','ALLOW','ROLE','deliveryBoss'),(337,'Parking','*','*','ALLOW','ROLE','employee'),(338,'Shelving','*','*','ALLOW','ROLE','employee'),(339,'OsTicket','*','*','ALLOW','ROLE','employee'),(340,'OsTicketConfig','*','*','ALLOW','ROLE','it'),(341,'ClientConsumptionQueue','*','WRITE','ALLOW','ROLE','employee'),(342,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','employee'),(343,'Ticket','deliveryNoteEmail','WRITE','ALLOW','ROLE','employee'),(344,'Ticket','deliveryNoteCsvPdf','READ','ALLOW','ROLE','employee'),(345,'Ticket','deliveryNoteCsvEmail','READ','ALLOW','ROLE','employee'),(346,'Client','campaignMetricsPdf','READ','ALLOW','ROLE','employee'),(347,'Client','campaignMetricsEmail','WRITE','ALLOW','ROLE','employee'),(348,'Client','clientWelcomeHtml','READ','ALLOW','ROLE','employee'),(349,'Client','clientWelcomeEmail','WRITE','ALLOW','ROLE','employee'),(350,'Client','creditRequestPdf','READ','ALLOW','ROLE','employee'),(351,'Client','creditRequestHtml','READ','ALLOW','ROLE','employee'),(352,'Client','creditRequestEmail','WRITE','ALLOW','ROLE','employee'),(353,'Client','printerSetupHtml','READ','ALLOW','ROLE','employee'),(354,'Client','printerSetupEmail','WRITE','ALLOW','ROLE','employee'),(355,'Client','sepaCoreEmail','WRITE','ALLOW','ROLE','employee'),(356,'Client','letterDebtorPdf','READ','ALLOW','ROLE','employee'),(357,'Client','letterDebtorStHtml','READ','ALLOW','ROLE','employee'),(358,'Client','letterDebtorStEmail','WRITE','ALLOW','ROLE','employee'),(359,'Client','letterDebtorNdHtml','READ','ALLOW','ROLE','employee'),(360,'Client','letterDebtorNdEmail','WRITE','ALLOW','ROLE','employee'),(361,'Client','clientDebtStatementPdf','READ','ALLOW','ROLE','employee'),(362,'Client','clientDebtStatementHtml','READ','ALLOW','ROLE','employee'),(363,'Client','clientDebtStatementEmail','WRITE','ALLOW','ROLE','employee'),(364,'Client','incotermsAuthorizationPdf','READ','ALLOW','ROLE','employee'),(365,'Client','incotermsAuthorizationHtml','READ','ALLOW','ROLE','employee'),(366,'Client','incotermsAuthorizationEmail','WRITE','ALLOW','ROLE','employee'),(367,'Client','consumptionSendQueued','WRITE','ALLOW','ROLE','system'),(368,'InvoiceOut','invoiceEmail','WRITE','ALLOW','ROLE','employee'),(369,'InvoiceOut','exportationPdf','READ','ALLOW','ROLE','employee'),(370,'InvoiceOut','sendQueued','WRITE','ALLOW','ROLE','system'),(371,'Ticket','invoiceCsvPdf','READ','ALLOW','ROLE','employee'),(372,'Ticket','invoiceCsvEmail','WRITE','ALLOW','ROLE','employee'),(373,'Supplier','campaignMetricsPdf','READ','ALLOW','ROLE','employee'),(374,'Supplier','campaignMetricsEmail','WRITE','ALLOW','ROLE','employee'),(375,'Travel','extraCommunityPdf','READ','ALLOW','ROLE','employee'),(376,'Travel','extraCommunityEmail','WRITE','ALLOW','ROLE','employee'),(377,'Entry','entryOrderPdf','READ','ALLOW','ROLE','employee'),(378,'OsTicket','osTicketReportEmail','WRITE','ALLOW','ROLE','system'),(379,'Item','buyerWasteEmail','WRITE','ALLOW','ROLE','system'),(380,'Claim','claimPickupPdf','READ','ALLOW','ROLE','employee'),(381,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','claimManager'),(382,'Item','labelPdf','READ','ALLOW','ROLE','employee'),(383,'Sector','*','READ','ALLOW','ROLE','employee'),(384,'Sector','*','WRITE','ALLOW','ROLE','employee'),(385,'Route','driverRoutePdf','READ','ALLOW','ROLE','employee'),(386,'Route','driverRouteEmail','WRITE','ALLOW','ROLE','employee'),(387,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','customer'),(388,'Supplier','newSupplier','WRITE','ALLOW','ROLE','administrative'),(389,'ClaimRma','*','READ','ALLOW','ROLE','claimManager'),(390,'ClaimRma','*','WRITE','ALLOW','ROLE','claimManager'),(391,'Notification','*','WRITE','ALLOW','ROLE','system'),(392,'Boxing','*','*','ALLOW','ROLE','employee'),(393,'Url','*','READ','ALLOW','ROLE','employee'),(394,'Url','*','WRITE','ALLOW','ROLE','it'),(395,'ItemShelving','*','READ','ALLOW','ROLE','employee'),(396,'ItemShelving','*','WRITE','ALLOW','ROLE','production'),(397,'ItemShelvingPlacementSupplyStock','*','READ','ALLOW','ROLE','employee'),(398,'NotificationQueue','*','*','ALLOW','ROLE','employee'),(399,'InvoiceOut','clientsToInvoice','WRITE','ALLOW','ROLE','invoicing'),(400,'InvoiceOut','invoiceClient','WRITE','ALLOW','ROLE','invoicing'),(401,'Sale','editTracked','WRITE','ALLOW','ROLE','production'),(402,'Sale','editFloramondo','WRITE','ALLOW','ROLE','salesAssistant'),(403,'Receipt','balanceCompensationEmail','WRITE','ALLOW','ROLE','employee'),(404,'Receipt','balanceCompensationPdf','READ','ALLOW','ROLE','employee'),(405,'Ticket','getTicketsFuture','READ','ALLOW','ROLE','employee'),(406,'Ticket','merge','WRITE','ALLOW','ROLE','employee'),(407,'Sale','editFloramondo','WRITE','ALLOW','ROLE','logistic'),(408,'ZipConfig','*','*','ALLOW','ROLE','employee'),(409,'Item','*','WRITE','ALLOW','ROLE','administrative'),(410,'Sale','editCloned','WRITE','ALLOW','ROLE','buyer'),(411,'Sale','editCloned','WRITE','ALLOW','ROLE','salesAssistant'),(414,'MdbVersion','*','READ','ALLOW','ROLE','$everyone'),(416,'TicketLog','getChanges','READ','ALLOW','ROLE','employee'),(417,'Ticket','getTicketsAdvance','READ','ALLOW','ROLE','employee'),(418,'EntryLog','*','READ','ALLOW','ROLE','administrative'),(419,'Sale','editTracked','WRITE','ALLOW','ROLE','buyer'),(420,'MdbBranch','*','READ','ALLOW','ROLE','$everyone'),(421,'ItemShelvingSale','*','*','ALLOW','ROLE','employee'),(422,'Docuware','checkFile','READ','ALLOW','ROLE','employee'),(423,'Docuware','download','READ','ALLOW','ROLE','salesPerson'),(424,'Docuware','upload','WRITE','ALLOW','ROLE','productionAssi'),(425,'Docuware','deliveryNoteEmail','WRITE','ALLOW','ROLE','salesPerson'),(426,'TpvTransaction','confirm','WRITE','ALLOW','ROLE','$everyone'),(427,'TpvTransaction','start','WRITE','ALLOW','ROLE','$authenticated'),(428,'TpvTransaction','end','WRITE','ALLOW','ROLE','$authenticated'),(429,'ItemConfig','*','READ','ALLOW','ROLE','employee'),(431,'Tag','onSubmit','WRITE','ALLOW','ROLE','employee'),(432,'Worker','updateAttributes','WRITE','ALLOW','ROLE','hr'),(433,'Worker','createAbsence','*','ALLOW','ROLE','employee'),(434,'Worker','updateAbsence','WRITE','ALLOW','ROLE','employee'),(435,'Worker','deleteAbsence','*','ALLOW','ROLE','employee'),(436,'Worker','new','WRITE','ALLOW','ROLE','hr'),(438,'Client','getClientOrSupplierReference','READ','ALLOW','ROLE','employee'),(439,'NotificationSubscription','*','*','ALLOW','ROLE','employee'),(440,'NotificationAcl','*','READ','ALLOW','ROLE','employee'),(441,'MdbApp','*','READ','ALLOW','ROLE','$everyone'),(442,'MdbApp','*','*','ALLOW','ROLE','developer'),(443,'ItemConfig','*','*','ALLOW','ROLE','employee'),(444,'DeviceProduction','*','*','ALLOW','ROLE','hr'),(445,'DeviceProductionModels','*','*','ALLOW','ROLE','hr'),(446,'DeviceProductionState','*','*','ALLOW','ROLE','hr'),(447,'DeviceProductionUser','*','*','ALLOW','ROLE','hr'),(448,'DeviceProduction','*','*','ALLOW','ROLE','productionAssi'),(449,'DeviceProductionModels','*','*','ALLOW','ROLE','productionAssi'),(450,'DeviceProductionState','*','*','ALLOW','ROLE','productionAssi'),(451,'DeviceProductionUser','*','*','ALLOW','ROLE','productionAssi'),(452,'Worker','deallocatePDA','*','ALLOW','ROLE','hr'),(453,'Worker','allocatePDA','*','ALLOW','ROLE','hr'),(454,'Worker','deallocatePDA','*','ALLOW','ROLE','productionAssi'),(455,'Worker','allocatePDA','*','ALLOW','ROLE','productionAssi'),(456,'Zone','*','*','ALLOW','ROLE','deliveryBoss'),(457,'Account','setPassword','WRITE','ALLOW','ROLE','itManagement'),(458,'Operator','*','READ','ALLOW','ROLE','employee'),(459,'Operator','*','WRITE','ALLOW','ROLE','employee'),(460,'InvoiceIn','getSerial','READ','ALLOW','ROLE','administrative'),(461,'Ticket','saveSign','WRITE','ALLOW','ROLE','employee'),(462,'InvoiceOut','negativeBases','READ','ALLOW','ROLE','administrative'),(463,'InvoiceOut','negativeBasesCsv','READ','ALLOW','ROLE','administrative'),(464,'WorkerObservation','*','*','ALLOW','ROLE','hr'),(465,'ClientInforma','*','READ','ALLOW','ROLE','employee'),(466,'ClientInforma','*','WRITE','ALLOW','ROLE','financial'),(467,'Receipt','receiptEmail','*','ALLOW','ROLE','salesAssistant'),(468,'Client','setRating','WRITE','ALLOW','ROLE','financial'),(469,'Client','*','READ','ALLOW','ROLE','employee'),(470,'Client','addressesPropagateRe','*','ALLOW','ROLE','employee'),(471,'Client','canBeInvoiced','*','ALLOW','ROLE','employee'),(472,'Client','canCreateTicket','*','ALLOW','ROLE','employee'),(473,'Client','consumption','*','ALLOW','ROLE','employee'),(474,'Client','createAddress','*','ALLOW','ROLE','employee'),(475,'Client','createWithUser','*','ALLOW','ROLE','employee'),(476,'Client','extendedListFilter','*','ALLOW','ROLE','employee'),(477,'Client','getAverageInvoiced','*','ALLOW','ROLE','employee'),(478,'Client','getCard','*','ALLOW','ROLE','employee'),(479,'Client','getDebt','*','ALLOW','ROLE','employee'),(480,'Client','getMana','*','ALLOW','ROLE','employee'),(481,'Client','transactions','*','ALLOW','ROLE','employee'),(482,'Client','hasCustomerRole','*','ALLOW','ROLE','employee'),(483,'Client','isValidClient','*','ALLOW','ROLE','employee'),(484,'Client','lastActiveTickets','*','ALLOW','ROLE','employee'),(485,'Client','sendSms','*','ALLOW','ROLE','employee'),(486,'Client','setPassword','*','ALLOW','ROLE','employee'),(487,'Client','summary','*','ALLOW','ROLE','employee'),(488,'Client','updateAddress','*','ALLOW','ROLE','employee'),(489,'Client','updateFiscalData','*','ALLOW','ROLE','employee'),(491,'Client','uploadFile','*','ALLOW','ROLE','employee'),(492,'Client','campaignMetricsPdf','*','ALLOW','ROLE','employee'),(493,'Client','campaignMetricsEmail','*','ALLOW','ROLE','employee'),(494,'Client','clientWelcomeHtml','*','ALLOW','ROLE','employee'),(495,'Client','clientWelcomeEmail','*','ALLOW','ROLE','employee'),(496,'Client','printerSetupHtml','*','ALLOW','ROLE','employee'),(497,'Client','printerSetupEmail','*','ALLOW','ROLE','employee'),(498,'Client','sepaCoreEmail','*','ALLOW','ROLE','employee'),(499,'Client','letterDebtorPdf','*','ALLOW','ROLE','employee'),(500,'Client','letterDebtorStHtml','*','ALLOW','ROLE','employee'),(501,'Client','letterDebtorStEmail','*','ALLOW','ROLE','employee'),(502,'Client','letterDebtorNdHtml','*','ALLOW','ROLE','employee'),(503,'Client','letterDebtorNdEmail','*','ALLOW','ROLE','employee'),(504,'Client','clientDebtStatementPdf','*','ALLOW','ROLE','employee'),(505,'Client','clientDebtStatementHtml','*','ALLOW','ROLE','employee'),(506,'Client','clientDebtStatementEmail','*','ALLOW','ROLE','employee'),(507,'Client','creditRequestPdf','*','ALLOW','ROLE','employee'),(508,'Client','creditRequestHtml','*','ALLOW','ROLE','employee'),(509,'Client','creditRequestEmail','*','ALLOW','ROLE','employee'),(510,'Client','incotermsAuthorizationPdf','*','ALLOW','ROLE','employee'),(511,'Client','incotermsAuthorizationHtml','*','ALLOW','ROLE','employee'),(512,'Client','incotermsAuthorizationEmail','*','ALLOW','ROLE','employee'),(513,'Client','consumptionSendQueued','*','ALLOW','ROLE','employee'),(514,'Client','filter','*','ALLOW','ROLE','employee'),(515,'Client','getClientOrSupplierReference','*','ALLOW','ROLE','employee'),(516,'Client','upsert','*','ALLOW','ROLE','employee'),(517,'Client','create','*','ALLOW','ROLE','employee'),(518,'Client','replaceById','*','ALLOW','ROLE','employee'),(519,'Client','updateAttributes','*','ALLOW','ROLE','employee'),(520,'Client','updateAttributes','*','ALLOW','ROLE','employee'),(521,'Client','deleteById','*','ALLOW','ROLE','employee'),(522,'Client','replaceOrCreate','*','ALLOW','ROLE','employee'),(523,'Client','updateAll','*','ALLOW','ROLE','employee'),(524,'Client','upsertWithWhere','*','ALLOW','ROLE','employee'),(525,'Defaulter','observationEmail','WRITE','ALLOW','ROLE','employee'),(527,'VnUser','acl','READ','ALLOW','ROLE','account'),(528,'VnUser','getCurrentUserData','READ','ALLOW','ROLE','account'),(530,'Account','exists','READ','ALLOW','ROLE','account'),(531,'Account','exists','READ','ALLOW','ROLE','account'),(532,'UserLog','*','READ','ALLOW','ROLE','employee'),(533,'RoleLog','*','READ','ALLOW','ROLE','employee'),(534,'WagonType','*','*','ALLOW','ROLE','productionAssi'),(535,'WagonTypeColor','*','*','ALLOW','ROLE','productionAssi'),(536,'WagonTypeTray','*','*','ALLOW','ROLE','productionAssi'),(537,'WagonConfig','*','*','ALLOW','ROLE','productionAssi'),(538,'CollectionWagon','*','*','ALLOW','ROLE','productionAssi'),(539,'CollectionWagonTicket','*','*','ALLOW','ROLE','productionAssi'),(540,'Wagon','*','*','ALLOW','ROLE','productionAssi'),(541,'WagonType','createWagonType','*','ALLOW','ROLE','productionAssi'),(542,'WagonType','deleteWagonType','*','ALLOW','ROLE','productionAssi'),(543,'WagonType','editWagonType','*','ALLOW','ROLE','productionAssi'),(544,'Docuware','deliveryNoteEmail','WRITE','ALLOW','ROLE','employee'),(545,'Agency','find','READ','ALLOW','ROLE','employee'),(546,'Agency','seeExpired','READ','ALLOW','ROLE','coolerAssist'),(547,'WorkerLog','models','READ','ALLOW','ROLE','hr'),(548,'Ticket','editDiscount','WRITE','ALLOW','ROLE','claimManager'),(549,'Ticket','editDiscount','WRITE','ALLOW','ROLE','salesPerson'),(550,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','salesAssistant'),(551,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','deliveryBoss'),(552,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','buyer'),(553,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','claimManager'),(554,'Ticket','deleteTicketWithPartPrepared','WRITE','ALLOW','ROLE','salesAssistant'),(555,'Ticket','editZone','WRITE','ALLOW','ROLE','deliveryBoss'),(556,'State','editableStates','READ','ALLOW','ROLE','employee'),(557,'State','seeEditableStates','READ','ALLOW','ROLE','administrative'),(558,'State','seeEditableStates','READ','ALLOW','ROLE','production'),(559,'State','isSomeEditable','READ','ALLOW','ROLE','salesPerson'),(560,'State','isAllEditable','READ','ALLOW','ROLE','production'),(561,'State','isAllEditable','READ','ALLOW','ROLE','administrative'),(562,'Agency','seeExpired','READ','ALLOW','ROLE','administrative'),(563,'Agency','seeExpired','READ','ALLOW','ROLE','productionBoss'),(564,'Claim','createAfterDeadline','WRITE','ALLOW','ROLE','claimManager'),(565,'Client','editAddressLogifloraAllowed','WRITE','ALLOW','ROLE','salesAssistant'),(566,'Client','editFiscalDataWithoutTaxDataCheck','WRITE','ALLOW','ROLE','salesAssistant'),(567,'Client','editVerifiedDataWithoutTaxDataCheck','WRITE','ALLOW','ROLE','salesAssistant'),(568,'Client','editCredit','WRITE','ALLOW','ROLE','financialBoss'),(569,'Client','zeroCreditEditor','WRITE','ALLOW','ROLE','financialBoss'),(570,'InvoiceOut','canCreatePdf','WRITE','ALLOW','ROLE','invoicing'),(571,'Supplier','editPayMethodCheck','WRITE','ALLOW','ROLE','financial'),(572,'Worker','isTeamBoss','WRITE','ALLOW','ROLE','teamBoss'),(573,'Worker','forceIsSubordinate','READ','ALLOW','ROLE','hr'),(574,'Claim','editState','WRITE','ALLOW','ROLE','claimManager'),(575,'Claim','find','READ','ALLOW','ROLE','salesPerson'),(576,'Claim','findById','READ','ALLOW','ROLE','salesPerson'),(577,'Claim','findOne','READ','ALLOW','ROLE','salesPerson'),(578,'Claim','getSummary','READ','ALLOW','ROLE','salesPerson'),(579,'Claim','updateClaim','WRITE','ALLOW','ROLE','salesPerson'),(580,'Claim','regularizeClaim','WRITE','ALLOW','ROLE','claimManager'),(581,'Claim','updateClaimDestination','WRITE','ALLOW','ROLE','claimManager'),(582,'Claim','downloadFile','READ','ALLOW','ROLE','claimManager'),(583,'Claim','deleteById','WRITE','ALLOW','ROLE','claimManager'),(584,'Claim','filter','READ','ALLOW','ROLE','salesPerson'),(585,'Claim','logs','READ','ALLOW','ROLE','claimManager'),(586,'Ticket','find','READ','ALLOW','ROLE','employee'),(587,'Ticket','findById','READ','ALLOW','ROLE','employee'),(588,'Ticket','findOne','READ','ALLOW','ROLE','employee'),(589,'Ticket','getVolume','READ','ALLOW','ROLE','employee'),(590,'Ticket','getTotalVolume','READ','ALLOW','ROLE','employee'),(591,'Ticket','summary','READ','ALLOW','ROLE','employee'),(592,'Ticket','priceDifference','READ','ALLOW','ROLE','employee'),(593,'Ticket','componentUpdate','WRITE','ALLOW','ROLE','employee'),(594,'Ticket','new','WRITE','ALLOW','ROLE','employee'),(595,'Ticket','isEditable','READ','ALLOW','ROLE','employee'),(596,'Ticket','setDeleted','WRITE','ALLOW','ROLE','salesPerson'),(597,'Ticket','restore','WRITE','ALLOW','ROLE','employee'),(598,'Ticket','getSales','READ','ALLOW','ROLE','employee'),(599,'Ticket','getSalesPersonMana','READ','ALLOW','ROLE','employee'),(600,'Ticket','filter','READ','ALLOW','ROLE','employee'),(601,'Ticket','makeInvoice','WRITE','ALLOW','ROLE','employee'),(602,'Ticket','updateEditableTicket','WRITE','ALLOW','ROLE','employee'),(603,'Ticket','updateDiscount','WRITE','ALLOW','ROLE','employee'),(604,'Ticket','transferSales','WRITE','ALLOW','ROLE','employee'),(605,'Ticket','sendSms','WRITE','ALLOW','ROLE','employee'),(606,'Ticket','isLocked','READ','ALLOW','ROLE','employee'),(607,'Ticket','freightCost','READ','ALLOW','ROLE','employee'),(608,'Ticket','getComponentsSum','READ','ALLOW','ROLE','employee'),(609,'Ticket','updateAttributes','WRITE','ALLOW','ROLE','delivery'),(610,'Ticket','deliveryNoteCsv','READ','ALLOW','ROLE','employee'),(611,'State','find','READ','ALLOW','ROLE','employee'),(612,'State','findById','READ','ALLOW','ROLE','employee'),(613,'State','findOne','READ','ALLOW','ROLE','employee'),(614,'Worker','find','READ','ALLOW','ROLE','employee'),(615,'Worker','findById','READ','ALLOW','ROLE','employee'),(616,'Worker','findOne','READ','ALLOW','ROLE','employee'),(617,'Worker','filter','READ','ALLOW','ROLE','employee'),(618,'Worker','getWorkedHours','READ','ALLOW','ROLE','employee'),(619,'Worker','active','READ','ALLOW','ROLE','employee'),(620,'Worker','activeWithRole','READ','ALLOW','ROLE','employee'),(621,'Worker','uploadFile','WRITE','ALLOW','ROLE','hr'),(622,'Worker','contracts','READ','ALLOW','ROLE','employee'),(623,'Worker','holidays','READ','ALLOW','ROLE','employee'),(624,'Worker','activeContract','READ','ALLOW','ROLE','employee'),(625,'Worker','activeWithInheritedRole','READ','ALLOW','ROLE','employee'),(626,'Ticket','collectionLabel','READ','ALLOW','ROLE','employee'),(628,'Ticket','expeditionPalletLabel','READ','ALLOW','ROLE','employee'),(629,'Ticket','editDiscount','WRITE','ALLOW','ROLE','artificialBoss'),(630,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','salesTeamBoss'),(635,'Ticket','updateAttributes','WRITE','ALLOW','ROLE','administrative'),(636,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','salesPerson'),(637,'Claim','downloadFile','READ','ALLOW','ROLE','salesPerson'),(638,'Agency','seeExpired','READ','ALLOW','ROLE','artificialBoss'),(639,'Agency','seeExpired','READ','ALLOW','ROLE','logisticAssistant'),(640,'Claim','filter','READ','ALLOW','ROLE','buyer'),(641,'Claim','find','READ','ALLOW','ROLE','buyer'),(642,'Claim','findById','READ','ALLOW','ROLE','buyer'),(643,'Claim','getSummary','READ','ALLOW','ROLE','buyer'),(644,'Claim','filter','READ','ALLOW','ROLE','handmadeBoss'),(645,'Claim','find','READ','ALLOW','ROLE','handmadeBoss'),(646,'Claim','findById','READ','ALLOW','ROLE','handmadeBoss'),(647,'Claim','getSummary','READ','ALLOW','ROLE','handmadeBoss'),(648,'Claim','__get__lines','READ','ALLOW','ROLE','claimManager'),(649,'Claim','__get__lines','READ','ALLOW','ROLE','salesPerson'),(650,'Claim','getSummary','READ','ALLOW','ROLE','deliveryBoss'),(651,'Claim','findById','READ','ALLOW','ROLE','deliveryBoss'),(652,'Claim','find','READ','ALLOW','ROLE','deliveryBoss'),(653,'Claim','filter','READ','ALLOW','ROLE','deliveryBoss'),(654,'Ticket','editZone','WRITE','ALLOW','ROLE','logisticAssistant'),(655,'Entry','addFromPackaging','WRITE','ALLOW','ROLE','production'),(656,'Entry','addFromBuy','WRITE','ALLOW','ROLE','production'),(657,'Supplier','getItemsPackaging','READ','ALLOW','ROLE','production'),(658,'Ticket','closeAll','WRITE','ALLOW','ROLE','system'),(659,'Account','*','*','ALLOW','ROLE','itManagement'),(660,'Account','*','READ','ALLOW','ROLE','employee'),(664,'MailForward','*','*','ALLOW','ROLE','itManagement'),(665,'Role','*','READ','ALLOW','ROLE','employee'),(666,'Role','*','WRITE','ALLOW','ROLE','it'),(667,'VnUser','*','*','ALLOW','ROLE','itManagement'),(668,'VnUser','__get__preview','READ','ALLOW','ROLE','employee'),(669,'VnUser','preview','*','ALLOW','ROLE','employee'),(670,'VnUser','create','*','ALLOW','ROLE','itManagement'),(671,'VnUser','renewToken','WRITE','ALLOW','ROLE','employee'),(672,'PackingSiteAdvanced','*','*','ALLOW','ROLE','production'),(673,'InvoiceOut','makePdfAndNotify','WRITE','ALLOW','ROLE','invoicing'),(674,'InvoiceOutConfig','*','READ','ALLOW','ROLE','invoicing'),(676,'Ticket','invoiceTickets','WRITE','ALLOW','ROLE','employee'),(680,'MailAliasAccount','*','READ','ALLOW','ROLE','employee'),(681,'MailAliasAccount','create','WRITE','ALLOW','ROLE','employee'),(682,'MailAliasAccount','deleteById','WRITE','ALLOW','ROLE','employee'),(683,'MailAliasAccount','canEditAlias','WRITE','ALLOW','ROLE','itManagement'),(684,'WorkerDisableExcluded','*','READ','ALLOW','ROLE','itManagement'),(685,'WorkerDisableExcluded','*','WRITE','ALLOW','ROLE','itManagement'),(686,'MailForward','*','*','ALLOW','ROLE','hr'),(687,'ClientSms','find','READ','ALLOW','ROLE','employee'),(688,'ClientSms','create','WRITE','ALLOW','ROLE','employee'),(689,'Vehicle','sorted','WRITE','ALLOW','ROLE','employee'),(690,'Roadmap','*','*','ALLOW','ROLE','palletizerBoss'),(691,'Roadmap','*','*','ALLOW','ROLE','productionBoss'),(692,'ExpeditionTruck','*','*','ALLOW','ROLE','palletizerBoss'),(693,'ExpeditionTruck','*','*','ALLOW','ROLE','productionBoss'),(694,'MailAliasAccount','canEditAlias','WRITE','ALLOW','ROLE','marketingBoss'),(695,'ViaexpressConfig','internationalExpedition','WRITE','ALLOW','ROLE','employee'),(696,'ViaexpressConfig','renderer','READ','ALLOW','ROLE','employee'),(697,'Ticket','transferClient','WRITE','ALLOW','ROLE','administrative'),(698,'Ticket','canEditWeekly','WRITE','ALLOW','ROLE','buyer'),(699,'TicketSms','find','READ','ALLOW','ROLE','salesPerson'),(701,'Docuware','upload','WRITE','ALLOW','ROLE','deliveryBoss'),(702,'Ticket','docuwareDownload','READ','ALLOW','ROLE','salesPerson'); +INSERT INTO `ACL` VALUES (3,'Address','*','*','ALLOW','ROLE','employee'),(5,'AgencyService','*','READ','ALLOW','ROLE','employee'),(9,'ClientObservation','*','*','ALLOW','ROLE','employee'),(11,'ContactChannel','*','READ','ALLOW','ROLE','trainee'),(13,'Employee','*','READ','ALLOW','ROLE','employee'),(14,'PayMethod','*','READ','ALLOW','ROLE','trainee'),(16,'FakeProduction','*','READ','ALLOW','ROLE','employee'),(17,'Warehouse','* ','READ','ALLOW','ROLE','trainee'),(20,'TicketState','*','*','ALLOW','ROLE','employee'),(24,'Delivery','*','READ','ALLOW','ROLE','employee'),(25,'Zone','*','READ','ALLOW','ROLE','employee'),(26,'ClientCredit','*','*','ALLOW','ROLE','employee'),(27,'ClientCreditLimit','*','READ','ALLOW','ROLE','trainee'),(30,'GreugeType','*','READ','ALLOW','ROLE','trainee'),(31,'Mandate','*','READ','ALLOW','ROLE','trainee'),(32,'MandateType','*','READ','ALLOW','ROLE','trainee'),(33,'Company','*','READ','ALLOW','ROLE','trainee'),(34,'Greuge','*','READ','ALLOW','ROLE','trainee'),(35,'AddressObservation','*','*','ALLOW','ROLE','employee'),(36,'ObservationType','*','*','ALLOW','ROLE','employee'),(37,'Greuge','*','WRITE','ALLOW','ROLE','employee'),(38,'AgencyMode','*','READ','ALLOW','ROLE','employee'),(39,'ItemTag','*','WRITE','ALLOW','ROLE','buyer'),(40,'ItemBotanical','*','WRITE','ALLOW','ROLE','buyer'),(41,'ItemBotanical','*','READ','ALLOW','ROLE','employee'),(42,'ItemPlacement','*','WRITE','ALLOW','ROLE','buyer'),(43,'ItemPlacement','*','WRITE','ALLOW','ROLE','replenisher'),(44,'ItemPlacement','*','READ','ALLOW','ROLE','employee'),(45,'ItemBarcode','*','READ','ALLOW','ROLE','employee'),(46,'ItemBarcode','*','WRITE','ALLOW','ROLE','buyer'),(47,'ItemBarcode','*','WRITE','ALLOW','ROLE','replenisher'),(51,'ItemTag','*','READ','ALLOW','ROLE','employee'),(53,'Item','*','READ','ALLOW','ROLE','employee'),(54,'Item','*','WRITE','ALLOW','ROLE','buyer'),(55,'Recovery','*','READ','ALLOW','ROLE','trainee'),(56,'Recovery','*','WRITE','ALLOW','ROLE','administrative'),(58,'CreditClassification','*','*','ALLOW','ROLE','insurance'),(60,'CreditInsurance','*','*','ALLOW','ROLE','insurance'),(61,'InvoiceOut','*','READ','ALLOW','ROLE','employee'),(63,'TicketObservation','*','*','ALLOW','ROLE','employee'),(64,'Route','*','READ','ALLOW','ROLE','employee'),(65,'Sale','*','READ','ALLOW','ROLE','employee'),(66,'TicketTracking','*','READ','ALLOW','ROLE','employee'),(68,'TicketPackaging','*','*','ALLOW','ROLE','employee'),(69,'Packaging','*','READ','ALLOW','ROLE','employee'),(70,'Packaging','*','WRITE','ALLOW','ROLE','logistic'),(72,'SaleComponent','*','READ','ALLOW','ROLE','employee'),(73,'Expedition','*','READ','ALLOW','ROLE','employee'),(74,'Expedition','*','WRITE','ALLOW','ROLE','deliveryAssistant'),(75,'Expedition','*','WRITE','ALLOW','ROLE','production'),(76,'AnnualAverageInvoiced','*','READ','ALLOW','ROLE','employee'),(77,'WorkerMana','*','READ','ALLOW','ROLE','employee'),(78,'TicketTracking','*','WRITE','ALLOW','ROLE','production'),(79,'TicketTracking','changeState','*','ALLOW','ROLE','employee'),(80,'Sale','deleteSales','*','ALLOW','ROLE','employee'),(81,'Sale','moveToTicket','*','ALLOW','ROLE','employee'),(82,'Sale','updateQuantity','*','ALLOW','ROLE','employee'),(83,'Sale','updatePrice','*','ALLOW','ROLE','employee'),(84,'Sale','updateDiscount','*','ALLOW','ROLE','employee'),(85,'SaleTracking','*','READ','ALLOW','ROLE','employee'),(86,'Order','*','*','ALLOW','ROLE','employee'),(87,'OrderRow','*','*','ALLOW','ROLE','employee'),(88,'ClientContact','*','*','ALLOW','ROLE','employee'),(89,'Sale','moveToNewTicket','*','ALLOW','ROLE','employee'),(90,'Sale','reserve','*','ALLOW','ROLE','employee'),(91,'TicketWeekly','*','READ','ALLOW','ROLE','employee'),(94,'Agency','landsThatDay','*','ALLOW','ROLE','employee'),(96,'ClaimEnd','*','READ','ALLOW','ROLE','employee'),(97,'ClaimEnd','*','WRITE','ALLOW','ROLE','claimManager'),(98,'ClaimBeginning','*','*','ALLOW','ROLE','employee'),(99,'ClaimDevelopment','*','READ','ALLOW','ROLE','employee'),(100,'ClaimDevelopment','*','WRITE','ALLOW','ROLE','claimManager'),(102,'Claim','createFromSales','*','ALLOW','ROLE','employee'),(104,'Item','*','WRITE','ALLOW','ROLE','marketingBoss'),(105,'ItemBarcode','*','WRITE','ALLOW','ROLE','marketingBoss'),(106,'ItemBotanical','*','WRITE','ALLOW','ROLE','marketingBoss'),(108,'ItemPlacement','*','WRITE','ALLOW','ROLE','marketingBoss'),(109,'UserConfig','*','*','ALLOW','ROLE','employee'),(110,'Bank','*','READ','ALLOW','ROLE','trainee'),(111,'ClientLog','*','READ','ALLOW','ROLE','trainee'),(112,'Defaulter','*','READ','ALLOW','ROLE','employee'),(113,'ClientRisk','*','READ','ALLOW','ROLE','trainee'),(114,'Receipt','*','READ','ALLOW','ROLE','trainee'),(115,'Receipt','*','WRITE','ALLOW','ROLE','administrative'),(116,'BankEntity','*','*','ALLOW','ROLE','employee'),(117,'ClientSample','*','*','ALLOW','ROLE','employee'),(118,'WorkerTeam','*','*','ALLOW','ROLE','salesPerson'),(119,'Travel','*','READ','ALLOW','ROLE','employee'),(120,'Travel','*','WRITE','ALLOW','ROLE','buyer'),(121,'Item','regularize','*','ALLOW','ROLE','employee'),(122,'TicketRequest','*','*','ALLOW','ROLE','employee'),(124,'Client','confirmTransaction','WRITE','ALLOW','ROLE','administrative'),(125,'Agency','getAgenciesWithWarehouse','*','ALLOW','ROLE','employee'),(126,'Client','activeWorkersWithRole','*','ALLOW','ROLE','employee'),(127,'TicketLog','*','READ','ALLOW','ROLE','employee'),(129,'TicketService','*','*','ALLOW','ROLE','employee'),(130,'Expedition','*','WRITE','ALLOW','ROLE','packager'),(131,'CreditInsurance','*','READ','ALLOW','ROLE','trainee'),(132,'CreditClassification','*','READ','ALLOW','ROLE','trainee'),(133,'ItemTag','*','WRITE','ALLOW','ROLE','marketingBoss'),(135,'ZoneGeo','*','READ','ALLOW','ROLE','employee'),(136,'ZoneCalendar','*','READ','ALLOW','ROLE','employee'),(137,'ZoneIncluded','*','READ','ALLOW','ROLE','employee'),(138,'LabourHoliday','*','READ','ALLOW','ROLE','employee'),(139,'LabourHolidayLegend','*','READ','ALLOW','ROLE','employee'),(140,'LabourHolidayType','*','READ','ALLOW','ROLE','employee'),(141,'Zone','*','*','ALLOW','ROLE','logisticBoss'),(142,'ZoneCalendar','*','WRITE','ALLOW','ROLE','deliveryAssistant'),(143,'ZoneIncluded','*','*','ALLOW','ROLE','deliveryAssistant'),(144,'Stowaway','*','*','ALLOW','ROLE','employee'),(145,'Ticket','getPossibleStowaways','READ','ALLOW','ROLE','employee'),(147,'UserConfigView','*','*','ALLOW','ROLE','employee'),(148,'UserConfigView','*','*','ALLOW','ROLE','employee'),(149,'Sip','*','READ','ALLOW','ROLE','employee'),(150,'Sip','*','WRITE','ALLOW','ROLE','hr'),(151,'Department','*','READ','ALLOW','ROLE','employee'),(152,'Department','*','WRITE','ALLOW','ROLE','hr'),(153,'Route','*','READ','ALLOW','ROLE','employee'),(154,'Route','*','WRITE','ALLOW','ROLE','delivery'),(155,'Calendar','*','READ','ALLOW','ROLE','hr'),(156,'WorkerLabour','*','READ','ALLOW','ROLE','hr'),(157,'Calendar','absences','READ','ALLOW','ROLE','employee'),(158,'ItemTag','*','WRITE','ALLOW','ROLE','accessory'),(160,'TicketServiceType','*','READ','ALLOW','ROLE','employee'),(161,'TicketConfig','*','READ','ALLOW','ROLE','employee'),(162,'InvoiceOut','delete','WRITE','ALLOW','ROLE','invoicing'),(163,'InvoiceOut','book','WRITE','ALLOW','ROLE','invoicing'),(165,'TicketDms','*','*','ALLOW','ROLE','employee'),(167,'Worker','isSubordinate','READ','ALLOW','ROLE','employee'),(168,'Worker','mySubordinates','READ','ALLOW','ROLE','employee'),(169,'WorkerTimeControl','filter','READ','ALLOW','ROLE','employee'),(170,'WorkerTimeControl','addTime','WRITE','ALLOW','ROLE','employee'),(171,'TicketServiceType','*','WRITE','ALLOW','ROLE','administrative'),(172,'Sms','*','READ','ALLOW','ROLE','employee'),(173,'Sms','send','WRITE','ALLOW','ROLE','employee'),(176,'Device','*','*','ALLOW','ROLE','employee'),(177,'Device','*','*','ALLOW','ROLE','employee'),(178,'WorkerTimeControl','*','*','ALLOW','ROLE','employee'),(179,'ItemLog','*','READ','ALLOW','ROLE','employee'),(180,'RouteLog','*','READ','ALLOW','ROLE','employee'),(181,'Dms','removeFile','WRITE','ALLOW','ROLE','employee'),(182,'Dms','uploadFile','WRITE','ALLOW','ROLE','employee'),(183,'Dms','downloadFile','READ','ALLOW','ROLE','employee'),(184,'Client','uploadFile','WRITE','ALLOW','ROLE','employee'),(185,'ClientDms','removeFile','WRITE','ALLOW','ROLE','employee'),(186,'ClientDms','*','READ','ALLOW','ROLE','trainee'),(187,'Ticket','uploadFile','WRITE','ALLOW','ROLE','employee'),(190,'Route','updateVolume','WRITE','ALLOW','ROLE','deliveryAssistant'),(191,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(192,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(194,'Postcode','*','WRITE','ALLOW','ROLE','deliveryAssistant'),(195,'Ticket','addSale','WRITE','ALLOW','ROLE','employee'),(196,'Dms','updateFile','WRITE','ALLOW','ROLE','employee'),(197,'Dms','*','READ','ALLOW','ROLE','trainee'),(198,'ClaimDms','removeFile','WRITE','ALLOW','ROLE','employee'),(199,'ClaimDms','*','READ','ALLOW','ROLE','employee'),(200,'Claim','uploadFile','WRITE','ALLOW','ROLE','employee'),(201,'Sale','updateConcept','WRITE','ALLOW','ROLE','employee'),(202,'Claim','updateClaimAction','WRITE','ALLOW','ROLE','claimManager'),(203,'UserPhone','*','*','ALLOW','ROLE','employee'),(204,'WorkerDms','removeFile','WRITE','ALLOW','ROLE','hr'),(205,'WorkerDms','*','READ','ALLOW','ROLE','hr'),(206,'Chat','*','*','ALLOW','ROLE','employee'),(207,'Chat','sendMessage','*','ALLOW','ROLE','employee'),(208,'Sale','recalculatePrice','WRITE','ALLOW','ROLE','employee'),(209,'Ticket','recalculateComponents','WRITE','ALLOW','ROLE','employee'),(211,'TravelLog','*','READ','ALLOW','ROLE','buyer'),(212,'Thermograph','*','*','ALLOW','ROLE','buyer'),(213,'TravelThermograph','*','WRITE','ALLOW','ROLE','buyer'),(214,'Entry','*','*','ALLOW','ROLE','buyer'),(215,'TicketWeekly','*','WRITE','ALLOW','ROLE','buyer'),(216,'TravelThermograph','*','READ','ALLOW','ROLE','employee'),(218,'Intrastat','*','*','ALLOW','ROLE','buyer'),(221,'UserConfig','getUserConfig','READ','ALLOW','ROLE','account'),(222,'Client','*','READ','ALLOW','ROLE','trainee'),(226,'ClientObservation','*','READ','ALLOW','ROLE','trainee'),(227,'Address','*','READ','ALLOW','ROLE','trainee'),(228,'AddressObservation','*','READ','ALLOW','ROLE','trainee'),(230,'ClientCredit','*','READ','ALLOW','ROLE','trainee'),(231,'ClientContact','*','READ','ALLOW','ROLE','trainee'),(232,'ClientSample','*','READ','ALLOW','ROLE','trainee'),(233,'EntryLog','*','READ','ALLOW','ROLE','buyer'),(234,'WorkerLog','find','READ','ALLOW','ROLE','hr'),(235,'CustomsAgent','*','*','ALLOW','ROLE','employee'),(236,'Buy','*','*','ALLOW','ROLE','buyer'),(237,'WorkerDms','filter','*','ALLOW','ROLE','employee'),(238,'Town','*','WRITE','ALLOW','ROLE','deliveryAssistant'),(239,'Province','*','WRITE','ALLOW','ROLE','deliveryAssistant'),(240,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(241,'SupplierContact','*','WRITE','ALLOW','ROLE','administrative'),(242,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(244,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(248,'RoleMapping','*','READ','ALLOW','ROLE','account'),(249,'UserPassword','*','READ','ALLOW','ROLE','account'),(250,'Town','*','WRITE','ALLOW','ROLE','deliveryAssistant'),(251,'Province','*','WRITE','ALLOW','ROLE','deliveryAssistant'),(252,'Supplier','*','READ','ALLOW','ROLE','employee'),(253,'Supplier','*','WRITE','ALLOW','ROLE','administrative'),(254,'SupplierLog','*','READ','ALLOW','ROLE','employee'),(256,'Image','*','WRITE','ALLOW','ROLE','employee'),(257,'FixedPrice','*','*','ALLOW','ROLE','buyer'),(258,'PayDem','*','READ','ALLOW','ROLE','employee'),(259,'Client','createReceipt','*','ALLOW','ROLE','salesAssistant'),(260,'PrintServerQueue','*','WRITE','ALLOW','ROLE','employee'),(261,'SupplierAccount','*','*','ALLOW','ROLE','administrative'),(262,'Entry','*','*','ALLOW','ROLE','administrative'),(263,'InvoiceIn','*','*','ALLOW','ROLE','administrative'),(264,'StarredModule','*','*','ALLOW','ROLE','employee'),(265,'ItemBotanical','*','WRITE','ALLOW','ROLE','logisticBoss'),(266,'ZoneLog','*','READ','ALLOW','ROLE','employee'),(267,'Genus','*','WRITE','ALLOW','ROLE','logisticBoss'),(268,'Specie','*','WRITE','ALLOW','ROLE','logisticBoss'),(269,'InvoiceOut','createPdf','WRITE','ALLOW','ROLE','employee'),(270,'SupplierAddress','*','*','ALLOW','ROLE','employee'),(271,'SalesMonitor','*','*','ALLOW','ROLE','employee'),(272,'InvoiceInLog','*','READ','ALLOW','ROLE','employee'),(273,'InvoiceInTax','*','*','ALLOW','ROLE','administrative'),(274,'InvoiceInLog','*','READ','ALLOW','ROLE','administrative'),(275,'InvoiceOut','createManualInvoice','WRITE','ALLOW','ROLE','invoicing'),(276,'InvoiceOut','globalInvoicing','WRITE','ALLOW','ROLE','invoicing'),(278,'RoleInherit','*','WRITE','ALLOW','ROLE','grant'),(279,'MailAlias','*','*','ALLOW','ROLE','marketing'),(283,'EntryObservation','*','*','ALLOW','ROLE','buyer'),(284,'LdapConfig','*','*','ALLOW','ROLE','sysadmin'),(285,'SambaConfig','*','*','ALLOW','ROLE','sysadmin'),(286,'ACL','*','*','ALLOW','ROLE','developer'),(287,'AccessToken','*','*','ALLOW','ROLE','developer'),(293,'RoleInherit','*','*','ALLOW','ROLE','it'),(294,'RoleRole','*','*','ALLOW','ROLE','it'),(295,'AccountConfig','*','*','ALLOW','ROLE','sysadmin'),(296,'Collection','*','READ','ALLOW','ROLE','employee'),(297,'Sale','refund','WRITE','ALLOW','ROLE','invoicing'),(298,'InvoiceInDueDay','*','*','ALLOW','ROLE','administrative'),(299,'Collection','setSaleQuantity','*','ALLOW','ROLE','employee'),(302,'AgencyTerm','*','*','ALLOW','ROLE','administrative'),(303,'ClaimLog','*','READ','ALLOW','ROLE','claimManager'),(304,'Edi','updateData','WRITE','ALLOW','ROLE','employee'),(305,'EducationLevel','*','*','ALLOW','ROLE','employee'),(306,'InvoiceInIntrastat','*','*','ALLOW','ROLE','employee'),(307,'SupplierAgencyTerm','*','*','ALLOW','ROLE','administrative'),(308,'InvoiceInIntrastat','*','*','ALLOW','ROLE','employee'),(309,'Zone','getZoneClosing','*','ALLOW','ROLE','employee'),(310,'ExpeditionState','*','READ','ALLOW','ROLE','employee'),(311,'Expense','*','READ','ALLOW','ROLE','employee'),(312,'Expense','*','WRITE','ALLOW','ROLE','administrative'),(314,'SupplierActivity','*','READ','ALLOW','ROLE','employee'),(315,'SupplierActivity','*','WRITE','ALLOW','ROLE','administrative'),(316,'Dms','deleteTrashFiles','WRITE','ALLOW','ROLE','employee'),(317,'ClientUnpaid','*','*','ALLOW','ROLE','administrative'),(318,'MdbVersion','*','*','ALLOW','ROLE','developer'),(319,'ItemType','*','READ','ALLOW','ROLE','employee'),(320,'ItemType','*','WRITE','ALLOW','ROLE','buyer'),(321,'InvoiceOut','refund','WRITE','ALLOW','ROLE','invoicing'),(322,'InvoiceOut','refund','WRITE','ALLOW','ROLE','salesAssistant'),(323,'InvoiceOut','refund','WRITE','ALLOW','ROLE','claimManager'),(324,'Ticket','refund','WRITE','ALLOW','ROLE','invoicing'),(325,'Ticket','refund','WRITE','ALLOW','ROLE','salesAssistant'),(326,'Ticket','refund','WRITE','ALLOW','ROLE','claimManager'),(327,'Sale','refund','WRITE','ALLOW','ROLE','salesAssistant'),(328,'Sale','refund','WRITE','ALLOW','ROLE','claimManager'),(329,'TicketRefund','*','WRITE','ALLOW','ROLE','invoicing'),(330,'ClaimObservation','*','WRITE','ALLOW','ROLE','salesPerson'),(331,'ClaimObservation','*','READ','ALLOW','ROLE','salesPerson'),(332,'Client','setPassword','WRITE','ALLOW','ROLE','salesPerson'),(333,'Client','updateUser','WRITE','ALLOW','ROLE','salesPerson'),(334,'ShelvingLog','*','READ','ALLOW','ROLE','employee'),(335,'ZoneExclusionGeo','*','READ','ALLOW','ROLE','employee'),(336,'ZoneExclusionGeo','*','WRITE','ALLOW','ROLE','deliveryAssistant'),(337,'Parking','*','*','ALLOW','ROLE','employee'),(338,'Shelving','*','*','ALLOW','ROLE','employee'),(339,'OsTicket','*','*','ALLOW','ROLE','employee'),(340,'OsTicketConfig','*','*','ALLOW','ROLE','it'),(341,'ClientConsumptionQueue','*','WRITE','ALLOW','ROLE','employee'),(342,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','employee'),(343,'Ticket','deliveryNoteEmail','WRITE','ALLOW','ROLE','employee'),(344,'Ticket','deliveryNoteCsvPdf','READ','ALLOW','ROLE','employee'),(345,'Ticket','deliveryNoteCsvEmail','READ','ALLOW','ROLE','employee'),(346,'Client','campaignMetricsPdf','READ','ALLOW','ROLE','employee'),(347,'Client','campaignMetricsEmail','WRITE','ALLOW','ROLE','employee'),(348,'Client','clientWelcomeHtml','READ','ALLOW','ROLE','employee'),(349,'Client','clientWelcomeEmail','WRITE','ALLOW','ROLE','employee'),(350,'Client','creditRequestPdf','READ','ALLOW','ROLE','employee'),(351,'Client','creditRequestHtml','READ','ALLOW','ROLE','employee'),(352,'Client','creditRequestEmail','WRITE','ALLOW','ROLE','employee'),(353,'Client','printerSetupHtml','READ','ALLOW','ROLE','employee'),(354,'Client','printerSetupEmail','WRITE','ALLOW','ROLE','employee'),(355,'Client','sepaCoreEmail','WRITE','ALLOW','ROLE','employee'),(356,'Client','letterDebtorPdf','READ','ALLOW','ROLE','employee'),(357,'Client','letterDebtorStHtml','READ','ALLOW','ROLE','employee'),(358,'Client','letterDebtorStEmail','WRITE','ALLOW','ROLE','employee'),(359,'Client','letterDebtorNdHtml','READ','ALLOW','ROLE','employee'),(360,'Client','letterDebtorNdEmail','WRITE','ALLOW','ROLE','employee'),(361,'Client','clientDebtStatementPdf','READ','ALLOW','ROLE','employee'),(362,'Client','clientDebtStatementHtml','READ','ALLOW','ROLE','employee'),(363,'Client','clientDebtStatementEmail','WRITE','ALLOW','ROLE','employee'),(364,'Client','incotermsAuthorizationPdf','READ','ALLOW','ROLE','employee'),(365,'Client','incotermsAuthorizationHtml','READ','ALLOW','ROLE','employee'),(366,'Client','incotermsAuthorizationEmail','WRITE','ALLOW','ROLE','employee'),(367,'Client','consumptionSendQueued','WRITE','ALLOW','ROLE','system'),(368,'InvoiceOut','invoiceEmail','WRITE','ALLOW','ROLE','employee'),(369,'InvoiceOut','exportationPdf','READ','ALLOW','ROLE','employee'),(370,'InvoiceOut','sendQueued','WRITE','ALLOW','ROLE','system'),(371,'Ticket','invoiceCsvPdf','READ','ALLOW','ROLE','employee'),(372,'Ticket','invoiceCsvEmail','WRITE','ALLOW','ROLE','employee'),(373,'Supplier','campaignMetricsPdf','READ','ALLOW','ROLE','employee'),(374,'Supplier','campaignMetricsEmail','WRITE','ALLOW','ROLE','employee'),(375,'Travel','extraCommunityPdf','READ','ALLOW','ROLE','employee'),(376,'Travel','extraCommunityEmail','WRITE','ALLOW','ROLE','employee'),(377,'Entry','entryOrderPdf','READ','ALLOW','ROLE','employee'),(378,'OsTicket','osTicketReportEmail','WRITE','ALLOW','ROLE','system'),(379,'Item','buyerWasteEmail','WRITE','ALLOW','ROLE','system'),(380,'Claim','claimPickupPdf','READ','ALLOW','ROLE','employee'),(381,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','claimManager'),(382,'Item','labelPdf','READ','ALLOW','ROLE','employee'),(383,'Sector','*','READ','ALLOW','ROLE','employee'),(384,'Sector','*','WRITE','ALLOW','ROLE','employee'),(385,'Route','driverRoutePdf','READ','ALLOW','ROLE','employee'),(386,'Route','driverRouteEmail','WRITE','ALLOW','ROLE','employee'),(387,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','customer'),(388,'Supplier','newSupplier','WRITE','ALLOW','ROLE','administrative'),(389,'ClaimRma','*','READ','ALLOW','ROLE','claimManager'),(390,'ClaimRma','*','WRITE','ALLOW','ROLE','claimManager'),(391,'Notification','*','WRITE','ALLOW','ROLE','system'),(392,'Boxing','*','*','ALLOW','ROLE','employee'),(393,'Url','*','READ','ALLOW','ROLE','employee'),(394,'Url','*','WRITE','ALLOW','ROLE','it'),(395,'ItemShelving','*','READ','ALLOW','ROLE','employee'),(396,'ItemShelving','*','WRITE','ALLOW','ROLE','production'),(397,'ItemShelvingPlacementSupplyStock','*','READ','ALLOW','ROLE','employee'),(398,'NotificationQueue','*','*','ALLOW','ROLE','employee'),(399,'InvoiceOut','clientsToInvoice','WRITE','ALLOW','ROLE','invoicing'),(400,'InvoiceOut','invoiceClient','WRITE','ALLOW','ROLE','invoicing'),(401,'Sale','editTracked','WRITE','ALLOW','ROLE','production'),(402,'Sale','editFloramondo','WRITE','ALLOW','ROLE','salesAssistant'),(403,'Receipt','balanceCompensationEmail','WRITE','ALLOW','ROLE','employee'),(404,'Receipt','balanceCompensationPdf','READ','ALLOW','ROLE','employee'),(405,'Ticket','getTicketsFuture','READ','ALLOW','ROLE','employee'),(406,'Ticket','merge','WRITE','ALLOW','ROLE','employee'),(407,'Sale','editFloramondo','WRITE','ALLOW','ROLE','logistic'),(408,'ZipConfig','*','*','ALLOW','ROLE','employee'),(409,'Item','*','WRITE','ALLOW','ROLE','administrative'),(410,'Sale','editCloned','WRITE','ALLOW','ROLE','buyer'),(411,'Sale','editCloned','WRITE','ALLOW','ROLE','salesAssistant'),(414,'MdbVersion','*','READ','ALLOW','ROLE','$everyone'),(416,'TicketLog','getChanges','READ','ALLOW','ROLE','employee'),(417,'Ticket','getTicketsAdvance','READ','ALLOW','ROLE','employee'),(418,'EntryLog','*','READ','ALLOW','ROLE','administrative'),(419,'Sale','editTracked','WRITE','ALLOW','ROLE','buyer'),(420,'MdbBranch','*','READ','ALLOW','ROLE','$everyone'),(421,'ItemShelvingSale','*','*','ALLOW','ROLE','employee'),(422,'Docuware','checkFile','READ','ALLOW','ROLE','employee'),(423,'Docuware','download','READ','ALLOW','ROLE','salesPerson'),(424,'Docuware','upload','WRITE','ALLOW','ROLE','productionAssi'),(425,'Docuware','deliveryNoteEmail','WRITE','ALLOW','ROLE','salesPerson'),(426,'TpvTransaction','confirm','WRITE','ALLOW','ROLE','$everyone'),(427,'TpvTransaction','start','WRITE','ALLOW','ROLE','$authenticated'),(428,'TpvTransaction','end','WRITE','ALLOW','ROLE','$authenticated'),(429,'ItemConfig','*','READ','ALLOW','ROLE','employee'),(431,'Tag','onSubmit','WRITE','ALLOW','ROLE','employee'),(432,'Worker','updateAttributes','WRITE','ALLOW','ROLE','hr'),(433,'Worker','createAbsence','*','ALLOW','ROLE','employee'),(434,'Worker','updateAbsence','WRITE','ALLOW','ROLE','employee'),(435,'Worker','deleteAbsence','*','ALLOW','ROLE','employee'),(436,'Worker','new','WRITE','ALLOW','ROLE','hr'),(438,'Client','getClientOrSupplierReference','READ','ALLOW','ROLE','employee'),(439,'NotificationSubscription','*','*','ALLOW','ROLE','employee'),(440,'NotificationAcl','*','READ','ALLOW','ROLE','employee'),(441,'MdbApp','*','READ','ALLOW','ROLE','$everyone'),(442,'MdbApp','*','*','ALLOW','ROLE','developer'),(443,'ItemConfig','*','*','ALLOW','ROLE','employee'),(444,'DeviceProduction','*','*','ALLOW','ROLE','hr'),(445,'DeviceProductionModels','*','*','ALLOW','ROLE','hr'),(446,'DeviceProductionState','*','*','ALLOW','ROLE','hr'),(447,'DeviceProductionUser','*','*','ALLOW','ROLE','hr'),(448,'DeviceProduction','*','*','ALLOW','ROLE','productionAssi'),(449,'DeviceProductionModels','*','*','ALLOW','ROLE','productionAssi'),(450,'DeviceProductionState','*','*','ALLOW','ROLE','productionAssi'),(451,'DeviceProductionUser','*','*','ALLOW','ROLE','productionAssi'),(452,'Worker','deallocatePDA','*','ALLOW','ROLE','hr'),(453,'Worker','allocatePDA','*','ALLOW','ROLE','hr'),(454,'Worker','deallocatePDA','*','ALLOW','ROLE','productionAssi'),(455,'Worker','allocatePDA','*','ALLOW','ROLE','productionAssi'),(456,'Zone','*','*','ALLOW','ROLE','deliveryAssistant'),(457,'Account','setPassword','WRITE','ALLOW','ROLE','itManagement'),(458,'Operator','*','READ','ALLOW','ROLE','employee'),(459,'Operator','*','WRITE','ALLOW','ROLE','employee'),(460,'InvoiceIn','getSerial','READ','ALLOW','ROLE','administrative'),(461,'Ticket','saveSign','WRITE','ALLOW','ROLE','employee'),(462,'InvoiceOut','negativeBases','READ','ALLOW','ROLE','administrative'),(463,'InvoiceOut','negativeBasesCsv','READ','ALLOW','ROLE','administrative'),(464,'WorkerObservation','*','*','ALLOW','ROLE','hr'),(465,'ClientInforma','*','READ','ALLOW','ROLE','employee'),(466,'ClientInforma','*','WRITE','ALLOW','ROLE','financial'),(467,'Receipt','receiptEmail','*','ALLOW','ROLE','salesAssistant'),(468,'Client','setRating','WRITE','ALLOW','ROLE','financial'),(469,'Client','*','READ','ALLOW','ROLE','employee'),(470,'Client','addressesPropagateRe','*','ALLOW','ROLE','employee'),(471,'Client','canBeInvoiced','*','ALLOW','ROLE','employee'),(472,'Client','canCreateTicket','*','ALLOW','ROLE','employee'),(473,'Client','consumption','*','ALLOW','ROLE','employee'),(474,'Client','createAddress','*','ALLOW','ROLE','employee'),(475,'Client','createWithUser','*','ALLOW','ROLE','employee'),(476,'Client','extendedListFilter','*','ALLOW','ROLE','employee'),(477,'Client','getAverageInvoiced','*','ALLOW','ROLE','employee'),(478,'Client','getCard','*','ALLOW','ROLE','employee'),(479,'Client','getDebt','*','ALLOW','ROLE','employee'),(480,'Client','getMana','*','ALLOW','ROLE','employee'),(481,'Client','transactions','*','ALLOW','ROLE','employee'),(482,'Client','hasCustomerRole','*','ALLOW','ROLE','employee'),(483,'Client','isValidClient','*','ALLOW','ROLE','employee'),(484,'Client','lastActiveTickets','*','ALLOW','ROLE','employee'),(485,'Client','sendSms','*','ALLOW','ROLE','employee'),(486,'Client','setPassword','*','ALLOW','ROLE','employee'),(487,'Client','summary','*','ALLOW','ROLE','employee'),(488,'Client','updateAddress','*','ALLOW','ROLE','employee'),(489,'Client','updateFiscalData','*','ALLOW','ROLE','employee'),(491,'Client','uploadFile','*','ALLOW','ROLE','employee'),(492,'Client','campaignMetricsPdf','*','ALLOW','ROLE','employee'),(493,'Client','campaignMetricsEmail','*','ALLOW','ROLE','employee'),(494,'Client','clientWelcomeHtml','*','ALLOW','ROLE','employee'),(495,'Client','clientWelcomeEmail','*','ALLOW','ROLE','employee'),(496,'Client','printerSetupHtml','*','ALLOW','ROLE','employee'),(497,'Client','printerSetupEmail','*','ALLOW','ROLE','employee'),(498,'Client','sepaCoreEmail','*','ALLOW','ROLE','employee'),(499,'Client','letterDebtorPdf','*','ALLOW','ROLE','employee'),(500,'Client','letterDebtorStHtml','*','ALLOW','ROLE','employee'),(501,'Client','letterDebtorStEmail','*','ALLOW','ROLE','employee'),(502,'Client','letterDebtorNdHtml','*','ALLOW','ROLE','employee'),(503,'Client','letterDebtorNdEmail','*','ALLOW','ROLE','employee'),(504,'Client','clientDebtStatementPdf','*','ALLOW','ROLE','employee'),(505,'Client','clientDebtStatementHtml','*','ALLOW','ROLE','employee'),(506,'Client','clientDebtStatementEmail','*','ALLOW','ROLE','employee'),(507,'Client','creditRequestPdf','*','ALLOW','ROLE','employee'),(508,'Client','creditRequestHtml','*','ALLOW','ROLE','employee'),(509,'Client','creditRequestEmail','*','ALLOW','ROLE','employee'),(510,'Client','incotermsAuthorizationPdf','*','ALLOW','ROLE','employee'),(511,'Client','incotermsAuthorizationHtml','*','ALLOW','ROLE','employee'),(512,'Client','incotermsAuthorizationEmail','*','ALLOW','ROLE','employee'),(513,'Client','consumptionSendQueued','*','ALLOW','ROLE','employee'),(514,'Client','filter','*','ALLOW','ROLE','employee'),(515,'Client','getClientOrSupplierReference','*','ALLOW','ROLE','employee'),(516,'Client','upsert','*','ALLOW','ROLE','employee'),(517,'Client','create','*','ALLOW','ROLE','employee'),(518,'Client','replaceById','*','ALLOW','ROLE','employee'),(519,'Client','updateAttributes','*','ALLOW','ROLE','employee'),(520,'Client','updateAttributes','*','ALLOW','ROLE','employee'),(521,'Client','deleteById','*','ALLOW','ROLE','employee'),(522,'Client','replaceOrCreate','*','ALLOW','ROLE','employee'),(523,'Client','updateAll','*','ALLOW','ROLE','employee'),(524,'Client','upsertWithWhere','*','ALLOW','ROLE','employee'),(525,'Defaulter','observationEmail','WRITE','ALLOW','ROLE','employee'),(527,'VnUser','acl','READ','ALLOW','ROLE','account'),(528,'VnUser','getCurrentUserData','READ','ALLOW','ROLE','account'),(530,'Account','exists','READ','ALLOW','ROLE','account'),(531,'Account','exists','READ','ALLOW','ROLE','account'),(532,'UserLog','*','READ','ALLOW','ROLE','employee'),(533,'RoleLog','*','READ','ALLOW','ROLE','employee'),(534,'WagonType','*','*','ALLOW','ROLE','productionAssi'),(535,'WagonTypeColor','*','*','ALLOW','ROLE','productionAssi'),(536,'WagonTypeTray','*','*','ALLOW','ROLE','productionAssi'),(537,'WagonConfig','*','*','ALLOW','ROLE','productionAssi'),(538,'CollectionWagon','*','*','ALLOW','ROLE','productionAssi'),(539,'CollectionWagonTicket','*','*','ALLOW','ROLE','productionAssi'),(540,'Wagon','*','*','ALLOW','ROLE','productionAssi'),(541,'WagonType','createWagonType','*','ALLOW','ROLE','productionAssi'),(542,'WagonType','deleteWagonType','*','ALLOW','ROLE','productionAssi'),(543,'WagonType','editWagonType','*','ALLOW','ROLE','productionAssi'),(544,'Docuware','deliveryNoteEmail','WRITE','ALLOW','ROLE','employee'),(545,'Agency','find','READ','ALLOW','ROLE','employee'),(546,'Agency','seeExpired','READ','ALLOW','ROLE','coolerAssist'),(547,'WorkerLog','models','READ','ALLOW','ROLE','hr'),(548,'Ticket','editDiscount','WRITE','ALLOW','ROLE','claimManager'),(549,'Ticket','editDiscount','WRITE','ALLOW','ROLE','salesPerson'),(550,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','salesAssistant'),(551,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','deliveryAssistant'),(552,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','buyer'),(553,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','claimManager'),(554,'Ticket','deleteTicketWithPartPrepared','WRITE','ALLOW','ROLE','salesAssistant'),(555,'Ticket','editZone','WRITE','ALLOW','ROLE','deliveryAssistant'),(556,'State','editableStates','READ','ALLOW','ROLE','employee'),(557,'State','seeEditableStates','READ','ALLOW','ROLE','administrative'),(558,'State','seeEditableStates','READ','ALLOW','ROLE','production'),(559,'State','isSomeEditable','READ','ALLOW','ROLE','salesPerson'),(560,'State','isAllEditable','READ','ALLOW','ROLE','production'),(561,'State','isAllEditable','READ','ALLOW','ROLE','administrative'),(562,'Agency','seeExpired','READ','ALLOW','ROLE','administrative'),(563,'Agency','seeExpired','READ','ALLOW','ROLE','productionBoss'),(564,'Claim','createAfterDeadline','WRITE','ALLOW','ROLE','claimManager'),(565,'Client','editAddressLogifloraAllowed','WRITE','ALLOW','ROLE','salesAssistant'),(566,'Client','editFiscalDataWithoutTaxDataCheck','WRITE','ALLOW','ROLE','salesAssistant'),(567,'Client','editVerifiedDataWithoutTaxDataCheck','WRITE','ALLOW','ROLE','salesAssistant'),(568,'Client','editCredit','WRITE','ALLOW','ROLE','financialBoss'),(569,'Client','zeroCreditEditor','WRITE','ALLOW','ROLE','financialBoss'),(570,'InvoiceOut','canCreatePdf','WRITE','ALLOW','ROLE','invoicing'),(571,'Supplier','editPayMethodCheck','WRITE','ALLOW','ROLE','financial'),(572,'Worker','isTeamBoss','WRITE','ALLOW','ROLE','teamBoss'),(573,'Worker','forceIsSubordinate','READ','ALLOW','ROLE','hr'),(574,'Claim','editState','WRITE','ALLOW','ROLE','claimManager'),(575,'Claim','find','READ','ALLOW','ROLE','salesPerson'),(576,'Claim','findById','READ','ALLOW','ROLE','salesPerson'),(577,'Claim','findOne','READ','ALLOW','ROLE','salesPerson'),(578,'Claim','getSummary','READ','ALLOW','ROLE','salesPerson'),(579,'Claim','updateClaim','WRITE','ALLOW','ROLE','salesPerson'),(580,'Claim','regularizeClaim','WRITE','ALLOW','ROLE','claimManager'),(581,'Claim','updateClaimDestination','WRITE','ALLOW','ROLE','claimManager'),(582,'Claim','downloadFile','READ','ALLOW','ROLE','claimManager'),(583,'Claim','deleteById','WRITE','ALLOW','ROLE','claimManager'),(584,'Claim','filter','READ','ALLOW','ROLE','salesPerson'),(585,'Claim','logs','READ','ALLOW','ROLE','claimManager'),(586,'Ticket','find','READ','ALLOW','ROLE','employee'),(587,'Ticket','findById','READ','ALLOW','ROLE','employee'),(588,'Ticket','findOne','READ','ALLOW','ROLE','employee'),(589,'Ticket','getVolume','READ','ALLOW','ROLE','employee'),(590,'Ticket','getTotalVolume','READ','ALLOW','ROLE','employee'),(591,'Ticket','summary','READ','ALLOW','ROLE','employee'),(592,'Ticket','priceDifference','READ','ALLOW','ROLE','employee'),(593,'Ticket','componentUpdate','WRITE','ALLOW','ROLE','employee'),(594,'Ticket','new','WRITE','ALLOW','ROLE','employee'),(595,'Ticket','isEditable','READ','ALLOW','ROLE','employee'),(596,'Ticket','setDeleted','WRITE','ALLOW','ROLE','salesPerson'),(597,'Ticket','restore','WRITE','ALLOW','ROLE','employee'),(598,'Ticket','getSales','READ','ALLOW','ROLE','employee'),(599,'Ticket','getSalesPersonMana','READ','ALLOW','ROLE','employee'),(600,'Ticket','filter','READ','ALLOW','ROLE','employee'),(601,'Ticket','makeInvoice','WRITE','ALLOW','ROLE','employee'),(602,'Ticket','updateEditableTicket','WRITE','ALLOW','ROLE','employee'),(603,'Ticket','updateDiscount','WRITE','ALLOW','ROLE','employee'),(604,'Ticket','transferSales','WRITE','ALLOW','ROLE','employee'),(605,'Ticket','sendSms','WRITE','ALLOW','ROLE','employee'),(606,'Ticket','isLocked','READ','ALLOW','ROLE','employee'),(607,'Ticket','freightCost','READ','ALLOW','ROLE','employee'),(608,'Ticket','getComponentsSum','READ','ALLOW','ROLE','employee'),(609,'Ticket','updateAttributes','WRITE','ALLOW','ROLE','delivery'),(610,'Ticket','deliveryNoteCsv','READ','ALLOW','ROLE','employee'),(611,'State','find','READ','ALLOW','ROLE','employee'),(612,'State','findById','READ','ALLOW','ROLE','employee'),(613,'State','findOne','READ','ALLOW','ROLE','employee'),(614,'Worker','find','READ','ALLOW','ROLE','employee'),(615,'Worker','findById','READ','ALLOW','ROLE','employee'),(616,'Worker','findOne','READ','ALLOW','ROLE','employee'),(617,'Worker','filter','READ','ALLOW','ROLE','employee'),(618,'Worker','getWorkedHours','READ','ALLOW','ROLE','employee'),(619,'Worker','active','READ','ALLOW','ROLE','employee'),(620,'Worker','activeWithRole','READ','ALLOW','ROLE','employee'),(621,'Worker','uploadFile','WRITE','ALLOW','ROLE','hr'),(622,'Worker','contracts','READ','ALLOW','ROLE','employee'),(623,'Worker','holidays','READ','ALLOW','ROLE','employee'),(624,'Worker','activeContract','READ','ALLOW','ROLE','employee'),(625,'Worker','activeWithInheritedRole','READ','ALLOW','ROLE','employee'),(626,'Ticket','collectionLabel','READ','ALLOW','ROLE','employee'),(628,'Ticket','expeditionPalletLabel','READ','ALLOW','ROLE','employee'),(629,'Ticket','editDiscount','WRITE','ALLOW','ROLE','artificialBoss'),(630,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','salesTeamBoss'),(635,'Ticket','updateAttributes','WRITE','ALLOW','ROLE','administrative'),(636,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','salesPerson'),(637,'Claim','downloadFile','READ','ALLOW','ROLE','salesPerson'),(638,'Agency','seeExpired','READ','ALLOW','ROLE','artificialBoss'),(639,'Agency','seeExpired','READ','ALLOW','ROLE','logisticAssistant'),(640,'Claim','filter','READ','ALLOW','ROLE','buyer'),(641,'Claim','find','READ','ALLOW','ROLE','buyer'),(642,'Claim','findById','READ','ALLOW','ROLE','buyer'),(643,'Claim','getSummary','READ','ALLOW','ROLE','buyer'),(644,'Claim','filter','READ','ALLOW','ROLE','handmadeBoss'),(645,'Claim','find','READ','ALLOW','ROLE','handmadeBoss'),(646,'Claim','findById','READ','ALLOW','ROLE','handmadeBoss'),(647,'Claim','getSummary','READ','ALLOW','ROLE','handmadeBoss'),(648,'Claim','__get__lines','READ','ALLOW','ROLE','claimManager'),(649,'Claim','__get__lines','READ','ALLOW','ROLE','salesPerson'),(650,'Claim','getSummary','READ','ALLOW','ROLE','deliveryAssistant'),(651,'Claim','findById','READ','ALLOW','ROLE','deliveryAssistant'),(652,'Claim','find','READ','ALLOW','ROLE','deliveryAssistant'),(653,'Claim','filter','READ','ALLOW','ROLE','deliveryAssistant'),(654,'Ticket','editZone','WRITE','ALLOW','ROLE','logisticAssistant'),(655,'Entry','addFromPackaging','WRITE','ALLOW','ROLE','production'),(656,'Entry','addFromBuy','WRITE','ALLOW','ROLE','production'),(657,'Supplier','getItemsPackaging','READ','ALLOW','ROLE','production'),(658,'Ticket','closeAll','WRITE','ALLOW','ROLE','system'),(659,'Account','*','*','ALLOW','ROLE','itManagement'),(660,'Account','*','READ','ALLOW','ROLE','employee'),(664,'MailForward','*','*','ALLOW','ROLE','itManagement'),(665,'Role','*','READ','ALLOW','ROLE','employee'),(666,'Role','*','WRITE','ALLOW','ROLE','it'),(667,'VnUser','*','*','ALLOW','ROLE','itManagement'),(668,'VnUser','__get__preview','READ','ALLOW','ROLE','employee'),(669,'VnUser','preview','*','ALLOW','ROLE','employee'),(670,'VnUser','create','*','ALLOW','ROLE','itManagement'),(671,'VnUser','renewToken','WRITE','ALLOW','ROLE','employee'),(672,'PackingSiteAdvanced','*','*','ALLOW','ROLE','production'),(673,'InvoiceOut','makePdfAndNotify','WRITE','ALLOW','ROLE','invoicing'),(674,'InvoiceOutConfig','*','READ','ALLOW','ROLE','invoicing'),(676,'Ticket','invoiceTickets','WRITE','ALLOW','ROLE','employee'),(680,'MailAliasAccount','*','READ','ALLOW','ROLE','employee'),(681,'MailAliasAccount','create','WRITE','ALLOW','ROLE','employee'),(682,'MailAliasAccount','deleteById','WRITE','ALLOW','ROLE','employee'),(683,'MailAliasAccount','canEditAlias','WRITE','ALLOW','ROLE','itManagement'),(684,'WorkerDisableExcluded','*','READ','ALLOW','ROLE','itManagement'),(685,'WorkerDisableExcluded','*','WRITE','ALLOW','ROLE','itManagement'),(686,'MailForward','*','*','ALLOW','ROLE','hr'),(687,'ClientSms','find','READ','ALLOW','ROLE','employee'),(688,'ClientSms','create','WRITE','ALLOW','ROLE','employee'),(689,'Vehicle','sorted','WRITE','ALLOW','ROLE','employee'),(690,'Roadmap','*','*','ALLOW','ROLE','palletizerBoss'),(691,'Roadmap','*','*','ALLOW','ROLE','productionBoss'),(692,'ExpeditionTruck','*','*','ALLOW','ROLE','palletizerBoss'),(693,'ExpeditionTruck','*','*','ALLOW','ROLE','productionBoss'),(694,'MailAliasAccount','canEditAlias','WRITE','ALLOW','ROLE','marketingBoss'),(695,'ViaexpressConfig','internationalExpedition','WRITE','ALLOW','ROLE','employee'),(696,'ViaexpressConfig','renderer','READ','ALLOW','ROLE','employee'),(697,'Ticket','transferClient','WRITE','ALLOW','ROLE','administrative'),(698,'Ticket','canEditWeekly','WRITE','ALLOW','ROLE','buyer'),(699,'TicketSms','find','READ','ALLOW','ROLE','salesPerson'),(701,'Docuware','upload','WRITE','ALLOW','ROLE','deliveryAssistant'),(702,'Ticket','docuwareDownload','READ','ALLOW','ROLE','salesPerson'); /*!40000 ALTER TABLE `ACL` ENABLE KEYS */; UNLOCK TABLES; diff --git a/e2e/paths/02-client/01_create_client.spec.js b/e2e/paths/02-client/01_create_client.spec.js index cb06d3616..744b11a72 100644 --- a/e2e/paths/02-client/01_create_client.spec.js +++ b/e2e/paths/02-client/01_create_client.spec.js @@ -8,7 +8,7 @@ describe('Client create path', () => { beforeAll(async() => { browser = await getBrowser(); page = browser.page; - await page.loginAndModule('deliveryBoss', 'client'); + await page.loginAndModule('deliveryAssistant', 'client'); }); afterAll(async() => { From a9b2aef27adb2ae6a967d3bdd377d1d2857ac2fa Mon Sep 17 00:00:00 2001 From: carlossa Date: Wed, 13 Sep 2023 12:02:25 +0200 Subject: [PATCH 083/427] refs #5660 join and value --- db/changes/233801/01-deliveryAssistantACL.sql | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/db/changes/233801/01-deliveryAssistantACL.sql b/db/changes/233801/01-deliveryAssistantACL.sql index 22ee9d796..34acf2427 100644 --- a/db/changes/233801/01-deliveryAssistantACL.sql +++ b/db/changes/233801/01-deliveryAssistantACL.sql @@ -1,21 +1,18 @@ -- Auto-generated SQL script. Actual values for binary/complex data types may differ - what you see is the default string representation of values. INSERT INTO `account`.`role` (name,description) - VALUES ('deliveryAssistant','Asistencia de envios'); - -INSERT INTO `account`.`roleInherit` (role,inheritsFrom) - SELECT (SELECT id FROM account.role r WHERE r.name = 'deliveryAssistant'), ri.inheritsFrom - FROM account.roleInherit ri - JOIN account.role r ON r.id = ri.`role` - WHERE r.name = 'deliveryBoss'; + VALUES ('deliveryAssistant','Jefe auxiliar repartos'); +INSERT INTO `account`.`roleInherit` (role, inheritsFrom) + SELECT (SELECT id FROM account.role r1 WHERE r1.name = 'deliveryAssistant'), ri.inheritsFrom +FROM account.roleInherit ri + JOIN account.role r2 ON r2.id = ri.`role` +WHERE r2.name = 'deliveryBoss'; DELETE FROM `account`.`roleInherit` WHERE role = 57; - + INSERT INTO `account`.`roleInherit` (role, inheritsFrom) - SELECT (SELECT id FROM account.role WHERE name = 'deliveryBoss') role, + SELECT (SELECT id FROM account.role WHERE name = 'deliveryBoss') role, (SELECT id FROM account.role WHERE name = 'deliveryAssistant') roleInherit; CALL account.role_syncPrivileges(); - - From f82af979ed5511e893c60651f2c1987892b31987 Mon Sep 17 00:00:00 2001 From: pablone Date: Wed, 13 Sep 2023 16:54:50 +0200 Subject: [PATCH 084/427] refs #6213 fixTraductionFile --- loopback/locale/es.json | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 6388c01a4..f568b9a58 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -317,6 +317,5 @@ "The ticket doesn't exist.": "No existe el ticket.", "Social name should be uppercase": "La razón social debe ir en mayúscula", "Street should be uppercase": "La dirección fiscal debe ir en mayúscula", - "Ticket without Route": "Ticket sin ruta", - "The account size must be exactly 10 characters": "The account size must be exactly 10 characters" + "Ticket without Route": "Ticket sin ruta" } \ No newline at end of file From 7ab8cb37cd4b2a34c3899ccfafac3a5c22e8d33f Mon Sep 17 00:00:00 2001 From: pablone Date: Wed, 13 Sep 2023 19:22:21 +0200 Subject: [PATCH 085/427] ref #6213 fixformat --- modules/supplier/back/models/supplier.js | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/modules/supplier/back/models/supplier.js b/modules/supplier/back/models/supplier.js index 6bfec86d1..0337fe9db 100644 --- a/modules/supplier/back/models/supplier.js +++ b/modules/supplier/back/models/supplier.js @@ -119,15 +119,12 @@ module.exports = Self => { Self.observe('after save', async function(ctx) { if (ctx.instance && ctx.isNewInstance) { - const supplierId = ctx.instance.id; - const models = Self.app.models; + const {id} = ctx.instance; + const {Supplier} = Self.app.models; - const supplier = await models.Supplier.findById(supplierId, null, ctx.options); - await supplier.updateAttribute( - 'account', - supplier.account + supplierId, - ctx.options - ); + const supplier = await Supplier.findById(id, null, ctx.options); + if (supplier) + await supplier.updateAttribute('account', `${supplier.account}${id}`, ctx.options); } }); From 66e851b5ea631c021d7461d1a35ec286130ead42 Mon Sep 17 00:00:00 2001 From: pablone Date: Wed, 13 Sep 2023 19:48:58 +0200 Subject: [PATCH 086/427] refs #4131 changeStateRefactor --- .../233801/00-ACLticketTrackingState.sql | 3 + .../233801/00-ticketSetStateRefactor.sql | 69 +++++++++++++++++++ db/dump/dumpedFixtures.sql | 2 +- front/core/directives/anchor.js | 4 +- modules/claim/front/summary/index.html | 2 +- modules/claim/front/summary/index.js | 2 +- modules/claim/front/summary/index.spec.js | 4 +- .../methods/ticket-tracking/setDelivered.js | 2 +- .../ticket-tracking/specs/changeState.spec.js | 10 +-- .../{changeState.js => state.js} | 6 +- modules/ticket/back/models/ticket-tracking.js | 2 +- modules/ticket/front/sale/index.html | 4 +- modules/ticket/front/sale/index.js | 4 +- modules/ticket/front/sale/index.spec.js | 6 +- modules/ticket/front/summary/index.html | 2 +- modules/ticket/front/summary/index.js | 4 +- modules/ticket/front/summary/index.spec.js | 6 +- modules/ticket/front/tracking/edit/index.html | 2 +- modules/ticket/front/tracking/edit/index.js | 2 +- .../ticket/front/tracking/edit/index.spec.js | 2 +- modules/worker/front/time-control/index.js | 2 +- 21 files changed, 106 insertions(+), 34 deletions(-) create mode 100644 db/changes/233801/00-ACLticketTrackingState.sql create mode 100644 db/changes/233801/00-ticketSetStateRefactor.sql rename modules/ticket/back/methods/ticket-tracking/{changeState.js => state.js} (94%) diff --git a/db/changes/233801/00-ACLticketTrackingState.sql b/db/changes/233801/00-ACLticketTrackingState.sql new file mode 100644 index 000000000..a0e3824db --- /dev/null +++ b/db/changes/233801/00-ACLticketTrackingState.sql @@ -0,0 +1,3 @@ +UPDATE `salix`.`ACL` + SET property = 'state' + WHERE property = 'changeState'; \ No newline at end of file diff --git a/db/changes/233801/00-ticketSetStateRefactor.sql b/db/changes/233801/00-ticketSetStateRefactor.sql new file mode 100644 index 000000000..1ad453299 --- /dev/null +++ b/db/changes/233801/00-ticketSetStateRefactor.sql @@ -0,0 +1,69 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_setState`( + vSelf INT, + vStateCode VARCHAR(255) COLLATE utf8_general_ci +) +BEGIN +/** + * Modifica el estado de un ticket si se cumplen las condiciones necesarias. + * + * @param vSelf el id del ticket + * @param vStateCode estado a modificar del ticket + */ + DECLARE vticketAlertLevel INT; + DECLARE vTicketStateCode VARCHAR(255); + DECLARE vCanChangeState BOOL; + DECLARE vPackedAlertLevel INT; + DECLARE vOnPreparationAlertLevel INT; + DECLARE vNextAlertLevel INT; + DECLARE vZoneFk INT; + + SELECT s.alertLevel, s.`code`, s2.alertLevel, t.zoneFk + INTO vticketAlertLevel, vTicketStateCode, vNextAlertLevel , vZoneFk + FROM state s + JOIN ticketTracking tt ON tt.stateFk = s.id + JOIN state s2 ON s2.code = vStateCode + JOIN ticket t ON t.id = tt.ticketFk + WHERE tt.ticketFk = vSelf + ORDER BY tt.created DESC + LIMIT 1; + + SELECT id INTO vPackedAlertLevel FROM alertLevel WHERE code = 'PACKED'; + SELECT id INTO vOnPreparationAlertLevel + FROM alertLevel + WHERE code = 'ON_PREPARATION'; + + IF vStateCode = 'OK' AND vZoneFk IS NULL THEN + CALL util.throw('ASSIGN_ZONE_FIRST'); + END IF; + + IF vNextAlertLevel > vticketAlertLevel && + vticketAlertLevel < vOnPreparationAlertLevel + THEN + UPDATE sale + SET originalQuantity = quantity + WHERE ticketFk = vSelf; + END IF; + + SET vCanChangeState = ( + vStateCode <> 'ON_CHECKING' OR + vticketAlertLevel < vPackedAlertLevel + )AND NOT ( + vTicketStateCode IN ('CHECKED', 'CHECKING') + AND vStateCode IN ('PREPARED', 'ON_PREPARATION') + ); + + IF vCanChangeState THEN + INSERT INTO ticketTracking (stateFk, ticketFk, workerFk) + SELECT id, vSelf, account.myUser_getId() + FROM state + WHERE `code` = vStateCode COLLATE utf8_unicode_ci; + + IF vStateCode = 'PACKED' THEN + CALL ticket_doCmr(vSelf); + END IF; + ELSE + CALL util.throw('INCORRECT_TICKET_STATE'); + END IF; +END$$ +DELIMITER ; diff --git a/db/dump/dumpedFixtures.sql b/db/dump/dumpedFixtures.sql index 2e1511b59..5ff2e03ef 100644 --- a/db/dump/dumpedFixtures.sql +++ b/db/dump/dumpedFixtures.sql @@ -164,7 +164,7 @@ USE `salix`; LOCK TABLES `ACL` WRITE; /*!40000 ALTER TABLE `ACL` DISABLE KEYS */; -INSERT INTO `ACL` VALUES (3,'Address','*','*','ALLOW','ROLE','employee'),(5,'AgencyService','*','READ','ALLOW','ROLE','employee'),(9,'ClientObservation','*','*','ALLOW','ROLE','employee'),(11,'ContactChannel','*','READ','ALLOW','ROLE','trainee'),(13,'Employee','*','READ','ALLOW','ROLE','employee'),(14,'PayMethod','*','READ','ALLOW','ROLE','trainee'),(16,'FakeProduction','*','READ','ALLOW','ROLE','employee'),(17,'Warehouse','* ','READ','ALLOW','ROLE','trainee'),(20,'TicketState','*','*','ALLOW','ROLE','employee'),(24,'Delivery','*','READ','ALLOW','ROLE','employee'),(25,'Zone','*','READ','ALLOW','ROLE','employee'),(26,'ClientCredit','*','*','ALLOW','ROLE','employee'),(27,'ClientCreditLimit','*','READ','ALLOW','ROLE','trainee'),(30,'GreugeType','*','READ','ALLOW','ROLE','trainee'),(31,'Mandate','*','READ','ALLOW','ROLE','trainee'),(32,'MandateType','*','READ','ALLOW','ROLE','trainee'),(33,'Company','*','READ','ALLOW','ROLE','trainee'),(34,'Greuge','*','READ','ALLOW','ROLE','trainee'),(35,'AddressObservation','*','*','ALLOW','ROLE','employee'),(36,'ObservationType','*','*','ALLOW','ROLE','employee'),(37,'Greuge','*','WRITE','ALLOW','ROLE','employee'),(38,'AgencyMode','*','READ','ALLOW','ROLE','employee'),(39,'ItemTag','*','WRITE','ALLOW','ROLE','buyer'),(40,'ItemBotanical','*','WRITE','ALLOW','ROLE','buyer'),(41,'ItemBotanical','*','READ','ALLOW','ROLE','employee'),(42,'ItemPlacement','*','WRITE','ALLOW','ROLE','buyer'),(43,'ItemPlacement','*','WRITE','ALLOW','ROLE','replenisher'),(44,'ItemPlacement','*','READ','ALLOW','ROLE','employee'),(45,'ItemBarcode','*','READ','ALLOW','ROLE','employee'),(46,'ItemBarcode','*','WRITE','ALLOW','ROLE','buyer'),(47,'ItemBarcode','*','WRITE','ALLOW','ROLE','replenisher'),(51,'ItemTag','*','READ','ALLOW','ROLE','employee'),(53,'Item','*','READ','ALLOW','ROLE','employee'),(54,'Item','*','WRITE','ALLOW','ROLE','buyer'),(55,'Recovery','*','READ','ALLOW','ROLE','trainee'),(56,'Recovery','*','WRITE','ALLOW','ROLE','administrative'),(58,'CreditClassification','*','*','ALLOW','ROLE','insurance'),(60,'CreditInsurance','*','*','ALLOW','ROLE','insurance'),(61,'InvoiceOut','*','READ','ALLOW','ROLE','employee'),(63,'TicketObservation','*','*','ALLOW','ROLE','employee'),(64,'Route','*','READ','ALLOW','ROLE','employee'),(65,'Sale','*','READ','ALLOW','ROLE','employee'),(66,'TicketTracking','*','READ','ALLOW','ROLE','employee'),(68,'TicketPackaging','*','*','ALLOW','ROLE','employee'),(69,'Packaging','*','READ','ALLOW','ROLE','employee'),(70,'Packaging','*','WRITE','ALLOW','ROLE','logistic'),(72,'SaleComponent','*','READ','ALLOW','ROLE','employee'),(73,'Expedition','*','READ','ALLOW','ROLE','employee'),(74,'Expedition','*','WRITE','ALLOW','ROLE','deliveryBoss'),(75,'Expedition','*','WRITE','ALLOW','ROLE','production'),(76,'AnnualAverageInvoiced','*','READ','ALLOW','ROLE','employee'),(77,'WorkerMana','*','READ','ALLOW','ROLE','employee'),(78,'TicketTracking','*','WRITE','ALLOW','ROLE','production'),(79,'TicketTracking','changeState','*','ALLOW','ROLE','employee'),(80,'Sale','deleteSales','*','ALLOW','ROLE','employee'),(81,'Sale','moveToTicket','*','ALLOW','ROLE','employee'),(82,'Sale','updateQuantity','*','ALLOW','ROLE','employee'),(83,'Sale','updatePrice','*','ALLOW','ROLE','employee'),(84,'Sale','updateDiscount','*','ALLOW','ROLE','employee'),(85,'SaleTracking','*','READ','ALLOW','ROLE','employee'),(86,'Order','*','*','ALLOW','ROLE','employee'),(87,'OrderRow','*','*','ALLOW','ROLE','employee'),(88,'ClientContact','*','*','ALLOW','ROLE','employee'),(89,'Sale','moveToNewTicket','*','ALLOW','ROLE','employee'),(90,'Sale','reserve','*','ALLOW','ROLE','employee'),(91,'TicketWeekly','*','READ','ALLOW','ROLE','employee'),(94,'Agency','landsThatDay','*','ALLOW','ROLE','employee'),(96,'ClaimEnd','*','READ','ALLOW','ROLE','employee'),(97,'ClaimEnd','*','WRITE','ALLOW','ROLE','claimManager'),(98,'ClaimBeginning','*','*','ALLOW','ROLE','employee'),(99,'ClaimDevelopment','*','READ','ALLOW','ROLE','employee'),(100,'ClaimDevelopment','*','WRITE','ALLOW','ROLE','claimManager'),(102,'Claim','createFromSales','*','ALLOW','ROLE','employee'),(104,'Item','*','WRITE','ALLOW','ROLE','marketingBoss'),(105,'ItemBarcode','*','WRITE','ALLOW','ROLE','marketingBoss'),(106,'ItemBotanical','*','WRITE','ALLOW','ROLE','marketingBoss'),(108,'ItemPlacement','*','WRITE','ALLOW','ROLE','marketingBoss'),(109,'UserConfig','*','*','ALLOW','ROLE','employee'),(110,'Bank','*','READ','ALLOW','ROLE','trainee'),(111,'ClientLog','*','READ','ALLOW','ROLE','trainee'),(112,'Defaulter','*','READ','ALLOW','ROLE','employee'),(113,'ClientRisk','*','READ','ALLOW','ROLE','trainee'),(114,'Receipt','*','READ','ALLOW','ROLE','trainee'),(115,'Receipt','*','WRITE','ALLOW','ROLE','administrative'),(116,'BankEntity','*','*','ALLOW','ROLE','employee'),(117,'ClientSample','*','*','ALLOW','ROLE','employee'),(118,'WorkerTeam','*','*','ALLOW','ROLE','salesPerson'),(119,'Travel','*','READ','ALLOW','ROLE','employee'),(120,'Travel','*','WRITE','ALLOW','ROLE','buyer'),(121,'Item','regularize','*','ALLOW','ROLE','employee'),(122,'TicketRequest','*','*','ALLOW','ROLE','employee'),(124,'Client','confirmTransaction','WRITE','ALLOW','ROLE','administrative'),(125,'Agency','getAgenciesWithWarehouse','*','ALLOW','ROLE','employee'),(126,'Client','activeWorkersWithRole','*','ALLOW','ROLE','employee'),(127,'TicketLog','*','READ','ALLOW','ROLE','employee'),(129,'TicketService','*','*','ALLOW','ROLE','employee'),(130,'Expedition','*','WRITE','ALLOW','ROLE','packager'),(131,'CreditInsurance','*','READ','ALLOW','ROLE','trainee'),(132,'CreditClassification','*','READ','ALLOW','ROLE','trainee'),(133,'ItemTag','*','WRITE','ALLOW','ROLE','marketingBoss'),(135,'ZoneGeo','*','READ','ALLOW','ROLE','employee'),(136,'ZoneCalendar','*','READ','ALLOW','ROLE','employee'),(137,'ZoneIncluded','*','READ','ALLOW','ROLE','employee'),(138,'LabourHoliday','*','READ','ALLOW','ROLE','employee'),(139,'LabourHolidayLegend','*','READ','ALLOW','ROLE','employee'),(140,'LabourHolidayType','*','READ','ALLOW','ROLE','employee'),(141,'Zone','*','*','ALLOW','ROLE','logisticBoss'),(142,'ZoneCalendar','*','WRITE','ALLOW','ROLE','deliveryBoss'),(143,'ZoneIncluded','*','*','ALLOW','ROLE','deliveryBoss'),(144,'Stowaway','*','*','ALLOW','ROLE','employee'),(145,'Ticket','getPossibleStowaways','READ','ALLOW','ROLE','employee'),(147,'UserConfigView','*','*','ALLOW','ROLE','employee'),(148,'UserConfigView','*','*','ALLOW','ROLE','employee'),(149,'Sip','*','READ','ALLOW','ROLE','employee'),(150,'Sip','*','WRITE','ALLOW','ROLE','hr'),(151,'Department','*','READ','ALLOW','ROLE','employee'),(152,'Department','*','WRITE','ALLOW','ROLE','hr'),(153,'Route','*','READ','ALLOW','ROLE','employee'),(154,'Route','*','WRITE','ALLOW','ROLE','delivery'),(155,'Calendar','*','READ','ALLOW','ROLE','hr'),(156,'WorkerLabour','*','READ','ALLOW','ROLE','hr'),(157,'Calendar','absences','READ','ALLOW','ROLE','employee'),(158,'ItemTag','*','WRITE','ALLOW','ROLE','accessory'),(160,'TicketServiceType','*','READ','ALLOW','ROLE','employee'),(161,'TicketConfig','*','READ','ALLOW','ROLE','employee'),(162,'InvoiceOut','delete','WRITE','ALLOW','ROLE','invoicing'),(163,'InvoiceOut','book','WRITE','ALLOW','ROLE','invoicing'),(165,'TicketDms','*','*','ALLOW','ROLE','employee'),(167,'Worker','isSubordinate','READ','ALLOW','ROLE','employee'),(168,'Worker','mySubordinates','READ','ALLOW','ROLE','employee'),(169,'WorkerTimeControl','filter','READ','ALLOW','ROLE','employee'),(170,'WorkerTimeControl','addTime','WRITE','ALLOW','ROLE','employee'),(171,'TicketServiceType','*','WRITE','ALLOW','ROLE','administrative'),(172,'Sms','*','READ','ALLOW','ROLE','employee'),(173,'Sms','send','WRITE','ALLOW','ROLE','employee'),(176,'Device','*','*','ALLOW','ROLE','employee'),(177,'Device','*','*','ALLOW','ROLE','employee'),(178,'WorkerTimeControl','*','*','ALLOW','ROLE','employee'),(179,'ItemLog','*','READ','ALLOW','ROLE','employee'),(180,'RouteLog','*','READ','ALLOW','ROLE','employee'),(181,'Dms','removeFile','WRITE','ALLOW','ROLE','employee'),(182,'Dms','uploadFile','WRITE','ALLOW','ROLE','employee'),(183,'Dms','downloadFile','READ','ALLOW','ROLE','employee'),(184,'Client','uploadFile','WRITE','ALLOW','ROLE','employee'),(185,'ClientDms','removeFile','WRITE','ALLOW','ROLE','employee'),(186,'ClientDms','*','READ','ALLOW','ROLE','trainee'),(187,'Ticket','uploadFile','WRITE','ALLOW','ROLE','employee'),(190,'Route','updateVolume','WRITE','ALLOW','ROLE','deliveryBoss'),(191,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(192,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(194,'Postcode','*','WRITE','ALLOW','ROLE','deliveryBoss'),(195,'Ticket','addSale','WRITE','ALLOW','ROLE','employee'),(196,'Dms','updateFile','WRITE','ALLOW','ROLE','employee'),(197,'Dms','*','READ','ALLOW','ROLE','trainee'),(198,'ClaimDms','removeFile','WRITE','ALLOW','ROLE','employee'),(199,'ClaimDms','*','READ','ALLOW','ROLE','employee'),(200,'Claim','uploadFile','WRITE','ALLOW','ROLE','employee'),(201,'Sale','updateConcept','WRITE','ALLOW','ROLE','employee'),(202,'Claim','updateClaimAction','WRITE','ALLOW','ROLE','claimManager'),(203,'UserPhone','*','*','ALLOW','ROLE','employee'),(204,'WorkerDms','removeFile','WRITE','ALLOW','ROLE','hr'),(205,'WorkerDms','*','READ','ALLOW','ROLE','hr'),(206,'Chat','*','*','ALLOW','ROLE','employee'),(207,'Chat','sendMessage','*','ALLOW','ROLE','employee'),(208,'Sale','recalculatePrice','WRITE','ALLOW','ROLE','employee'),(209,'Ticket','recalculateComponents','WRITE','ALLOW','ROLE','employee'),(211,'TravelLog','*','READ','ALLOW','ROLE','buyer'),(212,'Thermograph','*','*','ALLOW','ROLE','buyer'),(213,'TravelThermograph','*','WRITE','ALLOW','ROLE','buyer'),(214,'Entry','*','*','ALLOW','ROLE','buyer'),(215,'TicketWeekly','*','WRITE','ALLOW','ROLE','buyer'),(216,'TravelThermograph','*','READ','ALLOW','ROLE','employee'),(218,'Intrastat','*','*','ALLOW','ROLE','buyer'),(221,'UserConfig','getUserConfig','READ','ALLOW','ROLE','account'),(222,'Client','*','READ','ALLOW','ROLE','trainee'),(226,'ClientObservation','*','READ','ALLOW','ROLE','trainee'),(227,'Address','*','READ','ALLOW','ROLE','trainee'),(228,'AddressObservation','*','READ','ALLOW','ROLE','trainee'),(230,'ClientCredit','*','READ','ALLOW','ROLE','trainee'),(231,'ClientContact','*','READ','ALLOW','ROLE','trainee'),(232,'ClientSample','*','READ','ALLOW','ROLE','trainee'),(233,'EntryLog','*','READ','ALLOW','ROLE','buyer'),(234,'WorkerLog','find','READ','ALLOW','ROLE','hr'),(235,'CustomsAgent','*','*','ALLOW','ROLE','employee'),(236,'Buy','*','*','ALLOW','ROLE','buyer'),(237,'WorkerDms','filter','*','ALLOW','ROLE','employee'),(238,'Town','*','WRITE','ALLOW','ROLE','deliveryBoss'),(239,'Province','*','WRITE','ALLOW','ROLE','deliveryBoss'),(240,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(241,'SupplierContact','*','WRITE','ALLOW','ROLE','administrative'),(242,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(244,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(248,'RoleMapping','*','READ','ALLOW','ROLE','account'),(249,'UserPassword','*','READ','ALLOW','ROLE','account'),(250,'Town','*','WRITE','ALLOW','ROLE','deliveryBoss'),(251,'Province','*','WRITE','ALLOW','ROLE','deliveryBoss'),(252,'Supplier','*','READ','ALLOW','ROLE','employee'),(253,'Supplier','*','WRITE','ALLOW','ROLE','administrative'),(254,'SupplierLog','*','READ','ALLOW','ROLE','employee'),(256,'Image','*','WRITE','ALLOW','ROLE','employee'),(257,'FixedPrice','*','*','ALLOW','ROLE','buyer'),(258,'PayDem','*','READ','ALLOW','ROLE','employee'),(259,'Client','createReceipt','*','ALLOW','ROLE','salesAssistant'),(260,'PrintServerQueue','*','WRITE','ALLOW','ROLE','employee'),(261,'SupplierAccount','*','*','ALLOW','ROLE','administrative'),(262,'Entry','*','*','ALLOW','ROLE','administrative'),(263,'InvoiceIn','*','*','ALLOW','ROLE','administrative'),(264,'StarredModule','*','*','ALLOW','ROLE','employee'),(265,'ItemBotanical','*','WRITE','ALLOW','ROLE','logisticBoss'),(266,'ZoneLog','*','READ','ALLOW','ROLE','employee'),(267,'Genus','*','WRITE','ALLOW','ROLE','logisticBoss'),(268,'Specie','*','WRITE','ALLOW','ROLE','logisticBoss'),(269,'InvoiceOut','createPdf','WRITE','ALLOW','ROLE','employee'),(270,'SupplierAddress','*','*','ALLOW','ROLE','employee'),(271,'SalesMonitor','*','*','ALLOW','ROLE','employee'),(272,'InvoiceInLog','*','READ','ALLOW','ROLE','employee'),(273,'InvoiceInTax','*','*','ALLOW','ROLE','administrative'),(274,'InvoiceInLog','*','READ','ALLOW','ROLE','administrative'),(275,'InvoiceOut','createManualInvoice','WRITE','ALLOW','ROLE','invoicing'),(276,'InvoiceOut','globalInvoicing','WRITE','ALLOW','ROLE','invoicing'),(278,'RoleInherit','*','WRITE','ALLOW','ROLE','grant'),(279,'MailAlias','*','*','ALLOW','ROLE','marketing'),(283,'EntryObservation','*','*','ALLOW','ROLE','buyer'),(284,'LdapConfig','*','*','ALLOW','ROLE','sysadmin'),(285,'SambaConfig','*','*','ALLOW','ROLE','sysadmin'),(286,'ACL','*','*','ALLOW','ROLE','developer'),(287,'AccessToken','*','*','ALLOW','ROLE','developer'),(293,'RoleInherit','*','*','ALLOW','ROLE','it'),(294,'RoleRole','*','*','ALLOW','ROLE','it'),(295,'AccountConfig','*','*','ALLOW','ROLE','sysadmin'),(296,'Collection','*','READ','ALLOW','ROLE','employee'),(297,'Sale','refund','WRITE','ALLOW','ROLE','invoicing'),(298,'InvoiceInDueDay','*','*','ALLOW','ROLE','administrative'),(299,'Collection','setSaleQuantity','*','ALLOW','ROLE','employee'),(302,'AgencyTerm','*','*','ALLOW','ROLE','administrative'),(303,'ClaimLog','*','READ','ALLOW','ROLE','claimManager'),(304,'Edi','updateData','WRITE','ALLOW','ROLE','employee'),(305,'EducationLevel','*','*','ALLOW','ROLE','employee'),(306,'InvoiceInIntrastat','*','*','ALLOW','ROLE','employee'),(307,'SupplierAgencyTerm','*','*','ALLOW','ROLE','administrative'),(308,'InvoiceInIntrastat','*','*','ALLOW','ROLE','employee'),(309,'Zone','getZoneClosing','*','ALLOW','ROLE','employee'),(310,'ExpeditionState','*','READ','ALLOW','ROLE','employee'),(311,'Expense','*','READ','ALLOW','ROLE','employee'),(312,'Expense','*','WRITE','ALLOW','ROLE','administrative'),(314,'SupplierActivity','*','READ','ALLOW','ROLE','employee'),(315,'SupplierActivity','*','WRITE','ALLOW','ROLE','administrative'),(316,'Dms','deleteTrashFiles','WRITE','ALLOW','ROLE','employee'),(317,'ClientUnpaid','*','*','ALLOW','ROLE','administrative'),(318,'MdbVersion','*','*','ALLOW','ROLE','developer'),(319,'ItemType','*','READ','ALLOW','ROLE','employee'),(320,'ItemType','*','WRITE','ALLOW','ROLE','buyer'),(321,'InvoiceOut','refund','WRITE','ALLOW','ROLE','invoicing'),(322,'InvoiceOut','refund','WRITE','ALLOW','ROLE','salesAssistant'),(323,'InvoiceOut','refund','WRITE','ALLOW','ROLE','claimManager'),(324,'Ticket','refund','WRITE','ALLOW','ROLE','invoicing'),(325,'Ticket','refund','WRITE','ALLOW','ROLE','salesAssistant'),(326,'Ticket','refund','WRITE','ALLOW','ROLE','claimManager'),(327,'Sale','refund','WRITE','ALLOW','ROLE','salesAssistant'),(328,'Sale','refund','WRITE','ALLOW','ROLE','claimManager'),(329,'TicketRefund','*','WRITE','ALLOW','ROLE','invoicing'),(330,'ClaimObservation','*','WRITE','ALLOW','ROLE','salesPerson'),(331,'ClaimObservation','*','READ','ALLOW','ROLE','salesPerson'),(332,'Client','setPassword','WRITE','ALLOW','ROLE','salesPerson'),(333,'Client','updateUser','WRITE','ALLOW','ROLE','salesPerson'),(334,'ShelvingLog','*','READ','ALLOW','ROLE','employee'),(335,'ZoneExclusionGeo','*','READ','ALLOW','ROLE','employee'),(336,'ZoneExclusionGeo','*','WRITE','ALLOW','ROLE','deliveryBoss'),(337,'Parking','*','*','ALLOW','ROLE','employee'),(338,'Shelving','*','*','ALLOW','ROLE','employee'),(339,'OsTicket','*','*','ALLOW','ROLE','employee'),(340,'OsTicketConfig','*','*','ALLOW','ROLE','it'),(341,'ClientConsumptionQueue','*','WRITE','ALLOW','ROLE','employee'),(342,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','employee'),(343,'Ticket','deliveryNoteEmail','WRITE','ALLOW','ROLE','employee'),(344,'Ticket','deliveryNoteCsvPdf','READ','ALLOW','ROLE','employee'),(345,'Ticket','deliveryNoteCsvEmail','READ','ALLOW','ROLE','employee'),(346,'Client','campaignMetricsPdf','READ','ALLOW','ROLE','employee'),(347,'Client','campaignMetricsEmail','WRITE','ALLOW','ROLE','employee'),(348,'Client','clientWelcomeHtml','READ','ALLOW','ROLE','employee'),(349,'Client','clientWelcomeEmail','WRITE','ALLOW','ROLE','employee'),(350,'Client','creditRequestPdf','READ','ALLOW','ROLE','employee'),(351,'Client','creditRequestHtml','READ','ALLOW','ROLE','employee'),(352,'Client','creditRequestEmail','WRITE','ALLOW','ROLE','employee'),(353,'Client','printerSetupHtml','READ','ALLOW','ROLE','employee'),(354,'Client','printerSetupEmail','WRITE','ALLOW','ROLE','employee'),(355,'Client','sepaCoreEmail','WRITE','ALLOW','ROLE','employee'),(356,'Client','letterDebtorPdf','READ','ALLOW','ROLE','employee'),(357,'Client','letterDebtorStHtml','READ','ALLOW','ROLE','employee'),(358,'Client','letterDebtorStEmail','WRITE','ALLOW','ROLE','employee'),(359,'Client','letterDebtorNdHtml','READ','ALLOW','ROLE','employee'),(360,'Client','letterDebtorNdEmail','WRITE','ALLOW','ROLE','employee'),(361,'Client','clientDebtStatementPdf','READ','ALLOW','ROLE','employee'),(362,'Client','clientDebtStatementHtml','READ','ALLOW','ROLE','employee'),(363,'Client','clientDebtStatementEmail','WRITE','ALLOW','ROLE','employee'),(364,'Client','incotermsAuthorizationPdf','READ','ALLOW','ROLE','employee'),(365,'Client','incotermsAuthorizationHtml','READ','ALLOW','ROLE','employee'),(366,'Client','incotermsAuthorizationEmail','WRITE','ALLOW','ROLE','employee'),(367,'Client','consumptionSendQueued','WRITE','ALLOW','ROLE','system'),(368,'InvoiceOut','invoiceEmail','WRITE','ALLOW','ROLE','employee'),(369,'InvoiceOut','exportationPdf','READ','ALLOW','ROLE','employee'),(370,'InvoiceOut','sendQueued','WRITE','ALLOW','ROLE','system'),(371,'Ticket','invoiceCsvPdf','READ','ALLOW','ROLE','employee'),(372,'Ticket','invoiceCsvEmail','WRITE','ALLOW','ROLE','employee'),(373,'Supplier','campaignMetricsPdf','READ','ALLOW','ROLE','employee'),(374,'Supplier','campaignMetricsEmail','WRITE','ALLOW','ROLE','employee'),(375,'Travel','extraCommunityPdf','READ','ALLOW','ROLE','employee'),(376,'Travel','extraCommunityEmail','WRITE','ALLOW','ROLE','employee'),(377,'Entry','entryOrderPdf','READ','ALLOW','ROLE','employee'),(378,'OsTicket','osTicketReportEmail','WRITE','ALLOW','ROLE','system'),(379,'Item','buyerWasteEmail','WRITE','ALLOW','ROLE','system'),(380,'Claim','claimPickupPdf','READ','ALLOW','ROLE','employee'),(381,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','claimManager'),(382,'Item','labelPdf','READ','ALLOW','ROLE','employee'),(383,'Sector','*','READ','ALLOW','ROLE','employee'),(384,'Sector','*','WRITE','ALLOW','ROLE','employee'),(385,'Route','driverRoutePdf','READ','ALLOW','ROLE','employee'),(386,'Route','driverRouteEmail','WRITE','ALLOW','ROLE','employee'),(387,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','customer'),(388,'Supplier','newSupplier','WRITE','ALLOW','ROLE','administrative'),(389,'ClaimRma','*','READ','ALLOW','ROLE','claimManager'),(390,'ClaimRma','*','WRITE','ALLOW','ROLE','claimManager'),(391,'Notification','*','WRITE','ALLOW','ROLE','system'),(392,'Boxing','*','*','ALLOW','ROLE','employee'),(393,'Url','*','READ','ALLOW','ROLE','employee'),(394,'Url','*','WRITE','ALLOW','ROLE','it'),(395,'ItemShelving','*','READ','ALLOW','ROLE','employee'),(396,'ItemShelving','*','WRITE','ALLOW','ROLE','production'),(397,'ItemShelvingPlacementSupplyStock','*','READ','ALLOW','ROLE','employee'),(398,'NotificationQueue','*','*','ALLOW','ROLE','employee'),(399,'InvoiceOut','clientsToInvoice','WRITE','ALLOW','ROLE','invoicing'),(400,'InvoiceOut','invoiceClient','WRITE','ALLOW','ROLE','invoicing'),(401,'Sale','editTracked','WRITE','ALLOW','ROLE','production'),(402,'Sale','editFloramondo','WRITE','ALLOW','ROLE','salesAssistant'),(403,'Receipt','balanceCompensationEmail','WRITE','ALLOW','ROLE','employee'),(404,'Receipt','balanceCompensationPdf','READ','ALLOW','ROLE','employee'),(405,'Ticket','getTicketsFuture','READ','ALLOW','ROLE','employee'),(406,'Ticket','merge','WRITE','ALLOW','ROLE','employee'),(407,'Sale','editFloramondo','WRITE','ALLOW','ROLE','logistic'),(408,'ZipConfig','*','*','ALLOW','ROLE','employee'),(409,'Item','*','WRITE','ALLOW','ROLE','administrative'),(410,'Sale','editCloned','WRITE','ALLOW','ROLE','buyer'),(411,'Sale','editCloned','WRITE','ALLOW','ROLE','salesAssistant'),(414,'MdbVersion','*','READ','ALLOW','ROLE','$everyone'),(416,'TicketLog','getChanges','READ','ALLOW','ROLE','employee'),(417,'Ticket','getTicketsAdvance','READ','ALLOW','ROLE','employee'),(418,'EntryLog','*','READ','ALLOW','ROLE','administrative'),(419,'Sale','editTracked','WRITE','ALLOW','ROLE','buyer'),(420,'MdbBranch','*','READ','ALLOW','ROLE','$everyone'),(421,'ItemShelvingSale','*','*','ALLOW','ROLE','employee'),(422,'Docuware','checkFile','READ','ALLOW','ROLE','employee'),(423,'Docuware','download','READ','ALLOW','ROLE','salesPerson'),(424,'Docuware','upload','WRITE','ALLOW','ROLE','productionAssi'),(425,'Docuware','deliveryNoteEmail','WRITE','ALLOW','ROLE','salesPerson'),(426,'TpvTransaction','confirm','WRITE','ALLOW','ROLE','$everyone'),(427,'TpvTransaction','start','WRITE','ALLOW','ROLE','$authenticated'),(428,'TpvTransaction','end','WRITE','ALLOW','ROLE','$authenticated'),(429,'ItemConfig','*','READ','ALLOW','ROLE','employee'),(431,'Tag','onSubmit','WRITE','ALLOW','ROLE','employee'),(432,'Worker','updateAttributes','WRITE','ALLOW','ROLE','hr'),(433,'Worker','createAbsence','*','ALLOW','ROLE','employee'),(434,'Worker','updateAbsence','WRITE','ALLOW','ROLE','employee'),(435,'Worker','deleteAbsence','*','ALLOW','ROLE','employee'),(436,'Worker','new','WRITE','ALLOW','ROLE','hr'),(438,'Client','getClientOrSupplierReference','READ','ALLOW','ROLE','employee'),(439,'NotificationSubscription','*','*','ALLOW','ROLE','employee'),(440,'NotificationAcl','*','READ','ALLOW','ROLE','employee'),(441,'MdbApp','*','READ','ALLOW','ROLE','$everyone'),(442,'MdbApp','*','*','ALLOW','ROLE','developer'),(443,'ItemConfig','*','*','ALLOW','ROLE','employee'),(444,'DeviceProduction','*','*','ALLOW','ROLE','hr'),(445,'DeviceProductionModels','*','*','ALLOW','ROLE','hr'),(446,'DeviceProductionState','*','*','ALLOW','ROLE','hr'),(447,'DeviceProductionUser','*','*','ALLOW','ROLE','hr'),(448,'DeviceProduction','*','*','ALLOW','ROLE','productionAssi'),(449,'DeviceProductionModels','*','*','ALLOW','ROLE','productionAssi'),(450,'DeviceProductionState','*','*','ALLOW','ROLE','productionAssi'),(451,'DeviceProductionUser','*','*','ALLOW','ROLE','productionAssi'),(452,'Worker','deallocatePDA','*','ALLOW','ROLE','hr'),(453,'Worker','allocatePDA','*','ALLOW','ROLE','hr'),(454,'Worker','deallocatePDA','*','ALLOW','ROLE','productionAssi'),(455,'Worker','allocatePDA','*','ALLOW','ROLE','productionAssi'),(456,'Zone','*','*','ALLOW','ROLE','deliveryBoss'),(457,'Account','setPassword','WRITE','ALLOW','ROLE','itManagement'),(458,'Operator','*','READ','ALLOW','ROLE','employee'),(459,'Operator','*','WRITE','ALLOW','ROLE','employee'),(460,'InvoiceIn','getSerial','READ','ALLOW','ROLE','administrative'),(461,'Ticket','saveSign','WRITE','ALLOW','ROLE','employee'),(462,'InvoiceOut','negativeBases','READ','ALLOW','ROLE','administrative'),(463,'InvoiceOut','negativeBasesCsv','READ','ALLOW','ROLE','administrative'),(464,'WorkerObservation','*','*','ALLOW','ROLE','hr'),(465,'ClientInforma','*','READ','ALLOW','ROLE','employee'),(466,'ClientInforma','*','WRITE','ALLOW','ROLE','financial'),(467,'Receipt','receiptEmail','*','ALLOW','ROLE','salesAssistant'),(468,'Client','setRating','WRITE','ALLOW','ROLE','financial'),(469,'Client','*','READ','ALLOW','ROLE','employee'),(470,'Client','addressesPropagateRe','*','ALLOW','ROLE','employee'),(471,'Client','canBeInvoiced','*','ALLOW','ROLE','employee'),(472,'Client','canCreateTicket','*','ALLOW','ROLE','employee'),(473,'Client','consumption','*','ALLOW','ROLE','employee'),(474,'Client','createAddress','*','ALLOW','ROLE','employee'),(475,'Client','createWithUser','*','ALLOW','ROLE','employee'),(476,'Client','extendedListFilter','*','ALLOW','ROLE','employee'),(477,'Client','getAverageInvoiced','*','ALLOW','ROLE','employee'),(478,'Client','getCard','*','ALLOW','ROLE','employee'),(479,'Client','getDebt','*','ALLOW','ROLE','employee'),(480,'Client','getMana','*','ALLOW','ROLE','employee'),(481,'Client','transactions','*','ALLOW','ROLE','employee'),(482,'Client','hasCustomerRole','*','ALLOW','ROLE','employee'),(483,'Client','isValidClient','*','ALLOW','ROLE','employee'),(484,'Client','lastActiveTickets','*','ALLOW','ROLE','employee'),(485,'Client','sendSms','*','ALLOW','ROLE','employee'),(486,'Client','setPassword','*','ALLOW','ROLE','employee'),(487,'Client','summary','*','ALLOW','ROLE','employee'),(488,'Client','updateAddress','*','ALLOW','ROLE','employee'),(489,'Client','updateFiscalData','*','ALLOW','ROLE','employee'),(491,'Client','uploadFile','*','ALLOW','ROLE','employee'),(492,'Client','campaignMetricsPdf','*','ALLOW','ROLE','employee'),(493,'Client','campaignMetricsEmail','*','ALLOW','ROLE','employee'),(494,'Client','clientWelcomeHtml','*','ALLOW','ROLE','employee'),(495,'Client','clientWelcomeEmail','*','ALLOW','ROLE','employee'),(496,'Client','printerSetupHtml','*','ALLOW','ROLE','employee'),(497,'Client','printerSetupEmail','*','ALLOW','ROLE','employee'),(498,'Client','sepaCoreEmail','*','ALLOW','ROLE','employee'),(499,'Client','letterDebtorPdf','*','ALLOW','ROLE','employee'),(500,'Client','letterDebtorStHtml','*','ALLOW','ROLE','employee'),(501,'Client','letterDebtorStEmail','*','ALLOW','ROLE','employee'),(502,'Client','letterDebtorNdHtml','*','ALLOW','ROLE','employee'),(503,'Client','letterDebtorNdEmail','*','ALLOW','ROLE','employee'),(504,'Client','clientDebtStatementPdf','*','ALLOW','ROLE','employee'),(505,'Client','clientDebtStatementHtml','*','ALLOW','ROLE','employee'),(506,'Client','clientDebtStatementEmail','*','ALLOW','ROLE','employee'),(507,'Client','creditRequestPdf','*','ALLOW','ROLE','employee'),(508,'Client','creditRequestHtml','*','ALLOW','ROLE','employee'),(509,'Client','creditRequestEmail','*','ALLOW','ROLE','employee'),(510,'Client','incotermsAuthorizationPdf','*','ALLOW','ROLE','employee'),(511,'Client','incotermsAuthorizationHtml','*','ALLOW','ROLE','employee'),(512,'Client','incotermsAuthorizationEmail','*','ALLOW','ROLE','employee'),(513,'Client','consumptionSendQueued','*','ALLOW','ROLE','employee'),(514,'Client','filter','*','ALLOW','ROLE','employee'),(515,'Client','getClientOrSupplierReference','*','ALLOW','ROLE','employee'),(516,'Client','upsert','*','ALLOW','ROLE','employee'),(517,'Client','create','*','ALLOW','ROLE','employee'),(518,'Client','replaceById','*','ALLOW','ROLE','employee'),(519,'Client','updateAttributes','*','ALLOW','ROLE','employee'),(520,'Client','updateAttributes','*','ALLOW','ROLE','employee'),(521,'Client','deleteById','*','ALLOW','ROLE','employee'),(522,'Client','replaceOrCreate','*','ALLOW','ROLE','employee'),(523,'Client','updateAll','*','ALLOW','ROLE','employee'),(524,'Client','upsertWithWhere','*','ALLOW','ROLE','employee'),(525,'Defaulter','observationEmail','WRITE','ALLOW','ROLE','employee'),(527,'VnUser','acl','READ','ALLOW','ROLE','account'),(528,'VnUser','getCurrentUserData','READ','ALLOW','ROLE','account'),(530,'Account','exists','READ','ALLOW','ROLE','account'),(531,'Account','exists','READ','ALLOW','ROLE','account'),(532,'UserLog','*','READ','ALLOW','ROLE','employee'),(533,'RoleLog','*','READ','ALLOW','ROLE','employee'),(534,'WagonType','*','*','ALLOW','ROLE','productionAssi'),(535,'WagonTypeColor','*','*','ALLOW','ROLE','productionAssi'),(536,'WagonTypeTray','*','*','ALLOW','ROLE','productionAssi'),(537,'WagonConfig','*','*','ALLOW','ROLE','productionAssi'),(538,'CollectionWagon','*','*','ALLOW','ROLE','productionAssi'),(539,'CollectionWagonTicket','*','*','ALLOW','ROLE','productionAssi'),(540,'Wagon','*','*','ALLOW','ROLE','productionAssi'),(541,'WagonType','createWagonType','*','ALLOW','ROLE','productionAssi'),(542,'WagonType','deleteWagonType','*','ALLOW','ROLE','productionAssi'),(543,'WagonType','editWagonType','*','ALLOW','ROLE','productionAssi'),(544,'Docuware','deliveryNoteEmail','WRITE','ALLOW','ROLE','employee'),(545,'Agency','find','READ','ALLOW','ROLE','employee'),(546,'Agency','seeExpired','READ','ALLOW','ROLE','coolerAssist'),(547,'WorkerLog','models','READ','ALLOW','ROLE','hr'),(548,'Ticket','editDiscount','WRITE','ALLOW','ROLE','claimManager'),(549,'Ticket','editDiscount','WRITE','ALLOW','ROLE','salesPerson'),(550,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','salesAssistant'),(551,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','deliveryBoss'),(552,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','buyer'),(553,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','claimManager'),(554,'Ticket','deleteTicketWithPartPrepared','WRITE','ALLOW','ROLE','salesAssistant'),(555,'Ticket','editZone','WRITE','ALLOW','ROLE','deliveryBoss'),(556,'State','editableStates','READ','ALLOW','ROLE','employee'),(557,'State','seeEditableStates','READ','ALLOW','ROLE','administrative'),(558,'State','seeEditableStates','READ','ALLOW','ROLE','production'),(559,'State','isSomeEditable','READ','ALLOW','ROLE','salesPerson'),(560,'State','isAllEditable','READ','ALLOW','ROLE','production'),(561,'State','isAllEditable','READ','ALLOW','ROLE','administrative'),(562,'Agency','seeExpired','READ','ALLOW','ROLE','administrative'),(563,'Agency','seeExpired','READ','ALLOW','ROLE','productionBoss'),(564,'Claim','createAfterDeadline','WRITE','ALLOW','ROLE','claimManager'),(565,'Client','editAddressLogifloraAllowed','WRITE','ALLOW','ROLE','salesAssistant'),(566,'Client','editFiscalDataWithoutTaxDataCheck','WRITE','ALLOW','ROLE','salesAssistant'),(567,'Client','editVerifiedDataWithoutTaxDataCheck','WRITE','ALLOW','ROLE','salesAssistant'),(568,'Client','editCredit','WRITE','ALLOW','ROLE','financialBoss'),(569,'Client','zeroCreditEditor','WRITE','ALLOW','ROLE','financialBoss'),(570,'InvoiceOut','canCreatePdf','WRITE','ALLOW','ROLE','invoicing'),(571,'Supplier','editPayMethodCheck','WRITE','ALLOW','ROLE','financial'),(572,'Worker','isTeamBoss','WRITE','ALLOW','ROLE','teamBoss'),(573,'Worker','forceIsSubordinate','READ','ALLOW','ROLE','hr'),(574,'Claim','editState','WRITE','ALLOW','ROLE','claimManager'),(575,'Claim','find','READ','ALLOW','ROLE','salesPerson'),(576,'Claim','findById','READ','ALLOW','ROLE','salesPerson'),(577,'Claim','findOne','READ','ALLOW','ROLE','salesPerson'),(578,'Claim','getSummary','READ','ALLOW','ROLE','salesPerson'),(579,'Claim','updateClaim','WRITE','ALLOW','ROLE','salesPerson'),(580,'Claim','regularizeClaim','WRITE','ALLOW','ROLE','claimManager'),(581,'Claim','updateClaimDestination','WRITE','ALLOW','ROLE','claimManager'),(582,'Claim','downloadFile','READ','ALLOW','ROLE','claimManager'),(583,'Claim','deleteById','WRITE','ALLOW','ROLE','claimManager'),(584,'Claim','filter','READ','ALLOW','ROLE','salesPerson'),(585,'Claim','logs','READ','ALLOW','ROLE','claimManager'),(586,'Ticket','find','READ','ALLOW','ROLE','employee'),(587,'Ticket','findById','READ','ALLOW','ROLE','employee'),(588,'Ticket','findOne','READ','ALLOW','ROLE','employee'),(589,'Ticket','getVolume','READ','ALLOW','ROLE','employee'),(590,'Ticket','getTotalVolume','READ','ALLOW','ROLE','employee'),(591,'Ticket','summary','READ','ALLOW','ROLE','employee'),(592,'Ticket','priceDifference','READ','ALLOW','ROLE','employee'),(593,'Ticket','componentUpdate','WRITE','ALLOW','ROLE','employee'),(594,'Ticket','new','WRITE','ALLOW','ROLE','employee'),(595,'Ticket','isEditable','READ','ALLOW','ROLE','employee'),(596,'Ticket','setDeleted','WRITE','ALLOW','ROLE','salesPerson'),(597,'Ticket','restore','WRITE','ALLOW','ROLE','employee'),(598,'Ticket','getSales','READ','ALLOW','ROLE','employee'),(599,'Ticket','getSalesPersonMana','READ','ALLOW','ROLE','employee'),(600,'Ticket','filter','READ','ALLOW','ROLE','employee'),(601,'Ticket','makeInvoice','WRITE','ALLOW','ROLE','employee'),(602,'Ticket','updateEditableTicket','WRITE','ALLOW','ROLE','employee'),(603,'Ticket','updateDiscount','WRITE','ALLOW','ROLE','employee'),(604,'Ticket','transferSales','WRITE','ALLOW','ROLE','employee'),(605,'Ticket','sendSms','WRITE','ALLOW','ROLE','employee'),(606,'Ticket','isLocked','READ','ALLOW','ROLE','employee'),(607,'Ticket','freightCost','READ','ALLOW','ROLE','employee'),(608,'Ticket','getComponentsSum','READ','ALLOW','ROLE','employee'),(609,'Ticket','updateAttributes','WRITE','ALLOW','ROLE','delivery'),(610,'Ticket','deliveryNoteCsv','READ','ALLOW','ROLE','employee'),(611,'State','find','READ','ALLOW','ROLE','employee'),(612,'State','findById','READ','ALLOW','ROLE','employee'),(613,'State','findOne','READ','ALLOW','ROLE','employee'),(614,'Worker','find','READ','ALLOW','ROLE','employee'),(615,'Worker','findById','READ','ALLOW','ROLE','employee'),(616,'Worker','findOne','READ','ALLOW','ROLE','employee'),(617,'Worker','filter','READ','ALLOW','ROLE','employee'),(618,'Worker','getWorkedHours','READ','ALLOW','ROLE','employee'),(619,'Worker','active','READ','ALLOW','ROLE','employee'),(620,'Worker','activeWithRole','READ','ALLOW','ROLE','employee'),(621,'Worker','uploadFile','WRITE','ALLOW','ROLE','hr'),(622,'Worker','contracts','READ','ALLOW','ROLE','employee'),(623,'Worker','holidays','READ','ALLOW','ROLE','employee'),(624,'Worker','activeContract','READ','ALLOW','ROLE','employee'),(625,'Worker','activeWithInheritedRole','READ','ALLOW','ROLE','employee'),(626,'Ticket','collectionLabel','READ','ALLOW','ROLE','employee'),(628,'Ticket','expeditionPalletLabel','READ','ALLOW','ROLE','employee'),(629,'Ticket','editDiscount','WRITE','ALLOW','ROLE','artificialBoss'),(630,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','salesTeamBoss'),(635,'Ticket','updateAttributes','WRITE','ALLOW','ROLE','administrative'),(636,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','salesPerson'),(637,'Claim','downloadFile','READ','ALLOW','ROLE','salesPerson'),(638,'Agency','seeExpired','READ','ALLOW','ROLE','artificialBoss'),(639,'Agency','seeExpired','READ','ALLOW','ROLE','logisticAssistant'),(640,'Claim','filter','READ','ALLOW','ROLE','buyer'),(641,'Claim','find','READ','ALLOW','ROLE','buyer'),(642,'Claim','findById','READ','ALLOW','ROLE','buyer'),(643,'Claim','getSummary','READ','ALLOW','ROLE','buyer'),(644,'Claim','filter','READ','ALLOW','ROLE','handmadeBoss'),(645,'Claim','find','READ','ALLOW','ROLE','handmadeBoss'),(646,'Claim','findById','READ','ALLOW','ROLE','handmadeBoss'),(647,'Claim','getSummary','READ','ALLOW','ROLE','handmadeBoss'),(648,'Claim','__get__lines','READ','ALLOW','ROLE','claimManager'),(649,'Claim','__get__lines','READ','ALLOW','ROLE','salesPerson'),(650,'Claim','getSummary','READ','ALLOW','ROLE','deliveryBoss'),(651,'Claim','findById','READ','ALLOW','ROLE','deliveryBoss'),(652,'Claim','find','READ','ALLOW','ROLE','deliveryBoss'),(653,'Claim','filter','READ','ALLOW','ROLE','deliveryBoss'),(654,'Ticket','editZone','WRITE','ALLOW','ROLE','logisticAssistant'),(655,'Entry','addFromPackaging','WRITE','ALLOW','ROLE','production'),(656,'Entry','addFromBuy','WRITE','ALLOW','ROLE','production'),(657,'Supplier','getItemsPackaging','READ','ALLOW','ROLE','production'),(658,'Ticket','closeAll','WRITE','ALLOW','ROLE','system'),(659,'Account','*','*','ALLOW','ROLE','itManagement'),(660,'Account','*','READ','ALLOW','ROLE','employee'),(664,'MailForward','*','*','ALLOW','ROLE','itManagement'),(665,'Role','*','READ','ALLOW','ROLE','employee'),(666,'Role','*','WRITE','ALLOW','ROLE','it'),(667,'VnUser','*','*','ALLOW','ROLE','itManagement'),(668,'VnUser','__get__preview','READ','ALLOW','ROLE','employee'),(669,'VnUser','preview','*','ALLOW','ROLE','employee'),(670,'VnUser','create','*','ALLOW','ROLE','itManagement'),(671,'VnUser','renewToken','WRITE','ALLOW','ROLE','employee'),(672,'PackingSiteAdvanced','*','*','ALLOW','ROLE','production'),(673,'InvoiceOut','makePdfAndNotify','WRITE','ALLOW','ROLE','invoicing'),(674,'InvoiceOutConfig','*','READ','ALLOW','ROLE','invoicing'),(676,'Ticket','invoiceTickets','WRITE','ALLOW','ROLE','employee'),(680,'MailAliasAccount','*','READ','ALLOW','ROLE','employee'),(681,'MailAliasAccount','create','WRITE','ALLOW','ROLE','employee'),(682,'MailAliasAccount','deleteById','WRITE','ALLOW','ROLE','employee'),(683,'MailAliasAccount','canEditAlias','WRITE','ALLOW','ROLE','itManagement'),(684,'WorkerDisableExcluded','*','READ','ALLOW','ROLE','itManagement'),(685,'WorkerDisableExcluded','*','WRITE','ALLOW','ROLE','itManagement'),(686,'MailForward','*','*','ALLOW','ROLE','hr'),(687,'ClientSms','find','READ','ALLOW','ROLE','employee'),(688,'ClientSms','create','WRITE','ALLOW','ROLE','employee'),(689,'Vehicle','sorted','WRITE','ALLOW','ROLE','employee'),(690,'Roadmap','*','*','ALLOW','ROLE','palletizerBoss'),(691,'Roadmap','*','*','ALLOW','ROLE','productionBoss'),(692,'ExpeditionTruck','*','*','ALLOW','ROLE','palletizerBoss'),(693,'ExpeditionTruck','*','*','ALLOW','ROLE','productionBoss'),(694,'MailAliasAccount','canEditAlias','WRITE','ALLOW','ROLE','marketingBoss'),(695,'ViaexpressConfig','internationalExpedition','WRITE','ALLOW','ROLE','employee'),(696,'ViaexpressConfig','renderer','READ','ALLOW','ROLE','employee'),(697,'Ticket','transferClient','WRITE','ALLOW','ROLE','administrative'),(698,'Ticket','canEditWeekly','WRITE','ALLOW','ROLE','buyer'),(699,'TicketSms','find','READ','ALLOW','ROLE','salesPerson'),(701,'Docuware','upload','WRITE','ALLOW','ROLE','deliveryBoss'),(702,'Ticket','docuwareDownload','READ','ALLOW','ROLE','salesPerson'); +INSERT INTO `ACL` VALUES (3,'Address','*','*','ALLOW','ROLE','employee'),(5,'AgencyService','*','READ','ALLOW','ROLE','employee'),(9,'ClientObservation','*','*','ALLOW','ROLE','employee'),(11,'ContactChannel','*','READ','ALLOW','ROLE','trainee'),(13,'Employee','*','READ','ALLOW','ROLE','employee'),(14,'PayMethod','*','READ','ALLOW','ROLE','trainee'),(16,'FakeProduction','*','READ','ALLOW','ROLE','employee'),(17,'Warehouse','* ','READ','ALLOW','ROLE','trainee'),(20,'TicketState','*','*','ALLOW','ROLE','employee'),(24,'Delivery','*','READ','ALLOW','ROLE','employee'),(25,'Zone','*','READ','ALLOW','ROLE','employee'),(26,'ClientCredit','*','*','ALLOW','ROLE','employee'),(27,'ClientCreditLimit','*','READ','ALLOW','ROLE','trainee'),(30,'GreugeType','*','READ','ALLOW','ROLE','trainee'),(31,'Mandate','*','READ','ALLOW','ROLE','trainee'),(32,'MandateType','*','READ','ALLOW','ROLE','trainee'),(33,'Company','*','READ','ALLOW','ROLE','trainee'),(34,'Greuge','*','READ','ALLOW','ROLE','trainee'),(35,'AddressObservation','*','*','ALLOW','ROLE','employee'),(36,'ObservationType','*','*','ALLOW','ROLE','employee'),(37,'Greuge','*','WRITE','ALLOW','ROLE','employee'),(38,'AgencyMode','*','READ','ALLOW','ROLE','employee'),(39,'ItemTag','*','WRITE','ALLOW','ROLE','buyer'),(40,'ItemBotanical','*','WRITE','ALLOW','ROLE','buyer'),(41,'ItemBotanical','*','READ','ALLOW','ROLE','employee'),(42,'ItemPlacement','*','WRITE','ALLOW','ROLE','buyer'),(43,'ItemPlacement','*','WRITE','ALLOW','ROLE','replenisher'),(44,'ItemPlacement','*','READ','ALLOW','ROLE','employee'),(45,'ItemBarcode','*','READ','ALLOW','ROLE','employee'),(46,'ItemBarcode','*','WRITE','ALLOW','ROLE','buyer'),(47,'ItemBarcode','*','WRITE','ALLOW','ROLE','replenisher'),(51,'ItemTag','*','READ','ALLOW','ROLE','employee'),(53,'Item','*','READ','ALLOW','ROLE','employee'),(54,'Item','*','WRITE','ALLOW','ROLE','buyer'),(55,'Recovery','*','READ','ALLOW','ROLE','trainee'),(56,'Recovery','*','WRITE','ALLOW','ROLE','administrative'),(58,'CreditClassification','*','*','ALLOW','ROLE','insurance'),(60,'CreditInsurance','*','*','ALLOW','ROLE','insurance'),(61,'InvoiceOut','*','READ','ALLOW','ROLE','employee'),(63,'TicketObservation','*','*','ALLOW','ROLE','employee'),(64,'Route','*','READ','ALLOW','ROLE','employee'),(65,'Sale','*','READ','ALLOW','ROLE','employee'),(66,'TicketTracking','*','READ','ALLOW','ROLE','employee'),(68,'TicketPackaging','*','*','ALLOW','ROLE','employee'),(69,'Packaging','*','READ','ALLOW','ROLE','employee'),(70,'Packaging','*','WRITE','ALLOW','ROLE','logistic'),(72,'SaleComponent','*','READ','ALLOW','ROLE','employee'),(73,'Expedition','*','READ','ALLOW','ROLE','employee'),(74,'Expedition','*','WRITE','ALLOW','ROLE','deliveryBoss'),(75,'Expedition','*','WRITE','ALLOW','ROLE','production'),(76,'AnnualAverageInvoiced','*','READ','ALLOW','ROLE','employee'),(77,'WorkerMana','*','READ','ALLOW','ROLE','employee'),(78,'TicketTracking','*','WRITE','ALLOW','ROLE','production'),(79,'TicketTracking','state','*','ALLOW','ROLE','employee'),(80,'Sale','deleteSales','*','ALLOW','ROLE','employee'),(81,'Sale','moveToTicket','*','ALLOW','ROLE','employee'),(82,'Sale','updateQuantity','*','ALLOW','ROLE','employee'),(83,'Sale','updatePrice','*','ALLOW','ROLE','employee'),(84,'Sale','updateDiscount','*','ALLOW','ROLE','employee'),(85,'SaleTracking','*','READ','ALLOW','ROLE','employee'),(86,'Order','*','*','ALLOW','ROLE','employee'),(87,'OrderRow','*','*','ALLOW','ROLE','employee'),(88,'ClientContact','*','*','ALLOW','ROLE','employee'),(89,'Sale','moveToNewTicket','*','ALLOW','ROLE','employee'),(90,'Sale','reserve','*','ALLOW','ROLE','employee'),(91,'TicketWeekly','*','READ','ALLOW','ROLE','employee'),(94,'Agency','landsThatDay','*','ALLOW','ROLE','employee'),(96,'ClaimEnd','*','READ','ALLOW','ROLE','employee'),(97,'ClaimEnd','*','WRITE','ALLOW','ROLE','claimManager'),(98,'ClaimBeginning','*','*','ALLOW','ROLE','employee'),(99,'ClaimDevelopment','*','READ','ALLOW','ROLE','employee'),(100,'ClaimDevelopment','*','WRITE','ALLOW','ROLE','claimManager'),(102,'Claim','createFromSales','*','ALLOW','ROLE','employee'),(104,'Item','*','WRITE','ALLOW','ROLE','marketingBoss'),(105,'ItemBarcode','*','WRITE','ALLOW','ROLE','marketingBoss'),(106,'ItemBotanical','*','WRITE','ALLOW','ROLE','marketingBoss'),(108,'ItemPlacement','*','WRITE','ALLOW','ROLE','marketingBoss'),(109,'UserConfig','*','*','ALLOW','ROLE','employee'),(110,'Bank','*','READ','ALLOW','ROLE','trainee'),(111,'ClientLog','*','READ','ALLOW','ROLE','trainee'),(112,'Defaulter','*','READ','ALLOW','ROLE','employee'),(113,'ClientRisk','*','READ','ALLOW','ROLE','trainee'),(114,'Receipt','*','READ','ALLOW','ROLE','trainee'),(115,'Receipt','*','WRITE','ALLOW','ROLE','administrative'),(116,'BankEntity','*','*','ALLOW','ROLE','employee'),(117,'ClientSample','*','*','ALLOW','ROLE','employee'),(118,'WorkerTeam','*','*','ALLOW','ROLE','salesPerson'),(119,'Travel','*','READ','ALLOW','ROLE','employee'),(120,'Travel','*','WRITE','ALLOW','ROLE','buyer'),(121,'Item','regularize','*','ALLOW','ROLE','employee'),(122,'TicketRequest','*','*','ALLOW','ROLE','employee'),(124,'Client','confirmTransaction','WRITE','ALLOW','ROLE','administrative'),(125,'Agency','getAgenciesWithWarehouse','*','ALLOW','ROLE','employee'),(126,'Client','activeWorkersWithRole','*','ALLOW','ROLE','employee'),(127,'TicketLog','*','READ','ALLOW','ROLE','employee'),(129,'TicketService','*','*','ALLOW','ROLE','employee'),(130,'Expedition','*','WRITE','ALLOW','ROLE','packager'),(131,'CreditInsurance','*','READ','ALLOW','ROLE','trainee'),(132,'CreditClassification','*','READ','ALLOW','ROLE','trainee'),(133,'ItemTag','*','WRITE','ALLOW','ROLE','marketingBoss'),(135,'ZoneGeo','*','READ','ALLOW','ROLE','employee'),(136,'ZoneCalendar','*','READ','ALLOW','ROLE','employee'),(137,'ZoneIncluded','*','READ','ALLOW','ROLE','employee'),(138,'LabourHoliday','*','READ','ALLOW','ROLE','employee'),(139,'LabourHolidayLegend','*','READ','ALLOW','ROLE','employee'),(140,'LabourHolidayType','*','READ','ALLOW','ROLE','employee'),(141,'Zone','*','*','ALLOW','ROLE','logisticBoss'),(142,'ZoneCalendar','*','WRITE','ALLOW','ROLE','deliveryBoss'),(143,'ZoneIncluded','*','*','ALLOW','ROLE','deliveryBoss'),(144,'Stowaway','*','*','ALLOW','ROLE','employee'),(145,'Ticket','getPossibleStowaways','READ','ALLOW','ROLE','employee'),(147,'UserConfigView','*','*','ALLOW','ROLE','employee'),(148,'UserConfigView','*','*','ALLOW','ROLE','employee'),(149,'Sip','*','READ','ALLOW','ROLE','employee'),(150,'Sip','*','WRITE','ALLOW','ROLE','hr'),(151,'Department','*','READ','ALLOW','ROLE','employee'),(152,'Department','*','WRITE','ALLOW','ROLE','hr'),(153,'Route','*','READ','ALLOW','ROLE','employee'),(154,'Route','*','WRITE','ALLOW','ROLE','delivery'),(155,'Calendar','*','READ','ALLOW','ROLE','hr'),(156,'WorkerLabour','*','READ','ALLOW','ROLE','hr'),(157,'Calendar','absences','READ','ALLOW','ROLE','employee'),(158,'ItemTag','*','WRITE','ALLOW','ROLE','accessory'),(160,'TicketServiceType','*','READ','ALLOW','ROLE','employee'),(161,'TicketConfig','*','READ','ALLOW','ROLE','employee'),(162,'InvoiceOut','delete','WRITE','ALLOW','ROLE','invoicing'),(163,'InvoiceOut','book','WRITE','ALLOW','ROLE','invoicing'),(165,'TicketDms','*','*','ALLOW','ROLE','employee'),(167,'Worker','isSubordinate','READ','ALLOW','ROLE','employee'),(168,'Worker','mySubordinates','READ','ALLOW','ROLE','employee'),(169,'WorkerTimeControl','filter','READ','ALLOW','ROLE','employee'),(170,'WorkerTimeControl','addTime','WRITE','ALLOW','ROLE','employee'),(171,'TicketServiceType','*','WRITE','ALLOW','ROLE','administrative'),(172,'Sms','*','READ','ALLOW','ROLE','employee'),(173,'Sms','send','WRITE','ALLOW','ROLE','employee'),(176,'Device','*','*','ALLOW','ROLE','employee'),(177,'Device','*','*','ALLOW','ROLE','employee'),(178,'WorkerTimeControl','*','*','ALLOW','ROLE','employee'),(179,'ItemLog','*','READ','ALLOW','ROLE','employee'),(180,'RouteLog','*','READ','ALLOW','ROLE','employee'),(181,'Dms','removeFile','WRITE','ALLOW','ROLE','employee'),(182,'Dms','uploadFile','WRITE','ALLOW','ROLE','employee'),(183,'Dms','downloadFile','READ','ALLOW','ROLE','employee'),(184,'Client','uploadFile','WRITE','ALLOW','ROLE','employee'),(185,'ClientDms','removeFile','WRITE','ALLOW','ROLE','employee'),(186,'ClientDms','*','READ','ALLOW','ROLE','trainee'),(187,'Ticket','uploadFile','WRITE','ALLOW','ROLE','employee'),(190,'Route','updateVolume','WRITE','ALLOW','ROLE','deliveryBoss'),(191,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(192,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(194,'Postcode','*','WRITE','ALLOW','ROLE','deliveryBoss'),(195,'Ticket','addSale','WRITE','ALLOW','ROLE','employee'),(196,'Dms','updateFile','WRITE','ALLOW','ROLE','employee'),(197,'Dms','*','READ','ALLOW','ROLE','trainee'),(198,'ClaimDms','removeFile','WRITE','ALLOW','ROLE','employee'),(199,'ClaimDms','*','READ','ALLOW','ROLE','employee'),(200,'Claim','uploadFile','WRITE','ALLOW','ROLE','employee'),(201,'Sale','updateConcept','WRITE','ALLOW','ROLE','employee'),(202,'Claim','updateClaimAction','WRITE','ALLOW','ROLE','claimManager'),(203,'UserPhone','*','*','ALLOW','ROLE','employee'),(204,'WorkerDms','removeFile','WRITE','ALLOW','ROLE','hr'),(205,'WorkerDms','*','READ','ALLOW','ROLE','hr'),(206,'Chat','*','*','ALLOW','ROLE','employee'),(207,'Chat','sendMessage','*','ALLOW','ROLE','employee'),(208,'Sale','recalculatePrice','WRITE','ALLOW','ROLE','employee'),(209,'Ticket','recalculateComponents','WRITE','ALLOW','ROLE','employee'),(211,'TravelLog','*','READ','ALLOW','ROLE','buyer'),(212,'Thermograph','*','*','ALLOW','ROLE','buyer'),(213,'TravelThermograph','*','WRITE','ALLOW','ROLE','buyer'),(214,'Entry','*','*','ALLOW','ROLE','buyer'),(215,'TicketWeekly','*','WRITE','ALLOW','ROLE','buyer'),(216,'TravelThermograph','*','READ','ALLOW','ROLE','employee'),(218,'Intrastat','*','*','ALLOW','ROLE','buyer'),(221,'UserConfig','getUserConfig','READ','ALLOW','ROLE','account'),(222,'Client','*','READ','ALLOW','ROLE','trainee'),(226,'ClientObservation','*','READ','ALLOW','ROLE','trainee'),(227,'Address','*','READ','ALLOW','ROLE','trainee'),(228,'AddressObservation','*','READ','ALLOW','ROLE','trainee'),(230,'ClientCredit','*','READ','ALLOW','ROLE','trainee'),(231,'ClientContact','*','READ','ALLOW','ROLE','trainee'),(232,'ClientSample','*','READ','ALLOW','ROLE','trainee'),(233,'EntryLog','*','READ','ALLOW','ROLE','buyer'),(234,'WorkerLog','find','READ','ALLOW','ROLE','hr'),(235,'CustomsAgent','*','*','ALLOW','ROLE','employee'),(236,'Buy','*','*','ALLOW','ROLE','buyer'),(237,'WorkerDms','filter','*','ALLOW','ROLE','employee'),(238,'Town','*','WRITE','ALLOW','ROLE','deliveryBoss'),(239,'Province','*','WRITE','ALLOW','ROLE','deliveryBoss'),(240,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(241,'SupplierContact','*','WRITE','ALLOW','ROLE','administrative'),(242,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(244,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(248,'RoleMapping','*','READ','ALLOW','ROLE','account'),(249,'UserPassword','*','READ','ALLOW','ROLE','account'),(250,'Town','*','WRITE','ALLOW','ROLE','deliveryBoss'),(251,'Province','*','WRITE','ALLOW','ROLE','deliveryBoss'),(252,'Supplier','*','READ','ALLOW','ROLE','employee'),(253,'Supplier','*','WRITE','ALLOW','ROLE','administrative'),(254,'SupplierLog','*','READ','ALLOW','ROLE','employee'),(256,'Image','*','WRITE','ALLOW','ROLE','employee'),(257,'FixedPrice','*','*','ALLOW','ROLE','buyer'),(258,'PayDem','*','READ','ALLOW','ROLE','employee'),(259,'Client','createReceipt','*','ALLOW','ROLE','salesAssistant'),(260,'PrintServerQueue','*','WRITE','ALLOW','ROLE','employee'),(261,'SupplierAccount','*','*','ALLOW','ROLE','administrative'),(262,'Entry','*','*','ALLOW','ROLE','administrative'),(263,'InvoiceIn','*','*','ALLOW','ROLE','administrative'),(264,'StarredModule','*','*','ALLOW','ROLE','employee'),(265,'ItemBotanical','*','WRITE','ALLOW','ROLE','logisticBoss'),(266,'ZoneLog','*','READ','ALLOW','ROLE','employee'),(267,'Genus','*','WRITE','ALLOW','ROLE','logisticBoss'),(268,'Specie','*','WRITE','ALLOW','ROLE','logisticBoss'),(269,'InvoiceOut','createPdf','WRITE','ALLOW','ROLE','employee'),(270,'SupplierAddress','*','*','ALLOW','ROLE','employee'),(271,'SalesMonitor','*','*','ALLOW','ROLE','employee'),(272,'InvoiceInLog','*','READ','ALLOW','ROLE','employee'),(273,'InvoiceInTax','*','*','ALLOW','ROLE','administrative'),(274,'InvoiceInLog','*','READ','ALLOW','ROLE','administrative'),(275,'InvoiceOut','createManualInvoice','WRITE','ALLOW','ROLE','invoicing'),(276,'InvoiceOut','globalInvoicing','WRITE','ALLOW','ROLE','invoicing'),(278,'RoleInherit','*','WRITE','ALLOW','ROLE','grant'),(279,'MailAlias','*','*','ALLOW','ROLE','marketing'),(283,'EntryObservation','*','*','ALLOW','ROLE','buyer'),(284,'LdapConfig','*','*','ALLOW','ROLE','sysadmin'),(285,'SambaConfig','*','*','ALLOW','ROLE','sysadmin'),(286,'ACL','*','*','ALLOW','ROLE','developer'),(287,'AccessToken','*','*','ALLOW','ROLE','developer'),(293,'RoleInherit','*','*','ALLOW','ROLE','it'),(294,'RoleRole','*','*','ALLOW','ROLE','it'),(295,'AccountConfig','*','*','ALLOW','ROLE','sysadmin'),(296,'Collection','*','READ','ALLOW','ROLE','employee'),(297,'Sale','refund','WRITE','ALLOW','ROLE','invoicing'),(298,'InvoiceInDueDay','*','*','ALLOW','ROLE','administrative'),(299,'Collection','setSaleQuantity','*','ALLOW','ROLE','employee'),(302,'AgencyTerm','*','*','ALLOW','ROLE','administrative'),(303,'ClaimLog','*','READ','ALLOW','ROLE','claimManager'),(304,'Edi','updateData','WRITE','ALLOW','ROLE','employee'),(305,'EducationLevel','*','*','ALLOW','ROLE','employee'),(306,'InvoiceInIntrastat','*','*','ALLOW','ROLE','employee'),(307,'SupplierAgencyTerm','*','*','ALLOW','ROLE','administrative'),(308,'InvoiceInIntrastat','*','*','ALLOW','ROLE','employee'),(309,'Zone','getZoneClosing','*','ALLOW','ROLE','employee'),(310,'ExpeditionState','*','READ','ALLOW','ROLE','employee'),(311,'Expense','*','READ','ALLOW','ROLE','employee'),(312,'Expense','*','WRITE','ALLOW','ROLE','administrative'),(314,'SupplierActivity','*','READ','ALLOW','ROLE','employee'),(315,'SupplierActivity','*','WRITE','ALLOW','ROLE','administrative'),(316,'Dms','deleteTrashFiles','WRITE','ALLOW','ROLE','employee'),(317,'ClientUnpaid','*','*','ALLOW','ROLE','administrative'),(318,'MdbVersion','*','*','ALLOW','ROLE','developer'),(319,'ItemType','*','READ','ALLOW','ROLE','employee'),(320,'ItemType','*','WRITE','ALLOW','ROLE','buyer'),(321,'InvoiceOut','refund','WRITE','ALLOW','ROLE','invoicing'),(322,'InvoiceOut','refund','WRITE','ALLOW','ROLE','salesAssistant'),(323,'InvoiceOut','refund','WRITE','ALLOW','ROLE','claimManager'),(324,'Ticket','refund','WRITE','ALLOW','ROLE','invoicing'),(325,'Ticket','refund','WRITE','ALLOW','ROLE','salesAssistant'),(326,'Ticket','refund','WRITE','ALLOW','ROLE','claimManager'),(327,'Sale','refund','WRITE','ALLOW','ROLE','salesAssistant'),(328,'Sale','refund','WRITE','ALLOW','ROLE','claimManager'),(329,'TicketRefund','*','WRITE','ALLOW','ROLE','invoicing'),(330,'ClaimObservation','*','WRITE','ALLOW','ROLE','salesPerson'),(331,'ClaimObservation','*','READ','ALLOW','ROLE','salesPerson'),(332,'Client','setPassword','WRITE','ALLOW','ROLE','salesPerson'),(333,'Client','updateUser','WRITE','ALLOW','ROLE','salesPerson'),(334,'ShelvingLog','*','READ','ALLOW','ROLE','employee'),(335,'ZoneExclusionGeo','*','READ','ALLOW','ROLE','employee'),(336,'ZoneExclusionGeo','*','WRITE','ALLOW','ROLE','deliveryBoss'),(337,'Parking','*','*','ALLOW','ROLE','employee'),(338,'Shelving','*','*','ALLOW','ROLE','employee'),(339,'OsTicket','*','*','ALLOW','ROLE','employee'),(340,'OsTicketConfig','*','*','ALLOW','ROLE','it'),(341,'ClientConsumptionQueue','*','WRITE','ALLOW','ROLE','employee'),(342,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','employee'),(343,'Ticket','deliveryNoteEmail','WRITE','ALLOW','ROLE','employee'),(344,'Ticket','deliveryNoteCsvPdf','READ','ALLOW','ROLE','employee'),(345,'Ticket','deliveryNoteCsvEmail','READ','ALLOW','ROLE','employee'),(346,'Client','campaignMetricsPdf','READ','ALLOW','ROLE','employee'),(347,'Client','campaignMetricsEmail','WRITE','ALLOW','ROLE','employee'),(348,'Client','clientWelcomeHtml','READ','ALLOW','ROLE','employee'),(349,'Client','clientWelcomeEmail','WRITE','ALLOW','ROLE','employee'),(350,'Client','creditRequestPdf','READ','ALLOW','ROLE','employee'),(351,'Client','creditRequestHtml','READ','ALLOW','ROLE','employee'),(352,'Client','creditRequestEmail','WRITE','ALLOW','ROLE','employee'),(353,'Client','printerSetupHtml','READ','ALLOW','ROLE','employee'),(354,'Client','printerSetupEmail','WRITE','ALLOW','ROLE','employee'),(355,'Client','sepaCoreEmail','WRITE','ALLOW','ROLE','employee'),(356,'Client','letterDebtorPdf','READ','ALLOW','ROLE','employee'),(357,'Client','letterDebtorStHtml','READ','ALLOW','ROLE','employee'),(358,'Client','letterDebtorStEmail','WRITE','ALLOW','ROLE','employee'),(359,'Client','letterDebtorNdHtml','READ','ALLOW','ROLE','employee'),(360,'Client','letterDebtorNdEmail','WRITE','ALLOW','ROLE','employee'),(361,'Client','clientDebtStatementPdf','READ','ALLOW','ROLE','employee'),(362,'Client','clientDebtStatementHtml','READ','ALLOW','ROLE','employee'),(363,'Client','clientDebtStatementEmail','WRITE','ALLOW','ROLE','employee'),(364,'Client','incotermsAuthorizationPdf','READ','ALLOW','ROLE','employee'),(365,'Client','incotermsAuthorizationHtml','READ','ALLOW','ROLE','employee'),(366,'Client','incotermsAuthorizationEmail','WRITE','ALLOW','ROLE','employee'),(367,'Client','consumptionSendQueued','WRITE','ALLOW','ROLE','system'),(368,'InvoiceOut','invoiceEmail','WRITE','ALLOW','ROLE','employee'),(369,'InvoiceOut','exportationPdf','READ','ALLOW','ROLE','employee'),(370,'InvoiceOut','sendQueued','WRITE','ALLOW','ROLE','system'),(371,'Ticket','invoiceCsvPdf','READ','ALLOW','ROLE','employee'),(372,'Ticket','invoiceCsvEmail','WRITE','ALLOW','ROLE','employee'),(373,'Supplier','campaignMetricsPdf','READ','ALLOW','ROLE','employee'),(374,'Supplier','campaignMetricsEmail','WRITE','ALLOW','ROLE','employee'),(375,'Travel','extraCommunityPdf','READ','ALLOW','ROLE','employee'),(376,'Travel','extraCommunityEmail','WRITE','ALLOW','ROLE','employee'),(377,'Entry','entryOrderPdf','READ','ALLOW','ROLE','employee'),(378,'OsTicket','osTicketReportEmail','WRITE','ALLOW','ROLE','system'),(379,'Item','buyerWasteEmail','WRITE','ALLOW','ROLE','system'),(380,'Claim','claimPickupPdf','READ','ALLOW','ROLE','employee'),(381,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','claimManager'),(382,'Item','labelPdf','READ','ALLOW','ROLE','employee'),(383,'Sector','*','READ','ALLOW','ROLE','employee'),(384,'Sector','*','WRITE','ALLOW','ROLE','employee'),(385,'Route','driverRoutePdf','READ','ALLOW','ROLE','employee'),(386,'Route','driverRouteEmail','WRITE','ALLOW','ROLE','employee'),(387,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','customer'),(388,'Supplier','newSupplier','WRITE','ALLOW','ROLE','administrative'),(389,'ClaimRma','*','READ','ALLOW','ROLE','claimManager'),(390,'ClaimRma','*','WRITE','ALLOW','ROLE','claimManager'),(391,'Notification','*','WRITE','ALLOW','ROLE','system'),(392,'Boxing','*','*','ALLOW','ROLE','employee'),(393,'Url','*','READ','ALLOW','ROLE','employee'),(394,'Url','*','WRITE','ALLOW','ROLE','it'),(395,'ItemShelving','*','READ','ALLOW','ROLE','employee'),(396,'ItemShelving','*','WRITE','ALLOW','ROLE','production'),(397,'ItemShelvingPlacementSupplyStock','*','READ','ALLOW','ROLE','employee'),(398,'NotificationQueue','*','*','ALLOW','ROLE','employee'),(399,'InvoiceOut','clientsToInvoice','WRITE','ALLOW','ROLE','invoicing'),(400,'InvoiceOut','invoiceClient','WRITE','ALLOW','ROLE','invoicing'),(401,'Sale','editTracked','WRITE','ALLOW','ROLE','production'),(402,'Sale','editFloramondo','WRITE','ALLOW','ROLE','salesAssistant'),(403,'Receipt','balanceCompensationEmail','WRITE','ALLOW','ROLE','employee'),(404,'Receipt','balanceCompensationPdf','READ','ALLOW','ROLE','employee'),(405,'Ticket','getTicketsFuture','READ','ALLOW','ROLE','employee'),(406,'Ticket','merge','WRITE','ALLOW','ROLE','employee'),(407,'Sale','editFloramondo','WRITE','ALLOW','ROLE','logistic'),(408,'ZipConfig','*','*','ALLOW','ROLE','employee'),(409,'Item','*','WRITE','ALLOW','ROLE','administrative'),(410,'Sale','editCloned','WRITE','ALLOW','ROLE','buyer'),(411,'Sale','editCloned','WRITE','ALLOW','ROLE','salesAssistant'),(414,'MdbVersion','*','READ','ALLOW','ROLE','$everyone'),(416,'TicketLog','getChanges','READ','ALLOW','ROLE','employee'),(417,'Ticket','getTicketsAdvance','READ','ALLOW','ROLE','employee'),(418,'EntryLog','*','READ','ALLOW','ROLE','administrative'),(419,'Sale','editTracked','WRITE','ALLOW','ROLE','buyer'),(420,'MdbBranch','*','READ','ALLOW','ROLE','$everyone'),(421,'ItemShelvingSale','*','*','ALLOW','ROLE','employee'),(422,'Docuware','checkFile','READ','ALLOW','ROLE','employee'),(423,'Docuware','download','READ','ALLOW','ROLE','salesPerson'),(424,'Docuware','upload','WRITE','ALLOW','ROLE','productionAssi'),(425,'Docuware','deliveryNoteEmail','WRITE','ALLOW','ROLE','salesPerson'),(426,'TpvTransaction','confirm','WRITE','ALLOW','ROLE','$everyone'),(427,'TpvTransaction','start','WRITE','ALLOW','ROLE','$authenticated'),(428,'TpvTransaction','end','WRITE','ALLOW','ROLE','$authenticated'),(429,'ItemConfig','*','READ','ALLOW','ROLE','employee'),(431,'Tag','onSubmit','WRITE','ALLOW','ROLE','employee'),(432,'Worker','updateAttributes','WRITE','ALLOW','ROLE','hr'),(433,'Worker','createAbsence','*','ALLOW','ROLE','employee'),(434,'Worker','updateAbsence','WRITE','ALLOW','ROLE','employee'),(435,'Worker','deleteAbsence','*','ALLOW','ROLE','employee'),(436,'Worker','new','WRITE','ALLOW','ROLE','hr'),(438,'Client','getClientOrSupplierReference','READ','ALLOW','ROLE','employee'),(439,'NotificationSubscription','*','*','ALLOW','ROLE','employee'),(440,'NotificationAcl','*','READ','ALLOW','ROLE','employee'),(441,'MdbApp','*','READ','ALLOW','ROLE','$everyone'),(442,'MdbApp','*','*','ALLOW','ROLE','developer'),(443,'ItemConfig','*','*','ALLOW','ROLE','employee'),(444,'DeviceProduction','*','*','ALLOW','ROLE','hr'),(445,'DeviceProductionModels','*','*','ALLOW','ROLE','hr'),(446,'DeviceProductionState','*','*','ALLOW','ROLE','hr'),(447,'DeviceProductionUser','*','*','ALLOW','ROLE','hr'),(448,'DeviceProduction','*','*','ALLOW','ROLE','productionAssi'),(449,'DeviceProductionModels','*','*','ALLOW','ROLE','productionAssi'),(450,'DeviceProductionState','*','*','ALLOW','ROLE','productionAssi'),(451,'DeviceProductionUser','*','*','ALLOW','ROLE','productionAssi'),(452,'Worker','deallocatePDA','*','ALLOW','ROLE','hr'),(453,'Worker','allocatePDA','*','ALLOW','ROLE','hr'),(454,'Worker','deallocatePDA','*','ALLOW','ROLE','productionAssi'),(455,'Worker','allocatePDA','*','ALLOW','ROLE','productionAssi'),(456,'Zone','*','*','ALLOW','ROLE','deliveryBoss'),(457,'Account','setPassword','WRITE','ALLOW','ROLE','itManagement'),(458,'Operator','*','READ','ALLOW','ROLE','employee'),(459,'Operator','*','WRITE','ALLOW','ROLE','employee'),(460,'InvoiceIn','getSerial','READ','ALLOW','ROLE','administrative'),(461,'Ticket','saveSign','WRITE','ALLOW','ROLE','employee'),(462,'InvoiceOut','negativeBases','READ','ALLOW','ROLE','administrative'),(463,'InvoiceOut','negativeBasesCsv','READ','ALLOW','ROLE','administrative'),(464,'WorkerObservation','*','*','ALLOW','ROLE','hr'),(465,'ClientInforma','*','READ','ALLOW','ROLE','employee'),(466,'ClientInforma','*','WRITE','ALLOW','ROLE','financial'),(467,'Receipt','receiptEmail','*','ALLOW','ROLE','salesAssistant'),(468,'Client','setRating','WRITE','ALLOW','ROLE','financial'),(469,'Client','*','READ','ALLOW','ROLE','employee'),(470,'Client','addressesPropagateRe','*','ALLOW','ROLE','employee'),(471,'Client','canBeInvoiced','*','ALLOW','ROLE','employee'),(472,'Client','canCreateTicket','*','ALLOW','ROLE','employee'),(473,'Client','consumption','*','ALLOW','ROLE','employee'),(474,'Client','createAddress','*','ALLOW','ROLE','employee'),(475,'Client','createWithUser','*','ALLOW','ROLE','employee'),(476,'Client','extendedListFilter','*','ALLOW','ROLE','employee'),(477,'Client','getAverageInvoiced','*','ALLOW','ROLE','employee'),(478,'Client','getCard','*','ALLOW','ROLE','employee'),(479,'Client','getDebt','*','ALLOW','ROLE','employee'),(480,'Client','getMana','*','ALLOW','ROLE','employee'),(481,'Client','transactions','*','ALLOW','ROLE','employee'),(482,'Client','hasCustomerRole','*','ALLOW','ROLE','employee'),(483,'Client','isValidClient','*','ALLOW','ROLE','employee'),(484,'Client','lastActiveTickets','*','ALLOW','ROLE','employee'),(485,'Client','sendSms','*','ALLOW','ROLE','employee'),(486,'Client','setPassword','*','ALLOW','ROLE','employee'),(487,'Client','summary','*','ALLOW','ROLE','employee'),(488,'Client','updateAddress','*','ALLOW','ROLE','employee'),(489,'Client','updateFiscalData','*','ALLOW','ROLE','employee'),(491,'Client','uploadFile','*','ALLOW','ROLE','employee'),(492,'Client','campaignMetricsPdf','*','ALLOW','ROLE','employee'),(493,'Client','campaignMetricsEmail','*','ALLOW','ROLE','employee'),(494,'Client','clientWelcomeHtml','*','ALLOW','ROLE','employee'),(495,'Client','clientWelcomeEmail','*','ALLOW','ROLE','employee'),(496,'Client','printerSetupHtml','*','ALLOW','ROLE','employee'),(497,'Client','printerSetupEmail','*','ALLOW','ROLE','employee'),(498,'Client','sepaCoreEmail','*','ALLOW','ROLE','employee'),(499,'Client','letterDebtorPdf','*','ALLOW','ROLE','employee'),(500,'Client','letterDebtorStHtml','*','ALLOW','ROLE','employee'),(501,'Client','letterDebtorStEmail','*','ALLOW','ROLE','employee'),(502,'Client','letterDebtorNdHtml','*','ALLOW','ROLE','employee'),(503,'Client','letterDebtorNdEmail','*','ALLOW','ROLE','employee'),(504,'Client','clientDebtStatementPdf','*','ALLOW','ROLE','employee'),(505,'Client','clientDebtStatementHtml','*','ALLOW','ROLE','employee'),(506,'Client','clientDebtStatementEmail','*','ALLOW','ROLE','employee'),(507,'Client','creditRequestPdf','*','ALLOW','ROLE','employee'),(508,'Client','creditRequestHtml','*','ALLOW','ROLE','employee'),(509,'Client','creditRequestEmail','*','ALLOW','ROLE','employee'),(510,'Client','incotermsAuthorizationPdf','*','ALLOW','ROLE','employee'),(511,'Client','incotermsAuthorizationHtml','*','ALLOW','ROLE','employee'),(512,'Client','incotermsAuthorizationEmail','*','ALLOW','ROLE','employee'),(513,'Client','consumptionSendQueued','*','ALLOW','ROLE','employee'),(514,'Client','filter','*','ALLOW','ROLE','employee'),(515,'Client','getClientOrSupplierReference','*','ALLOW','ROLE','employee'),(516,'Client','upsert','*','ALLOW','ROLE','employee'),(517,'Client','create','*','ALLOW','ROLE','employee'),(518,'Client','replaceById','*','ALLOW','ROLE','employee'),(519,'Client','updateAttributes','*','ALLOW','ROLE','employee'),(520,'Client','updateAttributes','*','ALLOW','ROLE','employee'),(521,'Client','deleteById','*','ALLOW','ROLE','employee'),(522,'Client','replaceOrCreate','*','ALLOW','ROLE','employee'),(523,'Client','updateAll','*','ALLOW','ROLE','employee'),(524,'Client','upsertWithWhere','*','ALLOW','ROLE','employee'),(525,'Defaulter','observationEmail','WRITE','ALLOW','ROLE','employee'),(527,'VnUser','acl','READ','ALLOW','ROLE','account'),(528,'VnUser','getCurrentUserData','READ','ALLOW','ROLE','account'),(530,'Account','exists','READ','ALLOW','ROLE','account'),(531,'Account','exists','READ','ALLOW','ROLE','account'),(532,'UserLog','*','READ','ALLOW','ROLE','employee'),(533,'RoleLog','*','READ','ALLOW','ROLE','employee'),(534,'WagonType','*','*','ALLOW','ROLE','productionAssi'),(535,'WagonTypeColor','*','*','ALLOW','ROLE','productionAssi'),(536,'WagonTypeTray','*','*','ALLOW','ROLE','productionAssi'),(537,'WagonConfig','*','*','ALLOW','ROLE','productionAssi'),(538,'CollectionWagon','*','*','ALLOW','ROLE','productionAssi'),(539,'CollectionWagonTicket','*','*','ALLOW','ROLE','productionAssi'),(540,'Wagon','*','*','ALLOW','ROLE','productionAssi'),(541,'WagonType','createWagonType','*','ALLOW','ROLE','productionAssi'),(542,'WagonType','deleteWagonType','*','ALLOW','ROLE','productionAssi'),(543,'WagonType','editWagonType','*','ALLOW','ROLE','productionAssi'),(544,'Docuware','deliveryNoteEmail','WRITE','ALLOW','ROLE','employee'),(545,'Agency','find','READ','ALLOW','ROLE','employee'),(546,'Agency','seeExpired','READ','ALLOW','ROLE','coolerAssist'),(547,'WorkerLog','models','READ','ALLOW','ROLE','hr'),(548,'Ticket','editDiscount','WRITE','ALLOW','ROLE','claimManager'),(549,'Ticket','editDiscount','WRITE','ALLOW','ROLE','salesPerson'),(550,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','salesAssistant'),(551,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','deliveryBoss'),(552,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','buyer'),(553,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','claimManager'),(554,'Ticket','deleteTicketWithPartPrepared','WRITE','ALLOW','ROLE','salesAssistant'),(555,'Ticket','editZone','WRITE','ALLOW','ROLE','deliveryBoss'),(556,'State','editableStates','READ','ALLOW','ROLE','employee'),(557,'State','seeEditableStates','READ','ALLOW','ROLE','administrative'),(558,'State','seeEditableStates','READ','ALLOW','ROLE','production'),(559,'State','isSomeEditable','READ','ALLOW','ROLE','salesPerson'),(560,'State','isAllEditable','READ','ALLOW','ROLE','production'),(561,'State','isAllEditable','READ','ALLOW','ROLE','administrative'),(562,'Agency','seeExpired','READ','ALLOW','ROLE','administrative'),(563,'Agency','seeExpired','READ','ALLOW','ROLE','productionBoss'),(564,'Claim','createAfterDeadline','WRITE','ALLOW','ROLE','claimManager'),(565,'Client','editAddressLogifloraAllowed','WRITE','ALLOW','ROLE','salesAssistant'),(566,'Client','editFiscalDataWithoutTaxDataCheck','WRITE','ALLOW','ROLE','salesAssistant'),(567,'Client','editVerifiedDataWithoutTaxDataCheck','WRITE','ALLOW','ROLE','salesAssistant'),(568,'Client','editCredit','WRITE','ALLOW','ROLE','financialBoss'),(569,'Client','zeroCreditEditor','WRITE','ALLOW','ROLE','financialBoss'),(570,'InvoiceOut','canCreatePdf','WRITE','ALLOW','ROLE','invoicing'),(571,'Supplier','editPayMethodCheck','WRITE','ALLOW','ROLE','financial'),(572,'Worker','isTeamBoss','WRITE','ALLOW','ROLE','teamBoss'),(573,'Worker','forceIsSubordinate','READ','ALLOW','ROLE','hr'),(574,'Claim','editState','WRITE','ALLOW','ROLE','claimManager'),(575,'Claim','find','READ','ALLOW','ROLE','salesPerson'),(576,'Claim','findById','READ','ALLOW','ROLE','salesPerson'),(577,'Claim','findOne','READ','ALLOW','ROLE','salesPerson'),(578,'Claim','getSummary','READ','ALLOW','ROLE','salesPerson'),(579,'Claim','updateClaim','WRITE','ALLOW','ROLE','salesPerson'),(580,'Claim','regularizeClaim','WRITE','ALLOW','ROLE','claimManager'),(581,'Claim','updateClaimDestination','WRITE','ALLOW','ROLE','claimManager'),(582,'Claim','downloadFile','READ','ALLOW','ROLE','claimManager'),(583,'Claim','deleteById','WRITE','ALLOW','ROLE','claimManager'),(584,'Claim','filter','READ','ALLOW','ROLE','salesPerson'),(585,'Claim','logs','READ','ALLOW','ROLE','claimManager'),(586,'Ticket','find','READ','ALLOW','ROLE','employee'),(587,'Ticket','findById','READ','ALLOW','ROLE','employee'),(588,'Ticket','findOne','READ','ALLOW','ROLE','employee'),(589,'Ticket','getVolume','READ','ALLOW','ROLE','employee'),(590,'Ticket','getTotalVolume','READ','ALLOW','ROLE','employee'),(591,'Ticket','summary','READ','ALLOW','ROLE','employee'),(592,'Ticket','priceDifference','READ','ALLOW','ROLE','employee'),(593,'Ticket','componentUpdate','WRITE','ALLOW','ROLE','employee'),(594,'Ticket','new','WRITE','ALLOW','ROLE','employee'),(595,'Ticket','isEditable','READ','ALLOW','ROLE','employee'),(596,'Ticket','setDeleted','WRITE','ALLOW','ROLE','salesPerson'),(597,'Ticket','restore','WRITE','ALLOW','ROLE','employee'),(598,'Ticket','getSales','READ','ALLOW','ROLE','employee'),(599,'Ticket','getSalesPersonMana','READ','ALLOW','ROLE','employee'),(600,'Ticket','filter','READ','ALLOW','ROLE','employee'),(601,'Ticket','makeInvoice','WRITE','ALLOW','ROLE','employee'),(602,'Ticket','updateEditableTicket','WRITE','ALLOW','ROLE','employee'),(603,'Ticket','updateDiscount','WRITE','ALLOW','ROLE','employee'),(604,'Ticket','transferSales','WRITE','ALLOW','ROLE','employee'),(605,'Ticket','sendSms','WRITE','ALLOW','ROLE','employee'),(606,'Ticket','isLocked','READ','ALLOW','ROLE','employee'),(607,'Ticket','freightCost','READ','ALLOW','ROLE','employee'),(608,'Ticket','getComponentsSum','READ','ALLOW','ROLE','employee'),(609,'Ticket','updateAttributes','WRITE','ALLOW','ROLE','delivery'),(610,'Ticket','deliveryNoteCsv','READ','ALLOW','ROLE','employee'),(611,'State','find','READ','ALLOW','ROLE','employee'),(612,'State','findById','READ','ALLOW','ROLE','employee'),(613,'State','findOne','READ','ALLOW','ROLE','employee'),(614,'Worker','find','READ','ALLOW','ROLE','employee'),(615,'Worker','findById','READ','ALLOW','ROLE','employee'),(616,'Worker','findOne','READ','ALLOW','ROLE','employee'),(617,'Worker','filter','READ','ALLOW','ROLE','employee'),(618,'Worker','getWorkedHours','READ','ALLOW','ROLE','employee'),(619,'Worker','active','READ','ALLOW','ROLE','employee'),(620,'Worker','activeWithRole','READ','ALLOW','ROLE','employee'),(621,'Worker','uploadFile','WRITE','ALLOW','ROLE','hr'),(622,'Worker','contracts','READ','ALLOW','ROLE','employee'),(623,'Worker','holidays','READ','ALLOW','ROLE','employee'),(624,'Worker','activeContract','READ','ALLOW','ROLE','employee'),(625,'Worker','activeWithInheritedRole','READ','ALLOW','ROLE','employee'),(626,'Ticket','collectionLabel','READ','ALLOW','ROLE','employee'),(628,'Ticket','expeditionPalletLabel','READ','ALLOW','ROLE','employee'),(629,'Ticket','editDiscount','WRITE','ALLOW','ROLE','artificialBoss'),(630,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','salesTeamBoss'),(635,'Ticket','updateAttributes','WRITE','ALLOW','ROLE','administrative'),(636,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','salesPerson'),(637,'Claim','downloadFile','READ','ALLOW','ROLE','salesPerson'),(638,'Agency','seeExpired','READ','ALLOW','ROLE','artificialBoss'),(639,'Agency','seeExpired','READ','ALLOW','ROLE','logisticAssistant'),(640,'Claim','filter','READ','ALLOW','ROLE','buyer'),(641,'Claim','find','READ','ALLOW','ROLE','buyer'),(642,'Claim','findById','READ','ALLOW','ROLE','buyer'),(643,'Claim','getSummary','READ','ALLOW','ROLE','buyer'),(644,'Claim','filter','READ','ALLOW','ROLE','handmadeBoss'),(645,'Claim','find','READ','ALLOW','ROLE','handmadeBoss'),(646,'Claim','findById','READ','ALLOW','ROLE','handmadeBoss'),(647,'Claim','getSummary','READ','ALLOW','ROLE','handmadeBoss'),(648,'Claim','__get__lines','READ','ALLOW','ROLE','claimManager'),(649,'Claim','__get__lines','READ','ALLOW','ROLE','salesPerson'),(650,'Claim','getSummary','READ','ALLOW','ROLE','deliveryBoss'),(651,'Claim','findById','READ','ALLOW','ROLE','deliveryBoss'),(652,'Claim','find','READ','ALLOW','ROLE','deliveryBoss'),(653,'Claim','filter','READ','ALLOW','ROLE','deliveryBoss'),(654,'Ticket','editZone','WRITE','ALLOW','ROLE','logisticAssistant'),(655,'Entry','addFromPackaging','WRITE','ALLOW','ROLE','production'),(656,'Entry','addFromBuy','WRITE','ALLOW','ROLE','production'),(657,'Supplier','getItemsPackaging','READ','ALLOW','ROLE','production'),(658,'Ticket','closeAll','WRITE','ALLOW','ROLE','system'),(659,'Account','*','*','ALLOW','ROLE','itManagement'),(660,'Account','*','READ','ALLOW','ROLE','employee'),(664,'MailForward','*','*','ALLOW','ROLE','itManagement'),(665,'Role','*','READ','ALLOW','ROLE','employee'),(666,'Role','*','WRITE','ALLOW','ROLE','it'),(667,'VnUser','*','*','ALLOW','ROLE','itManagement'),(668,'VnUser','__get__preview','READ','ALLOW','ROLE','employee'),(669,'VnUser','preview','*','ALLOW','ROLE','employee'),(670,'VnUser','create','*','ALLOW','ROLE','itManagement'),(671,'VnUser','renewToken','WRITE','ALLOW','ROLE','employee'),(672,'PackingSiteAdvanced','*','*','ALLOW','ROLE','production'),(673,'InvoiceOut','makePdfAndNotify','WRITE','ALLOW','ROLE','invoicing'),(674,'InvoiceOutConfig','*','READ','ALLOW','ROLE','invoicing'),(676,'Ticket','invoiceTickets','WRITE','ALLOW','ROLE','employee'),(680,'MailAliasAccount','*','READ','ALLOW','ROLE','employee'),(681,'MailAliasAccount','create','WRITE','ALLOW','ROLE','employee'),(682,'MailAliasAccount','deleteById','WRITE','ALLOW','ROLE','employee'),(683,'MailAliasAccount','canEditAlias','WRITE','ALLOW','ROLE','itManagement'),(684,'WorkerDisableExcluded','*','READ','ALLOW','ROLE','itManagement'),(685,'WorkerDisableExcluded','*','WRITE','ALLOW','ROLE','itManagement'),(686,'MailForward','*','*','ALLOW','ROLE','hr'),(687,'ClientSms','find','READ','ALLOW','ROLE','employee'),(688,'ClientSms','create','WRITE','ALLOW','ROLE','employee'),(689,'Vehicle','sorted','WRITE','ALLOW','ROLE','employee'),(690,'Roadmap','*','*','ALLOW','ROLE','palletizerBoss'),(691,'Roadmap','*','*','ALLOW','ROLE','productionBoss'),(692,'ExpeditionTruck','*','*','ALLOW','ROLE','palletizerBoss'),(693,'ExpeditionTruck','*','*','ALLOW','ROLE','productionBoss'),(694,'MailAliasAccount','canEditAlias','WRITE','ALLOW','ROLE','marketingBoss'),(695,'ViaexpressConfig','internationalExpedition','WRITE','ALLOW','ROLE','employee'),(696,'ViaexpressConfig','renderer','READ','ALLOW','ROLE','employee'),(697,'Ticket','transferClient','WRITE','ALLOW','ROLE','administrative'),(698,'Ticket','canEditWeekly','WRITE','ALLOW','ROLE','buyer'),(699,'TicketSms','find','READ','ALLOW','ROLE','salesPerson'),(701,'Docuware','upload','WRITE','ALLOW','ROLE','deliveryBoss'),(702,'Ticket','docuwareDownload','READ','ALLOW','ROLE','salesPerson'); /*!40000 ALTER TABLE `ACL` ENABLE KEYS */; UNLOCK TABLES; diff --git a/front/core/directives/anchor.js b/front/core/directives/anchor.js index b460b3ada..81e252e04 100644 --- a/front/core/directives/anchor.js +++ b/front/core/directives/anchor.js @@ -8,7 +8,7 @@ export function stringifyParams(data) { return params; } -export function changeState($state, event, data) { +export function state($state, event, data) { const params = stringifyParams(data); $state.go(data.state, params); @@ -53,7 +53,7 @@ export function directive($state, $window) { if (ctrlPressed || data.target == '_blank') openNewTab($state, $window, event, data); else - changeState($state, event, data); + state($state, event, data); }); $element.on('mousedown', event => { diff --git a/modules/claim/front/summary/index.html b/modules/claim/front/summary/index.html index 3115cb451..877a8c0f2 100644 --- a/modules/claim/front/summary/index.html +++ b/modules/claim/front/summary/index.html @@ -21,7 +21,7 @@ value-field="id" show-field="description" url="claimStates" - on-change="$ctrl.changeState(value)"> + on-change="$ctrl.state(value)"> diff --git a/modules/claim/front/summary/index.js b/modules/claim/front/summary/index.js index 7cd4805e9..f1310c298 100644 --- a/modules/claim/front/summary/index.js +++ b/modules/claim/front/summary/index.js @@ -71,7 +71,7 @@ class Controller extends Summary { return this.vnFile.getPath(`/api/dms/${dmsId}/downloadFile`); } - changeState(value) { + state(value) { const params = { id: this.claim.id, claimStateFk: value diff --git a/modules/claim/front/summary/index.spec.js b/modules/claim/front/summary/index.spec.js index 8540a3a97..04a270c5f 100644 --- a/modules/claim/front/summary/index.spec.js +++ b/modules/claim/front/summary/index.spec.js @@ -28,14 +28,14 @@ describe('Claim', () => { }); }); - describe('changeState()', () => { + describe('state()', () => { it('should make an HTTP post query, then call the showSuccess()', () => { jest.spyOn(controller.vnApp, 'showSuccess').mockReturnThis(); const expectedParams = {id: 1, claimStateFk: 1}; $httpBackend.when('GET', `Claims/1/getSummary`).respond(200, 24); $httpBackend.expect('PATCH', `Claims/updateClaim/1`, expectedParams).respond(200); - controller.changeState(1); + controller.state(1); $httpBackend.flush(); expect(controller.vnApp.showSuccess).toHaveBeenCalled(); diff --git a/modules/ticket/back/methods/ticket-tracking/setDelivered.js b/modules/ticket/back/methods/ticket-tracking/setDelivered.js index bd6e32dcf..bfbc71942 100644 --- a/modules/ticket/back/methods/ticket-tracking/setDelivered.js +++ b/modules/ticket/back/methods/ticket-tracking/setDelivered.js @@ -47,7 +47,7 @@ module.exports = Self => { const promises = []; for (const id of ticketIds) { - const promise = models.TicketTracking.changeState(ctx, { + const promise = models.TicketTracking.state(ctx, { stateFk: state.id, workerFk: worker.id, ticketFk: id diff --git a/modules/ticket/back/methods/ticket-tracking/specs/changeState.spec.js b/modules/ticket/back/methods/ticket-tracking/specs/changeState.spec.js index 175bc4e4b..b01d02389 100644 --- a/modules/ticket/back/methods/ticket-tracking/specs/changeState.spec.js +++ b/modules/ticket/back/methods/ticket-tracking/specs/changeState.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); -describe('ticket changeState()', () => { +describe('ticket state()', () => { const salesPersonId = 18; const employeeId = 1; const productionId = 49; @@ -47,7 +47,7 @@ describe('ticket changeState()', () => { activeCtx.accessToken.userId = salesPersonId; const params = {ticketFk: 2, stateFk: 3}; - await models.TicketTracking.changeState(ctx, params, options); + await models.TicketTracking.state(ctx, params, options); await tx.rollback(); } catch (e) { @@ -69,7 +69,7 @@ describe('ticket changeState()', () => { activeCtx.accessToken.userId = employeeId; const params = {ticketFk: 11, stateFk: 13}; - await models.TicketTracking.changeState(ctx, params, options); + await models.TicketTracking.state(ctx, params, options); await tx.rollback(); } catch (e) { @@ -91,7 +91,7 @@ describe('ticket changeState()', () => { activeCtx.accessToken.userId = productionId; const params = {ticketFk: ticket.id, stateFk: 3}; - const ticketTracking = await models.TicketTracking.changeState(ctx, params, options); + const ticketTracking = await models.TicketTracking.state(ctx, params, options); expect(ticketTracking.__data.ticketFk).toBe(params.ticketFk); expect(ticketTracking.__data.stateFk).toBe(params.stateFk); @@ -115,7 +115,7 @@ describe('ticket changeState()', () => { const ctx = {req: {accessToken: {userId: 18}}}; const assignedState = await models.State.findOne({where: {code: 'PICKER_DESIGNED'}}, options); const params = {ticketFk: ticket.id, stateFk: assignedState.id, workerFk: 1}; - const res = await models.TicketTracking.changeState(ctx, params, options); + const res = await models.TicketTracking.state(ctx, params, options); expect(res.__data.ticketFk).toBe(params.ticketFk); expect(res.__data.stateFk).toBe(params.stateFk); diff --git a/modules/ticket/back/methods/ticket-tracking/changeState.js b/modules/ticket/back/methods/ticket-tracking/state.js similarity index 94% rename from modules/ticket/back/methods/ticket-tracking/changeState.js rename to modules/ticket/back/methods/ticket-tracking/state.js index 4ae9ab40c..cfc69b20c 100644 --- a/modules/ticket/back/methods/ticket-tracking/changeState.js +++ b/modules/ticket/back/methods/ticket-tracking/state.js @@ -1,7 +1,7 @@ const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { - Self.remoteMethodCtx('changeState', { + Self.remoteMethodCtx('state', { description: 'Change the state of a ticket', accessType: 'WRITE', accepts: [ @@ -18,12 +18,12 @@ module.exports = Self => { root: true }, http: { - path: `/changeState`, + path: `/state`, verb: 'POST' } }); - Self.changeState = async(ctx, params, options) => { + Self.state = async(ctx, params, options) => { const models = Self.app.models; const myOptions = {}; let tx; diff --git a/modules/ticket/back/models/ticket-tracking.js b/modules/ticket/back/models/ticket-tracking.js index 2e6d3403e..48e4c93d7 100644 --- a/modules/ticket/back/models/ticket-tracking.js +++ b/modules/ticket/back/models/ticket-tracking.js @@ -1,5 +1,5 @@ module.exports = function(Self) { - require('../methods/ticket-tracking/changeState')(Self); + require('../methods/ticket-tracking/state')(Self); require('../methods/ticket-tracking/setDelivered')(Self); Self.validatesPresenceOf('stateFk', {message: 'State cannot be blank'}); diff --git a/modules/ticket/front/sale/index.html b/modules/ticket/front/sale/index.html index be9e81964..a3bb861fe 100644 --- a/modules/ticket/front/sale/index.html +++ b/modules/ticket/front/sale/index.html @@ -15,7 +15,7 @@ + on-change="$ctrl.state(value)"> { + return this.$http.post('TicketTrackings/state', params).then(() => { this.vnApp.showSuccess(this.$t('Data saved!')); this.card.reload(); }).finally(() => this.resetChanges()); diff --git a/modules/ticket/front/sale/index.spec.js b/modules/ticket/front/sale/index.spec.js index 9da8e6e7c..a0906dd00 100644 --- a/modules/ticket/front/sale/index.spec.js +++ b/modules/ticket/front/sale/index.spec.js @@ -230,15 +230,15 @@ describe('Ticket', () => { }); }); - describe('changeState()', () => { + describe('state()', () => { it('should make an HTTP post query, then call the showSuccess(), reload() and resetChanges() methods', () => { jest.spyOn(controller.card, 'reload').mockReturnThis(); jest.spyOn(controller.vnApp, 'showSuccess').mockReturnThis(); jest.spyOn(controller, 'resetChanges').mockReturnThis(); const expectedParams = {ticketFk: 1, code: 'OK'}; - $httpBackend.expect('POST', `TicketTrackings/changeState`, expectedParams).respond(200); - controller.changeState('OK'); + $httpBackend.expect('POST', `TicketTrackings/state`, expectedParams).respond(200); + controller.state('OK'); $httpBackend.flush(); expect(controller.card.reload).toHaveBeenCalledWith(); diff --git a/modules/ticket/front/summary/index.html b/modules/ticket/front/summary/index.html index dd0e94f42..c35e5b118 100644 --- a/modules/ticket/front/summary/index.html +++ b/modules/ticket/front/summary/index.html @@ -18,7 +18,7 @@ value-field="code" fields="['id', 'name', 'alertLevel', 'code']" url="States/editableStates" - on-change="$ctrl.changeState(value)"> + on-change="$ctrl.state(value)"> { if ('id' in this.$params) this.reload(); }) diff --git a/modules/ticket/front/summary/index.spec.js b/modules/ticket/front/summary/index.spec.js index 599da73ae..b8c6f0513 100644 --- a/modules/ticket/front/summary/index.spec.js +++ b/modules/ticket/front/summary/index.spec.js @@ -43,15 +43,15 @@ describe('Ticket', () => { }); }); - describe('changeState()', () => { + describe('state()', () => { it('should change the state', () => { jest.spyOn(controller.vnApp, 'showSuccess'); const value = 'myTicketState'; let res = {id: 1, nickname: 'myNickname'}; $httpBackend.when('GET', `Tickets/1/summary`).respond(200, res); - $httpBackend.expectPOST(`TicketTrackings/changeState`).respond(200, 'ok'); - controller.changeState(value); + $httpBackend.expectPOST(`TicketTrackings/state`).respond(200, 'ok'); + controller.state(value); $httpBackend.flush(); expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Data saved!'); diff --git a/modules/ticket/front/tracking/edit/index.html b/modules/ticket/front/tracking/edit/index.html index bff8e71b1..90f045813 100644 --- a/modules/ticket/front/tracking/edit/index.html +++ b/modules/ticket/front/tracking/edit/index.html @@ -1,4 +1,4 @@ - + { + this.$http.post(`TicketTrackings/state`, this.params).then(() => { this.$.watcher.updateOriginalData(); this.card.reload(); this.vnApp.showSuccess(this.$t('Data saved!')); diff --git a/modules/ticket/front/tracking/edit/index.spec.js b/modules/ticket/front/tracking/edit/index.spec.js index 1ba5912b5..e97dc1337 100644 --- a/modules/ticket/front/tracking/edit/index.spec.js +++ b/modules/ticket/front/tracking/edit/index.spec.js @@ -61,7 +61,7 @@ describe('Ticket', () => { jest.spyOn(controller.vnApp, 'showSuccess'); jest.spyOn(controller.$state, 'go'); - $httpBackend.expectPOST(`TicketTrackings/changeState`, controller.params).respond({}); + $httpBackend.expectPOST(`TicketTrackings/state`, controller.params).respond({}); controller.onSubmit(); $httpBackend.flush(); diff --git a/modules/worker/front/time-control/index.js b/modules/worker/front/time-control/index.js index 38e6721d6..dae2a950b 100644 --- a/modules/worker/front/time-control/index.js +++ b/modules/worker/front/time-control/index.js @@ -385,7 +385,7 @@ class Controller extends Section { }); } - changeState(state, reason) { + state(state, reason) { this.state = state; this.reason = reason; this.repaint(); From d2cd522842dbb024f9812b68ed8a58fff4e2fc99 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Thu, 14 Sep 2023 07:47:10 +0200 Subject: [PATCH 087/427] refs #5652 modify:without fit --- db/changes/233801/00-item_setVisibleDiscard.sql | 13 +++++-------- db/changes/233801/00-ticketConfig.sql | 11 ----------- db/dump/fixtures.sql | 7 ++----- modules/client/back/methods/address/getAddress.js | 13 ++++++++----- .../back/methods/address/specs/getAddress.spec.js | 5 ++--- 5 files changed, 17 insertions(+), 32 deletions(-) diff --git a/db/changes/233801/00-item_setVisibleDiscard.sql b/db/changes/233801/00-item_setVisibleDiscard.sql index 1b9bf0ffb..e73a77046 100644 --- a/db/changes/233801/00-item_setVisibleDiscard.sql +++ b/db/changes/233801/00-item_setVisibleDiscard.sql @@ -14,9 +14,8 @@ BEGIN SELECT barcodeToItem(vItemFk) INTO vItemFk; - SELECT companyDefaultFk INTO vCompanyVnlFk - FROM ticketConfig ; - + SELECT DEFAULT(companyFk) INTO vCompanyVnlFk + FROM vn.ticket LIMIT 1; SELECT c.id INTO vClientFk FROM client c JOIN address a ON a.clientFk = c.id @@ -26,10 +25,8 @@ BEGIN FROM ticket t JOIN address a ON a.id = t.addressFk WHERE t.warehouseFk = vWarehouseFk - AND t.clientFk = vClientFk - AND DATE(t.shipped) = util.VN_CURDATE() - AND a.isDefaultAddress - LIMIT 1; + AND a.id = vAddressFk + AND DATE(t.shipped) = util.VN_CURDATE(); CALL cache.visible_refresh(vCalc, TRUE, vWarehouseFk); @@ -39,7 +36,7 @@ BEGIN util.VN_CURDATE(), vWarehouseFk, vCompanyVnlFk, - NULL, + vAddressFk, NULL, NULL, util.VN_CURDATE(), diff --git a/db/changes/233801/00-ticketConfig.sql b/db/changes/233801/00-ticketConfig.sql index 5cef1ba5f..5429878b4 100644 --- a/db/changes/233801/00-ticketConfig.sql +++ b/db/changes/233801/00-ticketConfig.sql @@ -1,15 +1,4 @@ -ALTER TABLE `vn`.`ticketConfig` ADD companyDefaultFk int(10) unsigned DEFAULT 442 NOT NULL COMMENT 'Compañía por defecto para crear ticket'; - -ALTER TABLE `vn`.`ticketConfig` ADD CONSTRAINT ticketConfig_FK FOREIGN KEY (companyDefaultFk) REFERENCES vn.company(id) ON DELETE CASCADE ON UPDATE CASCADE; - --- Se desactivan por utilizarse muy poco - -UPDATE vn.address - SET isDefaultAddress = 0, - isActive = 0 - WHERE id IN (6,47); - INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) VALUES('Item', 'setVisibleDiscard', 'WRITE', 'ALLOW', 'ROLE', 'employee'); diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 7ce39287e..4e56c8385 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -2959,11 +2959,8 @@ INSERT INTO `hedera`.`imageConfig` (`id`, `maxSize`, `useXsendfile`, `url`) VALUES (1, 0, 0, 'marvel.com'); ---fixtures for getaddressLastYear +--fixtures for getaddress UPDATE vn.client SET typeFk='loses' WHERE id=1101; - -UPDATE vn.ticket - SET created='2023-08-01 00:00:00' - WHERE id=6; \ No newline at end of file + \ No newline at end of file diff --git a/modules/client/back/methods/address/getAddress.js b/modules/client/back/methods/address/getAddress.js index a15fb8aba..86a23674f 100644 --- a/modules/client/back/methods/address/getAddress.js +++ b/modules/client/back/methods/address/getAddress.js @@ -1,6 +1,6 @@ module.exports = Self => { Self.remoteMethod('getAddress', { - description: 'Get all activated address client active', + description: 'Get all activated address with loses client activated', accessType: 'READ', accepts: [], returns: { @@ -12,10 +12,13 @@ module.exports = Self => { verb: 'GET' } }); - Self.getAddress = async() => { - const query = `CALL vn.address_getLoses()`; - const [result] = await Self.rawSql(query); - return result; + let getAddressQuery = ` + SELECT a.id, a.nickname + FROM vn.address a + JOIN vn.client c ON a.clientFk = c.id AND c.isActive = 1 + WHERE c.typeFk = 'loses' AND a.isActive = 1;`; + + return result = await Self.rawSql(getAddressQuery); }; }; diff --git a/modules/client/back/methods/address/specs/getAddress.spec.js b/modules/client/back/methods/address/specs/getAddress.spec.js index d2b219495..a86e1007c 100644 --- a/modules/client/back/methods/address/specs/getAddress.spec.js +++ b/modules/client/back/methods/address/specs/getAddress.spec.js @@ -1,10 +1,9 @@ const {models} = require('vn-loopback/server/server'); describe('getAddress()', () => { - it('return list of address last year', async() => { + it('return list of activated address with loses client activated', async() => { let response = await models.Address.getAddress(); - expect(response.length).toBeGreaterThan(0); - expect(response[0].addressFk).toEqual(1); + expect(response.length).toEqual(2); }); }); From 4c1ff2e4d7b53a7eaf15dea69b7b6f10bb6949d5 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Thu, 14 Sep 2023 08:27:49 +0200 Subject: [PATCH 088/427] refs #6141feat:buyer model --- back/model-config.json | 3 +++ back/models/buyer.json | 28 ++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 back/models/buyer.json diff --git a/back/model-config.json b/back/model-config.json index b88956dee..ebc0e321b 100644 --- a/back/model-config.json +++ b/back/model-config.json @@ -15,6 +15,9 @@ }, "Bank": { "dataSource": "vn" + }, + "Buyer": { + "dataSource": "vn" }, "Campaign": { "dataSource": "vn" diff --git a/back/models/buyer.json b/back/models/buyer.json new file mode 100644 index 000000000..a17d3b538 --- /dev/null +++ b/back/models/buyer.json @@ -0,0 +1,28 @@ +{ + "name": "Buyer", + "base": "VnModel", + "options": { + "mysql": { + "table": "buyer" + } + }, + "properties": { + "userFk": { + "type": "number", + "required": true, + "id": true + }, + "nickname": { + "type": "string", + "required": true + } + }, + "acls": [ + { + "accessType": "READ", + "principalType": "ROLE", + "principalId": "employee", + "permission": "ALLOW" + } + ] +} From 82631d6fcdf53aa8378e9848062f03e1f59ed72f Mon Sep 17 00:00:00 2001 From: jgallego Date: Thu, 14 Sep 2023 10:26:59 +0200 Subject: [PATCH 089/427] claimingRate divide por 100 --- modules/client/front/summary/index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/client/front/summary/index.html b/modules/client/front/summary/index.html index 15a55ec8c..c622913bb 100644 --- a/modules/client/front/summary/index.html +++ b/modules/client/front/summary/index.html @@ -255,7 +255,7 @@ value="{{$ctrl.summary.averageInvoiced.invoiced | currency: 'EUR':2}}"> + value="{{$ctrl.claimingRate($ctrl.summary.claimsRatio.claimingRate / 100) | percentage}}"> From 11109d72a69b9402387f507b318017b4d9f1c192 Mon Sep 17 00:00:00 2001 From: carlossa Date: Thu, 14 Sep 2023 11:36:09 +0200 Subject: [PATCH 090/427] move sql --- db/changes/{233601 => 233801}/00-firstScript.sql | 0 db/changes/{233401 => 233801}/01-deviceLog_acl.sql | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename db/changes/{233601 => 233801}/00-firstScript.sql (100%) rename db/changes/{233401 => 233801}/01-deviceLog_acl.sql (100%) diff --git a/db/changes/233601/00-firstScript.sql b/db/changes/233801/00-firstScript.sql similarity index 100% rename from db/changes/233601/00-firstScript.sql rename to db/changes/233801/00-firstScript.sql diff --git a/db/changes/233401/01-deviceLog_acl.sql b/db/changes/233801/01-deviceLog_acl.sql similarity index 100% rename from db/changes/233401/01-deviceLog_acl.sql rename to db/changes/233801/01-deviceLog_acl.sql From ca2257d29b858ddcd0eef6c1f602c02b5b29cbac Mon Sep 17 00:00:00 2001 From: jgallego Date: Thu, 14 Sep 2023 13:47:04 +0200 Subject: [PATCH 091/427] subo version 2340 --- CHANGELOG.md | 7 +++++++ db/changes/234001/.gitkeep | 0 package.json | 2 +- 3 files changed, 8 insertions(+), 1 deletion(-) create mode 100644 db/changes/234001/.gitkeep diff --git a/CHANGELOG.md b/CHANGELOG.md index acb5d7457..0573a6790 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,13 @@ 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). +## [2340.01] - 2023-10-05 + +### Added +### Changed + +### Fixed + ## [2338.01] - 2023-09-21 ### Added diff --git a/db/changes/234001/.gitkeep b/db/changes/234001/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/package.json b/package.json index 44a651af4..d250071a6 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "salix-back", - "version": "23.38.01", + "version": "23.40.01", "author": "Verdnatura Levante SL", "description": "Salix backend", "license": "GPL-3.0", From a44e5206a7f2701f9195fd9af64ae3a538c342c1 Mon Sep 17 00:00:00 2001 From: pablone Date: Thu, 14 Sep 2023 14:18:00 +0200 Subject: [PATCH 092/427] refs #6213 fixConcatBug --- modules/supplier/back/models/supplier.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/supplier/back/models/supplier.js b/modules/supplier/back/models/supplier.js index 0337fe9db..273c8c816 100644 --- a/modules/supplier/back/models/supplier.js +++ b/modules/supplier/back/models/supplier.js @@ -124,7 +124,7 @@ module.exports = Self => { const supplier = await Supplier.findById(id, null, ctx.options); if (supplier) - await supplier.updateAttribute('account', `${supplier.account}${id}`, ctx.options); + await supplier.updateAttribute('account', Number(supplier.account) + id, ctx.options); } }); From b756d2f938f715d3f4aa86326a02b7564c14def5 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Thu, 14 Sep 2023 18:03:30 +0200 Subject: [PATCH 093/427] refs #5652 modify --- .../233801/00-address_getLosesLastYear.sql | 14 --------- .../233801/00-item_setVisibleDiscard.sql | 6 ++-- db/dump/fixtures.sql | 31 +++++++++---------- .../client/back/methods/address/getAddress.js | 4 +-- 4 files changed, 19 insertions(+), 36 deletions(-) delete mode 100644 db/changes/233801/00-address_getLosesLastYear.sql diff --git a/db/changes/233801/00-address_getLosesLastYear.sql b/db/changes/233801/00-address_getLosesLastYear.sql deleted file mode 100644 index dc75c3121..000000000 --- a/db/changes/233801/00-address_getLosesLastYear.sql +++ /dev/null @@ -1,14 +0,0 @@ - -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`address_getLoses`() -BEGIN - SELECT t.addressFk , a.nickname, c.name - FROM ticket t - JOIN address a ON a.id = t.addressFk - JOIN client c ON a.clientFk = c.id - WHERE c.typeFk = 'loses' - AND a.isactive = 1 - GROUP BY t.addressFk; -END$$ -DELIMITER ; - diff --git a/db/changes/233801/00-item_setVisibleDiscard.sql b/db/changes/233801/00-item_setVisibleDiscard.sql index e73a77046..6ee66a947 100644 --- a/db/changes/233801/00-item_setVisibleDiscard.sql +++ b/db/changes/233801/00-item_setVisibleDiscard.sql @@ -16,9 +16,9 @@ BEGIN SELECT DEFAULT(companyFk) INTO vCompanyVnlFk FROM vn.ticket LIMIT 1; - SELECT c.id INTO vClientFk - FROM client c - JOIN address a ON a.clientFk = c.id + + SELECT a.clientFk INTO vClientFk + FROM address a WHERE a.id = vAddressFk; SELECT t.id INTO vTicketFk diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 03a805069..9be9d69f6 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -358,20 +358,20 @@ INSERT INTO `vn`.`contactChannel`(`id`, `name`) (4, 'GCN Channel'), (5, 'The Newspaper'); -INSERT INTO `vn`.`client`(`id`,`name`,`fi`,`socialName`,`contact`,`street`,`city`,`postcode`,`phone`,`mobile`,`isRelevant`,`email`,`iban`,`dueDay`,`accountingAccount`,`isEqualizated`,`provinceFk`,`hasToInvoice`,`credit`,`countryFk`,`isActive`,`gestdocFk`,`quality`,`payMethodFk`,`created`,`isToBeMailed`,`contactChannelFk`,`hasSepaVnl`,`hasCoreVnl`,`hasCoreVnh`,`riskCalculated`,`clientTypeFk`, `hasToInvoiceByAddress`,`isTaxDataChecked`,`isFreezed`,`creditInsurance`,`isCreatedAsServed`,`hasInvoiceSimplified`,`salesPersonFk`,`isVies`,`eypbc`, `businessTypeFk`) +INSERT INTO `vn`.`client`(`id`,`name`,`fi`,`socialName`,`contact`,`street`,`city`,`postcode`,`phone`,`mobile`,`isRelevant`,`email`,`iban`,`dueDay`,`accountingAccount`,`isEqualizated`,`provinceFk`,`hasToInvoice`,`credit`,`countryFk`,`isActive`,`gestdocFk`,`quality`,`payMethodFk`,`created`,`isToBeMailed`,`contactChannelFk`,`hasSepaVnl`,`hasCoreVnl`,`hasCoreVnh`,`riskCalculated`,`clientTypeFk`, `hasToInvoiceByAddress`,`isTaxDataChecked`,`isFreezed`,`creditInsurance`,`isCreatedAsServed`,`hasInvoiceSimplified`,`salesPersonFk`,`isVies`,`eypbc`, `businessTypeFk`,`typeFk`) VALUES - (1101, 'Bruce Wayne', '84612325V', 'BATMAN', 'Alfred', '1007 MOUNTAIN DRIVE, GOTHAM', 'Gotham', 46460, 1111111111, 222222222, 1, 'BruceWayne@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1, 'florist'), - (1102, 'Petter Parker', '87945234L', 'SPIDER MAN', 'Aunt May', '20 INGRAM STREET, QUEENS, USA', 'Gotham', 46460, 1111111111, 222222222, 1, 'PetterParker@mydomain.com', NULL, 0, 1234567890, 0, 2, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1, 'florist'), - (1103, 'Clark Kent', '06815934E', 'SUPER MAN', 'lois lane', '344 CLINTON STREET, APARTAMENT 3-D', 'Gotham', 46460, 1111111111, 222222222, 1, 'ClarkKent@mydomain.com', NULL, 0, 1234567890, 0, 3, 1, 0, 19, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1, 'florist'), - (1104, 'Tony Stark', '06089160W', 'IRON MAN', 'Pepper Potts', '10880 MALIBU POINT, 90265', 'Gotham', 46460, 1111111111, 222222222, 1, 'TonyStark@mydomain.com', NULL, 0, 1234567890, 0, 2, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1, 'florist'), - (1105, 'Max Eisenhardt', '251628698', 'MAGNETO', 'Rogue', 'UNKNOWN WHEREABOUTS', 'Gotham', 46460, 1111111111, 222222222, 1, 'MaxEisenhardt@mydomain.com', NULL, 0, 1234567890, 0, 3, 1, 300, 8, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 1, NULL, 0, 0, 18, 0, 1, 'florist'), - (1106, 'DavidCharlesHaller', '53136686Q', 'LEGION', 'Charles Xavier', 'CITY OF NEW YORK, NEW YORK, USA', 'Gotham', 46460, 1111111111, 222222222, 1, 'DavidCharlesHaller@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 0, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 0, NULL, 0, 0, 19, 0, 1, 'florist'), - (1107, 'Hank Pym', '09854837G', 'ANT MAN', 'Hawk', 'ANTHILL, SAN FRANCISCO, CALIFORNIA', 'Gotham', 46460, 1111111111, 222222222, 1, 'HankPym@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, 0, NULL, 0, 0, 19, 0, 1, 'florist'), - (1108, 'Charles Xavier', '22641921P', 'PROFESSOR X', 'Beast', '3800 VICTORY PKWY, CINCINNATI, OH 45207, USA', 'Gotham', 46460, 1111111111, 222222222, 1, 'CharlesXavier@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 1, NULL, 0, 0, 19, 0, 1, 'florist'), - (1109, 'Bruce Banner', '16104829E', 'HULK', 'Black widow', 'SOMEWHERE IN NEW YORK', 'Gotham', 46460, 1111111111, 222222222, 1, 'BruceBanner@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, 0, NULL, 0, 0, 9, 0, 1, 'florist'), - (1110, 'Jessica Jones', '58282869H', 'JESSICA JONES', 'Luke Cage', 'NYCC 2015 POSTER', 'Gotham', 46460, 1111111111, 222222222, 1, 'JessicaJones@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, 0, NULL, 0, 0, NULL, 0, 1, 'florist'), - (1111, 'Missing', NULL, 'MISSING MAN', 'Anton', 'THE SPACE, UNIVERSE FAR AWAY', 'Gotham', 46460, 1111111111, 222222222, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 4, 0, 1, 0, NULL, 1, 0, NULL, 0, 1, 'others'), - (1112, 'Trash', NULL, 'GARBAGE MAN', 'Unknown name', 'NEW YORK CITY, UNDERGROUND', 'Gotham', 46460, 1111111111, 222222222, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 4, 0, 1, 0, NULL, 1, 0, NULL, 0, 1, 'others'); + (1101, 'Bruce Wayne', '84612325V', 'BATMAN', 'Alfred', '1007 MOUNTAIN DRIVE, GOTHAM', 'Gotham', 46460, 1111111111, 222222222, 1, 'BruceWayne@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1, 'florist','loses'), + (1102, 'Petter Parker', '87945234L', 'SPIDER MAN', 'Aunt May', '20 INGRAM STREET, QUEENS, USA', 'Gotham', 46460, 1111111111, 222222222, 1, 'PetterParker@mydomain.com', NULL, 0, 1234567890, 0, 2, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1, 'florist','normal'), + (1103, 'Clark Kent', '06815934E', 'SUPER MAN', 'lois lane', '344 CLINTON STREET, APARTAMENT 3-D', 'Gotham', 46460, 1111111111, 222222222, 1, 'ClarkKent@mydomain.com', NULL, 0, 1234567890, 0, 3, 1, 0, 19, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1, 'florist','normal'), + (1104, 'Tony Stark', '06089160W', 'IRON MAN', 'Pepper Potts', '10880 MALIBU POINT, 90265', 'Gotham', 46460, 1111111111, 222222222, 1, 'TonyStark@mydomain.com', NULL, 0, 1234567890, 0, 2, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1, 'florist','normal'), + (1105, 'Max Eisenhardt', '251628698', 'MAGNETO', 'Rogue', 'UNKNOWN WHEREABOUTS', 'Gotham', 46460, 1111111111, 222222222, 1, 'MaxEisenhardt@mydomain.com', NULL, 0, 1234567890, 0, 3, 1, 300, 8, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 1, NULL, 0, 0, 18, 0, 1, 'florist','normal'), + (1106, 'DavidCharlesHaller', '53136686Q', 'LEGION', 'Charles Xavier', 'CITY OF NEW YORK, NEW YORK, USA', 'Gotham', 46460, 1111111111, 222222222, 1, 'DavidCharlesHaller@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 0, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 0, NULL, 0, 0, 19, 0, 1, 'florist','normal'), + (1107, 'Hank Pym', '09854837G', 'ANT MAN', 'Hawk', 'ANTHILL, SAN FRANCISCO, CALIFORNIA', 'Gotham', 46460, 1111111111, 222222222, 1, 'HankPym@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, 0, NULL, 0, 0, 19, 0, 1, 'florist','normal'), + (1108, 'Charles Xavier', '22641921P', 'PROFESSOR X', 'Beast', '3800 VICTORY PKWY, CINCINNATI, OH 45207, USA', 'Gotham', 46460, 1111111111, 222222222, 1, 'CharlesXavier@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 1, NULL, 0, 0, 19, 0, 1, 'florist','normal'), + (1109, 'Bruce Banner', '16104829E', 'HULK', 'Black widow', 'SOMEWHERE IN NEW YORK', 'Gotham', 46460, 1111111111, 222222222, 1, 'BruceBanner@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, 0, NULL, 0, 0, 9, 0, 1, 'florist','normal'), + (1110, 'Jessica Jones', '58282869H', 'JESSICA JONES', 'Luke Cage', 'NYCC 2015 POSTER', 'Gotham', 46460, 1111111111, 222222222, 1, 'JessicaJones@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, 0, NULL, 0, 0, NULL, 0, 1, 'florist','normal'), + (1111, 'Missing', NULL, 'MISSING MAN', 'Anton', 'THE SPACE, UNIVERSE FAR AWAY', 'Gotham', 46460, 1111111111, 222222222, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 4, 0, 1, 0, NULL, 1, 0, NULL, 0, 1, 'others','normal'), + (1112, 'Trash', NULL, 'GARBAGE MAN', 'Unknown name', 'NEW YORK CITY, UNDERGROUND', 'Gotham', 46460, 1111111111, 222222222, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 4, 0, 1, 0, NULL, 1, 0, NULL, 0, 1, 'others','normal'); INSERT INTO `vn`.`client`(`id`, `name`, `fi`, `socialName`, `contact`, `street`, `city`, `postcode`, `isRelevant`, `email`, `iban`,`dueDay`,`accountingAccount`, `isEqualizated`, `provinceFk`, `hasToInvoice`, `credit`, `countryFk`, `isActive`, `gestdocFk`, `quality`, `payMethodFk`,`created`, `isTaxDataChecked`) SELECT id, name, CONCAT(RPAD(CONCAT(id,9),8,id),'A'), CONCAT(name, 'Social'), CONCAT(name, 'Contact'), CONCAT(name, 'Street'), 'GOTHAM', 46460, 1, CONCAT(name,'@mydomain.com'), NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1,NULL, 10, 5, util.VN_CURDATE(), 1 @@ -2974,8 +2974,5 @@ INSERT INTO vn.XDiario (id, ASIEN, FECHA, SUBCTA, CONTRA, CONCEPTO, EURODEBE, EU (4, 2.0, util.VN_CURDATE(), '4300001104', NULL, 'n/fra T4444444', 8.88, NULL, NULL, NULL, '0', NULL, 0.00, NULL, NULL, NULL, NULL, NULL, '2', NULL, 1, 2, 'I.F.', 'Nombre Importador', 1, 0, 0, util.VN_CURDATE(), 0, 442, 0, 0, 0.00, NULL, NULL, util.VN_CURDATE(), NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, NULL, NULL, 0), (5, 2.0, util.VN_CURDATE(), '2000000000', '4300001104', 'n/fra T4444444 Tony Stark', NULL, 8.07, NULL, NULL, '0', NULL, 0.00, NULL, NULL, NULL, NULL, NULL, '2', NULL, 1, 2, 'I.F.', 'Nombre Importador', 1, 0, 0, util.VN_CURDATE(), 0, 442, 0, 0, 0.00, NULL, NULL, util.VN_CURDATE(), NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, NULL, NULL, 0), (6, 2.0, util.VN_CURDATE(), '4770000010', '4300001104', 'Inmovilizado pendiente : n/fra T4444444 Tony Stark', NULL, 0.81, 8.07, 'T', '4444444', 10.00, NULL, NULL, NULL, NULL, NULL, '', '2', '', 1, 1, '06089160W', 'IRON MAN', 1, 1, 0, util.VN_CURDATE(), 0, 442, 0, 0, 0.00, NULL, NULL, util.VN_CURDATE(), NULL, 1, 1, 1, 1, NULL, NULL, NULL, NULL, NULL, 0, NULL, NULL, 0); ---fixtures for getaddress -UPDATE vn.client - SET typeFk='loses' - WHERE id=1101; + \ No newline at end of file diff --git a/modules/client/back/methods/address/getAddress.js b/modules/client/back/methods/address/getAddress.js index 86a23674f..a62a0ec6f 100644 --- a/modules/client/back/methods/address/getAddress.js +++ b/modules/client/back/methods/address/getAddress.js @@ -16,8 +16,8 @@ module.exports = Self => { let getAddressQuery = ` SELECT a.id, a.nickname FROM vn.address a - JOIN vn.client c ON a.clientFk = c.id AND c.isActive = 1 - WHERE c.typeFk = 'loses' AND a.isActive = 1;`; + JOIN vn.client c ON a.clientFk = c.id AND c.isActive <> FALSE + WHERE c.typeFk = 'loses' AND a.isActive <> FALSE;`; return result = await Self.rawSql(getAddressQuery); }; From 0912bd40f3d51572cbd7c5923c056a0163ea31b4 Mon Sep 17 00:00:00 2001 From: carlossa Date: Fri, 15 Sep 2023 09:15:48 +0200 Subject: [PATCH 094/427] refs #5660 sql fix --- db/changes/{233801 => 234001}/01-deliveryAssistantACL.sql | 2 -- 1 file changed, 2 deletions(-) rename db/changes/{233801 => 234001}/01-deliveryAssistantACL.sql (93%) diff --git a/db/changes/233801/01-deliveryAssistantACL.sql b/db/changes/234001/01-deliveryAssistantACL.sql similarity index 93% rename from db/changes/233801/01-deliveryAssistantACL.sql rename to db/changes/234001/01-deliveryAssistantACL.sql index 34acf2427..9f3caf848 100644 --- a/db/changes/233801/01-deliveryAssistantACL.sql +++ b/db/changes/234001/01-deliveryAssistantACL.sql @@ -8,8 +8,6 @@ FROM account.roleInherit ri JOIN account.role r2 ON r2.id = ri.`role` WHERE r2.name = 'deliveryBoss'; -DELETE FROM `account`.`roleInherit` WHERE role = 57; - INSERT INTO `account`.`roleInherit` (role, inheritsFrom) SELECT (SELECT id FROM account.role WHERE name = 'deliveryBoss') role, (SELECT id FROM account.role WHERE name = 'deliveryAssistant') roleInherit; From 881a1ee0b84b5d9893a84b4adffa78f9c9eb750d Mon Sep 17 00:00:00 2001 From: sergiodt Date: Fri, 15 Sep 2023 11:24:17 +0200 Subject: [PATCH 095/427] refs #5652 modify: solved Tests --- .../back/methods/sales-monitor/specs/salesFilter.spec.js | 4 ++-- modules/ticket/back/methods/ticket/specs/filter.spec.js | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/modules/monitor/back/methods/sales-monitor/specs/salesFilter.spec.js b/modules/monitor/back/methods/sales-monitor/specs/salesFilter.spec.js index 4e0fb85b7..c3da7f08b 100644 --- a/modules/monitor/back/methods/sales-monitor/specs/salesFilter.spec.js +++ b/modules/monitor/back/methods/sales-monitor/specs/salesFilter.spec.js @@ -39,7 +39,7 @@ describe('SalesMonitor salesFilter()', () => { const filter = {}; const result = await models.SalesMonitor.salesFilter(ctx, filter, options); - expect(result.length).toBeGreaterThan(15); + expect(result.length).toBeGreaterThan(11); await tx.rollback(); } catch (e) { @@ -151,7 +151,7 @@ describe('SalesMonitor salesFilter()', () => { const result = await models.SalesMonitor.salesFilter(ctx, filter, options); const firstRow = result[0]; - expect(result.length).toEqual(12); + expect(result.length).toEqual(15); expect(firstRow.alertLevel).not.toEqual(0); await tx.rollback(); diff --git a/modules/ticket/back/methods/ticket/specs/filter.spec.js b/modules/ticket/back/methods/ticket/specs/filter.spec.js index 510446cab..2e5730980 100644 --- a/modules/ticket/back/methods/ticket/specs/filter.spec.js +++ b/modules/ticket/back/methods/ticket/specs/filter.spec.js @@ -68,7 +68,7 @@ describe('ticket filter()', () => { const filter = {}; const result = await models.Ticket.filter(ctx, filter, options); - expect(result.length).toEqual(6); + expect(result.length).toEqual(9); await tx.rollback(); } catch (e) { @@ -154,7 +154,7 @@ describe('ticket filter()', () => { const secondRow = result[1]; const thirdRow = result[2]; - expect(result.length).toBeGreaterThan(15); + expect(result.length).toBeGreaterThan(11); expect(firstRow.state).toEqual('Entregado'); expect(secondRow.state).toEqual('Entregado'); expect(thirdRow.state).toEqual('Entregado'); From 690df509d392970e1bde9edb1cef2ec941297b68 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 18 Sep 2023 07:10:12 +0200 Subject: [PATCH 096/427] refs #5684 Fixed no error --- back/methods/edi/updateData.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/back/methods/edi/updateData.js b/back/methods/edi/updateData.js index 10c81a795..6bebad1e4 100644 --- a/back/methods/edi/updateData.js +++ b/back/methods/edi/updateData.js @@ -139,7 +139,7 @@ module.exports = Self => { ftpClient.exec((err, response) => { if (err || response.error) { console.debug(`Error downloading checksum file... ${response.error}`); - return reject(err); + return reject(response.error || err); } resolve(response); From 55b53c86c436ca42f76a34c045dc9f961303106a Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 18 Sep 2023 07:38:30 +0200 Subject: [PATCH 097/427] refs #6213 formatfix --- modules/supplier/back/models/supplier.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/modules/supplier/back/models/supplier.js b/modules/supplier/back/models/supplier.js index 273c8c816..5cf357c13 100644 --- a/modules/supplier/back/models/supplier.js +++ b/modules/supplier/back/models/supplier.js @@ -123,8 +123,7 @@ module.exports = Self => { const {Supplier} = Self.app.models; const supplier = await Supplier.findById(id, null, ctx.options); - if (supplier) - await supplier.updateAttribute('account', Number(supplier.account) + id, ctx.options); + await supplier?.updateAttribute('account', Number(supplier.account) + id, ctx.options); } }); From fa87757d0f8452df28c936d52f7c0015622c972a Mon Sep 17 00:00:00 2001 From: carlossa Date: Mon, 18 Sep 2023 08:56:25 +0200 Subject: [PATCH 098/427] refs #5560 sql fix --- db/changes/234001/01-deliveryAssistantACL.sql | 2 -- 1 file changed, 2 deletions(-) diff --git a/db/changes/234001/01-deliveryAssistantACL.sql b/db/changes/234001/01-deliveryAssistantACL.sql index 9f3caf848..bde29d165 100644 --- a/db/changes/234001/01-deliveryAssistantACL.sql +++ b/db/changes/234001/01-deliveryAssistantACL.sql @@ -12,5 +12,3 @@ INSERT INTO `account`.`roleInherit` (role, inheritsFrom) SELECT (SELECT id FROM account.role WHERE name = 'deliveryBoss') role, (SELECT id FROM account.role WHERE name = 'deliveryAssistant') roleInherit; - -CALL account.role_syncPrivileges(); From 6c34421413c82ffb9ce255350e8fa3d8e7d990bd Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 18 Sep 2023 10:03:31 +0200 Subject: [PATCH 099/427] refs #5995 Requested changes --- loopback/locale/en.json | 3 ++- loopback/locale/es.json | 3 ++- modules/route/back/methods/route/downloadCmrsZip.js | 10 +++------- 3 files changed, 7 insertions(+), 9 deletions(-) diff --git a/loopback/locale/en.json b/loopback/locale/en.json index 46b48e2ea..30b0664b5 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -185,5 +185,6 @@ "You don't have enough privileges.": "You don't have enough privileges.", "This ticket is locked.": "This ticket is locked.", "This ticket is not editable.": "This ticket is not editable.", - "The ticket doesn't exist.": "The ticket doesn't exist." + "The ticket doesn't exist.": "The ticket doesn't exist.", + "The response is not a PDF": "The response is not a PDF" } diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 195b683ad..1cfcf2f83 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -315,5 +315,6 @@ "This ticket is not editable.": "Este ticket no es editable.", "The ticket doesn't exist.": "No existe el ticket.", "Social name should be uppercase": "La razón social debe ir en mayúscula", - "Street should be uppercase": "La dirección fiscal debe ir en mayúscula" + "Street should be uppercase": "La dirección fiscal debe ir en mayúscula", + "The response is not a PDF": "La respuesta no es un PDF" } diff --git a/modules/route/back/methods/route/downloadCmrsZip.js b/modules/route/back/methods/route/downloadCmrsZip.js index 61f9701b5..532e019b6 100644 --- a/modules/route/back/methods/route/downloadCmrsZip.js +++ b/modules/route/back/methods/route/downloadCmrsZip.js @@ -55,14 +55,10 @@ module.exports = Self => { responseType: 'arraybuffer', }); - if (response.headers['content-type'] !== 'application/pdf') { - throw new UserError(`The response for cmr id ${id} is not a PDF.`); - } + if (response.headers['content-type'] !== 'application/pdf') + throw new UserError(`The response is not a PDF`); - const pdfData = response.data; - const fileName = `${id}.pdf`; - - zip.file(fileName, pdfData, { binary: true }); + zip.file(`${id}.pdf`, response.data, { binary: true }); } const zipStream = zip.generateNodeStream({ streamFiles: true }); From cdf0951a1b9106015ffcf187d4c3da96e2e889d6 Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 18 Sep 2023 10:12:32 +0200 Subject: [PATCH 100/427] refs #6213 newSuplierSpec --- .../back/models/specs/supplier.spec.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/modules/supplier/back/models/specs/supplier.spec.js b/modules/supplier/back/models/specs/supplier.spec.js index f317f1fb9..d75c80558 100644 --- a/modules/supplier/back/models/specs/supplier.spec.js +++ b/modules/supplier/back/models/specs/supplier.spec.js @@ -124,4 +124,22 @@ describe('loopback model Supplier', () => { } }); }); + + describe('after save observer', () => { + fit('should update the account attribute when a new supplier is created', async() => { + const tx = await models.Supplier.beginTransaction({}); + const options = {transaction: tx}; + + try { + const newSupplier = await models.Supplier.create({id: '6969', name: 'Alfred Pennyworth'}, options); + const fetchedSupplier = await models.Supplier.findById(newSupplier.id, null, options); + + expect(fetchedSupplier.account).toEqual('4100006969'); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + }); }); From 63068ddfb82b42883935dae84bd2640439a7aa42 Mon Sep 17 00:00:00 2001 From: carlossa Date: Mon, 18 Sep 2023 12:24:26 +0200 Subject: [PATCH 101/427] refs #5660 call and insert --- db/changes/234001/01-deliveryAssistantACL.sql | 2 ++ 1 file changed, 2 insertions(+) diff --git a/db/changes/234001/01-deliveryAssistantACL.sql b/db/changes/234001/01-deliveryAssistantACL.sql index bde29d165..9f3caf848 100644 --- a/db/changes/234001/01-deliveryAssistantACL.sql +++ b/db/changes/234001/01-deliveryAssistantACL.sql @@ -12,3 +12,5 @@ INSERT INTO `account`.`roleInherit` (role, inheritsFrom) SELECT (SELECT id FROM account.role WHERE name = 'deliveryBoss') role, (SELECT id FROM account.role WHERE name = 'deliveryAssistant') roleInherit; + +CALL account.role_syncPrivileges(); From 3d1ee374c28d71a1a03a68b87f03f7ba4423e6ef Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 18 Sep 2023 13:49:45 +0200 Subject: [PATCH 102/427] refs #5673 feat: remove claim_development e2e --- .../{03_detail.spec.js => 02_detail.spec.js} | 2 +- e2e/paths/06-claim/02_development.spec.js | 97 ------------------- ...action.spec.js => 03_claim_action.spec.js} | 2 +- ...{05_summary.spec.js => 04_summary.spec.js} | 2 +- ...scriptor.spec.js => 05_descriptor.spec.js} | 2 +- .../{07_note.spec.js => 06_note.spec.js} | 0 6 files changed, 4 insertions(+), 101 deletions(-) rename e2e/paths/06-claim/{03_detail.spec.js => 02_detail.spec.js} (98%) delete mode 100644 e2e/paths/06-claim/02_development.spec.js rename e2e/paths/06-claim/{04_claim_action.spec.js => 03_claim_action.spec.js} (97%) rename e2e/paths/06-claim/{05_summary.spec.js => 04_summary.spec.js} (98%) rename e2e/paths/06-claim/{06_descriptor.spec.js => 05_descriptor.spec.js} (97%) rename e2e/paths/06-claim/{07_note.spec.js => 06_note.spec.js} (100%) diff --git a/e2e/paths/06-claim/03_detail.spec.js b/e2e/paths/06-claim/02_detail.spec.js similarity index 98% rename from e2e/paths/06-claim/03_detail.spec.js rename to e2e/paths/06-claim/02_detail.spec.js index ddcfd9302..eb4ac5d71 100644 --- a/e2e/paths/06-claim/03_detail.spec.js +++ b/e2e/paths/06-claim/02_detail.spec.js @@ -1,5 +1,5 @@ import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; +import getBrowser from '../../helpers/puppeteer.js'; // #1528 e2e claim/detail xdescribe('Claim detail', () => { diff --git a/e2e/paths/06-claim/02_development.spec.js b/e2e/paths/06-claim/02_development.spec.js deleted file mode 100644 index b7352dcc2..000000000 --- a/e2e/paths/06-claim/02_development.spec.js +++ /dev/null @@ -1,97 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Claim development', () => { - let browser; - let page; - - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('claimManager', 'claim'); - await page.accessToSearchResult('1'); - await page.accessToSection('claim.card.development'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it('should delete a development and create a new one', async() => { - await page.waitToClick(selectors.claimDevelopment.firstDeleteDevelopmentButton); - await page.waitToClick(selectors.claimDevelopment.addDevelopmentButton); - await page.autocompleteSearch(selectors.claimDevelopment.secondClaimReason, 'Baja calidad'); - await page.autocompleteSearch(selectors.claimDevelopment.secondClaimResult, 'Deshidratacion'); - await page.autocompleteSearch(selectors.claimDevelopment.secondClaimResponsible, 'Calidad general'); - await page.autocompleteSearch(selectors.claimDevelopment.secondClaimWorker, 'deliveryNick'); - await page.autocompleteSearch(selectors.claimDevelopment.secondClaimRedelivery, 'Reparto'); - await page.waitToClick(selectors.claimDevelopment.saveDevelopmentButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it(`should redirect to the next section of claims as the role is claimManager`, async() => { - await page.waitForState('claim.card.action'); - }); - - it('should edit a development', async() => { - await page.reloadSection('claim.card.development'); - await page.autocompleteSearch(selectors.claimDevelopment.firstClaimReason, 'Calor'); - await page.autocompleteSearch(selectors.claimDevelopment.firstClaimResult, 'Cocido'); - await page.autocompleteSearch(selectors.claimDevelopment.firstClaimResponsible, 'Calidad general'); - await page.autocompleteSearch(selectors.claimDevelopment.firstClaimWorker, 'adminAssistantNick'); - await page.autocompleteSearch(selectors.claimDevelopment.firstClaimRedelivery, 'Cliente'); - await page.waitToClick(selectors.claimDevelopment.saveDevelopmentButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it('should confirm the first development is the expected one', async() => { - await page.reloadSection('claim.card.development'); - const reason = await page - .waitToGetProperty(selectors.claimDevelopment.firstClaimReason, 'value'); - - const result = await page - .waitToGetProperty(selectors.claimDevelopment.firstClaimResult, 'value'); - - const responsible = await page - .waitToGetProperty(selectors.claimDevelopment.firstClaimResponsible, 'value'); - - const worker = await page - .waitToGetProperty(selectors.claimDevelopment.firstClaimWorker, 'value'); - - const redelivery = await page - .waitToGetProperty(selectors.claimDevelopment.firstClaimRedelivery, 'value'); - - expect(reason).toEqual('Calor'); - expect(result).toEqual('Baboso/Cocido'); - expect(responsible).toEqual('Calidad general'); - expect(worker).toEqual('adminAssistantNick'); - expect(redelivery).toEqual('Cliente'); - }); - - it('should confirm the second development is the expected one', async() => { - const reason = await page - .waitToGetProperty(selectors.claimDevelopment.secondClaimReason, 'value'); - - const result = await page - .waitToGetProperty(selectors.claimDevelopment.secondClaimResult, 'value'); - - const responsible = await page - .waitToGetProperty(selectors.claimDevelopment.secondClaimResponsible, 'value'); - - const worker = await page - .waitToGetProperty(selectors.claimDevelopment.secondClaimWorker, 'value'); - - const redelivery = await page - .waitToGetProperty(selectors.claimDevelopment.secondClaimRedelivery, 'value'); - - expect(reason).toEqual('Baja calidad'); - expect(result).toEqual('Deshidratacion'); - expect(responsible).toEqual('Calidad general'); - expect(worker).toEqual('deliveryNick'); - expect(redelivery).toEqual('Reparto'); - }); -}); diff --git a/e2e/paths/06-claim/04_claim_action.spec.js b/e2e/paths/06-claim/03_claim_action.spec.js similarity index 97% rename from e2e/paths/06-claim/04_claim_action.spec.js rename to e2e/paths/06-claim/03_claim_action.spec.js index 62a0ac232..ac6f72e37 100644 --- a/e2e/paths/06-claim/04_claim_action.spec.js +++ b/e2e/paths/06-claim/03_claim_action.spec.js @@ -1,5 +1,5 @@ import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; +import getBrowser from '../../helpers/puppeteer.js'; describe('Claim action path', () => { let browser; diff --git a/e2e/paths/06-claim/05_summary.spec.js b/e2e/paths/06-claim/04_summary.spec.js similarity index 98% rename from e2e/paths/06-claim/05_summary.spec.js rename to e2e/paths/06-claim/04_summary.spec.js index 1333ed01a..dda8484a6 100644 --- a/e2e/paths/06-claim/05_summary.spec.js +++ b/e2e/paths/06-claim/04_summary.spec.js @@ -1,6 +1,6 @@ import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; +import getBrowser from '../../helpers/puppeteer.js'; describe('Claim summary path', () => { let browser; diff --git a/e2e/paths/06-claim/06_descriptor.spec.js b/e2e/paths/06-claim/05_descriptor.spec.js similarity index 97% rename from e2e/paths/06-claim/06_descriptor.spec.js rename to e2e/paths/06-claim/05_descriptor.spec.js index 059bd68dd..49912b26a 100644 --- a/e2e/paths/06-claim/06_descriptor.spec.js +++ b/e2e/paths/06-claim/05_descriptor.spec.js @@ -1,5 +1,5 @@ import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; +import getBrowser from '../../helpers/puppeteer.js'; describe('Claim descriptor path', () => { let browser; diff --git a/e2e/paths/06-claim/07_note.spec.js b/e2e/paths/06-claim/06_note.spec.js similarity index 100% rename from e2e/paths/06-claim/07_note.spec.js rename to e2e/paths/06-claim/06_note.spec.js From 747ba0124c988287192526635cc3f5b4be3d2776 Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 18 Sep 2023 13:53:56 +0200 Subject: [PATCH 103/427] refs #4131 dumpedFixtures --- db/dump/dumpedFixtures.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/dump/dumpedFixtures.sql b/db/dump/dumpedFixtures.sql index 5ff2e03ef..2e1511b59 100644 --- a/db/dump/dumpedFixtures.sql +++ b/db/dump/dumpedFixtures.sql @@ -164,7 +164,7 @@ USE `salix`; LOCK TABLES `ACL` WRITE; /*!40000 ALTER TABLE `ACL` DISABLE KEYS */; -INSERT INTO `ACL` VALUES (3,'Address','*','*','ALLOW','ROLE','employee'),(5,'AgencyService','*','READ','ALLOW','ROLE','employee'),(9,'ClientObservation','*','*','ALLOW','ROLE','employee'),(11,'ContactChannel','*','READ','ALLOW','ROLE','trainee'),(13,'Employee','*','READ','ALLOW','ROLE','employee'),(14,'PayMethod','*','READ','ALLOW','ROLE','trainee'),(16,'FakeProduction','*','READ','ALLOW','ROLE','employee'),(17,'Warehouse','* ','READ','ALLOW','ROLE','trainee'),(20,'TicketState','*','*','ALLOW','ROLE','employee'),(24,'Delivery','*','READ','ALLOW','ROLE','employee'),(25,'Zone','*','READ','ALLOW','ROLE','employee'),(26,'ClientCredit','*','*','ALLOW','ROLE','employee'),(27,'ClientCreditLimit','*','READ','ALLOW','ROLE','trainee'),(30,'GreugeType','*','READ','ALLOW','ROLE','trainee'),(31,'Mandate','*','READ','ALLOW','ROLE','trainee'),(32,'MandateType','*','READ','ALLOW','ROLE','trainee'),(33,'Company','*','READ','ALLOW','ROLE','trainee'),(34,'Greuge','*','READ','ALLOW','ROLE','trainee'),(35,'AddressObservation','*','*','ALLOW','ROLE','employee'),(36,'ObservationType','*','*','ALLOW','ROLE','employee'),(37,'Greuge','*','WRITE','ALLOW','ROLE','employee'),(38,'AgencyMode','*','READ','ALLOW','ROLE','employee'),(39,'ItemTag','*','WRITE','ALLOW','ROLE','buyer'),(40,'ItemBotanical','*','WRITE','ALLOW','ROLE','buyer'),(41,'ItemBotanical','*','READ','ALLOW','ROLE','employee'),(42,'ItemPlacement','*','WRITE','ALLOW','ROLE','buyer'),(43,'ItemPlacement','*','WRITE','ALLOW','ROLE','replenisher'),(44,'ItemPlacement','*','READ','ALLOW','ROLE','employee'),(45,'ItemBarcode','*','READ','ALLOW','ROLE','employee'),(46,'ItemBarcode','*','WRITE','ALLOW','ROLE','buyer'),(47,'ItemBarcode','*','WRITE','ALLOW','ROLE','replenisher'),(51,'ItemTag','*','READ','ALLOW','ROLE','employee'),(53,'Item','*','READ','ALLOW','ROLE','employee'),(54,'Item','*','WRITE','ALLOW','ROLE','buyer'),(55,'Recovery','*','READ','ALLOW','ROLE','trainee'),(56,'Recovery','*','WRITE','ALLOW','ROLE','administrative'),(58,'CreditClassification','*','*','ALLOW','ROLE','insurance'),(60,'CreditInsurance','*','*','ALLOW','ROLE','insurance'),(61,'InvoiceOut','*','READ','ALLOW','ROLE','employee'),(63,'TicketObservation','*','*','ALLOW','ROLE','employee'),(64,'Route','*','READ','ALLOW','ROLE','employee'),(65,'Sale','*','READ','ALLOW','ROLE','employee'),(66,'TicketTracking','*','READ','ALLOW','ROLE','employee'),(68,'TicketPackaging','*','*','ALLOW','ROLE','employee'),(69,'Packaging','*','READ','ALLOW','ROLE','employee'),(70,'Packaging','*','WRITE','ALLOW','ROLE','logistic'),(72,'SaleComponent','*','READ','ALLOW','ROLE','employee'),(73,'Expedition','*','READ','ALLOW','ROLE','employee'),(74,'Expedition','*','WRITE','ALLOW','ROLE','deliveryBoss'),(75,'Expedition','*','WRITE','ALLOW','ROLE','production'),(76,'AnnualAverageInvoiced','*','READ','ALLOW','ROLE','employee'),(77,'WorkerMana','*','READ','ALLOW','ROLE','employee'),(78,'TicketTracking','*','WRITE','ALLOW','ROLE','production'),(79,'TicketTracking','state','*','ALLOW','ROLE','employee'),(80,'Sale','deleteSales','*','ALLOW','ROLE','employee'),(81,'Sale','moveToTicket','*','ALLOW','ROLE','employee'),(82,'Sale','updateQuantity','*','ALLOW','ROLE','employee'),(83,'Sale','updatePrice','*','ALLOW','ROLE','employee'),(84,'Sale','updateDiscount','*','ALLOW','ROLE','employee'),(85,'SaleTracking','*','READ','ALLOW','ROLE','employee'),(86,'Order','*','*','ALLOW','ROLE','employee'),(87,'OrderRow','*','*','ALLOW','ROLE','employee'),(88,'ClientContact','*','*','ALLOW','ROLE','employee'),(89,'Sale','moveToNewTicket','*','ALLOW','ROLE','employee'),(90,'Sale','reserve','*','ALLOW','ROLE','employee'),(91,'TicketWeekly','*','READ','ALLOW','ROLE','employee'),(94,'Agency','landsThatDay','*','ALLOW','ROLE','employee'),(96,'ClaimEnd','*','READ','ALLOW','ROLE','employee'),(97,'ClaimEnd','*','WRITE','ALLOW','ROLE','claimManager'),(98,'ClaimBeginning','*','*','ALLOW','ROLE','employee'),(99,'ClaimDevelopment','*','READ','ALLOW','ROLE','employee'),(100,'ClaimDevelopment','*','WRITE','ALLOW','ROLE','claimManager'),(102,'Claim','createFromSales','*','ALLOW','ROLE','employee'),(104,'Item','*','WRITE','ALLOW','ROLE','marketingBoss'),(105,'ItemBarcode','*','WRITE','ALLOW','ROLE','marketingBoss'),(106,'ItemBotanical','*','WRITE','ALLOW','ROLE','marketingBoss'),(108,'ItemPlacement','*','WRITE','ALLOW','ROLE','marketingBoss'),(109,'UserConfig','*','*','ALLOW','ROLE','employee'),(110,'Bank','*','READ','ALLOW','ROLE','trainee'),(111,'ClientLog','*','READ','ALLOW','ROLE','trainee'),(112,'Defaulter','*','READ','ALLOW','ROLE','employee'),(113,'ClientRisk','*','READ','ALLOW','ROLE','trainee'),(114,'Receipt','*','READ','ALLOW','ROLE','trainee'),(115,'Receipt','*','WRITE','ALLOW','ROLE','administrative'),(116,'BankEntity','*','*','ALLOW','ROLE','employee'),(117,'ClientSample','*','*','ALLOW','ROLE','employee'),(118,'WorkerTeam','*','*','ALLOW','ROLE','salesPerson'),(119,'Travel','*','READ','ALLOW','ROLE','employee'),(120,'Travel','*','WRITE','ALLOW','ROLE','buyer'),(121,'Item','regularize','*','ALLOW','ROLE','employee'),(122,'TicketRequest','*','*','ALLOW','ROLE','employee'),(124,'Client','confirmTransaction','WRITE','ALLOW','ROLE','administrative'),(125,'Agency','getAgenciesWithWarehouse','*','ALLOW','ROLE','employee'),(126,'Client','activeWorkersWithRole','*','ALLOW','ROLE','employee'),(127,'TicketLog','*','READ','ALLOW','ROLE','employee'),(129,'TicketService','*','*','ALLOW','ROLE','employee'),(130,'Expedition','*','WRITE','ALLOW','ROLE','packager'),(131,'CreditInsurance','*','READ','ALLOW','ROLE','trainee'),(132,'CreditClassification','*','READ','ALLOW','ROLE','trainee'),(133,'ItemTag','*','WRITE','ALLOW','ROLE','marketingBoss'),(135,'ZoneGeo','*','READ','ALLOW','ROLE','employee'),(136,'ZoneCalendar','*','READ','ALLOW','ROLE','employee'),(137,'ZoneIncluded','*','READ','ALLOW','ROLE','employee'),(138,'LabourHoliday','*','READ','ALLOW','ROLE','employee'),(139,'LabourHolidayLegend','*','READ','ALLOW','ROLE','employee'),(140,'LabourHolidayType','*','READ','ALLOW','ROLE','employee'),(141,'Zone','*','*','ALLOW','ROLE','logisticBoss'),(142,'ZoneCalendar','*','WRITE','ALLOW','ROLE','deliveryBoss'),(143,'ZoneIncluded','*','*','ALLOW','ROLE','deliveryBoss'),(144,'Stowaway','*','*','ALLOW','ROLE','employee'),(145,'Ticket','getPossibleStowaways','READ','ALLOW','ROLE','employee'),(147,'UserConfigView','*','*','ALLOW','ROLE','employee'),(148,'UserConfigView','*','*','ALLOW','ROLE','employee'),(149,'Sip','*','READ','ALLOW','ROLE','employee'),(150,'Sip','*','WRITE','ALLOW','ROLE','hr'),(151,'Department','*','READ','ALLOW','ROLE','employee'),(152,'Department','*','WRITE','ALLOW','ROLE','hr'),(153,'Route','*','READ','ALLOW','ROLE','employee'),(154,'Route','*','WRITE','ALLOW','ROLE','delivery'),(155,'Calendar','*','READ','ALLOW','ROLE','hr'),(156,'WorkerLabour','*','READ','ALLOW','ROLE','hr'),(157,'Calendar','absences','READ','ALLOW','ROLE','employee'),(158,'ItemTag','*','WRITE','ALLOW','ROLE','accessory'),(160,'TicketServiceType','*','READ','ALLOW','ROLE','employee'),(161,'TicketConfig','*','READ','ALLOW','ROLE','employee'),(162,'InvoiceOut','delete','WRITE','ALLOW','ROLE','invoicing'),(163,'InvoiceOut','book','WRITE','ALLOW','ROLE','invoicing'),(165,'TicketDms','*','*','ALLOW','ROLE','employee'),(167,'Worker','isSubordinate','READ','ALLOW','ROLE','employee'),(168,'Worker','mySubordinates','READ','ALLOW','ROLE','employee'),(169,'WorkerTimeControl','filter','READ','ALLOW','ROLE','employee'),(170,'WorkerTimeControl','addTime','WRITE','ALLOW','ROLE','employee'),(171,'TicketServiceType','*','WRITE','ALLOW','ROLE','administrative'),(172,'Sms','*','READ','ALLOW','ROLE','employee'),(173,'Sms','send','WRITE','ALLOW','ROLE','employee'),(176,'Device','*','*','ALLOW','ROLE','employee'),(177,'Device','*','*','ALLOW','ROLE','employee'),(178,'WorkerTimeControl','*','*','ALLOW','ROLE','employee'),(179,'ItemLog','*','READ','ALLOW','ROLE','employee'),(180,'RouteLog','*','READ','ALLOW','ROLE','employee'),(181,'Dms','removeFile','WRITE','ALLOW','ROLE','employee'),(182,'Dms','uploadFile','WRITE','ALLOW','ROLE','employee'),(183,'Dms','downloadFile','READ','ALLOW','ROLE','employee'),(184,'Client','uploadFile','WRITE','ALLOW','ROLE','employee'),(185,'ClientDms','removeFile','WRITE','ALLOW','ROLE','employee'),(186,'ClientDms','*','READ','ALLOW','ROLE','trainee'),(187,'Ticket','uploadFile','WRITE','ALLOW','ROLE','employee'),(190,'Route','updateVolume','WRITE','ALLOW','ROLE','deliveryBoss'),(191,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(192,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(194,'Postcode','*','WRITE','ALLOW','ROLE','deliveryBoss'),(195,'Ticket','addSale','WRITE','ALLOW','ROLE','employee'),(196,'Dms','updateFile','WRITE','ALLOW','ROLE','employee'),(197,'Dms','*','READ','ALLOW','ROLE','trainee'),(198,'ClaimDms','removeFile','WRITE','ALLOW','ROLE','employee'),(199,'ClaimDms','*','READ','ALLOW','ROLE','employee'),(200,'Claim','uploadFile','WRITE','ALLOW','ROLE','employee'),(201,'Sale','updateConcept','WRITE','ALLOW','ROLE','employee'),(202,'Claim','updateClaimAction','WRITE','ALLOW','ROLE','claimManager'),(203,'UserPhone','*','*','ALLOW','ROLE','employee'),(204,'WorkerDms','removeFile','WRITE','ALLOW','ROLE','hr'),(205,'WorkerDms','*','READ','ALLOW','ROLE','hr'),(206,'Chat','*','*','ALLOW','ROLE','employee'),(207,'Chat','sendMessage','*','ALLOW','ROLE','employee'),(208,'Sale','recalculatePrice','WRITE','ALLOW','ROLE','employee'),(209,'Ticket','recalculateComponents','WRITE','ALLOW','ROLE','employee'),(211,'TravelLog','*','READ','ALLOW','ROLE','buyer'),(212,'Thermograph','*','*','ALLOW','ROLE','buyer'),(213,'TravelThermograph','*','WRITE','ALLOW','ROLE','buyer'),(214,'Entry','*','*','ALLOW','ROLE','buyer'),(215,'TicketWeekly','*','WRITE','ALLOW','ROLE','buyer'),(216,'TravelThermograph','*','READ','ALLOW','ROLE','employee'),(218,'Intrastat','*','*','ALLOW','ROLE','buyer'),(221,'UserConfig','getUserConfig','READ','ALLOW','ROLE','account'),(222,'Client','*','READ','ALLOW','ROLE','trainee'),(226,'ClientObservation','*','READ','ALLOW','ROLE','trainee'),(227,'Address','*','READ','ALLOW','ROLE','trainee'),(228,'AddressObservation','*','READ','ALLOW','ROLE','trainee'),(230,'ClientCredit','*','READ','ALLOW','ROLE','trainee'),(231,'ClientContact','*','READ','ALLOW','ROLE','trainee'),(232,'ClientSample','*','READ','ALLOW','ROLE','trainee'),(233,'EntryLog','*','READ','ALLOW','ROLE','buyer'),(234,'WorkerLog','find','READ','ALLOW','ROLE','hr'),(235,'CustomsAgent','*','*','ALLOW','ROLE','employee'),(236,'Buy','*','*','ALLOW','ROLE','buyer'),(237,'WorkerDms','filter','*','ALLOW','ROLE','employee'),(238,'Town','*','WRITE','ALLOW','ROLE','deliveryBoss'),(239,'Province','*','WRITE','ALLOW','ROLE','deliveryBoss'),(240,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(241,'SupplierContact','*','WRITE','ALLOW','ROLE','administrative'),(242,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(244,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(248,'RoleMapping','*','READ','ALLOW','ROLE','account'),(249,'UserPassword','*','READ','ALLOW','ROLE','account'),(250,'Town','*','WRITE','ALLOW','ROLE','deliveryBoss'),(251,'Province','*','WRITE','ALLOW','ROLE','deliveryBoss'),(252,'Supplier','*','READ','ALLOW','ROLE','employee'),(253,'Supplier','*','WRITE','ALLOW','ROLE','administrative'),(254,'SupplierLog','*','READ','ALLOW','ROLE','employee'),(256,'Image','*','WRITE','ALLOW','ROLE','employee'),(257,'FixedPrice','*','*','ALLOW','ROLE','buyer'),(258,'PayDem','*','READ','ALLOW','ROLE','employee'),(259,'Client','createReceipt','*','ALLOW','ROLE','salesAssistant'),(260,'PrintServerQueue','*','WRITE','ALLOW','ROLE','employee'),(261,'SupplierAccount','*','*','ALLOW','ROLE','administrative'),(262,'Entry','*','*','ALLOW','ROLE','administrative'),(263,'InvoiceIn','*','*','ALLOW','ROLE','administrative'),(264,'StarredModule','*','*','ALLOW','ROLE','employee'),(265,'ItemBotanical','*','WRITE','ALLOW','ROLE','logisticBoss'),(266,'ZoneLog','*','READ','ALLOW','ROLE','employee'),(267,'Genus','*','WRITE','ALLOW','ROLE','logisticBoss'),(268,'Specie','*','WRITE','ALLOW','ROLE','logisticBoss'),(269,'InvoiceOut','createPdf','WRITE','ALLOW','ROLE','employee'),(270,'SupplierAddress','*','*','ALLOW','ROLE','employee'),(271,'SalesMonitor','*','*','ALLOW','ROLE','employee'),(272,'InvoiceInLog','*','READ','ALLOW','ROLE','employee'),(273,'InvoiceInTax','*','*','ALLOW','ROLE','administrative'),(274,'InvoiceInLog','*','READ','ALLOW','ROLE','administrative'),(275,'InvoiceOut','createManualInvoice','WRITE','ALLOW','ROLE','invoicing'),(276,'InvoiceOut','globalInvoicing','WRITE','ALLOW','ROLE','invoicing'),(278,'RoleInherit','*','WRITE','ALLOW','ROLE','grant'),(279,'MailAlias','*','*','ALLOW','ROLE','marketing'),(283,'EntryObservation','*','*','ALLOW','ROLE','buyer'),(284,'LdapConfig','*','*','ALLOW','ROLE','sysadmin'),(285,'SambaConfig','*','*','ALLOW','ROLE','sysadmin'),(286,'ACL','*','*','ALLOW','ROLE','developer'),(287,'AccessToken','*','*','ALLOW','ROLE','developer'),(293,'RoleInherit','*','*','ALLOW','ROLE','it'),(294,'RoleRole','*','*','ALLOW','ROLE','it'),(295,'AccountConfig','*','*','ALLOW','ROLE','sysadmin'),(296,'Collection','*','READ','ALLOW','ROLE','employee'),(297,'Sale','refund','WRITE','ALLOW','ROLE','invoicing'),(298,'InvoiceInDueDay','*','*','ALLOW','ROLE','administrative'),(299,'Collection','setSaleQuantity','*','ALLOW','ROLE','employee'),(302,'AgencyTerm','*','*','ALLOW','ROLE','administrative'),(303,'ClaimLog','*','READ','ALLOW','ROLE','claimManager'),(304,'Edi','updateData','WRITE','ALLOW','ROLE','employee'),(305,'EducationLevel','*','*','ALLOW','ROLE','employee'),(306,'InvoiceInIntrastat','*','*','ALLOW','ROLE','employee'),(307,'SupplierAgencyTerm','*','*','ALLOW','ROLE','administrative'),(308,'InvoiceInIntrastat','*','*','ALLOW','ROLE','employee'),(309,'Zone','getZoneClosing','*','ALLOW','ROLE','employee'),(310,'ExpeditionState','*','READ','ALLOW','ROLE','employee'),(311,'Expense','*','READ','ALLOW','ROLE','employee'),(312,'Expense','*','WRITE','ALLOW','ROLE','administrative'),(314,'SupplierActivity','*','READ','ALLOW','ROLE','employee'),(315,'SupplierActivity','*','WRITE','ALLOW','ROLE','administrative'),(316,'Dms','deleteTrashFiles','WRITE','ALLOW','ROLE','employee'),(317,'ClientUnpaid','*','*','ALLOW','ROLE','administrative'),(318,'MdbVersion','*','*','ALLOW','ROLE','developer'),(319,'ItemType','*','READ','ALLOW','ROLE','employee'),(320,'ItemType','*','WRITE','ALLOW','ROLE','buyer'),(321,'InvoiceOut','refund','WRITE','ALLOW','ROLE','invoicing'),(322,'InvoiceOut','refund','WRITE','ALLOW','ROLE','salesAssistant'),(323,'InvoiceOut','refund','WRITE','ALLOW','ROLE','claimManager'),(324,'Ticket','refund','WRITE','ALLOW','ROLE','invoicing'),(325,'Ticket','refund','WRITE','ALLOW','ROLE','salesAssistant'),(326,'Ticket','refund','WRITE','ALLOW','ROLE','claimManager'),(327,'Sale','refund','WRITE','ALLOW','ROLE','salesAssistant'),(328,'Sale','refund','WRITE','ALLOW','ROLE','claimManager'),(329,'TicketRefund','*','WRITE','ALLOW','ROLE','invoicing'),(330,'ClaimObservation','*','WRITE','ALLOW','ROLE','salesPerson'),(331,'ClaimObservation','*','READ','ALLOW','ROLE','salesPerson'),(332,'Client','setPassword','WRITE','ALLOW','ROLE','salesPerson'),(333,'Client','updateUser','WRITE','ALLOW','ROLE','salesPerson'),(334,'ShelvingLog','*','READ','ALLOW','ROLE','employee'),(335,'ZoneExclusionGeo','*','READ','ALLOW','ROLE','employee'),(336,'ZoneExclusionGeo','*','WRITE','ALLOW','ROLE','deliveryBoss'),(337,'Parking','*','*','ALLOW','ROLE','employee'),(338,'Shelving','*','*','ALLOW','ROLE','employee'),(339,'OsTicket','*','*','ALLOW','ROLE','employee'),(340,'OsTicketConfig','*','*','ALLOW','ROLE','it'),(341,'ClientConsumptionQueue','*','WRITE','ALLOW','ROLE','employee'),(342,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','employee'),(343,'Ticket','deliveryNoteEmail','WRITE','ALLOW','ROLE','employee'),(344,'Ticket','deliveryNoteCsvPdf','READ','ALLOW','ROLE','employee'),(345,'Ticket','deliveryNoteCsvEmail','READ','ALLOW','ROLE','employee'),(346,'Client','campaignMetricsPdf','READ','ALLOW','ROLE','employee'),(347,'Client','campaignMetricsEmail','WRITE','ALLOW','ROLE','employee'),(348,'Client','clientWelcomeHtml','READ','ALLOW','ROLE','employee'),(349,'Client','clientWelcomeEmail','WRITE','ALLOW','ROLE','employee'),(350,'Client','creditRequestPdf','READ','ALLOW','ROLE','employee'),(351,'Client','creditRequestHtml','READ','ALLOW','ROLE','employee'),(352,'Client','creditRequestEmail','WRITE','ALLOW','ROLE','employee'),(353,'Client','printerSetupHtml','READ','ALLOW','ROLE','employee'),(354,'Client','printerSetupEmail','WRITE','ALLOW','ROLE','employee'),(355,'Client','sepaCoreEmail','WRITE','ALLOW','ROLE','employee'),(356,'Client','letterDebtorPdf','READ','ALLOW','ROLE','employee'),(357,'Client','letterDebtorStHtml','READ','ALLOW','ROLE','employee'),(358,'Client','letterDebtorStEmail','WRITE','ALLOW','ROLE','employee'),(359,'Client','letterDebtorNdHtml','READ','ALLOW','ROLE','employee'),(360,'Client','letterDebtorNdEmail','WRITE','ALLOW','ROLE','employee'),(361,'Client','clientDebtStatementPdf','READ','ALLOW','ROLE','employee'),(362,'Client','clientDebtStatementHtml','READ','ALLOW','ROLE','employee'),(363,'Client','clientDebtStatementEmail','WRITE','ALLOW','ROLE','employee'),(364,'Client','incotermsAuthorizationPdf','READ','ALLOW','ROLE','employee'),(365,'Client','incotermsAuthorizationHtml','READ','ALLOW','ROLE','employee'),(366,'Client','incotermsAuthorizationEmail','WRITE','ALLOW','ROLE','employee'),(367,'Client','consumptionSendQueued','WRITE','ALLOW','ROLE','system'),(368,'InvoiceOut','invoiceEmail','WRITE','ALLOW','ROLE','employee'),(369,'InvoiceOut','exportationPdf','READ','ALLOW','ROLE','employee'),(370,'InvoiceOut','sendQueued','WRITE','ALLOW','ROLE','system'),(371,'Ticket','invoiceCsvPdf','READ','ALLOW','ROLE','employee'),(372,'Ticket','invoiceCsvEmail','WRITE','ALLOW','ROLE','employee'),(373,'Supplier','campaignMetricsPdf','READ','ALLOW','ROLE','employee'),(374,'Supplier','campaignMetricsEmail','WRITE','ALLOW','ROLE','employee'),(375,'Travel','extraCommunityPdf','READ','ALLOW','ROLE','employee'),(376,'Travel','extraCommunityEmail','WRITE','ALLOW','ROLE','employee'),(377,'Entry','entryOrderPdf','READ','ALLOW','ROLE','employee'),(378,'OsTicket','osTicketReportEmail','WRITE','ALLOW','ROLE','system'),(379,'Item','buyerWasteEmail','WRITE','ALLOW','ROLE','system'),(380,'Claim','claimPickupPdf','READ','ALLOW','ROLE','employee'),(381,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','claimManager'),(382,'Item','labelPdf','READ','ALLOW','ROLE','employee'),(383,'Sector','*','READ','ALLOW','ROLE','employee'),(384,'Sector','*','WRITE','ALLOW','ROLE','employee'),(385,'Route','driverRoutePdf','READ','ALLOW','ROLE','employee'),(386,'Route','driverRouteEmail','WRITE','ALLOW','ROLE','employee'),(387,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','customer'),(388,'Supplier','newSupplier','WRITE','ALLOW','ROLE','administrative'),(389,'ClaimRma','*','READ','ALLOW','ROLE','claimManager'),(390,'ClaimRma','*','WRITE','ALLOW','ROLE','claimManager'),(391,'Notification','*','WRITE','ALLOW','ROLE','system'),(392,'Boxing','*','*','ALLOW','ROLE','employee'),(393,'Url','*','READ','ALLOW','ROLE','employee'),(394,'Url','*','WRITE','ALLOW','ROLE','it'),(395,'ItemShelving','*','READ','ALLOW','ROLE','employee'),(396,'ItemShelving','*','WRITE','ALLOW','ROLE','production'),(397,'ItemShelvingPlacementSupplyStock','*','READ','ALLOW','ROLE','employee'),(398,'NotificationQueue','*','*','ALLOW','ROLE','employee'),(399,'InvoiceOut','clientsToInvoice','WRITE','ALLOW','ROLE','invoicing'),(400,'InvoiceOut','invoiceClient','WRITE','ALLOW','ROLE','invoicing'),(401,'Sale','editTracked','WRITE','ALLOW','ROLE','production'),(402,'Sale','editFloramondo','WRITE','ALLOW','ROLE','salesAssistant'),(403,'Receipt','balanceCompensationEmail','WRITE','ALLOW','ROLE','employee'),(404,'Receipt','balanceCompensationPdf','READ','ALLOW','ROLE','employee'),(405,'Ticket','getTicketsFuture','READ','ALLOW','ROLE','employee'),(406,'Ticket','merge','WRITE','ALLOW','ROLE','employee'),(407,'Sale','editFloramondo','WRITE','ALLOW','ROLE','logistic'),(408,'ZipConfig','*','*','ALLOW','ROLE','employee'),(409,'Item','*','WRITE','ALLOW','ROLE','administrative'),(410,'Sale','editCloned','WRITE','ALLOW','ROLE','buyer'),(411,'Sale','editCloned','WRITE','ALLOW','ROLE','salesAssistant'),(414,'MdbVersion','*','READ','ALLOW','ROLE','$everyone'),(416,'TicketLog','getChanges','READ','ALLOW','ROLE','employee'),(417,'Ticket','getTicketsAdvance','READ','ALLOW','ROLE','employee'),(418,'EntryLog','*','READ','ALLOW','ROLE','administrative'),(419,'Sale','editTracked','WRITE','ALLOW','ROLE','buyer'),(420,'MdbBranch','*','READ','ALLOW','ROLE','$everyone'),(421,'ItemShelvingSale','*','*','ALLOW','ROLE','employee'),(422,'Docuware','checkFile','READ','ALLOW','ROLE','employee'),(423,'Docuware','download','READ','ALLOW','ROLE','salesPerson'),(424,'Docuware','upload','WRITE','ALLOW','ROLE','productionAssi'),(425,'Docuware','deliveryNoteEmail','WRITE','ALLOW','ROLE','salesPerson'),(426,'TpvTransaction','confirm','WRITE','ALLOW','ROLE','$everyone'),(427,'TpvTransaction','start','WRITE','ALLOW','ROLE','$authenticated'),(428,'TpvTransaction','end','WRITE','ALLOW','ROLE','$authenticated'),(429,'ItemConfig','*','READ','ALLOW','ROLE','employee'),(431,'Tag','onSubmit','WRITE','ALLOW','ROLE','employee'),(432,'Worker','updateAttributes','WRITE','ALLOW','ROLE','hr'),(433,'Worker','createAbsence','*','ALLOW','ROLE','employee'),(434,'Worker','updateAbsence','WRITE','ALLOW','ROLE','employee'),(435,'Worker','deleteAbsence','*','ALLOW','ROLE','employee'),(436,'Worker','new','WRITE','ALLOW','ROLE','hr'),(438,'Client','getClientOrSupplierReference','READ','ALLOW','ROLE','employee'),(439,'NotificationSubscription','*','*','ALLOW','ROLE','employee'),(440,'NotificationAcl','*','READ','ALLOW','ROLE','employee'),(441,'MdbApp','*','READ','ALLOW','ROLE','$everyone'),(442,'MdbApp','*','*','ALLOW','ROLE','developer'),(443,'ItemConfig','*','*','ALLOW','ROLE','employee'),(444,'DeviceProduction','*','*','ALLOW','ROLE','hr'),(445,'DeviceProductionModels','*','*','ALLOW','ROLE','hr'),(446,'DeviceProductionState','*','*','ALLOW','ROLE','hr'),(447,'DeviceProductionUser','*','*','ALLOW','ROLE','hr'),(448,'DeviceProduction','*','*','ALLOW','ROLE','productionAssi'),(449,'DeviceProductionModels','*','*','ALLOW','ROLE','productionAssi'),(450,'DeviceProductionState','*','*','ALLOW','ROLE','productionAssi'),(451,'DeviceProductionUser','*','*','ALLOW','ROLE','productionAssi'),(452,'Worker','deallocatePDA','*','ALLOW','ROLE','hr'),(453,'Worker','allocatePDA','*','ALLOW','ROLE','hr'),(454,'Worker','deallocatePDA','*','ALLOW','ROLE','productionAssi'),(455,'Worker','allocatePDA','*','ALLOW','ROLE','productionAssi'),(456,'Zone','*','*','ALLOW','ROLE','deliveryBoss'),(457,'Account','setPassword','WRITE','ALLOW','ROLE','itManagement'),(458,'Operator','*','READ','ALLOW','ROLE','employee'),(459,'Operator','*','WRITE','ALLOW','ROLE','employee'),(460,'InvoiceIn','getSerial','READ','ALLOW','ROLE','administrative'),(461,'Ticket','saveSign','WRITE','ALLOW','ROLE','employee'),(462,'InvoiceOut','negativeBases','READ','ALLOW','ROLE','administrative'),(463,'InvoiceOut','negativeBasesCsv','READ','ALLOW','ROLE','administrative'),(464,'WorkerObservation','*','*','ALLOW','ROLE','hr'),(465,'ClientInforma','*','READ','ALLOW','ROLE','employee'),(466,'ClientInforma','*','WRITE','ALLOW','ROLE','financial'),(467,'Receipt','receiptEmail','*','ALLOW','ROLE','salesAssistant'),(468,'Client','setRating','WRITE','ALLOW','ROLE','financial'),(469,'Client','*','READ','ALLOW','ROLE','employee'),(470,'Client','addressesPropagateRe','*','ALLOW','ROLE','employee'),(471,'Client','canBeInvoiced','*','ALLOW','ROLE','employee'),(472,'Client','canCreateTicket','*','ALLOW','ROLE','employee'),(473,'Client','consumption','*','ALLOW','ROLE','employee'),(474,'Client','createAddress','*','ALLOW','ROLE','employee'),(475,'Client','createWithUser','*','ALLOW','ROLE','employee'),(476,'Client','extendedListFilter','*','ALLOW','ROLE','employee'),(477,'Client','getAverageInvoiced','*','ALLOW','ROLE','employee'),(478,'Client','getCard','*','ALLOW','ROLE','employee'),(479,'Client','getDebt','*','ALLOW','ROLE','employee'),(480,'Client','getMana','*','ALLOW','ROLE','employee'),(481,'Client','transactions','*','ALLOW','ROLE','employee'),(482,'Client','hasCustomerRole','*','ALLOW','ROLE','employee'),(483,'Client','isValidClient','*','ALLOW','ROLE','employee'),(484,'Client','lastActiveTickets','*','ALLOW','ROLE','employee'),(485,'Client','sendSms','*','ALLOW','ROLE','employee'),(486,'Client','setPassword','*','ALLOW','ROLE','employee'),(487,'Client','summary','*','ALLOW','ROLE','employee'),(488,'Client','updateAddress','*','ALLOW','ROLE','employee'),(489,'Client','updateFiscalData','*','ALLOW','ROLE','employee'),(491,'Client','uploadFile','*','ALLOW','ROLE','employee'),(492,'Client','campaignMetricsPdf','*','ALLOW','ROLE','employee'),(493,'Client','campaignMetricsEmail','*','ALLOW','ROLE','employee'),(494,'Client','clientWelcomeHtml','*','ALLOW','ROLE','employee'),(495,'Client','clientWelcomeEmail','*','ALLOW','ROLE','employee'),(496,'Client','printerSetupHtml','*','ALLOW','ROLE','employee'),(497,'Client','printerSetupEmail','*','ALLOW','ROLE','employee'),(498,'Client','sepaCoreEmail','*','ALLOW','ROLE','employee'),(499,'Client','letterDebtorPdf','*','ALLOW','ROLE','employee'),(500,'Client','letterDebtorStHtml','*','ALLOW','ROLE','employee'),(501,'Client','letterDebtorStEmail','*','ALLOW','ROLE','employee'),(502,'Client','letterDebtorNdHtml','*','ALLOW','ROLE','employee'),(503,'Client','letterDebtorNdEmail','*','ALLOW','ROLE','employee'),(504,'Client','clientDebtStatementPdf','*','ALLOW','ROLE','employee'),(505,'Client','clientDebtStatementHtml','*','ALLOW','ROLE','employee'),(506,'Client','clientDebtStatementEmail','*','ALLOW','ROLE','employee'),(507,'Client','creditRequestPdf','*','ALLOW','ROLE','employee'),(508,'Client','creditRequestHtml','*','ALLOW','ROLE','employee'),(509,'Client','creditRequestEmail','*','ALLOW','ROLE','employee'),(510,'Client','incotermsAuthorizationPdf','*','ALLOW','ROLE','employee'),(511,'Client','incotermsAuthorizationHtml','*','ALLOW','ROLE','employee'),(512,'Client','incotermsAuthorizationEmail','*','ALLOW','ROLE','employee'),(513,'Client','consumptionSendQueued','*','ALLOW','ROLE','employee'),(514,'Client','filter','*','ALLOW','ROLE','employee'),(515,'Client','getClientOrSupplierReference','*','ALLOW','ROLE','employee'),(516,'Client','upsert','*','ALLOW','ROLE','employee'),(517,'Client','create','*','ALLOW','ROLE','employee'),(518,'Client','replaceById','*','ALLOW','ROLE','employee'),(519,'Client','updateAttributes','*','ALLOW','ROLE','employee'),(520,'Client','updateAttributes','*','ALLOW','ROLE','employee'),(521,'Client','deleteById','*','ALLOW','ROLE','employee'),(522,'Client','replaceOrCreate','*','ALLOW','ROLE','employee'),(523,'Client','updateAll','*','ALLOW','ROLE','employee'),(524,'Client','upsertWithWhere','*','ALLOW','ROLE','employee'),(525,'Defaulter','observationEmail','WRITE','ALLOW','ROLE','employee'),(527,'VnUser','acl','READ','ALLOW','ROLE','account'),(528,'VnUser','getCurrentUserData','READ','ALLOW','ROLE','account'),(530,'Account','exists','READ','ALLOW','ROLE','account'),(531,'Account','exists','READ','ALLOW','ROLE','account'),(532,'UserLog','*','READ','ALLOW','ROLE','employee'),(533,'RoleLog','*','READ','ALLOW','ROLE','employee'),(534,'WagonType','*','*','ALLOW','ROLE','productionAssi'),(535,'WagonTypeColor','*','*','ALLOW','ROLE','productionAssi'),(536,'WagonTypeTray','*','*','ALLOW','ROLE','productionAssi'),(537,'WagonConfig','*','*','ALLOW','ROLE','productionAssi'),(538,'CollectionWagon','*','*','ALLOW','ROLE','productionAssi'),(539,'CollectionWagonTicket','*','*','ALLOW','ROLE','productionAssi'),(540,'Wagon','*','*','ALLOW','ROLE','productionAssi'),(541,'WagonType','createWagonType','*','ALLOW','ROLE','productionAssi'),(542,'WagonType','deleteWagonType','*','ALLOW','ROLE','productionAssi'),(543,'WagonType','editWagonType','*','ALLOW','ROLE','productionAssi'),(544,'Docuware','deliveryNoteEmail','WRITE','ALLOW','ROLE','employee'),(545,'Agency','find','READ','ALLOW','ROLE','employee'),(546,'Agency','seeExpired','READ','ALLOW','ROLE','coolerAssist'),(547,'WorkerLog','models','READ','ALLOW','ROLE','hr'),(548,'Ticket','editDiscount','WRITE','ALLOW','ROLE','claimManager'),(549,'Ticket','editDiscount','WRITE','ALLOW','ROLE','salesPerson'),(550,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','salesAssistant'),(551,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','deliveryBoss'),(552,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','buyer'),(553,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','claimManager'),(554,'Ticket','deleteTicketWithPartPrepared','WRITE','ALLOW','ROLE','salesAssistant'),(555,'Ticket','editZone','WRITE','ALLOW','ROLE','deliveryBoss'),(556,'State','editableStates','READ','ALLOW','ROLE','employee'),(557,'State','seeEditableStates','READ','ALLOW','ROLE','administrative'),(558,'State','seeEditableStates','READ','ALLOW','ROLE','production'),(559,'State','isSomeEditable','READ','ALLOW','ROLE','salesPerson'),(560,'State','isAllEditable','READ','ALLOW','ROLE','production'),(561,'State','isAllEditable','READ','ALLOW','ROLE','administrative'),(562,'Agency','seeExpired','READ','ALLOW','ROLE','administrative'),(563,'Agency','seeExpired','READ','ALLOW','ROLE','productionBoss'),(564,'Claim','createAfterDeadline','WRITE','ALLOW','ROLE','claimManager'),(565,'Client','editAddressLogifloraAllowed','WRITE','ALLOW','ROLE','salesAssistant'),(566,'Client','editFiscalDataWithoutTaxDataCheck','WRITE','ALLOW','ROLE','salesAssistant'),(567,'Client','editVerifiedDataWithoutTaxDataCheck','WRITE','ALLOW','ROLE','salesAssistant'),(568,'Client','editCredit','WRITE','ALLOW','ROLE','financialBoss'),(569,'Client','zeroCreditEditor','WRITE','ALLOW','ROLE','financialBoss'),(570,'InvoiceOut','canCreatePdf','WRITE','ALLOW','ROLE','invoicing'),(571,'Supplier','editPayMethodCheck','WRITE','ALLOW','ROLE','financial'),(572,'Worker','isTeamBoss','WRITE','ALLOW','ROLE','teamBoss'),(573,'Worker','forceIsSubordinate','READ','ALLOW','ROLE','hr'),(574,'Claim','editState','WRITE','ALLOW','ROLE','claimManager'),(575,'Claim','find','READ','ALLOW','ROLE','salesPerson'),(576,'Claim','findById','READ','ALLOW','ROLE','salesPerson'),(577,'Claim','findOne','READ','ALLOW','ROLE','salesPerson'),(578,'Claim','getSummary','READ','ALLOW','ROLE','salesPerson'),(579,'Claim','updateClaim','WRITE','ALLOW','ROLE','salesPerson'),(580,'Claim','regularizeClaim','WRITE','ALLOW','ROLE','claimManager'),(581,'Claim','updateClaimDestination','WRITE','ALLOW','ROLE','claimManager'),(582,'Claim','downloadFile','READ','ALLOW','ROLE','claimManager'),(583,'Claim','deleteById','WRITE','ALLOW','ROLE','claimManager'),(584,'Claim','filter','READ','ALLOW','ROLE','salesPerson'),(585,'Claim','logs','READ','ALLOW','ROLE','claimManager'),(586,'Ticket','find','READ','ALLOW','ROLE','employee'),(587,'Ticket','findById','READ','ALLOW','ROLE','employee'),(588,'Ticket','findOne','READ','ALLOW','ROLE','employee'),(589,'Ticket','getVolume','READ','ALLOW','ROLE','employee'),(590,'Ticket','getTotalVolume','READ','ALLOW','ROLE','employee'),(591,'Ticket','summary','READ','ALLOW','ROLE','employee'),(592,'Ticket','priceDifference','READ','ALLOW','ROLE','employee'),(593,'Ticket','componentUpdate','WRITE','ALLOW','ROLE','employee'),(594,'Ticket','new','WRITE','ALLOW','ROLE','employee'),(595,'Ticket','isEditable','READ','ALLOW','ROLE','employee'),(596,'Ticket','setDeleted','WRITE','ALLOW','ROLE','salesPerson'),(597,'Ticket','restore','WRITE','ALLOW','ROLE','employee'),(598,'Ticket','getSales','READ','ALLOW','ROLE','employee'),(599,'Ticket','getSalesPersonMana','READ','ALLOW','ROLE','employee'),(600,'Ticket','filter','READ','ALLOW','ROLE','employee'),(601,'Ticket','makeInvoice','WRITE','ALLOW','ROLE','employee'),(602,'Ticket','updateEditableTicket','WRITE','ALLOW','ROLE','employee'),(603,'Ticket','updateDiscount','WRITE','ALLOW','ROLE','employee'),(604,'Ticket','transferSales','WRITE','ALLOW','ROLE','employee'),(605,'Ticket','sendSms','WRITE','ALLOW','ROLE','employee'),(606,'Ticket','isLocked','READ','ALLOW','ROLE','employee'),(607,'Ticket','freightCost','READ','ALLOW','ROLE','employee'),(608,'Ticket','getComponentsSum','READ','ALLOW','ROLE','employee'),(609,'Ticket','updateAttributes','WRITE','ALLOW','ROLE','delivery'),(610,'Ticket','deliveryNoteCsv','READ','ALLOW','ROLE','employee'),(611,'State','find','READ','ALLOW','ROLE','employee'),(612,'State','findById','READ','ALLOW','ROLE','employee'),(613,'State','findOne','READ','ALLOW','ROLE','employee'),(614,'Worker','find','READ','ALLOW','ROLE','employee'),(615,'Worker','findById','READ','ALLOW','ROLE','employee'),(616,'Worker','findOne','READ','ALLOW','ROLE','employee'),(617,'Worker','filter','READ','ALLOW','ROLE','employee'),(618,'Worker','getWorkedHours','READ','ALLOW','ROLE','employee'),(619,'Worker','active','READ','ALLOW','ROLE','employee'),(620,'Worker','activeWithRole','READ','ALLOW','ROLE','employee'),(621,'Worker','uploadFile','WRITE','ALLOW','ROLE','hr'),(622,'Worker','contracts','READ','ALLOW','ROLE','employee'),(623,'Worker','holidays','READ','ALLOW','ROLE','employee'),(624,'Worker','activeContract','READ','ALLOW','ROLE','employee'),(625,'Worker','activeWithInheritedRole','READ','ALLOW','ROLE','employee'),(626,'Ticket','collectionLabel','READ','ALLOW','ROLE','employee'),(628,'Ticket','expeditionPalletLabel','READ','ALLOW','ROLE','employee'),(629,'Ticket','editDiscount','WRITE','ALLOW','ROLE','artificialBoss'),(630,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','salesTeamBoss'),(635,'Ticket','updateAttributes','WRITE','ALLOW','ROLE','administrative'),(636,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','salesPerson'),(637,'Claim','downloadFile','READ','ALLOW','ROLE','salesPerson'),(638,'Agency','seeExpired','READ','ALLOW','ROLE','artificialBoss'),(639,'Agency','seeExpired','READ','ALLOW','ROLE','logisticAssistant'),(640,'Claim','filter','READ','ALLOW','ROLE','buyer'),(641,'Claim','find','READ','ALLOW','ROLE','buyer'),(642,'Claim','findById','READ','ALLOW','ROLE','buyer'),(643,'Claim','getSummary','READ','ALLOW','ROLE','buyer'),(644,'Claim','filter','READ','ALLOW','ROLE','handmadeBoss'),(645,'Claim','find','READ','ALLOW','ROLE','handmadeBoss'),(646,'Claim','findById','READ','ALLOW','ROLE','handmadeBoss'),(647,'Claim','getSummary','READ','ALLOW','ROLE','handmadeBoss'),(648,'Claim','__get__lines','READ','ALLOW','ROLE','claimManager'),(649,'Claim','__get__lines','READ','ALLOW','ROLE','salesPerson'),(650,'Claim','getSummary','READ','ALLOW','ROLE','deliveryBoss'),(651,'Claim','findById','READ','ALLOW','ROLE','deliveryBoss'),(652,'Claim','find','READ','ALLOW','ROLE','deliveryBoss'),(653,'Claim','filter','READ','ALLOW','ROLE','deliveryBoss'),(654,'Ticket','editZone','WRITE','ALLOW','ROLE','logisticAssistant'),(655,'Entry','addFromPackaging','WRITE','ALLOW','ROLE','production'),(656,'Entry','addFromBuy','WRITE','ALLOW','ROLE','production'),(657,'Supplier','getItemsPackaging','READ','ALLOW','ROLE','production'),(658,'Ticket','closeAll','WRITE','ALLOW','ROLE','system'),(659,'Account','*','*','ALLOW','ROLE','itManagement'),(660,'Account','*','READ','ALLOW','ROLE','employee'),(664,'MailForward','*','*','ALLOW','ROLE','itManagement'),(665,'Role','*','READ','ALLOW','ROLE','employee'),(666,'Role','*','WRITE','ALLOW','ROLE','it'),(667,'VnUser','*','*','ALLOW','ROLE','itManagement'),(668,'VnUser','__get__preview','READ','ALLOW','ROLE','employee'),(669,'VnUser','preview','*','ALLOW','ROLE','employee'),(670,'VnUser','create','*','ALLOW','ROLE','itManagement'),(671,'VnUser','renewToken','WRITE','ALLOW','ROLE','employee'),(672,'PackingSiteAdvanced','*','*','ALLOW','ROLE','production'),(673,'InvoiceOut','makePdfAndNotify','WRITE','ALLOW','ROLE','invoicing'),(674,'InvoiceOutConfig','*','READ','ALLOW','ROLE','invoicing'),(676,'Ticket','invoiceTickets','WRITE','ALLOW','ROLE','employee'),(680,'MailAliasAccount','*','READ','ALLOW','ROLE','employee'),(681,'MailAliasAccount','create','WRITE','ALLOW','ROLE','employee'),(682,'MailAliasAccount','deleteById','WRITE','ALLOW','ROLE','employee'),(683,'MailAliasAccount','canEditAlias','WRITE','ALLOW','ROLE','itManagement'),(684,'WorkerDisableExcluded','*','READ','ALLOW','ROLE','itManagement'),(685,'WorkerDisableExcluded','*','WRITE','ALLOW','ROLE','itManagement'),(686,'MailForward','*','*','ALLOW','ROLE','hr'),(687,'ClientSms','find','READ','ALLOW','ROLE','employee'),(688,'ClientSms','create','WRITE','ALLOW','ROLE','employee'),(689,'Vehicle','sorted','WRITE','ALLOW','ROLE','employee'),(690,'Roadmap','*','*','ALLOW','ROLE','palletizerBoss'),(691,'Roadmap','*','*','ALLOW','ROLE','productionBoss'),(692,'ExpeditionTruck','*','*','ALLOW','ROLE','palletizerBoss'),(693,'ExpeditionTruck','*','*','ALLOW','ROLE','productionBoss'),(694,'MailAliasAccount','canEditAlias','WRITE','ALLOW','ROLE','marketingBoss'),(695,'ViaexpressConfig','internationalExpedition','WRITE','ALLOW','ROLE','employee'),(696,'ViaexpressConfig','renderer','READ','ALLOW','ROLE','employee'),(697,'Ticket','transferClient','WRITE','ALLOW','ROLE','administrative'),(698,'Ticket','canEditWeekly','WRITE','ALLOW','ROLE','buyer'),(699,'TicketSms','find','READ','ALLOW','ROLE','salesPerson'),(701,'Docuware','upload','WRITE','ALLOW','ROLE','deliveryBoss'),(702,'Ticket','docuwareDownload','READ','ALLOW','ROLE','salesPerson'); +INSERT INTO `ACL` VALUES (3,'Address','*','*','ALLOW','ROLE','employee'),(5,'AgencyService','*','READ','ALLOW','ROLE','employee'),(9,'ClientObservation','*','*','ALLOW','ROLE','employee'),(11,'ContactChannel','*','READ','ALLOW','ROLE','trainee'),(13,'Employee','*','READ','ALLOW','ROLE','employee'),(14,'PayMethod','*','READ','ALLOW','ROLE','trainee'),(16,'FakeProduction','*','READ','ALLOW','ROLE','employee'),(17,'Warehouse','* ','READ','ALLOW','ROLE','trainee'),(20,'TicketState','*','*','ALLOW','ROLE','employee'),(24,'Delivery','*','READ','ALLOW','ROLE','employee'),(25,'Zone','*','READ','ALLOW','ROLE','employee'),(26,'ClientCredit','*','*','ALLOW','ROLE','employee'),(27,'ClientCreditLimit','*','READ','ALLOW','ROLE','trainee'),(30,'GreugeType','*','READ','ALLOW','ROLE','trainee'),(31,'Mandate','*','READ','ALLOW','ROLE','trainee'),(32,'MandateType','*','READ','ALLOW','ROLE','trainee'),(33,'Company','*','READ','ALLOW','ROLE','trainee'),(34,'Greuge','*','READ','ALLOW','ROLE','trainee'),(35,'AddressObservation','*','*','ALLOW','ROLE','employee'),(36,'ObservationType','*','*','ALLOW','ROLE','employee'),(37,'Greuge','*','WRITE','ALLOW','ROLE','employee'),(38,'AgencyMode','*','READ','ALLOW','ROLE','employee'),(39,'ItemTag','*','WRITE','ALLOW','ROLE','buyer'),(40,'ItemBotanical','*','WRITE','ALLOW','ROLE','buyer'),(41,'ItemBotanical','*','READ','ALLOW','ROLE','employee'),(42,'ItemPlacement','*','WRITE','ALLOW','ROLE','buyer'),(43,'ItemPlacement','*','WRITE','ALLOW','ROLE','replenisher'),(44,'ItemPlacement','*','READ','ALLOW','ROLE','employee'),(45,'ItemBarcode','*','READ','ALLOW','ROLE','employee'),(46,'ItemBarcode','*','WRITE','ALLOW','ROLE','buyer'),(47,'ItemBarcode','*','WRITE','ALLOW','ROLE','replenisher'),(51,'ItemTag','*','READ','ALLOW','ROLE','employee'),(53,'Item','*','READ','ALLOW','ROLE','employee'),(54,'Item','*','WRITE','ALLOW','ROLE','buyer'),(55,'Recovery','*','READ','ALLOW','ROLE','trainee'),(56,'Recovery','*','WRITE','ALLOW','ROLE','administrative'),(58,'CreditClassification','*','*','ALLOW','ROLE','insurance'),(60,'CreditInsurance','*','*','ALLOW','ROLE','insurance'),(61,'InvoiceOut','*','READ','ALLOW','ROLE','employee'),(63,'TicketObservation','*','*','ALLOW','ROLE','employee'),(64,'Route','*','READ','ALLOW','ROLE','employee'),(65,'Sale','*','READ','ALLOW','ROLE','employee'),(66,'TicketTracking','*','READ','ALLOW','ROLE','employee'),(68,'TicketPackaging','*','*','ALLOW','ROLE','employee'),(69,'Packaging','*','READ','ALLOW','ROLE','employee'),(70,'Packaging','*','WRITE','ALLOW','ROLE','logistic'),(72,'SaleComponent','*','READ','ALLOW','ROLE','employee'),(73,'Expedition','*','READ','ALLOW','ROLE','employee'),(74,'Expedition','*','WRITE','ALLOW','ROLE','deliveryBoss'),(75,'Expedition','*','WRITE','ALLOW','ROLE','production'),(76,'AnnualAverageInvoiced','*','READ','ALLOW','ROLE','employee'),(77,'WorkerMana','*','READ','ALLOW','ROLE','employee'),(78,'TicketTracking','*','WRITE','ALLOW','ROLE','production'),(79,'TicketTracking','changeState','*','ALLOW','ROLE','employee'),(80,'Sale','deleteSales','*','ALLOW','ROLE','employee'),(81,'Sale','moveToTicket','*','ALLOW','ROLE','employee'),(82,'Sale','updateQuantity','*','ALLOW','ROLE','employee'),(83,'Sale','updatePrice','*','ALLOW','ROLE','employee'),(84,'Sale','updateDiscount','*','ALLOW','ROLE','employee'),(85,'SaleTracking','*','READ','ALLOW','ROLE','employee'),(86,'Order','*','*','ALLOW','ROLE','employee'),(87,'OrderRow','*','*','ALLOW','ROLE','employee'),(88,'ClientContact','*','*','ALLOW','ROLE','employee'),(89,'Sale','moveToNewTicket','*','ALLOW','ROLE','employee'),(90,'Sale','reserve','*','ALLOW','ROLE','employee'),(91,'TicketWeekly','*','READ','ALLOW','ROLE','employee'),(94,'Agency','landsThatDay','*','ALLOW','ROLE','employee'),(96,'ClaimEnd','*','READ','ALLOW','ROLE','employee'),(97,'ClaimEnd','*','WRITE','ALLOW','ROLE','claimManager'),(98,'ClaimBeginning','*','*','ALLOW','ROLE','employee'),(99,'ClaimDevelopment','*','READ','ALLOW','ROLE','employee'),(100,'ClaimDevelopment','*','WRITE','ALLOW','ROLE','claimManager'),(102,'Claim','createFromSales','*','ALLOW','ROLE','employee'),(104,'Item','*','WRITE','ALLOW','ROLE','marketingBoss'),(105,'ItemBarcode','*','WRITE','ALLOW','ROLE','marketingBoss'),(106,'ItemBotanical','*','WRITE','ALLOW','ROLE','marketingBoss'),(108,'ItemPlacement','*','WRITE','ALLOW','ROLE','marketingBoss'),(109,'UserConfig','*','*','ALLOW','ROLE','employee'),(110,'Bank','*','READ','ALLOW','ROLE','trainee'),(111,'ClientLog','*','READ','ALLOW','ROLE','trainee'),(112,'Defaulter','*','READ','ALLOW','ROLE','employee'),(113,'ClientRisk','*','READ','ALLOW','ROLE','trainee'),(114,'Receipt','*','READ','ALLOW','ROLE','trainee'),(115,'Receipt','*','WRITE','ALLOW','ROLE','administrative'),(116,'BankEntity','*','*','ALLOW','ROLE','employee'),(117,'ClientSample','*','*','ALLOW','ROLE','employee'),(118,'WorkerTeam','*','*','ALLOW','ROLE','salesPerson'),(119,'Travel','*','READ','ALLOW','ROLE','employee'),(120,'Travel','*','WRITE','ALLOW','ROLE','buyer'),(121,'Item','regularize','*','ALLOW','ROLE','employee'),(122,'TicketRequest','*','*','ALLOW','ROLE','employee'),(124,'Client','confirmTransaction','WRITE','ALLOW','ROLE','administrative'),(125,'Agency','getAgenciesWithWarehouse','*','ALLOW','ROLE','employee'),(126,'Client','activeWorkersWithRole','*','ALLOW','ROLE','employee'),(127,'TicketLog','*','READ','ALLOW','ROLE','employee'),(129,'TicketService','*','*','ALLOW','ROLE','employee'),(130,'Expedition','*','WRITE','ALLOW','ROLE','packager'),(131,'CreditInsurance','*','READ','ALLOW','ROLE','trainee'),(132,'CreditClassification','*','READ','ALLOW','ROLE','trainee'),(133,'ItemTag','*','WRITE','ALLOW','ROLE','marketingBoss'),(135,'ZoneGeo','*','READ','ALLOW','ROLE','employee'),(136,'ZoneCalendar','*','READ','ALLOW','ROLE','employee'),(137,'ZoneIncluded','*','READ','ALLOW','ROLE','employee'),(138,'LabourHoliday','*','READ','ALLOW','ROLE','employee'),(139,'LabourHolidayLegend','*','READ','ALLOW','ROLE','employee'),(140,'LabourHolidayType','*','READ','ALLOW','ROLE','employee'),(141,'Zone','*','*','ALLOW','ROLE','logisticBoss'),(142,'ZoneCalendar','*','WRITE','ALLOW','ROLE','deliveryBoss'),(143,'ZoneIncluded','*','*','ALLOW','ROLE','deliveryBoss'),(144,'Stowaway','*','*','ALLOW','ROLE','employee'),(145,'Ticket','getPossibleStowaways','READ','ALLOW','ROLE','employee'),(147,'UserConfigView','*','*','ALLOW','ROLE','employee'),(148,'UserConfigView','*','*','ALLOW','ROLE','employee'),(149,'Sip','*','READ','ALLOW','ROLE','employee'),(150,'Sip','*','WRITE','ALLOW','ROLE','hr'),(151,'Department','*','READ','ALLOW','ROLE','employee'),(152,'Department','*','WRITE','ALLOW','ROLE','hr'),(153,'Route','*','READ','ALLOW','ROLE','employee'),(154,'Route','*','WRITE','ALLOW','ROLE','delivery'),(155,'Calendar','*','READ','ALLOW','ROLE','hr'),(156,'WorkerLabour','*','READ','ALLOW','ROLE','hr'),(157,'Calendar','absences','READ','ALLOW','ROLE','employee'),(158,'ItemTag','*','WRITE','ALLOW','ROLE','accessory'),(160,'TicketServiceType','*','READ','ALLOW','ROLE','employee'),(161,'TicketConfig','*','READ','ALLOW','ROLE','employee'),(162,'InvoiceOut','delete','WRITE','ALLOW','ROLE','invoicing'),(163,'InvoiceOut','book','WRITE','ALLOW','ROLE','invoicing'),(165,'TicketDms','*','*','ALLOW','ROLE','employee'),(167,'Worker','isSubordinate','READ','ALLOW','ROLE','employee'),(168,'Worker','mySubordinates','READ','ALLOW','ROLE','employee'),(169,'WorkerTimeControl','filter','READ','ALLOW','ROLE','employee'),(170,'WorkerTimeControl','addTime','WRITE','ALLOW','ROLE','employee'),(171,'TicketServiceType','*','WRITE','ALLOW','ROLE','administrative'),(172,'Sms','*','READ','ALLOW','ROLE','employee'),(173,'Sms','send','WRITE','ALLOW','ROLE','employee'),(176,'Device','*','*','ALLOW','ROLE','employee'),(177,'Device','*','*','ALLOW','ROLE','employee'),(178,'WorkerTimeControl','*','*','ALLOW','ROLE','employee'),(179,'ItemLog','*','READ','ALLOW','ROLE','employee'),(180,'RouteLog','*','READ','ALLOW','ROLE','employee'),(181,'Dms','removeFile','WRITE','ALLOW','ROLE','employee'),(182,'Dms','uploadFile','WRITE','ALLOW','ROLE','employee'),(183,'Dms','downloadFile','READ','ALLOW','ROLE','employee'),(184,'Client','uploadFile','WRITE','ALLOW','ROLE','employee'),(185,'ClientDms','removeFile','WRITE','ALLOW','ROLE','employee'),(186,'ClientDms','*','READ','ALLOW','ROLE','trainee'),(187,'Ticket','uploadFile','WRITE','ALLOW','ROLE','employee'),(190,'Route','updateVolume','WRITE','ALLOW','ROLE','deliveryBoss'),(191,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(192,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(194,'Postcode','*','WRITE','ALLOW','ROLE','deliveryBoss'),(195,'Ticket','addSale','WRITE','ALLOW','ROLE','employee'),(196,'Dms','updateFile','WRITE','ALLOW','ROLE','employee'),(197,'Dms','*','READ','ALLOW','ROLE','trainee'),(198,'ClaimDms','removeFile','WRITE','ALLOW','ROLE','employee'),(199,'ClaimDms','*','READ','ALLOW','ROLE','employee'),(200,'Claim','uploadFile','WRITE','ALLOW','ROLE','employee'),(201,'Sale','updateConcept','WRITE','ALLOW','ROLE','employee'),(202,'Claim','updateClaimAction','WRITE','ALLOW','ROLE','claimManager'),(203,'UserPhone','*','*','ALLOW','ROLE','employee'),(204,'WorkerDms','removeFile','WRITE','ALLOW','ROLE','hr'),(205,'WorkerDms','*','READ','ALLOW','ROLE','hr'),(206,'Chat','*','*','ALLOW','ROLE','employee'),(207,'Chat','sendMessage','*','ALLOW','ROLE','employee'),(208,'Sale','recalculatePrice','WRITE','ALLOW','ROLE','employee'),(209,'Ticket','recalculateComponents','WRITE','ALLOW','ROLE','employee'),(211,'TravelLog','*','READ','ALLOW','ROLE','buyer'),(212,'Thermograph','*','*','ALLOW','ROLE','buyer'),(213,'TravelThermograph','*','WRITE','ALLOW','ROLE','buyer'),(214,'Entry','*','*','ALLOW','ROLE','buyer'),(215,'TicketWeekly','*','WRITE','ALLOW','ROLE','buyer'),(216,'TravelThermograph','*','READ','ALLOW','ROLE','employee'),(218,'Intrastat','*','*','ALLOW','ROLE','buyer'),(221,'UserConfig','getUserConfig','READ','ALLOW','ROLE','account'),(222,'Client','*','READ','ALLOW','ROLE','trainee'),(226,'ClientObservation','*','READ','ALLOW','ROLE','trainee'),(227,'Address','*','READ','ALLOW','ROLE','trainee'),(228,'AddressObservation','*','READ','ALLOW','ROLE','trainee'),(230,'ClientCredit','*','READ','ALLOW','ROLE','trainee'),(231,'ClientContact','*','READ','ALLOW','ROLE','trainee'),(232,'ClientSample','*','READ','ALLOW','ROLE','trainee'),(233,'EntryLog','*','READ','ALLOW','ROLE','buyer'),(234,'WorkerLog','find','READ','ALLOW','ROLE','hr'),(235,'CustomsAgent','*','*','ALLOW','ROLE','employee'),(236,'Buy','*','*','ALLOW','ROLE','buyer'),(237,'WorkerDms','filter','*','ALLOW','ROLE','employee'),(238,'Town','*','WRITE','ALLOW','ROLE','deliveryBoss'),(239,'Province','*','WRITE','ALLOW','ROLE','deliveryBoss'),(240,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(241,'SupplierContact','*','WRITE','ALLOW','ROLE','administrative'),(242,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(244,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(248,'RoleMapping','*','READ','ALLOW','ROLE','account'),(249,'UserPassword','*','READ','ALLOW','ROLE','account'),(250,'Town','*','WRITE','ALLOW','ROLE','deliveryBoss'),(251,'Province','*','WRITE','ALLOW','ROLE','deliveryBoss'),(252,'Supplier','*','READ','ALLOW','ROLE','employee'),(253,'Supplier','*','WRITE','ALLOW','ROLE','administrative'),(254,'SupplierLog','*','READ','ALLOW','ROLE','employee'),(256,'Image','*','WRITE','ALLOW','ROLE','employee'),(257,'FixedPrice','*','*','ALLOW','ROLE','buyer'),(258,'PayDem','*','READ','ALLOW','ROLE','employee'),(259,'Client','createReceipt','*','ALLOW','ROLE','salesAssistant'),(260,'PrintServerQueue','*','WRITE','ALLOW','ROLE','employee'),(261,'SupplierAccount','*','*','ALLOW','ROLE','administrative'),(262,'Entry','*','*','ALLOW','ROLE','administrative'),(263,'InvoiceIn','*','*','ALLOW','ROLE','administrative'),(264,'StarredModule','*','*','ALLOW','ROLE','employee'),(265,'ItemBotanical','*','WRITE','ALLOW','ROLE','logisticBoss'),(266,'ZoneLog','*','READ','ALLOW','ROLE','employee'),(267,'Genus','*','WRITE','ALLOW','ROLE','logisticBoss'),(268,'Specie','*','WRITE','ALLOW','ROLE','logisticBoss'),(269,'InvoiceOut','createPdf','WRITE','ALLOW','ROLE','employee'),(270,'SupplierAddress','*','*','ALLOW','ROLE','employee'),(271,'SalesMonitor','*','*','ALLOW','ROLE','employee'),(272,'InvoiceInLog','*','READ','ALLOW','ROLE','employee'),(273,'InvoiceInTax','*','*','ALLOW','ROLE','administrative'),(274,'InvoiceInLog','*','READ','ALLOW','ROLE','administrative'),(275,'InvoiceOut','createManualInvoice','WRITE','ALLOW','ROLE','invoicing'),(276,'InvoiceOut','globalInvoicing','WRITE','ALLOW','ROLE','invoicing'),(278,'RoleInherit','*','WRITE','ALLOW','ROLE','grant'),(279,'MailAlias','*','*','ALLOW','ROLE','marketing'),(283,'EntryObservation','*','*','ALLOW','ROLE','buyer'),(284,'LdapConfig','*','*','ALLOW','ROLE','sysadmin'),(285,'SambaConfig','*','*','ALLOW','ROLE','sysadmin'),(286,'ACL','*','*','ALLOW','ROLE','developer'),(287,'AccessToken','*','*','ALLOW','ROLE','developer'),(293,'RoleInherit','*','*','ALLOW','ROLE','it'),(294,'RoleRole','*','*','ALLOW','ROLE','it'),(295,'AccountConfig','*','*','ALLOW','ROLE','sysadmin'),(296,'Collection','*','READ','ALLOW','ROLE','employee'),(297,'Sale','refund','WRITE','ALLOW','ROLE','invoicing'),(298,'InvoiceInDueDay','*','*','ALLOW','ROLE','administrative'),(299,'Collection','setSaleQuantity','*','ALLOW','ROLE','employee'),(302,'AgencyTerm','*','*','ALLOW','ROLE','administrative'),(303,'ClaimLog','*','READ','ALLOW','ROLE','claimManager'),(304,'Edi','updateData','WRITE','ALLOW','ROLE','employee'),(305,'EducationLevel','*','*','ALLOW','ROLE','employee'),(306,'InvoiceInIntrastat','*','*','ALLOW','ROLE','employee'),(307,'SupplierAgencyTerm','*','*','ALLOW','ROLE','administrative'),(308,'InvoiceInIntrastat','*','*','ALLOW','ROLE','employee'),(309,'Zone','getZoneClosing','*','ALLOW','ROLE','employee'),(310,'ExpeditionState','*','READ','ALLOW','ROLE','employee'),(311,'Expense','*','READ','ALLOW','ROLE','employee'),(312,'Expense','*','WRITE','ALLOW','ROLE','administrative'),(314,'SupplierActivity','*','READ','ALLOW','ROLE','employee'),(315,'SupplierActivity','*','WRITE','ALLOW','ROLE','administrative'),(316,'Dms','deleteTrashFiles','WRITE','ALLOW','ROLE','employee'),(317,'ClientUnpaid','*','*','ALLOW','ROLE','administrative'),(318,'MdbVersion','*','*','ALLOW','ROLE','developer'),(319,'ItemType','*','READ','ALLOW','ROLE','employee'),(320,'ItemType','*','WRITE','ALLOW','ROLE','buyer'),(321,'InvoiceOut','refund','WRITE','ALLOW','ROLE','invoicing'),(322,'InvoiceOut','refund','WRITE','ALLOW','ROLE','salesAssistant'),(323,'InvoiceOut','refund','WRITE','ALLOW','ROLE','claimManager'),(324,'Ticket','refund','WRITE','ALLOW','ROLE','invoicing'),(325,'Ticket','refund','WRITE','ALLOW','ROLE','salesAssistant'),(326,'Ticket','refund','WRITE','ALLOW','ROLE','claimManager'),(327,'Sale','refund','WRITE','ALLOW','ROLE','salesAssistant'),(328,'Sale','refund','WRITE','ALLOW','ROLE','claimManager'),(329,'TicketRefund','*','WRITE','ALLOW','ROLE','invoicing'),(330,'ClaimObservation','*','WRITE','ALLOW','ROLE','salesPerson'),(331,'ClaimObservation','*','READ','ALLOW','ROLE','salesPerson'),(332,'Client','setPassword','WRITE','ALLOW','ROLE','salesPerson'),(333,'Client','updateUser','WRITE','ALLOW','ROLE','salesPerson'),(334,'ShelvingLog','*','READ','ALLOW','ROLE','employee'),(335,'ZoneExclusionGeo','*','READ','ALLOW','ROLE','employee'),(336,'ZoneExclusionGeo','*','WRITE','ALLOW','ROLE','deliveryBoss'),(337,'Parking','*','*','ALLOW','ROLE','employee'),(338,'Shelving','*','*','ALLOW','ROLE','employee'),(339,'OsTicket','*','*','ALLOW','ROLE','employee'),(340,'OsTicketConfig','*','*','ALLOW','ROLE','it'),(341,'ClientConsumptionQueue','*','WRITE','ALLOW','ROLE','employee'),(342,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','employee'),(343,'Ticket','deliveryNoteEmail','WRITE','ALLOW','ROLE','employee'),(344,'Ticket','deliveryNoteCsvPdf','READ','ALLOW','ROLE','employee'),(345,'Ticket','deliveryNoteCsvEmail','READ','ALLOW','ROLE','employee'),(346,'Client','campaignMetricsPdf','READ','ALLOW','ROLE','employee'),(347,'Client','campaignMetricsEmail','WRITE','ALLOW','ROLE','employee'),(348,'Client','clientWelcomeHtml','READ','ALLOW','ROLE','employee'),(349,'Client','clientWelcomeEmail','WRITE','ALLOW','ROLE','employee'),(350,'Client','creditRequestPdf','READ','ALLOW','ROLE','employee'),(351,'Client','creditRequestHtml','READ','ALLOW','ROLE','employee'),(352,'Client','creditRequestEmail','WRITE','ALLOW','ROLE','employee'),(353,'Client','printerSetupHtml','READ','ALLOW','ROLE','employee'),(354,'Client','printerSetupEmail','WRITE','ALLOW','ROLE','employee'),(355,'Client','sepaCoreEmail','WRITE','ALLOW','ROLE','employee'),(356,'Client','letterDebtorPdf','READ','ALLOW','ROLE','employee'),(357,'Client','letterDebtorStHtml','READ','ALLOW','ROLE','employee'),(358,'Client','letterDebtorStEmail','WRITE','ALLOW','ROLE','employee'),(359,'Client','letterDebtorNdHtml','READ','ALLOW','ROLE','employee'),(360,'Client','letterDebtorNdEmail','WRITE','ALLOW','ROLE','employee'),(361,'Client','clientDebtStatementPdf','READ','ALLOW','ROLE','employee'),(362,'Client','clientDebtStatementHtml','READ','ALLOW','ROLE','employee'),(363,'Client','clientDebtStatementEmail','WRITE','ALLOW','ROLE','employee'),(364,'Client','incotermsAuthorizationPdf','READ','ALLOW','ROLE','employee'),(365,'Client','incotermsAuthorizationHtml','READ','ALLOW','ROLE','employee'),(366,'Client','incotermsAuthorizationEmail','WRITE','ALLOW','ROLE','employee'),(367,'Client','consumptionSendQueued','WRITE','ALLOW','ROLE','system'),(368,'InvoiceOut','invoiceEmail','WRITE','ALLOW','ROLE','employee'),(369,'InvoiceOut','exportationPdf','READ','ALLOW','ROLE','employee'),(370,'InvoiceOut','sendQueued','WRITE','ALLOW','ROLE','system'),(371,'Ticket','invoiceCsvPdf','READ','ALLOW','ROLE','employee'),(372,'Ticket','invoiceCsvEmail','WRITE','ALLOW','ROLE','employee'),(373,'Supplier','campaignMetricsPdf','READ','ALLOW','ROLE','employee'),(374,'Supplier','campaignMetricsEmail','WRITE','ALLOW','ROLE','employee'),(375,'Travel','extraCommunityPdf','READ','ALLOW','ROLE','employee'),(376,'Travel','extraCommunityEmail','WRITE','ALLOW','ROLE','employee'),(377,'Entry','entryOrderPdf','READ','ALLOW','ROLE','employee'),(378,'OsTicket','osTicketReportEmail','WRITE','ALLOW','ROLE','system'),(379,'Item','buyerWasteEmail','WRITE','ALLOW','ROLE','system'),(380,'Claim','claimPickupPdf','READ','ALLOW','ROLE','employee'),(381,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','claimManager'),(382,'Item','labelPdf','READ','ALLOW','ROLE','employee'),(383,'Sector','*','READ','ALLOW','ROLE','employee'),(384,'Sector','*','WRITE','ALLOW','ROLE','employee'),(385,'Route','driverRoutePdf','READ','ALLOW','ROLE','employee'),(386,'Route','driverRouteEmail','WRITE','ALLOW','ROLE','employee'),(387,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','customer'),(388,'Supplier','newSupplier','WRITE','ALLOW','ROLE','administrative'),(389,'ClaimRma','*','READ','ALLOW','ROLE','claimManager'),(390,'ClaimRma','*','WRITE','ALLOW','ROLE','claimManager'),(391,'Notification','*','WRITE','ALLOW','ROLE','system'),(392,'Boxing','*','*','ALLOW','ROLE','employee'),(393,'Url','*','READ','ALLOW','ROLE','employee'),(394,'Url','*','WRITE','ALLOW','ROLE','it'),(395,'ItemShelving','*','READ','ALLOW','ROLE','employee'),(396,'ItemShelving','*','WRITE','ALLOW','ROLE','production'),(397,'ItemShelvingPlacementSupplyStock','*','READ','ALLOW','ROLE','employee'),(398,'NotificationQueue','*','*','ALLOW','ROLE','employee'),(399,'InvoiceOut','clientsToInvoice','WRITE','ALLOW','ROLE','invoicing'),(400,'InvoiceOut','invoiceClient','WRITE','ALLOW','ROLE','invoicing'),(401,'Sale','editTracked','WRITE','ALLOW','ROLE','production'),(402,'Sale','editFloramondo','WRITE','ALLOW','ROLE','salesAssistant'),(403,'Receipt','balanceCompensationEmail','WRITE','ALLOW','ROLE','employee'),(404,'Receipt','balanceCompensationPdf','READ','ALLOW','ROLE','employee'),(405,'Ticket','getTicketsFuture','READ','ALLOW','ROLE','employee'),(406,'Ticket','merge','WRITE','ALLOW','ROLE','employee'),(407,'Sale','editFloramondo','WRITE','ALLOW','ROLE','logistic'),(408,'ZipConfig','*','*','ALLOW','ROLE','employee'),(409,'Item','*','WRITE','ALLOW','ROLE','administrative'),(410,'Sale','editCloned','WRITE','ALLOW','ROLE','buyer'),(411,'Sale','editCloned','WRITE','ALLOW','ROLE','salesAssistant'),(414,'MdbVersion','*','READ','ALLOW','ROLE','$everyone'),(416,'TicketLog','getChanges','READ','ALLOW','ROLE','employee'),(417,'Ticket','getTicketsAdvance','READ','ALLOW','ROLE','employee'),(418,'EntryLog','*','READ','ALLOW','ROLE','administrative'),(419,'Sale','editTracked','WRITE','ALLOW','ROLE','buyer'),(420,'MdbBranch','*','READ','ALLOW','ROLE','$everyone'),(421,'ItemShelvingSale','*','*','ALLOW','ROLE','employee'),(422,'Docuware','checkFile','READ','ALLOW','ROLE','employee'),(423,'Docuware','download','READ','ALLOW','ROLE','salesPerson'),(424,'Docuware','upload','WRITE','ALLOW','ROLE','productionAssi'),(425,'Docuware','deliveryNoteEmail','WRITE','ALLOW','ROLE','salesPerson'),(426,'TpvTransaction','confirm','WRITE','ALLOW','ROLE','$everyone'),(427,'TpvTransaction','start','WRITE','ALLOW','ROLE','$authenticated'),(428,'TpvTransaction','end','WRITE','ALLOW','ROLE','$authenticated'),(429,'ItemConfig','*','READ','ALLOW','ROLE','employee'),(431,'Tag','onSubmit','WRITE','ALLOW','ROLE','employee'),(432,'Worker','updateAttributes','WRITE','ALLOW','ROLE','hr'),(433,'Worker','createAbsence','*','ALLOW','ROLE','employee'),(434,'Worker','updateAbsence','WRITE','ALLOW','ROLE','employee'),(435,'Worker','deleteAbsence','*','ALLOW','ROLE','employee'),(436,'Worker','new','WRITE','ALLOW','ROLE','hr'),(438,'Client','getClientOrSupplierReference','READ','ALLOW','ROLE','employee'),(439,'NotificationSubscription','*','*','ALLOW','ROLE','employee'),(440,'NotificationAcl','*','READ','ALLOW','ROLE','employee'),(441,'MdbApp','*','READ','ALLOW','ROLE','$everyone'),(442,'MdbApp','*','*','ALLOW','ROLE','developer'),(443,'ItemConfig','*','*','ALLOW','ROLE','employee'),(444,'DeviceProduction','*','*','ALLOW','ROLE','hr'),(445,'DeviceProductionModels','*','*','ALLOW','ROLE','hr'),(446,'DeviceProductionState','*','*','ALLOW','ROLE','hr'),(447,'DeviceProductionUser','*','*','ALLOW','ROLE','hr'),(448,'DeviceProduction','*','*','ALLOW','ROLE','productionAssi'),(449,'DeviceProductionModels','*','*','ALLOW','ROLE','productionAssi'),(450,'DeviceProductionState','*','*','ALLOW','ROLE','productionAssi'),(451,'DeviceProductionUser','*','*','ALLOW','ROLE','productionAssi'),(452,'Worker','deallocatePDA','*','ALLOW','ROLE','hr'),(453,'Worker','allocatePDA','*','ALLOW','ROLE','hr'),(454,'Worker','deallocatePDA','*','ALLOW','ROLE','productionAssi'),(455,'Worker','allocatePDA','*','ALLOW','ROLE','productionAssi'),(456,'Zone','*','*','ALLOW','ROLE','deliveryBoss'),(457,'Account','setPassword','WRITE','ALLOW','ROLE','itManagement'),(458,'Operator','*','READ','ALLOW','ROLE','employee'),(459,'Operator','*','WRITE','ALLOW','ROLE','employee'),(460,'InvoiceIn','getSerial','READ','ALLOW','ROLE','administrative'),(461,'Ticket','saveSign','WRITE','ALLOW','ROLE','employee'),(462,'InvoiceOut','negativeBases','READ','ALLOW','ROLE','administrative'),(463,'InvoiceOut','negativeBasesCsv','READ','ALLOW','ROLE','administrative'),(464,'WorkerObservation','*','*','ALLOW','ROLE','hr'),(465,'ClientInforma','*','READ','ALLOW','ROLE','employee'),(466,'ClientInforma','*','WRITE','ALLOW','ROLE','financial'),(467,'Receipt','receiptEmail','*','ALLOW','ROLE','salesAssistant'),(468,'Client','setRating','WRITE','ALLOW','ROLE','financial'),(469,'Client','*','READ','ALLOW','ROLE','employee'),(470,'Client','addressesPropagateRe','*','ALLOW','ROLE','employee'),(471,'Client','canBeInvoiced','*','ALLOW','ROLE','employee'),(472,'Client','canCreateTicket','*','ALLOW','ROLE','employee'),(473,'Client','consumption','*','ALLOW','ROLE','employee'),(474,'Client','createAddress','*','ALLOW','ROLE','employee'),(475,'Client','createWithUser','*','ALLOW','ROLE','employee'),(476,'Client','extendedListFilter','*','ALLOW','ROLE','employee'),(477,'Client','getAverageInvoiced','*','ALLOW','ROLE','employee'),(478,'Client','getCard','*','ALLOW','ROLE','employee'),(479,'Client','getDebt','*','ALLOW','ROLE','employee'),(480,'Client','getMana','*','ALLOW','ROLE','employee'),(481,'Client','transactions','*','ALLOW','ROLE','employee'),(482,'Client','hasCustomerRole','*','ALLOW','ROLE','employee'),(483,'Client','isValidClient','*','ALLOW','ROLE','employee'),(484,'Client','lastActiveTickets','*','ALLOW','ROLE','employee'),(485,'Client','sendSms','*','ALLOW','ROLE','employee'),(486,'Client','setPassword','*','ALLOW','ROLE','employee'),(487,'Client','summary','*','ALLOW','ROLE','employee'),(488,'Client','updateAddress','*','ALLOW','ROLE','employee'),(489,'Client','updateFiscalData','*','ALLOW','ROLE','employee'),(491,'Client','uploadFile','*','ALLOW','ROLE','employee'),(492,'Client','campaignMetricsPdf','*','ALLOW','ROLE','employee'),(493,'Client','campaignMetricsEmail','*','ALLOW','ROLE','employee'),(494,'Client','clientWelcomeHtml','*','ALLOW','ROLE','employee'),(495,'Client','clientWelcomeEmail','*','ALLOW','ROLE','employee'),(496,'Client','printerSetupHtml','*','ALLOW','ROLE','employee'),(497,'Client','printerSetupEmail','*','ALLOW','ROLE','employee'),(498,'Client','sepaCoreEmail','*','ALLOW','ROLE','employee'),(499,'Client','letterDebtorPdf','*','ALLOW','ROLE','employee'),(500,'Client','letterDebtorStHtml','*','ALLOW','ROLE','employee'),(501,'Client','letterDebtorStEmail','*','ALLOW','ROLE','employee'),(502,'Client','letterDebtorNdHtml','*','ALLOW','ROLE','employee'),(503,'Client','letterDebtorNdEmail','*','ALLOW','ROLE','employee'),(504,'Client','clientDebtStatementPdf','*','ALLOW','ROLE','employee'),(505,'Client','clientDebtStatementHtml','*','ALLOW','ROLE','employee'),(506,'Client','clientDebtStatementEmail','*','ALLOW','ROLE','employee'),(507,'Client','creditRequestPdf','*','ALLOW','ROLE','employee'),(508,'Client','creditRequestHtml','*','ALLOW','ROLE','employee'),(509,'Client','creditRequestEmail','*','ALLOW','ROLE','employee'),(510,'Client','incotermsAuthorizationPdf','*','ALLOW','ROLE','employee'),(511,'Client','incotermsAuthorizationHtml','*','ALLOW','ROLE','employee'),(512,'Client','incotermsAuthorizationEmail','*','ALLOW','ROLE','employee'),(513,'Client','consumptionSendQueued','*','ALLOW','ROLE','employee'),(514,'Client','filter','*','ALLOW','ROLE','employee'),(515,'Client','getClientOrSupplierReference','*','ALLOW','ROLE','employee'),(516,'Client','upsert','*','ALLOW','ROLE','employee'),(517,'Client','create','*','ALLOW','ROLE','employee'),(518,'Client','replaceById','*','ALLOW','ROLE','employee'),(519,'Client','updateAttributes','*','ALLOW','ROLE','employee'),(520,'Client','updateAttributes','*','ALLOW','ROLE','employee'),(521,'Client','deleteById','*','ALLOW','ROLE','employee'),(522,'Client','replaceOrCreate','*','ALLOW','ROLE','employee'),(523,'Client','updateAll','*','ALLOW','ROLE','employee'),(524,'Client','upsertWithWhere','*','ALLOW','ROLE','employee'),(525,'Defaulter','observationEmail','WRITE','ALLOW','ROLE','employee'),(527,'VnUser','acl','READ','ALLOW','ROLE','account'),(528,'VnUser','getCurrentUserData','READ','ALLOW','ROLE','account'),(530,'Account','exists','READ','ALLOW','ROLE','account'),(531,'Account','exists','READ','ALLOW','ROLE','account'),(532,'UserLog','*','READ','ALLOW','ROLE','employee'),(533,'RoleLog','*','READ','ALLOW','ROLE','employee'),(534,'WagonType','*','*','ALLOW','ROLE','productionAssi'),(535,'WagonTypeColor','*','*','ALLOW','ROLE','productionAssi'),(536,'WagonTypeTray','*','*','ALLOW','ROLE','productionAssi'),(537,'WagonConfig','*','*','ALLOW','ROLE','productionAssi'),(538,'CollectionWagon','*','*','ALLOW','ROLE','productionAssi'),(539,'CollectionWagonTicket','*','*','ALLOW','ROLE','productionAssi'),(540,'Wagon','*','*','ALLOW','ROLE','productionAssi'),(541,'WagonType','createWagonType','*','ALLOW','ROLE','productionAssi'),(542,'WagonType','deleteWagonType','*','ALLOW','ROLE','productionAssi'),(543,'WagonType','editWagonType','*','ALLOW','ROLE','productionAssi'),(544,'Docuware','deliveryNoteEmail','WRITE','ALLOW','ROLE','employee'),(545,'Agency','find','READ','ALLOW','ROLE','employee'),(546,'Agency','seeExpired','READ','ALLOW','ROLE','coolerAssist'),(547,'WorkerLog','models','READ','ALLOW','ROLE','hr'),(548,'Ticket','editDiscount','WRITE','ALLOW','ROLE','claimManager'),(549,'Ticket','editDiscount','WRITE','ALLOW','ROLE','salesPerson'),(550,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','salesAssistant'),(551,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','deliveryBoss'),(552,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','buyer'),(553,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','claimManager'),(554,'Ticket','deleteTicketWithPartPrepared','WRITE','ALLOW','ROLE','salesAssistant'),(555,'Ticket','editZone','WRITE','ALLOW','ROLE','deliveryBoss'),(556,'State','editableStates','READ','ALLOW','ROLE','employee'),(557,'State','seeEditableStates','READ','ALLOW','ROLE','administrative'),(558,'State','seeEditableStates','READ','ALLOW','ROLE','production'),(559,'State','isSomeEditable','READ','ALLOW','ROLE','salesPerson'),(560,'State','isAllEditable','READ','ALLOW','ROLE','production'),(561,'State','isAllEditable','READ','ALLOW','ROLE','administrative'),(562,'Agency','seeExpired','READ','ALLOW','ROLE','administrative'),(563,'Agency','seeExpired','READ','ALLOW','ROLE','productionBoss'),(564,'Claim','createAfterDeadline','WRITE','ALLOW','ROLE','claimManager'),(565,'Client','editAddressLogifloraAllowed','WRITE','ALLOW','ROLE','salesAssistant'),(566,'Client','editFiscalDataWithoutTaxDataCheck','WRITE','ALLOW','ROLE','salesAssistant'),(567,'Client','editVerifiedDataWithoutTaxDataCheck','WRITE','ALLOW','ROLE','salesAssistant'),(568,'Client','editCredit','WRITE','ALLOW','ROLE','financialBoss'),(569,'Client','zeroCreditEditor','WRITE','ALLOW','ROLE','financialBoss'),(570,'InvoiceOut','canCreatePdf','WRITE','ALLOW','ROLE','invoicing'),(571,'Supplier','editPayMethodCheck','WRITE','ALLOW','ROLE','financial'),(572,'Worker','isTeamBoss','WRITE','ALLOW','ROLE','teamBoss'),(573,'Worker','forceIsSubordinate','READ','ALLOW','ROLE','hr'),(574,'Claim','editState','WRITE','ALLOW','ROLE','claimManager'),(575,'Claim','find','READ','ALLOW','ROLE','salesPerson'),(576,'Claim','findById','READ','ALLOW','ROLE','salesPerson'),(577,'Claim','findOne','READ','ALLOW','ROLE','salesPerson'),(578,'Claim','getSummary','READ','ALLOW','ROLE','salesPerson'),(579,'Claim','updateClaim','WRITE','ALLOW','ROLE','salesPerson'),(580,'Claim','regularizeClaim','WRITE','ALLOW','ROLE','claimManager'),(581,'Claim','updateClaimDestination','WRITE','ALLOW','ROLE','claimManager'),(582,'Claim','downloadFile','READ','ALLOW','ROLE','claimManager'),(583,'Claim','deleteById','WRITE','ALLOW','ROLE','claimManager'),(584,'Claim','filter','READ','ALLOW','ROLE','salesPerson'),(585,'Claim','logs','READ','ALLOW','ROLE','claimManager'),(586,'Ticket','find','READ','ALLOW','ROLE','employee'),(587,'Ticket','findById','READ','ALLOW','ROLE','employee'),(588,'Ticket','findOne','READ','ALLOW','ROLE','employee'),(589,'Ticket','getVolume','READ','ALLOW','ROLE','employee'),(590,'Ticket','getTotalVolume','READ','ALLOW','ROLE','employee'),(591,'Ticket','summary','READ','ALLOW','ROLE','employee'),(592,'Ticket','priceDifference','READ','ALLOW','ROLE','employee'),(593,'Ticket','componentUpdate','WRITE','ALLOW','ROLE','employee'),(594,'Ticket','new','WRITE','ALLOW','ROLE','employee'),(595,'Ticket','isEditable','READ','ALLOW','ROLE','employee'),(596,'Ticket','setDeleted','WRITE','ALLOW','ROLE','salesPerson'),(597,'Ticket','restore','WRITE','ALLOW','ROLE','employee'),(598,'Ticket','getSales','READ','ALLOW','ROLE','employee'),(599,'Ticket','getSalesPersonMana','READ','ALLOW','ROLE','employee'),(600,'Ticket','filter','READ','ALLOW','ROLE','employee'),(601,'Ticket','makeInvoice','WRITE','ALLOW','ROLE','employee'),(602,'Ticket','updateEditableTicket','WRITE','ALLOW','ROLE','employee'),(603,'Ticket','updateDiscount','WRITE','ALLOW','ROLE','employee'),(604,'Ticket','transferSales','WRITE','ALLOW','ROLE','employee'),(605,'Ticket','sendSms','WRITE','ALLOW','ROLE','employee'),(606,'Ticket','isLocked','READ','ALLOW','ROLE','employee'),(607,'Ticket','freightCost','READ','ALLOW','ROLE','employee'),(608,'Ticket','getComponentsSum','READ','ALLOW','ROLE','employee'),(609,'Ticket','updateAttributes','WRITE','ALLOW','ROLE','delivery'),(610,'Ticket','deliveryNoteCsv','READ','ALLOW','ROLE','employee'),(611,'State','find','READ','ALLOW','ROLE','employee'),(612,'State','findById','READ','ALLOW','ROLE','employee'),(613,'State','findOne','READ','ALLOW','ROLE','employee'),(614,'Worker','find','READ','ALLOW','ROLE','employee'),(615,'Worker','findById','READ','ALLOW','ROLE','employee'),(616,'Worker','findOne','READ','ALLOW','ROLE','employee'),(617,'Worker','filter','READ','ALLOW','ROLE','employee'),(618,'Worker','getWorkedHours','READ','ALLOW','ROLE','employee'),(619,'Worker','active','READ','ALLOW','ROLE','employee'),(620,'Worker','activeWithRole','READ','ALLOW','ROLE','employee'),(621,'Worker','uploadFile','WRITE','ALLOW','ROLE','hr'),(622,'Worker','contracts','READ','ALLOW','ROLE','employee'),(623,'Worker','holidays','READ','ALLOW','ROLE','employee'),(624,'Worker','activeContract','READ','ALLOW','ROLE','employee'),(625,'Worker','activeWithInheritedRole','READ','ALLOW','ROLE','employee'),(626,'Ticket','collectionLabel','READ','ALLOW','ROLE','employee'),(628,'Ticket','expeditionPalletLabel','READ','ALLOW','ROLE','employee'),(629,'Ticket','editDiscount','WRITE','ALLOW','ROLE','artificialBoss'),(630,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','salesTeamBoss'),(635,'Ticket','updateAttributes','WRITE','ALLOW','ROLE','administrative'),(636,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','salesPerson'),(637,'Claim','downloadFile','READ','ALLOW','ROLE','salesPerson'),(638,'Agency','seeExpired','READ','ALLOW','ROLE','artificialBoss'),(639,'Agency','seeExpired','READ','ALLOW','ROLE','logisticAssistant'),(640,'Claim','filter','READ','ALLOW','ROLE','buyer'),(641,'Claim','find','READ','ALLOW','ROLE','buyer'),(642,'Claim','findById','READ','ALLOW','ROLE','buyer'),(643,'Claim','getSummary','READ','ALLOW','ROLE','buyer'),(644,'Claim','filter','READ','ALLOW','ROLE','handmadeBoss'),(645,'Claim','find','READ','ALLOW','ROLE','handmadeBoss'),(646,'Claim','findById','READ','ALLOW','ROLE','handmadeBoss'),(647,'Claim','getSummary','READ','ALLOW','ROLE','handmadeBoss'),(648,'Claim','__get__lines','READ','ALLOW','ROLE','claimManager'),(649,'Claim','__get__lines','READ','ALLOW','ROLE','salesPerson'),(650,'Claim','getSummary','READ','ALLOW','ROLE','deliveryBoss'),(651,'Claim','findById','READ','ALLOW','ROLE','deliveryBoss'),(652,'Claim','find','READ','ALLOW','ROLE','deliveryBoss'),(653,'Claim','filter','READ','ALLOW','ROLE','deliveryBoss'),(654,'Ticket','editZone','WRITE','ALLOW','ROLE','logisticAssistant'),(655,'Entry','addFromPackaging','WRITE','ALLOW','ROLE','production'),(656,'Entry','addFromBuy','WRITE','ALLOW','ROLE','production'),(657,'Supplier','getItemsPackaging','READ','ALLOW','ROLE','production'),(658,'Ticket','closeAll','WRITE','ALLOW','ROLE','system'),(659,'Account','*','*','ALLOW','ROLE','itManagement'),(660,'Account','*','READ','ALLOW','ROLE','employee'),(664,'MailForward','*','*','ALLOW','ROLE','itManagement'),(665,'Role','*','READ','ALLOW','ROLE','employee'),(666,'Role','*','WRITE','ALLOW','ROLE','it'),(667,'VnUser','*','*','ALLOW','ROLE','itManagement'),(668,'VnUser','__get__preview','READ','ALLOW','ROLE','employee'),(669,'VnUser','preview','*','ALLOW','ROLE','employee'),(670,'VnUser','create','*','ALLOW','ROLE','itManagement'),(671,'VnUser','renewToken','WRITE','ALLOW','ROLE','employee'),(672,'PackingSiteAdvanced','*','*','ALLOW','ROLE','production'),(673,'InvoiceOut','makePdfAndNotify','WRITE','ALLOW','ROLE','invoicing'),(674,'InvoiceOutConfig','*','READ','ALLOW','ROLE','invoicing'),(676,'Ticket','invoiceTickets','WRITE','ALLOW','ROLE','employee'),(680,'MailAliasAccount','*','READ','ALLOW','ROLE','employee'),(681,'MailAliasAccount','create','WRITE','ALLOW','ROLE','employee'),(682,'MailAliasAccount','deleteById','WRITE','ALLOW','ROLE','employee'),(683,'MailAliasAccount','canEditAlias','WRITE','ALLOW','ROLE','itManagement'),(684,'WorkerDisableExcluded','*','READ','ALLOW','ROLE','itManagement'),(685,'WorkerDisableExcluded','*','WRITE','ALLOW','ROLE','itManagement'),(686,'MailForward','*','*','ALLOW','ROLE','hr'),(687,'ClientSms','find','READ','ALLOW','ROLE','employee'),(688,'ClientSms','create','WRITE','ALLOW','ROLE','employee'),(689,'Vehicle','sorted','WRITE','ALLOW','ROLE','employee'),(690,'Roadmap','*','*','ALLOW','ROLE','palletizerBoss'),(691,'Roadmap','*','*','ALLOW','ROLE','productionBoss'),(692,'ExpeditionTruck','*','*','ALLOW','ROLE','palletizerBoss'),(693,'ExpeditionTruck','*','*','ALLOW','ROLE','productionBoss'),(694,'MailAliasAccount','canEditAlias','WRITE','ALLOW','ROLE','marketingBoss'),(695,'ViaexpressConfig','internationalExpedition','WRITE','ALLOW','ROLE','employee'),(696,'ViaexpressConfig','renderer','READ','ALLOW','ROLE','employee'),(697,'Ticket','transferClient','WRITE','ALLOW','ROLE','administrative'),(698,'Ticket','canEditWeekly','WRITE','ALLOW','ROLE','buyer'),(699,'TicketSms','find','READ','ALLOW','ROLE','salesPerson'),(701,'Docuware','upload','WRITE','ALLOW','ROLE','deliveryBoss'),(702,'Ticket','docuwareDownload','READ','ALLOW','ROLE','salesPerson'); /*!40000 ALTER TABLE `ACL` ENABLE KEYS */; UNLOCK TABLES; From aef34165d276edad2e12556d43ea2fad276f7c7c Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 18 Sep 2023 13:57:17 +0200 Subject: [PATCH 104/427] refs #4131 reverse claim changes --- front/core/directives/anchor.js | 4 ++-- modules/claim/front/summary/index.html | 2 +- modules/claim/front/summary/index.js | 2 +- modules/claim/front/summary/index.spec.js | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/front/core/directives/anchor.js b/front/core/directives/anchor.js index 81e252e04..b460b3ada 100644 --- a/front/core/directives/anchor.js +++ b/front/core/directives/anchor.js @@ -8,7 +8,7 @@ export function stringifyParams(data) { return params; } -export function state($state, event, data) { +export function changeState($state, event, data) { const params = stringifyParams(data); $state.go(data.state, params); @@ -53,7 +53,7 @@ export function directive($state, $window) { if (ctrlPressed || data.target == '_blank') openNewTab($state, $window, event, data); else - state($state, event, data); + changeState($state, event, data); }); $element.on('mousedown', event => { diff --git a/modules/claim/front/summary/index.html b/modules/claim/front/summary/index.html index 877a8c0f2..3115cb451 100644 --- a/modules/claim/front/summary/index.html +++ b/modules/claim/front/summary/index.html @@ -21,7 +21,7 @@ value-field="id" show-field="description" url="claimStates" - on-change="$ctrl.state(value)"> + on-change="$ctrl.changeState(value)"> diff --git a/modules/claim/front/summary/index.js b/modules/claim/front/summary/index.js index f1310c298..7cd4805e9 100644 --- a/modules/claim/front/summary/index.js +++ b/modules/claim/front/summary/index.js @@ -71,7 +71,7 @@ class Controller extends Summary { return this.vnFile.getPath(`/api/dms/${dmsId}/downloadFile`); } - state(value) { + changeState(value) { const params = { id: this.claim.id, claimStateFk: value diff --git a/modules/claim/front/summary/index.spec.js b/modules/claim/front/summary/index.spec.js index 04a270c5f..8540a3a97 100644 --- a/modules/claim/front/summary/index.spec.js +++ b/modules/claim/front/summary/index.spec.js @@ -28,14 +28,14 @@ describe('Claim', () => { }); }); - describe('state()', () => { + describe('changeState()', () => { it('should make an HTTP post query, then call the showSuccess()', () => { jest.spyOn(controller.vnApp, 'showSuccess').mockReturnThis(); const expectedParams = {id: 1, claimStateFk: 1}; $httpBackend.when('GET', `Claims/1/getSummary`).respond(200, 24); $httpBackend.expect('PATCH', `Claims/updateClaim/1`, expectedParams).respond(200); - controller.state(1); + controller.changeState(1); $httpBackend.flush(); expect(controller.vnApp.showSuccess).toHaveBeenCalled(); From 90b3107537db966d037d727b6593e838e2dcb340 Mon Sep 17 00:00:00 2001 From: pablone Date: Tue, 19 Sep 2023 07:07:52 +0200 Subject: [PATCH 105/427] refs #4131 grant and revoke --- db/changes/233801/00-ACLticketTrackingState.sql | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/db/changes/233801/00-ACLticketTrackingState.sql b/db/changes/233801/00-ACLticketTrackingState.sql index a0e3824db..ddd838e7e 100644 --- a/db/changes/233801/00-ACLticketTrackingState.sql +++ b/db/changes/233801/00-ACLticketTrackingState.sql @@ -1,3 +1,11 @@ UPDATE `salix`.`ACL` SET property = 'state' - WHERE property = 'changeState'; \ No newline at end of file + 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'@; From 361c2b4cad3cfccaddb2d012055ecd72ed10a77d Mon Sep 17 00:00:00 2001 From: pablone Date: Tue, 19 Sep 2023 07:33:27 +0200 Subject: [PATCH 106/427] refs #6213 fixSpec --- .../{233801 => 234001}/00-supplierAccountCheckLength.sql | 0 modules/supplier/back/models/specs/supplier.spec.js | 4 ++-- 2 files changed, 2 insertions(+), 2 deletions(-) rename db/changes/{233801 => 234001}/00-supplierAccountCheckLength.sql (100%) diff --git a/db/changes/233801/00-supplierAccountCheckLength.sql b/db/changes/234001/00-supplierAccountCheckLength.sql similarity index 100% rename from db/changes/233801/00-supplierAccountCheckLength.sql rename to db/changes/234001/00-supplierAccountCheckLength.sql diff --git a/modules/supplier/back/models/specs/supplier.spec.js b/modules/supplier/back/models/specs/supplier.spec.js index d75c80558..043399dc9 100644 --- a/modules/supplier/back/models/specs/supplier.spec.js +++ b/modules/supplier/back/models/specs/supplier.spec.js @@ -126,12 +126,12 @@ describe('loopback model Supplier', () => { }); describe('after save observer', () => { - fit('should update the account attribute when a new supplier is created', async() => { + it('should update the account attribute when a new supplier is created', async() => { const tx = await models.Supplier.beginTransaction({}); const options = {transaction: tx}; try { - const newSupplier = await models.Supplier.create({id: '6969', name: 'Alfred Pennyworth'}, options); + const newSupplier = await models.Supplier.create({id: '9999', name: 'Alfred Pennyworth'}, options); const fetchedSupplier = await models.Supplier.findById(newSupplier.id, null, options); expect(fetchedSupplier.account).toEqual('4100006969'); From 971d77a198148582d8411d5eee04c34760eba906 Mon Sep 17 00:00:00 2001 From: pablone Date: Tue, 19 Sep 2023 07:46:44 +0200 Subject: [PATCH 107/427] refs #6213 specChangeId --- modules/supplier/back/models/specs/supplier.spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/supplier/back/models/specs/supplier.spec.js b/modules/supplier/back/models/specs/supplier.spec.js index 043399dc9..9dd84d9fa 100644 --- a/modules/supplier/back/models/specs/supplier.spec.js +++ b/modules/supplier/back/models/specs/supplier.spec.js @@ -134,7 +134,7 @@ describe('loopback model Supplier', () => { const newSupplier = await models.Supplier.create({id: '9999', name: 'Alfred Pennyworth'}, options); const fetchedSupplier = await models.Supplier.findById(newSupplier.id, null, options); - expect(fetchedSupplier.account).toEqual('4100006969'); + expect(fetchedSupplier.account).toEqual('4100009999'); await tx.rollback(); } catch (e) { await tx.rollback(); From 9524ff69320c1b3e806406211472f75f6178fcf0 Mon Sep 17 00:00:00 2001 From: carlossa Date: Tue, 19 Sep 2023 11:02:12 +0200 Subject: [PATCH 108/427] refs #5660 fix sql --- db/changes/234001/01-deliveryAssistantACL.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/changes/234001/01-deliveryAssistantACL.sql b/db/changes/234001/01-deliveryAssistantACL.sql index 9f3caf848..44459c432 100644 --- a/db/changes/234001/01-deliveryAssistantACL.sql +++ b/db/changes/234001/01-deliveryAssistantACL.sql @@ -13,4 +13,4 @@ INSERT INTO `account`.`roleInherit` (role, inheritsFrom) (SELECT id FROM account.role WHERE name = 'deliveryAssistant') roleInherit; -CALL account.role_syncPrivileges(); +CALL `account`.`role_syncPrivileges`(); From 661563a2b6a0fe9bf8689170b81b54e95b129087 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 19 Sep 2023 12:14:55 +0200 Subject: [PATCH 109/427] refs #6210 Refactor filter client (zoneFk) --- modules/client/back/methods/client/filter.js | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/modules/client/back/methods/client/filter.js b/modules/client/back/methods/client/filter.js index 3bf29501b..d7d1450ab 100644 --- a/modules/client/back/methods/client/filter.js +++ b/modules/client/back/methods/client/filter.js @@ -80,10 +80,15 @@ module.exports = Self => { Object.assign(myOptions, options); if (args.zoneFk) { - query = `CALL vn.zone_getPostalCode(?)`; - const [geos] = await Self.rawSql(query, [args.zoneFk]); - for (let geo of geos) - postalCode.push(geo.name); + let stmts = []; + stmts.push(new ParameterizedSQL('CALL vn.zone_getPostalCode(?)', [ args.zoneFk])); + stmts.push(`SELECT name FROM tmp.zoneNodes`); + stmts.push(`DROP TEMPORARY TABLE IF EXISTS tmp.zoneNodes`); + const sql = ParameterizedSQL.join(stmts, ';'); + const [results] = await conn.executeStmt(sql); + + for (let result of results) + postalCode.push(result.name); } const where = buildFilter(ctx.args, (param, value) => { From 77b55e5b0947cd14d855326ba12a6260bbd671a5 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 19 Sep 2023 12:15:23 +0200 Subject: [PATCH 110/427] refs #6210 Minor change --- modules/client/back/methods/client/filter.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/client/back/methods/client/filter.js b/modules/client/back/methods/client/filter.js index d7d1450ab..c109ea5b7 100644 --- a/modules/client/back/methods/client/filter.js +++ b/modules/client/back/methods/client/filter.js @@ -81,7 +81,7 @@ module.exports = Self => { if (args.zoneFk) { let stmts = []; - stmts.push(new ParameterizedSQL('CALL vn.zone_getPostalCode(?)', [ args.zoneFk])); + stmts.push(new ParameterizedSQL('CALL vn.zone_getPostalCode(?)', [args.zoneFk])); stmts.push(`SELECT name FROM tmp.zoneNodes`); stmts.push(`DROP TEMPORARY TABLE IF EXISTS tmp.zoneNodes`); const sql = ParameterizedSQL.join(stmts, ';'); From 2686fd0601aca0b92d6635c355005c0836d938bd Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 19 Sep 2023 12:18:46 +0200 Subject: [PATCH 111/427] refs #6210 Minor change --- modules/client/back/methods/client/filter.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/client/back/methods/client/filter.js b/modules/client/back/methods/client/filter.js index c109ea5b7..eaf4ecf30 100644 --- a/modules/client/back/methods/client/filter.js +++ b/modules/client/back/methods/client/filter.js @@ -83,7 +83,7 @@ module.exports = Self => { let stmts = []; stmts.push(new ParameterizedSQL('CALL vn.zone_getPostalCode(?)', [args.zoneFk])); stmts.push(`SELECT name FROM tmp.zoneNodes`); - stmts.push(`DROP TEMPORARY TABLE IF EXISTS tmp.zoneNodes`); + stmts.push(`DROP TEMPORARY TABLE tmp.zoneNodes`); const sql = ParameterizedSQL.join(stmts, ';'); const [results] = await conn.executeStmt(sql); From 45cf1b1ff313287560ea3bf16803196033ccd7e5 Mon Sep 17 00:00:00 2001 From: jgallego Date: Wed, 20 Sep 2023 08:12:07 +0200 Subject: [PATCH 112/427] fixes #6241 dbTest fixed --- db/dump/fixtures.sql | 4 +- db/tests/vn/item_getBalance.spec.js | 6 +-- db/tests/vn/logAddWithUser.spec.js | 42 ------------------- .../vn/timeControl_calculateByUser.spec.js | 24 ++--------- db/tests/vn/zone_getFromGeo.spec.js | 2 +- .../05-ticket/06_basic_data_steps.spec.js | 2 +- .../methods/sale/specs/updatePrice.spec.js | 2 +- 7 files changed, 12 insertions(+), 70 deletions(-) delete mode 100644 db/tests/vn/logAddWithUser.spec.js diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 9187e2871..78b0967b9 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -1013,7 +1013,7 @@ INSERT INTO `vn`.`sale`(`id`, `itemFk`, `ticketFk`, `concept`, `quantity`, `pric (4, 4, 1, 'Melee weapon heavy shield 100cm', 20, 1.69, 0, 0, 0, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH)), (5, 1, 2, 'Ranged weapon longbow 200cm', 1, 110.33, 0, 0, 0, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH)), (6, 1, 3, 'Ranged weapon longbow 200cm', 1, 110.33, 0, 0, 0, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH)), - (7, 2, 11, 'Melee weapon combat fist 15cm', 15, 7.44, 0, 0, 0, util.VN_CURDATE()), + (7, 2, 11, 'Melee weapon combat fist 15cm', 15, 7.74, 0, 0, 0, util.VN_CURDATE()), (8, 4, 11, 'Melee weapon heavy shield 100cm', 10, 1.79, 0, 0, 0, util.VN_CURDATE()), (9, 1, 16, 'Ranged weapon longbow 200cm', 1, 103.49, 0, 0, 0, util.VN_CURDATE()), (10, 2, 16, 'Melee weapon combat fist 15cm', 10, 7.09, 0, 0, 0, util.VN_CURDATE()), @@ -2973,4 +2973,4 @@ INSERT INTO vn.XDiario (id, ASIEN, FECHA, SUBCTA, CONTRA, CONCEPTO, EURODEBE, EU (3, 1.0, util.VN_CURDATE(), '4770000010', '4300001104', 'Inmovilizado pendiente : n/fra T3333333 Tony Stark', NULL, 0.81, 8.07, 'T', '3333333', 10.00, NULL, NULL, NULL, NULL, NULL, '', '2', '', 1, 1, '06089160W', 'IRON MAN', 1, 1, 0, util.VN_CURDATE(), 0, 442, 0, 0, 0.00, NULL, NULL, util.VN_CURDATE(), NULL, 1, 1, 1, 1, NULL, NULL, NULL, NULL, NULL, 0, NULL, NULL, 1), (4, 2.0, util.VN_CURDATE(), '4300001104', NULL, 'n/fra T4444444', 8.88, NULL, NULL, NULL, '0', NULL, 0.00, NULL, NULL, NULL, NULL, NULL, '2', NULL, 1, 2, 'I.F.', 'Nombre Importador', 1, 0, 0, util.VN_CURDATE(), 0, 442, 0, 0, 0.00, NULL, NULL, util.VN_CURDATE(), NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, NULL, NULL, 0), (5, 2.0, util.VN_CURDATE(), '2000000000', '4300001104', 'n/fra T4444444 Tony Stark', NULL, 8.07, NULL, NULL, '0', NULL, 0.00, NULL, NULL, NULL, NULL, NULL, '2', NULL, 1, 2, 'I.F.', 'Nombre Importador', 1, 0, 0, util.VN_CURDATE(), 0, 442, 0, 0, 0.00, NULL, NULL, util.VN_CURDATE(), NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, NULL, NULL, 0), - (6, 2.0, util.VN_CURDATE(), '4770000010', '4300001104', 'Inmovilizado pendiente : n/fra T4444444 Tony Stark', NULL, 0.81, 8.07, 'T', '4444444', 10.00, NULL, NULL, NULL, NULL, NULL, '', '2', '', 1, 1, '06089160W', 'IRON MAN', 1, 1, 0, util.VN_CURDATE(), 0, 442, 0, 0, 0.00, NULL, NULL, util.VN_CURDATE(), NULL, 1, 1, 1, 1, NULL, NULL, NULL, NULL, NULL, 0, NULL, NULL, 0); \ No newline at end of file + (6, 2.0, util.VN_CURDATE(), '4770000010', '4300001104', 'Inmovilizado pendiente : n/fra T4444444 Tony Stark', NULL, 0.81, 8.07, 'T', '4444444', 10.00, NULL, NULL, NULL, NULL, NULL, '', '2', '', 1, 1, '06089160W', 'IRON MAN', 1, 1, 0, util.VN_CURDATE(), 0, 442, 0, 0, 0.00, NULL, NULL, util.VN_CURDATE(), NULL, 1, 1, 1, 1, NULL, NULL, NULL, NULL, NULL, 0, NULL, NULL, 0); diff --git a/db/tests/vn/item_getBalance.spec.js b/db/tests/vn/item_getBalance.spec.js index 2e24d5ce7..74e1e6659 100644 --- a/db/tests/vn/item_getBalance.spec.js +++ b/db/tests/vn/item_getBalance.spec.js @@ -6,13 +6,13 @@ describe('item_getBalance()', () => { let stmts = []; let params = { - warehouseFk: 1, - itemFk: 1 + itemFk: 1, + warehouseFk: 1 }; const conn = await app.models.Item.dataSource.connector; - stmts.push(new ParameterizedSQL('CALL vn.item_getBalance(?, ?)', [ + stmts.push(new ParameterizedSQL('CALL vn.item_getBalance(?, ?, NULL)', [ params.warehouseFk, params.itemFk ])); diff --git a/db/tests/vn/logAddWithUser.spec.js b/db/tests/vn/logAddWithUser.spec.js deleted file mode 100644 index 8711769d0..000000000 --- a/db/tests/vn/logAddWithUser.spec.js +++ /dev/null @@ -1,42 +0,0 @@ -const app = require('vn-loopback/server/server'); -const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; - -describe('logAddWithUser()', () => { - it('should log any action taken by the user in a table ending in Log', async() => { - let stmts = []; - let stmt; - - stmts.push('START TRANSACTION'); - - let params = { - ticketFk: 1, - userId: 9, - actionCode: 'update', - targetEntity: 'ticket', - description: 'we are testing stuff' - }; - - stmt = new ParameterizedSQL('CALL vn.logAddWithUser(?, ?, ?, ?, ?)', [ - params.ticketFk, - params.userId, - params.actionCode, - params.targetEntity, - params.description - ]); - stmts.push(stmt); - - stmt = new ParameterizedSQL('SELECT * FROM vn.ticketLog WHERE description = ?', [ - params.description - ]); - let ticketLogIndex = stmts.push(stmt) - 1; - - stmts.push('ROLLBACK'); - - let sql = ParameterizedSQL.join(stmts, ';'); - let result = await app.models.Ticket.rawStmt(sql); - - savedDescription = result[ticketLogIndex][0].description; - - expect(savedDescription).toEqual(params.description); - }); -}); diff --git a/db/tests/vn/timeControl_calculateByUser.spec.js b/db/tests/vn/timeControl_calculateByUser.spec.js index 73e00ec3a..0b385d2c9 100644 --- a/db/tests/vn/timeControl_calculateByUser.spec.js +++ b/db/tests/vn/timeControl_calculateByUser.spec.js @@ -14,14 +14,6 @@ describe('timeControl_calculateByUser()', () => { let stmts = []; let stmt; - stmts.push('START TRANSACTION'); - - stmts.push(` - DROP TEMPORARY TABLE IF EXISTS - tmp.timeControlCalculate, - tmp.timeBusinessCalculate - `); - let params = { workerID: 1106, start: start, @@ -37,17 +29,15 @@ describe('timeControl_calculateByUser()', () => { let tableIndex = stmts.push('SELECT * FROM tmp.timeControlCalculate') - 1; - stmts.push('ROLLBACK'); - let sql = ParameterizedSQL.join(stmts, ';'); let result = await app.models.Ticket.rawStmt(sql); let [timeControlCalculateTable] = result[tableIndex]; - expect(timeControlCalculateTable.timeWorkSeconds).toEqual(29400); + expect(timeControlCalculateTable.timeWorkSeconds).toEqual(28200); }); - - it(`should return the worked hours between last sunday and monday`, async() => { + // #2261 + xit(`should return the worked hours between last sunday and monday`, async() => { let lastSunday = Date.vnNew(); let daysSinceSunday = lastSunday.getDay(); if (daysSinceSunday === 0) // this means today is sunday but you need the previous sunday :) @@ -65,13 +55,7 @@ describe('timeControl_calculateByUser()', () => { stmts.push('START TRANSACTION'); - stmts.push(` - DROP TEMPORARY TABLE IF EXISTS - tmp.timeControlCalculate, - tmp.timeBusinessCalculate - `); - - const workerID = 1107; + const workerID = 1108; stmt = new ParameterizedSQL(` INSERT INTO vn.workerTimeControl(userFk, timed, manual, direction) diff --git a/db/tests/vn/zone_getFromGeo.spec.js b/db/tests/vn/zone_getFromGeo.spec.js index 0dccf92cc..74b6e00cc 100644 --- a/db/tests/vn/zone_getFromGeo.spec.js +++ b/db/tests/vn/zone_getFromGeo.spec.js @@ -7,7 +7,7 @@ describe('zone zone_getFromGeo()', () => { let stmt; stmts.push('START TRANSACTION'); - let geoFk = 17; + let geoFk = 16; stmt = new ParameterizedSQL('CALL zone_getFromGeo(?)', [ geoFk, diff --git a/e2e/paths/05-ticket/06_basic_data_steps.spec.js b/e2e/paths/05-ticket/06_basic_data_steps.spec.js index 55aec45fb..77f0e0459 100644 --- a/e2e/paths/05-ticket/06_basic_data_steps.spec.js +++ b/e2e/paths/05-ticket/06_basic_data_steps.spec.js @@ -75,7 +75,7 @@ describe('Ticket Edit basic data path', () => { const result = await page .waitToGetProperty(selectors.ticketBasicData.stepTwoTotalPriceDif, 'innerText'); - expect(result).toContain('-€232.75'); + expect(result).toContain('-€228.25'); }); it(`should select a new reason for the changes made then click on finalize`, async() => { diff --git a/modules/ticket/back/methods/sale/specs/updatePrice.spec.js b/modules/ticket/back/methods/sale/specs/updatePrice.spec.js index 133be8de3..9d1403df0 100644 --- a/modules/ticket/back/methods/sale/specs/updatePrice.spec.js +++ b/modules/ticket/back/methods/sale/specs/updatePrice.spec.js @@ -108,7 +108,7 @@ describe('sale updatePrice()', () => { }}, options); expect(updatedSale.price).toBe(price); - expect(createdSaleComponent.value).toEqual(-2.04); + expect(createdSaleComponent.value).toEqual(-2.34); const updatedSalesPersonMana = await models.WorkerMana.findById(18, null, options); From 4870b0830b720ba609afe4880d2b8f3813759aa6 Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 20 Sep 2023 11:06:30 +0200 Subject: [PATCH 113/427] ref #5914 fix refund and change method name --- .../00-transferInvoiceACL.sql} | 2 +- loopback/locale/es.json | 304 +----------------- .../methods/invoiceOut/transferInvoice.js | 2 +- modules/invoiceOut/back/models/invoice-out.js | 2 +- modules/ticket/back/methods/sale/refund.js | 83 +---- 5 files changed, 13 insertions(+), 380 deletions(-) rename db/changes/{233201/00-transferInvoiceOutACL.sql => 233601/00-transferInvoiceACL.sql} (80%) diff --git a/db/changes/233201/00-transferInvoiceOutACL.sql b/db/changes/233601/00-transferInvoiceACL.sql similarity index 80% rename from db/changes/233201/00-transferInvoiceOutACL.sql rename to db/changes/233601/00-transferInvoiceACL.sql index 6e8d88c5d..a45e3f479 100644 --- a/db/changes/233201/00-transferInvoiceOutACL.sql +++ b/db/changes/233601/00-transferInvoiceACL.sql @@ -3,4 +3,4 @@ INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalTyp ('CplusRectificationType', '*', 'READ', 'ALLOW', 'ROLE', 'employee'), ('CplusInvoiceType477', '*', 'READ', 'ALLOW', 'ROLE', 'employee'), ('InvoiceCorrectionType', '*', 'READ', 'ALLOW', 'ROLE', 'employee'), - ('InvoiceOut', 'transferInvoiceOut', 'WRITE', 'ALLOW', 'ROLE', 'employee'); \ No newline at end of file + ('InvoiceOut', 'transferInvoice', 'WRITE', 'ALLOW', 'ROLE', 'employee'); \ No newline at end of file diff --git a/loopback/locale/es.json b/loopback/locale/es.json index b2c6ae3e9..d436ec197 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -8,7 +8,6 @@ "Invalid email": "Invalid email", "Phone cannot be blank": "Phone cannot be blank", "The credit must be an integer greater than or equal to zero": "The credit must be an integer greater than or equal to zero", -<<<<<<< HEAD "The grade must be an integer greater than or equal to zero": "The grade must be an integer greater than or equal to zero", "Description should have maximum of 45 characters": "Description should have maximum of 45 characters", "Amount cannot be zero": "Amount cannot be zero", @@ -22,304 +21,5 @@ "State cannot be blank": "State cannot be blank", "Worker cannot be blank": "Worker cannot be blank", "Description cannot be blank": "Description cannot be blank", - "Agency cannot be blank": "Agency cannot be blank", - "The renew period has not been exceeded": "The renew period has not been exceeded" -} -======= - "The grade must be similar to the last one": "El grade debe ser similar al último", - "Only manager can change the credit": "Solo el gerente puede cambiar el credito de este cliente", - "Name cannot be blank": "El nombre no puede estar en blanco", - "Phone cannot be blank": "El teléfono no puede estar en blanco", - "Period cannot be blank": "El periodo no puede estar en blanco", - "Choose a company": "Selecciona una empresa", - "Se debe rellenar el campo de texto": "Se debe rellenar el campo de texto", - "Description should have maximum of 45 characters": "La descripción debe tener maximo 45 caracteres", - "Cannot be blank": "El campo no puede estar en blanco", - "The grade must be an integer greater than or equal to zero": "El grade debe ser un entero mayor o igual a cero", - "Sample type cannot be blank": "El tipo de plantilla no puede quedar en blanco", - "Description cannot be blank": "Se debe rellenar el campo de texto", - "The new quantity should be smaller than the old one": "La nueva cantidad debe de ser menor que la anterior", - "The value should not be greater than 100%": "El valor no debe de ser mayor de 100%", - "The value should be a number": "El valor debe ser un numero", - "This order is not editable": "Esta orden no se puede modificar", - "You can't create an order for a frozen client": "No puedes crear una orden para un cliente congelado", - "You can't create an order for a client that has a debt": "No puedes crear una orden para un cliente con deuda", - "is not a valid date": "No es una fecha valida", - "Barcode must be unique": "El código de barras debe ser único", - "The warehouse can't be repeated": "El almacén no puede repetirse", - "The tag or priority can't be repeated for an item": "El tag o prioridad no puede repetirse para un item", - "The observation type can't be repeated": "El tipo de observación no puede repetirse", - "A claim with that sale already exists": "Ya existe una reclamación para esta línea", - "You don't have enough privileges to change that field": "No tienes permisos para cambiar ese campo", - "Warehouse cannot be blank": "El almacén no puede quedar en blanco", - "Agency cannot be blank": "La agencia no puede quedar en blanco", - "Not enough privileges to edit a client with verified data": "No tienes permisos para hacer cambios en un cliente con datos comprobados", - "This address doesn't exist": "Este consignatario no existe", - "You must delete the claim id %d first": "Antes debes borrar la reclamación %d", - "You don't have enough privileges": "No tienes suficientes permisos", - "Cannot check Equalization Tax in this NIF/CIF": "No se puede marcar RE en este NIF/CIF", - "You can't make changes on the basic data of an confirmed order or with rows": "No puedes cambiar los datos basicos de una orden con artículos", - "INVALID_USER_NAME": "El nombre de usuario solo debe contener letras minúsculas o, a partir del segundo carácter, números o subguiones, no esta permitido el uso de la letra ñ", - "You can't create a ticket for a frozen client": "No puedes crear un ticket para un cliente congelado", - "You can't create a ticket for a inactive client": "No puedes crear un ticket para un cliente inactivo", - "Tag value cannot be blank": "El valor del tag no puede quedar en blanco", - "ORDER_EMPTY": "Cesta vacía", - "You don't have enough privileges to do that": "No tienes permisos para cambiar esto", - "NO SE PUEDE DESACTIVAR EL CONSIGNAT": "NO SE PUEDE DESACTIVAR EL CONSIGNAT", - "Error. El NIF/CIF está repetido": "Error. El NIF/CIF está repetido", - "Street cannot be empty": "Dirección no puede estar en blanco", - "City cannot be empty": "Cuidad no puede estar en blanco", - "Code cannot be blank": "Código no puede estar en blanco", - "You cannot remove this department": "No puedes eliminar este departamento", - "The extension must be unique": "La extensión debe ser unica", - "The secret can't be blank": "La contraseña no puede estar en blanco", - "We weren't able to send this SMS": "No hemos podido enviar el SMS", - "This client can't be invoiced": "Este cliente no puede ser facturado", - "This ticket can't be invoiced": "Este ticket no puede ser facturado", - "You cannot add or modify services to an invoiced ticket": "No puedes añadir o modificar servicios a un ticket facturado", - "This ticket can not be modified": "Este ticket no puede ser modificado", - "The introduced hour already exists": "Esta hora ya ha sido introducida", - "INFINITE_LOOP": "Existe una dependencia entre dos Jefes", - "The sales of the receiver ticket can't be modified": "Las lineas del ticket al que envias no pueden ser modificadas", - "NO_AGENCY_AVAILABLE": "No hay una zona de reparto disponible con estos parámetros", - "ERROR_PAST_SHIPMENT": "No puedes seleccionar una fecha de envío en pasado", - "The current ticket can't be modified": "El ticket actual no puede ser modificado", - "The current claim can't be modified": "La reclamación actual no puede ser modificada", - "The sales of this ticket can't be modified": "Las lineas de este ticket no pueden ser modificadas", - "The sales do not exists": "La(s) línea(s) seleccionada(s) no existe(n)", - "Please select at least one sale": "Por favor selecciona al menos una linea", - "All sales must belong to the same ticket": "Todas las lineas deben pertenecer al mismo ticket", - "NO_ZONE_FOR_THIS_PARAMETERS": "Para este día no hay ninguna zona configurada", - "This item doesn't exists": "El artículo no existe", - "NOT_ZONE_WITH_THIS_PARAMETERS": "Para este día no hay ninguna zona configurada", - "Extension format is invalid": "El formato de la extensión es inválido", - "Invalid parameters to create a new ticket": "Parámetros inválidos para crear un nuevo ticket", - "This item is not available": "Este artículo no está disponible", - "This postcode already exists": "Este código postal ya existe", - "Concept cannot be blank": "El concepto no puede quedar en blanco", - "File doesn't exists": "El archivo no existe", - "You don't have privileges to change the zone": "No tienes permisos para cambiar la zona o para esos parámetros hay más de una opción de envío, hable con las agencias", - "This ticket is already on weekly tickets": "Este ticket ya está en tickets programados", - "Ticket id cannot be blank": "El id de ticket no puede quedar en blanco", - "Weekday cannot be blank": "El día de la semana no puede quedar en blanco", - "You can't delete a confirmed order": "No puedes borrar un pedido confirmado", - "The social name has an invalid format": "El nombre fiscal tiene un formato incorrecto", - "Invalid quantity": "Cantidad invalida", - "This postal code is not valid": "This postal code is not valid", - "is invalid": "is invalid", - "The postcode doesn't exist. Please enter a correct one": "El código postal no existe. Por favor, introduce uno correcto", - "The department name can't be repeated": "El nombre del departamento no puede repetirse", - "This phone already exists": "Este teléfono ya existe", - "You cannot move a parent to its own sons": "No puedes mover un elemento padre a uno de sus hijos", - "You can't create a claim for a removed ticket": "No puedes crear una reclamación para un ticket eliminado", - "You cannot delete a ticket that part of it is being prepared": "No puedes eliminar un ticket en el que una parte que está siendo preparada", - "You must delete all the buy requests first": "Debes eliminar todas las peticiones de compra primero", - "You should specify a date": "Debes especificar una fecha", - "You should specify at least a start or end date": "Debes especificar al menos una fecha de inicio o de fín", - "Start date should be lower than end date": "La fecha de inicio debe ser menor que la fecha de fín", - "You should mark at least one week day": "Debes marcar al menos un día de la semana", - "Swift / BIC can't be empty": "Swift / BIC no puede estar vacío", - "Customs agent is required for a non UEE member": "El agente de aduanas es requerido para los clientes extracomunitarios", - "Incoterms is required for a non UEE member": "El incoterms es requerido para los clientes extracomunitarios", - "Deleted sales from ticket": "He eliminado las siguientes lineas del ticket [{{ticketId}}]({{{ticketUrl}}}): {{{deletions}}}", - "Added sale to ticket": "He añadido la siguiente linea al ticket [{{ticketId}}]({{{ticketUrl}}}): {{{addition}}}", - "Changed sale discount": "He cambiado el descuento de las siguientes lineas al ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}", - "Created claim": "He creado la reclamación [{{claimId}}]({{{claimUrl}}}) de las siguientes lineas del ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}", - "Changed sale price": "He cambiado el precio de [{{itemId}} {{concept}}]({{{itemUrl}}}) ({{quantity}}) de {{oldPrice}}€ ➔ *{{newPrice}}€* del ticket [{{ticketId}}]({{{ticketUrl}}})", - "Changed sale quantity": "He cambiado la cantidad de [{{itemId}} {{concept}}]({{{itemUrl}}}) de {{oldQuantity}} ➔ *{{newQuantity}}* del ticket [{{ticketId}}]({{{ticketUrl}}})", - "State": "Estado", - "regular": "normal", - "reserved": "reservado", - "Changed sale reserved state": "He cambiado el estado reservado de las siguientes lineas al ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}", - "Bought units from buy request": "Se ha comprado {{quantity}} unidades de [{{itemId}} {{concept}}]({{{urlItem}}}) para el ticket id [{{ticketId}}]({{{url}}})", - "Deny buy request": "Se ha rechazado la petición de compra para el ticket id [{{ticketId}}]({{{url}}}). Motivo: {{observation}}", - "MESSAGE_INSURANCE_CHANGE": "He cambiado el crédito asegurado del cliente [{{clientName}} ({{clientId}})]({{{url}}}) a *{{credit}} €*", - "Changed client paymethod": "He cambiado la forma de pago del cliente [{{clientName}} ({{clientId}})]({{{url}}})", - "Sent units from ticket": "Envio *{{quantity}}* unidades de [{{concept}} ({{itemId}})]({{{itemUrl}}}) a *\"{{nickname}}\"* provenientes del ticket id [{{ticketId}}]({{{ticketUrl}}})", - "Change quantity": "{{concept}} cambia de {{oldQuantity}} a {{newQuantity}}", - "Claim will be picked": "Se recogerá el género de la reclamación [({{claimId}})]({{{claimUrl}}}) del cliente *{{clientName}}*", - "Claim state has changed to incomplete": "Se ha cambiado el estado de la reclamación [({{claimId}})]({{{claimUrl}}}) del cliente *{{clientName}}* a *incompleta*", - "Claim state has changed to canceled": "Se ha cambiado el estado de la reclamación [({{claimId}})]({{{claimUrl}}}) del cliente *{{clientName}}* a *anulado*", - "Client checked as validated despite of duplication": "Cliente comprobado a pesar de que existe el cliente id {{clientId}}", - "ORDER_ROW_UNAVAILABLE": "No hay disponibilidad de este producto", - "Distance must be lesser than 1000": "La distancia debe ser inferior a 1000", - "This ticket is deleted": "Este ticket está eliminado", - "Unable to clone this travel": "No ha sido posible clonar este travel", - "This thermograph id already exists": "La id del termógrafo ya existe", - "Choose a date range or days forward": "Selecciona un rango de fechas o días en adelante", - "ORDER_ALREADY_CONFIRMED": "ORDER_ALREADY_CONFIRMED", - "Invalid password": "Invalid password", - "Password does not meet requirements": "La contraseña no cumple los requisitos", - "Role already assigned": "Role already assigned", - "Invalid role name": "Invalid role name", - "Role name must be written in camelCase": "Role name must be written in camelCase", - "Email already exists": "Email already exists", - "User already exists": "User already exists", - "Absence change notification on the labour calendar": "Notificacion de cambio de ausencia en el calendario laboral", - "Record of hours week": "Registro de horas semana {{week}} año {{year}} ", - "Created absence": "El empleado {{author}} ha añadido una ausencia de tipo '{{absenceType}}' a {{employee}} para el día {{dated}}.", - "Deleted absence": "El empleado {{author}} ha eliminado una ausencia de tipo '{{absenceType}}' a {{employee}} del día {{dated}}.", - "I have deleted the ticket id": "He eliminado el ticket id [{{id}}]({{{url}}})", - "I have restored the ticket id": "He restaurado el ticket id [{{id}}]({{{url}}})", - "You can only restore a ticket within the first hour after deletion": "Únicamente puedes restaurar el ticket dentro de la primera hora después de su eliminación", - "Changed this data from the ticket": "He cambiado estos datos del ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}", - "agencyModeFk": "Agencia", - "clientFk": "Cliente", - "zoneFk": "Zona", - "warehouseFk": "Almacén", - "shipped": "F. envío", - "landed": "F. entrega", - "addressFk": "Consignatario", - "companyFk": "Empresa", - "The social name cannot be empty": "La razón social no puede quedar en blanco", - "The nif cannot be empty": "El NIF no puede quedar en blanco", - "You need to fill sage information before you check verified data": "Debes rellenar la información de sage antes de marcar datos comprobados", - "ASSIGN_ZONE_FIRST": "Asigna una zona primero", - "Amount cannot be zero": "El importe no puede ser cero", - "Company has to be official": "Empresa inválida", - "You can not select this payment method without a registered bankery account": "No se puede utilizar este método de pago si no has registrado una cuenta bancaria", - "Action not allowed on the test environment": "Esta acción no está permitida en el entorno de pruebas", - "The selected ticket is not suitable for this route": "El ticket seleccionado no es apto para esta ruta", - "New ticket request has been created with price": "Se ha creado una nueva petición de compra '{{description}}' para el día *{{shipped}}*, con una cantidad de *{{quantity}}* y un precio de *{{price}} €*", - "New ticket request has been created": "Se ha creado una nueva petición de compra '{{description}}' para el día *{{shipped}}*, con una cantidad de *{{quantity}}*", - "Swift / BIC cannot be empty": "Swift / BIC no puede estar vacío", - "This BIC already exist.": "Este BIC ya existe.", - "That item doesn't exists": "Ese artículo no existe", - "There's a new urgent ticket:": "Hay un nuevo ticket urgente:", - "Invalid account": "Cuenta inválida", - "Compensation account is empty": "La cuenta para compensar está vacia", - "This genus already exist": "Este genus ya existe", - "This specie already exist": "Esta especie ya existe", - "Client assignment has changed": "He cambiado el comercial ~*\"<{{previousWorkerName}}>\"*~ por *\"<{{currentWorkerName}}>\"* del cliente [{{clientName}} ({{clientId}})]({{{url}}})", - "None": "Ninguno", - "The contract was not active during the selected date": "El contrato no estaba activo durante la fecha seleccionada", - "Cannot add more than one '1/2 day vacation'": "No puedes añadir más de un 'Vacaciones 1/2 dia'", - "This document already exists on this ticket": "Este documento ya existe en el ticket", - "Some of the selected tickets are not billable": "Algunos de los tickets seleccionados no son facturables", - "You can't invoice tickets from multiple clients": "No puedes facturar tickets de multiples clientes", - "nickname": "nickname", - "INACTIVE_PROVIDER": "Proveedor inactivo", - "This client is not invoiceable": "Este cliente no es facturable", - "serial non editable": "Esta serie no permite asignar la referencia", - "Max shipped required": "La fecha límite es requerida", - "Can't invoice to future": "No se puede facturar a futuro", - "Can't invoice to past": "No se puede facturar a pasado", - "This ticket is already invoiced": "Este ticket ya está facturado", - "A ticket with an amount of zero can't be invoiced": "No se puede facturar un ticket con importe cero", - "A ticket with a negative base can't be invoiced": "No se puede facturar un ticket con una base negativa", - "Global invoicing failed": "[Facturación global] No se han podido facturar algunos clientes", - "Wasn't able to invoice the following clients": "No se han podido facturar los siguientes clientes", - "Can't verify data unless the client has a business type": "No se puede verificar datos de un cliente que no tiene tipo de negocio", - "You don't have enough privileges to set this credit amount": "No tienes suficientes privilegios para establecer esta cantidad de crédito", - "You can't change the credit set to zero from a financialBoss": "No puedes cambiar el cŕedito establecido a cero por un jefe de finanzas", - "Amounts do not match": "Las cantidades no coinciden", - "The PDF document does not exist": "El documento PDF no existe. Prueba a regenerarlo desde la opción 'Regenerar PDF factura'", - "The type of business must be filled in basic data": "El tipo de negocio debe estar rellenado en datos básicos", - "You can't create a claim from a ticket delivered more than seven days ago": "No puedes crear una reclamación de un ticket entregado hace más de siete días", - "The worker has hours recorded that day": "El trabajador tiene horas fichadas ese día", - "The worker has a marked absence that day": "El trabajador tiene marcada una ausencia ese día", - "You can not modify is pay method checked": "No se puede modificar el campo método de pago validado", - "Can't transfer claimed sales": "No puedes transferir lineas reclamadas", - "You don't have privileges to create refund": "No tienes permisos para crear un abono", - "The item is required": "El artículo es requerido", - "The agency is already assigned to another autonomous": "La agencia ya está asignada a otro autónomo", - "date in the future": "Fecha en el futuro", - "reference duplicated": "Referencia duplicada", - "This ticket is already a refund": "Este ticket ya es un abono", - "isWithoutNegatives": "isWithoutNegatives", - "routeFk": "routeFk", - "Can't change the password of another worker": "No se puede cambiar la contraseña de otro trabajador", - "No hay un contrato en vigor": "No hay un contrato en vigor", - "No se permite fichar a futuro": "No se permite fichar a futuro", - "No está permitido trabajar": "No está permitido trabajar", - "Fichadas impares": "Fichadas impares", - "Descanso diario 12h.": "Descanso diario 12h.", - "Descanso semanal 36h. / 72h.": "Descanso semanal 36h. / 72h.", - "Dirección incorrecta": "Dirección incorrecta", - "Modifiable user details only by an administrator": "Detalles de usuario modificables solo por un administrador", - "Modifiable password only via recovery or by an administrator": "Contraseña modificable solo a través de la recuperación o por un administrador", - "Not enough privileges to edit a client": "No tienes suficientes privilegios para editar un cliente", - "This route does not exists": "Esta ruta no existe", - "Claim pickup order sent": "Reclamación Orden de recogida enviada [{{claimId}}]({{{claimUrl}}}) al cliente *{{clientName}}*", - "You don't have grant privilege": "No tienes privilegios para dar privilegios", - "You don't own the role and you can't assign it to another user": "No eres el propietario del rol y no puedes asignarlo a otro usuario", - "Ticket merged": "Ticket [{{originId}}]({{{originFullPath}}}) ({{{originDated}}}) fusionado con [{{destinationId}}]({{{destinationFullPath}}}) ({{{destinationDated}}})", - "Already has this status": "Ya tiene este estado", - "There aren't records for this week": "No existen registros para esta semana", - "Empty data source": "Origen de datos vacio", - "App locked": "Aplicación bloqueada por el usuario {{userId}}", - "Email verify": "Correo de verificación", - "Landing cannot be lesser than shipment": "Landing cannot be lesser than shipment", - "Receipt's bank was not found": "No se encontró el banco del recibo", - "This receipt was not compensated": "Este recibo no ha sido compensado", - "Client's email was not found": "No se encontró el email del cliente", - "Negative basis": "Base negativa", - "This worker code already exists": "Este codigo de trabajador ya existe", - "This personal mail already exists": "Este correo personal ya existe", - "This worker already exists": "Este trabajador ya existe", - "App name does not exist": "El nombre de aplicación no es válido", - "Try again": "Vuelve a intentarlo", - "Aplicación bloqueada por el usuario 9": "Aplicación bloqueada por el usuario 9", - "Failed to upload delivery note": "Error al subir albarán {{id}}", - "The DOCUWARE PDF document does not exists": "El documento PDF Docuware no existe", - "It is not possible to modify tracked sales": "No es posible modificar líneas de pedido que se hayan empezado a preparar", - "It is not possible to modify sales that their articles are from Floramondo": "No es posible modificar líneas de pedido cuyos artículos sean de Floramondo", - "It is not possible to modify cloned sales": "No es posible modificar líneas de pedido clonadas", - "A supplier with the same name already exists. Change the country.": "Un proveedor con el mismo nombre ya existe. Cambie el país.", - "There is no assigned email for this client": "No hay correo asignado para este cliente", - "Exists an invoice with a future date": "Existe una factura con fecha posterior", - "Invoice date can't be less than max date": "La fecha de factura no puede ser inferior a la fecha límite", - "Warehouse inventory not set": "El almacén inventario no está establecido", - "This locker has already been assigned": "Esta taquilla ya ha sido asignada", - "Tickets with associated refunds": "No se pueden borrar tickets con abonos asociados. Este ticket está asociado al abono Nº %d", - "Not exist this branch": "La rama no existe", - "This ticket cannot be signed because it has not been boxed": "Este ticket no puede firmarse porque no ha sido encajado", - "Collection does not exist": "La colección no existe", - "Cannot obtain exclusive lock": "No se puede obtener un bloqueo exclusivo", - "Insert a date range": "Inserte un rango de fechas", - "Added observation": "{{user}} añadió esta observacion: {{text}}", - "Comment added to client": "Observación añadida al cliente {{clientFk}}", - "Invalid auth code": "Código de verificación incorrecto", - "Invalid or expired verification code": "Código de verificación incorrecto o expirado", - "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", - "Pass expired": "La contraseña ha caducado, cambiela desde Salix", - "Invalid NIF for VIES": "Invalid NIF for VIES", - "Ticket does not exist": "Este ticket no existe", - "Ticket is already signed": "Este ticket ya ha sido firmado", - "Authentication failed": "Autenticación fallida", - "You can't use the same password": "No puedes usar la misma contraseña", - "You can only add negative amounts in refund tickets": "Solo se puede añadir cantidades negativas en tickets abono", - "Fecha fuera de rango": "Fecha fuera de rango", - "Error while generating PDF": "Error al generar PDF", - "Error when sending mail to client": "Error al enviar el correo al cliente", - "Mail not sent": "Se ha producido un fallo al enviar la factura al cliente [{{clientId}}]({{{clientUrl}}}), por favor revisa la dirección de correo electrónico", - "The renew period has not been exceeded": "El periodo de renovación no ha sido superado", - "Valid priorities": "Prioridades válidas: %d", - "Negative basis of tickets": "Base negativa para los tickets: {{ticketsIds}}", - "You cannot assign an alias that you are not assigned to": "No puede asignar un alias que no tenga asignado", - "This ticket cannot be left empty.": "Este ticket no se puede dejar vacío. %s", - "The company has not informed the supplier account for bank transfers": "La empresa no tiene informado la cuenta de proveedor para transferencias bancarias", - "You cannot assign/remove an alias that you are not assigned to": "No puede asignar/eliminar un alias que no tenga asignado", - "This invoice has a linked vehicle.": "Esta factura tiene un vehiculo vinculado", - "You don't have enough privileges.": "No tienes suficientes permisos.", - "This ticket is locked.": "Este ticket está bloqueado.", - "This ticket is not editable.": "Este ticket no es editable.", - "The ticket doesn't exist.": "No existe el ticket.", - "Social name should be uppercase": "La razón social debe ir en mayúscula", - "Street should be uppercase": "La dirección fiscal debe ir en mayúscula", - "The response is not a PDF": "La respuesta no es un PDF", - "Ticket without Route": "Ticket sin ruta" -} ->>>>>>> 72a8256aee7bff0be1dd68c8d4cfbe2edcf8ce60 + "Agency cannot be blank": "Agency cannot be blank" +} \ No newline at end of file diff --git a/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js b/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js index c590ff9ea..0b123dd3d 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js +++ b/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js @@ -44,7 +44,7 @@ module.exports = Self => { } }); - Self.transferInvoiceOut = async(ctx, id, ref, newClientFk, cplusRectificationId, cplusInvoiceType477Id, invoiceCorrectionTypeId, options) => { + Self.transferInvoice = async(ctx, id, ref, newClientFk, cplusRectificationId, cplusInvoiceType477Id, invoiceCorrectionTypeId, options) => { const models = Self.app.models; const myOptions = {userId: ctx.req.accessToken.userId}; diff --git a/modules/invoiceOut/back/models/invoice-out.js b/modules/invoiceOut/back/models/invoice-out.js index 0bb31ce12..ca77c856f 100644 --- a/modules/invoiceOut/back/models/invoice-out.js +++ b/modules/invoiceOut/back/models/invoice-out.js @@ -23,7 +23,7 @@ module.exports = Self => { require('../methods/invoiceOut/getInvoiceDate')(Self); require('../methods/invoiceOut/negativeBases')(Self); require('../methods/invoiceOut/negativeBasesCsv')(Self); - require('../methods/invoiceOut/transferInvoiceOut')(Self); + require('../methods/invoiceOut/transferInvoice')(Self); Self.filePath = async function(id, options) { const fields = ['ref', 'issued']; diff --git a/modules/ticket/back/methods/sale/refund.js b/modules/ticket/back/methods/sale/refund.js index 303d830b6..3f7e1cd21 100644 --- a/modules/ticket/back/methods/sale/refund.js +++ b/modules/ticket/back/methods/sale/refund.js @@ -5,7 +5,8 @@ module.exports = Self => { accepts: [ { arg: 'salesIds', - type: ['number'] + type: ['number'], + required: true }, { arg: 'servicesIds', @@ -40,7 +41,6 @@ module.exports = Self => { myOptions.transaction = tx; } - let refundTicket = null; try { const refundAgencyMode = await models.AgencyMode.findOne({ include: { @@ -55,42 +55,14 @@ module.exports = Self => { const refoundZoneId = refundAgencyMode.zones()[0].id; - if (salesIds) { - const salesFilter = { - where: {id: {inq: salesIds}}, - include: { - relation: 'components', - scope: { - fields: ['saleFk', 'componentFk', 'value'] - } + const salesFilter = { + where: {id: {inq: salesIds}}, + include: { + relation: 'components', + scope: { + fields: ['saleFk', 'componentFk', 'value'] } - }; - const sales = await models.Sale.find(salesFilter, myOptions); - const ticketsIds = [...new Set(sales.map(sale => sale.ticketFk))]; - - const now = Date.vnNew(); - const [firstTicketId] = ticketsIds; - - // eslint-disable-next-line max-len - refundTicket = await createTicketRefund(firstTicketId, now, refundAgencyMode, refoundZoneId, withWarehouse, myOptions); - - for (const sale of sales) { - const createdSale = await models.Sale.create({ - ticketFk: refundTicket.id, - itemFk: sale.itemFk, - quantity: - sale.quantity, - concept: sale.concept, - price: sale.price, - discount: sale.discount, - }, myOptions); - - const components = sale.components(); - for (const component of components) - component.saleFk = createdSale.id; - - await models.SaleComponent.create(components, myOptions); } -<<<<<<< HEAD }; // const sales = await models.Sale.find(salesFilter, myOptions); const refundTicket = await models.Sale.clone( @@ -105,45 +77,6 @@ module.exports = Self => { ); if (tx && !options) await tx.commit(); -======= - } - - if (!refundTicket) { - const servicesFilter = { - where: {id: {inq: servicesIds}} - }; - const services = await models.TicketService.find(servicesFilter, myOptions); - const ticketsIds = [...new Set(services.map(service => service.ticketFk))]; - - const now = Date.vnNew(); - const [firstTicketId] = ticketsIds; - - // eslint-disable-next-line max-len - refundTicket = await createTicketRefund(firstTicketId, now, refundAgencyMode, refoundZoneId, withWarehouse, myOptions); - } - - if (servicesIds && servicesIds.length > 0) { - const servicesFilter = { - where: {id: {inq: servicesIds}} - }; - const services = await models.TicketService.find(servicesFilter, myOptions); - for (const service of services) { - await models.TicketService.create({ - description: service.description, - quantity: service.quantity, - price: - service.price, - taxClassFk: service.taxClassFk, - ticketFk: refundTicket.id, - ticketServiceTypeFk: service.ticketServiceTypeFk, - }, myOptions); - } - } - - const query = `CALL vn.ticket_recalc(?, NULL)`; - await Self.rawSql(query, [refundTicket.id], myOptions); - - if (tx) await tx.commit(); ->>>>>>> 72a8256aee7bff0be1dd68c8d4cfbe2edcf8ce60 return refundTicket; } catch (e) { From f60b6b84fedb6e0ca9b0b75bf7c2fe48f2825a8a Mon Sep 17 00:00:00 2001 From: carlossa Date: Wed, 20 Sep 2023 11:58:36 +0200 Subject: [PATCH 114/427] refs #5843 fix back --- .../{233601 => 234001}/00-dropUserFk.sql | 0 .../234001/00-timeBusiness_calculate.sql | 86 +++++++++++++++++++ .../importToNewRefundTicket.js | 2 +- .../client/back/models/client-observation.js | 2 +- .../back/methods/ticket-request/deny.js | 2 +- .../methods/ticket-tracking/changeState.js | 2 +- .../methods/ticket-tracking/setDelivered.js | 2 +- modules/ticket/back/models/ticket-request.js | 2 +- modules/zone/back/methods/zone/deleteZone.js | 2 +- 9 files changed, 93 insertions(+), 7 deletions(-) rename db/changes/{233601 => 234001}/00-dropUserFk.sql (100%) create mode 100644 db/changes/234001/00-timeBusiness_calculate.sql diff --git a/db/changes/233601/00-dropUserFk.sql b/db/changes/234001/00-dropUserFk.sql similarity index 100% rename from db/changes/233601/00-dropUserFk.sql rename to db/changes/234001/00-dropUserFk.sql diff --git a/db/changes/234001/00-timeBusiness_calculate.sql b/db/changes/234001/00-timeBusiness_calculate.sql new file mode 100644 index 000000000..599dba74a --- /dev/null +++ b/db/changes/234001/00-timeBusiness_calculate.sql @@ -0,0 +1,86 @@ +DELIMITER $$ +$$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`timeBusiness_calculate`(vDatedFrom DATETIME, vDatedTo DATETIME) +BEGIN +/** + * Horas que debe trabajar un empleado según contrato y día. + * @param vDatedFrom workerTimeControl + * @param vDatedTo workerTimeControl + * @table tmp.user(userFk) + * @return tmp.timeBusinessCalculate + */ + DROP TEMPORARY TABLE IF EXISTS tmp.timeBusinessCalculate; + CREATE TEMPORARY TABLE tmp.timeBusinessCalculate + (INDEX (departmentFk)) + SELECT dated, + businessFk, + sub.id userFk, + departmentFk, + hourStart, + hourEnd, + timeTable, + timeWorkSeconds, + SEC_TO_TIME(timeWorkSeconds) timeWorkSexagesimal, + timeWorkSeconds / 3600 timeWorkDecimal, + timeWorkSeconds timeBusinessSeconds, + SEC_TO_TIME(timeWorkSeconds) timeBusinessSexagesimal, + timeWorkSeconds / 3600 timeBusinessDecimal, + name type, + permissionRate, + hoursWeek, + discountRate, + isAllowedToWork + FROM(SELECT t.dated, + b.id businessFk, + w.id, + b.departmentFk, + IF(bs.started = NULL, NULL, GROUP_CONCAT(DISTINCT LEFT(bs.started,5) ORDER BY bs.started ASC SEPARATOR ' - ')) hourStart , + IF(bs.started = NULL, NULL, GROUP_CONCAT(DISTINCT LEFT(bs.ended,5) ORDER BY bs.ended ASC SEPARATOR ' - ')) hourEnd, + IF(bs.started = NULL, NULL, GROUP_CONCAT(DISTINCT LEFT(bs.started,5), " - ", LEFT(bs.ended,5) ORDER BY bs.ended ASC SEPARATOR ' - ')) timeTable, + IF(bs.started = NULL, 0, IFNULL(SUM(TIME_TO_SEC(bs.ended)) - SUM(TIME_TO_SEC(bs.started)), 0)) timeWorkSeconds, + at2.name, + at2.permissionRate, + at2.discountRate, + ct.hoursWeek hoursWeek, + at2.isAllowedToWork + FROM time t + LEFT JOIN business b ON t.dated BETWEEN b.started AND IFNULL(b.ended, vDatedTo) + LEFT JOIN worker w ON w.id = b.workerFk + JOIN tmp.`user` u ON u.userFK = w.id + LEFT JOIN workCenter wc ON wc.id = b.workcenterFK + LEFT JOIN calendarType ct ON ct.id = b.calendarTypeFk + LEFT JOIN businessSchedule bs ON bs.businessFk = b.id AND bs.weekday = WEEKDAY(t.dated) + 1 + LEFT JOIN calendar c ON c.businessFk = b.id AND c.dated = t.dated + LEFT JOIN absenceType at2 ON at2.id = c.dayOffTypeFk + WHERE t.dated BETWEEN vDatedFrom AND vDatedTo + GROUP BY w.id, t.dated + )sub; + + UPDATE tmp.timeBusinessCalculate t + LEFT JOIN businessSchedule bs ON bs.businessFk = t.businessFk + SET t.timeWorkSeconds = t.hoursWeek / 5 * 3600, + t.timeWorkSexagesimal = SEC_TO_TIME( t.hoursWeek / 5 * 3600), + t.timeWorkDecimal = t.hoursWeek / 5, + t.timeBusinessSeconds = t.hoursWeek / 5 * 3600, + t.timeBusinessSexagesimal = SEC_TO_TIME( t.hoursWeek / 5 * 3600), + t.timeBusinessDecimal = t.hoursWeek / 5 + WHERE DAYOFWEEK(t.dated) IN(2,3,4,5,6) AND bs.id IS NULL ; + + UPDATE tmp.timeBusinessCalculate t + SET t.timeWorkSeconds = t.timeWorkSeconds - (t.timeWorkSeconds * permissionRate) , + t.timeWorkSexagesimal = SEC_TO_TIME ((t.timeWorkDecimal - (t.timeWorkDecimal * permissionRate)) * 3600), + t.timeWorkDecimal = t.timeWorkDecimal - (t.timeWorkDecimal * permissionRate) + WHERE permissionRate <> 0; + + UPDATE tmp.timeBusinessCalculate t + JOIN calendarHolidays ch ON ch.dated = t.dated + JOIN business b ON b.id = t.businessFk + AND b.workcenterFk = ch.workcenterFk + SET t.timeWorkSeconds = 0, + t.timeWorkSexagesimal = 0, + t.timeWorkDecimal = 0, + t.permissionrate = 1, + t.type = 'Festivo' + WHERE t.type IS NULL; +END$$ +DELIMITER ; diff --git a/modules/claim/back/methods/claim-beginning/importToNewRefundTicket.js b/modules/claim/back/methods/claim-beginning/importToNewRefundTicket.js index cdf3fc2c3..be3baccd7 100644 --- a/modules/claim/back/methods/claim-beginning/importToNewRefundTicket.js +++ b/modules/claim/back/methods/claim-beginning/importToNewRefundTicket.js @@ -75,7 +75,7 @@ module.exports = Self => { try { const worker = await models.Worker.findOne({ - where: {userFk: userId} + where: {id: userId} }, myOptions); const obsevationType = await models.ObservationType.findOne({ diff --git a/modules/client/back/models/client-observation.js b/modules/client/back/models/client-observation.js index f208cb552..e34eedca9 100644 --- a/modules/client/back/models/client-observation.js +++ b/modules/client/back/models/client-observation.js @@ -9,7 +9,7 @@ module.exports = function(Self) { let token = ctx.options.accessToken; let userId = token && token.userId; - Self.app.models.Worker.findOne({where: {userFk: userId}}, (err, user) => { + Self.app.models.Worker.findOne({where: {id: userId}}, (err, user) => { if (err) return next(err); ctx.instance.workerFk = user.id; next(); diff --git a/modules/ticket/back/methods/ticket-request/deny.js b/modules/ticket/back/methods/ticket-request/deny.js index 35de765d7..92f020083 100644 --- a/modules/ticket/back/methods/ticket-request/deny.js +++ b/modules/ticket/back/methods/ticket-request/deny.js @@ -39,7 +39,7 @@ module.exports = Self => { try { const userId = ctx.req.accessToken.userId; - const worker = await Self.app.models.Worker.findOne({where: {userFk: userId}}, myOptions); + const worker = await Self.app.models.Worker.findOne({where: {id: userId}}, myOptions); const params = { isOk: false, diff --git a/modules/ticket/back/methods/ticket-tracking/changeState.js b/modules/ticket/back/methods/ticket-tracking/changeState.js index 4ae9ab40c..dbef8762e 100644 --- a/modules/ticket/back/methods/ticket-tracking/changeState.js +++ b/modules/ticket/back/methods/ticket-tracking/changeState.js @@ -53,7 +53,7 @@ module.exports = Self => { if (!params.workerFk) { const worker = await models.Worker.findOne({ - where: {userFk: userId} + where: {id: userId} }, myOptions); params.workerFk = worker.id; diff --git a/modules/ticket/back/methods/ticket-tracking/setDelivered.js b/modules/ticket/back/methods/ticket-tracking/setDelivered.js index bd6e32dcf..df482fd01 100644 --- a/modules/ticket/back/methods/ticket-tracking/setDelivered.js +++ b/modules/ticket/back/methods/ticket-tracking/setDelivered.js @@ -43,7 +43,7 @@ module.exports = Self => { fields: ['id', 'name', 'alertLevel', 'code'] }, myOptions); - const worker = await models.Worker.findOne({where: {userFk: userId}}, myOptions); + const worker = await models.Worker.findOne({where: {id: userId}}, myOptions); const promises = []; for (const id of ticketIds) { diff --git a/modules/ticket/back/models/ticket-request.js b/modules/ticket/back/models/ticket-request.js index 4125126dc..d133f85d5 100644 --- a/modules/ticket/back/models/ticket-request.js +++ b/modules/ticket/back/models/ticket-request.js @@ -10,7 +10,7 @@ module.exports = function(Self) { Self.observe('before save', async function(ctx) { if (ctx.isNewInstance) { const loopBackContext = LoopBackContext.getCurrentContext(); - const filter = {where: {userFk: loopBackContext.active.accessToken.userId}}; + const filter = {where: {id: loopBackContext.active.accessToken.userId}}; const models = Self.app.models; const worker = await models.Worker.findOne(filter); diff --git a/modules/zone/back/methods/zone/deleteZone.js b/modules/zone/back/methods/zone/deleteZone.js index bcfb91e3d..13d45428c 100644 --- a/modules/zone/back/methods/zone/deleteZone.js +++ b/modules/zone/back/methods/zone/deleteZone.js @@ -54,7 +54,7 @@ module.exports = Self => { const ticketList = await models.Ticket.find(filter, myOptions); const fixingState = await models.State.findOne({where: {code: 'FIXING'}}, myOptions); const worker = await models.Worker.findOne({ - where: {userFk: userId} + where: {id: userId} }, myOptions); await models.Ticket.rawSql('UPDATE ticket SET zoneFk = NULL WHERE zoneFk = ?', [id], myOptions); From 3b90d7e5e5927c063cd806fcbb29ea706d61fe5a Mon Sep 17 00:00:00 2001 From: alexm Date: Wed, 20 Sep 2023 15:10:28 +0200 Subject: [PATCH 115/427] refs #6067 refactor: vnUser and mailForward privileges. fix: emailVerification --- back/models/vn-user.js | 92 ++++++++++++------- back/models/vn-user.json | 12 ++- db/changes/234001/00-account_acl.sql | 12 +++ modules/account/back/models/mail-forward.js | 14 +++ modules/account/back/models/mail-forward.json | 16 +++- modules/account/front/routes.json | 3 +- 6 files changed, 107 insertions(+), 42 deletions(-) create mode 100644 db/changes/234001/00-account_acl.sql create mode 100644 modules/account/back/models/mail-forward.js diff --git a/back/models/vn-user.js b/back/models/vn-user.js index cf210b61b..642d3fdf3 100644 --- a/back/models/vn-user.js +++ b/back/models/vn-user.js @@ -1,6 +1,7 @@ const vnModel = require('vn-loopback/common/models/vn-model'); const LoopBackContext = require('loopback-context'); const {Email} = require('vn-print'); +const UserError = require('vn-loopback/util/user-error'); module.exports = function(Self) { vnModel(Self); @@ -178,45 +179,68 @@ module.exports = function(Self) { Self.sharedClass._methods.find(method => method.name == 'changePassword').ctor.settings.acls .filter(acl => acl.property != 'changePassword'); + Self.observe('before save', async ctx => { + const instance = ctx.currentInstance || ctx.instance; + console.log(ctx); + await Self.userSecurity(ctx, instance.id); + }); + + Self.userSecurity = async(ctx, userId) => { + const models = Self.app.models; + const accessToken = ctx.options.accessToken || LoopBackContext.getCurrentContext().active.accessToken; + console.log(accessToken, LoopBackContext.getCurrentContext().active.http.req); + const ctxToken = {req: {accessToken}}; + + const hasHigherPrivileges = await models.ACL.checkAccessAcl(ctxToken, 'VnUser', 'higherPrivileges'); + if (hasHigherPrivileges) return; + + const hasMediumPrivileges = await models.ACL.checkAccessAcl(ctxToken, 'VnUser', 'mediumPrivileges'); + const user = await models.VnUser.findById(userId, {fields: ['id', 'emailVerified']}); + if (!user.emailVerified && hasMediumPrivileges) return; + + if (userId != accessToken.userId) + throw new UserError(`You don't have enough privileges`); + }; + // FIXME: https://redmine.verdnatura.es/issues/5761 - // Self.afterRemote('prototype.patchAttributes', async(ctx, instance) => { - // if (!ctx.args || !ctx.args.data.email) return; + Self.afterRemote('prototype.patchAttributes', async(ctx, instance) => { + if (!ctx.args || !ctx.args.data.email) return; - // const loopBackContext = LoopBackContext.getCurrentContext(); - // const httpCtx = {req: loopBackContext.active}; - // const httpRequest = httpCtx.req.http.req; - // const headers = httpRequest.headers; - // const origin = headers.origin; - // const url = origin.split(':'); + const loopBackContext = LoopBackContext.getCurrentContext(); + const httpCtx = {req: loopBackContext.active}; + const httpRequest = httpCtx.req.http.req; + const headers = httpRequest.headers; + const origin = headers.origin; + const url = origin.split(':'); - // class Mailer { - // async send(verifyOptions, cb) { - // const params = { - // url: verifyOptions.verifyHref, - // recipient: verifyOptions.to, - // lang: ctx.req.getLocale() - // }; + class Mailer { + async send(verifyOptions, cb) { + const params = { + url: verifyOptions.verifyHref, + recipient: verifyOptions.to, + lang: ctx.req.getLocale() + }; - // const email = new Email('email-verify', params); - // email.send(); + const email = new Email('email-verify', params); + email.send(); - // cb(null, verifyOptions.to); - // } - // } + cb(null, verifyOptions.to); + } + } - // const options = { - // type: 'email', - // to: instance.email, - // from: {}, - // redirect: `${origin}/#!/account/${instance.id}/basic-data?emailConfirmed`, - // template: false, - // mailer: new Mailer, - // host: url[1].split('/')[2], - // port: url[2], - // protocol: url[0], - // user: Self - // }; + const options = { + type: 'email', + to: instance.email, + from: {}, + redirect: `${origin}/#!/account/${instance.id}/basic-data?emailConfirmed`, + template: false, + mailer: new Mailer, + host: url[1].split('/')[2], + port: url[2], + protocol: url[0], + user: Self + }; - // await instance.verify(options); - // }); + await instance.verify(options); + }); }; diff --git a/back/models/vn-user.json b/back/models/vn-user.json index 9131c9134..23df2241f 100644 --- a/back/models/vn-user.json +++ b/back/models/vn-user.json @@ -13,10 +13,6 @@ "type": "number", "id": true }, - "name": { - "type": "string", - "required": true - }, "username": { "type": "string", "mysql": { @@ -127,7 +123,13 @@ "principalType": "ROLE", "principalId": "$authenticated", "permission": "ALLOW" - } + }, + { + "principalType": "ROLE", + "principalId": "$authenticated", + "permission": "ALLOW", + "property": "patchAttributes" + } ], "scopes": { "preview": { diff --git a/db/changes/234001/00-account_acl.sql b/db/changes/234001/00-account_acl.sql new file mode 100644 index 000000000..23f47b99f --- /dev/null +++ b/db/changes/234001/00-account_acl.sql @@ -0,0 +1,12 @@ +DELETE FROM `salix`.`ACL` + WHERE + model = 'MailForward' + AND accessType = '*' + AND property = '*' + AND principalId = 'hr'; + + +INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) + VALUES + ('VnUser', 'higherPrivileges', '*', 'ALLOW', 'ROLE', 'itManagement'), + ('VnUser', 'mediumPrivileges', '*', 'ALLOW', 'ROLE', 'hr'); diff --git a/modules/account/back/models/mail-forward.js b/modules/account/back/models/mail-forward.js new file mode 100644 index 000000000..d55f5ddbc --- /dev/null +++ b/modules/account/back/models/mail-forward.js @@ -0,0 +1,14 @@ + +module.exports = Self => { + Self.observe('loaded', async ctx => { + if (!ctx.data.account) return; + await Self.app.models.VnUser.userSecurity(ctx, ctx.data.account); + }); + Self.observe('before save', async ctx => { + const instance = ctx.currentInstance || ctx.instance; + await Self.app.models.VnUser.userSecurity(ctx, instance.account); + }); + Self.observe('before delete', async ctx => { + await Self.app.models.VnUser.userSecurity(ctx, ctx.where.account); + }); +}; diff --git a/modules/account/back/models/mail-forward.json b/modules/account/back/models/mail-forward.json index edef1bf08..af4de3218 100644 --- a/modules/account/back/models/mail-forward.json +++ b/modules/account/back/models/mail-forward.json @@ -21,5 +21,19 @@ "model": "VnUser", "foreignKey": "account" } - } + }, + "acls": [ + { + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$authenticated", + "permission": "ALLOW" + }, + { + "accessType": "WRITE", + "principalType": "ROLE", + "principalId": "$authenticated", + "permission": "ALLOW" + } + ] } diff --git a/modules/account/front/routes.json b/modules/account/front/routes.json index fd33e7122..8472c3574 100644 --- a/modules/account/front/routes.json +++ b/modules/account/front/routes.json @@ -77,8 +77,7 @@ "url": "/basic-data?emailConfirmed", "state": "account.card.basicData", "component": "vn-user-basic-data", - "description": "Basic data", - "acl": ["itManagement"] + "description": "Basic data" }, { "url" : "/log", From 4e6808ec4aad00f121777076618bec717a669d32 Mon Sep 17 00:00:00 2001 From: jgallego Date: Thu, 21 Sep 2023 08:24:57 +0200 Subject: [PATCH 116/427] fixes #4059 muevo archivos a changes actual --- db/changes/{233801 => 234001}/00-aclClient.sql | 0 db/changes/{233801 => 234001}/01-aclAccount.sql | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename db/changes/{233801 => 234001}/00-aclClient.sql (100%) rename db/changes/{233801 => 234001}/01-aclAccount.sql (100%) diff --git a/db/changes/233801/00-aclClient.sql b/db/changes/234001/00-aclClient.sql similarity index 100% rename from db/changes/233801/00-aclClient.sql rename to db/changes/234001/00-aclClient.sql diff --git a/db/changes/233801/01-aclAccount.sql b/db/changes/234001/01-aclAccount.sql similarity index 100% rename from db/changes/233801/01-aclAccount.sql rename to db/changes/234001/01-aclAccount.sql From b615062c09c2683a1c775eeeaad2df0875884a56 Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 21 Sep 2023 08:40:17 +0200 Subject: [PATCH 117/427] refs #6225 add more info in changelog --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index acb5d7457..7fa6d453c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - (Ticket -> Servicios) Se pueden abonar servicios +- (Facturas -> Datos básicos) Muestra valores por defecto +- (Facturas -> Borrado) Notificación al borrar un asiento ya enlazado en Sage ### Changed - (Trabajadores -> Calendario) Icono de check arreglado cuando pulsas un tipo de dia From acd4f398c7d22da5c1f5857cc45ee2cc5fc3dd70 Mon Sep 17 00:00:00 2001 From: pablone Date: Thu, 21 Sep 2023 08:44:52 +0200 Subject: [PATCH 118/427] refs #6159 procBasedUpdate --- .../233801/00-updateAfterBusinnesInsert.sql | 66 ++++++++++++++----- 1 file changed, 51 insertions(+), 15 deletions(-) diff --git a/db/changes/233801/00-updateAfterBusinnesInsert.sql b/db/changes/233801/00-updateAfterBusinnesInsert.sql index 82c71507c..71356db80 100644 --- a/db/changes/233801/00-updateAfterBusinnesInsert.sql +++ b/db/changes/233801/00-updateAfterBusinnesInsert.sql @@ -1,21 +1,57 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`business_afterInsert` - AFTER INSERT ON `business` - FOR EACH ROW +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `account`.`account_enable`(vSelf INT) BEGIN - CALL worker_updateBusiness(NEW.workerFk); - UPDATE account.user - SET active = TRUE - WHERE id = NEW.workerFk; +/** + * Enables a worker's account and sets up email configurations. + */ + UPDATE user + SET active = TRUE + WHERE id = vSelf; - INSERT IGNORE INTO account.mailAliasAccount (mailAlias, account) - SELECT id, NEW.workerFk - FROM account.mailAlias - WHERE alias = 'general'; + INSERT IGNORE INTO account + SET id = vSelf; - INSERT IGNORE INTO account.mailForward (account, forwardTo) - SELECT NEW.workerFk, email - FROM account.user - WHERE id = NEW.workerFk; + INSERT IGNORE INTO mailAliasAccount (mailAlias, account) + SELECT id, vSelf + FROM mailAlias + WHERE alias = 'general'; + + INSERT IGNORE INTO mailForward (account, forwardTo) + SELECT vSelf, email + FROM user + WHERE id = vSelf; +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`worker_updateBusiness`(vSelf INT) +BEGIN +/** + * Activates an account and configures its email settings. + * + * @param vSelf account id. + */ + DECLARE vOldBusinessFk INT; + DECLARE vNewBusinessFk INT; + + SELECT businessFk INTO vOldBusinessFk FROM worker WHERE id = vSelf; + + SELECT id INTO vNewBusinessFk + FROM business + WHERE workerFk = vSelf + AND util.VN_CURDATE() BETWEEN started AND IFNULL(ended, util.VN_CURDATE()); + + UPDATE worker + SET businessFk = vNewBusinessFk + WHERE id = vSelf; + + IF NOT (vOldBusinessFk <=> vNewBusinessFk) THEN + IF vNewBusinessFk IS NULL THEN + CALL workerDisable(vSelf); + END IF; + IF vOldBusinessFk IS NULL THEN + CALL account.account_enable(vSelf); + END IF; + END IF; END$$ DELIMITER ; From ac4aea7d38f6d0492561606818af213c3ef1698f Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 21 Sep 2023 09:14:46 +0200 Subject: [PATCH 119/427] ref #5914 created transfer issued invoice --- db/dump/fixtures.sql | 17 +- loopback/locale/en.json | 10 +- loopback/locale/es.json | 341 ++++++++++++++++-- .../methods/invoiceOut/transferInvoice.js | 39 +- modules/ticket/back/methods/sale/clone.js | 1 - modules/ticket/back/methods/sale/refund.js | 55 +-- .../back/methods/sale/specs/refund.spec.js | 2 +- 7 files changed, 351 insertions(+), 114 deletions(-) diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 691f7e6df..bb46880bd 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -604,7 +604,7 @@ INSERT INTO `vn`.`invoiceOutSerial` (`code`, `description`, `isTaxed`, `taxAreaF INSERT INTO `vn`.`invoiceOut`(`id`, `serial`, `amount`, `issued`,`clientFk`, `created`, `companyFk`, `dued`, `booked`, `bankFk`, `hasPdf`) VALUES - (1, 'T', 1014.24, util.VN_CURDATE(), 1101, util.VN_CURDATE(), 442, util.VN_CURDATE(), util.VN_CURDATE(), 1, 0), + (1, 'T', 1026.24, util.VN_CURDATE(), 1101, util.VN_CURDATE(), 442, util.VN_CURDATE(), util.VN_CURDATE(), 1, 0), (2, 'T', 121.36, util.VN_CURDATE(), 1102, util.VN_CURDATE(), 442, util.VN_CURDATE(), util.VN_CURDATE(), 1, 0), (3, 'T', 8.88, util.VN_CURDATE(), 1103, util.VN_CURDATE(), 442, util.VN_CURDATE(), util.VN_CURDATE(), 1, 0), (4, 'T', 8.88, util.VN_CURDATE(), 1103, util.VN_CURDATE(), 442, util.VN_CURDATE(), util.VN_CURDATE(), 1, 0), @@ -2966,20 +2966,6 @@ INSERT INTO `hedera`.`imageConfig` (`id`, `maxSize`, `useXsendfile`, `url`) VALUES (1, 0, 0, 'marvel.com'); -<<<<<<< HEAD -INSERT INTO `vn`.`cplusCorrectingType` (`description`) - VALUES - ('Embalajes'), - ('Anulación'), - ('Impagado'), - ('Moroso'); - -INSERT INTO `vn`.`invoiceCorrectionType` (`description`) - VALUES - ('Error en el cálculo del IVA'), - ('Error en el detalle de las ventas'), - ('Error en los datos del cliente'); -======= INSERT INTO vn.XDiario (id, ASIEN, FECHA, SUBCTA, CONTRA, CONCEPTO, EURODEBE, EUROHABER, BASEEURO, SERIE, FACTURA, IVA, RECEQUIV, CLAVE, CAMBIO, DEBEME, HABERME, AUXILIAR, MONEDAUSO, TIPOOPE, NFACTICK, TERIDNIF, TERNIF, TERNOM, OPBIENES, L340, enlazado, FECHA_EX, LRECT349, empresa_id, LDIFADUAN, METAL, METALIMP, CLIENTE, METALEJE, FECHA_OP, FACTURAEX, TIPOCLAVE, TIPOEXENCI, TIPONOSUJE, TIPOFACT, TIPORECTIF, SERIE_RT, FACTU_RT, BASEIMP_RT, BASEIMP_RF, RECTIFICA, FECHA_RT, FECREGCON, enlazadoSage) VALUES (1, 1.0, util.VN_CURDATE(), '4300001104', NULL, 'n/fra T3333333', 8.88, NULL, NULL, NULL, '0', NULL, 0.00, NULL, NULL, NULL, NULL, NULL, '2', NULL, 1, 2, 'I.F.', 'Nombre Importador', 1, 0, 0, util.VN_CURDATE(), 0, 442, 0, 0, 0.00, NULL, NULL, util.VN_CURDATE(), NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, NULL, NULL, 1), @@ -2988,4 +2974,3 @@ INSERT INTO vn.XDiario (id, ASIEN, FECHA, SUBCTA, CONTRA, CONCEPTO, EURODEBE, EU (4, 2.0, util.VN_CURDATE(), '4300001104', NULL, 'n/fra T4444444', 8.88, NULL, NULL, NULL, '0', NULL, 0.00, NULL, NULL, NULL, NULL, NULL, '2', NULL, 1, 2, 'I.F.', 'Nombre Importador', 1, 0, 0, util.VN_CURDATE(), 0, 442, 0, 0, 0.00, NULL, NULL, util.VN_CURDATE(), NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, NULL, NULL, 0), (5, 2.0, util.VN_CURDATE(), '2000000000', '4300001104', 'n/fra T4444444 Tony Stark', NULL, 8.07, NULL, NULL, '0', NULL, 0.00, NULL, NULL, NULL, NULL, NULL, '2', NULL, 1, 2, 'I.F.', 'Nombre Importador', 1, 0, 0, util.VN_CURDATE(), 0, 442, 0, 0, 0.00, NULL, NULL, util.VN_CURDATE(), NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, NULL, NULL, 0), (6, 2.0, util.VN_CURDATE(), '4770000010', '4300001104', 'Inmovilizado pendiente : n/fra T4444444 Tony Stark', NULL, 0.81, 8.07, 'T', '4444444', 10.00, NULL, NULL, NULL, NULL, NULL, '', '2', '', 1, 1, '06089160W', 'IRON MAN', 1, 1, 0, util.VN_CURDATE(), 0, 442, 0, 0, 0.00, NULL, NULL, util.VN_CURDATE(), NULL, 1, 1, 1, 1, NULL, NULL, NULL, NULL, NULL, 0, NULL, NULL, 0); ->>>>>>> 72a8256aee7bff0be1dd68c8d4cfbe2edcf8ce60 diff --git a/loopback/locale/en.json b/loopback/locale/en.json index fb4e72bd6..3755c4a67 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -187,5 +187,11 @@ "This ticket is not editable.": "This ticket is not editable.", "The ticket doesn't exist.": "The ticket doesn't exist.", "The sales do not exists": "The sales do not exists", - "Ticket without Route": "Ticket without route" -} + "Ticket without Route": "Ticket without route", + "Select a different customer": "Select a different customer", + "Fill all the fields": "Fill all the fields", + "Error while generating PDF": "Error while generating PDF", + "Can't invoice to future": "Can't invoice to future", + "This ticket is already invoiced": "This ticket is already invoiced", + "Negative basis of tickets: 23": "Negative basis of tickets: 23" +} \ No newline at end of file diff --git a/loopback/locale/es.json b/loopback/locale/es.json index d436ec197..f5973dcb7 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -1,25 +1,322 @@ { - "Name cannot be blank": "Name cannot be blank", - "Swift / BIC cannot be empty": "Swift / BIC cannot be empty", - "Social name should be uppercase": "Social name should be uppercase", - "Street cannot be empty": "Street cannot be empty", - "Street should be uppercase": "Street should be uppercase", - "City cannot be empty": "City cannot be empty", - "Invalid email": "Invalid email", - "Phone cannot be blank": "Phone cannot be blank", + "Phone format is invalid": "El formato del teléfono no es correcto", + "You are not allowed to change the credit": "No tienes privilegios para modificar el crédito", + "Unable to mark the equivalence surcharge": "No se puede marcar el recargo de equivalencia", + "The default consignee can not be unchecked": "No se puede desmarcar el consignatario predeterminado", + "Unable to default a disabled consignee": "No se puede poner predeterminado un consignatario desactivado", + "Can't be blank": "No puede estar en blanco", + "Invalid TIN": "NIF/CIF invalido", + "TIN must be unique": "El NIF/CIF debe ser único", + "A client with that Web User name already exists": "Ya existe un cliente con ese Usuario Web", + "Is invalid": "Is invalid", + "Quantity cannot be zero": "La cantidad no puede ser cero", + "Enter an integer different to zero": "Introduce un entero distinto de cero", + "Package cannot be blank": "El embalaje no puede estar en blanco", + "The company name must be unique": "La razón social debe ser única", + "Invalid email": "Correo electrónico inválido", + "The IBAN does not have the correct format": "El IBAN no tiene el formato correcto", + "That payment method requires an IBAN": "El método de pago seleccionado requiere un IBAN", + "That payment method requires a BIC": "El método de pago seleccionado requiere un BIC", + "State cannot be blank": "El estado no puede estar en blanco", + "Worker cannot be blank": "El trabajador no puede estar en blanco", + "Cannot change the payment method if no salesperson": "No se puede cambiar la forma de pago si no hay comercial asignado", + "can't be blank": "El campo no puede estar vacío", + "Observation type must be unique": "El tipo de observación no puede repetirse", "The credit must be an integer greater than or equal to zero": "The credit must be an integer greater than or equal to zero", - "The grade must be an integer greater than or equal to zero": "The grade must be an integer greater than or equal to zero", - "Description should have maximum of 45 characters": "Description should have maximum of 45 characters", - "Amount cannot be zero": "Amount cannot be zero", - "Period cannot be blank": "Period cannot be blank", - "Sample type cannot be blank": "Sample type cannot be blank", - "Cannot be blank": "Cannot be blank", - "The social name cannot be empty": "The social name cannot be empty", - "Concept cannot be blank": "Concept cannot be blank", - "Enter an integer different to zero": "Enter an integer different to zero", - "Package cannot be blank": "Package cannot be blank", - "State cannot be blank": "State cannot be blank", - "Worker cannot be blank": "Worker cannot be blank", - "Description cannot be blank": "Description cannot be blank", - "Agency cannot be blank": "Agency cannot be blank" + "The grade must be similar to the last one": "El grade debe ser similar al último", + "Only manager can change the credit": "Solo el gerente puede cambiar el credito de este cliente", + "Name cannot be blank": "El nombre no puede estar en blanco", + "Phone cannot be blank": "El teléfono no puede estar en blanco", + "Period cannot be blank": "El periodo no puede estar en blanco", + "Choose a company": "Selecciona una empresa", + "Se debe rellenar el campo de texto": "Se debe rellenar el campo de texto", + "Description should have maximum of 45 characters": "La descripción debe tener maximo 45 caracteres", + "Cannot be blank": "El campo no puede estar en blanco", + "The grade must be an integer greater than or equal to zero": "El grade debe ser un entero mayor o igual a cero", + "Sample type cannot be blank": "El tipo de plantilla no puede quedar en blanco", + "Description cannot be blank": "Se debe rellenar el campo de texto", + "The new quantity should be smaller than the old one": "La nueva cantidad debe de ser menor que la anterior", + "The value should not be greater than 100%": "El valor no debe de ser mayor de 100%", + "The value should be a number": "El valor debe ser un numero", + "This order is not editable": "Esta orden no se puede modificar", + "You can't create an order for a frozen client": "No puedes crear una orden para un cliente congelado", + "You can't create an order for a client that has a debt": "No puedes crear una orden para un cliente con deuda", + "is not a valid date": "No es una fecha valida", + "Barcode must be unique": "El código de barras debe ser único", + "The warehouse can't be repeated": "El almacén no puede repetirse", + "The tag or priority can't be repeated for an item": "El tag o prioridad no puede repetirse para un item", + "The observation type can't be repeated": "El tipo de observación no puede repetirse", + "A claim with that sale already exists": "Ya existe una reclamación para esta línea", + "You don't have enough privileges to change that field": "No tienes permisos para cambiar ese campo", + "Warehouse cannot be blank": "El almacén no puede quedar en blanco", + "Agency cannot be blank": "La agencia no puede quedar en blanco", + "Not enough privileges to edit a client with verified data": "No tienes permisos para hacer cambios en un cliente con datos comprobados", + "This address doesn't exist": "Este consignatario no existe", + "You must delete the claim id %d first": "Antes debes borrar la reclamación %d", + "You don't have enough privileges": "No tienes suficientes permisos", + "Cannot check Equalization Tax in this NIF/CIF": "No se puede marcar RE en este NIF/CIF", + "You can't make changes on the basic data of an confirmed order or with rows": "No puedes cambiar los datos basicos de una orden con artículos", + "INVALID_USER_NAME": "El nombre de usuario solo debe contener letras minúsculas o, a partir del segundo carácter, números o subguiones, no esta permitido el uso de la letra ñ", + "You can't create a ticket for a frozen client": "No puedes crear un ticket para un cliente congelado", + "You can't create a ticket for a inactive client": "No puedes crear un ticket para un cliente inactivo", + "Tag value cannot be blank": "El valor del tag no puede quedar en blanco", + "ORDER_EMPTY": "Cesta vacía", + "You don't have enough privileges to do that": "No tienes permisos para cambiar esto", + "NO SE PUEDE DESACTIVAR EL CONSIGNAT": "NO SE PUEDE DESACTIVAR EL CONSIGNAT", + "Error. El NIF/CIF está repetido": "Error. El NIF/CIF está repetido", + "Street cannot be empty": "Dirección no puede estar en blanco", + "City cannot be empty": "Cuidad no puede estar en blanco", + "Code cannot be blank": "Código no puede estar en blanco", + "You cannot remove this department": "No puedes eliminar este departamento", + "The extension must be unique": "La extensión debe ser unica", + "The secret can't be blank": "La contraseña no puede estar en blanco", + "We weren't able to send this SMS": "No hemos podido enviar el SMS", + "This client can't be invoiced": "Este cliente no puede ser facturado", + "This ticket can't be invoiced": "Este ticket no puede ser facturado", + "You cannot add or modify services to an invoiced ticket": "No puedes añadir o modificar servicios a un ticket facturado", + "This ticket can not be modified": "Este ticket no puede ser modificado", + "The introduced hour already exists": "Esta hora ya ha sido introducida", + "INFINITE_LOOP": "Existe una dependencia entre dos Jefes", + "The sales of the receiver ticket can't be modified": "Las lineas del ticket al que envias no pueden ser modificadas", + "NO_AGENCY_AVAILABLE": "No hay una zona de reparto disponible con estos parámetros", + "ERROR_PAST_SHIPMENT": "No puedes seleccionar una fecha de envío en pasado", + "The current ticket can't be modified": "El ticket actual no puede ser modificado", + "The current claim can't be modified": "La reclamación actual no puede ser modificada", + "The sales of this ticket can't be modified": "Las lineas de este ticket no pueden ser modificadas", + "The sales do not exists": "La(s) línea(s) seleccionada(s) no existe(n)", + "Please select at least one sale": "Por favor selecciona al menos una linea", + "All sales must belong to the same ticket": "Todas las lineas deben pertenecer al mismo ticket", + "NO_ZONE_FOR_THIS_PARAMETERS": "Para este día no hay ninguna zona configurada", + "This item doesn't exists": "El artículo no existe", + "NOT_ZONE_WITH_THIS_PARAMETERS": "Para este día no hay ninguna zona configurada", + "Extension format is invalid": "El formato de la extensión es inválido", + "Invalid parameters to create a new ticket": "Parámetros inválidos para crear un nuevo ticket", + "This item is not available": "Este artículo no está disponible", + "This postcode already exists": "Este código postal ya existe", + "Concept cannot be blank": "El concepto no puede quedar en blanco", + "File doesn't exists": "El archivo no existe", + "You don't have privileges to change the zone": "No tienes permisos para cambiar la zona o para esos parámetros hay más de una opción de envío, hable con las agencias", + "This ticket is already on weekly tickets": "Este ticket ya está en tickets programados", + "Ticket id cannot be blank": "El id de ticket no puede quedar en blanco", + "Weekday cannot be blank": "El día de la semana no puede quedar en blanco", + "You can't delete a confirmed order": "No puedes borrar un pedido confirmado", + "The social name has an invalid format": "El nombre fiscal tiene un formato incorrecto", + "Invalid quantity": "Cantidad invalida", + "This postal code is not valid": "This postal code is not valid", + "is invalid": "is invalid", + "The postcode doesn't exist. Please enter a correct one": "El código postal no existe. Por favor, introduce uno correcto", + "The department name can't be repeated": "El nombre del departamento no puede repetirse", + "This phone already exists": "Este teléfono ya existe", + "You cannot move a parent to its own sons": "No puedes mover un elemento padre a uno de sus hijos", + "You can't create a claim for a removed ticket": "No puedes crear una reclamación para un ticket eliminado", + "You cannot delete a ticket that part of it is being prepared": "No puedes eliminar un ticket en el que una parte que está siendo preparada", + "You must delete all the buy requests first": "Debes eliminar todas las peticiones de compra primero", + "You should specify a date": "Debes especificar una fecha", + "You should specify at least a start or end date": "Debes especificar al menos una fecha de inicio o de fín", + "Start date should be lower than end date": "La fecha de inicio debe ser menor que la fecha de fín", + "You should mark at least one week day": "Debes marcar al menos un día de la semana", + "Swift / BIC can't be empty": "Swift / BIC no puede estar vacío", + "Customs agent is required for a non UEE member": "El agente de aduanas es requerido para los clientes extracomunitarios", + "Incoterms is required for a non UEE member": "El incoterms es requerido para los clientes extracomunitarios", + "Deleted sales from ticket": "He eliminado las siguientes lineas del ticket [{{ticketId}}]({{{ticketUrl}}}): {{{deletions}}}", + "Added sale to ticket": "He añadido la siguiente linea al ticket [{{ticketId}}]({{{ticketUrl}}}): {{{addition}}}", + "Changed sale discount": "He cambiado el descuento de las siguientes lineas al ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}", + "Created claim": "He creado la reclamación [{{claimId}}]({{{claimUrl}}}) de las siguientes lineas del ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}", + "Changed sale price": "He cambiado el precio de [{{itemId}} {{concept}}]({{{itemUrl}}}) ({{quantity}}) de {{oldPrice}}€ ➔ *{{newPrice}}€* del ticket [{{ticketId}}]({{{ticketUrl}}})", + "Changed sale quantity": "He cambiado la cantidad de [{{itemId}} {{concept}}]({{{itemUrl}}}) de {{oldQuantity}} ➔ *{{newQuantity}}* del ticket [{{ticketId}}]({{{ticketUrl}}})", + "State": "Estado", + "regular": "normal", + "reserved": "reservado", + "Changed sale reserved state": "He cambiado el estado reservado de las siguientes lineas al ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}", + "Bought units from buy request": "Se ha comprado {{quantity}} unidades de [{{itemId}} {{concept}}]({{{urlItem}}}) para el ticket id [{{ticketId}}]({{{url}}})", + "Deny buy request": "Se ha rechazado la petición de compra para el ticket id [{{ticketId}}]({{{url}}}). Motivo: {{observation}}", + "MESSAGE_INSURANCE_CHANGE": "He cambiado el crédito asegurado del cliente [{{clientName}} ({{clientId}})]({{{url}}}) a *{{credit}} €*", + "Changed client paymethod": "He cambiado la forma de pago del cliente [{{clientName}} ({{clientId}})]({{{url}}})", + "Sent units from ticket": "Envio *{{quantity}}* unidades de [{{concept}} ({{itemId}})]({{{itemUrl}}}) a *\"{{nickname}}\"* provenientes del ticket id [{{ticketId}}]({{{ticketUrl}}})", + "Change quantity": "{{concept}} cambia de {{oldQuantity}} a {{newQuantity}}", + "Claim will be picked": "Se recogerá el género de la reclamación [({{claimId}})]({{{claimUrl}}}) del cliente *{{clientName}}*", + "Claim state has changed to incomplete": "Se ha cambiado el estado de la reclamación [({{claimId}})]({{{claimUrl}}}) del cliente *{{clientName}}* a *incompleta*", + "Claim state has changed to canceled": "Se ha cambiado el estado de la reclamación [({{claimId}})]({{{claimUrl}}}) del cliente *{{clientName}}* a *anulado*", + "Client checked as validated despite of duplication": "Cliente comprobado a pesar de que existe el cliente id {{clientId}}", + "ORDER_ROW_UNAVAILABLE": "No hay disponibilidad de este producto", + "Distance must be lesser than 1000": "La distancia debe ser inferior a 1000", + "This ticket is deleted": "Este ticket está eliminado", + "Unable to clone this travel": "No ha sido posible clonar este travel", + "This thermograph id already exists": "La id del termógrafo ya existe", + "Choose a date range or days forward": "Selecciona un rango de fechas o días en adelante", + "ORDER_ALREADY_CONFIRMED": "ORDER_ALREADY_CONFIRMED", + "Invalid password": "Invalid password", + "Password does not meet requirements": "La contraseña no cumple los requisitos", + "Role already assigned": "Role already assigned", + "Invalid role name": "Invalid role name", + "Role name must be written in camelCase": "Role name must be written in camelCase", + "Email already exists": "Email already exists", + "User already exists": "User already exists", + "Absence change notification on the labour calendar": "Notificacion de cambio de ausencia en el calendario laboral", + "Record of hours week": "Registro de horas semana {{week}} año {{year}} ", + "Created absence": "El empleado {{author}} ha añadido una ausencia de tipo '{{absenceType}}' a {{employee}} para el día {{dated}}.", + "Deleted absence": "El empleado {{author}} ha eliminado una ausencia de tipo '{{absenceType}}' a {{employee}} del día {{dated}}.", + "I have deleted the ticket id": "He eliminado el ticket id [{{id}}]({{{url}}})", + "I have restored the ticket id": "He restaurado el ticket id [{{id}}]({{{url}}})", + "You can only restore a ticket within the first hour after deletion": "Únicamente puedes restaurar el ticket dentro de la primera hora después de su eliminación", + "Changed this data from the ticket": "He cambiado estos datos del ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}", + "agencyModeFk": "Agencia", + "clientFk": "Cliente", + "zoneFk": "Zona", + "warehouseFk": "Almacén", + "shipped": "F. envío", + "landed": "F. entrega", + "addressFk": "Consignatario", + "companyFk": "Empresa", + "The social name cannot be empty": "La razón social no puede quedar en blanco", + "The nif cannot be empty": "El NIF no puede quedar en blanco", + "You need to fill sage information before you check verified data": "Debes rellenar la información de sage antes de marcar datos comprobados", + "ASSIGN_ZONE_FIRST": "Asigna una zona primero", + "Amount cannot be zero": "El importe no puede ser cero", + "Company has to be official": "Empresa inválida", + "You can not select this payment method without a registered bankery account": "No se puede utilizar este método de pago si no has registrado una cuenta bancaria", + "Action not allowed on the test environment": "Esta acción no está permitida en el entorno de pruebas", + "The selected ticket is not suitable for this route": "El ticket seleccionado no es apto para esta ruta", + "New ticket request has been created with price": "Se ha creado una nueva petición de compra '{{description}}' para el día *{{shipped}}*, con una cantidad de *{{quantity}}* y un precio de *{{price}} €*", + "New ticket request has been created": "Se ha creado una nueva petición de compra '{{description}}' para el día *{{shipped}}*, con una cantidad de *{{quantity}}*", + "Swift / BIC cannot be empty": "Swift / BIC no puede estar vacío", + "This BIC already exist.": "Este BIC ya existe.", + "That item doesn't exists": "Ese artículo no existe", + "There's a new urgent ticket:": "Hay un nuevo ticket urgente:", + "Invalid account": "Cuenta inválida", + "Compensation account is empty": "La cuenta para compensar está vacia", + "This genus already exist": "Este genus ya existe", + "This specie already exist": "Esta especie ya existe", + "Client assignment has changed": "He cambiado el comercial ~*\"<{{previousWorkerName}}>\"*~ por *\"<{{currentWorkerName}}>\"* del cliente [{{clientName}} ({{clientId}})]({{{url}}})", + "None": "Ninguno", + "The contract was not active during the selected date": "El contrato no estaba activo durante la fecha seleccionada", + "Cannot add more than one '1/2 day vacation'": "No puedes añadir más de un 'Vacaciones 1/2 dia'", + "This document already exists on this ticket": "Este documento ya existe en el ticket", + "Some of the selected tickets are not billable": "Algunos de los tickets seleccionados no son facturables", + "You can't invoice tickets from multiple clients": "No puedes facturar tickets de multiples clientes", + "nickname": "nickname", + "INACTIVE_PROVIDER": "Proveedor inactivo", + "This client is not invoiceable": "Este cliente no es facturable", + "serial non editable": "Esta serie no permite asignar la referencia", + "Max shipped required": "La fecha límite es requerida", + "Can't invoice to future": "No se puede facturar a futuro", + "Can't invoice to past": "No se puede facturar a pasado", + "This ticket is already invoiced": "Este ticket ya está facturado", + "A ticket with an amount of zero can't be invoiced": "No se puede facturar un ticket con importe cero", + "A ticket with a negative base can't be invoiced": "No se puede facturar un ticket con una base negativa", + "Global invoicing failed": "[Facturación global] No se han podido facturar algunos clientes", + "Wasn't able to invoice the following clients": "No se han podido facturar los siguientes clientes", + "Can't verify data unless the client has a business type": "No se puede verificar datos de un cliente que no tiene tipo de negocio", + "You don't have enough privileges to set this credit amount": "No tienes suficientes privilegios para establecer esta cantidad de crédito", + "You can't change the credit set to zero from a financialBoss": "No puedes cambiar el cŕedito establecido a cero por un jefe de finanzas", + "Amounts do not match": "Las cantidades no coinciden", + "The PDF document does not exist": "El documento PDF no existe. Prueba a regenerarlo desde la opción 'Regenerar PDF factura'", + "The type of business must be filled in basic data": "El tipo de negocio debe estar rellenado en datos básicos", + "You can't create a claim from a ticket delivered more than seven days ago": "No puedes crear una reclamación de un ticket entregado hace más de siete días", + "The worker has hours recorded that day": "El trabajador tiene horas fichadas ese día", + "The worker has a marked absence that day": "El trabajador tiene marcada una ausencia ese día", + "You can not modify is pay method checked": "No se puede modificar el campo método de pago validado", + "Can't transfer claimed sales": "No puedes transferir lineas reclamadas", + "You don't have privileges to create refund": "No tienes permisos para crear un abono", + "The item is required": "El artículo es requerido", + "The agency is already assigned to another autonomous": "La agencia ya está asignada a otro autónomo", + "date in the future": "Fecha en el futuro", + "reference duplicated": "Referencia duplicada", + "This ticket is already a refund": "Este ticket ya es un abono", + "isWithoutNegatives": "isWithoutNegatives", + "routeFk": "routeFk", + "Can't change the password of another worker": "No se puede cambiar la contraseña de otro trabajador", + "No hay un contrato en vigor": "No hay un contrato en vigor", + "No se permite fichar a futuro": "No se permite fichar a futuro", + "No está permitido trabajar": "No está permitido trabajar", + "Fichadas impares": "Fichadas impares", + "Descanso diario 12h.": "Descanso diario 12h.", + "Descanso semanal 36h. / 72h.": "Descanso semanal 36h. / 72h.", + "Dirección incorrecta": "Dirección incorrecta", + "Modifiable user details only by an administrator": "Detalles de usuario modificables solo por un administrador", + "Modifiable password only via recovery or by an administrator": "Contraseña modificable solo a través de la recuperación o por un administrador", + "Not enough privileges to edit a client": "No tienes suficientes privilegios para editar un cliente", + "This route does not exists": "Esta ruta no existe", + "Claim pickup order sent": "Reclamación Orden de recogida enviada [{{claimId}}]({{{claimUrl}}}) al cliente *{{clientName}}*", + "You don't have grant privilege": "No tienes privilegios para dar privilegios", + "You don't own the role and you can't assign it to another user": "No eres el propietario del rol y no puedes asignarlo a otro usuario", + "Ticket merged": "Ticket [{{originId}}]({{{originFullPath}}}) ({{{originDated}}}) fusionado con [{{destinationId}}]({{{destinationFullPath}}}) ({{{destinationDated}}})", + "Already has this status": "Ya tiene este estado", + "There aren't records for this week": "No existen registros para esta semana", + "Empty data source": "Origen de datos vacio", + "App locked": "Aplicación bloqueada por el usuario {{userId}}", + "Email verify": "Correo de verificación", + "Landing cannot be lesser than shipment": "Landing cannot be lesser than shipment", + "Receipt's bank was not found": "No se encontró el banco del recibo", + "This receipt was not compensated": "Este recibo no ha sido compensado", + "Client's email was not found": "No se encontró el email del cliente", + "Negative basis": "Base negativa", + "This worker code already exists": "Este codigo de trabajador ya existe", + "This personal mail already exists": "Este correo personal ya existe", + "This worker already exists": "Este trabajador ya existe", + "App name does not exist": "El nombre de aplicación no es válido", + "Try again": "Vuelve a intentarlo", + "Aplicación bloqueada por el usuario 9": "Aplicación bloqueada por el usuario 9", + "Failed to upload delivery note": "Error al subir albarán {{id}}", + "The DOCUWARE PDF document does not exists": "El documento PDF Docuware no existe", + "It is not possible to modify tracked sales": "No es posible modificar líneas de pedido que se hayan empezado a preparar", + "It is not possible to modify sales that their articles are from Floramondo": "No es posible modificar líneas de pedido cuyos artículos sean de Floramondo", + "It is not possible to modify cloned sales": "No es posible modificar líneas de pedido clonadas", + "A supplier with the same name already exists. Change the country.": "Un proveedor con el mismo nombre ya existe. Cambie el país.", + "There is no assigned email for this client": "No hay correo asignado para este cliente", + "Exists an invoice with a future date": "Existe una factura con fecha posterior", + "Invoice date can't be less than max date": "La fecha de factura no puede ser inferior a la fecha límite", + "Warehouse inventory not set": "El almacén inventario no está establecido", + "This locker has already been assigned": "Esta taquilla ya ha sido asignada", + "Tickets with associated refunds": "No se pueden borrar tickets con abonos asociados. Este ticket está asociado al abono Nº %d", + "Not exist this branch": "La rama no existe", + "This ticket cannot be signed because it has not been boxed": "Este ticket no puede firmarse porque no ha sido encajado", + "Collection does not exist": "La colección no existe", + "Cannot obtain exclusive lock": "No se puede obtener un bloqueo exclusivo", + "Insert a date range": "Inserte un rango de fechas", + "Added observation": "{{user}} añadió esta observacion: {{text}}", + "Comment added to client": "Observación añadida al cliente {{clientFk}}", + "Invalid auth code": "Código de verificación incorrecto", + "Invalid or expired verification code": "Código de verificación incorrecto o expirado", + "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", + "Pass expired": "La contraseña ha caducado, cambiela desde Salix", + "Invalid NIF for VIES": "Invalid NIF for VIES", + "Ticket does not exist": "Este ticket no existe", + "Ticket is already signed": "Este ticket ya ha sido firmado", + "Authentication failed": "Autenticación fallida", + "You can't use the same password": "No puedes usar la misma contraseña", + "You can only add negative amounts in refund tickets": "Solo se puede añadir cantidades negativas en tickets abono", + "Fecha fuera de rango": "Fecha fuera de rango", + "Error while generating PDF": "Error al generar PDF", + "Error when sending mail to client": "Error al enviar el correo al cliente", + "Mail not sent": "Se ha producido un fallo al enviar la factura al cliente [{{clientId}}]({{{clientUrl}}}), por favor revisa la dirección de correo electrónico", + "The renew period has not been exceeded": "El periodo de renovación no ha sido superado", + "Valid priorities": "Prioridades válidas: %d", + "Negative basis of tickets": "Base negativa para los tickets: {{ticketsIds}}", + "You cannot assign an alias that you are not assigned to": "No puede asignar un alias que no tenga asignado", + "This ticket cannot be left empty.": "Este ticket no se puede dejar vacío. %s", + "The company has not informed the supplier account for bank transfers": "La empresa no tiene informado la cuenta de proveedor para transferencias bancarias", + "You cannot assign/remove an alias that you are not assigned to": "No puede asignar/eliminar un alias que no tenga asignado", + "This invoice has a linked vehicle.": "Esta factura tiene un vehiculo vinculado", + "You don't have enough privileges.": "No tienes suficientes permisos.", + "This ticket is locked.": "Este ticket está bloqueado.", + "This ticket is not editable.": "Este ticket no es editable.", + "The ticket doesn't exist.": "No existe el ticket.", + "Social name should be uppercase": "La razón social debe ir en mayúscula", + "Street should be uppercase": "La dirección fiscal debe ir en mayúscula", + "Ticket without Route": "Ticket sin ruta", + "Select a different customer": "Seleccione un cliente distinto", + "Fill all the fields": "Rellene todos los campos" } \ No newline at end of file diff --git a/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js b/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js index 0b123dd3d..65b671716 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js +++ b/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js @@ -1,3 +1,5 @@ +const UserError = require('vn-loopback/util/user-error'); + module.exports = Self => { Self.remoteMethodCtx('transferInvoice', { description: 'Transfer an issued invoice to another client', @@ -6,7 +8,8 @@ module.exports = Self => { { arg: 'id', type: 'number', - required: true + required: true, + description: 'Issued invoice id' }, { arg: 'ref', @@ -16,22 +19,18 @@ module.exports = Self => { { arg: 'newClientFk', type: 'number', - required: true }, { arg: 'cplusRectificationId', type: 'number', - required: true }, { arg: 'cplusInvoiceType477Id', type: 'number', - required: true }, { arg: 'invoiceCorrectionTypeId', type: 'number', - required: true }, ], returns: { @@ -44,26 +43,32 @@ module.exports = Self => { } }); - Self.transferInvoice = async(ctx, id, ref, newClientFk, cplusRectificationId, cplusInvoiceType477Id, invoiceCorrectionTypeId, options) => { + Self.transferInvoice = async(ctx, options) => { const models = Self.app.models; const myOptions = {userId: ctx.req.accessToken.userId}; - + const args = ctx.args; let tx; if (typeof options == 'object') Object.assign(myOptions, options); + const {clientFk} = await models.InvoiceOut.findById(args.id); + + if (clientFk == args.newClientFk) + throw new UserError(`Select a different customer`); + + if (!args.newClientFk || !args.cplusRectificationId || !args.cplusInvoiceType477Id || !args.invoiceCorrectionTypeId) + throw new UserError(`Fill all the fields`); + if (!myOptions.transaction) { tx = await Self.beginTransaction({}); myOptions.transaction = tx; } try { - // Refund tickets and group - const filterRef = {where: {refFk: ref}}; + const filterRef = {where: {refFk: args.ref}}; const tickets = await models.Ticket.find(filterRef, myOptions); const ticketsIds = tickets.map(ticket => ticket.id); await models.Ticket.refund(ctx, ticketsIds, null, myOptions); - // Clone tickets const filterTicket = {where: {ticketFk: {inq: ticketsIds}}}; const services = await models.TicketService.find(filterTicket, myOptions); @@ -75,28 +80,24 @@ module.exports = Self => { const clonedTickets = await models.Sale.clone(salesIds, servicesIds, null, false, false, myOptions); const clonedTicketIds = []; - // Update client for (const clonedTicket of clonedTickets) { - await clonedTicket.updateAttribute('clientFk', newClientFk, myOptions); + await clonedTicket.updateAttribute('clientFk', args.newClientFk, myOptions); clonedTicketIds.push(clonedTicket.id); } - // Quick invoice const invoiceIds = await models.Ticket.invoiceTickets(ctx, clonedTicketIds, myOptions); const [invoiceId] = invoiceIds; - // Insert InvoiceCorrection await models.InvoiceCorrection.create({ correctingFk: invoiceId, - correctedFk: id, - cplusRectificationTypeFk: cplusRectificationId, - cplusInvoiceType477Fk: cplusInvoiceType477Id, - invoiceCorrectionType: invoiceCorrectionTypeId + correctedFk: args.id, + cplusRectificationTypeFk: args.cplusRectificationId, + cplusInvoiceType477Fk: args.cplusInvoiceType477Id, + invoiceCorrectionType: args.invoiceCorrectionTypeId }, myOptions); if (tx) await tx.commit(); - // Crear PDF await models.InvoiceOut.makePdfAndNotify(ctx, invoiceId, null); return invoiceId; diff --git a/modules/ticket/back/methods/sale/clone.js b/modules/ticket/back/methods/sale/clone.js index 9a3b5fedc..d899b3c44 100644 --- a/modules/ticket/back/methods/sale/clone.js +++ b/modules/ticket/back/methods/sale/clone.js @@ -28,7 +28,6 @@ module.exports = Self => { const refundTickets = []; const mappedTickets = new Map(); const now = Date.vnNew(); - const [firstTicketId] = ticketsIds; if (group) { await createTicketRefund( diff --git a/modules/ticket/back/methods/sale/refund.js b/modules/ticket/back/methods/sale/refund.js index 3f7e1cd21..ba7d71253 100644 --- a/modules/ticket/back/methods/sale/refund.js +++ b/modules/ticket/back/methods/sale/refund.js @@ -42,35 +42,10 @@ module.exports = Self => { } try { - const refundAgencyMode = await models.AgencyMode.findOne({ - include: { - relation: 'zones', - scope: { - limit: 1, - field: ['id', 'name'] - } - }, - where: {code: 'refund'} - }, myOptions); - - const refoundZoneId = refundAgencyMode.zones()[0].id; - - const salesFilter = { - where: {id: {inq: salesIds}}, - include: { - relation: 'components', - scope: { - fields: ['saleFk', 'componentFk', 'value'] - } - } - }; - // const sales = await models.Sale.find(salesFilter, myOptions); - const refundTicket = await models.Sale.clone( + const refundsTicket = await models.Sale.clone( salesIds, servicesIds, withWarehouse, - // refundAgencyMode, - // refoundZoneId, true, true, myOptions @@ -78,36 +53,10 @@ module.exports = Self => { if (tx && !options) await tx.commit(); - return refundTicket; + return refundsTicket[0]; } catch (e) { if (tx) await tx.rollback(); throw e; } }; - - /* async function createTicketRefund(ticketId, now, refundAgencyMode, refoundZoneId, withWarehouse, myOptions) { - const models = Self.app.models; - - const filter = {include: {relation: 'address'}}; - const ticket = await models.Ticket.findById(ticketId, filter, myOptions); - - const refundTicket = await models.Ticket.create({ - clientFk: ticket.clientFk, - shipped: now, - addressFk: ticket.address().id, - agencyModeFk: refundAgencyMode.id, - nickname: ticket.address().nickname, - warehouseFk: withWarehouse ? ticket.warehouseFk : null, - companyFk: ticket.companyFk, - landed: now, - zoneFk: refoundZoneId - }, myOptions); - - await models.TicketRefund.create({ - refundTicketFk: refundTicket.id, - originalTicketFk: ticket.id, - }, myOptions); - - return refundTicket; - } */ }; diff --git a/modules/ticket/back/methods/sale/specs/refund.spec.js b/modules/ticket/back/methods/sale/specs/refund.spec.js index 727ce2fac..b81f7f84d 100644 --- a/modules/ticket/back/methods/sale/specs/refund.spec.js +++ b/modules/ticket/back/methods/sale/specs/refund.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); -fdescribe('Sale refund()', () => { +describe('Sale refund()', () => { const userId = 5; const ctx = {req: {accessToken: userId}}; const activeCtx = { From 4761b0f7840c78d0ce8fbef765feec97fc834d9a Mon Sep 17 00:00:00 2001 From: jgallego Date: Thu, 21 Sep 2023 10:41:20 +0200 Subject: [PATCH 120/427] =?UTF-8?q?fixes=20#4059=20a=C3=B1ado=20comillas?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- db/changes/234001/00-aclClient.sql | 16 ++++++++-------- db/changes/234001/01-aclAccount.sql | 10 +++++----- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/db/changes/234001/00-aclClient.sql b/db/changes/234001/00-aclClient.sql index 8e85c027b..109b3a4fb 100644 --- a/db/changes/234001/00-aclClient.sql +++ b/db/changes/234001/00-aclClient.sql @@ -1,19 +1,19 @@ -- No encuentro este back -DELETE FROM salix.ACL WHERE property = 'activeWorkersWithRole'; -DELETE FROM salix.ACL WHERE model = 'Client' AND property = '*'; +DELETE FROM `salix`.`ACL` WHERE property = 'activeWorkersWithRole'; +DELETE FROM `salix`.`ACL` WHERE model = 'Client' AND property = '*'; -INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) +INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId) VALUES ('Client','findOne','READ','ALLOW','ROLE','employee'); -INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) +INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId) VALUES ('Client','findById','READ','ALLOW','ROLE','employee'); -INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) +INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId) VALUES ('Client','find','READ','ALLOW','ROLE','employee'); -INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) +INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId) VALUES ('Client','exists','READ','ALLOW','ROLE','employee'); -INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) +INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId) VALUES ('Client','__get__addresses','READ','ALLOW','ROLE','employee'); -DELETE FROM salix.ACL WHERE model = 'Client' AND property = '*' AND accessType IN ( +DELETE FROM `salix`.`ACL` WHERE model = 'Client' AND property = '*' AND accessType IN ( 'campaignMetricsEmail', 'campaignMetricsPdf', 'clientDebtStatementEmail', diff --git a/db/changes/234001/01-aclAccount.sql b/db/changes/234001/01-aclAccount.sql index 0f2d6d48c..d749b52ab 100644 --- a/db/changes/234001/01-aclAccount.sql +++ b/db/changes/234001/01-aclAccount.sql @@ -1,10 +1,10 @@ -DELETE FROM salix.ACL WHERE model = 'Account' AND property = '*' AND principalId = 'employee'; +DELETE FROM `salix`.`ACL` WHERE model = 'Account' AND property = '*' AND principalId = 'employee'; -INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) +INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId) VALUES ('Account','findOne','READ','ALLOW','ROLE','employee'); -INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) +INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId) VALUES ('Account','findById','READ','ALLOW','ROLE','employee'); -INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) +INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId) VALUES ('Account','find','READ','ALLOW','ROLE','employee'); -INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) +INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId) VALUES ('Account','exists','READ','ALLOW','ROLE','employee'); From 1f1dfae7e32bc6217b2b18f53cfd6cb7e79f47d4 Mon Sep 17 00:00:00 2001 From: carlossa Date: Thu, 21 Sep 2023 12:50:07 +0200 Subject: [PATCH 121/427] refs #5843 changes models --- back/models/vn-user.json | 2 +- db/changes/234001/00-dropUserFk.sql | 3 +- db/changes/234001/01-deliveryAssistantACL.sql | 2 +- db/changes/234001/01-workerCreate.sql | 20 +++++ db/dump/structure.sql | 82 ++----------------- .../back/models/client-observation.json | 2 +- modules/route/back/models/roadmap.json | 2 +- modules/shelving/back/models/shelving.json | 2 +- modules/worker/back/methods/worker/filter.js | 2 - .../back/models/worker-time-control.json | 2 +- modules/worker/front/search-panel/index.html | 4 +- 11 files changed, 35 insertions(+), 88 deletions(-) create mode 100644 db/changes/234001/01-workerCreate.sql diff --git a/back/models/vn-user.json b/back/models/vn-user.json index 9131c9134..9e3f8df89 100644 --- a/back/models/vn-user.json +++ b/back/models/vn-user.json @@ -84,7 +84,7 @@ "worker": { "type": "hasOne", "model": "Worker", - "foreignKey": "userFk" + "foreignKey": "id" }, "userConfig": { "type": "hasOne", diff --git a/db/changes/234001/00-dropUserFk.sql b/db/changes/234001/00-dropUserFk.sql index ad4db3110..d6ce328a8 100644 --- a/db/changes/234001/00-dropUserFk.sql +++ b/db/changes/234001/00-dropUserFk.sql @@ -1,5 +1,4 @@ -ALTER TABLE `vn`.`workerDocument` DROP FOREIGN KEY `workerDocument_ibfk_1`; - ALTER TABLE `vn`.`worker` DROP KEY `user_id_UNIQUE`; ALTER TABLE `vn`.`worker` DROP COLUMN `userFk`; + diff --git a/db/changes/234001/01-deliveryAssistantACL.sql b/db/changes/234001/01-deliveryAssistantACL.sql index 44459c432..504760d6f 100644 --- a/db/changes/234001/01-deliveryAssistantACL.sql +++ b/db/changes/234001/01-deliveryAssistantACL.sql @@ -1,5 +1,5 @@ -- Auto-generated SQL script. Actual values for binary/complex data types may differ - what you see is the default string representation of values. -INSERT INTO `account`.`role` (name,description) +INSERT INTO `account`.`role` (name, description) VALUES ('deliveryAssistant','Jefe auxiliar repartos'); INSERT INTO `account`.`roleInherit` (role, inheritsFrom) diff --git a/db/changes/234001/01-workerCreate.sql b/db/changes/234001/01-workerCreate.sql new file mode 100644 index 000000000..166c65a26 --- /dev/null +++ b/db/changes/234001/01-workerCreate.sql @@ -0,0 +1,20 @@ +DELIMITER $$ +$$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`workerCreate`( + vFirstname VARCHAR(50), + vLastName VARCHAR(50), + vCode CHAR(3), + vBossFk INT, + vUserFk INT, + vFi VARCHAR(15) , + vBirth DATE +) +BEGIN +/** + * Create new worker + * + */ + INSERT INTO worker(id, code, firstName, lastName, bossFk, fi, birth) + VALUES (vUserFk, vCode, vFirstname, vLastName, vBossFk, vFi, vBirth); +END$$ +DELIMITER ; diff --git a/db/dump/structure.sql b/db/dump/structure.sql index eea10eeed..73f6e92cb 100644 --- a/db/dump/structure.sql +++ b/db/dump/structure.sql @@ -24255,7 +24255,6 @@ BEGIN 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.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; @@ -45804,23 +45803,6 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` FUNCTION `getWorkerCode`() RETURNS varchar(3) CHARSET utf8mb3 COLLATE utf8mb3_general_ci - READS SQL DATA -BEGIN - DECLARE vUserCode VARCHAR(3) CHARSET utf8 COLLATE utf8_unicode_ci; - - SELECT code INTO vUserCode - FROM worker - WHERE userFk = account.myUser_getId(); - - RETURN vUserCode; -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 */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP FUNCTION IF EXISTS `hasAnyNegativeBase` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -48196,56 +48178,6 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` FUNCTION `workerIsBoss`(vUserId INT) RETURNS int(11) - DETERMINISTIC -BEGIN -/** - * Comprueba por jerarquía si el trabajador actual es jefe - * de un trabajador en concreto. - * - * @param vUserId Id del trabajador que se desea comprobar. - * @return Revuelve verdadero si es jefe del empleado por escala jerárquica. - */ - DECLARE vWorkerId INT; - DECLARE vBossId INT; - - SELECT id INTO vWorkerId - FROM vn.worker - WHERE userFk = vUserId; - IF vWorkerId IS NULL THEN - CALL util.throw('USER_NOT_FOUND'); - END IF; - - DROP TEMPORARY TABLE IF EXISTS tCheckedWorker; - CREATE TEMPORARY TABLE tCheckedWorker - (PRIMARY KEY (workerFk)) - ENGINE = MEMORY - SELECT id workerFk FROM worker LIMIT 0; - LOOP - SELECT bossFk INTO vBossId - FROM vn.worker - WHERE id = vWorkerId; - IF (SELECT COUNT(*) FROM tCheckedWorker WHERE workerFk = vBossId) THEN - CALL util.throw('INFINITE_LOOP'); - END IF; - IF vBossId = vWorkerId THEN - RETURN FALSE; - ELSEIF vBossId = account.myUser_getId() THEN - RETURN TRUE; - ELSE - INSERT INTO tCheckedWorker VALUES (vWorkerId); - SET vWorkerId = vBossId; - END IF; - END LOOP; - DROP TEMPORARY TABLE tCheckedWorker; - RETURN FALSE; -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 */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP FUNCTION IF EXISTS `workerMachinery_isRegistered` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -71229,9 +71161,8 @@ BEGIN IF (vLanding IS NULL) THEN SELECT e.email INTO vSalesPersonEmail - FROM vn.client c - JOIN vn.worker sp ON sp.id = c.salesPersonFk - JOIN account.emailUser e ON e.userFk = sp.userFk + FROM client c + JOIN account.emailUser e ON e.userFk = c.salesPersonFk WHERE c.id = vClientFk; SET vSubject = CONCAT('Turnos - No se ha podido clonar correctamente el ticket ', @@ -73418,7 +73349,8 @@ BEGIN at2.permissionRate, at2.discountRate, ct.hoursWeek hoursWeek, - at2.isAllowedToWork + at2.isAllowedToWork, + u.userFk FROM time t LEFT JOIN business b ON t.dated BETWEEN b.started AND IFNULL(b.ended, vDatedTo) LEFT JOIN worker w ON w.id = b.workerFk @@ -73946,7 +73878,7 @@ BEGIN CREATE TEMPORARY TABLE tmp.`user` SELECT u.id userFk FROM account.user u - JOIN vn.worker w ON w.id = u.id + JOIN vn.worker w ON w.userFk = u.id WHERE w.id = vWorkerFk; CALL vn.timeControl_calculate(vDatedFrom, vDatedTo); @@ -76048,8 +75980,7 @@ BEGIN LIMIT 10000000000000000000)sub GROUP BY cont HAVING cont2 MOD 2 = 1 - )sub2 - JOIN worker w ON w.userFk = sub2.userFk; + )sub2; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -82085,7 +82016,6 @@ USE `vn`; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; - -- -- Final view structure for view `workerTimeJourneyNG` -- diff --git a/modules/client/back/models/client-observation.json b/modules/client/back/models/client-observation.json index b8852b186..95d00d374 100644 --- a/modules/client/back/models/client-observation.json +++ b/modules/client/back/models/client-observation.json @@ -41,7 +41,7 @@ "include": { "relation": "worker", "scope": { - "fields": ["userFk"], + "fields": ["id"], "include": { "relation": "user", "scope": { diff --git a/modules/route/back/models/roadmap.json b/modules/route/back/models/roadmap.json index 7ca8fe0f6..2f6bb8c02 100644 --- a/modules/route/back/models/roadmap.json +++ b/modules/route/back/models/roadmap.json @@ -47,7 +47,7 @@ "worker": { "type": "belongsTo", "model": "Worker", - "foreignKey": "userFk" + "foreignKey": "id" }, "supplier": { "type": "belongsTo", diff --git a/modules/shelving/back/models/shelving.json b/modules/shelving/back/models/shelving.json index 5f60318a5..aab569d7b 100644 --- a/modules/shelving/back/models/shelving.json +++ b/modules/shelving/back/models/shelving.json @@ -41,7 +41,7 @@ "worker": { "type": "belongsTo", "model": "Worker", - "foreignKey": "userFk" + "foreignKey": "id" } } } diff --git a/modules/worker/back/methods/worker/filter.js b/modules/worker/back/methods/worker/filter.js index 15a56949f..f9eae2db8 100644 --- a/modules/worker/back/methods/worker/filter.js +++ b/modules/worker/back/methods/worker/filter.js @@ -94,8 +94,6 @@ module.exports = Self => { {'u.nickname': {like: `%${value}%`}} ]}; case 'id': - case 'userFk': - return {'w.id': value}; case 'firstName': return {'w.firstName': {like: `%${value}%`}}; case 'lastName': diff --git a/modules/worker/back/models/worker-time-control.json b/modules/worker/back/models/worker-time-control.json index b045946e7..c40989d84 100644 --- a/modules/worker/back/models/worker-time-control.json +++ b/modules/worker/back/models/worker-time-control.json @@ -36,7 +36,7 @@ "worker": { "type": "hasOne", "model": "Worker", - "foreignKey": "userFk" + "foreignKey": "id" }, "warehouse": { "type": "belongsTo", diff --git a/modules/worker/front/search-panel/index.html b/modules/worker/front/search-panel/index.html index 2adb56587..c93eef78b 100644 --- a/modules/worker/front/search-panel/index.html +++ b/modules/worker/front/search-panel/index.html @@ -18,7 +18,7 @@ + ng-model="filter.id"> @@ -64,4 +64,4 @@ -

\ No newline at end of file + From 7b246b1bacb6d8501b9cb8fa5c77d66610081ae0 Mon Sep 17 00:00:00 2001 From: carlossa Date: Thu, 21 Sep 2023 13:15:00 +0200 Subject: [PATCH 122/427] refs #5768 trad choose address --- modules/client/front/sample/create/index.html | 17 +++++++++--- .../incoterms-authorization.html | 3 ++- .../incoterms-authorization.js | 3 +++ .../incoterms-authorization/locale/es.yml | 27 +++++++++---------- .../incoterms-authorization/locale/pt.yml | 21 +++++++-------- 5 files changed, 40 insertions(+), 31 deletions(-) diff --git a/modules/client/front/sample/create/index.html b/modules/client/front/sample/create/index.html index 5df2b29ef..7d6cab673 100644 --- a/modules/client/front/sample/create/index.html +++ b/modules/client/front/sample/create/index.html @@ -8,9 +8,9 @@ auto-load="true" url="Samples/visible" fields="[ - 'id', + 'id', 'code', - 'description', + 'description', 'model', 'hasCompany', 'hasPreview', @@ -65,7 +65,16 @@ model="ClientSample.companyFk" data="companiesData" show-field="code" - label="Company" + label="Company" + ng-if="sampleType.selection.hasCompany" + required="true"> +
+ @@ -85,7 +94,7 @@

diff --git a/print/templates/reports/incoterms-authorization/incoterms-authorization.js b/print/templates/reports/incoterms-authorization/incoterms-authorization.js index 53425487e..0fbbd10d2 100755 --- a/print/templates/reports/incoterms-authorization/incoterms-authorization.js +++ b/print/templates/reports/incoterms-authorization/incoterms-authorization.js @@ -17,6 +17,9 @@ module.exports = { companyId: { type: Number, required: true + }, + address: { + type: String } } }; diff --git a/print/templates/reports/incoterms-authorization/locale/es.yml b/print/templates/reports/incoterms-authorization/locale/es.yml index 6936ebda9..8bdce7085 100644 --- a/print/templates/reports/incoterms-authorization/locale/es.yml +++ b/print/templates/reports/incoterms-authorization/locale/es.yml @@ -1,28 +1,25 @@ reportName: autorizacion-incoterms description: '{socialName} una sociedad debidamente constituida con responsabilidad limitada -y registrada conforme al derecho de sociedades de {country} y aquí representada por -___________________. {socialName}, con domicilio en {address}, +y registrada conforme al derecho de sociedades de {country} y aquí representada por {socialName}, con domicilio en {address}, CIF {fiscalID}. En adelante denominada {name}.' issued: 'En {0}, a {1} de {2} de {3}' client: 'Cliente {0}' declaration: '{socialName} declara por la presente que:' declarations: - - 'Todas las compras realizadas por {socialName} con {companyName} se -entregan, Ex Works (Incoterms), en el almacén de {companyName} situado en -{companyCity}.' - - '{socialName} reconoce que es importante para {companyName} tener -comprobante de la entrega intracomunitaria de la mercancía a {destinationCountry} para + - 'Todas las compras realizadas por {socialName} con {companyName} se entregan según las condiciones definidas en el incoterm {incotermsFk} ({Incoterm description}).' + - '{socialName} reconoce que es importante para {companyName} tener +comprobante de la entrega intracomunitaria de la mercancía a {destinationCountry} para poder facturar con 0% de IVA.' - - 'Por tanto, al firmar este acuerdo, {socialName} declara que todos los bienes que + - 'Por tanto, al firmar este acuerdo, {socialName} declara que todos los bienes que se compren a {companyName} serán entregados a {destinationCountry}.' - - 'Además, {socialName} deberá, a primera solicitud de {companyName}, -proporcionar una prueba de que todos los productos comprados a {companyName} han + - 'Además, {socialName} deberá, a primera solicitud de {companyName}, +proporcionar una prueba de que todos los productos comprados a {companyName} han sido entregados en {destinationCountry}.' - - 'Además de lo anterior, {companyName} proporcionará a {socialName} -un resumen mensual en el que se incluyen todas las facturas (y las entregas correspondientes). -{socialName} firmará y devolverá el resumen mensual a {companyName}, + - 'Además de lo anterior, {companyName} proporcionará a {socialName} +un resumen mensual en el que se incluyen todas las facturas (y las entregas correspondientes). +{socialName} firmará y devolverá el resumen mensual a {companyName}, S.L. dentro de los 5 días posteriores a la recepción del resumen.' -signer: +signer: representative: Representante representativeRole: Cargo del representante signed: Fecha de firma @@ -39,4 +36,4 @@ months: - 'Septiembre' - 'Octubre' - 'Noviembre' - - 'Diciembre' \ No newline at end of file + - 'Diciembre' diff --git a/print/templates/reports/incoterms-authorization/locale/pt.yml b/print/templates/reports/incoterms-authorization/locale/pt.yml index 2d33e6a1a..996c0961e 100644 --- a/print/templates/reports/incoterms-authorization/locale/pt.yml +++ b/print/templates/reports/incoterms-authorization/locale/pt.yml @@ -1,28 +1,27 @@ reportName: autorizacion-incoterms description: '{socialName} uma sociedade devidamente constituída com responsabilidade limitada e registada -conforme ao direito de sociedades da {country} e aqui representada por -___________________. {socialName}, com domicílio em {address}, +conforme ao direito de sociedades da {country} e aqui representada por {socialName}, com domicílio em {address}, CIF {fiscalID}. Em adiante denominada {name}.' issued: 'Em {0}, em {1} de {2} de {3}' client: 'Cliente {0}' declaration: '{socialName} declara através da presente que:' declarations: - - 'Todas as compras realizadas por {socialName} a {companyName} se entregam, + - 'Todas as compras realizadas por {socialName} a {companyName} se entregam, Ex Works (Incoterms), no armazém da {companyName} situado em {companyCity}.' - - '{socialName} reconhece ser importante para {companyName} - ter o comprovante da entrega intracomunitária da mercadoria a {destinationCountry} + - '{socialName} reconhece ser importante para {companyName} + ter o comprovante da entrega intracomunitária da mercadoria em {destinationCountry} para poder faturar com 0% de IVA.' - - 'Portanto, ao assinar este acordo, {socialName} declara que todos os bens + - 'Portanto, ao assinar este acordo, {socialName} declara que todos os bens que se comprem na {companyName} serão entregues na {destinationCountry}.' - 'Além disto, {socialName} deverá, na primeira solicitude da {companyName}, - proporcionar uma prova de que todos os produtos comprados na {companyName} - foram entregues na {destinationCountry}.' - - 'Além do anterio, {companyName} proporcionará a {socialName} + proporcionar uma prova de que todos os produtos comprados em {companyName} + foram entregues em {destinationCountry}.' + - 'Além do anterior, {companyName} proporcionará a {socialName} um resumo mensal onde se incluem todas as faturas (e as entregas correspondentes). {socialName} assinará e devolverá o resumo mensal à {companyName}, dentro dos 5 dias posteriores à receção do resumo.' -signer: +signer: representative: Representante representativeRole: Cargo de representante signed: Data da assinatura @@ -39,4 +38,4 @@ months: - 'Setembro' - 'Outubro' - 'Novembro' - - 'Dezembro' \ No newline at end of file + - 'Dezembro' From 850df643489f5025453379e822e1ff3ba7e6b0a7 Mon Sep 17 00:00:00 2001 From: pablone Date: Thu, 21 Sep 2023 14:59:26 +0200 Subject: [PATCH 123/427] refs #6159 moveChangefile --- db/changes/{233801 => 234001}/00-updateAfterBusinnesInsert.sql | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename db/changes/{233801 => 234001}/00-updateAfterBusinnesInsert.sql (100%) diff --git a/db/changes/233801/00-updateAfterBusinnesInsert.sql b/db/changes/234001/00-updateAfterBusinnesInsert.sql similarity index 100% rename from db/changes/233801/00-updateAfterBusinnesInsert.sql rename to db/changes/234001/00-updateAfterBusinnesInsert.sql From a78348f2de7624b3e44b004ede1f055659c256c0 Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 21 Sep 2023 15:06:14 +0200 Subject: [PATCH 124/427] refs #6067 feat(account_basicData): use vnUser/preview --- modules/account/front/basic-data/index.html | 14 ++++++++------ modules/account/front/basic-data/index.js | 7 +++++++ 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/modules/account/front/basic-data/index.html b/modules/account/front/basic-data/index.html index 6f757753e..1f7ce1a05 100644 --- a/modules/account/front/basic-data/index.html +++ b/modules/account/front/basic-data/index.html @@ -1,9 +1,11 @@ + + where="{id: $ctrl.$params.id}" + form="form" + save="post">
diff --git a/modules/account/front/basic-data/index.js b/modules/account/front/basic-data/index.js index 77d3eab26..43d1c0468 100644 --- a/modules/account/front/basic-data/index.js +++ b/modules/account/front/basic-data/index.js @@ -2,6 +2,13 @@ import ngModule from '../module'; import Section from 'salix/components/section'; export default class Controller extends Section { + set user(value) { + this._user = value; + console.log(value); + } + get user() { + return this._user; + } $onInit() { if (this.$params.emailConfirmed) this.vnApp.showSuccess(this.$t('Email verified successfully!')); From 82f14e62ade80aed1df3ebd0e45bebba603def3b Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 21 Sep 2023 16:08:55 +0200 Subject: [PATCH 125/427] ref #5914 tests fixed --- modules/invoiceOut/back/models/invoice-out.js | 1 + modules/ticket/back/methods/sale/refund.js | 2 +- modules/ticket/back/methods/ticket/invoiceTickets.js | 2 +- print/templates/reports/invoice/invoice.js | 2 -- 4 files changed, 3 insertions(+), 4 deletions(-) diff --git a/modules/invoiceOut/back/models/invoice-out.js b/modules/invoiceOut/back/models/invoice-out.js index ca77c856f..34b4dc798 100644 --- a/modules/invoiceOut/back/models/invoice-out.js +++ b/modules/invoiceOut/back/models/invoice-out.js @@ -44,6 +44,7 @@ module.exports = Self => { Self.makePdf = async function(id, options) { const fields = ['id', 'hasPdf', 'ref']; const invoiceOut = await Self.findById(id, {fields}, options); + console.log('Recoge invoiceOut?'); const invoiceReport = new print.Report('invoice', { reference: invoiceOut.ref }); diff --git a/modules/ticket/back/methods/sale/refund.js b/modules/ticket/back/methods/sale/refund.js index ba7d71253..5d8297a4e 100644 --- a/modules/ticket/back/methods/sale/refund.js +++ b/modules/ticket/back/methods/sale/refund.js @@ -51,7 +51,7 @@ module.exports = Self => { myOptions ); - if (tx && !options) await tx.commit(); + if (tx) await tx.commit(); return refundsTicket[0]; } catch (e) { diff --git a/modules/ticket/back/methods/ticket/invoiceTickets.js b/modules/ticket/back/methods/ticket/invoiceTickets.js index e65c14e9a..fa3ee93af 100644 --- a/modules/ticket/back/methods/ticket/invoiceTickets.js +++ b/modules/ticket/back/methods/ticket/invoiceTickets.js @@ -79,7 +79,7 @@ module.exports = function(Self) { } if (tx) { for (const invoiceId of invoicesIds) - await models.InvoiceOut.makePdfAndNotify(ctx, invoiceId, null, myOptions); + await models.InvoiceOut.makePdfAndNotify(ctx, invoiceId, null); } return invoicesIds; diff --git a/print/templates/reports/invoice/invoice.js b/print/templates/reports/invoice/invoice.js index 4424c8ea3..b26472b08 100755 --- a/print/templates/reports/invoice/invoice.js +++ b/print/templates/reports/invoice/invoice.js @@ -6,9 +6,7 @@ module.exports = { name: 'invoice', mixins: [vnReport], async serverPrefetch() { - console.log(this.reference); this.invoice = await this.findOneFromDef('invoice', [this.reference]); - console.log(this.invoice); this.checkMainEntity(this.invoice); this.client = await this.findOneFromDef('client', [this.reference]); From c7e26f9155e3be023a7f7bdbc745fae1e5b6c23a Mon Sep 17 00:00:00 2001 From: carlossa Date: Fri, 22 Sep 2023 06:08:07 +0200 Subject: [PATCH 126/427] refs #5768 autocomplete --- modules/client/front/sample/create/index.html | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/modules/client/front/sample/create/index.html b/modules/client/front/sample/create/index.html index 7d6cab673..134c097e8 100644 --- a/modules/client/front/sample/create/index.html +++ b/modules/client/front/sample/create/index.html @@ -69,15 +69,15 @@ ng-if="sampleType.selection.hasCompany" required="true"> - - + --> Date: Fri, 22 Sep 2023 09:14:08 +0200 Subject: [PATCH 127/427] refs #6159 fixFixtures --- db/dump/fixtures.sql | 3 +++ modules/worker/back/methods/calendar/specs/absences.spec.js | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 36bb49bc8..fbdd1ad1c 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -1967,6 +1967,9 @@ INSERT INTO `vn`.`calendarType` (`id`, `description`, `hoursWeek`, `isPartial`) VALUES (1, 'General schedule', 40, 0); +INSERT INTO `vn`.`workerBusinessAgreement` (`id`, `name`, `monthHolidays`, `yearHours`, `started`, `ended`) + VALUES(1, 'flowers', 2.5, 1830, '2001-01-01', NULL); + DROP TEMPORARY TABLE IF EXISTS tmp.worker; CREATE TEMPORARY TABLE tmp.worker (PRIMARY KEY (id)) diff --git a/modules/worker/back/methods/calendar/specs/absences.spec.js b/modules/worker/back/methods/calendar/specs/absences.spec.js index 365773182..ce27c1762 100644 --- a/modules/worker/back/methods/calendar/specs/absences.spec.js +++ b/modules/worker/back/methods/calendar/specs/absences.spec.js @@ -50,7 +50,7 @@ describe('Worker absences()', () => { } }); - it('should give the same holidays as worked days since the holidays amount matches the amount of days in a year', async() => { + it('should holidays should equal worked days as both are the same number of days in a year', async() => { const businessId = 1106; const workerId = 1106; From 3013e3cd9cf7c127642eb4529cd1b3f158b4e6fb Mon Sep 17 00:00:00 2001 From: pablone Date: Fri, 22 Sep 2023 09:14:59 +0200 Subject: [PATCH 128/427] refs #6159 removeSpaces --- db/dump/fixtures.sql | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index fbdd1ad1c..36400b0d7 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -1967,8 +1967,8 @@ INSERT INTO `vn`.`calendarType` (`id`, `description`, `hoursWeek`, `isPartial`) VALUES (1, 'General schedule', 40, 0); -INSERT INTO `vn`.`workerBusinessAgreement` (`id`, `name`, `monthHolidays`, `yearHours`, `started`, `ended`) - VALUES(1, 'flowers', 2.5, 1830, '2001-01-01', NULL); +INSERT INTO `vn`.`workerBusinessAgreement` (`id`, `name`, `monthHolidays`, `yearHours`, `started`, `ended`) + VALUES(1, 'flowers', 2.5, 1830, '2001-01-01', NULL); DROP TEMPORARY TABLE IF EXISTS tmp.worker; CREATE TEMPORARY TABLE tmp.worker From c175bcfc974b6a8272c1f4aef4ebbd39863d6c1f Mon Sep 17 00:00:00 2001 From: pablone Date: Fri, 22 Sep 2023 09:40:37 +0200 Subject: [PATCH 129/427] refs #6159 rename spec --- modules/worker/back/methods/calendar/specs/absences.spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/worker/back/methods/calendar/specs/absences.spec.js b/modules/worker/back/methods/calendar/specs/absences.spec.js index ce27c1762..b27c9549c 100644 --- a/modules/worker/back/methods/calendar/specs/absences.spec.js +++ b/modules/worker/back/methods/calendar/specs/absences.spec.js @@ -50,7 +50,7 @@ describe('Worker absences()', () => { } }); - it('should holidays should equal worked days as both are the same number of days in a year', async() => { + it('Should have an equal number of holidays and workdays, as they both total the days in a year', async() => { const businessId = 1106; const workerId = 1106; From c7f84ad6db8c5c2cac798e2bd720106d4cfc9657 Mon Sep 17 00:00:00 2001 From: carlossa Date: Fri, 22 Sep 2023 10:36:51 +0200 Subject: [PATCH 130/427] refs #5843 add return --- modules/worker/back/methods/worker/filter.js | 1 + 1 file changed, 1 insertion(+) diff --git a/modules/worker/back/methods/worker/filter.js b/modules/worker/back/methods/worker/filter.js index f9eae2db8..2f328d28f 100644 --- a/modules/worker/back/methods/worker/filter.js +++ b/modules/worker/back/methods/worker/filter.js @@ -94,6 +94,7 @@ module.exports = Self => { {'u.nickname': {like: `%${value}%`}} ]}; case 'id': + return {'w.id': value}; case 'firstName': return {'w.firstName': {like: `%${value}%`}}; case 'lastName': From a854fff94f8db16786ae10232098e1ef4e17b242 Mon Sep 17 00:00:00 2001 From: pablone Date: Fri, 22 Sep 2023 10:59:48 +0200 Subject: [PATCH 131/427] refs #3126 changes --- db/.archive/231001/00-packagingFk.sql | 2 + db/.archive/231001/00-packagingFkviews.sql | 146 ++++ db/.archive/231001/02-packagingFktrigger.sql | 57 ++ db/.archive/231001/03-packagingFkProc.sql | 669 ++++++++++++++++++ db/dump/fixtures.sql | 2 +- e2e/helpers/selectors.js | 2 +- e2e/paths/13-supplier/03_fiscal_data.spec.js | 25 +- modules/entry/back/locale/buy/en.yml | 2 +- modules/entry/back/locale/buy/es.yml | 2 +- .../entry/back/methods/entry/addFromBuy.js | 2 +- modules/entry/back/methods/entry/getBuys.js | 2 +- .../entry/back/methods/entry/importBuys.js | 2 +- .../back/methods/entry/importBuysPreview.js | 2 +- .../back/methods/entry/latestBuysFilter.js | 115 ++- .../methods/entry/specs/importBuys.spec.js | 4 +- .../entry/specs/importBuysPreview.spec.js | 6 +- modules/entry/back/models/buy.json | 2 +- modules/entry/front/buy/import/index.html | 4 +- modules/entry/front/buy/index/index.html | 4 +- modules/entry/front/buy/index/index.js | 2 +- modules/entry/front/buy/index/index.spec.js | 2 +- modules/entry/front/latest-buys/index.html | 4 +- modules/entry/front/latest-buys/index.js | 4 +- modules/entry/front/summary/index.html | 4 +- .../back/methods/item/lastEntriesFilter.js | 76 +- modules/item/front/last-entries/index.html | 4 +- modules/item/front/last-entries/index.js | 2 +- .../methods/travel/extraCommunityFilter.js | 20 +- .../travel/back/methods/travel/getEntries.js | 2 +- 29 files changed, 1020 insertions(+), 150 deletions(-) create mode 100644 db/.archive/231001/00-packagingFk.sql create mode 100644 db/.archive/231001/00-packagingFkviews.sql create mode 100644 db/.archive/231001/02-packagingFktrigger.sql create mode 100644 db/.archive/231001/03-packagingFkProc.sql diff --git a/db/.archive/231001/00-packagingFk.sql b/db/.archive/231001/00-packagingFk.sql new file mode 100644 index 000000000..5ed1d9512 --- /dev/null +++ b/db/.archive/231001/00-packagingFk.sql @@ -0,0 +1,2 @@ + ALTER TABLE vn.buy CHANGE packageFk packagingFk varchar(10) + CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT '--' NULL; \ No newline at end of file diff --git a/db/.archive/231001/00-packagingFkviews.sql b/db/.archive/231001/00-packagingFkviews.sql new file mode 100644 index 000000000..f355325f3 --- /dev/null +++ b/db/.archive/231001/00-packagingFkviews.sql @@ -0,0 +1,146 @@ +CREATE OR REPLACE DEFINER=`root`@`localhost` + SQL SECURITY DEFINER + VIEW `vn2008`.`Compres` +AS SELECT `c`.`id` AS `Id_Compra`, + `c`.`entryFk` AS `Id_Entrada`, + `c`.`itemFk` AS `Id_Article`, + `c`.`buyingValue` AS `Costefijo`, + `c`.`quantity` AS `Cantidad`, + `c`.`packagingFk` AS `Id_Cubo`, + `c`.`stickers` AS `Etiquetas`, + `c`.`freightValue` AS `Portefijo`, + `c`.`packageValue` AS `Embalajefijo`, + `c`.`comissionValue` AS `Comisionfija`, + `c`.`packing` AS `Packing`, + `c`.`grouping` AS `grouping`, + `c`.`groupingMode` AS `caja`, + `c`.`location` AS `Nicho`, + `c`.`price1` AS `Tarifa1`, + `c`.`price2` AS `Tarifa2`, + `c`.`price3` AS `Tarifa3`, + `c`.`minPrice` AS `PVP`, + `c`.`printedStickers` AS `Vida`, + `c`.`isChecked` AS `punteo`, + `c`.`ektFk` AS `buy_edi_id`, + `c`.`created` AS `odbc_date`, + `c`.`isIgnored` AS `Novincular`, + `c`.`isPickedOff` AS `isPickedOff`, + `c`.`workerFk` AS `Id_Trabajador`, + `c`.`weight` AS `weight`, + `c`.`dispatched` AS `dispatched`, + `c`.`containerFk` AS `container_id`, + `c`.`itemOriginalFk` AS `itemOriginalFk` +FROM `vn`.`buy` `c`; + +CREATE OR REPLACE DEFINER=`root`@`localhost` + SQL SECURITY DEFINER + VIEW `vn2008`.`buySource` +AS SELECT `b`.`entryFk` AS `Id_Entrada`, + `b`.`isPickedOff` AS `isPickedOff`, + NULL AS `tarifa0`, + `e`.`kop` AS `kop`, + `b`.`id` AS `Id_Compra`, + `i`.`typeFk` AS `tipo_id`, + `b`.`itemFk` AS `Id_Article`, + `i`.`size` AS `Medida`, + `i`.`stems` AS `Tallos`, + `b`.`stickers` AS `Etiquetas`, + `b`.`packagingFk` AS `Id_Cubo`, + `b`.`buyingValue` AS `Costefijo`, + `b`.`packing` AS `Packing`, + `b`.`grouping` AS `Grouping`, + `b`.`quantity` AS `Cantidad`, + `b`.`price2` AS `Tarifa2`, + `b`.`price3` AS `Tarifa3`, + `b`.`isChecked` AS `Punteo`, + `b`.`groupingMode` AS `Caja`, + `i`.`isToPrint` AS `Imprimir`, + `i`.`name` AS `Article`, + `vn`.`ink`.`picture` AS `Tinta`, + `i`.`originFk` AS `id_origen`, + `i`.`minPrice` AS `PVP`, + NULL AS `Id_Accion`, + `s`.`company_name` AS `pro`, + `i`.`hasMinPrice` AS `Min`, + `b`.`isIgnored` AS `Novincular`, + `b`.`freightValue` AS `Portefijo`, + round(`b`.`buyingValue` * `b`.`quantity`, 2) AS `Importe`, + `b`.`printedStickers` AS `Vida`, + `i`.`comment` AS `reference`, + `b`.`workerFk` AS `Id_Trabajador`, + `e`.`s1` AS `S1`, + `e`.`s2` AS `S2`, + `e`.`s3` AS `S3`, + `e`.`s4` AS `S4`, + `e`.`s5` AS `S5`, + `e`.`s6` AS `S6`, + 0 AS `price_fixed`, + `i`.`producerFk` AS `producer_id`, + `i`.`subName` AS `tag1`, + `i`.`value5` AS `tag2`, + `i`.`value6` AS `tag3`, + `i`.`value7` AS `tag4`, + `i`.`value8` AS `tag5`, + `i`.`value9` AS `tag6`, + `s`.`company_name` AS `company_name`, + `b`.`weight` AS `weightPacking`, + `i`.`packingOut` AS `packingOut`, + `b`.`itemOriginalFk` AS `itemOriginalFk`, + `io`.`longName` AS `itemOriginalName`, + `it`.`gramsMax` AS `gramsMax` +FROM ( + ( + ( + ( + ( + ( + `vn`.`item` `i` + JOIN `vn`.`itemType` `it` ON(`it`.`id` = `i`.`typeFk`) + ) + LEFT JOIN `vn`.`ink` ON(`vn`.`ink`.`id` = `i`.`inkFk`) + ) + LEFT JOIN `vn`.`buy` `b` ON(`b`.`itemFk` = `i`.`id`) + ) + LEFT JOIN `vn`.`item` `io` ON(`io`.`id` = `b`.`itemOriginalFk`) + ) + LEFT JOIN `edi`.`ekt` `e` ON(`e`.`id` = `b`.`ektFk`) + ) + LEFT JOIN `edi`.`supplier` `s` ON(`e`.`pro` = `s`.`supplier_id`) + ); + +CREATE OR REPLACE DEFINER=`root`@`localhost` + SQL SECURITY DEFINER + VIEW `vn`.`awbVolume` +AS SELECT `d`.`awbFk` AS `awbFk`, + `b`.`stickers` * `i`.`density` * IF( + `p`.`volume` > 0, + `p`.`volume`, + `p`.`width` * `p`.`depth` * IF(`p`.`height` = 0, `i`.`size` + 10, `p`.`height`) + ) / (`vc`.`aerealVolumetricDensity` * 1000) AS `volume`, + `b`.`id` AS `buyFk` +FROM ( + ( + ( + ( + ( + ( + ( + ( + `vn`.`buy` `b` + JOIN `vn`.`item` `i` ON(`b`.`itemFk` = `i`.`id`) + ) + JOIN `vn`.`itemType` `it` ON(`i`.`typeFk` = `it`.`id`) + ) + JOIN `vn`.`packaging` `p` ON(`p`.`id` = `b`.`packagingFk`) + ) + JOIN `vn`.`entry` `e` ON(`b`.`entryFk` = `e`.`id`) + ) + JOIN `vn`.`travel` `t` ON(`t`.`id` = `e`.`travelFk`) + ) + JOIN `vn`.`duaEntry` `de` ON(`de`.`entryFk` = `e`.`id`) + ) + JOIN `vn`.`dua` `d` ON(`d`.`id` = `de`.`duaFk`) + ) + JOIN `vn`.`volumeConfig` `vc` + ) +WHERE `t`.`shipped` > makedate(year(`util`.`VN_CURDATE`()) - 1, 1); \ No newline at end of file diff --git a/db/.archive/231001/02-packagingFktrigger.sql b/db/.archive/231001/02-packagingFktrigger.sql new file mode 100644 index 000000000..4edcd3f3e --- /dev/null +++ b/db/.archive/231001/02-packagingFktrigger.sql @@ -0,0 +1,57 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`buy_afterUpdate` + AFTER UPDATE ON `buy` + FOR EACH ROW +trig: BEGIN + DECLARE vLanded DATE; + DECLARE vBuyerFk INT; + DECLARE vIsBuyerToBeEmailed BOOL; + DECLARE vItemName VARCHAR(50); + + IF @isModeInventory OR @isTriggerDisabled THEN + LEAVE trig; + END IF; + + IF !(NEW.id <=> OLD.id) + OR !(NEW.entryFk <=> OLD.entryFk) + OR !(NEW.itemFk <=> OLD.itemFk) + OR !(NEW.quantity <=> OLD.quantity) + OR !(NEW.created <=> OLD.created) THEN + CALL stock.log_add('buy', NEW.id, OLD.id); + END IF; + + CALL buy_afterUpsert(NEW.id); + + SELECT w.isBuyerToBeEmailed, t.landed + INTO vIsBuyerToBeEmailed, vLanded + FROM entry e + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseInFk + WHERE e.id = NEW.entryFk; + + SELECT it.workerFk, i.longName + INTO vBuyerFk, vItemName + FROM itemCategory k + JOIN itemType it ON it.categoryFk = k.id + JOIN item i ON i.typeFk = it.id + WHERE i.id = OLD.itemFk; + + IF vIsBuyerToBeEmailed AND + vBuyerFk != account.myUser_getId() AND + vLanded = util.VN_CURDATE() THEN + IF !(NEW.itemFk <=> OLD.itemFk) OR + !(NEW.quantity <=> OLD.quantity) OR + !(NEW.packing <=> OLD.packing) OR + !(NEW.grouping <=> OLD.grouping) OR + !(NEW.packagingFk <=> OLD.packagingFk) OR + !(NEW.weight <=> OLD.weight) THEN + CALL vn.mail_insert( + CONCAT(account.user_getNameFromId(vBuyerFk),'@verdnatura.es'), + CONCAT(account.myUser_getName(),'@verdnatura.es'), + CONCAT('E ', NEW.entryFk ,' Se ha modificado item ', NEW.itemFk, ' ', vItemName), + 'Este email se ha generado automáticamente' + ); + END IF; + END IF; +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/.archive/231001/03-packagingFkProc.sql b/db/.archive/231001/03-packagingFkProc.sql new file mode 100644 index 000000000..acbf54a76 --- /dev/null +++ b/db/.archive/231001/03-packagingFkProc.sql @@ -0,0 +1,669 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`travelVolume`(vTravelFk INT) +BEGIN + + SELECT w1.name AS ORI, + w2.name AS DES, + tr.shipped shipment, + tr.landed landing, + a.name Agencia, + s.name Proveedor, + e.id Id_Entrada, + e.invoiceNumber Referencia, + CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) * + vn.item_getVolume(b.itemFk ,b.packagingFk)) / vc.trolleyM3 / 1000000 ,1) AS DECIMAL(10,2)) AS CC, + CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) * + vn.item_getVolume(b.itemFk ,b.packagingFk)) / vc.palletM3 / 1000000,1) AS DECIMAL(10,2)) AS espais + FROM vn.buy b + JOIN vn.entry e ON e.id = b.entryFk + JOIN vn.supplier s ON s.id = e.supplierFk + JOIN vn.travel tr ON tr.id = e.travelFk + JOIN vn.agencyMode a ON a.id = tr.agencyModeFk + JOIN vn.warehouse w1 ON w1.id = tr.warehouseInFk + JOIN vn.warehouse w2 ON w2.id = tr.warehouseOutFk + JOIN vn.volumeConfig vc + JOIN vn.item i ON i.id = b.itemFk + JOIN vn.itemType it ON it.id = i.typeFk + WHERE tr.id = vTravelFk; + +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`travelVolume_get`(vFromDated DATE, vToDated DATE, vWarehouseFk INT) +BEGIN + SELECT tr.landed Fecha, + a.name Agencia, + count(DISTINCT e.id) numEntradas, + FLOOR(sum(item_getVolume(b.itemFk, b.packagingFk) * b.stickers / 1000000 )) AS m3 + FROM vn.travel tr + JOIN vn.agencyMode a ON a.id = tr.agencyModeFk + JOIN vn.entry e ON e.travelFk = tr.id + JOIN vn.buy b ON b.entryFk = e.id + WHERE tr.landed BETWEEN vFromDated AND vToDated + AND e.isRaid = FALSE + AND tr.warehouseInFk = vWarehouseFk + GROUP BY tr.landed , a.name ; +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`travel_getEntriesMissingPackage`(vSelf INT) +BEGIN + DECLARE vpackageOrPackingNull INT; + DECLARE vTravelFk INT; + + SELECT travelfk INTO vTravelFk + FROM entry + WHERE id = vSelf; + + SELECT e.id entryFk + FROM travel t + JOIN entry e ON e.travelFk = t.id + JOIN buy b ON b.entryFk = e.id + WHERE t.id = vTravelFk + AND (b.packing IS NULL OR b.packagingFk IS NULL); +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketBoxesView`(IN vTicketFk INT) +BEGIN + + SELECT s.id, + s.itemFk, + s.concept, + floor(s.quantity / b.packing) as Cajas, + b.packing, + s.isPicked, + i.size + FROM ticket t + JOIN sale s ON s.ticketFk = t.id + JOIN item i ON i.id = s.itemFk + JOIN cache.last_buy lb on lb.warehouse_id = t.warehouseFk AND lb.item_id = s.itemFk + JOIN buy b on b.id = lb.buy_id + JOIN packaging p on p.id = b.packagingFk + WHERE s.quantity >= b.packing + AND t.id = vTicketFk + AND p.isBox + GROUP BY s.itemFk; + + +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`stockBuyedByWorker`( + vDate DATE, + vWorker INT) +BEGIN +/** + * Calculates the space reserved by buyers of the same container + * + * @param vdate date of container delivery + * @param vWorker buyer reserving space in the container + */ + DECLARE vVolume DECIMAL(10, 2); + DECLARE vWarehouseFk INT; + DECLARE vCompressionRatio DECIMAL(1, 1); + + CALL stockTraslation(vDate); + + SELECT warehouseFk, conversionCoefficient INTO vWarehouseFk, vCompressionRatio + FROM auctionConfig; + + SELECT volume INTO vVolume + FROM vn.packaging WHERE id = 'cc'; + + SELECT b.entryFk Id_Entrada, + i.id Id_Article, + i.name Article, + ti.amount Cantidad, + (vCompressionRatio * (ti.amount / b.packing) * vn.buy_getVolume(b.id)) + / vVolume buyed, + b.packagingFk id_cubo, + b.packing + FROM tmp.item ti + JOIN item i ON i.id = ti.item_id + JOIN itemType it ON i.typeFk = it.id + JOIN itemCategory ic ON ic.id = it.categoryFk + JOIN worker w ON w.id = it.workerFk + JOIN tmp.buyUltimate bu ON bu.itemFk = i.id + AND bu.warehouseFk = vWarehouseFk + JOIN buy b ON b.id = bu.buyFk + WHERE ic.display AND w.id = vWorker; + + DROP TEMPORARY TABLE + tmp.buyUltimate, + tmp.item; +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingMakeFromDate`(IN `vShelvingFk` VARCHAR(8), IN `vBarcode` VARCHAR(22), IN `vQuantity` INT, IN `vPackagingFk` VARCHAR(10), IN `vGrouping` INT, IN `vPacking` INT, IN `vWarehouseFk` INT, `vCreated` VARCHAR(22)) +BEGIN + + DECLARE vItemFk INT; + + SELECT vn.barcodeToItem(vBarcode) INTO vItemFk; + + SELECT itemFk INTO vItemFk + FROM vn.buy b + WHERE b.id = vItemFk; + + IF (SELECT COUNT(*) FROM vn.shelving WHERE code = vShelvingFk COLLATE utf8_unicode_ci) = 0 THEN + + INSERT IGNORE INTO vn.parking(`code`) VALUES(vShelvingFk); + INSERT INTO vn.shelving(`code`, parkingFk) + SELECT vShelvingFk, id + FROM vn.parking + WHERE `code` = vShelvingFk COLLATE utf8_unicode_ci; + + END IF; + + IF (SELECT COUNT(*) FROM vn.itemShelving + WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk + AND itemFk = vItemFk + AND packing = vPacking) = 1 THEN + + UPDATE vn.itemShelving + SET visible = visible+vQuantity, + created = vCreated + WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk + AND itemFk = vItemFk + AND packing = vPacking; + + ELSE + CALL cache.last_buy_refresh(FALSE); + INSERT INTO itemShelving( itemFk, + shelvingFk, + visible, + created, + `grouping`, + packing, + packagingFk) + SELECT vItemFk, + vShelvingFk, + vQuantity, + vCreated, + IF(vGrouping = 0, IFNULL(b.packing, vPacking), vGrouping) `grouping`, + IF(vPacking = 0, b.packing, vPacking) packing, + IF(vPackagingFk = '', b.packagingFk, vPackagingFk) packaging + FROM vn.item i + LEFT JOIN cache.last_buy lb ON i.id = lb.item_id AND lb.warehouse_id = vWarehouseFk + LEFT JOIN vn.buy b ON b.id = lb.buy_id + WHERE i.id = vItemFk; + END IF; + +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelving_add`(IN vShelvingFk VARCHAR(8), IN vBarcode VARCHAR(22), IN vQuantity INT, IN vPackagingFk VARCHAR(10), IN vGrouping INT, IN vPacking INT, IN vWarehouseFk INT) +BEGIN + + +/** + * Añade registro o lo actualiza si ya existe. + * + * @param vShelvingFk matrícula del carro + * @param vBarcode el id del registro + * @param vQuantity indica la cantidad del producto + * @param vPackagingFk el packaging del producto en itemShelving, NULL para coger el de la ultima compra + * @param vGrouping el grouping del producto en itemShelving, NULL para coger el de la ultima compra + * @param vPacking el packing del producto, NULL para coger el de la ultima compra + * @param vWarehouseFk indica el sector + * + **/ + + DECLARE vItemFk INT; + + SELECT barcodeToItem(vBarcode) INTO vItemFk; + + IF (SELECT COUNT(*) FROM shelving WHERE code = vShelvingFk COLLATE utf8_unicode_ci) = 0 THEN + + INSERT IGNORE INTO parking(code) VALUES(vShelvingFk); + INSERT INTO shelving(code, parkingFk) + SELECT vShelvingFk, id + FROM parking + WHERE `code` = vShelvingFk COLLATE utf8_unicode_ci; + + END IF; + + IF (SELECT COUNT(*) FROM itemShelving + WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk + AND itemFk = vItemFk + AND packing = vPacking) = 1 THEN + + UPDATE itemShelving + SET visible = visible+vQuantity + WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk AND itemFk = vItemFk AND packing = vPacking; + + ELSE + CALL cache.last_buy_refresh(FALSE); + INSERT INTO itemShelving( itemFk, + shelvingFk, + visible, + grouping, + packing, + packagingFk) + + SELECT vItemFk, + vShelvingFk, + vQuantity, + IFNULL(vGrouping, b.grouping), + IFNULL(vPacking, b.packing), + IFNULL(vPackagingFk, b.packagingFk) + FROM item i + LEFT JOIN cache.last_buy lb ON i.id = lb.item_id AND lb.warehouse_id = vWarehouseFk + LEFT JOIN buy b ON b.id = lb.buy_id + WHERE i.id = vItemFk; + END IF; +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemFreight_Show`(vItemFk INT, vWarehouseFk INT) +BEGIN + + SELECT cm3 Volumen_Entrada, + cm3delivery Volumen_Salida, + p.volume Volumen_del_embalaje, + p.width Ancho_del_embalaje, + p.`depth` Largo_del_embalaje, + b.packagingFk , + IFNULL(p.height, i.`size`) + 10 Altura, + b.packing Packing_Entrada, + i.packingOut Packing_Salida, + i.id itemFk, + b.id buyFk, + b.entryFk, + w.name warehouseFk + FROM vn.itemCost ic + JOIN vn.item i ON i.id = ic.itemFk + LEFT JOIN cache.last_buy lb ON lb.item_id = ic.itemFk AND lb.warehouse_id = ic.warehouseFk + LEFT JOIN vn.buy b ON b.id = lb.buy_id + LEFT JOIN vn.packaging p ON p.id = b.packagingFk + LEFT JOIN vn.warehouse w ON w.id = ic.warehouseFk + WHERE ic.itemFk = vItemFk + AND ic.warehouseFk = vWarehouseFk; +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`inventoryMake`(vDate DATE, vWh INT) +proc: BEGIN +/** +* Recalcula los inventarios de todos los almacenes, si vWh = 0 +* +* @param vDate Fecha de los nuevos inventarios +* @param vWh almacen al cual hacer el inventario +*/ + + DECLARE vDone BOOL; + DECLARE vEntryFk INT; + DECLARE vTravelFk INT; + DECLARE vDateLastInventory DATE; + DECLARE vDateYesterday DATETIME DEFAULT vDate - INTERVAL 1 SECOND; + DECLARE vWarehouseOutFkInventory INT; + DECLARE vInventorySupplierFk INT; + DECLARE vAgencyModeFkInventory INT; + + DECLARE cWarehouses CURSOR FOR + SELECT id + FROM warehouse + WHERE isInventory + AND vWh IN (0,id); + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + OPEN cWarehouses; + SET @isModeInventory := TRUE; + l: LOOP + + SET vDone = FALSE; + FETCH cWarehouses INTO vWh; + + IF vDone THEN + LEAVE l; + END IF; + + SELECT w.id INTO vWarehouseOutFkInventory + FROM warehouse w + WHERE w.code = 'inv'; + + SELECT inventorySupplierFk INTO vInventorySupplierFk + FROM entryConfig; + + SELECT am.id INTO vAgencyModeFkInventory + FROM agencyMode am + where code = 'inv'; + + SELECT MAX(landed) INTO vDateLastInventory + FROM travel tr + JOIN entry e ON e.travelFk = tr.id + JOIN buy b ON b.entryFk = e.id + WHERE warehouseOutFk = vWarehouseOutFkInventory + AND landed < vDate + AND e.supplierFk = vInventorySupplierFk + AND warehouseInFk = vWh + AND NOT isRaid; + + IF vDateLastInventory IS NULL THEN + SELECT inventoried INTO vDateLastInventory FROM config; + END IF; + + -- Generamos travel, si no existe. + SET vTravelFK = 0; + + SELECT id INTO vTravelFk + FROM travel + WHERE warehouseOutFk = vWarehouseOutFkInventory + AND warehouseInFk = vWh + AND landed = vDate + AND agencyModeFk = vAgencyModeFkInventory + AND ref = 'inventario' + LIMIT 1; + + IF NOT vTravelFK THEN + + INSERT INTO travel SET + warehouseOutFk = vWarehouseOutFkInventory, + warehouseInFk = vWh, + shipped = vDate, + landed = vDate, + agencyModeFk = vAgencyModeFkInventory, + ref = 'inventario', + isDelivered = TRUE, + isReceived = TRUE; + + SELECT LAST_INSERT_ID() INTO vTravelFk; + + END IF; + + -- Generamos entrada si no existe, o la vaciamos. + SET vEntryFk = 0; + + SELECT id INTO vEntryFk + FROM entry + WHERE supplierFk = vInventorySupplierFk + AND travelFk = vTravelFk; + + IF NOT vEntryFk THEN + + INSERT INTO entry SET + supplierFk = vInventorySupplierFk, + isConfirmed = TRUE, + isOrdered = TRUE, + travelFk = vTravelFk; + + SELECT LAST_INSERT_ID() INTO vEntryFk; + + ELSE + + DELETE FROM buy WHERE entryFk = vEntryFk; + + END IF; + + -- Preparamos tabla auxilar + CREATE OR REPLACE TEMPORARY TABLE tmp.inventory ( + itemFk INT(11) NOT NULL PRIMARY KEY, + quantity int(11) DEFAULT '0', + buyingValue decimal(10,3) DEFAULT '0.000', + freightValue decimal(10,3) DEFAULT '0.000', + packing int(11) DEFAULT '0', + `grouping` smallint(5) unsigned NOT NULL DEFAULT '1', + groupingMode tinyint(4) NOT NULL DEFAULT 0 , + comissionValue decimal(10,3) DEFAULT '0.000', + packageValue decimal(10,3) DEFAULT '0.000', + packageFk varchar(10) COLLATE utf8_unicode_ci DEFAULT '--', + price1 decimal(10,2) DEFAULT '0.00', + price2 decimal(10,2) DEFAULT '0.00', + price3 decimal(10,2) DEFAULT '0.00', + minPrice decimal(10,2) DEFAULT '0.00', + producer varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + INDEX (itemFK)) ENGINE = MEMORY; + + -- Compras + INSERT INTO tmp.inventory(itemFk,quantity) + SELECT b.itemFk, SUM(b.quantity) + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel tr ON tr.id = e.travelFk + WHERE tr.warehouseInFk = vWh + AND tr.landed BETWEEN vDateLastInventory + AND vDateYesterday + AND NOT isRaid + GROUP BY b.itemFk; + SELECT vDateLastInventory , vDateYesterday; + + -- Traslados + INSERT INTO tmp.inventory(itemFk, quantity) + SELECT itemFk, quantityOut + FROM ( + SELECT b.itemFk,- SUM(b.quantity) quantityOut + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel tr ON tr.id = e.travelFk + WHERE tr.warehouseOutFk = vWh + AND tr.shipped BETWEEN vDateLastInventory + AND vDateYesterday + AND NOT isRaid + GROUP BY b.itemFk + ) sub + ON DUPLICATE KEY UPDATE quantity = IFNULL(quantity, 0) + sub.quantityOut; + + -- Ventas + INSERT INTO tmp.inventory(itemFk,quantity) + SELECT itemFk, saleOut + FROM ( + SELECT s.itemFk, - SUM(s.quantity) saleOut + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + WHERE t.warehouseFk = vWh + AND t.shipped BETWEEN vDateLastInventory AND vDateYesterday + GROUP BY s.itemFk + ) sub + ON DUPLICATE KEY UPDATE quantity = IFNULL(quantity,0) + sub.saleOut; + + -- Actualiza valores de la ultima compra + UPDATE tmp.inventory inv + JOIN cache.last_buy lb ON lb.item_id = inv.itemFk AND lb.warehouse_id = vWh + JOIN buy b ON b.id = lb.buy_id + JOIN item i ON i.id = b.itemFk + LEFT JOIN producer p ON p.id = i.producerFk + SET inv.buyingValue = b.buyingValue, + inv.freightValue = b.freightValue, + inv.packing = b.packing, + inv.`grouping`= b.`grouping`, + inv.groupingMode = b.groupingMode, + inv.comissionValue = b.comissionValue, + inv.packageValue = b.packageValue, + inv.packageFk = b.packagingFk, + inv.price1 = b.price1, + inv.price2 = b.price2, + inv.price3 = b.price3, + inv.minPrice = b.minPrice, + inv.producer = p.name; + + INSERT INTO buy( itemFk, + quantity, + buyingValue, + freightValue, + packing, + `grouping`, + groupingMode, + comissionValue, + packageValue, + packagingFk, + price1, + price2, + price3, + minPrice, + entryFk) + SELECT itemFk, + GREATEST(quantity, 0), + buyingValue, + freightValue, + packing, + `grouping`, + groupingMode, + comissionValue, + packageValue, + packagingFk, + price1, + price2, + price3, + minPrice, + vEntryFk + FROM tmp.inventory; + + SELECT vWh, COUNT(*), util.VN_NOW() FROM tmp.inventory; + + -- Actualizamos el campo lastUsed de item + UPDATE item i + JOIN tmp.inventory i2 ON i2.itemFk = i.id + SET i.lastUsed = NOW() + WHERE i2.quantity; + + -- DROP TEMPORARY TABLE tmp.inventory; + + END LOOP; + + CLOSE cWarehouses; + + UPDATE config SET inventoried = vDate; + SET @isModeInventory := FALSE; + + DROP TEMPORARY TABLE IF EXISTS tmp.entryToDelete; + CREATE TEMPORARY TABLE tmp.entryToDelete + (INDEX(entryId) USING BTREE) ENGINE = MEMORY + SELECT e.id as entryId, + t.id as travelId + FROM travel t + JOIN `entry` e ON e.travelFk = t.id + WHERE e.supplierFk = vInventorySupplierFk + AND t.shipped <= util.VN_CURDATE() - INTERVAL 12 DAY + AND (DAY(t.shipped) <> 1 OR shipped < util.VN_CURDATE() - INTERVAL 12 DAY); + + DELETE e + FROM `entry` e + JOIN tmp.entryToDelete tmp ON tmp.entryId = e.id; + + DELETE IGNORE t + FROM travel t + JOIN tmp.entryToDelete tmp ON tmp.travelId = t.id; +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`inventory_repair`() +BEGIN + + DROP TEMPORARY TABLE IF EXISTS tmp.lastEntry; + CREATE TEMPORARY TABLE tmp.lastEntry + (PRIMARY KEY (buyFk)) + SELECT + i.id AS itemFk, + w.id AS warehouseFk, + w.name AS warehouse, + tr.landed, + b.id AS buyFk, + b.entryFk, + b.isIgnored, + b.price2, + b.price3, + b.stickers, + b.packing, + b.grouping, + b.groupingMode, + b.weight, + i.stems, + b.quantity, + b.buyingValue, + b.packagingFk , + s.id AS supplierFk, + s.name AS supplier + FROM itemType it + RIGHT JOIN (entry e + LEFT JOIN supplier s ON s.id = e.supplierFk + RIGHT JOIN buy b ON b.entryFk = e.id + LEFT JOIN item i ON i.id = b.itemFk + LEFT JOIN ink ON ink.id = i.inkFk + LEFT JOIN travel tr ON tr.id = e.travelFk + LEFT JOIN warehouse w ON w.id = tr.warehouseInFk + LEFT JOIN origin o ON o.id = i.originFk + ) ON it.id = i.typeFk + LEFT JOIN edi.ekt ek ON b.ektFk = ek.id + WHERE (b.packagingFk = "--" OR b.price2 = 0 OR b.packing = 0 OR b.buyingValue = 0) AND tr.landed > util.firstDayOfMonth(TIMESTAMPADD(MONTH,-1,util.VN_CURDATE())) AND s.name = 'INVENTARIO'; + + DROP TEMPORARY TABLE IF EXISTS tmp.lastEntryOk; + CREATE TEMPORARY TABLE tmp.lastEntryOk + (PRIMARY KEY (buyFk)) + SELECT + i.id AS itemFk, + w.id AS warehouseFk, + w.name AS warehouse, + tr.landed, + b.id AS buyFk, + b.entryFk, + b.isIgnored, + b.price2, + b.price3, + b.stickers, + b.packing, + b.grouping, + b.groupingMode, + b.weight, + i.stems, + b.quantity, + b.buyingValue, + b.packagingFk, + s.id AS supplierFk, + s.name AS supplier + FROM itemType it + RIGHT JOIN (entry e + LEFT JOIN supplier s ON s.id = e.supplierFk + RIGHT JOIN buy b ON b.entryFk = e.id + LEFT JOIN item i ON i.id = b.itemFk + LEFT JOIN ink ON ink.id = i.inkFk + LEFT JOIN travel tr ON tr.id = e.travelFk + LEFT JOIN warehouse w ON w.id = tr.warehouseInFk + LEFT JOIN origin o ON o.id = i.originFk + ) ON it.id = i.typeFk + LEFT JOIN edi.ekt ek ON b.ektFk = ek.id + WHERE b.packagingFk != "--" AND b.price2 != 0 AND b.packing != 0 AND b.buyingValue > 0 AND tr.landed > util.firstDayOfMonth(TIMESTAMPADD(MONTH,-2,util.VN_CURDATE())) + ORDER BY tr.landed DESC; + + DROP TEMPORARY TABLE IF EXISTS tmp.lastEntryOkGroup; + CREATE TEMPORARY TABLE tmp.lastEntryOkGroup + (INDEX (warehouseFk,itemFk)) + SELECT * + FROM tmp.lastEntryOk tmp + GROUP BY tmp.itemFk,tmp.warehouseFk; + + UPDATE buy b + JOIN tmp.lastEntry lt ON lt.buyFk = b.id + JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk + SET b.packagingFk = eo.packagingFk WHERE b.packagingFk = "--"; + + UPDATE buy b + JOIN tmp.lastEntry lt ON lt.buyFk = b.id + JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk + SET b.price2 = eo.price2 WHERE b.price2 = 0 ; + + UPDATE buy b + JOIN tmp.lastEntry lt ON lt.buyFk = b.id + JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk + SET b.packing = eo.packing WHERE b.packing = 0; + + UPDATE buy b + JOIN tmp.lastEntry lt ON lt.buyFk = b.id + JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk + SET b.buyingValue = eo.buyingValue WHERE b.buyingValue = 0; + + DROP TEMPORARY TABLE tmp.lastEntry; + DROP TEMPORARY TABLE tmp.lastEntryOk; + DROP TEMPORARY TABLE tmp.lastEntryOkGroup; +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 36400b0d7..bd5bed897 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -1456,7 +1456,7 @@ INSERT INTO `bs`.`waste`(`buyer`, `year`, `week`, `family`, `itemFk`, `itemTypeF ('HankPym', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 'Miscellaneous Accessories', 6, 1, '186', '0', '0.0'), ('HankPym', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 'Adhesives', 7, 1, '277', '0', '0.0'); -INSERT INTO `vn`.`buy`(`id`,`entryFk`,`itemFk`,`buyingValue`,`quantity`,`packageFk`,`stickers`,`freightValue`,`packageValue`,`comissionValue`,`packing`,`grouping`,`groupingMode`,`location`,`price1`,`price2`,`price3`, `printedStickers`,`isChecked`,`isIgnored`,`weight`, `created`) +INSERT INTO `vn`.`buy`(`id`,`entryFk`,`itemFk`,`buyingValue`,`quantity`,`packagingFk`,`stickers`,`freightValue`,`packageValue`,`comissionValue`,`packing`,`grouping`,`groupingMode`,`location`,`price1`,`price2`,`price3`, `printedStickers`,`isChecked`,`isIgnored`,`weight`, `created`) VALUES (1, 1, 1, 50, 5000, 4, 1, 1.500, 1.500, 0.000, 1, 1, 1, NULL, 0.00, 99.6, 99.4, 0, 1, 0, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH)), (2, 2, 1, 50, 100, 4, 1, 1.500, 1.500, 0.000, 1, 1, 1, NULL, 0.00, 99.6, 99.4, 0, 1, 0, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH)), diff --git a/e2e/helpers/selectors.js b/e2e/helpers/selectors.js index 1b18eb866..5c0caffe4 100644 --- a/e2e/helpers/selectors.js +++ b/e2e/helpers/selectors.js @@ -1193,7 +1193,7 @@ export default { secondBuyPacking: 'vn-entry-buy-index tbody:nth-child(3) > tr:nth-child(1) vn-input-number[ng-model="buy.packing"]', secondBuyWeight: 'vn-entry-buy-index tbody:nth-child(3) > tr:nth-child(1) vn-input-number[ng-model="buy.weight"]', secondBuyStickers: 'vn-entry-buy-index tbody:nth-child(3) > tr:nth-child(1) vn-input-number[ng-model="buy.stickers"]', - secondBuyPackage: 'vn-entry-buy-index tbody:nth-child(3) > tr:nth-child(1) vn-autocomplete[ng-model="buy.packageFk"]', + secondBuyPackage: 'vn-entry-buy-index tbody:nth-child(3) > tr:nth-child(1) vn-autocomplete[ng-model="buy.packagingFk"]', secondBuyQuantity: 'vn-entry-buy-index tbody:nth-child(3) > tr:nth-child(1) vn-input-number[ng-model="buy.quantity"]', secondBuyItem: 'vn-entry-buy-index tbody:nth-child(3) > tr:nth-child(1) vn-autocomplete[ng-model="buy.itemFk"]', importButton: 'vn-entry-buy-index vn-icon[icon="publish"]', diff --git a/e2e/paths/13-supplier/03_fiscal_data.spec.js b/e2e/paths/13-supplier/03_fiscal_data.spec.js index 891b769c9..96977e708 100644 --- a/e2e/paths/13-supplier/03_fiscal_data.spec.js +++ b/e2e/paths/13-supplier/03_fiscal_data.spec.js @@ -1,20 +1,5 @@ import getBrowser from '../../helpers/puppeteer'; -const $ = { - saveButton: 'vn-supplier-fiscal-data button[type="submit"]', -}; -const $inputs = { - province: 'vn-supplier-fiscal-data [name="province"]', - country: 'vn-supplier-fiscal-data [name="country"]', - postcode: 'vn-supplier-fiscal-data [name="postcode"]', - city: 'vn-supplier-fiscal-data [name="city"]', - socialName: 'vn-supplier-fiscal-data [name="socialName"]', - taxNumber: 'vn-supplier-fiscal-data [name="taxNumber"]', - account: 'vn-supplier-fiscal-data [name="account"]', - sageWithholding: 'vn-supplier-fiscal-data [ng-model="$ctrl.supplier.sageWithholdingFk"]', - sageTaxType: 'vn-supplier-fiscal-data [ng-model="$ctrl.supplier.sageTaxTypeFk"]' -}; - describe('Supplier fiscal data path', () => { let browser; let page; @@ -30,7 +15,7 @@ describe('Supplier fiscal data path', () => { await browser.close(); }); - it('should attempt to edit the fiscal data and check data is saved', async() => { + it('should attempt to edit the fiscal data and check data iss saved', async() => { await page.accessToSection('supplier.card.fiscalData'); const form = 'vn-supplier-fiscal-data form'; @@ -40,16 +25,16 @@ describe('Supplier fiscal data path', () => { postcode: null, city: 'Valencia', socialName: 'Farmer King SL', - taxNumber: 'Wrong tax number', + taxNumber: '12345678Z', account: '0123456789', sageWithholding: 'retencion estimacion objetiva', sageTaxType: 'operaciones no sujetas' }; - const errorMessage = await page.sendForm(form, values); - const message = await page.sendForm(form, { - taxNumber: '12345678Z' + const errorMessage = await page.sendForm(form, { + taxNumber: 'Wrong tax number' }); + const message = await page.sendForm(form, values); await page.reloadSection('supplier.card.fiscalData'); const formValues = await page.fetchForm(form, Object.keys(values)); diff --git a/modules/entry/back/locale/buy/en.yml b/modules/entry/back/locale/buy/en.yml index 2db7c7be5..949aa8ed0 100644 --- a/modules/entry/back/locale/buy/en.yml +++ b/modules/entry/back/locale/buy/en.yml @@ -15,4 +15,4 @@ columns: weight: weight entryFk: entry itemFk: item - packageFk: package + packagingFk: package diff --git a/modules/entry/back/locale/buy/es.yml b/modules/entry/back/locale/buy/es.yml index 666bf7640..2aa7688eb 100644 --- a/modules/entry/back/locale/buy/es.yml +++ b/modules/entry/back/locale/buy/es.yml @@ -15,4 +15,4 @@ columns: weight: peso entryFk: entrada itemFk: artículo - packageFk: paquete + packagingFk: paquete diff --git a/modules/entry/back/methods/entry/addFromBuy.js b/modules/entry/back/methods/entry/addFromBuy.js index 82645b166..307c04b97 100644 --- a/modules/entry/back/methods/entry/addFromBuy.js +++ b/modules/entry/back/methods/entry/addFromBuy.js @@ -80,7 +80,7 @@ module.exports = Self => { comissionValue: buyUltimate.comissionValue, packageValue: buyUltimate.packageValue, location: buyUltimate.location, - packageFk: buyUltimate.packageFk, + packagingFk: buyUltimate.packagingFk, price1: buyUltimate.price1, price2: buyUltimate.price2, price3: buyUltimate.price3, diff --git a/modules/entry/back/methods/entry/getBuys.js b/modules/entry/back/methods/entry/getBuys.js index ebb271df1..90c1bb9d0 100644 --- a/modules/entry/back/methods/entry/getBuys.js +++ b/modules/entry/back/methods/entry/getBuys.js @@ -44,7 +44,7 @@ module.exports = Self => { 'grouping', 'groupingMode', 'quantity', - 'packageFk', + 'packagingFk', 'weight', 'buyingValue', 'price2', diff --git a/modules/entry/back/methods/entry/importBuys.js b/modules/entry/back/methods/entry/importBuys.js index 1e6f01a5e..812775a1b 100644 --- a/modules/entry/back/methods/entry/importBuys.js +++ b/modules/entry/back/methods/entry/importBuys.js @@ -108,7 +108,7 @@ module.exports = Self => { packing: buy.packing, grouping: buy.grouping, buyingValue: buy.buyingValue, - packageFk: buy.packageFk, + packagingFk: buy.packagingFk, groupingMode: lastBuy.groupingMode, weight: lastBuy.weight }); diff --git a/modules/entry/back/methods/entry/importBuysPreview.js b/modules/entry/back/methods/entry/importBuysPreview.js index 730ecab0a..de8fa732d 100644 --- a/modules/entry/back/methods/entry/importBuysPreview.js +++ b/modules/entry/back/methods/entry/importBuysPreview.js @@ -39,7 +39,7 @@ module.exports = Self => { }, myOptions); if (packaging) - buy.packageFk = packaging.id; + buy.packagingFk = packaging.id; const reference = await models.ItemMatchProperties.findOne({ fields: ['itemFk'], diff --git a/modules/entry/back/methods/entry/latestBuysFilter.js b/modules/entry/back/methods/entry/latestBuysFilter.js index 30d47a2a3..dbf7d2b17 100644 --- a/modules/entry/back/methods/entry/latestBuysFilter.js +++ b/modules/entry/back/methods/entry/latestBuysFilter.js @@ -153,64 +153,63 @@ module.exports = Self => { const date = Date.vnNew(); date.setHours(0, 0, 0, 0); stmt = new ParameterizedSQL(` - SELECT - i.image, - i.id AS itemFk, - i.size, - i.weightByPiece, - it.code, - i.typeFk, - i.family, - i.isActive, - i.minPrice, - i.description, - i.name, - i.subName, - i.packingOut, - i.tag5, - i.value5, - i.tag6, - i.value6, - i.tag7, - i.value7, - i.tag8, - i.value8, - i.tag9, - i.value9, - i.tag10, - i.value10, - t.name AS type, - intr.description AS intrastat, - ori.code AS origin, - b.entryFk, - b.id, - b.quantity, - b.buyingValue, - b.freightValue, - b.isIgnored, - b.packing, - b.grouping, - b.groupingMode, - b.comissionValue, - b.packageValue, - b.price2, - b.price3, - b.ektFk, - b.weight, - b.packageFk, - lb.landing - FROM cache.last_buy lb - LEFT JOIN cache.visible v ON v.item_id = lb.item_id - AND v.calc_id = @calc_id - JOIN item i ON i.id = lb.item_id - JOIN itemType it ON it.id = i.typeFk AND lb.warehouse_id = ? - JOIN buy b ON b.id = lb.buy_id - LEFT JOIN itemCategory ic ON ic.id = it.categoryFk - LEFT JOIN itemType t ON t.id = i.typeFk - LEFT JOIN intrastat intr ON intr.id = i.intrastatFk - LEFT JOIN origin ori ON ori.id = i.originFk - LEFT JOIN entry e ON e.id = b.entryFk AND e.created >= DATE_SUB(? ,INTERVAL 1 YEAR) - LEFT JOIN supplier s ON s.id = e.supplierFk` + SELECT i.image, + i.id AS itemFk, + i.size, + i.weightByPiece, + it.code, + i.typeFk, + i.family, + i.isActive, + i.minPrice, + i.description, + i.name, + i.subName, + i.packingOut, + i.tag5, + i.value5, + i.tag6, + i.value6, + i.tag7, + i.value7, + i.tag8, + i.value8, + i.tag9, + i.value9, + i.tag10, + i.value10, + t.name AS type, + intr.description AS intrastat, + ori.code AS origin, + b.entryFk, + b.id, + b.quantity, + b.buyingValue, + b.freightValue, + b.isIgnored, + b.packing, + b.grouping, + b.groupingMode, + b.comissionValue, + b.packageValue, + b.price2, + b.price3, + b.ektFk, + b.weight, + b.packagingFk, + lb.landing + FROM cache.last_buy lb + LEFT JOIN cache.visible v ON v.item_id = lb.item_id + AND v.calc_id = @calc_id + JOIN item i ON i.id = lb.item_id + JOIN itemType it ON it.id = i.typeFk AND lb.warehouse_id = ? + JOIN buy b ON b.id = lb.buy_id + LEFT JOIN itemCategory ic ON ic.id = it.categoryFk + LEFT JOIN itemType t ON t.id = i.typeFk + LEFT JOIN intrastat intr ON intr.id = i.intrastatFk + LEFT JOIN origin ori ON ori.id = i.originFk + LEFT JOIN entry e ON e.id = b.entryFk AND e.created >= DATE_SUB(? ,INTERVAL 1 YEAR) + LEFT JOIN supplier s ON s.id = e.supplierFk` , [userConfig.warehouseFk, date]); if (ctx.args.tags) { diff --git a/modules/entry/back/methods/entry/specs/importBuys.spec.js b/modules/entry/back/methods/entry/specs/importBuys.spec.js index 4f9204c6a..a352294b9 100644 --- a/modules/entry/back/methods/entry/specs/importBuys.spec.js +++ b/modules/entry/back/methods/entry/specs/importBuys.spec.js @@ -33,7 +33,7 @@ describe('entry import()', () => { packing: 1, size: 1, volume: 1200, - packageFk: '94' + packagingFk: '94' }, { itemFk: 4, @@ -43,7 +43,7 @@ describe('entry import()', () => { packing: 1, size: 25, volume: 1125, - packageFk: '94' + packagingFk: '94' } ] } diff --git a/modules/entry/back/methods/entry/specs/importBuysPreview.spec.js b/modules/entry/back/methods/entry/specs/importBuysPreview.spec.js index 41971a64c..c860e228e 100644 --- a/modules/entry/back/methods/entry/specs/importBuysPreview.spec.js +++ b/modules/entry/back/methods/entry/specs/importBuysPreview.spec.js @@ -10,12 +10,12 @@ describe('entry importBuysPreview()', () => { }); }); - it('should return the buys with the calculated packageFk', async() => { + it('should return the buys with the calculated packagingFk', async() => { const tx = await models.Entry.beginTransaction({}); const options = {transaction: tx}; try { - const expectedPackageFk = '3'; + const expectedPackagingFk = '3'; const buys = [ { itemFk: 1, @@ -39,7 +39,7 @@ describe('entry importBuysPreview()', () => { const randomIndex = Math.floor(Math.random() * result.length); const buy = result[randomIndex]; - expect(buy.packageFk).toEqual(expectedPackageFk); + expect(buy.packagingFk).toEqual(expectedPackagingFk); await tx.rollback(); } catch (e) { diff --git a/modules/entry/back/models/buy.json b/modules/entry/back/models/buy.json index af205533f..30379eaf6 100644 --- a/modules/entry/back/models/buy.json +++ b/modules/entry/back/models/buy.json @@ -103,7 +103,7 @@ "package": { "type": "belongsTo", "model": "Packaging", - "foreignKey": "packageFk" + "foreignKey": "packagingFk" }, "worker": { "type": "belongsTo", diff --git a/modules/entry/front/buy/import/index.html b/modules/entry/front/buy/import/index.html index ccb1a5dac..28396434c 100644 --- a/modules/entry/front/buy/import/index.html +++ b/modules/entry/front/buy/import/index.html @@ -83,14 +83,14 @@ {{::buy.packing | dashIfEmpty}} {{::buy.grouping | dashIfEmpty}} {{::buy.buyingValue | currency: 'EUR':2}} - + + ng-model="buy.packagingFk"> diff --git a/modules/entry/front/buy/index/index.html b/modules/entry/front/buy/index/index.html index 28fdabdb4..203d6c522 100644 --- a/modules/entry/front/buy/index/index.html +++ b/modules/entry/front/buy/index/index.html @@ -88,12 +88,12 @@ diff --git a/modules/entry/front/buy/index/index.js b/modules/entry/front/buy/index/index.js index 649e69286..c991b745b 100644 --- a/modules/entry/front/buy/index/index.js +++ b/modules/entry/front/buy/index/index.js @@ -4,7 +4,7 @@ import Section from 'salix/components/section'; export default class Controller extends Section { saveBuy(buy) { - const missingData = !buy.itemFk || !buy.quantity || !buy.packageFk; + const missingData = !buy.itemFk || !buy.quantity || !buy.packagingFk; if (missingData) return; let options; diff --git a/modules/entry/front/buy/index/index.spec.js b/modules/entry/front/buy/index/index.spec.js index 0e221302c..b9d5fab51 100644 --- a/modules/entry/front/buy/index/index.spec.js +++ b/modules/entry/front/buy/index/index.spec.js @@ -17,7 +17,7 @@ describe('Entry buy', () => { describe('saveBuy()', () => { it(`should call the buys patch route if the received buy has an ID`, () => { - const buy = {id: 1, itemFk: 1, quantity: 1, packageFk: 1}; + const buy = {id: 1, itemFk: 1, quantity: 1, packagingFk: 1}; const query = `Buys/${buy.id}`; diff --git a/modules/entry/front/latest-buys/index.html b/modules/entry/front/latest-buys/index.html index a2cf62da2..16e039cf0 100644 --- a/modules/entry/front/latest-buys/index.html +++ b/modules/entry/front/latest-buys/index.html @@ -104,7 +104,7 @@ Weight - + Package @@ -207,7 +207,7 @@ {{::buy.minPrice | currency: 'EUR':3}} {{::buy.ektFk | dashIfEmpty}} {{::buy.weight}} - {{::buy.packageFk}} + {{::buy.packagingFk}} {{::buy.packingOut}} {{::buy.landing | date: 'dd/MM/yyyy'}} diff --git a/modules/entry/front/latest-buys/index.js b/modules/entry/front/latest-buys/index.js index d9065193e..292c5b805 100644 --- a/modules/entry/front/latest-buys/index.js +++ b/modules/entry/front/latest-buys/index.js @@ -48,7 +48,7 @@ export default class Controller extends Section { } }, { - field: 'packageFk', + field: 'packagingFk', autocomplete: { url: 'Packagings', showField: 'id' @@ -133,7 +133,7 @@ export default class Controller extends Section { case 'price3': case 'ektFk': case 'weight': - case 'packageFk': + case 'packagingFk': return {[`b.${param}`]: value}; } } diff --git a/modules/entry/front/summary/index.html b/modules/entry/front/summary/index.html index d5d3ebf1e..655dcd66f 100644 --- a/modules/entry/front/summary/index.html +++ b/modules/entry/front/summary/index.html @@ -105,7 +105,7 @@ Quantity Stickers - Package + Package Weight Packing Grouping @@ -118,7 +118,7 @@ {{::line.quantity}} {{::line.stickers | dashIfEmpty}} - {{::line.packageFk | dashIfEmpty}} + {{::line.packagingFk | dashIfEmpty}} {{::line.weight}} diff --git a/modules/item/back/methods/item/lastEntriesFilter.js b/modules/item/back/methods/item/lastEntriesFilter.js index 83a8fe7a2..5aafbb4f6 100644 --- a/modules/item/back/methods/item/lastEntriesFilter.js +++ b/modules/item/back/methods/item/lastEntriesFilter.js @@ -29,44 +29,44 @@ module.exports = Self => { Object.assign(myOptions, options); const stmt = new ParameterizedSQL( - `SELECT - w.id AS warehouseFk, - w.name AS warehouse, - tr.landed, - b.id AS buyFk, - b.entryFk, - b.isIgnored, - b.price2, - b.price3, - b.stickers, - b.packing, - b.grouping, - b.groupingMode, - b.weight, - i.stems, - b.quantity, - b.buyingValue + - b.freightValue + - b.comissionValue + - b.packageValue AS cost, - b.buyingValue, - b.freightValue, - b.comissionValue, - b.packageValue, - b.packageFk , - s.id AS supplierFk, - s.name AS supplier - FROM itemType it - RIGHT JOIN (entry e - LEFT JOIN supplier s ON s.id = e.supplierFk - RIGHT JOIN buy b ON b.entryFk = e.id - LEFT JOIN item i ON i.id = b.itemFk - LEFT JOIN ink ON ink.id = i.inkFk - LEFT JOIN travel tr ON tr.id = e.travelFk - LEFT JOIN warehouse w ON w.id = tr.warehouseInFk - LEFT JOIN origin o ON o.id = i.originFk - ) ON it.id = i.typeFk - LEFT JOIN edi.ekt ek ON b.ektFk = ek.id`); + `SELECT w.id AS warehouseFk, + w.name AS warehouse, + tr.landed, + b.id AS buyFk, + b.entryFk, + b.isIgnored, + b.price2, + b.price3, + b.stickers, + b.packing, + b.grouping, + b.groupingMode, + b.weight, + i.stems, + b.quantity, + b.buyingValue + + b.freightValue + + b.comissionValue + + b.packageValue AS cost, + b.buyingValue, + b.freightValue, + b.comissionValue, + b.packageValue, + b.packagingFk , + s.id AS supplierFk, + s.name AS supplier + FROM itemType it + RIGHT JOIN (entry e + LEFT JOIN supplier s ON s.id = e.supplierFk + RIGHT JOIN buy b ON b.entryFk = e.id + LEFT JOIN item i ON i.id = b.itemFk + LEFT JOIN ink ON ink.id = i.inkFk + LEFT JOIN travel tr ON tr.id = e.travelFk + LEFT JOIN warehouse w ON w.id = tr.warehouseInFk + LEFT JOIN origin o ON o.id = i.originFk + ) ON it.id = i.typeFk + LEFT JOIN edi.ekt ek ON b.ektFk = ek.id` + ); stmt.merge(conn.makeSuffix(filter)); return conn.executeStmt(stmt, myOptions); diff --git a/modules/item/front/last-entries/index.html b/modules/item/front/last-entries/index.html index 609cdb7fa..429955ef5 100644 --- a/modules/item/front/last-entries/index.html +++ b/modules/item/front/last-entries/index.html @@ -45,7 +45,7 @@ Quantity Cost Kg. - Cube + Cube Provider @@ -94,7 +94,7 @@ {{::entry.weight | dashIfEmpty}} - {{::entry.packageFk | dashIfEmpty}} + {{::entry.packagingFk | dashIfEmpty}} {{::entry.supplier | dashIfEmpty}} diff --git a/modules/item/front/last-entries/index.js b/modules/item/front/last-entries/index.js index 0c6804838..31616f8a7 100644 --- a/modules/item/front/last-entries/index.js +++ b/modules/item/front/last-entries/index.js @@ -71,7 +71,7 @@ class Controller extends Section { switch (param) { case 'id': case 'quantity': - case 'packageFk': + case 'packagingFk': return {[`b.${param}`]: value}; case 'supplierFk': return {[`s.id`]: value}; diff --git a/modules/travel/back/methods/travel/extraCommunityFilter.js b/modules/travel/back/methods/travel/extraCommunityFilter.js index 388ba52a1..488297318 100644 --- a/modules/travel/back/methods/travel/extraCommunityFilter.js +++ b/modules/travel/back/methods/travel/extraCommunityFilter.js @@ -132,12 +132,18 @@ module.exports = Self => { s.nickname AS cargoSupplierNickname, s.name AS supplierName, CAST(SUM(b.weight * b.stickers) as DECIMAL(10,0)) as loadedKg, - CAST(SUM(vc.aerealVolumetricDensity * b.stickers * IF(pkg.volume, pkg.volume, pkg.width * pkg.depth * pkg.height) / 1000000) as DECIMAL(10,0)) as volumeKg + CAST( + SUM( + vc.aerealVolumetricDensity * + b.stickers * + IF(pkg.volume, pkg.volume, pkg.width * pkg.depth * pkg.height) / 1000000 + ) as DECIMAL(10,0) + ) as volumeKg FROM travel t LEFT JOIN supplier s ON s.id = t.cargoSupplierFk LEFT JOIN entry e ON e.travelFk = t.id LEFT JOIN buy b ON b.entryFk = e.id - LEFT JOIN packaging pkg ON pkg.id = b.packageFk + LEFT JOIN packaging pkg ON pkg.id = b.packagingFk LEFT JOIN item i ON i.id = b.itemFk LEFT JOIN itemType it ON it.id = i.typeFk JOIN warehouse w ON w.id = t.warehouseInFk @@ -169,11 +175,17 @@ module.exports = Self => { e.evaNotes, e.invoiceAmount, CAST(SUM(b.weight * b.stickers) AS DECIMAL(10,0)) as loadedkg, - CAST(SUM(vc.aerealVolumetricDensity * b.stickers * IF(pkg.volume, pkg.volume, pkg.width * pkg.depth * pkg.height) / 1000000) AS DECIMAL(10,0)) as volumeKg + CAST( + SUM( + vc.aerealVolumetricDensity * + b.stickers * + IF(pkg.volume, pkg.volume, pkg.width * pkg.depth * pkg.height) / 1000000 + ) AS DECIMAL(10,0) + ) as volumeKg FROM tmp.travel tr JOIN entry e ON e.travelFk = tr.id JOIN buy b ON b.entryFk = e.id - JOIN packaging pkg ON pkg.id = b.packageFk + JOIN packaging pkg ON pkg.id = b.packagingFk JOIN item i ON i.id = b.itemFk JOIN itemType it ON it.id = i.typeFk JOIN supplier s ON s.id = e.supplierFk diff --git a/modules/travel/back/methods/travel/getEntries.js b/modules/travel/back/methods/travel/getEntries.js index 71bb0d8fb..50088ccfa 100644 --- a/modules/travel/back/methods/travel/getEntries.js +++ b/modules/travel/back/methods/travel/getEntries.js @@ -47,7 +47,7 @@ module.exports = Self => { LEFT JOIN vn.buy b ON b.entryFk = e.id LEFT JOIN vn.supplier s ON e.supplierFk = s.id JOIN vn.item i ON i.id = b.itemFk - LEFT JOIN vn.packaging p ON p.id = b.packageFk + LEFT JOIN vn.packaging p ON p.id = b.packagingFk JOIN vn.packaging pcc ON pcc.id = 'cc' JOIN vn.packaging ppallet ON ppallet.id = 'pallet 100' JOIN vn.packagingConfig pconfig From ed1d8ca94f4ef6ec8a6f78eab0f30c19c7895f59 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Fri, 22 Sep 2023 12:29:56 +0200 Subject: [PATCH 132/427] refs #5134 feat: models --- .../models/item-shelving-placement-supply.json | 6 ++++++ modules/item/back/models/item-shelving.json | 6 ++++++ modules/shelving/back/models/shelving.json | 3 +-- modules/ticket/back/model-config.json | 6 ++++++ modules/ticket/back/models/expeditionPallet.json | 16 ++++++++++++++++ modules/ticket/back/models/expeditionScan.json | 16 ++++++++++++++++ 6 files changed, 51 insertions(+), 2 deletions(-) create mode 100644 modules/ticket/back/models/expeditionPallet.json create mode 100644 modules/ticket/back/models/expeditionScan.json diff --git a/modules/item/back/models/item-shelving-placement-supply.json b/modules/item/back/models/item-shelving-placement-supply.json index a54013e05..18d0a8d56 100644 --- a/modules/item/back/models/item-shelving-placement-supply.json +++ b/modules/item/back/models/item-shelving-placement-supply.json @@ -26,11 +26,17 @@ "shelving": { "type": "string" }, + "subName": { + "type": "string" + }, "packing": { "type": "number" }, "stock": { "type": "number" + }, + "size": { + "type": "number" } } } \ No newline at end of file diff --git a/modules/item/back/models/item-shelving.json b/modules/item/back/models/item-shelving.json index 8628bfeee..7f82f48b3 100644 --- a/modules/item/back/models/item-shelving.json +++ b/modules/item/back/models/item-shelving.json @@ -20,10 +20,16 @@ }, "created": { "type": "date" + }, + "grouping": { + "type": "number" }, "isChecked": { "type": "boolean" }, + "packing": { + "type": "number" + }, "visible": { "type": "number" }, diff --git a/modules/shelving/back/models/shelving.json b/modules/shelving/back/models/shelving.json index 5f60318a5..5459e29fd 100644 --- a/modules/shelving/back/models/shelving.json +++ b/modules/shelving/back/models/shelving.json @@ -9,12 +9,11 @@ "properties": { "id": { "type": "number", - "id": true, "description": "Identifier" }, "code": { "type": "string", - "required": true + "id": true }, "parkingFk": { "type": "number" diff --git a/modules/ticket/back/model-config.json b/modules/ticket/back/model-config.json index e90d0409f..247e18d01 100644 --- a/modules/ticket/back/model-config.json +++ b/modules/ticket/back/model-config.json @@ -17,6 +17,12 @@ "Expedition": { "dataSource": "vn" }, + "ExpeditionPallet": { + "dataSource": "vn" + }, + "ExpeditionScan": { + "dataSource": "vn" + }, "ExpeditionState": { "dataSource": "vn" }, diff --git a/modules/ticket/back/models/expeditionPallet.json b/modules/ticket/back/models/expeditionPallet.json new file mode 100644 index 000000000..2c56a65e0 --- /dev/null +++ b/modules/ticket/back/models/expeditionPallet.json @@ -0,0 +1,16 @@ +{ + "name": "ExpeditionPallet", + "options": { + "mysql": { + "table": "expeditionPallet" + } + }, + "acls": [{ + "accessType": "WRITE", + "principalType": "ROLE", + "principalId": "production", + "permission": "ALLOW" + }] + + } + diff --git a/modules/ticket/back/models/expeditionScan.json b/modules/ticket/back/models/expeditionScan.json new file mode 100644 index 000000000..f43ad0539 --- /dev/null +++ b/modules/ticket/back/models/expeditionScan.json @@ -0,0 +1,16 @@ +{ + "name": "ExpeditionScan", + "options": { + "mysql": { + "table": "expeditionScan" + } + }, + "acls": [{ + "accessType": "WRITE", + "principalType": "ROLE", + "principalId": "production", + "permission": "ALLOW" + }] + + } + From 6fe52ba3e8efbe3203ad2f95250f54d8b944d341 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 22 Sep 2023 12:48:54 +0200 Subject: [PATCH 133/427] ref #6246 check sales and update test --- modules/ticket/back/methods/ticket/setDeleted.js | 2 +- modules/ticket/back/methods/ticket/specs/merge.spec.js | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/ticket/back/methods/ticket/setDeleted.js b/modules/ticket/back/methods/ticket/setDeleted.js index 2f8c402da..fcd9972fe 100644 --- a/modules/ticket/back/methods/ticket/setDeleted.js +++ b/modules/ticket/back/methods/ticket/setDeleted.js @@ -118,7 +118,7 @@ module.exports = Self => { // Send notification to salesPerson const salesPersonUser = ticket.client().salesPersonUser(); - if (salesPersonUser) { + if (salesPersonUser && sales.length) { const origin = ctx.req.headers.origin; const message = $t(`I have deleted the ticket id`, { id: id, diff --git a/modules/ticket/back/methods/ticket/specs/merge.spec.js b/modules/ticket/back/methods/ticket/specs/merge.spec.js index 3be6b8bac..560dac7ee 100644 --- a/modules/ticket/back/methods/ticket/specs/merge.spec.js +++ b/modules/ticket/back/methods/ticket/specs/merge.spec.js @@ -34,7 +34,7 @@ describe('ticket merge()', () => { return value; }; - it('should merge two tickets', async() => { + it('should merge a ticket', async() => { const tx = await models.Ticket.beginTransaction({}); try { @@ -49,7 +49,7 @@ describe('ticket merge()', () => { expect(deletedTicket.isDeleted).toEqual(true); expect(salesTicketFuture.length).toEqual(2); - expect(chatNotificationBeforeMerge.length).toEqual(chatNotificationAfterMerge.length - 2); + expect(chatNotificationBeforeMerge.length).toEqual(chatNotificationAfterMerge.length - 1); await tx.rollback(); } catch (e) { From cf36b10763f1681e8b9259b0b37efc3b1e52ab6d Mon Sep 17 00:00:00 2001 From: alexm Date: Fri, 22 Sep 2023 14:29:48 +0200 Subject: [PATCH 134/427] refs #4815 feat: add serialNumber in deviceLog --- db/dump/structure.sql | 10283 ++++++++++--------- modules/worker/back/models/device-log.json | 3 + 2 files changed, 5145 insertions(+), 5141 deletions(-) diff --git a/db/dump/structure.sql b/db/dump/structure.sql index 218d1c183..08df0541c 100644 --- a/db/dump/structure.sql +++ b/db/dump/structure.sql @@ -787,7 +787,7 @@ DELIMITER ;; FOR EACH ROW BEGIN SET NEW.editorFk = account.myUser_getId(); - + CALL user_checkName(NEW.`name`); IF NEW.nickname = '' THEN @@ -1018,7 +1018,7 @@ BEGIN SET vSignature = util.hmacSha2(256, CONCAT_WS('/', @userId, @userName), vKey); RETURN vSignature = @userSignature; END IF; - + RETURN FALSE; END ;; @@ -1047,7 +1047,7 @@ BEGIN * @return The user id */ DECLARE vUser INT DEFAULT NULL; - + IF myUser_checkLogin() THEN SET vUser = @userId; @@ -1055,7 +1055,7 @@ BEGIN SELECT id INTO vUser FROM user WHERE name = LEFT(USER(), INSTR(USER(), '@') - 1); END IF; - + RETURN vUser; END ;; DELIMITER ; @@ -1090,7 +1090,7 @@ BEGIN ELSE SET vUser = LEFT(USER(), INSTR(USER(), '@') - 1); END IF; - + RETURN vUser; END ;; DELIMITER ; @@ -1185,10 +1185,10 @@ BEGIN DECLARE vDigitChars TEXT DEFAULT '1234567890'; DECLARE vPunctChars TEXT DEFAULT '!$%&()=.'; - SELECT length, nAlpha, nUpper, nDigits, nPunct + SELECT length, nAlpha, nUpper, nDigits, nPunct INTO vMinLength, vMinAlpha, vMinUpper, vMinDigits, vMinPunct FROM userPassword; - WHILE LENGTH(vPwd) < vMinLength OR vAlpha < vMinAlpha + WHILE LENGTH(vPwd) < vMinLength OR vAlpha < vMinAlpha OR vUpper < vMinUpper OR vDigits < vMinDigits OR vPunct < vMinPunct DO SET vRandIndex = FLOOR((RAND() * 4) + 1); @@ -1263,7 +1263,7 @@ BEGIN DECLARE vRole VARCHAR(255); SELECT CONCAT(IF(r.hasLogin, c.rolePrefix, ''), r.name) INTO vRole - FROM role r + FROM role r JOIN user u ON u.role = r.id JOIN roleConfig c WHERE u.name = vUserName; @@ -1290,16 +1290,16 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `user_getNameFromId`(vSelf INT) RETUR BEGIN /** * Gets user name from it's id. - * + * * @param vSelf The user id * @return The user name */ DECLARE vName VARCHAR(30); - - SELECT `name` INTO vName - FROM user + + SELECT `name` INTO vName + FROM user WHERE id = vSelf; - + RETURN vName; END ;; DELIMITER ; @@ -1371,7 +1371,7 @@ BEGIN JOIN role r ON r.id = rr.inheritsFrom WHERE u.`name` = vUser AND r.id = vRoleId; - + RETURN vHasRole; END ;; DELIMITER ; @@ -1405,7 +1405,7 @@ BEGIN AND password = MD5(vPassword) AND active; - IF vAuthIsOk + IF vAuthIsOk THEN CALL myUser_loginWithName (vUserName); ELSE @@ -1466,7 +1466,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `myUser_loginWithName`(vUserName VAR BEGIN /** * Logs in using only the user name. This procedure is intended to be executed - * by users with a high level of privileges so that normal users should not have + * by users with a high level of privileges so that normal users should not have * execute permissions on it. * * @param vUserName The user name @@ -1502,7 +1502,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `myUser_logout`() BEGIN /** * Logouts the user. - */ + */ SET @userId = NULL; SET @userName = NULL; SET @userSignature = NULL; @@ -1600,9 +1600,9 @@ BEGIN SELECT COUNT(*) > 0 INTO vIsRoot FROM tmp.role t - JOIN role r ON r.id = t.id + JOIN role r ON r.id = t.id WHERE r.`name` = 'root'; - + IF vIsRoot THEN INSERT IGNORE INTO tmp.role (id) SELECT id FROM role; @@ -2321,7 +2321,7 @@ BEGIN IF vChr REGEXP '[[:alpha:]]' THEN SET vNAlpha = vNAlpha+1; - + IF vChr REGEXP '[A-Z]' THEN SET vNUpper = vNUpper+1; @@ -2792,7 +2792,7 @@ BEGIN IF NOT (NEW.`schema`REGEXP '^[0-9a-zA-Z_]+$') OR NOT (NEW.`procedure`REGEXP '^[0-9a-zA-Z_]+$') THEN CALL util.throw('ONLY_ALPHANUMERICS_ALLOWED'); - + END IF; END */;; @@ -2818,7 +2818,7 @@ BEGIN IF NOT (NEW.`schema`REGEXP '^[0-9a-zA-Z_]+$') OR NOT (NEW.`procedure`REGEXP '^[0-9a-zA-Z_]+$') THEN CALL util.throw('ONLY_ALPHANUMERICS_ALLOWED'); - + END IF; END */;; @@ -3341,11 +3341,11 @@ BEGIN DECLARE vTramo VARCHAR(20); DECLARE vHour INT; - + SET vHour = HOUR(vDateTime) ; - + SET vTramo = - CASE + CASE WHEN vHour BETWEEN 0 AND 14 THEN 'Mañana' WHEN vHour BETWEEN 15 AND 24 THEN 'Tarde' END ; @@ -3373,7 +3373,7 @@ BEGIN * Inserta en la tabla bancos_evolution los saldos acumulados de cada banco * * @param vStartingDate Fecha desde la cual se recalculan la tabla bs.bancos_evolution - */ + */ DECLARE vCurrentDate DATE; DECLARE vMaxDate DATE DEFAULT TIMESTAMPADD(MONTH, 7, util.VN_CURDATE()); IF IFNULL(vStartingDate,0) < TIMESTAMPADD(YEAR, -5, util.VN_CURDATE()) THEN @@ -3387,49 +3387,49 @@ BEGIN SELECT vCurrentDate, Id_Banco, deuda FROM bs.bancos_evolution WHERE Fecha = TIMESTAMPADD(DAY,-1,vCurrentDate); - + WHILE vCurrentDate < vMaxDate DO -- insertar solo el dia de ayer INSERT INTO bs.bancos_evolution(Fecha ,Id_Banco, saldo) - SELECT vCurrentDate, Id_Banco, SUM(saldo) + SELECT vCurrentDate, Id_Banco, SUM(saldo) FROM ( SELECT Id_Banco ,saldo FROM bs.bancos_evolution WHERE Fecha = TIMESTAMPADD(DAY,-1,vCurrentDate) -- los saldos acumulados del dia anterior UNION ALL - + SELECT c.Id_Banco, IFNULL(SUM(Entrada),0) - IFNULL(SUM(Salida),0) as saldo FROM vn2008.Cajas c JOIN vn2008.Bancos b using(Id_Banco) -- saldos de las cajas - JOIN vn.accountingType at2 ON at2.id = b.cash + JOIN vn.accountingType at2 ON at2.id = b.cash WHERE at2.code IN ('wireTransfer','fundingLine') AND Cajafecha = vCurrentDate AND (Serie = 'MB' OR at2.code = 'fundingLine') GROUP BY Id_Banco - )sub + )sub GROUP BY Id_Banco ON DUPLICATE KEY UPDATE saldo = saldo + VALUES(saldo); - + SET vCurrentDate = TIMESTAMPADD(DAY,1,vCurrentDate); END WHILE; - -- Ahora actualizamos la quilla + -- Ahora actualizamos la quilla UPDATE bs.bancos_evolution be JOIN ( SELECT bp.Id_Banco, - sum(bp.importe) as quilla, t.dated - FROM vn.time t + FROM vn.time t JOIN vn2008.Bancos_poliza bp ON t.dated between apertura AND IFNULL(cierre, t.dated) WHERE t.dated BETWEEN vStartingDate AND vMaxDate GROUP BY Id_Banco, t.dated ) sub ON be.Id_Banco = sub.Id_Banco AND sub.dated = be.Fecha - SET be.quilla = sub.quilla; + SET be.quilla = sub.quilla; -- pagos futuros no concilidados INSERT INTO bs.bancos_evolution(Fecha, Id_Banco, saldo) SELECT t.dated, p.id_banco, - importe - FROM vn.time t + FROM vn.time t join vn2008.pago p ON p.fecha <= t.dated WHERE t.dated BETWEEN util.VN_CURDATE() AND vMaxDate AND p.fecha BETWEEN util.VN_CURDATE() AND vMaxDate @@ -3439,7 +3439,7 @@ BEGIN -- cobros futuros INSERT INTO bs.bancos_evolution(Fecha, Id_Banco, saldo) SELECT t.dated, r.Id_Banco, SUM(Entregado) - FROM vn.time t + FROM vn.time t JOIN vn2008.Recibos r ON r.Fechacobro <= t.dated WHERE r.Fechacobro > util.VN_CURDATE() AND r.Fechacobro <= vMaxDate AND t.dated BETWEEN util.VN_CURDATE() AND vMaxDate @@ -3449,10 +3449,10 @@ BEGIN -- saldos de la tabla prevision INSERT INTO bs.bancos_evolution(Fecha, Id_Banco, saldo) SELECT t.dated, sp.Id_Banco, SUM(Importe) - FROM vn.time t + FROM vn.time t JOIN vn2008.Saldos_Prevision sp ON sp.Fecha <= t.dated JOIN vn2008.Bancos b ON sp.Id_Banco = b.Id_Banco - JOIN vn.accountingType at2 ON at2.id = b.cash + JOIN vn.accountingType at2 ON at2.id = b.cash WHERE at2.code IN ('wireTransfer','fundingLine') AND t.dated BETWEEN vStartingDate AND vMaxDate GROUP BY t.dated, sp.Id_Banco @@ -3466,12 +3466,12 @@ BEGIN -- Deuda UPDATE bs.bancos_evolution be JOIN vn2008.Bancos b using(Id_Banco) - JOIN vn.accountingType at2 ON at2.id = b.cash + JOIN vn.accountingType at2 ON at2.id = b.cash SET be.deuda = IF(at2.code = 'fundingLine', be.saldo_aux, 0) , be.saldo = IF(at2.code = 'fundingLine', 0, be.saldo_aux) WHERE Fecha >= vStartingDate; - -- Liquidez + -- Liquidez update bs.bancos_evolution set liquidez = saldo - quilla + deuda WHERE Fecha >= vStartingDate; -- Disponibilidad update bs.bancos_evolution set `disponibilidad ajena` = - quilla + deuda WHERE Fecha >= vStartingDate; @@ -3494,14 +3494,14 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `campaignComparative`(vDateFrom DATE, vDateTo DATE) BEGIN - SELECT - workerName, - id, - name, - CAST(SUM(previousAmmount) AS DECIMAL(10, 0)) AS previousAmmount, - CAST(SUM(currentAmmount) AS DECIMAL(10, 0)) AS currentAmmount + SELECT + workerName, + id, + name, + CAST(SUM(previousAmmount) AS DECIMAL(10, 0)) AS previousAmmount, + CAST(SUM(currentAmmount) AS DECIMAL(10, 0)) AS currentAmmount FROM ( - (SELECT + (SELECT CONCAT(w.firstname, ' ', w.lastName) AS workerName, c.id, c.name, @@ -3510,11 +3510,11 @@ BEGIN FROM bs.ventas v INNER JOIN vn.`client` c ON v.Id_Cliente = c.id INNER JOIN vn.worker w ON c.salesPersonFk = w.id - WHERE v.fecha BETWEEN DATE_ADD(vDateFrom, INTERVAL - 1 YEAR) + WHERE v.fecha BETWEEN DATE_ADD(vDateFrom, INTERVAL - 1 YEAR) AND DATE_ADD(vDateTo, INTERVAL - 1 YEAR) GROUP BY w.id, v.Id_Cliente) UNION ALL - (SELECT + (SELECT CONCAT(w.firstname, ' ', w.lastName) AS workerName, c.id, c.name, @@ -3548,21 +3548,21 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `carteras_add`() -BEGIN -/** - * Inserta en @bs.carteras. - */ - DELETE FROM bs.carteras - WHERE Año >= YEAR(util.VN_CURDATE()) - 1; - - INSERT INTO bs.carteras(Año,Mes,CodigoTrabajador,Peso) - SELECT t.year AS Año, t.month AS Mes, w.code AS CodigoTrabajador, SUM(v.importe) AS Peso - FROM vn.time t - JOIN bs.ventas v on t.dated = v.fecha - JOIN vn.client c on c.id = v.Id_Cliente - JOIN vn.worker w ON w.id = c.salesPersonFk - WHERE t.year >= YEAR(util.VN_CURDATE()) - 1 - GROUP BY w.code, t.year , t.month; +BEGIN +/** + * Inserta en @bs.carteras. + */ + DELETE FROM bs.carteras + WHERE Año >= YEAR(util.VN_CURDATE()) - 1; + + INSERT INTO bs.carteras(Año,Mes,CodigoTrabajador,Peso) + SELECT t.year AS Año, t.month AS Mes, w.code AS CodigoTrabajador, SUM(v.importe) AS Peso + FROM vn.time t + JOIN bs.ventas v on t.dated = v.fecha + JOIN vn.client c on c.id = v.Id_Cliente + JOIN vn.worker w ON w.id = c.salesPersonFk + WHERE t.year >= YEAR(util.VN_CURDATE()) - 1 + GROUP BY w.code, t.year , t.month; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -3594,24 +3594,24 @@ BEGIN DELETE FROM bs.clientNewBorn WHERE lastShipped < vOneYearAgo; - + DELETE FROM ventas WHERE fecha < vFourYearsAgo; - + DELETE FROM payMethodClient WHERE dated < vOneYearAgo; DELETE FROM payMethodClientEvolution WHERE dated < vFourYearsAgo; - DELETE FROM bs.salesByclientSalesPerson + DELETE FROM bs.salesByclientSalesPerson WHERE dated < vFourYearsAgo; - - DELETE FROM bs.m3 + + DELETE FROM bs.m3 WHERE fecha < vTwoYearAgo; DELETE FROM salesByItemTypeDay - WHERE dated < vThreeYearAgo; + WHERE dated < vThreeYearAgo; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -3710,16 +3710,16 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `clientNewBorn_recalc`() BLOCK1: BEGIN DECLARE vClientFk INT; - DECLARE vShipped DATE; + DECLARE vShipped DATE; DECLARE vPreviousShipped DATE; - DECLARE vDone boolean; - DECLARE cur cursor for - - SELECT clientFk, firstShipped - FROM bs.clientNewBorn; - - DECLARE continue HANDLER FOR NOT FOUND SET vDone = TRUE; - SET vDone := FALSE; + DECLARE vDone boolean; + DECLARE cur cursor for + + SELECT clientFk, firstShipped + FROM bs.clientNewBorn; + + DECLARE continue HANDLER FOR NOT FOUND SET vDone = TRUE; + SET vDone := FALSE; DELETE FROM bs.clientNewBorn WHERE isModified = FALSE; @@ -3731,7 +3731,7 @@ BLOCK1: BEGIN WHERE t.shipped BETWEEN TIMESTAMPADD(YEAR, -1, util.VN_CURDATE()) AND util.VN_CURDATE() AND cb.isModified is null GROUP BY c.id; OPEN cur; - + LOOP1: LOOP SET vDone := FALSE; FETCH cur INTO vClientFk, vShipped; @@ -3742,37 +3742,37 @@ BLOCK1: BEGIN END IF; BLOCK2: BEGIN - DECLARE vCurrentShipped DATE; - DECLARE vDone2 boolean; + DECLARE vCurrentShipped DATE; + DECLARE vDone2 boolean; DECLARE cur2 CURSOR FOR - SELECT shipped - FROM vn.ticket + SELECT shipped + FROM vn.ticket WHERE clientFk = vClientFk AND shipped <= util.VN_CURDATE() ORDER BY shipped DESC; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone2 = TRUE; SET vDone2 := FALSE; OPEN cur2; - + SET vPreviousShipped := vShipped; LOOP2: LOOP SET vDone2 := FALSE; FETCH cur2 INTO vCurrentShipped; - + IF DATEDIFF(vPreviousShipped,vCurrentShipped) > 365 THEN - UPDATE bs.clientNewBorn - SET firstShipped = vPreviousShipped + UPDATE bs.clientNewBorn + SET firstShipped = vPreviousShipped WHERE clientFk= vClientFk; - + CLOSE cur2; - LEAVE LOOP2; + LEAVE LOOP2; END IF; - + SET vPreviousShipped := vCurrentShipped; IF vDone2 THEN - UPDATE bs.clientNewBorn - SET firstShipped = vCurrentShipped + UPDATE bs.clientNewBorn + SET firstShipped = vCurrentShipped WHERE clientFk= vClientFk; CLOSE cur2; LEAVE LOOP2; @@ -3782,14 +3782,14 @@ BLOCK1: BEGIN END BLOCK2; END LOOP LOOP1; - UPDATE bs.clientNewBorn cnb + UPDATE bs.clientNewBorn cnb LEFT JOIN (SELECT DISTINCT t.clientFk FROM vn.ticket t JOIN vn.productionConfig pc WHERE t.shipped BETWEEN util.VN_CURDATE() + INTERVAL -(`notBuyingMonths`) MONTH AND util.VN_CURDATE() + INTERVAL -(`pc`.`rookieDays`) DAY) notRookie ON notRookie.clientFk = cnb.clientFk - SET cnb.isRookie = ISNULL(notRookie.clientFk); - + SET cnb.isRookie = ISNULL(notRookie.clientFk); + END BLOCK1 ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -3810,16 +3810,16 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `comercialesCompleto`(IN vWorker INT BEGIN DECLARE vAYearAgoStarted DATE DEFAULT DATE_FORMAT(TIMESTAMPADD(YEAR, - 1, vDate), '%Y-%m-01'); DECLARE vAYearAgoEnded DATE DEFAULT TIMESTAMPADD(YEAR, - 1, LAST_DAY(vDate)); - + CALL vn.worker_GetHierarchy(vWorker); - + INSERT IGNORE INTO tmp.workerHierarchyList (workerFk) SELECT wd2.workerFk FROM vn.workerDepartment wd2 WHERE wd2.workerFk = vWorker; - + -- Falta que en algunos casos solo tenga en cuenta los tipos afectados. - SELECT + SELECT c.Id_Cliente id_cliente, c.Cliente cliente, cr.recobro * 100 tarifa, @@ -3844,7 +3844,7 @@ BEGIN FROM vn2008.Clientes c LEFT JOIN - (SELECT g.Id_Cliente, CAST( SUM(Importe) as DECIMAL(12,2)) AS Greuge + (SELECT g.Id_Cliente, CAST( SUM(Importe) as DECIMAL(12,2)) AS Greuge FROM vn2008.Greuges g JOIN vn.`client` c ON c.id = g.Id_Cliente LEFT JOIN vn.worker w ON c.salesPersonFk = w.id @@ -3866,14 +3866,14 @@ BEGIN WHERE v.fecha BETWEEN TIMESTAMPADD(YEAR, - 1, vDate) AND vDate GROUP BY v.Id_Cliente) c365 ON c365.Id_Cliente = c.Id_Cliente LEFT JOIN - (SELECT + (SELECT Id_Cliente, SUM(importe) consumo FROM bs.ventas v INNER JOIN vn2008.Clientes c USING (Id_Cliente) LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador WHERE - (c.Id_Trabajador = vWorker OR tr.boss = vWorker) + (c.Id_Trabajador = vWorker OR tr.boss = vWorker) AND (v.fecha BETWEEN TIMESTAMPADD(DAY, - DAY(vDate) + 1, vDate) AND TIMESTAMPADD(DAY, - 1, vDate)) GROUP BY Id_Cliente) mes_actual ON mes_actual.Id_Cliente = c.Id_Cliente LEFT JOIN @@ -3934,17 +3934,17 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `compradores_add`(IN vYear INT, IN v BEGIN /** * Sustituye los registros de "bs.compradores". - * + * * @param vYear: año ventas * @param vWeekFrom: semana desde * @param vWeekTo: semana hasta */ REPLACE bs.compradores - SELECT it.workerFk AS Id_Trabajador, vYear AS año, tm.week AS semana, SUM(importe) AS importe, 0 AS comision + SELECT it.workerFk AS Id_Trabajador, vYear AS año, tm.week AS semana, SUM(importe) AS importe, 0 AS comision FROM bs.ventas v JOIN vn.time tm ON tm.dated = v.fecha - JOIN vn.itemType it ON it.id = v.tipo_id - WHERE tm.year = vYear + JOIN vn.itemType it ON it.id = v.tipo_id + WHERE tm.year = vYear AND tm.week BETWEEN vWeekFrom AND vWeekTo AND it.categoryFk != 6 GROUP BY it.workerFk, tm.week; @@ -3970,22 +3970,22 @@ BEGIN DECLARE vYear INT; DECLARE vWeek INT; DECLARE done BOOL DEFAULT FALSE; - + DECLARE rs CURSOR FOR SELECT year, week FROM vn.time - WHERE dated <= util.VN_CURDATE() - AND year = vYear + WHERE dated <= util.VN_CURDATE() + AND year = vYear AND week >= vWeek; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - - SELECT MAX(año) INTO vYear + + SELECT MAX(año) INTO vYear FROM compradores; - + SELECT MAX(semana) INTO vWeek - FROM compradores - WHERE año = vYear; + FROM compradores + WHERE año = vYear; OPEN rs; @@ -3994,7 +3994,7 @@ BEGIN WHILE NOT done DO CALL compradores_add(vYear, vWeek, vWeek); - + FETCH rs INTO vYear, vWeek; END WHILE; @@ -4002,7 +4002,7 @@ BEGIN CLOSE rs; CALL compradores_evolution_add; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -4023,17 +4023,17 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `compradores_evolution_add`() BEGIN /** * Inserta en la tabla compradores_evolution las ventas acumuladas en los ultimos 365 dias - * + * */ DECLARE vDated DATE; DECLARE vCount INT DEFAULT 1; - SELECT MAX(fecha) + INTERVAL 1 DAY INTO vDated + SELECT MAX(fecha) + INTERVAL 1 DAY INTO vDated FROM compradores_evolution; IF vDated IS NULL THEN - - SELECT MIN(dated) INTO vDated + + SELECT MIN(dated) INTO vDated FROM sale; INSERT INTO compradores_evolution( @@ -4054,7 +4054,7 @@ BEGIN WHILE vDated < util.VN_CURDATE() DO SET vCount = vCount + 1; - + REPLACE compradores_evolution( Id_Trabajador, fecha, @@ -4066,18 +4066,18 @@ BEGIN SELECT Id_Trabajador, importe FROM compradores_evolution JOIN ( - SELECT DISTINCT it.workerFk - FROM vn.itemType it + SELECT DISTINCT it.workerFk + FROM vn.itemType it )sub2 ON sub2.workerFk = Id_Trabajador - WHERE fecha = vDated - INTERVAL 1 DAY + WHERE fecha = vDated - INTERVAL 1 DAY UNION ALL - SELECT it.workerFk, s.amount * IF(s.dated < vDated, -1, 1) + SELECT it.workerFk, s.amount * IF(s.dated < vDated, -1, 1) FROM sale s JOIN vn.itemType it ON it.id = s.typeFk JOIN vn.itemCategory ic ON ic.id = it.categoryFk WHERE s.dated IN (vDated, vDated - INTERVAL 1 YEAR) AND ic.merchandise - )sub + )sub GROUP BY Id_Trabajador; SET vDated = vDated + INTERVAL 1 DAY; @@ -4104,49 +4104,49 @@ BEGIN * Inserta en la tabla fondo_maniobra los saldos acumulados en los ultimos 365 dias */ DECLARE datFEC DATE DEFAULT '2015-01-01'; - - SELECT TIMESTAMPADD(DAY,1,MAX(fecha)) - INTO datFEC + + SELECT TIMESTAMPADD(DAY,1,MAX(fecha)) + INTO datFEC FROM bs.fondo_maniobra; - + WHILE datFEC < util.VN_CURDATE() DO - + IF DAY(datFEC) MOD 28 = 0 THEN -- esto solo sirve para no aburrirse mientras esperamos... SELECT datFEC; END IF; - + REPLACE bs.fondo_maniobra(Fecha, clientes_facturas, clientes_cobros,proveedores_facturas,proveedores_pagos, fondo) SELECT datFEC AS Fecha, Facturas, Cobros,Recibidas,Pagos, Facturas + Cobros + Recibidas + Pagos FROM ( SELECT SUM(io.amount) AS Facturas FROM vn.invoiceOut io - JOIN vn.client c ON io.clientFk = c.id + JOIN vn.client c ON io.clientFk = c.id WHERE c.isRelevant - AND io.companyFk <> 1381 + AND io.companyFk <> 1381 AND io.issued BETWEEN '2011-01-01' AND datFEC ) fac JOIN ( SELECT - SUM(r.amountPaid) AS Cobros - FROM vn.receipt r - JOIN vn.client c ON r.clientFk = c.id - WHERE c.isRelevant + FROM vn.receipt r + JOIN vn.client c ON r.clientFk = c.id + WHERE c.isRelevant AND r.companyFk <> 1381 AND r.payed BETWEEN '2011-01-01' AND datFEC ) cob JOIN ( SELECT - SUM(id.amount) AS Recibidas - FROM vn.invoiceIn ii - JOIN vn.invoiceInDueDay id ON ii.id = id.invoiceInFk + FROM vn.invoiceIn ii + JOIN vn.invoiceInDueDay id ON ii.id = id.invoiceInFk WHERE ii.companyFk <> 1381 AND ii.issued BETWEEN '2015-01-01' AND datFEC ) rec JOIN ( SELECT SUM(p.amount) AS Pagos - FROM vn.payment p - WHERE p.companyFk <>1381 + FROM vn.payment p + WHERE p.companyFk <>1381 AND p.received BETWEEN '2015-01-01' AND datFEC ) pag; - + UPDATE bs.fondo_maniobra JOIN ( SELECT AVG(fondo) AS media @@ -4154,7 +4154,7 @@ BEGIN WHERE fecha <= datFEC ) sub SET fondo_medio = media WHERE fecha = datFEC; - + SET datFEC = TIMESTAMPADD(DAY,1,datFEC); END WHILE; @@ -4178,7 +4178,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `fruitsEvolution`() BEGIN -select Id_Cliente, +select Id_Cliente, Cliente, count(semana) as semanas, (w.code IS NOT NULL) isWorker from ( select distinct v.Id_Cliente, c.name as Cliente, week(fecha, 3) as semana @@ -4219,40 +4219,40 @@ BEGIN -- Ventas totales del ultimo año UPDATE indicators - SET lastYearSales = + SET lastYearSales = (SELECT SUM(importe + recargo) FROM ventas v JOIN vn2008.empresa e ON e.id = v.empresa_id JOIN vn2008.empresa_grupo eg ON eg.empresa_grupo_id = e.empresa_grupo WHERE fecha BETWEEN oneYearBefore AND vDated AND eg.grupo = 'Verdnatura' - ) + ) WHERE updated = vDated; - + -- Greuge total acumulado UPDATE indicators - SET totalGreuge = + SET totalGreuge = (SELECT SUM(amount) FROM vn.greuge WHERE shipped <= vDated - ) + ) WHERE updated = vDated; -- Tasa de morosidad con respecto a las ventas del último mes UPDATE indicators - SET latePaymentRate = - (SELECT SUM(amount) - FROM bi.defaulters + SET latePaymentRate = + (SELECT SUM(amount) + FROM bi.defaulters WHERE date = vDated AND amount > 0) / - (SELECT SUM(importe + recargo) - FROM ventas + (SELECT SUM(importe + recargo) + FROM ventas WHERE fecha BETWEEN oneMonthBefore AND vDated) WHERE updated = vDated; -- Número de trabajadores activos UPDATE indicators - SET countEmployee = + SET countEmployee = (SELECT CAST(SUM(ct.hoursWeek) / 40 AS DECIMAL (10, 2)) FROM vn.business b JOIN vn.calendarType ct ON ct.id = b.calendarTypeFk @@ -4271,7 +4271,7 @@ BEGIN -- Número de clientes que han comprado en los últimos 30 dias UPDATE indicators - SET lastMonthActiveClients = + SET lastMonthActiveClients = (SELECT COUNT(DISTINCT t.clientFk) FROM vn.ticket t WHERE t.shipped BETWEEN oneMonthBefore AND vDated @@ -4280,9 +4280,9 @@ BEGIN -- Número de clientes que no han comprado en los últimos 30 dias, pero compraron en los 30 anteriores UPDATE indicators - SET lastMonthLostClients = + SET lastMonthLostClients = (SELECT COUNT(lm.clientFk) - FROM + FROM (SELECT DISTINCT t.clientFk FROM vn.ticket t WHERE t.shipped BETWEEN oneMonthBefore AND vDated @@ -4299,9 +4299,9 @@ BEGIN -- Número de clientes que han comprado en los últimos 30 dias, pero no compraron en los 30 anteriores UPDATE indicators - SET lastMonthNewClients = + SET lastMonthNewClients = (SELECT COUNT(cm.clientFk) - FROM + FROM (SELECT DISTINCT t.clientFk FROM vn.ticket t WHERE t.shipped BETWEEN oneMonthBefore AND vDated @@ -4327,7 +4327,7 @@ BEGIN -- Cálculo de las ventas agrupado por semanas SELECT week INTO vWeek - FROM vn.time + FROM vn.time WHERE dated = vDated; TRUNCATE salesByWeek; @@ -4341,12 +4341,12 @@ BEGIN -- Indicador Ventas semana actual UPDATE indicators i - JOIN salesByWeek s ON s.week= vWeek + JOIN salesByWeek s ON s.week= vWeek AND s.year = YEAR(vDated) SET i.thisWeekSales = s.sales WHERE updated = vDated; - -- Indicador ventas semana actual en el año pasado + -- Indicador ventas semana actual en el año pasado UPDATE indicators i JOIN salesByWeek s ON s.week = vWeek AND s.year = YEAR(vDated)-1 @@ -4377,15 +4377,15 @@ BEGIN SELECT IFNULL(TIMESTAMPADD(DAY,1,MAX(updated)), '2018-04-01') INTO vDated FROM bs.indicators; - + WHILE vDated < util.VN_CURDATE() DO - + CALL indicatorsUpdate(vDated); - + SELECT TIMESTAMPADD(DAY,1,MAX(updated)) INTO vDated FROM bs.indicators; - + END WHILE; END ;; @@ -4414,7 +4414,7 @@ BEGIN DECLARE vCalc INT; DECLARE vWarehouseFk INT; - DECLARE cWarehouses CURSOR FOR + DECLARE cWarehouses CURSOR FOR SELECT id FROM vn.warehouse WHERE isInventory; @@ -4427,13 +4427,13 @@ BEGIN read_loop: LOOP SET vDone = FALSE; FETCH cWarehouses INTO vWarehouseFk; - + IF vDone THEN LEAVE read_loop; END IF; - + CALL cache.visible_refresh(vCalc, FALSE, vWarehouseFk); - + CREATE OR REPLACE TEMPORARY TABLE tVisible SELECT itemFk, SUM(visible) totalVisible FROM vn.itemShelving ish @@ -4442,7 +4442,7 @@ BEGIN JOIN vn.sector sc ON sc.id = p.sectorFk WHERE sc.warehouseFk = vWarehouseFk GROUP BY itemFk; - + INSERT INTO inventoryDiscrepancyDetail( warehouseFk, itemFk, @@ -4514,15 +4514,15 @@ BEGIN DECLARE datSTART DATE; DECLARE datEND DATE; - + SELECT TIMESTAMPADD(WEEK, -1,MAX(fecha)) INTO datSTART FROM bs.m3; - + SET datEND = TIMESTAMPADD(DAY,-1,util.VN_CURDATE()); - - DELETE FROM bs.m3 + + DELETE FROM bs.m3 WHERE fecha >= datSTART; - + INSERT INTO bs.m3 (fecha, provinceFk, warehouseFk, m3, year, month, week, day, dayName, euros) SELECT v.fecha, a.provinceFk, t.warehouseFk, sum(s.quantity * ic.cm3delivery) / 1000000 AS m3, tm.year, tm.month, tm.week, tm.day, dayname(v.fecha), sum(importe) @@ -4565,51 +4565,51 @@ BEGIN DECLARE vManaBankId INT; DECLARE vManaGreugeTypeId INT; - SELECT id INTO vManaId + SELECT id INTO vManaId FROM vn.component WHERE code = 'mana'; - - SELECT id INTO vManaAutoId + + SELECT id INTO vManaAutoId FROM vn.component WHERE code = 'autoMana'; - + SELECT id INTO vClaimManaId FROM vn.component WHERE code = 'manaClaim'; - - SELECT id INTO vManaBankId + + SELECT id INTO vManaBankId FROM vn.bank WHERE code = 'mana'; - - SELECT id INTO vManaGreugeTypeId + + SELECT id INTO vManaGreugeTypeId FROM vn.greugeType WHERE code = 'mana'; SELECT IFNULL(MAX(dated), '2016-01-01') - INTO vFromDated + INTO vFromDated FROM vn.clientManaCache; - + DELETE FROM vn.clientManaCache WHERE dated = vFromDated; SELECT IFNULL(MAX(dated), '2016-01-01') - INTO vFromDated + INTO vFromDated FROM vn.clientManaCache; WHILE timestampadd(DAY,30,vFromDated) < util.VN_CURDATE() DO SELECT timestampadd(DAY,30,vFromDated), - timestampadd(DAY,-90,vFromDated) - INTO + timestampadd(DAY,-90,vFromDated) + INTO vToDated, vForDeleteDated; - + DELETE FROM vn.clientManaCache WHERE dated <= vForDeleteDated; INSERT INTO vn.clientManaCache(clientFk, mana, dated) - SELECT + SELECT Id_Cliente, cast(sum(mana) as decimal(10,2)) as mana, - vToDated as dated - FROM + vToDated as dated + FROM ( SELECT cs.Id_Cliente, Cantidad * Valor as mana FROM vn2008.Tickets t @@ -4617,20 +4617,20 @@ BEGIN JOIN vn2008.Movimientos m on m.Id_Ticket = t.Id_Ticket JOIN vn2008.Movimientos_componentes mc on mc.Id_Movimiento = m.Id_Movimiento WHERE Id_Componente IN (vManaAutoId, vManaId, vClaimManaId) - AND t.Fecha > vFromDated + AND t.Fecha > vFromDated AND date(t.Fecha) <= vToDated UNION ALL SELECT r.Id_Cliente, - Entregado FROM vn2008.Recibos r WHERE Id_Banco = vManaBankId - AND Fechacobro > vFromDated + AND Fechacobro > vFromDated AND Fechacobro <= vToDated - + UNION ALL SELECT g.Id_Cliente, g.Importe FROM vn2008.Greuges g WHERE Greuges_type_id = vManaGreugeTypeId - AND Fecha > vFromDated + AND Fecha > vFromDated AND Fecha <= vToDated UNION ALL SELECT clientFk, mana @@ -4641,7 +4641,7 @@ BEGIN HAVING Id_Cliente; SET vFromDated = vToDated; - + END WHILE; END ;; @@ -4662,22 +4662,22 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `manaSpellers_actualize`() BEGIN -/** - * Recalcula el valor del campo con el modificador de precio +/** + * Recalcula el valor del campo con el modificador de precio * para el componente de maná automático. */ - UPDATE vn.workerMana wm + UPDATE vn.workerMana wm JOIN ( - SELECT c.lastSalesPersonFk, + SELECT c.lastSalesPersonFk, FLOOR(SUM(s.amount) / 12) amount FROM salesByclientSalesPerson s JOIN vn.client c ON c.id = s.clientFk WHERE s.dated BETWEEN util.VN_CURDATE() - INTERVAL 1 YEAR AND util.VN_CURDATE() GROUP BY c.lastSalesPersonFk - )avgPortfolioWeight ON avgPortfolioWeight.lastSalesPersonFk = wm.workerFk + )avgPortfolioWeight ON avgPortfolioWeight.lastSalesPersonFk = wm.workerFk JOIN vn.salespersonConfig spc SET wm.pricesModifierRate = GREATEST( - spc.manaMinRate, + spc.manaMinRate, LEAST(spc.manaMaxRate, ROUND( - wm.amount / avgPortfolioWeight.amount))); END ;; DELIMITER ; @@ -4710,8 +4710,8 @@ BEGIN DECLARE vId INT; DECLARE rs CURSOR FOR - SELECT id, `schema`, `procedure` - FROM nightTask + SELECT id, `schema`, `procedure` + FROM nightTask WHERE finished <= util.VN_CURDATE() OR finished IS NULL ORDER BY `order`; @@ -4744,7 +4744,7 @@ BEGIN vError, vErrorCode ); - + IF vError IS NOT NULL THEN SET vNErrors = vNErrors + 1; @@ -4814,7 +4814,7 @@ BEGIN vError = MESSAGE_TEXT, vErrorCode = RETURNED_SQLSTATE; - CALL util.exec(CONCAT('CALL `', vSchema ,'`.`', vProcedure ,'`')); + CALL util.exec(CONCAT('CALL `', vSchema ,'`.`', vProcedure ,'`')); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -4833,22 +4833,22 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `payMethodClientAdd`() BEGIN - INSERT IGNORE INTO `bs`.`payMethodClient` (dated, payMethodFk, clientFk) + INSERT IGNORE INTO `bs`.`payMethodClient` (dated, payMethodFk, clientFk) SELECT util.VN_CURDATE(), c.payMethodFk, c.id - FROM vn.client c + FROM vn.client c JOIN vn.payMethod p ON c.payMethodFk = p.id; - + TRUNCATE `bs`.`payMethodClientEvolution` ; - + INSERT INTO `bs`.`payMethodClientEvolution` (dated, payMethodName, amountClient, amount, equalizationTax) - SELECT p.dated, pm.name, COUNT(p.clientFk), SUM(sub.importe) , SUM(sub.recargo) + SELECT p.dated, pm.name, COUNT(p.clientFk), SUM(sub.importe) , SUM(sub.recargo) FROM bs.payMethodClient p - JOIN (SELECT SUM(v.importe) AS importe, SUM(v.recargo) as recargo, v.fecha, v.Id_cliente + JOIN (SELECT SUM(v.importe) AS importe, SUM(v.recargo) as recargo, v.fecha, v.Id_cliente FROM bs.ventas v WHERE v.fecha>= (SELECT MIN(dated) FROM bs. payMethodClient) GROUP BY v.Id_cliente, v.fecha) sub ON sub.fecha = p.dated AND sub.Id_cliente = p.ClientFk JOIN vn.payMethod pm ON p.payMethodFk = pm.id - GROUP BY dated,payMethodFk; + GROUP BY dated,payMethodFk; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -4868,12 +4868,12 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `saleGraphic`(IN vItemFk INT, IN vTypeFk INT, IN vCategoryFk INT, IN vFromDate DATE, IN vToDate DATE, IN vProducerFk INT) BEGIN - + DECLARE vFromDateLastYear DATE; DECLARE vToDateLastYear DATE; DECLARE vFromDateTwoYearsAgo DATE; DECLARE vToDateTwoYearsAgo DATE; - + SET vItemFk = IFNULL(vItemFk,0); SET vTypeFk = IFNULL(vTypeFk, 0); SET vCategoryFk = IFNULL(vCategoryFk,0); @@ -4888,19 +4888,19 @@ BEGIN SELECT s.quantity, CAST(v.importe AS DECIMAL(10,0)) importe, v.fecha FROM bs.ventas v - JOIN vn.sale s ON s.id = v.Id_Movimiento - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.itemType it ON it.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk + JOIN vn.sale s ON s.id = v.Id_Movimiento + JOIN vn.item i ON i.id = s.itemFk + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk WHERE vItemFk IN (i.id, 0) AND vTypeFk IN (i.typeFk, 0) AND vCategoryFk IN (it.categoryFk, 0) AND vProducerFk IN (i.producerFk, 0) AND (v.fecha BETWEEN vFromDate AND vToDate OR v.fecha BETWEEN vFromDateLastYear AND vToDateLastYear - OR v.fecha BETWEEN vFromDateTwoYearsAgo AND vToDateTwoYearsAgo + OR v.fecha BETWEEN vFromDateTwoYearsAgo AND vToDateTwoYearsAgo ); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -4919,21 +4919,21 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `salePersonEvolutionAdd`(IN vDateStart DATETIME) BEGIN - DELETE FROM bs.salePersonEvolution + DELETE FROM bs.salePersonEvolution WHERE dated <= DATE_SUB(util.VN_CURDATE(), INTERVAL 1 YEAR); - - + + INSERT INTO bs.salePersonEvolution (dated, amount, equalizationTax, salesPersonFk) - SELECT fecha dated, - CAST(SUM(importe) AS DECIMAL(10,2) ) amount, + SELECT fecha dated, + CAST(SUM(importe) AS DECIMAL(10,2) ) amount, CAST(SUM(recargo) AS DECIMAL(10,2) ) equalizationTax , IFNULL(salesPersonFk,0) salesPersonFk FROM bs.ventas v - JOIN vn.client c ON v.Id_Cliente = c.id + JOIN vn.client c ON v.Id_Cliente = c.id JOIN vn.company co ON co.id = v.empresa_id WHERE co.code = "VNL" AND fecha >= vDateStart GROUP BY v.fecha,c.salesPersonFk - ORDER BY salesPersonFk,dated ASC; + ORDER BY salesPersonFk,dated ASC; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -4955,7 +4955,7 @@ BEGIN /** * Agrupa las ventas por cliente/comercial/fecha en la tabla bs.salesByclientSalesPerson * El asociación cliente/comercial/fecha, se mantiene correcta en el tiempo - * + * * @param vDatedFrom el cálculo se realizará desde la fecha introducida hasta ayer */ @@ -4963,17 +4963,17 @@ BEGIN SET vDatedFrom = util.VN_CURDATE() - INTERVAL 1 MONTH; END IF; - UPDATE salesByclientSalesPerson + UPDATE salesByclientSalesPerson SET amount = 0, equalizationTax = 0, amountNewBorn = 0 WHERE dated BETWEEN vDatedFrom AND util.yesterday(); - - INSERT INTO salesByclientSalesPerson( - dated, - salesPersonFk, - clientFk, - amount, + + INSERT INTO salesByclientSalesPerson( + dated, + salesPersonFk, + clientFk, + amount, equalizationTax) SELECT s.dated, c.salesPersonFk, @@ -4982,7 +4982,7 @@ BEGIN SUM(s.surcharge) FROM sale s JOIN vn.client c on s.clientFk = c.id - WHERE s.dated BETWEEN vDatedFrom AND util.yesterday() + WHERE s.dated BETWEEN vDatedFrom AND util.yesterday() GROUP BY s.dated, c.salesPersonFk, s.clientFk ON DUPLICATE KEY UPDATE amount= VALUES(amount), equalizationTax= VALUES(equalizationTax); @@ -5156,8 +5156,8 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `salesByItemTypeDay_addLauncher`() -BEGIN - CALL bs.salesByItemTypeDay_add(util.VN_CURDATE() - INTERVAL 30 DAY, util.VN_CURDATE()); +BEGIN + CALL bs.salesByItemTypeDay_add(util.VN_CURDATE() - INTERVAL 30 DAY, util.VN_CURDATE()); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -5177,35 +5177,35 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `salesPersonEvolution_add`() BEGIN /** - * Calcula los datos para los gráficos de evolución agrupado por salesPersonFk y día. + * Calcula los datos para los gráficos de evolución agrupado por salesPersonFk y día. * Recalcula automáticamente los 3 últimos meses para comprobar si hay algún cambio. */ DECLARE vDated DATE; DECLARE vCont INT DEFAULT 1; - SELECT MAX(dated) - INTERVAL 3 MONTH INTO vDated + SELECT MAX(dated) - INTERVAL 3 MONTH INTO vDated FROM salesPersonEvolution; - DELETE FROM salesPersonEvolution + DELETE FROM salesPersonEvolution WHERE dated >= vDated; IF ISNULL(vDated) THEN - SELECT MIN(dated) INTO vDated + SELECT MIN(dated) INTO vDated FROM salesByclientSalesPerson; - + INSERT INTO salesPersonEvolution( - salesPersonFk, - dated, - amount, - equalizationTax, + salesPersonFk, + dated, + amount, + equalizationTax, amountNewBorn ) - SELECT salesPersonFk, - dated, - amount, - equalizationTax, + SELECT salesPersonFk, + dated, + amount, + equalizationTax, amountNewBorn - FROM salesByclientSalesPerson + FROM salesByclientSalesPerson WHERE dated = vDated GROUP BY salesPersonFk; @@ -5213,21 +5213,21 @@ BEGIN END IF; WHILE vDated < util.VN_CURDATE() DO - + SET vCont = vCont + 1; REPLACE salesPersonEvolution(salesPersonFk, dated, amount) SELECT salesPersonFk, vDated, amount FROM(SELECT salesPersonFk, SUM(amount) amount FROM(SELECT salesPersonFk, amount - FROM salesPersonEvolution + FROM salesPersonEvolution WHERE dated = vDated - INTERVAL 1 DAY UNION ALL - SELECT salesPersonFk, amount - FROM salesByclientSalesPerson + SELECT salesPersonFk, amount + FROM salesByclientSalesPerson WHERE dated = vDated UNION ALL SELECT salesPersonFk, - amount - FROM salesByclientSalesPerson + FROM salesByclientSalesPerson WHERE dated = vDated - INTERVAL 1 YEAR )sub GROUP BY salesPersonFk @@ -5256,7 +5256,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `vendedores_add_launcher`() BEGIN CALL bs.salesByclientSalesPerson_add(util.VN_CURDATE()- INTERVAL 45 DAY); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -5280,7 +5280,7 @@ BEGIN /** * Añade las ventas que se realizaron entre * vStarted y vEnded -* +* * @param vStarted Fecha de inicio * @param vEnded Fecha de finalizacion * @@ -5288,7 +5288,7 @@ BEGIN DECLARE vStartingDate DATETIME; DECLARE vEndingDate DATETIME; - IF vStarted < TIMESTAMPADD(YEAR,-5,util.VN_CURDATE()) + IF vStarted < TIMESTAMPADD(YEAR,-5,util.VN_CURDATE()) OR vEnded < TIMESTAMPADD(YEAR,-5,util.VN_CURDATE()) THEN CALL util.throw('fechaDemasiadoAntigua'); END IF; @@ -5297,8 +5297,8 @@ BEGIN SET vStartingDate = vStarted ; SET vEndingDate = util.dayEnd(vStartingDate); - DELETE - FROM sale + DELETE + FROM sale WHERE dated BETWEEN vStartingDate AND vEnded; WHILE vEndingDate <= vEnded DO @@ -5319,28 +5319,28 @@ BEGIN JOIN vn.itemType it ON it.id = i.typeFk JOIN vn.itemCategory ic ON ic.id = it.categoryFk JOIN vn.ticket t ON t.id = s.ticketFk - JOIN vn.address a ON a.id = t.addressFk + JOIN vn.address a ON a.id = t.addressFk JOIN vn.client cl ON cl.id = a.clientFk WHERE t.shipped BETWEEN vStartingDate AND vEndingDate AND s.quantity <> 0 AND s.discount <> 100 - AND ic.merchandise + AND ic.merchandise GROUP BY sc.saleFk HAVING IFNULL(importe,0) <> 0 OR IFNULL(recargo,0) <> 0; UPDATE sale s JOIN ( - SELECT s.id, + SELECT s.id, SUM(s.quantity * sc.value ) margen, s.quantity * s.price * (100 - s.discount ) / 100 pvp FROM vn.sale s - JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.ticket t ON t.id = s.ticketFk JOIN vn.saleComponent sc ON sc.saleFk = s.id - JOIN vn.component c ON c.id = sc.componentFk - JOIN vn.componentType ct ON ct.id = c.typeFk + JOIN vn.component c ON c.id = sc.componentFk + JOIN vn.componentType ct ON ct.id = c.typeFk WHERE t.shipped BETWEEN vStartingDate AND vEndingDate AND ct.isMargin = TRUE - GROUP BY s.id) sub ON sub.id = s.saleFk + GROUP BY s.id) sub ON sub.id = s.saleFk SET s.margin = sub.margen + s.amount + s.surcharge - sub.pvp; SET vStartingDate = TIMESTAMPADD(DAY,1, vStartingDate); @@ -5368,7 +5368,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `ventas_add_launcher`() BEGIN /** * Añade las ventas a la tabla bs.sale que se realizaron desde hace un mes hasta hoy - * + * */ DECLARE vCurDate DATE DEFAULT util.VN_CURDATE(); @@ -5392,7 +5392,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ventas_contables_add`(IN vYear INT, IN vMonth INT) BEGIN - + /** * Reemplaza las ventas contables del último año. * Es el origen de datos para el balance de Entradas @@ -5404,8 +5404,8 @@ BEGIN DECLARE TIPO_PATRIMONIAL INT DEFAULT 188; - DELETE FROM bs.ventas_contables - WHERE year = vYear + DELETE FROM bs.ventas_contables + WHERE year = vYear AND month = vMonth; DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; @@ -5416,7 +5416,7 @@ BEGIN FROM vn2008.Tickets t JOIN vn2008.Facturas f ON f.Id_Factura = t.Factura WHERE year(f.Fecha) = vYear - AND month(f.Fecha) = vMonth; + AND month(f.Fecha) = vMonth; INSERT INTO bs.ventas_contables(year , month @@ -5426,7 +5426,7 @@ BEGIN , tipo_id , empresa_id , gasto) - + SELECT vYear , vMonth , round(sum(Cantidad * Preu * (100 - m.Descuento)/100)) @@ -5438,13 +5438,13 @@ BEGIN , tp.reino_id , a.tipo_id , t.empresa_id - , 7000000000 + , 7000000000 + IF(e.empresa_grupo = e2.empresa_grupo ,1 ,IF(e2.empresa_grupo,2,0) - ) * 1000000 + ) * 1000000 + tp.reino_id * 10000 as Gasto - FROM vn2008.Movimientos m + FROM vn2008.Movimientos m JOIN vn2008.Tickets t on t.Id_Ticket = m.Id_Ticket JOIN vn2008.Consignatarios cs on cs.Id_Consigna = t.Id_Consigna JOIN vn2008.Clientes c on c.Id_Cliente = cs.Id_Cliente @@ -5458,7 +5458,7 @@ BEGIN AND m.Descuento <> 100 AND a.tipo_id != TIPO_PATRIMONIAL GROUP BY grupo, reino_id, tipo_id, empresa_id, Gasto; - + INSERT INTO bs.ventas_contables(year , month , venta @@ -5477,17 +5477,17 @@ BEGIN ) as grupo , NULL , NULL - , t.companyFk + , t.companyFk , 7050000000 - FROM vn.ticketService ts + FROM vn.ticketService ts JOIN vn.ticket t ON ts.ticketFk = t.id - JOIN vn.address a on a.id = t.addressFk - JOIN vn.client cl on cl.id = a.clientFk + JOIN vn.address a on a.id = t.addressFk + JOIN vn.client cl on cl.id = a.clientFk JOIN tmp.ticket_list tt on tt.Id_Ticket = t.id - JOIN vn.company c on c.id = t.companyFk + JOIN vn.company c on c.id = t.companyFk LEFT JOIN vn.company c2 on c2.clientFk = cl.id - GROUP BY grupo, t.companyFk ; - + GROUP BY grupo, t.companyFk ; + DROP TEMPORARY TABLE tmp.ticket_list; END ;; DELIMITER ; @@ -5507,13 +5507,13 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ventas_contables_add_launcher`() BEGIN - + /** * Reemplaza las ventas contables del último año. * Es el origen de datos para el balance de Entradas * **/ - + CALL bs.ventas_contables_add(YEAR(TIMESTAMPADD(MONTH,-1,util.VN_CURDATE())), MONTH(TIMESTAMPADD(MONTH,-1,util.VN_CURDATE()))); END ;; @@ -5534,12 +5534,12 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ventas_contables_por_cliente`(IN vYear INT, IN vMonth INT) BEGIN - + /** * Muestra las ventas (€) de cada cliente * dependiendo del año */ - + DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; CREATE TEMPORARY TABLE tmp.ticket_list @@ -5548,8 +5548,8 @@ BEGIN FROM vn2008.Tickets t JOIN vn2008.Facturas f ON f.Id_Factura = t.Factura WHERE year(f.Fecha) = vYear - AND month(f.Fecha) = vMonth; - + AND month(f.Fecha) = vMonth; + SELECT vYear Año, vMonth Mes, t.Id_Cliente, @@ -5559,7 +5559,7 @@ BEGIN IF(e2.empresa_grupo,2,0)) AS grupo, t.empresa_id empresa - FROM vn2008.Movimientos m + FROM vn2008.Movimientos m JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket JOIN vn2008.Consignatarios cs ON cs.Id_Consigna = t.Id_Consigna JOIN vn2008.Clientes c ON c.Id_Cliente = cs.Id_Cliente @@ -5573,9 +5573,9 @@ BEGIN AND m.Descuento <> 100 AND a.tipo_id != 188 GROUP BY t.Id_Cliente, grupo,t.empresa_id; - + DROP TEMPORARY TABLE tmp.ticket_list; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -5594,7 +5594,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `vivosMuertos`() BEGIN - + /** * Devuelve el número de clientes nuevos y muertos, * dependiendo de la fecha actual. @@ -5605,9 +5605,9 @@ BEGIN SET @datSTART = TIMESTAMPADD(YEAR,-2,util.VN_CURDATE()); SET @datEND = TIMESTAMPADD(DAY,-DAY(util.VN_CURDATE()),util.VN_CURDATE()); - + DROP TEMPORARY TABLE IF EXISTS tmp.VivosMuertos; - + CREATE TEMPORARY TABLE tmp.VivosMuertos SELECT c.Id_Cliente, tm.yearMonth, f.Compra, 0 as Nuevo, 0 as Muerto FROM vn2008.Clientes c @@ -5623,10 +5623,10 @@ BEGIN WHERE Fecha BETWEEN @datSTART AND @datEND) f ON f.yearMonth = tm.yearMonth AND f.Id_Cliente = c.Id_Cliente; - + UPDATE tmp.VivosMuertos vm JOIN - (SELECT MIN(tm.yearMonth) firstMonth, f.Id_Cliente + (SELECT MIN(tm.yearMonth) firstMonth, f.Id_Cliente FROM vn2008.Facturas f JOIN vn2008.time tm ON tm.date = f.Fecha WHERE Fecha BETWEEN @datSTART AND @datEND @@ -5634,9 +5634,9 @@ BEGIN AND fm.Id_Cliente = vm.Id_Cliente SET Nuevo = 1; - + SELECT max(yearMonth) INTO @lastYearMonth FROM tmp.VivosMuertos; - + UPDATE tmp.VivosMuertos vm JOIN ( SELECT MAX(tm.yearMonth) firstMonth, f.Id_Cliente @@ -5677,23 +5677,23 @@ BEGIN INTO vWeek, vYear FROM vn.time WHERE dated = util.VN_CURDATE(); - + REPLACE bs.waste SELECT *, 100 * mermas / total as porcentaje FROM ( - SELECT buyer, - year, + SELECT buyer, + year, week, family, itemFk, itemTypeFk, - floor(sum(value)) as total, + floor(sum(value)) as total, floor(sum(IF(clientTypeFk = 'loses', value, 0))) as mermas - FROM vn.saleValue + FROM vn.saleValue where year = vYear and week = vWeek - + GROUP BY family, itemFk - + ) sub ORDER BY mermas DESC; END ;; @@ -5725,56 +5725,56 @@ BEGIN DECLARE vDateEnded DATE; DECLARE vCursor CURSOR FOR - SELECT util.firstDayOfMonth(t.dated), LAST_DAY(t.dated) + SELECT util.firstDayOfMonth(t.dated), LAST_DAY(t.dated) FROM vn.time t WHERE t.dated BETWEEN vDateStarted AND vDateEnded - GROUP BY year,month; + GROUP BY year,month; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + IF DAY(util.VN_CURDATE()) = 21 THEN - + SELECT util.firstDayOfMonth(DATE_SUB(util.VN_CURDATE(), INTERVAL 12 MONTH)), LAST_DAY(DATE_SUB(util.VN_CURDATE(), INTERVAL 1 MONTH)) - INTO vDateStarted, + INTO vDateStarted, vDateEnded; - - DELETE FROM workerLabourDataByMonth + + DELETE FROM workerLabourDataByMonth WHERE CONCAT(`year`, '-',`month`, '-01') BETWEEN vDateStarted AND vDateEnded; OPEN vCursor; l: LOOP SET vDone = FALSE; - + FETCH vCursor INTO vFristDay, vLastDay; - + IF vDone THEN LEAVE l; END IF; - + -- Altas periodo - INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent) - SELECT 'hiring', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent) + INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent) + SELECT 'hiring', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent) FROM vn.business b JOIN vn.workCenter wc ON wc.id = b.workCenterFk JOIN vn.worker w ON w.id = b.workerFk LEFT JOIN vn.workerBusinessType wbt ON wbt.id = b.workerBusinessTypeFk LEFT JOIN (SELECT b.id, b.workerFk FROM vn.business b - LEFT JOIN (SELECT ended, workerFk FROM vn.business) wl + LEFT JOIN (SELECT ended, workerFk FROM vn.business) wl ON wl.ended = DATE_SUB(b.started, INTERVAL 1 DAY) AND wl.workerFk = b.workerFk - WHERE b.started BETWEEN vFristDay AND vLastDay AND wl.ended + WHERE b.started BETWEEN vFristDay AND vLastDay AND wl.ended )sub ON sub.workerFk = b.workerFk WHERE wc.payrollCenterFk IS NOT NULL AND b.workCenterFk IS NOT NULL AND b.started BETWEEN vFristDay AND vLastDay AND sub.workerFk IS NULL - AND NOT w.isFreelance; + AND NOT w.isFreelance; -- Bajas periodo - INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent) - SELECT 'layoffs', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent) + INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent) + SELECT 'layoffs', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent) FROM vn.business b JOIN vn.worker w ON w.id = b.workerFk JOIN vn.workCenter wc ON wc.id = b.workCenterFk @@ -5785,12 +5785,12 @@ BEGIN AND b.ended BETWEEN vFristDay AND vLastDay AND wl.started IS NULL AND NOT w.isFreelance; - + -- Anterior al periodo SET vLastDay = LAST_DAY(DATE_SUB(vFristDay, INTERVAL 1 DAY)); - INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent) - SELECT 'staff', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent) + INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent) + SELECT 'staff', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent) FROM vn.business b JOIN vn.worker w ON w.id = b.workerFk JOIN vn.workCenter wc ON wc.id = b.workCenterFk @@ -5800,8 +5800,8 @@ BEGIN AND NOT w.isFreelance; -- Discapacidad - INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent) - SELECT 'disabled', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent) + INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent) + SELECT 'disabled', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent) FROM vn.business b JOIN vn.worker w ON w.id = b.workerFk JOIN vn.workCenter wc ON wc.id = b.workCenterFk @@ -6210,7 +6210,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `addressFriendship_Update`() BEGIN - REPLACE cache.addressFriendship + REPLACE cache.addressFriendship SELECT addressFk1, addressFk2, count(*) friendship FROM ( @@ -6221,7 +6221,7 @@ BEGIN AND t2.shipped >= TIMESTAMPADD(MONTH,-3,util.VN_CURDATE()) AND t.addressFk != t2.addressFk) sub GROUP BY addressFk1, addressFk2; - + REPLACE cache.zoneAgencyFriendship SELECT r.agencyModeFk, t.zoneFk, count(*) friendship FROM vn.route r @@ -6395,12 +6395,12 @@ BEGIN FROM available a LEFT JOIN tCalc c ON c.id = a.calc_id WHERE c.id IS NULL; - + DELETE a FROM availableNoRaids a LEFT JOIN tCalc c ON c.id = a.calc_id WHERE c.id IS NULL; - + DROP TEMPORARY TABLE tCalc; END ;; DELIMITER ; @@ -6579,27 +6579,27 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `cache_calc_end`(IN `v_calc` INT) -BEGIN - DECLARE v_cache_name VARCHAR(255); - DECLARE v_params VARCHAR(255); - - -- Libera el bloqueo y actualiza la fecha de ultimo refresco. - - UPDATE cache_calc cc JOIN cache c ON c.id = cc.cache_id - SET - cc.last_refresh = NOW(), - cc.expires = ADDTIME(NOW(), c.lifetime), - cc.connection_id = NULL - WHERE cc.id = v_calc; - - SELECT c.name, ca.params INTO v_cache_name, v_params - FROM cache c - JOIN cache_calc ca ON c.id = ca.cache_id - WHERE ca.id = v_calc; - - IF v_cache_name IS NOT NULL THEN - DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, ''))); - END IF; +BEGIN + DECLARE v_cache_name VARCHAR(255); + DECLARE v_params VARCHAR(255); + + -- Libera el bloqueo y actualiza la fecha de ultimo refresco. + + UPDATE cache_calc cc JOIN cache c ON c.id = cc.cache_id + SET + cc.last_refresh = NOW(), + cc.expires = ADDTIME(NOW(), c.lifetime), + cc.connection_id = NULL + WHERE cc.id = v_calc; + + SELECT c.name, ca.params INTO v_cache_name, v_params + FROM cache c + JOIN cache_calc ca ON c.id = ca.cache_id + WHERE ca.id = v_calc; + + IF v_cache_name IS NOT NULL THEN + DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, ''))); + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -6617,89 +6617,89 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `cache_calc_start`(OUT `v_calc` INT, INOUT `v_refresh` INT, IN `v_cache_name` VARCHAR(50), IN `v_params` VARCHAR(100)) -proc: BEGIN - DECLARE v_valid BOOL; - DECLARE v_lock_id VARCHAR(100); - DECLARE v_cache_id INT; - DECLARE v_expires DATETIME; - DECLARE v_clean_time DATETIME; - DECLARE vLastRefresh DATETIME; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - IF v_lock_id IS NOT NULL THEN - DO RELEASE_LOCK(v_lock_id); - END IF; - - RESIGNAL; - END; - - SET v_params = IFNULL(v_params, ''); - - -- Si el servidor se ha reiniciado invalida todos los calculos. - - SELECT COUNT(*) > 0 INTO v_valid FROM cache_valid; - - IF !v_valid - THEN - DELETE FROM cache_calc; - INSERT INTO cache_valid (valid) VALUES (TRUE); - END IF; - - -- Obtiene un bloqueo exclusivo para que no haya problemas de concurrencia. - - SET v_lock_id = CONCAT_WS('/', v_cache_name, v_params); - - IF !GET_LOCK(v_lock_id, 30) - THEN - SET v_calc = NULL; - SET v_refresh = FALSE; - LEAVE proc; - END IF; - - -- Comprueba si el calculo solicitado existe y esta actualizado. - - SELECT c.id, ca.id, ca.expires, ca.last_refresh - INTO v_cache_id, v_calc, v_expires, vLastRefresh - FROM cache c - LEFT JOIN cache_calc ca - ON ca.cache_id = c.id AND ca.params = v_params COLLATE 'utf8_general_ci' - WHERE c.name = v_cache_name COLLATE 'utf8_general_ci'; - - -- Si existe una calculo valido libera el bloqueo y devuelve su identificador. - - IF !v_refresh AND NOW() < v_expires AND vLastRefresh >= CURDATE() - THEN - DO RELEASE_LOCK(v_lock_id); - SET v_refresh = FALSE; - LEAVE proc; - END IF; - - -- Si el calculo no existe le crea una entrada en la tabla de calculos. - - IF v_calc IS NULL - THEN - INSERT INTO cache_calc SET - cache_id = v_cache_id, - cacheName = v_cache_name, - params = v_params, - last_refresh = NULL, - expires = NULL, - connection_id = CONNECTION_ID(); - - SET v_calc = LAST_INSERT_ID(); - ELSE - UPDATE cache_calc - SET - last_refresh = NULL, - expires = NULL, - connection_id = CONNECTION_ID() - WHERE id = v_calc; - END IF; - - -- Si se debe recalcular mantiene el bloqueo y devuelve su identificador. - - SET v_refresh = TRUE; +proc: BEGIN + DECLARE v_valid BOOL; + DECLARE v_lock_id VARCHAR(100); + DECLARE v_cache_id INT; + DECLARE v_expires DATETIME; + DECLARE v_clean_time DATETIME; + DECLARE vLastRefresh DATETIME; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + IF v_lock_id IS NOT NULL THEN + DO RELEASE_LOCK(v_lock_id); + END IF; + + RESIGNAL; + END; + + SET v_params = IFNULL(v_params, ''); + + -- Si el servidor se ha reiniciado invalida todos los calculos. + + SELECT COUNT(*) > 0 INTO v_valid FROM cache_valid; + + IF !v_valid + THEN + DELETE FROM cache_calc; + INSERT INTO cache_valid (valid) VALUES (TRUE); + END IF; + + -- Obtiene un bloqueo exclusivo para que no haya problemas de concurrencia. + + SET v_lock_id = CONCAT_WS('/', v_cache_name, v_params); + + IF !GET_LOCK(v_lock_id, 30) + THEN + SET v_calc = NULL; + SET v_refresh = FALSE; + LEAVE proc; + END IF; + + -- Comprueba si el calculo solicitado existe y esta actualizado. + + SELECT c.id, ca.id, ca.expires, ca.last_refresh + INTO v_cache_id, v_calc, v_expires, vLastRefresh + FROM cache c + LEFT JOIN cache_calc ca + ON ca.cache_id = c.id AND ca.params = v_params COLLATE 'utf8_general_ci' + WHERE c.name = v_cache_name COLLATE 'utf8_general_ci'; + + -- Si existe una calculo valido libera el bloqueo y devuelve su identificador. + + IF !v_refresh AND NOW() < v_expires AND vLastRefresh >= CURDATE() + THEN + DO RELEASE_LOCK(v_lock_id); + SET v_refresh = FALSE; + LEAVE proc; + END IF; + + -- Si el calculo no existe le crea una entrada en la tabla de calculos. + + IF v_calc IS NULL + THEN + INSERT INTO cache_calc SET + cache_id = v_cache_id, + cacheName = v_cache_name, + params = v_params, + last_refresh = NULL, + expires = NULL, + connection_id = CONNECTION_ID(); + + SET v_calc = LAST_INSERT_ID(); + ELSE + UPDATE cache_calc + SET + last_refresh = NULL, + expires = NULL, + connection_id = CONNECTION_ID() + WHERE id = v_calc; + END IF; + + -- Si se debe recalcular mantiene el bloqueo y devuelve su identificador. + + SET v_refresh = TRUE; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -6729,7 +6729,7 @@ proc: BEGIN FROM cache c JOIN cache_calc ca ON c.id = ca.cache_id WHERE ca.id = v_calc; - + DELETE FROM cache_calc WHERE id = v_calc; IF v_cache_name IS NOT NULL THEN @@ -6825,7 +6825,7 @@ DECLARE rs CURSOR FOR DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - SET myTime = HOUR(util.VN_NOW()) + MINUTE(util.VN_NOW()) / 60; + SET myTime = HOUR(util.VN_NOW()) + MINUTE(util.VN_NOW()) / 60; OPEN rs; @@ -6834,23 +6834,23 @@ DECLARE rs CURSOR FOR WHILE NOT done DO SET resto = IF(inicioProd < rsDeparture, rsDeparture - inicioProd,0); - + SET inicioProd = rsDeparture - rsHoras; - + IF inicioProd - resto < myTime THEN - + SET done = TRUE; - + ELSE - + SET departureLimit = rsDeparture; - + FETCH rs INTO rsDeparture, rsHoras , rsInicio; - + -- SELECT rsDeparture, rsHoras , rsInicio; - + END IF; - + END WHILE; SET departureLimit = IFNULL(departureLimit,24); @@ -6895,7 +6895,7 @@ proc: BEGIN DECLARE started DATE; DECLARE ended DATE; DECLARE vLastRefresh DATE; - + DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN CALL cache_calc_unlock (vCalc); @@ -6945,14 +6945,14 @@ proc: BEGIN DECLARE datEQ DATETIME; DECLARE timDIF TIME; DECLARE v_calc INT; - + CALL cache_calc_start (v_calc, v_refresh, 'prod_graphic', wh_id); - + IF !v_refresh THEN LEAVE proc; END IF; - + CALL vn2008.production_control_source(wh_id, 0); DELETE FROM prod_graphic_source; @@ -6970,8 +6970,8 @@ proc: BEGIN WHERE Fecha = util.VN_CURDATE() GROUP BY wh_id, graphCategory ; - - + + CALL cache_calc_end (v_calc); END ;; DELIMITER ; @@ -6992,7 +6992,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `stock_refresh`(v_refresh BOOL) proc: BEGIN /** - * Crea o actualiza la cache con el disponible hasta el día de + * Crea o actualiza la cache con el disponible hasta el día de * ayer. Esta cache es usada como base para otros procedimientos * como el cáculo del visible o del ATP. * @@ -7018,21 +7018,21 @@ proc: BEGIN SET v_date_inv = (SELECT inventoried FROM vn.config LIMIT 1); SET vCURDATE = util.VN_CURDATE(); - + DELETE FROM stock; - + INSERT INTO stock (item_id, warehouse_id, amount) SELECT item_id, warehouse_id, SUM(amount) amount FROM ( - SELECT itemFk AS item_id, warehouseFk AS warehouse_id, quantity AS amount + SELECT itemFk AS item_id, warehouseFk AS warehouse_id, quantity AS amount FROM vn.itemTicketOut WHERE shipped >= v_date_inv AND shipped < vCURDATE UNION ALL - SELECT itemFk ASitem_id, warehouseInFk AS warehouse_id, quantity AS amount + SELECT itemFk ASitem_id, warehouseInFk AS warehouse_id, quantity AS amount FROM vn.itemEntryIn WHERE landed >= v_date_inv AND landed < vCURDATE AND isVirtualStock is FALSE UNION ALL - SELECT itemFk AS item_id ,warehouseOutFk AS warehouse_id, quantity AS amount + SELECT itemFk AS item_id ,warehouseOutFk AS warehouse_id, quantity AS amount FROM vn.itemEntryOut WHERE shipped >= v_date_inv AND shipped < vCURDATE ) t @@ -7062,12 +7062,12 @@ BEGIN (INDEX (id)) ENGINE = MEMORY SELECT id FROM cache_calc; - + DELETE v FROM visible v LEFT JOIN tCalc c ON c.id = v.calc_id WHERE c.id IS NULL; - + DROP TEMPORARY TABLE tCalc; END ;; DELIMITER ; @@ -7991,9 +7991,9 @@ DELIMITER ;; BEGIN DECLARE nextID INT; - + SELECT 1 + MAX(id) INTO nextID FROM putOrder ; - + SET NEW.orderTradelineItemID = nextID; END */;; @@ -8015,36 +8015,36 @@ DELIMITER ;; BEFORE UPDATE ON `putOrder` FOR EACH ROW BEGIN - + DECLARE vError VARCHAR(100) DEFAULT 'Orderregel niet meer teruggevonden op basis van de orderps'; DECLARE vVmpIdError INT DEFAULT 7; DECLARE vVmpFk INT; DECLARE vSupplyResponseNumberOfUnits INT; - - SELECT sr.vmpID INTO vVmpFk - FROM edi.supplyResponse sr + + SELECT sr.vmpID INTO vVmpFk + FROM edi.supplyResponse sr WHERE sr.id = NEW.supplyResponseID; - - IF NEW.OrderStatus = 3 - AND NOT (NEW.OrderStatus <=> OLD.OrderStatus) - AND NEW.error = vError - AND vVmpFk = vVmpIdError - - THEN - + + IF NEW.OrderStatus = 3 + AND NOT (NEW.OrderStatus <=> OLD.OrderStatus) + AND NEW.error = vError + AND vVmpFk = vVmpIdError + + THEN + SET NEW.OrderStatus = 2; - + END IF; - + -- Error de disponible menor de lo solicitado IF NEW.error LIKE 'error2602%' THEN - + SELECT NumberOfUnits INTO vSupplyResponseNumberOfUnits - FROM edi.supplyResponse sr + FROM edi.supplyResponse sr WHERE sr.ID = NEW.supplyResponseID; - + SET NEW.error = CONCAT('(',vSupplyResponseNumberOfUnits,') ', NEW.error); - + END IF; END */;; DELIMITER ; @@ -8071,16 +8071,16 @@ BEGIN DECLARE vIsEktSender BOOLEAN; IF NEW.OrderStatus = vOrderStatusDenied AND NOT (NEW.OrderStatus <=> OLD.OrderStatus) THEN - + SELECT s.id INTO vSaleFk - FROM vn.sale s + FROM vn.sale s JOIN vn.ticket t ON s.ticketFk = t.id JOIN vn.item i ON i.id = s.itemFk JOIN deliveryInformation di ON di.ID = NEW.deliveryInformationID WHERE t.clientFk = NEW.EndUserPartyGLN AND t.shipped >= util.VN_CURDATE() AND i.supplyResponseFk = NEW.supplyResponseID LIMIT 1; - + UPDATE vn.sale s JOIN vn.ticket t ON s.ticketFk = t.id JOIN vn.item i ON i.id = s.itemFk @@ -8088,7 +8088,7 @@ BEGIN SET s.quantity = 0 WHERE t.clientFk = NEW.EndUserPartyGLN AND t.shipped >= util.VN_CURDATE() AND i.supplyResponseFk = NEW.supplyResponseID; - + INSERT INTO vn.mail (sender, `subject`, body) SELECT IF(u.id IS NOT NULL AND c.email IS NOT NULL, c.email, @@ -8100,26 +8100,26 @@ BEGIN IF (u.id IS NOT NULL AND c.email IS NOT NULL , CONCAT('https://shop.verdnatura.es/#!form=ecomerce%2Fticket&ticket=', t.id ), CONCAT('https://salix.verdnatura.es/#!/ticket/', t.id ,'/summary'))) - FROM vn.sale s + FROM vn.sale s JOIN vn.ticket t ON t.id = s.ticketFk JOIN vn.`client` c ON c.id = t.clientFk LEFT JOIN account.user u ON u.id= c.salesPersonFk AND u.name IN ('ruben', 'ismaelalcolea') WHERE s.id = vSaleFk; - + END IF; IF NEW.OrderStatus = vOrderStatusOK AND NOT (NEW.OrderStatus <=> OLD.OrderStatus) THEN - SELECT v.isEktSender INTO vIsEktSender + SELECT v.isEktSender INTO vIsEktSender FROM edi.VMPSettings v - JOIN edi.supplyResponse sr ON sr.vmpID = v.VMPID + JOIN edi.supplyResponse sr ON sr.vmpID = v.VMPID WHERE sr.id = NEW.supplyResponseID; - + IF NOT vIsEktSender THEN CALL edi.ekt_add(NEW.id); - + END IF; IF NEW.barcode THEN @@ -8128,7 +8128,7 @@ BEGIN SELECT i.id, NEW.barcode FROM vn.item i WHERE i.supplyResponseFk = NEW.supplyResponseID; - + END IF; END IF; @@ -8326,8 +8326,8 @@ BEGIN UPDATE vn.buy b JOIN vn.entry e ON e.id = b.entryFk - JOIN vn.travel tr ON tr.id = e.travelFk - JOIN vn.agencyMode am ON am.id = tr.agencyModeFk + JOIN vn.travel tr ON tr.id = e.travelFk + JOIN vn.agencyMode am ON am.id = tr.agencyModeFk JOIN vn.item i ON i.id = b.itemFk JOIN edi.supplyResponse sr ON i.supplyResponseFk = sr.ID SET b.quantity = NEW.NumberOfItemsPerCask * NEW.NumberOfUnits, @@ -8336,7 +8336,7 @@ BEGIN AND am.name = 'LOGIFLORA' AND e.isRaid AND tr.landed >= util.VN_CURDATE(); - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -8478,7 +8478,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `imageName`(vPictureReference VARCHAR(255)) RETURNS varchar(255) CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci DETERMINISTIC BEGIN - + SET vPictureReference = REPLACE(vPictureReference,'.',''); SET vPictureReference = REPLACE(vPictureReference,'/',''); @@ -8490,7 +8490,7 @@ BEGIN SET vPictureReference = REPLACE(vPictureReference,'?',''); SET vPictureReference = REPLACE(vPictureReference,'=',''); - + RETURN vPictureReference; END ;; @@ -8546,27 +8546,27 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `deliveryInformation_Delete`() BEGIN - + DECLARE vID INT; DECLARE vGap INT DEFAULT 100; DECLARE vTope INT; - - SELECT MIN(ID), MAX(ID) + + SELECT MIN(ID), MAX(ID) INTO vID, vTope FROM edi.deliveryInformation; - WHILE vID <= vTope DO - + WHILE vID <= vTope DO + SET vID = vID + vGap; - - DELETE - FROM edi.deliveryInformation + + DELETE + FROM edi.deliveryInformation WHERE ID < vID AND EarliestDespatchDateTime IS NULL; - + END WHILE; - - + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -8585,15 +8585,15 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ekt_add`(vPutOrderFk INT) BEGIN - + /** * Añade ekt para las ordenes de compra de proveedores que no envian el ekt por email - * + * * @param vPutOrderFk PutOrderId de donde coger los datos **/ - - INSERT INTO edi.ekt(entryYear, - deliveryNumber, + + INSERT INTO edi.ekt(entryYear, + deliveryNumber, fec, hor, item, @@ -8633,17 +8633,17 @@ BEGIN i.value10 s6, p.id putOrderFk, sr.Item_ArticleCode, - sr.vmpID + sr.vmpID FROM edi.putOrder p - JOIN edi.supplyResponse sr ON sr.ID = p.supplyResponseID - JOIN edi.deliveryInformation di ON di.id = p.deliveryInformationID - JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID - JOIN vn.item i ON i.supplyResponseFk = sr.ID - JOIN vn.origin o ON o.id = i.originFk + JOIN edi.supplyResponse sr ON sr.ID = p.supplyResponseID + JOIN edi.deliveryInformation di ON di.id = p.deliveryInformationID + JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID + JOIN vn.item i ON i.supplyResponseFk = sr.ID + JOIN vn.origin o ON o.id = i.originFk WHERE p.id = vPutOrderFk; - + CALL edi.ekt_load(LAST_INSERT_ID()); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -8662,7 +8662,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ekt_load`(IN `vSelf` INT) proc:BEGIN - + DECLARE vRef INT; DECLARE vBuy INT; DECLARE vItem INT; @@ -8687,51 +8687,51 @@ proc:BEGIN FROM edi.ekt e LEFT JOIN edi.item i ON e.ref = i.id LEFT JOIN edi.putOrder po ON po.id = e.putOrderFk - LEFT JOIN vn.item i2 ON i2.supplyResponseFk = po.supplyResponseID + LEFT JOIN vn.item i2 ON i2.supplyResponseFk = po.supplyResponseID LEFT JOIN vn.ektEntryAssign eea ON eea.sub = e.sub LEFT JOIN edi.item_groupToOffer igto ON igto.group_code = i.group_id WHERE e.id = vSelf LIMIT 1; - + IF NOT vHasItemGroup THEN - + CALL vn.mail_insert('logistica@verdnatura.es', 'nocontestar@verdnatura.es', 'Nuevo grupo en Floramondo', vDescription); - + CALL vn.mail_insert('pako@verdnatura.es', 'nocontestar@verdnatura.es', CONCAT('Nuevo grupo en Floramondo: ', vDescription), vDescription); - + LEAVE proc; - + END IF; - + -- Asigna la entrada SELECT vn.ekt_getEntry(vSelf) INTO vEntryFk; - + -- Inserta el cubo si no existe IF vPackage = 800 THEN - + SET vHasToChangePackagingFk = TRUE; - + IF vItem THEN - + SELECT vn.item_getPackage(vItem) INTO vPackage ; - + ELSE - + SET vPackage = 8000 + vQty; INSERT IGNORE INTO vn.packaging(id, width, `depth`) SELECT vPackage, vc.ccLength / vQty, vc.ccWidth FROM vn.volumeConfig vc; - + END IF; - + ELSE - + INSERT IGNORE INTO vn2008.Cubos (Id_Cubo, X, Y, Z) SELECT bucket_id, ROUND(x_size/10), ROUND(y_size/10), ROUND(z_size/10) FROM bucket WHERE bucket_id = vPackage; - + IF ROW_COUNT() > 0 THEN INSERT INTO vn2008.mail SET @@ -8740,27 +8740,27 @@ proc:BEGIN `to` = 'ekt@verdnatura.es'; END IF; END IF; - + -- Si es una compra de Logiflora obtiene el articulo IF vPutOrderFk THEN - + SELECT i.id INTO vItem FROM edi.putOrder po JOIN vn.item i ON i.supplyResponseFk = po.supplyResponseID WHERE po.id = vPutOrderFk LIMIT 1; - + END IF; INSERT IGNORE INTO item_track SET item_id = vRef; - + IF IFNULL(vItem,0) = 0 THEN - + -- Intenta obtener el artículo en base a los atributos holandeses - + SELECT b.id, IFNULL(b.itemOriginalFk ,b.itemFk) INTO vBuy, vItem - FROM edi.ekt e + FROM edi.ekt e JOIN edi.item_track t ON t.item_id = e.ref LEFT JOIN edi.ekt l ON l.ref = e.ref LEFT JOIN vn.buy b ON b.ektFk = l.id @@ -8781,19 +8781,19 @@ proc:BEGIN AND IF(t.pro, l.pro = e.pro, TRUE) AND IF(t.package, l.package = e.package, TRUE) AND IF(t.item, l.item = e.item, TRUE) - AND i.isFloramondo = vIsFloramondoDirect - ORDER BY l.now DESC, b.id ASC + AND i.isFloramondo = vIsFloramondoDirect + ORDER BY l.now DESC, b.id ASC LIMIT 1; END IF; - + -- Si no encuentra el articulo lo crea en el caso de las compras directas en Floramondo IF ISNULL(vItem) AND vIsFloramondoDirect THEN - + CALL edi.item_getNewByEkt(vSelf, vItem); - + END IF; - + INSERT INTO vn.buy ( entryFk @@ -8816,15 +8816,15 @@ proc:BEGIN ,e.qty stickers ,@pac := IFNULL(i.stemMultiplier, 1) * e.pac / @t packing ,IFNULL(b.`grouping`, e.pac) - ,@pac * e.qty + ,@pac * e.qty ,vForceToPacking ,IF(vHasToChangePackagingFk OR ISNULL(b.packageFk), vPackage, b.packageFk) ,(IFNULL(i.weightByPiece,0) * @pac)/1000 - FROM edi.ekt e + FROM edi.ekt e LEFT JOIN vn.buy b ON b.id = vBuy LEFT JOIN vn.item i ON i.id = b.itemFk LEFT JOIN vn.supplier s ON e.pro = s.id - JOIN vn2008.config cfg + JOIN vn2008.config cfg WHERE e.id = vSelf LIMIT 1; @@ -8832,36 +8832,36 @@ proc:BEGIN CREATE TEMPORARY TABLE tmp.buyRecalc SELECT buy.id - FROM vn.buy + FROM vn.buy WHERE ektFk = vSelf; CALL vn.buy_recalcPrices(); -- Si es una compra de Logiflora hay que informar la tabla vn.saleBuy IF vPutOrderFk THEN - + REPLACE vn.saleBuy(saleFk, buyFk, workerFk) SELECT po.saleFk, b.id, account.myUser_getId() FROM edi.putOrder po JOIN vn.buy b ON b.ektFk = vSelf WHERE po.id = vPutOrderFk; - + END IF; - -- Si es una compra directa en Floramondo hay que añadirlo al ticket + -- Si es una compra directa en Floramondo hay que añadirlo al ticket IF vIsFloramondoDirect THEN SELECT t.id INTO vTicketFk FROM vn.ticket t - JOIN vn.ektEntryAssign eea - ON eea.addressFk = t.addressFk + JOIN vn.ektEntryAssign eea + ON eea.addressFk = t.addressFk AND t.warehouseFk = eea.warehouseInFk - JOIN edi.ekt e - ON e.sub = eea.sub + JOIN edi.ekt e + ON e.sub = eea.sub AND e.id = vSelf WHERE e.fec = t.shipped LIMIT 1; - + IF ISNULL(vTicketFk) THEN INSERT INTO vn.ticket ( @@ -8889,8 +8889,8 @@ proc:BEGIN z.id, z.price, z.bonus - FROM edi.ekt e - JOIN vn.ektEntryAssign eea ON eea.sub = e.sub + FROM edi.ekt e + JOIN vn.ektEntryAssign eea ON eea.sub = e.sub JOIN vn.address a ON a.id = eea.addressFk JOIN vn.company c ON c.code = 'VNL' JOIN vn.`zone` z ON z.code = 'FLORAMONDO' @@ -8898,11 +8898,11 @@ proc:BEGIN LIMIT 1; SET vTicketFk = LAST_INSERT_ID(); - + INSERT INTO vn.ticketLog - SET originFk = vTicketFk, - userFk = account.myUser_getId(), - `action` = 'insert', + SET originFk = vTicketFk, + userFk = account.myUser_getId(), + `action` = 'insert', description = CONCAT('EktLoad ha creado el ticket:', ' ', vTicketFk); END IF; @@ -8912,9 +8912,9 @@ proc:BEGIN FROM edi.ekt e JOIN edi.floraHollandConfig fhc WHERE e.id = vSelf; - + SELECT LAST_INSERT_ID() INTO vSaleFk; - + REPLACE vn.saleBuy(saleFk, buyFk, workerFk) SELECT vSaleFk, b.id, account.myUser_getId() FROM vn.buy b @@ -8925,9 +8925,9 @@ proc:BEGIN FROM edi.ekt e JOIN vn.component c ON c.code = 'purchaseValue' WHERE e.id = vSelf; - + INSERT INTO vn.saleComponent(saleFk, componentFk, value) - SELECT vSaleFk, c.id, e.pri * fhc.floramondoMargin + SELECT vSaleFk, c.id, e.pri * fhc.floramondoMargin FROM edi.ekt e JOIN edi.floraHollandConfig fhc JOIN vn.component c ON c.code = 'margin' @@ -9068,7 +9068,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `ekt_scan`(vBarcode VARCHAR(512)) BEGIN /** * Busca transaciones a partir de un código de barras, las marca como escaneadas - * y las devuelve. + * y las devuelve. * Ver https://wiki.verdnatura.es/index.php/Ekt#Algoritmos_de_lectura * * @param vBarcode Código de compra de una etiqueta de subasta @@ -9107,19 +9107,19 @@ BEGIN ENGINE = MEMORY SELECT id ektFk FROM ekt LIMIT 0; - CASE + CASE WHEN LENGTH(vBarcode) <= vFloridayBarcodeLength THEN INSERT INTO tmp.ekt - SELECT id + SELECT id FROM edi.ektRecent e WHERE e.cps = vBarcode OR e.batchNumber = vBarcode; WHEN LENGTH(vBarcode) = vFloramondoBarcodeLength THEN INSERT INTO tmp.ekt - SELECT e.id + SELECT e.id FROM edi.ektRecent e - WHERE e.pro = MID(vBarcode,2,6) + WHERE e.pro = MID(vBarcode,2,6) AND CAST(e.ptd AS SIGNED) = MID(vBarcode,8,5); ELSE @@ -9134,7 +9134,7 @@ BEGIN -- Clásico de subasta -- Trade standard -- Trade que construye como la subasta - -- Trade como el anterior pero sin trade code + -- Trade como el anterior pero sin trade code INSERT INTO tmp.ekt SELECT id FROM ekt @@ -9155,9 +9155,9 @@ BEGIN -- BatchNumber largo IF NOT vIsFound THEN INSERT INTO tmp.ekt - SELECT id + SELECT id FROM edi.ektRecent e - WHERE e.batchNumber + WHERE e.batchNumber = LEFT(vBarcode,vUsefulAuctionLeftSegmentLength) AND e.batchNumber > 0; @@ -9167,7 +9167,7 @@ BEGIN -- Order Number IF NOT vIsFound THEN INSERT INTO tmp.ekt - SELECT id + SELECT id FROM edi.ektRecent e WHERE e.putOrderFk = vBarcode; @@ -9177,7 +9177,7 @@ BEGIN -- deliveryNumber incrustado IF NOT vIsFound THEN INSERT INTO tmp.ekt - SELECT id + SELECT id FROM edi.ektRecent e WHERE e.deliveryNumber = MID(vBarcode, 4, 13) @@ -9188,7 +9188,7 @@ BEGIN END CASE; IF vIsFound THEN - UPDATE ekt e + UPDATE ekt e JOIN tmp.ekt t ON t.ektFk = e.id SET e.scanned = TRUE; END IF; @@ -9209,524 +9209,524 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `floramondo_offerRefresh`() -proc: BEGIN - DECLARE vLanded DATETIME; - DECLARE vDone INT DEFAULT FALSE; - DECLARE vFreeId INT; - DECLARE vSupplyResponseFk INT; - DECLARE vLastInserted DATETIME; - DECLARE vIsAuctionDay BOOLEAN; - DECLARE vMaxNewItems INT DEFAULT 10000; - DECLARE vStartingTime DATETIME; - DECLARE vAalsmeerMarketPlaceID VARCHAR(13) DEFAULT '8713783439043'; - DECLARE vDayRange INT; - - DECLARE cur1 CURSOR FOR - SELECT id - FROM edi.item_free; - - DECLARE cur2 CURSOR FOR - SELECT srId - FROM itemToInsert; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - DECLARE EXIT HANDLER FOR SQLSTATE '45000' - BEGIN - ROLLBACK; - RESIGNAL; - END; - - DECLARE CONTINUE HANDLER FOR SQLEXCEPTION - BEGIN - DO RELEASE_LOCK('edi.floramondo_offerRefresh'); - SET @isTriggerDisabled = FALSE; - RESIGNAL; - END; - - IF 'test' = (SELECT environment FROM util.config) THEN - LEAVE proc; - END IF; - - IF !GET_LOCK('edi.floramondo_offerRefresh', 0) THEN - LEAVE proc; - END IF; - - SELECT dayRange INTO vDayRange - FROM offerRefreshConfig; - - IF vDayRange IS NULL THEN - CALL util.throw("Variable vDayRange not declared"); - END IF; - - SET vStartingTime = util.VN_NOW(); - - TRUNCATE edi.offerList; - - INSERT INTO edi.offerList(supplier, total) - SELECT v.name, COUNT(DISTINCT sr.ID) total - FROM edi.supplyResponse sr - JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID - WHERE sr.NumberOfUnits > 0 - AND sr.EmbalageCode != 999 - GROUP BY sr.vmpID; - - UPDATE edi.offerList o - JOIN (SELECT v.name, COUNT(*) total - FROM edi.supplyOffer sr - JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID - GROUP BY sr.vmpID) sub ON o.supplier = sub.name - SET o.`filter` = sub.total; - - -- Elimina de la lista de items libres aquellos que ya existen - DELETE itf.* - FROM edi.item_free itf - JOIN vn.item i ON i.id = itf.id; - - CREATE OR REPLACE TEMPORARY TABLE tmp - (INDEX (`Item_ArticleCode`)) - ENGINE = MEMORY - SELECT t.* - FROM ( - SELECT * - FROM edi.supplyOffer - ORDER BY (MarketPlaceID = vAalsmeerMarketPlaceID) DESC, - NumberOfUnits DESC LIMIT 10000000000000000000) t - GROUP BY t.srId; - - CREATE OR REPLACE TEMPORARY TABLE edi.offer (INDEX (`srID`), INDEX (`EmbalageCode`), - INDEX (`ef1`), INDEX (`ef2`), INDEX (`ef3`), INDEX (`ef4`),INDEX (`ef5`), INDEX (`ef6`), - INDEX (`s1Value`), INDEX (`s2Value`), INDEX (`s3Value`), INDEX (`s4Value`),INDEX (`s5Value`), INDEX (`s6Value`)) - ENGINE = MEMORY - SELECT so.*, - ev1.type_description s1Value, - ev2.type_description s2Value, - ev3.type_description s3Value, - ev4.type_description s4Value, - ev5.type_description s5Value, - ev6.type_description s6Value, - eif1.feature ef1, - eif2.feature ef2, - eif3.feature ef3, - eif4.feature ef4, - eif5.feature ef5, - eif6.feature ef6 - FROM tmp so - LEFT JOIN edi.item_feature eif1 ON eif1.item_id = so.Item_ArticleCode - AND eif1.presentation_order = 1 - AND eif1.expiry_date IS NULL - LEFT JOIN edi.item_feature eif2 ON eif2.item_id = so.Item_ArticleCode - AND eif2.presentation_order = 2 - AND eif2.expiry_date IS NULL - LEFT JOIN edi.item_feature eif3 ON eif3.item_id = so.Item_ArticleCode - AND eif3.presentation_order = 3 - AND eif3.expiry_date IS NULL - LEFT JOIN edi.item_feature eif4 ON eif4.item_id = so.Item_ArticleCode - AND eif4.presentation_order = 4 - AND eif4.expiry_date IS NULL - LEFT JOIN edi.item_feature eif5 ON eif5.item_id = so.Item_ArticleCode - AND eif5.presentation_order = 5 - AND eif5.expiry_date IS NULL - LEFT JOIN edi.item_feature eif6 ON eif6.item_id = so.Item_ArticleCode - AND eif6.presentation_order = 6 - AND eif6.expiry_date IS NULL - LEFT JOIN edi.`value` ev1 ON ev1.type_id = eif1.feature - AND so.s1 = ev1.type_value - LEFT JOIN edi.`value` ev2 ON ev2.type_id = eif2.feature - AND so.s2 = ev2.type_value - LEFT JOIN edi.`value` ev3 ON ev3.type_id = eif3.feature - AND so.s3 = ev3.type_value - LEFT JOIN edi.`value` ev4 ON ev4.type_id = eif4.feature - AND so.s4 = ev4.type_value - LEFT JOIN edi.`value` ev5 ON ev5.type_id = eif5.feature - AND so.s5 = ev5.type_value - LEFT JOIN edi.`value` ev6 ON ev6.type_id = eif6.feature - AND so.s6 = ev6.type_value - ORDER BY Price; - - DROP TEMPORARY TABLE tmp; - - DELETE o - FROM edi.offer o - LEFT JOIN vn.tag t1 ON t1.ediTypeFk = o.ef1 AND t1.overwrite = 'size' - LEFT JOIN vn.tag t2 ON t2.ediTypeFk = o.ef2 AND t2.overwrite = 'size' - LEFT JOIN vn.tag t3 ON t3.ediTypeFk = o.ef3 AND t3.overwrite = 'size' - LEFT JOIN vn.tag t4 ON t4.ediTypeFk = o.ef4 AND t4.overwrite = 'size' - LEFT JOIN vn.tag t5 ON t5.ediTypeFk = o.ef5 AND t5.overwrite = 'size' - LEFT JOIN vn.tag t6 ON t6.ediTypeFk = o.ef6 AND t6.overwrite = 'size' - JOIN vn.floramondoConfig fc ON TRUE - WHERE (t1.id IS NOT NULL AND CONVERT(s1Value, UNSIGNED) > fc.itemMaxSize) - OR (t2.id IS NOT NULL AND CONVERT(s2Value, UNSIGNED) > fc.itemMaxSize) - OR (t3.id IS NOT NULL AND CONVERT(s3Value, UNSIGNED) > fc.itemMaxSize) - OR (t4.id IS NOT NULL AND CONVERT(s4Value, UNSIGNED) > fc.itemMaxSize) - OR (t5.id IS NOT NULL AND CONVERT(s5Value, UNSIGNED) > fc.itemMaxSize) - OR (t6.id IS NOT NULL AND CONVERT(s6Value, UNSIGNED) > fc.itemMaxSize); - - START TRANSACTION; - - -- Actualizamos el campo supplyResponseFk para aquellos articulos que ya estan creados y reutilizamos - UPDATE IGNORE edi.offer o - JOIN vn.item i - ON i.name = o.product_name - AND i.subname <=> o.company_name - AND i.value5 <=> o.s1Value - AND i.value6 <=> o.s2Value - AND i.value7 <=> o.s3Value - AND i.value8 <=> o.s4Value - AND i.value9 <=> o.s5Value - AND i.value10 <=> o.s6Value - AND i.NumberOfItemsPerCask <=> o.NumberOfItemsPerCask - AND i.EmbalageCode <=> o.EmbalageCode - AND i.quality <=> o.Quality - JOIN vn.itemType it ON it.id = i.typeFk - LEFT JOIN vn.sale s ON s.itemFk = i.id - LEFT JOIN vn.ticket t ON t.id = s.ticketFk - AND t.shipped > (util.VN_CURDATE() - INTERVAL 1 WEEK) - LEFT JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk - LEFT JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID - LEFT JOIN edi.putOrder po ON po.supplyResponseID = i.supplyResponseFk - AND po.OrderTradeLineDateTime > (util.VN_CURDATE() - INTERVAL 1 WEEK) - SET i.supplyResponseFk = o.srID - WHERE (sr.ID IS NULL - OR sr.NumberOfUnits = 0 - OR di.LatestOrderDateTime < util.VN_NOW() - OR di.ID IS NULL) - AND it.isInventory - AND t.id IS NULL - AND po.id IS NULL; - - CREATE OR REPLACE TEMPORARY TABLE itemToInsert - ENGINE = MEMORY - SELECT o.*, CAST(NULL AS DECIMAL(6,0)) itemFk - FROM edi.offer o - LEFT JOIN vn.item i ON i.supplyResponseFk = o.srId - WHERE i.id IS NULL - LIMIT vMaxNewItems; - - -- Reciclado de nº de item - OPEN cur1; - OPEN cur2; - - read_loop: LOOP - - FETCH cur2 INTO vSupplyResponseFk; - FETCH cur1 INTO vFreeId; - - IF vDone THEN - LEAVE read_loop; - END IF; - - UPDATE itemToInsert - SET itemFk = vFreeId - WHERE srId = vSupplyResponseFk; - - END LOOP; - - CLOSE cur1; - CLOSE cur2; - - -- Insertamos todos los items en Articles de la oferta - INSERT INTO vn.item(id, - `name`, - longName, - subName, - expenceFk, - typeFk, - intrastatFk, - originFk, - supplyResponseFk, - numberOfItemsPerCask, - embalageCode, - quality, - isFloramondo) - SELECT iti.itemFk, - iti.product_name, - iti.product_name, - iti.company_name, - iti.expenseFk, - iti.itemTypeFk, - iti.intrastatFk, - iti.originFk, - iti.`srId`, - iti.NumberOfItemsPerCask, - iti.EmbalageCode, - iti.Quality, - TRUE - FROM itemToInsert iti; - - -- Inserta la foto de los articulos nuevos (prioridad alta) - INSERT IGNORE INTO vn.itemImageQueue(itemFk, url) - SELECT i.id, PictureReference - FROM itemToInsert ii - JOIN vn.item i ON i.supplyResponseFk = ii.srId - WHERE PictureReference IS NOT NULL - AND i.image IS NULL; - - INSERT INTO edi.`log`(tableName, fieldName,fieldValue) - SELECT 'itemImageQueue','NumImagenesPtes', COUNT(*) - FROM vn.itemImageQueue - WHERE attempts = 0; - - -- Inserta si se añadiesen tags nuevos - INSERT IGNORE INTO vn.tag (name, ediTypeFk) - SELECT description, type_id FROM edi.type; - - -- Desabilita el trigger para recalcular los tags al final - SET @isTriggerDisabled = TRUE; - - -- Inserta los tags sólo en los articulos nuevos - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , ii.product_name, 1 - FROM itemToInsert ii - JOIN vn.tag t ON t.`name` = 'Producto' - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT ii.product_name IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , ii.Quality, 3 - FROM itemToInsert ii - JOIN vn.tag t ON t.`name` = 'Calidad' - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT ii.Quality IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , ii.company_name, 4 - FROM itemToInsert ii - JOIN vn.tag t ON t.`name` = 'Productor' - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT ii.company_name IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s1Value, 5 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef1 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s1Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s2Value, 6 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef2 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s2Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s3Value, 7 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef3 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s3Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s4Value, 8 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef4 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s4Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s5Value, 9 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef5 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s5Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s6Value, 10 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef6 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s6Value IS NULL; - - INSERT IGNORE INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id, IFNULL(ink.name, ik.color), 11 - FROM itemToInsert ii - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - JOIN vn.tag t ON t.`name` = 'Color' - LEFT JOIN edi.feature f ON f.item_id = ii.Item_ArticleCode - LEFT JOIN edi.`type` tp ON tp.type_id = f.feature_type_id - AND tp.`description` = 'Hoofdkleur 1' - LEFT JOIN vn.ink ON ink.dutchCode = f.feature_value - LEFT JOIN vn.itemInk ik ON ik.longName = i.longName - WHERE ink.name IS NOT NULL - OR ik.color IS NOT NULL; - - CREATE OR REPLACE TABLE tmp.item - (PRIMARY KEY (id)) - SELECT i.id FROM vn.item i - JOIN itemToInsert ii ON i.supplyResponseFk = ii.`srId`; - - CALL vn.item_refreshTags(); - - DROP TABLE tmp.item; - - SELECT MIN(LatestDeliveryDateTime) INTO vLanded - FROM edi.supplyResponse sr - JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID - JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID - JOIN vn.floramondoConfig fc - WHERE mp.isLatestOrderDateTimeRelevant - AND di.LatestOrderDateTime > IF( - fc.MaxLatestOrderHour > HOUR(util.VN_NOW()), - util.VN_CURDATE(), - util.VN_CURDATE() + INTERVAL 1 DAY); - - UPDATE vn.floramondoConfig - SET nextLanded = vLanded - WHERE vLanded IS NOT NULL; - - -- Elimina la oferta obsoleta - UPDATE vn.buy b - JOIN vn.entry e ON e.id = b.entryFk - JOIN vn.travel tr ON tr.id = e.travelFk - JOIN vn.agencyMode am ON am.id = tr.agencyModeFk - JOIN vn.item i ON i.id = b.itemFk - LEFT JOIN edi.supplyResponse sr ON i.supplyResponseFk = sr.ID - LEFT JOIN edi.deliveryInformation di ON di.ID = b.deliveryFk - SET b.quantity = 0 - WHERE (IFNULL(di.LatestOrderDateTime,util.VN_NOW()) <= util.VN_NOW() - OR i.supplyResponseFk IS NULL - OR sr.NumberOfUnits = 0) - AND am.name = 'LOGIFLORA' - AND e.isRaid; - - -- Localiza las entradas de cada almacen - UPDATE edi.warehouseFloramondo - SET entryFk = vn.entry_getForLogiflora(vLanded + INTERVAL travellingDays DAY, warehouseFk); - - IF vLanded IS NOT NULL THEN - -- Actualiza la oferta existente - UPDATE vn.buy b - JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk - JOIN vn.item i ON i.id = b.itemFk - JOIN edi.offer o ON i.supplyResponseFk = o.`srId` - SET b.quantity = o.NumberOfUnits * o.NumberOfItemsPerCask, - b.buyingValue = o.price - WHERE (b.quantity <> o.NumberOfUnits * o.NumberOfItemsPerCask - OR b.buyingValue <> o.price); - - -- Inserta el resto - SET vLastInserted := util.VN_NOW(); - - -- Inserta la oferta - INSERT INTO vn.buy ( - entryFk, - itemFk, - quantity, - buyingValue, - stickers, - packing, - `grouping`, - groupingMode, - packageFk, - deliveryFk) - SELECT wf.entryFk, - i.id, - o.NumberOfUnits * o.NumberOfItemsPerCask quantity, - o.Price, - o.NumberOfUnits etiquetas, - o.NumberOfItemsPerCask packing, - GREATEST(1, IFNULL(o.MinimumQuantity,0)) * o.NumberOfItemsPerCask `grouping`, - 2, -- Obliga al Packing - o.embalageCode, - o.diId - FROM edi.offer o - JOIN vn.item i ON i.supplyResponseFk = o.srId - JOIN edi.warehouseFloramondo wf - JOIN vn.packaging p ON p.id - LIKE o.embalageCode - LEFT JOIN vn.buy b ON b.itemFk = i.id - AND b.entryFk = wf.entryFk - WHERE b.id IS NULL; -- Quitar esta linea y mirar de crear los packages a tiempo REAL - - INSERT INTO vn.itemCost( - itemFk, - warehouseFk, - cm3, - cm3delivery) - SELECT b.itemFk, - wf.warehouseFk, - @cm3 := vn.buy_getUnitVolume(b.id), - IFNULL((vc.standardFlowerBox * 1000) / i.packingOut, @cm3) - FROM warehouseFloramondo wf - JOIN vn.volumeConfig vc - JOIN vn.buy b ON b.entryFk = wf.entryFk - JOIN vn.item i ON i.id = b.itemFk - LEFT JOIN vn.itemCost ic ON ic.itemFk = b.itemFk - AND ic.warehouseFk = wf.warehouseFk - WHERE (ic.cm3 IS NULL OR ic.cm3 = 0) - ON DUPLICATE KEY UPDATE cm3 = @cm3, cm3delivery = IFNULL((vc.standardFlowerBox * 1000) / i.packingOut, @cm3); - - CREATE OR REPLACE TEMPORARY TABLE tmp.buyRecalc - SELECT b.id - FROM vn.buy b - JOIN warehouseFloramondo wf ON wf.entryFk = b.entryFk - WHERE b.created >= vLastInserted; - - CALL vn.buy_recalcPrices(); - - UPDATE edi.offerList o - JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total - FROM vn.buy b - JOIN vn.item i ON i.id = b.itemFk - JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk - JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID - JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk - JOIN vn.warehouse w ON w.id = wf.warehouseFk - WHERE w.name = 'VNH' - AND b.quantity > 0 - GROUP BY sr.vmpID) sub ON o.supplier = sub.name - SET o.vnh = sub.total; - - UPDATE edi.offerList o - JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total - FROM vn.buy b - JOIN vn.item i ON i.id = b.itemFk - JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk - JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID - JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk - JOIN vn.warehouse w ON w.id = wf.warehouseFk - WHERE w.name = 'ALGEMESI' - AND b.quantity > 0 - GROUP BY sr.vmpID) sub ON o.supplier = sub.name - SET o.algemesi = sub.total; - END IF; - - DROP TEMPORARY TABLE - edi.offer, - itemToInsert; - - SET @isTriggerDisabled = FALSE; - - COMMIT; - - -- Esto habria que pasarlo a procesos programados o trabajar con tags y dejar las familias - UPDATE vn.item i - SET typeFk = 121 - WHERE i.longName LIKE 'Rosa Garden %' - AND typeFk = 17; - - UPDATE vn.item i - SET typeFk = 156 - WHERE i.longName LIKE 'Rosa ec %' - AND typeFk = 17; - - -- Refresca las fotos de los items existentes que mostramos (prioridad baja) - INSERT IGNORE INTO vn.itemImageQueue(itemFk, url, priority) - SELECT i.id, sr.PictureReference, 100 - FROM edi.supplyResponse sr - JOIN vn.item i ON i.supplyResponseFk = sr.ID - JOIN edi.supplyOffer so ON so.srId = sr.ID - JOIN hedera.image i2 ON i2.name = i.image - AND i2.collectionFk = 'catalog' - WHERE i2.updated <= (UNIX_TIMESTAMP(util.VN_NOW()) - vDayRange) - AND sr.NumberOfUnits; - - INSERT INTO edi.`log` - SET tableName = 'floramondo_offerRefresh', - fieldName = 'Tiempo de proceso', - fieldValue = TIMEDIFF(util.VN_NOW(), vStartingTime); - - DO RELEASE_LOCK('edi.floramondo_offerRefresh'); +proc: BEGIN + DECLARE vLanded DATETIME; + DECLARE vDone INT DEFAULT FALSE; + DECLARE vFreeId INT; + DECLARE vSupplyResponseFk INT; + DECLARE vLastInserted DATETIME; + DECLARE vIsAuctionDay BOOLEAN; + DECLARE vMaxNewItems INT DEFAULT 10000; + DECLARE vStartingTime DATETIME; + DECLARE vAalsmeerMarketPlaceID VARCHAR(13) DEFAULT '8713783439043'; + DECLARE vDayRange INT; + + DECLARE cur1 CURSOR FOR + SELECT id + FROM edi.item_free; + + DECLARE cur2 CURSOR FOR + SELECT srId + FROM itemToInsert; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + DECLARE EXIT HANDLER FOR SQLSTATE '45000' + BEGIN + ROLLBACK; + RESIGNAL; + END; + + DECLARE CONTINUE HANDLER FOR SQLEXCEPTION + BEGIN + DO RELEASE_LOCK('edi.floramondo_offerRefresh'); + SET @isTriggerDisabled = FALSE; + RESIGNAL; + END; + + IF 'test' = (SELECT environment FROM util.config) THEN + LEAVE proc; + END IF; + + IF !GET_LOCK('edi.floramondo_offerRefresh', 0) THEN + LEAVE proc; + END IF; + + SELECT dayRange INTO vDayRange + FROM offerRefreshConfig; + + IF vDayRange IS NULL THEN + CALL util.throw("Variable vDayRange not declared"); + END IF; + + SET vStartingTime = util.VN_NOW(); + + TRUNCATE edi.offerList; + + INSERT INTO edi.offerList(supplier, total) + SELECT v.name, COUNT(DISTINCT sr.ID) total + FROM edi.supplyResponse sr + JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID + WHERE sr.NumberOfUnits > 0 + AND sr.EmbalageCode != 999 + GROUP BY sr.vmpID; + + UPDATE edi.offerList o + JOIN (SELECT v.name, COUNT(*) total + FROM edi.supplyOffer sr + JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID + GROUP BY sr.vmpID) sub ON o.supplier = sub.name + SET o.`filter` = sub.total; + + -- Elimina de la lista de items libres aquellos que ya existen + DELETE itf.* + FROM edi.item_free itf + JOIN vn.item i ON i.id = itf.id; + + CREATE OR REPLACE TEMPORARY TABLE tmp + (INDEX (`Item_ArticleCode`)) + ENGINE = MEMORY + SELECT t.* + FROM ( + SELECT * + FROM edi.supplyOffer + ORDER BY (MarketPlaceID = vAalsmeerMarketPlaceID) DESC, + NumberOfUnits DESC LIMIT 10000000000000000000) t + GROUP BY t.srId; + + CREATE OR REPLACE TEMPORARY TABLE edi.offer (INDEX (`srID`), INDEX (`EmbalageCode`), + INDEX (`ef1`), INDEX (`ef2`), INDEX (`ef3`), INDEX (`ef4`),INDEX (`ef5`), INDEX (`ef6`), + INDEX (`s1Value`), INDEX (`s2Value`), INDEX (`s3Value`), INDEX (`s4Value`),INDEX (`s5Value`), INDEX (`s6Value`)) + ENGINE = MEMORY + SELECT so.*, + ev1.type_description s1Value, + ev2.type_description s2Value, + ev3.type_description s3Value, + ev4.type_description s4Value, + ev5.type_description s5Value, + ev6.type_description s6Value, + eif1.feature ef1, + eif2.feature ef2, + eif3.feature ef3, + eif4.feature ef4, + eif5.feature ef5, + eif6.feature ef6 + FROM tmp so + LEFT JOIN edi.item_feature eif1 ON eif1.item_id = so.Item_ArticleCode + AND eif1.presentation_order = 1 + AND eif1.expiry_date IS NULL + LEFT JOIN edi.item_feature eif2 ON eif2.item_id = so.Item_ArticleCode + AND eif2.presentation_order = 2 + AND eif2.expiry_date IS NULL + LEFT JOIN edi.item_feature eif3 ON eif3.item_id = so.Item_ArticleCode + AND eif3.presentation_order = 3 + AND eif3.expiry_date IS NULL + LEFT JOIN edi.item_feature eif4 ON eif4.item_id = so.Item_ArticleCode + AND eif4.presentation_order = 4 + AND eif4.expiry_date IS NULL + LEFT JOIN edi.item_feature eif5 ON eif5.item_id = so.Item_ArticleCode + AND eif5.presentation_order = 5 + AND eif5.expiry_date IS NULL + LEFT JOIN edi.item_feature eif6 ON eif6.item_id = so.Item_ArticleCode + AND eif6.presentation_order = 6 + AND eif6.expiry_date IS NULL + LEFT JOIN edi.`value` ev1 ON ev1.type_id = eif1.feature + AND so.s1 = ev1.type_value + LEFT JOIN edi.`value` ev2 ON ev2.type_id = eif2.feature + AND so.s2 = ev2.type_value + LEFT JOIN edi.`value` ev3 ON ev3.type_id = eif3.feature + AND so.s3 = ev3.type_value + LEFT JOIN edi.`value` ev4 ON ev4.type_id = eif4.feature + AND so.s4 = ev4.type_value + LEFT JOIN edi.`value` ev5 ON ev5.type_id = eif5.feature + AND so.s5 = ev5.type_value + LEFT JOIN edi.`value` ev6 ON ev6.type_id = eif6.feature + AND so.s6 = ev6.type_value + ORDER BY Price; + + DROP TEMPORARY TABLE tmp; + + DELETE o + FROM edi.offer o + LEFT JOIN vn.tag t1 ON t1.ediTypeFk = o.ef1 AND t1.overwrite = 'size' + LEFT JOIN vn.tag t2 ON t2.ediTypeFk = o.ef2 AND t2.overwrite = 'size' + LEFT JOIN vn.tag t3 ON t3.ediTypeFk = o.ef3 AND t3.overwrite = 'size' + LEFT JOIN vn.tag t4 ON t4.ediTypeFk = o.ef4 AND t4.overwrite = 'size' + LEFT JOIN vn.tag t5 ON t5.ediTypeFk = o.ef5 AND t5.overwrite = 'size' + LEFT JOIN vn.tag t6 ON t6.ediTypeFk = o.ef6 AND t6.overwrite = 'size' + JOIN vn.floramondoConfig fc ON TRUE + WHERE (t1.id IS NOT NULL AND CONVERT(s1Value, UNSIGNED) > fc.itemMaxSize) + OR (t2.id IS NOT NULL AND CONVERT(s2Value, UNSIGNED) > fc.itemMaxSize) + OR (t3.id IS NOT NULL AND CONVERT(s3Value, UNSIGNED) > fc.itemMaxSize) + OR (t4.id IS NOT NULL AND CONVERT(s4Value, UNSIGNED) > fc.itemMaxSize) + OR (t5.id IS NOT NULL AND CONVERT(s5Value, UNSIGNED) > fc.itemMaxSize) + OR (t6.id IS NOT NULL AND CONVERT(s6Value, UNSIGNED) > fc.itemMaxSize); + + START TRANSACTION; + + -- Actualizamos el campo supplyResponseFk para aquellos articulos que ya estan creados y reutilizamos + UPDATE IGNORE edi.offer o + JOIN vn.item i + ON i.name = o.product_name + AND i.subname <=> o.company_name + AND i.value5 <=> o.s1Value + AND i.value6 <=> o.s2Value + AND i.value7 <=> o.s3Value + AND i.value8 <=> o.s4Value + AND i.value9 <=> o.s5Value + AND i.value10 <=> o.s6Value + AND i.NumberOfItemsPerCask <=> o.NumberOfItemsPerCask + AND i.EmbalageCode <=> o.EmbalageCode + AND i.quality <=> o.Quality + JOIN vn.itemType it ON it.id = i.typeFk + LEFT JOIN vn.sale s ON s.itemFk = i.id + LEFT JOIN vn.ticket t ON t.id = s.ticketFk + AND t.shipped > (util.VN_CURDATE() - INTERVAL 1 WEEK) + LEFT JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk + LEFT JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID + LEFT JOIN edi.putOrder po ON po.supplyResponseID = i.supplyResponseFk + AND po.OrderTradeLineDateTime > (util.VN_CURDATE() - INTERVAL 1 WEEK) + SET i.supplyResponseFk = o.srID + WHERE (sr.ID IS NULL + OR sr.NumberOfUnits = 0 + OR di.LatestOrderDateTime < util.VN_NOW() + OR di.ID IS NULL) + AND it.isInventory + AND t.id IS NULL + AND po.id IS NULL; + + CREATE OR REPLACE TEMPORARY TABLE itemToInsert + ENGINE = MEMORY + SELECT o.*, CAST(NULL AS DECIMAL(6,0)) itemFk + FROM edi.offer o + LEFT JOIN vn.item i ON i.supplyResponseFk = o.srId + WHERE i.id IS NULL + LIMIT vMaxNewItems; + + -- Reciclado de nº de item + OPEN cur1; + OPEN cur2; + + read_loop: LOOP + + FETCH cur2 INTO vSupplyResponseFk; + FETCH cur1 INTO vFreeId; + + IF vDone THEN + LEAVE read_loop; + END IF; + + UPDATE itemToInsert + SET itemFk = vFreeId + WHERE srId = vSupplyResponseFk; + + END LOOP; + + CLOSE cur1; + CLOSE cur2; + + -- Insertamos todos los items en Articles de la oferta + INSERT INTO vn.item(id, + `name`, + longName, + subName, + expenceFk, + typeFk, + intrastatFk, + originFk, + supplyResponseFk, + numberOfItemsPerCask, + embalageCode, + quality, + isFloramondo) + SELECT iti.itemFk, + iti.product_name, + iti.product_name, + iti.company_name, + iti.expenseFk, + iti.itemTypeFk, + iti.intrastatFk, + iti.originFk, + iti.`srId`, + iti.NumberOfItemsPerCask, + iti.EmbalageCode, + iti.Quality, + TRUE + FROM itemToInsert iti; + + -- Inserta la foto de los articulos nuevos (prioridad alta) + INSERT IGNORE INTO vn.itemImageQueue(itemFk, url) + SELECT i.id, PictureReference + FROM itemToInsert ii + JOIN vn.item i ON i.supplyResponseFk = ii.srId + WHERE PictureReference IS NOT NULL + AND i.image IS NULL; + + INSERT INTO edi.`log`(tableName, fieldName,fieldValue) + SELECT 'itemImageQueue','NumImagenesPtes', COUNT(*) + FROM vn.itemImageQueue + WHERE attempts = 0; + + -- Inserta si se añadiesen tags nuevos + INSERT IGNORE INTO vn.tag (name, ediTypeFk) + SELECT description, type_id FROM edi.type; + + -- Desabilita el trigger para recalcular los tags al final + SET @isTriggerDisabled = TRUE; + + -- Inserta los tags sólo en los articulos nuevos + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , ii.product_name, 1 + FROM itemToInsert ii + JOIN vn.tag t ON t.`name` = 'Producto' + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT ii.product_name IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , ii.Quality, 3 + FROM itemToInsert ii + JOIN vn.tag t ON t.`name` = 'Calidad' + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT ii.Quality IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , ii.company_name, 4 + FROM itemToInsert ii + JOIN vn.tag t ON t.`name` = 'Productor' + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT ii.company_name IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s1Value, 5 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef1 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s1Value IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s2Value, 6 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef2 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s2Value IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s3Value, 7 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef3 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s3Value IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s4Value, 8 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef4 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s4Value IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s5Value, 9 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef5 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s5Value IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s6Value, 10 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef6 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s6Value IS NULL; + + INSERT IGNORE INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id, IFNULL(ink.name, ik.color), 11 + FROM itemToInsert ii + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + JOIN vn.tag t ON t.`name` = 'Color' + LEFT JOIN edi.feature f ON f.item_id = ii.Item_ArticleCode + LEFT JOIN edi.`type` tp ON tp.type_id = f.feature_type_id + AND tp.`description` = 'Hoofdkleur 1' + LEFT JOIN vn.ink ON ink.dutchCode = f.feature_value + LEFT JOIN vn.itemInk ik ON ik.longName = i.longName + WHERE ink.name IS NOT NULL + OR ik.color IS NOT NULL; + + CREATE OR REPLACE TABLE tmp.item + (PRIMARY KEY (id)) + SELECT i.id FROM vn.item i + JOIN itemToInsert ii ON i.supplyResponseFk = ii.`srId`; + + CALL vn.item_refreshTags(); + + DROP TABLE tmp.item; + + SELECT MIN(LatestDeliveryDateTime) INTO vLanded + FROM edi.supplyResponse sr + JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID + JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID + JOIN vn.floramondoConfig fc + WHERE mp.isLatestOrderDateTimeRelevant + AND di.LatestOrderDateTime > IF( + fc.MaxLatestOrderHour > HOUR(util.VN_NOW()), + util.VN_CURDATE(), + util.VN_CURDATE() + INTERVAL 1 DAY); + + UPDATE vn.floramondoConfig + SET nextLanded = vLanded + WHERE vLanded IS NOT NULL; + + -- Elimina la oferta obsoleta + UPDATE vn.buy b + JOIN vn.entry e ON e.id = b.entryFk + JOIN vn.travel tr ON tr.id = e.travelFk + JOIN vn.agencyMode am ON am.id = tr.agencyModeFk + JOIN vn.item i ON i.id = b.itemFk + LEFT JOIN edi.supplyResponse sr ON i.supplyResponseFk = sr.ID + LEFT JOIN edi.deliveryInformation di ON di.ID = b.deliveryFk + SET b.quantity = 0 + WHERE (IFNULL(di.LatestOrderDateTime,util.VN_NOW()) <= util.VN_NOW() + OR i.supplyResponseFk IS NULL + OR sr.NumberOfUnits = 0) + AND am.name = 'LOGIFLORA' + AND e.isRaid; + + -- Localiza las entradas de cada almacen + UPDATE edi.warehouseFloramondo + SET entryFk = vn.entry_getForLogiflora(vLanded + INTERVAL travellingDays DAY, warehouseFk); + + IF vLanded IS NOT NULL THEN + -- Actualiza la oferta existente + UPDATE vn.buy b + JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk + JOIN vn.item i ON i.id = b.itemFk + JOIN edi.offer o ON i.supplyResponseFk = o.`srId` + SET b.quantity = o.NumberOfUnits * o.NumberOfItemsPerCask, + b.buyingValue = o.price + WHERE (b.quantity <> o.NumberOfUnits * o.NumberOfItemsPerCask + OR b.buyingValue <> o.price); + + -- Inserta el resto + SET vLastInserted := util.VN_NOW(); + + -- Inserta la oferta + INSERT INTO vn.buy ( + entryFk, + itemFk, + quantity, + buyingValue, + stickers, + packing, + `grouping`, + groupingMode, + packageFk, + deliveryFk) + SELECT wf.entryFk, + i.id, + o.NumberOfUnits * o.NumberOfItemsPerCask quantity, + o.Price, + o.NumberOfUnits etiquetas, + o.NumberOfItemsPerCask packing, + GREATEST(1, IFNULL(o.MinimumQuantity,0)) * o.NumberOfItemsPerCask `grouping`, + 2, -- Obliga al Packing + o.embalageCode, + o.diId + FROM edi.offer o + JOIN vn.item i ON i.supplyResponseFk = o.srId + JOIN edi.warehouseFloramondo wf + JOIN vn.packaging p ON p.id + LIKE o.embalageCode + LEFT JOIN vn.buy b ON b.itemFk = i.id + AND b.entryFk = wf.entryFk + WHERE b.id IS NULL; -- Quitar esta linea y mirar de crear los packages a tiempo REAL + + INSERT INTO vn.itemCost( + itemFk, + warehouseFk, + cm3, + cm3delivery) + SELECT b.itemFk, + wf.warehouseFk, + @cm3 := vn.buy_getUnitVolume(b.id), + IFNULL((vc.standardFlowerBox * 1000) / i.packingOut, @cm3) + FROM warehouseFloramondo wf + JOIN vn.volumeConfig vc + JOIN vn.buy b ON b.entryFk = wf.entryFk + JOIN vn.item i ON i.id = b.itemFk + LEFT JOIN vn.itemCost ic ON ic.itemFk = b.itemFk + AND ic.warehouseFk = wf.warehouseFk + WHERE (ic.cm3 IS NULL OR ic.cm3 = 0) + ON DUPLICATE KEY UPDATE cm3 = @cm3, cm3delivery = IFNULL((vc.standardFlowerBox * 1000) / i.packingOut, @cm3); + + CREATE OR REPLACE TEMPORARY TABLE tmp.buyRecalc + SELECT b.id + FROM vn.buy b + JOIN warehouseFloramondo wf ON wf.entryFk = b.entryFk + WHERE b.created >= vLastInserted; + + CALL vn.buy_recalcPrices(); + + UPDATE edi.offerList o + JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total + FROM vn.buy b + JOIN vn.item i ON i.id = b.itemFk + JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk + JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID + JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk + JOIN vn.warehouse w ON w.id = wf.warehouseFk + WHERE w.name = 'VNH' + AND b.quantity > 0 + GROUP BY sr.vmpID) sub ON o.supplier = sub.name + SET o.vnh = sub.total; + + UPDATE edi.offerList o + JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total + FROM vn.buy b + JOIN vn.item i ON i.id = b.itemFk + JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk + JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID + JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk + JOIN vn.warehouse w ON w.id = wf.warehouseFk + WHERE w.name = 'ALGEMESI' + AND b.quantity > 0 + GROUP BY sr.vmpID) sub ON o.supplier = sub.name + SET o.algemesi = sub.total; + END IF; + + DROP TEMPORARY TABLE + edi.offer, + itemToInsert; + + SET @isTriggerDisabled = FALSE; + + COMMIT; + + -- Esto habria que pasarlo a procesos programados o trabajar con tags y dejar las familias + UPDATE vn.item i + SET typeFk = 121 + WHERE i.longName LIKE 'Rosa Garden %' + AND typeFk = 17; + + UPDATE vn.item i + SET typeFk = 156 + WHERE i.longName LIKE 'Rosa ec %' + AND typeFk = 17; + + -- Refresca las fotos de los items existentes que mostramos (prioridad baja) + INSERT IGNORE INTO vn.itemImageQueue(itemFk, url, priority) + SELECT i.id, sr.PictureReference, 100 + FROM edi.supplyResponse sr + JOIN vn.item i ON i.supplyResponseFk = sr.ID + JOIN edi.supplyOffer so ON so.srId = sr.ID + JOIN hedera.image i2 ON i2.name = i.image + AND i2.collectionFk = 'catalog' + WHERE i2.updated <= (UNIX_TIMESTAMP(util.VN_NOW()) - vDayRange) + AND sr.NumberOfUnits; + + INSERT INTO edi.`log` + SET tableName = 'floramondo_offerRefresh', + fieldName = 'Tiempo de proceso', + fieldValue = TIMEDIFF(util.VN_NOW(), vStartingTime); + + DO RELEASE_LOCK('edi.floramondo_offerRefresh'); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -9793,7 +9793,7 @@ BEGIN /** * Devuelve un número nuevo de item a partir de un registro de la tabla edi.ekt - * + * * @param vEktFk Identificador de la tabla edi.ekt */ @@ -9802,17 +9802,17 @@ BEGIN SELECT MIN(id) id INTO vItemFk FROM edi.item_free; - DELETE FROM edi.item_free + DELETE FROM edi.item_free WHERE id = vItemFk; - + COMMIT; - + IF ISNULL(vItemFk) THEN SELECT MAX(i.id) + 1 INTO vItemFk FROM vn.item i; END IF; - + INSERT INTO vn.item(id, `name`, longName, @@ -9838,118 +9838,118 @@ BEGIN least(IF((e.package = 800),((e.package * 10) + e.pac), e.package), IFNULL(idt.bucket_id, '999')) packageFk, e.cat, TRUE - FROM edi.ekt e - JOIN edi.item i ON i.id = e.`ref` - JOIN edi.item_groupToOffer igto ON igto.group_code = i.group_id - LEFT JOIN edi.item_defaultType idt ON idt.item_id = e.`ref` + FROM edi.ekt e + JOIN edi.item i ON i.id = e.`ref` + JOIN edi.item_groupToOffer igto ON igto.group_code = i.group_id + LEFT JOIN edi.item_defaultType idt ON idt.item_id = e.`ref` WHERE e.id = vEktFk; SET @isTriggerDisabled = TRUE; - + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id , e.item , 1 - FROM edi.ekt e + SELECT vItemFk, t.id , e.item , 1 + FROM edi.ekt e JOIN vn.tag t ON t.`name` = 'Producto' WHERE e.id = vEktFk AND NOT ISNULL(e.item); INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id , e.cat , 3 - FROM edi.ekt e + SELECT vItemFk, t.id , e.cat , 3 + FROM edi.ekt e JOIN vn.tag t ON t.`name` = 'Calidad' WHERE e.id = vEktFk AND NOT ISNULL(e.cat); - + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id , s.company_name , 4 - FROM edi.ekt e + SELECT vItemFk, t.id , s.company_name , 4 + FROM edi.ekt e JOIN edi.supplier s ON s.supplier_id = e.pro JOIN vn.tag t ON t.`name` = 'Productor' WHERE e.id = vEktFk AND NOT ISNULL(s.company_name); INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id , e.s1, 5 + SELECT vItemFk, t.id , e.s1, 5 FROM edi.ekt e - LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` - AND eif.presentation_order = 1 + LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` + AND eif.presentation_order = 1 AND eif.expiry_date IS NULL - LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature + LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature AND e.s1 = ev.type_value JOIN vn.tag t ON t.ediTypeFk = eif.feature WHERE e.id = vEktFk AND NOT ISNULL(e.s1); - + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id , e.s2, 6 + SELECT vItemFk, t.id , e.s2, 6 FROM edi.ekt e - LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` - AND eif.presentation_order = 2 + LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` + AND eif.presentation_order = 2 AND eif.expiry_date IS NULL - LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature + LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature AND e.s2 = ev.type_value JOIN vn.tag t ON t.ediTypeFk = eif.feature WHERE e.id = vEktFk AND NOT ISNULL(e.s2); - + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id , e.s3, 7 + SELECT vItemFk, t.id , e.s3, 7 FROM edi.ekt e - LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` - AND eif.presentation_order = 3 + LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` + AND eif.presentation_order = 3 AND eif.expiry_date IS NULL - LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature + LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature AND e.s3 = ev.type_value JOIN vn.tag t ON t.ediTypeFk = eif.feature WHERE e.id = vEktFk AND NOT ISNULL(e.s3); - + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id , e.s4, 8 + SELECT vItemFk, t.id , e.s4, 8 FROM edi.ekt e - LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` + LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` AND eif.presentation_order = 4 AND eif.expiry_date IS NULL - LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature + LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature AND e.s4 = ev.type_value JOIN vn.tag t ON t.ediTypeFk = eif.feature WHERE e.id = vEktFk AND NOT ISNULL(e.s4); - + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id , e.s5, 9 + SELECT vItemFk, t.id , e.s5, 9 FROM edi.ekt e - LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` + LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` AND eif.presentation_order = 5 AND eif.expiry_date IS NULL - LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature + LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature AND e.s5 = ev.type_value JOIN vn.tag t ON t.ediTypeFk = eif.feature WHERE e.id = vEktFk AND NOT ISNULL(e.s5); INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id , e.s6, 10 + SELECT vItemFk, t.id , e.s6, 10 FROM edi.ekt e - LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` + LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` AND eif.presentation_order = 6 AND eif.expiry_date IS NULL - LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature + LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature AND e.s6 = ev.type_value JOIN vn.tag t ON t.ediTypeFk = eif.feature WHERE e.id = vEktFk AND NOT ISNULL(e.s6); INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id, IFNULL(ink.name, ik.color), 11 - FROM edi.ekt e + SELECT vItemFk, t.id, IFNULL(ink.name, ik.color), 11 + FROM edi.ekt e JOIN vn.tag t ON t.`name` = 'Color' - LEFT JOIN edi.feature f ON f.item_id = e.`ref` + LEFT JOIN edi.feature f ON f.item_id = e.`ref` LEFT JOIN edi.`type` tp ON tp.type_id = f.feature_type_id AND tp.`description` = 'Hoofdkleur 1' LEFT JOIN vn.ink ON ink.dutchCode = f.feature_value LEFT JOIN vn.itemInk ik ON ik.longName = e.item WHERE e.id = vEktFk - AND ( ink.name IS NOT NULL + AND ( ink.name IS NOT NULL OR ik.color IS NOT NULL) LIMIT 1; @@ -10016,7 +10016,7 @@ BEGIN sender = vSender, senderFk = vSenderId, messageId = vMessageId; - + IF vIsDuplicated THEN SELECT id INTO vSelf FROM mail @@ -10838,7 +10838,7 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `hedera`.`order_afterInsert` AFTER INSERT ON `order` FOR EACH ROW -BEGIN +BEGIN IF NEW.address_id = 2850 THEN -- Fallo que se insertan no se sabe como tickets en este cliente CALL vn.mail_insert( @@ -10847,7 +10847,7 @@ BEGIN 'Creada order al address 2850', CONCAT(account.myUser_getName(), ' ha creado la order ',NEW.id) ); - + END IF; END */;; DELIMITER ; @@ -10864,27 +10864,27 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `hedera`.`order_afterUpdate` - AFTER UPDATE ON `order` - FOR EACH ROW -BEGIN - CALL stock.log_add('order', NEW.id, OLD.id); - - IF !(OLD.address_id <=> NEW.address_id) - OR !(OLD.company_id <=> NEW.company_id) - OR !(OLD.customer_id <=> NEW.customer_id) THEN - CALL order_requestRecalc(NEW.id); - END IF; - - IF !(OLD.address_id <=> NEW.address_id) AND NEW.address_id = 2850 THEN - -- Fallo que se actualiza no se sabe como tickets en este cliente - CALL vn.mail_insert( - 'jgallego@verdnatura.es', - 'noreply@verdnatura.es', - 'Actualizada order al address 2850', - CONCAT(account.myUser_getName(), ' ha creado la order ',NEW.id) - ); - END IF; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `hedera`.`order_afterUpdate` + AFTER UPDATE ON `order` + FOR EACH ROW +BEGIN + CALL stock.log_add('order', NEW.id, OLD.id); + + IF !(OLD.address_id <=> NEW.address_id) + OR !(OLD.company_id <=> NEW.company_id) + OR !(OLD.customer_id <=> NEW.customer_id) THEN + CALL order_requestRecalc(NEW.id); + END IF; + + IF !(OLD.address_id <=> NEW.address_id) AND NEW.address_id = 2850 THEN + -- Fallo que se actualiza no se sabe como tickets en este cliente + CALL vn.mail_insert( + 'jgallego@verdnatura.es', + 'noreply@verdnatura.es', + 'Actualizada order al address 2850', + CONCAT(account.myUser_getName(), ' ha creado la order ',NEW.id) + ); + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -10999,12 +10999,12 @@ DELIMITER ;; BEGIN DECLARE vIsFirst BOOL; - SELECT (first_row_stamp IS NULL) INTO vIsFirst - FROM `order` + SELECT (first_row_stamp IS NULL) INTO vIsFirst + FROM `order` WHERE id = NEW.orderFk; IF vIsFirst THEN - UPDATE `order` SET first_row_stamp = util.VN_NOW() + UPDATE `order` SET first_row_stamp = util.VN_NOW() WHERE id = NEW.orderFk; END IF; END */;; @@ -11593,7 +11593,7 @@ BEGIN IF vCount = 0 THEN RETURN FALSE; - END IF; + END IF; SELECT COUNT(*) > 0 INTO vHasRole @@ -11674,14 +11674,14 @@ BEGIN * @return tmp.ticketComponent * @return tmp.ticketLot * @return tmp.zoneGetShipped - */ + */ DECLARE vAgencyMode INT; - + SELECT a.agencyModeFk INTO vAgencyMode FROM myClient c JOIN vn.address a ON a.clientFk = c.id - WHERE a.id = vAddress; + WHERE a.id = vAddress; CALL vn.available_calc(vDelivery, vAddress, vAgencyMode); @@ -11694,7 +11694,7 @@ BEGIN JOIN tmp.availableCalc a ON a.calcFk = c.calc_id WHERE c.available > 0 GROUP BY c.item_id; - + CALL vn.catalog_calculate(vDelivery, vAddress, vAgencyMode); DROP TEMPORARY TABLE tmp.item; @@ -11796,7 +11796,7 @@ BEGIN */ DROP TEMPORARY TABLE IF EXISTS tmp.item; CREATE TEMPORARY TABLE tmp.item - ENGINE = MEMORY + ENGINE = MEMORY SELECT vSelf itemFk; CALL vn.catalog_calculate(vLanded, vAddressFk, vAgencyModeFk); @@ -11836,7 +11836,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getVisible`( vType INT, vPrefix VARCHAR(255)) BEGIN - + /** * Gets visible items of the specified type at specified date. * @@ -11845,7 +11845,7 @@ BEGIN * @param vType The type id * @param vPrefix The article prefix to filter or %NULL for all * @return tmp.itemVisible Visible items - */ + */ DECLARE vPrefixLen SMALLINT; DECLARE vFilter VARCHAR(255) DEFAULT NULL; DECLARE vDateInv DATE DEFAULT vn2008.date_inv(); @@ -11854,13 +11854,13 @@ BEGIN GET DIAGNOSTICS CONDITION 1 @message = MESSAGE_TEXT; CALL vn.mail_insert( - 'cau@verdnatura.es', - NULL, + 'cau@verdnatura.es', + NULL, CONCAT('hedera.item_getVisible error: ', @message), CONCAT( - 'warehouse: ', IFNULL(vWarehouse, ''), - ', Fecha:', IFNULL(vDate, ''), - ', tipo: ', IFNULL(vType,''), + 'warehouse: ', IFNULL(vWarehouse, ''), + ', Fecha:', IFNULL(vDate, ''), + ', tipo: ', IFNULL(vType,''), ', prefijo: ', IFNULL(vPrefix,''))); RESIGNAL; END; @@ -11939,7 +11939,7 @@ BEGIN IF(p.depth > 0, p.depth, 0) depth, p.width, p.height, CEIL(s.quantity / t.packing) etiquetas FROM vn.item i - JOIN `filter` f ON f.itemFk = i.id + JOIN `filter` f ON f.itemFk = i.id JOIN currentStock s ON s.itemFk = i.id LEFT JOIN tmp t ON t.itemFk = i.id LEFT JOIN vn.packaging p ON p.id = t.packageFk @@ -12416,15 +12416,15 @@ BEGIN START TRANSACTION; - SELECT a.agencyModeFk, a.id + SELECT a.agencyModeFk, a.id INTO vAgencyMode, vAddressFk - FROM vn.address a + FROM vn.address a WHERE a.id = vAddressFk; - + SELECT deliveryMethodFk INTO vDeliveryMethodId FROM vn.agencyMode am WHERE am.id = vAgencyMode; - + IF vCompany IS NULL THEN SELECT defaultCompanyFk INTO vCompany @@ -12442,7 +12442,7 @@ BEGIN company_id = vCompany; SET vSelf = LAST_INSERT_ID(); - + CALL order_checkConfig(vSelf); COMMIT; @@ -12488,15 +12488,15 @@ BEGIN START TRANSACTION; - SELECT a.agencyModeFk, a.id + SELECT a.agencyModeFk, a.id INTO vAgencyMode, vAddress FROM myClient c JOIN vn.address a ON a.id = c.defaultAddressFk; - + SELECT deliveryMethodFk INTO vDeliveryMethodId FROM vn.agencyMode am WHERE am.id = vAgencyMode; - + IF vCompany IS NULL THEN SELECT defaultCompanyFk INTO vCompany @@ -12514,7 +12514,7 @@ BEGIN company_id = vCompany; SET vSelf = LAST_INSERT_ID(); - + CALL order_checkConfig(vSelf); COMMIT; @@ -12697,7 +12697,7 @@ BEGIN SELECT t.id ticketFk FROM myTicket t WHERE shipped BETWEEN TIMESTAMP(vFrom) AND TIMESTAMP(vTo, '23:59:59'); - + CALL vn.ticketGetTotal(NULL); SELECT v.id, IFNULL(v.landed, v.shipped) landed, @@ -12962,10 +12962,10 @@ BEGIN CREATE TEMPORARY TABLE tmp.item (PRIMARY KEY (itemFk)) ENGINE = MEMORY - SELECT itemFk FROM orderRow + SELECT itemFk FROM orderRow WHERE orderFk = vSelf GROUP BY itemFk; - + CALL vn.catalog_calculate(vDate, vAddress, vAgencyMode); DROP TEMPORARY TABLE tmp.item; @@ -13340,7 +13340,7 @@ BEGIN END; -- Carga los datos del pedido - SELECT o.date_send, o.address_id, o.note, a.clientFk, + SELECT o.date_send, o.address_id, o.note, a.clientFk, o.company_id, o.agency_id, c.isTaxDataChecked INTO vDelivery, vAddress, vNotes, vClientId, vCompanyId, vAgencyModeId, vIsTaxDataChecked @@ -13661,7 +13661,7 @@ BEGIN INTO vDelivery, vAddress, vAgencyMode FROM `order` WHERE id = vSelf; - + CALL vn.available_calc(vDelivery, vAddress, vAgencyMode); DROP TEMPORARY TABLE IF EXISTS tmp.itemAvailable; @@ -13703,7 +13703,7 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.addressCompany; CREATE TEMPORARY TABLE tmp.addressCompany (INDEX (addressFk, companyFk)) - ENGINE = MEMORY + ENGINE = MEMORY SELECT DISTINCT o.address_id addressFk, o.company_id companyFk FROM tmp.`order` tmpOrder JOIN hedera.`order` o ON o.id = tmpOrder.orderFk; @@ -13738,7 +13738,7 @@ BEGIN JOIN vn.taxClass tc ON tc.id = bp.taxClassFk GROUP BY tmpOrder.orderFk, pgc.`code`, pgc.rate HAVING taxableBase != 0; - + DROP TEMPORARY TABLE IF EXISTS tmp.orderAmount; CREATE TEMPORARY TABLE tmp.orderAmount (INDEX (orderFk)) @@ -13747,7 +13747,7 @@ BEGIN SUM(CAST(taxableBase * rate / 100 AS DECIMAL(10, 2))) tax FROM tmp.orderTax GROUP BY orderFk, `code`; - + DROP TEMPORARY TABLE tmp.addressTaxArea; END ;; DELIMITER ; @@ -13817,7 +13817,7 @@ BEGIN CREATE TEMPORARY TABLE tmp.`order` ENGINE = MEMORY SELECT vSelf orderFk; - + CALL order_getTax; SELECT IFNULL(SUM(taxableBase), 0.0), IFNULL(SUM(tax), 0.0) @@ -13908,7 +13908,7 @@ proc: BEGIN FROM orderRow r JOIN orderRowComponent c ON c.rowFk = r.id WHERE r.orderFk = vSelf; - + UPDATE orderRow r LEFT JOIN tmp.ticketComponentPrice p ON p.warehouseFk = r.warehouseFk @@ -13933,7 +13933,7 @@ proc: BEGIN ON t.id = c.componentFk AND (t.classRate IS NULL OR t.classRate = r.rate) WHERE r.orderFk = vSelf; - + CALL vn.ticketCalculatePurge; END IF; @@ -14461,13 +14461,13 @@ p: BEGIN AND DATE(FECHA) = vDate AND EURODEBE = vAmount LIMIT 1; - + -- Actualiza la transaccion UPDATE tpvTransaction SET response = NULL, status = 'started' WHERE id = vSelf; - + COMMIT; END ;; DELIMITER ; @@ -14500,7 +14500,7 @@ BEGIN UPDATE userSession SET userVisitFk = vUserVisit WHERE ssid = vSsid; - + DELETE FROM userSession WHERE lastUpdate < TIMESTAMPADD(HOUR, -1, util.VN_NOW()); END ;; @@ -14624,7 +14624,7 @@ BEGIN UPDATE visitAgent SET firstAccessFk = vAccessId WHERE id = vAgentId; END IF; - + -- Returns the visit info SELECT vVisit visit, vAccessId access; @@ -15333,7 +15333,7 @@ BEGIN WHILE vI < vLen DO SET vChr = SUBSTR(vPhone, vI + 1, 1); - + IF vChr REGEXP '^[0-9]$' THEN SET vNewPhone = CONCAT(vNewPhone, vChr); @@ -15341,7 +15341,7 @@ BEGIN THEN SET vNewPhone = CONCAT(vNewPhone, '00'); END IF; - + SET vI = vI + 1; END WHILE; @@ -15440,18 +15440,18 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sip_getExtension`(vUserId INT(10)) BEGIN - + /* * Devuelve la extensión pbx del usuario - * - * @param vUserId Id del usuario - * + * + * @param vUserId Id del usuario + * */ SELECT extension - FROM sip s + FROM sip s WHERE s.user_id = vUserId; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -16239,22 +16239,22 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `company_getCode`(vCompanyFk INT) RET READS SQL DATA BEGIN /** - * Devuelve la correspondencía del código de empresa de sage. + * Devuelve la correspondencía del código de empresa de sage. * Tiene en cuenta el entorno - * + * * @param vSelf Id de empresa de verdnatura * @return Código de empresa sage */ DECLARE vCompanySageFk INT(2); - - SELECT IF(c.environment = 'production', - co.companyCode, + + SELECT IF(c.environment = 'production', + co.companyCode, co.companyCodeTest ) INTO vCompanySageFk FROM util.config c JOIN vn.company co WHERE co.id = vCompanyFk; - + RETURN vCompanySageFk; END ;; DELIMITER ; @@ -16273,12 +16273,12 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `accountingMovements_add`( - vYear INT, + vYear INT, vCompanyFk INT ) BEGIN /** - * Traslada la info de contabilidad generada en base a vn.XDiario a la tabla sage.movConta + * Traslada la info de contabilidad generada en base a vn.XDiario a la tabla sage.movConta * para poder ejecutar posteriormente el proceso de importación de datos de SQL Server * Solo traladará los asientos marcados con el campo vn.XDiario.enlazadoSage = FALSE * @vYear Año contable del que se quiere trasladar la información @@ -16594,8 +16594,8 @@ BEGIN mci.FechaFacturaOriginal = x.FECHA_EX, mci.SuFacturaNo = x.FACTURAEX, mci.FechaOperacion = x.FECHA_OP, - mci.ImporteFactura = mci.ImporteFactura + - x.BASEEURO + + mci.ImporteFactura = mci.ImporteFactura + + x.BASEEURO + CAST((x.IVA / 100) * x.BASEEURO AS DECIMAL(10, 2)) WHERE pm.description = 'HP Iva pendiente' AND mci.enlazadoSage = FALSE @@ -16614,7 +16614,7 @@ BEGIN mci.CodigoIva2 = vTaxImportFk, mci.IvaDeducible2 = TRUE, mci.ImporteFactura = mci.ImporteFactura + - x.BASEEURO + + x.BASEEURO + CAST((x.IVA / 100) * x.BASEEURO AS DECIMAL(10, 2)) WHERE pm.description = 'HP Iva pendiente' AND mci.enlazadoSage = FALSE @@ -16632,8 +16632,8 @@ BEGIN mci.CodigoTransaccion3 = vDuaTransactionFk , mci.CodigoIva3 = vTaxImportSuperReducedFk, mci.IvaDeducible3 = TRUE, - mci.ImporteFactura = mci.ImporteFactura + - x.BASEEURO + + mci.ImporteFactura = mci.ImporteFactura + + x.BASEEURO + CAST((x.IVA / 100) * x.BASEEURO AS DECIMAL(10, 2)) WHERE pm.description = 'HP Iva pendiente' AND mci.enlazadoSage = FALSE @@ -16667,14 +16667,14 @@ BEGIN OR CodigoTransaccion2 = vTransactionExportFk OR CodigoTransaccion3 = vTransactionExportFk OR CodigoTransaccion4 = vTransactionExportFk) - AND SiglaNacion IN (vCountryCanariasCode COLLATE utf8mb3_unicode_ci, + AND SiglaNacion IN (vCountryCanariasCode COLLATE utf8mb3_unicode_ci, vCountryCeutaMelillaCode COLLATE utf8mb3_unicode_ci); UPDATE movConta mc SET CodigoDivisa = 'USD', FactorCambio = TRUE, - ImporteCambio = ABS( CAST( IF( ImporteDivisa <> 0 AND ImporteCambio = 0, - ImporteAsiento / ImporteDivisa, + ImporteCambio = ABS( CAST( IF( ImporteDivisa <> 0 AND ImporteCambio = 0, + ImporteAsiento / ImporteDivisa, ImporteCambio) AS DECIMAL( 10, 2))) WHERE enlazadoSage = FALSE AND (ImporteCambio <> 0 OR ImporteDivisa <> 0 OR FactorCambio); @@ -16716,8 +16716,8 @@ BEGIN AND sub.amountTaxableBase/2 <> sub2.amountTaxableBase) sub; IF vBookEntries IS NOT NULL THEN - SELECT util.notification_send ("book-entries-imported-incorrectly", - CONCAT('{"bookEntries":"', vBookEntries,'"}'), + SELECT util.notification_send ("book-entries-imported-incorrectly", + CONCAT('{"bookEntries":"', vBookEntries,'"}'), null); END IF; END ;; @@ -16798,8 +16798,8 @@ BEGIN IF(n.SiglaNacion = vCountryCanariasCode COLLATE utf8mb3_unicode_ci, IF(@isCeutaMelilla := IF(pr.Provincia IN ('CEUTA', 'MELILLA'), TRUE, FALSE), vCountryCeutaMelillaFk, IF (@isCanarias, vCountryCanariasCode, n.CodigoNacion)), n.CodigoNacion), IF(n.SiglaNacion = vCountryCanariasCode COLLATE utf8mb3_unicode_ci, IF(@isCeutaMelilla, vCountryCeutaMelillaCode, IF (@isCanarias, vCountryCanariasCode, n.SiglaNacion)), n.SiglaNacion), IF((c.fi REGEXP '^([[:blank:]]|[[:digit:]])'), 'J','F'), - IF(cu.code = 'ES', - 1, + IF(cu.code = 'ES', + 1, IF((cu.isUeeMember AND c.isVies), 2, 4)), IFNULL(c.taxTypeSageFk,0), IF(n.SiglaNacion = vCountryCanariasCode COLLATE utf8mb3_unicode_ci, @@ -16877,10 +16877,10 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceIn_add`(vInvoiceInFk INT, vX BEGIN /** * Traslada la info de contabilidad relacionada con las facturas recibidas - * + * * @vInvoiceInFk Factura recibida * @vXDiarioFk Id tabla XDiario - */ + */ DECLARE vDone BOOL DEFAULT FALSE; DECLARE vBase DOUBLE; DECLARE vVat DOUBLE; @@ -16897,25 +16897,25 @@ BEGIN DECLARE vInvoiceTypeInformative VARCHAR(1); DECLARE vIsInformativeExportation BOOL DEFAULT FALSE; - DECLARE vCursor CURSOR FOR + DECLARE vCursor CURSOR FOR SELECT it.taxableBase, CAST((( it.taxableBase / 100) * t.PorcentajeIva) AS DECIMAL (10,2)), t.PorcentajeIva, it.transactionTypeSageFk, it.taxTypeSageFk, tty.isIntracommunity, - tt.ClaveOperacionDefecto + tt.ClaveOperacionDefecto FROM vn.invoiceIn i JOIN vn.invoiceInTax it ON it.InvoiceInFk = i.id JOIN TiposIva t ON t.CodigoIva = it.taxTypeSageFk JOIN taxType tty ON tty.id = t.CodigoIva JOIN TiposTransacciones tt ON tt.CodigoTransaccion = it.transactionTypeSageFk LEFT JOIN vn.dua d ON d.id = vInvoiceInFk - WHERE i.id = vInvoiceInFk + WHERE i.id = vInvoiceInFk AND d.id IS NULL; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + DELETE FROM movContaIVA WHERE id = vXDiarioFk; @@ -16938,22 +16938,22 @@ BEGIN vTaxCode, vIsIntracommunity, vOperationCode; - - IF vDone THEN + + IF vDone THEN LEAVE l; END IF; - SET vTransactionCodeOld = vTransactionCode; - SET vTaxCodeOld = vTaxCode; + SET vTransactionCodeOld = vTransactionCode; + SET vTaxCodeOld = vTaxCode; - IF vOperationCode IS NOT NULL THEN + IF vOperationCode IS NOT NULL THEN UPDATE movContaIVA SET ClaveOperacionFactura = vOperationCode WHERE id = vXDiarioFk; END IF; - + SET vCounter = vCounter + 1; - CASE vCounter + CASE vCounter WHEN 1 THEN UPDATE movContaIVA SET BaseIva1 = vBase, @@ -16989,31 +16989,31 @@ BEGIN WHERE id = vXDiarioFk; ELSE SELECT vXDiarioFk INTO vXDiarioFk; - END CASE; + END CASE; IF vIsIntracommunity THEN UPDATE movContaIVA SET Intracomunitaria = TRUE WHERE id = vXDiarioFk; END IF; - - SET vTransactionCodeOld = vTransactionCode; - SET vTaxCodeOld = vTaxCode; - + + SET vTransactionCodeOld = vTransactionCode; + SET vTaxCodeOld = vTaxCode; + END LOOP; CLOSE vCursor; SELECT d.ASIEN AND x.ASIEN IS NULL INTO vIsInformativeExportation FROM vn.dua d - LEFT JOIN vn.XDiario x ON x.ASIEN = d.ASIEN + LEFT JOIN vn.XDiario x ON x.ASIEN = d.ASIEN AND x.SERIE = vSerialDua COLLATE utf8mb3_unicode_ci WHERE d.ASIEN = ( SELECT ASIEN - FROM vn.XDiario + FROM vn.XDiario WHERE id = vXDiarioFk) LIMIT 1; - + UPDATE movContaIVA mci JOIN tmp.invoiceIn ii ON ii.id = vInvoiceInFk JOIN vn.XDiario x ON x.id = mci.id @@ -17025,13 +17025,13 @@ BEGIN mci.Serie = ii.serial, mci.Factura = ii.id, mci.FechaFactura = ii.issued, - mci.ImporteFactura = IFNULL(mci.BaseIva1, 0) + IFNULL(mci.CuotaIva1, 0) + - IFNULL(mci.BaseIva2, 0) + IFNULL(mci.CuotaIva2, 0) + - IFNULL(mci.BaseIva3, 0) + IFNULL(mci.CuotaIva3, 0) + + mci.ImporteFactura = IFNULL(mci.BaseIva1, 0) + IFNULL(mci.CuotaIva1, 0) + + IFNULL(mci.BaseIva2, 0) + IFNULL(mci.CuotaIva2, 0) + + IFNULL(mci.BaseIva3, 0) + IFNULL(mci.CuotaIva3, 0) + IFNULL(mci.BaseIva4, 0) + IFNULL(mci.CuotaIva4, 0), - mci.TipoFactura = IF(id.id, - IF( ii.serial = vSerialDua COLLATE utf8mb3_unicode_ci, vInvoiceTypeReceived, vInvoiceTypeInformative), - IF(vIsInformativeExportation,vInvoiceTypeInformative, vInvoiceTypeReceived)), + mci.TipoFactura = IF(id.id, + IF( ii.serial = vSerialDua COLLATE utf8mb3_unicode_ci, vInvoiceTypeReceived, vInvoiceTypeInformative), + IF(vIsInformativeExportation,vInvoiceTypeInformative, vInvoiceTypeReceived)), mci.CodigoCuentaFactura = x.SUBCTA, mci.CifDni = IF(LEFT(TRIM(s.nif), 2) = n.SiglaNacion, SUBSTRING(TRIM(s.nif), 3), s.nif), mci.Nombre = s.name, @@ -17059,7 +17059,7 @@ BEGIN JOIN (SELECT SUM(x2.BASEEURO) taxableBase, SUM(x2.EURODEBE) taxBase FROM vn.XDiario x1 JOIN vn.XDiario x2 ON x1.ASIEN = x2.ASIEN - WHERE x2.BASEEURO <> 0 + WHERE x2.BASEEURO <> 0 AND x1.id = vXDiarioFk )sub JOIN ClavesOperacion co ON co.Descripcion = 'Arrendamiento de locales de negocio' @@ -17067,8 +17067,8 @@ BEGIN mci.ClaveOperacionFactura = IF( t.Retencion = 'ARRENDAMIENTO Y SUBARRENDAMIENTO', co.ClaveOperacionFactura_, mci.ClaveOperacionFactura), mci.BaseRetencion = IF (t.Retencion = 'ACTIVIDADES AGRICOLAS O GANADERAS', sub.taxableBase + sub.taxBase, sub.taxableBase), mci.PorRetencion = t.PorcentajeRetencion, - mci.ImporteRetencion = iit.taxableBase * - 1 - WHERE mci.id = vXDiarioFk + mci.ImporteRetencion = iit.taxableBase * - 1 + WHERE mci.id = vXDiarioFk AND e.name = 'Retenciones' AND id.id IS NULL; @@ -17091,10 +17091,10 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceIn_manager`(vYear INT, vCompanyFk INT) BEGIN /** - * Traslada la info de contabilidad relacionada con las facturas recibidas - * + * Traslada la info de contabilidad relacionada con las facturas recibidas + * * @vYear Año contable del que se quiere trasladar la información - * @vCompany Empresa de la que se quiere trasladar datos + * @vCompany Empresa de la que se quiere trasladar datos */ DECLARE vDone BOOL DEFAULT FALSE; DECLARE vInvoiceFk INT; @@ -17106,22 +17106,22 @@ BEGIN DECLARE vAccountTaxOutstanding VARCHAR(10); DECLARE vInvoiceTypeSended VARCHAR(1); DECLARE vCursor CURSOR FOR - SELECT IFNULL(x.CLAVE, x.FACTURA) invoiceInFk, + SELECT IFNULL(x.CLAVE, x.FACTURA) invoiceInFk, x.id XDiarioFk - FROM vn.XDiario x + FROM vn.XDiario x JOIN(SELECT DISTINCT(x.ASIEN) FROM vn.XDiario x LEFT JOIN vn.invoiceIn ii ON x.CLAVE = ii.id LEFT JOIN vn.invoiceInTax it ON it.invoiceInFk = ii.id - WHERE(it.taxTypeSageFk IS NOT NULL OR x.SERIE = vSerialDua COLLATE utf8mb3_unicode_ci) - AND x.enlazadoSage = FALSE + WHERE(it.taxTypeSageFk IS NOT NULL OR x.SERIE = vSerialDua COLLATE utf8mb3_unicode_ci) + AND x.enlazadoSage = FALSE AND x.FECHA BETWEEN vDatedFrom AND vDatedTo - AND x.empresa_id = vCompanyFk + AND x.empresa_id = vCompanyFk ) sub ON sub.ASIEN = x.ASIEN WHERE x.CLAVE IS NOT NULL; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + SELECT CAST(CONCAT(vYear, '-01-01') AS DATETIME), util.dayEnd(CAST(CONCAT(vYear, '-12-31') AS DATE)) INTO vDatedFrom, vDatedTo; @@ -17135,15 +17135,15 @@ BEGIN SELECT codeSage INTO vInvoiceTypeSended FROM invoiceType WHERE `code` ='sended'; - + DROP TEMPORARY TABLE IF EXISTS tmp.invoiceDua; CREATE TEMPORARY TABLE tmp.invoiceDua - SELECT x.id + SELECT x.id FROM vn.XDiario x JOIN vn.company c ON c.id = x.empresa_id JOIN (SELECT ASIEN - FROM vn.XDiario x - WHERE x.enlazadoSage = FALSE + FROM vn.XDiario x + WHERE x.enlazadoSage = FALSE AND x.SUBCTA = vAccountTaxOutstanding COLLATE utf8mb3_unicode_ci AND x.FECHA BETWEEN vDatedFrom AND vDatedTo )sub ON sub.ASIEN = x.ASIEN @@ -17161,7 +17161,7 @@ BEGIN FROM vn.invoiceIn i JOIN vn.currency c ON c.id = i.currencyFk WHERE i.bookEntried BETWEEN vDatedFrom AND vDatedTo - UNION ALL + UNION ALL SELECT d.id, d.code, vSerialDua COLLATE utf8mb3_unicode_ci, @@ -17169,8 +17169,8 @@ BEGIN d.issued, FALSE, '' -- EUROS - FROM vn.dua d - WHERE d.issued IS NOT NULL + FROM vn.dua d + WHERE d.issued IS NOT NULL AND code IS NOT NULL; OPEN vCursor; @@ -17178,7 +17178,7 @@ BEGIN l: LOOP FETCH vCursor INTO vInvoiceFk, vXDiarioFk; - IF vDone THEN + IF vDone THEN LEAVE l; END IF; CALL invoiceIn_add(vInvoiceFk, vXDiarioFk); @@ -17266,21 +17266,21 @@ BEGIN JOIN (SELECT x.ASIEN, x.id FROM vn.XDiario x JOIN(SELECT DISTINCT(x.ASIEN) ASIEN - FROM vn.XDiario x + FROM vn.XDiario x JOIN (SELECT DISTINCT(ASIEN) FROM vn.XDiario x - WHERE SUBCTA LIKE '472%' + WHERE SUBCTA LIKE '472%' AND x.enlazadoSage = FALSE AND x.empresa_id = vCompanyFk AND x.FECHA BETWEEN vDatedFrom AND vDatedTo ) sub ON sub.ASIEN = x.ASIEN WHERE x.SUBCTA LIKE '477%' )sub2 ON sub2.ASIEN = x.ASIEN - WHERE x.CONTRA IS NOT NULL + WHERE x.CONTRA IS NOT NULL AND x.SUBCTA LIKE '477%' GROUP BY x.ASIEN )sub3 ON sub3.ASIEN = x.ASIEN; - + INSERT INTO movContaIVA (`id`, `CodigoDivisa`, @@ -17351,9 +17351,9 @@ BEGIN `FechaGrabacion`, `Intracomunitaria`, `moveData`) - SELECT * + SELECT * FROM tmp.movContaIVA; - + DROP TEMPORARY TABLE tmp.movContaIVA; END ;; @@ -17375,10 +17375,10 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOut_add`(IN vInvoiceOutFk INT, IN vXDiarioFk INT) BEGIN /** - * Traslada la info de contabilidad relacionada con las facturas emitidas - * + * Traslada la info de contabilidad relacionada con las facturas emitidas + * * @vYear Año contable del que se quiere trasladar la información - * @vCompany Empresa de la que se quiere trasladar datos + * @vCompany Empresa de la que se quiere trasladar datos */ DECLARE vDone BOOL DEFAULT FALSE; DECLARE vMaxLengthName INT DEFAULT 35; @@ -17398,12 +17398,12 @@ BEGIN DECLARE vHasCustomsAccountingNote BOOL; DECLARE vCursor CURSOR FOR - SELECT oit.taxableBase, - oit.vat, - pgc.rate, - pgc.mod347, - pgcRE.rate, - oitRE.vat, + SELECT oit.taxableBase, + oit.vat, + pgc.rate, + pgc.mod347, + pgcRE.rate, + oitRE.vat, tc.transactionCode, tc.taxCode, tc.isIntracommunity, @@ -17412,7 +17412,7 @@ BEGIN JOIN vn.pgc ON pgc.code = oit.pgcFk LEFT JOIN vn.pgcEqu e ON e.vatFk = oit.pgcFk LEFT JOIN vn.pgcEqu eRE ON eRE.equFk = oit.pgcFk - LEFT JOIN vn.invoiceOutTax oitRE ON oitRE.invoiceOutFk = oit.invoiceOutFk + LEFT JOIN vn.invoiceOutTax oitRE ON oitRE.invoiceOutFk = oit.invoiceOutFk AND oitRE.pgcFk = e.equFk LEFT JOIN vn.pgc pgcRE ON pgcRE.code = oitRE.pgcFk LEFT JOIN vn.taxCode tc ON tc.code = pgc.code COLLATE 'utf8mb3_unicode_ci' @@ -17428,12 +17428,12 @@ BEGIN WHERE ASIEN = (SELECT ASIEN FROM vn.XDiario WHERE id = vXDiarioFk); SELECT codeSage INTO vInvoiceTypeSended - FROM invoiceType + FROM invoiceType WHERE code = IF(vHasCustomsAccountingNote, 'informative', 'sended'); - + DELETE FROM movContaIVA WHERE id = vXDiarioFk; - + INSERT INTO movContaIVA(id) VALUES (vXDiarioFk); OPEN vCursor; @@ -17450,13 +17450,13 @@ BEGIN vIsIntracommunity, vOperationCode; - IF vDone THEN + IF vDone THEN LEAVE l; END IF; SET vCounter = vCounter + 1; - - CASE vCounter + + CASE vCounter WHEN 1 THEN UPDATE movContaIVA SET BaseIva1 = vBase, @@ -17497,7 +17497,7 @@ BEGIN CodigoTransaccion4 = vTransactionCode, CodigoIva4 = vTaxCode WHERE id = vXDiarioFk; - END CASE; + END CASE; UPDATE movContaIVA SET Exclusion347 = NOT vMod347, @@ -17508,7 +17508,7 @@ BEGIN END LOOP; CLOSE vCursor; - + UPDATE movContaIVA mci JOIN vn.invoiceOut i ON i.id = vInvoiceOutFk LEFT JOIN vn.invoiceCorrection ic ON ic.correctedFk = vInvoiceOutFk @@ -17533,25 +17533,25 @@ BEGIN mci.MantenerAsiento = TRUE, mci.FechaFacturaOriginal = x.FECHA_EX WHERE mci.id = vXDiarioFk; - + SELECT correctedFk INTO vInvoiceOutCorrectedFk FROM vn.invoiceCorrection WHERE correctingFk = vInvoiceOutFk; - - IF vInvoiceOutCorrectedFk THEN + + IF vInvoiceOutCorrectedFk THEN UPDATE movContaIVA mci JOIN vn.invoiceOut i ON i.id = vInvoiceOutCorrectedFk JOIN vn.invoiceCorrection ic ON ic.correctedFk = vInvoiceOutCorrectedFk - JOIN (SELECT SUM(IF(IFNULL(e.vatFk, TRUE), iot.taxableBase, 0)) taxableBase, + JOIN (SELECT SUM(IF(IFNULL(e.vatFk, TRUE), iot.taxableBase, 0)) taxableBase, SUM(IF(IFNULL(e.vatFk, TRUE), iot.vat, 0)) vat, SUM(IF(IFNULL(e.vatFk, TRUE), 0, iot.vat)) equ FROM vn.invoiceOutTax iot - LEFT JOIN vn.pgcEqu e ON e.vatFk = iot.pgcFk + LEFT JOIN vn.pgcEqu e ON e.vatFk = iot.pgcFk WHERE iot.invoiceOutFk = vInvoiceOutCorrectedFk ) tax JOIN ClavesOperacion co ON co.Descripcion = 'Factura rectificativa' SET mci.TipoRectificativa = 2, - mci.ClaseAbonoRectificativas = 1, + mci.ClaseAbonoRectificativas = 1, mci.FechaFacturaOriginal = i.issued, mci.FechaOperacion = i.issued, mci.BaseImponibleOriginal = tax.taxableBase, @@ -17582,10 +17582,10 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOut_manager`(vYear INT, vCompanyFk INT) BEGIN /** - * Traslada la info de contabilidad relacionada con las facturas emitidas - * + * Traslada la info de contabilidad relacionada con las facturas emitidas + * * @vYear Año contable del que se quiere trasladar la información - * @vCompany Empresa de la que se quiere trasladar datos + * @vCompany Empresa de la que se quiere trasladar datos */ DECLARE vDone BOOL DEFAULT FALSE; DECLARE vInvoiceFk INT; @@ -17602,7 +17602,7 @@ BEGIN JOIN (SELECT x.ASIEN, CONCAT(x.SERIE, x.FACTURA) refFk FROM vn.XDiario x WHERE x.enlazadoSage = FALSE - AND x.FACTURA + AND x.FACTURA AND x.empresa_id = vCompanyFk AND x.FECHA BETWEEN vDatedFrom AND vDatedTo GROUP BY refFk @@ -17611,19 +17611,19 @@ BEGIN )sub2 ON sub2.refFk = i.ref; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + SELECT CAST(CONCAT(vYear, '-01-01') AS DATETIME), util.dayEnd(CAST(CONCAT(vYear, '-12-31') AS DATE)) INTO vDatedFrom, vDatedTo; - + OPEN vCursor; l: LOOP FETCH vCursor INTO vInvoiceFk, vXDiarioFk; - IF vDone THEN + IF vDone THEN LEAVE l; END IF; - + CALL invoiceOut_add(vInvoiceFk, vXDiarioFk); END LOOP; @@ -17649,7 +17649,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `pgc_add`(vCompanyFk INT) BEGIN /** - * Añade cuentas del plan general contable para exportarlos a Sage + * Añade cuentas del plan general contable para exportarlos a Sage * @vCompanyFk Empresa de la que se quiere trasladar datos */ TRUNCATE TABLE planCuentasPGC; @@ -17659,25 +17659,25 @@ BEGIN CodigoCuenta, Cuenta, ClienteOProveedor) - SELECT * + SELECT * FROM (SELECT company_getCode(vCompanyFk) companyFk, e.id accountFk, UCASE(e.name), '' FROM vn.expence e - UNION + UNION SELECT company_getCode(vCompanyFk), - b.account, + b.account, UCASE(b.bank), - '' + '' FROM vn.bank b WHERE b.isActive AND b.`account` - UNION + UNION SELECT CodigoEmpresa, CodigoCuenta, Nombre, - ClienteOProveedor + ClienteOProveedor FROM clientesProveedores)sub GROUP BY companyFk, accountFk; END ;; @@ -18026,7 +18026,7 @@ DELIMITER ;; FOR EACH ROW BEGIN SET NEW.isPicked = NEW.isPicked OR NEW.dated < util.VN_CURDATE(); - + CALL visible_log( NEW.isPicked, NEW.warehouseFk, @@ -18150,7 +18150,7 @@ DELIMITER ;; BEGIN SET NEW.lack = NEW.quantity; SET NEW.isPicked = NEW.isPicked OR NEW.dated < util.VN_CURDATE(); - + CALL visible_log( NEW.isPicked, NEW.warehouseFk, @@ -18361,7 +18361,7 @@ BEGIN DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + SET vSupplied = 0; OPEN vPicks; @@ -18377,7 +18377,7 @@ BEGIN SET vPickGranted = LEAST(vRequested - vSupplied, vPickQuantity); SET vSupplied = vSupplied + vPickGranted; CALL inbound_removePick(vSelf, vOutboundFk, vPickGranted, vPickQuantity); - + UPDATE outbound SET isSync = FALSE, lack = lack + vPickGranted @@ -18457,7 +18457,7 @@ BEGIN END IF; SET vSupplied = LEAST(vAvailable, vLack); - + IF vSupplied > 0 THEN SET vAvailable = vAvailable - vSupplied; UPDATE outbound @@ -18470,7 +18470,7 @@ BEGIN SET vSupplied = vSupplied + vSuppliedFromRequest; SET vAvailable = vAvailable - vSuppliedFromRequest; END IF; - + IF vSupplied > 0 THEN CALL inbound_addPick(vSelf, vOutboundFk, vSupplied); END IF; @@ -18599,7 +18599,7 @@ BEGIN DO RELEASE_LOCK('stock.log_sync'); RESIGNAL; END; - + IF !GET_LOCK('stock.log_sync', 30) THEN CALL util.throw('Lock timeout exceeded'); END IF; @@ -19070,7 +19070,7 @@ BEGIN SET vPickGranted = LEAST(vRequested - vSupplied, vPickQuantity); SET vSupplied = vSupplied + vPickGranted; CALL inbound_removePick(vInboundFk, vSelf, vPickGranted, vPickQuantity); - + UPDATE inbound SET isSync = FALSE, available = available + vPickGranted @@ -19510,11 +19510,11 @@ BEGIN WHILE vI < vLen DO SET vSpaceIni = vI; - + WHILE MID(vString, vI, 1) REGEXP '[[:space:]]' DO SET vI = vI + 1; END WHILE; - + SET vWordIni = vI; SET vI = vWordIni + 1; @@ -19551,11 +19551,11 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `crypt`(vText VARCHAR(255), vKey VARC BEGIN DECLARE vResult VARCHAR(255); - + CALL vn.crypt(vText, vKey, vResult); RETURN vResult; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -19577,11 +19577,11 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `cryptOff`(vText VARCHAR(255), vKey V BEGIN DECLARE vResult VARCHAR(255); - + CALL vn.cryptOff(vText, vKey, vResult); RETURN vResult; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -19749,7 +19749,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `hasDateOverlapped`(vSarted1 DATE, vEnded1 DATE, vSarted2 DATE, vEnded2 DATE) RETURNS tinyint(1) DETERMINISTIC -BEGIN +BEGIN RETURN GREATEST(vSarted1, vSarted2) <= LEAST(vEnded1,vEnded2); @@ -19778,7 +19778,7 @@ BEGIN */ DECLARE vHashlen INT UNSIGNED; DECLARE vOpad, vIpad TINYBLOB; - + CASE vAlg WHEN 224 THEN SET vHashlen = 64; WHEN 256 THEN SET vHashlen = 64; @@ -19786,16 +19786,16 @@ BEGIN WHEN 512 THEN SET vHashlen = 128; ELSE CALL throw ('WRONG_ALGORYTHM_IDENTIFICATOR_USED'); END CASE; - + IF LENGTH(vKey) > vHashlen THEN SET vKey = UNHEX(SHA2(vKey, vAlg)); END IF; - + SET vKey = RPAD(vKey, vHashlen, 0x00); - + SET vIpad = stringXor(vKey, 0x36); SET vOpad = stringXor(vKey, 0x5C); - + RETURN SHA2(CONCAT(vOpad, UNHEX(SHA2(CONCAT(vIpad, vMsg), vAlg))), vAlg); END ;; DELIMITER ; @@ -19818,7 +19818,7 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `isLeapYear`(vYear INT) RETURNS tinyi BEGIN RETURN (DAYOFYEAR(CONCAT(vYear, "-02-29")) IS NOT NULL); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -19977,7 +19977,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `midnight`() RETURNS datetime READS SQL DATA BEGIN - + RETURN TIMESTAMP(util.VN_CURDATE(), '23:59:59'); END ;; @@ -20105,7 +20105,7 @@ BEGIN * modo 3. */ DECLARE vYear INT DEFAULT FLOOR(vYearWeek / 100); - + IF vYearWeek < YEARWEEK(CONCAT(vYear, '-12-31'), 3) THEN RETURN vYearWeek + 1; ELSE @@ -20211,16 +20211,16 @@ BEGIN */ DECLARE vLen, vPos INT UNSIGNED; DECLARE vResult MEDIUMBLOB; - + SET vLen = LENGTH(vString); SET vPos = 1; SET vResult = ''; - + WHILE vPos <= vLen DO SET vResult = CONCAT(vResult, LPAD(HEX( ORD(SUBSTR(vString, vPos, 1)) ^ vConst), 2, '0')); SET vPos = vPos + 1; END WHILE; - + RETURN UNHEX(vResult); END ;; DELIMITER ; @@ -20491,11 +20491,11 @@ BEGIN IF vYear = vCurYear THEN RETURN 'curYear'; END IF; - + IF vYear = vCurYear - 1 THEN RETURN 'lastYear'; END IF; - + IF vYear = vCurYear - 2 THEN RETURN 'twoYearsAgo'; END IF; @@ -20578,7 +20578,7 @@ BEGIN * @param vValue Valor de la variable */ DECLARE vIndex INT DEFAULT INSTR(USER(), '@'); - + INSERT INTO debug SET `connectionId` = CONNECTION_ID(), `user` = LEFT(USER(), vIndex - 1), @@ -20981,7 +20981,7 @@ BEGIN INSERT INTO tmp.time (dated) VALUES (vCurrentDate); SET vCurrentDate = DATE_ADD(vCurrentDate, INTERVAL 1 DAY); END WHILE; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -21375,11 +21375,11 @@ BEGIN END IF; IF NEW.isEqualizated IS NULL THEN - SELECT isEqualizated + SELECT isEqualizated INTO vIsEqualizated FROM client WHERE id = NEW.clientFk; - + SET NEW.isEqualizated = vIsEqualizated; END IF; END */;; @@ -21401,7 +21401,7 @@ DELIMITER ;; BEFORE UPDATE ON `address` FOR EACH ROW BEGIN - + SET NEW.editorFk = account.myUser_getId(); IF !(NEW.phone <=> OLD.phone) AND (NEW.phone <> '') THEN @@ -21433,16 +21433,16 @@ DELIMITER ;; BEGIN -- Recargos de equivalencia distintos implican facturacion por consignatario IF NEW.isEqualizated != OLD.isEqualizated THEN - IF + IF (SELECT COUNT(*) FROM ( SELECT DISTINCT (isEqualizated = FALSE) as Equ - FROM address + FROM address WHERE clientFk = NEW.clientFk ) t1 ) > 1 - THEN - UPDATE client + THEN + UPDATE client SET hasToInvoiceByAddress = TRUE WHERE id = NEW.clientFk; END IF; @@ -21450,10 +21450,10 @@ BEGIN IF NEW.isDefaultAddress AND NEW.isActive = FALSE THEN CALL util.throw ('Cannot desactivate the default address'); END IF; - + IF NOT (NEW.isEqualizated <=> OLD.isEqualizated) THEN INSERT IGNORE INTO ticketRecalc (ticketFk) - SELECT id FROM ticket t + SELECT id FROM ticket t WHERE t.addressFk = NEW.id AND t.refFk IS NULL; END IF; @@ -21870,8 +21870,8 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`autonomy_BI` BEFORE INSERT ON `autonomy` FOR EACH ROW -BEGIN - +BEGIN + SET NEW.geoFk = zoneGeo_new('autonomy', NEW.`name`, (SELECT geoFk FROM country WHERE id = NEW.countryFk)); END */;; @@ -21921,7 +21921,7 @@ DELIMITER ;; AFTER DELETE ON `autonomy` FOR EACH ROW BEGIN - CALL zoneGeo_delete(OLD.geoFk); + CALL zoneGeo_delete(OLD.geoFk); END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -21996,7 +21996,7 @@ DELIMITER ;; BEFORE INSERT ON `awb` FOR EACH ROW BEGIN - + SET NEW.year= year(util.VN_CURDATE()); @@ -22370,11 +22370,11 @@ DELIMITER ;; BEFORE INSERT ON `budgetNotes` FOR EACH ROW BEGIN - + IF ISNULL(NEW.userFk) THEN - + SET NEW.userFk = account.myUser_getId(); - + END IF; END */;; @@ -22468,7 +22468,7 @@ DELIMITER ;; FOR EACH ROW BEGIN SET NEW.editorFk = account.myUser_getId(); - + IF NEW.ended IS NULL THEN SET NEW.payedHolidays = 0; END IF; @@ -22514,25 +22514,25 @@ BEGIN DECLARE isOverlapping BOOL; SET NEW.editorFk = account.myUser_getId(); - + IF NEW.ended IS NULL THEN SET NEW.payedHolidays = 0; END IF; IF !(OLD.started <=> NEW.started AND OLD.ended <=> NEW.ended) THEN - + SELECT COUNT(*) > 0 INTO isOverlapping FROM business b WHERE (util.hasDateOverlapped( - NEW.started, + NEW.started, IFNULL(NEW.ended, b.started), b.started, IFNULL(b.ended, NEW.started)) OR (NEW.ended <=> NULL AND b.ended <=> NULL)) AND b.id <> OLD.id AND workerFk = OLD.workerFk; - - IF isOverlapping THEN + + IF isOverlapping THEN CALL util.throw ('IS_OVERLAPPING'); END IF; @@ -22793,7 +22793,7 @@ trig: BEGIN END IF; END IF; IF NEW.quantity < 0 THEN - SET NEW.isIgnored = TRUE; + SET NEW.isIgnored = TRUE; END IF; END */;; DELIMITER ; @@ -22988,7 +22988,7 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`buy_beforeDelete` BEFORE DELETE ON buy FOR EACH ROW -BEGIN +BEGIN IF OLD.printedStickers <> 0 THEN CALL util.throw("it is not possible to delete buys with printed labels "); END IF; @@ -24192,7 +24192,7 @@ BEGIN END IF; SET NEW.accountingAccount = 4300000000 + NEW.id; - + SET NEW.lastSalesPersonFk = NEW.salesPersonFk; END */;; DELIMITER ; @@ -24217,7 +24217,7 @@ BEGIN DECLARE vPayMethodFk INT; SET NEW.editorFk = account.myUser_getId(); - + -- Comprueba que el formato de los teléfonos es válido IF !(NEW.phone <=> OLD.phone) AND (NEW.phone <> '') THEN @@ -24299,18 +24299,18 @@ BEGIN IF !(NEW.defaultAddressFk <=> OLD.defaultAddressFk) THEN UPDATE `address` SET isDefaultAddress = 0 WHERE clientFk = NEW.id; - + UPDATE `address` SET isDefaultAddress = 1 - WHERE id = NEW.defaultAddressFk; + WHERE id = NEW.defaultAddressFk; END IF; IF NOT (NEW.provinceFk <=> OLD.provinceFk) OR NOT (NEW.isVies <=> OLD.isVies) THEN INSERT IGNORE INTO ticketRecalc (ticketFk) - SELECT id FROM ticket t + SELECT id FROM ticket t WHERE t.clientFk = NEW.id AND t.refFk IS NULL; END IF; - + IF NOT NEW.isActive THEN UPDATE account.`user` SET active = FALSE @@ -24506,15 +24506,15 @@ DELIMITER ;; AFTER INSERT ON clientCredit FOR EACH ROW BEGIN - + DECLARE vSender VARCHAR(50); SELECT u.name INTO vSender FROM account.`user` u WHERE u.id = NEW.workerFk; - + IF vSender IN ('juanvi','pepe') THEN - + CALL `vn`.`mail_insert`('pako@verdnatura.es', NULL, CONCAT('ClientCredit ',vSender, ' ', NEW.clientFk, ' ' , NEW.amount, ' €'), @@ -25095,7 +25095,7 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`cmr_beforeDelete` BEFORE DELETE ON `cmr` FOR EACH ROW -BEGIN +BEGIN IF NOT (OLD.companyFk <=> NULL AND OLD.addressFromFk <=> NULL AND OLD.packagesList <=> NULL) THEN CALL util.throw("Can not delete cmr, fields required not empty"); END IF; @@ -25226,39 +25226,39 @@ CREATE TABLE `collection` ( /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`collection_BEFORE_UPDATE` - BEFORE UPDATE ON `collection` - FOR EACH ROW -BEGIN - - DECLARE vStateFk INT; - DECLARE vTotalLines INT; - DECLARE vPickedLines INT; - - IF NEW.saleTotalCount <= NEW.salePickedCount - AND (NEW.saleTotalCount != OLD.saleTotalCount - OR NEW.salePickedCount != OLD.salePickedCount) - THEN - - SELECT id INTO vStateFk - FROM vn.state - WHERE code = 'PREPARED'; - - SET NEW.stateFk = vStateFk; - - END IF; - - IF NEW.saleTotalCount > NEW.salePickedCount - AND (NEW.saleTotalCount != OLD.saleTotalCount OR NEW.salePickedCount != OLD.salePickedCount) THEN - - SELECT id INTO vStateFk - FROM vn.state - WHERE code = 'ON_PREPARATION'; - - SET NEW.stateFk = vStateFk; - - END IF; - +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`collection_BEFORE_UPDATE` + BEFORE UPDATE ON `collection` + FOR EACH ROW +BEGIN + + DECLARE vStateFk INT; + DECLARE vTotalLines INT; + DECLARE vPickedLines INT; + + IF NEW.saleTotalCount <= NEW.salePickedCount + AND (NEW.saleTotalCount != OLD.saleTotalCount + OR NEW.salePickedCount != OLD.salePickedCount) + THEN + + SELECT id INTO vStateFk + FROM vn.state + WHERE code = 'PREPARED'; + + SET NEW.stateFk = vStateFk; + + END IF; + + IF NEW.saleTotalCount > NEW.salePickedCount + AND (NEW.saleTotalCount != OLD.saleTotalCount OR NEW.salePickedCount != OLD.salePickedCount) THEN + + SELECT id INTO vStateFk + FROM vn.state + WHERE code = 'ON_PREPARATION'; + + SET NEW.stateFk = vStateFk; + + END IF; + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -26194,7 +26194,7 @@ BEGIN UPDATE `client` c JOIN vn.creditClassification cc ON cc.client = c.id SET creditInsurance = NEW.credit WHERE cc.id = NEW.creditClassification; - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -26463,7 +26463,7 @@ BEGIN JOIN vn.department d ON d.id = b.departmentFk SET b.departmentFk = d.parentFk WHERE b.departmentFk = OLD.id; - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -26483,9 +26483,9 @@ DELIMITER ;; AFTER DELETE ON `department` FOR EACH ROW BEGIN - + UPDATE vn.department_recalc SET isChanged = TRUE; - + UPDATE vn.business b JOIN vn.department d ON d.id = b.departmentFk SET b.departmentFk = d.parentFk @@ -26556,6 +26556,7 @@ CREATE TABLE `deviceLog` ( `created` timestamp NOT NULL DEFAULT current_timestamp(), `nameApp` varchar(45) DEFAULT NULL, `versionApp` varchar(45) DEFAULT NULL, + `serialNumber` varchar(45) DEFAULT NULL, PRIMARY KEY (`id`), KEY `deviceLog_FK` (`userFk`), CONSTRAINT `deviceLog_FK` FOREIGN KEY (`userFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE @@ -26988,20 +26989,20 @@ DELIMITER ;; BEGIN DECLARE vHardCopyNumber INT; DECLARE vDmsTypeCode INT; - + IF (SELECT NOT hasDms FROM warehouse WHERE id = NEW.warehouseFk) THEN CALL util.throw('this warehouse has not dms'); END IF; IF NEW.hasFile THEN - SELECT 1 + MAX(hardCopyNumber) INTO vHardCopyNumber - FROM dms + SELECT 1 + MAX(hardCopyNumber) INTO vHardCopyNumber + FROM dms WHERE warehouseFk = NEW.warehouseFk; - + SET NEW.hardCopyNumber = IFNULL(vHardCopyNumber,1); END IF; - - SELECT code INTO vDmsTypeCode + + SELECT code INTO vDmsTypeCode FROM dmsType WHERE NEW.dmsTypeFk = id; IF (vDmsTypeCode ='ticket') THEN UPDATE ticket SET isSigned = 1 WHERE id = NEW.reference; @@ -27021,31 +27022,31 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`dms_beforeUpdate` - BEFORE UPDATE ON `dms` - FOR EACH ROW -BEGIN - DECLARE vHardCopyNumber INT; - - IF (NEW.hasFile <> 0) AND (OLD.hasFile = 0) AND (NEW.hardCopyNumber IS NULL) - OR - (NEW.hardCopyNumber = OLD.hardCopyNumber AND OLD.warehouseFk <> NEW.warehouseFk) THEN - - IF (SELECT NOT hasDms FROM warehouse WHERE id = NEW.warehouseFk) THEN - SET NEW.warehouseFk = (SELECT id FROM warehouse WHERE name = 'Algemesi'); - END IF; - - SELECT 1 + MAX(hardCopyNumber) INTO vHardCopyNumber - FROM dms - WHERE warehouseFk = NEW.warehouseFk; - - SET NEW.hardCopyNumber = IFNULL(vHardCopyNumber,1); - END IF; - - IF ((NEW.hardCopyNumber = 0) OR NEW.hardCopyNumber IS NULL) AND (OLD.hardCopyNumber <> 0) THEN - - SET NEW.hasFile = 0; - END IF; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`dms_beforeUpdate` + BEFORE UPDATE ON `dms` + FOR EACH ROW +BEGIN + DECLARE vHardCopyNumber INT; + + IF (NEW.hasFile <> 0) AND (OLD.hasFile = 0) AND (NEW.hardCopyNumber IS NULL) + OR + (NEW.hardCopyNumber = OLD.hardCopyNumber AND OLD.warehouseFk <> NEW.warehouseFk) THEN + + IF (SELECT NOT hasDms FROM warehouse WHERE id = NEW.warehouseFk) THEN + SET NEW.warehouseFk = (SELECT id FROM warehouse WHERE name = 'Algemesi'); + END IF; + + SELECT 1 + MAX(hardCopyNumber) INTO vHardCopyNumber + FROM dms + WHERE warehouseFk = NEW.warehouseFk; + + SET NEW.hardCopyNumber = IFNULL(vHardCopyNumber,1); + END IF; + + IF ((NEW.hardCopyNumber = 0) OR NEW.hardCopyNumber IS NULL) AND (OLD.hardCopyNumber <> 0) THEN + + SET NEW.hasFile = 0; + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -27064,14 +27065,14 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`dms_beforeDelete` BEFORE DELETE ON `dms` FOR EACH ROW -BEGIN +BEGIN DECLARE vCanNotBeDeleted INT; - SELECT COUNT(*) INTO vCanNotBeDeleted - FROM dmsType dt - WHERE NOT (code <=> 'trash') + SELECT COUNT(*) INTO vCanNotBeDeleted + FROM dmsType dt + WHERE NOT (code <=> 'trash') AND dt.id = OLD.dmsTypeFk; - - IF vCanNotBeDeleted THEN + + IF vCanNotBeDeleted THEN CALL util.throw('A dms can not be deleted'); END IF; END */;; @@ -27649,7 +27650,7 @@ BEGIN END IF; IF NOT (NEW.travelFk <=> OLD.travelFk) - OR NOT (NEW.currencyFk <=> OLD.currencyFk) THEN + OR NOT (NEW.currencyFk <=> OLD.currencyFk) THEN SET NEW.commission = entry_getCommission(NEW.travelFk, NEW.currencyFk,NEW.supplierFk); END IF; END */;; @@ -28149,17 +28150,17 @@ BEGIN SET NEW.editorFk = account.myUser_getId(); - IF NEW.freightItemFk IS NOT NULL THEN + IF NEW.freightItemFk IS NOT NULL THEN UPDATE ticket SET packages = nz(packages) + 1 WHERE id = NEW.ticketFk; - SELECT IFNULL(MAX(counter),0) +1 INTO intcounter - FROM expedition e - INNER JOIN ticket t1 ON e.ticketFk = t1.id + SELECT IFNULL(MAX(counter),0) +1 INTO intcounter + FROM expedition e + INNER JOIN ticket t1 ON e.ticketFk = t1.id LEFT JOIN ticketState ts ON ts.ticket = t1.id - INNER JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped) + INNER JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped) AND t1.warehouseFk = t2.warehouseFk - WHERE t2.id = NEW.ticketFk AND ts.alertLevel < 3 AND t1.companyFk = t2.companyFk + WHERE t2.id = NEW.ticketFk AND ts.alertLevel < 3 AND t1.companyFk = t2.companyFk AND t1.agencyModeFk = t2.agencyModeFk; SET NEW.`counter` = intcounter; @@ -28186,9 +28187,9 @@ BEGIN SET NEW.editorFk = account.myUser_getId(); IF NEW.counter <> OLD.counter THEN - IF (SELECT COUNT(*) FROM expedition e + IF (SELECT COUNT(*) FROM expedition e INNER JOIN ticket t1 ON e.ticketFk = t1.id - INNER JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped) + INNER JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped) WHERE t1.id = NEW.ticketFk AND counter = NEW.counter) > 0 THEN SET NEW.id = NULL; END IF; @@ -28212,11 +28213,11 @@ DELIMITER ;; BEFORE DELETE ON `expedition` FOR EACH ROW BEGIN - UPDATE ticket t - SET packages = (SELECT COUNT(counter)-1 + UPDATE ticket t + SET packages = (SELECT COUNT(counter)-1 FROM expedition e WHERE e.ticketFk = OLD.ticketFk and e.freightItemFk) - WHERE t.id = OLD.ticketFk; - + WHERE t.id = OLD.ticketFk; + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -28355,13 +28356,13 @@ DELIMITER ;; BEGIN DECLARE vNewPosition INT; - + SELECT MAX(position) + 1 INTO vNewPosition FROM vn.expeditionPallet WHERE truckFk = NEW.truckFk; - + SET NEW.position = IFNULL(vNewPosition,1); - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -28460,7 +28461,7 @@ DELIMITER ;; BEGIN SET NEW.workerFk = vn.getUser(); - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -28521,9 +28522,9 @@ DELIMITER ;; BEFORE INSERT ON expeditionState FOR EACH ROW BEGIN - + SET NEW.userFk = account.myUser_getId(); - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -28547,7 +28548,7 @@ BEGIN UPDATE vn.expedition e SET e.stateTypeFk = NEW.typeFk WHERE e.id = NEW.expeditionFk; - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -29578,42 +29579,42 @@ BEGIN DECLARE vWithholdingSageFk INT; SET NEW.editorFk = account.myUser_getId(); - - SELECT withholdingSageFk INTO vWithholdingSageFk - FROM vn.supplier + + SELECT withholdingSageFk INTO vWithholdingSageFk + FROM vn.supplier WHERE id = NEW.supplierFk; - SET NEW.withholdingSageFk = vWithholdingSageFk; - - SELECT countryFk, isActive INTO vIssuingCountry, vActive - FROM vn.supplier + SET NEW.withholdingSageFk = vWithholdingSageFk; + + SELECT countryFk, isActive INTO vIssuingCountry, vActive + FROM vn.supplier WHERE id = NEW.supplierFk; - - SELECT countryFk INTO vhostCountry - FROM vn.supplier + + SELECT countryFk INTO vhostCountry + FROM vn.supplier WHERE id = NEW.companyFk; IF vActive = 0 THEN CALL util.throw('INACTIVE_PROVIDER'); END IF; - - IF (SELECT COUNT(*) FROM vn.invoiceIn - WHERE supplierRef = NEW.supplierRef - AND supplierFk = NEW.supplierFk + + IF (SELECT COUNT(*) FROM vn.invoiceIn + WHERE supplierRef = NEW.supplierRef + AND supplierFk = NEW.supplierFk AND YEAR(issued) = YEAR(NEW.issued) ) THEN CALL util.throw('reference duplicated'); END IF; - + SELECT CASE WHEN (SELECT account FROM vn.supplier where id = NEW.supplierFk) LIKE '___3______' THEN 'C' - WHEN (SELECT vIssuingCountry=vhostCountry from vn.country p1 join vn.country p2 ON p2.id = vhostCountry AND p1.id = vIssuingCountry + WHEN (SELECT vIssuingCountry=vhostCountry from vn.country p1 join vn.country p2 ON p2.id = vhostCountry AND p1.id = vIssuingCountry where p1.CEE < 2 and p2.CEE < 2) = 1 THEN 'R' - WHEN (SELECT vIssuingCountry <> vhostCountry from vn.country p1 join vn.country p2 ON p2.id = vhostCountry AND p1.id = vIssuingCountry - where p1.CEE < 2 and p2.CEE < 2) = 1 THEN 'E' + WHEN (SELECT vIssuingCountry <> vhostCountry from vn.country p1 join vn.country p2 ON p2.id = vhostCountry AND p1.id = vIssuingCountry + where p1.CEE < 2 and p2.CEE < 2) = 1 THEN 'E' WHEN (SELECT vIssuingCountry<>vhostCountry from vn.country p1 join vn.country p2 ON p2.id = vhostCountry AND p1.id = vIssuingCountry - where NOT p1.CEE < 2 AND not p1.id = 1) = 1 THEN 'W' + where NOT p1.CEE < 2 AND not p1.id = 1) = 1 THEN 'W' END INTO vSerie; - + SET NEW.serial = IFNULL(vSerie,'R'); END */;; @@ -29640,9 +29641,9 @@ BEGIN SET NEW.editorFk = account.myUser_getId(); - IF (SELECT COUNT(*) FROM vn.invoiceIn - WHERE supplierRef = NEW.supplierRef - AND supplierFk = NEW.supplierFk + IF (SELECT COUNT(*) FROM vn.invoiceIn + WHERE supplierRef = NEW.supplierRef + AND supplierFk = NEW.supplierFk AND YEAR(issued) = YEAR(NEW.issued) AND id <> NEW.id ) THEN @@ -29652,7 +29653,7 @@ BEGIN IF NEW.supplierFk != OLD.supplierFk THEN CALL supplier_checkIsActive(NEW.supplierFk); SELECT withholdingSageFk INTO vWithholdingSageFk - FROM vn.supplier + FROM vn.supplier WHERE id = NEW.supplierFk; SET NEW.withholdingSageFk = vWithholdingSageFk; END IF; @@ -29677,23 +29678,23 @@ DELIMITER ;; FOR EACH ROW BEGIN - IF NEW.issued != OLD.issued + IF NEW.issued != OLD.issued OR NEW.currencyFk != OLD.currencyFk THEN UPDATE invoiceInTax iit JOIN invoiceIn ii ON ii.id = iit.invoiceInFk LEFT JOIN referenceRate rr ON rr.dated = ii.issued - AND rr.currencyFk = ii.currencyFk + AND rr.currencyFk = ii.currencyFk SET iit.taxableBase = IF(iit.foreignValue IS NULL, iit.taxableBase, iit.foreignValue / rr.value) WHERE ii.id = NEW.id; - + UPDATE invoiceInDueDay iidd JOIN invoiceIn ii ON ii.id = iidd.invoiceInFk LEFT JOIN referenceRate rr ON rr.dated = ii.issued - AND rr.currencyFk = ii.currencyFk + AND rr.currencyFk = ii.currencyFk SET iidd.amount = IF(iidd.foreignValue IS NULL, iidd.amount, iidd.foreignValue / rr.value) - WHERE ii.id = NEW.id; - + WHERE ii.id = NEW.id; + END IF; END */;; @@ -29787,13 +29788,13 @@ BEGIN DECLARE vIsNotified BOOLEAN; SET NEW.editorFk = account.myUser_getId(); - - SELECT isNotified INTO vIsNotified - FROM vn.invoiceIn ii + + SELECT isNotified INTO vIsNotified + FROM vn.invoiceIn ii JOIN vn.supplier s ON s.id = ii.supplierFk JOIN vn.payMethod pm ON pm.id = s.payMethodFk WHERE ii.id = NEW.invoiceInFk; - + IF (NEW.dueDated <= util.VN_CURDATE() AND vIsNotified) THEN CALL mail_insert( @@ -29801,12 +29802,12 @@ BEGIN 'begonya@verdnatura.es', 'Añadido vencimiento en el pasado', CONCAT( - account.myUser_getName(), ' ha añadido un vencimiento de ', + account.myUser_getName(), ' ha añadido un vencimiento de ', NEW.amount, '€ en una fecha pasada en la recibida ', NEW.invoiceInFk ) ); END IF; - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -29829,13 +29830,13 @@ BEGIN DECLARE vIsNotified BOOLEAN; SET NEW.editorFk = account.myUser_getId(); - - SELECT isNotified INTO vIsNotified - FROM vn.invoiceIn ii + + SELECT isNotified INTO vIsNotified + FROM vn.invoiceIn ii JOIN vn.supplier s ON s.id = ii.supplierFk JOIN vn.payMethod pm ON pm.id = s.payMethodFk WHERE ii.id = NEW.invoiceInFk; - + IF (NEW.dueDated <= util.VN_CURDATE() AND vIsNotified) THEN CALL mail_insert( @@ -29843,12 +29844,12 @@ BEGIN 'begonya@verdnatura.es', 'Añadido vencimiento en el pasado', CONCAT( - account.myUser_getName(), ' ha añadido un vencimiento de ', + account.myUser_getName(), ' ha añadido un vencimiento de ', NEW.amount,'€ en una fecha pasada en la recibida ',NEW.invoiceInFk ) ); END IF; - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -30984,15 +30985,15 @@ BEGIN IF NEW.itemFk IN (95, 98) THEN SET NEW.cm3 = 0; END IF; - + IF !(NEW.cm3delivery <=> OLD.cm3delivery) THEN INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) - SELECT r.id + SELECT r.id FROM vn.itemCost ic JOIN vn.sale s ON s.itemFk = ic.itemFk - JOIN vn.ticket t ON t.id = s.ticketFk AND t.warehouseFk = ic.warehouseFk + JOIN vn.ticket t ON t.id = s.ticketFk AND t.warehouseFk = ic.warehouseFk JOIN vn.route r ON r.id = t.routeFk - WHERE r.isOk = FALSE + WHERE r.isOk = FALSE AND ic.itemFk = NEW.itemFk AND r.created >= util.VN_CURDATE() GROUP BY r.id; @@ -31312,10 +31313,10 @@ DELIMITER ;; BEFORE INSERT ON `itemShelving` FOR EACH ROW BEGIN - + SET NEW.userFk = account.myUser_getId(); - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -31424,8 +31425,8 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemShelving_BEFORE_DELETE` BEFORE DELETE ON `itemShelving` FOR EACH ROW -INSERT INTO vn.itemShelvingLog(itemShelvingFk, - workerFk, +INSERT INTO vn.itemShelvingLog(itemShelvingFk, + workerFk, accion, shelvingFk, itemFk) @@ -31609,7 +31610,7 @@ DELIMITER ;; BEGIN UPDATE vn.sale - SET isPicked = TRUE + SET isPicked = TRUE WHERE id = NEW.saleFk; END */;; @@ -31799,9 +31800,9 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemTag_beforeUpdate` BEFORE UPDATE ON `itemTag` FOR EACH ROW -BEGIN +BEGIN SET NEW.editorFk = account.myUser_getId(); - + IF !(OLD.`value` <=> NEW.`value`) OR !(OLD.intValue <=> NEW.intValue) THEN SET NEW.intValue = itemTag_getIntValue(NEW.`value`); @@ -31834,7 +31835,7 @@ trig: BEGIN IF @isTriggerDisabled OR visTriggerDisabled THEN LEAVE trig; END IF; - + SET vItemFk = NEW.itemFk; DROP TEMPORARY TABLE IF EXISTS tmp.item; CREATE TEMPORARY TABLE tmp.item @@ -32341,7 +32342,7 @@ DELIMITER ;; BEFORE INSERT ON `machine` FOR EACH ROW BEGIN - + SET NEW.workerFk = vn.getUser(); END */;; @@ -32475,9 +32476,9 @@ DELIMITER ;; BEGIN IF NEW.sender IS NOT NULL THEN - + SET NEW.receiver = NEW.sender; - + END IF; END */;; @@ -32540,8 +32541,8 @@ DELIMITER ;; FOR EACH ROW BEGIN IF (NEW.code IS NULL) THEN - SET NEW.code=CONCAT(NEW.clientFk,'-',(SELECT AUTO_INCREMENT - FROM information_schema.TABLES + SET NEW.code=CONCAT(NEW.clientFk,'-',(SELECT AUTO_INCREMENT + FROM information_schema.TABLES WHERE TABLE_SCHEMA='vn' and TABLE_NAME='mandate')); END IF; END */;; @@ -33535,7 +33536,7 @@ DELIMITER ;; BEGIN -- SET new.`code` = CONCAT(new.`column`,' - ',new.`row`) ; - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -33660,13 +33661,13 @@ BEGIN SELECT account INTO cuenta_banco FROM bank WHERE id = NEW.bankFk; - + SELECT account INTO cuenta_proveedor FROM supplier WHERE id = NEW.supplierFk; - + CALL vn.ledger_next(vNewBookEntry); - + INSERT INTO XDiario ( ASIEN, FECHA, SUBCTA, @@ -33692,7 +33693,7 @@ BEGIN cuenta_banco CONTRA, NEW.amount EURODEBE, 0 EUROHABER) gf; - + IF NEW.bankingFees <> 0 THEN INSERT INTO XDiario ( ASIEN, FECHA, @@ -33714,7 +33715,7 @@ BEGIN FROM supplier s JOIN country c ON s.countryFk = c.id WHERE s.id = NEW.supplierFk; - END IF; + END IF; END IF; SET NEW.dueDated = IFNULL(NEW.dueDated, NEW.received); @@ -33722,15 +33723,15 @@ BEGIN SELECT isActive INTO isSupplierActive FROM supplier WHERE id = NEW.supplierFk; - + IF isSupplierActive = FALSE THEN CALL util.throw('SUPPLIER_INACTIVE'); END IF; - + IF ISNULL(NEW.workerFk) THEN SET NEW.workerFk = account.myUser_getId(); END IF; - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -33752,12 +33753,12 @@ DELIMITER ;; BEGIN DECLARE vIsPayMethodChecked BOOLEAN; DECLARE vEmail VARCHAR(150); - + SELECT isPayMethodChecked INTO vIsPayMethodChecked FROM supplier WHERE id = NEW.supplierFk; - - + + IF vIsPayMethodChecked = FALSE THEN SELECT notificationEmail INTO vEmail @@ -34639,11 +34640,11 @@ DELIMITER ;; BEFORE INSERT ON projectNotes FOR EACH ROW BEGIN - + IF ISNULL(NEW.userFk) THEN - + SET NEW.userFk = account.myUser_getId(); - + END IF; END */;; @@ -34804,10 +34805,10 @@ DELIMITER ;; BEFORE INSERT ON `province` FOR EACH ROW BEGIN - + SET NEW.geoFk = zoneGeo_new('province', NEW.`name`, (SELECT geoFk FROM autonomy WHERE id = NEW.autonomyFk)); - + SET NEW.countryFk = (SELECT a.countryFk FROM vn.autonomy a WHERE a.id = NEW.autonomyFk); END */;; @@ -34828,14 +34829,14 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`province_beforeUpdate` BEFORE UPDATE ON `province` FOR EACH ROW -BEGIN - +BEGIN + IF !(OLD.autonomyFk <=> NEW.autonomyFk) THEN - + SET NEW.countryFk = (SELECT a.countryFk FROM vn.autonomy a WHERE a.id = NEW.autonomyFk); END IF; - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -34851,19 +34852,19 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`province_afterUpdate` - AFTER UPDATE ON `province` - FOR EACH ROW -BEGIN - IF !(OLD.autonomyFk <=> NEW.autonomyFk) THEN - CALL zoneGeo_setParent(NEW.geoFk, - (SELECT geoFk FROM autonomy WHERE id = NEW.autonomyFk)); - END IF; - - IF !(OLD.`name` <=> NEW.`name`) THEN - UPDATE zoneGeo SET `name` = NEW.`name` - WHERE id = NEW.geoFk; - END IF; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`province_afterUpdate` + AFTER UPDATE ON `province` + FOR EACH ROW +BEGIN + IF !(OLD.autonomyFk <=> NEW.autonomyFk) THEN + CALL zoneGeo_setParent(NEW.geoFk, + (SELECT geoFk FROM autonomy WHERE id = NEW.autonomyFk)); + END IF; + + IF !(OLD.`name` <=> NEW.`name`) THEN + UPDATE zoneGeo SET `name` = NEW.`name` + WHERE id = NEW.geoFk; + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -34883,7 +34884,7 @@ DELIMITER ;; AFTER DELETE ON `province` FOR EACH ROW BEGIN - CALL zoneGeo_delete(OLD.geoFk); + CALL zoneGeo_delete(OLD.geoFk); END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -35107,20 +35108,20 @@ CREATE TABLE `receipt` ( /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`receipt_beforeInsert` - BEFORE INSERT ON `receipt` - FOR EACH ROW -BEGIN - DECLARE vIsAutoConciliated BOOLEAN; - - IF NEW.isConciliate = FALSE THEN - SELECT isAutoConciliated INTO vIsAutoConciliated - FROM accounting a - JOIN accountingType at2 ON at2.id = a.accountingTypeFk - WHERE a.id = NEW.bankFk; - - SET NEW.isConciliate = vIsAutoConciliated; - END IF; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`receipt_beforeInsert` + BEFORE INSERT ON `receipt` + FOR EACH ROW +BEGIN + DECLARE vIsAutoConciliated BOOLEAN; + + IF NEW.isConciliate = FALSE THEN + SELECT isAutoConciliated INTO vIsAutoConciliated + FROM accounting a + JOIN accountingType at2 ON at2.id = a.accountingTypeFk + WHERE a.id = NEW.bankFk; + + SET NEW.isConciliate = vIsAutoConciliated; + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -35176,18 +35177,18 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`receipt_afterUpdate` - AFTER UPDATE ON `receipt` - FOR EACH ROW -BEGIN - IF NEW.isConciliate = FALSE AND NEW.payed > OLD.payed THEN - CALL mail_insert( - 'finanzas@verdnatura.es', - NULL, - CONCAT('Cambios de recibos del cliente: ', NEW.clientFk), - CONCAT('Se ha cambiado el recibo: ', NEW.Id, ' de ', OLD.payed, ' a ', NEW.payed) - ); - END IF; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`receipt_afterUpdate` + AFTER UPDATE ON `receipt` + FOR EACH ROW +BEGIN + IF NEW.isConciliate = FALSE AND NEW.payed > OLD.payed THEN + CALL mail_insert( + 'finanzas@verdnatura.es', + NULL, + CONCAT('Cambios de recibos del cliente: ', NEW.clientFk), + CONCAT('Se ha cambiado el recibo: ', NEW.Id, ' de ', OLD.payed, ' a ', NEW.payed) + ); + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -35535,7 +35536,7 @@ BEGIN DECLARE vDefaultAgencyModeFk INT; SET NEW.editorFk = account.myUser_getId(); - + SET NEW.commissionWorkCenterFk = ( SELECT IFNULL(b.workCenterFK, r.defaultWorkCenterFk) FROM vn.routeConfig r @@ -35569,7 +35570,7 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`route_afterInsert` AFTER INSERT ON `route` FOR EACH ROW -BEGIN +BEGIN CALL route_calcCommission(NEW.id); END */;; DELIMITER ; @@ -35591,16 +35592,16 @@ DELIMITER ;; FOR EACH ROW BEGIN DECLARE vKmMax INT; - + SET NEW.editorFk = account.myUser_getId(); - + IF NEW.isOk <> FALSE AND OLD.isOk = FALSE THEN - SET NEW.m3 = ( SELECT SUM(litros)/1000 - FROM vn.saleVolume s - JOIN vn.ticket t ON s.ticketFk = t.id + SET NEW.m3 = ( SELECT SUM(litros)/1000 + FROM vn.saleVolume s + JOIN vn.ticket t ON s.ticketFk = t.id WHERE t.routeFk = NEW.id); END IF; - + IF NEW.kmEnd < NEW.kmStart AND NEW.kmEnd <> 0 THEN CALL util.throw ('KmEnd menor que kmStart'); END IF; @@ -35630,18 +35631,18 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`route_afterUpdate` AFTER UPDATE ON `route` FOR EACH ROW -BEGIN +BEGIN IF IFNULL(NEW.gestdocFk,0) <> IFNULL(OLD.gestdocFk,0) AND NEW.gestdocFk > 0 THEN -- JGF 09/09/14 cuando se añade un gestdoc a una ruta, se le asigna automagicamente a todos sus Tickets - + -- Inserta el gestdoc en todos los tickets de la ruta INSERT INTO ticketDms(ticketFk,dmsFk) SELECT id, NEW.gestdocFk FROM ticket WHERE routeFk = NEW.id ON DUPLICATE KEY UPDATE dmsFk = NEW.gestdocFk; - -- Update del firmado - UPDATE ticket t - JOIN ticketDms tg ON t.id = tg.ticketFk + -- Update del firmado + UPDATE ticket t + JOIN ticketDms tg ON t.id = tg.ticketFk SET isSigned = 1 WHERE t.routeFk = NEW.id; END IF; @@ -36099,20 +36100,20 @@ DELIMITER ;; BEFORE UPDATE ON `sale` FOR EACH ROW BEGIN -/* +/* IF (SELECT COUNT(*) from item i WHERE id = NEW.itemFk AND family = 'SER') THEN CALL util.throw('Cannot insert a service item into a ticket'); END IF; */ SET NEW.editorFk = account.myUser_getId(); - + IF NEW.discount > 100 THEN SET NEW.discount = 0; END IF; IF old.discount > 0 AND NEW.discount = 0 THEN INSERT INTO ticketLog - SET originFk = NEW.ticketFk, userFk = account.myUser_getId(), `action` = 'insert', + SET originFk = NEW.ticketFk, userFk = account.myUser_getId(), `action` = 'insert', description = CONCAT('Cambio de descuento del item :', ' ', new.itemFk, ' de ', old.discount ,' a 0 '); END IF; END */;; @@ -36244,11 +36245,11 @@ DELIMITER ;; BEGIN IF OLD.quantity > 0 THEN INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) - SELECT r.id + SELECT r.id FROM vn.sale s JOIN vn.ticket t ON t.id = s.ticketFk JOIN vn.route r ON r.id = t.routeFk - WHERE r.isOk = FALSE + WHERE r.isOk = FALSE AND s.id = OLD.id AND r.created >= util.VN_CURDATE() GROUP BY r.id; @@ -36350,10 +36351,10 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`BEFORE_INSERT` BEFORE INSERT ON `saleBuy` FOR EACH ROW -BEGIN - +BEGIN + SET NEW.workerFk = vn.getUser(); - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -36372,13 +36373,13 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`saleBuy_AI` AFTER INSERT ON `saleBuy` FOR EACH ROW -BEGIN +BEGIN /* Activar de nuevo cuando volvamos a vender fruta y verdura - * + * UPDATE vn.sale s SET s.concept = CONCAT(s.concept, ' Lote: ', NEW.buyFk) WHERE s.id = NEW.saleFk; -*/ +*/ END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -36644,14 +36645,14 @@ DELIMITER ;; AFTER INSERT ON `saleTracking` FOR EACH ROW BEGIN - - IF NEW.isChecked THEN - + + IF NEW.isChecked THEN + UPDATE vn.sale s - SET s.isPicked = TRUE + SET s.isPicked = TRUE WHERE s.id = NEW.saleFk AND s.isPicked = 0; - + END IF; END */;; @@ -37037,9 +37038,9 @@ BEGIN IF NEW.workerFk = NEW.workerSubstitute THEN CALL util.throw ('worker and workerSubstitute must be different'); ELSE - INSERT IGNORE INTO sharingCartDaily (ownerFk, substituteFk, dated) - SELECT NEW.workerFk, NEW.workerSubstitute, dated - FROM time + INSERT IGNORE INTO sharingCartDaily (ownerFk, substituteFk, dated) + SELECT NEW.workerFk, NEW.workerSubstitute, dated + FROM time WHERE dated BETWEEN NEW.started AND NEW.ended; END IF; END */;; @@ -37064,14 +37065,14 @@ BEGIN IF NEW.workerFk = NEW.workerSubstitute THEN CALL util.throw ('worker and workerSubstitute must be different'); ELSE - DELETE sc FROM sharingCartDaily sc - WHERE sc.dated BETWEEN OLD.started AND OLD.ended AND - sc.ownerFk = OLD.workerFk AND + DELETE sc FROM sharingCartDaily sc + WHERE sc.dated BETWEEN OLD.started AND OLD.ended AND + sc.ownerFk = OLD.workerFk AND sc.substituteFk = OLD.workerSubstitute; - - INSERT IGNORE INTO sharingCartDaily (ownerFk, substituteFk, dated) - SELECT NEW.workerFk, NEW.workerSubstitute, dated - FROM time + + INSERT IGNORE INTO sharingCartDaily (ownerFk, substituteFk, dated) + SELECT NEW.workerFk, NEW.workerSubstitute, dated + FROM time WHERE dated BETWEEN NEW.started AND NEW.ended; END IF; @@ -37094,9 +37095,9 @@ DELIMITER ;; BEFORE DELETE ON `sharingCart` FOR EACH ROW BEGIN - DELETE sc FROM sharingCartDaily sc - WHERE sc.dated BETWEEN OLD.started AND OLD.ended AND - sc.ownerFk = OLD.workerFk AND + DELETE sc FROM sharingCartDaily sc + WHERE sc.dated BETWEEN OLD.started AND OLD.ended AND + sc.ownerFk = OLD.workerFk AND sc.substituteFk = OLD.workerSubstitute; END */;; DELIMITER ; @@ -37478,7 +37479,7 @@ DELIMITER ;; FOR EACH ROW BEGIN UPDATE vn2008.Clientes c - JOIN creditClassification cc ON c.Id_Cliente = cc.client + JOIN creditClassification cc ON c.Id_Cliente = cc.client JOIN creditInsurance ci ON ci.creditClassification = cc.id SET creditInsurance = ci.credit * 2 WHERE ci.id = NEW.creditInsurance; END */;; @@ -37502,12 +37503,12 @@ DELIMITER ;; BEGIN IF NEW.dateLeaving IS NOT NULL THEN UPDATE vn2008.Clientes c - JOIN creditClassification cc ON c.Id_Cliente = cc.client + JOIN creditClassification cc ON c.Id_Cliente = cc.client JOIN creditInsurance ci ON ci.creditClassification = cc.id SET creditInsurance = ci.credit WHERE ci.id = OLD.creditInsurance; ELSE UPDATE vn2008.Clientes c - JOIN creditClassification cc ON c.Id_Cliente = cc.client + JOIN creditClassification cc ON c.Id_Cliente = cc.client JOIN creditInsurance ci ON ci.creditClassification = cc.id SET creditInsurance = ci.credit * 2 WHERE ci.id = OLD.creditInsurance; END IF; @@ -37531,7 +37532,7 @@ DELIMITER ;; FOR EACH ROW BEGIN UPDATE vn2008.Clientes c - JOIN creditClassification cc ON c.Id_Cliente = cc.client + JOIN creditClassification cc ON c.Id_Cliente = cc.client JOIN creditInsurance ci ON ci.creditClassification = cc.id SET creditInsurance = ci.credit WHERE ci.id = OLD.creditInsurance; END */;; @@ -38743,7 +38744,7 @@ DELIMITER ;; AFTER INSERT ON `ticket` FOR EACH ROW BEGIN - + DECLARE vClientType VARCHAR(255); DECLARE vStateCode VARCHAR(255); DECLARE vTransferorFirstShipped DATE; @@ -38771,7 +38772,7 @@ BEGIN 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 */;; @@ -38798,10 +38799,10 @@ BEGIN SET NEW.editorFk = account.myUser_getId(); IF !(NEW.routeFk <=> OLD.routeFk) THEN - INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) - SELECT r.id + INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) + SELECT r.id FROM vn.route r - WHERE r.isOk = FALSE + WHERE r.isOk = FALSE AND r.id IN (OLD.routeFk,NEW.routeFk) AND r.created >= util.VN_CURDATE() GROUP BY r.id; @@ -38818,13 +38819,13 @@ BEGIN END IF; END IF; - + IF !(NEW.isDeleted <=> OLD.isDeleted) AND NEW.isDeleted THEN - INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) - SELECT r.id + INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) + SELECT r.id FROM vn.ticket t JOIN vn.route r ON r.id = t.routeFk - WHERE r.isOk = FALSE + WHERE r.isOk = FALSE AND t.id = NEW.id AND r.created >= util.VN_CURDATE() GROUP BY r.id; @@ -38834,7 +38835,7 @@ BEGIN SET NEW.zoneFk = NULL; END IF; - IF NEW.routeFk AND NEW.isDeleted THEN + IF NEW.routeFk AND NEW.isDeleted THEN CALL util.throw ('This ticket is deleted'); END IF; @@ -38843,12 +38844,12 @@ BEGIN FROM vn.ticket WHERE routeFk = NEW.routeFk HAVING MAX(TIME(shipped)) > TIME(NEW.shipped); - + IF vNewTime THEN SET NEW.shipped = TIMESTAMP(DATE(NEW.shipped), vNewTime); END IF; INSERT IGNORE INTO zoneAgencyMode (agencyModeFk,zoneFk) - SELECT r.agencyModeFk, NEW.zoneFk FROM route r + SELECT r.agencyModeFk, NEW.zoneFk FROM route r WHERE r.id = NEW.routeFk; CALL vn.routeUpdateM3(NEW.routeFk); @@ -38886,7 +38887,7 @@ BEGIN END IF; IF NEW.routeFk <> OLD.routeFk THEN - UPDATE expedition + UPDATE expedition SET hasNewRoute = TRUE WHERE ticketFk = NEW.id; END IF; @@ -38909,11 +38910,11 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`ticket_beforeDelete` BEFORE DELETE ON `ticket` FOR EACH ROW -BEGIN - INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) - SELECT r.id +BEGIN + INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) + SELECT r.id FROM vn.route r - WHERE r.isOk = FALSE + WHERE r.isOk = FALSE AND r.id = OLD.routeFk AND r.created >= util.VN_CURDATE() GROUP BY r.id; @@ -38990,31 +38991,31 @@ CREATE TABLE `ticketCollection` ( /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER ticketCollection_afterDelete -AFTER DELETE -ON ticketCollection FOR EACH ROW -BEGIN - - DECLARE vSalesRemaining INT; - - SELECT count(*) INTO vSalesRemaining - FROM vn.ticketCollection tc - JOIN sale s ON s.ticketFk = tc.ticketFk - WHERE collectionFk = OLD.collectionFk - AND tc.id != OLD.id; - - IF NOT vSalesRemaining THEN - - DELETE FROM vn.collection WHERE id = OLD.collectionFk; - - ELSE - - UPDATE vn.collection - SET saleTotalCount = vSalesRemaining - WHERE id = OLD.collectionFk; - - END IF; - +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER ticketCollection_afterDelete +AFTER DELETE +ON ticketCollection FOR EACH ROW +BEGIN + + DECLARE vSalesRemaining INT; + + SELECT count(*) INTO vSalesRemaining + FROM vn.ticketCollection tc + JOIN sale s ON s.ticketFk = tc.ticketFk + WHERE collectionFk = OLD.collectionFk + AND tc.id != OLD.id; + + IF NOT vSalesRemaining THEN + + DELETE FROM vn.collection WHERE id = OLD.collectionFk; + + ELSE + + UPDATE vn.collection + SET saleTotalCount = vSalesRemaining + WHERE id = OLD.collectionFk; + + END IF; + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -39112,13 +39113,13 @@ DELIMITER ;; BEFORE DELETE ON `ticketDms` FOR EACH ROW BEGIN - UPDATE dms - SET dmsTypeFk = (SELECT id - FROM dmsType + UPDATE dms + SET dmsTypeFk = (SELECT id + FROM dmsType WHERE `code` = 'trash' ) - WHERE id = OLD.dmsFk AND ( SELECT IF(COUNT(*) > 0, FALSE, TRUE) - FROM ticketDms + WHERE id = OLD.dmsFk AND ( SELECT IF(COUNT(*) > 0, FALSE, TRUE) + FROM ticketDms WHERE dmsFk = OLD.dmsFk ) ; END */;; @@ -39594,7 +39595,7 @@ DELIMITER ;; BEGIN SET NEW.workerFk = vn.getUser(); - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -39922,7 +39923,7 @@ DELIMITER ;; BEGIN CALL ticket_requestRecalc(NEW.ticketFk); - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -39992,7 +39993,7 @@ BEGIN `changedModel` = 'TicketService', `changedModelId` = OLD.id, `userFk` = account.myUser_getId(); - + CALL ticket_requestRecalc(OLD.ticketFk); END */;; @@ -40143,11 +40144,11 @@ DELIMITER ;; FOR EACH ROW BEGIN DECLARE vNumTicketsPrepared INT; - + REPLACE vn.ticketLastState(ticketFk, ticketTrackingFk, name) SELECT NEW.ticketFk, NEW.id, `name` FROM state - WHERE id = NEW.stateFk; + WHERE id = NEW.stateFk; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -40190,21 +40191,21 @@ BEGIN DECLARE vTicketFk INT; DECLARE vTicketTrackingFk INT; DECLARE vStateName VARCHAR(15); - + IF NEW.stateFk <> OLD.stateFk THEN REPLACE vn.ticketLastState(ticketFk, ticketTrackingFk, name) SELECT NEW.ticketFk, NEW.id, `name` FROM state WHERE id = NEW.stateFk; END IF; - + IF NEW.ticketFk <> OLD.ticketFk THEN SELECT i.ticketFk, i.id, s.`name` - INTO vTicketFk, vTicketTrackingFk, vStateName - FROM ticketTracking i - JOIN state s ON i.stateFk = s.id - WHERE ticketFk = NEW.ticketFk - ORDER BY created DESC + INTO vTicketFk, vTicketTrackingFk, vStateName + FROM ticketTracking i + JOIN state s ON i.stateFk = s.id + WHERE ticketFk = NEW.ticketFk + ORDER BY created DESC LIMIT 1; IF vTicketFk > 0 THEN @@ -40246,18 +40247,18 @@ BEGIN `changedModel` = 'TicketTracking', `changedModelId` = OLD.id, `userFk` = account.myUser_getId(); - + CALL util.debugAdd('deletedState', CONCAT('interFk: ', OLD.id, ' ticketFk: ', OLD.ticketFk, ' stateFk: ', OLD.stateFk)); SELECT i.ticketFk, i.id, s.`name` - INTO vTicketFk, vTicketTrackingFk, vStateName - FROM ticketTracking i - JOIN state s ON i.stateFk = s.id - WHERE ticketFk = OLD.ticketFk - ORDER BY created DESC + INTO vTicketFk, vTicketTrackingFk, vStateName + FROM ticketTracking i + JOIN state s ON i.stateFk = s.id + WHERE ticketFk = OLD.ticketFk + ORDER BY created DESC LIMIT 1; IF vTicketFk > 0 THEN @@ -40449,13 +40450,13 @@ CREATE TABLE `till` ( /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`till_beforeInsert` - BEFORE INSERT ON `till` - FOR EACH ROW -BEGIN - IF NEW.concept IS NULL OR NEW.concept REGEXP '^[[:space:]]*$' THEN - SET NEW.concept = 'SIN DETALLE'; - END IF; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`till_beforeInsert` + BEFORE INSERT ON `till` + FOR EACH ROW +BEGIN + IF NEW.concept IS NULL OR NEW.concept REGEXP '^[[:space:]]*$' THEN + SET NEW.concept = 'SIN DETALLE'; + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -40878,7 +40879,7 @@ DELIMITER ;; FOR EACH ROW BEGIN SET NEW.editorFk = account.myUser_getId(); - + IF NOT (NEW.landed <=> OLD.landed) OR NOT (NEW.shipped <=> OLD.shipped) THEN CALL travel_checkDates(NEW.shipped, NEW.landed); @@ -40920,7 +40921,7 @@ BEGIN CALL stock.log_add('travel', NEW.id, OLD.id); IF !(NEW.shipped <=> OLD.shipped) THEN - UPDATE entry + UPDATE entry SET commission = entry_getCommission(travelFk, currencyFk,supplierFk) WHERE travelFk = NEW.id; END IF; @@ -42634,9 +42635,9 @@ DELIMITER ;; AFTER INSERT ON `workerTimeControl` FOR EACH ROW BEGIN - IF NEW.timed > DATE_ADD(util.VN_NOW(), INTERVAL 1 DAY) THEN + IF NEW.timed > DATE_ADD(util.VN_NOW(), INTERVAL 1 DAY) THEN CALL util.throw('date in the future'); - END IF; + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -43168,10 +43169,10 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`zoneExclusion_BI` BEFORE INSERT ON `zoneExclusion` FOR EACH ROW -BEGIN +BEGIN SET NEW.editorFk = account.myUser_getId(); SET NEW.userFk = account.myUser_getId(); - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -43190,10 +43191,10 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`zoneExclusion_BU` BEFORE UPDATE ON `zoneExclusion` FOR EACH ROW -BEGIN +BEGIN SET NEW.editorFk = account.myUser_getId(); SET NEW.userFk = account.myUser_getId(); - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -43590,8 +43591,8 @@ DELIMITER ;; FROM client c LEFT JOIN ticket t ON t.clientFk = c.id WHERE c.salesPersonFk IS NOT NULL - OR t.created > util.VN_CURDATE() - INTERVAL 2 MONTH - OR shipped > util.VN_CURDATE() - INTERVAL 2 MONTH + OR t.created > util.VN_CURDATE() - INTERVAL 2 MONTH + OR shipped > util.VN_CURDATE() - INTERVAL 2 MONTH ); END */ ;; /*!50003 SET time_zone = @saved_time_zone */ ;; @@ -44057,7 +44058,7 @@ BEGIN DECLARE vGeoFk INT; SELECT p.geoFk INTO vGeoFk - FROM address a + FROM address a JOIN town t ON t.provinceFk = a.provinceFk JOIN postCode p ON p.townFk = t.id AND p.`code` = a.postalCode WHERE a.id = vSelf @@ -44084,12 +44085,12 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `barcodeToItem`(vBarcode VARCHAR(22)) RETURNS int(11) DETERMINISTIC BEGIN - + /** * Obtiene el id del artículo * * @param vBarcode código de barras - * + * * return id del item */ @@ -44099,35 +44100,35 @@ BEGIN FROM vn.item WHERE id = vBarcode OR comment = vBarcode LIMIT 1; - - IF vItemFk THEN + + IF vItemFk THEN RETURN vItemFk; END IF; - SELECT itemFk INTO vItemFk - FROM buy + SELECT itemFk INTO vItemFk + FROM buy WHERE id = vBarcode; - - IF vItemFk THEN - RETURN vItemFk; - END IF; - - SELECT itemFk INTO vItemFk - FROM itemBarcode - WHERE code = vBarcode; - - IF vItemFk THEN + + IF vItemFk THEN RETURN vItemFk; END IF; - SELECT i.id INTO vItemFk + SELECT itemFk INTO vItemFk + FROM itemBarcode + WHERE code = vBarcode; + + IF vItemFk THEN + RETURN vItemFk; + END IF; + + SELECT i.id INTO vItemFk FROM vn.item i WHERE i.name LIKE CONCAT('%',vBarcode,'%') ORDER BY i.id ASC LIMIT 1; - + RETURN vItemFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -44150,9 +44151,9 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `botanicExport_isUpdatable`(vEdiGenus DETERMINISTIC BEGIN DECLARE vIsUpdatable INTEGER; - SELECT COUNT(*) INTO vIsUpdatable - FROM botanicExport - WHERE ediGenusFk = vEdiGenusFk + SELECT COUNT(*) INTO vIsUpdatable + FROM botanicExport + WHERE ediGenusFk = vEdiGenusFk AND (vEdiSpecieFk = ediSpecieFk OR IFNULL(vEdiSpecieFk,ediSpecieFk) IS NULL) AND vRestriction = restriction; RETURN vIsUpdatable; @@ -44248,16 +44249,16 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `catalog_componentReverse`(vWarehouse DETERMINISTIC BEGIN /* Calcula los componentes para un cliente a partir de un coste y volumen - * @param vWarehouse + * @param vWarehouse * @param vCost Valor de coste del articulo * @param vM3 m3 del articulo - * @param vAddressFk + * @param vAddressFk * @param vZoneFk - * @return vRetailedPrice precio de venta sin iva + * @return vRetailedPrice precio de venta sin iva * @return tmp.catalog_component (warehouseFk, itemFk, componentFk, cost) */ - - DECLARE vBoxVolume BIGINT; + + DECLARE vBoxVolume BIGINT; DECLARE vCustomer INT; DECLARE vComponentRecovery INT DEFAULT 17; DECLARE vComponentMana INT DEFAULT 39; @@ -44266,11 +44267,11 @@ BEGIN DECLARE vComponentCost INT DEFAULT 28; DECLARE vRetailedPrice DECIMAL(10,2); DECLARE vItem INT DEFAULT 98; - + SELECT volume INTO vBoxVolume FROM vn.packaging WHERE id = '94'; - + SELECT clientFk INTO vCustomer FROM address WHERE id = vAddressFk; DROP TEMPORARY TABLE IF EXISTS tmp.catalog_component; @@ -44294,7 +44295,7 @@ BEGIN -- Margen -- No se aplica margen, cau 12589 /* INSERT INTO tmp.catalog_component (warehouseFk, itemFk, componentFk, cost) - SELECT vWarehouse, vItem, vComponentMargin, (vCost / ((100 - rate2) / 100)) - vCost + SELECT vWarehouse, vItem, vComponentMargin, (vCost / ((100 - rate2) / 100)) - vCost FROM vn.rate WHERE dated <= util.VN_CURDATE() AND warehouseFk = vWarehouse @@ -44303,7 +44304,7 @@ BEGIN */ -- Recobro INSERT INTO tmp.catalog_component (warehouseFk, itemFk, componentFk, cost) - SELECT vWarehouse, vItem, vComponentRecovery, ROUND(LEAST(recobro,0.25), 3) + SELECT vWarehouse, vItem, vComponentRecovery, ROUND(LEAST(recobro,0.25), 3) FROM bi.claims_ratio WHERE Id_Cliente = vCustomer AND recobro > 0.009; @@ -44320,7 +44321,7 @@ BEGIN ROUND( vM3 * (z.price - z.bonus) - * z.inflation + * z.inflation / vBoxVolume, 4 ) FROM zone z @@ -44363,30 +44364,30 @@ BEGIN DECLARE vAutoManaComponent INT; DECLARE vManaBank INT; DECLARE vManaGreugeType INT; - + SELECT id INTO vManaGreugeType FROM greugeType WHERE code = 'mana'; SELECT id INTO vManaBank FROM bank WHERE code = 'mana'; SELECT id INTO vManaComponent FROM component WHERE code = 'mana'; SELECT id INTO vAutoManaComponent FROM component WHERE code = 'autoMana'; - + SELECT COUNT(*) INTO vHasMana FROM `client` c WHERE c.id = vClient AND c.typeFk = 'normal'; - + IF NOT vHasMana THEN RETURN 0; END IF; - + SELECT max(dated) INTO vFromDated FROM clientManaCache; SELECT sum(mana) INTO vMana - FROM + FROM ( SELECT mana FROM clientManaCache WHERE clientFk = vClient - AND dated = vFromDated + AND dated = vFromDated UNION ALL SELECT s.quantity * value FROM ticket t @@ -44394,7 +44395,7 @@ BEGIN JOIN sale s on s.ticketFk = t.id JOIN saleComponent sc on sc.saleFk = s.id WHERE sc.componentFk IN (vManaComponent, vAutoManaComponent) - AND t.shipped > vFromDated + AND t.shipped > vFromDated AND t.shipped < TIMESTAMPADD(DAY,1,util.VN_CURDATE()) AND a.clientFk = vClient UNION ALL @@ -44458,7 +44459,7 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `clientTaxArea`(vClientId INT, vCompa READS SQL DATA BEGIN /** -* Devuelve el area de un cliente, +* Devuelve el area de un cliente, * intracomunitario, extracomunitario o nacional. * * @param vClient Id del cliente @@ -44505,7 +44506,7 @@ BEGIN SELECT COUNT(*) INTO vHasDebt FROM `client` c WHERE c.id = vClient AND c.typeFk = 'normal'; - + IF NOT vHasDebt THEN RETURN 0; END IF; @@ -44593,8 +44594,8 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `client_getSalesPerson`(vClientFk INT DETERMINISTIC BEGIN /** - * Dado un id cliente y una fecha, devuelve su comercial para ese dia, teniendo - * en cuenta la jerarquía de las tablas: 1º la de sharingclient, 2º la de + * Dado un id cliente y una fecha, devuelve su comercial para ese dia, teniendo + * en cuenta la jerarquía de las tablas: 1º la de sharingclient, 2º la de * sharingcart y tercero la de clientes. * * @param vClientFk El id del cliente @@ -44632,29 +44633,29 @@ BEGIN l: LOOP SELECT workerSubstitute INTO vWorkerSubstituteFk - FROM sharingCart + FROM sharingCart WHERE util.VN_CURDATE() BETWEEN started AND ended AND workerFk = vSalesPersonFk ORDER BY id LIMIT 1; - + IF vWorkerSubstituteFk IS NULL THEN LEAVE l; END IF; - + SELECT COUNT(*) > 0 INTO vLoop FROM tmp.stack WHERE substitute = vWorkerSubstituteFk; IF vLoop THEN LEAVE l; END IF; - + INSERT INTO tmp.stack SET substitute = vWorkerSubstituteFk; - + SET vSalesPersonFk = vWorkerSubstituteFk; END LOOP; - + DROP TEMPORARY TABLE tmp.stack; END IF; @@ -44688,11 +44689,11 @@ BEGIN **/ DECLARE vClientFk INT; DECLARE vDated DATE; - + SELECT clientFk, shipped INTO vClientFk, vDated FROM ticket WHERE id = vTicketFk; - + RETURN client_getSalesPerson(vClientFk, vDated); END ;; DELIMITER ; @@ -44723,12 +44724,12 @@ BEGIN **/ DECLARE vWorkerCode CHAR(3); DECLARE vSalesPersonFk INT; - + SET vSalesPersonFk = client_getSalesPerson(vClientFk, vDated); SELECT code INTO vWorkerCode - FROM worker + FROM worker WHERE id = vSalesPersonFk; RETURN vWorkerCode; @@ -44761,11 +44762,11 @@ BEGIN **/ DECLARE vClientFk INT; DECLARE vDated DATE; - + SELECT clientFk, shipped INTO vClientFk, vDated FROM ticket WHERE id = vTicketFk; - + RETURN client_getSalesPersonCode(vClientFk, vDated); END ;; DELIMITER ; @@ -44857,7 +44858,7 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `currentRate`(vCurrencyFk INT, vDated BEGIN DECLARE curRate DECIMAL(10,4); - + SELECT value INTO curRate FROM referenceRate WHERE dated <= vDated @@ -44888,23 +44889,23 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `deviceProductionUser_accessGranted`( BEGIN /* * Comprueba si el usuario puede entrar en la aplicacion de almacen con ese movil - * + * * */ - + /*DECLARE vIsGranted BOOLEAN; DECLARE vDeviceProductionFk INT(11) DEFAULT NULL; - SELECT dp.id INTO vDeviceProductionFk - FROM vn.deviceProduction dp + SELECT dp.id INTO vDeviceProductionFk + FROM vn.deviceProduction dp WHERE dp.android_id = android_id; IF vDeviceProductionFk THEN - - SELECT COUNT(*) INTO vIsGranted - FROM vn.deviceProductionUser dpu - WHERE dpu.userFk = vUserFK + + SELECT COUNT(*) INTO vIsGranted + FROM vn.deviceProductionUser dpu + WHERE dpu.userFk = vUserFK AND dpu.deviceProductionFk = vDeviceProductionFk; - + RETURN vIsGranted; END IF;*/ RETURN TRUE; @@ -44928,16 +44929,16 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `duaTax_getRate`(vDua INT, vTaxClass DETERMINISTIC BEGIN DECLARE vCountryFk INTEGER; - + SELECT s.countryFk INTO vCountryFk FROM dua d JOIN supplier s ON s.id = d.companyFk WHERE d.id = vDua; - + RETURN (SELECT rate FROM (SELECT taxClassFk, rate - FROM invoiceInTaxBookingAccount + FROM invoiceInTaxBookingAccount WHERE effectived <= util.VN_CURDATE() AND countryFk = vCountryFk AND taxClassFk = vTaxClass @@ -44965,24 +44966,24 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `ekt_getEntry`(vEktFk INT) RETURNS in READS SQL DATA BEGIN /** - * Devuelve el numero de entrada para el ekt - * + * Devuelve el numero de entrada para el ekt + * * @param vEktFk Identificador de edi.ekt - */ + */ DECLARE vTravelFk INT; DECLARE vEntryFk INT DEFAULT 0; DECLARE vEntryAssignFk INT; - SELECT ea.id + SELECT ea.id INTO vEntryAssignFk FROM edi.ekt e - JOIN vn.ektEntryAssign ea ON + JOIN vn.ektEntryAssign ea ON IFNULL(ea.sub, e.sub) <=> e.sub AND IFNULL(ea.kop, e.kop) <=> e.kop AND IFNULL(ea.pro, e.pro) <=> e.pro AND IFNULL(ea.auction, e.auction) <=> e.auction WHERE e.id = vEktFk - ORDER BY + ORDER BY IF(ea.sub,1,0) * 1000 + IF(ea.kop,1,0) * 100 + IF(ea.pro,1,0) * 10 + @@ -44993,7 +44994,7 @@ BEGIN IF vTravelFk THEN - SELECT MAX(e.id) + SELECT MAX(e.id) INTO vEntryFk FROM vn.entry e JOIN vn.ektEntryAssign ea ON ea.id = vEntryAssignFk @@ -45008,13 +45009,13 @@ BEGIN INSERT INTO vn.entry(travelFk, supplierFk, companyFk, currencyFk, kop, sub, reference, pro, auction) SELECT vTravelFk, ea.supplierFk, ea.companyFk, cu.id, ea.kop, ea.sub, ea.ref, ea.pro, ea.auction FROM vn.ektEntryAssign ea - JOIN vn.currency cu ON cu.code = 'EUR' + JOIN vn.currency cu ON cu.code = 'EUR' WHERE ea.id = vEntryAssignFk; SET vEntryFk = LAST_INSERT_ID(); END IF; - UPDATE vn.ektEntryAssign + UPDATE vn.ektEntryAssign SET entryFk = vEntryFk WHERE id = vEntryAssignFk; @@ -45048,7 +45049,7 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `ekt_getTravel`(vEntryAssignFk INT, v BEGIN /** * Devuelve un vn.travel.id - * + * * @param vEntryAssignFk Identificador de vn.entryAssign */ DECLARE vTravelFk INT; @@ -45109,36 +45110,36 @@ BEGIN DECLARE vCurrentCommission INT; DECLARE vIsCurrencyUsd INT; DECLARE vLastEntryFk INT; - + SELECT count(*) INTO vIsCurrencyUsd FROM currency c WHERE c.code = 'USD' AND id = vCurrencyFk; - + IF NOT vIsCurrencyUsd THEN - + SELECT e.id INTO vLastEntryFk FROM vn.entry e JOIN vn.travel tr ON tr.id = e.travelFk WHERE e.supplierFk = vSupplierFk ORDER BY tr.landed DESC LIMIT 1; - + IF vLastEntryFk THEN - + SELECT commission INTO vCurrentCommission FROM vn.entry WHERE id = vLastEntryFk; - + ELSE - + SELECT commission INTO vCurrentCommission FROM supplier s WHERE s.id = vSupplierFk; - + END IF; - + RETURN vCurrentCommission; - + ELSE SELECT ROUND(-100 * (1 - (1 / r.value))) INTO vCommission @@ -45147,11 +45148,11 @@ BEGIN WHERE t.id = vTravelFk ORDER BY r.`dated` DESC LIMIT 1; - + RETURN IFNULL(vCommission, 0); - + END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -45202,10 +45203,10 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `entry_getForLogiflora`(vLanded DATE, vWarehouseFk INT) RETURNS int(11) READS SQL DATA BEGIN - + /** * Devuelve una entrada para Logiflora. Si no existe la crea. - * + * * @param vLanded Fecha de llegada al almacén * @param vWarehouseFk Identificador de vn.warehouse */ @@ -45213,51 +45214,51 @@ BEGIN DECLARE vTravelFk INT; DECLARE vEntryFk INT; DECLARE previousEntryFk INT; - + SET vTravelFk = vn.travel_getForLogiflora(vLanded, vWarehouseFk); - + IF vLanded THEN - - SELECT IFNULL(MAX(id),0) INTO vEntryFk + + SELECT IFNULL(MAX(id),0) INTO vEntryFk FROM vn.entry - WHERE travelFk = vTravelFk + WHERE travelFk = vTravelFk AND isRaid; IF NOT vEntryFk THEN - + INSERT INTO vn.entry(travelFk, supplierFk, commission, companyFk, currencyFk, isRaid) SELECT vTravelFk, s.id, 4, c.id, cu.id, TRUE FROM vn.supplier s JOIN vn.company c ON c.code = 'VNL' JOIN vn.currency cu ON cu.code = 'EUR' WHERE s.name = 'KONINKLIJE COOPERATIEVE BLOEMENVEILING FLORAHOLLAN'; - - SELECT MAX(id) INTO vEntryFk + + SELECT MAX(id) INTO vEntryFk FROM vn.entry WHERE travelFk = vTravelFk; - - END IF; - - END IF; - SELECT entryFk INTO previousEntryFk + END IF; + + END IF; + + SELECT entryFk INTO previousEntryFk FROM edi.warehouseFloramondo wf WHERE wf.warehouseFk = vWarehouseFk; - + IF IFNULL(previousEntryFk,0) != vEntryFk THEN - - UPDATE buy b - SET b.printedStickers = 0 + + UPDATE buy b + SET b.printedStickers = 0 WHERE entryFk = previousEntryFk; DELETE FROM buy WHERE entryFk = previousEntryFk; - + DELETE FROM entry WHERE id = previousEntryFk; - + END IF; - + RETURN vEntryFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -45290,21 +45291,21 @@ BEGIN SELECT IFNULL(a.isUeeMember, c.isUeeMember), c.id INTO vIsUeeSupplier, vSupplierCountry - FROM entry e - JOIN supplier s ON s.id = e.supplierFk - JOIN country c ON c.id = s.countryFk + FROM entry e + JOIN supplier s ON s.id = e.supplierFk + JOIN country c ON c.id = s.countryFk LEFT JOIN province p ON p.id = s.provinceFk LEFT JOIN autonomy a ON a.id = p.autonomyFk WHERE e.id = vSelf; - + SELECT IFNULL(a.isUeeMember, c.isUeeMember), c.id INTO vIsUeeCompany, vCompanyCountry - FROM entry e - JOIN supplier s ON s.id = e.companyFk - JOIN country c ON c.id = s.countryFk + FROM entry e + JOIN supplier s ON s.id = e.companyFk + JOIN country c ON c.id = s.countryFk LEFT JOIN province p ON p.id = s.provinceFk LEFT JOIN autonomy a ON a.id = p.autonomyFk - WHERE e.id = vSelf; + WHERE e.id = vSelf; RETURN vIsUeeCompany AND vIsUeeSupplier AND (vSupplierCountry <> vCompanyCountry); @@ -45369,17 +45370,17 @@ BEGIN DECLARE vHasDistinctRoutes BOOL; SELECT t.routeFk INTO vRouteFk - FROM vn.expedition e + FROM vn.expedition e JOIN vn.ticket t ON e.ticketFk = t.id WHERE e.id = vExpeditionFk; - + SELECT COUNT(*) > 0 INTO vHasDistinctRoutes FROM vn.expeditionScan es JOIN vn.expedition e ON es.expeditionFk = e.id JOIN vn.ticket t ON e.ticketFk = t.id WHERE es.palletFk = vPalletFk AND t.routeFk <> vRouteFk; - + RETURN vHasDistinctRoutes; END ;; @@ -45440,27 +45441,27 @@ BEGIN DECLARE vDeliveryType INTEGER DEFAULT 0; DECLARE isWaitingForPickUp BOOLEAN DEFAULT FALSE; DECLARE vCode VARCHAR(45); - + SELECT am.deliveryMethodFk - INTO vDeliveryType + INTO vDeliveryType FROM ticket t JOIN agencyMode am ON am.id = t.agencyModeFk WHERE t.id = vTicket; - + CASE vDeliveryType WHEN 1 THEN -- AGENCIAS SET vCode = 'DELIVERED'; - + WHEN 2 THEN -- REPARTO SET vCode = 'ON_DELIVERY'; - + ELSE -- MERCADO, OTROS SELECT MIN(t.warehouseFk <> w.id) INTO isWaitingForPickUp - FROM ticket t + FROM ticket t LEFT JOIN warehouse w ON w.pickUpagencyModeFk = t.agencyModeFk WHERE t.id = vTicket; - + IF isWaitingForPickUp THEN SET vCode = 'WAITING_FOR_PICKUP'; ELSE @@ -45490,28 +45491,28 @@ BEGIN DECLARE vDeliveryType INTEGER DEFAULT 0; DECLARE isWaitingForPickUp BOOLEAN DEFAULT FALSE; DECLARE vCode VARCHAR(45); - - SELECT + + SELECT a.Vista - INTO vDeliveryType + INTO vDeliveryType FROM vn2008.Tickets t JOIN vn2008.Agencias a ON a.Id_Agencia = t.Id_Agencia WHERE Id_Ticket = vTicket; - + CASE vDeliveryType WHEN 1 THEN -- AGENCIAS SET vCode = 'DELIVERED'; - + WHEN 2 THEN -- REPARTO SET vCode = 'ON_DELIVERY'; - + ELSE -- MERCADO, OTROS SELECT t.warehouse_id <> w.warehouse_id INTO isWaitingForPickUp - FROM vn2008.Tickets t - LEFT JOIN vn2008.warehouse_pickup w + FROM vn2008.Tickets t + LEFT JOIN vn2008.warehouse_pickup w ON w.agency_id = t.Id_Agencia AND w.warehouse_id = t.warehouse_id WHERE t.Id_Ticket = vTicket; - + IF isWaitingForPickUp THEN SET vCode = 'WAITING_FOR_PICKUP'; ELSE @@ -45619,16 +45620,16 @@ BEGIN DECLARE vReturn DATE; DECLARE vDuaDate DATE; DECLARE vDuaDateDay INT; - + SELECT TIMESTAMPADD(DAY, vGapDays, vDated) INTO vDuaDate; IF vDuaDate = CONCAT(YEAR(vDuaDate), '-03-01') THEN - SET vDuaDate = TIMESTAMPADD (DAY , -1, vDuaDate); + SET vDuaDate = TIMESTAMPADD (DAY , -1, vDuaDate); ELSEIF vDuaDate = CONCAT(YEAR(vDuaDate), '-02-29') THEN - SET vDuaDate = TIMESTAMPADD (DAY , -2, vDuaDate); + SET vDuaDate = TIMESTAMPADD (DAY , -2, vDuaDate); END IF; - IF MONTH(vDuaDate) = 2 AND vPayDay = 30 THEN + IF MONTH(vDuaDate) = 2 AND vPayDay = 30 THEN IF util.isLeapYear(YEAR(vDuaDate)) THEN SET vPayDay = 29; ELSE @@ -45636,7 +45637,7 @@ BEGIN END IF; END IF; - SELECT DAY(vDuaDate) INTO vDuaDateDay; + SELECT DAY(vDuaDate) INTO vDuaDateDay; RETURN TIMESTAMPADD(MONTH, (vDuaDateDay > vPayDay), DATE_FORMAT(vDuaDate, CONCAT('%y/%m/', vPayDay))); END ;; DELIMITER ; @@ -45658,11 +45659,11 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `getShipmentHour`(vTicket INT) RETURN READS SQL DATA BEGIN DECLARE vShipmentHour INT; - + SELECT HOUR(shipped) INTO vShipmentHour FROM ticket WHERE id = vTicket; - + IF vShipmentHour = 0 THEN DROP TEMPORARY TABLE IF EXISTS tmp.production_buffer; @@ -45677,11 +45678,11 @@ BEGIN JOIN agencyMode am on am.id = t.agencyModeFk JOIN address a on a.id = t.addressFk WHERE t.id = vTicket; - - SELECT Hora INTO vShipmentHour + + SELECT Hora INTO vShipmentHour FROM tmp.production_buffer; END IF; - + RETURN vShipmentHour; END ;; DELIMITER ; @@ -45706,12 +45707,12 @@ BEGIN SELECT rate3 INTO price FROM vn.priceFixed - WHERE itemFk = vItemFk + WHERE itemFk = vItemFk AND util.VN_CURDATE() BETWEEN started AND ended ORDER BY created DESC LIMIT 1; - SELECT `value` INTO price + SELECT `value` INTO price FROM vn.specialPrice - WHERE itemFk = vItemFk + WHERE itemFk = vItemFk AND clientFk = vClientFk ; RETURN price; END ;; @@ -45735,7 +45736,7 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `getTicketTrolleyLabelCount`(vTicket BEGIN DECLARE vLabelCount INT DEFAULT 0; - SELECT labelCount INTO vLabelCount + SELECT labelCount INTO vLabelCount FROM ticketTrolley WHERE ticket = vTicket; @@ -45865,17 +45866,17 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `hasItemsInSector`(vTicketFk INT, vSe BEGIN DECLARE vItemCount INT; - + SELECT count(*) INTO vItemCount - FROM vn.sale s + FROM vn.sale s JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk JOIN vn.shelving sh ON sh.code = ish.shelvingFk JOIN vn.parking p ON p.id = sh.parkingFk WHERE s.ticketFk = vTicketFk AND p.sectorFk = vSectorFk; - + RETURN vItemCount; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -45898,7 +45899,7 @@ BEGIN DECLARE vCountry INT; DECLARE hasSomeNegativeBase BOOLEAN; - SELECT s.countryFk + SELECT s.countryFk INTO vCountry FROM supplier s JOIN ticket t ON t.companyFk = s.id @@ -45907,9 +45908,9 @@ BEGIN SELECT COUNT(*) INTO hasSomeNegativeBase FROM ( SELECT SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2)) taxableBase - FROM sale s + FROM sale s JOIN item i ON i.id = s.itemFk - JOIN itemTaxCountry itc + JOIN itemTaxCountry itc ON itc.itemFk = i.id AND itc.countryFk = vCountry WHERE s.ticketFk = vTicket GROUP BY itc.taxClassFk @@ -45939,12 +45940,12 @@ BEGIN DECLARE totalAmount DECIMAL(10,2); SELECT SUM(vat) INTO totalAmount - FROM ( + FROM ( SELECT iot.vat FROM invoiceOutTax iot JOIN invoiceOut io ON io.id = iot.invoiceOutFk WHERE io.ref = vInvoiceRef - UNION ALL + UNION ALL SELECT ioe.amount FROM invoiceOutExpence ioe JOIN invoiceOut io ON io.id = ioe.invoiceOutFk @@ -45975,23 +45976,23 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `invoiceOut_getMaxIssued`(vSerial VAR READS SQL DATA BEGIN /** - * Retorna la fecha a partir de la cual es válido emitir una factura + * Retorna la fecha a partir de la cual es válido emitir una factura * - * @param vSerial Serie de facturación + * @param vSerial Serie de facturación * @param vCompanyFk Empresa factura emitida * @param vYear Año contable * @return vInvoiceOutIssued fecha factura válida */ DECLARE vInvoiceOutIssued DATE; DECLARE vFirstDayOfYear DATE; - + SET vFirstDayOfYear := MAKEDATE(vYear, 1); - SELECT IFNULL(MAX(io.issued), vFirstDayOfYear) INTO vInvoiceOutIssued + SELECT IFNULL(MAX(io.issued), vFirstDayOfYear) INTO vInvoiceOutIssued FROM invoiceOut io WHERE io.serial = vSerial AND io.companyFk = vCompanyFk - AND io.issued BETWEEN vFirstDayOfYear + AND io.issued BETWEEN vFirstDayOfYear AND util.lastDayOfYear(vFirstDayOfYear); RETURN vInvoiceOutIssued; @@ -46017,7 +46018,7 @@ BEGIN DECLARE vIssued DATE; DECLARE vSerial VARCHAR(15); - SELECT issued, ref + SELECT issued, ref INTO vIssued, vSerial FROM invoiceOut WHERE id = vSelf; @@ -46089,9 +46090,9 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `invoiceSerial`(vClientFk INT, vCompa DETERMINISTIC BEGIN /** - * Obtiene la serie de de una factura + * Obtiene la serie de de una factura * dependiendo del area del cliente. - * + * * @param vClientFk Id del cliente * @param vCompanyFk Id de la empresa * @param vType Tipo de factura ["R", "M", "G"] @@ -46172,18 +46173,18 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `isLogifloraDay`(vShipped DATE, vWarehouse INT) RETURNS tinyint(1) DETERMINISTIC BEGIN - + DECLARE vIsLogifloraDay BOOLEAN; SELECT COUNT(*) INTO vIsLogifloraDay FROM edi.warehouseFloramondo wf - JOIN vn.floramondoConfig fc + JOIN vn.floramondoConfig fc WHERE wf.warehouseFk = vWarehouse AND vShipped BETWEEN DATE(TIMESTAMPADD(DAY, wf.travellingDays , fc.nextLanded)) AND DATE(TIMESTAMPADD(DAY, wf.travellingDays + wf.dayRange , fc.nextLanded)); - + RETURN vIsLogifloraDay; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -46220,7 +46221,7 @@ BEGIN WHERE sl.scan_id = vScanId AND t.Id_Ruta ) t1; - + RETURN vDistinctRoutesInThePallet = 1; END ;; DELIMITER ; @@ -46244,20 +46245,20 @@ BEGIN DECLARE vPacking INTEGER DEFAULT 0; DECLARE vItemFk INTEGER; - + SELECT vn.barcodeToItem(vBarcode) INTO vItemFk; - - SELECT IFNULL(packing,0) INTO vPacking - FROM vn.buy + + SELECT IFNULL(packing,0) INTO vPacking + FROM vn.buy WHERE id = CAST(vBarcode AS DECIMAL(18,0)); - - - - + + + + IF NOT vPacking THEN CALL cache.last_buy_refresh(FALSE); SELECT IFNULL(packing,1) INTO vPacking - FROM + FROM (SELECT packing , created FROM vn.itemShelving WHERE itemFk = vItemFk @@ -46270,11 +46271,11 @@ BEGIN ) packings ORDER BY created desc LIMIT 1; - + END IF; - + RETURN vPacking; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -46299,11 +46300,11 @@ BEGIN DECLARE vColumn INT; DECLARE vClosestParkingFk INT; DECLARE vSectorFk INT; - + SELECT p.column, sectorFk INTO vColumn, vSectorFk FROM vn.parking p WHERE p.id = vParkingFk; - + SELECT itemShelvingFk INTO vClosestParkingFk FROM ( @@ -46313,12 +46314,12 @@ BEGIN JOIN vn.itemPlacementSupplyList ipsl ON ipsl.sectorFk = ispss.sectorFk AND ipsl.itemFk = ispss.itemFk WHERE p.sectorFk = vSectorFk AND ipsl.saldo > 0 - ) sub + ) sub ORDER BY distance LIMIT 1; - + RETURN vClosestParkingFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -46340,17 +46341,17 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `itemsInSector_get`(vTicketFk INT, vS BEGIN DECLARE vItemCount INT; - + SELECT count(*) INTO vItemCount - FROM vn.sale s + FROM vn.sale s JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk JOIN vn.shelving sh ON sh.code = ish.shelvingFk JOIN vn.parking p ON p.id = sh.parkingFk WHERE s.ticketFk = vTicketFk AND p.sectorFk = vSectorFk; - + RETURN vItemCount; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -46423,29 +46424,29 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `item_getPackage`(vItemFk INT) RETURNS varchar(50) CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci DETERMINISTIC BEGIN - + DECLARE vDiameter INT; DECLARE vPackageFk VARCHAR(50); DECLARE vCoeficient DOUBLE DEFAULT 1.08; - + SELECT MAX(LEFT(value,3)) INTO vDiameter - FROM vn.itemTag it + FROM vn.itemTag it JOIN vn.tag t ON t.id = it.tagFk WHERE it.itemFk = vItemFk AND t.overwrite = 'diameter'; - + SELECT 8000 + FLOOR(vc.ccLength * vc.ccWidth / (vCoeficient * PI() * (vDiameter / 2) * (vDiameter / 2))) INTO vPackageFk FROM vn.volumeConfig vc; - + INSERT IGNORE INTO vn.packaging(id, width, `depth`) - SELECT vPackageFk, - FLOOR(vc.ccWidth / FLOOR(vc.ccWidth / vDiameter)), + SELECT vPackageFk, + FLOOR(vc.ccWidth / FLOOR(vc.ccWidth / vDiameter)), FLOOR(vc.ccLength / FLOOR(vc.ccLength / vDiameter)) FROM vn.volumeConfig vc; - + RETURN vPackageFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -46482,7 +46483,7 @@ BEGIN FROM packaging p JOIN item i ON i.id = vSelf WHERE p.id = vPackaging; - + RETURN vVolume; END ;; @@ -46503,7 +46504,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `lastDayOfWeek`(vYear INT, vWeek INT) RETURNS date DETERMINISTIC -BEGIN +BEGIN /** * Returns the date of the last day of the week * @@ -46542,16 +46543,16 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `machine_checkPlate`(vPlate VARCHAR(1 BEGIN /** * Comprueba si existe matrícula - * + * * @param vPlate matrícula del vehículo * @return Devuelve TRUE en caso de que exista - * + * */ - + IF (SELECT COUNT(*) - FROM machine m + FROM machine m WHERE m.plate = vPlate - ) THEN + ) THEN RETURN TRUE; ELSE RETURN FALSE; @@ -46578,9 +46579,9 @@ BEGIN DECLARE result INT; DECLARE vSenderFk INT; - SELECT id INTO vSenderFk + SELECT id INTO vSenderFk FROM account.user WHERE `name` = account.myUser_getName(); - + RETURN (SELECT messageSendWithUser(vSenderFk, vRecipient, vMessage)); END ;; DELIMITER ; @@ -46607,9 +46608,9 @@ BEGIN DECLARE vSendDate DATETIME DEFAULT util.VN_NOW(); DECLARE vSender VARCHAR(255) CHARSET utf8; - SELECT `name` INTO vSender + SELECT `name` INTO vSender FROM account.user WHERE id = vSenderFK; - + SET vRecipient = LOWER(vRecipient); DROP TEMPORARY TABLE IF EXISTS tRecipients; @@ -46630,7 +46631,7 @@ BEGIN IF vCount = 0 THEN RETURN vCount; - END IF; + END IF; SET vUuid = UUID(); @@ -46641,7 +46642,7 @@ BEGIN message = vMessage, sendDate = vSendDate; - INSERT INTO messageInbox (uuid, sender, recipient, finalRecipient, message, sendDate) + INSERT INTO messageInbox (uuid, sender, recipient, finalRecipient, message, sendDate) SELECT vUuid, vSender, vRecipient, finalRecipient, vMessage, vSendDate FROM tRecipients; @@ -46715,7 +46716,7 @@ BEGIN -- Devuelte el volumen total de la orden sumada DECLARE vWarehouseId INTEGER; DECLARE vVolume DECIMAL(10,3); - + SELECT IFNULL(SUM(o.amount * ic.cm3delivery)/1000000,0) INTO vVolume FROM hedera.orderRow o JOIN item i ON i.id = o.itemFk @@ -46792,7 +46793,7 @@ BEGIN WHERE cb.id = packagingReturnFk; SET vValue = IF (vAmount IS NULL, - IFNULL(base,0), + IFNULL(base,0), vAmount / IFNULL(upload, 0) + IFNULL(base, 0)); ELSE SET vValue = IFNULL(price, 0) + IFNULL(base, 0); @@ -46819,7 +46820,7 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `phytoPassport`(vRef VARCHAR(15)) RET DETERMINISTIC BEGIN DECLARE vPhyto TEXT CHARSET utf8 COLLATE utf8_unicode_ci; -SELECT +SELECT GROUP_CONCAT(i.id, ':', ppa.denomination, @@ -46908,20 +46909,20 @@ BEGIN DECLARE vRouteFk INT; DECLARE vAddressFk INT; - + DECLARE vLanded DATE; DECLARE vZoneFk INT; DECLARE vSignificativeFriendship INT DEFAULT 6; DECLARE vVolumeMax DECIMAL(5,1) DEFAULT 10; - + SELECT addressFk, zoneFk, landed INTO vAddressFk, vZoneFk, vLanded - FROM vn.ticket + FROM vn.ticket WHERE id = vTicketFk; - + -- Se inicia la selección de rutas posibles con aquellas cuyas agencias alguna vez han estado asociadas con nuestra zona DROP TEMPORARY TABLE IF EXISTS tmp.route; CREATE TEMPORARY TABLE tmp.route - SELECT r.id routeFk, + SELECT r.id routeFk, zf.friendship zoneFriendship FROM vn.route r JOIN cache.zoneAgencyFriendship zf ON zf.agencyModeFk = r.agencyModeFk @@ -46929,16 +46930,16 @@ BEGIN AND zf.zoneFk = vZoneFk AND r.created = vLanded ORDER BY friendship; - + -- Se eliminan aquellas que superan el volumen máximo DELETE r.* - FROM tmp.route r + FROM tmp.route r JOIN (SELECT routeFk, sum(volume) volume FROM vn.saleVolume WHERE landed = vLanded GROUP BY routeFk) sub ON sub.routeFk = r.routeFk WHERE sub.volume > vVolumeMax; - + -- Se ordenan las que quedan en función con la afinidad del resto de consignatarios de cada ruta SELECT routeFk INTO vRouteFk FROM @@ -46950,7 +46951,7 @@ BEGIN ORDER BY zoneFriendship DESC, friendshipSum DESC ) sub LIMIT 1; - + RETURN vRouteFk; END ;; DELIMITER ; @@ -46975,9 +46976,9 @@ BEGIN DECLARE vRouteFk INT; DECLARE vAddressFk INT; DECLARE vShipped DATETIME; - + SELECT addressFk, date(shipped) INTO vAddressFk, vShipped - FROM vn.ticket + FROM vn.ticket WHERE id = vTicketFk; SELECT routeFk INTO vRouteFk @@ -46991,7 +46992,7 @@ BEGIN ORDER BY friendshipSum DESC ) sub LIMIT 1; - + RETURN vRouteFk; END ;; DELIMITER ; @@ -47015,20 +47016,20 @@ BEGIN DECLARE vRouteFk INT; DECLARE vAddressFk INT; - + DECLARE vLanded DATE; DECLARE vZoneFk INT; DECLARE vSignificativeFriendship INT DEFAULT 6; DECLARE vVolumeMax DECIMAL(5,1) DEFAULT 10; - + SELECT addressFk, zoneFk, landed INTO vAddressFk, vZoneFk, vLanded - FROM vn.ticket + FROM vn.ticket WHERE id = vTicketFk; - + -- Se inicia la selección de rutas posibles con aquellas cuyas agencias alguna vez han estado asociadas con nuestra zona DROP TEMPORARY TABLE IF EXISTS tmp.route; CREATE TEMPORARY TABLE tmp.route - SELECT r.id routeFk, + SELECT r.id routeFk, zf.friendship zoneFriendship FROM vn.route r JOIN cache.zoneAgencyFriendship zf ON zf.agencyModeFk = r.agencyModeFk @@ -47036,16 +47037,16 @@ BEGIN AND zf.zoneFk = vZoneFk AND r.created = vLanded ORDER BY friendship; - + -- Se eliminan aquellas que superan el volumen máximo DELETE r.* - FROM tmp.route r + FROM tmp.route r JOIN (SELECT routeFk, sum(volume) volume FROM vn.saleVolume WHERE landed = vLanded GROUP BY routeFk) sub ON sub.routeFk = r.routeFk WHERE sub.volume > vVolumeMax; - + -- Se ordenan las que quedan en función con la afinidad del resto de consignatarios de cada ruta SELECT routeFk INTO vRouteFk FROM @@ -47057,7 +47058,7 @@ BEGIN ORDER BY zoneFriendship DESC, friendshipSum DESC ) sub LIMIT 1; - + RETURN vRouteFk; END ;; DELIMITER ; @@ -47078,26 +47079,26 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `specie_IsForbidden`(vItemFk INT, vAddressFk INT) RETURNS tinyint(1) READS SQL DATA BEGIN - + DECLARE vIsForbbiden BOOL; DECLARE vLeft INT; SELECT zg.lft INTO vLeft - FROM vn.address a - JOIN vn.zoneGeo zg ON zg.name = a.postalCode + FROM vn.address a + JOIN vn.zoneGeo zg ON zg.name = a.postalCode WHERE a.id = vAddressFk; - + SELECT sgi.isForbidden INTO vIsForbbiden - FROM vn.specieGeoInvasive sgi - JOIN vn.zoneGeo zg ON zg.id = sgi.zoneGeofk + FROM vn.specieGeoInvasive sgi + JOIN vn.zoneGeo zg ON zg.id = sgi.zoneGeofk JOIN vn.itemBotanical ib ON ib.genusFk = sgi.genusFk AND sgi.specieFk IN ('sp.',ib.specieFk) WHERE vLeft BETWEEN zg.lft AND zg.rgt AND ib.itemFk = vItemFk - ORDER BY zg.`depth` DESC + ORDER BY zg.`depth` DESC LIMIT 1; RETURN IFNULL(vIsForbbiden, FALSE); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -47117,7 +47118,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `testCIF`(vCIF VARCHAR(9)) RETURNS varchar(10) CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci DETERMINISTIC BEGIN - + DECLARE vLetraInicial VARCHAR(1); DECLARE vLetraFinal VARCHAR(1); DECLARE vParteNumerica VARCHAR(7); @@ -47129,60 +47130,60 @@ BEGIN SET vLetraInicial = SUBSTR(vCIF, 1, 1); SET vLetraFinal = SUBSTR(vCIF, 9, 1); SET vParteNumerica = SUBSTR(vCIF, 2, 7); - - WHILE i < 7 DO - + + WHILE i < 7 DO + SET i = i + 1; - + SET vNumero = CAST(SUBSTR(vParteNumerica, i, 1) AS DECIMAL(1,0)); - + IF i MOD 2 THEN - + SET vNumero = vNumero * 2; SET vNumero = vNumero MOD 10 + FLOOR(vNumero/10); - + END IF; - + SET vSuma = vSuma + vNumero; - + END WHILE; - + SET vSuma = vSuma MOD 10; - + IF vSuma > 0 THEN - + SET vSuma = 10 - vSuma; - + END IF; - + -- Comprobación de dígito de control IF CAST(vLetraFinal AS DECIMAL(1,0)) = vSuma THEN - + SET vResult = TRUE; - + END IF; - + IF vSuma = 0 THEN - + SET vSuma = 10; - + END IF; - + IF CHAR(64 + vSuma) = vLetraFinal THEN - + SET vResult = TRUE; - + END IF; - + -- Sólo se aceptan letras como caracter inicial IF ASCII(vLetraInicial) < 65 OR ASCII(vLetraInicial) > 87 THEN -- Ha de ser entre la A y la W - + SET vResult = FALSE; - + END IF; - + RETURN vResult; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -47202,7 +47203,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `testNIE`(vNIE VARCHAR(9)) RETURNS tinyint(1) DETERMINISTIC BEGIN - + DECLARE vIndice INT; DECLARE vNumero VARCHAR(7); DECLARE vOperador VARCHAR(9); @@ -47211,45 +47212,45 @@ BEGIN DECLARE vLetraFinal VARCHAR(1); DECLARE vLetrasFinalesPosibles VARCHAR(24) DEFAULT "TRWAGMYFPDXBNJZSQVHLCKE"; DECLARE vLetraInicialEsIncorrecta BOOL DEFAULT FALSE; - + SET vLetraInicial = SUBSTR(vNIE, 1, 1); SET vLetraFinal = SUBSTR(vNIE, 9, 1); SET vNumero = SUBSTR(vNIE, 2, 7); CASE vLetraInicial - + WHEN 'X' THEN - + SET vOperador = "0"; - + WHEN 'Y' THEN - + SET vOperador = "1"; - + WHEN 'Z' THEN - + SET vOperador = "2"; - + ELSE - + SET vLetraInicialEsIncorrecta = TRUE; - + END CASE; - + SET vOperador = CONCAT(vOperador, vNumero); SET vParteNumerica = CAST(vOperador AS DECIMAL(8,0)); SET vIndice = Round(vParteNumerica Mod 23, 0) + 1; IF SUBSTR(vLetrasFinalesPosibles, vIndice, 1) = vLetraFinal AND vLetraInicialEsIncorrecta = FALSE THEN - + RETURN TRUE; - + ELSE - + RETURN FALSE; - + END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -47274,23 +47275,23 @@ BEGIN DECLARE vParteNumerica DECIMAL(8,0); DECLARE vLetra VARCHAR(1); DECLARE vLetrasPosibles VARCHAR(24) DEFAULT "TRWAGMYFPDXBNJZSQVHLCKE"; - + SET vLetra = SUBSTRING(vNIF, 9, 1); - + SET vParteNumerica = CAST(SUBSTRING(vNIF, 1, 8) AS DECIMAL(8,0)); - + SET vIndice = Round(vParteNumerica MOD 23, 0) + 1; - + If SUBSTRING(vLetrasPosibles, vIndice, 1) = vLetra Then - + RETURN TRUE; - + ELSE - + RETURN FALSE; - + END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -47310,21 +47311,21 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `ticketCollection_getNoPacked`(vCollectionFk INT) RETURNS varchar(100) CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci DETERMINISTIC BEGIN - + /* * return message with tickets and collection if there is tickets of a collection without expeditions - * + * * @param vCollectionFk the collection to check * @return an array with collection and tickets without expeditions - * + * */ - + DECLARE vAnswer VARCHAR(100) DEFAULT ''; IF collection_isPacked(vCollectionFk) = FALSE THEN SELECT CONCAT('Colección: ',tc.collectionFk,' Tickets: ' , GROUP_CONCAT(tc.ticketFk) ) INTO vAnswer FROM vn.ticketCollection tc - LEFT JOIN vn.expedition e ON e.ticketFk = tc.ticketFk + LEFT JOIN vn.expedition e ON e.ticketFk = tc.ticketFk WHERE tc.collectionFk = vCollectionFk AND ISNULL(e.id); END IF; @@ -47370,9 +47371,9 @@ BEGIN DROP TEMPORARY TABLE tmp.ticket, tmp.ticketTotal; - + RETURN vTotal; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -47392,7 +47393,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `ticketPositionInPath`(vTicketId INT) RETURNS varchar(10) CHARSET utf8mb3 COLLATE utf8mb3_general_ci DETERMINISTIC BEGIN - + DECLARE vRestTicketsMaxOrder INT; DECLARE vRestTicketsMinOrder INT; DECLARE vRestTicketsPacking INT; @@ -47404,7 +47405,7 @@ BEGIN DECLARE vExpeditionsCount INT; DECLARE vIsValenciaPath BOOLEAN DEFAULT FALSE; -SELECT `order` +SELECT `order` INTO PACKING_ORDER FROM state WHERE code = 'PACKING'; @@ -47415,7 +47416,7 @@ SELECT t.routeFk, t.warehouseFk, IFNULL(ts.productionOrder,0) LEFT JOIN ticketState ts on ts.ticket = t.id WHERE t.id = vTicketId; -SELECT (ag.`name` = 'VN_VALENCIA') +SELECT (ag.`name` = 'VN_VALENCIA') INTO vIsValenciaPath FROM vn2008.Rutas r JOIN vn2008.Agencias a on a.Id_Agencia = r.Id_Agencia @@ -47429,7 +47430,7 @@ IF vIsValenciaPath THEN -- Rutas Valencia FROM expedition e JOIN ticket t ON t.id = e.ticketFk WHERE t.routeFk = vMyPath; - + SELECT MAX(ts.productionOrder), MIN(ts.productionOrder) INTO vRestTicketsMaxOrder, vRestTicketsMinOrder FROM ticket t @@ -47438,7 +47439,7 @@ IF vIsValenciaPath THEN -- Rutas Valencia AND t.warehouseFk = vMyWarehouse AND t.id != vTicketid; - SELECT COUNT(*) + SELECT COUNT(*) INTO vRestTicketsPacking FROM ticket t LEFT JOIN ticketState ts on t.id = ts.ticket @@ -47493,9 +47494,9 @@ BEGIN LEFT JOIN vn2008.movement_label l ON l.Id_Movimiento = s.id WHERE ticketFk = vTicketFk ) sub; - + RETURN IFNULL(vSplitCounter,'--'); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -47544,21 +47545,21 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `ticketTotalVolumeBoxes`(vTicketId IN DETERMINISTIC BEGIN -/* +/* * Devuelve el volumen estimado del ticket sumado, en cajas * * vTicketId Numero de ticket - * + * */ DECLARE vVolumeBoxM3 DOUBLE; DECLARE vTicketTotalVolumeBoxes DECIMAL(10,1); DECLARE vVnBoxId VARCHAR(10) DEFAULT '94'; - + SELECT volume / 1000000 INTO vVolumeBoxM3 FROM packaging WHERE id = vVnBoxId; - + SET vTicketTotalVolumeBoxes = ticketTotalVolume(vTicketId) / vVolumeBoxM3; - + RETURN vTicketTotalVolumeBoxes; END ;; @@ -47583,7 +47584,7 @@ BEGIN DECLARE vWarehouseFk INT; SELECT warehouseFk INTO vWarehouseFk - FROM ticket + FROM ticket WHERE id = vTicketFk; RETURN vWarehouseFk; @@ -47606,18 +47607,18 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `ticket_CC_volume`(vTicketFk INT) RETURNS decimal(10,1) READS SQL DATA BEGIN - + DECLARE vCC DECIMAL(10,1); SELECT sum(sv.volume * IF(i.itemPackingTypeFk = 'H', vc.dutchCompressionRate, 1)) / (p.volume / 1000000) INTO vCC - FROM vn.saleVolume sv - JOIN vn.sale s ON s.id = sv.saleFk - JOIN vn.item i ON i.id = s.itemFk + FROM vn.saleVolume sv + JOIN vn.sale s ON s.id = sv.saleFk + JOIN vn.item i ON i.id = s.itemFk JOIN vn.packaging p ON p.id = 'CC' - JOIN vn.volumeConfig vc + JOIN vn.volumeConfig vc WHERE sv.ticketFk = vTicketFk; - + RETURN vCC; END ;; @@ -47639,44 +47640,44 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `ticket_get`(vParamFk INT) RETURNS int(11) READS SQL DATA proc:BEGIN - + /* Devuelve el número de ticket o collection consultando en varias tablas posibles - * + * * @param vParamFk Número a validar * @return vValidFk Identificador validado */ - + DECLARE vValidFk INT; -- Tabla vn.saleGroup SELECT s.ticketFk INTO vValidFk FROM vn.sale s JOIN vn.saleGroupDetail sgd ON sgd.saleFk = s.id - JOIN vn.saleGroup sg ON sg.id = sgd.saleGroupFk + JOIN vn.saleGroup sg ON sg.id = sgd.saleGroupFk WHERE sg.id = vParamFk AND sg.created > TIMESTAMPADD(WEEK,-1, util.VN_CURDATE()) LIMIT 1; - + IF vValidFk THEN - + RETURN vValidFk; - + LEAVE proc; - + END IF; -- Tabla vn.collection SELECT c.id INTO vValidFk - FROM vn.collection c + FROM vn.collection c WHERE c.id = vParamFk AND c.created > TIMESTAMPADD(WEEK,-1, util.VN_CURDATE()); - + IF vValidFk THEN - + RETURN vValidFk; - + LEAVE proc; - + END IF; -- Tabla vn.ticket @@ -47684,17 +47685,17 @@ proc:BEGIN FROM vn.ticket t WHERE t.id = vParamFk AND t.shipped > TIMESTAMPADD(WEEK,-1, util.VN_CURDATE()); - + IF vValidFk THEN - + RETURN vValidFk; - + LEAVE proc; - + END IF; RETURN NULL; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -47720,8 +47721,8 @@ BEGIN * @vTicketFk Id del ticket a calcular */ DECLARE deliveryPrice DECIMAL (10,2); - - IF (SELECT isVolumetric FROM ticket t JOIN zone z ON t.zoneFk = z.id + + IF (SELECT isVolumetric FROM ticket t JOIN zone z ON t.zoneFk = z.id WHERE t.id = vTicketFk) THEN SELECT SUM(sv.freight) INTO deliveryPrice FROM vn.saleVolume sv @@ -47732,7 +47733,7 @@ BEGIN LEFT JOIN expedition e ON e.ticketFk = t.id JOIN expeditionBoxVol ebv ON ebv.boxFk = e.freightItemFk WHERE t.id = vTicketFk; - + END IF; RETURN deliveryPrice; END ;; @@ -47756,16 +47757,16 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `ticket_getWeight`(vTicketFk INT) RET BEGIN /** * Devuelve el peso total del ticket - * + * * @return Total peso */ - + DECLARE vWeight DECIMAL(10,3); SELECT sum(weight) INTO vWeight FROM saleVolume WHERE ticketFk = vTicketFk; - + RETURN vWeight; END ;; @@ -47787,15 +47788,15 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `ticket_HasUbication`(vTicketFk INT) RETURNS tinyint(1) READS SQL DATA BEGIN - + DECLARE hasUbication BOOL; SELECT COUNT(*) INTO hasUbication FROM vn.ticket t JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk - WHERE rm.beachFk + WHERE rm.beachFk AND t.id = vTicketFk; - + RETURN hasUbication; END ;; @@ -47944,7 +47945,7 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `timeWorkerControl_getDirection`(vUse READS SQL DATA BEGIN /** - * Verifica la dirección de la fichada + * Verifica la dirección de la fichada * @param vUserFk Identificador del trabajador * @param vTimed Hora de la fichada * @return Retorna sentido de la fichada 'in, out, middle' @@ -47957,40 +47958,40 @@ BEGIN DECLARE vDayStayMax INT; DECLARE vTimedSeconds INT; DECLARE vLastTimeIn INT; - + SELECT UNIX_TIMESTAMP(vTimed) INTO vTimedSeconds; - + SELECT dayStayMax INTO vDayStayMax FROM vn.workerTimeControlParams; SELECT timed, direction INTO vNext,vNextDirection - FROM vn.workerTimeControl - WHERE userFk = vUserFk + FROM vn.workerTimeControl + WHERE userFk = vUserFk AND direction IN ('in','out') AND timed > vTimed ORDER BY timed ASC LIMIT 1; - + SELECT timed, direction INTO vPrevious, vPreviousDirection - FROM vn.workerTimeControl - WHERE userFk = vUserFk + FROM vn.workerTimeControl + WHERE userFk = vUserFk AND direction IN ('in','out') AND timed < vTimed ORDER BY timed DESC - LIMIT 1; - - IF (vTimedSeconds - UNIX_TIMESTAMP(vPrevious) + UNIX_TIMESTAMP(vNext) - vTimedSeconds)<= vDayStayMax AND vPreviousDirection = 'in' AND vNextDirection = 'out' THEN + LIMIT 1; + + IF (vTimedSeconds - UNIX_TIMESTAMP(vPrevious) + UNIX_TIMESTAMP(vNext) - vTimedSeconds)<= vDayStayMax AND vPreviousDirection = 'in' AND vNextDirection = 'out' THEN RETURN 'middle'; END IF; - - + + IF (vTimedSeconds> UNIX_TIMESTAMP(vPrevious)) THEN - IF vPreviousDirection = 'in' THEN + IF vPreviousDirection = 'in' THEN RETURN 'out'; ELSE SELECT UNIX_TIMESTAMP(MAX(timed)) INTO vLastTimeIn - FROM vn.workerTimeControl - WHERE userFk = vUserFk + FROM vn.workerTimeControl + WHERE userFk = vUserFk AND direction ='in' AND timed < vPrevious; IF vTimedSeconds - vLastTimeIn <= vDayStayMax THEN @@ -48044,11 +48045,11 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `travel_getForLogiflora`(vLanded DATE, vWarehouseFk INT) RETURNS int(11) READS SQL DATA BEGIN - + /** * Devuelve un número de travel para compras de Logiflora a partir de la fecha de llegada y del almacén. * Si no existe lo genera. - * + * * @param vLanded Fecha de llegada al almacén * @param vWarehouseFk Identificador de vn.warehouse */ @@ -48056,8 +48057,8 @@ BEGIN DECLARE vTravelFk INT; IF vLanded THEN - - SELECT IFNULL(MAX(tr.id),0) INTO vTravelFk + + SELECT IFNULL(MAX(tr.id),0) INTO vTravelFk FROM vn.travel tr JOIN vn.warehouse wIn ON wIn.id = tr.warehouseInFk JOIN vn.warehouse wOut ON wOut.id = tr.warehouseOutFk @@ -48068,14 +48069,14 @@ BEGIN AND landed = vLanded; IF NOT vTravelFk THEN - + INSERT INTO vn.travel(landed, shipped, warehouseInFk, warehouseOutFk, agencyModeFk) - SELECT vLanded, util.VN_CURDATE(), vWarehouseFk, wOut.id, am.id - FROM vn.warehouse wOut + SELECT vLanded, util.VN_CURDATE(), vWarehouseFk, wOut.id, am.id + FROM vn.warehouse wOut JOIN vn.agencyMode am ON am.name = 'LOGIFLORA' WHERE wOut.name = 'Holanda'; - - SELECT MAX(tr.id) INTO vTravelFk + + SELECT MAX(tr.id) INTO vTravelFk FROM vn.travel tr JOIN vn.warehouse wIn ON wIn.id = tr.warehouseInFk JOIN vn.warehouse wOut ON wOut.id = tr.warehouseOutFk @@ -48083,11 +48084,11 @@ BEGIN AND wOut.name = 'Holanda' AND landed = vLanded; END IF; - + END IF; - + RETURN vTravelFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -48114,21 +48115,21 @@ BEGIN DECLARE vChar INT; SET vLength = length(vString); - + WHILE vLength > 0 DO - + SET vChar = MID(vString,vLength,1); - + SET vSeed = vSeed + ASCII(vChar); - + SET vLength = vLength - 1; - + END WHILE; SET vCode = FLOOR(SQRT(vSeed)*1000000) mod 1000; RETURN vCode; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -48155,21 +48156,21 @@ BEGIN DECLARE vChar INT; SET vLength = length(vString); - + WHILE vLength > 0 DO - + SET vChar = MID(vString,vLength,1); - + SET vSeed = vSeed + ASCII(vChar); - + SET vLength = vLength - 1; - + END WHILE; SET vCode = FLOOR(SQRT(vSeed)*1000000) mod 1000; RETURN vCode; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -48230,15 +48231,15 @@ BEGIN * @param vTimeOut * @return vNigthlyHours */ - DECLARE vNigthlyHours DECIMAL(5,2); + DECLARE vNigthlyHours DECIMAL(5,2); DECLARE vSecondsPerHour INT(4) DEFAULT 3600; - + SELECT GREATEST(0, TIMESTAMPDIFF(SECOND, - IF(TIME(vTimeIn) BETWEEN endNightlyHours AND startNightlyHours, - CONCAT(DATE(vTimeIn), ' ', startNightlyHours), + IF(TIME(vTimeIn) BETWEEN endNightlyHours AND startNightlyHours, + CONCAT(DATE(vTimeIn), ' ', startNightlyHours), vTimeIn), - IF(TIME(vTimeOut) BETWEEN endNightlyHours AND startNightlyHours, - CONCAT(DATE(vTimeOut), ' ', endNightlyHours), + IF(TIME(vTimeOut) BETWEEN endNightlyHours AND startNightlyHours, + CONCAT(DATE(vTimeOut), ' ', endNightlyHours), vTimeOut))) / vSecondsPerHour INTO vNigthlyHours FROM vn.workerTimeControlConfig; @@ -48270,47 +48271,47 @@ BEGIN SELECT dayStayMax INTO vDayStayMax FROM workerTimeControlParams; - + SELECT timeWorkerControl_getDirection(vUserFk,vTimed) INTO vDirection; IF vDirection = 'out' THEN - + SELECT MAX(timed) INTO vLastIn - FROM workerTimeControl - WHERE userFk = vUserFk + FROM workerTimeControl + WHERE userFk = vUserFk AND direction = 'in' AND timed < vTimed; - + UPDATE workerTimeControl wtc SET wtc.direction = 'middle' WHERE userFk = vUserFk AND direction = 'out' AND timed BETWEEN vLastIn AND vTimed; - + ELSE IF vDirection = 'in' THEN - - SELECT COUNT(*) INTO vHasDirectionOut + + SELECT COUNT(*) INTO vHasDirectionOut FROM workerTimeControl wtc - WHERE userFk = vUserFk + WHERE userFk = vUserFk AND direction = 'out' - AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); + AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); UPDATE workerTimeControl wtc SET wtc.direction = IF (vHasDirectionOut,'middle','out') WHERE userFk = vUserFk AND direction = 'in' - AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); + AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); END IF; END IF; - + INSERT INTO workerTimeControl(userFk, timed, warehouseFk, direction, manual) VALUES(vUserFk, vTimed, vWarehouseFk, vDirection, vIsManual); - + SET vLastInsertedId = LAST_INSERT_ID(); - + CALL workerTimeControlSOWP(vUserFk, vTimed); - + RETURN vLastInsertedId; END ;; DELIMITER ; @@ -48339,47 +48340,47 @@ BEGIN SELECT dayStayMax INTO vDayStayMax FROM workerTimeControlParams; - + SELECT timeWorkerControl_getDirection(vUserFk,vTimed) INTO vDirection; IF vDirection = 'out' THEN - + SELECT MAX(timed) INTO vLastIn - FROM workerTimeControl - WHERE userFk = vUserFk + FROM workerTimeControl + WHERE userFk = vUserFk AND direction = 'in' AND timed < vTimed; - + UPDATE workerTimeControl wtc SET wtc.direction = 'middle' WHERE userFk = vUserFk AND direction = 'out' AND timed BETWEEN vLastIn AND vTimed; - + ELSE IF vDirection = 'in' THEN - - SELECT COUNT(*) INTO vHasDirectionOut + + SELECT COUNT(*) INTO vHasDirectionOut FROM workerTimeControl wtc - WHERE userFk = vUserFk + WHERE userFk = vUserFk AND direction = 'out' - AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); + AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); UPDATE workerTimeControl wtc SET wtc.direction = IF (vHasDirectionOut,'middle','out') WHERE userFk = vUserFk AND direction = 'in' - AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); + AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); END IF; END IF; - + INSERT INTO workerTimeControl(userFk, timed, warehouseFk, direction, manual) VALUES(vUserFk, vTimed, vWarehouseFk, vDirection, vIsManual); - + SET vLastInsertedId = LAST_INSERT_ID(); - + CALL workerTimeControlSOWP(vUserFk, vTimed); - + RETURN vLastInsertedId; END ;; DELIMITER ; @@ -48490,17 +48491,17 @@ BEGIN * @return Devuelve TRUE en caso de que este trabajando. Si se encuentra en un descanso devolverá FALSE */ DECLARE vLastIn DATETIME ; - + SELECT MAX(timed) INTO vLastIn - FROM vn.workerTimeControl + FROM vn.workerTimeControl WHERE userFk = vWorkerFk AND direction = 'in'; - IF (SELECT MOD(COUNT(*),2) - FROM vn.workerTimeControl - WHERE userFk = vWorkerFk AND + IF (SELECT MOD(COUNT(*),2) + FROM vn.workerTimeControl + WHERE userFk = vWorkerFk AND timed >= vLastIn - ) THEN + ) THEN RETURN TRUE; ELSE RETURN FALSE; @@ -48594,7 +48595,7 @@ BEGIN SET `type` = vType, `name` = vName, parentFk = vParentFk; - + SET vSelf = LAST_INSERT_ID(); UPDATE zoneGeoRecalc SET isChanged = TRUE; @@ -48618,7 +48619,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `addNoteFromDelivery`(idTicket INT,nota TEXT) BEGIN - + DECLARE observationTypeFk INT DEFAULT 3; /*3 = REPARTIDOR*/ INSERT INTO ticketObservation(ticketFk,observationTypeFk,description) @@ -48646,23 +48647,23 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `addressTaxArea`() READS SQL DATA BEGIN /** - * Devuelve el taxArea para un conjunto de Consignatarios y empresas, + * Devuelve el taxArea para un conjunto de Consignatarios y empresas, * * @table tmp.addressCompany(addressFk, companyFk) valores a calcular * @return tmp.addressTaxArea(addressFk,companyFk) */ - + DROP TEMPORARY TABLE IF EXISTS tmp.addressTaxArea; CREATE TEMPORARY TABLE tmp.addressTaxArea (PRIMARY KEY (addressFk, companyFk)) ENGINE = MEMORY - SELECT CASE - WHEN (NOT IFNULL(auClient.isUeeMember, cClient.isUeeMember) OR NOT cSupplier.isUeeMember) - AND NOT (auSupplier.id <=> auClient.id) THEN + SELECT CASE + WHEN (NOT IFNULL(auClient.isUeeMember, cClient.isUeeMember) OR NOT cSupplier.isUeeMember) + AND NOT (auSupplier.id <=> auClient.id) THEN 'WORLD' - WHEN cClient.isUeeMember AND cSupplier.isUeeMember AND c.countryFk != s.countryFk AND c.isVies THEN + WHEN cClient.isUeeMember AND cSupplier.isUeeMember AND c.countryFk != s.countryFk AND c.isVies THEN 'CEE' - WHEN a.isEqualizated AND cClient.code = 'ES' THEN + WHEN a.isEqualizated AND cClient.code = 'ES' THEN 'EQU' ELSE 'NATIONAL' @@ -48703,27 +48704,27 @@ BEGIN * @param vAddress id de la direccion * @param vWarehouse id del warehouse * @return vShipped la primera fecha disponible y vLanded la fecha de llegada/recojida -*/ +*/ DECLARE vAgency INT; DECLARE vShipped DATE; DECLARE vLanded DATE DEFAULT util.VN_CURDATE(); SELECT agencyFk INTO vAgency FROM agencyMode WHERE id= vAgencyMode; l: LOOP - + CALL agencyHourGetShipped(vLanded,vAddress,vAgency); - SELECT shipped INTO vShipped + SELECT shipped INTO vShipped FROM tmp.agencyHourGetShipped WHERE warehouseFk = vWarehouse LIMIT 1; - + IF vShipped THEN LEAVE l; END IF; - + SET vLanded = DATE_ADD(vLanded, INTERVAL +1 DAY); - + END LOOP; - + SELECT vShipped,vLanded; END ;; DELIMITER ; @@ -48774,7 +48775,7 @@ BEGIN LIMIT 1 ) t WHERE IF(vDated = util.VN_CURDATE(), t.maxHour > HOUR(util.VN_NOW()), TRUE) AND t.substractDay < 225; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -48797,14 +48798,14 @@ BEGIN * DEPRECATED usar zoneGetWarehouse * Devuelve el listado de agencias disponibles para la fecha, * dirección y warehouuse pasadas - * + * * @param vAddress no puede ser NULL * @param vWarehouse warehouse donde comprobaremos las agencias y fecha * @param vDate Fecha de recogida * @table agencyModeWarehouseList Listado de agencias disponibles */ DECLARE vAgency INT; - DECLARE vDone BOOL DEFAULT FALSE; + DECLARE vDone BOOL DEFAULT FALSE; DECLARE vCur CURSOR FOR SELECT DISTINCT a.id FROM agency a @@ -48828,13 +48829,13 @@ BEGIN PRIMARY KEY(id) ) ENGINE = MEMORY; - + OPEN vCur; FETCH vCur INTO vAgency; WHILE NOT vDone DO - + INSERT INTO tmp.agencyModeWarehouseList SELECT am.id, am.name, am.description,am.deliveryMethodFk, TIMESTAMPADD(DAY, -ah.substractDay, vDate), w.name FROM agencyHour ah @@ -48863,7 +48864,7 @@ BEGIN END WHILE; CLOSE vCur; - + SELECT * FROM tmp.agencyModeWarehouseList; DROP TEMPORARY TABLE tmp.agencyModeWarehouseList; END ;; @@ -48889,9 +48890,9 @@ BEGIN CALL vn.agencyHourGetShipped(vDate, vAddress, vAgency); SELECT * FROM tmp.agencyHourGetShipped; - + DROP TEMPORARY TABLE IF EXISTS tmp.agencyHourGetShipped; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -48929,7 +48930,7 @@ BEGIN DECLARE cWarehouses CURSOR FOR SELECT warehouseFk, shipped FROM tmp.zoneGetShipped; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; @@ -48938,7 +48939,7 @@ BEGIN CALL vn.zone_getShipped (vDate, vAddress, vAgencyMode, FALSE); DROP TEMPORARY TABLE IF EXISTS tmp.availableCalc; - CREATE TEMPORARY TABLE tmp.availableCalc( + CREATE TEMPORARY TABLE tmp.availableCalc( calcFk INT UNSIGNED, PRIMARY KEY (calcFk) ) @@ -48949,7 +48950,7 @@ BEGIN l: LOOP SET vDone = FALSE; FETCH cWarehouses INTO vWarehouse, vShipment; - + IF vDone THEN LEAVE l; END IF; @@ -48982,7 +48983,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `bankEntity_checkBic`(vBic VARCHAR(2 BEGIN /** * If the bic length is Incorrect throw exception - * + * * @param vBic bic code */ @@ -48990,7 +48991,7 @@ BEGIN SELECT bicLength INTO vConfigBicLenght FROM vn.bankEntityConfig bec; - + IF LENGTH(vBic) <> vConfigBicLenght THEN CALL util.throw(CONCAT('bic must be of length ', vConfigBicLenght )); END IF; @@ -49017,14 +49018,14 @@ BEGIN * Manda correo cuando caduca un seguro * de los leasing * -*/ +*/ INSERT INTO mail (receiver,replyTo,subject,body) SELECT 'administracion@verdnatura.es' receiver, 'noreply@verdnatura.es' replyTo, CONCAT('El seguro de la poliza ',b.id,' ',b.bank,' ha finalizado.') subject, CONCAT('El seguro de la poliza ',b.id,' ',b.bank,' ha finalizado.') body - FROM vn.bankPolicy bp - LEFT JOIN vn.supplier s + FROM vn.bankPolicy bp + LEFT JOIN vn.supplier s ON s.id = bp.supplierFk LEFT JOIN vn.bank b ON b.id = bp.bankFk @@ -49253,19 +49254,19 @@ BEGIN DECLARE vIsFeedStock BOOL; DECLARE vWeight DECIMAL(10,2); DECLARE vPacking INT; - - SELECT b.entryFk, - b.itemFk, - i.packingOut, - ic.merchandise, + + SELECT b.entryFk, + b.itemFk, + i.packingOut, + ic.merchandise, vc.standardFlowerBox, b.weight, - b.packing - INTO - vEntryFk, - vItemFk, - vPackingOut, - vIsMerchandise, + b.packing + INTO + vEntryFk, + vItemFk, + vPackingOut, + vIsMerchandise, vStandardFlowerBox, vWeight, vPacking @@ -49273,7 +49274,7 @@ BEGIN LEFT JOIN item i ON i.id = b.itemFk LEFT JOIN itemType it ON it.id = i.typeFk LEFT JOIN itemCategory ic ON ic.id = it.categoryFk - LEFT JOIN packaging p ON p.id = b.packageFk AND NOT p.isBox + LEFT JOIN packaging p ON p.id = b.packageFk AND NOT p.isBox JOIN volumeConfig vc ON TRUE WHERE b.id = vSelf; @@ -49290,7 +49291,7 @@ BEGIN warehouseFk = vWarehouse, cm3 = buy_getUnitVolume(vSelf), cm3Delivery = IFNULL((vStandardFlowerBox * 1000) / vPackingOut, buy_getUnitVolume(vSelf)); - + IF vWeight AND vPacking THEN UPDATE itemCost SET grams = vWeight * 1000 / vPacking @@ -49311,7 +49312,7 @@ BEGIN WHERE b.id = vSelf; END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -49358,10 +49359,10 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_getSplit`(vSelf INT, vDated DATE) BEGIN /** - * Devuelve tantos registros como etiquetas se necesitan para cada uno de los cubos o cajas de - * las ventas correspondientes a la compra que se pasa como parámetro, en los almacenes que tienen + * Devuelve tantos registros como etiquetas se necesitan para cada uno de los cubos o cajas de + * las ventas correspondientes a la compra que se pasa como parámetro, en los almacenes que tienen * habilitada la venta de productos con stock virtual, aunque los productos pueden ser de cualquier tipo. - * + * * @param vSelf Identificador de vn.buy * @param vDated Fecha de preparación de las ventas que queremos etiquetar */ @@ -49436,7 +49437,7 @@ BEGIN WHILE vLabels >= vCounter DO INSERT INTO tmp.split SET - id = vSaleFk, + id = vSaleFk, labels = vLabels, counter = vCounter; @@ -49458,11 +49459,11 @@ BEGIN -- Devuelve los splits creados SELECT CONCAT(sp.counter,'/',sp.labels) labels, COALESCE(sfc.nickname, sfa.nickname, a.nickname) destination, - s.itemFk, - i.longName, - i.`size`, - vn.ticketSplitCounter(t.id) counter, - IF(sfa.id OR sfc.id, + s.itemFk, + i.longName, + i.`size`, + vn.ticketSplitCounter(t.id) counter, + IF(sfa.id OR sfc.id, a.nickname, CONCAT(a.id, ' ', p.`name`,' (', c.`code`,')')) destination2 FROM tmp.split sp @@ -49507,12 +49508,12 @@ BEGIN item_getVolume(b.itemFk, b.packageFk)) / vc.trolleyM3 / 1000000 ,1) AS DECIMAL(10,2)) carros , CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) * item_getVolume(b.itemFk, b.packageFk)) / vc.palletM3 / 1000000,1) AS DECIMAL(10,2)) espais - FROM buy b + FROM buy b JOIN tmp.buy tb ON tb.buyFk = b.id JOIN volumeConfig vc JOIN item i ON i.id = b.itemFk JOIN itemType it ON it.id = i.typeFk - LEFT JOIN temperature t ON t.code = it.temperatureFk + LEFT JOIN temperature t ON t.code = it.temperatureFk GROUP BY Temp; END ;; DELIMITER ; @@ -49532,21 +49533,21 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_getVolumeByAgency`(vDated DATE, vAgencyFk INT) BEGIN - + DROP TEMPORARY TABLE IF EXISTS tmp.buy; CREATE TEMPORARY TABLE tmp.buy (buyFk INT NOT NULL, PRIMARY KEY (buyFk)) ENGINE = MEMORY; - INSERT INTO tmp.buy + INSERT INTO tmp.buy SELECT b.id - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk WHERE t.landed = vDated AND t.agencyModeFk IN (0, vAgencyFk); CALL buy_getVolume(); DROP TEMPORARY TABLE tmp.buy; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -49565,19 +49566,19 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_getVolumeByEntry`(vEntryFk INT) BEGIN - + DROP TEMPORARY TABLE IF EXISTS tmp.buy; CREATE TEMPORARY TABLE tmp.buy (buyFk INT NOT NULL, PRIMARY KEY (buyFk)) ENGINE = MEMORY; - - INSERT INTO tmp.buy + + INSERT INTO tmp.buy SELECT b.id - FROM buy b - JOIN entry e ON e.id = b.entryFk + FROM buy b + JOIN entry e ON e.id = b.entryFk WHERE e.id = vEntryFk; CALL buy_getVolume(); DROP TEMPORARY TABLE tmp.buy; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -49665,12 +49666,12 @@ BEGIN * inserta en tmp.buyRecalc las compras de un awb * * @param awbFk - */ + */ DROP TEMPORARY TABLE IF EXISTS tmp.buyRecalc; CREATE TEMPORARY TABLE tmp.buyRecalc SELECT b.id - FROM buy b + FROM buy b JOIN entry e ON e.id = b.entryFk JOIN duaEntry de ON de.entryFk = e.id JOIN dua d ON d.id = de.duaFk @@ -49702,7 +49703,7 @@ BEGIN * Recalcula los precios de una compra * * @param vBuyFk - */ + */ DROP TEMPORARY TABLE IF EXISTS tmp.buyRecalc; CREATE TEMPORARY TABLE tmp.buyRecalc @@ -49733,12 +49734,12 @@ BEGIN * Recalcula los precios de una entrada * * @param vEntryFk - */ + */ DROP TEMPORARY TABLE IF EXISTS tmp.buyRecalc; CREATE TEMPORARY TABLE tmp.buyRecalc SELECT b.id - FROM buy b + FROM buy b WHERE b.entryFk = vEntryFk; CALL buy_recalcPrices(); @@ -49778,12 +49779,12 @@ BEGIN LIMIT 0; INSERT INTO tBuy(buyFk) - SELECT b.id + SELECT b.id FROM buy b JOIN tmp.ekt t ON t.ektFk = b.ektFk JOIN vn.entry en ON en.id = b.entryFk JOIN vn.travel tr ON tr.id = en.travelFk - JOIN vn.warehouse w ON w.id = tr.warehouseInFk + JOIN vn.warehouse w ON w.id = tr.warehouseInFk JOIN vn.country c ON c.id = w.countryFk AND c.code = 'NL'; SELECT b.id buy, i.doPhoto do_photo, b.stickers - CAST(b.printedStickers AS INT) stickersToPrint @@ -49849,7 +49850,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_updatePacking`(vWarehouseFk INT, vItemFk INT, vPacking INT) BEGIN /** - * Actualiza packing + * Actualiza packing * * @param vWarehouseFk warehouse del item * @param vItemFk id del item @@ -49859,8 +49860,8 @@ BEGIN UPDATE buy b JOIN tmp.buyUltimate bu ON b.id = bu.buyFk - SET b.packing = vPacking - WHERE bu.warehouseFk = vWarehouseFk + SET b.packing = vPacking + WHERE bu.warehouseFk = vWarehouseFk AND bu.itemFk = vItemFk; DROP TEMPORARY TABLE tmp.buyUltimate; @@ -49899,7 +49900,7 @@ BEGIN */ DROP TEMPORARY TABLE IF EXISTS tmp.item; CREATE TEMPORARY TABLE tmp.item - ENGINE = MEMORY + ENGINE = MEMORY SELECT vItemFk itemFk; CALL catalog_calculate(vLanded, vAddressFk, vAgencyModeFk); @@ -49921,7 +49922,7 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `catalog_calculate`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT) -BEGIN +BEGIN /** * Calcula los articulos disponibles y sus precios * @@ -49929,7 +49930,7 @@ BEGIN * @param vLanded Fecha de recepcion de mercancia * @param vAddressFk Id del consignatario * @param vAgencyModeFk Id de la agencia - * @return tmp.ticketCalculateItem(itemFk, available, producer, + * @return tmp.ticketCalculateItem(itemFk, available, producer, * item, size, stems, category, inkFk, image, origin, price) * @return tmp.ticketLot(warehouseFk, itemFk, available, buyFk) * @return tmp.ticketComponent @@ -49964,22 +49965,22 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.ticketCalculateItem; CREATE TEMPORARY TABLE tmp.ticketCalculateItem( - itemFk INT(11) NOT NULL, + itemFk INT(11) NOT NULL, available INT(11), - producer VARCHAR(50), - item VARCHAR(50), - size INT(10) UNSIGNED, - stems INT(11), - category VARCHAR(3), - inkFk VARCHAR(3), + producer VARCHAR(50), + item VARCHAR(50), + size INT(10) UNSIGNED, + stems INT(11), + category VARCHAR(3), + inkFk VARCHAR(3), image VARCHAR(50), - origin VARCHAR(3), + origin VARCHAR(3), price DECIMAL(10,2), priceKg DECIMAL(10,2), `grouping` INT(10) UNSIGNED, PRIMARY KEY `itemFk` (`itemFk`) ) ENGINE = MEMORY DEFAULT CHARSET=utf8; - + OPEN cTravelTree; l: LOOP @@ -50001,20 +50002,20 @@ BEGIN bu.buyFk, vZoneFk FROM `cache`.available a - LEFT JOIN cache.availableNoRaids anr ON anr.item_id = a.item_id + LEFT JOIN cache.availableNoRaids anr ON anr.item_id = a.item_id AND anr.calc_id = vAvailableNoRaidsCalc JOIN tmp.item i ON i.itemFk = a.item_id JOIN vn.item it ON it.id = i.itemFk JOIN vn.`zone` z ON z.id = vZoneFk - LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = a.item_id - LEFT JOIN edi.supplyResponse sr ON sr.ID = it.supplyResponseFk - LEFT JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID + LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = a.item_id + LEFT JOIN edi.supplyResponse sr ON sr.ID = it.supplyResponseFk + LEFT JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID LEFT JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID LEFT JOIN (SELECT isVNHSupplier, isEarlyBird, TRUE AS itemAllowed FROM vn.addressFilter af - JOIN (SELECT ad.provinceFk, p.countryFk, ad.isLogifloraAllowed - FROM vn.address ad - JOIN vn.province p ON p.id = ad.provinceFk + JOIN (SELECT ad.provinceFk, p.countryFk, ad.isLogifloraAllowed + FROM vn.address ad + JOIN vn.province p ON p.id = ad.provinceFk WHERE ad.id = vAddressFk ) sub2 ON sub2.provinceFk <=> IFNULL(af.provinceFk, sub2.provinceFk) AND sub2.countryFk <=> IFNULL(af.countryFk, sub2.countryFk) @@ -50031,13 +50032,13 @@ BEGIN JOIN vn.itemType itt ON itt.id = it.typeFk JOIN vn.itemCategory itc on itc.id = itt.categoryFk JOIN vn.address ad ON ad.id = vAddressFk - LEFT JOIN vn.clientItemType cit + LEFT JOIN vn.clientItemType cit ON cit.clientFk = ad.clientFk AND cit.itemTypeFk = itt.id - LEFT JOIN vn.zoneItemType zit + LEFT JOIN vn.zoneItemType zit ON zit.zoneFk = vZoneFk AND zit.itemTypeFk = itt.id - LEFT JOIN vn.agencyModeItemType ait + LEFT JOIN vn.agencyModeItemType ait ON ait.agencyModeFk = vAgencyModeFk AND ait.itemTypeFk = itt.id WHERE a.calc_id = vAvailableCalc @@ -50130,7 +50131,7 @@ BEGIN * Calcula los componentes de los articulos de tmp.ticketLot * * @param vZoneFk para calcular el transporte - * @param vAddressFk Consignatario + * @param vAddressFk Consignatario * @param vShipped dia de salida del pedido * @param vWarehouseFk warehouse de salida del pedido * @table tmp.ticketLot (warehouseFk, available, itemFk, buyFk, zoneFk) @@ -50144,7 +50145,7 @@ BEGIN SELECT clientFk INTO vClientFK FROM address WHERE id = vAddressFk; - + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentCalculate (PRIMARY KEY (itemFk, warehouseFk)) ENGINE = MEMORY @@ -50156,7 +50157,7 @@ BEGIN IFNULL(pf.packing, GREATEST(b.grouping, b.packing)) packing, IFNULL(pf.`grouping`, b.`grouping`) `grouping`, ABS(IFNULL(pf.box, b.groupingMode)) groupingMode, - tl.buyFk, + tl.buyFk, i.typeFk, IF(i.hasKgPrice, b.weight / b.packing, NULL) weightGrouping FROM tmp.ticketLot tl @@ -50164,7 +50165,7 @@ BEGIN JOIN item i ON i.id = tl.itemFk JOIN itemType it ON it.id = i.typeFk JOIN itemCategory ic ON ic.id = it.categoryFk - LEFT JOIN specialPrice sp ON sp.itemFk = i.id + LEFT JOIN specialPrice sp ON sp.itemFk = i.id AND sp.clientFk = vClientFk LEFT JOIN ( SELECT * FROM ( @@ -50183,7 +50184,7 @@ BEGIN LIMIT 10000000000000000000 ) tpf GROUP BY tpf.itemFk, tpf.warehouseFk - ) pf ON pf.itemFk = tl.itemFk + ) pf ON pf.itemFk = tl.itemFk AND pf.warehouseFk = tl.warehouseFk WHERE b.buyingValue + b.freightValue + b.packageValue + b.comissionValue > 0.01 AND ic.merchandise @@ -50215,10 +50216,10 @@ BEGIN FROM tmp.ticketComponent tc JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tc.itemFk AND tcc.warehouseFk = tc.warehouseFk GROUP BY tc.itemFk, warehouseFk; - + -- RECOBRO INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost) - SELECT tcb.warehouseFk, tcb.itemFk, c2.id, + SELECT tcb.warehouseFk, tcb.itemFk, c2.id, ROUND(tcb.base * LEAST( MAX(GREATEST(IFNULL(cr.priceIncreasing,0), @@ -50249,29 +50250,29 @@ BEGIN ROUND(base * (0.01 + wm.pricesModifierRate), 3) manaAuto FROM tmp.ticketComponentBase tcb JOIN `client` c on c.id = vClientFk - JOIN workerMana wm ON c.salesPersonFk = wm.workerFk + JOIN workerMana wm ON c.salesPersonFk = wm.workerFk JOIN vn.component c2 ON c2.code = 'autoMana' WHERE wm.isPricesModifierActivated HAVING manaAuto <> 0; - + -- Precios especiales INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost) SELECT tcb.warehouseFk, tcb.itemFk, c2.id, GREATEST( - IFNULL(ROUND(tcb.base * c2.tax, 4), 0), + IFNULL(ROUND(tcb.base * c2.tax, 4), 0), IF(i.hasMinPrice, i.minPrice,0) - tcc.rate3 ) cost FROM tmp.ticketComponentBase tcb JOIN vn.component c2 ON c2.code = 'lastUnitsDiscount' - JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tcb.itemFk AND tcc.warehouseFk = tcb.warehouseFk + JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tcb.itemFk AND tcc.warehouseFk = tcb.warehouseFk LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk JOIN vn.item i ON i.id = tcb.itemFk WHERE sp.value IS NULL AND i.supplyResponseFk IS NULL; - -- Individual + -- Individual INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost) SELECT tcb.warehouseFk, tcb.itemFk, @@ -50282,10 +50283,10 @@ BEGIN JOIN vn.client c ON c.id = vClientFk JOIN vn.businessType bt ON bt.code = c.businessTypeFk WHERE bt.code = 'individual'; - + -- Venta por paquetes INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost) - SELECT tcc.warehouseFk, tcc.itemFk, c2.id, tcc.rate2 - tcc.rate3 + SELECT tcc.warehouseFk, tcc.itemFk, c2.id, tcc.rate2 - tcc.rate3 FROM tmp.ticketComponentCalculate tcc JOIN vn.component c2 ON c2.code = 'salePerPackage' JOIN buy b ON b.id = tcc.buyFk @@ -50297,7 +50298,7 @@ BEGIN SELECT vZoneFk id; CALL zone_getOptionsForShipment(vShipped, TRUE); - + -- Reparto INSERT INTO tmp.ticketComponent SELECT tcc.warehouseFK, @@ -50311,7 +50312,7 @@ BEGIN JOIN agencyMode am ON am.id = z.agencyModeFk JOIN vn.volumeConfig vc JOIN vn.component c2 ON c2.code = 'delivery' - LEFT JOIN itemCost ic ON ic.warehouseFk = tcc.warehouseFk + LEFT JOIN itemCost ic ON ic.warehouseFk = tcc.warehouseFk AND ic.itemFk = tcc.itemFk HAVING cost <> 0; @@ -50364,9 +50365,9 @@ BEGIN CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) price, CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) / weightGrouping priceKg FROM tmp.ticketComponentCalculate tcc - JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk + JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk AND tcs.warehouseFk = tcc.warehouseFk - WHERE IFNULL(tcs.classRate, 1) = 1 + WHERE IFNULL(tcs.classRate, 1) = 1 AND tcc.groupingMode < 2 AND (tcc.packing > tcc.`grouping` or tcc.groupingMode = 0) GROUP BY tcs.warehouseFk, tcs.itemFk; @@ -50403,7 +50404,7 @@ BEGIN SELECT * FROM tmp.ticketComponentRate ORDER BY price LIMIT 10000000000000000000 ) t GROUP BY itemFk, warehouseFk, `grouping`; - + DROP TEMPORARY TABLE tmp.ticketComponentCalculate, tmp.ticketComponentSum, @@ -50428,7 +50429,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `catalog_componentPrepare`() BEGIN - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent; CREATE TEMPORARY TABLE tmp.ticketComponent ( `warehouseFk` INT UNSIGNED NOT NULL, @@ -50438,9 +50439,9 @@ BEGIN INDEX `itemWarehouse` USING BTREE (`itemFk` ASC, `warehouseFk` ASC), UNIQUE `fkItemWarehouseComponent` (`itemFk` ASC, `warehouseFk` ASC, `componentFk` ASC) )ENGINE=MEMORY DEFAULT CHARSET=utf8; - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentPrice; - CREATE TEMPORARY TABLE tmp.ticketComponentPrice ( + CREATE TEMPORARY TABLE tmp.ticketComponentPrice ( `warehouseFk` INT UNSIGNED NOT NULL, `itemFk` INT NOT NULL, `rate` INT NOT NULL, @@ -50449,7 +50450,7 @@ BEGIN `priceKg` DECIMAL(10,4), INDEX `itemWarehouse` USING BTREE (`itemFk` ASC, `warehouseFk` ASC), UNIQUE `fkItemWarehouseRate` (`itemFk` ASC, `warehouseFk` ASC, `rate` ASC) - )ENGINE=MEMORY DEFAULT CHARSET=utf8; + )ENGINE=MEMORY DEFAULT CHARSET=utf8; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -50468,7 +50469,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `catalog_componentPurge`() BEGIN - DROP TEMPORARY TABLE + DROP TEMPORARY TABLE tmp.ticketComponentPrice, tmp.ticketComponent, tmp.ticketLot; @@ -50523,7 +50524,7 @@ BEGIN DELETE FROM sms WHERE created < v18Month; DELETE FROM saleTracking WHERE created < vOneYearAgo; DELETE FROM ticketTracking WHERE created < v18Month; - DELETE tobs FROM ticketObservation tobs + DELETE tobs FROM ticketObservation tobs JOIN ticket t ON tobs.ticketFk = t.id WHERE t.shipped < TIMESTAMPADD(YEAR,-2,util.VN_CURDATE()); DELETE sc.* FROM saleCloned sc JOIN sale s ON s.id = sc.saleClonedFk JOIN ticket t ON t.id = s.ticketFk WHERE t.shipped < vOneYearAgo; DELETE FROM sharingCart where ended < vDateShort; @@ -50597,12 +50598,12 @@ BEGIN FROM vn.travel t LEFT JOIN vn.entry e ON e.travelFk = t.id WHERE t.shipped < TIMESTAMPADD(MONTH, -3, util.VN_CURDATE()) AND e.travelFk IS NULL; - + UPDATE dms d - JOIN dmsType dt ON dt.id = d.dmsTypeFk - SET d.dmsTypeFk = vTrashId + JOIN dmsType dt ON dt.id = d.dmsTypeFk + SET d.dmsTypeFk = vTrashId WHERE created < TIMESTAMPADD(MONTH, -dt.monthToDelete, util.VN_CURDATE()); - + -- borrar entradas sin compras DROP TEMPORARY TABLE IF EXISTS tmp.entryToDelete; CREATE TEMPORARY TABLE tmp.entryToDelete @@ -50621,7 +50622,7 @@ BEGIN CREATE TEMPORARY TABLE tmp.routeToDelete SELECT * FROM vn.route r - WHERE created < TIMESTAMPADD(YEAR,-4,util.VN_CURDATE()); + WHERE created < TIMESTAMPADD(YEAR,-4,util.VN_CURDATE()); UPDATE tmp.routeToDelete tmp JOIN vn.dms d ON d.id = tmp.gestdocFk @@ -50804,21 +50805,21 @@ BEGIN */ DECLARE vClientDebt DOUBLE; - + SELECT vn.client_getDebt(vClientFk, util.VN_CURDATE()) INTO vClientDebt; - + INSERT INTO vn.greuge(clientFk, description, amount, shipped, greugeTypeFk) VALUES (vClientFk, 'Saldo pendiente', vClientDebt, util.VN_CURDATE(), 5); - + CALL vn.clientGreugeSpray(vClientFk, TRUE, '', TRUE); - + INSERT INTO vn.greuge(clientFk, description, amount, shipped, greugeTypeFk) SELECT vClientFk, 'Liquidación cliente', sum(amount), util.VN_CURDATE(), 5 FROM vn.greuge WHERE clientFk = vClientFk; - - UPDATE vn.client - SET salesPersonFk = NULL + + UPDATE vn.client + SET salesPersonFk = NULL WHERE id = vClientFk; END ;; @@ -50908,33 +50909,33 @@ BEGIN DECLARE vIssued DATETIME; DECLARE vBalance DOUBLE DEFAULT 0.00; DECLARE cur CURSOR FOR - SELECT - created, - issued, + SELECT + created, + issued, ROUND(amount, 2) AS balance FROM invoiceOut - WHERE clientFk = vClientFk AND companyFk = vCompanyFk - UNION ALL - SELECT - created, - payed, + WHERE clientFk = vClientFk AND companyFk = vCompanyFk + UNION ALL + SELECT + created, + payed, ROUND(-1 * amountPaid, 2) AS balance - FROM receipt + FROM receipt WHERE clientFk = vClientFk AND companyFk = vCompanyFk ORDER BY issued, created; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + OPEN cur; - + proc: LOOP SET vDone = FALSE; - + FETCH cur INTO vCreated, vIssued, vBalance; IF vDate IS NULL THEN SET vDate=vIssued; END IF; - + IF vDone THEN LEAVE proc; END IF; @@ -50946,66 +50947,66 @@ BEGIN SET vDone = TRUE; END IF; END LOOP; - + CLOSE cur; - - SELECT - issued, - CAST(debtOut AS DECIMAL(10,2)) debtOut, + + SELECT + issued, + CAST(debtOut AS DECIMAL(10,2)) debtOut, CAST(debtIn AS DECIMAL(10,2)) debtIn, - ref, - companyFk, + ref, + companyFk, priority FROM - (SELECT - NULL AS issued, - SUM(amountUnpaid) AS debtOut, - NULL AS debtIn, - 'Saldo Anterior' AS ref, + (SELECT + NULL AS issued, + SUM(amountUnpaid) AS debtOut, + NULL AS debtIn, + 'Saldo Anterior' AS ref, companyFk, - 0 as priority - FROM - (SELECT SUM(amount) AS amountUnpaid, companyFk, 0 + 0 as priority + FROM + (SELECT SUM(amount) AS amountUnpaid, companyFk, 0 FROM invoiceOut - WHERE clientFk = vClientFK - AND issued < vDate - GROUP BY companyFk - - UNION ALL - - SELECT SUM(-1 * amountPaid), companyFk, 0 - FROM receipt - WHERE clientFk = vClientFK - AND payed < vDate - GROUP BY companyFk) AS transactions - GROUP BY companyFk - - UNION ALL - - SELECT - issued, - amount as debtOut, - NULL AS debtIn, + WHERE clientFk = vClientFK + AND issued < vDate + GROUP BY companyFk + + UNION ALL + + SELECT SUM(-1 * amountPaid), companyFk, 0 + FROM receipt + WHERE clientFk = vClientFK + AND payed < vDate + GROUP BY companyFk) AS transactions + GROUP BY companyFk + + UNION ALL + + SELECT + issued, + amount as debtOut, + NULL AS debtIn, ref, companyFk, - 1 - FROM invoiceOut - WHERE clientFk = vClientFK + 1 + FROM invoiceOut + WHERE clientFk = vClientFK AND issued >= vDate - UNION ALL - - SELECT - r.payed, - NULL as debtOut, - r.amountPaid, - r.invoiceFk, + UNION ALL + + SELECT + r.payed, + NULL as debtOut, + r.amountPaid, + r.invoiceFk, r.companyFk, - 0 + 0 FROM receipt r - WHERE r.clientFk = vClientFK - AND r.payed >= vDate) t - INNER JOIN `client` c ON c.id = vClientFK - HAVING debtOut <> 0 OR debtIn <> 0 + WHERE r.clientFk = vClientFK + AND r.payed >= vDate) t + INNER JOIN `client` c ON c.id = vClientFK + HAVING debtOut <> 0 OR debtIn <> 0 ORDER BY issued, priority DESC, debtIn; END ;; DELIMITER ; @@ -51063,13 +51064,13 @@ BEGIN WHERE id = vClientFk; ELSE - + SELECT id INTO vOwner FROM vn.worker WHERE code = vWorkerCode COLLATE utf8_general_ci; END IF; - + DROP TEMPORARY TABLE IF EXISTS tmp.clientList; CREATE TEMPORARY TABLE tmp.clientList SELECT DISTINCT t.clientFk, floor(cr.yearSale / 12) monthSale @@ -51081,7 +51082,7 @@ BEGIN AND t.shipped >= TIMESTAMPADD(MONTH,-1,util.VN_CURDATE()) AND c.id != vClientFk HAVING monthSale > 100; - + SELECT SUM(monthSale) INTO vTotalSale FROM tmp.clientList; @@ -51092,7 +51093,7 @@ BEGIN SELECT vClientFk, 'Reparto greuge', -vGreuge, util.VN_CURDATE(), vGreugeTypeFk; END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -51287,11 +51288,11 @@ BEGIN LEFT JOIN clientProtected cp ON cp.clientFk = cd.id JOIN client c ON c.id = cd.id JOIN province p ON p.id = c.provinceFk - LEFT JOIN autonomy a ON a.id = p.autonomyFk + LEFT JOIN autonomy a ON a.id = p.autonomyFk JOIN country co ON co.id = p.countryFk WHERE cd.Aviso = 'TERCER AVISO' AND cp.clientFk IS NULL - AND co.code NOT IN ('PT') + AND co.code NOT IN ('PT') AND a.name <> 'Canarias' AND c.salesPersonFk IS NOT NULL; @@ -51402,7 +51403,7 @@ BEGIN JOIN client c ON c.accountingAccount = lc.account WHERE lc.`date` BETWEEN vDateFrom AND vDateTo )sub - GROUP BY companyFk, clientFk + GROUP BY companyFk, clientFk ) sub1 ON sub1.clientFk = c.id JOIN supplier s ON s.id = sub1.companyFk JOIN company co ON co.id = sub1.companyFk @@ -51546,13 +51547,13 @@ BEGIN SET vEnded = TIMESTAMP(IFNULL(vDate, util.VN_CURDATE()), '23:59:59'); DROP TEMPORARY TABLE IF EXISTS tClientRisk; - CREATE TEMPORARY TABLE tClientRisk + CREATE TEMPORARY TABLE tClientRisk ENGINE = MEMORY SELECT cr.clientFk, SUM(cr.amount) amount FROM clientRisk cr JOIN tmp.clientGetDebt c ON c.clientFk = cr.clientFk GROUP BY cr.clientFk; - + INSERT INTO tClientRisk SELECT c.clientFk, SUM(r.amountPaid) FROM receipt r @@ -51567,7 +51568,7 @@ BEGIN WHERE t.receiptFk IS NULL AND t.status = 'ok' GROUP BY t.clientFk; - + INSERT INTO tClientRisk SELECT t.clientFk, totalWithVat FROM ticket t @@ -51583,7 +51584,7 @@ BEGIN FROM client c JOIN tClientRisk cr ON cr.clientFk = c.id GROUP BY c.id; - + DROP TEMPORARY TABLE tClientRisk; END ;; DELIMITER ; @@ -51607,9 +51608,9 @@ BEGIN DECLARE i INT DEFAULT 0; DECLARE c INT DEFAULT 0; DECLARE maxClientFk INT; - + DROP TEMPORARY TABLE IF EXISTS tmp.client; - + CREATE TEMPORARY TABLE tmp.`client` (id INT AUTO_INCREMENT, clientFk INT, @@ -51617,40 +51618,40 @@ BEGIN PRIMARY KEY(id), UNIQUE KEY clientFk (clientFk)) ENGINE = MEMORY; - + INSERT INTO tmp.client(clientFk) SELECT DISTINCT clientFk FROM vn.invoiceOut WHERE issued > TIMESTAMPADD(MONTH, -2, util.VN_CURDATE()); - + SELECT max(id) INTO maxClientFk FROM tmp.client; - - + + WHILE i < vNumber DO - + SET i = i + 1; - + WHILE c = 0 DO - + SELECT id INTO c FROM tmp.client WHERE id = floor(RAND() * maxClientFk) + 1 AND isSelected = FALSE LIMIT 1; - + END WHILE; - + -- SELECT i, maxClientFk, c; - - UPDATE tmp.client - SET isSelected = TRUE + + UPDATE tmp.client + SET isSelected = TRUE WHERE id = c; - + SET c = 0; - + END WHILE; - + SELECT c.id, c.name FROM tmp.client tc JOIN vn.client c ON c.id = tc.clientFk WHERE isSelected @@ -51791,35 +51792,35 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `cmr_getByTicket`(vTicketFk INT) BEGIN DECLARE vLanded DATE; - + SELECT DATE_ADD(util.VN_CURDATE(), INTERVAL landingDays DAY) INTO vLanded FROM vn.cmrConfig; IF vTicketFk THEN - + IF (SELECT count(ticketFk) FROM vn.cmr WHERE ticketFk = vTicketFk) THEN - + SELECT id FROM vn.cmr WHERE ticketFk = vTicketFk; - + ELSE - + INSERT INTO vn.cmr(ticketFk, companyFk, addressFromFk, addressToFk, ead) SELECT vTicketFk, t.companyFk, a.id, t.addressFk, vLanded FROM vn.ticket t - JOIN vn.warehouse w ON w.id = t.warehouseFk - JOIN vn.address a ON a.id = w.addressFk + JOIN vn.warehouse w ON w.id = t.warehouseFk + JOIN vn.address a ON a.id = w.addressFk WHERE t.id = vTicketFk; - + SELECT LAST_INSERT_ID(); - + END IF; - + ELSE - + INSERT INTO vn.cmr(ead) VALUES(vLanded); - + SELECT LAST_INSERT_ID(); - + END IF; END ;; DELIMITER ; @@ -51842,7 +51843,7 @@ BEGIN /** * Insert the monthly CMR summary in vn.mail on the 5th of each month. */ - + SET SESSION group_concat_max_len = 1000000; -- IF (DAY(util.VN_CURDATE()) = 5) THEN INSERT INTO @@ -51870,7 +51871,7 @@ BEGIN CMR Ticket ' - , GROUP_CONCAT(' ', c.id, ' ', c.ticketFk, ' ' ORDER BY c.id SEPARATOR '' ), + , GROUP_CONCAT(' ', c.id, ' ', c.ticketFk, ' ' ORDER BY c.id SEPARATOR '' ), '

@@ -51888,7 +51889,7 @@ BEGIN -- Actualizamos el estado a 'Enviado' UPDATE vn.cmr c SET c.state = 'Sent' - WHERE c.state = 'Pending' + WHERE c.state = 'Pending' AND MONTH(c.created) = MONTH(util.VN_CURDATE() - INTERVAL 1 MONTH) AND YEAR(c.created) = YEAR(util.VN_CURDATE() - INTERVAL 1 MONTH); -- END IF; @@ -52101,15 +52102,15 @@ BEGIN DATE_FORMAT(util.VN_NOW(), '%H:%i' ), ' ', i.name - ) INTO vConcept + ) INTO vConcept FROM item i WHERE i.id = vItemFk; SELECT name INTO vItemName FROM item WHERE id = vBarccodeFk; - SELECT CONCAT('Añadido articulo ', + SELECT CONCAT('Añadido articulo ', vItemName, - ' cantidad:', + ' cantidad:', vQuantity ) INTO vDescription; @@ -52146,7 +52147,7 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_assign`(vUserFk INT, OUT vCollectionFk INT) -proc:BEGIN +proc:BEGIN /* Comprueba si existen colecciones libres que se ajustan al perfil del usuario * y le asigna la más antigua. * Añade un registro al semillero de colecciones @@ -52179,14 +52180,14 @@ proc:BEGIN FROM vn.collection c JOIN vn.ticketCollection tc ON tc.collectionFk = c.id JOIN vn.state s ON s.code = 'PRINTED_AUTO' - JOIN vn.productionConfig pc - WHERE c.workerFk IS NULL + JOIN vn.productionConfig pc + WHERE c.workerFk IS NULL AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; DELETE c.* FROM vn.collection c - JOIN vn.productionConfig pc - WHERE c.workerFk IS NULL + JOIN vn.productionConfig pc + WHERE c.workerFk IS NULL AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; -- Se a�ade registro al semillero @@ -52196,8 +52197,8 @@ proc:BEGIN -- Comprueba si hay colecciones disponibles que se ajustan a su configuracion SELECT MIN(c.id) INTO vCollectionFk - FROM vn.collection c - JOIN vn.operator o + FROM vn.collection c + JOIN vn.operator o ON (o.itemPackingTypeFk = c.itemPackingTypeFk OR c.itemPackingTypeFk IS NULL) AND o.numberOfWagons = c.wagons AND o.trainFk = c.trainFk @@ -52244,18 +52245,18 @@ BEGIN SELECT c.id collectionFk, date(c.created) created, COUNT(DISTINCT tc.ticketFk) ticketTotalCount - FROM collection c - JOIN ticketCollection tc ON tc.collectionFk = c.id - JOIN sale s ON s.ticketFk = tc.ticketFk + FROM collection c + JOIN ticketCollection tc ON tc.collectionFk = c.id + JOIN sale s ON s.ticketFk = tc.ticketFk JOIN ticketState ts ON ts.ticketFk = tc.ticketFk JOIN state s2 ON s2.id = ts.stateFk JOIN productionConfig pc JOIN vn.state ss on ss.code = 'PREPARED' LEFT JOIN vn.saleTracking st on st.saleFk = s.id AND st.stateFk = ss.id - WHERE c.workerFk = vWorkerFk + WHERE c.workerFk = vWorkerFk AND TIMESTAMPDIFF(HOUR, c.created , util.VN_NOW()) < pc.pendingCollectionsAge AND s.quantity != 0 - AND s2.order < pc.pendingCollectionsOrder + AND s2.order < pc.pendingCollectionsOrder GROUP BY c.id HAVING COUNT(*) > COUNT(DISTINCT st.id); @@ -52282,15 +52283,15 @@ BEGIN * Selecciona los tickets de una colección/ticket * @param vParamFk ticketFk/collectionFk * @return Retorna ticketFk, level, agencyName, warehouseFk, salesPersonFk, observaciones - */ + */ DECLARE vItemPackingTypeFk VARCHAR(1); -- Si los sacadores son los de pruebas, pinta los colores SELECT itemPackingTypeFk INTO vItemPackingTypeFk - FROM vn.collection + FROM vn.collection WHERE id = vParamFk; - SELECT t.id ticketFk, + SELECT t.id ticketFk, IF (!(vItemPackingTypeFk <=> 'V'), cc.code,CONCAT(SUBSTRING('ABCDEFGH',tc.wagon, 1),'-',tc.`level` )) `level`, am.name agencyName, t.warehouseFk, @@ -52300,20 +52301,20 @@ BEGIN FROM vn.ticket t LEFT JOIN vn.ticketCollection tc ON t.id = tc.ticketFk LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk -- PAK 23/12/21 - LEFT JOIN vn.collectionColors cc - ON cc.wagon = tc.wagon - AND cc.shelve = tc.`level` + LEFT JOIN vn.collectionColors cc + ON cc.wagon = tc.wagon + AND cc.shelve = tc.`level` AND cc.trainFk = c2.trainFk -- PAK 23/12/21 - LEFT JOIN vn.zone z ON z.id = t.zoneFk + LEFT JOIN vn.zone z ON z.id = t.zoneFk LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk LEFT JOIN vn.client c ON c.id = t.clientFk LEFT JOIN vn.worker w ON w.id = c.salesPersonFk - LEFT JOIN vn.ticketObservation tob ON tob.ticketFk = t.id + LEFT JOIN vn.ticketObservation tob ON tob.ticketFk = t.id AND tob.observationTypeFk = 1 - WHERE t.id = vParamFk + WHERE t.id = vParamFk AND t.shipped >= util.yesterday() UNION ALL - SELECT t.id ticketFk, + SELECT t.id ticketFk, IF(!(vItemPackingTypeFk <=> 'V'), cc.code, CONCAT(SUBSTRING('ABCDEFGH', tc.wagon, 1), '-', tc.`level`)) `level`, am.name agencyName, t.warehouseFk, @@ -52323,15 +52324,15 @@ BEGIN FROM vn.ticket t JOIN vn.ticketCollection tc ON t.id = tc.ticketFk LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk -- PAK 23/12/21 - LEFT JOIN vn.collectionColors cc - ON cc.wagon = tc.wagon - AND cc.shelve = tc.`level` + LEFT JOIN vn.collectionColors cc + ON cc.wagon = tc.wagon + AND cc.shelve = tc.`level` AND cc.trainFk = c2.trainFk -- PAK 23/12/21 - LEFT JOIN vn.zone z ON z.id = t.zoneFk + LEFT JOIN vn.zone z ON z.id = t.zoneFk LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk LEFT JOIN vn.client c ON c.id = t.clientFk LEFT JOIN vn.worker w ON w.id = c.salesPersonFk - LEFT JOIN vn.ticketObservation tob ON tob.ticketFk = t.id + LEFT JOIN vn.ticketObservation tob ON tob.ticketFk = t.id AND tob.observationTypeFk = 1 WHERE tc.collectionFk = vParamFk; @@ -52694,8 +52695,8 @@ proc:BEGIN -- Se anulan el resto de carros libres para que sólo uno lleve un pedido excesivo DELETE tt.* FROM tTrain tt - LEFT JOIN (SELECT DISTINCT wagon - FROM tTrain + LEFT JOIN (SELECT DISTINCT wagon + FROM tTrain WHERE ticketFk IS NOT NULL ) nn ON nn.wagon = tt.wagon WHERE nn.wagon IS NULL; @@ -52863,7 +52864,7 @@ BEGIN DECLARE vDone INT DEFAULT FALSE; DECLARE vCursor CURSOR FOR SELECT DISTINCT ticketFk - FROM ticketCollection tc + FROM ticketCollection tc WHERE tc.collectionFk = vSelf; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; @@ -52910,25 +52911,25 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `company_getFiscaldata`(workerFk INT) BEGIN - + DECLARE vCompanyFk INT; - - SELECT IFNULL(uc.companyFk, rc.defaultCompanyFk) + + SELECT IFNULL(uc.companyFk, rc.defaultCompanyFk) INTO vCompanyFk FROM vn.routeConfig rc LEFT JOIN userConfig uc ON uc.userFk = workerFk; - - + + SELECT s.name AS name , s.NIF AS nif , s.street AS street , s.city AS city , - s.postCode AS postCode - - FROM vn.company c + s.postCode AS postCode + + FROM vn.company c JOIN vn.worker w ON w.id = c.workerManagerFk - JOIN vn.supplier s ON s.id = c.id + JOIN vn.supplier s ON s.id = c.id WHERE c.id = vCompanyFk; END ;; DELIMITER ; @@ -52985,7 +52986,7 @@ BEGIN IF (p.currencyFk = vCurrencyEuroFk, p.amount, p.divisa) AS amount, p.dueDated < vStartingDate isBeforeStarting, p.currencyFk - FROM payment p + FROM payment p WHERE p.received > vStartDate AND p.companyFk = vSelf UNION ALL @@ -52993,9 +52994,9 @@ BEGIN r.companyFk, - IF (r.currencyFk = vCurrencyEuroFk, rv.amount, rv.foreignValue) AS Total, rv.dueDated < vStartingDate isBeforeStarting, - r.currencyFk - FROM invoiceIn r - INNER JOIN invoiceInDueDay rv ON r.id = rv.invoiceInFk + r.currencyFk + FROM invoiceIn r + INNER JOIN invoiceInDueDay rv ON r.id = rv.invoiceInFk WHERE r.issued > vStartDate AND r.isBooked AND r.companyFk = vSelf @@ -53047,11 +53048,11 @@ BEGIN -IF (r.currencyFk = vCurrencyEuroFk, rv.amount, rv.foreignValue), r.currencyFk, FALSE isPayment, - TRUE - FROM invoiceIn r + TRUE + FROM invoiceIn r LEFT JOIN tOpeningBalances si ON r.companyFk = si.companyFk AND r.supplierFk = si.supplierFk - AND r.currencyFk = si.currencyFk + AND r.currencyFk = si.currencyFk JOIN invoiceInDueDay rv ON r.id = rv.invoiceInFk WHERE rv.dueDated >= vStartingDate AND (si.closingBalances IS NULL OR si.closingBalances <> 0) @@ -53106,7 +53107,7 @@ BEGIN FROM tPendingDuedates WHERE balance < vInvalidBalances AND balance > - vInvalidBalances; - + DELETE vp.* FROM tPendingDuedates vp JOIN tRowsToDelete rd ON ( @@ -53134,9 +53135,9 @@ BEGIN FROM tPendingDuedates vp LEFT JOIN supplier s ON s.id = vp.supplierFk LEFT JOIN client c ON c.fi = s.nif - LEFT JOIN clientRisk cr ON cr.clientFk = c.id + LEFT JOIN clientRisk cr ON cr.clientFk = c.id AND cr.companyFk = vp.companyFk; - + DROP TEMPORARY TABLE tOpeningBalances; DROP TEMPORARY TABLE tPendingDuedates; DROP TEMPORARY TABLE tRowsToDelete; @@ -53159,7 +53160,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `conveyorExpedition_Add`(vStarted DATETIME, vEnded DATETIME) BEGIN - + DECLARE startingMinute INT; TRUNCATE vn.conveyorExpedition; @@ -53176,23 +53177,23 @@ BEGIN conveyorBuildingClassFk) SELECT e.id, e.created, - 10 * p.depth as depth, + 10 * p.depth as depth, 10 * p.width as width, 10 * p.height as height, IFNULL(t.routeFk,am.agencyFk) routeFk, hour(e.created) * 60 + minute(e.created), IFNULL(et.description , a.name), IFNULL(t.routeFk,am.agencyFk) criterion, - IFNULL(p.conveyorBuildingClassFk , pc.defaultConveyorBuildingClass) + IFNULL(p.conveyorBuildingClassFk , pc.defaultConveyorBuildingClass) FROM vn.expedition e JOIN vn.ticket t ON t.id = e.ticketFk JOIN vn.packaging p ON p.id = e.packagingFk LEFT JOIN vn.zone z ON z.id = t.zoneFk LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk - LEFT JOIN vn.agency a ON a.id = am.agencyFk - LEFT JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk - LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk - JOIN vn.packagingConfig pc + LEFT JOIN vn.agency a ON a.id = am.agencyFk + LEFT JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk + LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk + JOIN vn.packagingConfig pc WHERE t.warehouseFk IN (60,1,44) AND e.created BETWEEN vStarted AND vEnded AND p.height < 140 @@ -53201,8 +53202,8 @@ BEGIN SELECT MIN(productionMinute) INTO startingMinute FROM vn.conveyorExpedition ce ; - - UPDATE vn.conveyorExpedition + + UPDATE vn.conveyorExpedition SET productionMinute = productionMinute - startingMinute; END ;; @@ -53271,7 +53272,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `createPedidoInterno`(vItemFk INT,vQuantity INT) BEGIN - + UPDATE vn.item SET upToDown = vQuantity WHERE id = vItemFk; END ;; @@ -53294,52 +53295,52 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `crypt`(vText VARCHAR(255), vKey VAR BEGIN DECLARE vEncryptedText VARCHAR(255) DEFAULT ''; - + DECLARE vKeyLength INT; DECLARE vKeyPosition INT DEFAULT 1; DECLARE vKeyChar VARCHAR(1); - + DECLARE vTextLength INT; DECLARE vTextPosition INT DEFAULT 1; DECLARE vTextChar VARCHAR(1); - + DECLARE vEncryptedChar VARCHAR(1); DECLARE vEncryptedCharPosition INT; - + DECLARE vChain VARCHAR(255) DEFAULT '#$.-_0123456789abcdefghijklmnopqrstuvwxyz'; DECLARE vChainTextPosition INT; DECLARE vChainKeyPosition INT; DECLARE vChainLength INT; - + DECLARE vInvalidadChars VARCHAR(255) DEFAULT ''; - - SET vTextLength = LENGTH(vText); + + SET vTextLength = LENGTH(vText); SET vKeyLength = LENGTH(vKey); SET vChainLength = LENGTH(vChain); - + WHILE vTextPosition <= vTextLength DO - + SET vTextChar = MID(vText,vTextPosition,1); SET vKeyChar = MID(vKey,vKeyPosition,1); - + SET vChainTextPosition = LOCATE(vTextChar, vChain); SET vInvalidadChars = IF(vChainTextPosition, vInvalidadChars, CONCAT(vInvalidadChars,vTextChar)); SET vChainKeyPosition = LOCATE(vKeyChar, vChain); SET vEncryptedCharPosition = vChainTextPosition + vChainKeyPosition; - + IF vEncryptedCharPosition > vChainLength THEN - + SET vEncryptedCharPosition = vEncryptedCharPosition - vChainLength; - + END IF; - + SET vEncryptedChar = MID(vChain, vEncryptedCharPosition,1); - + SET vEncryptedText = CONCAT(vEncryptedText, vEncryptedChar); - + SET vKeyPosition = IF(vKeyPosition = vKeyLength, 1,vKeyPosition + 1); SET vTextPosition = vTextPosition + 1; - + END WHILE; SET vResult = IF(LENGTH(vInvalidadChars), CONCAT('Caracteres no válidos: ',vInvalidadChars),vEncryptedText); @@ -53364,49 +53365,49 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `cryptOff`(vText VARCHAR(255), vKey BEGIN DECLARE vUncryptedText VARCHAR(255) DEFAULT ''; - + DECLARE vKeyLength INT; DECLARE vKeyPosition INT DEFAULT 1; DECLARE vKeyChar VARCHAR(1); - + DECLARE vTextLength INT; DECLARE vTextPosition INT DEFAULT 1; DECLARE vTextChar VARCHAR(1); - + DECLARE vUncryptedChar VARCHAR(1); DECLARE vUncryptedCharPosition INT; - + DECLARE vChain VARCHAR(255) DEFAULT '#$.-_0123456789abcdefghijklmnopqrstuvwxyz'; DECLARE vChainTextPosition INT; DECLARE vChainKeyPosition INT; DECLARE vChainLength INT; - - SET vTextLength = LENGTH(vText); + + SET vTextLength = LENGTH(vText); SET vKeyLength = LENGTH(vKey); SET vChainLength = LENGTH(vChain); - + WHILE vTextPosition <= vTextLength DO - + SET vTextChar = MID(vText,vTextPosition,1); SET vKeyChar = MID(vKey,vKeyPosition,1); - + SET vChainTextPosition = LOCATE(vTextChar, vChain); SET vChainKeyPosition = LOCATE(vKeyChar, vChain); SET vUncryptedCharPosition = vChainTextPosition - vChainKeyPosition; - + IF vUncryptedCharPosition < 1 THEN - + SET vUncryptedCharPosition = vUncryptedCharPosition + vChainLength; - + END IF; - + SET vUncryptedChar = MID(vChain, vUncryptedCharPosition,1); - + SET vUncryptedText = CONCAT(vUncryptedText, vUncryptedChar); - + SET vKeyPosition = IF(vKeyPosition = vKeyLength, 1,vKeyPosition + 1); SET vTextPosition = vTextPosition + 1; - + END WHILE; SET vResult = vUncryptedText; @@ -53502,7 +53503,7 @@ BEGIN OR (vSelf IS NOT NULL AND parentFk = vSelf); DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + SET vSons = 0; OPEN vChildren; @@ -53513,11 +53514,11 @@ BEGIN IF vDone THEN LEAVE myLoop; END IF; - + SET vIndex = vIndex + 1; SET vLft = vIndex; SET vSons = vSons + 1; - + CALL department_calcTreeRec( vChildFk, CONCAT(vPath, vChildFk, '/'), @@ -53572,7 +53573,7 @@ proc: BEGIN SELECT isChanged INTO vIsChanged FROM department_recalc; - + IF vIsChanged THEN UPDATE department_recalc SET isChanged = FALSE; CALL vn.department_calcTree; @@ -53597,17 +53598,17 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `department_getHasMistake`() BEGIN - + /** * Obtiene los sectores a los cuales les ponemos errores * */ - + SELECT id, name FROM department WHERE hasToMistake <> FALSE; - - + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -53666,19 +53667,19 @@ BEGIN FROM department g JOIN tChilds c ON c.id = g.id WHERE g.parentFk IS NOT NULL; - + INSERT IGNORE INTO tNodes SELECT id FROM tParents; - + IF ROW_COUNT() = 0 THEN LEAVE myLoop; END IF; - + DELETE FROM tChilds; INSERT INTO tChilds SELECT id FROM tParents; END LOOP; - + DROP TEMPORARY TABLE tChilds, tParents; @@ -53745,12 +53746,12 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `deviceProductionUser_exists`(vUserFk INT) BEGIN - + /* SELECT COUNT(*) AS UserExists - FROM vn.deviceProductionUser dpu + FROM vn.deviceProductionUser dpu WHERE dpu.userFk = vUserFk;*/ SELECT TRUE; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -53822,10 +53823,10 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `device_checkLogin`(vUserFk INT, vAndroidID VARCHAR(50)) BEGIN - + /* * Comprueba si está registrado el dispositivo mediante su androidId - * + * * @param vUSerFk el id del user * @param vAndroidID es el identificador android_id del dispositivo */ @@ -53837,20 +53838,20 @@ BEGIN SELECT dpc.isAllUsersallowed INTO vIsAllUsersAllowed FROM vn.deviceProductionConfig dpc; - IF NOT vIsAllUsersAllowed THEN - + IF NOT vIsAllUsersAllowed THEN + SELECT COUNT(*) INTO vIsDepartment - FROM vn.workerDepartment dp + FROM vn.workerDepartment dp JOIN department d ON d.id = dp.departmentFk WHERE dp.workerFk = vUserFk AND d.hasToCheckLogin; - + IF vIsDepartment THEN SELECT COUNT(*) INTO vIsAuthorized - FROM vn.deviceProductionUser dpu + FROM vn.deviceProductionUser dpu JOIN vn.deviceProduction dp ON dp.id = dpu.deviceProductionFk WHERE dpu.userFk = vUserFk AND dp.android_id = vAndroidID; - + IF NOT vIsAuthorized THEN SET vMessage = 'Usuario no autorizado'; END IF; @@ -53880,15 +53881,15 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `duaEntryValueUpdate`(vDuaFk INT) BEGIN UPDATE duaEntry de - JOIN + JOIN ( SELECT b.entryFk, sum(b.quantity * b.buyingValue) as total FROM buy b JOIN duaEntry de ON de.entryFk = b.entryFk WHERE duaFk = vDuaFk GROUP BY b.entryFk ) sub ON sub.entryFk = de.entryFk - - LEFT JOIN + + LEFT JOIN (SELECT e.id, sum(iit.taxableBase) as euros FROM entry e JOIN invoiceInTax iit ON iit.invoiceInFk = e.invoiceInFk @@ -53896,11 +53897,11 @@ BEGIN WHERE de.duaFk = vDuaFk GROUP BY e.id ) sub2 ON sub2.id = de.entryFk - + SET de.value = sub.total, de.euroValue = sub2.euros WHERE duaFk = vDuaFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -53924,7 +53925,7 @@ BEGIN DECLARE vInvoiceFk INT; DECLARE vASIEN BIGINT DEFAULT 0; DECLARE vCounter INT DEFAULT 0; - + DECLARE rs CURSOR FOR SELECT e.invoiceInFk FROM entry e @@ -53937,7 +53938,7 @@ BEGIN DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; OPEN rs; - + UPDATE invoiceIn ii JOIN entry e ON e.invoiceInFk = ii.id JOIN duaEntry de ON de.entryFk = e.id @@ -53949,41 +53950,41 @@ BEGIN ii.bookEntried = IFNULL(ii.bookEntried,d.bookEntried), e.isConfirmed = TRUE WHERE d.id = vDuaFk; - + SELECT IFNULL(ASIEN,0) INTO vASIEN FROM dua WHERE id = vDuaFk; - + FETCH rs INTO vInvoiceFk; - + WHILE NOT done DO CALL invoiceIn_booking(vInvoiceFk); - + IF vCounter > 0 OR vASIEN > 0 THEN - + UPDATE vn2008.XDiario x JOIN vn.ledgerConfig lc ON lc.lastBookEntry = x.ASIEN SET x.ASIEN = vASIEN; - + ELSE - + SELECT lastBookEntry INTO vASIEN FROM vn.ledgerConfig; - + END IF; - + SET vCounter = vCounter + 1; - + FETCH rs INTO vInvoiceFk; END WHILE; - + CLOSE rs; - - UPDATE dua + + UPDATE dua SET ASIEN = vASIEN WHERE id = vDuaFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -54009,9 +54010,9 @@ BEGIN SELECT awbFk,companyFk FROM dua WHERE id = vDuaFk; - + SELECT LAST_INSERT_ID() INTO vNewDuaFk; - + INSERT INTO duaEntry(duaFk, entryFk, value, customsValue) SELECT vNewDuaFk, entryFk, value, value - customsValue FROM duaEntry @@ -54040,11 +54041,11 @@ BEGIN DECLARE vBookDated DATE; DECLARE vDiff DECIMAL(10,2); DECLARE vApunte BIGINT; - + SELECT ASIEN, IFNULL(bookEntried, util.VN_CURDATE()) INTO vBookNumber, vBookDated - FROM dua + FROM dua WHERE id = vDuaFk; - + IF vBookNumber IS NULL OR NOT vBookNumber THEN CALL ledger_next(vBookNumber); END IF; @@ -54055,14 +54056,14 @@ BEGIN ASIEN, FECHA, SUBCTA, - CONCEPTO, + CONCEPTO, EUROHABER, SERIE, empresa_id, CLAVE, FACTURA) - SELECT + SELECT vBookNumber, d.bookEntried, '4700000999', @@ -54075,20 +54076,20 @@ BEGIN FROM duaTax dt JOIN dua d ON d.id = dt.duaFk WHERE dt.duaFk = vDuaFk; - + -- Apuntes por tipo de IVA y proveedor - + INSERT INTO XDiario( ASIEN, FECHA, SUBCTA, - CONTRA, + CONTRA, EURODEBE, BASEEURO, - CONCEPTO, - FACTURA, + CONCEPTO, + FACTURA, IVA, - AUXILIAR, + AUXILIAR, SERIE, FECHA_EX, FECHA_OP, @@ -54108,17 +54109,17 @@ BEGIN FECREGCON ) - SELECT + SELECT vBookNumber ASIEN, vBookDated FECHA, tr.account SUBCTA, '4330002067' CONTRA, sum(dt.tax) EURODEBE, - sum(dt.base) BASEEURO, + sum(dt.base) BASEEURO, CONCAT('DUA nº',d.code) CONCEPTO, d.id FACTURA, dt.rate IVA, - '*' AUXILIAR, + '*' AUXILIAR, 'D' SERIE, d.issued FECHA_EX, d.operated FECHA_OP, @@ -54145,10 +54146,10 @@ BEGIN WHERE ta.effectived <= vBookDated AND taxAreaFk = 'WORLD' ORDER BY ta.effectived DESC - LIMIT 10000000000000000000 + LIMIT 10000000000000000000 ) tba GROUP BY rate - ) tr ON tr.rate = dt.rate + ) tr ON tr.rate = dt.rate JOIN supplier s ON s.id = d.companyFk JOIN country c ON c.id = s.countryFk WHERE d.id = vDuaFk @@ -54157,16 +54158,16 @@ BEGIN SELECT SUM(EURODEBE) -SUM(EUROHABER), MAX(id) INTO vDiff, vApunte FROM XDiario WHERE ASIEN = vBookNumber; - + UPDATE XDiario SET BASEEURO = 100 * (EURODEBE - vDiff) / IVA, - EURODEBE = EURODEBE - vDiff + EURODEBE = EURODEBE - vDiff WHERE id = vApunte; UPDATE dua SET ASIEN = vBookNumber WHERE id = vDuaFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -54187,21 +54188,21 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `duaTax_doRecalc`(vDuaFk INT) BEGIN /** * Borra los valores de duaTax y los vuelve a crear en base a la tabla duaEntry - * + * * @param vDuaFk Id del dua a recalcular **/ DELETE FROM duaTax WHERE duaFk = vDuaFk; - - INSERT INTO duaTax(duaFk, supplierFk, taxClassFk, base) + + INSERT INTO duaTax(duaFk, supplierFk, taxClassFk, base) SELECT vDuaFk, supplierFk, taxClassFk, sum(sub.Base) as Base FROM intrastat ist JOIN (SELECT - e.supplierFk, + e.supplierFk, i.intrastatFk, CAST(sum(b.quantity * b.buyingValue * de.customsValue / de.value) * di.amount/ tei.Base AS DECIMAL(10,2)) as Base - FROM buy b + FROM buy b JOIN item i ON i.id = b.itemFk JOIN entry e ON e.id = b.entryFk JOIN duaEntry de ON de.entryFk = e.id @@ -54209,15 +54210,15 @@ BEGIN ( SELECT i.intrastatFk, CAST(sum(b.quantity * b.buyingValue * de.customsValue / de.value) AS DECIMAL(10,2)) as Base - FROM buy b + FROM buy b JOIN item i ON i.id = b.itemFk JOIN entry e ON e.id = b.entryFk JOIN duaEntry de ON de.entryFk = e.id WHERE de.duaFk = vDuaFk GROUP BY i.intrastatFk - + ) tei ON tei.intrastatFk = i.intrastatFk - JOIN + JOIN ( SELECT intrastatFk, sum(amount) as amount FROM duaIntrastat @@ -54226,7 +54227,7 @@ BEGIN ) di ON di.intrastatFk = i.intrastatFk WHERE de.duaFk = vDuaFk GROUP BY e.supplierFk, i.intrastatFk - HAVING Base + HAVING Base ) sub ON ist.id = sub.intrastatFk GROUP BY ist.taxClassFk, sub.supplierFk; END ;; @@ -54247,13 +54248,13 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ediTables_Update`() BEGIN - - INSERT IGNORE INTO vn.genus(name) + + INSERT IGNORE INTO vn.genus(name) SELECT latin_genus_name FROM edi.genus ; - INSERT IGNORE INTO vn.specie(name) - SELECT LCASE(latin_species_name) + INSERT IGNORE INTO vn.specie(name) + SELECT LCASE(latin_species_name) FROM edi.specie ; END ;; DELIMITER ; @@ -54293,71 +54294,71 @@ DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; OPEN cur1; read_loop: LOOP - + SET done = FALSE; SET vEntryFk = 0; - + FETCH cur1 INTO vId; - + IF done THEN LEAVE read_loop; END IF; - + SELECT IFNULL(e.id,0) INTO vEntryFk FROM vn.entry e JOIN vn.travel tr ON tr.id = e.travelFk - JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk + JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk AND ea.warehouseInFk = tr.warehouseInFk AND ea.agencyModeFk = tr.agencyModeFk AND ea.supplierFk = e.supplierFk WHERE ea.id = vId AND tr.landed = vLanded LIMIT 1; - + IF NOT vEntryFk THEN - + SELECT IFNULL(e.id,0) INTO vEntryFk FROM vn.entry e JOIN vn.travel tr ON tr.id = e.travelFk - JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk + JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk AND ea.warehouseInFk = tr.warehouseInFk AND ea.agencyModeFk = tr.agencyModeFk WHERE ea.id = vId AND tr.landed = vLanded AND ea.supplierFk IS NULL LIMIT 1; - + END IF; - + IF NOT vEntryFk THEN - + SET vTravelFk = 0; - - SELECT IFNULL(MAX(tr.id),0) INTO vTravelFk + + SELECT IFNULL(MAX(tr.id),0) INTO vTravelFk FROM vn.travel tr - JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk + JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk AND ea.warehouseInFk = tr.warehouseInFk AND ea.agencyModeFk = tr.agencyModeFk WHERE ea.id = vId AND tr.landed = vLanded; - + IF NOT vTravelFk THEN - + INSERT INTO vn.travel(landed, shipped, warehouseInFk, warehouseOutFk, agencyModeFk) SELECT vLanded, vLanded, warehouseInFk, warehouseOutFk, agencyModeFk - FROM vn.ektEntryAssign + FROM vn.ektEntryAssign WHERE id = vId; - - SELECT MAX(tr.id) INTO vTravelFk + + SELECT MAX(tr.id) INTO vTravelFk FROM vn.travel tr - JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk + JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk AND ea.warehouseInFk = tr.warehouseInFk AND ea.agencyModeFk = tr.agencyFk WHERE ea.id = vId AND tr.landed = vLanded; - + END IF; - + INSERT INTO vn.entry(travelFk, supplierFk, companyFk, currencyFk) SELECT vTravelFk, IFNULL(ea.supplierFk,s.id), c.id, cu.id FROM vn.supplier s @@ -54365,13 +54366,13 @@ OPEN cur1; JOIN vn.currency cu ON cu.code = 'EUR' JOIN vn.ektEntryAssign ea ON ea.id = vId WHERE s.name = 'KONINKLIJE COOPERATIEVE BLOEMENVEILING FLORAHOLLAN'; - - SELECT MAX(id) INTO vEntryFk + + SELECT MAX(id) INTO vEntryFk FROM vn.entry WHERE travelFk = vTravelFk; - + END IF; - + UPDATE vn.ektEntryAssign SET entryFk = vEntryFk WHERE id = vId; @@ -54379,7 +54380,7 @@ OPEN cur1; END LOOP; CLOSE cur1; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -54399,18 +54400,18 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `energyMeter_record`(vInput INT, vActiveTime INT) BEGIN DECLARE vConsumption INT; - + SELECT consumption INTO vConsumption FROM energyInput WHERE input = vInput; - INSERT INTO vn.energyMeter - SET - `input` = vInput, - `period` = DATE_FORMAT(util.VN_NOW(), '%Y-%m-%d %H:00:00'), + INSERT INTO vn.energyMeter + SET + `input` = vInput, + `period` = DATE_FORMAT(util.VN_NOW(), '%Y-%m-%d %H:00:00'), `activeTime` = vActiveTime, `consumption` = CAST(IFNULL((vConsumption / 3600) * vActiveTime, 0) AS DECIMAL(10,2)) - ON DUPLICATE KEY UPDATE + ON DUPLICATE KEY UPDATE `activeTime` = `activeTime` + vActiveTime, `consumption` = `consumption` + CAST(VALUES(`consumption`) AS DECIMAL(10,2)); END ;; @@ -54433,28 +54434,28 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `entryDelivered`(vDated DATE, vEntry BEGIN DECLARE vTravelFk INT; - + SELECT travelFk INTO vTravelFk - FROM vn.entry + FROM vn.entry WHERE id = vEntryFk; - + IF (SELECT COUNT(*) FROM vn.entry WHERE travelFk = vTravelFk) = 1 THEN - + UPDATE vn.travel SET shipped = LEAST(shipped, vDated), landed = vDated WHERE id = vTravelFk; - + ELSE - + INSERT INTO vn.travel(shipped, landed, warehouseInFk, warehouseOutFk, agencyModeFk, ref, isDelivered, isReceived) SELECT LEAST(shipped, vDated), vDated, warehouseInFk, warehouseOutFk, agencyModeFk, CONCAT(account.myUser_getName(),' ', vEntryFk), TRUE, TRUE FROM vn.travel WHERE id = vTravelFk; - + SELECT LAST_INSERT_ID() INTO vTravelFk; - - UPDATE vn.entry - SET travelFk = vTravelFk + + UPDATE vn.entry + SET travelFk = vTravelFk WHERE id = vEntryFk; - + END IF; END ;; @@ -54480,29 +54481,29 @@ BEGIN DECLARE vEntry INT; DECLARE vBucket VARCHAR(10); DECLARE vSupplierFk INT; - + SET vSupplierFk = IF (vLandingWarehouse = 1, 850, 963); -- seleccionamos travel SELECT t.id, e.id INTO vTravel, vEntry FROM travel t LEFT JOIN entry e ON t.id = e.travelFk - WHERE t.landed = vInOutDate AND t.shipped = vInOutDate AND t.warehouseOutFk = vShipmentWarehouse + WHERE t.landed = vInOutDate AND t.shipped = vInOutDate AND t.warehouseOutFk = vShipmentWarehouse AND t.warehouseInFk = vLandingWarehouse AND t.agencyModeFk IS NULL AND e.supplierFk = vSupplierFk - LIMIT 1; - + LIMIT 1; + -- creamos el travel si es necesario IF IFNULL(vTravel, FALSE) = FALSE THEN INSERT INTO travel (shipped, landed, warehouseInFk, warehouseOutFk) VALUES (vInOutDate, vInOutDate, vLandingWarehouse, vShipmentWarehouse); SELECT LAST_INSERT_ID() INTO vTravel; END IF; - + -- creamos la Entrada si es necesario IF IFNULL(vEntry, FALSE) = FALSE THEN INSERT INTO entry (supplierFk, travelFk) VALUES (vSupplierFk, vTravel); -- proveedor 'CONFECCION ARTIFICIAL' SELECT LAST_INSERT_ID() INTO vEntry; END IF; - + -- creamos el cubo si es necesario SELECT id INTO vBucket FROM packaging WHERE volume = vVolume LIMIT 1; IF vBucket IS NULL THEN @@ -54512,7 +54513,7 @@ BEGIN SELECT id INTO vBucket FROM packaging WHERE volume = vVolume LIMIT 1; END IF; - INSERT INTO buy(itemFk,quantity, entryFk, packageFk, packing, stickers, buyingValue, price2, price3) + INSERT INTO buy(itemFk,quantity, entryFk, packageFk, packing, stickers, buyingValue, price2, price3) SELECT itemFk, quantity, vEntry, @@ -54544,7 +54545,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_checkPackaging`(vEntryFk INT) BEGIN /** * Comprueba que los campos package y packaging no sean nulos - * + * * @param vEntryFk Id de entrada */ DECLARE vpackageOrPackingNull INT; @@ -54846,7 +54847,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_getRate`(vSelf INT) BEGIN /** - * Prepara una tabla con las tarifas aplicables en funcion de la fecha + * Prepara una tabla con las tarifas aplicables en funcion de la fecha * y el almacén * * @param vSelf Id de la tabla entry @@ -54856,7 +54857,7 @@ BEGIN DECLARE vWarehouseFk INT; SELECT t.landed, t.warehouseInFk INTO vDated, vWarehouseFk - FROM entry e + FROM entry e JOIN travel t ON t.id = e.travelFk WHERE e.id = vSelf; @@ -54986,7 +54987,7 @@ BEGIN FROM buy b WHERE b.entryFk = vSelf AND b.printedStickers != b.stickers; - + IF vChangeEntry THEN UPDATE buy SET stickers = printedStickers, @@ -54998,7 +54999,7 @@ BEGIN FROM item i WHERE i.description = 'MISFIT' LIMIT 1; - + INSERT INTO buy(entryFk, itemFk, quantity, @@ -55065,7 +55066,7 @@ BEGIN UPDATE entry SET gestDocFk = (SELECT gestDocFk FROM entry WHERE id = vSelf LIMIT 1) WHERE id = vNewEntryFk; - + INSERT INTO duaEntry (duaFk, entryFk) SELECT duaFk, vNewEntryFk FROM duaEntry WHERE entryFk = vSelf LIMIT 1; END ;; @@ -55139,12 +55140,12 @@ BEGIN */ DECLARE v_done BOOL DEFAULT FALSE; DECLARE vEntryFk INTEGER; - + DECLARE vCur CURSOR FOR SELECT id FROM tmp.recalcEntryCommision; DECLARE CONTINUE HANDLER FOR NOT FOUND - SET v_done = TRUE; + SET v_done = TRUE; OPEN vCur; @@ -55155,7 +55156,7 @@ BEGIN IF v_done THEN LEAVE l; END IF; - + CALL vn2008.buy_tarifas_entry(vEntryFk); END LOOP; @@ -55180,7 +55181,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_splitByShelving`(vShelvingFk BEGIN /** * Divide las compras entre dos entradas de acuerdo con lo ubicado en una matr�cula - * + * * @param vShelvingFk Identificador de vn.shelving * @param vFromEntryFk Entrada origen * @param vToEntryFk Entrada destino @@ -55190,49 +55191,49 @@ BEGIN DECLARE vBuyStickers INT; DECLARE vDone BOOLEAN DEFAULT FALSE; - DECLARE cur CURSOR FOR + DECLARE cur CURSOR FOR SELECT bb.id buyFk, FLOOR(ish.visible / ish.packing) ishStickers, bb.stickers buyStickers FROM vn.itemShelving ish - JOIN (SELECT b.id, b.itemFk, b.stickers - FROM vn.buy b + JOIN (SELECT b.id, b.itemFk, b.stickers + FROM vn.buy b WHERE b.entryFk = vFromEntryFk ORDER BY b.stickers DESC - LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk + LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk AND bb.stickers >= FLOOR(ish.visible / ish.packing) WHERE shelvingFk = vShelvingFk COLLATE utf8_general_ci GROUP BY ish.id; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - -- Cantidades de la matrícula que exceden la de las entradas - SELECT ish.itemFk, - i.longName, + + -- Cantidades de la matrícula que exceden la de las entradas + SELECT ish.itemFk, + i.longName, FLOOR(ish.visible / ish.packing) AS etiEnMatricula, bb.stickers etiEnEntrada FROM vn.itemShelving ish - JOIN vn.item i ON i.id = ish.itemFk - LEFT JOIN (SELECT b.id, b.itemFk, b.stickers - FROM vn.buy b + JOIN vn.item i ON i.id = ish.itemFk + LEFT JOIN (SELECT b.id, b.itemFk, b.stickers + FROM vn.buy b WHERE b.entryFk = vFromEntryFk ORDER BY b.stickers DESC LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk WHERE shelvingFk = vShelvingFk COLLATE utf8_general_ci AND IFNULL(bb.stickers,0) < FLOOR(ish.visible / ish.packing) GROUP BY ish.id; - + OPEN cur; read_loop: LOOP SET vDone = FALSE; - + FETCH cur INTO vBuyFk, vIshStickers, vBuyStickers; - + IF vDone THEN LEAVE read_loop; END IF; - + IF vIshStickers = vBuyStickers THEN UPDATE vn.buy SET entryFk = vToEntryFk @@ -55240,9 +55241,9 @@ BEGIN ELSE UPDATE vn.buy SET stickers = stickers - vIshStickers, - quantity = stickers * packing + quantity = stickers * packing WHERE id = vBuyFk; - + INSERT INTO vn.buy(entryFk, itemFk, quantity, @@ -55322,16 +55323,16 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_splitMisfit`(vSelf INT) BEGIN - + /* Divide una entrada, pasando los registros que ha insertado vn.entry_fixMisfit de la entrada original * a la nueva */ - + DECLARE vNewEntryFk INT; DECLARE vBuyFk INT; SELECT MAX(b.id) INTO vBuyFk - FROM vn.buy b + FROM vn.buy b JOIN vn.item i ON i.id = b.itemFk WHERE b.entryFk = vSelf AND i.description = 'MISFIT'; @@ -55340,17 +55341,17 @@ BEGIN SELECT supplierFk, dated, travelFk, currencyFk, companyFk FROM vn.entry e WHERE e.id = vSelf; - - SET vNewEntryFk = LAST_INSERT_ID(); - UPDATE vn.buy b + SET vNewEntryFk = LAST_INSERT_ID(); + + UPDATE vn.buy b SET b.entryFk = vNewEntryFk WHERE b.entryFk = vSelf AND b.id > vBuyFk; - + SELECT vNewEntryFk; - - + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -55373,7 +55374,7 @@ BEGIN * Unlock the indicated entry * @vSelf params entry id */ - UPDATE `entry` + UPDATE `entry` SET lockerUserFk = NULL, locked = NULL WHERE id = vSelf; @@ -55404,21 +55405,21 @@ BEGIN DECLARE vComission INT; CREATE OR REPLACE TEMPORARY TABLE tmp.recalcEntryCommision - SELECT e.id + SELECT e.id FROM vn.entry e JOIN vn.travel t ON t.id = e.travelFk - JOIN vn.warehouse w ON w.id = t.warehouseInFk + JOIN vn.warehouse w ON w.id = t.warehouseInFk WHERE t.shipped >= util.VN_CURDATE() AND e.currencyFk = vCurrency; SET vComission = currency_getCommission(vCurrency); - UPDATE vn.entry e + UPDATE vn.entry e JOIN tmp.recalcEntryCommision tmp ON tmp.id = e.id SET e.commission = vComission; - SELECT `name` INTO vCurrencyName - FROM currency + SELECT `name` INTO vCurrencyName + FROM currency WHERE id = vCurrency; CALL entry_recalc(); @@ -55507,7 +55508,7 @@ BEGIN WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo AND cr.description = vDepartment GROUP BY cd.workerFk; - + CREATE OR REPLACE TEMPORARY TABLE volume ENGINE = MEMORY SELECT SUM(w.volume) volume, @@ -55518,15 +55519,15 @@ BEGIN CREATE OR REPLACE TEMPORARY TABLE errorsByChecker ENGINE = MEMORY - SELECT sub1.workerFk, COUNT(id) errors + SELECT sub1.workerFk, COUNT(id) errors FROM ( SELECT st.workerFk, t.id FROM saleMistake sm JOIN saleTracking st ON sm.saleFk = st.saleFk JOIN `state` s2 ON s2.id = st.stateFk - JOIN sale s ON s.id = sm.saleFk - JOIN ticket t on t.id = s.ticketFk + JOIN sale s ON s.id = sm.saleFk + JOIN ticket t on t.id = s.ticketFk WHERE (t.shipped BETWEEN vDatedFrom AND vDatedTo) AND s2.code IN ('OK','PREVIOUS_PREPARATION','PREPARED','CHECKED') ) sub1 @@ -55537,13 +55538,13 @@ BEGIN SELECT COUNT(t.id) errors, e.workerFk FROM vn.expeditionMistake pm - JOIN vn.expedition e ON e.id = pm.expeditionFk + JOIN vn.expedition e ON e.id = pm.expeditionFk JOIN vn.ticket t ON t.id = e.ticketFk WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo GROUP BY e.workerFk; IF (vDepartment = 'Sacadores') THEN - + INSERT INTO errorProduction(userFk, firstname, lastname, @@ -55576,12 +55577,12 @@ BEGIN LEFT JOIN errorsByChecker ec2 ON ec2.workerFk = t.workerFk JOIN (SELECT DISTINCT w.id -- Verificamos que son sacadores FROM vn.collection c - JOIN vn.state s ON s.id = c.stateFk + JOIN vn.state s ON s.id = c.stateFk JOIN vn.train tn ON tn.id = c.trainFk - JOIN vn.worker w ON w.id = c.workerFk + JOIN vn.worker w ON w.id = c.workerFk WHERE c.created BETWEEN vDatedFrom AND vDatedTo) sub ON sub.id = w.id GROUP BY w.id; - + CREATE OR REPLACE TEMPORARY TABLE itemPickerErrors -- Errores de los sacadores, derivadores de los revisadores ENGINE = MEMORY SELECT COUNT(c.ticketFk) errors, @@ -55601,7 +55602,7 @@ BEGIN JOIN itemPickerErrors ipe ON ipe.workerFk = ep.userFk SET ep.error = ep.error + ipe.errors WHERE vDatedFrom = ep.dated AND ep.rol = 'Sacadores'; - + DROP TEMPORARY TABLE itemPickerErrors; ELSE INSERT INTO errorProduction(userFk, @@ -55637,7 +55638,7 @@ BEGIN LEFT JOIN expeditionErrors pe ON pe.workerFk = t.workerFk GROUP BY w.id; END IF; - + DROP TEMPORARY TABLE total, errorsByClaim, volume, @@ -55663,7 +55664,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `errorProduction_addLauncher`() BEGIN DECLARE vDatedFrom DATETIME; DECLARE vDatedTo DATETIME; - + SELECT DATE_SUB(util.VN_CURDATE(),INTERVAL 1 DAY), CONCAT(DATE_SUB(util.VN_CURDATE(),INTERVAL 1 DAY),' 23:59:59') INTO vDatedFrom, vDatedTo; CALL vn.errorProduction_add('SACAR', vDatedFrom, vDatedTo); @@ -55694,7 +55695,7 @@ BEGIN DECLARE vRouteFk INT DEFAULT 0; SELECT t.routeFk INTO vRouteFk - FROM vn.expedition exp + FROM vn.expedition exp INNER JOIN ticket t on t.id = exp.ticketFk WHERE exp.id = vExpeditionFk; @@ -55897,14 +55898,14 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionPallet_printLabel`(vSelf INT) BEGIN /** - * Calls the report_print procedure and passes it + * Calls the report_print procedure and passes it * the necessary parameters for printing. * * @param vSelf expeditioPallet id. */ DECLARE vPrinterFk INT; DECLARE vUserFk INT DEFAULT account.myUser_getId(); - + SELECT o.labelerFk INTO vPrinterFk FROM operator o WHERE o.workerFk = vUserFk; @@ -55971,22 +55972,22 @@ BEGIN DECLARE vTotal INT DEFAULT 0; IF vPalletFk = 0 THEN -- Nuevo pallet - - INSERT INTO vn.expeditionPallet(truckFk) + + INSERT INTO vn.expeditionPallet(truckFk) VALUES(vTruckFk); - + SELECT LAST_INSERT_ID() INTO vPalletFk; - + END IF; - + SELECT COUNT(expeditionFk) INTO vTotal FROM vn.expeditionScan WHERE palletFk = vPalletFk; - + IF vTotal <> 0 THEN - SELECT expeditionFk, + SELECT expeditionFk, palletFk - FROM vn.expeditionScan + FROM vn.expeditionScan WHERE palletFk = vPalletFk; - ELSE + ELSE SELECT 0 expeditionFk,vPalletFk palletFk; END IF; END ;; @@ -56059,12 +56060,12 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionScan_Put`(vPalletFk INT, vExpeditionFk INT) BEGIN - - REPLACE vn.expeditionScan(expeditionFk, palletFk) + + REPLACE vn.expeditionScan(expeditionFk, palletFk) VALUES(vExpeditionFk, vPalletFk); - + SELECT LAST_INSERT_ID() INTO vPalletFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -56083,32 +56084,32 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionState_add`(vParam INT, vStateCode VARCHAR(100)) BEGIN - + /** * Inserta nuevos registros en la tabla vn.expeditionState, segun el parámetro - * + * * @param vParam Identificador de vn.expedition o de vn.route * @param vStateCode Corresponde a vn.expeditionStateType.code */ - + IF (SELECT COUNT(*) FROM vn.route r WHERE r.id = vParam) THEN - + INSERT INTO vn.expeditionState(expeditionFk, typeFk) SELECT e.id, est.id FROM vn.expedition e JOIN vn.ticket t ON t.id = e.ticketFk JOIN vn.expeditionStateType est ON est.code = vStateCode WHERE t.routeFk = vParam; - + ELSE - + INSERT INTO vn.expeditionState(expeditionFk, typeFk) SELECT vParam, est.id FROM vn.expeditionStateType est WHERE est.code = vStateCode; - + END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -56140,7 +56141,7 @@ BEGIN SELECT e.id, est.id FROM vn.expedition e JOIN vn.expeditionStateType est ON est.code = vStateCode - JOIN vn.ticket t ON t.id = e.ticketFk + JOIN vn.ticket t ON t.id = e.ticketFk WHERE t.addressFk = vAdressFk AND t.routeFk = vRouteFk; END ;; @@ -56161,14 +56162,14 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionState_addByExpedition`(vExpeditionFk INT, vStateCode VARCHAR(100)) BEGIN - + /** * Inserta nuevos registros en la tabla vn.expeditionState - * + * * @param vExpeditionFk Identificador de vn.expedition * @param vStateCode Corresponde a vn.expeditionStateType.code */ - + INSERT INTO vn.expeditionState(expeditionFk, typeFk) SELECT vExpeditionFk, est.id FROM vn.expeditionStateType est @@ -56194,7 +56195,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionState_addByPallet`(vPalle BEGIN /** * Inserta nuevos registros en la tabla vn.expeditionState - * + * * @param vPalletFk Identificador de vn.expedition * @param vStateCode Corresponde a vn.expeditionStateType.code */ @@ -56211,7 +56212,7 @@ BEGIN IF NOT hasExpeditions THEN DROP TEMPORARY TABLE tExpeditionScan; - CALL util.throw('palletDoesNotExist'); + CALL util.throw('palletDoesNotExist'); END IF; INSERT INTO vn.expeditionState(expeditionFk, typeFk) @@ -56236,21 +56237,21 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionState_addByRoute`(vRouteFk INT, vStateCode VARCHAR(100)) BEGIN - + /** * Inserta nuevos registros en la tabla vn.expeditionState, por rutas - * + * * @param vRouteFk Identificador de vn.route * @param vStateCode Corresponde a vn.expeditionStateType.code */ - + INSERT INTO vn.expeditionState(expeditionFk, typeFk) SELECT e.id, est.id FROM vn.expedition e JOIN vn.ticket t ON t.id = e.ticketFk JOIN vn.expeditionStateType est ON est.code = vStateCode WHERE t.routeFk = vRouteFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -56292,8 +56293,8 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionTruck_List`() BEGIN - SELECT id truckFk, - eta, + SELECT id truckFk, + eta, description Destino FROM expeditionTruck WHERE eta BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE()) @@ -56337,7 +56338,7 @@ BEGIN JOIN address a ON t.addressFk = a.id JOIN route r ON r.id = t.routeFk LEFT JOIN warehouse w ON t.warehouseFk = w.id - LEFT JOIN (SELECT sub.ticketFk, + LEFT JOIN (SELECT sub.ticketFk, CONCAT('(', GROUP_CONCAT(DISTINCT sub.itemPackingTypeFk ORDER BY sub.items DESC SEPARATOR ','), ') ') itemPackingTypeConcat FROM (SELECT s.ticketFk , i.itemPackingTypeFk, COUNT(*) items FROM ticket t @@ -56368,7 +56369,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_getState`(vExpeditionFk INT) BEGIN - + DECLARE vTicketsPendientes INT; DECLARE vEtiquetasTotales INT; DECLARE vEtiquetasEscaneadas INT; @@ -56378,24 +56379,24 @@ BEGIN FROM vn.ticket t JOIN vn.expedition e ON e.ticketFk = t.id WHERE e.id = vExpeditionFk; - + SELECT COUNT(*) INTO vTicketsPendientes FROM vn.ticket t LEFT JOIN vn.expedition e ON e.ticketFk = t.id WHERE t.routeFk = vRouteFk AND ISNULL(e.id); - + SELECT COUNT(*) INTO vEtiquetasTotales - FROM vn.expedition e + FROM vn.expedition e JOIN vn.ticket t ON t.id = e.ticketFk WHERE t.routeFk = vRouteFk; - + SELECT COUNT(*) INTO vEtiquetasEscaneadas - FROM vn.expeditionScan es + FROM vn.expeditionScan es JOIN vn.expedition e ON e.id = es.expeditionFk - JOIN vn.ticket t ON t.id = e.ticketFk + JOIN vn.ticket t ON t.id = e.ticketFk WHERE t.routeFk = vRouteFk; - + SELECT e.ticketFk ticket, t.nickname cliente, a.city ciudad, @@ -56409,17 +56410,17 @@ BEGIN vTicketsPendientes AS ticketsPendientes, vEtiquetasTotales AS etiquetasTotales, vEtiquetasEscaneadas AS etiquetasEscaneadas - FROM vn.expedition e - JOIN vn.ticket t ON t.id = e.ticketFk - JOIN vn.address a ON a.id = t.addressFk - JOIN vn.province p ON p.id = a.provinceFk - JOIN vn.`zone`z ON z.id = t.zoneFk - LEFT JOIN vn.route r ON r.id = t.routeFk - LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk - LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id - LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk + FROM vn.expedition e + JOIN vn.ticket t ON t.id = e.ticketFk + JOIN vn.address a ON a.id = t.addressFk + JOIN vn.province p ON p.id = a.provinceFk + JOIN vn.`zone`z ON z.id = t.zoneFk + LEFT JOIN vn.route r ON r.id = t.routeFk + LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk + LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id + LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk WHERE e.id = vExpeditionFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -56438,12 +56439,12 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_StateGet`(vExpeditionFk INT) BEGIN - + /* Devuelve una "ficha" con todos los datos relativos a la expedición - * - * param vExpeditionFk + * + * param vExpeditionFk */ - + DECLARE vTicketsPendientes INT; DECLARE vEtiquetasTotales INT; DECLARE vEtiquetasEscaneadas INT; @@ -56454,34 +56455,34 @@ BEGIN FROM vn.ticket t JOIN vn.expedition e ON e.ticketFk = t.id WHERE e.id = vExpeditionFk; - + SELECT COUNT(*) INTO vTicketsPendientes FROM vn.ticket t LEFT JOIN vn.expedition e ON e.ticketFk = t.id WHERE t.routeFk = vRouteFk AND ISNULL(e.id); - + SELECT COUNT(*) INTO vEtiquetasTotales - FROM vn.expedition e + FROM vn.expedition e JOIN vn.ticket t ON t.id = e.ticketFk WHERE t.routeFk = vRouteFk; - + SELECT COUNT(*) INTO vEtiquetasEscaneadas - FROM vn.expeditionScan es + FROM vn.expeditionScan es JOIN vn.expedition e ON e.id = es.expeditionFk - JOIN vn.ticket t ON t.id = e.ticketFk + JOIN vn.ticket t ON t.id = e.ticketFk WHERE t.routeFk = vRouteFk; - + SELECT COUNT(*) INTO vEtiquetasLeidasSorter - FROM srt.expedition e + FROM srt.expedition e JOIN vn.expedition ve ON ve.id = e.id LEFT JOIN vn.expeditionScan es ON es.expeditionFk = e.id - JOIN vn.ticket t ON t.id = ve.ticketFk + JOIN vn.ticket t ON t.id = ve.ticketFk WHERE t.routeFk = vRouteFk AND e.created != e.updated - AND ISNULL(es.expeditionFk); - - + AND ISNULL(es.expeditionFk); + + SELECT e.ticketFk ticket, t.nickname cliente, a.city ciudad, @@ -56496,17 +56497,17 @@ BEGIN vEtiquetasTotales AS etiquetasTotales, vEtiquetasEscaneadas AS etiquetasEscaneadas, vEtiquetasLeidasSorter AS etiquetasSorter - FROM vn.expedition e - JOIN vn.ticket t ON t.id = e.ticketFk - JOIN vn.address a ON a.id = t.addressFk - JOIN vn.province p ON p.id = a.provinceFk - JOIN vn.`zone`z ON z.id = t.zoneFk - LEFT JOIN vn.route r ON r.id = t.routeFk - LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk - LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id - LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk + FROM vn.expedition e + JOIN vn.ticket t ON t.id = e.ticketFk + JOIN vn.address a ON a.id = t.addressFk + JOIN vn.province p ON p.id = a.provinceFk + JOIN vn.`zone`z ON z.id = t.zoneFk + LEFT JOIN vn.route r ON r.id = t.routeFk + LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk + LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id + LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk WHERE e.id = vExpeditionFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -56552,7 +56553,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `fustControl`(vFromDated DATE, vToDated DATE) BEGIN - + DECLARE vSijsnerClientFk INT DEFAULT 19752; DECLARE vDateStart DATETIME; @@ -56561,68 +56562,68 @@ BEGIN SET vDateStart = vFromDated; SET vDateEnd = util.Dayend(vToDated); - SELECT p.id FustCode, - CAST(sent.stucks AS DECIMAL(10,0)) FH, - CAST(tp.stucks AS DECIMAL(10,0)) Tickets, - CAST(-sj.stucks AS DECIMAL(10,0)) Sijsner, + SELECT p.id FustCode, + CAST(sent.stucks AS DECIMAL(10,0)) FH, + CAST(tp.stucks AS DECIMAL(10,0)) Tickets, + CAST(-sj.stucks AS DECIMAL(10,0)) Sijsner, CAST(IFNULL(sent.stucks,0) - IFNULL(tp.stucks,0) + IFNULL(sj.stucks,0) AS DECIMAL(10,0)) saldo FROM vn.packaging p LEFT JOIN ( SELECT FustCode, sum(fustQuantity) stucks FROM ( SELECT IFNULL(pe.equivalentFk ,b.packageFk) FustCode, s.quantity / b.packing AS fustQuantity - FROM vn.sale s - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN vn.warehouse w ON w.id = t.warehouseFk - JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk - JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND lb.warehouse_id = t.warehouseFk - JOIN vn.buy b ON b.id = lb.buy_id - JOIN vn.packaging p ON p.id = b.packageFk + FROM vn.sale s + JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.warehouse w ON w.id = t.warehouseFk + JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk + JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND lb.warehouse_id = t.warehouseFk + JOIN vn.buy b ON b.id = lb.buy_id + JOIN vn.packaging p ON p.id = b.packageFk LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id - JOIN vn.address a ON a.id = t.addressFk - JOIN vn.province p2 ON p2.id = a.provinceFk - JOIN vn.country c ON c.id = p2.countryFk + JOIN vn.address a ON a.id = t.addressFk + JOIN vn.province p2 ON p2.id = a.provinceFk + JOIN vn.country c ON c.id = p2.countryFk WHERE t.shipped BETWEEN vDateStart AND vDateEnd AND wa.name = 'VNH' - AND p.isPackageReturnable - AND c.country = 'FRANCIA') sub + AND p.isPackageReturnable + AND c.country = 'FRANCIA') sub GROUP BY FustCode) sent ON sent.FustCode = p.id LEFT JOIN ( SELECT FustCode, sum(quantity) stucks FROM ( SELECT IFNULL(pe.equivalentFk ,tp.packagingFk) FustCode, tp.quantity - FROM vn.ticketPackaging tp - JOIN vn.ticket t ON t.id = tp.ticketFk - JOIN vn.warehouse w ON w.id = t.warehouseFk - JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk - JOIN vn.packaging p ON p.id = tp.packagingFk + FROM vn.ticketPackaging tp + JOIN vn.ticket t ON t.id = tp.ticketFk + JOIN vn.warehouse w ON w.id = t.warehouseFk + JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk + JOIN vn.packaging p ON p.id = tp.packagingFk LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id - JOIN vn.address a ON a.id = t.addressFk - JOIN vn.province p2 ON p2.id = a.provinceFk - JOIN vn.country c ON c.id = p2.countryFk + JOIN vn.address a ON a.id = t.addressFk + JOIN vn.province p2 ON p2.id = a.provinceFk + JOIN vn.country c ON c.id = p2.countryFk WHERE t.shipped BETWEEN vDateStart AND vDateEnd AND wa.name = 'VNH' - AND p.isPackageReturnable + AND p.isPackageReturnable AND c.country = 'FRANCIA' AND t.clientFk != vSijsnerClientFk - AND tp.quantity > 0) sub + AND tp.quantity > 0) sub GROUP BY FustCode) tp ON tp.FustCode = p.id LEFT JOIN ( SELECT FustCode, sum(quantity) stucks FROM ( SELECT IFNULL(pe.equivalentFk ,tp.packagingFk) FustCode, tp.quantity - FROM vn.ticketPackaging tp - JOIN vn.ticket t ON t.id = tp.ticketFk - JOIN vn.warehouse w ON w.id = t.warehouseFk - JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk - JOIN vn.packaging p ON p.id = tp.packagingFk + FROM vn.ticketPackaging tp + JOIN vn.ticket t ON t.id = tp.ticketFk + JOIN vn.warehouse w ON w.id = t.warehouseFk + JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk + JOIN vn.packaging p ON p.id = tp.packagingFk LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id WHERE t.shipped BETWEEN TIMESTAMPADD(DAY, 1, vDateStart ) AND TIMESTAMPADD(DAY, 1, vDateEnd ) AND wa.name = 'VNH' - AND p.isPackageReturnable - AND t.clientFk = vSijsnerClientFk) sub + AND p.isPackageReturnable + AND t.clientFk = vSijsnerClientFk) sub GROUP BY FustCode) sj ON sj.FustCode = p.id - WHERE sent.stucks + WHERE sent.stucks OR tp.stucks OR sj.stucks; @@ -56644,7 +56645,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `fustControlDetail`(vFromDated DATE, vToDated DATE) BEGIN - + DECLARE vSijsnerClientFk INT DEFAULT 19752; DECLARE vDateStart DATETIME; @@ -56652,29 +56653,29 @@ BEGIN SET vDateStart = vFromDated; SET vDateEnd = util.Dayend(vToDated); - + SELECT a.nickname shopName, - a.city , - IFNULL(pe.equivalentFk ,tp.packagingFk) FustCode, + a.city , + IFNULL(pe.equivalentFk ,tp.packagingFk) FustCode, tp.quantity, tp.ticketFk, CONCAT('From ', vFromDated,' to ', vToDated) AS dateRange - FROM vn.ticketPackaging tp - JOIN vn.ticket t ON t.id = tp.ticketFk - JOIN vn.warehouse w ON w.id = t.warehouseFk - JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk - JOIN vn.packaging p ON p.id = tp.packagingFk + FROM vn.ticketPackaging tp + JOIN vn.ticket t ON t.id = tp.ticketFk + JOIN vn.warehouse w ON w.id = t.warehouseFk + JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk + JOIN vn.packaging p ON p.id = tp.packagingFk LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id - JOIN vn.address a ON a.id = t.addressFk - JOIN vn.province p2 ON p2.id = a.provinceFk - JOIN vn.country c ON c.id = p2.countryFk + JOIN vn.address a ON a.id = t.addressFk + JOIN vn.province p2 ON p2.id = a.provinceFk + JOIN vn.country c ON c.id = p2.countryFk WHERE t.shipped BETWEEN vFromDated AND util.dayend(vToDated) AND wa.name = 'VNH' - AND p.isPackageReturnable + AND p.isPackageReturnable AND c.country = 'FRANCIA' AND t.clientFk != vSijsnerClientFk AND tp.quantity > 0; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -56700,8 +56701,8 @@ DECLARE vTicketFk INT; DECLARE vSaleFk INT; DECLARE vClonTicket INT DEFAULT 0; -DECLARE cur1 CURSOR FOR -SELECT s.ticketFk, s.id +DECLARE cur1 CURSOR FOR +SELECT s.ticketFk, s.id FROM vn.sale s JOIN vn.ticket t ON t.id = s.ticketFk JOIN vn.item i ON i.id = s.itemFk @@ -56717,17 +56718,17 @@ OPEN cur1; FETCH cur1 INTO vTicketFk, vSaleFk; WHILE done = 0 DO - + SELECT t.id INTO vClonTicket FROM vn.ticket t JOIN (SELECT addressFk, shipped FROM vn.ticket WHERE id = vTicketFk) sub USING(addressFk, shipped) WHERE t.warehouseFk = 44 LIMIT 1; - + SELECT vTicketFk, vClonTicket; - + IF vClonTicket = 0 THEN - + INSERT INTO ticket ( clientFk, shipped, @@ -56755,12 +56756,12 @@ FETCH cur1 INTO vTicketFk, vSaleFk; zonePrice, zoneBonus, routeFk - + FROM ticket WHERE id = vTicketFk; SET vClonTicket = LAST_INSERT_ID(); - + SELECT 'lstID', vClonTicket; /* INSERT INTO ticketObservation(ticketFk, observationTypeFk, description) @@ -56770,20 +56771,20 @@ FETCH cur1 INTO vTicketFk, vSaleFk; WHERE t.id = vClonTicket; */ INSERT INTO ticketLog - SET originFk = vTicketFk, userFk = account.myUser_getId(), `action` = 'insert', + SET originFk = vTicketFk, userFk = account.myUser_getId(), `action` = 'insert', description = CONCAT('Ha creado el ticket:', ' ', vClonTicket, ' clonando el ', vTicketFk); - + END IF; - + UPDATE vn.sale SET ticketFk = vClonTicket WHERE id = vSaleFk; SET vClonTicket = 0; - + SET done = 0; FETCH cur1 INTO vTicketFk, vSaleFk; - + END WHILE; CLOSE cur1; @@ -56808,8 +56809,8 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `getDayExpeditions`() BEGIN - SELECT - e.expeditions_id as expeditionFk, + SELECT + e.expeditions_id as expeditionFk, date_format(e.odbc_date,'%Y-%m-%d') as expeditionDate, e.ticket_id as ticketFk, t.routeFk as routeFk @@ -56886,7 +56887,7 @@ BEGIN SELECT DATE_SUB(util.VN_CURDATE(), INTERVAL yearsToDelete YEAR) INTO vDated FROM vn.greugeConfig; - + INSERT INTO vn.greuge(clientFk, description, amount, shipped, created, greugeTypeFk) SELECT clientFk, 'Suma agrupada', SUM(amount), MAX(shipped), MAX(created), greugeTypeFk FROM vn.greuge @@ -57004,8 +57005,8 @@ DECLARE done BOOL DEFAULT FALSE; DECLARE vTicketFk INT; DECLARE rs CURSOR FOR - SELECT id FROM vn.ticket - WHERE shipped = util.yesterday() + SELECT id FROM vn.ticket + WHERE shipped = util.yesterday() AND clientFk = 400 AND warehouseFk IN (1,44); @@ -57016,13 +57017,13 @@ OPEN rs; FETCH rs INTO vTicketFk; WHILE NOT done DO - + INSERT INTO vn.inventoryFailure(dated, itemFk, quantity, value, warehouseFk, throwerFk) - SELECT t.shipped, - s.itemFk, - s.quantity, + SELECT t.shipped, + s.itemFk, + s.quantity, b.buyingValue + b.freightValue + b.packageValue + b.comissionValue, - t.warehouseFk, + t.warehouseFk, w.id FROM vn.ticket t JOIN vn.sale s ON s.ticketFk = t.id @@ -57033,7 +57034,7 @@ WHILE NOT done DO AND s.quantity > 0; FETCH rs INTO vTicketFk; - + END WHILE; @@ -57101,7 +57102,7 @@ proc: BEGIN SELECT inventorySupplierFk INTO vInventorySupplierFk FROM entryConfig; - + SELECT am.id INTO vAgencyModeFkInventory FROM agencyMode am where code = 'inv'; @@ -57198,7 +57199,7 @@ proc: BEGIN JOIN entry e ON e.id = b.entryFk JOIN travel tr ON tr.id = e.travelFk WHERE tr.warehouseInFk = vWh - AND tr.landed BETWEEN vDateLastInventory + AND tr.landed BETWEEN vDateLastInventory AND vDateYesterday AND NOT isRaid GROUP BY b.itemFk; @@ -57252,7 +57253,7 @@ proc: BEGIN inv.price3 = b.price3, inv.minPrice = b.minPrice, inv.producer = p.name; - + INSERT INTO buy( itemFk, quantity, buyingValue, @@ -57286,15 +57287,15 @@ proc: BEGIN FROM tmp.inventory; SELECT vWh, COUNT(*), util.VN_NOW() FROM tmp.inventory; - + -- Actualizamos el campo lastUsed de item UPDATE item i JOIN tmp.inventory i2 ON i2.itemFk = i.id SET i.lastUsed = NOW() WHERE i2.quantity; - + -- DROP TEMPORARY TABLE tmp.inventory; - + END LOOP; CLOSE cWarehouses; @@ -57308,11 +57309,11 @@ proc: BEGIN SELECT e.id as entryId, t.id as travelId FROM travel t - JOIN `entry` e ON e.travelFk = t.id + JOIN `entry` e ON e.travelFk = t.id WHERE e.supplierFk = vInventorySupplierFk AND t.shipped <= util.VN_CURDATE() - INTERVAL 12 DAY AND (DAY(t.shipped) <> 1 OR shipped < util.VN_CURDATE() - INTERVAL 12 DAY); - + DELETE e FROM `entry` e JOIN tmp.entryToDelete tmp ON tmp.entryId = e.id; @@ -57374,7 +57375,7 @@ BEGIN b.id AS buyFk, b.entryFk, b.isIgnored, - b.price2, + b.price2, b.price3, b.stickers, b.packing, @@ -57388,20 +57389,20 @@ BEGIN s.id AS supplierFk, s.name AS supplier FROM itemType it - RIGHT JOIN (entry e + RIGHT JOIN (entry e LEFT JOIN supplier s ON s.id = e.supplierFk RIGHT JOIN buy b ON b.entryFk = e.id LEFT JOIN item i ON i.id = b.itemFk - LEFT JOIN ink ON ink.id = i.inkFk + LEFT JOIN ink ON ink.id = i.inkFk LEFT JOIN travel tr ON tr.id = e.travelFk LEFT JOIN warehouse w ON w.id = tr.warehouseInFk LEFT JOIN origin o ON o.id = i.originFk ) ON it.id = i.typeFk LEFT JOIN edi.ekt ek ON b.ektFk = ek.id WHERE (b.packageFk = "--" OR b.price2 = 0 OR b.packing = 0 OR b.buyingValue = 0) AND tr.landed > util.firstDayOfMonth(TIMESTAMPADD(MONTH,-1,util.VN_CURDATE())) AND s.name = 'INVENTARIO'; - + DROP TEMPORARY TABLE IF EXISTS tmp.lastEntryOk; - CREATE TEMPORARY TABLE tmp.lastEntryOk + CREATE TEMPORARY TABLE tmp.lastEntryOk (PRIMARY KEY (buyFk)) SELECT i.id AS itemFk, @@ -57411,7 +57412,7 @@ BEGIN b.id AS buyFk, b.entryFk, b.isIgnored, - b.price2, + b.price2, b.price3, b.stickers, b.packing, @@ -57425,11 +57426,11 @@ BEGIN s.id AS supplierFk, s.name AS supplier FROM itemType it - RIGHT JOIN (entry e + RIGHT JOIN (entry e LEFT JOIN supplier s ON s.id = e.supplierFk RIGHT JOIN buy b ON b.entryFk = e.id LEFT JOIN item i ON i.id = b.itemFk - LEFT JOIN ink ON ink.id = i.inkFk + LEFT JOIN ink ON ink.id = i.inkFk LEFT JOIN travel tr ON tr.id = e.travelFk LEFT JOIN warehouse w ON w.id = tr.warehouseInFk LEFT JOIN origin o ON o.id = i.originFk @@ -57437,34 +57438,34 @@ BEGIN LEFT JOIN edi.ekt ek ON b.ektFk = ek.id WHERE b.packageFk != "--" AND b.price2 != 0 AND b.packing != 0 AND b.buyingValue > 0 AND tr.landed > util.firstDayOfMonth(TIMESTAMPADD(MONTH,-2,util.VN_CURDATE())) ORDER BY tr.landed DESC; - + DROP TEMPORARY TABLE IF EXISTS tmp.lastEntryOkGroup; - CREATE TEMPORARY TABLE tmp.lastEntryOkGroup + CREATE TEMPORARY TABLE tmp.lastEntryOkGroup (INDEX (warehouseFk,itemFk)) SELECT * FROM tmp.lastEntryOk tmp GROUP BY tmp.itemFk,tmp.warehouseFk; - + UPDATE buy b JOIN tmp.lastEntry lt ON lt.buyFk = b.id JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk SET b.packageFk = eo.packageFk WHERE b.packageFk = "--"; - + UPDATE buy b JOIN tmp.lastEntry lt ON lt.buyFk = b.id JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk SET b.price2 = eo.price2 WHERE b.price2 = 0 ; - + UPDATE buy b JOIN tmp.lastEntry lt ON lt.buyFk = b.id JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk SET b.packing = eo.packing WHERE b.packing = 0; - + UPDATE buy b JOIN tmp.lastEntry lt ON lt.buyFk = b.id JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk SET b.buyingValue = eo.buyingValue WHERE b.buyingValue = 0; - + DROP TEMPORARY TABLE tmp.lastEntry; DROP TEMPORARY TABLE tmp.lastEntryOk; DROP TEMPORARY TABLE tmp.lastEntryOkGroup; @@ -57624,7 +57625,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceInDueDay_calculate`(vInvoiceInFk INT) BEGIN /** - * Calcula los vctos. de una factura recibida + * Calcula los vctos. de una factura recibida * En caso de haberlos informado previamente o que el proveedor sea español, no los recalculará * * @param vInvoiceInFk Factura recibida @@ -57645,46 +57646,46 @@ BEGIN WHERE ii.id = vInvoiceInFk; SELECT COUNT(*) INTO vHasDueDay - FROM invoiceInDueDay iid + FROM invoiceInDueDay iid WHERE iid.invoiceInFk = vInvoiceInFk; IF NOT vHasDueDay AND vCompanyCountryCode = 'ES' THEN SET @cont := 0; INSERT INTO invoiceInDueDay ( - invoiceInFk, - dueDated, - amount, + invoiceInFk, + dueDated, + amount, foreignValue ) SELECT vInvoiceInFk, - IF(payDay, + IF(payDay, IF(getNextDueDate(issued, pdd.detail, payDay) < created, created, - getNextDueDate(issued, pdd.detail, payDay)), + getNextDueDate(issued, pdd.detail, payDay)), GREATEST(created, issued + INTERVAL pdd.detail DAY)), - IF((@cont := @cont + 1) < cont, - TRUNCATE(venc / cont, 2), - venc - (TRUNCATE(venc / cont, 2) * (cont - 1))), - IF(@cont < cont, - TRUNCATE(foreignValue / cont, 2), - foreignValue - (TRUNCATE(foreignValue / cont, 2) * (cont - 1))) - FROM ( - SELECT SUM((1 + (IFNULL(ti.PorcentajeIva, 0) / 100) * vHasDueDayTax) - * iit.taxableBase) / COUNT(DISTINCT(pdd.detail)) venc, + IF((@cont := @cont + 1) < cont, + TRUNCATE(venc / cont, 2), + venc - (TRUNCATE(venc / cont, 2) * (cont - 1))), + IF(@cont < cont, + TRUNCATE(foreignValue / cont, 2), + foreignValue - (TRUNCATE(foreignValue / cont, 2) * (cont - 1))) + FROM ( + SELECT SUM((1 + (IFNULL(ti.PorcentajeIva, 0) / 100) * vHasDueDayTax) + * iit.taxableBase) / COUNT(DISTINCT(pdd.detail)) venc, SUM(iit.foreignValue) / COUNT(DISTINCT(pdd.detail)) foreignValue, - s.payDemFk, + s.payDemFk, ii.companyFk, COUNT(DISTINCT(pdd.detail)) cont, s.payDay, ii.issued, DATE(ii.created) + INTERVAL 2 DAY created - FROM invoiceIn ii - JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id - LEFT JOIN sage.TiposIva ti ON ti.CodigoIva= iit.taxTypeSageFk - JOIN supplier s ON s.id = ii.supplierFk - JOIN payDemDetail pdd ON pdd.id = s.payDemFk - WHERE ii.id = vInvoiceInFk + FROM invoiceIn ii + JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id + LEFT JOIN sage.TiposIva ti ON ti.CodigoIva= iit.taxTypeSageFk + JOIN supplier s ON s.id = ii.supplierFk + JOIN payDemDetail pdd ON pdd.id = s.payDemFk + WHERE ii.id = vInvoiceInFk GROUP BY ii.id )sub JOIN payDemDetail pdd ON pdd.id = sub.payDemFk @@ -57712,9 +57713,9 @@ BEGIN DELETE FROM invoiceInDueDay WHERE invoiceInFk = vInvoiceInFk; - + CALL invoiceInDueDay_calculate(vInvoiceInFk); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -57798,7 +57799,7 @@ BEGIN CALL invoiceInTax_getFromEntries(vInvoiceInFk); CALL invoiceInDueDay_calculate(vInvoiceInFk); - + FETCH rs INTO vInvoiceInFk; END WHILE; @@ -57830,7 +57831,7 @@ BEGIN SELECT MAX(rr.dated) INTO vDated FROM referenceRate rr JOIN invoiceIn ii ON ii.id = vId - WHERE rr.dated <= ii.issued + WHERE rr.dated <= ii.issued AND rr.currencyFk = ii.currencyFk ; IF vDated THEN @@ -57839,13 +57840,13 @@ BEGIN WHERE dated = vDated; END IF; - SELECT id INTO vExpenceFk - FROM vn.expence - WHERE `name` = 'Adquisición mercancia Extracomunitaria' - GROUP BY id + SELECT id INTO vExpenceFk + FROM vn.expence + WHERE `name` = 'Adquisición mercancia Extracomunitaria' + GROUP BY id LIMIT 1; - - DELETE FROM invoiceInTax + + DELETE FROM invoiceInTax WHERE invoiceInFk = vId; INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenceFk, foreignValue, taxTypeSageFk, transactionTypeSageFk) @@ -57859,9 +57860,9 @@ BEGIN JOIN entry e ON e.invoiceInFk = ii.id JOIN supplier s ON s.id = e.supplierFk JOIN buy b ON b.entryFk = e.id - LEFT JOIN referenceRate rr ON rr.currencyFk = ii.currencyFk + LEFT JOIN referenceRate rr ON rr.currencyFk = ii.currencyFk AND rr.dated = ii.issued - WHERE ii.id = vId + WHERE ii.id = vId HAVING taxableBase IS NOT NULL; END ;; DELIMITER ; @@ -57888,7 +57889,7 @@ BEGIN SELECT ii.bookEntried, iit.foreignValue, ii.companyFk, - ii.expenceFkDeductible, + ii.expenceFkDeductible, iit.taxableBase, iit.transactionTypeSageFk, ii.serial, @@ -57927,7 +57928,7 @@ BEGIN JOIN country c ON c.id = s.countryFk JOIN supplier sc ON sc.id = ii.companyFk JOIN country cc ON cc.id = sc.countryFk - JOIN invoiceInSerial iis ON iis.code = ii.serial + JOIN invoiceInSerial iis ON iis.code = ii.serial JOIN cplusInvoiceType472 cit ON cit.id = ii.cplusInvoiceType472Fk LEFT JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id LEFT JOIN sage.TiposTransacciones ttr ON ttr.CodigoTransaccion = iit.transactionTypeSageFk @@ -57950,18 +57951,18 @@ BEGIN NFACTICK, CLAVE, empresa_id) - SELECT + SELECT vBookNumber ASIEN, tii.bookEntried FECHA, tii.supplierAccount SUBCTA, - SUM(tii.taxableBase * - IF(tii.serial= 'R' AND ((tii.taxCode IS NULL OR tii.taxCode <> 'ISP21') - AND tii.taxTypeSageFk IS NOT NULL), - 1 + (tii.PorcentajeIva / 100), - 1)) EUROHABER, - CONCAT('s/fra', - RIGHT(tii.supplierRef, 8), - ':', + SUM(tii.taxableBase * + IF(tii.serial= 'R' AND ((tii.taxCode IS NULL OR tii.taxCode <> 'ISP21') + AND tii.taxTypeSageFk IS NOT NULL), + 1 + (tii.PorcentajeIva / 100), + 1)) EUROHABER, + CONCAT('s/fra', + RIGHT(tii.supplierRef, 8), + ':', LEFT(tii.supplierName, 10)) CONCEPTO, CAST(tii.taxableBase / tii.foreignValue AS DECIMAL (10,4)) CAMBIO, SUM(tii.foreignValue * IF(tii.serial = 'R', 1 + (tii.PorcentajeIva / 100), 1)) HABERME, @@ -57978,7 +57979,7 @@ BEGIN CONTRA, EURODEBE, EUROHABER, - CONCEPTO, + CONCEPTO, CAMBIO, DEBEME, HABERME, @@ -57990,9 +57991,9 @@ BEGIN tii.supplierAccount CONTRA, IF(tii.isWithheld AND tii.taxableBase < 0, NULL, ROUND(SUM(tii.taxableBase),2)) EURODEBE, IF(tii.isWithheld AND tii.taxableBase < 0, ROUND(SUM(-tii.taxableBase), 2), NULL) EUROHABER, - CONCAT('s/fra', - RIGHT(tii.supplierRef, 8), - ':', + CONCAT('s/fra', + RIGHT(tii.supplierRef, 8), + ':', LEFT(tii.supplierName, 10)) CONCEPTO, CAST(tii.taxableBase / tii.foreignValue AS DECIMAL (10, 4)) CAMBIO, IF(tii.isWithheld, NULL,ABS(ROUND(SUM(tii.foreignValue), 2))) DEBEME, @@ -58004,17 +58005,17 @@ BEGIN GROUP BY tii.expenceFk; -- Líneas de IVA - INSERT INTO XDiario( + INSERT INTO XDiario( ASIEN, FECHA, SUBCTA, - CONTRA, + CONTRA, EURODEBE, BASEEURO, CONCEPTO, - FACTURA, + FACTURA, IVA, - AUXILIAR, + AUXILIAR, SERIE, TIPOOPE, FECHA_EX, @@ -58063,28 +58064,28 @@ BEGIN tii.companyFk FROM tInvoiceIn tii LEFT JOIN ( - SELECT e.id + SELECT e.id FROM tInvoiceIn tii - JOIN expence e ON e.id = tii.expenceFk + JOIN expence e ON e.id = tii.expenceFk WHERE e.isWithheld LIMIT 1 - ) eWithheld ON TRUE - WHERE tii.taxTypeSageFk IS NOT NULL - AND (tii.taxCode IS NULL OR tii.taxCode NOT IN ('import10', 'import21')) + ) eWithheld ON TRUE + WHERE tii.taxTypeSageFk IS NOT NULL + AND (tii.taxCode IS NULL OR tii.taxCode NOT IN ('import10', 'import21')) GROUP BY tii.PorcentajeIva, tii.expenceFk; -- Línea iva inversor sujeto pasivo - INSERT INTO XDiario( + INSERT INTO XDiario( ASIEN, FECHA, SUBCTA, - CONTRA, + CONTRA, EUROHABER, BASEEURO, CONCEPTO, - FACTURA, + FACTURA, IVA, - AUXILIAR, + AUXILIAR, SERIE, TIPOOPE, FECHA_EX, @@ -58133,31 +58134,31 @@ BEGIN JOIN sage.config c WHERE tii.taxCode = 'ISP21' OR MID(tii.supplierAccount, 4, 1) = '1' AND tii.taxTypeSageFk IS NOT NULL - AND NOT(tii.isVies - AND c.nontaxableTransactionTypeFk = tii.transactionTypeSageFk + AND NOT(tii.isVies + AND c.nontaxableTransactionTypeFk = tii.transactionTypeSageFk AND tii.taxCode = 'nonTaxable') GROUP BY tii.PorcentajeIva, tii.expenceFk; - - -- Actualización del registro original + + -- Actualización del registro original UPDATE invoiceIn ii SET ii.isBooked = TRUE WHERE ii.id = vSelf; - + -- Problemas derivados de la precisión en los decimales al calcular los impuestos - UPDATE XDiario - SET EURODEBE = EURODEBE - + UPDATE XDiario + SET EURODEBE = EURODEBE - (SELECT IF(ABS(sub.difference) = 0.01, sub.difference, 0) FROM( - SELECT SUM(IFNULL(ROUND(EURODEBE, 2),0)) - SUM(IFNULL(ROUND(EUROHABER, 2), 0)) difference + SELECT SUM(IFNULL(ROUND(EURODEBE, 2),0)) - SUM(IFNULL(ROUND(EUROHABER, 2), 0)) difference FROM XDiario WHERE ASIEN = vBookNumber )sub ) - WHERE ASIEN = vBookNumber + WHERE ASIEN = vBookNumber AND EURODEBE <> 0 ORDER BY id DESC LIMIT 1; - + DROP TEMPORARY TABLE tInvoiceIn; END ;; DELIMITER ; @@ -58272,7 +58273,7 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS rs; CREATE TEMPORARY TABLE rs - SELECT + SELECT c.accountingAccount AS clientBookingAccount, io.amount as totalAmount, CONCAT('n/fra ', io.ref) as simpleConcept, @@ -58306,19 +58307,19 @@ BEGIN WHERE io.id = vInvoice; CALL vn.ledger_next(vBookNumber); - + -- Linea del cliente INSERT INTO XDiario( ASIEN, FECHA, - SUBCTA, + SUBCTA, EURODEBE, - CONCEPTO, + CONCEPTO, FECHA_EX, FECHA_OP, empresa_id ) - SELECT + SELECT vBookNumber AS ASIEN, rs.FECHA, rs.clientBookingAccount AS SUBCTA, @@ -58334,14 +58335,14 @@ BEGIN ASIEN, FECHA, SUBCTA, - CONTRA, + CONTRA, EUROHABER, - CONCEPTO, + CONCEPTO, FECHA_EX, FECHA_OP, empresa_id ) - SELECT + SELECT vBookNumber AS ASIEN, rs.FECHA, ioe.expenceFk AS SUBCTA, @@ -58355,8 +58356,8 @@ BEGIN JOIN invoiceOutExpence ioe WHERE ioe.invoiceOutFk = vInvoice; - SELECT GROUP_CONCAT(`name` SEPARATOR ',') - INTO vExpenceConcept + SELECT GROUP_CONCAT(`name` SEPARATOR ',') + INTO vExpenceConcept FROM expence e JOIN invoiceOutExpence ioe ON ioe.expenceFk = e.id WHERE ioe.invoiceOutFk = vInvoice; @@ -58366,7 +58367,7 @@ BEGIN ASIEN, FECHA, SUBCTA, - CONTRA, + CONTRA, EUROHABER, BASEEURO, CONCEPTO, @@ -58394,7 +58395,7 @@ BEGIN TIPORECTIF, empresa_id ) - SELECT + SELECT vBookNumber AS ASIEN, rs.FECHA, iot.pgcFk AS SUBCTA, @@ -58414,11 +58415,11 @@ BEGIN rs.FECHA_OP, rs.FECHA_EX, rs.TIPOOPE, - rs.NFACTICK, + rs.NFACTICK, rs.TERIDNIF, rs.TERNIF, rs.TERNOM, - pgc.mod340 AS L340, + pgc.mod340 AS L340, pgc.cplusTrascendency477Fk AS TIPOCLAVE, pgc.cplusTaxBreakFk as TIPOEXENCI, rs.TIPONOSUJE, @@ -58426,13 +58427,13 @@ BEGIN rs.TIPORECTIF, rs.companyFk AS empresa_id FROM rs - JOIN invoiceOutTax iot + JOIN invoiceOutTax iot JOIN pgc ON pgc.code = iot.pgcFk LEFT JOIN pgcEqu pe ON pe.vatFk = iot.pgcFk -- --------------- Comprueba si la linea es de iva con rec.equiv. asociado - LEFT JOIN pgc pgce ON pgce.code = pe.equFk + LEFT JOIN pgc pgce ON pgce.code = pe.equFk LEFT JOIN pgcEqu pe2 ON pe2.equFk = iot.pgcFk -- --------------- Comprueba si la linea es de rec.equiv. WHERE iot.invoiceOutFk = vInvoice; - + UPDATE invoiceOut SET booked = util.VN_CURDATE() WHERE id = vInvoice; @@ -58464,7 +58465,7 @@ BEGIN DECLARE done BOOL DEFAULT FALSE; - DECLARE rs CURSOR FOR + DECLARE rs CURSOR FOR SELECT io.id FROM invoiceOut io WHERE RIGHT(ref,7) BETWEEN 1724215 AND 1724224 @@ -58479,15 +58480,15 @@ BEGIN WHILE NOT done DO CALL invoiceOutBooking(vInvoice); - + FETCH rs INTO vInvoice ; - + SET vContador = vContador + 1; - + IF vContador MOD 50 = 0 THEN - + SELECT CONCAT(vContador, ' de momento') AS FACTURAS_ASENTADAS; - + END IF; END WHILE; @@ -58517,14 +58518,14 @@ BEGIN DECLARE vAsien INTEGER; DECLARE vSendMail BOOL; DECLARE vBody TEXT; - + SELECT ASIEN INTO vAsien - FROM XDiario + FROM XDiario WHERE SERIE = SUBSTRING(vRef, 1, 1) AND FACTURA = SUBSTRING(vRef, 2, LENGTH(vRef)-1) LIMIT 1; - SELECT IF(enlazado OR enlazadoSage, TRUE, FALSE), + SELECT IF(enlazado OR enlazadoSage, TRUE, FALSE), CONCAT( ' @@ -58533,7 +58534,7 @@ BEGIN - ', + ', GROUP_CONCAT( CONCAT(' @@ -58546,14 +58547,14 @@ BEGIN ) SEPARATOR ' ' ), '
FECHACONCEPTO EURODEBE EUROHABER
', IFNULL(FECHA,''), '
' - ) + ) INTO vSendMail, vBody - FROM XDiario + FROM XDiario WHERE ASIEN = vAsien; - DELETE FROM XDiario + DELETE FROM XDiario WHERE ASIEN = vAsien; - + IF vSendMail THEN CALL mail_insert( 'administracion@verdnatura.es', @@ -58571,7 +58572,7 @@ BEGIN SET refFk = NULL WHERE refFk = vRef; - DELETE + DELETE FROM invoiceOut WHERE ref = vRef; @@ -58594,7 +58595,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOutListByCompany`(vCompany INT, vStarted DATE, vEnded DATE) BEGIN -SELECT +SELECT c.socialName as RazonSocial, c.fi as NIF, io.ref as Factura, @@ -58606,7 +58607,7 @@ SELECT pgc.rate as Tipo, iot.vat as Cuota, pgc.name as Concepto - + FROM vn.invoiceOut io JOIN vn.invoiceOutTax iot ON iot.invoiceOutFk = io.id JOIN vn.client c ON c.id = io.clientFk @@ -59051,17 +59052,17 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOut_newFromClient`( - IN vClientFk INT, - IN vSerial CHAR(2), + IN vClientFk INT, + IN vSerial CHAR(2), IN vMaxShipped DATE, - IN vCompanyFk INT, + IN vCompanyFk INT, IN vTaxArea VARCHAR(25), - IN vRef VARCHAR(25), + IN vRef VARCHAR(25), OUT vInvoiceId INT) BEGIN /** * Factura los tickets de un cliente hasta una fecha dada - * @param vClientFk Id del cliente a facturar + * @param vClientFk Id del cliente a facturar * @param vSerial Serie de factura * @param vMaxShipped Fecha hasta la cual cogera tickets para facturar * @param vCompanyFk Id de la empresa desde la que se factura @@ -59080,11 +59081,11 @@ BEGIN IF NOT vIsRefEditable THEN CALL util.throw('serial non editable'); END IF; - END IF; + END IF; SELECT COUNT(*) INTO vIsExportation FROM vn.invoiceOutSerial - WHERE taxAreaFk = 'WORLD' + WHERE taxAreaFk = 'WORLD' AND `code` = vSerial; IF vIsExportation THEN @@ -59097,7 +59098,7 @@ BEGIN UPDATE invoiceOut SET `ref` = vRef - WHERE id = vInvoiceId + WHERE id = vInvoiceId AND vRef IS NOT NULL; IF vSerial <> 'R' AND NOT ISNULL(vInvoiceId) AND vInvoiceId <> 0 THEN @@ -59126,7 +59127,7 @@ BEGIN * Factura un ticket * @param vTicketFk Id del ticket * @param vSerial Serie de factura - * @param vTaxArea Area de la factura en caso de querer forzarlo, + * @param vTaxArea Area de la factura en caso de querer forzarlo, * en la mayoria de los casos poner NULL * @return vInvoiceId */ @@ -59141,11 +59142,11 @@ BEGIN IF NOT vIsRefEditable THEN CALL util.throw('serial non editable'); END IF; - - UPDATE invoiceOut + + UPDATE invoiceOut SET `ref` = vRef WHERE id = vInvoiceId; - END IF; + END IF; IF vSerial <> 'R' AND NOT ISNULL(vInvoiceId) AND vInvoiceId <> 0 THEN CALL invoiceOutBooking(vInvoiceId); @@ -59227,7 +59228,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `itemBarcode_update`(vItemFk INT,vCo BEGIN IF vDelete THEN DELETE FROM vn.itemBarcode WHERE itemFk = vItemFk AND code = vCode; -ELSE +ELSE INSERT INTO vn.itemBarcode(itemFk,code) VALUES (vItemFk,vCode); END IF; @@ -59249,8 +59250,8 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemFreight_Show`(vItemFk INT, vWarehouseFk INT) BEGIN - - SELECT cm3 Volumen_Entrada, + + SELECT cm3 Volumen_Entrada, cm3delivery Volumen_Salida, p.volume Volumen_del_embalaje, p.width Ancho_del_embalaje, @@ -59263,11 +59264,11 @@ BEGIN b.id buyFk, b.entryFk, w.name warehouseFk - FROM vn.itemCost ic - JOIN vn.item i ON i.id = ic.itemFk - LEFT JOIN cache.last_buy lb ON lb.item_id = ic.itemFk AND lb.warehouse_id = ic.warehouseFk - LEFT JOIN vn.buy b ON b.id = lb.buy_id - LEFT JOIN vn.packaging p ON p.id = b.packageFk + FROM vn.itemCost ic + JOIN vn.item i ON i.id = ic.itemFk + LEFT JOIN cache.last_buy lb ON lb.item_id = ic.itemFk AND lb.warehouse_id = ic.warehouseFk + LEFT JOIN vn.buy b ON b.id = lb.buy_id + LEFT JOIN vn.packaging p ON p.id = b.packageFk LEFT JOIN vn.warehouse w ON w.id = ic.warehouseFk WHERE ic.itemFk = vItemFk AND ic.warehouseFk = vWarehouseFk; @@ -59291,33 +59292,33 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `itemFuentesBalance`(vDaysInFuture I BEGIN /* Se utiliza para calcular la necesidad de mover mercancia entre el almacén de fuentes y el nuestro - * + * * @param vDaysInFuture Rango de dias para calcular entradas y salidas - * + * */ - + DECLARE vWarehouseFk INT; SELECT s.warehouseFk INTO vWarehouseFk - FROM vn.sector s + FROM vn.sector s WHERE s.code = 'FUENTES_PICASSE'; - + CALL cache.stock_refresh(FALSE); - SELECT i.id itemFk, + SELECT i.id itemFk, i.longName, i.size, i.subName, - v.amount - IFNULL(fue.Fuentes,0) - IFNULL(alb.albenfruit,0) as visible, - fue.Fuentes, + v.amount - IFNULL(fue.Fuentes,0) - IFNULL(alb.albenfruit,0) as visible, + fue.Fuentes, alb.Albenfruit, - sale.venta, - IFNULL(buy.compra,0) + IFNULL(mov.traslado,0) as compra, - IFNULL(v.amount,0) + IFNULL(sale.venta,0) + IFNULL(buy.compra,0) + IFNULL(mov.traslado,0) + sale.venta, + IFNULL(buy.compra,0) + IFNULL(mov.traslado,0) as compra, + IFNULL(v.amount,0) + IFNULL(sale.venta,0) + IFNULL(buy.compra,0) + IFNULL(mov.traslado,0) - IFNULL(fue.Fuentes,0) - IFNULL(alb.albenfruit,0) as saldo - FROM vn.item i - JOIN vn.itemType it ON it.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk + FROM vn.item i + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk LEFT JOIN ( SELECT ish.itemFk, CAST(SUM(ish.visible) AS DECIMAL(10,0)) AS Fuentes FROM vn.itemShelving ish @@ -59325,7 +59326,7 @@ BEGIN JOIN vn.parking p ON p.id = sh.parkingFk JOIN vn.sector s ON s.id = p.sectorFk WHERE s.code = 'FUENTES_PICASSE' - GROUP BY ish.itemFk + GROUP BY ish.itemFk ) fue ON fue.itemFk = i.id LEFT JOIN ( SELECT ish.itemFk, CAST(SUM(ish.visible) AS DECIMAL(10,0)) AS Albenfruit @@ -59334,7 +59335,7 @@ BEGIN JOIN vn.parking p ON p.id = sh.parkingFk JOIN vn.sector s ON s.id = p.sectorFk WHERE s.code = 'ALBENFRUIT' - GROUP BY ish.itemFk + GROUP BY ish.itemFk ) alb ON alb.itemFk = i.id LEFT JOIN cache.stock v ON i.id = v.item_id AND v.warehouse_id = vWarehouseFk LEFT JOIN ( @@ -59359,9 +59360,9 @@ BEGIN AND warehouse_id = vWarehouseFk GROUP BY item_id ) mov ON mov.item_id = i.id - WHERE (v.amount OR fue.Fuentes OR alb.Albenfruit) + WHERE (v.amount OR fue.Fuentes OR alb.Albenfruit) AND i.itemPackingTypeFk = 'H' - AND ic.shortLife + AND ic.shortLife ; END ;; @@ -59383,7 +59384,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemPlacementFromTicket`(vTicket INT) BEGIN /** - * Llama a itemPlacementUpdateVisible + * Llama a itemPlacementUpdateVisible * de los articulos de la tabla temporal tmp.itemPlacement(itemFk) * @treturn tmp.itemPlacement * @param vTicket Id del Ticket @@ -59397,9 +59398,9 @@ BEGIN FROM ticket t JOIN sale s ON s.ticketFk = t.id WHERE t.id = vTicket; - + CALL itemPlacementUpdateVisible(); - + DROP TEMPORARY TABLE tmp.itemPlacement; END ;; DELIMITER ; @@ -59432,7 +59433,7 @@ BEGIN CAST(FLOOR(LEAST(ish.stock,quantity) / ish.packing) AS DECIMAL(10,0)), ' x ', ish.packing, - IF ( + IF ( LEAST(ish.stock,quantity) MOD ish.packing, CONCAT(' + ',CAST(LEAST(ish.stock,quantity) MOD ish.packing AS DECIMAL(10,0))), '' @@ -59463,7 +59464,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemPlacementSupplyCloseOrder`(vId INT, vQuantity INT) BEGIN - UPDATE vn.itemPlacementSupply + UPDATE vn.itemPlacementSupply SET priority = 10 WHERE id = vId; @@ -59489,7 +59490,7 @@ BEGIN DECLARE vId INT; DECLARE vLastParkingFk INT; DECLARE vNextParkingFk INT; - + SELECT sh.parkingFk INTO vLastParkingFk FROM vn.itemShelvingPlacementSupply isps JOIN vn.itemShelving ish ON ish.id = isps.itemShelvingFk @@ -59497,9 +59498,9 @@ BEGIN WHERE isps.userFk = getUser() ORDER BY isps.created DESC LIMIT 1; - + SET vNextParkingFk = vn.itemShelvingPlacementSupply_ClosestGet(vLastParkingFk); - + SELECT ipsl.id INTO vId FROM vn.itemPlacementSupplyList ipsl JOIN vn.itemShelvingPlacementSupplyStock ispss ON ispss.itemFk = ipsl.itemFk @@ -59508,13 +59509,13 @@ BEGIN AND ipsl.sectorFk = vSector ORDER BY ipsl.repoUserFk DESC, ipsl.priority DESC, (ispss.parkingFk = vNextParkingFk) DESC, ispss.parking DESC, ipsl.created LIMIT 1; - + UPDATE vn.itemPlacementSupply SET repoUserFk = getUser() WHERE id = vId; - - SELECT * FROM vn.itemPlacementSupplyList - WHERE id = vId + + SELECT * FROM vn.itemPlacementSupplyList + WHERE id = vId AND sectorFk = vSector; END ;; @@ -59589,20 +59590,20 @@ BEGIN * @param vItemFk item id * @param vTicketFk ticket id * @param vShowType mostrar tipos - */ + */ DECLARE vWarehouseFk INT; DECLARE vShipped DATE; DECLARE vCalcFk INT; DECLARE vTypeFk INT; - - + + DECLARE vTag1 VARCHAR(25); DECLARE vTag5 VARCHAR(25); DECLARE vTag6 VARCHAR(25); DECLARE vTag7 VARCHAR(25); DECLARE vTag8 VARCHAR(25); - + DECLARE vValue1 VARCHAR(50); DECLARE vValue5 VARCHAR(50); DECLARE vValue6 VARCHAR(50); @@ -59612,16 +59613,16 @@ BEGIN SELECT warehouseFk, shipped INTO vWarehouseFk, vShipped FROM vn.ticket WHERE id = vTicketFk; - + SELECT typeFk, tag5, value5, tag6, value6, tag7, value7, tag8, value8, t1.name, it1.value INTO vTypeFk, vTag5, vValue5, vTag6, vValue6, vTag7, vValue7, vTag8, vValue8, vTag1, vValue1 FROM vn.item i LEFT JOIN vn.itemTag it1 ON it1.itemFk = i.id AND it1.priority = 1 LEFT JOIN vn.tag t1 ON t1.id = it1.tagFk WHERE i.id = vItemFk; - + CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, vShipped); - + SELECT i.id itemFk, i.longName, i.subName, @@ -59654,7 +59655,7 @@ BEGIN ORDER BY counter DESC, (t1.name = vTag1 COLLATE utf8_general_ci) DESC, (it1.value = vValue1 COLLATE utf8_general_ci) DESC, - (i.tag6 = vTag6 COLLATE utf8_general_ci) DESC, + (i.tag6 = vTag6 COLLATE utf8_general_ci) DESC, (i.value6 = vValue6 COLLATE utf8_general_ci) DESC, (i.tag5 = vTag5 COLLATE utf8_general_ci) DESC, (i.value5 = vValue5 COLLATE utf8_general_ci) DESC, @@ -59662,7 +59663,7 @@ BEGIN (i.value7 = vValue7 COLLATE utf8_general_ci) DESC, (i.tag8 = vTag8 COLLATE utf8_general_ci) DESC, (i.value8 = vValue8 COLLATE utf8_general_ci) DESC; - + END ;; DELIMITER ; @@ -59688,7 +59689,7 @@ BEGIN * @param vSaleFk id de la tabla sale * @param vMateFk articulo sustituto * @ param vQuantity cantidad que se va a sustituir - */ + */ DECLARE vTicketFk INT; DECLARE vItemFk INT; DECLARE vWarehouseFk SMALLINT; @@ -59697,41 +59698,41 @@ BEGIN DECLARE vBox INT; DECLARE vPacking INT; DECLARE vRoundQuantity INT DEFAULT 1; - + SELECT s.ticketFk, LEAST(s.quantity, vQuantity), s.itemFk,t.shipped,t.warehouseFk INTO vTicketFk, vQuantity, vItemFk,vDate,vWarehouseFk FROM vn.sale s JOIN vn.ticket t ON t.id = s.ticketFk WHERE s.id = vSaleFk; - + UPDATE vn.sale SET quantity = quantity - vQuantity WHERE id = vSaleFk; - + CALL vn.buyUltimate(vWarehouseFk, vDate); - + SELECT `grouping`, groupingMode, packing INTO vGrouping,vBox,vPacking FROM buy b JOIN tmp.buyUltimate tmp ON b.id = tmp.buyFk WHERE tmp.itemFk = vMateFk AND tmp.WarehouseFk = vWarehouseFk; - + IF vBox = 2 AND vPacking > 0 THEN SET vRoundQuantity = vPacking; END IF; IF vBox = 1 AND vGrouping > 0 THEN SET vRoundQuantity = vGrouping; END IF; - + INSERT INTO vn.sale(ticketFk, itemFk, quantity, concept) SELECT vTicketFk, vMateFk, CEIL(vQuantity / vRoundQuantity) * vRoundQuantity, CONCAT('+ ',i.longName) FROM vn.item i WHERE id = vMateFk; - + SELECT LAST_INSERT_ID() INTO vSaleFk; - + CALL vn.sale_calculateComponent(vSaleFk, NULL); - + INSERT INTO vn.itemProposal(itemFk, mateFk, counter) VALUES(vItemFk, vMateFk, 1) ON DUPLICATE KEY UPDATE counter = counter + 1; @@ -59760,13 +59761,13 @@ BEGIN DECLARE vCalcFk INT; DECLARE vTypeFk INT; DECLARE vResultsMax INT DEFAULT 10; - + DECLARE vTag1 VARCHAR(25); DECLARE vTag5 VARCHAR(25); DECLARE vTag6 VARCHAR(25); DECLARE vTag7 VARCHAR(25); DECLARE vTag8 VARCHAR(25); - + DECLARE vValue1 VARCHAR(50); DECLARE vValue5 VARCHAR(50); DECLARE vValue6 VARCHAR(50); @@ -59776,16 +59777,16 @@ BEGIN SELECT warehouseFk, shipped INTO vWarehouseFk, vShipped FROM vn.ticket WHERE id = vTicketFk; - + SELECT typeFk, tag5, value5, tag6, value6, tag7, value7, tag8, value8, t1.name, it1.value INTO vTypeFk, vTag5, vValue5, vTag6, vValue6, vTag7, vValue7, vTag8, vValue8, vTag1, vValue1 - FROM vn.item i + FROM vn.item i LEFT JOIN vn.itemTag it1 ON it1.itemFk = i.id AND it1.priority = 1 LEFT JOIN vn.tag t1 ON t1.id = it1.tagFk WHERE i.id = vItemFk; - + CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, vShipped); - + SELECT i.id itemFk, i.longName, i.subName, @@ -59803,7 +59804,7 @@ BEGIN (i.value8 <=> vValue8 COLLATE utf8_general_ci) match8, a.available, IFNULL(ip.counter,0) counter - FROM vn.item i + FROM vn.item i JOIN cache.available a ON a.item_id = i.id LEFT JOIN vn.itemProposal ip ON ip.mateFk = i.id AND ip.itemFk = vItemFk LEFT JOIN vn.itemTag it1 ON it1.itemFk = i.id AND it1.priority = 1 @@ -59817,7 +59818,7 @@ BEGIN (it1.value = vValue1 COLLATE utf8_general_ci) DESC, (i.tag5 = vTag5 COLLATE utf8_general_ci) DESC, (i.value5 = vValue5 COLLATE utf8_general_ci) DESC, - (i.tag6 = vTag6 COLLATE utf8_general_ci) DESC, + (i.tag6 = vTag6 COLLATE utf8_general_ci) DESC, (i.value6 = vValue6 COLLATE utf8_general_ci) DESC, (i.tag7 = vTag7 COLLATE utf8_general_ci) DESC, (i.value7 = vValue7 COLLATE utf8_general_ci) DESC, @@ -59853,7 +59854,7 @@ BEGIN CREATE TEMPORARY TABLE tmp.item SELECT vItem id; - + CALL item_refreshTags(); DROP TEMPORARY TABLE tmp.item; @@ -59876,23 +59877,23 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemSale_byWeek`(vWeek INT, IN vYear INT, vItemFk INT, vWarehouseFk INT) BEGIN - + DECLARE vStarted DATE; DECLARE vEnded DATETIME; SELECT MIN(dated), util.dayEnd(MAX(dated)) INTO vStarted, vEnded - FROM `time` t + FROM `time` t WHERE CONCAT(vYear, LPAD(vWeek, 2, 0)) = t.period; SELECT t.shipped, w.name warehouse, - s.ticketFk, + s.ticketFk, t.nickname client, - am.name agencyName, + am.name agencyName, wk.code salesPerson, s.itemFk, - IFNULL(CONCAT(ig.longName,' ',ig.`size`,' ',ig.subName), s.concept) AS concept, - s.quantity, + IFNULL(CONCAT(ig.longName,' ',ig.`size`,' ',ig.subName), s.concept) AS concept, + s.quantity, s.price, s.priceFixed, s.discount, @@ -59902,15 +59903,15 @@ BEGIN wk.id salesPersonFk FROM sale s JOIN ticket t ON t.id = s.ticketFk - JOIN warehouse w ON w.id = t.warehouseFk + JOIN warehouse w ON w.id = t.warehouseFk JOIN address a ON a.id = t.addressFk LEFT JOIN agencyMode am ON am.id = t.agencyModeFk JOIN `client` c ON c.id = a.clientFk - LEFT JOIN worker wk ON wk.id = c.salesPersonFk + LEFT JOIN worker wk ON wk.id = c.salesPersonFk LEFT JOIN ticketLastState tls ON tls.ticketFk = t.id - LEFT JOIN saleBuy sb ON sb.saleFk = s.id - LEFT JOIN buy b ON b.id = sb.buyFk - LEFT JOIN item ig ON ig.id = b.itemOriginalFk + LEFT JOIN saleBuy sb ON sb.saleFk = s.id + LEFT JOIN buy b ON b.id = sb.buyFk + LEFT JOIN item ig ON ig.id = b.itemOriginalFk WHERE s.itemFk = vItemFk AND t.shipped BETWEEN vStarted AND vEnded AND IF(vWarehouseFk = 0, w.hasComission , t.warehouseFk = vWarehouseFk) @@ -59937,9 +59938,9 @@ BEGIN DECLARE vItemFk INT; SELECT vn.barcodeToItem(vBarcode) INTO vItemFk; - + UPDATE vn.item SET minimum = min WHERE id = vItemFk; - + END ;; @@ -59961,8 +59962,8 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemSearchShelving`(`vShelvingFk` VARCHAR(3)) BEGIN SELECT p.`column` AS col , p.`row` - FROM vn.shelving s - JOIN parking p ON s.parkingFk = p.id + FROM vn.shelving s + JOIN parking p ON s.parkingFk = p.id WHERE s.`code` = vShelvingFk COLLATE utf8_general_ci; END ;; DELIMITER ; @@ -60003,36 +60004,36 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingLog_get`(vShelvingFk VARCHAR(10) ) BEGIN - + /** * Devuelve el log de los item en cada carro * - * @param vShelvingFk Matrícula del carro - * + * @param vShelvingFk Matrícula del carro + * */ - - SELECT isl.itemShelvingFk, - isl.created, - isl.accion, - isl.itemFk, - isl.shelvingFk, - isl.quantity, + + SELECT isl.itemShelvingFk, + isl.created, + isl.accion, + isl.itemFk, + isl.shelvingFk, + isl.quantity, isl.visible, - isl.available, - isl.grouping, - isl.packing, - isl.stars, - item.longName, - item.size, - item.subName, - worker.code, + isl.available, + isl.grouping, + isl.packing, + isl.stars, + item.longName, + item.size, + item.subName, + worker.code, isl.accion - FROM item - JOIN itemShelvingLog isl ON item.id = isl.itemFk + FROM item + JOIN itemShelvingLog isl ON item.id = isl.itemFk JOIN worker ON isl.workerFk = worker.id WHERE shelvingFk = vShelvingFk OR isl.itemFk = vShelvingFk ORDER BY isl.created DESC; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60051,7 +60052,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingMakeFromDate`(IN `vShelvingFk` VARCHAR(8), IN `vBarcode` VARCHAR(22), IN `vQuantity` INT, IN `vPackagingFk` VARCHAR(10), IN `vGrouping` INT, IN `vPacking` INT, IN `vWarehouseFk` INT, `vCreated` VARCHAR(22)) BEGIN - + DECLARE vItemFk INT; SELECT vn.barcodeToItem(vBarcode) INTO vItemFk; @@ -60070,9 +60071,9 @@ BEGIN END IF; - IF (SELECT COUNT(*) FROM vn.itemShelving - WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk - AND itemFk = vItemFk + IF (SELECT COUNT(*) FROM vn.itemShelving + WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk + AND itemFk = vItemFk AND packing = vPacking) = 1 THEN UPDATE vn.itemShelving @@ -60102,8 +60103,8 @@ BEGIN LEFT JOIN cache.last_buy lb ON i.id = lb.item_id AND lb.warehouse_id = vWarehouseFk LEFT JOIN vn.buy b ON b.id = lb.buy_id WHERE i.id = vItemFk; - END IF; - + END IF; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60124,9 +60125,9 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingMatch`(vEntryFk INT, vA BEGIN DECLARE vTravelFk INT; - - SELECT travelFk INTO vTravelFk - FROM entry + + SELECT travelFk INTO vTravelFk + FROM entry WHERE id = vEntryFk; SELECT i.id, i.longName, i.size, i.subName, b.stickers, ish.etiquetas, b.printed @@ -60139,7 +60140,7 @@ BEGIN GROUP BY itemFk ) b ON b.itemFk = i.id LEFT JOIN ( - SELECT itemFk, sum(cast(visible / packing AS DECIMAL(10,0))) AS etiquetas + SELECT itemFk, sum(cast(visible / packing AS DECIMAL(10,0))) AS etiquetas FROM itemShelving ish JOIN shelving sh ON sh.code = ish.shelvingFk LEFT JOIN parking pk ON pk.id = sh.parkingFk @@ -60179,7 +60180,7 @@ BEGIN UPDATE vn.itemShelving SET visible = visible - vQuantity WHERE id = vItemShelvingFk; - + END ;; DELIMITER ; @@ -60202,47 +60203,47 @@ BEGIN DECLARE vVisibleCache INT; DECLARE vWarehouseFk INT; - + SELECT warehouseFk INTO vWarehouseFk FROM vn.sector WHERE id = vSectorFk; CALL cache.visible_refresh (vVisibleCache, FALSE, vWarehouseFk); - - SELECT t.id as ticketFk, - CAST(s.quantity AS DECIMAL(10,0)) as Cantidad, - s.itemFk, - s.concept, - v.visible - GREATEST(0,iss.visible) + IFNULL(sub3.transit,0) as Nicho, + + SELECT t.id as ticketFk, + CAST(s.quantity AS DECIMAL(10,0)) as Cantidad, + s.itemFk, + s.concept, + v.visible - GREATEST(0,iss.visible) + IFNULL(sub3.transit,0) as Nicho, i.subName, - GREATEST(0,iss.visible - IFNULL(sub3.transit,0)) as Altillo, + GREATEST(0,iss.visible - IFNULL(sub3.transit,0)) as Altillo, s.id as saleFk, IFNULL(sub3.transit,0) transit, v.visible, s.isPicked, s.reserved, t.shipped, tst.productionOrder, mm.Id_Movimiento - FROM vn.ticket t + FROM vn.ticket t JOIN vn.ticketState tst ON tst.ticketFk = t.id JOIN vn.sale s ON s.ticketFk = t.id JOIN vn.item i ON i.id = s.itemFk JOIN cache.visible v ON s.itemFk = v.item_id AND v.calc_id = vVisibleCache LEFT JOIN vn2008.Movimientos_mark mm ON mm.Id_Movimiento = s.id AND mm.stateFk = 26 - JOIN vn.itemShelvingStock iss ON iss.itemFk = v.item_id + JOIN vn.itemShelvingStock iss ON iss.itemFk = v.item_id LEFT JOIN - (SELECT itemFk, sum(saldo) as transit - FROM vn.itemPlacementSupplyList - WHERE saldo > 0 + (SELECT itemFk, sum(saldo) as transit + FROM vn.itemPlacementSupplyList + WHERE saldo > 0 AND sectorFk = vSectorFk GROUP BY itemFk) sub3 ON sub3.itemFk = i.id - WHERE v.visible + IFNULL(sub3.transit,0) - GREATEST(0,iss.visible) < s.quantity + WHERE v.visible + IFNULL(sub3.transit,0) - GREATEST(0,iss.visible) < s.quantity AND IFNULL(sub3.transit,0) < s.quantity - AND s.isPicked = FALSE + AND s.isPicked = FALSE AND s.reserved = FALSE - AND t.shipped BETWEEN util.VN_CURDATE() AND MIDNIGHT(util.VN_CURDATE()) + AND t.shipped BETWEEN util.VN_CURDATE() AND MIDNIGHT(util.VN_CURDATE()) AND tst.isPreviousPreparable = TRUE AND t.warehouseFk = vWarehouseFk AND iss.sectorFk = vSectorFk AND mm.Id_Movimiento IS NULL ORDER BY itemFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60261,7 +60262,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingRadar`(vSectorFk INT) proc:BEGIN - + DECLARE vCalcVisibleFk INT; DECLARE vCalcAvailableFk INT; DECLARE hasFatherSector BOOLEAN; @@ -60269,17 +60270,17 @@ proc:BEGIN DECLARE vWarehouseFk INT DEFAULT 0; DECLARE vSonSectorFk INT; DECLARE vWorkerFk INT; - - SELECT s.workerFk - INTO vWorkerFk + + SELECT s.workerFk + INTO vWorkerFk FROM vn.sector s WHERE s.id = vSectorFk; SELECT w.id, s.warehouseFk INTO vBuyerFk, vWarehouseFk - FROM vn.worker w + FROM vn.worker w JOIN vn.sector s ON s.code = w.code WHERE s.id = vSectorFk; - + SELECT s.id INTO vSectorFk FROM vn.sector s WHERE s.warehouseFk = vWarehouseFk @@ -60289,21 +60290,21 @@ proc:BEGIN SELECT COUNT(*) INTO hasFatherSector FROM vn.sector WHERE sonFk = vSectorFk; - + SELECT warehouseFk, sonFk INTO vWarehouseFk, vSonSectorFk FROM vn.sector WHERE id = vSectorFk; - + CALL cache.visible_refresh(vCalcVisibleFk, TRUE, vWarehouseFk); CALL cache.available_refresh(vCalcAvailableFk, FALSE, vWarehouseFk, util.VN_CURDATE()); - + DROP TEMPORARY TABLE IF EXISTS tmp.itemShelvingRadar; - + IF hasFatherSector THEN CREATE TEMPORARY TABLE tmp.itemShelvingRadar (PRIMARY KEY (itemFk)) - ENGINE = MEMORY + ENGINE = MEMORY SELECT * FROM ( SELECT iss.itemFk, i.longName, @@ -60314,7 +60315,7 @@ proc:BEGIN SUM(IF(iss.sectorFk = vSectorFk, IFNULL(iss.visible,0), 0)) downstairs, IF(it.isPackaging, null, IFNULL(v.visible,0)) as visible, vSectorFk as sectorFk - + FROM vn.itemShelvingStock iss JOIN vn.sector s ON s.id = iss.sectorFk JOIN vn.item i on i.id = iss.itemFk @@ -60323,11 +60324,11 @@ proc:BEGIN LEFT JOIN cache.visible v ON v.item_id = iss.itemFk AND v.calc_id = vCalcVisibleFk WHERE vSectorFk IN (iss.sectorFk, s.sonFk) AND it.workerFk != 3366 - + GROUP BY iss.itemFk - + UNION ALL - + SELECT v.item_id, i.longName, i.size, @@ -60337,7 +60338,7 @@ proc:BEGIN 0 downstairs, IF(it.isPackaging, NULL, v.visible) visible, vSectorFk as sectorFk - FROM cache.visible v + FROM cache.visible v JOIN vn.item i on i.id = v.item_id JOIN vn.itemType it ON it.id = i.typeFk AND vBuyerFk IN (0,it.workerFk) LEFT JOIN vn.itemShelvingStock iss ON iss.itemFk = v.item_id AND iss.warehouseFk = vWarehouseFk @@ -60346,8 +60347,8 @@ proc:BEGIN AND iss.itemFk IS NULL AND it.isInventory ) sub GROUP BY itemFk; - - SELECT ishr.*, + + SELECT ishr.*, CAST(visible - upstairs - downstairs AS DECIMAL(10,0)) AS nicho, CAST(downstairs - IFNULL(notPickedYed,0) AS DECIMAL(10,0)) as pendiente FROM tmp.itemShelvingRadar ishr @@ -60362,13 +60363,13 @@ proc:BEGIN ) sub ON sub.itemFk = ishr.itemFk ORDER BY i.typeFk, i.longName ; - - + + ELSE - + CREATE TEMPORARY TABLE tmp.itemShelvingRadar (PRIMARY KEY (itemFk)) - ENGINE = MEMORY + ENGINE = MEMORY SELECT iss.itemFk, 0 `hour`, 0 `minute`, @@ -60380,7 +60381,7 @@ proc:BEGIN IFNULL(a.available,0) available, IFNULL(v.visible - iss.visible,0) dayEndVisible, IFNULL(v.visible - iss.visible,0) firstNegative, - IFNULL(v.visible - iss.visible,0) itemPlacementVisible, + IFNULL(v.visible - iss.visible,0) itemPlacementVisible, IFNULL(i.minimum * b.packing,0) itemPlacementSize, ips.onTheWay, iss.visible itemShelvingStock, @@ -60394,13 +60395,13 @@ proc:BEGIN LEFT JOIN cache.available a ON a.item_id = iss.itemFk AND a.calc_id = vCalcAvailableFk LEFT JOIN cache.visible v ON v.item_id = iss.itemFk AND v.calc_id = vCalcVisibleFk LEFT JOIN (SELECT itemFk, sum(saldo) as onTheWay - FROM vn.itemPlacementSupplyList - WHERE saldo > 0 + FROM vn.itemPlacementSupplyList + WHERE saldo > 0 GROUP BY itemFk ) ips ON ips.itemFk = i.id - WHERE IFNULL(iss.sectorFk,0) IN (0, vSectorFk) - OR iss.sectorFk = vSectorFk; - /* + WHERE IFNULL(iss.sectorFk,0) IN (0, vSectorFk) + OR iss.sectorFk = vSectorFk; + /* UPDATE tmp.itemShelvingRadar isr JOIN vn.itemShelvingStock iss ON iss.itemFk = isr.itemFk SET isr.dayEndVisible = isr.dayEndVisible + iss.visible, @@ -60411,10 +60412,10 @@ proc:BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.itemOutTime; CREATE TEMPORARY TABLE tmp.itemOutTime SELECT *,SUM(amount) quantity - FROM + FROM (SELECT item_id itemFk, - amount, - IF(HOUR(t.shipped), HOUR(t.shipped), HOUR(z.`hour`)) as hours, + amount, + IF(HOUR(t.shipped), HOUR(t.shipped), HOUR(z.`hour`)) as hours, IF(MINUTE(t.shipped), MINUTE(t.shipped), MINUTE(z.`hour`)) as minutes FROM vn2008.item_out io JOIN tmp.itemShelvingRadar isr ON isr.itemFk = io.item_id @@ -60422,23 +60423,23 @@ proc:BEGIN JOIN vn.ticketState ts on ts.ticketFk = io.ticketFk JOIN vn.state s ON s.id = ts.stateFk LEFT JOIN vn.zone z ON z.id = t.zoneFk - LEFT JOIN (SELECT DISTINCT saleFk - FROM vn.saleTracking st - WHERE st.created > util.VN_CURDATE() + LEFT JOIN (SELECT DISTINCT saleFk + FROM vn.saleTracking st + WHERE st.created > util.VN_CURDATE() AND st.isChecked ) stPrevious ON `stPrevious`.`saleFk` = io.saleFk WHERE t.warehouseFk = vWarehouseFk - AND s.isPicked = 0 - AND NOT io.Reservado + AND s.isPicked = 0 + AND NOT io.Reservado AND stPrevious.saleFk IS NULL - AND io.dat >= util.VN_CURDATE() + AND io.dat >= util.VN_CURDATE() AND io.dat < util.VN_CURDATE() + INTERVAL 1 DAY ) sub GROUP BY itemFk, hours, minutes; - + INSERT INTO tmp.itemShelvingRadar (itemFk) SELECT itemFk FROM tmp.itemOutTime - ON DUPLICATE KEY UPDATE dayEndVisible = dayEndVisible + quantity, + ON DUPLICATE KEY UPDATE dayEndVisible = dayEndVisible + quantity, firstNegative = if (firstNegative < 0, firstNegative, firstNegative + quantity), `hour` = ifnull(if (firstNegative > 0 , `hour`, hours),0), `minute` = ifnull(if (firstNegative > 0, `minute`, minutes),0); @@ -60454,7 +60455,7 @@ proc:BEGIN END IF; DROP TEMPORARY TABLE tmp.itemShelvingRadar; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60478,24 +60479,24 @@ BEGIN DECLARE vCalcVisibleFk INT; DECLARE vCalcAvailableFk INT; DECLARE vTodayDayEnd DATETIME DEFAULT util.dayEnd(util.VN_CURDATE()); - + CALL cache.visible_refresh(vCalcVisibleFk, FALSE, 1); CALL cache.available_refresh(vCalcAvailableFk, FALSE, vWarehouseFk, util.VN_CURDATE()); - + DROP TEMPORARY TABLE IF EXISTS tmp.item; CREATE TEMPORARY TABLE tmp.item ENGINE = MEMORY SELECT DISTINCT itemFk - FROM vn.buy + FROM vn.buy WHERE entryFk = vEntryFk; - + DROP TEMPORARY TABLE IF EXISTS tmp.item2; CREATE TEMPORARY TABLE tmp.item2 ENGINE = MEMORY SELECT * FROM tmp.item; - - SELECT i.id as itemFk, + + SELECT i.id as itemFk, i.minimum, CAST(IFNULL(v.visible,0) - IFNULL(iss.visible,0) AS DECIMAL(10,0)) as enNicho, CAST(IFNULL(a.available,0) AS DECIMAL(10,0)) as disponible, @@ -60515,11 +60516,11 @@ BEGIN AND IFNULL(tst.productionOrder,0) < 5 GROUP BY s.itemFK ) ts ON ts.itemFk = i.id; - - + + DROP TEMPORARY TABLE tmp.item; DROP TEMPORARY TABLE tmp.item2; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60543,34 +60544,34 @@ BEGIN DECLARE vCalcVisibleFk INT; DECLARE vCalcAvailableFk INT; DECLARE vTodayDayEnd DATETIME DEFAULT util.dayEnd(util.VN_CURDATE()); - + CALL cache.visible_refresh(vCalcVisibleFk, FALSE, 1); CALL cache.available_refresh(vCalcAvailableFk, FALSE, vWarehouseFk, util.VN_CURDATE()); - + DROP TEMPORARY TABLE IF EXISTS tmp.item; CREATE TEMPORARY TABLE tmp.item ENGINE = MEMORY SELECT DISTINCT itemFk - FROM vn.buy + FROM vn.buy WHERE entryFk = vEntryFk; - + DROP TEMPORARY TABLE IF EXISTS tmp.item2; CREATE TEMPORARY TABLE tmp.item2 ENGINE = MEMORY SELECT * FROM tmp.item; - - SELECT i.id as itemFk, + + SELECT i.id as itemFk, CAST(IFNULL(iss.visible,0) - IFNULL(v.visible,0) AS DECIMAL(10,0)) as outShelving FROM vn.item i JOIN tmp.item ti ON ti.itemFk = i.id LEFT JOIN cache.visible v ON v.calc_id = vCalcVisibleFk AND v.item_id = i.id LEFT JOIN vn.itemShelvingStock iss ON iss.itemFk = i.id; - - + + DROP TEMPORARY TABLE tmp.item; DROP TEMPORARY TABLE tmp.item2; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60591,10 +60592,10 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_Add`(vItemShelving BEGIN /** * Añade línea a itemShelvingSale y regulariza el carro - * + * * @param vItemShelvingFk Id itemShelving * @param vSaleFk Id de sale - * @param vQuantity cantidad a regularizar + * @param vQuantity cantidad a regularizar */ INSERT INTO itemShelvingSale(itemShelvingFk, saleFk, @@ -60689,7 +60690,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_add`(IN vShelvingFk VARCHAR(8), IN vBarcode VARCHAR(22), IN vQuantity INT, IN vPackagingFk VARCHAR(10), IN vGrouping INT, IN vPacking INT, IN vWarehouseFk INT) BEGIN - + /** * Añade registro o lo actualiza si ya existe. @@ -60701,7 +60702,7 @@ BEGIN * @param vGrouping el grouping del producto en itemShelving, NULL para coger el de la ultima compra * @param vPacking el packing del producto, NULL para coger el de la ultima compra * @param vWarehouseFk indica el sector - * + * **/ DECLARE vItemFk INT; @@ -60711,21 +60712,21 @@ BEGIN IF (SELECT COUNT(*) FROM shelving WHERE code = vShelvingFk COLLATE utf8_unicode_ci) = 0 THEN INSERT IGNORE INTO parking(code) VALUES(vShelvingFk); - INSERT INTO shelving(code, parkingFk) + INSERT INTO shelving(code, parkingFk) SELECT vShelvingFk, id - FROM parking + FROM parking WHERE `code` = vShelvingFk COLLATE utf8_unicode_ci; END IF; - IF (SELECT COUNT(*) FROM itemShelving - WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk - AND itemFk = vItemFk + IF (SELECT COUNT(*) FROM itemShelving + WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk + AND itemFk = vItemFk AND packing = vPacking) = 1 THEN UPDATE itemShelving SET visible = visible+vQuantity - WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk AND itemFk = vItemFk AND packing = vPacking; + WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk AND itemFk = vItemFk AND packing = vPacking; ELSE CALL cache.last_buy_refresh(FALSE); @@ -60870,7 +60871,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_BuyerGet`( ) BEGIN SELECT * FROM vn.buyer; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60897,10 +60898,10 @@ proc:BEGIN * @return Lista de articulos */ DECLARE vCalcVisibleFk INT; - + CALL cache.visible_refresh(vCalcVisibleFk, TRUE, vWarehouseFk); - SELECT * FROM + SELECT * FROM (SELECT sub.itemFk, sub.longName, CONCAT('Hoy saldrán ', CAST(sub2.pendiente AS DECIMAL(10,0)), ' unidades.') `size`, @@ -60917,28 +60918,28 @@ proc:BEGIN 0 upstairs, SUM(IFNULL(iss.visible,0)) downstairs, IF(it.isPackaging, null, IFNULL(v.visible, 0)) visible, - ik.name + ik.name FROM itemShelvingStock iss JOIN sector s ON s.id = iss.sectorFk JOIN item i on i.id = iss.itemFk - LEFT JOIN ink ik ON ik.id = i.inkFk + LEFT JOIN ink ik ON ik.id = i.inkFk JOIN itemType it ON it.id = i.typeFk LEFT JOIN cache.visible v ON v.item_id = iss.itemFk AND v.calc_id = vCalcVisibleFk WHERE s.warehouseFk = vWarehouseFk AND it.workerFk = vBuyerFk - GROUP BY itemFk + GROUP BY itemFk ) sub LEFT JOIN (SELECT s.itemFk, SUM(s.quantity) pendiente FROM sale s LEFT JOIN saleTracking st ON st.saleFk = s.id - JOIN ticket t ON t.id = s.ticketFk + JOIN ticket t ON t.id = s.ticketFk JOIN client c on c.id = t.clientFk JOIN clientType ct ON ct.id = c.clientTypeFk WHERE t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE()) AND st.saleFk IS NULL AND ct.code IN ('normal', 'trust') GROUP BY s.itemFk - ) sub2 ON sub2.itemFk = sub.itemFk - UNION ALL + ) sub2 ON sub2.itemFk = sub.itemFk + UNION ALL SELECT v.item_id , i.longName, CONCAT('Hoy saldrán ', CAST(sub5.pendiente AS DECIMAL(10,0)), ' unidades.') `size`, @@ -60956,7 +60957,7 @@ proc:BEGIN LEFT JOIN (SELECT s.itemFk, SUM(s.quantity) pendiente FROM sale s LEFT JOIN saleTracking st ON st.saleFk = s.id - JOIN ticket t ON t.id = s.ticketFk + JOIN ticket t ON t.id = s.ticketFk JOIN client c on c.id = t.clientFk JOIN clientType ct ON ct.id = c.clientTypeFk WHERE t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE()) @@ -60989,12 +60990,12 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_get`(IN vSelf VARCHAR(8)) BEGIN /** -* Lista artículos de itemshelving +* Lista artículos de itemshelving * * @param vSelf matrícula del carro **/ - SELECT ish.itemFk item, - IFNULL(i.longName, CONCAT(i.name, ' ', i.size)) description, + SELECT ish.itemFk item, + IFNULL(i.longName, CONCAT(i.name, ' ', i.size)) description, ish.visible, CEIL(ish.visible/ish.packing) stickers, ish.packing, @@ -61032,7 +61033,7 @@ BEGIN * * @param vShelvingFk matricula del carro */ - SELECT is2.id,is2.shelvingFk , p.code, is2.itemFk , is2.visible, p.pickingOrder + SELECT is2.id,is2.shelvingFk , p.code, is2.itemFk , is2.visible, p.pickingOrder FROM itemShelving is2 JOIN shelving sh ON sh.code = is2.shelvingFk JOIN parking p ON p.id = sh.parkingFk @@ -61098,35 +61099,35 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_getSaleDate`(vShelvingFk VARCHAR(3)) BEGIN - + /* Devuelve la minima fecha en que se necesita cada producto en esa matricula. - * + * * @param vShelvingFk Matrícula del carro o pallet */ - + DECLARE vWarehouseFk INT; SELECT warehouseFk INTO vWarehouseFk FROM shelving s - JOIN parking p ON s.parkingFk = p.id + JOIN parking p ON s.parkingFk = p.id JOIN sector st ON st.id = p.sectorFk WHERE s.code = vShelvingFk COLLATE utf8_unicode_ci; - + DROP TEMPORARY TABLE IF EXISTS tmp.itemShelvingDistinct; CREATE TEMPORARY TABLE tmp.itemShelvingDistinct (PRIMARY KEY (itemFk)) ENGINE = MEMORY SELECT itemFk, SUM(visible) visible - FROM vn.itemShelving + FROM vn.itemShelving WHERE shelvingFk = vShelvingFk COLLATE utf8_unicode_ci - GROUP BY itemFk; - + GROUP BY itemFk; + DROP TEMPORARY TABLE IF EXISTS tmp.item; CREATE TEMPORARY TABLE tmp.item (PRIMARY KEY (itemFk)) ENGINE = MEMORY SELECT * FROM tmp.itemShelvingDistinct; - + DROP TEMPORARY TABLE IF EXISTS tmp.stockByDay; CREATE TEMPORARY TABLE tmp.stockByDay (index (itemFk, dated)) @@ -61137,16 +61138,16 @@ BEGIN FROM ( SELECT * FROM ( SELECT t2.* FROM ( - SELECT item_id itemFk, amount, util.VN_CURDATE() dated - FROM cache.stock + SELECT item_id itemFk, amount, util.VN_CURDATE() dated + FROM cache.stock WHERE warehouse_id = vWarehouseFk UNION ALL SELECT ish.itemFk, - sum(visible), util.VN_CURDATE() - FROM vn.itemShelving ish - JOIN shelving sh ON sh.code = ish.shelvingFk - JOIN parking p ON sh.parkingFk = p.id + FROM vn.itemShelving ish + JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN parking p ON sh.parkingFk = p.id JOIN sector s ON s.id = p.sectorFk - WHERE s.isReserve + WHERE s.isReserve GROUP BY ish.itemFk UNION ALL SELECT item_id, sum(iei.amount), dat @@ -61155,9 +61156,9 @@ BEGIN AND warehouse_id = vWarehouseFk AND isVirtualStock = FALSE GROUP BY item_id, dat - UNION ALL + UNION ALL SELECT item_id, sum(ieo.amount), dat - FROM vn2008.item_entry_out ieo + FROM vn2008.item_entry_out ieo WHERE dat >= util.VN_CURDATE() AND warehouse_id = vWarehouseFk GROUP BY item_id, dat @@ -61168,11 +61169,11 @@ BEGIN WHERE io.dat >= util.VN_CURDATE() AND io.warehouse_id = vWarehouseFk GROUP BY io.item_id, io.dat - ) t2 + ) t2 JOIN tmp.itemShelvingDistinct ish ON ish.itemFk = t2.itemFk) t order by t.itemFk, DATE(t.dated), t.amount DESC) t3; - - SELECT sbd.itemFk, i.longName, DATE(dated) dated, ish.visible amount, sbd.stock + + SELECT sbd.itemFk, i.longName, DATE(dated) dated, ish.visible amount, sbd.stock FROM tmp.stockByDay sbd JOIN vn.item i ON i.id = sbd.itemFk JOIN tmp.itemShelvingDistinct ish ON ish.itemFk = sbd.itemFk @@ -61275,15 +61276,15 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_selfConsumption`( - vShelvingFk VARCHAR(10) COLLATE utf8_general_ci, - vItemFk INT, + vShelvingFk VARCHAR(10) COLLATE utf8_general_ci, + vItemFk INT, vQuantity INT ) -BEGIN +BEGIN /** - * Leave the indicated amount on the shelf + * Leave the indicated amount on the shelf * and create a ticket with the difference. - * + * * @param vShelvingFk id of the shelf where the item is located. * @param vItemFk article of which the self-consumption ticket is to be created. * @param vQuantity amount that will stay on the shelf @@ -61327,10 +61328,10 @@ BEGIN END IF; SELECT SUM(visible), id INTO vVisible, vItemShelvingFk - FROM itemShelving + FROM itemShelving WHERE shelvingFk = vShelvingFk AND itemFk = vItemFk; - + IF vVisible IS NULL THEN CALL util.throw('The item is not on the shelf.'); END IF; @@ -61383,9 +61384,9 @@ BEGIN * @param vGrouping el grouping del producto en itemShelving */ UPDATE itemShelving - SET visible = vVisible, - packing = vPacking, - grouping = vGrouping + SET visible = vVisible, + packing = vPacking, + grouping = vGrouping WHERE id = vShelf; END ;; @@ -61407,7 +61408,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemTagMake`(vItemFk INT) BEGIN -/* * Crea los tags usando la tabla plantilla itemTag +/* * Crea los tags usando la tabla plantilla itemTag * y si no existe a partir de la ficha del artículo. * @param vItemFk El item al que se le añaden los tags */ @@ -61417,33 +61418,33 @@ BEGIN DECLARE vProducer VARCHAR(50); DECLARE vOrigin VARCHAR(20); DECLARE vTypeFk INTEGER; - - DELETE FROM itemTag + + DELETE FROM itemTag WHERE itemFk = vItemFk; - - SELECT typeFk INTO vTypeFk + + SELECT typeFk INTO vTypeFk FROM item WHERE id = vItemFk; - + INSERT INTO itemTag(itemFk, tagFk, value, priority) SELECT vItemFk, itt.tagFk, NULL, itt.priority FROM itemTag it LEFT JOIN itemTypeTag itt ON itt.itemTypeFk = vTypeFk WHERE it.itemFk = vItemFk; - + IF (SELECT COUNT(*) FROM itemTag WHERE itemFk = vItemFk LIMIT 1) = 0 THEN - SELECT ik.name, i.size, i.category, p.name, o.name + SELECT ik.name, i.size, i.category, p.name, o.name INTO vInk, vSize, vCategory, vProducer, vOrigin FROM item i LEFT JOIN ink ik ON ik.id = i.inkFk LEFT JOIN producer p ON p.id = i.producerFk AND p.isVisible LEFT JOIN origin o ON o.id = i.originFk WHERE i.id = vItemFk; - + INSERT IGNORE INTO itemTag(itemFk, tagFk, value, priority) VALUES(vItemFk, 1, vInk, 1); - + INSERT IGNORE INTO itemTag(itemFk, tagFk, value, priority) VALUES (vItemFk, 8, vSize, 2); @@ -61452,11 +61453,11 @@ BEGIN INSERT IGNORE INTO itemTag(itemFk, tagFk, value, priority) VALUES(vItemFk, 37, vProducer, 4); - + INSERT IGNORE INTO itemTag(itemFk, tagFk, value, priority) VALUES(vItemFk, 35, vOrigin, 5); END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -61477,12 +61478,12 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `itemTagReorder`(itemTypeFk INT) BEGIN SET @isTriggerDisabled = TRUE; - + -- No se puede usar temporary porque da error Error Code: 1137. No puedo reabrir tabla: 'i DROP TABLE IF EXISTS tmp.item; CREATE TABLE tmp.item SELECT DISTINCT i.id - FROM vn.item i + FROM vn.item i WHERE i.typeFk = itemTypeFk; UPDATE itemTag it @@ -61491,8 +61492,8 @@ BEGIN JOIN itemTypeTag itt ON itt.itemTypeFk = item.typeFk AND itt.tagFk = it.tagFk SET it.priority = itt.priority WHERE itt.itemTypeFk = itemTypeFk; - - CALL item_refreshTags(); + + CALL item_refreshTags(); SET @isTriggerDisabled = FALSE; @@ -61517,12 +61518,12 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `itemTagReorderByName`(vName VARCHAR BEGIN SET @isTriggerDisabled = TRUE; - + -- No se puede usar temporary porque da error Error Code: 1137. No puedo reabrir tabla: 'i DROP TABLE IF EXISTS tmp.item; CREATE TABLE tmp.item SELECT DISTINCT i.id - FROM vn.item i + FROM vn.item i WHERE i.`name` LIKE CONCAT(vName,'%'); UPDATE itemTag it @@ -61531,8 +61532,8 @@ BEGIN JOIN itemTypeTag itt ON itt.itemTypeFk = item.typeFk AND itt.tagFk = it.tagFk SET it.priority = itt.priority WHERE itt.itemTypeFk = itemTypeFk; - - CALL item_refreshTags(); + + CALL item_refreshTags(); SET @isTriggerDisabled = FALSE; @@ -61555,36 +61556,36 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemTag_replace`(vItemFromFk INT, vItemToFk INT, vPicture VARCHAR(100)) BEGIN - + /* Reemplaza los tags de un artículo por los de otro, así como su imagen - * + * * @param vItemFromFk id de vn.item con el artículo del que se toman los tags * @param vItemToFk id de vn.item con el artículo del que se toman los tags * @param vPicture imagen del artículo. Opcional. Si no se especifica, hereada la del vItemFromFk */ - DELETE FROM vn.itemTag + DELETE FROM vn.itemTag WHERE itemFk = vItemToFk; - + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) SELECT vItemToFk, tagFk, value, priority - FROM vn.itemTag + FROM vn.itemTag WHERE itemFk = vItemFromFk; - + IF ISNULL(vPicture) THEN - - SELECT image INTO vPicture - FROM vn.item + + SELECT image INTO vPicture + FROM vn.item WHERE id = vItemFromFk; - + END IF; - UPDATE vn.item i + UPDATE vn.item i SET i.image = vPicture WHERE i.id = vItemToFk; - + CALL vn.itemRefreshTags(vItemToFk); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -61609,9 +61610,9 @@ BEGIN SELECT DISTINCT id FROM vn.itemCategory WHERE merchandise <> FALSE; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN + DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN RESIGNAL; END; @@ -61622,45 +61623,45 @@ BEGIN INNER JOIN bs.ventas v ON v.Id_Movimiento = s.id WHERE v.fecha BETWEEN TIMESTAMPADD(DAY, - 7, util.VN_CURDATE()) AND util.VN_CURDATE() GROUP BY s.itemFk; - + DROP TABLE IF EXISTS tmp.topSeller; - CREATE TEMPORARY TABLE tmp.topSeller - ( + CREATE TEMPORARY TABLE tmp.topSeller + ( `id` int(11) NOT NULL DEFAULT '0', `typeFk` smallint(5) unsigned NOT NULL, `itemCategoryFk` int(10) unsigned NOT NULL, `total` bigint(21) NOT NULL DEFAULT '0' ) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; - + OPEN rs; read_loop: LOOP FETCH rs INTO vCategoryFk; - + IF vDone THEN LEAVE read_loop; END IF; - + INSERT INTO tmp.topSeller SELECT tsm.itemFk, tsm.typeFk, it.categoryFk, tsm.total FROM tmp.topSellerMin tsm INNER JOIN vn.itemType it ON it.id = tsm.typeFk WHERE it.categoryFk = vCategoryFk ORDER BY tsm.itemFk ,tsm.total DESC - LIMIT 5; + LIMIT 5; END LOOP; CLOSE rs; - + SELECT i.name ,i.id, i.image, i.typeFk, it.categoryFk AS itemCategoryFk, ic.name AS itemCategoryName, it.name AS itemTypeName, ts.total FROM tmp.topSeller ts INNER JOIN vn.item i ON i.id = ts.id INNER JOIN vn.itemType it ON it.id = ts.typeFk INNER JOIN vn.itemCategory ic ON ic.id = it.categoryFk; - + DROP TABLE IF EXISTS topSellerMin; DROP TABLE IF EXISTS tmp.topSeller; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -61770,7 +61771,7 @@ SET tag6 = t.name, value6 = it.value WHERE it.priority = 2 AND (vItem IS NULL OR vItem = it.itemFk); -UPDATE item i +UPDATE item i JOIN itemTag it ON it.itemFk = i.id JOIN tag t ON t.id = it.tagFk SET tag7 = t.name, value7 = it.value @@ -61803,7 +61804,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `item_cleanFloramondo`() BEGIN /** -* Elimina todos los items repetidos de floramondo +* Elimina todos los items repetidos de floramondo * y los sustituye por el que tiene menor id */ DECLARE vItemFrom INT; @@ -61869,7 +61870,7 @@ BEGIN AND i2.EmbalageCode <=> i.EmbalageCode AND i2.quality <=> i.quality JOIN ( - SELECT DISTINCT b.itemFk + SELECT DISTINCT b.itemFk FROM buy b JOIN item i ON i.id = b.itemFk WHERE i.isFloramondo @@ -61877,7 +61878,7 @@ BEGIN )sub2 ON sub2.itemFk = GREATEST(i.id, i2.id) WHERE i.isFloramondo AND i.id <> i2.id; - + DECLARE EXIT HANDLER FOR SQLEXCEPTION SET vDone = TRUE; BEGIN SET vDone = TRUE; @@ -62131,13 +62132,13 @@ BEGIN /** * @vItemFk item a buscar * @vWarehouseFk almacen donde buscar - * @vDate Si la fecha es null, muestra el histórico desde el inventario. + * @vDate Si la fecha es null, muestra el histórico desde el inventario. * Si la fecha no es null, muestra histórico desde la fecha pasada. */ DECLARE vDateInventory DATETIME; IF vDate IS NULL THEN - SELECT inventoried INTO vDateInventory + SELECT inventoried INTO vDateInventory FROM config; ELSE SELECT mockUtcTime INTO vDateInventory @@ -62163,7 +62164,7 @@ BEGIN inventorySupplierFk INT(10) ); - INSERT INTO tItemDiary + INSERT INTO tItemDiary SELECT tr.landed shipped, b.quantity `in`, NULL `out`, @@ -62184,14 +62185,14 @@ BEGIN JOIN entry e ON e.id = b.entryFk JOIN travel tr ON tr.id = e.travelFk JOIN supplier s ON s.id = e.supplierFk - JOIN state st ON st.`code` = IF( tr.landed < util.VN_CURDATE() + JOIN state st ON st.`code` = IF( tr.landed < util.VN_CURDATE() OR (util.VN_CURDATE() AND tr.isReceived), - 'DELIVERED', + 'DELIVERED', 'FREE') JOIN entryConfig ec WHERE tr.landed >= vDateInventory AND vWarehouseFk = tr.warehouseInFk - AND (s.id <> ec.inventorySupplierFk OR vDate IS NULL) + AND (s.id <> ec.inventorySupplierFk OR vDate IS NULL) AND b.itemFk = vItemFk AND e.isExcludedFromAvailable = FALSE AND e.isRaid = FALSE @@ -62217,14 +62218,14 @@ BEGIN JOIN travel tr ON tr.id = e.travelFk JOIN warehouse w ON w.id = tr.warehouseOutFk JOIN supplier s ON s.id = e.supplierFk - JOIN state st ON st.`code` = IF(tr.shipped < util.VN_CURDATE() + JOIN state st ON st.`code` = IF(tr.shipped < util.VN_CURDATE() OR (tr.shipped = util.VN_CURDATE() AND tr.isReceived), - 'DELIVERED', + 'DELIVERED', 'FREE') JOIN entryConfig ec WHERE tr.shipped >= vDateInventory AND vWarehouseFk = tr.warehouseOutFk - AND (s.id <> ec.inventorySupplierFk OR vDate IS NULL) + AND (s.id <> ec.inventorySupplierFk OR vDate IS NULL) AND b.itemFk = vItemFk AND e.isExcludedFromAvailable = FALSE AND w.isFeedStock = FALSE @@ -62253,12 +62254,12 @@ BEGIN JOIN client c ON c.id = t.clientFk JOIN clientType ct ON ct.id = c.clientTypeFk JOIN state st2 ON st2.`code` = IF(t.shipped < util.VN_CURDATE(), - 'DELIVERED', + 'DELIVERED', IF (t.shipped > util.dayEnd(util.VN_CURDATE()), 'FREE', IFNULL(ts.code, 'FREE'))) LEFT JOIN state stPrep ON stPrep.`code` = 'PREPARED' - LEFT JOIN saleTracking stk ON stk.saleFk = s.id + LEFT JOIN saleTracking stk ON stk.saleFk = s.id AND stk.stateFk = stPrep.id LEFT JOIN claimBeginning cb ON s.id = cb.saleFk WHERE t.shipped >= vDateInventory @@ -62274,7 +62275,7 @@ BEGIN `out` DESC; IF vDate IS NULL THEN - + SET @a := 0; SET @currentLineFk := 0; SET @shipped := ''; @@ -62289,9 +62290,9 @@ BEGIN `in` invalue, `out`, @a := @a + IFNULL(`in`, 0) - IFNULL(`out`, 0) balance, - @currentLineFk := IF (@shipped < util.VN_CURDATE() + @currentLineFk := IF (@shipped < util.VN_CURDATE() OR (@shipped = util.VN_CURDATE() AND (isPicked OR a.`code` >= 'ON_PREPARATION')), - lineFk, + lineFk, @currentLineFk) lastPreparedLineFk, isTicket, lineFk, @@ -62323,25 +62324,25 @@ BEGIN 0 clientType, 0 claimFk UNION ALL - SELECT shipped, - alertlevel, - stateName, - origin, - reference, - clientFk, - name, `in`, - `out`, - @a := @a + IFNULL(`in`, 0) - IFNULL(`out`, 0), - 0, - isTicket, - lineFk, - isPicked, - clientType, + SELECT shipped, + alertlevel, + stateName, + origin, + reference, + clientFk, + name, `in`, + `out`, + @a := @a + IFNULL(`in`, 0) - IFNULL(`out`, 0), + 0, + isTicket, + lineFk, + isPicked, + clientType, claimFk FROM tItemDiary WHERE shipped >= vDate; END IF; - + DROP TEMPORARY TABLE tItemDiary; END ;; DELIMITER ; @@ -62448,7 +62449,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getLack`(IN vForce BOOLEAN, IN BEGIN /** * Calcula una tabla con el máximo negativo visible para cada producto y almacen - * + * * @param vForce Fuerza el recalculo del stock * @param vDays Numero de dias a considerar **/ @@ -62457,31 +62458,31 @@ BEGIN CALL item_getMinacum(NULL, util.VN_CURDATE(), vDays, NULL); CALL item_getMinETD(); - SELECT i.id itemFk, + SELECT i.id itemFk, i.longName, w.id warehouseFk, - p.`name` producer, + p.`name` producer, i.`size`, i.category, - w.name warehouse, + w.name warehouse, SUM(IFNULL(sub.amount,0)) lack, i.inkFk, - IFNULL(im.timed, util.midnight()) timed - FROM (SELECT item_id, - warehouse_id, + IFNULL(im.timed, util.midnight()) timed + FROM (SELECT item_id, + warehouse_id, amount FROM cache.stock WHERE amount > 0 UNION ALL - SELECT itemFk, - warehouseFk, + SELECT itemFk, + warehouseFk, amount FROM tmp.itemMinacum ) sub JOIN warehouse w ON w.id = sub.warehouse_id JOIN item i ON i.id = sub.item_id - LEFT JOIN producer p ON p.id = i.producerFk - JOIN itemType it ON it.id = i.typeFk + LEFT JOIN producer p ON p.id = i.producerFk + JOIN itemType it ON it.id = i.typeFk JOIN itemCategory ic ON ic.id = it.categoryFk LEFT JOIN tmp.itemMinETD im ON im.itemFk = i.id WHERE w.isForTicket @@ -62602,12 +62603,12 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getMinETD`() BEGIN - + /* Devuelve una tabla temporal con la primera ETD, para todos los artículos con salida hoy. - * + * * @return tmp.itemMinETD(itemFk, timed) */ - + DECLARE vMidnight DATETIME DEFAULT util.midnight(); DROP TEMPORARY TABLE IF EXISTS tmp.itemMinETD; @@ -62618,7 +62619,7 @@ BEGIN SELECT s.itemFk, MIN(TIME(IFNULL(z.`hour`,vMidnight))) timed FROM ticket t JOIN sale s ON s.ticketFk = t.id - LEFT JOIN `zone` z ON z.id = t.zoneFk + LEFT JOIN `zone` z ON z.id = t.zoneFk WHERE t.shipped BETWEEN util.VN_CURDATE() AND vMidnight GROUP BY s.itemFk; END ;; @@ -62648,33 +62649,33 @@ BEGIN * @param vWarehouseFk warehouse id * @param vDate fecha para revisar disponible * @param vIsShowedByType para mostrar solo artículos de ese tipo - */ + */ DECLARE vCalcFk INT; DECLARE vTypeFk INT; - + DECLARE vTag1 VARCHAR(25) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; DECLARE vTag5 VARCHAR(25) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; DECLARE vTag6 VARCHAR(25) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; DECLARE vTag7 VARCHAR(25) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; DECLARE vTag8 VARCHAR(25) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; - + DECLARE vValue1 VARCHAR(50) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; DECLARE vValue5 VARCHAR(50) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; DECLARE vValue6 VARCHAR(50) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; DECLARE vValue7 VARCHAR(50) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; DECLARE vValue8 VARCHAR(50) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; - + SELECT typeFk, tag5, value5, tag6, value6, tag7, value7, tag8, value8, t1.name, it1.value INTO vTypeFk, vTag5, vValue5, vTag6, vValue6, vTag7, vValue7, vTag8, vValue8, vTag1, vValue1 FROM vn.item i LEFT JOIN vn.itemTag it1 ON it1.itemFk = i.id AND it1.priority = 1 LEFT JOIN vn.tag t1 ON t1.id = it1.tagFk WHERE i.id = vItemFk; - + CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, vDate); - + SELECT i.id itemFk, i.longName, i.subName, @@ -62707,7 +62708,7 @@ BEGIN ORDER BY counter DESC, (t1.name = vTag1) DESC, (it1.value = vValue1) DESC, - (i.tag6 = vTag6) DESC, + (i.tag6 = vTag6) DESC, (i.value6 = vValue6) DESC, (i.tag5 = vTag5) DESC, (i.value5 = vValue5) DESC, @@ -62716,7 +62717,7 @@ BEGIN (i.tag8 = vTag8) DESC, (i.value8 = vValue8) DESC LIMIT 30; - + END ;; DELIMITER ; @@ -63001,11 +63002,11 @@ BEGIN * @param vBarcode del item * @param vReference referencia a actualizar */ - + DECLARE vItemFk INT; SELECT barcodeToItem(vBarcode) INTO vItemFk; - + UPDATE item SET comment = vReference WHERE id = vItemFk; END ;; @@ -63028,7 +63029,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `item_setGeneric`(vSelf INT) BEGIN /** * Asigna el código genérico a un item, salvo que sea un código de item genérico. - * + * * @param vSelf identificador de vn.item */ DECLARE vGenericFk INT; @@ -63038,7 +63039,7 @@ BEGIN SELECT itemFk, SUM(matches) = maxMatches `match` FROM ( SELECT ga.id gaid, ga.itemFk, - CASE + CASE WHEN t.code = 'nflowers' THEN it.value <=> ga.numFlores WHEN t.code = 'origin' THEN @@ -63069,13 +63070,13 @@ BEGIN AND (i.`size` = ga.`size` OR ga.`size` IS NULL) AND i.id != ga.itemFk WHERE i.id = vSelf - AND NOT i.isFloramondo) sub + AND NOT i.isFloramondo) sub GROUP BY gaid HAVING `match`) sub2 LIMIT 1; - UPDATE vn.item - SET genericFk = vGenericFk + UPDATE vn.item + SET genericFk = vGenericFk WHERE id = vSelf; END ;; DELIMITER ; @@ -63095,18 +63096,18 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `item_updatePackingShelve`(vSelf INT, vPacking INT) BEGIN - + /** * Actualiza el valor de item.packingShelve - * + * * @param vSelf Identificador de vn.item * @param vPacking Cantidad de unidades de venta que caben en una bandeja */ - - UPDATE vn.item i + + UPDATE vn.item i SET i.packingShelve = vPacking WHERE i.id = vSelf; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -63156,9 +63157,9 @@ BEGIN DECLARE vHasNotInventory BOOLEAN DEFAULT FALSE; DECLARE vInventoried2 DATE; DECLARE vDateDayEnd DATETIME; - + SET vDateDayEnd = util.dayEnd(vDated); - + SELECT landed INTO vInventoried FROM travel tr JOIN entry E ON E.travelFk = tr.id @@ -63168,7 +63169,7 @@ BEGIN LIMIT 1; SET vHasNotInventory = IF (vInventoried is null, TRUE, FALSE); - + IF vHasNotInventory THEN SELECT landed INTO vInventoried2 @@ -63189,13 +63190,13 @@ BEGIN CREATE TEMPORARY TABLE inv (warehouseFk SMALLINT, Id_Article BIGINT, - cantidad INT, + cantidad INT, coste DOUBLE DEFAULT 0, total DOUBLE DEFAULT 0, Almacen VARCHAR(20), PRIMARY KEY (Almacen, Id_Article) USING HASH) ENGINE = MEMORY; - + IF vHasNotInventory = TRUE THEN INSERT INTO inv(warehouseFk, Id_Article, cantidad, Almacen) @@ -63272,7 +63273,7 @@ BEGIN AND it.isInventory ON DUPLICATE KEY UPDATE inv.cantidad = inv.cantidad + s.quantity * IF(vHasNotInventory,0,1); - END IF; + END IF; -- Mercancia en transito INSERT INTO inv(warehouseFk, Id_Article, cantidad, Almacen) @@ -63290,7 +63291,7 @@ BEGIN AND t.isInventory AND e.isConfirmed ON DUPLICATE KEY UPDATE inv.cantidad = inv.cantidad + (b.quantity); - + CALL vn.buyUltimate(NULL,vDateDayEnd); UPDATE inv i @@ -63305,20 +63306,20 @@ BEGIN IF vIsDetailed THEN SELECT inv.warehouseFk, - i.id itemFk, - i.longName , - i.size, - inv.Cantidad, + i.id itemFk, + i.longName , + i.size, + inv.Cantidad, tp.name Tipo, - ic.name Reino, - inv.coste, + ic.name Reino, + inv.coste, cast(inv.total as decimal(10,2)) total, almacen FROM inv JOIN warehouse w on w.id = warehouseFk JOIN item i ON i.id = inv.Id_Article JOIN itemType tp ON tp.id = i.typeFk - JOIN itemCategory ic ON ic.id = tp.categoryFk + JOIN itemCategory ic ON ic.id = tp.categoryFk WHERE w.valuatedInventory and inv.total > 0 order by inv.total desc; @@ -63365,37 +63366,37 @@ BEGIN * @param vConcept descripcion * @param vAmount cantidad que se compensa * @param vCompany empresa - * @param vOriginalAccount cuenta contable desde la cual se compensa - * - */ + * @param vOriginalAccount cuenta contable desde la cual se compensa + * + */ DECLARE vNewBookEntry INT; DECLARE vIsClientCompensation INT; DECLARE vClientFk INT; DECLARE vSupplierFk INT; DECLARE vIsOriginalAClient BOOL; DECLARE vPayMethodCompensation INT; - + CALL ledger_next(vNewBookEntry); SELECT COUNT(id) INTO vIsOriginalAClient FROM client WHERE accountingAccount LIKE vOriginalAccount COLLATE utf8_general_ci; - SELECT id, COUNT(id) INTO vClientFk, vIsClientCompensation - FROM client + SELECT id, COUNT(id) INTO vClientFk, vIsClientCompensation + FROM client WHERE accountingAccount LIKE vCompensationAccount COLLATE utf8_general_ci; - + SET @vAmount1:= 0.0; SET @vAmount2:= 0.0; - INSERT INTO XDiario (ASIEN, FECHA, SUBCTA, CONTRA, CONCEPTO, EURODEBE, EUROHABER, empresa_id) - VALUES ( vNewBookEntry, - vDated, - vOriginalAccount, - vCompensationAccount, - vConcept, + INSERT INTO XDiario (ASIEN, FECHA, SUBCTA, CONTRA, CONCEPTO, EURODEBE, EUROHABER, empresa_id) + VALUES ( vNewBookEntry, + vDated, + vOriginalAccount, + vCompensationAccount, + vConcept, @vAmount1:= IF( - (vIsOriginalAClient AND vAmount > 0) OR - (NOT vIsOriginalAClient AND vAmount < 0), - 0, + (vIsOriginalAClient AND vAmount > 0) OR + (NOT vIsOriginalAClient AND vAmount < 0), + 0, ABS(vAmount) ), @vAmount2:= IF(@vAmount1, @@ -63404,20 +63405,20 @@ BEGIN ), vCompanyFk ), - ( vNewBookEntry, - vDated, - vCompensationAccount, - vOriginalAccount, - vConcept, + ( vNewBookEntry, + vDated, + vCompensationAccount, + vOriginalAccount, + vConcept, @vAmount2, @vAmount1, vCompanyFk); - + IF vIsClientCompensation THEN IF vIsOriginalAClient THEN SET vAmount = -vAmount; END IF; - INSERT INTO receipt(invoiceFk, amountPaid, payed, bankFk, companyFk, clientFk, isConciliate) + INSERT INTO receipt(invoiceFk, amountPaid, payed, bankFk, companyFk, clientFk, isConciliate) VALUES (vConcept, vAmount, vDated, vBankFk, vCompanyFk, vClientFk, TRUE); ELSE IF NOT vIsOriginalAClient THEN @@ -63425,7 +63426,7 @@ BEGIN END IF; SELECT id INTO vSupplierFk FROM supplier WHERE `account` LIKE vCompensationAccount COLLATE utf8_general_ci; SELECT id INTO vPayMethodCompensation FROM payMethod WHERE `code` = 'compensation'; - + INSERT INTO payment (received, dueDated, supplierFk, amount, bankFk, payMethodFk, concept, companyFk, isConciliated) VALUES(vDated, vDated, vSupplierFk, vAmount, vBankFk, vPayMethodCompensation, vConcept, vCompanyFk, TRUE); END IF; @@ -63447,10 +63448,10 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ledger_next`(OUT vNewBookEntry INT) BEGIN - + UPDATE vn.ledgerConfig SET lastBookEntry = LAST_INSERT_ID(lastBookEntry + 1); SET vNewBookEntry = LAST_INSERT_ID(); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -63476,15 +63477,15 @@ BEGIN * @param vEntity Nombre que hace referencia a la tabla. */ DECLARE vTableName VARCHAR(45); - + SET vTableName = CONCAT(vEntity, 'Log'); - + SET @qryLog := CONCAT( 'SELECT ot.id, ot.originFk, ot.userFk, u.name, ot.action, ot.creationDate, ot.description FROM ', vTableName, ' AS ot', ' INNER JOIN account.user u ON u.id = ot.userFk', ' WHERE ot.originFk = ', vOriginFk, ' ORDER BY ot.creationDate DESC' ); - + PREPARE stmt FROM @qryLog; EXECUTE stmt; END ;; @@ -63509,9 +63510,9 @@ BEGIN SET @buildingOrder := 0; SET @route := 0; set @cajas := 0; - + UPDATE tmp.sorter - SET buildingOrder = @buildingOrder := IF(@route = @route := routeFk, @buildingOrder, 0) + 1 + SET buildingOrder = @buildingOrder := IF(@route = @route := routeFk, @buildingOrder, 0) + 1 where date(created) = vDate order by routeFk, created, weight DESC; @@ -63529,23 +63530,23 @@ set @cajas := 0; UPDATE tmp.sorter SET lungGrow = IF(palletOrder = 0, -13, lungGrow); - + DELETE FROM tmp.lungSize WHERE dia = vDate; - + INSERT INTO tmp.lungSize(dia, hora,size) select vDate,hora, @cajas := @cajas + cajas as size from ( select IF(lungGrow BETWEEN -12 AND -1, ETD,time_format(created,"%H:%i")) as hora, sum(if(lungGrow <= 0, lungGrow, 1)) as cajas, @cajas := 0 - from tmp.sorter + from tmp.sorter where date(created) = vDate group by hora ) sub; - + SELECT * FROM tmp.lungSize WHERE dia = vDate; - - + + END ;; @@ -63566,23 +63567,23 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `machineWorker_add`(vPlate VARCHAR(10), vWorkerFk INT) BEGIN - + /** * Inserta registro si el vWorkerFk no ha registrado nada en las últimas 12 horas * @param vPlate número de matrícula - * @param vWorkerFk id del worker - * -*/ - UPDATE vn.machineWorker mw - JOIN vn.machine m ON m.id = mw.machineFk + * @param vWorkerFk id del worker + * +*/ + UPDATE vn.machineWorker mw + JOIN vn.machine m ON m.id = mw.machineFk SET mw.outTimed = util.VN_NOW() WHERE (mw.workerFk = vWorkerFk OR m.plate = vPlate) AND ISNULL(mw.outTimed); - + INSERT INTO machineWorker (machineFk, workerFk) SELECT m.id, vWorkerFk FROM machine m - WHERE m.plate= vPlate; + WHERE m.plate= vPlate; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -63602,21 +63603,21 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `machineWorker_getHistorical`(vPlate VARCHAR(20), vWorkerFk INT) BEGIN /** - * Obtiene historial de la matrícula vPlate que el trabajador vWorkerFk escanea, + * Obtiene historial de la matrícula vPlate que el trabajador vWorkerFk escanea, * si es jefe de producción muestra el historial completo. - * + * * @param vPlate número de matrícula - * @param vWorkerFk id del trabajador - * + * @param vWorkerFk id del trabajador + * */ DECLARE vWorkerName VARCHAR(255) DEFAULT account.user_getNameFromId(vWorkerFk); - SELECT mw.inTimed,account.user_getNameFromId(mw.workerFk) as workerName, mw.outTimed + SELECT mw.inTimed,account.user_getNameFromId(mw.workerFk) as workerName, mw.outTimed FROM machineWorker mw JOIN machine m ON m.plate = vPlate WHERE mw.machineFk = m.id AND mw.workerFk = IF(account.user_hasRole(vWorkerName, 'coolerAssist'), mw.workerFk, vWorkerFk) - ORDER BY mw.inTimed DESC; + ORDER BY mw.inTimed DESC; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -63635,13 +63636,13 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `machineWorker_update`(vPlate VARCHAR(10), vWorkerFk INT) BEGIN - + /** - * Actualiza el registro correspondiente si el vWorkerFk se ha registrado en las últimas horas (campo maxHours de machineWorkerConfig) con vPlate, - * + * Actualiza el registro correspondiente si el vWorkerFk se ha registrado en las últimas horas (campo maxHours de machineWorkerConfig) con vPlate, + * * @param vPlate número de matrícula - * @param vWorkerFk id del trabajador - * + * @param vWorkerFk id del trabajador + * */ DECLARE vMachineFk INT(10); @@ -63650,24 +63651,24 @@ BEGIN SELECT m.id INTO vMachineFk FROM machine m WHERE m.plate = vPlate; - + SELECT maxHours INTO vMaxHours FROM machineWorkerConfig; - IF (SELECT COUNT(*) + IF (SELECT COUNT(*) FROM machineWorker m WHERE m.workerFk = vWorkerFk - AND m.inTimed >= TIMESTAMPADD(HOUR , -vMaxHours, util.VN_NOW()) AND ISNULL(m.outTimed)) THEN - + AND m.inTimed >= TIMESTAMPADD(HOUR , -vMaxHours, util.VN_NOW()) AND ISNULL(m.outTimed)) THEN + UPDATE machineWorker m SET m.outTimed = CURRENT_TIMESTAMP() - WHERE m.workerFk = vWorkerFk - AND m.inTimed >= TIMESTAMPADD(HOUR , -vMaxHours, util.VN_NOW()) + WHERE m.workerFk = vWorkerFk + AND m.inTimed >= TIMESTAMPADD(HOUR , -vMaxHours, util.VN_NOW()) AND ISNULL(m.outTimed) AND m.machineFk = vMachineFk; - + END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -63722,12 +63723,12 @@ BEGIN /** * Inserta en la tabla vn.mail * - * @param vReceiver Receptor del correo + * @param vReceiver Receptor del correo * @param vReplyTo A quién contestar el correo * @param vSubject Título del correo * @param vBody Cuerpo del correo */ - + DECLARE vIsRepeated BOOLEAN; SELECT COUNT(*) INTO vIsRepeated @@ -63768,12 +63769,12 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `makeNewItem`() BEGIN DECLARE newItemFk INT; - + SELECT getNewItemId() INTO newItemFk; - + INSERT INTO item(id,name,typeFk,originFk) SELECT newItemFk, 'Nuevo artículo', 78,39; - + SELECT newItemFk; @@ -63801,34 +63802,34 @@ BEGIN DECLARE vMinute INT DEFAULT 0; DECLARE vBoxes INT; - + DROP TEMPORARY TABLE IF EXISTS vn.pcsDay; CREATE TEMPORARY TABLE vn.pcsDay SELECT 0 as hh, 0 as mm, 0 as boxes; - + -- Creamos una tabla soporte para acumular las cajas a lo largo del dia WHILE vHour < 24 DO - + WHILE vMinute < 59 DO - + SET vMinute = vMinute + 1; - + INSERT INTO vn.pcsDay(hh,mm) VALUES(vHour, vMinute); - + END WHILE; - + SET vMinute = -1; SET vHour = vHour + 1; - + END WHILE; - + -- Acumulamos UPDATE vn.pcsDay pd LEFT JOIN (SELECT * FROM vn.pcs_graf WHERE dia = vDated) pg USING(hh,mm) SET pd.boxes = pd.boxes + pg.box; - + SELECT * FROM vn.pcsDay; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -63851,7 +63852,7 @@ BEGIN * Recalcula el mana consumido por un trabajador * * @param vWorkerFk Id Trabajador - */ + */ DECLARE vWorkerIsExcluded BOOLEAN; DECLARE vFromDated DATE; DECLARE vToDated DATE DEFAULT TIMESTAMPADD(DAY,1,util.VN_CURDATE()); @@ -63860,32 +63861,32 @@ BEGIN DECLARE vClaimMana INT; DECLARE vManaBank INT; DECLARE vManaGreugeType INT; - + SELECT COUNT(*) INTO vWorkerIsExcluded FROM workerManaExcluded WHERE workerFk = vWorkerFk; - + IF NOT vWorkerIsExcluded THEN - SELECT id INTO vMana + SELECT id INTO vMana FROM `component` WHERE code = 'mana'; - - SELECT id INTO vAutoMana + + SELECT id INTO vAutoMana FROM `component` WHERE code = 'autoMana'; - - SELECT id INTO vClaimMana + + SELECT id INTO vClaimMana FROM `component` WHERE code = 'manaClaim'; - - SELECT id INTO vManaBank + + SELECT id INTO vManaBank FROM `bank` WHERE code = 'mana'; - - SELECT id INTO vManaGreugeType + + SELECT id INTO vManaGreugeType FROM `greugeType` WHERE code = 'mana'; - SELECT max(dated) INTO vFromDated + SELECT max(dated) INTO vFromDated FROM clientManaCache; - + REPLACE workerMana (workerFk, amount) - SELECT vWorkerFk, sum(mana) FROM + SELECT vWorkerFk, sum(mana) FROM ( SELECT s.quantity * sc.value as mana FROM ticket t @@ -63906,8 +63907,8 @@ BEGIN FROM greuge g JOIN client c ON c.id = g.clientFk WHERE c.salesPersonFk = vWorkerFk AND g.greugeTypeFk = vManaGreugeType - AND g.shipped > vFromDated and g.shipped < util.VN_CURDATE() - UNION ALL + AND g.shipped > vFromDated and g.shipped < util.VN_CURDATE() + UNION ALL SELECT cc.mana FROM clientManaCache cc JOIN client c ON c.id = cc.clientFk @@ -63934,20 +63935,20 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `mysqlConnectionsSorter_kill`() BEGIN /** - * Elimina conexiones del usuario sorter con tiempo >= 30seg. Asociado al evento con el mismo nombre - */ - + * Elimina conexiones del usuario sorter con tiempo >= 30seg. Asociado al evento con el mismo nombre + */ + DECLARE vDone INT DEFAULT 0; DECLARE vProcesId INT; DECLARE vCursor CURSOR FOR - SELECT p.id + SELECT p.id FROM information_schema.processlist p - WHERE USER = 'sorter' + WHERE USER = 'sorter' AND TIME >= 30; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + OPEN vCursor; l: LOOP @@ -63984,7 +63985,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `mysqlPreparedCount_check`() BEGIN DECLARE vPreparedCount INTEGER; - SELECT VARIABLE_VALUE INTO vPreparedCount + SELECT VARIABLE_VALUE INTO vPreparedCount FROM INFORMATION_SCHEMA.GLOBAL_STATUS WHERE VARIABLE_NAME LIKE '%prepared_stmt_count%'; @@ -63992,7 +63993,7 @@ BEGIN CALL `vn`.`mail_insert`('cau@verdnatura.es', NULL, 'Problemas BBDD prepared_stmt_count', - CONCAT('Existen problemas con el servicio de Logiflora, prepared_stmt_count con valor: ', + CONCAT('Existen problemas con el servicio de Logiflora, prepared_stmt_count con valor: ', vPreparedCount, ', está próximo a exceder su límite. \r\n Hay que reiniciar el servicio LF.VMP.Service del servidor a3.') ); @@ -64019,37 +64020,37 @@ BEGIN DECLARE newShelving VARCHAR(3); DECLARE vCode VARCHAR(3); - + SELECT MAX(code) INTO vCode FROM vn.shelving WHERE isPrinted = FALSE; - + SET @a1 := ASCII(MID(vCode,1,1)); SET @a2 := ASCII(MID(vCode,2,1)); SET @a3 := ASCII(MID(vCode,3,1)) + 1; - + IF @a3 > 90 THEN - + SET @a3 = 65; SET @a2 = @a2 + 1; - + IF @a2 > 90 THEN - + SET @a2 = 65; SET @a1 = @a1 + 1; - + IF @a1 > 90 THEN - + SET @a1 = 65; - + END IF; - + END IF; - + END IF; SET newShelving = CHAR(@a1,@a2,@a3 USING utf8); - + INSERT INTO vn.shelving(code) VALUES(newShelving); END ;; @@ -64078,18 +64079,18 @@ BEGIN * @param descripcion Texto de la observacion */ DECLARE vTableName VARCHAR(45); - + SET vTableName = CONCAT(vTableCode,'Observation'); - + IF ISNULL(vTableName) THEN CALL util.throw('CODE_NOT_FOUND'); END IF; - + SET @qryLog := CONCAT( 'INSERT INTO ', vTableName, ' (originFk, userFk, description)', ' VALUES (', vOriginFk, ', ', account.myUser_getId(), ', "', vDescription, '")' ); - + PREPARE stmt FROM @qryLog; EXECUTE stmt; DEALLOCATE PREPARE stmt; @@ -64119,15 +64120,15 @@ BEGIN DECLARE vDeliveryMethod INT; DECLARE vClient INT; - + SELECT deliveryMethodFk INTO vDeliveryMethod - FROM vn.agencyMode + FROM vn.agencyMode WHERE id = vAgencyMode; - + SELECT clientFk INTO vClient FROM vn.address WHERE id = vAddress; - + INSERT INTO hedera.order(date_send,customer_id,delivery_method_id,agency_id,address_id,source_app) VALUES( vLanded,vClient ,vDeliveryMethod,vAgencyMode ,vAddress ,vSourceApp); @@ -64153,7 +64154,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `orderDelete`(IN vId INT) BEGIN DELETE FROM hedera.`order` where id = vId; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -64180,7 +64181,7 @@ BEGIN DECLARE vOrderId INT; CALL vn.orderCreate(vLanded,vAgencyMode,vAddress,vSourceApp,vOrderId); SELECT vOrderId; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -64200,7 +64201,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `orderListVolume`(IN vOrderId INT) BEGIN - SELECT + SELECT o.id, o.itemFk, i.description, @@ -64226,7 +64227,7 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `packageInvoicing`( +CREATE DEFINER=`root`@`localhost` PROCEDURE `packageInvoicing`( IN vClient INT, IN vDate DATE, IN vCompany INT, @@ -64245,20 +64246,20 @@ BEGIN SET vGraceDays = IF(vIsAllInvoiceable ,0, 30); SET vGraceDate = TIMESTAMPADD(DAY, - vGraceDays, vDate); - - /* Clientes especiales: + + /* Clientes especiales: 3240 MADEFLOR 992 JAVIER FELIU 4 TONI VENDRELL */ - + IF vClient IN (992, 3240, 4) THEN - + SET vGraceDays = 365; - + END IF; /* Fin clientes especiales */ - + SET vDateEnd = DATE_ADD(vDate, INTERVAL 1 DAY); DROP TEMPORARY TABLE IF EXISTS tmp.packageToInvoice; @@ -64282,22 +64283,22 @@ BEGIN FROM tmp.packageToInvoice GROUP BY itemFk HAVING totalQuantity > 0; - + SELECT COUNT(*) INTO vIsInvoiceable FROM tmp.packageToInvoicePositives; IF vIsInvoiceable THEN - CALL ticket_add(vClient, + CALL ticket_add(vClient, vDateEnd, - vWarehouse, - vCompany, - NULL, - NULL, - NULL, - vDateEnd, - account.myUser_getId(), + vWarehouse, + vCompany, + NULL, + NULL, + NULL, + vDateEnd, + account.myUser_getId(), TRUE, vNewTicket); @@ -64306,44 +64307,44 @@ BEGIN packagingFk, quantity, pvp) - SELECT vNewTicket, - pti.packagingFk, - - SUM(pti.quantity) AS totalQuantity, + SELECT vNewTicket, + pti.packagingFk, + - SUM(pti.quantity) AS totalQuantity, pti.price FROM tmp.packageToInvoice pti - LEFT JOIN tmp.packageToInvoicePositives ptip ON pti.itemFk = ptip.itemFk - WHERE ptip.itemFK IS NOT NULL + LEFT JOIN tmp.packageToInvoicePositives ptip ON pti.itemFk = ptip.itemFk + WHERE ptip.itemFK IS NOT NULL OR vIsAllInvoiceable GROUP BY packagingFk HAVING totalQuantity; INSERT INTO sale( ticketFk, - itemFk, - concept, - quantity, + itemFk, + concept, + quantity, price ) - SELECT vNewTicket, - pti.itemFk, - i.name as concept, - sum(pti.quantity) as totalQuantity, + SELECT vNewTicket, + pti.itemFk, + i.name as concept, + sum(pti.quantity) as totalQuantity, pti.price FROM tmp.packageToInvoice pti JOIN item i ON i.id = pti.itemFk LEFT JOIN tmp.packageToInvoicePositives ptip ON pti.itemFk = ptip.itemFk - WHERE ptip.itemFK IS NOT NULL + WHERE ptip.itemFK IS NOT NULL OR vIsAllInvoiceable GROUP BY pti.itemFk HAVING totalQuantity; - + INSERT INTO saleComponent(saleFk, componentFk, value) SELECT id, vComponentCost, price FROM sale WHERE ticketFk = vNewTicket; - + END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -64369,7 +64370,7 @@ BEGIN WHERE mm.valor = 1 -- Listo para imprimir AND mm.stateFk = 9 -- Encajando AND m.Id_Ticket = ticketFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -64391,15 +64392,15 @@ BEGIN DECLARE valueFk INT; DECLARE encajando INT DEFAULT 9; - - SELECT valor INTO valueFk - FROM vn2008.Movimientos_mark - WHERE Id_Movimiento = saleFk + + SELECT valor INTO valueFk + FROM vn2008.Movimientos_mark + WHERE Id_Movimiento = saleFk AND stateFk = encajando; - + SET valueFk = (IFNULL(valueFk,0) + 1) MOD 3; - - REPLACE vn2008.Movimientos_mark(Id_Movimiento, valor, Id_Trabajador, stateFk) + + REPLACE vn2008.Movimientos_mark(Id_Movimiento, valor, Id_Trabajador, stateFk) VALUES(saleFk,valueFk,account.myUser_getId(),encajando); @@ -64491,34 +64492,34 @@ BEGIN DECLARE vLetters VARCHAR(26) DEFAULT 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; DECLARE vMaxId INT; DECLARE vCode VARCHAR(8); - + SET vColumn = vFromColumn; SET vRow = vFromRow; SET vCode = CONCAT(LPAD(vColumn,3,'0'),'-',IF(vIsLetterMode, MID(vLetters, vRow, 1), LPAD(vRow, 2,'0'))); - + SELECT MAX(id) INTO vMaxId FROM vn.parking; WHILE vColumn <= vToColumn DO - + WHILE vRow <= vToRow DO - + INSERT IGNORE INTO vn.parking(`column`, `row`, sectorFk, `code`, pickingOrder) VALUES (vColumn, vRow, vSectorFk, vCode, vColumn * 100 + vRow ) ON DUPLICATE KEY UPDATE `code` = vCode; - + SET vRow = vRow + 1; SET vCode = CONCAT(LPAD(vColumn,3,'0'),'-',IF(vIsLetterMode, MID(vLetters, vRow, 1), LPAD(vRow, 2,'0'))); - + END WHILE; - + SET vRow = vFromRow; SET vColumn = vColumn + 1; - + SET vCode = CONCAT(LPAD(vColumn,3,'0'),'-',IF(vIsLetterMode, MID(vLetters, vRow, 1), LPAD(vRow, 2,'0'))); - + END WHILE; - + SELECT * FROM vn.parking WHERE `column` BETWEEN vFromColumn AND vToColumn; END ;; @@ -64543,59 +64544,59 @@ BEGIN DECLARE vRow INT; DECLARE vCode VARCHAR(8); DECLARE i INT; - + IF vToRow < vFromRow THEN - + SET vRow = vFromRow; - + WHILE vRow >= vToRow DO - + SET i = 1; - + WHILE i <= vTrolleysByLine DO - + SET vCode = CONCAT(vLetter,'-', LPAD(vRow,2,'0'),'-', i); - + INSERT IGNORE INTO vn.parking( sectorFk, `code`, pickingOrder) VALUES (vSectorFk, vCode, vPickingOrder + (i * 10)) ON DUPLICATE KEY UPDATE `code` = vCode; - + SET i = i + 1; - + END WHILE; - + SET vRow = vRow - 1; - + END WHILE; ELSE - + SET vRow = vFromRow; - + WHILE vRow <= vToRow DO - + SET i = 1; - + WHILE i <= vTrolleysByLine DO - + SET vCode = CONCAT(vLetter,'-', LPAD(vRow,2,'0'),'-', i); - + INSERT IGNORE INTO vn.parking( sectorFk, `code`, pickingOrder) VALUES (vSectorFk, vCode, vPickingOrder + (i * 10) ) ON DUPLICATE KEY UPDATE `code` = vCode; - + SET i = i + 1; - + END WHILE; - + SET vRow = vRow + 1; - + END WHILE; - - + + END IF; - - + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -64619,28 +64620,28 @@ BEGIN DECLARE vColumn INT; DECLARE vLetters VARCHAR(200); DECLARE vLettersLength INT; - + SET vColumn = vStart; SET vRow = 1; SET vLetters = 'ABCDEF'; SET vLettersLength = LENGTH(vLetters); - + WHILE vColumn <= vEnd DO - + REPLACE vn.parking(`column`, `row`, `code`, sectorFk) VALUES(vColumn, vRow, CONCAT(vColumn,MID(vLetters,vRow,1)), vSectorFk); - + SET vRow = vRow + 1; - + IF vRow > vLettersLength THEN - + SET vRow = 1; SET vColumn = vColumn + 1; - + END IF; - + END WHILE; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -64659,11 +64660,11 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `parking_setOrder`(vWarehouseFk INT) BEGIN - + /* * Ordena el orden de preparacion de los parking de acuerdo con la tabla vn.corridor */ - + UPDATE vn.parking p JOIN ( SELECT code, @@ -64672,15 +64673,15 @@ BEGIN SELECT c.prepOrder, p.code, @orden := 0, - IF(c.isAscendent, 1,-1) * CAST(SUBSTRING(p.code,3,2) AS DECIMAL(2,0)) subCorridor , - CAST(IF(LENGTH(p.code) > 5, SUBSTRING(p.code,6,2), 0) AS DECIMAL(2,0)) ubication + IF(c.isAscendent, 1,-1) * CAST(SUBSTRING(p.code,3,2) AS DECIMAL(2,0)) subCorridor , + CAST(IF(LENGTH(p.code) > 5, SUBSTRING(p.code,6,2), 0) AS DECIMAL(2,0)) ubication FROM vn.parking p - JOIN vn.sector s ON s.id = p.sectorFk + JOIN vn.sector s ON s.id = p.sectorFk JOIN vn.corridor c ON c.code = LEFT(p.code,1) COLLATE utf8_general_ci - WHERE s.warehouseFk = vWarehouseFk) sub - ORDER BY sub.prepOrder, subCorridor, ubication) sub2 ON sub2.code = p.code + WHERE s.warehouseFk = vWarehouseFk) sub + ORDER BY sub.prepOrder, subCorridor, ubication) sub2 ON sub2.code = p.code SET p.pickingOrder = sub2.po; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -64699,17 +64700,17 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `prepareClientList`() BEGIN - + /* * Require la tabla tmp.ticket(id,clientFk) */ - + DROP TEMPORARY TABLE IF EXISTS tmp.client; CREATE TEMPORARY TABLE tmp.client (PRIMARY KEY (id)) ENGINE = MEMORY SELECT DISTINCT clientFk id - FROM tmp.ticket; + FROM tmp.ticket; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -64837,14 +64838,14 @@ BEGIN /** * Comprueba si la impresora pertenece al sector * - * @param vLabelerFk id de la impresora + * @param vLabelerFk id de la impresora * @param vSector sector a comprobar */ DECLARE isPrinterInNewSector BOOL; IF vLabelerFk IS NOT NULL THEN SELECT COUNT(sectorFK) INTO isPrinterInNewSector - FROM vn.printer p + FROM vn.printer p WHERE id = vLabelerFk AND sectorFk = vSector; IF !isPrinterInNewSector THEN @@ -64868,7 +64869,7 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `productionControl`( - vWarehouseFk INT, + vWarehouseFk INT, vScopeDays INT ) proc: BEGIN @@ -64969,7 +64970,7 @@ proc: BEGIN LEFT JOIN parking pk ON pk.id = tp.parkingFk WHERE t.warehouseFk = vWarehouseFk AND dm.code IN ('AGENCY', 'DELIVERY', 'PICKUP'); - + UPDATE tmp.productionBuffer pb JOIN ( SELECT pb.ticketFk, GROUP_CONCAT(p.code) previaParking @@ -64977,12 +64978,12 @@ proc: BEGIN JOIN sale s ON s.ticketFk = pb.ticketFk JOIN saleGroupDetail sgd ON sgd.saleFk = s.id JOIN saleGroup sg ON sg.id = sgd.saleGroupFk - JOIN parking p ON p.id = sg.parkingFk + JOIN parking p ON p.id = sg.parkingFk GROUP BY pb.ticketFk ) t ON t.ticketFk = pb.ticketFk SET pb.previaParking = t.previaParking; - -- Problemas por ticket + -- Problemas por ticket ALTER TABLE tmp.productionBuffer CHANGE COLUMN `problem` `problem` VARCHAR(255), ADD COLUMN `collectionH` INT, @@ -65263,7 +65264,7 @@ BEGIN `yearMonth` INT ) ENGINE = MEMORY; - + WHILE vDated <= vEnded DO INSERT INTO tmp.rangeDate SET `dated` = vDated, @@ -65273,7 +65274,7 @@ BEGIN `day` = DAY(vDated), `week` = WEEK(vDated, 1), `yearMonth` = YEAR(vDated) * 100 + MONTH(vDated); - + SET vDated = DATE_ADD(vDated, INTERVAL 1 DAY); END WHILE; END ;; @@ -65362,7 +65363,7 @@ BEGIN CALL cache.available_refresh(vCalc, FALSE, vWarehouseFk, vDate); DROP TEMPORARY TABLE IF EXISTS tmp.recipeCook; - + CREATE TEMPORARY TABLE tmp.recipeCook SELECT *, @counter := IF(@element = element COLLATE utf8_general_ci , @counter + 1, 1) as counter, @@ -65380,22 +65381,22 @@ BEGIN IFNULL((i.inkFk = r.inkFk ) ,0) + IFNULL((i.size = r.size) ,0) + IFNULL((i.name LIKE CONCAT('%',r.name,'%')) ,0) - + IFNULL((i.longName LIKE CONCAT('%',r.longName,'%')),0) + + IFNULL((i.longName LIKE CONCAT('%',r.longName,'%')),0) + IFNULL((i.typeFk = r.typeFk),0) as matches, i.typeFk, rl.previousSelected - FROM vn.recipe r + FROM vn.recipe r JOIN vn.item i ON (IFNULL(i.name LIKE CONCAT('%',r.name,'%'), 0) OR IFNULL(i.longName LIKE CONCAT('%',r.longName,'%'),0)) OR i.typeFk <=> r.typeFk JOIN cache.available a ON a.item_id = i.id AND a.calc_id = vCalc LEFT JOIN (SELECT recipe_ItemFk, element as log_element, selected_ItemFk, count(*) as previousSelected FROM vn.recipe_log - GROUP BY recipe_ItemFk, element, selected_ItemFk) rl ON rl.recipe_ItemFk = r.itemFk + GROUP BY recipe_ItemFk, element, selected_ItemFk) rl ON rl.recipe_ItemFk = r.itemFk AND rl.log_element = r.element AND rl.selected_ItemFk = i.id WHERE r.itemFk = vItemFk - AND a.available > vBunchesQuantity * r.quantity + AND a.available > vBunchesQuantity * r.quantity UNION ALL SELECT 100 itemFk, CONCAT('? ',r.element,' ',IFNULL(r.size,''),' ',IFNULL(r.inkFk,'')) as longName, @@ -65412,15 +65413,15 @@ BEGIN WHERE r.itemFk = vItemFk GROUP BY r.element ) sub - + ORDER BY element, matches DESC, previousSelected DESC; - - SELECT * + + SELECT * FROM tmp.recipeCook WHERE counter < 6 - OR itemFk = 100 + OR itemFk = 100 ; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -65445,71 +65446,71 @@ BEGIN DECLARE vShipped DATE; DECLARE vEntryFk INT; DECLARE vTravelFk INT; - + CALL cache.last_buy_refresh(FALSE); - - SELECT warehouseFk, shipped + + SELECT warehouseFk, shipped INTO vWarehouseFk, vShipped - FROM vn.ticket + FROM vn.ticket WHERE id = vTicketFk; UPDATE vn.ticket t JOIN vn.item i ON i.id = vItemFk SET t.nickname = CONCAT(vQuantity,' ',i.longName) WHERE t.id = vTicketFk; - + SELECT b.buyingValue INTO vLastCost FROM vn.buy b JOIN cache.last_buy lb ON lb.buy_id = b.id WHERE lb.item_id = vItemFk ORDER BY (lb.warehouse_id = vWarehouseFk) DESC LIMIT 1; - + INSERT INTO vn.sale(ticketFk, itemFk, quantity, concept, price) SELECT vTicketFk, 98, - vQuantity, i.longName, vLastCost FROM vn.item i WHERE i.id = vItemFk; - /* + /* SELECT tr.id INTO vTravelFk FROM vn.travel tr JOIN vn.warehouse w ON w.id = tr.warehouseOutFk WHERE tr.warehouseInFk = vWarehouseFk AND tr.landed = vShipped AND w.name = 'Confeccion'; - + IF IFNULL(vTravelFk,0) = 0 THEN - + INSERT INTO vn.travel(shipped, landed, warehouseInFk, warehouseOutFk, agencyFk) SELECT vShipped, vShipped, vWarehouseFk, w.id, am.id - FROM vn.warehouse w - JOIN vn.agencyMode am + FROM vn.warehouse w + JOIN vn.agencyMode am WHERE w.name = 'Confeccion' AND am.name = 'DIRECTO PROVEEDOR'; - + SET vTravelFk = LAST_INSERT_ID(); - - END IF; - + + END IF; + SELECT e.id INTO vEntryFk FROM vn.entry e JOIN vn.supplier s ON s.id = supplierFk WHERE e.travelFk = vTravelFk AND s.name = 'Confeccion Natural' AND e.isRaid = FALSE; - + IF IFNULL(vEntryFk,0) = 0 THEN - + INSERT INTO vn.entry(supplierFk, evaNotes, travelFk, companyFk) SELECT s.id, t.nickname, vTravelFk, c.id FROM vn.supplier s JOIN vn.ticket t ON t.id = vTicketFk - JOIN vn.company c ON c.code = 'VNL' + JOIN vn.company c ON c.code = 'VNL' WHERE s.name = 'Confeccion Natural'; - + SET vEntryFk = LAST_INSERT_ID(); - + END IF; - + INSERT INTO vn.buy(entryFk, itemFk, quantity, buyingValue, packageFk, packing, grouping) SELECT vEntryFk, b.itemFk, vQuantity, b.buyingValue, b.packageFk, b.packing, b.grouping FROM cache.last_buy lb @@ -65611,7 +65612,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `report_print`( ) BEGIN /** - * Inserts in the print queue the report to be printed and the necessary parameters for this + * Inserts in the print queue the report to be printed and the necessary parameters for this * one taking into account the paper size of both the printer and the report. * * @param vReportName the report to be printed. @@ -65654,11 +65655,11 @@ BEGIN END IF; IF vReportFk IS NULL THEN - CALL util.throw('reportNotExists'); + CALL util.throw('reportNotExists'); END IF; IF vReportSize <> vPrinteSize THEN - CALL util.throw('incorrectSize'); + CALL util.throw('incorrectSize'); END IF; START TRANSACTION; @@ -65667,7 +65668,7 @@ BEGIN priorityFk = vPriorityFk, reportFk = vReportFk, workerFk = vUserFk; - + SET vPrintQueueFk = LAST_INSERT_ID(); WHILE vI < vLength DO @@ -65700,16 +65701,16 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `riskAllClients`(maxRiskDate DATE) BEGIN - + DROP TEMPORARY TABLE IF EXISTS tmp.client_list; CREATE TEMPORARY TABLE tmp.client_list (PRIMARY KEY (Id_Cliente)) ENGINE = MEMORY SELECT id Id_Cliente, null grade FROM vn.client; - + CALL vn2008.risk_vs_client_list(maxRiskDate); - - SELECT + + SELECT c.RazonSocial, c.Id_Cliente, c.Credito, @@ -65721,7 +65722,7 @@ BEGIN JOIN tmp.risk r ON r.Id_Cliente = c.Id_Cliente JOIN tmp.client_list ci ON c.Id_Cliente = ci.Id_Cliente GROUP BY c.Id_cliente; - + DROP TEMPORARY TABLE IF EXISTS tmp.risk; DROP TEMPORARY TABLE IF EXISTS tmp.client_list; END ;; @@ -65780,25 +65781,25 @@ BEGIN DECLARE vM3 INT; DECLARE vKg INT; DECLARE vMatricula varchar(50); - + SELECT sum(packages) as bultos INTO vPackages - FROM vn.ticket t + FROM vn.ticket t WHERE routeFk = vRouteFk; - + SELECT SUM(sv.physicalVolume), SUM(sv.physicalWeight) INTO vM3, vKg FROM vn.saleVolume sv WHERE sv.routeFk = vRouteFk; - + SELECT v.numberPlate as matricula INTO vMatricula - FROM vn.route r + FROM vn.route r JOIN vn.vehicle v ON r.vehicleFk = v.id WHERE r.id = vRouteFk; - + SELECT vRouteFk as Ruta, - vPackages as Bultos, + vPackages as Bultos, vM3 as m3, vKg as Kg, vMatricula as Matricula; @@ -65863,7 +65864,7 @@ BEGIN ) sub ON sub.routeFk = rm.routeFk SET rm.ticketFree = sub.ticketFree; - UPDATE routesMonitor rm + UPDATE routesMonitor rm JOIN( SELECT t.routeFk, COUNT(*) AS ticketPacked FROM vn.ticket t @@ -65949,11 +65950,11 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `routeSetOk`( vRouteFk INT) BEGIN - + UPDATE vn.route r SET r.isOk = 1 WHERE r.id = vRouteFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -66018,17 +66019,17 @@ proc: BEGIN IF vIsFreelance THEN INSERT INTO routeCommission ( - routeFk, - workCenterFk, - freelanceYearlyM3, - cat4m3, + routeFk, + workCenterFk, + freelanceYearlyM3, + cat4m3, cat5m3 ) SELECT vSelf, r.commissionWorkCenterFk, rc.freelanceM3 * IF( - IFNULL(r.m3, 0) >= rc.freelanceMinM3, - IFNULL(r.m3, 0), + IFNULL(r.m3, 0) >= rc.freelanceMinM3, + IFNULL(r.m3, 0), 0), rc.distributionCat4M3 * IFNULL(r.m3, 0), rc.distributionCat5M3 * IFNULL(r.m3, 0) @@ -66040,20 +66041,20 @@ proc: BEGIN AND r.commissionWorkCenterFk; ELSE INSERT INTO routeCommission ( - routeFk, - workCenterFk, - km, - m3, - yearlyKm, - yearlyM3, - cat4m3, + routeFk, + workCenterFk, + km, + m3, + yearlyKm, + yearlyM3, + cat4m3, cat5m3 ) SELECT vSelf, r.commissionWorkCenterFk, - (r.kmEnd - r.kmStart) * + (r.kmEnd - r.kmStart) * IF(v.isKmTruckRate, rc.kmHeavy, rc.kmLight), - IFNULL(r.m3, 0) * + IFNULL(r.m3, 0) * IF(v.isKmTruckRate, rc.deliveryM3Cat5, rc.deliveryM3Cat4), (r.kmEnd - r.kmStart) * rc.kmYearly, IFNULL(r.m3, 0) * rc.m3Yearly, @@ -66090,7 +66091,7 @@ proc: BEGIN /** * Recalculates modified route. */ - + DECLARE vDone BOOL; DECLARE vRouteFk INT; @@ -66099,7 +66100,7 @@ proc: BEGIN DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + DECLARE CONTINUE HANDLER FOR SQLEXCEPTION BEGIN DO RELEASE_LOCK('vn.route_doRecalc'); @@ -66257,27 +66258,27 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `saleBuy_Add`(vSaleFk INT, vBuyFk INT) BEGIN - + /* Añade un registro a la tabla saleBuy en el caso de que sea posible mantener la trazabilidad - * + * * @param vSaleFk clave primaria de vn.sale * @param vBuyFk clave primaria de vn.buy */ - /*IF (SELECT COUNT(*) + /*IF (SELECT COUNT(*) FROM vn.sale s JOIN vn.item i ON i.id = s.itemFk - JOIN vn.itemType it ON it.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk WHERE s.id = vSaleFk AND ic.code = 'fruit') THEN */ - - IF (SELECT COUNT(*) FROM vn.buy WHERE id = vBuyFk AND itemOriginalFk) THEN - + + IF (SELECT COUNT(*) FROM vn.buy WHERE id = vBuyFk AND itemOriginalFk) THEN + INSERT INTO vn.saleBuy (saleFk, buyFk) VALUES(vSaleFk, vBuyFk); - + END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -66301,7 +66302,7 @@ BEGIN * * @param vSectorFk Identificador de vn.sector */ - INSERT INTO vn.saleGroup(userFk, sectorFk) + INSERT INTO vn.saleGroup(userFk, sectorFk) VALUES (account.myUser_getId(), vSectorFk); SELECT LAST_INSERT_ID(); @@ -66433,41 +66434,41 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sales_merge`(vTicketFk INT) -BEGIN - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - CREATE OR REPLACE TEMPORARY TABLE tSalesToPreserve - SELECT s.id, s.itemFk, SUM(s.quantity) newQuantity - FROM sale s - JOIN item i ON i.id = s.itemFk - JOIN itemType it ON it.id = i.typeFk - WHERE s.ticketFk = vTicketFk - AND it.isMergeable - GROUP BY s.itemFk, s.price, s.discount; - - START TRANSACTION; - - UPDATE sale s - JOIN tSalesToPreserve stp ON stp.id = s.id - SET quantity = newQuantity - WHERE s.ticketFk = vTicketFk; - - DELETE s.* - FROM sale s - LEFT JOIN tSalesToPreserve stp ON stp.id = s.id - JOIN item i ON i.id = s.itemFk - JOIN itemType it ON it.id = i.typeFk - WHERE s.ticketFk = vTicketFk - AND stp.id IS NULL - AND it.isMergeable; - - COMMIT; - - DROP TEMPORARY TABLE tSalesToPreserve; +BEGIN + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + CREATE OR REPLACE TEMPORARY TABLE tSalesToPreserve + SELECT s.id, s.itemFk, SUM(s.quantity) newQuantity + FROM sale s + JOIN item i ON i.id = s.itemFk + JOIN itemType it ON it.id = i.typeFk + WHERE s.ticketFk = vTicketFk + AND it.isMergeable + GROUP BY s.itemFk, s.price, s.discount; + + START TRANSACTION; + + UPDATE sale s + JOIN tSalesToPreserve stp ON stp.id = s.id + SET quantity = newQuantity + WHERE s.ticketFk = vTicketFk; + + DELETE s.* + FROM sale s + LEFT JOIN tSalesToPreserve stp ON stp.id = s.id + JOIN item i ON i.id = s.itemFk + JOIN itemType it ON it.id = i.typeFk + WHERE s.ticketFk = vTicketFk + AND stp.id IS NULL + AND it.isMergeable; + + COMMIT; + + DROP TEMPORARY TABLE tSalesToPreserve; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -66502,17 +66503,17 @@ BEGIN OPEN cCur; myLoop: LOOP - + SET vDone = FALSE; - + FETCH cCur INTO vTicketFk; IF vDone THEN LEAVE myLoop; END IF; - + CALL vn.sales_merge(vTicketFk); - + END LOOP; CLOSE cCur; @@ -66643,9 +66644,9 @@ BEGIN DELETE st.* FROM vn.saleTracking st JOIN vn.state s ON s.id = st.stateFk - WHERE st.saleFk = vSaleFk + WHERE st.saleFk = vSaleFk AND s.code = vState COLLATE utf8_unicode_ci; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -66662,12 +66663,12 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `saleTracking_new`( - vSaleFK INT, - vIsChecked BOOLEAN, - vOriginalQuantity INT, - vWorkerFk INT, - vAction VARCHAR(50), +CREATE DEFINER=`root`@`localhost` PROCEDURE `saleTracking_new`( + vSaleFK INT, + vIsChecked BOOLEAN, + vOriginalQuantity INT, + vWorkerFk INT, + vAction VARCHAR(50), vState VARCHAR(50), vIsScanned BOOLEAN) BEGIN @@ -66683,12 +66684,12 @@ BEGIN * @param vIsScanned Identificador si se ha escaneado automáticamente o manual */ - REPLACE vn.saleTracking(saleFk, - isChecked, - originalQuantity, - workerFk, + REPLACE vn.saleTracking(saleFk, + isChecked, + originalQuantity, + workerFk, stateFk, - isScanned) + isScanned) SELECT vSaleFK, vIsChecked, vOriginalQuantity, @@ -66715,27 +66716,27 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `saleTracking_updateIsChecked`(vSaleFK INT, vIsChecked BOOL, vIsScanned BOOL) BEGIN - + /** * Actualiza el estado del campo vn.saleTracking.isChecked y elimina las lineas de vn.itemShelving * si procede, en el caso de las preparaciones previas, por usuario - * + * * @param vSaleFk Identificador de vn.sale * @param vIsChecked Estado del registro */ - + UPDATE vn.saleTracking st JOIN vn.state s ON s.id = st.stateFk AND s.code = 'PREVIOUS_PREPARATION' SET st.isChecked = vIsChecked, st.isScanned = vIsScanned WHERE st.saleFk = vSaleFK AND st.workerFk = account.myUser_getId(); - + IF vIsChecked = FALSE THEN - - DELETE FROM vn.itemShelvingSale + + DELETE FROM vn.itemShelvingSale WHERE saleFk = vSaleFK; - + END IF; END ;; @@ -66761,14 +66762,14 @@ proc: BEGIN * * @param vSelf Id de la venta * @param vOption indica en que componente pone el descuadre, NULL en casos habituales - */ + */ CREATE OR REPLACE TEMPORARY TABLE tmp.recalculateSales SELECT s.id FROM sale s WHERE s.id = vSelf; - + CALL sale_recalcComponent(vOption); - + DROP TEMPORARY TABLE tmp.recalculateSales; END ;; DELIMITER ; @@ -66815,7 +66816,7 @@ BEGIN GROUP BY s.id; DECLARE CONTINUE HANDLER FOR NOT FOUND - SET v_done = TRUE; + SET v_done = TRUE; DROP TEMPORARY TABLE IF EXISTS tmp.coste; @@ -66823,7 +66824,7 @@ BEGIN CREATE TEMPORARY TABLE tmp.coste (PRIMARY KEY (id)) ENGINE = MEMORY SELECT s.id - FROM sale s + FROM sale s JOIN item i ON i.id = s.itemFk JOIN itemType tp ON tp.id = i.typeFk JOIN itemCategory ic ON ic.id = tp.categoryFk @@ -66842,17 +66843,17 @@ BEGIN IF v_done THEN LEAVE l; END IF; - + SELECT ticketFk, concept INTO vTicketFk, vConcept FROM sale WHERE id = vSaleFk; - + CALL sale_calculateComponent(vSaleFk, 1); END LOOP; CLOSE vCur; - DROP TEMPORARY TABLE tmp.coste; + DROP TEMPORARY TABLE tmp.coste; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -66938,7 +66939,7 @@ DECLARE vIsCollection BOOL; TRIM(CONCAT(LPAD(s.concept,30,' '), ' ', RPAD(IFNULL(i.size,''),5,' '))) line1, '' cel1, - TRIM(CONCAT(LPAD(IFNULL(ip.productor,''),30,' '), ' ',LPAD(IFNULL(o.code,''),4,' '))) line2, + TRIM(CONCAT(LPAD(IFNULL(ip.productor,''),30,' '), ' ',LPAD(IFNULL(o.code,''),4,' '))) line2, IF(s.quantity MOD IFNULL(b.packing,s.quantity + 1), CONCAT(CAST(s.quantity/IFNULL(b.`grouping`,1) AS DECIMAL(10,0)),' x ',IFNULL(b.`grouping`,1)), CONCAT(CAST(s.quantity / IFNULL(b.packing,1) AS DECIMAL(10,0)),' pack de ',IFNULL(b.packing,1))) cel2, @@ -66955,12 +66956,12 @@ DECLARE vIsCollection BOOL; JOIN sale s ON s.ticketFk = t.id JOIN ticket tt ON tt.id = t.id LEFT JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND lb.warehouse_id = tt.warehouseFk - LEFT JOIN buy b ON b.id = lb.buy_id + LEFT JOIN buy b ON b.id = lb.buy_id JOIN item i ON i.id = s.itemFk LEFT JOIN ticketCollection tc ON tc.ticketFk = t.id LEFT JOIN collection c ON c.id = tc.collectionFk - LEFT JOIN (SELECT sub.saleFk, sub.isChecked, sub.stateFk, sub.originalQuantity - FROM (SELECT DISTINCT st.id, st.saleFk, st.isChecked, st.stateFk, st.originalQuantity + LEFT JOIN (SELECT sub.saleFk, sub.isChecked, sub.stateFk, sub.originalQuantity + FROM (SELECT DISTINCT st.id, st.saleFk, st.isChecked, st.stateFk, st.originalQuantity FROM tmp.ticket2 t JOIN sale s ON s.ticketFk = t.id JOIN saleTracking st ON st.saleFk = s.id @@ -66972,7 +66973,7 @@ DECLARE vIsCollection BOOL; LEFT JOIN itemColor ic ON ic.itemFk = s.itemFk LEFT JOIN itemProductor ip ON ip.itemFk = s.itemFk LEFT JOIN origin o ON o.id = i.originFk - LEFT JOIN saleGroupDetail sgd ON sgd.saleFk = s.id + LEFT JOIN saleGroupDetail sgd ON sgd.saleFk = s.id LEFT JOIN saleGroup sg ON sg.id = sgd.saleGroupFk LEFT JOIN parking p ON p.id = sg.parkingFk LEFT JOIN saleMistake sm ON sm.saleFk = s.id @@ -67024,8 +67025,8 @@ BEGIN DELETE tt.* FROM tmp.sale_getProblems tt JOIN vn.ticketObservation tto ON tto.ticketFk = tt.ticketFk - JOIN vn.observationType ot ON ot.id = tto.observationTypeFk - WHERE ot.code = 'administrative' + JOIN vn.observationType ot ON ot.id = tto.observationTypeFk + WHERE ot.code = 'administrative' AND tto.description = 'Miriam'; CREATE OR REPLACE TEMPORARY TABLE tmp.sale_problems ( @@ -67057,7 +67058,7 @@ BEGIN -- Too Little INSERT INTO tmp.sale_problems(ticketFk, isTooLittle) - SELECT tp.ticketFk, TRUE + SELECT tp.ticketFk, TRUE FROM tmp.sale_getProblems tp JOIN vn.ticket t ON t.id = tp.ticketFk JOIN (SELECT t.addressFk, SUM(sv.litros) litros, t.totalWithoutVat @@ -67144,25 +67145,25 @@ BEGIN -- Disponible: no va a haber suficiente producto para preparar todos los pedidos CALL cache.available_refresh(vAvailableCache, FALSE, vWarehouseFk, vDate); - - -- Faltas: visible, disponible y ubicado son menores que la cantidad vendida + + -- Faltas: visible, disponible y ubicado son menores que la cantidad vendida CALL cache.visible_refresh(vVisibleCache, FALSE, vWarehouseFk); INSERT INTO tmp.sale_problems(ticketFk, itemShortage, saleFk) SELECT ticketFk, problem, saleFk FROM ( - SELECT tl.ticketFk, - LEFT(CONCAT('F: ',GROUP_CONCAT(i.id, ' ', i.longName, ' ')),250) problem, + SELECT tl.ticketFk, + LEFT(CONCAT('F: ',GROUP_CONCAT(i.id, ' ', i.longName, ' ')),250) problem, s.id AS saleFk FROM tmp.ticket_list tl JOIN vn.ticket t ON t.id = tl.ticketFk JOIN vn.sale s ON s.ticketFk = t.id JOIN vn.item i ON i.id = s.itemFk JOIN vn.itemType it on it.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk LEFT JOIN cache.visible v ON v.item_id = i.id AND v.calc_id = vVisibleCache LEFT JOIN cache.available av ON av.item_id = i.id AND av.calc_id = vAvailableCache - LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk + LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk WHERE IFNULL(v.visible,0) < s.quantity AND IFNULL(av.available ,0) < s.quantity AND IFNULL(issw.visible, 0) < s.quantity @@ -67175,7 +67176,7 @@ BEGIN AND t.warehouseFk = vWarehouseFk GROUP BY tl.ticketFk) sub ON DUPLICATE KEY UPDATE itemShortage = sub.problem, saleFk = sub.saleFk; - + -- Inventario: Visible suficiente, pero ubicado menor a la cantidad vendida INSERT INTO tmp.sale_problems(ticketFk, itemLost, saleFk) SELECT ticketFk, problem, saleFk @@ -67188,7 +67189,7 @@ BEGIN JOIN vn.itemType it on it.id = i.typeFk JOIN vn.itemCategory ic ON ic.id = it.categoryFk LEFT JOIN cache.visible v ON v.item_id = s.itemFk AND v.calc_id = vVisibleCache - LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk + LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk WHERE IFNULL(v.visible,0) >= s.quantity AND IFNULL(issw.visible, 0) < s.quantity AND s.quantity > 0 @@ -67201,7 +67202,7 @@ BEGIN AND t.warehouseFk = vWarehouseFk GROUP BY tl.ticketFk) sub ON DUPLICATE KEY UPDATE itemDelay = sub.problem, saleFk = sub.saleFk; - + -- Retraso: Disponible suficiente, pero no visible ni ubicado INSERT INTO tmp.sale_problems(ticketFk, itemDelay, saleFk) SELECT ticketFk, problem, saleFk @@ -67215,7 +67216,7 @@ BEGIN JOIN vn.itemCategory ic ON ic.id = it.categoryFk LEFT JOIN cache.visible v ON v.item_id = s.itemFk AND v.calc_id = vVisibleCache LEFT JOIN cache.available av ON av.item_id = i.id AND av.calc_id = vAvailableCache - LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk + LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk WHERE IFNULL(v.visible,0) < s.quantity AND IFNULL(av.available ,0) >= s.quantity AND IFNULL(issw.visible, 0) < s.quantity @@ -67235,13 +67236,13 @@ BEGIN INSERT INTO tmp.sale_problems(ticketFk, hasRounding, saleFk) SELECT ticketFk, problem, saleFk FROM ( - SELECT - tl.ticketFk, + SELECT + tl.ticketFk, s.id saleFk , - LEFT(GROUP_CONCAT('RE: ',i.id, ' ', IFNULL(i.longName,''), ' '), 250) problem, + LEFT(GROUP_CONCAT('RE: ',i.id, ' ', IFNULL(i.longName,''), ' '), 250) problem, MOD(s.quantity, b.`grouping`) hasRounding FROM tmp.ticket_list tl - JOIN ticket t ON t.id = tl.ticketFk + JOIN ticket t ON t.id = tl.ticketFk AND t.warehouseFk = vWarehouseFk JOIN sale s ON s.ticketFk = tl.ticketFk JOIN item i ON i.id = s.itemFk @@ -67249,12 +67250,12 @@ BEGIN JOIN buy b ON b.id = bu.buyFk GROUP BY tl.ticketFk HAVING hasRounding - ) sub + ) sub ON DUPLICATE KEY UPDATE hasRounding = sub.problem, saleFk = sub.saleFk; END LOOP; CLOSE vCursor; - + INSERT INTO tmp.sale_problems(ticketFk, isTaxDataChecked) SELECT DISTINCT tl.ticketFk, FALSE FROM tmp.ticket_list tl @@ -67284,16 +67285,16 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_getProblemsByTicket`(IN vTicketFk INT, IN vIsTodayRelative TINYINT(1)) BEGIN /** - * Calcula los problemas de cada venta + * Calcula los problemas de cada venta * para un conjunto de tickets. * * @return Problems result */ DROP TEMPORARY TABLE IF EXISTS tmp.sale_getProblems; - CREATE TEMPORARY TABLE tmp.sale_getProblems + CREATE TEMPORARY TABLE tmp.sale_getProblems (INDEX (ticketFk)) ENGINE = MEMORY - SELECT t.id ticketFk, t.clientFk, t.warehouseFk, t.shipped + SELECT t.id ticketFk, t.clientFk, t.warehouseFk, t.shipped FROM ticket t WHERE t.id = vTicketFk; @@ -67322,7 +67323,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_PriceFix`(vTicketFk INT) BEGIN - + DELETE sc.* FROM vn.saleComponent sc JOIN vn.sale s ON s.id = sc.saleFk @@ -67358,52 +67359,52 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_recalcComponent`(vOption INT) proc: BEGIN /** - * Este procedimiento recalcula los componentes de un conjunto de sales, + * Este procedimiento recalcula los componentes de un conjunto de sales, * eliminando los componentes existentes e insertandolos de nuevo * * @param vOption si no se quiere forzar llamar con NULL * @table tmp.recalculateSales (id) - */ - DECLARE vShipped DATE; + */ + DECLARE vShipped DATE; DECLARE vWarehouseFk SMALLINT; DECLARE vAgencyModeFk INT; DECLARE vAddressFk INT; DECLARE vTicketFk INT; - DECLARE vLanded DATE; + DECLARE vLanded DATE; DECLARE vIsEditable BOOLEAN; DECLARE vZoneFk INTEGER; DECLARE vDone BOOL DEFAULT FALSE; - + DECLARE vCur CURSOR FOR SELECT DISTINCT s.ticketFk FROM tmp.recalculateSales rs JOIN vn.sale s ON s.id = rs.id; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + OPEN vCur; l: LOOP SET vDone = FALSE; - FETCH vCur INTO vTicketFk; - + FETCH vCur INTO vTicketFk; + IF vDone THEN LEAVE l; END IF; - SELECT (hasToRecalcPrice OR ts.alertLevel IS NULL) AND t.refFk IS NULL, - t.zoneFk, - t.warehouseFk, - t.shipped, - t.addressFk, - t.agencyModeFk, + SELECT (hasToRecalcPrice OR ts.alertLevel IS NULL) AND t.refFk IS NULL, + t.zoneFk, + t.warehouseFk, + t.shipped, + t.addressFk, + t.agencyModeFk, t.landed - INTO vIsEditable, - vZoneFk, - vWarehouseFk, - vShipped, - vAddressFk, - vAgencyModeFk, + INTO vIsEditable, + vZoneFk, + vWarehouseFk, + vShipped, + vAddressFk, + vAgencyModeFk, vLanded FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket @@ -67411,31 +67412,31 @@ proc: BEGIN WHERE t.id = vTicketFk; CALL zone_getLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk, TRUE); - + IF NOT EXISTS (SELECT TRUE FROM tmp.zoneGetLanded LIMIT 1) THEN CALL util.throw(CONCAT('There is no zone for these parameters ', vTicketFk)); END IF; - + IF vLanded IS NULL OR vZoneFk IS NULL THEN - + UPDATE ticket t - SET t.landed = (SELECT landed FROM tmp.zoneGetLanded LIMIT 1) + SET t.landed = (SELECT landed FROM tmp.zoneGetLanded LIMIT 1) WHERE t.id = vTicketFk AND t.landed IS NULL; - + IF vZoneFk IS NULL THEN SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetLanded LIMIT 1; UPDATE ticket t SET t.zoneFk = vZoneFk WHERE t.id = vTicketFk AND t.zoneFk IS NULL; END IF; - + END IF; - + DROP TEMPORARY TABLE tmp.zoneGetLanded; - - -- rellena la tabla buyUltimate con la ultima compra - CALL buyUltimate (vWarehouseFk, vShipped); - + + -- rellena la tabla buyUltimate con la ultima compra + CALL buyUltimate (vWarehouseFk, vShipped); + CREATE OR REPLACE TEMPORARY TABLE tmp.sale (PRIMARY KEY (saleFk)) ENGINE = MEMORY SELECT s.id saleFk, vWarehouseFk warehouseFk @@ -67443,7 +67444,7 @@ proc: BEGIN JOIN tmp.recalculateSales rs ON s.id = rs.id WHERE s.ticketFk = vTicketFk; - CREATE OR REPLACE TEMPORARY TABLE tmp.ticketLot + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketLot SELECT vWarehouseFk warehouseFk, NULL available, s.itemFk, bu.buyFk, vZoneFk zoneFk FROM sale s JOIN tmp.recalculateSales rs ON s.id = rs.id @@ -67457,15 +67458,15 @@ proc: BEGIN IF vOption IS NULL THEN SET vOption = IF(vIsEditable, 1, 6); END IF; - - CALL ticketComponentUpdateSale(vOption); + + CALL ticketComponentUpdateSale(vOption); CALL catalog_componentPurge(); - + DROP TEMPORARY TABLE tmp.buyUltimate; DROP TEMPORARY TABLE tmp.sale; - + END LOOP; - CLOSE vCur; + CLOSE vCur; END ;; DELIMITER ; @@ -67486,22 +67487,22 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sectorCollectionSaleGroup_add`(vSaleGroupFk INT, vSectorCollectionFk INT) BEGIN /** - * Inserta un nuevo registro en vn.sectorCollectionSaleGroup + * Inserta un nuevo registro en vn.sectorCollectionSaleGroup * Actualiza el usuario en vn.saleGroup y reemplaza los registros de vn.saleTracking - * + * * @param vSaleGroupFk Identificador de vn.saleGroup * @param vSectorCollectionFk Identificador de vn.sectorCollection */ REPLACE sectorCollectionSaleGroup - SET sectorCollectionFk = vSectorCollectionFk, + SET sectorCollectionFk = vSectorCollectionFk, saleGroupFk = vSaleGroupFk; - + UPDATE saleGroup sg JOIN sectorCollectionSaleGroup scsg ON scsg.saleGroupFk = sg.id JOIN sectorCollection sc ON sc.id = scsg.sectorCollectionFk - SET sg.userFk = sc.userFk + SET sg.userFk = sc.userFk WHERE sg.id = vSaleGroupFk; - + INSERT IGNORE saleTracking( saleFk, isChecked, @@ -67513,8 +67514,8 @@ BEGIN sc.userFk, s.id FROM saleGroupDetail sgd - JOIN sectorCollectionSaleGroup scsg - ON scsg.saleGroupFk = sgd.saleGroupFk + JOIN sectorCollectionSaleGroup scsg + ON scsg.saleGroupFk = sgd.saleGroupFk JOIN sectorCollection sc ON sc.id = scsg.sectorCollectionFk JOIN state s ON s.code = 'PREVIOUS_PREPARATION' WHERE sgd.saleGroupFk = vSaleGroupFk; @@ -67615,30 +67616,30 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sectorCollection_new`(vSectorFk INT) -BEGIN -/** - * Inserta una nueva colección, si el usuario no tiene ninguna vacia. - * Esto se hace para evitar que por error se generen colecciones sin sentido. - * - * @param vSectorFk Identificador de #vn.sector - */ - DECLARE hasEmptyCollections BOOL; - DECLARE vUserFk INT; - - SET vUserFk = account.myUser_getId(); - - SELECT (COUNT(sc.id) > 0) INTO hasEmptyCollections - FROM vn.sectorCollection sc - LEFT JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id - WHERE ISNULL(scsg.id) - AND sc.userFk = vUserFk - AND sc.sectorFk = vSectorFk - AND sc.created >= util.VN_CURDATE(); - - IF NOT hasEmptyCollections THEN - INSERT INTO vn.sectorCollection(userFk, sectorFk) - VALUES(vUserFk, vSectorFk); - END IF; +BEGIN +/** + * Inserta una nueva colección, si el usuario no tiene ninguna vacia. + * Esto se hace para evitar que por error se generen colecciones sin sentido. + * + * @param vSectorFk Identificador de #vn.sector + */ + DECLARE hasEmptyCollections BOOL; + DECLARE vUserFk INT; + + SET vUserFk = account.myUser_getId(); + + SELECT (COUNT(sc.id) > 0) INTO hasEmptyCollections + FROM vn.sectorCollection sc + LEFT JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id + WHERE ISNULL(scsg.id) + AND sc.userFk = vUserFk + AND sc.sectorFk = vSectorFk + AND sc.created >= util.VN_CURDATE(); + + IF NOT hasEmptyCollections THEN + INSERT INTO vn.sectorCollection(userFk, sectorFk) + VALUES(vUserFk, vSectorFk); + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -67774,7 +67775,7 @@ BEGIN SELECT s.warehouseFk FROM vn.sector s WHERE s.id = vSectorFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -67869,10 +67870,10 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `shelvingChange`(IN `vShelvingO` VAR BEGIN UPDATE vn.itemShelving - SET shelvingFk = vShelvingD COLLATE utf8_unicode_ci - WHERE shelvingFk = vShelvingO COLLATE utf8_unicode_ci; - - + SET shelvingFk = vShelvingD COLLATE utf8_unicode_ci + WHERE shelvingFk = vShelvingO COLLATE utf8_unicode_ci; + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -67891,16 +67892,16 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `shelvingLog_get`(shelvingFk VARCHAR(10)) BEGIN - + /* Lista el log de un carro - * + * * @param shelvingFk matrícula del carro - * + * */ - + SELECT originFk, name, creationDate, description FROM shelvingLog sl - JOIN account.user u ON u.id = sl.userFk + JOIN account.user u ON u.id = sl.userFk WHERE sl.originFk = shelvingFk COLLATE utf8_general_ci ORDER BY creationDate DESC; @@ -67923,22 +67924,22 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `shelvingParking_get`(vShelvingFk VARCHAR(10), vWarehouseFk INT, vDayRange INT) BEGIN - -SELECT s.itemFk, + +SELECT s.itemFk, s.concept, - CAST(SUM(s.quantity) AS DECIMAL(10,0)) as sinServir, - CAST(IFNULL(ist.visible,0) AS DECIMAL(10,0)) as aparcado + CAST(SUM(s.quantity) AS DECIMAL(10,0)) as sinServir, + CAST(IFNULL(ist.visible,0) AS DECIMAL(10,0)) as aparcado FROM vn.sale s LEFT JOIN vn.itemShelvingSale iss ON iss.saleFk = s.id JOIN vn.ticket t ON t.id = s.ticketFk LEFT JOIN vn.itemShelvingStock ist ON ist.itemFk = s.itemFk AND ist.warehouseFk = vWarehouseFk JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk AND ish.shelvingFk = vShelvingFk COLLATE utf8_general_ci - WHERE t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(TIMESTAMPADD(DAY, GREATEST(0,vDayRange), util.VN_CURDATE())) + WHERE t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(TIMESTAMPADD(DAY, GREATEST(0,vDayRange), util.VN_CURDATE())) AND iss.saleFk IS NULL AND t.warehouseFk = vWarehouseFk GROUP BY s.itemFk HAVING sinServir > aparcado; - + END ;; DELIMITER ; @@ -67983,12 +67984,12 @@ BEGIN DELETE FROM vn.shelving WHERE length(code) > 3 AND parked < TIMESTAMPADD(WEEK,-1,util.VN_CURDATE()); - + DELETE FROM vn.itemShelving WHERE visible <= 0 AND created < TIMESTAMPADD(MONTH,-1,util.VN_CURDATE()); - DELETE ish.* + DELETE ish.* FROM vn.itemShelving ish JOIN vn.shelving sh ON sh.code = ish.shelvingFk WHERE sh.parkingFk IS NULL @@ -67996,12 +67997,12 @@ BEGIN UPDATE vn.shelving sh LEFT JOIN vn.itemShelving its ON its.shelvingFk = sh.`code` - SET isPrinted = 0, + SET isPrinted = 0, parkingFk = NULL WHERE its.id IS NULL - AND sh.isRecyclable - AND ( sh.parked IS NULL - OR + AND sh.isRecyclable + AND ( sh.parked IS NULL + OR sh.parked < TIMESTAMPADD(MONTH,-1,util.VN_CURDATE()) ); @@ -68178,20 +68179,20 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `solunionRiskRequest`() BEGIN - + DROP TEMPORARY TABLE IF EXISTS tmp.client_list; CREATE TEMPORARY TABLE tmp.client_list (PRIMARY KEY (Id_Cliente)) ENGINE = MEMORY - SELECT * FROM (SELECT cc.client Id_Cliente, ci.grade FROM vn.creditClassification cc + SELECT * FROM (SELECT cc.client Id_Cliente, ci.grade FROM vn.creditClassification cc JOIN vn.creditInsurance ci ON cc.id = ci.creditClassification WHERE dateEnd IS NULL ORDER BY ci.creationDate DESC LIMIT 10000000000000000000) t1 GROUP BY Id_Cliente; - + CALL vn2008.risk_vs_client_list(util.VN_CURDATE()); - - SELECT + + SELECT c.Id_Cliente, c.Cliente, c.Credito credito_vn, c.creditInsurance solunion, cast(r.risk as DECIMAL(10,0)) riesgo_vivo, cast(c.creditInsurance - r.risk as decimal(10,0)) margen_vivo, f.Consumo consumo_anual, c.Vencimiento, ci.grade @@ -68201,7 +68202,7 @@ BEGIN JOIN tmp.client_list ci ON c.Id_Cliente = ci.Id_Cliente JOIN bi.facturacion_media_anual f ON c.Id_Cliente = f.Id_Cliente GROUP BY Id_cliente; - + DROP TEMPORARY TABLE IF EXISTS tmp.risk; DROP TEMPORARY TABLE IF EXISTS tmp.client_list; END ;; @@ -68416,10 +68417,10 @@ BEGIN DECLARE vBossId INT; DECLARE vDone BOOL; DECLARE workerCur CURSOR FOR - SELECT workerFk - FROM tmp.subordinate + SELECT workerFk + FROM tmp.subordinate WHERE NOT isChecked; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; DECLARE EXIT HANDLER FOR 1062 BEGIN @@ -68427,29 +68428,29 @@ BEGIN END; DROP TEMPORARY TABLE IF EXISTS tmp.subordinate; - + CREATE TEMPORARY TABLE tmp.subordinate (PRIMARY KEY (workerFk)) ENGINE = MEMORY SELECT vBossFk AS workerFk, 0 AS isChecked; - + WHILE (SELECT COUNT(*) FROM tmp.subordinate WHERE NOT isChecked) > 0 DO OPEN workerCur; workerLoop: LOOP SET vDone = FALSE; FETCH workerCur INTO vBossId; - + IF vDone THEN LEAVE workerLoop; END IF; - - INSERT INTO tmp.subordinate - SELECT id, 0 - FROM worker + + INSERT INTO tmp.subordinate + SELECT id, 0 + FROM worker WHERE bossFk = vBossId; - - UPDATE tmp.subordinate + + UPDATE tmp.subordinate SET isChecked = 1 WHERE workerFk = vBossId; END LOOP; @@ -68489,13 +68490,13 @@ BEGIN -- Calcula el balance inicial y final de cada proveedor INSERT INTO openingBalance SELECT MAX(dueDated), - supplierFk, - companyFk, + supplierFk, + companyFk, sum(amount) eurAmount, sum(divisa) foreignAmount FROM ( SELECT p.dueDated, - p.supplierFk, + p.supplierFk, p.companyFk, p.amount, p.divisa @@ -68511,7 +68512,7 @@ BEGIN SELECT iidd.dueDated, ii.supplierFk, ii.companyFk, - - iidd.amount, + - iidd.amount, - iidd.foreignValue FROM invoiceIn ii JOIN invoiceInDueDay iidd ON ii.id = iidd.invoiceInFk @@ -68519,14 +68520,14 @@ BEGIN JOIN company co ON co.id = ii.companyFk WHERE iidd.dueDated > '2014-12-31' AND iidd.dueDated <= vEnded - AND ii.isBooked AND co.`code` = 'VNL' + AND ii.isBooked AND co.`code` = 'VNL' AND c.`code` <> 'EUR' UNION ALL SELECT se.dueDated, se.supplierFk, se.companyFk, - - se.amount, + - se.amount, 0 FROM supplierExpense se JOIN currency c ON c.id = se.currencyFk @@ -68536,7 +68537,7 @@ BEGIN AND co.`code` = 'VNL' AND c.`code` <> 'EUR' ) sub GROUP BY companyFk, supplierFk; - + SELECT ob.dueDated , ob.supplierFk , ob.companyFk @@ -68750,7 +68751,7 @@ BEGIN - SUM(iid.amount) mysql, 0 sage FROM invoiceInDueDay iid - JOIN invoiceIn ii ON ii.id = iid.invoiceInFk + JOIN invoiceIn ii ON ii.id = iid.invoiceInFk WHERE IFNULL(ii.bookEntried, ii.issued) BETWEEN vDateFrom AND vDateTo AND ii.isBooked GROUP BY ii.id @@ -68889,15 +68890,15 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketBoxesView`(IN vTicketFk INT) BEGIN - - SELECT s.id, - s.itemFk, - s.concept, - floor(s.quantity / b.packing) as Cajas, - b.packing, - s.isPicked, + + SELECT s.id, + s.itemFk, + s.concept, + floor(s.quantity / b.packing) as Cajas, + b.packing, + s.isPicked, i.size - FROM ticket t + FROM ticket t JOIN sale s ON s.ticketFk = t.id JOIN item i ON i.id = s.itemFk JOIN cache.last_buy lb on lb.warehouse_id = t.warehouseFk AND lb.item_id = s.itemFk @@ -68908,7 +68909,7 @@ BEGIN AND p.isBox GROUP BY s.itemFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -68930,7 +68931,7 @@ BEGIN DECLARE vDateStart DATETIME DEFAULT DATE(vDate); DECLARE vDateEnd DATETIME DEFAULT util.dayEnd(vDate); - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketBuiltTime; CREATE TEMPORARY TABLE tmp.ticketBuiltTime @@ -68943,7 +68944,7 @@ BEGIN SELECT ticketFk, builtTime FROM ( - SELECT + SELECT ticketFk, created as builtTime FROM @@ -68951,13 +68952,13 @@ BEGIN WHERE created BETWEEN vDateStart AND vDateEnd ORDER BY ticketFk, created DESC LIMIT 10000000000000000000 - ) sub + ) sub GROUP BY ticketFk ) sub2 ON sub2.ticketFk = t.id WHERE t.shipped BETWEEN vDate AND util.dayEnd(vDate) AND t.clientFk NOT IN (50,400,200) AND t.companyFk = 442 - + ; END ;; @@ -68986,30 +68987,30 @@ BEGIN */ REPLACE INTO orderTicket(orderFk,ticketFk) - SELECT orderFk, vTicketNew - FROM orderTicket + SELECT orderFk, vTicketNew + FROM orderTicket WHERE ticketFk = vTicketOld; - + -- Bionizamos lineas con Preu = 0 CREATE OR REPLACE TEMPORARY TABLE tmp.recalculateSales (PRIMARY KEY (id)) ENGINE = MEMORY - SELECT id + SELECT id FROM sale WHERE ticketFk = vTicketNew AND price = 0; - + CALL sale_recalcComponent(1); -- Bionizamos lineas con Preu > 0 CREATE OR REPLACE TEMPORARY TABLE tmp.recalculateSales (PRIMARY KEY (id)) ENGINE = MEMORY - SELECT id + SELECT id FROM sale WHERE ticketFk = vTicketNew AND price > 0; - + CALL sale_recalcComponent(6); DROP TEMPORARY TABLE IF EXISTS tmp.recalculateSales; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -69032,12 +69033,12 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketCalculateFromType`( vLanded D vTypeFk INT) BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.item; - CREATE TEMPORARY TABLE tmp.item - (INDEX (itemFk)) - ENGINE = MEMORY + CREATE TEMPORARY TABLE tmp.item + (INDEX (itemFk)) + ENGINE = MEMORY SELECT id itemFk FROM vn.item WHERE typeFk = vTypeFk; - + CALL catalog_calculate(vLanded, vAddressFk, vAgencyModeFk); DROP TEMPORARY TABLE tmp.item; DROP TEMPORARY TABLE tmp.ticketLot; @@ -69059,7 +69060,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketCalculatePurge`() BEGIN - DROP TEMPORARY TABLE + DROP TEMPORARY TABLE tmp.ticketCalculateItem, tmp.ticketComponentPrice, tmp.ticketComponent, @@ -69083,56 +69084,56 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketClon`(vTicketFk INT, vNewShipped DATE) BEGIN - + DECLARE done INT DEFAULT FALSE; - DECLARE vNewTicketFk INT; + DECLARE vNewTicketFk INT; DECLARE vOldSaleFk INT; DECLARE vNewSaleFk INT; - + DECLARE cur1 CURSOR FOR SELECT id FROM vn.sale WHERE ticketFk = vTicketFk; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - + SET vNewShipped = IFNULL(vNewShipped, util.VN_CURDATE()); - + CALL vn.ticket_Clone(vTicketFk, vNewTicketFk); - - UPDATE vn.ticket + + UPDATE vn.ticket SET landed = TIMESTAMPADD(DAY, DATEDIFF(vNewShipped, shipped), landed), shipped = vNewShipped WHERE id = vNewTicketFk; - + OPEN cur1; - + read_loop: LOOP - + FETCH cur1 INTO vOldSaleFk; - + IF done THEN LEAVE read_loop; END IF; - + INSERT INTO vn.sale(ticketFk, itemFk, quantity, concept, price, discount, priceFixed, isPriceFixed) SELECT vNewTicketFk, itemFk, quantity, concept, price, discount, priceFixed, isPriceFixed FROM vn.sale WHERE id = vOldSaleFk; - + SELECT max(id) INTO vNewSaleFk FROM vn.sale WHERE ticketFk = vNewTicketFk; - + INSERT INTO vn.saleComponent(saleFk, componentFk, value, isGreuge) SELECT vNewSaleFk, componentFk, value, isGreuge FROM vn.saleComponent WHERE saleFk = vOldSaleFk; - + END LOOP; CLOSE cur1; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -69154,18 +69155,18 @@ BEGIN DECLARE vShipped DATE; DECLARE vMaxDated DATE; - - SELECT shipped, TIMESTAMPADD(YEAR,1,shipped) + + SELECT shipped, TIMESTAMPADD(YEAR,1,shipped) INTO vShipped, vMaxDated FROM vn.ticket WHERE id = vTicketFk; - + WHILE vShipped <= vMaxDated DO - + SET vShipped = TIMESTAMPADD(WEEK, 1, vShipped); - + CALL vn.ticketClon(vTicketFk, vShipped); - + END WHILE; END ;; @@ -69187,10 +69188,10 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketCollection_get`(vTicketFk INT) BEGIN - SELECT tc.collectionFk + SELECT tc.collectionFk FROM vn.ticketCollection tc WHERE ticketFk = vTicketFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -69209,18 +69210,18 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketCollection_setUsedShelves`(vTicketFk INT, vUsedShelves INT) BEGIN - + /* * Inserta número de baldas que ocupa un ticket - * + * * @param vTicketFk Identificador de ticket * @param vUsedShelves Número de baldas */ - + UPDATE ticketCollection tc SET tc.usedShelves = vUsedShelves WHERE tc.ticketFk = vTicketFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -69258,18 +69259,18 @@ BEGIN END; START TRANSACTION; - + IF (SELECT addressFk FROM ticket WHERE id = vTicketFk) <> vAddressFk THEN - - UPDATE ticket t + + UPDATE ticket t JOIN address a ON a.id = vAddressFk SET t.nickname = a.nickname WHERE t.id = vTicketFk; - + END IF; - + UPDATE ticket t - SET + SET t.clientFk = vClientFk, t.agencyModeFk = vAgencyModeFk, t.addressFk = vAddressFk, @@ -69280,12 +69281,12 @@ BEGIN t.isDeleted = vIsDeleted WHERE t.id = vTicketFk; - + IF vHasToBeUnrouted THEN UPDATE ticket t SET t.routeFk = NULL WHERE t.id = vTicketFk; END IF; - + IF vOption <> 8 THEN DROP TEMPORARY TABLE IF EXISTS tmp.sale; CREATE TEMPORARY TABLE tmp.sale @@ -69327,104 +69328,104 @@ BEGIN DECLARE vComponentFk INT; DECLARE vRenewComponents BOOLEAN; DECLARE vKeepPrices BOOLEAN; - + CASE vOption - WHEN 1 THEN + WHEN 1 THEN SET vRenewComponents = TRUE; SET vKeepPrices = FALSE; WHEN 2 THEN - SELECT id INTO vComponentFk FROM component WHERE `code` = 'debtCollection'; + SELECT id INTO vComponentFk FROM component WHERE `code` = 'debtCollection'; SET vRenewComponents = TRUE; SET vKeepPrices = TRUE; - WHEN 3 THEN - SELECT id INTO vComponentFk FROM component WHERE `code` = 'mana'; - SET vRenewComponents = TRUE; - SET vKeepPrices = TRUE; - WHEN 4 THEN - SELECT id INTO vComponentFk FROM component WHERE `code` = 'buyerDiscount'; + WHEN 3 THEN + SELECT id INTO vComponentFk FROM component WHERE `code` = 'mana'; SET vRenewComponents = TRUE; SET vKeepPrices = TRUE; - /* WHEN 5 THEN + WHEN 4 THEN + SELECT id INTO vComponentFk FROM component WHERE `code` = 'buyerDiscount'; + SET vRenewComponents = TRUE; + SET vKeepPrices = TRUE; + /* WHEN 5 THEN SET vComponentFk = 35; SET vRenewComponents = TRUE; SET vKeepPrices = TRUE;*/ - WHEN 6 THEN + WHEN 6 THEN SELECT id INTO vComponentFk FROM component WHERE `code` = 'imbalance'; SET vRenewComponents = TRUE; SET vKeepPrices = TRUE; WHEN 7 THEN REPLACE INTO saleComponent(saleFk, componentFk, value) - SELECT s.id, 28, ROUND(((s.price * (100 - s.discount) / 100) - SUM(IFNULL(sc.value, 0))) * 0.8, 3) + SELECT s.id, 28, ROUND(((s.price * (100 - s.discount) / 100) - SUM(IFNULL(sc.value, 0))) * 0.8, 3) FROM sale s JOIN tmp.sale tmps ON tmps.saleFk = s.id - LEFT JOIN saleComponent sc ON sc.saleFk = s.id + LEFT JOIN saleComponent sc ON sc.saleFk = s.id AND sc.componentFk NOT IN (28, 29) GROUP BY s.id; - + REPLACE INTO saleComponent(saleFk, componentFk, value) - SELECT s.id, 29, ROUND(((s.price * (100 - s.discount) / 100) - SUM(IFNULL(sc.value, 0))) * 0.2, 3) + SELECT s.id, 29, ROUND(((s.price * (100 - s.discount) / 100) - SUM(IFNULL(sc.value, 0))) * 0.2, 3) FROM sale s JOIN tmp.sale tmps ON tmps.saleFk = s.id - LEFT JOIN saleComponent sc ON sc.saleFk = s.id + LEFT JOIN saleComponent sc ON sc.saleFk = s.id AND sc.componentFk NOT IN (28, 29) GROUP BY s.id; - + SET vRenewComponents = FALSE; SET vKeepPrices = FALSE; WHEN 8 THEN - DELETE sc.* + DELETE sc.* FROM tmp.sale tmps JOIN saleComponent sc ON sc.saleFk = tmps.saleFk; - + REPLACE INTO saleComponent(saleFk, componentFk, value) - SELECT s.id, 28, ROUND(((s.price * (100 - s.discount) / 100)), 3) + SELECT s.id, 28, ROUND(((s.price * (100 - s.discount) / 100)), 3) FROM sale s JOIN tmp.sale tmps ON tmps.saleFk = s.id; - + SET vRenewComponents = FALSE; SET vKeepPrices = FALSE; - WHEN 9 THEN + WHEN 9 THEN SET vRenewComponents = TRUE; SET vKeepPrices = TRUE; END CASE; IF vRenewComponents THEN - DELETE sc.* - FROM tmp.sale tmps + DELETE sc.* + FROM tmp.sale tmps JOIN saleComponent sc ON sc.saleFk = tmps.saleFk JOIN `component` c ON c.id = sc.componentFk WHERE c.isRenewable; - + REPLACE INTO saleComponent(saleFk, componentFk, value) SELECT s.id, tc.componentFk, tc.cost - FROM sale s + FROM sale s JOIN tmp.sale tmps ON tmps.saleFk = s.id JOIN tmp.ticketComponent tc ON tc.itemFk = s.itemFk AND tc.warehouseFk = tmps.warehouseFk - LEFT JOIN saleComponent sc ON sc.saleFk = s.id - AND sc.componentFk = tc.componentFk - LEFT JOIN `component` c ON c.id = tc.componentFk + LEFT JOIN saleComponent sc ON sc.saleFk = s.id + AND sc.componentFk = tc.componentFk + LEFT JOIN `component` c ON c.id = tc.componentFk WHERE IF(sc.componentFk IS NULL AND NOT c.isRenewable, FALSE, TRUE); - - -- Añadir componente venta por paquete + + -- Añadir componente venta por paquete DROP TEMPORARY TABLE IF EXISTS tmp.sale2; CREATE TEMPORARY TABLE tmp.sale2 (PRIMARY KEY (saleFk)) - ENGINE = MEMORY + ENGINE = MEMORY SELECT * FROM tmp.sale; - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent2; CREATE TEMPORARY TABLE tmp.ticketComponent2 - SELECT * FROM tmp.ticketComponent; - - REPLACE INTO saleComponent(saleFk, componentFk, value) + SELECT * FROM tmp.ticketComponent; + + REPLACE INTO saleComponent(saleFk, componentFk, value) SELECT t.id, t.componentFk, t.cost FROM ( SELECT s.id, tc.componentFk, tc.cost, MOD(s.quantity, b.packing) as resto FROM vn.sale s JOIN tmp.sale tmps ON tmps.saleFk = s.id - JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND tmps.warehouseFk = lb.warehouse_id + JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND tmps.warehouseFk = lb.warehouse_id JOIN vn.buy b ON b.id = buy_id JOIN tmp.ticketComponent tc ON tc.itemFk = s.itemFk AND tc.warehouseFk = tmps.warehouseFk - JOIN `component` c ON c.id = tc.componentFk AND c.code = 'salePerPackage' + JOIN `component` c ON c.id = tc.componentFk AND c.code = 'salePerPackage' LEFT JOIN ( SELECT s.id FROM vn.sale s @@ -69435,8 +69436,8 @@ BEGIN ) tp ON tp.id = s.id WHERE tp.id IS NULL HAVING resto <> 0) t; - - DROP TEMPORARY TABLE IF EXISTS + + DROP TEMPORARY TABLE IF EXISTS tmp.sale2, tmp.ticketComponent2; END IF; @@ -69454,26 +69455,26 @@ BEGIN UPDATE sale s JOIN item i on i.id = s.itemFk JOIN itemType it on it.id = i.typeFk - JOIN (SELECT SUM(sc.value) sumValue, sc.saleFk + JOIN (SELECT SUM(sc.value) sumValue, sc.saleFk FROM saleComponent sc JOIN tmp.sale tmps ON tmps.saleFk = sc.saleFk GROUP BY sc.saleFk) sc ON sc.saleFk = s.id SET s.price = sumValue / ((100 - s.discount) / 100) - WHERE it.code != 'PRT' ; - + WHERE it.code != 'PRT' ; + REPLACE INTO saleComponent(saleFk, componentFk, value) SELECT s.id, 21, ROUND((s.price * (100 - s.discount) / 100) - SUM(value), 3) saleValue FROM sale s JOIN tmp.sale tmps ON tmps.saleFk = s.id LEFT JOIN saleComponent sc ON sc.saleFk = s.id WHERE sc.componentFk != 21 - GROUP BY s.id + GROUP BY s.id HAVING ROUND(saleValue, 4) <> 0; END IF; - + UPDATE sale s JOIN ( - SELECT SUM(sc.value) sumValue, sc.saleFk + SELECT SUM(sc.value) sumValue, sc.saleFk FROM saleComponent sc JOIN tmp.sale tmps ON tmps.saleFk = sc.saleFk JOIN `component` c ON c.id = sc.componentFk @@ -69487,10 +69488,10 @@ BEGIN JOIN sale s on s.id = sc.saleFk JOIN item i ON i.id = s.itemFk JOIN itemType it ON it.id = i.typeFk - WHERE it.code = 'PRT'; - + WHERE it.code = 'PRT'; + INSERT INTO saleComponent(saleFk, componentFk, value) - SELECT s.id, 15, s.price + SELECT s.id, 15, s.price FROM sale s JOIN tmp.sale tmps ON tmps.saleFk = s.id JOIN item i ON i.id = s.itemFK @@ -69557,24 +69558,24 @@ BEGIN CREATE TEMPORARY TABLE tmp.ticket ENGINE = MEMORY SELECT vTicketFk ticketFk; - + CALL vn.ticket_getTax(NULL); - SELECT + SELECT tt.ticketFk, CAST(tt.taxableBase AS DECIMAL(10, 2)) AS taxableBase, CAST(tt.rate * tt.taxableBase / 100 AS DECIMAL(10, 2)) AS tax, - pgc.*, + pgc.*, CAST(IF(pe.equFk IS NULL, taxableBase, 0) AS DECIMAL(10, 2)) AS Base, pgc.rate / 100 as vatPercent FROM tmp.ticketTax tt JOIN vn.pgc ON pgc.code = tt.pgcFk LEFT JOIN vn.pgcEqu pe ON pe.equFk = pgc.code; - + DROP TEMPORARY TABLE tmp.ticket; DROP TEMPORARY TABLE tmp.ticketTax; DROP TEMPORARY TABLE tmp.ticketAmount; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -69612,29 +69613,29 @@ BEGIN JOIN ticket t ON t.id = tmpTicket.ticketFk; CALL addressTaxArea (); - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketTax; CREATE TEMPORARY TABLE tmp.ticketTax (INDEX (ticketFk)) ENGINE = MEMORY SELECT tmpTicket.ticketFk, bp.pgcFk, - SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2) + SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2) ) AS taxableBase, SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2) ) * pgc.rate / 100 AS tax, tc.code - + FROM tmp.ticket tmpTicket JOIN sale s ON s.ticketFk = tmpTicket.ticketFk JOIN item i ON i.id = s.itemFk JOIN ticket t ON t.id = tmpTicket.ticketFk JOIN supplier su ON su.id = t.companyFk - JOIN tmp.addressTaxArea ata + JOIN tmp.addressTaxArea ata ON ata.addressFk = t.addressFk AND ata.companyFk = t.companyFk - JOIN itemTaxCountry itc + JOIN itemTaxCountry itc ON itc.itemFk = i.id AND itc.countryFk = su.countryFk - JOIN bookingPlanner bp + JOIN bookingPlanner bp ON bp.countryFk = su.countryFk AND bp.taxAreaFk = ata.areaFk AND bp.taxClassFk = itc.taxClassFk @@ -69642,7 +69643,7 @@ BEGIN JOIN taxClass tc ON tc.id = bp.taxClassFk GROUP BY tmpTicket.ticketFk, pgc.code HAVING taxableBase != 0; - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketAmount; CREATE TEMPORARY TABLE tmp.ticketAmount (INDEX (ticketFk)) @@ -69653,7 +69654,7 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.addressCompany; DROP TEMPORARY TABLE IF EXISTS tmp.addressTaxArea; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -69674,7 +69675,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketGetTotal`(vTaxArea VARCHAR(25 BEGIN /** * Calcula el total con IVA para un conjunto de tickets. - * + * * @param vTaxArea * @table tmp.ticket(ticketFk) Identificadores de los tickets a calcular * @return tmp.ticketTotal Total para cada ticket @@ -69691,7 +69692,7 @@ BEGIN FROM tmp.ticket t LEFT JOIN tmp.ticketAmount ta ON t.ticketFk = ta.ticketFk GROUP BY ticketFk; - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketAmount; DROP TEMPORARY TABLE IF EXISTS tmp.ticketTax; END ;; @@ -69763,18 +69764,18 @@ BEGIN DECLARE vParked DATETIME; DECLARE vLevel INT; DECLARE vCollectionFk INT; - - SELECT IFNULL(`level`,0), IFNULL(collectionFk,0) + + SELECT IFNULL(`level`,0), IFNULL(collectionFk,0) INTO vLevel, vCollectionFk FROM vn.ticketCollection WHERE ticketFk = vTicketFk LIMIT 1; - - SELECT created, parkingFk + + SELECT created, parkingFk INTO vParked, vParkingFk FROM vn.ticketParking WHERE ticketFk = vTicketFk; - + SELECT tp.ticketFk, CONCAT(tc.collectionFk, ' - ', tc.level) coleccion, tp.created, p.code, am.name as Agencia FROM vn.ticketParking tp JOIN vn.parking p ON p.id = tp.parkingFk @@ -69801,7 +69802,7 @@ BEGIN AND sc.isPackagingArea AND tp.created < vParked AND t.packages <=> 0); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -69822,7 +69823,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketNotInvoicedByClient`(vClientF BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.ticket; - + CREATE TEMPORARY TABLE tmp.ticket SELECT id ticketFk FROM ticket @@ -69832,7 +69833,7 @@ BEGIN CALL vn.ticketGetTotal(NULL); - SELECT c.id, + SELECT c.id, c.name as Cliente, t.shipped as Fecha, t.id as Id_Ticket, @@ -69843,7 +69844,7 @@ BEGIN DROP TEMPORARY TABLE tmp.ticket, - tmp.ticketTotal; + tmp.ticketTotal; END ;; DELIMITER ; @@ -69863,21 +69864,21 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketObservation_addNewBorn`(vTicketFk INT) BEGIN - + /** * Inserta observaciones para los tickets con clientes nuevos o recuperados - * + * * @param vTicketFk Identificador de vn.ticket */ - + DECLARE vDescription VARCHAR(20) DEFAULT '¡Cliente NUEVO! '; INSERT INTO vn.ticketObservation(ticketFk, observationTypeFk, description) SELECT vTicketFk, ot.id, vDescription FROM vn.observationType ot WHERE ot.hasNewBornMessage - ON DUPLICATE KEY UPDATE description = CONCAT(vDescription, ticketObservation.description); - + ON DUPLICATE KEY UPDATE description = CONCAT(vDescription, ticketObservation.description); + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -69917,7 +69918,7 @@ BEGIN DECLARE vComponentCost INT; DECLARE vDone INT DEFAULT FALSE; DECLARE vClientId INT; - + DECLARE vCursor CURSOR FOR SELECT DISTINCT clientFk FROM ( @@ -69934,31 +69935,31 @@ BEGIN RESIGNAL; END; - SELECT id INTO vWarehouseInventory - FROM warehouse + SELECT id INTO vWarehouseInventory + FROM warehouse WHERE `code`= 'inv'; - - SELECT id INTO vComponentCost - FROM component + + SELECT id INTO vComponentCost + FROM component WHERE `code`= 'purchaseValue'; - - SELECT packagingInvoicingDated INTO vDateStart - FROM ticketConfig; - + + SELECT packagingInvoicingDated INTO vDateStart + FROM ticketConfig; + IF vWarehouseInventory IS NULL THEN CALL util.throw('Warehouse inventory not set'); END IF; IF vComponentCost IS NULL THEN CALL util.throw('Component cost not set'); - END IF; + END IF; SET vDateEnd = vDated + INTERVAL 1 DAY; - + IF NOT vWithoutPeriodGrace THEN SET vGraceDate = vGraceDate -INTERVAL 1 MONTH; END IF; - + DROP TEMPORARY TABLE IF EXISTS tmp.packagingToInvoice; CREATE TEMPORARY TABLE tmp.packagingToInvoice (INDEX (clientFk)) @@ -69971,7 +69972,7 @@ BEGIN t.clientFk FROM ticketPackaging tp JOIN packaging p ON p.id = tp.packagingFk - JOIN ticket t ON t.id = tp.ticketFk + JOIN ticket t ON t.id = tp.ticketFk JOIN client c ON c.id = t.clientFk WHERE c.isActive AND (vClientFk IS NULL OR t.clientFk = vClientFk) @@ -69979,7 +69980,7 @@ BEGIN AND (tp.quantity < 0 OR (tp.quantity > 0 AND t.shipped < vGraceDate)) AND tp.quantity AND p.itemFk; - + OPEN vCursor; l: LOOP @@ -69992,25 +69993,25 @@ BEGIN START TRANSACTION; CALL ticket_add( - vClientId, + vClientId, vDateEnd, - vWarehouseInventory, - vCompanyFk, - NULL, - NULL, - NULL, - vDateEnd, - account.myUser_getId(), + vWarehouseInventory, + vCompanyFk, + NULL, + NULL, + NULL, + vDateEnd, + account.myUser_getId(), TRUE, vNewTicket); - + INSERT INTO ticketPackaging(ticketFk, packagingFk, quantity, pvp) SELECT vNewTicket, packagingFk, - SUM(quantity) totalQuantity, price - FROM tmp.packagingToInvoice + FROM tmp.packagingToInvoice WHERE clientFk = vClientId GROUP BY packagingFk HAVING IF(vWithoutPeriodGrace, totalQuantity <> 0, totalQuantity < 0); - + INSERT INTO sale(ticketFk, itemFk, concept, quantity, price) SELECT vNewTicket, pti.itemFk, i.name, SUM(pti.quantity) totalQuantity, pti.price FROM tmp.packagingToInvoice pti @@ -70018,12 +70019,12 @@ BEGIN WHERE pti.clientFk = vClientId GROUP BY pti.itemFk HAVING IF(vWithoutPeriodGrace, totalQuantity <> 0, totalQuantity > 0); - + INSERT INTO saleComponent(saleFk, componentFk, value) SELECT id, vComponentCost, price FROM sale WHERE ticketFk = vNewTicket; - + COMMIT; END LOOP; CLOSE vCursor; @@ -70047,37 +70048,37 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketParking_findSkipped`(vTicketFk INT, vItemPackingTypeFk VARCHAR(1)) BEGIN - + /** * Averigua los tickets que se han saltado por un error en el proceso encajado * @param vTicketFk Ticket * @param vItemPackingTypeFk Modo de encajado * @return un select con los tickets afectados - */ + */ DECLARE vParkingFk INT; DECLARE vParked DATETIME; DECLARE vLevel INT; DECLARE vWagon INT; DECLARE vCollectionFk INT; - - SELECT IFNULL(`level`,0), IFNULL(`wagon`,0),IFNULL(collectionFk,0) + + SELECT IFNULL(`level`,0), IFNULL(`wagon`,0),IFNULL(collectionFk,0) INTO vLevel, vWagon, vCollectionFk FROM vn.ticketCollection tc JOIN vn.collection c ON c.id = tc.collectionFk AND c.itemPackingTypeFk = vItemPackingTypeFk WHERE ticketFk = vTicketFk ORDER BY c.id DESC LIMIT 1; - - SELECT created, parkingFk + + SELECT created, parkingFk INTO vParked, vParkingFk FROM vn.ticketParking tp - JOIN vn.parking p ON p.id = tp.parkingFk - JOIN vn.sector s ON s.id = p.sectorFk + JOIN vn.parking p ON p.id = tp.parkingFk + JOIN vn.sector s ON s.id = p.sectorFk WHERE ticketFk = vTicketFk AND s.itemPackingTypeFk = vItemPackingTypeFk AND s.isPackagingArea ; - + SELECT tp.ticketFk, CONCAT(tc.collectionFk, ' ', tc.wagon, ' - ', tc.level) coleccion, tp.created, p.code, am.name as Agencia FROM vn.ticketParking tp JOIN vn.parking p ON p.id = tp.parkingFk @@ -70094,9 +70095,9 @@ BEGIN AND ( ( IFNULL(tc.collectionFk,-1) != IFNULL(@vCollectionFk,0) AND tp.created < vParked ) OR - ( tc.collectionFk = vCollectionFk + ( tc.collectionFk = vCollectionFk AND (LEFT(tc.wagon,1) < LEFT(vWagon,1) - OR (LEFT(tc.wagon,1) = LEFT(vWagon,1) AND LEFT(tc.level,1) < LEFT(vLevel,1))) + OR (LEFT(tc.wagon,1) = LEFT(vWagon,1) AND LEFT(tc.level,1) < LEFT(vLevel,1))) ) ) ) -- Etiquetas que no se han escaneado y ya estamos con una posterior @@ -70104,7 +70105,7 @@ BEGIN (s.alertLevel > 1 AND tp.parkingFk = vParkingFk AND sc.isPackagingArea - AND tp.created < vParked + AND tp.created < vParked AND t.packages <=> 0); END ;; DELIMITER ; @@ -70156,11 +70157,11 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketRequest_Add`(vDescription VARCHAR(255), vQuantity INT, vPrice DOUBLE, vTicketFk INT, vBuyerCode VARCHAR(3)) BEGIN - INSERT INTO vn.ticketRequest(description, - quantity, - price, - ticketFk, - buyerCode, + INSERT INTO vn.ticketRequest(description, + quantity, + price, + ticketFk, + buyerCode, requesterFk) VALUES(vDescription, vQuantity, @@ -70168,7 +70169,7 @@ BEGIN vTicketFk, vBuyerCode, vn.getUser()); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -70187,26 +70188,26 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketStateToday_setState`(vTicketFk INT, vStateCode VARCHAR(45)) BEGIN - + /* Modifica el estado de un ticket de hoy - * + * * @param vTicketFk el id del ticket * @param vStateCode estado a modificar del ticket - * + * */ - + DECLARE vAlertLevel INT; - - SELECT s.alertLevel INTO vAlertLevel - FROM state s - JOIN ticketStateToday tst ON tst.state = s.id + + SELECT s.alertLevel INTO vAlertLevel + FROM state s + JOIN ticketStateToday tst ON tst.state = s.id WHERE tst.ticket = vTicketFk LIMIT 1; - + IF vAlertLevel < 2 THEN - + CALL vn.ticket_setState(vTicketFk, vStateCode); - + END IF; END ;; @@ -70227,23 +70228,23 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketStateUpdate`(vTicketFk INT, vStateCode VARCHAR(45)) BEGIN - + /* * @deprecated:utilizar ticket_setState */ - + DECLARE vAlertLevel INT; - SELECT s.alertLevel INTO vAlertLevel + SELECT s.alertLevel INTO vAlertLevel FROM vn.state s JOIN vn.ticketState ts ON ts.stateFk = s.id WHERE ts.ticketFk = vTicketFk; - - IF !(vStateCode = 'ON_CHECKING' AND vAlertLevel > 1) THEN - + + IF !(vStateCode = 'ON_CHECKING' AND vAlertLevel > 1) THEN + INSERT INTO ticketTracking(stateFk, ticketFk, workerFk) SELECT id, vTicketFk, account.myUser_getId() - FROM vn.state + FROM vn.state WHERE `code` = vStateCode collate utf8_unicode_ci; END IF; @@ -70523,20 +70524,20 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_administrativeCopy`(vOriginalTicket INT, OUT vNewTicket INT) BEGIN - + INSERT INTO vn.ticket(clientFk, addressFk, shipped, warehouseFk, companyFk, landed) - SELECT t.clientFk , t.addressFk , t.shipped ,w.id, t.companyFk , t.landed + SELECT t.clientFk , t.addressFk , t.shipped ,w.id, t.companyFk , t.landed FROM vn.ticket t JOIN vn.warehouse w ON w.name = 'INVENTARIO' WHERE t.id = vOriginalTicket; - + SELECT LAST_INSERT_ID() INTO vNewTicket; INSERT INTO vn.sale(ticketFk, itemFk, concept, quantity, price, discount) - SELECT vNewTicket, s.itemFk , s.concept , s.quantity , s.price , s.discount + SELECT vNewTicket, s.itemFk , s.concept , s.quantity , s.price , s.discount FROM vn.sale s WHERE s.ticketFk = vOriginalTicket; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -70780,7 +70781,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_canMerge`(vDated DATE, vScop BEGIN /** * Devuelve un listado de tickets susceptibles de fusionarse con otros tickets en el futuro - * + * * @param vDated Fecha en cuestión * @param vScopeDays Dias en el futuro a sondear * @param vLitersMax Volumen máximo de los tickets a catapultar @@ -70861,10 +70862,10 @@ BEGIN * Comprueba que los tickets entre un rango de fechas tienen componentes * y recalcula sus componentes * - * @param vShippedFrom rango inicial de fecha + * @param vShippedFrom rango inicial de fecha * @param vShippedTo rango final de fecha */ - + CREATE OR REPLACE TEMPORARY TABLE tmp.coste (primary key (id)) ENGINE = MEMORY SELECT s.id @@ -70893,9 +70894,9 @@ BEGIN AND ic.merchandise; CALL vn.sale_recalcComponent(1); - + DROP TEMPORARY TABLE tmp.recalculateSales; - DROP TEMPORARY TABLE tmp.coste; + DROP TEMPORARY TABLE tmp.coste; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -71011,7 +71012,7 @@ BEGIN t.companyFk, t.addressFk, tt.agencyModeFk - FROM ticketWeekly tt + FROM ticketWeekly tt JOIN ticket t ON tt.ticketFk = t.id; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vIsDone = TRUE; @@ -71025,15 +71026,15 @@ BEGIN DECLARE vIsDuplicateMail BOOL; DECLARE vSubject VARCHAR(150); DECLARE vMessage TEXT; - + SET vIsDone = FALSE; FETCH rsTicket INTO vTicketFk, vWeekDay, vClientFk, vWarehouseFk, vCompanyFk, vAddressFk, vAgencyModeFk; IF vIsDone THEN LEAVE myLoop; END IF; - - SELECT dated INTO vShipment + + SELECT dated INTO vShipment FROM `time` WHERE `year` = vYear AND `week` = vWeek AND WEEKDAY(dated) = vWeekDay; @@ -71044,17 +71045,17 @@ BEGIN JOIN saleCloned sc ON sc.saleOriginalFk = saleOrig.id JOIN sale saleClon ON saleClon.id = sc.saleClonedFk JOIN ticket tClon ON tClon.id = saleClon.ticketFk - WHERE tOrig.id = vTicketFk - AND tClon.isDeleted = FALSE + WHERE tOrig.id = vTicketFk + AND tClon.isDeleted = FALSE AND DATE(tClon.shipped) = vShipment) THEN ITERATE myLoop; END IF; IF vAgencyModeFk IS NULL THEN - SELECT agencyModeFk INTO vAgencyModeFk + SELECT agencyModeFk INTO vAgencyModeFk FROM address - WHERE clientFk = vClientFk + WHERE clientFk = vClientFk AND isDefaultAddress; END IF; @@ -71075,8 +71076,8 @@ BEGIN FALSE, vNewTicket); - UPDATE ticket - SET clonedFrom = vTicketFk + UPDATE ticket + SET clonedFrom = vTicketFk WHERE id = vNewTicket; INSERT INTO sale (ticketFk, itemFk, concept, quantity, price, @@ -71095,7 +71096,7 @@ BEGIN INSERT IGNORE INTO saleCloned(saleOriginalFk, saleClonedFk) SELECT saleOriginal.id, saleClon.id FROM sale saleOriginal - JOIN sale saleClon ON saleOriginal.itemFk = saleClon.itemFk + JOIN sale saleClon ON saleOriginal.itemFk = saleClon.itemFk AND saleOriginal.quantity = saleClon.quantity WHERE saleOriginal.ticketFk = vTicketFk AND saleClon.ticketFk = vNewTicket; @@ -71125,7 +71126,7 @@ BEGIN buyed, requesterFk, attenderFk, - vNewTicket + vNewTicket FROM ticketRequest WHERE ticketFk =vTicketFk; @@ -71140,26 +71141,26 @@ BEGIN INSERT INTO ticketObservation( ticketFk, observationTypeFk, - description) + description) VALUES( vNewTicket, vSalesPersonFK, CONCAT('turno desde ticket: ',vTicketFk)) - ON DUPLICATE KEY UPDATE description = + ON DUPLICATE KEY UPDATE description = CONCAT(ticketObservation.description,VALUES(description),' '); INSERT INTO ticketObservation(ticketFk, observationTypeFk, - description) + description) VALUES( vNewTicket, vItemPicker, 'ATENCION: Contiene lineas de TURNO') - ON DUPLICATE KEY UPDATE description = + ON DUPLICATE KEY UPDATE description = CONCAT(ticketObservation.description,VALUES(description),' '); IF (vLanding IS NULL) THEN - + SELECT e.email INTO vSalesPersonEmail FROM client c JOIN account.emailUser e ON e.userFk = c.salesPersonFk @@ -71167,8 +71168,8 @@ BEGIN SET vSubject = CONCAT('Turnos - No se ha podido clonar correctamente el ticket ', vTicketFk,' para el dia: ', vShipment); - SET vMessage = CONCAT('No se ha podido clonar el ticket ', vTicketFk, - ' para el dia: ', vShipment, + SET vMessage = CONCAT('No se ha podido clonar el ticket ', vTicketFk, + ' para el dia: ', vShipment, ' porque no hay una zona de envío disponible. Se ha creado el ticket: ', vNewTicket, ' pero ha que revisar las fechas y la agencia'); @@ -71207,7 +71208,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_close`() BEGIN /** - * Realiza el cierre de todos los + * Realiza el cierre de todos los * tickets de la tabla tmp.ticket_close. * * @table tmp.ticket_close(ticketFk) Identificadores de los tickets a cerrar @@ -71225,7 +71226,7 @@ BEGIN DECLARE cur CURSOR FOR SELECT ticketFk FROM tmp.ticket_close; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN RESIGNAL; @@ -71235,7 +71236,7 @@ BEGIN proc: LOOP SET vDone = FALSE; - + FETCH cur INTO vCurTicketFk; IF vDone THEN @@ -71252,12 +71253,12 @@ BEGIN c.hasToInvoice INTO vClientFk, vIsTaxDataChecked, - vCompanyFk, + vCompanyFk, vShipped, vHasDailyInvoice, vWithPackage, vHasToInvoice - FROM ticket t + FROM ticket t JOIN `client` c ON c.id = t.clientFk JOIN province p ON p.id = c.provinceFk LEFT JOIN autonomy a ON a.id = p.autonomyFk @@ -71267,22 +71268,22 @@ BEGIN INSERT INTO ticketPackaging (ticketFk, packagingFk, quantity) (SELECT vCurTicketFk, p.id, COUNT(*) - FROM expedition e + FROM expedition e JOIN packaging p ON p.itemFk = e.freightItemFk WHERE e.ticketFk = vCurTicketFk AND p.isPackageReturnable AND vWithPackage GROUP BY p.itemFk); -- No retornables o no catalogados - INSERT INTO sale (itemFk, ticketFk, concept, quantity, price, isPriceFixed) + INSERT INTO sale (itemFk, ticketFk, concept, quantity, price, isPriceFixed) (SELECT e.freightItemFk, vCurTicketFk, i.name, COUNT(*) AS amount, getSpecialPrice(e.freightItemFk, vClientFk), 1 - FROM expedition e + FROM expedition e JOIN item i ON i.id = e.freightItemFk LEFT JOIN packaging p ON p.itemFk = i.id WHERE e.ticketFk = vCurTicketFk AND IFNULL(p.isPackageReturnable, 0) = 0 AND getSpecialPrice(e.freightItemFk, vClientFk) > 0 GROUP BY e.freightItemFk); - + IF(vHasDailyInvoice) AND vHasToInvoice THEN -- Facturacion rapida @@ -71290,10 +71291,10 @@ BEGIN -- Facturar si está contabilizado IF vIsTaxDataChecked THEN CALL invoiceOut_newFromClient( - vClientFk, - (SELECT invoiceSerial(vClientFk, vCompanyFk, 'M')), - vShipped, - vCompanyFk, + vClientFk, + (SELECT invoiceSerial(vClientFk, vCompanyFk, 'M')), + vShipped, + vCompanyFk, NULL, NULL, vNewInvoiceId); @@ -71361,25 +71362,25 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_componentMakeUpdate`( - vTicketFk INT, + vTicketFk INT, vClientFk INT, - vNickname VARCHAR(50), + vNickname VARCHAR(50), vAgencyModeFk INT, - vAddressFk INT, - vZoneFk INT, + vAddressFk INT, + vZoneFk INT, vWarehouseFk INT, - vCompanyFk INT, + vCompanyFk INT, vShipped DATETIME, - vLanded DATE, + vLanded DATE, vIsDeleted BOOLEAN, - vHasToBeUnrouted BOOLEAN, + vHasToBeUnrouted BOOLEAN, vOption INT) BEGIN - + /** * Modifica en el ticket los campos que se le pasan por parámetro * y cambia sus componentes - * + * * @param vTicketFk Id del ticket a modificar * @param vClientFk nuevo cliente * @param vNickname nuevo alias @@ -71394,29 +71395,29 @@ BEGIN * @param vHasToBeUnrouted si se le elimina la ruta al ticket * @param vOption opcion para el case del proc ticketComponentUpdateSale */ - + DECLARE vPrice DECIMAL(10,2); DECLARE vBonus DECIMAL(10,2); CALL ticket_componentPreview (vTicketFk, vLanded, vAddressFk, vZoneFk, vWarehouseFk); IF (SELECT addressFk FROM ticket WHERE id = vTicketFk) <> vAddressFk THEN - - UPDATE ticket t + + UPDATE ticket t JOIN address a ON a.id = vAddressFk SET t.nickname = a.nickname WHERE t.id = vTicketFk; - + END IF; CALL zone_getShipped(vLanded, vAddressFk, vAgencyModeFk, TRUE); - SELECT zoneFk, price, bonus INTO vZoneFk, vPrice, vBonus + SELECT zoneFk, price, bonus INTO vZoneFk, vPrice, vBonus FROM tmp.zoneGetShipped WHERE shipped BETWEEN DATE(vShipped) AND util.dayEnd(vShipped) AND warehouseFk = vWarehouseFk LIMIT 1; - + UPDATE ticket t - SET + SET t.clientFk = vClientFk, t.nickname = vNickname, t.agencyModeFk = vAgencyModeFk, @@ -71431,12 +71432,12 @@ BEGIN t.isDeleted = vIsDeleted WHERE t.id = vTicketFk; - + IF vHasToBeUnrouted THEN UPDATE ticket t SET t.routeFk = NULL WHERE t.id = vTicketFk; END IF; - + IF vOption <> 8 THEN DROP TEMPORARY TABLE IF EXISTS tmp.sale; CREATE TEMPORARY TABLE tmp.sale @@ -71474,7 +71475,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_componentPreview`( vTicketFk INT, - vLanded DATE, + vLanded DATE, vAddressFk INT, vZoneFk INT, vWarehouseFk SMALLINT) @@ -71490,7 +71491,7 @@ BEGIN * * @return tmp.ticketComponentPreview (warehouseFk, itemFk, componentFk, cost) */ - DECLARE vHasDataChanged BOOL DEFAULT FALSE; + DECLARE vHasDataChanged BOOL DEFAULT FALSE; DECLARE vHasAddressChanged BOOL; DECLARE vHasZoneChanged BOOL DEFAULT FALSE; DECLARE vHasWarehouseChanged BOOL DEFAULT FALSE; @@ -71501,8 +71502,8 @@ BEGIN DECLARE vHasChangeAll BOOL DEFAULT FALSE; - SELECT DATE(landed) <> vLanded, - addressFk <> vAddressFk, + SELECT DATE(landed) <> vLanded, + addressFk <> vAddressFk, zoneFk <> vZoneFk, warehouseFk <> vWarehouseFk INTO @@ -71525,15 +71526,15 @@ BEGIN SET vAgencyModeTypeRateFk = 6; END IF; - SELECT TIMESTAMPADD(DAY, -travelingDays, vLanded) INTO vShipped + SELECT TIMESTAMPADD(DAY, -travelingDays, vLanded) INTO vShipped FROM zone WHERE id = vZoneFk; - + CALL buyUltimate(vWarehouseFk, vShipped); - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; - CREATE TEMPORARY TABLE tmp.ticketLot ENGINE = MEMORY ( - SELECT + CREATE TEMPORARY TABLE tmp.ticketLot ENGINE = MEMORY ( + SELECT vWarehouseFk AS warehouseFk, NULL AS available, s.itemFk, @@ -71553,9 +71554,9 @@ BEGIN JOIN sale s ON s.id = sc.saleFk JOIN ticket t ON t.id = s.ticketFk JOIN `component` c ON c.id = sc.componentFk - WHERE s.ticketFk = vTicketFk - AND (c.isRenewable = FALSE - OR + WHERE s.ticketFk = vTicketFk + AND (c.isRenewable = FALSE + OR (NOT vHasChangeAll AND (NOT (c.typeFk <=> vAddressTypeRateFk OR c.typeFk <=> vAgencyModeTypeRateFk)))); @@ -71635,52 +71636,52 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_DelayTruckSplit`(vTicketFk INT) BEGIN - + /* * Splita las lineas de ticket que no estan ubicadas - * + * */ - + DECLARE vNewTicketFk INT; DECLARE vTotalLines INT; DECLARE vLinesToSplit INT; DROP TEMPORARY TABLE IF EXISTS tmp.SalesToSplit; - + SELECT COUNT(*) INTO vTotalLines - FROM vn.sale + FROM vn.sale WHERE ticketFk = vTicketFk; - + CREATE TEMPORARY TABLE tmp.SalesToSplit SELECT s.id saleFk FROM vn.ticket t - JOIN vn.sale s ON t.id = s.ticketFk - LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = s.itemFk AND issw.warehouseFk = t.warehouseFk + JOIN vn.sale s ON t.id = s.ticketFk + LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = s.itemFk AND issw.warehouseFk = t.warehouseFk WHERE s.quantity > IFNULL(issw.visible, 0) AND s.quantity > 0 AND s.isPicked = FALSE AND s.reserved = FALSE AND t.id = vTicketFk; - + SELECT COUNT(*) INTO vLinesToSplit FROM tmp.SalesToSplit; - + IF vLinesToSplit = vTotalLines AND vLinesToSplit > 0 THEN - + SET vNewTicketFk = vTicketFk; - + ELSE - + CALL vn.ticket_Clone(vTicketFk, vNewTicketFk); - - UPDATE vn.sale s - JOIN tmp.SalesToSplit sts ON sts.saleFk = s.id + + UPDATE vn.sale s + JOIN tmp.SalesToSplit sts ON sts.saleFk = s.id SET s.ticketFk = vNewTicketFk; - + END IF; - + CALL vn.ticketStateUpdate(vNewTicketFk, 'FIXING'); - + DROP TEMPORARY TABLE tmp.SalesToSplit; END ;; @@ -71700,91 +71701,91 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_doCmr`(vSelf INT) -BEGIN -/** -* Crea u actualiza la información del CMR asociado con -* un ticket específico en caso de que sea necesario. -* -* @param vSelf El id del ticket -*/ - DECLARE vCmrFk, vPreviousCmrFk, vCurrentCmrFk INT; - SELECT cmrFk INTO vCmrFk - FROM ticket - WHERE id = vSelf; - - CREATE OR REPLACE TEMPORARY TABLE tTicket - SELECT wo.firstName, - v.numberPlate, - com.id companyFk, - a.id addressFk, - c2.defaultAddressFk, - su.id supplierFk, - t.landed - FROM ticket t - JOIN ticketState ts ON ts.ticketFk = t.id - JOIN `state` s ON s.id = ts.stateFk - JOIN alertLevel al ON al.id = s.alertLevel - JOIN client c ON c.id = t.clientFk - JOIN `address` a ON a.id = t.addressFk - JOIN province p ON p.id = a.provinceFk - JOIN country co ON co.id = p.countryFk - JOIN agencyMode am ON am.id = t.agencyModeFk - JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk - JOIN warehouse w ON w.id = t.warehouseFk - JOIN company com ON com.id = t.companyFk - JOIN client c2 ON c2.id = com.clientFk - JOIN supplierAccount sa ON sa.id = com.supplierAccountFk - JOIN supplier su ON su.id = sa.supplierFk - LEFT JOIN route r ON r.id = t.routeFk - LEFT JOIN worker wo ON wo.id = r.workerFk - LEFT JOIN vehicle v ON v.id = r.vehicleFk - WHERE t.shipped BETWEEN util.yesterday() AND util.dayEnd(util.VN_CURDATE()) - AND al.code IN ('PACKED', 'DELIVERED') - AND co.code <> 'ES' - AND am.name <> 'ABONO' - AND w.code = 'ALG' - AND dm.code = 'DELIVERY' - AND t.id = vSelf - GROUP BY t.id; - - START TRANSACTION; - - IF vCmrFk THEN - UPDATE cmr c - JOIN tTicket t - SET c.senderInstruccions = t.firstName, - c.truckPlate = t.numberPlate, - c.companyFk = t.companyFk, - c.addressToFk = t.addressFk, - c.addressFromFk = t.defaultAddressFk, - c.supplierFk = t.supplierFk, - c.ead = t.landed - WHERE id = vCmrFk; - ELSE - SELECT MAX(id) INTO vPreviousCmrFk FROM cmr; - - INSERT INTO cmr ( - senderInstruccions, - truckPlate, - companyFk, - addressToFk, - addressFromFk, - supplierFk, - ead - ) - SELECT * FROM tTicket; - - SELECT MAX(id) INTO vCurrentCmrFk FROM cmr; - - IF vPreviousCmrFk <> vCurrentCmrFk THEN - UPDATE ticket - SET cmrFk = vCurrentCmrFk - WHERE id = vSelf; - END IF; - END IF; - - COMMIT; - DROP TEMPORARY TABLE tTicket; +BEGIN +/** +* Crea u actualiza la información del CMR asociado con +* un ticket específico en caso de que sea necesario. +* +* @param vSelf El id del ticket +*/ + DECLARE vCmrFk, vPreviousCmrFk, vCurrentCmrFk INT; + SELECT cmrFk INTO vCmrFk + FROM ticket + WHERE id = vSelf; + + CREATE OR REPLACE TEMPORARY TABLE tTicket + SELECT wo.firstName, + v.numberPlate, + com.id companyFk, + a.id addressFk, + c2.defaultAddressFk, + su.id supplierFk, + t.landed + FROM ticket t + JOIN ticketState ts ON ts.ticketFk = t.id + JOIN `state` s ON s.id = ts.stateFk + JOIN alertLevel al ON al.id = s.alertLevel + JOIN client c ON c.id = t.clientFk + JOIN `address` a ON a.id = t.addressFk + JOIN province p ON p.id = a.provinceFk + JOIN country co ON co.id = p.countryFk + JOIN agencyMode am ON am.id = t.agencyModeFk + JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk + JOIN warehouse w ON w.id = t.warehouseFk + JOIN company com ON com.id = t.companyFk + JOIN client c2 ON c2.id = com.clientFk + JOIN supplierAccount sa ON sa.id = com.supplierAccountFk + JOIN supplier su ON su.id = sa.supplierFk + LEFT JOIN route r ON r.id = t.routeFk + LEFT JOIN worker wo ON wo.id = r.workerFk + LEFT JOIN vehicle v ON v.id = r.vehicleFk + WHERE t.shipped BETWEEN util.yesterday() AND util.dayEnd(util.VN_CURDATE()) + AND al.code IN ('PACKED', 'DELIVERED') + AND co.code <> 'ES' + AND am.name <> 'ABONO' + AND w.code = 'ALG' + AND dm.code = 'DELIVERY' + AND t.id = vSelf + GROUP BY t.id; + + START TRANSACTION; + + IF vCmrFk THEN + UPDATE cmr c + JOIN tTicket t + SET c.senderInstruccions = t.firstName, + c.truckPlate = t.numberPlate, + c.companyFk = t.companyFk, + c.addressToFk = t.addressFk, + c.addressFromFk = t.defaultAddressFk, + c.supplierFk = t.supplierFk, + c.ead = t.landed + WHERE id = vCmrFk; + ELSE + SELECT MAX(id) INTO vPreviousCmrFk FROM cmr; + + INSERT INTO cmr ( + senderInstruccions, + truckPlate, + companyFk, + addressToFk, + addressFromFk, + supplierFk, + ead + ) + SELECT * FROM tTicket; + + SELECT MAX(id) INTO vCurrentCmrFk FROM cmr; + + IF vPreviousCmrFk <> vCurrentCmrFk THEN + UPDATE ticket + SET cmrFk = vCurrentCmrFk + WHERE id = vSelf; + END IF; + END IF; + + COMMIT; + DROP TEMPORARY TABLE tTicket; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -72017,37 +72018,37 @@ BEGIN * @param vTicketFk -> Ticket * @param vDatedNew -> Nueva fecha * @return Sales con Movible -*/ +*/ DECLARE vDatedOld DATETIME; SET vDatedNew = DATE_ADD(vDatedNew, INTERVAL 1 DAY); SELECT t.shipped INTO vDatedOld - FROM ticket t + FROM ticket t WHERE t.id = vTicketFk; - CALL item_getStock(vWarehouseFk, vDatedNew, NULL); + CALL item_getStock(vWarehouseFk, vDatedNew, NULL); CALL item_getMinacum(vWarehouseFk, vDatedNew, DATEDIFF(DATE_SUB(vDatedOld, INTERVAL 1 DAY), vDatedNew), NULL); - - SELECT s.id, - s.itemFk, - s.quantity, - s.concept, - s.price, + + SELECT s.id, + s.itemFk, + s.quantity, + s.concept, + s.price, s.reserved, - s.discount, - i.image, - i.subName, + s.discount, + i.image, + i.subName, il.stock + IFNULL(im.amount, 0) AS movable FROM ticket t JOIN sale s ON s.ticketFk = t.id - JOIN item i ON i.id = s.itemFk + JOIN item i ON i.id = s.itemFk LEFT JOIN tmp.itemMinacum im ON im.itemFk = s.itemFk AND im.warehouseFk = vWarehouseFk LEFT JOIN tmp.itemList il ON il.itemFk = s.itemFk WHERE t.id = vTicketFk; DROP TEMPORARY TABLE IF EXISTS tmp.itemList; - DROP TEMPORARY TABLE IF EXISTS tmp.itemMinacum; - + DROP TEMPORARY TABLE IF EXISTS tmp.itemMinacum; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -72076,10 +72077,10 @@ BEGIN CALL sale_getProblems(vIsTodayRelative); DROP TEMPORARY TABLE IF EXISTS tmp.ticket_problems; - CREATE TEMPORARY TABLE tmp.ticket_problems + CREATE TEMPORARY TABLE tmp.ticket_problems (PRIMARY KEY (ticketFk)) ENGINE = MEMORY - SELECT + SELECT ticketFk, MAX(p.isFreezed) isFreezed, MAX(p.risk) risk, @@ -72097,7 +72098,7 @@ BEGIN GROUP BY ticketFk; UPDATE tmp.ticket_problems tp - SET tp.totalProblems = + SET tp.totalProblems = ( (tp.isFreezed) + IF(tp.risk, TRUE, FALSE) + @@ -72151,17 +72152,17 @@ BEGIN (saleFk INT PRIMARY KEY, ticketFk INT, problem VARCHAR(1)) ENGINE = MEMORY; - + INSERT INTO tmp.salesToSplit(saleFk, ticketFk, problem) SELECT s.id, s.ticketFk, 'F' FROM vn.ticket t JOIN vn.sale s ON s.ticketFk = t.id JOIN vn.item i ON i.id = s.itemFk JOIN vn.itemType it on it.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk LEFT JOIN cache.visible v ON v.item_id = i.id AND v.calc_id = vVisibleCache LEFT JOIN cache.available av ON av.item_id = i.id AND av.calc_id = vAvailableCache - LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk + LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk WHERE IFNULL(v.visible,0) < s.quantity AND IFNULL(av.available ,0) < s.quantity AND IFNULL(issw.visible, 0) < s.quantity @@ -72171,16 +72172,16 @@ BEGIN AND t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE()) AND NOT i.generic AND t.warehouseFk = vWarehouseFk; - + INSERT IGNORE INTO tmp.salesToSplit(saleFk, ticketFk, problem) SELECT s.id, s.ticketFk, 'I' - FROM vn.ticket t + FROM vn.ticket t JOIN vn.sale s ON s.ticketFk = t.id JOIN vn.item i ON i.id = s.itemFk JOIN vn.itemType it on it.id = i.typeFk JOIN vn.itemCategory ic ON ic.id = it.categoryFk LEFT JOIN cache.visible v ON v.item_id = s.itemFk AND v.calc_id = vVisibleCache - LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk + LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk WHERE IFNULL(v.visible,0) >= s.quantity AND IFNULL(issw.visible, 0) < s.quantity AND s.quantity > 0 @@ -72190,7 +72191,7 @@ BEGIN AND t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE()) AND NOT i.generic AND t.warehouseFk = vWarehouseFk; - + INSERT IGNORE INTO tmp.salesToSplit(saleFk, ticketFk, problem) SELECT s.id, s.ticketFk, 'R' FROM vn.ticket t @@ -72200,7 +72201,7 @@ BEGIN JOIN vn.itemCategory ic ON ic.id = it.categoryFk LEFT JOIN cache.visible v ON v.item_id = s.itemFk AND v.calc_id = vVisibleCache LEFT JOIN cache.available av ON av.item_id = i.id AND av.calc_id = vAvailableCache - LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk + LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk WHERE IFNULL(v.visible,0) < s.quantity AND IFNULL(av.available ,0) >= s.quantity AND IFNULL(issw.visible, 0) < s.quantity @@ -72211,7 +72212,7 @@ BEGIN AND t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE()) AND NOT i.generic AND t.warehouseFk = vWarehouseFk; - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketsToSplit; CREATE TEMPORARY TABLE tmp.ticketsToSplit @@ -72232,11 +72233,11 @@ BEGIN JOIN vn.ticket t ON t.id = ss.ticketFk JOIN vn.sale s ON s.id = ss.saleFk JOIN vn.item i ON i.id = s.itemFk - LEFT JOIN vn.zoneClosure zc ON zc.zoneFk = t.zoneFk + LEFT JOIN vn.zoneClosure zc ON zc.zoneFk = t.zoneFk GROUP BY ss.ticketFk; - - SELECT - ts.*, + + SELECT + ts.*, t.id ticketFuture, st.name state, zc.`hour` tfEtd, @@ -72245,23 +72246,23 @@ BEGIN FROM tmp.ticketsToSplit ts LEFT JOIN vn.ticketState ts2 ON ts2.ticketFk = ts.ticketFk LEFT JOIN vn.state st ON st.id = ts2.stateFk - LEFT JOIN vn.ticket t - ON t.id != ts.ticketFk + LEFT JOIN vn.ticket t + ON t.id != ts.ticketFk AND t.addressFk = ts.addressFk AND t.shipped BETWEEN vDated AND util.dayend(vDated) LEFT JOIN vn.zoneClosure zc ON zc.zoneFk = t.zoneFk AND zc.dated = vDated LEFT JOIN vn.sale s ON s.ticketFk = t.id LEFT JOIN vn.item i ON i.id = s.itemFk - LEFT JOIN vn.ticketState tst ON tst.ticketFk = t.id + LEFT JOIN vn.ticketState tst ON tst.ticketFk = t.id LEFT JOIN vn.state st2 ON st2.id = tst.stateFk - WHERE (t.id IS NULL + WHERE (t.id IS NULL OR (vDated > util.VN_CURDATE()) OR (vDated = util.VN_CURDATE() AND vHour >= zc.`hour`)) AND ts.etd <= vHour GROUP BY ts.ticketFk, t.id ORDER BY ts.etd, ts.ticketFk; - - DROP TEMPORARY TABLE + + DROP TEMPORARY TABLE tmp.ticketsToSplit; END ;; DELIMITER ; @@ -72298,7 +72299,7 @@ BEGIN JOIN ticket t ON t.id = tmpTicket.ticketFk; CALL addressTaxArea (); - + IF vTaxArea IS NOT NULL THEN UPDATE tmp.addressTaxArea SET areaFk = vTaxArea; @@ -72370,8 +72371,8 @@ BEGIN CREATE TEMPORARY TABLE tmp.ticketAmount (INDEX (ticketFk)) ENGINE = MEMORY - SELECT ticketFk, - taxableBase, + SELECT ticketFk, + taxableBase, SUM(CAST(taxableBase * rate / 100 AS DECIMAL(10, 2))) tax, code FROM tmp.ticketTax @@ -72451,11 +72452,11 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_getWithParameters`( - vClientFk INT, + vClientFk INT, vWarehouseFk INT, - vShipped DATE, - vAddressFk INT, - vCompanyFk INT, + vShipped DATE, + vAddressFk INT, + vCompanyFk INT, vAgencyModeFk INT, OUT vTicketFk INT ) @@ -72469,8 +72470,8 @@ BEGIN * @param vAddressFk Consignatario * @param vCompanyFk Empresa * @param vAgencyModeFk agencia - */ - + */ + SELECT t.id INTO vTicketFk FROM vn.ticket t WHERE t.clientFk <=> vClientFk @@ -72480,7 +72481,7 @@ BEGIN AND (t.companyFk <=> vCompanyFk OR vCompanyFk IS NULL) AND (t.agencyModeFk <=> vAgencyModeFk OR vAgencyModeFk IS NULL) LIMIT 1; - + IF vTicketFk IS NULL THEN CALL vn.ticket_add( vClientFk, @@ -72520,24 +72521,24 @@ BEGIN DECLARE vAddressFk INT; DECLARE vAgencyModeFk INT; DECLARE vWarehouseFk INT; - DECLARE vCursor CURSOR FOR + DECLARE vCursor CURSOR FOR SELECT id, landed, addressFk, agencyModeFk, warehouseFk FROM vn.ticket WHERE shipped > '2020-01-01' AND zoneFk is null; DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET vDone = 1; - + OPEN vCursor; REPEAT FETCH vCursor INTO vFechedTicket, vLanded, vAddressFk, vAgencyModeFk, vWarehouseFk; CALL vn.zone_getShipped (vlanded, vAddressFk, vAgencyModeFk, TRUE); - + UPDATE vn.ticket t JOIN tmp.zoneGetShipped zgs ON zgs.warehouseFk = vWarehouseFk SET t.zoneFk = zgs.zoneFk WHERE t.id = vFechedTicket; - + UNTIL vDone END REPEAT; DROP TEMPORARY TABLE tmp.zoneGetShipped; - + CLOSE vCursor; END ;; DELIMITER ; @@ -72557,14 +72558,14 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_priceDifference`( vTicketFk INT, - vLanded DATE, + vLanded DATE, vAddressFk INT, vZoneFk INT, vWarehouseFk INT) BEGIN /** * Devuelve las diferencias de precio de los movimientos de un ticket. - * + * * @param vTicketFk Id del ticket * @param vLanded Fecha de recepcion * @param vAddressFk Id del consignatario @@ -72573,26 +72574,26 @@ BEGIN */ CALL vn.ticket_componentPreview(vTicketFk, vLanded, vAddressFk, vZoneFk, vWarehouseFk); - SELECT s.itemFk, - i.name, - i.size, - i.category, - IFNULL(s.quantity, 0) AS quantity, - IFNULL(s.price, 0) AS price, + SELECT s.itemFk, + i.name, + i.size, + i.category, + IFNULL(s.quantity, 0) AS quantity, + IFNULL(s.price, 0) AS price, ROUND(SUM(tc.cost), 2) AS newPrice, s.quantity * (s.price - ROUND(SUM(tc.cost), 2)) difference, s.id AS saleFk FROM sale s - JOIN item i ON i.id = s.itemFk - JOIN ticket t ON t.id = s.ticketFk - LEFT JOIN tmp.ticketComponentPreview tc ON tc.itemFk = s.itemFk + JOIN item i ON i.id = s.itemFk + JOIN ticket t ON t.id = s.ticketFk + LEFT JOIN tmp.ticketComponentPreview tc ON tc.itemFk = s.itemFk AND tc.warehouseFk = vWarehouseFk - LEFT JOIN saleComponent sc ON sc.saleFk = s.id + LEFT JOIN saleComponent sc ON sc.saleFk = s.id AND sc.componentFk = tc.componentFk - LEFT JOIN `component` c ON c.id = tc.componentFk - WHERE t.id = vTicketFk - AND IF(sc.componentFk IS NULL - AND c.classRate IS NOT NULL, FALSE, TRUE) + LEFT JOIN `component` c ON c.id = tc.componentFk + WHERE t.id = vTicketFk + AND IF(sc.componentFk IS NULL + AND c.classRate IS NOT NULL, FALSE, TRUE) GROUP BY s.id ORDER BY s.id; DROP TEMPORARY TABLE tmp.ticketComponentPreview; @@ -72615,7 +72616,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_printLabelPrevious`(vTicketFk INT) BEGIN /** - * Calls the report_print procedure and passes it + * Calls the report_print procedure and passes it * the necessary parameters for printing. * * @param vTicketFk id ticket to print. @@ -72623,18 +72624,18 @@ BEGIN DECLARE vPrinterFk INT; DECLARE vSaleGroup INT; DECLARE vUserFk INT DEFAULT account.myUser_getId(); - + SELECT sg.id, o.labelerFk INTO vSaleGroup, vPrinterFk FROM saleGroup sg JOIN sector sc ON sc.id = sg.sectorFk - JOIN saleGroupDetail sgd ON sg.id = sgd.saleGroupFk + JOIN saleGroupDetail sgd ON sg.id = sgd.saleGroupFk JOIN sale s ON sgd.saleFk = s.id JOIN ticket t ON s.ticketFk = t.id JOIN operator o ON o.workerFk = vUserFk - WHERE sc.id = o.sectorFk + WHERE sc.id = o.sectorFk AND t.id = vTicketFk LIMIT 1; - + CALL report_print( 'LabelPrevia', vPrinterFk, @@ -72668,12 +72669,12 @@ proc:BEGIN */ DECLARE hasInvoice BOOL; - SELECT COUNT(*) INTO hasInvoice - FROM ticket + SELECT COUNT(*) INTO hasInvoice + FROM ticket WHERE id = vSelf AND refFk IS NOT NULL; - - IF hasInvoice THEN + + IF hasInvoice THEN LEAVE proc; END IF; @@ -72907,62 +72908,62 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_setState`(vSelf INT, vStateCode VARCHAR(255) COLLATE utf8_general_ci) -BEGIN -/** - * Modifica el estado de un ticket si se cumplen las condiciones necesarias. - * - * @param vSelf el id del ticket - * @param vStateCode estado a modificar del ticket - */ - DECLARE vticketAlertLevel INT; - DECLARE vTicketStateCode VARCHAR(255); - DECLARE vCanChangeState BOOL; - DECLARE vPackedAlertLevel INT; - DECLARE vOnPreparationAlertLevel INT; - DECLARE vNextAlertLevel INT; - DECLARE vZoneFk INT; - - SELECT s.alertLevel, s.`code`, s2.alertLevel, t.zoneFk - INTO vticketAlertLevel, vTicketStateCode, vNextAlertLevel , vZoneFk - FROM state s - JOIN ticketTracking tt ON tt.stateFk = s.id - JOIN state s2 ON s2.code = vStateCode - JOIN ticket t ON t.id = tt.ticketFk - WHERE tt.ticketFk = vSelf - ORDER BY tt.created DESC - LIMIT 1; - - SELECT id INTO vPackedAlertLevel FROM alertLevel WHERE code = 'PACKED'; - SELECT id INTO vOnPreparationAlertLevel FROM alertLevel WHERE code = 'ON_PREPARATION'; - - IF vStateCode = 'OK' AND vZoneFk IS NULL THEN - CALL util.throw('ASSIGN_ZONE_FIRST'); - END IF; - - IF vNextAlertLevel > vticketAlertLevel && vticketAlertLevel < vOnPreparationAlertLevel THEN - UPDATE sale - SET originalQuantity = quantity - WHERE ticketFk = vSelf; - END IF; - - SET vCanChangeState = (vStateCode <> 'ON_CHECKING' OR vticketAlertLevel < vPackedAlertLevel) - AND NOT ( - vTicketStateCode IN ('CHECKED', 'CHECKING') - AND vStateCode IN ('PREPARED', 'ON_PREPARATION') - ); - - IF vCanChangeState THEN - INSERT INTO ticketTracking (stateFk, ticketFk, workerFk) - SELECT id, vSelf, account.myUser_getId() - FROM state - WHERE `code` = vStateCode COLLATE utf8_unicode_ci; - - IF vStateCode = 'PACKED' THEN - CALL ticket_doCmr(vSelf); - END IF; - ELSE - CALL util.throw('INCORRECT_TICKET_STATE'); - END IF; +BEGIN +/** + * Modifica el estado de un ticket si se cumplen las condiciones necesarias. + * + * @param vSelf el id del ticket + * @param vStateCode estado a modificar del ticket + */ + DECLARE vticketAlertLevel INT; + DECLARE vTicketStateCode VARCHAR(255); + DECLARE vCanChangeState BOOL; + DECLARE vPackedAlertLevel INT; + DECLARE vOnPreparationAlertLevel INT; + DECLARE vNextAlertLevel INT; + DECLARE vZoneFk INT; + + SELECT s.alertLevel, s.`code`, s2.alertLevel, t.zoneFk + INTO vticketAlertLevel, vTicketStateCode, vNextAlertLevel , vZoneFk + FROM state s + JOIN ticketTracking tt ON tt.stateFk = s.id + JOIN state s2 ON s2.code = vStateCode + JOIN ticket t ON t.id = tt.ticketFk + WHERE tt.ticketFk = vSelf + ORDER BY tt.created DESC + LIMIT 1; + + SELECT id INTO vPackedAlertLevel FROM alertLevel WHERE code = 'PACKED'; + SELECT id INTO vOnPreparationAlertLevel FROM alertLevel WHERE code = 'ON_PREPARATION'; + + IF vStateCode = 'OK' AND vZoneFk IS NULL THEN + CALL util.throw('ASSIGN_ZONE_FIRST'); + END IF; + + IF vNextAlertLevel > vticketAlertLevel && vticketAlertLevel < vOnPreparationAlertLevel THEN + UPDATE sale + SET originalQuantity = quantity + WHERE ticketFk = vSelf; + END IF; + + SET vCanChangeState = (vStateCode <> 'ON_CHECKING' OR vticketAlertLevel < vPackedAlertLevel) + AND NOT ( + vTicketStateCode IN ('CHECKED', 'CHECKING') + AND vStateCode IN ('PREPARED', 'ON_PREPARATION') + ); + + IF vCanChangeState THEN + INSERT INTO ticketTracking (stateFk, ticketFk, workerFk) + SELECT id, vSelf, account.myUser_getId() + FROM state + WHERE `code` = vStateCode COLLATE utf8_unicode_ci; + + IF vStateCode = 'PACKED' THEN + CALL ticket_doCmr(vSelf); + END IF; + ELSE + CALL util.throw('INCORRECT_TICKET_STATE'); + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -72996,40 +72997,40 @@ proc:BEGIN SELECT COUNT(*) INTO vProblemLines FROM tmp.salesToSplit WHERE ticketFk = vTicketFk; - + SELECT count(*) INTO vTotalLines - FROM vn.sale s + FROM vn.sale s WHERE s.ticketFk = vTicketFk; - + SET vHasFullProblem = (vTotalLines = vProblemLines); -- Ticket completo IF vHasFullProblem THEN - + UPDATE vn.ticket SET landed = vDated + INTERVAL 1 DAY, shipped = vDated, nickname = CONCAT('(',DAY(util.VN_CURDATE()),') ', nickname ) WHERE id = vTicketFk; - + SELECT CONCAT("Se ha cambiado el ticket ", vTicketFk, " al dia ", vDated); LEAVE proc; - + END IF; -- Ticket a futuro existe IF vTicketFutureFk THEN - - UPDATE vn.sale s + + UPDATE vn.sale s JOIN tmp.salesToSplit ss ON s.id = ss.saleFk SET s.ticketFk = vTicketFutureFk, s.concept = CONCAT('(s) ', s.concept) WHERE ss.ticketFk = vTicketFk; - - SELECT CONCAT("Se han movido lineas del ticket ", vTicketFk, + + SELECT CONCAT("Se han movido lineas del ticket ", vTicketFk, " al ticket existente ", vTicketFutureFk,"(", vDated,")"); LEAVE proc; - + END IF; -- Ticket nuevo @@ -73041,18 +73042,18 @@ proc:BEGIN t.landed = vDated + INTERVAL 1 DAY, t.shipped = vDated, t.agencyModeFk = pc.defautlAgencyMode, - t.zoneFk = pc.defaultZone + t.zoneFk = pc.defaultZone WHERE t.id = vTicketFutureFk; - - UPDATE vn.sale s - JOIN tmp.salesToSplit sts ON sts.saleFk = s.id + + UPDATE vn.sale s + JOIN tmp.salesToSplit sts ON sts.saleFk = s.id SET s.ticketFk = vTicketFutureFk, s.concept = CONCAT('(s) ', s.concept) WHERE sts.ticketFk = vTicketFk; CALL vn.ticketStateUpdate(vTicketFutureFk, 'FIXING'); - SELECT CONCAT("Se han movido lineas del ticket ", vTicketFk, + SELECT CONCAT("Se han movido lineas del ticket ", vTicketFk, " al nuevo ticket ", vTicketFutureFk,"(", vDated,")"); END ;; DELIMITER ; @@ -73191,43 +73192,43 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_splitPackingComplete`(vTicketFk INT, vSectorFk INT) BEGIN - + DECLARE vNeedToSplit BOOLEAN; DECLARE vNewTicketFk INT; - + DROP TEMPORARY TABLE IF EXISTS tmpSale; - + CREATE TEMPORARY TABLE tmpSale SELECT DISTINCT s.id - FROM vn.ticket t + FROM vn.ticket t JOIN vn.sale s ON s.ticketFk = t.id - JOIN vn.item i ON i.id = s.itemFk + JOIN vn.item i ON i.id = s.itemFk LEFT JOIN vn.itemShelvingStock iss ON iss.itemFk = s.itemFk AND iss.sectorFk = vSectorFk - JOIN vn.packagingConfig pc + JOIN vn.packagingConfig pc WHERE t.id = vTicketFk AND ( s.quantity MOD IFNULL(iss.packing,1) != 0 - OR + OR IFNULL(iss.packing,1) = 1 - OR + OR i.`size` <= pc.previousPreparationMinimumSize ); - - SELECT COUNT(*) + + SELECT COUNT(*) INTO vNeedToSplit - FROM tmpSale; - + FROM tmpSale; + IF vNeedToSplit THEN - + CALL vn.ticket_Clone(vTicketFk, vNewTicketFk); - + UPDATE vn.sale s - JOIN vn.tmpSale ts ON ts.id = s.id + JOIN vn.tmpSale ts ON ts.id = s.id SET s.ticketFk = vNewTicketFk; - + END IF; - + DROP TEMPORARY TABLE tmpSale; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -73258,7 +73259,7 @@ BEGIN WHERE ot.description = 'Peso Aduana' AND t.clientFk = vClientFk AND t.shipped BETWEEN vDated AND util.dayend(vDated); - + SELECT sum(IF(sv.physicalWeight = 0, sv.weight, sv.physicalWeight)) INTO vTheorycalWeight FROM vn.ticket t JOIN vn.sale s ON s.ticketFk = t.id @@ -73267,9 +73268,9 @@ BEGIN JOIN vn.itemCost ic ON ic.itemFk = i.id AND ic.warehouseFk = t.warehouseFk WHERE t.clientFk = vClientFk AND t.shipped BETWEEN vDated AND util.dayend(vDated); - + SET vRatio = vRealWeight / vTheorycalWeight; - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketWeight; CREATE TEMPORARY TABLE tmp.ticketWeight @@ -73290,7 +73291,7 @@ BEGIN AND t.shipped BETWEEN vDated AND util.dayend(vDated) GROUP BY ib.ediBotanic, o.code; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -73410,18 +73411,18 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `timeBusiness_calculateAll`(vDatedFr BEGIN /** - * @param vDatedFrom Fecha desde + * @param vDatedFrom Fecha desde * @param vDatedTo Fecha hasta */ - CREATE OR REPLACE TEMPORARY TABLE tmp.`user` + CREATE OR REPLACE TEMPORARY TABLE tmp.`user` SELECT w.id userFk FROM vn.worker w; - + CALL vn.timeBusiness_calculate(vDatedFrom, vDatedTo); DROP TEMPORARY TABLE tmp.`user`; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -73441,21 +73442,21 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `timeBusiness_calculateByDepartment`(vDepartmentFk INT, vDatedFrom DATETIME, vDatedTo DATETIME) BEGIN /** - * @param vDepartmentFk + * @param vDepartmentFk * @param vDatedFrom workerTimeControl * @param vDatedTo workerTimeControl */ DROP TEMPORARY TABLE IF EXISTS tmp.`user`; - + CREATE TEMPORARY TABLE tmp.`user` SELECT DISTINCT b.workerFk userFk - FROM business AS b - WHERE (b.started BETWEEN vDatedFrom AND vDatedTo + FROM business AS b + WHERE (b.started BETWEEN vDatedFrom AND vDatedTo OR IFNULL(b.ended, vDatedTo) BETWEEN vDatedFrom AND vDatedTo OR (b.started <= vDatedFrom AND b.ended >= vDatedTo) ) AND b.departmentFk = vDepartmentFk ORDER BY b.ended DESC; - + CALL timeBusiness_calculate(vDatedFrom, vDatedTo); DROP TEMPORARY TABLE tmp.`user`; @@ -73480,19 +73481,19 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `timeBusiness_calculateByUser`(vUser BEGIN /** - * @param vUserFk + * @param vUserFk * @param vDatedFrom workerTimeControl * @param vDatedTo workerTimeControl */ - + DROP TEMPORARY TABLE IF EXISTS tmp.`user`; - + CREATE TEMPORARY TABLE tmp.`user` SELECT id userFk - FROM account.user - WHERE id = vUserFk; + FROM account.user + WHERE id = vUserFk; CALL vn.timeBusiness_calculate(vDatedFrom, vDatedTo); - + DROP TEMPORARY TABLE tmp.`user`; END ;; @@ -73519,14 +73520,14 @@ BEGIN * @param vDatedFrom Fecha desde * @param vDatedTo Fecha hasta */ - - CREATE OR REPLACE TEMPORARY TABLE tmp.`user` + + CREATE OR REPLACE TEMPORARY TABLE tmp.`user` SELECT w.id userFk FROM worker w WHERE w.id = vWorkerFk; - + CALL timeBusiness_calculate(vDatedFrom, vDatedTo); - + DROP TEMPORARY TABLE tmp.`user`; END ;; @@ -73546,30 +73547,30 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `timeControl_calculate`( - vDatedFrom DATETIME, + vDatedFrom DATETIME, vDatedTo DATETIME) BEGIN /* * @param vDatedFrom - * @param vDatedTo - * Cálculo de horas trabajadas por empleado y día, + * @param vDatedTo + * Cálculo de horas trabajadas por empleado y día, * sin tener en cuenta los días con fichadas incorrectas (tabla tmp.timeControlError) - * En el caso de haber hecho descanso y trabajado un mínimo de tiempo (vTimeToBreakTime), + * En el caso de haber hecho descanso y trabajado un mínimo de tiempo (vTimeToBreakTime), * se añade al tiempo de trabajo efectivo el descanso (vBreakTime) - * @return tmp.timeControlCalculate + * @return tmp.timeControlCalculate * (workerFk, dated, timeWorkSeconds, timeWorkSexagesimal, timeWorkDecimal, timed) */ DECLARE vHourToSeconds INTEGER; DECLARE vDatedFromYesterday DATETIME; - DECLARE vDatedToTomorrow DATETIME; + DECLARE vDatedToTomorrow DATETIME; DECLARE vTimeToBreakTime INT; DECLARE vBreakTime INT; - - SELECT DATE_SUB(vDatedFrom, INTERVAL 1 DAY), DATE_ADD(vDatedTo, INTERVAL 1 DAY) + + SELECT DATE_SUB(vDatedFrom, INTERVAL 1 DAY), DATE_ADD(vDatedTo, INTERVAL 1 DAY) INTO vDatedFromYesterday, vDatedToTomorrow; - + SELECT timeToBreakTime, breakTime INTO vTimeToBreakTime, vBreakTime - FROM workerTimeControlConfig + FROM workerTimeControlConfig LIMIT 1; CALL timeControl_getError(vDatedFrom, vDatedTo); @@ -73578,9 +73579,9 @@ BEGIN CREATE TEMPORARY TABLE tmp.workerTimeControl (INDEX (userFk), INDEX (timed)) ENGINE = MEMORY - SELECT DISTINCT(wtc.id), - wtc.userFk, - wtc.timed, + SELECT DISTINCT(wtc.id), + wtc.userFk, + wtc.timed, wtc.direction, TRUE isReal FROM workerTimeControl wtc @@ -73590,10 +73591,10 @@ BEGIN AND tce.id IS NULL ORDER BY wtc.userFk, wtc.timed ASC; - SELECT MAX(id) INTO @vCont + SELECT MAX(id) INTO @vCont FROM tmp.workerTimeControl; - DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControlAux; + DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControlAux; CREATE TEMPORARY TABLE tmp.workerTimeControlAux ( `id` int(11) , `userFk` int(10) unsigned , @@ -73606,14 +73607,14 @@ BEGIN -- Cambio de dia en medio de un descanso INSERT INTO tmp.workerTimeControlAux (id, userFk, timed, direction) - SELECT @vCont:= @vCont + 1 id, - userFk, - util.dayEnd(dated) timed, + SELECT @vCont:= @vCont + 1 id, + userFk, + util.dayEnd(dated) timed, 'middle' direction FROM(SELECT wtc.userFk, DATE(@lastTimed) dated, (@vIsOdd := NOT @vIsOdd) isOdd, - IF(@vIsOdd AND wtc.direction = 'middle' + IF(@vIsOdd AND wtc.direction = 'middle' AND DATE(timed) <> DATE(@lastTimed), TRUE, FALSE) hasBreak, @lastTimed := wtc.timed FROM tmp.workerTimeControl wtc @@ -73626,14 +73627,14 @@ BEGIN SET @vIsOdd := FALSE; INSERT INTO tmp.workerTimeControlAux (id, userFk, timed, direction) - SELECT @vCont:= @vCont + 1, - userFk, - DATE_ADD(sub.dated, INTERVAL 1 DAY), + SELECT @vCont:= @vCont + 1, + userFk, + DATE_ADD(sub.dated, INTERVAL 1 DAY), 'middle' FROM(SELECT wtc.userFk, DATE(@lastTimed) dated, (@vIsOdd := NOT @vIsOdd) isOdd, - IF(@vIsOdd AND wtc.direction = 'middle' + IF(@vIsOdd AND wtc.direction = 'middle' AND DATE(timed) <> DATE(@lastTimed), TRUE, FALSE) hasBreak, @lastTimed := wtc.timed FROM tmp.workerTimeControl wtc @@ -73644,9 +73645,9 @@ BEGIN -- Cambio de dia INSERT INTO tmp.workerTimeControlAux (id, userFk, timed, direction) - SELECT @vCont:= @vCont + 1 id, - sub.userFk, - util.dayEnd(sub.dated) timed, + SELECT @vCont:= @vCont + 1 id, + sub.userFk, + util.dayEnd(sub.dated) timed, 'out' direction FROM (SELECT MAX(wtc.timed) timed, wtc.userFk, date(wtc.timed) dated FROM workerTimeControl wtc @@ -73656,7 +73657,7 @@ BEGIN AND tce.id IS NULL GROUP BY wtc.userFk, DATE(wtc.timed) ) sub - JOIN tmp.workerTimeControl wtc ON wtc.timed = sub.timed + JOIN tmp.workerTimeControl wtc ON wtc.timed = sub.timed AND wtc.userFk = sub.userFk WHERE wtc.direction <> 'out'; @@ -73670,7 +73671,7 @@ BEGIN AND tce.id IS NULL GROUP BY wtc.userFk, DATE(wtc.timed) ) sub - JOIN tmp.workerTimeControl wtc ON wtc.timed = sub.timed + JOIN tmp.workerTimeControl wtc ON wtc.timed = sub.timed AND wtc.userFk = sub.userFk WHERE wtc.direction <> 'out'; @@ -73687,7 +73688,7 @@ BEGIN CREATE TEMPORARY TABLE tmp.workerBreakDays (INDEX (userFk), INDEX (dated)) ENGINE = MEMORY - SELECT sub.userFk, + SELECT sub.userFk, sub.dated FROM (SELECT (@vIsOdd := NOT @vIsOdd), IF(wtc.direction = 'in', @vIsOdd := TRUE, NULL), @@ -73696,7 +73697,7 @@ BEGIN IF(direction='in', @vDated := DATE(wtc.timed), @vDated) dated, wtc.userFk FROM tmp.workerTimeControl wtc - ORDER BY wtc.userFk, wtc.timed, wtc.id + ORDER BY wtc.userFk, wtc.timed, wtc.id LIMIT 10000000000000000000 )sub GROUP BY sub.userFk, sub.dated @@ -73707,9 +73708,9 @@ BEGIN SET @vLastTimed := 0; DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControlAux2; - CREATE TEMPORARY TABLE tmp.workerTimeControlAux2 + CREATE TEMPORARY TABLE tmp.workerTimeControlAux2 SELECT * - FROM tmp.workerTimeControl + FROM tmp.workerTimeControl WHERE timed BETWEEN vDatedFromYesterday AND vDatedTo ORDER BY userFk, timed, id; @@ -73722,7 +73723,7 @@ BEGIN IF(wb.userFk, vBreakTime, 0) + SUM(sub.timeWork) timeWorkSeconds, SEC_TO_TIME(IF(wb.userFk, vBreakTime, 0) + SUM(sub.timeWork)) timeWorkSexagesimal, (IF(wb.userFk, vBreakTime, 0) + SUM(sub.timeWork)) / vHourToSeconds timeWorkDecimal, - CAST(GROUP_CONCAT(DATE_FORMAT(sub.realTimed, "%H:%i") + CAST(GROUP_CONCAT(DATE_FORMAT(sub.realTimed, "%H:%i") ORDER BY sub.timed ASC SEPARATOR ' - ') AS CHAR(256)) timed FROM (SELECT (@vIsOdd := NOT @vIsOdd), IF(direction='in', @vIsOdd := TRUE, 0), @@ -73767,14 +73768,14 @@ BEGIN * @param vDatedTo Fecha hasta */ - CREATE OR REPLACE TEMPORARY TABLE tmp.`user` + CREATE OR REPLACE TEMPORARY TABLE tmp.`user` SELECT w.id userFk FROM vn.worker w; - + CALL vn.timeControl_calculate(vDatedFrom, vDatedTo); DROP TEMPORARY TABLE tmp.`user`; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -73794,21 +73795,21 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `timeControl_calculateByDepartment`(vDepartmentFk INT, vDatedFrom DATETIME, vDatedTo DATETIME) BEGIN /** - * @param vDepartmentFk + * @param vDepartmentFk * @param vDatedFrom workerTimeControl * @param vDatedTo workerTimeControl */ DROP TEMPORARY TABLE IF EXISTS tmp.`user`; - + CREATE TEMPORARY TABLE tmp.`user` SELECT DISTINCT b.workerFk userFk - FROM business AS b - WHERE (b.started BETWEEN vDatedFrom AND vDatedTo + FROM business AS b + WHERE (b.started BETWEEN vDatedFrom AND vDatedTo OR IFNULL(b.ended, vDatedTo) BETWEEN vDatedFrom AND vDatedTo OR (b.started <= vDatedFrom AND b.ended >= vDatedTo) ) AND b.departmentFk = vDepartmentFk ORDER BY b.ended DESC; - + CALL timeControl_calculate(vDatedFrom, vDatedTo); DROP TEMPORARY TABLE tmp.`user`; @@ -73833,19 +73834,19 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `timeControl_calculateByUser`(vUserF BEGIN /** - * @param vUserFk + * @param vUserFk * @param vDatedFrom workerTimeControl * @param vDatedTo workerTimeControl */ - + DROP TEMPORARY TABLE IF EXISTS tmp.`user`; - + CREATE TEMPORARY TABLE tmp.`user` SELECT id userFk - FROM account.user - WHERE id = vUserFk; + FROM account.user + WHERE id = vUserFk; CALL vn.timeControl_calculate(vDatedFrom, vDatedTo); - + DROP TEMPORARY TABLE tmp.`user`; END ;; @@ -73868,21 +73869,21 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `timeControl_calculateByWorker`(vWor BEGIN /** - * @param vWorkerFk + * @param vWorkerFk * @param vDatedFrom workerTimeControl * @param vDatedTo workerTimeControl */ - + DROP TEMPORARY TABLE IF EXISTS tmp.`user`; - + CREATE TEMPORARY TABLE tmp.`user` SELECT u.id userFk FROM account.user u JOIN vn.worker w ON w.userFk = u.id WHERE w.id = vWorkerFk; - + CALL vn.timeControl_calculate(vDatedFrom, vDatedTo); - + DROP TEMPORARY TABLE tmp.`user`; END ;; @@ -73905,12 +73906,12 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `timeControl_getError`(vDatedFrom DA BEGIN /* * @param vDatedFrom - * @param vDatedTo + * @param vDatedTo * @table tmp.`user`(userFk) * Fichadas incorrectas de las cuales no se puede calcular horas trabajadas * @return tmp.timeControlError (id) */ - DECLARE vDayMaxTime INTEGER; + DECLARE vDayMaxTime INTEGER; SET @journeyCounter := 0; SET @lastUserFk := NULL; @@ -73918,16 +73919,16 @@ BEGIN SELECT dayMaxTime INTO vDayMaxTime FROM workerTimeControlConfig LIMIT 1; - DROP TEMPORARY TABLE IF EXISTS tmp.timeControl; - CREATE TEMPORARY TABLE tmp.timeControl + DROP TEMPORARY TABLE IF EXISTS tmp.timeControl; + CREATE TEMPORARY TABLE tmp.timeControl (INDEX(id), INDEX(journeyCounter)) ENGINE = MEMORY SELECT sub.id, - sub.direction, + sub.direction, sub.timed, IF(sub.direction = 'in' OR @hasOut OR sub.userFk <> @lastUserFk, @journeyCounter := @journeyCounter + 1, @journeyCounter) journeyCounter, - @lastUserFk := sub.userFk workerFk, - IF(sub.direction = 'out', @hasOut:= TRUE, @hasOut:= FALSE) + @lastUserFk := sub.userFk workerFk, + IF(sub.direction = 'out', @hasOut:= TRUE, @hasOut:= FALSE) FROM ( SELECT DISTINCT wtc.id, wtc.direction, @@ -73938,36 +73939,36 @@ BEGIN WHERE wtc.timed BETWEEN DATE_SUB(vDatedFrom, INTERVAL 1 DAY) AND DATE_ADD(vDatedTo, INTERVAL 1 DAY) ORDER BY wtc.userFk, wtc.timed ) sub; - - DROP TEMPORARY TABLE IF EXISTS tmp.timeControlAux; + + DROP TEMPORARY TABLE IF EXISTS tmp.timeControlAux; CREATE TEMPORARY TABLE tmp.timeControlAux (INDEX(id), INDEX(journeyCounter)) ENGINE = MEMORY SELECT * FROM tmp.timeControl; - DROP TEMPORARY TABLE IF EXISTS tmp.timeControlError; - CREATE TEMPORARY TABLE tmp.timeControlError + DROP TEMPORARY TABLE IF EXISTS tmp.timeControlError; + CREATE TEMPORARY TABLE tmp.timeControlError (INDEX(id)) ENGINE = MEMORY - SELECT id + SELECT id FROM tmp.timeControlAux tca JOIN ( - SELECT journeyCounter, + SELECT journeyCounter, UNIX_TIMESTAMP(MAX(timed)) - UNIX_TIMESTAMP(MIN(timed)) timeWork, - SUM(direction = 'in') totalIn, + SUM(direction = 'in') totalIn, SUM(direction = 'out') totalOut, timed FROM tmp.timeControl GROUP BY journeyCounter - HAVING COUNT(*) MOD 2 = 1 - OR totalIn <> 1 - OR totalOut <> 1 + HAVING COUNT(*) MOD 2 = 1 + OR totalIn <> 1 + OR totalOut <> 1 OR timeWork >= vDayMaxTime )sub ON sub.journeyCounter = tca.journeyCounter WHERE sub.timed BETWEEN vDatedFrom AND vDatedTo; - DROP TEMPORARY TABLE IF EXISTS tmp.timeControl; - DROP TEMPORARY TABLE IF EXISTS tmp.timeControlAux; + DROP TEMPORARY TABLE IF EXISTS tmp.timeControl; + DROP TEMPORARY TABLE IF EXISTS tmp.timeControlAux; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -73990,7 +73991,7 @@ proc: BEGIN * deprecated call workerTimeControl_check */ CALL vn.workerTimeControl_check(vUserFk,vDated,vTabletFk); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -74046,12 +74047,12 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `travelVolume`(vTravelFk INT) BEGIN - - SELECT w1.name AS ORI, - w2.name AS DES, + + SELECT w1.name AS ORI, + w2.name AS DES, tr.shipped shipment, tr.landed landing, - a.name Agencia, + a.name Agencia, s.name Proveedor, e.id Id_Entrada, e.invoiceNumber Referencia, @@ -74059,18 +74060,18 @@ BEGIN vn.item_getVolume(b.itemFk ,b.packageFk)) / vc.trolleyM3 / 1000000 ,1) AS DECIMAL(10,2)) AS CC, CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) * vn.item_getVolume(b.itemFk ,b.packageFk)) / vc.palletM3 / 1000000,1) AS DECIMAL(10,2)) AS espais - FROM vn.buy b - JOIN vn.entry e ON e.id = b.entryFk - JOIN vn.supplier s ON s.id = e.supplierFk - JOIN vn.travel tr ON tr.id = e.travelFk + FROM vn.buy b + JOIN vn.entry e ON e.id = b.entryFk + JOIN vn.supplier s ON s.id = e.supplierFk + JOIN vn.travel tr ON tr.id = e.travelFk JOIN vn.agencyMode a ON a.id = tr.agencyModeFk - JOIN vn.warehouse w1 ON w1.id = tr.warehouseInFk - JOIN vn.warehouse w2 ON w2.id = tr.warehouseOutFk - JOIN vn.volumeConfig vc - JOIN vn.item i ON i.id = b.itemFk + JOIN vn.warehouse w1 ON w1.id = tr.warehouseInFk + JOIN vn.warehouse w2 ON w2.id = tr.warehouseOutFk + JOIN vn.volumeConfig vc + JOIN vn.item i ON i.id = b.itemFk JOIN vn.itemType it ON it.id = i.typeFk WHERE tr.id = vTravelFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -74126,11 +74127,11 @@ BEGIN * @param vShipped The shipment date * @param vLanded The landing date */ - + IF vLanded < vShipped THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Landing cannot be lesser than shipment'; - END IF; + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -74194,7 +74195,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `travel_checkWarehouseIsFeedStock`(v proc: BEGIN /* * Check that the warehouse is not Feed Stock - * + * * @vWarehouseFk param warehouse id */ IF vWarehouseFk IS NULL THEN @@ -74282,13 +74283,13 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `travel_cloneWithEntries`( - IN vTravelFk INT, - IN vDateStart DATE, + IN vTravelFk INT, + IN vDateStart DATE, IN vDateEnd DATE, IN vWarehouseOutFk INT, - IN vWarehouseInFk INT, - IN vRef VARCHAR(255), - IN vAgencyModeFk INT, + IN vWarehouseInFk INT, + IN vRef VARCHAR(255), + IN vAgencyModeFk INT, OUT vNewTravelFk INT) BEGIN /** @@ -74312,29 +74313,29 @@ BEGIN FROM entry e JOIN travel t ON t.id = e.travelFk WHERE e.travelFk = vTravelFk; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN + BEGIN ROLLBACK; RESIGNAL; END; - + START TRANSACTION; INSERT INTO travel (shipped, landed, warehouseInFk, warehouseOutFk, agencyModeFk, `ref`, isDelivered, isReceived, m3, cargoSupplierFk, kg,clonedFrom) SELECT vDateStart, vDateEnd, vWarehouseInFk, vWarehouseOutFk, vAgencyModeFk, vRef, isDelivered, isReceived, m3,cargoSupplierFk, kg,vTravelFk FROM travel WHERE id = vTravelFk; - + SET vNewTravelFk = LAST_INSERT_ID(); SET vDone = FALSE; SET @isModeInventory = TRUE; OPEN vRsEntry; - + l: LOOP SET vDone = FALSE; FETCH vRsEntry INTO vAuxEntryFk; @@ -74403,11 +74404,11 @@ BEGIN SELECT COUNT(*) INTO vTotalEntries FROM entry WHERE travelFk = vTravelFk; - + UPDATE travel SET totalEntries = vTotalEntries WHERE id = vTravelFk; - + DELETE FROM travelRecalc WHERE travelFk = vTravelFk; END LOOP; @@ -74438,10 +74439,10 @@ BEGIN WHERE id = vSelf; SELECT e.id entryFk - FROM travel t - JOIN entry e ON e.travelFk = t.id - JOIN buy b ON b.entryFk = e.id - WHERE t.id = vTravelFk + FROM travel t + JOIN entry e ON e.travelFk = t.id + JOIN buy b ON b.entryFk = e.id + WHERE t.id = vTravelFk AND (b.packing IS NULL OR b.packageFk IS NULL); END ;; DELIMITER ; @@ -74464,7 +74465,7 @@ BEGIN /* * Desplaza al dia siguiente los travels que contengan redadas y avisa a los compradores - * + * */ DECLARE vDone BOOL DEFAULT FALSE; DECLARE vWorkerName VARCHAR(50); @@ -74476,7 +74477,7 @@ BEGIN SELECT GROUP_CONCAT( DISTINCT CONCAT('https://salix.verdnatura.es/#!/travel/', ttr.id, '/summary ') ORDER BY ttr.id SEPARATOR '\n\r'), u.name FROM tmp.travel ttr - JOIN entry e ON e.travelFk = ttr.id + JOIN entry e ON e.travelFk = ttr.id JOIN buy b ON b.entryFk = e.id JOIN item i ON i.id = b.itemFk JOIN itemType it ON it.id = i.typeFk @@ -74484,19 +74485,19 @@ BEGIN GROUP BY u.name; DECLARE CONTINUE HANDLER FOR NOT FOUND - SET vDone = TRUE; + SET vDone = TRUE; DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN ROLLBACK; RESIGNAL; END; - + DROP TEMPORARY TABLE IF EXISTS tmp.travel; CREATE TEMPORARY TABLE tmp.travel SELECT tr.id,tr.landed FROM travel tr - JOIN entry e ON e.travelFk = tr.id + JOIN entry e ON e.travelFk = tr.id WHERE tr.landed = util.tomorrow() AND e.isRaid GROUP BY tr.id; @@ -74554,7 +74555,7 @@ proc: BEGIN IF vSelf IS NULL THEN LEAVE proc; END IF; - + INSERT IGNORE INTO travelRecalc SET travelFk = vSelf; END ;; DELIMITER ; @@ -74580,10 +74581,10 @@ BEGIN * @param vItemFk id del item * @param vPacking nuevo packing */ - + DECLARE vAuctionWarehouseFk INT; DECLARE vMainWarehouseFk INT; - + SELECT warehouseFk INTO vAuctionWarehouseFk FROM auctionConfig; @@ -74643,7 +74644,7 @@ BEGIN FROM travelClonedWeekly WHERE travelFk; - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; SET vCounter = vSinceWeek; @@ -74705,12 +74706,12 @@ BEGIN /* * Plantilla para modificar reemplazar todos los tags * por los valores que tienen los articulos - * + * * @param vTypeFk tipo a modificar - * + * */ - DELETE it.* - FROM itemTag it + DELETE it.* + FROM itemTag it JOIN item i ON i.id = it.itemFk WHERE i.typeFk = vTypeFk; @@ -74719,40 +74720,40 @@ BEGIN FROM item i JOIN tag t ON t.name = 'Longitud' COLLATE utf8_general_ci WHERE i.typeFk = vTypeFk; - + INSERT INTO itemTag(itemFk, tagFk, value, priority) SELECT i.id, t.id, i.category, 5 FROM item i JOIN tag t ON t.name = 'Categoria' COLLATE utf8_general_ci WHERE i.typeFk = vTypeFk; - + INSERT INTO itemTag(itemFk, tagFk, value, priority) SELECT i.id, t.id, ink.name, 2 FROM item i JOIN tag t ON t.name = 'Color' COLLATE utf8_general_ci JOIN ink ON ink.id = i.inkFk WHERE i.typeFk = vTypeFk; - + INSERT INTO itemTag(itemFk, tagFk, value, priority) SELECT i.id, t.id, p.name, 3 FROM item i JOIN tag t ON t.name = 'Productor' COLLATE utf8_general_ci JOIN producer p ON p.id = i.producerFk - WHERE i.typeFk = vTypeFk; - + WHERE i.typeFk = vTypeFk; + INSERT INTO itemTag(itemFk, tagFk, value, priority) SELECT i.id, t.id, o.name, 4 FROM item i JOIN tag t ON t.name = 'Origen' COLLATE utf8_general_ci JOIN origin o ON o.id = i.originFk WHERE i.typeFk = vTypeFk; - /* + /* INSERT INTO itemTag(itemFk, tagFk, value, priority) SELECT i.id, t.id, i.stems, 6 FROM item i JOIN tag t ON t.name = 'Tallos' COLLATE utf8_general_ci - WHERE i.typeFk = vTypeFk; - */ + WHERE i.typeFk = vTypeFk; + */ -- CALL itemTagArrangedUpdate(NULL); END ;; @@ -74775,7 +74776,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `updatePedidosInternos`(vItemFk INT) BEGIN UPDATE vn.item SET upToDown = 0 WHERE item.id = vItemFk; - + END ;; DELIMITER ; @@ -74803,7 +74804,7 @@ BEGIN SELECT vp.regex INTO vRegex FROM vehiclePlateRegex vp WHERE vp.countryCodeFk = vCountryCodeFk; - + IF NOT vNumberPlate REGEXP BINARY (vRegex)THEN CALL util.throw(CONCAT('Error: la matricula ', vNumberPlate, ' no es valida para ',vCountryCodeFk)); END IF; @@ -74836,7 +74837,7 @@ proc:BEGIN ROLLBACK; RESIGNAL; END; - + SELECT eventEarlyDays INTO vEventEarlyDays FROM vehicleConfig; @@ -74854,7 +74855,7 @@ proc:BEGIN IF NOT vHasEvents THEN LEAVE proc; END IF; - + START TRANSACTION; SELECT util.notification_send('vehicle-event-expired', @@ -74889,21 +74890,21 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `visible_getMisfit`(vSectorFk INT) BEGIN - + /* Devuelve una tabla temporal con los descuadres entre el visible teórico y lo ubicado en la práctica - * + * * @param vSectorFk Identificador de vn.sector - * + * * @return tmp.stockMisfit(itemFk, visible, parked) */ - + DECLARE vCalcVisibleFk INT; DECLARE vWarehouseFk INT; SELECT warehouseFk INTO vWarehouseFk - FROM vn.sector s + FROM vn.sector s WHERE s.id = vSectorFk; - + CALL cache.visible_refresh(vCalcVisibleFk, FALSE, vWarehouseFk); DROP TEMPORARY TABLE IF EXISTS tmp.stockMisfit; @@ -74916,17 +74917,17 @@ BEGIN INSERT INTO tmp.stockMisfit(itemFk, parked) SELECT iss.itemFk , sum(iss.visible ) - FROM vn.itemShelvingStock iss - JOIN vn.sector s ON s.id = iss.sectorFk + FROM vn.itemShelvingStock iss + JOIN vn.sector s ON s.id = iss.sectorFk WHERE vSectorFk IN (s.id, s.sonFk) GROUP BY iss.itemFk; - + INSERT INTO tmp.stockMisfit(itemFk, visible) - SELECT v.item_id , v.visible - FROM cache.visible v - WHERE v.calc_id = vCalcVisibleFk + SELECT v.item_id , v.visible + FROM cache.visible v + WHERE v.calc_id = vCalcVisibleFk ON DUPLICATE KEY UPDATE visible = v.visible; - + DELETE FROM tmp.stockMisfit WHERE visible = parked; @@ -74950,17 +74951,17 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `warehouseFitting`(IN vWhOrigin INT BEGIN DECLARE vCacheVisibleOriginFk INT; DECLARE vCacheVisibleDestinyFk INT; - + CALL cache.visible_refresh(vCacheVisibleOriginFk, FALSE, vWhOrigin); CALL cache.visible_refresh(vCacheVisibleDestinyFk, FALSE, vWhDestiny); - + SELECT i.id itemFk, i.longName, i.size, i.subName, vOrigin.visible AS Origen, vDestiny.visible Destino - + FROM vn.item i JOIN vn.itemType it ON it.id = i.typeFk LEFT JOIN cache.visible vOrigin ON vOrigin.calc_id = vCacheVisibleOriginFk AND vOrigin.item_id = i.id @@ -74989,13 +74990,13 @@ BEGIN DECLARE vWhOrigin INT; DECLARE vWhDestiny INT; - + SELECT warehouseInFk, warehouseOutFk INTO vWhDestiny, vWhOrigin FROM vn.travel WHERE id = vTravelFk; - + CALL vn.warehouseFitting(vWhOrigin, vWhDestiny); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -75059,7 +75060,7 @@ BEGIN * Calcula los días y horas de vacaciones en función de un contrato y año * * @param vYear - * @param vBusinessFk + * @param vBusinessFk * @return tmp.workerCalendarCalculateBusiness (days, hours, daysEnjoyed, hoursEnjoyed) */ DECLARE vStarted DATE; @@ -75071,17 +75072,17 @@ BEGIN DECLARE vPayedHolidays DECIMAL(5,2); DECLARE vDifDays INT; - SELECT IF(b.started < CONCAT(vYear,"-01-01"), CONCAT(vYear,"-01-01"),b.started), - IF(b.ended IS NULL OR YEAR(b.ended)>vYear , CONCAT(vYear,"-12-31"), b.ended), + SELECT IF(b.started < CONCAT(vYear,"-01-01"), CONCAT(vYear,"-01-01"),b.started), + IF(b.ended IS NULL OR YEAR(b.ended)>vYear , CONCAT(vYear,"-12-31"), b.ended), IF(wbt.hasHolidayEntitlement, w.days, 0), c.hoursWeek, IF(YEAR(b.ended) = vYear, b.payedHolidays, 0) payedHolidays - INTO vStarted, - vEnded, - vDaysHoliday, + INTO vStarted, + vEnded, + vDaysHoliday, vHoursWeek, vPayedHolidays - FROM business b + FROM business b JOIN workerBusinessType wbt ON wbt.id = b.workerBusinessTypeFk JOIN workCenterHoliday w ON w.workcenterFk = b.workcenterFk LEFT JOIN calendarType c ON c.id = b.calendarTypeFk @@ -75089,23 +75090,23 @@ BEGIN AND w.year = vYear; DROP TEMPORARY TABLE IF EXISTS tmp.workerCalendarCalculateBusiness; - + IF vStarted < vEnded THEN SET vDifDays = DAYOFYEAR(vEnded) - DAYOFYEAR(vStarted) + 1; - SELECT IFNULL(SUM(a.holidayEntitlementRate), 0), + SELECT IFNULL(SUM(a.holidayEntitlementRate), 0), SUM(-(a.discountRate - 1)) + vPayedHolidays - INTO vDaysToSubtract, - vDaysHolidayEnjoyed + INTO vDaysToSubtract, + vDaysHolidayEnjoyed FROM calendar c JOIN absenceType a ON a.id = c.dayOffTypeFk JOIN business b ON b.id = c.businessFk - WHERE b.id = vBusinessFk + WHERE b.id = vBusinessFk AND YEAR(c.dated) = vYear; END IF; - CREATE TEMPORARY TABLE tmp.workerCalendarCalculateBusiness + CREATE TEMPORARY TABLE tmp.workerCalendarCalculateBusiness ENGINE = MEMORY SELECT @days := IFNULL(ROUND((vDaysHoliday * (vDifDays - vDaysToSubtract) / IF(util.isLeapYear(vYear) , 366, 365)), 1), 0) days, @days * (vHoursWeek / 5) hours, @@ -75133,32 +75134,32 @@ BEGIN /** * Calcula los días y horas de vacaciones en función de un trabajador y año * - * @param vYear - * @param vWorkerFk + * @param vYear + * @param vWorkerFk * @return tmp.workerCalendarCalculateYear (days, hours, daysEnjoyed, hoursEnjoyed) - */ + */ DECLARE vDone BOOL; DECLARE vBusinessFk INT; DECLARE cur CURSOR FOR - SELECT b.id + SELECT b.id FROM business b - WHERE vYear BETWEEN YEAR(b.started) AND IFNULL(YEAR(b.ended), vYear) + WHERE vYear BETWEEN YEAR(b.started) AND IFNULL(YEAR(b.ended), vYear) AND b.workerFk = vWorkerFk; DECLARE CONTINUE HANDLER FOR NOT FOUND - SET vDone = TRUE; - + SET vDone = TRUE; + DROP TEMPORARY TABLE IF EXISTS tmp.workerCalendarCalculateYear; CREATE TEMPORARY TABLE tmp.workerCalendarCalculateYear - (days DEC(5,2), + (days DEC(5,2), hours DEC(5,2), - daysEnjoyed DEC(5,2), - hoursEnjoyed DEC(5,2)) + daysEnjoyed DEC(5,2), + hoursEnjoyed DEC(5,2)) ENGINE = MEMORY; INSERT INTO tmp.workerCalendarCalculateYear VALUES(0, 0, 0, 0); - + OPEN cur; l: LOOP @@ -75171,12 +75172,12 @@ BEGIN CALL workerCalendar_calculateBusiness(vYear, vBusinessFk); UPDATE tmp.workerCalendarCalculateYear w - JOIN tmp.workerCalendarCalculateBusiness wc + JOIN tmp.workerCalendarCalculateBusiness wc SET w.days = w.days + wc.days, w.hours = w.hours + wc.hours, w.daysEnjoyed = w.daysEnjoyed + wc.daysEnjoyed, w.hoursEnjoyed = w.hoursEnjoyed + wc.hoursEnjoyed; - + DROP TEMPORARY TABLE tmp.workerCalendarCalculateBusiness; END LOOP; @@ -75201,7 +75202,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerCreate`( vFirstname VARCHAR(50), - vLastName VARCHAR(50), + vLastName VARCHAR(50), vCode CHAR(3), vBossFk INT, vUserFk INT, @@ -75213,7 +75214,7 @@ BEGIN * Create new worker * */ - INSERT INTO worker(id, code, firstName, lastName, bossFk, fi, birth,userFk) + INSERT INTO worker(id, code, firstName, lastName, bossFk, fi, birth,userFk) VALUES (vUserFk, vCode, vFirstname, vLastName, vBossFk, vFi, vBirth,vUserFk); END ;; DELIMITER ; @@ -75279,20 +75280,20 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.workerDepartmentByDate; CREATE TEMPORARY TABLE tmp.workerDepartmentByDate ENGINE = MEMORY - SELECT w.id userFk, - w.lastName name, - w.firstName firstname, - d.name department, + SELECT w.id userFk, + w.lastName name, + w.firstName firstname, + d.name department, d.id departmentFk, - b.started, - d.isProduction, + b.started, + d.isProduction, CAST(12 * b.amount / ct.hoursWeek / 52 AS DECIMAL(10,2)) costeHora, w.fi nif FROM business b JOIN calendarType ct ON ct.id = b.calendarTypeFk JOIN department d ON d.id = b.departmentFk JOIN worker w ON w.id = b.workerFk - WHERE b.started <= vDate + WHERE b.started <= vDate AND (b.ended > vDate OR b.ended IS NULL); END ;; DELIMITER ; @@ -75319,18 +75320,18 @@ mainLabel:BEGIN DELETE FROM account.account WHERE id = vUserId; - UPDATE account.user + UPDATE account.user SET role = 2 - WHERE id = vUserId; + WHERE id = vUserId; - DELETE FROM pbx.sip - WHERE user_id = vUserId; + DELETE FROM pbx.sip + WHERE user_id = vUserId; UPDATE `client` c JOIN payMethod p ON p.name = 'CONTADO' SET c.credit = 0, c.payMethodFk = p.id, hasCoreVnl = FALSE WHERE c.id = vUserId; - + UPDATE `client` c SET c.salesPersonFk = null WHERE c.salesPersonFk = vUserId; @@ -75359,12 +75360,12 @@ BEGIN SELECT b.workerFk FROM business b JOIN vn.worker w ON w.id = b.workerFk - JOIN account.account a ON a.id = b.workerFk - LEFT JOIN (SELECT b.workerFk + JOIN account.account a ON a.id = b.workerFk + LEFT JOIN (SELECT b.workerFk FROM business b WHERE (ended IS NULL OR ended >=util.VN_CURDATE()) )sub ON sub.workerFk = a.id - LEFT JOIN vn.workerDisableExcluded wd ON wd.workerFk = b.workerFk + LEFT JOIN vn.workerDisableExcluded wd ON wd.workerFk = b.workerFk WHERE sub.workerFk IS NULL AND wd.workerFk IS NULL GROUP BY w.id; @@ -75382,7 +75383,7 @@ BEGIN END WHILE; CLOSE rs; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -75446,19 +75447,19 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerJourney_replace`( - vDatedFrom DATE, - vDatedTo DATE, + vDatedFrom DATE, + vDatedTo DATE, vWorkerFk INT) BEGIN /** - * Actualiza la tabla workerJourney para que actue como caché permanente revisable + * Actualiza la tabla workerJourney para que actue como caché permanente revisable * de las jornadas laborales. * @param vDatedFrom workerTimeControl * @param vDatedTo workerTimeControl * @param vWorkerFk, en caso de pasar 0 ó NULL se aplica a todos - */ + */ DECLARE vDatedTimeTo DATETIME; - DECLARE vMaxTimePerDay INT; + DECLARE vMaxTimePerDay INT; DECLARE vMinHoursToBreak DECIMAL(10,2); DECLARE vBreakHours DECIMAL(10,2); DECLARE vMonthByYear INT; @@ -75466,57 +75467,57 @@ BEGIN DECLARE vMonthsByYear INT DEFAULT 12; DECLARE vDaysByWeek INT DEFAULT 5; DECLARE vDatedFromYesterday DATETIME; - DECLARE vDatedToTomorrow DATETIME; - - SELECT DATE_SUB(vDatedFrom, INTERVAL 1 DAY), DATE_ADD(vDatedTo, INTERVAL 1 DAY) + DECLARE vDatedToTomorrow DATETIME; + + SELECT DATE_SUB(vDatedFrom, INTERVAL 1 DAY), DATE_ADD(vDatedTo, INTERVAL 1 DAY) INTO vDatedFromYesterday, vDatedToTomorrow; SET vDatedTimeTo = util.dayEnd(vDatedTo); - - SELECT minHoursToBreak, breakHours, maxTimePerDay + + SELECT minHoursToBreak, breakHours, maxTimePerDay INTO vMinHoursToBreak, vBreakHours, vMaxTimePerDay FROM workerTimeControlConfig; DELETE FROM workerJourney - WHERE dated BETWEEN vDatedFrom AND vDatedTo + WHERE dated BETWEEN vDatedFrom AND vDatedTo AND NOT isPaid AND NOT isUpdated - AND (vWorkerFk IS NULL OR userFK = vWorkerFk); + AND (vWorkerFk IS NULL OR userFK = vWorkerFk); - -- Se inserta todos los días del periodo por worker y business en el rango de fechas. + -- Se inserta todos los días del periodo por worker y business en el rango de fechas. INSERT IGNORE INTO workerJourney(userFk, dated, businessFk) SELECT b.workerFk, t.dated, b.id - FROM business b + FROM business b JOIN time t ON t.dated BETWEEN b.started AND IFNULL(b.ended,util.VN_CURDATE()) WHERE t.dated BETWEEN vDatedFrom AND vDatedTo AND (vWorkerFk IS NULL OR b.workerFk = vWorkerFk) ORDER BY b.workerFk, t.dated, b.id; - + DROP TEMPORARY TABLE IF EXISTS tmp.`user`; IF vWorkerFk THEN CALL timeControl_calculateByUser(vWorkerFk, vDatedFrom , vDatedTimeTo); - CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` - SELECT vWorkerFk userFk; + CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` + SELECT vWorkerFk userFk; ELSE CALL timeControl_calculateAll(vDatedFrom, vDatedTimeTo); - CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` + CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` SELECT id userFk FROM worker w; - END IF; + END IF; UPDATE workerJourney wj JOIN tmp.timeControlCalculate t ON wj.dated = t.dated AND wj.userFk = t.userFk - SET wj.total = CAST(IF(t.timeWorkDecimal >= vMinHoursToBreak, - t.timeWorkDecimal - vBreakHours, + SET wj.total = CAST(IF(t.timeWorkDecimal >= vMinHoursToBreak, + t.timeWorkDecimal - vBreakHours, t.timeWorkDecimal) AS DECIMAL (10,2)), wj.lunch = IF(t.timeWorkDecimal >= vMinHoursToBreak , vBreakHours , 0) WHERE wj.dated BETWEEN vDatedFrom AND vDatedTo AND NOT wj.isPaid AND NOT wj.isUpdated AND (vWorkerFk IS NULL OR wj.userFk = vWorkerFk); - - -- NOCTURNIDAD + + -- NOCTURNIDAD CALL timeControl_getError(vDatedFrom, vDatedTimeTo); SET @vIsOdd := TRUE; @@ -75526,9 +75527,9 @@ BEGIN CREATE TEMPORARY TABLE tmp.workerTimeControl (INDEX (userFk), INDEX (timed)) ENGINE = MEMORY - SELECT DISTINCT(wtc.id), - wtc.userFk, - wtc.timed, + SELECT DISTINCT(wtc.id), + wtc.userFk, + wtc.timed, wtc.direction FROM workerTimeControl wtc JOIN tmp.`user` w ON w.userFk = wtc.userFk @@ -75538,10 +75539,10 @@ BEGIN AND (vWorkerFk IS NULL OR wtc.userFk = vWorkerFk) ORDER BY wtc.userFk, wtc.timed ASC; - SELECT MAX(id) INTO @vCont + SELECT MAX(id) INTO @vCont FROM tmp.workerTimeControl; - DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControlAux; + DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControlAux; CREATE TEMPORARY TABLE tmp.workerTimeControlAux ( `id` int(11) , `userFk` int(10) unsigned , @@ -75563,9 +75564,9 @@ BEGIN DATE(@lastTimed) dated, @lastUserFk lastUserFk, IF(direction ='middle', @vIsOdd := NOT @vIsOdd, FALSE) isOdd, - IF(@vIsOdd - AND @lastDirection = 'middle' - AND (DATE(@lastTimed) <> date(timed) + IF(@vIsOdd + AND @lastDirection = 'middle' + AND (DATE(@lastTimed) <> date(timed) OR @lastUserFk <> userFk), TRUE, FALSE) hasBreak, @lastTimed := wtc.timed, @lastUserFk := userFk, @@ -75579,16 +75580,16 @@ BEGIN SET @lastDirection := NULL; INSERT INTO tmp.workerTimeControlAux (id, userFk, timed, direction) - SELECT @vCont:= @vCont + 1, - lastUserFk, - DATE_ADD(sub.dated, INTERVAL 1 DAY), + SELECT @vCont:= @vCont + 1, + lastUserFk, + DATE_ADD(sub.dated, INTERVAL 1 DAY), 'middle' FROM (SELECT IF(@lastUserFk <> userFk, @vIsOdd := TRUE, NULL), DATE(@lastTimed) dated, @lastUserFk lastUserFk, IF(direction ='middle', @vIsOdd := NOT @vIsOdd, FALSE) isOdd, - IF(@vIsOdd - AND @lastDirection = 'middle' + IF(@vIsOdd + AND @lastDirection = 'middle' AND (DATE(@lastTimed)<>date(timed) OR @lastUserFk<>userFk), TRUE, FALSE) hasBreak, @lastTimed := wtc.timed, @@ -75601,7 +75602,7 @@ BEGIN -- Cambio de dia INSERT INTO tmp.workerTimeControlAux (id, userFk, timed, direction) SELECT @vCont:= @vCont + 1, - wtc.userFk, + wtc.userFk, util.dayEnd(date(wtc.timed)), 'out' FROM workerTimeControl wtc @@ -75612,8 +75613,8 @@ BEGIN GROUP BY wtc.userFk, DATE(wtc.timed); INSERT INTO tmp.workerTimeControlAux (id, userFk, timed, direction) - SELECT @vCont:= @vCont + 1, - wtc.userFk, + SELECT @vCont:= @vCont + 1, + wtc.userFk, DATE_ADD(date(wtc.timed), INTERVAL 1 DAY), 'in' FROM workerTimeControl wtc @@ -75639,8 +75640,8 @@ BEGIN IF(@vIsOdd, @vLastTimed:=UNIX_TIMESTAMP(timed),@vLastTimed), IF(direction='in', @vDated := DATE(wtc.timed), @vDated ) dated, wtc.userFk, - IF(UNIX_TIMESTAMP(timed)- @vLastTimed < vMaxTimePerDay, - workerNigthlyHours_calculate(FROM_UNIXTIME(@vLastTimed), wtc.timed), + IF(UNIX_TIMESTAMP(timed)- @vLastTimed < vMaxTimePerDay, + workerNigthlyHours_calculate(FROM_UNIXTIME(@vLastTimed), wtc.timed), 0) NigthlyHours, @lastUserFk := userFk FROM (SELECT DISTINCT(wtc.id), wtc.userFk, wtc.timed, wtc.direction @@ -75653,7 +75654,7 @@ BEGIN ) wtc ORDER BY wtc.userFk, wtc.timed )sub - WHERE sub.dated BETWEEN vDatedFrom AND vDatedTo + WHERE sub.dated BETWEEN vDatedFrom AND vDatedTo GROUP BY userFk, sub.dated )night ON night.userFk = wj.userFk AND night.dated = wj.dated SET wj.nocturn = night.NigthlyHours @@ -75665,8 +75666,8 @@ BEGIN UPDATE workerJourney wj JOIN business b ON b.id = wj.businessFk JOIN calendarType ct ON ct.id = b.calendarTypeFk - SET wj.priceOrdinaryHour = - (vMonthsByYear * b.amount) / + SET wj.priceOrdinaryHour = + (vMonthsByYear * b.amount) / (vWeeksByYear * ct.hoursWeek), wj.contractJourney = ct.hoursWeek / vDaysByWeek WHERE wj.dated BETWEEN vDatedFrom AND vDatedTo @@ -75674,7 +75675,7 @@ BEGIN AND NOT wj.isPaid AND NOT isUpdated; - -- Precio Extras, Vacaciones y Nocturnas + -- Precio Extras, Vacaciones y Nocturnas UPDATE workerJourney wj JOIN(SELECT MAX(w.dated), t.dated, w.holidayInc, w.nightInc, w.extraInc FROM time t @@ -75698,12 +75699,12 @@ BEGIN WHERE ct.isPartial AND wj.dated BETWEEN vDatedFrom AND vDatedTo AND (vWorkerFk IS NULL OR wj.userFk = vWorkerFk) - AND NOT wj.isPaid + AND NOT wj.isPaid AND NOT wj.isUpdated; -- Ausencias UPDATE workerJourney wj - JOIN businessCalendar bc ON bc.businessFk = wj.businessFk + JOIN businessCalendar bc ON bc.businessFk = wj.businessFk AND bc.dated = wj.dated JOIN absenceType ab ON ab.id = bc.absenceTypeFk SET wj.permission = ab.permissionRate * wj.contractJourney, @@ -75718,7 +75719,7 @@ BEGIN UPDATE workerJourney SET holiday = IF(DAYNAME(dated)='sábado', 0, total), contractJourney = 0 - WHERE DAYNAME(dated) IN ('sábado', 'domingo') + WHERE DAYNAME(dated) IN ('sábado', 'domingo') AND dated BETWEEN vDatedFrom AND vDatedTo AND (vWorkerFk IS NULL OR userFk = vWorkerFk) AND NOT isPaid @@ -75727,8 +75728,8 @@ BEGIN -- Festivos por centro de trabajo UPDATE workerJourney wj JOIN calendarHolidays ch ON ch.dated = wj.dated - JOIN business b ON b.id = wj.businessFk - AND b.workcenterFk = ch.workcenterFk + JOIN business b ON b.id = wj.businessFk + AND b.workcenterFk = ch.workcenterFk SET wj.holiday = wj.total, wj.permission = wj.contractJourney, wj.contractJourney = 0 @@ -75738,7 +75739,7 @@ BEGIN AND NOT wj.isUpdated; -- Horas extras - UPDATE workerJourney + UPDATE workerJourney SET extra = lunch + total - contractJourney WHERE dated BETWEEN vDatedFrom AND vDatedTo AND (vWorkerFk IS NULL OR userFk = vWorkerFk) @@ -75768,15 +75769,15 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerMistakeType_get`() BEGIN - + /** * Obtiene los tipos de error para los trabajadores */ - - SELECT code, description - FROM workerMistakeType + + SELECT code, description + FROM workerMistakeType ORDER BY description; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -75803,7 +75804,7 @@ BEGIN * */ INSERT INTO vn.workerMistake(userFk, workerMistakeTypeFk) - VALUES(vWorkerFk, vWorkerMistakeTypeFk); + VALUES(vWorkerFk, vWorkerMistakeTypeFk); END ;; DELIMITER ; @@ -75826,11 +75827,11 @@ BEGIN /*INSERT INTO workerTimeControl(userFk, timed, manual, warehouseFk) VALUES(vUserFk, vDated, FALSE, vWarehouseFk); - + CALL vn.workerTimeControlSOWP(vUserFk , vDated);*/ - + CALL vn.workerTimeControl_add(vUserFk,vWarehouseFk,util.VN_NOW(),FALSE); - + END ;; DELIMITER ; @@ -75856,8 +75857,8 @@ BEGIN * */ - - + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -75906,13 +75907,13 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControlSOWP`(IN vUserFk INT, IN vDated DATE) BEGIN SET @order := 0; - - UPDATE workerTimeControl - SET `order` = @order := @order + 1 - WHERE vUserFk =userFk + + UPDATE workerTimeControl + SET `order` = @order := @order + 1 + WHERE vUserFk =userFk AND vDated = DATE(timed) ORDER BY timed; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -75931,8 +75932,8 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControl_add`(IN vUserFk INT, IN vWarehouseFk INT, IN vTimed DATETIME, IN vIsManual BOOL) BEGIN - - + + SELECT workerTimeControl_add(vUserFk,vWarehouseFk,vTimed,vIsManual); END ;; DELIMITER ; @@ -76020,73 +76021,73 @@ proc: BEGIN DECLARE vTo VARCHAR(50) DEFAULT NULL; DECLARE vUserName VARCHAR(50) DEFAULT NULL; DECLARE vBody VARCHAR(255) DEFAULT NULL; - - SELECT dayBreak, weekBreak, weekScope, dayWorkMax, dayStayMax + + SELECT dayBreak, weekBreak, weekScope, dayWorkMax, dayStayMax INTO vDayBreak, vWeekBreak, vWeekScope, vDayWorkMax, vDayStayMax FROM workerTimeControlParams; SELECT MAX(timed) INTO vLastIn - FROM workerTimeControl - WHERE userFk = vUserFk + FROM workerTimeControl + WHERE userFk = vUserFk AND direction = 'in'; - + SELECT MAX(timed) INTO vLastOut - FROM workerTimeControl - WHERE userFk = vUserFk - AND direction = 'out'; + FROM workerTimeControl + WHERE userFk = vUserFk + AND direction = 'out'; SELECT CONCAT(u.name,'@verdnatura.es') INTO vTo FROM account.user u - WHERE u.id = (SELECT bossFk FROM worker WHERE id = vUserFk); - + WHERE u.id = (SELECT bossFk FROM worker WHERE id = vUserFk); + SELECT CONCAT(firstName,' ',lastName) INTO vUserName FROM worker w WHERE w.id = vUserFk; IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastIn) > vDayStayMax THEN -- NUEVA JORNADA - - -- VERIFICAR DESCANSO DIARIO - IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastOut) < vDayBreak THEN + + -- VERIFICAR DESCANSO DIARIO + IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastOut) < vDayBreak THEN SELECT "Descansos 12 h" AS problem; -- ENVIAMOS CORREO AL BOSSFK SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Descansos 12 h") INTO vBody; CALL mail_insert(vTo,vTo,'error al fichar',vBody); LEAVE proc; - END IF; - + END IF; + -- VERIFICAR FICHADAS IMPARES DEL ÚLTIMO DÍA QUE SE FICHÓ - IF (SELECT MOD(COUNT(*),2) -- <>0 - FROM workerTimeControl + IF (SELECT MOD(COUNT(*),2) -- <>0 + FROM workerTimeControl WHERE userFk = vUserFk AND timed >= vLastIn - ) THEN + ) THEN SELECT "Dias con fichadas impares" AS problem; -- ENVIAMOS CORREO AL BOSSFK SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Dias con fichadas impares") INTO vBody; CALL mail_insert(vTo,vTo,'error al fichar',vBody); - LEAVE proc; + LEAVE proc; END IF; - + -- VERIFICAR VACACIONES SELECT at2.name INTO vCalendarStateType - FROM calendar c + FROM calendar c JOIN business b ON b.id = c.businessFk JOIN absenceType at2 ON at2.id = c.dayOffTypeFk WHERE c.dated = util.VN_CURDATE() AND at2.isAllowedToWork = FALSE AND b.workerFk = vUserFk LIMIT 1; - + IF(LENGTH(vCalendarStateType)) THEN SELECT vCalendarStateType AS problem; -- ENVIAMOS CORREO AL BOSSFK SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Vacaciones") INTO vBody; CALL mail_insert(vTo,vTo,'error al fichar',vBody); - LEAVE proc; - + LEAVE proc; + END IF; - + -- VERIFICAR CONTRATO EN VIGOR IF (SELECT COUNT(*) FROM business b @@ -76098,44 +76099,44 @@ proc: BEGIN -- ENVIAMOS CORREO AL BOSSFK SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"No hay un contrato en vigor") INTO vBody; CALL mail_insert(vTo,vTo,'error al fichar',vBody); - LEAVE proc; - + LEAVE proc; + END IF; -- VERIFICAR DESCANSO SEMANAL SET @vHasBreakWeek:= FALSE; - SET @vLastTimed:= UNIX_TIMESTAMP((util.VN_NOW() - INTERVAL vWeekScope SECOND)); - + SET @vLastTimed:= UNIX_TIMESTAMP((util.VN_NOW() - INTERVAL vWeekScope SECOND)); + DROP TEMPORARY TABLE IF EXISTS tmp.trash; CREATE TEMPORARY TABLE tmp.trash SELECT IF(vWeekBreak-(UNIX_TIMESTAMP(timed)-@vLastTimed) <= 0, @vHasBreakWeek:=TRUE, TRUE) alias, @vLastTimed:= UNIX_TIMESTAMP(timed) - FROM workerTimeControl + FROM workerTimeControl WHERE timed>= (util.VN_NOW() - INTERVAL vWeekScope SECOND) AND userFk= vUserFk AND direction IN ('in','out') - ORDER BY timed ASC; - - IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastOut) < vWeekBreak AND @vHasBreakWeek = FALSE THEN -- REVISA SI EL DESCANSO SE HA REALIZADO DESPUÉS DE LA ÚLTIMA FICHADA + ORDER BY timed ASC; + + IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastOut) < vWeekBreak AND @vHasBreakWeek = FALSE THEN -- REVISA SI EL DESCANSO SE HA REALIZADO DESPUÉS DE LA ÚLTIMA FICHADA SELECT "Descansos 36 h" AS problem; -- ENVIAMOS CORREO AL BOSSFK SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Descansos 36 h") INTO vBody; CALL mail_insert(vTo,vTo,'error al fichar',vBody); LEAVE proc; END IF; - - DROP TEMPORARY TABLE tmp.trash; - ELSE -- DIA ACTUAL - + DROP TEMPORARY TABLE tmp.trash; + + ELSE -- DIA ACTUAL + -- VERIFICA QUE EL TIEMPO EFECTIVO NO SUPERE EL MÁXIMO - SELECT IFNULL(SUM(if( mod(wtc.order,2)=1, -UNIX_TIMESTAMP(timed), UNIX_TIMESTAMP(timed))),0) - IF( MOD(COUNT(*),2), UNIX_TIMESTAMP(util.VN_NOW()), 0) INTO vTimedWorked + SELECT IFNULL(SUM(if( mod(wtc.order,2)=1, -UNIX_TIMESTAMP(timed), UNIX_TIMESTAMP(timed))),0) - IF( MOD(COUNT(*),2), UNIX_TIMESTAMP(util.VN_NOW()), 0) INTO vTimedWorked FROM workerTimeControl wtc - WHERE userFk = vUserFk + WHERE userFk = vUserFk AND timed >= vLastIn ORDER BY timed; - IF vTimedWorked > vDayWorkMax THEN + IF vTimedWorked > vDayWorkMax THEN SELECT "Jornadas" AS problem; -- ENVIAMOS CORREO AL BOSSFK SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Jornadas") INTO vBody; @@ -76158,10 +76159,10 @@ proc: BEGIN -- ENVIAMOS CORREO AL BOSSFK SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"No perteneces a este departamento.") INTO vBody; CALL mail_insert(vTo,vTo,'error al fichar',vBody); - LEAVE proc; + LEAVE proc; END IF; END IF;*/ - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -76181,7 +76182,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControl_checkBreak`(vStarted DATE) BEGIN /** - * Retorna los trabajadores que no han respetado el descanso semanal de 36/72 horas + * Retorna los trabajadores que no han respetado el descanso semanal de 36/72 horas * El sistema verificará el descanso corto en la siguiente semana * o el largo en las 2 siguientes semanas a partir de la fecha dada * @param vStarted día inicio de la semana en el que se quiere verificar @@ -76192,27 +76193,27 @@ BEGIN DECLARE vShortWeekBreak INT; DECLARE vLongWeekBreak INT; - SELECT util.dayEnd(DATE_ADD(vStarted, INTERVAL shortWeekDays DAY)), + SELECT util.dayEnd(DATE_ADD(vStarted, INTERVAL shortWeekDays DAY)), util.dayEnd(DATE_ADD(vStarted, INTERVAL longWeekDays DAY)), - shortWeekBreak, + shortWeekBreak, longWeekBreak INTO vShortEnded, vLongEnded, vShortWeekBreak, vLongWeekBreak FROM workerTimeControlConfig; - + SET @previousTimed:= UNIX_TIMESTAMP(vStarted); SET @lastUserFk := NULL; - + -- Descanso corto en la semana - + DROP TEMPORARY TABLE IF EXISTS tmp.worker; CREATE TEMPORARY TABLE tmp.worker (PRIMARY KEY(workerFk)) ENGINE = MEMORY SELECT DISTINCT userFk workerFk - FROM workerTimeControl + FROM workerTimeControl WHERE timed BETWEEN vStarted AND vShortEnded AND direction IN ('in', 'out'); - + DROP TEMPORARY TABLE IF EXISTS tmp.worker2; CREATE TEMPORARY TABLE tmp.worker2 (PRIMARY KEY(workerFk)) @@ -76225,28 +76226,28 @@ BEGIN SELECT sub2.userFk workerFk FROM(SELECT sub.userFk, IF(sub.userFk <> @lastUserFk, - @previousTimed:= sub.timed, + @previousTimed:= sub.timed, FALSE), - IF(sub.timed - @previousTimed >= vShortWeekBreak, - TRUE, + IF(sub.timed - @previousTimed >= vShortWeekBreak, + TRUE, FALSE) hasShortWeekBreak, @previousTimed:= sub.timed, @lastUserFk:= sub.userFk FROM ( SELECT userFk, UNIX_TIMESTAMP(timed) timed - FROM workerTimeControl + FROM workerTimeControl WHERE timed BETWEEN vStarted AND vShortEnded AND direction IN ('in', 'out') - UNION + UNION SELECT w.workerFk, UNIX_TIMESTAMP(IFNULL( - MIN(wtc.timed), + MIN(wtc.timed), DATE_ADD(vShortEnded, INTERVAL vShortWeekBreak SECOND))) FROM tmp.worker w - LEFT JOIN workerTimeControl wtc - ON wtc.userFk = w.workerFk - AND wtc.timed BETWEEN vShortEnded - AND DATE_ADD(vShortEnded, INTERVAL vShortWeekBreak SECOND) + LEFT JOIN workerTimeControl wtc + ON wtc.userFk = w.workerFk + AND wtc.timed BETWEEN vShortEnded + AND DATE_ADD(vShortEnded, INTERVAL vShortWeekBreak SECOND) GROUP BY w.workerFk UNION SELECT w.workerFk, @@ -76254,10 +76255,10 @@ BEGIN MAX(wtc.timed), DATE_SUB(vStarted, INTERVAL vShortWeekBreak SECOND))) FROM tmp.worker2 w - LEFT JOIN workerTimeControl wtc - ON wtc.userFk = w.workerFk - AND wtc.timed BETWEEN - DATE_SUB(vStarted, INTERVAL vShortWeekBreak SECOND) + LEFT JOIN workerTimeControl wtc + ON wtc.userFk = w.workerFk + AND wtc.timed BETWEEN + DATE_SUB(vStarted, INTERVAL vShortWeekBreak SECOND) AND vStarted GROUP BY w.workerFk ORDER BY userFk, timed @@ -76267,7 +76268,7 @@ BEGIN GROUP BY sub2.userFk HAVING NOT SUM(hasShortWeekBreak); - -- Descanso largo en las 2 siguientes semanas + -- Descanso largo en las 2 siguientes semanas DROP TEMPORARY TABLE tmp.worker; CREATE TEMPORARY TABLE tmp.worker (PRIMARY KEY(workerFk)) @@ -76287,12 +76288,12 @@ BEGIN (PRIMARY KEY(workerFk)) ENGINE = MEMORY SELECT sub2.userFk workerFk - FROM(SELECT userFk, + FROM(SELECT userFk, IF(userFk <> @lastUserFk, - @previousTimed:= timed, + @previousTimed:= timed, TRUE), - IF(timed - @previousTimed >= vLongWeekBreak, - TRUE, + IF(timed - @previousTimed >= vLongWeekBreak, + TRUE, FALSE) hasLongWeekBreak, @previousTimed:= timed, @lastUserFk:= userFk @@ -76301,24 +76302,24 @@ BEGIN JOIN tmp.workerWithoutShortWeekBreak wws ON wws.workerFk = wtc.userFk WHERE timed BETWEEN vStarted AND vLongEnded AND direction IN ('in', 'out') - UNION + UNION SELECT w.workerFk, - UNIX_TIMESTAMP(IFNULL(MIN(wtc.timed), + UNIX_TIMESTAMP(IFNULL(MIN(wtc.timed), DATE_ADD(vLongEnded, INTERVAL vLongWeekBreak SECOND))) FROM tmp.worker w - LEFT JOIN workerTimeControl wtc - ON wtc.userFk = w.workerFk - AND timed BETWEEN vLongEnded - AND DATE_ADD(vLongEnded, INTERVAL vLongWeekBreak SECOND) + LEFT JOIN workerTimeControl wtc + ON wtc.userFk = w.workerFk + AND timed BETWEEN vLongEnded + AND DATE_ADD(vLongEnded, INTERVAL vLongWeekBreak SECOND) GROUP BY w.workerFk UNION - SELECT w.workerFk, - UNIX_TIMESTAMP(IFNULL(MAX(wtc.timed), + SELECT w.workerFk, + UNIX_TIMESTAMP(IFNULL(MAX(wtc.timed), DATE_SUB(vStarted, INTERVAL vLongWeekBreak SECOND))) FROM tmp.worker2 w - LEFT JOIN workerTimeControl wtc - ON wtc.userFk = w.workerFk - AND timed BETWEEN DATE_SUB(vStarted, INTERVAL vLongWeekBreak SECOND) + LEFT JOIN workerTimeControl wtc + ON wtc.userFk = w.workerFk + AND timed BETWEEN DATE_SUB(vStarted, INTERVAL vLongWeekBreak SECOND) AND vStarted GROUP BY w.workerFk ORDER BY userFk, timed @@ -76695,27 +76696,27 @@ BEGIN * Devuelve que direcciones de fichadas son lógicas a partir de la anterior fichada * @param vWorkerFk Identificador del trabajador * @return (option1, option2) - * Los valores posibles de retorno son ('in', 'inMiddle', 'outMiddle', 'out') + * Los valores posibles de retorno son ('in', 'inMiddle', 'outMiddle', 'out') */ DECLARE vLastIn DATETIME ; DECLARE vIsMiddleOdd BOOLEAN ; - IF (vTimed IS NULL) THEN + IF (vTimed IS NULL) THEN SET vTimed = util.VN_NOW(); END IF; - + SELECT timed INTO vLastIn - FROM workerTimeControl + FROM workerTimeControl WHERE userFk = vWorkerFk - AND direction = 'in' + AND direction = 'in' AND timed < vTimed ORDER BY timed DESC LIMIT 1; - + SELECT (COUNT(*)mod 2 = 1) INTO vIsMiddleOdd - FROM workerTimeControl + FROM workerTimeControl WHERE userFk = vWorkerFk - AND direction = 'middle' + AND direction = 'middle' AND timed BETWEEN vLastIn AND util.VN_NOW(); DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControlDirection; @@ -76764,7 +76765,7 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControl_getClockIn`( - vUserFk INT, + vUserFk INT, vDated DATE) BEGIN /** @@ -76774,9 +76775,9 @@ BEGIN * @param vDated Fecha proporcionada */ CALL timeControl_calculateByWorker( - vUserFk, + vUserFk, DATE_SUB(vDated, INTERVAL 6 DAY), util.dayEnd(vDated)); - + SET @position := 0; SET @lastDated := NULL; @@ -76793,7 +76794,7 @@ BEGIN MAX(2daysAgoDirection) 2daysAgoDirection, MAX(1daysAgo) 1daysAgo, MAX(1daysAgoDirection) 1daysAgoDirection, - MAX(0daysAgo) 0daysAgo, + MAX(0daysAgo) 0daysAgo, MAX(0daysAgoDirection) 0daysAgoDirection FROM(SELECT IF(daysAgo = 6, timed, '') 6daysAgo, IF(daysAgo = 5, timed, '') 5daysAgo, @@ -76813,7 +76814,7 @@ BEGIN direction, position FROM(SELECT DATEDIFF(vDated, timed) daysAgo, - TIME_FORMAT(timed,'%H:%i') timed, + TIME_FORMAT(timed,'%H:%i') timed, IF(DATE(timed) <> @lastDated, @position := 0, NULL), @position := @position+1 position, @lastDated := DATE(timed), @@ -76825,18 +76826,18 @@ BEGIN LIMIT 10000000000000000000 )sub )sub2 - GROUP BY position) sub3 + GROUP BY position) sub3 JOIN (SELECT MAX(IF(daysAgo = 6, timeWorkSeconds, 0)) 6daysAgoTotal, MAX(IF(daysAgo = 5, timeWorkSeconds, 0)) 5daysAgoTotal, MAX(IF(daysAgo = 4, timeWorkSeconds, 0)) 4daysAgoTotal, MAX(IF(daysAgo = 3, timeWorkSeconds, 0)) 3daysAgoTotal, MAX(IF(daysAgo = 2, timeWorkSeconds, 0)) 2daysAgoTotal, MAX(IF(daysAgo = 1, timeWorkSeconds, 0)) 1daysAgoTotal, - MAX(IF(daysAgo = 0, timeWorkSeconds, 0)) 0daysAgoTotal + MAX(IF(daysAgo = 0, timeWorkSeconds, 0)) 0daysAgoTotal FROM (SELECT DATEDIFF(vDated, dated) daysAgo, timeWorkSeconds FROM tmp.timeControlCalculate) sub4)sub5 ON TRUE; - + DROP TEMPORARY TABLE tmp.timeControlCalculate; END ;; DELIMITER ; @@ -76900,45 +76901,45 @@ BEGIN DECLARE vDirectionPrevious VARCHAR(6); DECLARE vTimedPrevious DATETIME; - SELECT direction INTO vDirectionRemove - FROM vn.workerTimeControl - WHERE userFk = vUserFk + SELECT direction INTO vDirectionRemove + FROM vn.workerTimeControl + WHERE userFk = vUserFk AND timed = vTimed ; IF vDirectionRemove = 'out' THEN - + SELECT timed, direction INTO vTimedPrevious, vDirectionPrevious - FROM vn.workerTimeControl - WHERE userFk = vUserFk + FROM vn.workerTimeControl + WHERE userFk = vUserFk AND timed < vTimed ORDER BY timed DESC - LIMIT 1; - + LIMIT 1; + IF vDirectionPrevious = "middle" THEN - UPDATE vn.workerTimeControl + UPDATE vn.workerTimeControl SET direction = "out" WHERE userFk = vUserFk AND timed = vTimedPrevious; END IF; - + ELSE IF vDirectionRemove = 'in' THEN - UPDATE vn.workerTimeControl + UPDATE vn.workerTimeControl SET direction = "in" WHERE userFk = vUserFk AND timed > vTimed ORDER BY timed ASC - LIMIT 1; + LIMIT 1; END IF; - + END IF; - + DELETE FROM vn.workerTimeControl - WHERE userFk = vUserFk + WHERE userFk = vUserFk AND timed = vTimed; - + CALL vn.workerTimeControlSOWP(vUserFk, vTimed); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -76966,31 +76967,31 @@ proc: BEGIN UPDATE vn.workerTimeControl SET direction = 'middle'; /*2- poner los out*/ -UPDATE vn.workerTimeControl wtc - JOIN +UPDATE vn.workerTimeControl wtc + JOIN (SELECT userFk,MAX(timed) maxTimed FROM (SELECT id, userFk, timed, date(timed) dated - FROM vn.workerTimeControl - ) sub + FROM vn.workerTimeControl + ) sub GROUP BY userFk,dated )sub SET direction = "out" - WHERE wtc.userFk = sub.userFk + WHERE wtc.userFk = sub.userFk AND wtc.timed = sub.maxTimed; - - /*3- poner los in*/ -UPDATE vn.workerTimeControl wtc - JOIN + + /*3- poner los in*/ +UPDATE vn.workerTimeControl wtc + JOIN (SELECT userFk,MIN(timed) maxTimed FROM (SELECT id, userFk, timed, date(timed) dated - FROM vn.workerTimeControl - ) sub + FROM vn.workerTimeControl + ) sub GROUP BY userFk,dated )sub SET direction = "in" - WHERE wtc.userFk = sub.userFk - AND wtc.timed = sub.maxTimed ; - + WHERE wtc.userFk = sub.userFk + AND wtc.timed = sub.maxTimed ; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -77063,7 +77064,7 @@ BEGIN AND w.businessFk GROUP BY tm.userFk,t.dated ORDER BY tm.userFk,t.dated; - + INSERT INTO vn.mail (receiver, replyTo, subject, body) SELECT eu.email, 'laboral@verdnatura.es', CONCAT('Registro de horas semana ', WEEK(vDatedFrom), ' año ', YEAR(vDatedFrom)) , CONCAT(' @@ -77155,7 +77156,7 @@ BEGIN IF (DAYNAME(util.VN_CURDATE()) = 'miércoles') THEN SELECT DATE_SUB(util.VN_CURDATE(), INTERVAL 9 DAY), CONCAT(DATE_SUB(util.VN_CURDATE(), INTERVAL 3 DAY), ' 23:59:59') INTO vDatedFrom, vDatedTo; - + CALL vn.workerTimeControl_sendMailByDepartment(vDatedFrom, vDatedTo, NULL); END IF; END ;; @@ -77205,9 +77206,9 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControl_weekCheckBreak`(vStarted DATE, vEnded DATE) BEGIN /** - * Retorna los trabajadores que no han respetado el descanso semanal de 36/72 horas - * El sistema verificará el descanso corto en la siguiente semana - * o el largo en las 2 siguientes semanas a partir de las fechas dadas + * Retorna los trabajadores que no han respetado el descanso semanal de 36/72 horas + * El sistema verificará el descanso corto en la siguiente semana + * o el largo en las 2 siguientes semanas a partir de las fechas dadas * @param vStarted día inicio para verificar * @param vEnded día final para verificar * @return tmp.workerWithoutWeekBreak (workerFk) @@ -77229,10 +77230,10 @@ BEGIN CALL workerTimeControl_checkBreak(vStarted); INSERT IGNORE INTO tmp.workerWithoutWeekBreakInWeek - SELECT workerFk + SELECT workerFk FROM tmp.workerWithoutWeekBreak; DROP TEMPORARY TABLE IF EXISTS tmp.workerWithoutWeekBreak; - SET vStarted = DATE_ADD(vStarted, INTERVAL 1 DAY); + SET vStarted = DATE_ADD(vStarted, INTERVAL 1 DAY); END WHILE; END ;; @@ -77270,7 +77271,7 @@ BEGIN DECLARE vDepartmentFk INT; DECLARE isEnabled BOOLEAN DEFAULT TRUE; - SELECT COUNT(*) INTO vHasSignedToday + SELECT COUNT(*) INTO vHasSignedToday FROM workerTimeControl WHERE timed >= vDated AND userFk = vUserFk; SET @day := 0; @@ -77283,16 +77284,16 @@ BEGIN SELECT fichada_anterior, fichada_actual, interval_in_minutes, jornadas FROM ( - SELECT @lastTimed fichada_anterior, + SELECT @lastTimed fichada_anterior, timed, CAST(time_to_sec(timediff(timed,@lastTimed )) / 60 AS UNSIGNED) as interval_in_minutes, IF(day(timed) != @day, 1, 0) as jornadas, @day := day(timed) dia_del_mes, - @lastTimed := timed fichada_actual + @lastTimed := timed fichada_actual FROM ( SELECT day(timed) as dayNumber, dayname(timed) as dayName, timed - FROM + FROM (SELECT TIMESTAMPADD(DAY, -11, util.VN_NOW()) as timed, vUserFk as userFk -- Fichada virtual para los en los que no se ha trabajado la semana anterior UNION ALL SELECT timed, userFk @@ -77300,18 +77301,18 @@ BEGIN WHERE userFk = vUserFk AND timed >= TIMESTAMPADD(DAY, -10,vDated) UNION ALL - SELECT IF(vHasSignedToday, '2000-01-01 00:00', util.VN_NOW()) as timed, vUserFk + SELECT IF(vHasSignedToday, '2000-01-01 00:00', util.VN_NOW()) as timed, vUserFk ) sub4 ORDER BY timed ) sub - + ) sub2 WHERE fichada_actual >= TIMESTAMPADD(WEEK, -1, vDated) ) sub3 ; SELECT IFNULL(SUM(impar),0) into vImpares FROM ( - SELECT day(timed) as dayNumber, + SELECT day(timed) as dayNumber, count(*) mod 2 as impar FROM vn.workerTimeControl wtc WHERE userFk = vUserFk @@ -77328,29 +77329,29 @@ BEGIN AND at2.isAllowedToWork = FALSE AND b.workerFk = vUserFk LIMIT 1; - + -- Contrato en vigor SELECT IF(COUNT(*),vCantWork,'Sin contrato') INTO vCantWork FROM business b WHERE b.workerFk = vUserFk AND b.started <= vDated AND IFNULL(b.ended, vDated) >= vDated; - + -- Departamento si vTabletFk es 0 no hacemos comprobacion (Madrid y Vilassar) IF vTabletFk <> '0' THEN -- 1 Obtener el departamento del usuario SELECT wtcu.departmentFk INTO vDepartmentFk FROM workerTimeControlUserInfo wtcu WHERE wtcu.userFk = vUserFk; - -- 2 Comprobar si la tablet pertenece al departamento + -- 2 Comprobar si la tablet pertenece al departamento SELECT COUNT(td.tabletFk) INTO isEnabled FROM tabletDepartment td WHERE td.tabletFk = vTabletFk AND td.departmentFk = vDepartmentFk; - + END IF; - + IF vJornadas IS NOT NULL THEN - + SELECT 'Jornadas' as Item, vJornadas as Cantidad, 'Correcto' AS Análisis UNION ALL SELECT 'Descansos 12 h' as Item, vDescansos12h as Cantidad, IF(vDescansos12h >= vJornadas, 'Correcto','Error: 1 por jornada') as Análisis @@ -77359,9 +77360,9 @@ BEGIN UNION ALL SELECT 'Dias con fichadas impares' as Item, vImpares as Cantidad, IF(vImpares = 0, 'Correcto','Error') as Análisis UNION ALL - SELECT IF (LENGTH(vCantWork),CONCAT('Dia no laborable: ', vCantWork),'Dia laborable') as Item, - '' as Cantidad, - IF(LENGTH(vCantWork),'Error', 'Correcto') as Análisis + SELECT IF (LENGTH(vCantWork),CONCAT('Dia no laborable: ', vCantWork),'Dia laborable') as Item, + '' as Cantidad, + IF(LENGTH(vCantWork),'Error', 'Correcto') as Análisis UNION ALL SELECT 'El fichador no pertenece a tu departamento.' as Item, '' as Cantidad, IF(isEnabled, 'Correcto','Error') as Análisis; @@ -77375,7 +77376,7 @@ BEGIN UNION ALL SELECT 'Dias con fichadas impares' as Item, vImpares as Cantidad, 'Correcto' as Análisis UNION ALL - SELECT IF (LENGTH(vCantWork),CONCAT('Dia no laborable: ', vCantWork),'Dia laborable') as Item, + SELECT IF (LENGTH(vCantWork),CONCAT('Dia no laborable: ', vCantWork),'Dia laborable') as Item, '' as Cantidad, IF(LENGTH(vCantWork),'Error', 'Correcto') as Análisis UNION ALL SELECT 'El fichador no pertenece a tu departamento.' as Item, '' as Cantidad, IF(isEnabled, 'Correcto','Error') as Análisis; @@ -77405,11 +77406,11 @@ BEGIN * @param vDepartmentFk id del departamento * */ - - SELECT w.id,w.firstName, w.lastName,d.name - FROM worker w - JOIN workerDepartment wd ON wd.workerFk = w.id - JOIN department d ON d.id = wd.departmentFk + + SELECT w.id,w.firstName, w.lastName,d.name + FROM worker w + JOIN workerDepartment wd ON wd.workerFk = w.id + JOIN department d ON d.id = wd.departmentFk WHERE d.id = vDepartmentFk ORDER BY firstName; @@ -77440,7 +77441,7 @@ BEGIN (PRIMARY KEY (workerFk)) ENGINE = MEMORY SELECT vBoss AS workerFk; - + DROP TEMPORARY TABLE IF EXISTS tmp.workerHierarchyList; CREATE TEMPORARY TABLE tmp.workerHierarchyList (PRIMARY KEY (workerFk)) @@ -77451,7 +77452,7 @@ BEGIN WHILE (SELECT COUNT(*) FROM tmp.workerHierarchyList WHERE NOT isChecked) > 0 DO INSERT INTO tmp.workerHierarchyList - SELECT w.id, 0 + SELECT w.id, 0 FROM worker w JOIN workerHierarchy wh ON wh.workerFk = w.bossFk; @@ -77462,12 +77463,12 @@ BEGIN TRUNCATE workerHierarchy; INSERT INTO workerHierarchy - SELECT workerFk + SELECT workerFk FROM tmp.workerHierarchyList WHERE NOT isChecked; END WHILE; - + DROP TEMPORARY TABLE IF EXISTS workerHierarchy; END ;; DELIMITER ; @@ -77494,7 +77495,7 @@ BEGIN SELECT s.id,s.description,s.warehouseFk FROM sector s - JOIN operator o ON o.sectorFk = s.id + JOIN operator o ON o.sectorFk = s.id WHERE o.workerFk = account.myUser_getId(); END ;; @@ -77579,8 +77580,8 @@ BEGIN DECLARE vDone BOOL; DECLARE vCursor CURSOR FOR - SELECT DISTINCT b.workerFk - FROM business b + SELECT DISTINCT b.workerFk + FROM business b WHERE b.started > vBusinessUpdated AND b.started <= vCurdate OR b.ended >= vBusinessUpdated AND b.ended < vCurdate; @@ -77623,10 +77624,10 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workingHours`(username varchar(255), logon boolean) BEGIN DECLARE userid int(11); - + SELECT vn.getUserId(username) INTO userid; SELECT username, userid; - IF userid IS NOT NULL THEN + IF userid IS NOT NULL THEN IF (logon) THEN CALL vn.workingHoursTimeIn(userid); ELSE @@ -77695,17 +77696,17 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `wrongEqualizatedClient`() BEGIN SELECT clientFk, c.name, c.isActive, c.isTaxDataChecked, count(ie) as num FROM vn.client c - JOIN + JOIN ( - SELECT DISTINCT + SELECT DISTINCT `a`.`clientFk` , a.isEqualizated = 0 as ie - + FROM `vn`.`address` `a` ) sub ON sub.clientFk = c.id WHERE c.hasToInvoiceByAddress = FALSE - + GROUP BY clientFk HAVING num > 1 UNION ALL @@ -77789,27 +77790,27 @@ proc: BEGIN SELECT scope INTO vScope FROM zoneConfig; - + DROP TEMPORARY TABLE IF EXISTS tmp.zone; CREATE TEMPORARY TABLE tmp.zone (INDEX (id)) ENGINE = MEMORY SELECT id FROM zone; - + TRUNCATE TABLE zoneClosure; - + WHILE vCounter <= vScope DO - + CALL zone_getOptionsForShipment(vShipped, TRUE); - + REPLACE zoneClosure(zoneFk, dated, `hour`) - SELECT zoneFk, vShipped, `hour` + SELECT zoneFk, vShipped, `hour` FROM tmp.zoneOption; - + SET vCounter = vCounter + 1; SET vShipped = TIMESTAMPADD(DAY, 1, vShipped); END WHILE; - + -- DROP TEMPORARY TABLE tmp.zone; DO RELEASE_LOCK('vn.zoneClosure_recalc'); END ;; @@ -77903,7 +77904,7 @@ BEGIN OR (vSelf IS NOT NULL AND parentFk = vSelf); DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + SET vSons = 0; OPEN vChildren; @@ -77914,11 +77915,11 @@ BEGIN IF vDone THEN LEAVE myLoop; END IF; - + SET vIndex = vIndex + 1; SET vLft = vIndex; SET vSons = vSons + 1; - + CALL zoneGeo_calcTreeRec( vChildFk, CONCAT(vPath, vChildFk, '/'), @@ -78021,7 +78022,7 @@ proc: BEGIN SELECT isChanged INTO vIsChanged FROM zoneGeoRecalc; - + IF vIsChanged THEN UPDATE zoneGeoRecalc SET isChanged = FALSE; CALL vn.zoneGeo_calcTree; @@ -78209,7 +78210,7 @@ proc:BEGIN * @table tmp.closedZones(zoneFk, warehouseFk); */ DROP TEMPORARY TABLE IF EXISTS tmp.closedZones; - + CREATE TEMPORARY TABLE tmp.closedZones ( `zoneFk` int(11) NOT NULL, `warehouseFk` smallint(6) unsigned NOT NULL, @@ -78251,7 +78252,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getCollisions`() BEGIN /** - * Calcula si para un mismo codigo postal y dia + * Calcula si para un mismo codigo postal y dia * hay mas de una zona configurada y manda correo * */ @@ -78260,16 +78261,16 @@ BEGIN DECLARE vIsDone INT DEFAULT FALSE; DECLARE vTableCollisions TEXT; DECLARE cur1 CURSOR FOR SELECT zoneFk from tmp.zoneOption; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vIsDone = TRUE; DROP TEMPORARY TABLE IF EXISTS tmp.zone; CREATE TEMPORARY TABLE tmp.zone - SELECT z.id + SELECT z.id FROM zone z JOIN agencyMode am ON am.id = z.agencyModeFk JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk - WHERE dm.code IN ('AGENCY','DELIVERY'); + WHERE dm.code IN ('AGENCY','DELIVERY'); CALL zone_getOptionsForShipment(util.VN_CURDATE(),FALSE); @@ -78284,7 +78285,7 @@ BEGIN PRIMARY KEY zoneFkk (zoneFk, geoFk), INDEX(geoFk)) ENGINE = MyISAM; - + OPEN cur1; cur1Loop: LOOP SET vIsDone = FALSE; @@ -78292,40 +78293,40 @@ BEGIN IF vIsDone THEN LEAVE cur1Loop; END IF; - + CALL zone_getLeaves(vZoneFk, NULL, NULL, TRUE); - myLoop: LOOP + myLoop: LOOP SET vGeoFk = NULL; - SELECT geoFk INTO vGeoFk + SELECT geoFk INTO vGeoFk FROM tmp.zoneNodes zn WHERE NOT isChecked LIMIT 1; - + IF vGeoFk IS NULL THEN LEAVE myLoop; END IF; - + CALL zone_getLeaves(vZoneFk, vGeoFk, NULL, TRUE); UPDATE tmp.zoneNodes - SET isChecked = TRUE + SET isChecked = TRUE WHERE geoFk = vGeoFk; END LOOP; END LOOP; CLOSE cur1; - DELETE FROM tmp.zoneNodes + DELETE FROM tmp.zoneNodes WHERE sons > 0; - + DROP TEMPORARY TABLE IF EXISTS geoCollision; CREATE TEMPORARY TABLE geoCollision SELECT z.agencyModeFk, zn.geoFk, zw.warehouseFk FROM tmp.zoneNodes zn JOIN zone z ON z.id = zn.zoneFk - JOIN zoneWarehouse zw ON z.id = zw.zoneFk + JOIN zoneWarehouse zw ON z.id = zw.zoneFk GROUP BY z.agencyModeFk, zn.geoFk, zw.warehouseFk HAVING count(*) > 1; - + SELECT ' @@ -78335,39 +78336,39 @@ BEGIN ' INTO vTableCollisions; - - INSERT INTO mail (receiver,replyTo,subject,body) + + INSERT INTO mail (receiver,replyTo,subject,body) SELECT 'pepe@verdnatura.es' receiver, 'noreply@verdnatura.es' replyTo, CONCAT('Colisiones en zonas ', util.VN_CURDATE()) subject, CONCAT(vTableCollisions, GROUP_CONCAT(sub.td SEPARATOR ''), '
C.PostalAlmacén Salix
') body - FROM(SELECT + FROM(SELECT CONCAT(' ', zn.name, ' ', zoneFk,' ', z.price,' ', z.name,' ', w.name, ' - ', CONCAT('' - 'https://salix.verdnatura.es/#!/zone/', + 'https://salix.verdnatura.es/#!/zone/', zoneFk, '/location?q=%7B%22search%22:%22', - zn.name, + zn.name, '%22%7D'),' ') td FROM tmp.zoneNodes zn JOIN zone z ON z.id = zn.zoneFk JOIN geoCollision gc ON gc.agencyModeFk = z.agencyModeFk AND zn.geoFk = gc.geoFk JOIN warehouse w ON w.id = gc.warehouseFk) sub; - - DROP TEMPORARY TABLE - geoCollision, + + DROP TEMPORARY TABLE + geoCollision, tmp.zone, tmp.zoneNodes; END ;; @@ -78474,18 +78475,18 @@ BEGIN DECLARE vChildFk INT DEFAULT vGeoFk; DECLARE vParentFk INT; DECLARE vLevel INT DEFAULT 1; - + DROP TEMPORARY TABLE IF EXISTS tNodes; CREATE TEMPORARY TABLE tNodes (PRIMARY KEY (id)) ENGINE = MEMORY SELECT vGeoFk id, vLevel `level`; - + myLoop: LOOP SELECT parentFk INTO vParentFk FROM zoneGeo WHERE id = vChildFk; - + SET vChildFk = vParentFk; SET vLevel = vLevel + 1; @@ -78493,7 +78494,7 @@ BEGIN SELECT vChildFk, vLevel FROM DUAL WHERE vChildFk IS NOT NULL; - + IF ROW_COUNT() = 0 THEN LEAVE myLoop; END IF; @@ -78592,126 +78593,126 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getLeaves`( - vSelf INT, - vParentFk INT, - vSearch VARCHAR(255), - vHasInsert BOOL +CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getLeaves`( + vSelf INT, + vParentFk INT, + vSearch VARCHAR(255), + vHasInsert BOOL ) -BEGIN -/** - * Devuelve las ubicaciones incluidas en la ruta y que sean hijos de parentFk. - * @param vSelf Id de la zona - * @param vParentFk Id del geo a calcular - * @param vSearch Cadena a buscar - * @param vHasInsert Indica si inserta en tmp.zoneNodes - * Optional @table tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) - */ - DECLARE vIsNumber BOOL; - DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch <> ''; - - CREATE OR REPLACE TEMPORARY TABLE tNodes - (UNIQUE (id)) - ENGINE = MEMORY - SELECT id - FROM zoneGeo - LIMIT 0; - - IF vIsSearch THEN - SET vIsNumber = vSearch REGEXP '^[0-9]+$'; - - INSERT INTO tNodes - SELECT id - FROM zoneGeo - WHERE (vIsNumber AND `name` = vSearch) - OR (!vIsNumber AND `name` LIKE CONCAT('%', vSearch, '%')) - LIMIT 1000; - - ELSEIF vParentFk IS NULL THEN - INSERT INTO tNodes - SELECT geoFk - FROM zoneIncluded - WHERE zoneFk = vSelf; - END IF; - - IF vParentFk IS NULL THEN - CREATE OR REPLACE TEMPORARY TABLE tChilds - (INDEX(id)) - ENGINE = MEMORY - SELECT id FROM tNodes; - - CREATE OR REPLACE TEMPORARY TABLE tParents - (INDEX(id)) - ENGINE = MEMORY - SELECT id FROM zoneGeo LIMIT 0; - - myLoop: LOOP - DELETE FROM tParents; - INSERT INTO tParents - SELECT parentFk id - FROM zoneGeo g - JOIN tChilds c ON c.id = g.id - WHERE g.parentFk IS NOT NULL; - - INSERT IGNORE INTO tNodes - SELECT id FROM tParents; - - IF NOT ROW_COUNT() THEN - LEAVE myLoop; - END IF; - - DELETE FROM tChilds; - INSERT INTO tChilds - SELECT id FROM tParents; - END LOOP; - - DROP TEMPORARY TABLE tChilds, tParents; - END IF; - - IF NOT vIsSearch THEN - INSERT IGNORE INTO tNodes - SELECT id - FROM zoneGeo - WHERE parentFk <=> vParentFk; - END IF; - - CREATE OR REPLACE TEMPORARY TABLE tZones - SELECT g.id, - g.name, - g.parentFk, - g.sons, - NOT g.sons OR `type` = 'country' isChecked, - i.isIncluded selected, - g.`depth`, - vSelf - FROM zoneGeo g - JOIN tNodes n ON n.id = g.id - LEFT JOIN zoneIncluded i ON i.geoFk = g.id - AND i.zoneFk = vSelf - ORDER BY g.`depth`, selected DESC, g.name; - - IF vHasInsert THEN - INSERT IGNORE INTO tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) - SELECT id, - name, - parentFk, - sons, - isChecked, - vSelf - FROM tZones - WHERE selected - OR (selected IS NULL AND vParentFk IS NOT NULL); - ELSE - SELECT id, - name, - parentFk, - sons, - selected - FROM tZones - ORDER BY `depth`, selected DESC, name; - END IF; - - DROP TEMPORARY TABLE tNodes, tZones; +BEGIN +/** + * Devuelve las ubicaciones incluidas en la ruta y que sean hijos de parentFk. + * @param vSelf Id de la zona + * @param vParentFk Id del geo a calcular + * @param vSearch Cadena a buscar + * @param vHasInsert Indica si inserta en tmp.zoneNodes + * Optional @table tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) + */ + DECLARE vIsNumber BOOL; + DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch <> ''; + + CREATE OR REPLACE TEMPORARY TABLE tNodes + (UNIQUE (id)) + ENGINE = MEMORY + SELECT id + FROM zoneGeo + LIMIT 0; + + IF vIsSearch THEN + SET vIsNumber = vSearch REGEXP '^[0-9]+$'; + + INSERT INTO tNodes + SELECT id + FROM zoneGeo + WHERE (vIsNumber AND `name` = vSearch) + OR (!vIsNumber AND `name` LIKE CONCAT('%', vSearch, '%')) + LIMIT 1000; + + ELSEIF vParentFk IS NULL THEN + INSERT INTO tNodes + SELECT geoFk + FROM zoneIncluded + WHERE zoneFk = vSelf; + END IF; + + IF vParentFk IS NULL THEN + CREATE OR REPLACE TEMPORARY TABLE tChilds + (INDEX(id)) + ENGINE = MEMORY + SELECT id FROM tNodes; + + CREATE OR REPLACE TEMPORARY TABLE tParents + (INDEX(id)) + ENGINE = MEMORY + SELECT id FROM zoneGeo LIMIT 0; + + myLoop: LOOP + DELETE FROM tParents; + INSERT INTO tParents + SELECT parentFk id + FROM zoneGeo g + JOIN tChilds c ON c.id = g.id + WHERE g.parentFk IS NOT NULL; + + INSERT IGNORE INTO tNodes + SELECT id FROM tParents; + + IF NOT ROW_COUNT() THEN + LEAVE myLoop; + END IF; + + DELETE FROM tChilds; + INSERT INTO tChilds + SELECT id FROM tParents; + END LOOP; + + DROP TEMPORARY TABLE tChilds, tParents; + END IF; + + IF NOT vIsSearch THEN + INSERT IGNORE INTO tNodes + SELECT id + FROM zoneGeo + WHERE parentFk <=> vParentFk; + END IF; + + CREATE OR REPLACE TEMPORARY TABLE tZones + SELECT g.id, + g.name, + g.parentFk, + g.sons, + NOT g.sons OR `type` = 'country' isChecked, + i.isIncluded selected, + g.`depth`, + vSelf + FROM zoneGeo g + JOIN tNodes n ON n.id = g.id + LEFT JOIN zoneIncluded i ON i.geoFk = g.id + AND i.zoneFk = vSelf + ORDER BY g.`depth`, selected DESC, g.name; + + IF vHasInsert THEN + INSERT IGNORE INTO tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) + SELECT id, + name, + parentFk, + sons, + isChecked, + vSelf + FROM tZones + WHERE selected + OR (selected IS NULL AND vParentFk IS NOT NULL); + ELSE + SELECT id, + name, + parentFk, + sons, + selected + FROM tZones + ORDER BY `depth`, selected DESC, name; + END IF; + + DROP TEMPORARY TABLE tNodes, tZones; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -78736,7 +78737,7 @@ BEGIN * @table tmp.zone(id) The zones ids * @param vLanded The delivery date * @return tmp.zoneOption The computed options - */ + */ DROP TEMPORARY TABLE IF EXISTS tmp.zoneOption; CREATE TEMPORARY TABLE tmp.zoneOption ENGINE = MEMORY @@ -78777,13 +78778,13 @@ BEGIN END LIMIT 10000000000000000000 ) t - GROUP BY zoneFk; - + GROUP BY zoneFk; + DELETE t FROM tmp.zoneOption t JOIN zoneExclusion e ON e.zoneFk = t.zoneFk AND e.`dated` = t.landed LEFT JOIN zoneExclusionGeo eg ON eg.zoneExclusionFk = e.id WHERE eg.zoneExclusionFk IS NULL; - + IF NOT vShowExpiredZones THEN DELETE FROM tmp.zoneOption WHERE shipped < util.VN_CURDATE() @@ -78815,7 +78816,7 @@ BEGIN * @return tmp.zoneOption(zoneFk, hour, travelingDays, price, bonus, specificity) The computed options */ DECLARE vHour TIME DEFAULT TIME(util.VN_NOW()); - + DROP TEMPORARY TABLE IF EXISTS tLandings; CREATE TEMPORARY TABLE tLandings (INDEX (eventFk)) @@ -78894,53 +78895,53 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getPostalCode`(vSelf INT) -BEGIN -/** - * Devuelve los códigos postales incluidos en una zona - */ - DECLARE vGeoFk INT DEFAULT NULL; - - DROP TEMPORARY TABLE IF EXISTS tmp.zoneNodes; - CREATE TEMPORARY TABLE tmp.zoneNodes ( - geoFk INT, - name VARCHAR(100), - parentFk INT, - sons INT, - isChecked BOOL DEFAULT 0, - zoneFk INT, - PRIMARY KEY zoneNodesPk (zoneFk, geoFk), - INDEX(geoFk)) - ENGINE = MEMORY; - - CALL zone_getLeaves(vSelf, NULL , NULL, TRUE); - - UPDATE tmp.zoneNodes zn - SET isChecked = 0 - WHERE parentFk IS NULL; - - myLoop: LOOP - SET vGeoFk = NULL; - SELECT geoFk INTO vGeoFk - FROM tmp.zoneNodes zn - WHERE NOT isChecked - LIMIT 1; - - CALL zone_getLeaves(vSelf, vGeoFk, NULL, TRUE); - UPDATE tmp.zoneNodes - SET isChecked = TRUE - WHERE geoFk = vGeoFk; - - IF vGeoFk IS NULL THEN - LEAVE myLoop; - END IF; - END LOOP; - - DELETE FROM tmp.zoneNodes - WHERE sons > 0; - - SELECT zn.geoFk, zn.name - FROM tmp.zoneNodes zn - JOIN zone z ON z.id = zn.zoneFk; +BEGIN +/** + * Devuelve los códigos postales incluidos en una zona + */ + DECLARE vGeoFk INT DEFAULT NULL; + + DROP TEMPORARY TABLE IF EXISTS tmp.zoneNodes; + CREATE TEMPORARY TABLE tmp.zoneNodes ( + geoFk INT, + name VARCHAR(100), + parentFk INT, + sons INT, + isChecked BOOL DEFAULT 0, + zoneFk INT, + PRIMARY KEY zoneNodesPk (zoneFk, geoFk), + INDEX(geoFk)) + ENGINE = MEMORY; + + CALL zone_getLeaves(vSelf, NULL , NULL, TRUE); + + UPDATE tmp.zoneNodes zn + SET isChecked = 0 + WHERE parentFk IS NULL; + + myLoop: LOOP + SET vGeoFk = NULL; + SELECT geoFk INTO vGeoFk + FROM tmp.zoneNodes zn + WHERE NOT isChecked + LIMIT 1; + + CALL zone_getLeaves(vSelf, vGeoFk, NULL, TRUE); + UPDATE tmp.zoneNodes + SET isChecked = TRUE + WHERE geoFk = vGeoFk; + + IF vGeoFk IS NULL THEN + LEAVE myLoop; + END IF; + END LOOP; + + DELETE FROM tmp.zoneNodes + WHERE sons > 0; + + SELECT zn.geoFk, zn.name + FROM tmp.zoneNodes zn + JOIN zone z ON z.id = zn.zoneFk; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -78971,7 +78972,7 @@ BEGIN DECLARE vZoneGeo INT; SELECT address_getGeo(vAddressFk) INTO vZoneGeo; - + CALL vn.zone_getFromGeo(vZoneGeo); CALL vn.zone_getOptionsForLanding(vLanded, vShowExpiredZones); CALL vn.zone_excludeFromGeo(vZoneGeo); @@ -78991,7 +78992,7 @@ BEGIN FROM tmp.zoneOption zo JOIN vn.zoneWarehouse zw ON zw.zoneFk = zo.zoneFk JOIN vn.`zone` z ON z.id = zo.zoneFk - LEFT JOIN tmp.closedZones cz + LEFT JOIN tmp.closedZones cz ON cz.warehouseFk = zw.warehouseFk AND cz.zoneFk = zw.zoneFk AND zo.shipped = util.VN_CURDATE() @@ -79025,9 +79026,9 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getState`(vDated DATE) BEGIN /** * Devuelve las zonas y el estado para la fecha solicitada - * + * * @param vDated Fecha en cuestión - */ + */ DROP TEMPORARY TABLE IF EXISTS tmp.zone; CREATE TEMPORARY TABLE tmp.zone ( @@ -79041,7 +79042,7 @@ BEGIN CALL vn.zone_getOptionsForShipment(vDated, TRUE); CALL vn.zone_getClosed(); - + SELECT zo.zoneFk, zo.`hour`etd, (zo.`hour` <= TIME(util.VN_NOW())) isLate, @@ -79051,11 +79052,11 @@ BEGIN FROM tmp.zoneOption zo JOIN vn.zone z ON z.id = zo.zoneFk JOIN vn.zoneWarehouse zw ON zw.zoneFk = z.id - LEFT JOIN tmp.closedZones cz - ON cz.warehouseFk = zw.warehouseFk + LEFT JOIN tmp.closedZones cz + ON cz.warehouseFk = zw.warehouseFk AND cz.zoneFk = zo.zoneFk; - - DROP TEMPORARY TABLE + + DROP TEMPORARY TABLE tmp.closedZones, tmp.zoneOption, tmp.zone; @@ -79081,21 +79082,21 @@ BEGIN /** * Devuelve el listado de agencias disponibles para la fecha, * dirección y almacén pasados. - * + * * @param vAddress * @param vWarehouse warehouse * @param vLanded Fecha de recogida * @select Listado de agencias disponibles */ - + CALL zone_getFromGeo(address_getGeo(vAddress)); CALL zone_getOptionsForLanding(vLanded, FALSE); - - SELECT am.id agencyModeFk, - am.name agencyMode, - am.description, + + SELECT am.id agencyModeFk, + am.name agencyMode, + am.description, am.deliveryMethodFk, - TIMESTAMPADD(DAY, -zo.travelingDays, vLanded) shipped, + TIMESTAMPADD(DAY, -zo.travelingDays, vLanded) shipped, zw.warehouseFk, z.id zoneFk FROM tmp.zoneOption zo @@ -79105,11 +79106,11 @@ BEGIN WHERE zw.warehouseFk = vWarehouse GROUP BY z.agencyModeFk ORDER BY agencyMode; - + DROP TEMPORARY TABLE tmp.zone, tmp.zoneOption; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -79130,7 +79131,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_upcomingDeliveries`() BEGIN DECLARE vForwardDays INT; - + SELECT forwardDays INTO vForwardDays FROM zoneConfig; CALL util.time_createTable(util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL vForwardDays DAY)); @@ -79146,7 +79147,7 @@ BEGIN JOIN zoneEvent e ON e.zoneFk = z.id JOIN tmp.time ti ON ti.dated BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(DAY, vForwardDays, util.VN_CURDATE()); - DROP TEMPORARY TABLE IF EXISTS tmp.zoneOption; + DROP TEMPORARY TABLE IF EXISTS tmp.zoneOption; CREATE TEMPORARY TABLE tmp.zoneOption ENGINE = MEMORY SELECT * @@ -79187,7 +79188,7 @@ BEGIN JOIN zoneExclusion e ON e.zoneFk = t.zoneFk AND e.`dated` = t.landed LEFT JOIN zoneExclusionGeo eg ON eg.zoneExclusionFk = e.id WHERE eg.zoneExclusionFk IS NULL; - + SELECT MAX(zo.`hour`) `hour`, zg.`name`, zo.shipped, zo.zoneFk FROM tmp.zoneOption zo JOIN `zone` z ON z.id = zo.zoneFk @@ -79198,7 +79199,7 @@ BEGIN WHERE dm.code = 'DELIVERY' GROUP BY shipped, zg.`name` ORDER BY shipped, zg.`name`; - + DROP TEMPORARY TABLE tmp.time, tLandings; END ;; DELIMITER ; diff --git a/modules/worker/back/models/device-log.json b/modules/worker/back/models/device-log.json index 9278b9038..2b55e9474 100644 --- a/modules/worker/back/models/device-log.json +++ b/modules/worker/back/models/device-log.json @@ -28,6 +28,9 @@ }, "deviceProductionFk": { "type": "number" + }, + "serialNumber": { + "type": "string" } }, "relations": { From 731bad59818e3d1e8adb3cef2238561ccaa8400f Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 22 Sep 2023 14:52:56 +0200 Subject: [PATCH 135/427] ref #5914 create ticket with new and refactor --- .../00-transferInvoiceACL.sql | 8 +-- loopback/locale/en.json | 2 +- loopback/locale/es.json | 34 +++++----- .../methods/invoiceOut/transferInvoice.js | 13 ++-- modules/invoiceOut/back/models/invoice-out.js | 1 - .../front/descriptor-menu/style.scss | 2 +- modules/ticket/back/methods/sale/clone.js | 67 ++++++------------- modules/ticket/back/methods/sale/refund.js | 3 +- .../methods/ticket/invoiceTicketsWithPdf.js | 0 modules/ticket/back/models/ticket.json | 5 -- 10 files changed, 51 insertions(+), 84 deletions(-) rename db/changes/{233601 => 234001}/00-transferInvoiceACL.sql (67%) delete mode 100644 modules/ticket/back/methods/ticket/invoiceTicketsWithPdf.js diff --git a/db/changes/233601/00-transferInvoiceACL.sql b/db/changes/234001/00-transferInvoiceACL.sql similarity index 67% rename from db/changes/233601/00-transferInvoiceACL.sql rename to db/changes/234001/00-transferInvoiceACL.sql index a45e3f479..2bf4ec688 100644 --- a/db/changes/233601/00-transferInvoiceACL.sql +++ b/db/changes/234001/00-transferInvoiceACL.sql @@ -1,6 +1,6 @@ INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) VALUES - ('CplusRectificationType', '*', 'READ', 'ALLOW', 'ROLE', 'employee'), - ('CplusInvoiceType477', '*', 'READ', 'ALLOW', 'ROLE', 'employee'), - ('InvoiceCorrectionType', '*', 'READ', 'ALLOW', 'ROLE', 'employee'), - ('InvoiceOut', 'transferInvoice', 'WRITE', 'ALLOW', 'ROLE', 'employee'); \ No newline at end of file + ('CplusRectificationType', '*', 'READ', 'ALLOW', 'ROLE', 'administrative'), + ('CplusInvoiceType477', '*', 'READ', 'ALLOW', 'ROLE', 'administrative'), + ('InvoiceCorrectionType', '*', 'READ', 'ALLOW', 'ROLE', 'administrative'), + ('InvoiceOut', 'transferInvoice', 'WRITE', 'ALLOW', 'ROLE', 'administrative'); \ No newline at end of file diff --git a/loopback/locale/en.json b/loopback/locale/en.json index 3755c4a67..95e5ebc1c 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -188,7 +188,7 @@ "The ticket doesn't exist.": "The ticket doesn't exist.", "The sales do not exists": "The sales do not exists", "Ticket without Route": "Ticket without route", - "Select a different customer": "Select a different customer", + "Select a different client": "Select a different client", "Fill all the fields": "Fill all the fields", "Error while generating PDF": "Error while generating PDF", "Can't invoice to future": "Can't invoice to future", diff --git a/loopback/locale/es.json b/loopback/locale/es.json index f5973dcb7..18f51d7f8 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -5,10 +5,10 @@ "The default consignee can not be unchecked": "No se puede desmarcar el consignatario predeterminado", "Unable to default a disabled consignee": "No se puede poner predeterminado un consignatario desactivado", "Can't be blank": "No puede estar en blanco", - "Invalid TIN": "NIF/CIF invalido", + "Invalid TIN": "NIF/CIF inválido", "TIN must be unique": "El NIF/CIF debe ser único", "A client with that Web User name already exists": "Ya existe un cliente con ese Usuario Web", - "Is invalid": "Is invalid", + "Is invalid": "Es inválido", "Quantity cannot be zero": "La cantidad no puede ser cero", "Enter an integer different to zero": "Introduce un entero distinto de cero", "Package cannot be blank": "El embalaje no puede estar en blanco", @@ -55,8 +55,8 @@ "You must delete the claim id %d first": "Antes debes borrar la reclamación %d", "You don't have enough privileges": "No tienes suficientes permisos", "Cannot check Equalization Tax in this NIF/CIF": "No se puede marcar RE en este NIF/CIF", - "You can't make changes on the basic data of an confirmed order or with rows": "No puedes cambiar los datos basicos de una orden con artículos", - "INVALID_USER_NAME": "El nombre de usuario solo debe contener letras minúsculas o, a partir del segundo carácter, números o subguiones, no esta permitido el uso de la letra ñ", + "You can't make changes on the basic data of an confirmed order or with rows": "No puedes cambiar los datos básicos de una orden con artículos", + "INVALID_USER_NAME": "El nombre de usuario solo debe contener letras minúsculas o, a partir del segundo carácter, números o subguiones, no está permitido el uso de la letra ñ", "You can't create a ticket for a frozen client": "No puedes crear un ticket para un cliente congelado", "You can't create a ticket for a inactive client": "No puedes crear un ticket para un cliente inactivo", "Tag value cannot be blank": "El valor del tag no puede quedar en blanco", @@ -65,7 +65,7 @@ "NO SE PUEDE DESACTIVAR EL CONSIGNAT": "NO SE PUEDE DESACTIVAR EL CONSIGNAT", "Error. El NIF/CIF está repetido": "Error. El NIF/CIF está repetido", "Street cannot be empty": "Dirección no puede estar en blanco", - "City cannot be empty": "Cuidad no puede estar en blanco", + "City cannot be empty": "Ciudad no puede estar en blanco", "Code cannot be blank": "Código no puede estar en blanco", "You cannot remove this department": "No puedes eliminar este departamento", "The extension must be unique": "La extensión debe ser unica", @@ -102,8 +102,8 @@ "You can't delete a confirmed order": "No puedes borrar un pedido confirmado", "The social name has an invalid format": "El nombre fiscal tiene un formato incorrecto", "Invalid quantity": "Cantidad invalida", - "This postal code is not valid": "This postal code is not valid", - "is invalid": "is invalid", + "This postal code is not valid": "Este código postal no es válido", + "is invalid": "es inválido", "The postcode doesn't exist. Please enter a correct one": "El código postal no existe. Por favor, introduce uno correcto", "The department name can't be repeated": "El nombre del departamento no puede repetirse", "This phone already exists": "Este teléfono ya existe", @@ -112,8 +112,8 @@ "You cannot delete a ticket that part of it is being prepared": "No puedes eliminar un ticket en el que una parte que está siendo preparada", "You must delete all the buy requests first": "Debes eliminar todas las peticiones de compra primero", "You should specify a date": "Debes especificar una fecha", - "You should specify at least a start or end date": "Debes especificar al menos una fecha de inicio o de fín", - "Start date should be lower than end date": "La fecha de inicio debe ser menor que la fecha de fín", + "You should specify at least a start or end date": "Debes especificar al menos una fecha de inicio o de fin", + "Start date should be lower than end date": "La fecha de inicio debe ser menor que la fecha de fin", "You should mark at least one week day": "Debes marcar al menos un día de la semana", "Swift / BIC can't be empty": "Swift / BIC no puede estar vacío", "Customs agent is required for a non UEE member": "El agente de aduanas es requerido para los clientes extracomunitarios", @@ -144,15 +144,15 @@ "Unable to clone this travel": "No ha sido posible clonar este travel", "This thermograph id already exists": "La id del termógrafo ya existe", "Choose a date range or days forward": "Selecciona un rango de fechas o días en adelante", - "ORDER_ALREADY_CONFIRMED": "ORDER_ALREADY_CONFIRMED", + "ORDER_ALREADY_CONFIRMED": "ORDEN YA CONFIRMADA", "Invalid password": "Invalid password", "Password does not meet requirements": "La contraseña no cumple los requisitos", - "Role already assigned": "Role already assigned", - "Invalid role name": "Invalid role name", - "Role name must be written in camelCase": "Role name must be written in camelCase", - "Email already exists": "Email already exists", - "User already exists": "User already exists", - "Absence change notification on the labour calendar": "Notificacion de cambio de ausencia en el calendario laboral", + "Role already assigned": "Rol ya asignado", + "Invalid role name": "Nombre de rol no válido", + "Role name must be written in camelCase": "El nombre del rol debe escribirse en camelCase", + "Email already exists": "El correo ya existe", + "User already exists": "El/La usuario/a ya existe", + "Absence change notification on the labour calendar": "Notificación de cambio de ausencia en el calendario laboral", "Record of hours week": "Registro de horas semana {{week}} año {{year}} ", "Created absence": "El empleado {{author}} ha añadido una ausencia de tipo '{{absenceType}}' a {{employee}} para el día {{dated}}.", "Deleted absence": "El empleado {{author}} ha eliminado una ausencia de tipo '{{absenceType}}' a {{employee}} del día {{dated}}.", @@ -317,6 +317,6 @@ "Social name should be uppercase": "La razón social debe ir en mayúscula", "Street should be uppercase": "La dirección fiscal debe ir en mayúscula", "Ticket without Route": "Ticket sin ruta", - "Select a different customer": "Seleccione un cliente distinto", + "Select a different client": "Seleccione un cliente distinto", "Fill all the fields": "Rellene todos los campos" } \ No newline at end of file diff --git a/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js b/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js index 65b671716..c4f6e9445 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js +++ b/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js @@ -19,18 +19,22 @@ module.exports = Self => { { arg: 'newClientFk', type: 'number', + required: true }, { arg: 'cplusRectificationId', type: 'number', + required: true }, { arg: 'cplusInvoiceType477Id', type: 'number', + required: true }, { arg: 'invoiceCorrectionTypeId', type: 'number', + required: true }, ], returns: { @@ -54,10 +58,7 @@ module.exports = Self => { const {clientFk} = await models.InvoiceOut.findById(args.id); if (clientFk == args.newClientFk) - throw new UserError(`Select a different customer`); - - if (!args.newClientFk || !args.cplusRectificationId || !args.cplusInvoiceType477Id || !args.invoiceCorrectionTypeId) - throw new UserError(`Fill all the fields`); + throw new UserError(`Select a different client`); if (!myOptions.transaction) { tx = await Self.beginTransaction({}); @@ -77,7 +78,7 @@ module.exports = Self => { const sales = await models.Sale.find(filterTicket, myOptions); const salesIds = sales.map(sale => sale.id); - const clonedTickets = await models.Sale.clone(salesIds, servicesIds, null, false, false, myOptions); + const clonedTickets = await models.Sale.clone(ctx, salesIds, servicesIds, null, false, false, myOptions); const clonedTicketIds = []; for (const clonedTicket of clonedTickets) { @@ -93,7 +94,7 @@ module.exports = Self => { correctedFk: args.id, cplusRectificationTypeFk: args.cplusRectificationId, cplusInvoiceType477Fk: args.cplusInvoiceType477Id, - invoiceCorrectionType: args.invoiceCorrectionTypeId + invoiceCorrectionTypeFk: args.invoiceCorrectionTypeId }, myOptions); if (tx) await tx.commit(); diff --git a/modules/invoiceOut/back/models/invoice-out.js b/modules/invoiceOut/back/models/invoice-out.js index 34b4dc798..ca77c856f 100644 --- a/modules/invoiceOut/back/models/invoice-out.js +++ b/modules/invoiceOut/back/models/invoice-out.js @@ -44,7 +44,6 @@ module.exports = Self => { Self.makePdf = async function(id, options) { const fields = ['id', 'hasPdf', 'ref']; const invoiceOut = await Self.findById(id, {fields}, options); - console.log('Recoge invoiceOut?'); const invoiceReport = new print.Report('invoice', { reference: invoiceOut.ref }); diff --git a/modules/invoiceOut/front/descriptor-menu/style.scss b/modules/invoiceOut/front/descriptor-menu/style.scss index 25c02c80c..9e4cf4297 100644 --- a/modules/invoiceOut/front/descriptor-menu/style.scss +++ b/modules/invoiceOut/front/descriptor-menu/style.scss @@ -25,6 +25,6 @@ vn-invoice-out-descriptor-menu { } @media screen and (min-width: 1000px) { .transferInvoice { - min-width: 900px; + min-width: $width-md; } } diff --git a/modules/ticket/back/methods/sale/clone.js b/modules/ticket/back/methods/sale/clone.js index d899b3c44..7ce7675da 100644 --- a/modules/ticket/back/methods/sale/clone.js +++ b/modules/ticket/back/methods/sale/clone.js @@ -1,5 +1,5 @@ module.exports = Self => { - Self.clone = async(salesIds, servicesIds, withWarehouse, group, negative, options) => { + Self.clone = async(ctx, salesIds, servicesIds, withWarehouse, group, negative, options) => { const models = Self.app.models; const myOptions = {}; let tx; @@ -23,32 +23,24 @@ module.exports = Self => { } }; const sales = await models.Sale.find(salesFilter, myOptions); - const ticketsIds = [...new Set(sales.map(sale => sale.ticketFk))]; + let ticketsIds = [...new Set(sales.map(sale => sale.ticketFk))]; const refundTickets = []; const mappedTickets = new Map(); const now = Date.vnNew(); - const [firstTicketId] = ticketsIds; - if (group) { + + if (group) ticketsIds = [ticketsIds[0]]; + + for (let ticketId in ticketsIds) { await createTicketRefund( - firstTicketId, + ctx, + ticketsIds[ticketId], withWarehouse, refundTickets, - mappedTickets, now, myOptions ); - } else { - for (let ticketId of ticketsIds) { - await createTicketRefund( - ticketId, - withWarehouse, - refundTickets, - mappedTickets, - now, - myOptions - ); - } + mappedTickets.set(ticketsIds[ticketId], refundTickets[ticketId].id); } for (const sale of sales) { @@ -100,47 +92,26 @@ module.exports = Self => { }; async function createTicketRefund( + ctx, ticketId, withWarehouse, refundTickets, - mappedTickets, now, myOptions ) { const models = Self.app.models; - const filter = { - include: [ - { - relation: 'address' - }, - { - relation: 'agencyMode' - }, - { - relation: 'zone' - } - ] - }; - const ticket = await models.Ticket.findById(ticketId, filter, myOptions); - const refundTicket = await models.Ticket.create({ - clientFk: ticket.clientFk, - shipped: now, - addressFk: ticket.address().id, - agencyModeFk: ticket.agencyMode().id, - nickname: ticket.address().nickname, - warehouseFk: withWarehouse ? ticket.warehouseFk : null, - companyFk: ticket.companyFk, - zonePrice: ticket.zonePrice, - zoneBonus: ticket.zoneBonus, - weight: ticket.weight, - landed: now, - zoneFk: ticket.zone().id, - }, myOptions); + const ticket = await models.Ticket.findById(ticketId, myOptions); + ctx.args.clientId = ticket.clientFk; + ctx.args.shipped = now; + ctx.args.landed = now; + ctx.args.warehouseId = withWarehouse ? ticket.warehouseFk : null; + ctx.args.companyId = ticket.companyFk; + ctx.args.addressId = ticket.addressFk; + + const refundTicket = await models.Ticket.new(ctx, myOptions); refundTickets.push(refundTicket); - - mappedTickets.set(ticketId, refundTicket.id); } async function getTicketRefundId(group, ticketId, refundTickets, mappedTickets) { diff --git a/modules/ticket/back/methods/sale/refund.js b/modules/ticket/back/methods/sale/refund.js index 5d8297a4e..17b70f12b 100644 --- a/modules/ticket/back/methods/sale/refund.js +++ b/modules/ticket/back/methods/sale/refund.js @@ -43,10 +43,11 @@ module.exports = Self => { try { const refundsTicket = await models.Sale.clone( + ctx, salesIds, servicesIds, withWarehouse, - true, + false, true, myOptions ); diff --git a/modules/ticket/back/methods/ticket/invoiceTicketsWithPdf.js b/modules/ticket/back/methods/ticket/invoiceTicketsWithPdf.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/modules/ticket/back/models/ticket.json b/modules/ticket/back/models/ticket.json index 1c5610a2a..ec4193bed 100644 --- a/modules/ticket/back/models/ticket.json +++ b/modules/ticket/back/models/ticket.json @@ -136,11 +136,6 @@ "type": "belongsTo", "model": "Zone", "foreignKey": "zoneFk" - }, - "sale": { - "type": "hasMany", - "model": "Sale", - "foreignKey": "ticketFk" } } } From 9b10a2904c39fd5d6931dd796bb43759a574983c Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 25 Sep 2023 08:23:23 +0200 Subject: [PATCH 136/427] refs #6213 unifyTest --- modules/supplier/back/models/specs/supplier.spec.js | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/modules/supplier/back/models/specs/supplier.spec.js b/modules/supplier/back/models/specs/supplier.spec.js index 9dd84d9fa..782c5cdf0 100644 --- a/modules/supplier/back/models/specs/supplier.spec.js +++ b/modules/supplier/back/models/specs/supplier.spec.js @@ -123,10 +123,8 @@ describe('loopback model Supplier', () => { throw e; } }); - }); - describe('after save observer', () => { - it('should update the account attribute when a new supplier is created', async() => { + fit('should update the account attribute when a new supplier is created', async() => { const tx = await models.Supplier.beginTransaction({}); const options = {transaction: tx}; From af8773612cf1b2e8da64a88df81ee30c94fc0b69 Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 25 Sep 2023 08:23:59 +0200 Subject: [PATCH 137/427] refs #6213 remove f --- modules/supplier/back/models/specs/supplier.spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/supplier/back/models/specs/supplier.spec.js b/modules/supplier/back/models/specs/supplier.spec.js index 782c5cdf0..3db273a95 100644 --- a/modules/supplier/back/models/specs/supplier.spec.js +++ b/modules/supplier/back/models/specs/supplier.spec.js @@ -124,7 +124,7 @@ describe('loopback model Supplier', () => { } }); - fit('should update the account attribute when a new supplier is created', async() => { + it('should update the account attribute when a new supplier is created', async() => { const tx = await models.Supplier.beginTransaction({}); const options = {transaction: tx}; From 6cf1095b100fca4169ac71a4debd9cfdb644ded4 Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 25 Sep 2023 08:33:16 +0200 Subject: [PATCH 138/427] refs #6067 feat: vnUser use verify() and more security when update user and mailForward --- back/methods/vn-user/update-user.js | 41 ++++++++++++++++++ back/models/specs/vn-user.spec.js | 38 ++++++++++++++++ back/models/vn-user.js | 43 +++++++++---------- back/models/vn-user.json | 17 +++----- db/changes/234001/00-account_acl.sql | 13 ++---- modules/account/back/models/mail-forward.js | 4 -- modules/account/back/models/mail-forward.json | 16 +------ modules/account/front/basic-data/index.html | 6 +-- modules/account/front/basic-data/index.js | 10 ++--- modules/account/front/routes.json | 5 ++- 10 files changed, 120 insertions(+), 73 deletions(-) create mode 100644 back/methods/vn-user/update-user.js diff --git a/back/methods/vn-user/update-user.js b/back/methods/vn-user/update-user.js new file mode 100644 index 000000000..85f6df762 --- /dev/null +++ b/back/methods/vn-user/update-user.js @@ -0,0 +1,41 @@ +module.exports = Self => { + Self.remoteMethodCtx('updateUser', { + description: 'Update user data', + accepts: [ + { + arg: 'id', + type: 'integer', + description: 'The user id', + required: true, + http: {source: 'path'} + }, { + arg: 'name', + type: 'string', + description: 'The user name', + }, { + arg: 'nickname', + type: 'string', + description: 'The user nickname', + }, { + arg: 'email', + type: 'string', + description: 'The user email' + }, { + arg: 'lang', + type: 'string', + description: 'The user lang' + } + ], + http: { + path: `/:id/update-user`, + verb: 'PATCH' + } + }); + + Self.updateUser = async(ctx, id) => { + await Self.userSecurity(ctx, id); + const user = await Self.app.models.VnUser.findById(id, + {fields: ['id', 'name', 'nickname', 'email', 'lang', 'password']}); + await user.updateAttributes(ctx.args); + }; +}; diff --git a/back/models/specs/vn-user.spec.js b/back/models/specs/vn-user.spec.js index 3700b919a..5638942fb 100644 --- a/back/models/specs/vn-user.spec.js +++ b/back/models/specs/vn-user.spec.js @@ -12,4 +12,42 @@ describe('loopback model VnUser', () => { expect(result).toBeFalsy(); }); + + describe('userSecurity', () => { + const itManagementId = 115; + const hrId = 37; + const employeeId = 1; + + it('should check if you are the same user', async() => { + const ctx = {options: {accessToken: {userId: employeeId}}}; + await models.VnUser.userSecurity(ctx, employeeId); + }); + + it('should check for higher privileges', async() => { + const ctx = {options: {accessToken: {userId: itManagementId}}}; + await models.VnUser.userSecurity(ctx, employeeId); + }); + + it('should check if you have medium privileges and the user email is not verified', async() => { + const ctx = {options: {accessToken: {userId: hrId}}}; + await models.VnUser.userSecurity(ctx, employeeId); + }); + + it('should throw an error if you have medium privileges and the users email is verified', async() => { + const tx = await models.VnUser.beginTransaction({}); + const ctx = {options: {accessToken: {userId: hrId}}}; + try { + const options = {transaction: tx}; + const userToUpdate = await models.VnUser.findById(1, null, options); + userToUpdate.updateAttribute('emailVerified', 1, options); + + await models.VnUser.userSecurity(ctx, employeeId, options); + await tx.rollback(); + } catch (error) { + await tx.rollback(); + + expect(error.message).toEqual(`You don't have enough privileges`); + } + }); + }); }); diff --git a/back/models/vn-user.js b/back/models/vn-user.js index 642d3fdf3..6aac21561 100644 --- a/back/models/vn-user.js +++ b/back/models/vn-user.js @@ -13,6 +13,7 @@ module.exports = function(Self) { require('../methods/vn-user/privileges')(Self); require('../methods/vn-user/validate-auth')(Self); require('../methods/vn-user/renew-token')(Self); + require('../methods/vn-user/update-user')(Self); Self.definition.settings.acls = Self.definition.settings.acls.filter(acl => acl.property !== 'create'); @@ -179,32 +180,31 @@ module.exports = function(Self) { Self.sharedClass._methods.find(method => method.name == 'changePassword').ctor.settings.acls .filter(acl => acl.property != 'changePassword'); - Self.observe('before save', async ctx => { - const instance = ctx.currentInstance || ctx.instance; - console.log(ctx); - await Self.userSecurity(ctx, instance.id); - }); - - Self.userSecurity = async(ctx, userId) => { + Self.userSecurity = async(ctx, userId, options) => { const models = Self.app.models; - const accessToken = ctx.options.accessToken || LoopBackContext.getCurrentContext().active.accessToken; - console.log(accessToken, LoopBackContext.getCurrentContext().active.http.req); + const accessToken = ctx?.options?.accessToken || LoopBackContext.getCurrentContext().active.accessToken; const ctxToken = {req: {accessToken}}; - const hasHigherPrivileges = await models.ACL.checkAccessAcl(ctxToken, 'VnUser', 'higherPrivileges'); + if (userId === accessToken.userId) return; + + const myOptions = {}; + if (typeof options == 'object') + Object.assign(myOptions, options); + + const hasHigherPrivileges = await models.ACL.checkAccessAcl(ctxToken, 'VnUser', 'higherPrivileges', myOptions); if (hasHigherPrivileges) return; - const hasMediumPrivileges = await models.ACL.checkAccessAcl(ctxToken, 'VnUser', 'mediumPrivileges'); - const user = await models.VnUser.findById(userId, {fields: ['id', 'emailVerified']}); + const hasMediumPrivileges = await models.ACL.checkAccessAcl(ctxToken, 'VnUser', 'mediumPrivileges', myOptions); + const user = await models.VnUser.findById(userId, {fields: ['id', 'emailVerified']}, myOptions); if (!user.emailVerified && hasMediumPrivileges) return; - if (userId != accessToken.userId) - throw new UserError(`You don't have enough privileges`); + throw new UserError(`You don't have enough privileges`); }; - // FIXME: https://redmine.verdnatura.es/issues/5761 - Self.afterRemote('prototype.patchAttributes', async(ctx, instance) => { - if (!ctx.args || !ctx.args.data.email) return; + Self.observe('after save', async ctx => { + const newEmail = ctx?.instance?.email; + const oldEmail = ctx?.hookState?.oldInstance?.email; + if (!ctx.isNewInstance && (!newEmail || !oldEmail || newEmail == oldEmail)) return; const loopBackContext = LoopBackContext.getCurrentContext(); const httpCtx = {req: loopBackContext.active}; @@ -217,8 +217,7 @@ module.exports = function(Self) { async send(verifyOptions, cb) { const params = { url: verifyOptions.verifyHref, - recipient: verifyOptions.to, - lang: ctx.req.getLocale() + recipient: verifyOptions.to }; const email = new Email('email-verify', params); @@ -230,9 +229,9 @@ module.exports = function(Self) { const options = { type: 'email', - to: instance.email, + to: newEmail, from: {}, - redirect: `${origin}/#!/account/${instance.id}/basic-data?emailConfirmed`, + redirect: `${origin}/#!/account/${ctx.instance.id}/basic-data?emailConfirmed`, template: false, mailer: new Mailer, host: url[1].split('/')[2], @@ -241,6 +240,6 @@ module.exports = function(Self) { user: Self }; - await instance.verify(options); + await ctx.instance.verify(options, ctx.options); }); }; diff --git a/back/models/vn-user.json b/back/models/vn-user.json index d233bf7b4..3ae942958 100644 --- a/back/models/vn-user.json +++ b/back/models/vn-user.json @@ -13,11 +13,12 @@ "type": "number", "id": true }, - "username": { + "name": { "type": "string", - "mysql": { - "columnName": "name" - } + "required": true + }, + "username": { + "type": "string" }, "password": { "type": "string", @@ -123,13 +124,7 @@ "principalType": "ROLE", "principalId": "$authenticated", "permission": "ALLOW" - }, - { - "principalType": "ROLE", - "principalId": "$authenticated", - "permission": "ALLOW", - "property": "patchAttributes" - } + } ], "scopes": { "preview": { diff --git a/db/changes/234001/00-account_acl.sql b/db/changes/234001/00-account_acl.sql index 23f47b99f..8dfe1d1ec 100644 --- a/db/changes/234001/00-account_acl.sql +++ b/db/changes/234001/00-account_acl.sql @@ -1,12 +1,7 @@ -DELETE FROM `salix`.`ACL` - WHERE - model = 'MailForward' - AND accessType = '*' - AND property = '*' - AND principalId = 'hr'; - - INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) VALUES ('VnUser', 'higherPrivileges', '*', 'ALLOW', 'ROLE', 'itManagement'), - ('VnUser', 'mediumPrivileges', '*', 'ALLOW', 'ROLE', 'hr'); + ('VnUser', 'mediumPrivileges', '*', 'ALLOW', 'ROLE', 'hr'), + ('VnUser', 'updateUser', '*', 'ALLOW', 'ROLE', 'employee'); + +ALTER TABLE `account`.`user` ADD `username` varchar(30) AS (name) VIRTUAL; diff --git a/modules/account/back/models/mail-forward.js b/modules/account/back/models/mail-forward.js index d55f5ddbc..adc282155 100644 --- a/modules/account/back/models/mail-forward.js +++ b/modules/account/back/models/mail-forward.js @@ -1,9 +1,5 @@ module.exports = Self => { - Self.observe('loaded', async ctx => { - if (!ctx.data.account) return; - await Self.app.models.VnUser.userSecurity(ctx, ctx.data.account); - }); Self.observe('before save', async ctx => { const instance = ctx.currentInstance || ctx.instance; await Self.app.models.VnUser.userSecurity(ctx, instance.account); diff --git a/modules/account/back/models/mail-forward.json b/modules/account/back/models/mail-forward.json index af4de3218..edef1bf08 100644 --- a/modules/account/back/models/mail-forward.json +++ b/modules/account/back/models/mail-forward.json @@ -21,19 +21,5 @@ "model": "VnUser", "foreignKey": "account" } - }, - "acls": [ - { - "accessType": "READ", - "principalType": "ROLE", - "principalId": "$authenticated", - "permission": "ALLOW" - }, - { - "accessType": "WRITE", - "principalType": "ROLE", - "principalId": "$authenticated", - "permission": "ALLOW" - } - ] + } } diff --git a/modules/account/front/basic-data/index.html b/modules/account/front/basic-data/index.html index 1f7ce1a05..9fd3506fe 100644 --- a/modules/account/front/basic-data/index.html +++ b/modules/account/front/basic-data/index.html @@ -1,11 +1,9 @@ - + + save="patch"> Date: Mon, 25 Sep 2023 10:49:47 +0200 Subject: [PATCH 139/427] ref #5914 fixed tests e2e --- e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js | 6 +++--- loopback/locale/en.json | 2 +- loopback/locale/es.json | 2 +- .../back/methods/invoiceOut/specs/refund.spec.js | 2 +- modules/ticket/back/methods/sale/specs/refund.spec.js | 8 +++++--- modules/ticket/back/methods/ticket/new.js | 2 +- modules/ticket/back/methods/ticket/specs/new.spec.js | 2 +- modules/ticket/back/methods/ticket/transferSales.js | 2 +- 8 files changed, 14 insertions(+), 12 deletions(-) diff --git a/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js b/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js index 6264073f6..da4b2c92b 100644 --- a/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js +++ b/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js @@ -220,7 +220,7 @@ describe('Ticket Edit sale path', () => { it('should log in as salesAssistant and navigate to ticket sales', async() => { await page.loginAndModule('salesAssistant', 'ticket'); - await page.accessToSearchResult('17'); + await page.accessToSearchResult('15'); await page.accessToSection('ticket.card.sale'); }); @@ -324,7 +324,7 @@ describe('Ticket Edit sale path', () => { }); it('should confirm the transfered quantity is the correct one', async() => { - const result = await page.waitToGetProperty(selectors.ticketSales.secondSaleQuantityCell, 'innerText'); + const result = await page.waitToGetProperty(selectors.ticketSales.firstSaleQuantityCell, 'innerText'); expect(result).toContain('20'); }); @@ -378,7 +378,7 @@ describe('Ticket Edit sale path', () => { await page.waitToClick(selectors.ticketSales.moveToNewTicketButton); const message = await page.waitForSnackbar(); - expect(message.text).toContain(`You can't create a ticket for a inactive client`); + expect(message.text).toContain(`You can't create a ticket for an inactive client`); await page.closePopup(); }); diff --git a/loopback/locale/en.json b/loopback/locale/en.json index 95e5ebc1c..b56c3de77 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -23,7 +23,7 @@ "Agency cannot be blank": "Agency cannot be blank", "The IBAN does not have the correct format": "The IBAN does not have the correct format", "You can't make changes on the basic data of an confirmed order or with rows": "You can't make changes on the basic data of an confirmed order or with rows", - "You can't create a ticket for a inactive client": "You can't create a ticket for a inactive client", + "You can't create a ticket for an inactive client": "You can't create a ticket for an inactive client", "Worker cannot be blank": "Worker cannot be blank", "You must delete the claim id %d first": "You must delete the claim id %d first", "You don't have enough privileges": "You don't have enough privileges", diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 18f51d7f8..568c9a306 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -58,7 +58,7 @@ "You can't make changes on the basic data of an confirmed order or with rows": "No puedes cambiar los datos básicos de una orden con artículos", "INVALID_USER_NAME": "El nombre de usuario solo debe contener letras minúsculas o, a partir del segundo carácter, números o subguiones, no está permitido el uso de la letra ñ", "You can't create a ticket for a frozen client": "No puedes crear un ticket para un cliente congelado", - "You can't create a ticket for a inactive client": "No puedes crear un ticket para un cliente inactivo", + "You can't create a ticket for an inactive client": "No puedes crear un ticket para un cliente inactivo", "Tag value cannot be blank": "El valor del tag no puede quedar en blanco", "ORDER_EMPTY": "Cesta vacía", "You don't have enough privileges to do that": "No tienes permisos para cambiar esto", diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/refund.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/refund.spec.js index 6ecfe6015..22891f161 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/specs/refund.spec.js +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/refund.spec.js @@ -3,7 +3,7 @@ const LoopBackContext = require('loopback-context'); describe('InvoiceOut refund()', () => { const userId = 5; - const ctx = {req: {accessToken: userId}}; + const ctx = {req: {accessToken: userId}, args: {}}; const withWarehouse = true; const activeCtx = { accessToken: {userId: userId}, diff --git a/modules/ticket/back/methods/sale/specs/refund.spec.js b/modules/ticket/back/methods/sale/specs/refund.spec.js index b81f7f84d..08eb1fabd 100644 --- a/modules/ticket/back/methods/sale/specs/refund.spec.js +++ b/modules/ticket/back/methods/sale/specs/refund.spec.js @@ -3,7 +3,7 @@ const LoopBackContext = require('loopback-context'); describe('Sale refund()', () => { const userId = 5; - const ctx = {req: {accessToken: userId}}; + const ctx = {req: {accessToken: userId}, args: {}}; const activeCtx = { accessToken: {userId}, }; @@ -40,6 +40,7 @@ describe('Sale refund()', () => { try { const options = {transaction: tx}; + const ticketsBefore = await models.Ticket.find({}, options); const ticket = await models.Sale.refund(ctx, salesIds, servicesIds, withWarehouse, options); @@ -61,12 +62,13 @@ describe('Sale refund()', () => { } ] }, options); - + const ticketsAfter = await models.Ticket.find({}, options); const salesLength = refundedTicket.ticketSales().length; const componentsLength = refundedTicket.ticketSales()[0].components().length; expect(refundedTicket).toBeDefined(); - expect(salesLength).toEqual(2); + expect(salesLength).toEqual(1); + expect(ticketsBefore.length).toEqual(ticketsAfter.length - 2); expect(componentsLength).toEqual(4); await tx.rollback(); diff --git a/modules/ticket/back/methods/ticket/new.js b/modules/ticket/back/methods/ticket/new.js index b461fb26d..65bc76c5d 100644 --- a/modules/ticket/back/methods/ticket/new.js +++ b/modules/ticket/back/methods/ticket/new.js @@ -96,7 +96,7 @@ module.exports = Self => { if (address.client().type().code === 'normal' && (!agencyMode || agencyMode.code != 'refund')) { const canCreateTicket = await models.Client.canCreateTicket(args.clientId, myOptions); if (!canCreateTicket) - throw new UserError(`You can't create a ticket for a inactive client`); + throw new UserError(`You can't create a ticket for an inactive client`); } if (!args.shipped && args.landed) { diff --git a/modules/ticket/back/methods/ticket/specs/new.spec.js b/modules/ticket/back/methods/ticket/specs/new.spec.js index 0a2f93bc4..9aa073a7b 100644 --- a/modules/ticket/back/methods/ticket/specs/new.spec.js +++ b/modules/ticket/back/methods/ticket/specs/new.spec.js @@ -30,7 +30,7 @@ describe('ticket new()', () => { await tx.rollback(); } - expect(error).toEqual(new UserError(`You can't create a ticket for a inactive client`)); + expect(error).toEqual(new UserError(`You can't create a ticket for an inactive client`)); }); it('should throw an error if the address doesnt exist', async() => { diff --git a/modules/ticket/back/methods/ticket/transferSales.js b/modules/ticket/back/methods/ticket/transferSales.js index 1124f7ec7..f2cb89205 100644 --- a/modules/ticket/back/methods/ticket/transferSales.js +++ b/modules/ticket/back/methods/ticket/transferSales.js @@ -66,7 +66,7 @@ module.exports = Self => { const ticket = await models.Ticket.findById(id); const canCreateTicket = await models.Client.canCreateTicket(ticket.clientFk); if (!canCreateTicket) - throw new UserError(`You can't create a ticket for a inactive client`); + throw new UserError(`You can't create a ticket for an inactive client`); ticketId = await cloneTicket(originalTicket, myOptions); } From 98ee9bbaf320684102e08f91fee8813abf5c7417 Mon Sep 17 00:00:00 2001 From: jorgep Date: Mon, 25 Sep 2023 12:54:31 +0200 Subject: [PATCH 140/427] ref #5914 back test added --- ...rInvoiceACL.sql => 00-transferInvoice.sql} | 6 ++- .../invoiceOut/specs/transferinvoice.spec.js | 43 +++++++++++++++++++ .../methods/invoiceOut/transferInvoice.js | 7 +-- 3 files changed, 52 insertions(+), 4 deletions(-) rename db/changes/234001/{00-transferInvoiceACL.sql => 00-transferInvoice.sql} (76%) create mode 100644 modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js diff --git a/db/changes/234001/00-transferInvoiceACL.sql b/db/changes/234001/00-transferInvoice.sql similarity index 76% rename from db/changes/234001/00-transferInvoiceACL.sql rename to db/changes/234001/00-transferInvoice.sql index 2bf4ec688..f0608327a 100644 --- a/db/changes/234001/00-transferInvoiceACL.sql +++ b/db/changes/234001/00-transferInvoice.sql @@ -3,4 +3,8 @@ INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalTyp ('CplusRectificationType', '*', 'READ', 'ALLOW', 'ROLE', 'administrative'), ('CplusInvoiceType477', '*', 'READ', 'ALLOW', 'ROLE', 'administrative'), ('InvoiceCorrectionType', '*', 'READ', 'ALLOW', 'ROLE', 'administrative'), - ('InvoiceOut', 'transferInvoice', 'WRITE', 'ALLOW', 'ROLE', 'administrative'); \ No newline at end of file + ('InvoiceOut', 'transferInvoice', 'WRITE', 'ALLOW', 'ROLE', 'administrative'); + +INSERT INTO `vn`.`invoiceCorrectionType` (description) + VALUES + ('Error en el cálculo del IVA') \ No newline at end of file diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js new file mode 100644 index 000000000..cea4ffacc --- /dev/null +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js @@ -0,0 +1,43 @@ +const models = require('vn-loopback/server/server').models; + +describe('InvoiceOut tranferInvoice()', () => { + const userId = 5; + const ctx = {req: {accessToken: userId}}; + ctx.args = { + id: '1', + ref: 'T1111111', + newClientFk: 1, + cplusRectificationId: 1, + cplusInvoiceType477Id: 1, + invoiceCorrectionTypeId: 1 + }; + it('should return the id of the created issued invoice', async() => { + const tx = await models.InvoiceOut.beginTransaction({}); + const options = {transaction: tx}; + try { + const result = await models.InvoiceOut.transferInvoice( + ctx, + options); + + expect(result).toBeDefined(); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('should throw an UserError when it is the same client', async() => { + const tx = await models.InvoiceOut.beginTransaction({}); + const options = {transaction: tx}; + try { + ctx.args.newClientFk = 1101; + await models.InvoiceOut.transferInvoice( + ctx, + options); + } catch (e) { + expect(e.message).toBe(`Select a different client`); + await tx.rollback(); + } + }); +}); diff --git a/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js b/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js index c4f6e9445..8a0609b8d 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js +++ b/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js @@ -97,9 +97,10 @@ module.exports = Self => { invoiceCorrectionTypeFk: args.invoiceCorrectionTypeId }, myOptions); - if (tx) await tx.commit(); - - await models.InvoiceOut.makePdfAndNotify(ctx, invoiceId, null); + if (tx) { + await tx.commit(); + await models.InvoiceOut.makePdfAndNotify(ctx, invoiceId, null); + } return invoiceId; } catch (e) { From eb0e6dd985b433f2a41a3d99f07f1761440cbcca Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 25 Sep 2023 13:06:28 +0200 Subject: [PATCH 141/427] refs #6033 feat(VnLog): can use accountDescriptor --- front/salix/components/log/index.html | 5 ++++- front/salix/components/log/index.js | 5 ++++- .../front/descriptor-popover/index.html | 4 ++++ .../account/front/descriptor-popover/index.js | 9 ++++++++ modules/account/front/descriptor/index.js | 22 +++++++++++++++++++ modules/account/front/index.js | 1 + 6 files changed, 44 insertions(+), 2 deletions(-) create mode 100644 modules/account/front/descriptor-popover/index.html create mode 100644 modules/account/front/descriptor-popover/index.js diff --git a/front/salix/components/log/index.html b/front/salix/components/log/index.html index 6a1367e28..c75030100 100644 --- a/front/salix/components/log/index.html +++ b/front/salix/components/log/index.html @@ -28,7 +28,7 @@ + ng-click="$ctrl.showDescriptor($event, userLog)"> @@ -260,3 +260,6 @@ + + diff --git a/front/salix/components/log/index.js b/front/salix/components/log/index.js index 176815eef..a77f0b984 100644 --- a/front/salix/components/log/index.js +++ b/front/salix/components/log/index.js @@ -362,7 +362,10 @@ export default class Controller extends Section { } } - showWorkerDescriptor(event, userLog) { + showDescriptor(event, userLog) { + if (this.$state.current.name.split('.')[0] == 'account') + return this.$.accountDescriptor.show(event.target, userLog.userFk); + if (userLog.user?.worker) this.$.workerDescriptor.show(event.target, userLog.userFk); } diff --git a/modules/account/front/descriptor-popover/index.html b/modules/account/front/descriptor-popover/index.html new file mode 100644 index 000000000..f3131a84b --- /dev/null +++ b/modules/account/front/descriptor-popover/index.html @@ -0,0 +1,4 @@ + + + + diff --git a/modules/account/front/descriptor-popover/index.js b/modules/account/front/descriptor-popover/index.js new file mode 100644 index 000000000..d7b052473 --- /dev/null +++ b/modules/account/front/descriptor-popover/index.js @@ -0,0 +1,9 @@ +import ngModule from '../module'; +import DescriptorPopover from 'salix/components/descriptor-popover'; + +class Controller extends DescriptorPopover {} + +ngModule.vnComponent('vnAccountDescriptorPopover', { + slotTemplate: require('./index.html'), + controller: Controller +}); diff --git a/modules/account/front/descriptor/index.js b/modules/account/front/descriptor/index.js index 150c9d660..786870d36 100644 --- a/modules/account/front/descriptor/index.js +++ b/modules/account/front/descriptor/index.js @@ -24,6 +24,28 @@ class Controller extends Descriptor { .then(res => this.hasAccount = res.data.exists); } + loadData() { + const filter = { + where: {id: this.$params.id}, + include: { + relation: 'role', + scope: { + fields: ['id', 'name'] + } + } + }; + + return Promise.all([ + this.$http.get(`VnUsers/preview`, {filter}) + .then(res => { + const [user] = res.data; + this.user = user; + }), + this.$http.get(`Accounts/${this.$params.id}/exists`) + .then(res => this.hasAccount = res.data.exists) + ]); + } + onDelete() { return this.$http.delete(`VnUsers/${this.id}`) .then(() => this.$state.go('account.index')) diff --git a/modules/account/front/index.js b/modules/account/front/index.js index 695f36967..4d6aedcae 100644 --- a/modules/account/front/index.js +++ b/modules/account/front/index.js @@ -9,6 +9,7 @@ import './acl'; import './summary'; import './card'; import './descriptor'; +import './descriptor-popover'; import './search-panel'; import './create'; import './basic-data'; From 5a3094cd7021ca3b8c8ed3c8931136a4f04f1a40 Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 25 Sep 2023 13:24:30 +0200 Subject: [PATCH 142/427] refs #6033 feat(VnLog): better if --- front/salix/components/log/index.js | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/front/salix/components/log/index.js b/front/salix/components/log/index.js index a77f0b984..1edaa72ae 100644 --- a/front/salix/components/log/index.js +++ b/front/salix/components/log/index.js @@ -363,11 +363,10 @@ export default class Controller extends Section { } showDescriptor(event, userLog) { - if (this.$state.current.name.split('.')[0] == 'account') - return this.$.accountDescriptor.show(event.target, userLog.userFk); + if (userLog.user?.worker && this.$state.current.name.split('.')[0] != 'account') + return this.$.workerDescriptor.show(event.target, userLog.userFk); - if (userLog.user?.worker) - this.$.workerDescriptor.show(event.target, userLog.userFk); + this.$.accountDescriptor.show(event.target, userLog.userFk); } } From 64eb216367d6702ad1e0d2a672df05e9103d28c2 Mon Sep 17 00:00:00 2001 From: jorgep Date: Mon, 25 Sep 2023 14:01:40 +0200 Subject: [PATCH 143/427] ref #5914 fixed back test --- .../invoiceOut/specs/transferinvoice.spec.js | 27 ++++++++++++------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js index cea4ffacc..75bf649ec 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js @@ -3,17 +3,18 @@ const models = require('vn-loopback/server/server').models; describe('InvoiceOut tranferInvoice()', () => { const userId = 5; const ctx = {req: {accessToken: userId}}; - ctx.args = { - id: '1', - ref: 'T1111111', - newClientFk: 1, - cplusRectificationId: 1, - cplusInvoiceType477Id: 1, - invoiceCorrectionTypeId: 1 - }; it('should return the id of the created issued invoice', async() => { const tx = await models.InvoiceOut.beginTransaction({}); const options = {transaction: tx}; + const args = { + id: '1', + ref: 'T1111111', + newClientFk: 1, + cplusRectificationId: 1, + cplusInvoiceType477Id: 1, + invoiceCorrectionTypeId: 1 + }; + ctx.args = args; try { const result = await models.InvoiceOut.transferInvoice( ctx, @@ -30,8 +31,16 @@ describe('InvoiceOut tranferInvoice()', () => { it('should throw an UserError when it is the same client', async() => { const tx = await models.InvoiceOut.beginTransaction({}); const options = {transaction: tx}; + const args = { + id: '1', + ref: 'T1111111', + newClientFk: 1101, + cplusRectificationId: 1, + cplusInvoiceType477Id: 1, + invoiceCorrectionTypeId: 1 + }; + ctx.args = args; try { - ctx.args.newClientFk = 1101; await models.InvoiceOut.transferInvoice( ctx, options); From 474399b383cefa9c6d9a715082222cc4d8ada3b9 Mon Sep 17 00:00:00 2001 From: jorgep Date: Mon, 25 Sep 2023 15:23:51 +0200 Subject: [PATCH 144/427] ref #5914 refactor --- db/changes/234001/00-transferInvoice.sql | 4 ---- db/dump/fixtures.sql | 6 ++++++ modules/ticket/back/methods/sale/clone.js | 13 +++---------- 3 files changed, 9 insertions(+), 14 deletions(-) diff --git a/db/changes/234001/00-transferInvoice.sql b/db/changes/234001/00-transferInvoice.sql index f0608327a..7a9890ae4 100644 --- a/db/changes/234001/00-transferInvoice.sql +++ b/db/changes/234001/00-transferInvoice.sql @@ -4,7 +4,3 @@ INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalTyp ('CplusInvoiceType477', '*', 'READ', 'ALLOW', 'ROLE', 'administrative'), ('InvoiceCorrectionType', '*', 'READ', 'ALLOW', 'ROLE', 'administrative'), ('InvoiceOut', 'transferInvoice', 'WRITE', 'ALLOW', 'ROLE', 'administrative'); - -INSERT INTO `vn`.`invoiceCorrectionType` (description) - VALUES - ('Error en el cálculo del IVA') \ No newline at end of file diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 1d115af0d..15d78adff 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -2974,3 +2974,9 @@ INSERT INTO vn.XDiario (id, ASIEN, FECHA, SUBCTA, CONTRA, CONCEPTO, EURODEBE, EU (4, 2.0, util.VN_CURDATE(), '4300001104', NULL, 'n/fra T4444444', 8.88, NULL, NULL, NULL, '0', NULL, 0.00, NULL, NULL, NULL, NULL, NULL, '2', NULL, 1, 2, 'I.F.', 'Nombre Importador', 1, 0, 0, util.VN_CURDATE(), 0, 442, 0, 0, 0.00, NULL, NULL, util.VN_CURDATE(), NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, NULL, NULL, 0), (5, 2.0, util.VN_CURDATE(), '2000000000', '4300001104', 'n/fra T4444444 Tony Stark', NULL, 8.07, NULL, NULL, '0', NULL, 0.00, NULL, NULL, NULL, NULL, NULL, '2', NULL, 1, 2, 'I.F.', 'Nombre Importador', 1, 0, 0, util.VN_CURDATE(), 0, 442, 0, 0, 0.00, NULL, NULL, util.VN_CURDATE(), NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, NULL, NULL, 0), (6, 2.0, util.VN_CURDATE(), '4770000010', '4300001104', 'Inmovilizado pendiente : n/fra T4444444 Tony Stark', NULL, 0.81, 8.07, 'T', '4444444', 10.00, NULL, NULL, NULL, NULL, NULL, '', '2', '', 1, 1, '06089160W', 'IRON MAN', 1, 1, 0, util.VN_CURDATE(), 0, 442, 0, 0, 0.00, NULL, NULL, util.VN_CURDATE(), NULL, 1, 1, 1, 1, NULL, NULL, NULL, NULL, NULL, 0, NULL, NULL, 0); + +INSERT INTO `vn`.`invoiceCorrectionType` (`id`, `description`) + VALUES + (1, 'Error en el cálculo del IVA'), + (2, 'Error en el detalle de las ventas'), + (3, 'Error en los datos del cliente'); \ No newline at end of file diff --git a/modules/ticket/back/methods/sale/clone.js b/modules/ticket/back/methods/sale/clone.js index 7ce7675da..84f0e02f8 100644 --- a/modules/ticket/back/methods/sale/clone.js +++ b/modules/ticket/back/methods/sale/clone.js @@ -44,7 +44,7 @@ module.exports = Self => { } for (const sale of sales) { - const refundTicketId = await getTicketRefundId(group, sale.ticketFk, refundTickets, mappedTickets); + const refundTicketId = mappedTickets.get(sale.ticketFk); const createdSale = await models.Sale.create({ ticketFk: refundTicketId, @@ -62,14 +62,14 @@ module.exports = Self => { await models.SaleComponent.create(components, myOptions); } - if (servicesIds && servicesIds.length > 0) { + if (servicesIds && servicesIds.length) { const servicesFilter = { where: {id: {inq: servicesIds}} }; const services = await models.TicketService.find(servicesFilter, myOptions); for (const service of services) { - const refundTicketId = await getTicketRefundId(group, service.ticketFk, refundTickets, mappedTickets); + const refundTicketId = mappedTickets.get(service.ticketFk); await models.TicketService.create({ description: service.description, @@ -113,11 +113,4 @@ module.exports = Self => { refundTickets.push(refundTicket); } - - async function getTicketRefundId(group, ticketId, refundTickets, mappedTickets) { - if (group) { - const [firstRefundTicket] = refundTickets; - return firstRefundTicket.id; - } else return mappedTickets.get(ticketId); - } }; From db8dc8487b7ba76a507259a024c13a0f802b7b1f Mon Sep 17 00:00:00 2001 From: jorgep Date: Mon, 25 Sep 2023 15:28:08 +0200 Subject: [PATCH 145/427] ref #6246 replace name --- modules/ticket/back/methods/ticket/specs/merge.spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/ticket/back/methods/ticket/specs/merge.spec.js b/modules/ticket/back/methods/ticket/specs/merge.spec.js index 560dac7ee..646b9739f 100644 --- a/modules/ticket/back/methods/ticket/specs/merge.spec.js +++ b/modules/ticket/back/methods/ticket/specs/merge.spec.js @@ -34,7 +34,7 @@ describe('ticket merge()', () => { return value; }; - it('should merge a ticket', async() => { + it('should merge two tickets', async() => { const tx = await models.Ticket.beginTransaction({}); try { From e36f98195c413f65c67486ae4df02ca06354cccc Mon Sep 17 00:00:00 2001 From: alexm Date: Tue, 26 Sep 2023 08:15:19 +0200 Subject: [PATCH 146/427] refs #6033 feat: create user-photo component for worker and user descriptor --- front/salix/components/index.js | 1 + front/salix/components/user-photo/index.html | 15 +++++++++ front/salix/components/user-photo/index.js | 31 +++++++++++++++++++ .../salix/components/user-photo/locale/es.yml | 6 ++++ modules/account/front/descriptor/index.html | 3 ++ modules/worker/front/descriptor/index.html | 16 +--------- modules/worker/front/descriptor/index.js | 11 ------- 7 files changed, 57 insertions(+), 26 deletions(-) create mode 100644 front/salix/components/user-photo/index.html create mode 100644 front/salix/components/user-photo/index.js create mode 100644 front/salix/components/user-photo/locale/es.yml diff --git a/front/salix/components/index.js b/front/salix/components/index.js index 555a18450..f632904c4 100644 --- a/front/salix/components/index.js +++ b/front/salix/components/index.js @@ -18,6 +18,7 @@ import './section'; import './summary'; import './topbar/topbar'; import './user-popover'; +import './user-photo'; import './upload-photo'; import './bank-entity'; import './log'; diff --git a/front/salix/components/user-photo/index.html b/front/salix/components/user-photo/index.html new file mode 100644 index 000000000..2d7bbcb82 --- /dev/null +++ b/front/salix/components/user-photo/index.html @@ -0,0 +1,15 @@ +

+ + + +
+ + + diff --git a/front/salix/components/user-photo/index.js b/front/salix/components/user-photo/index.js new file mode 100644 index 000000000..23190c1b6 --- /dev/null +++ b/front/salix/components/user-photo/index.js @@ -0,0 +1,31 @@ +import ngModule from '../../module'; + +export default class Controller { + constructor($element, $, $rootScope) { + Object.assign(this, { + $element, + $, + $rootScope, + }); + } + + onUploadResponse() { + const timestamp = Date.vnNew().getTime(); + const src = this.$rootScope.imagePath('user', '520x520', this.userId); + const zoomSrc = this.$rootScope.imagePath('user', '1600x1600', this.userId); + const newSrc = `${src}&t=${timestamp}`; + const newZoomSrc = `${zoomSrc}&t=${timestamp}`; + + this.$.photo.setAttribute('src', newSrc); + this.$.photo.setAttribute('zoom-image', newZoomSrc); + } +} +Controller.$inject = ['$element', '$scope', '$rootScope']; + +ngModule.vnComponent('vnUserPhoto', { + template: require('./index.html'), + controller: Controller, + bindings: { + userId: '@?', + } +}); diff --git a/front/salix/components/user-photo/locale/es.yml b/front/salix/components/user-photo/locale/es.yml new file mode 100644 index 000000000..7518a98bc --- /dev/null +++ b/front/salix/components/user-photo/locale/es.yml @@ -0,0 +1,6 @@ +My account: Mi cuenta +Local warehouse: Almacén local +Local bank: Banco local +Local company: Empresa local +User warehouse: Almacén del usuario +User company: Empresa del usuario \ No newline at end of file diff --git a/modules/account/front/descriptor/index.html b/modules/account/front/descriptor/index.html index 381b2991c..94497aaa9 100644 --- a/modules/account/front/descriptor/index.html +++ b/modules/account/front/descriptor/index.html @@ -2,6 +2,9 @@ module="account" description="$ctrl.user.nickname" summary="$ctrl.$.summary"> + + + -
- - - -
+
@@ -76,8 +67,3 @@ - - - diff --git a/modules/worker/front/descriptor/index.js b/modules/worker/front/descriptor/index.js index a53528ef2..0214f8500 100644 --- a/modules/worker/front/descriptor/index.js +++ b/modules/worker/front/descriptor/index.js @@ -71,17 +71,6 @@ class Controller extends Descriptor { return this.getData(`Workers/${this.id}`, {filter}) .then(res => this.entity = res.data); } - - onUploadResponse() { - const timestamp = Date.vnNew().getTime(); - const src = this.$rootScope.imagePath('user', '520x520', this.worker.id); - const zoomSrc = this.$rootScope.imagePath('user', '1600x1600', this.worker.id); - const newSrc = `${src}&t=${timestamp}`; - const newZoomSrc = `${zoomSrc}&t=${timestamp}`; - - this.$.photo.setAttribute('src', newSrc); - this.$.photo.setAttribute('zoom-image', newZoomSrc); - } } Controller.$inject = ['$element', '$scope', '$rootScope']; From 3ffc4e39f1d214e5f94f3fa7c4cf0fe15bdb0c7e Mon Sep 17 00:00:00 2001 From: alexm Date: Tue, 26 Sep 2023 08:19:17 +0200 Subject: [PATCH 147/427] refs #6033 add changeLog --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 79688cb56..373a6ec71 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,9 +9,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [2340.01] - 2023-10-05 ### Added +- (Usuarios -> Foto) Se muestra la foto del trabajador + ### Changed ### Fixed +- (Usuarios -> Historial) Abre el descriptor del usuario correctamente ## [2338.01] - 2023-09-21 From 50543963c104dc1adf421f4c25f4dbf3480254aa Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 26 Sep 2023 12:42:45 +0200 Subject: [PATCH 148/427] ref #5914 refactor createTicketRefund --- modules/ticket/back/methods/sale/clone.js | 57 +++++++++++------------ 1 file changed, 26 insertions(+), 31 deletions(-) diff --git a/modules/ticket/back/methods/sale/clone.js b/modules/ticket/back/methods/sale/clone.js index 84f0e02f8..dd1b108b2 100644 --- a/modules/ticket/back/methods/sale/clone.js +++ b/modules/ticket/back/methods/sale/clone.js @@ -3,6 +3,7 @@ module.exports = Self => { const models = Self.app.models; const myOptions = {}; let tx; + const refundTickets = []; if (typeof options == 'object') Object.assign(myOptions, options); @@ -25,22 +26,19 @@ module.exports = Self => { const sales = await models.Sale.find(salesFilter, myOptions); let ticketsIds = [...new Set(sales.map(sale => sale.ticketFk))]; - const refundTickets = []; const mappedTickets = new Map(); - const now = Date.vnNew(); if (group) ticketsIds = [ticketsIds[0]]; - for (let ticketId in ticketsIds) { - await createTicketRefund( + for (let ticketId of ticketsIds) { + const ticketRefund = await createTicketRefund( ctx, - ticketsIds[ticketId], + ticketId, withWarehouse, - refundTickets, - now, myOptions ); - mappedTickets.set(ticketsIds[ticketId], refundTickets[ticketId].id); + refundTickets.push(ticketRefund); + mappedTickets.set(ticketId, ticketRefund.id); } for (const sale of sales) { @@ -89,28 +87,25 @@ module.exports = Self => { if (tx) await tx.rollback(); throw e; } + + async function createTicketRefund( + ctx, + ticketId, + withWarehouse, + myOptions + ) { + const models = Self.app.models; + const now = Date.vnNew(); + + const ticket = await models.Ticket.findById(ticketId, null, myOptions); + ctx.args.clientId = ticket.clientFk; + ctx.args.shipped = now; + ctx.args.landed = now; + ctx.args.warehouseId = withWarehouse ? ticket.warehouseFk : null; + ctx.args.companyId = ticket.companyFk; + ctx.args.addressId = ticket.addressFk; + + return models.Ticket.new(ctx, myOptions); + } }; - - async function createTicketRefund( - ctx, - ticketId, - withWarehouse, - refundTickets, - now, - myOptions - ) { - const models = Self.app.models; - - const ticket = await models.Ticket.findById(ticketId, myOptions); - ctx.args.clientId = ticket.clientFk; - ctx.args.shipped = now; - ctx.args.landed = now; - ctx.args.warehouseId = withWarehouse ? ticket.warehouseFk : null; - ctx.args.companyId = ticket.companyFk; - ctx.args.addressId = ticket.addressFk; - - const refundTicket = await models.Ticket.new(ctx, myOptions); - - refundTickets.push(refundTicket); - } }; From 2ea2943ecadc3f660b8c389cb7ac47e4db73983d Mon Sep 17 00:00:00 2001 From: sergiodt Date: Tue, 26 Sep 2023 13:12:18 +0200 Subject: [PATCH 149/427] refs #5134 feat: models --- modules/shelving/back/models/shelving.json | 6 ++-- .../ticket/back/models/expeditionPallet.json | 10 ++++-- .../ticket/back/models/expeditionScan.json | 35 +++++++++++++++++-- 3 files changed, 44 insertions(+), 7 deletions(-) diff --git a/modules/shelving/back/models/shelving.json b/modules/shelving/back/models/shelving.json index 5459e29fd..bb2401666 100644 --- a/modules/shelving/back/models/shelving.json +++ b/modules/shelving/back/models/shelving.json @@ -9,11 +9,11 @@ "properties": { "id": { "type": "number", - "description": "Identifier" + "description": "Identifier", + "id": true }, "code": { - "type": "string", - "id": true + "type": "string" }, "parkingFk": { "type": "number" diff --git a/modules/ticket/back/models/expeditionPallet.json b/modules/ticket/back/models/expeditionPallet.json index 2c56a65e0..c5a38df75 100644 --- a/modules/ticket/back/models/expeditionPallet.json +++ b/modules/ticket/back/models/expeditionPallet.json @@ -4,6 +4,13 @@ "mysql": { "table": "expeditionPallet" } + }, + "properties": { + "id": { + "type": "number", + "id": true, + "description": "Identifier" + } }, "acls": [{ "accessType": "WRITE", @@ -11,6 +18,5 @@ "principalId": "production", "permission": "ALLOW" }] - - } +} diff --git a/modules/ticket/back/models/expeditionScan.json b/modules/ticket/back/models/expeditionScan.json index f43ad0539..1db2c1238 100644 --- a/modules/ticket/back/models/expeditionScan.json +++ b/modules/ticket/back/models/expeditionScan.json @@ -5,12 +5,43 @@ "table": "expeditionScan" } }, + "properties": { + "id": { + "type": "number", + "description": "Identifier" + }, + "expeditionFk": { + "type": "number", + "description": "Identifier", + "id": true + }, + "palletFk": { + "type": "number", + "description": "Identifier", + "id": true + }, + "scanned": { + "type": "date", + "default": "$now" + } + }, + "relations": { + "expedition": { + "type": "belongsTo", + "model": "Expedition", + "foreignKey": "expeditionFk" + }, + "pallet": { + "type": "belongsTo", + "model": "expeditionPallet", + "foreignKey": "palletFk" + } + }, "acls": [{ "accessType": "WRITE", "principalType": "ROLE", "principalId": "production", "permission": "ALLOW" }] - - } +} From a7c0949f0ea80cf1606547cb91d4d535178ed92f Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 27 Sep 2023 08:57:31 +0200 Subject: [PATCH 150/427] ref #6065 replace then by async/await --- modules/worker/front/card/index.js | 11 +++++------ modules/worker/front/time-control/index.js | 11 +++++------ 2 files changed, 10 insertions(+), 12 deletions(-) diff --git a/modules/worker/front/card/index.js b/modules/worker/front/card/index.js index b8b533c5d..dcba2efcd 100644 --- a/modules/worker/front/card/index.js +++ b/modules/worker/front/card/index.js @@ -2,7 +2,7 @@ import ngModule from '../module'; import ModuleCard from 'salix/components/module-card'; class Controller extends ModuleCard { - reload() { + async reload() { const filter = { include: [ { @@ -31,13 +31,12 @@ class Controller extends ModuleCard { } ] }; - - return Promise.all([ - this.$http.get(`Workers/${this.$params.id}`, {filter}) - .then(res => this.worker = res.data), + const promises = await Promise.all([ + this.$http.get(`Workers/${this.$params.id}`, {filter}), this.$http.get(`Workers/${this.$params.id}/activeContract`) - .then(res => this.hasWorkCenter = res.data?.workCenterFk) ]); + this.worker = await promises[0].data; + this.worker.hasWorkCenter = await promises[1].data?.workCenterFk; } } diff --git a/modules/worker/front/time-control/index.js b/modules/worker/front/time-control/index.js index 38e6721d6..e21bfbfbb 100644 --- a/modules/worker/front/time-control/index.js +++ b/modules/worker/front/time-control/index.js @@ -132,7 +132,7 @@ class Controller extends Section { } } - fetchHours() { + async fetchHours() { const params = {workerFk: this.$params.id}; const filter = { where: {and: [ @@ -140,12 +140,11 @@ class Controller extends Section { {timed: {lte: this.ended}} ]} }; - this.$.model.applyFilter(filter, params).then(() => { - if (!this.card.hasWorkCenter) return; + await this.$.model.applyFilter(filter, params); + if (!this.worker.hasWorkCenter) return; - this.getWorkedHours(this.started, this.ended); - this.getAbsences(); - }); + await this.getWorkedHours(this.started, this.ended); + await this.getAbsences(); } hasEvents(day) { From ac3e9c811d124a8ce496e96eeb11960d5bb1ccff Mon Sep 17 00:00:00 2001 From: sergiodt Date: Wed, 27 Sep 2023 14:01:17 +0200 Subject: [PATCH 151/427] refs #5890 feat: itemShelvingSaleAsignado --- db/changes/234001/01-itemShelvingSale.sql | 299 ++++++++++++++++++ loopback/locale/en.json | 3 +- loopback/locale/es.json | 7 +- .../itemShelvingSaleByCollection.js | 22 ++ .../itemShelvingSaleSetQuantity.js | 31 ++ .../item/back/models/item-shelving-sale.js | 2 + 6 files changed, 360 insertions(+), 4 deletions(-) create mode 100644 db/changes/234001/01-itemShelvingSale.sql create mode 100644 modules/item/back/methods/item-shelving-sale/itemShelvingSaleByCollection.js create mode 100644 modules/item/back/methods/item-shelving-sale/itemShelvingSaleSetQuantity.js diff --git a/db/changes/234001/01-itemShelvingSale.sql b/db/changes/234001/01-itemShelvingSale.sql new file mode 100644 index 000000000..af68d465a --- /dev/null +++ b/db/changes/234001/01-itemShelvingSale.sql @@ -0,0 +1,299 @@ + +ALTER TABLE vn.itemShelvingSale ADD isPicked TINYINT(1) DEFAULT FALSE NOT NULL; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_addByCollection`( + vCollectionFk INT(11) +) +BEGIN +/** + * Guarda la ubicación para el contenido de una colección + * + * @param vCollectionFk Identificador de collection + */ + CREATE OR REPLACE TEMPORARY TABLE tmp.sale + (INDEX(saleFk)) + ENGINE = MEMORY + SELECT s.id saleFk, NULL userFk + FROM ticketCollection tc + JOIN sale s ON s.ticketFk = tc.ticketFk + LEFT JOIN ( + SELECT DISTINCT saleFk + FROM saleTracking st + JOIN state s ON s.id = st.stateFk + WHERE st.isChecked + AND s.semaphore = 1)st ON st.saleFk = s.id + WHERE tc.collectionFk = vCollectionFk + AND st.saleFk IS NULL + AND NOT s.isPicked; + + CALL itemShelvingSale_addNew(); +END$$ +DELIMITER ; + + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_setQuantity`( + vItemShelvingSaleFk INT(10), + vQuantity DECIMAL(10,0), + vIsItemShelvingSaleEmpty BOOLEAN +) +BEGIN +/** + * Gestiona la reserva de un itemShelvingFk, actualizando isPicked y quantity + * en vn.itemShelvingSale y vn.sale.isPicked en caso necesario. + * Si la reserva de la ubicación es fallida, se regulariza la situación + * + * @param vItemShelvingSaleFk Id itemShelvingSaleFK + * @param vQuantity Cantidad real que se ha cogido de la ubicación + * @param vIsItemShelvingSaleEmpty determina si ka ubicación itemShelvingSale se ha + * quedado vacio tras el movimiento + */ + DECLARE vSaleFk INT; + DECLARE vCursorSaleFk INT; + DECLARE vItemShelvingFk INT; + DECLARE vReservedQuantity INT; + DECLARE vRemainingQuantity INT; + DECLARE vItemFk INT; + DECLARE vUserFk INT; + DECLARE vDone BOOLEAN DEFAULT FALSE; + DECLARE vSales CURSOR FOR + SELECT iss.saleFk, iss.userFk + FROM itemShelvingSale iss + JOIN sale s ON s.id = iss.saleFk + WHERE iss.id = vItemShelvingSaleFk + AND s.itemFk = vItemFk + AND NOT iss.isPicked; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + IF (SELECT isPicked FROM itemShelvingSale WHERE id = vItemShelvingSaleFk) THEN + CALL util.throw('Booking completed'); + END IF; + + SELECT s.itemFk, iss.saleFk, iss.itemShelvingFk + INTO vItemFk, vSaleFk, vItemShelvingFk + FROM itemShelvingSale iss + JOIN sale s ON s.id = iss.saleFk + WHERE iss.id = vItemShelvingSaleFk + AND NOT iss.isPicked; + + UPDATE itemShelvingSale + SET isPicked = TRUE, + quantity = vQuantity + WHERE id = vItemShelvingSaleFk; + + UPDATE itemShelving + SET visible = IF(vIsItemShelvingSaleEmpty, 0, GREATEST(0,visible - vQuantity)) + WHERE id = vItemShelvingFk; + + /*Se podría preguntar por la cantidad correcta de la ubicació o insertar en una tabla + para que lo tenga en cuenta la gente que está haciendo inventario*/ + + IF vIsItemShelvingSaleEmpty THEN + OPEN vSales; +l: LOOP + SET vDone = FALSE; + FETCH vSales INTO vCursorSaleFk, vUserFk; + IF vDone THEN + LEAVE l; + END IF; + + CREATE OR REPLACE TEMPORARY TABLE tmp.sale + (INDEX(saleFk, userFk)) + ENGINE = MEMORY + SELECT vCursorSaleFk, vUserFk; + + CALL itemShelvingSale_addNewWhitUser(); + DROP TEMPORARY TABLE tmp.sale; + + END LOOP; + CLOSE vSales; + + DELETE iss + FROM itemShelvingSale iss + JOIN sale s ON s.id = iss.saleFk + WHERE iss.id = vItemShelvingSaleFk + AND s.itemFk = vItemFk + AND NOT iss.isPicked; + END IF; + + SELECT SUM(quantity) INTO vRemainingQuantity + FROM itemShelvingSale + WHERE saleFk = vSaleFk + AND NOT isPicked; + + IF vRemainingQuantity THEN + CALL itemShelvingSale_addBySale (vSaleFk, vRemainingQuantity, NULL); + + SELECT SUM(quantity) INTO vRemainingQuantity + FROM itemShelvingSale + WHERE saleFk = vSaleFk + AND NOT isPicked; + + IF NOT vRemainingQuantity <=> 0 THEN + SELECT SUM(iss.quantity) + INTO vReservedQuantity + FROM itemShelvingSale iss + WHERE iss.saleFk = vSaleFk; + + CALL saleTracking_new( + vSaleFk, + TRUE, + vReservedQuantity, + `account`.`myUser_getId`(), + NULL, + 'PREPARED', + TRUE); + + UPDATE sale s + SET s.quantity = vReservedQuantity + WHERE s.id = vSaleFk ; + END IF; + END IF; +END$$ +DELIMITER ; + + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_addNew`() +BEGIN +/** + * Guarda la ubicacion para un conjunto de sales del mismo wareHouse + * + * @table tmp.sale(saleFk, userFk) + */ + DECLARE vCalcFk INT; + DECLARE vWarehouseFk INT; + DECLARE vCurrentYear INT DEFAULT YEAR(util.VN_NOW()); + DECLARE vLastPickingOrder INT; + + SELECT t.warehouseFk, MAX(p.pickingOrder) + INTO vWarehouseFk, vLastPickingOrder + FROM ticket t + JOIN sale s ON s.ticketFk = t.id + JOIN tmp.sale ts ON ts.saleFk = s.id + LEFT JOIN itemShelvingSale iss ON iss.saleFk = ts.saleFk + LEFT JOIN itemShelving ish ON ish.id = iss.itemShelvingFk + LEFT JOIN shelving sh ON sh.code = ish.shelvingFk + LEFT JOIN parking p ON p.id = sh.parkingFk + WHERE t.warehouseFk IS NOT NULL; + + IF vWarehouseFk IS NULL THEN + CALL util.throw('Warehouse not set'); + END IF; + + CALL cache.visible_refresh(vCalcFk, FALSE, vWarehouseFk); + + SET @outstanding = 0; + SET @oldsaleFk = 0; + + CREATE OR REPLACE TEMPORARY TABLE tSalePlacementQuantity + (INDEX(saleFk)) + ENGINE = MEMORY + SELECT saleFk, userFk, quantityToReserve, itemShelvingFk + FROM( SELECT saleFk, + sub.userFk, + itemShelvingFk , + IF(saleFk <> @oldsaleFk, @outstanding := quantity, @outstanding), + @qtr := LEAST(@outstanding, available) quantityToReserve, + @outStanding := @outStanding - @qtr, + @oldsaleFk := saleFk + FROM( + SELECT ts.saleFk, + ts.userFk, + s.quantity, + ish.id itemShelvingFk, + ish.visible - IFNULL(ishr.reservedQuantity, 0) available + FROM tmp.sale ts + JOIN sale s ON s.id = ts.saleFk + JOIN itemShelving ish ON ish.itemFk = s.itemFk + LEFT JOIN ( + SELECT itemShelvingFk, SUM(quantity) reservedQuantity + FROM itemShelvingSale + WHERE NOT isPicked + GROUP BY itemShelvingFk) ishr ON ishr.itemShelvingFk = ish.id + JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN parking p ON p.id = sh.parkingFk + JOIN sector sc ON sc.id = p.sectorFk + JOIN warehouse w ON w.id = sc.warehouseFk + JOIN productionConfig pc + WHERE w.id = vWarehouseFk + AND NOT sc.isHideForPickers + ORDER BY + s.id, + p.pickingOrder >= vLastPickingOrder, + sh.priority DESC, + ish.visible >= s.quantity DESC, + s.quantity MOD ish.grouping = 0 DESC, + ish.grouping DESC, + IF(pc.orderMode = 'Location', p.pickingOrder, ish.created) + LIMIT 100000000000000000 + )sub + )sub2 + WHERE quantityToReserve > 0 + ; + + INSERT INTO itemShelvingSale( + itemShelvingFk, + saleFk, + quantity, + userFk) + SELECT itemShelvingFk, + saleFk, + quantityToReserve, + IFNULL(userFk, getUser()) + FROM tSalePlacementQuantity spl; + + DROP TEMPORARY TABLE tmp.sale; +END$$ +DELIMITER ; + + + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_addBySale`( + vSelf INT , + vQuantity INT, + vUserFk INT +) +BEGIN +/** + * Reserva la ubicación para una saleFk + * + * @param vSelf Identificador de la venta + * @param vQuantity Cantidad a reservar + * @param vUserFk Id de usuario que realiza la reserva + */ + CREATE OR REPLACE TEMPORARY TABLE tmp.sale + ENGINE = MEMORY + SELECT vSelf saleFk, vUserFk userFk; + + CALL itemShelvingSale_addNew(); +END$$ +DELIMITER ; + + + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`itemShelvingSale_AFTER_INSERT` + AFTER INSERT ON `itemShelvingSale` + FOR EACH ROW +BEGIN + + UPDATE vn.sale + SET isPicked = TRUE + WHERE id = NEW.saleFk; + +END$$ +DELIMITER ; + +ALTER TABLE vn.itemShelvingSale DROP COLUMN IF EXISTS isPicked; + +ALTER TABLE vn.itemShelvingSale + ADD isPicked TINYINT(1) DEFAULT FALSE NOT NULL; + +ALTER TABLE vn.productionConfig DROP COLUMN IF EXISTS orderMode; + +ALTER TABLE vn.productionConfig + ADD orderMode ENUM('Location', 'Age') NOT NULL DEFAULT 'Location'; \ No newline at end of file diff --git a/loopback/locale/en.json b/loopback/locale/en.json index fb4e72bd6..7e194451f 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -187,5 +187,6 @@ "This ticket is not editable.": "This ticket is not editable.", "The ticket doesn't exist.": "The ticket doesn't exist.", "The sales do not exists": "The sales do not exists", - "Ticket without Route": "Ticket without route" + "Ticket without Route": "Ticket without route", + "Booking completed": "Booking completed" } diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 756ce301a..034f267d0 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -314,8 +314,9 @@ "This ticket is locked.": "Este ticket está bloqueado.", "This ticket is not editable.": "Este ticket no es editable.", "The ticket doesn't exist.": "No existe el ticket.", - "Social name should be uppercase": "La razón social debe ir en mayúscula", + "Social name should be uppercase": "La razón social debe ir en mayúscula", "Street should be uppercase": "La dirección fiscal debe ir en mayúscula", "The response is not a PDF": "La respuesta no es un PDF", - "Ticket without Route": "Ticket sin ruta" -} + "Ticket without Route": "Ticket sin ruta", + "Booking completed": "Reserva completada" +} \ No newline at end of file diff --git a/modules/item/back/methods/item-shelving-sale/itemShelvingSaleByCollection.js b/modules/item/back/methods/item-shelving-sale/itemShelvingSaleByCollection.js new file mode 100644 index 000000000..2eb61a875 --- /dev/null +++ b/modules/item/back/methods/item-shelving-sale/itemShelvingSaleByCollection.js @@ -0,0 +1,22 @@ +module.exports = Self => { + Self.remoteMethod('itemShelvingSaleByCollection', { + description: 'Insert sales of the collection in itemShelvingSale', + accessType: 'WRITE', + accepts: [ + { + arg: 'id', + type: 'Number', + description: 'The collection id', + http: {source: 'path'} + } + ], + http: { + path: `/:id/itemShelvingSaleByCollection`, + verb: 'POST' + } + }); + + Self.itemShelvingSaleByCollection = async id => { + await Self.rawSql(`CALL vn.itemShelvingSale_addByCollection(?)`, [id]); + }; +}; diff --git a/modules/item/back/methods/item-shelving-sale/itemShelvingSaleSetQuantity.js b/modules/item/back/methods/item-shelving-sale/itemShelvingSaleSetQuantity.js new file mode 100644 index 000000000..bb2c4db0a --- /dev/null +++ b/modules/item/back/methods/item-shelving-sale/itemShelvingSaleSetQuantity.js @@ -0,0 +1,31 @@ +module.exports = Self => { + Self.remoteMethod('itemShelvingSaleSetQuantity', { + description: 'Set quanitity of a sale in itemShelvingSale', + accessType: 'WRITE', + accepts: [ + { + arg: 'id', + type: 'Number', + description: 'The sale id', + }, + { + arg: 'quantity', + type: 'Number', + description: 'The quantity to set', + }, + { + arg: 'isItemShelvingSaleEmpty', + type: 'Boolean', + description: 'True if the shelvingFk is empty ', + } + ], + http: { + path: `/itemShelvingSaleSetQuantity`, + verb: 'POST' + } + }); + + Self.itemShelvingSaleSetQuantity = async(id, quantity, isItemShelvingSaleEmpty) => { + await Self.rawSql(`CALL vn.itemShelvingSale_setQuantity(?, ?, ? )`, [id, quantity, isItemShelvingSaleEmpty]); + }; +}; diff --git a/modules/item/back/models/item-shelving-sale.js b/modules/item/back/models/item-shelving-sale.js index b89be9f00..e2d27564a 100644 --- a/modules/item/back/models/item-shelving-sale.js +++ b/modules/item/back/models/item-shelving-sale.js @@ -1,3 +1,5 @@ module.exports = Self => { require('../methods/item-shelving-sale/filter')(Self); + require('../methods/item-shelving-sale/itemShelvingSaleByCollection')(Self); + require('../methods/item-shelving-sale/itemShelvingSaleSetQuantity')(Self); }; From 1307d4727c9ee4284278941395556701961d1067 Mon Sep 17 00:00:00 2001 From: alexm Date: Wed, 27 Sep 2023 15:08:36 +0200 Subject: [PATCH 152/427] refs #6254 feat(collection): add getTickets --- back/methods/collection/getTickets.js | 179 ++++++++++++++++++ .../collection/spec/getTickets.spec.js | 11 ++ back/models/collection.js | 1 + .../234001/00-collectionGetTicketsACL.sql | 3 + loopback/locale/en.json | 3 +- loopback/locale/es.json | 8 +- 6 files changed, 201 insertions(+), 4 deletions(-) create mode 100644 back/methods/collection/getTickets.js create mode 100644 back/methods/collection/spec/getTickets.spec.js create mode 100644 db/changes/234001/00-collectionGetTicketsACL.sql diff --git a/back/methods/collection/getTickets.js b/back/methods/collection/getTickets.js new file mode 100644 index 000000000..196ff0ce6 --- /dev/null +++ b/back/methods/collection/getTickets.js @@ -0,0 +1,179 @@ + +module.exports = Self => { + Self.remoteMethodCtx('getTickets', { + description: 'Make a new collection of tickets', + accessType: 'WRITE', + accepts: [{ + arg: 'paramId', + type: 'number', + description: 'The collection or ticket id', + required: true + }, { + arg: 'print', + type: 'boolean', + description: 'True if you want to print' + }], + returns: { + type: ['object'], + root: true + }, + http: { + path: `/getTickets`, + verb: 'POST' + } + }); + + Self.getTickets = async(ctx, paramId, print, options) => { + const userId = ctx.req.accessToken.userId; + const origin = ctx.req.headers.origin; + const $t = ctx.req.__; // $translate + const myOptions = {}; + + let tx; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + myOptions.userId = userId; + + const promises = []; + try { + const [tickets] = await Self.rawSql(`CALL vn.collection_getTickets(?)`, [paramId], myOptions); + const sales = await Self.rawSql(` + SELECT + s.ticketFk, + sgd.saleGroupFk, + s.id saleFk, + s.itemFk, + i.longName, + i.size, + IFNULL(sub2.semaphore,st.semaphore) semaphore, + ic.color, + ip.productor, + o.code origin, + s.concept, + b.packing, + b.grouping, + s.isAdded, + c.workerFk, + i.packingShelve, + sm.id hasMistake, + s.originalQuantity, + s.quantity saleQuantity, + IF(p2.code IS NOT NULL, s.quantity, iss.quantity) reservedQuantity, + sh.code, + IFNULL(p2.code, p.code) parkingCode, + IFNULL(p2.pickingOrder, p.pickingOrder) pickingOrder, + iss.id itemShelvingSaleFk + FROM ticketCollection tc + LEFT JOIN collection c ON c.id = tc.collectionFk + JOIN ticket t ON t.id = tc.ticketFk + JOIN sale s ON s.ticketFk = t.id + LEFT JOIN saleGroupDetail sgd ON sgd.saleFk = s.id + LEFT JOIN saleGroup sg ON sg.id = sgd.saleGroupFk + LEFT JOIN parking p2 ON p2.id = sg.parkingFk + LEFT JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND lb.warehouse_id = t.warehouseFk + LEFT JOIN buy b ON b.id = lb.buy_id + JOIN item i ON i.id = s.itemFk + LEFT JOIN itemShelvingSale iss ON iss.saleFk = s.id + LEFT JOIN itemShelving ish ON ish.id = iss.itemShelvingFk + LEFT JOIN shelving sh ON sh.code = ish.shelvingFk + LEFT JOIN parking p ON p.id = sh.parkingFk + LEFT JOIN ( + SELECT sub.saleFk, sub.isChecked, sub.stateFk, sub.originalQuantity, sub.semaphore + FROM ( + SELECT DISTINCT st.id, + st.saleFk, st.isChecked, st.stateFk, st.originalQuantity ,sta.semaphore + FROM ticketCollection tc + JOIN sale s ON s.ticketFk = tc.ticketFk + JOIN saleTracking st ON st.saleFk = s.id + JOIN state sta ON sta.id = st.stateFk + WHERE tc.collectionFk = ? + ORDER BY st.id DESC + LIMIT 10000000000000000000) sub + GROUP BY sub.saleFk, sub.stateFK + ) sub2 ON sub2.saleFk = s.id AND sub2.isChecked = 1 + LEFT JOIN state st ON st.id = sub2.stateFk + LEFT JOIN itemColor ic ON ic.itemFk = s.itemFk + LEFT JOIN itemProductor ip ON ip.itemFk = s.itemFk + LEFT JOIN origin o ON o.id = i.originFk + LEFT JOIN saleMistake sm ON sm.saleFk = s.id + WHERE tc.collectionFk = ? + GROUP BY s.id, p.code, p2.code + ORDER BY pickingOrder`, [paramId, paramId], myOptions); + + if (print) + await Self.rawSql(`CALL vn.collection_printSticker(?, ?)`, [paramId, null], myOptions); + + const collection = {collectionFk: paramId, tickets: []}; + if (tickets && tickets.length) { + for (let ticket of tickets) { + const ticketId = ticket.ticketFk; + + // SEND ROCKET + if (ticket.observaciones != '') { + for (observation of ticket.observaciones.split(' ')) { + if (['#', '@'].includes(observation.charAt(0))) { + promises.push(Self.app.models.Chat.send(ctx, observation, + $t('The ticket is in preparation', { + ticketId: ticketId, + ticketUrl: `${origin}/#!/ticket/${ticketId}/summary`, + salesPersonId: ticket.salesPersonFk + }))); + } + } + } + + // SET COLLECTION + if (sales && sales.length) { + // GET BARCODES + const barcodes = await Self.rawSql(` + SELECT s.id saleFk, b.code, c.id + FROM vn.sale s + LEFT JOIN vn.itemBarcode b ON b.itemFk = s.itemFk + LEFT JOIN vn.buy c ON c.itemFk = s.itemFk + LEFT JOIN vn.entry e ON e.id = c.entryFk + LEFT JOIN vn.travel tr ON tr.id = e.travelFk + WHERE s.ticketFk = ? AND tr.landed >= DATE_SUB(util.VN_CURDATE(), INTERVAL 1 YEAR)`, + [ticketId], myOptions); + + // BINDINGS + ticket.sales = sales.reduce((acc, sale) => { + if (sale.ticketFk == ticketId) { + sale.Barcodes = []; + if (barcodes && barcodes.length) { + sale.Barcodes = barcodes.reduce((bacc, barcode) => { + if (barcode.saleFk == sale.saleFk) { + for (let prop in barcode) { + if (['id', 'code'].includes(prop) && barcode[prop]) { + bacc.push(barcode[prop].toString()); + bacc.push('0' + barcode[prop]); + } + } + } + return bacc; + }, []); + } + acc.push(sale); + } + return acc; + }, []); + } + collection.tickets.push(ticket); + } + } + + if (tx) await tx.commit(); + await Promise.all(promises); + + return collection; + } catch (e) { + if (tx) await tx.rollback(); + throw e; + } + }; +}; diff --git a/back/methods/collection/spec/getTickets.spec.js b/back/methods/collection/spec/getTickets.spec.js new file mode 100644 index 000000000..eddbb21b1 --- /dev/null +++ b/back/methods/collection/spec/getTickets.spec.js @@ -0,0 +1,11 @@ +const models = require('vn-loopback/server/server').models; + +describe('collection getTickets()', () => { + it('should return a list of tickets from a collection', async() => { + let ctx = {req: {accessToken: {userId: 1107}}}; + let response = await models.Collection.getCollection(ctx); + + expect(response.length).toBeGreaterThan(0); + expect(response[0].collectionFk).toEqual(3); + }); +}); diff --git a/back/models/collection.js b/back/models/collection.js index a41742ee7..bfa906af6 100644 --- a/back/models/collection.js +++ b/back/models/collection.js @@ -4,4 +4,5 @@ module.exports = Self => { require('../methods/collection/getSectors')(Self); require('../methods/collection/setSaleQuantity')(Self); require('../methods/collection/previousLabel')(Self); + require('../methods/collection/getTickets')(Self); }; diff --git a/db/changes/234001/00-collectionGetTicketsACL.sql b/db/changes/234001/00-collectionGetTicketsACL.sql new file mode 100644 index 000000000..06b584386 --- /dev/null +++ b/db/changes/234001/00-collectionGetTicketsACL.sql @@ -0,0 +1,3 @@ +INSERT INTO `salix`.`ACL`(model, property, accessType, permission, principalType, principalId) + VALUES + ('Collection', 'getTickets', 'WRITE', 'ALLOW', 'ROLE', 'employee'); diff --git a/loopback/locale/en.json b/loopback/locale/en.json index fb4e72bd6..3ce4761a1 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -187,5 +187,6 @@ "This ticket is not editable.": "This ticket is not editable.", "The ticket doesn't exist.": "The ticket doesn't exist.", "The sales do not exists": "The sales do not exists", - "Ticket without Route": "Ticket without route" + "Ticket without Route": "Ticket without route", + "The ticket is in preparation": "The ticket [{{ticketId}}]({{{ticketUrl}}}) of the sales person {{salesPersonId}} is in preparation" } diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 756ce301a..71a01f91a 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -314,8 +314,10 @@ "This ticket is locked.": "Este ticket está bloqueado.", "This ticket is not editable.": "Este ticket no es editable.", "The ticket doesn't exist.": "No existe el ticket.", - "Social name should be uppercase": "La razón social debe ir en mayúscula", + "Social name should be uppercase": "La razón social debe ir en mayúscula", "Street should be uppercase": "La dirección fiscal debe ir en mayúscula", "The response is not a PDF": "La respuesta no es un PDF", - "Ticket without Route": "Ticket sin ruta" -} + "Ticket without Route": "Ticket sin ruta", + "The ticket is in preparation": "El ticket [{{ticketId}}]({{{ticketUrl}}}) del comercial {{salesPersonId}} està en preparación", + "Invalid collection or ticket": "Invalid collection or ticket" +} \ No newline at end of file From a86469ccd28a971139f9ae52c634b5b7d3f2a752 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Thu, 28 Sep 2023 07:42:44 +0200 Subject: [PATCH 153/427] refs #5134 fix: format --- db/changes/233401/00-models.sql | 29 ------------------- db/changes/{233401 => 234001}/.gitkeep | 0 db/changes/234001/00-models.sql | 11 +++++++ modules/shelving/back/models/shelving.json | 2 +- modules/ticket/back/model-config.json | 2 +- .../back/models/expeditionMistakeType.json | 7 ++--- modules/worker/back/models/mistakeType.json | 2 +- modules/worker/back/models/workerMistake.json | 8 ++--- 8 files changed, 21 insertions(+), 40 deletions(-) delete mode 100644 db/changes/233401/00-models.sql rename db/changes/{233401 => 234001}/.gitkeep (100%) create mode 100644 db/changes/234001/00-models.sql diff --git a/db/changes/233401/00-models.sql b/db/changes/233401/00-models.sql deleted file mode 100644 index c06965b3f..000000000 --- a/db/changes/233401/00-models.sql +++ /dev/null @@ -1,29 +0,0 @@ -INSERT INTO `salix`.`ACL` ( model, property, accessType, permission, principalType, principalId) - VALUES('ExpeditionMistakeType', '*', 'READ', 'ALLOW', 'ROLE', 'employee'); - -INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) - VALUES('WorkerMistakeType', '*', 'READ', 'ALLOW', 'ROLE', 'employee'); - -INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId) - VALUES ('ExpeditionMistake','*','WRITE','ALLOW','ROLE','employee'); - -INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) - VALUES('WorkerMistake', '*', 'WRITE', 'ALLOW', 'ROLE', 'coolerBoss'); - -INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) - VALUES('WorkerMistake', '*', 'WRITE', 'ALLOW', 'ROLE', 'coolerBoss'); - -INSERT INTO `salix`.`ACL` ( model, property, accessType, permission, principalType, principalId) - VALUES('MistakesTypes', '*', 'WRITE', 'ALLOW', 'ROLE', 'coolerBoss'); - -INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId) - VALUES ('MistakeType','*','READ','ALLOW','ROLE','employee'); - -INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) - VALUES('MachineWorker', '*', 'READ', 'ALLOW', 'ROLE', 'coolerAssist'); - -INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId) - VALUES ('Printer','*','READ','ALLOW','ROLE','employee'); - -INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) - VALUES( 'SaleMistake', '*', 'WRITE', 'ALLOW', 'ROLE', 'production'); diff --git a/db/changes/233401/.gitkeep b/db/changes/234001/.gitkeep similarity index 100% rename from db/changes/233401/.gitkeep rename to db/changes/234001/.gitkeep diff --git a/db/changes/234001/00-models.sql b/db/changes/234001/00-models.sql new file mode 100644 index 000000000..51ffa1554 --- /dev/null +++ b/db/changes/234001/00-models.sql @@ -0,0 +1,11 @@ +INSERT INTO `salix`.`ACL` ( model, property, accessType, permission, principalType, principalId) + VALUES + ('ExpeditionMistakeType', '*', 'READ', 'ALLOW', 'ROLE', 'employee'); + ('WorkerMistakeType', '*', 'READ', 'ALLOW', 'ROLE', 'employee'); + ('ExpeditionMistake','*','WRITE','ALLOW','ROLE','employee'); + ('WorkerMistake', '*', 'WRITE', 'ALLOW', 'ROLE', 'coolerBoss'); + ('MistakesTypes', '*', 'WRITE', 'ALLOW', 'ROLE', 'coolerBoss'); + ('MistakeType','*','READ','ALLOW','ROLE','employee'); + ('MachineWorker', '*', 'READ', 'ALLOW', 'ROLE', 'coolerAssist'); + ('Printer','*','READ','ALLOW','ROLE','employee'); + ('SaleMistake', '*', 'WRITE', 'ALLOW', 'ROLE', 'production'); diff --git a/modules/shelving/back/models/shelving.json b/modules/shelving/back/models/shelving.json index bb2401666..8bfcac9a1 100644 --- a/modules/shelving/back/models/shelving.json +++ b/modules/shelving/back/models/shelving.json @@ -10,7 +10,7 @@ "id": { "type": "number", "description": "Identifier", - "id": true + "id": true }, "code": { "type": "string" diff --git a/modules/ticket/back/model-config.json b/modules/ticket/back/model-config.json index 247e18d01..92bd83ac5 100644 --- a/modules/ticket/back/model-config.json +++ b/modules/ticket/back/model-config.json @@ -36,7 +36,7 @@ "dataSource": "vn" }, "ExpeditionMistakeType": { - "dataSource": "vn" + "dataSource": "vn" }, "PrintServerQueue": { "dataSource": "vn" diff --git a/modules/ticket/back/models/expeditionMistakeType.json b/modules/ticket/back/models/expeditionMistakeType.json index cf997a963..c7eaa3cac 100644 --- a/modules/ticket/back/models/expeditionMistakeType.json +++ b/modules/ticket/back/models/expeditionMistakeType.json @@ -7,10 +7,9 @@ } }, "properties": { - "code": { - "id":true, - "type": "string" - + "code": { + "id":true, + "type": "string" }, "description": { "type": "string" diff --git a/modules/worker/back/models/mistakeType.json b/modules/worker/back/models/mistakeType.json index 71d9e4744..c9fe3ee39 100644 --- a/modules/worker/back/models/mistakeType.json +++ b/modules/worker/back/models/mistakeType.json @@ -7,7 +7,7 @@ } }, "properties": { - "id": { + "id": { "id":true, "type": "number" }, diff --git a/modules/worker/back/models/workerMistake.json b/modules/worker/back/models/workerMistake.json index 47ed95f80..00978761e 100644 --- a/modules/worker/back/models/workerMistake.json +++ b/modules/worker/back/models/workerMistake.json @@ -7,10 +7,10 @@ } }, "properties": { - "id": { - "id":true, - "type": "number" - }, + "id": { + "id":true, + "type": "number" + }, "userFk": { "type": "number" }, From 18de92f9e71a641f049ad6dec0d5329459e67ad9 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Thu, 28 Sep 2023 07:51:54 +0200 Subject: [PATCH 154/427] refs #5134 fix: format --- db/changes/234001/00-models.sql | 16 ++++++++-------- modules/worker/back/models/mistakeType.json | 4 ++-- .../worker/back/models/workerMistakeType.json | 7 +++---- 3 files changed, 13 insertions(+), 14 deletions(-) diff --git a/db/changes/234001/00-models.sql b/db/changes/234001/00-models.sql index 51ffa1554..abf1e3ea5 100644 --- a/db/changes/234001/00-models.sql +++ b/db/changes/234001/00-models.sql @@ -1,11 +1,11 @@ INSERT INTO `salix`.`ACL` ( model, property, accessType, permission, principalType, principalId) VALUES - ('ExpeditionMistakeType', '*', 'READ', 'ALLOW', 'ROLE', 'employee'); - ('WorkerMistakeType', '*', 'READ', 'ALLOW', 'ROLE', 'employee'); - ('ExpeditionMistake','*','WRITE','ALLOW','ROLE','employee'); - ('WorkerMistake', '*', 'WRITE', 'ALLOW', 'ROLE', 'coolerBoss'); - ('MistakesTypes', '*', 'WRITE', 'ALLOW', 'ROLE', 'coolerBoss'); - ('MistakeType','*','READ','ALLOW','ROLE','employee'); - ('MachineWorker', '*', 'READ', 'ALLOW', 'ROLE', 'coolerAssist'); - ('Printer','*','READ','ALLOW','ROLE','employee'); + ('ExpeditionMistakeType', '*', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('WorkerMistakeType', '*', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('ExpeditionMistake','*','WRITE','ALLOW','ROLE','employee'), + ('WorkerMistake', '*', 'WRITE', 'ALLOW', 'ROLE', 'coolerBoss'), + ('MistakesTypes', '*', 'WRITE', 'ALLOW', 'ROLE', 'coolerBoss'), + ('MistakeType','*','READ','ALLOW','ROLE','employee'), + ('MachineWorker', '*', 'READ', 'ALLOW', 'ROLE', 'coolerAssist'), + ('Printer','*','READ','ALLOW','ROLE','employee'), ('SaleMistake', '*', 'WRITE', 'ALLOW', 'ROLE', 'production'); diff --git a/modules/worker/back/models/mistakeType.json b/modules/worker/back/models/mistakeType.json index c9fe3ee39..e999b3e28 100644 --- a/modules/worker/back/models/mistakeType.json +++ b/modules/worker/back/models/mistakeType.json @@ -8,8 +8,8 @@ }, "properties": { "id": { - "id":true, - "type": "number" + "id":true, + "type": "number" }, "description": { "type": "string" diff --git a/modules/worker/back/models/workerMistakeType.json b/modules/worker/back/models/workerMistakeType.json index 3c808f24c..c5e6e6383 100644 --- a/modules/worker/back/models/workerMistakeType.json +++ b/modules/worker/back/models/workerMistakeType.json @@ -7,10 +7,9 @@ } }, "properties": { - "code": { - "id":true, - "type": "string" - + "code": { + "id":true, + "type": "string" }, "description": { "type": "string" From 4048627c765553f7acb6b804b5b42bbf7a4e5ab5 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Thu, 28 Sep 2023 08:08:40 +0200 Subject: [PATCH 155/427] refs #5890 fix: format --- db/changes/234001/01-itemShelvingSale.sql | 8 ++++---- .../item-shelving-sale/itemShelvingSaleByCollection.js | 3 ++- .../item-shelving-sale/itemShelvingSaleSetQuantity.js | 9 ++++++--- 3 files changed, 12 insertions(+), 8 deletions(-) diff --git a/db/changes/234001/01-itemShelvingSale.sql b/db/changes/234001/01-itemShelvingSale.sql index af68d465a..3b01f7da7 100644 --- a/db/changes/234001/01-itemShelvingSale.sql +++ b/db/changes/234001/01-itemShelvingSale.sql @@ -288,12 +288,12 @@ BEGIN END$$ DELIMITER ; -ALTER TABLE vn.itemShelvingSale DROP COLUMN IF EXISTS isPicked; +ALTER TABLE `vn`.`itemShelvingSale` DROP COLUMN IF EXISTS isPicked; -ALTER TABLE vn.itemShelvingSale +ALTER TABLE`vn`.`itemShelvingSale` ADD isPicked TINYINT(1) DEFAULT FALSE NOT NULL; -ALTER TABLE vn.productionConfig DROP COLUMN IF EXISTS orderMode; +ALTER TABLE `vn`.`productionConfig` DROP COLUMN IF EXISTS orderMode; -ALTER TABLE vn.productionConfig +ALTER TABLE `vn`.`productionConfig` ADD orderMode ENUM('Location', 'Age') NOT NULL DEFAULT 'Location'; \ No newline at end of file diff --git a/modules/item/back/methods/item-shelving-sale/itemShelvingSaleByCollection.js b/modules/item/back/methods/item-shelving-sale/itemShelvingSaleByCollection.js index 2eb61a875..2128d68a9 100644 --- a/modules/item/back/methods/item-shelving-sale/itemShelvingSaleByCollection.js +++ b/modules/item/back/methods/item-shelving-sale/itemShelvingSaleByCollection.js @@ -5,8 +5,9 @@ module.exports = Self => { accepts: [ { arg: 'id', - type: 'Number', + type: 'number', description: 'The collection id', + required: true, http: {source: 'path'} } ], diff --git a/modules/item/back/methods/item-shelving-sale/itemShelvingSaleSetQuantity.js b/modules/item/back/methods/item-shelving-sale/itemShelvingSaleSetQuantity.js index bb2c4db0a..6fe0e28a0 100644 --- a/modules/item/back/methods/item-shelving-sale/itemShelvingSaleSetQuantity.js +++ b/modules/item/back/methods/item-shelving-sale/itemShelvingSaleSetQuantity.js @@ -5,17 +5,20 @@ module.exports = Self => { accepts: [ { arg: 'id', - type: 'Number', + type: 'number', + required: true, description: 'The sale id', }, { arg: 'quantity', - type: 'Number', + type: 'number', + required: true, description: 'The quantity to set', }, { arg: 'isItemShelvingSaleEmpty', - type: 'Boolean', + type: 'boolean', + required: true, description: 'True if the shelvingFk is empty ', } ], From 65b0ec387f844bebb502771401161d2399c3d50d Mon Sep 17 00:00:00 2001 From: sergiodt Date: Thu, 28 Sep 2023 08:09:54 +0200 Subject: [PATCH 156/427] refs #5890 fix: format --- db/changes/234001/01-itemShelvingSale.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/changes/234001/01-itemShelvingSale.sql b/db/changes/234001/01-itemShelvingSale.sql index 3b01f7da7..b98004bc5 100644 --- a/db/changes/234001/01-itemShelvingSale.sql +++ b/db/changes/234001/01-itemShelvingSale.sql @@ -1,5 +1,5 @@ -ALTER TABLE vn.itemShelvingSale ADD isPicked TINYINT(1) DEFAULT FALSE NOT NULL; +ALTER TABLE `vn`.`itemShelvingSale` ADD isPicked TINYINT(1) DEFAULT FALSE NOT NULL; DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_addByCollection`( From 463fc8ae958d8ebe7c388636575636c0ad5ded1b Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 28 Sep 2023 08:20:59 +0200 Subject: [PATCH 157/427] ref #5914 added fixtures in English --- db/dump/fixtures.sql | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 15d78adff..31ec9b138 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -2977,6 +2977,6 @@ INSERT INTO vn.XDiario (id, ASIEN, FECHA, SUBCTA, CONTRA, CONCEPTO, EURODEBE, EU INSERT INTO `vn`.`invoiceCorrectionType` (`id`, `description`) VALUES - (1, 'Error en el cálculo del IVA'), - (2, 'Error en el detalle de las ventas'), - (3, 'Error en los datos del cliente'); \ No newline at end of file + (1, 'Error in VAT calculation'), + (2, 'Error in sales details'), + (3, 'Error in customer data'); \ No newline at end of file From d4e5815d417122c905e7583ef314311d21793fcf Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 28 Sep 2023 08:30:50 +0200 Subject: [PATCH 158/427] refs #6254 feat(collection_getTickets): refactor code and add test --- back/methods/collection/getTickets.js | 46 +++++++++---------- .../collection/spec/getTickets.spec.js | 38 +++++++++++++-- db/changes/233802/.gitkeep | 0 .../00-collectionGetTicketsACL.sql | 0 4 files changed, 56 insertions(+), 28 deletions(-) create mode 100644 db/changes/233802/.gitkeep rename db/changes/{234001 => 233802}/00-collectionGetTicketsACL.sql (100%) diff --git a/back/methods/collection/getTickets.js b/back/methods/collection/getTickets.js index 196ff0ce6..1d0daa43a 100644 --- a/back/methods/collection/getTickets.js +++ b/back/methods/collection/getTickets.js @@ -4,10 +4,11 @@ module.exports = Self => { description: 'Make a new collection of tickets', accessType: 'WRITE', accepts: [{ - arg: 'paramId', + arg: 'id', type: 'number', - description: 'The collection or ticket id', - required: true + description: 'The collection id', + required: true, + http: {source: 'path'} }, { arg: 'print', type: 'boolean', @@ -18,12 +19,12 @@ module.exports = Self => { root: true }, http: { - path: `/getTickets`, + path: `/:id/getTickets`, verb: 'POST' } }); - Self.getTickets = async(ctx, paramId, print, options) => { + Self.getTickets = async(ctx, id, print, options) => { const userId = ctx.req.accessToken.userId; const origin = ctx.req.headers.origin; const $t = ctx.req.__; // $translate @@ -42,7 +43,7 @@ module.exports = Self => { const promises = []; try { - const [tickets] = await Self.rawSql(`CALL vn.collection_getTickets(?)`, [paramId], myOptions); + const [tickets] = await Self.rawSql(`CALL vn.collection_getTickets(?)`, [id], myOptions); const sales = await Self.rawSql(` SELECT s.ticketFk, @@ -104,14 +105,14 @@ module.exports = Self => { LEFT JOIN saleMistake sm ON sm.saleFk = s.id WHERE tc.collectionFk = ? GROUP BY s.id, p.code, p2.code - ORDER BY pickingOrder`, [paramId, paramId], myOptions); + ORDER BY pickingOrder`, [id, id], myOptions); if (print) - await Self.rawSql(`CALL vn.collection_printSticker(?, ?)`, [paramId, null], myOptions); + await Self.rawSql(`CALL vn.collection_printSticker(?, ?)`, [id, null], myOptions); - const collection = {collectionFk: paramId, tickets: []}; + const collection = {collectionFk: id, tickets: []}; if (tickets && tickets.length) { - for (let ticket of tickets) { + for (const ticket of tickets) { const ticketId = ticket.ticketFk; // SEND ROCKET @@ -142,26 +143,25 @@ module.exports = Self => { [ticketId], myOptions); // BINDINGS - ticket.sales = sales.reduce((acc, sale) => { - if (sale.ticketFk == ticketId) { + ticket.sales = []; + for (const sale of sales) { + if (sale.ticketFk === ticketId) { sale.Barcodes = []; + if (barcodes && barcodes.length) { - sale.Barcodes = barcodes.reduce((bacc, barcode) => { - if (barcode.saleFk == sale.saleFk) { + for (const barcode of barcodes) { + if (barcode.saleFk === sale.saleFk) { for (let prop in barcode) { - if (['id', 'code'].includes(prop) && barcode[prop]) { - bacc.push(barcode[prop].toString()); - bacc.push('0' + barcode[prop]); - } + if (['id', 'code'].includes(prop) && barcode[prop]) + sale.Barcodes.push(barcode[prop].toString(), '0' + barcode[prop]); } } - return bacc; - }, []); + } } - acc.push(sale); + + ticket.sales.push(sale); } - return acc; - }, []); + } } collection.tickets.push(ticket); } diff --git a/back/methods/collection/spec/getTickets.spec.js b/back/methods/collection/spec/getTickets.spec.js index eddbb21b1..e6b9e6a17 100644 --- a/back/methods/collection/spec/getTickets.spec.js +++ b/back/methods/collection/spec/getTickets.spec.js @@ -1,11 +1,39 @@ const models = require('vn-loopback/server/server').models; describe('collection getTickets()', () => { - it('should return a list of tickets from a collection', async() => { - let ctx = {req: {accessToken: {userId: 1107}}}; - let response = await models.Collection.getCollection(ctx); + let ctx; + beforeAll(async() => { + ctx = { + req: { + accessToken: {userId: 9}, + headers: {origin: 'http://localhost'} + } + }; + }); - expect(response.length).toBeGreaterThan(0); - expect(response[0].collectionFk).toEqual(3); + it('should get tickets, sales and barcodes from collection', async() => { + const tx = await models.Collection.beginTransaction({}); + + try { + const options = {transaction: tx}; + const collectionId = 1; + + const collectionTickets = await models.Collection.getTickets(ctx, collectionId, null, options); + + expect(collectionTickets.collectionFk).toEqual(collectionId); + expect(collectionTickets.tickets.length).toEqual(3); + expect(collectionTickets.tickets[0].ticketFk).toEqual(1); + expect(collectionTickets.tickets[1].ticketFk).toEqual(2); + expect(collectionTickets.tickets[2].ticketFk).toEqual(23); + expect(collectionTickets.tickets[0].sales[0].ticketFk).toEqual(1); + expect(collectionTickets.tickets[0].sales[1].ticketFk).toEqual(1); + expect(collectionTickets.tickets[0].sales[2].ticketFk).toEqual(1); + expect(collectionTickets.tickets[0].sales[0].Barcodes.length).toBeTruthy(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/db/changes/233802/.gitkeep b/db/changes/233802/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/db/changes/234001/00-collectionGetTicketsACL.sql b/db/changes/233802/00-collectionGetTicketsACL.sql similarity index 100% rename from db/changes/234001/00-collectionGetTicketsACL.sql rename to db/changes/233802/00-collectionGetTicketsACL.sql From 869bdab7ced8ca982a0cbb59e67d36eb895c8903 Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 28 Sep 2023 11:36:03 +0200 Subject: [PATCH 159/427] ref #6065 fetchHours relocated --- modules/worker/front/card/index.js | 11 +- modules/worker/front/time-control/index.js | 181 +++++++++--------- .../worker/front/time-control/index.spec.js | 3 +- 3 files changed, 99 insertions(+), 96 deletions(-) diff --git a/modules/worker/front/card/index.js b/modules/worker/front/card/index.js index dcba2efcd..b8b533c5d 100644 --- a/modules/worker/front/card/index.js +++ b/modules/worker/front/card/index.js @@ -2,7 +2,7 @@ import ngModule from '../module'; import ModuleCard from 'salix/components/module-card'; class Controller extends ModuleCard { - async reload() { + reload() { const filter = { include: [ { @@ -31,12 +31,13 @@ class Controller extends ModuleCard { } ] }; - const promises = await Promise.all([ - this.$http.get(`Workers/${this.$params.id}`, {filter}), + + return Promise.all([ + this.$http.get(`Workers/${this.$params.id}`, {filter}) + .then(res => this.worker = res.data), this.$http.get(`Workers/${this.$params.id}/activeContract`) + .then(res => this.hasWorkCenter = res.data?.workCenterFk) ]); - this.worker = await promises[0].data; - this.worker.hasWorkCenter = await promises[1].data?.workCenterFk; } } diff --git a/modules/worker/front/time-control/index.js b/modules/worker/front/time-control/index.js index e21bfbfbb..943b40eb1 100644 --- a/modules/worker/front/time-control/index.js +++ b/modules/worker/front/time-control/index.js @@ -52,6 +52,28 @@ class Controller extends Section { set worker(value) { this._worker = value; + this.fetchHours(); + } + + /** + * Worker hours data + */ + get hours() { + return this._hours; + } + + set hours(value) { + this._hours = value; + + for (const weekDay of this.weekDays) { + if (value) { + let day = weekDay.dated.getDay(); + weekDay.hours = value + .filter(hour => new Date(hour.timed).getDay() == day) + .sort((a, b) => new Date(a.timed) - new Date(b.timed)); + } else + weekDay.hours = null; + } } /** @@ -87,10 +109,17 @@ class Controller extends Section { dayIndex.setDate(dayIndex.getDate() + 1); } - this.fetchHours(); this.getWeekData(); } + set weekTotalHours(totalHours) { + this._weekTotalHours = this.formatHours(totalHours); + } + + get weekTotalHours() { + return this._weekTotalHours; + } + getWeekData() { const filter = { where: { @@ -101,38 +130,19 @@ class Controller extends Section { }; this.$http.get('WorkerTimeControlMails', {filter}) .then(res => { - const workerTimeControlMail = res.data; - if (!workerTimeControlMail.length) { + const mail = res.data; + if (!mail.length) { this.state = null; return; } - this.state = workerTimeControlMail[0].state; - this.reason = workerTimeControlMail[0].reason; + this.state = mail[0].state; + this.reason = mail[0].reason; }); } - /** - * Worker hours data - */ - get hours() { - return this._hours; - } + fetchHours() { + if (!this.worker || !this.date) return; - set hours(value) { - this._hours = value; - - for (const weekDay of this.weekDays) { - if (value) { - let day = weekDay.dated.getDay(); - weekDay.hours = value - .filter(hour => new Date(hour.timed).getDay() == day) - .sort((a, b) => new Date(a.timed) - new Date(b.timed)); - } else - weekDay.hours = null; - } - } - - async fetchHours() { const params = {workerFk: this.$params.id}; const filter = { where: {and: [ @@ -140,62 +150,11 @@ class Controller extends Section { {timed: {lte: this.ended}} ]} }; - await this.$.model.applyFilter(filter, params); - if (!this.worker.hasWorkCenter) return; + this.$.model.applyFilter(filter, params).then(() => { + if (!this.card.hasWorkCenter) return; - await this.getWorkedHours(this.started, this.ended); - await this.getAbsences(); - } - - hasEvents(day) { - return day >= this.started && day < this.ended; - } - - getAbsences() { - const fullYear = this.started.getFullYear(); - let params = { - workerFk: this.$params.id, - businessFk: null, - year: fullYear - }; - - return this.$http.get(`Calendars/absences`, {params}) - .then(res => this.onData(res.data)); - } - - onData(data) { - const events = {}; - - const addEvent = (day, event) => { - events[new Date(day).getTime()] = event; - }; - - if (data.holidays) { - data.holidays.forEach(holiday => { - const holidayDetail = holiday.detail && holiday.detail.description; - const holidayType = holiday.type && holiday.type.name; - const holidayName = holidayDetail || holidayType; - - addEvent(holiday.dated, { - name: holidayName, - color: '#ff0' - }); - }); - } - if (data.absences) { - data.absences.forEach(absence => { - const type = absence.absenceType; - addEvent(absence.dated, { - name: type.name, - color: type.rgb - }); - }); - } - - this.weekDays.forEach(day => { - const timestamp = day.dated.getTime(); - if (events[timestamp]) - day.event = events[timestamp]; + this.getWorkedHours(this.started, this.ended); + this.getAbsences(); }); } @@ -238,6 +197,58 @@ class Controller extends Section { }); } + getAbsences() { + const fullYear = this.started.getFullYear(); + let params = { + workerFk: this.$params.id, + businessFk: null, + year: fullYear + }; + + return this.$http.get(`Calendars/absences`, {params}) + .then(res => this.onData(res.data)); + } + + hasEvents(day) { + return day >= this.started && day < this.ended; + } + + onData(data) { + const events = {}; + + const addEvent = (day, event) => { + events[new Date(day).getTime()] = event; + }; + + if (data.holidays) { + data.holidays.forEach(holiday => { + const holidayDetail = holiday.detail && holiday.detail.description; + const holidayType = holiday.type && holiday.type.name; + const holidayName = holidayDetail || holidayType; + + addEvent(holiday.dated, { + name: holidayName, + color: '#ff0' + }); + }); + } + if (data.absences) { + data.absences.forEach(absence => { + const type = absence.absenceType; + addEvent(absence.dated, { + name: type.name, + color: type.rgb + }); + }); + } + + this.weekDays.forEach(day => { + const timestamp = day.dated.getTime(); + if (events[timestamp]) + day.event = events[timestamp]; + }); + } + getFinishTime() { if (!this.weekDays) return; @@ -266,14 +277,6 @@ class Controller extends Section { } } - set weekTotalHours(totalHours) { - this._weekTotalHours = this.formatHours(totalHours); - } - - get weekTotalHours() { - return this._weekTotalHours; - } - formatHours(timestamp = 0) { let hour = Math.floor(timestamp / 3600); let min = Math.floor(timestamp / 60 - 60 * hour); diff --git a/modules/worker/front/time-control/index.spec.js b/modules/worker/front/time-control/index.spec.js index 6d8510ba8..10e8aba0d 100644 --- a/modules/worker/front/time-control/index.spec.js +++ b/modules/worker/front/time-control/index.spec.js @@ -22,7 +22,7 @@ describe('Component vnWorkerTimeControl', () => { })); describe('date() setter', () => { - it(`should set the weekDays, the date in the controller and call fetchHours`, () => { + it(`should set the weekDays and the date in the controller`, () => { let today = Date.vnNew(); jest.spyOn(controller, 'fetchHours').mockReturnThis(); @@ -32,7 +32,6 @@ describe('Component vnWorkerTimeControl', () => { expect(controller.started).toBeDefined(); expect(controller.ended).toBeDefined(); expect(controller.weekDays.length).toEqual(7); - expect(controller.fetchHours).toHaveBeenCalledWith(); }); }); From e209ab28f467a3c252fb33046981b753cff35402 Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 28 Sep 2023 11:53:09 +0200 Subject: [PATCH 160/427] ref #6065 first time hours load fixed --- modules/worker/front/time-control/index.js | 1 + 1 file changed, 1 insertion(+) diff --git a/modules/worker/front/time-control/index.js b/modules/worker/front/time-control/index.js index 943b40eb1..71de1cef4 100644 --- a/modules/worker/front/time-control/index.js +++ b/modules/worker/front/time-control/index.js @@ -109,6 +109,7 @@ class Controller extends Section { dayIndex.setDate(dayIndex.getDate() + 1); } + if (!this.weekTotalHours) this.fetchHours(); this.getWeekData(); } From e51df063d3cdd8d819368f6bdd1f53cae03ac506 Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 28 Sep 2023 13:26:05 +0200 Subject: [PATCH 161/427] refs #5890 feat: add userId in rawSql --- .../itemShelvingSaleByCollection.js | 11 ++++++++--- .../itemShelvingSaleSetQuantity.js | 13 ++++++++++--- 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/modules/item/back/methods/item-shelving-sale/itemShelvingSaleByCollection.js b/modules/item/back/methods/item-shelving-sale/itemShelvingSaleByCollection.js index 2128d68a9..2059c28c9 100644 --- a/modules/item/back/methods/item-shelving-sale/itemShelvingSaleByCollection.js +++ b/modules/item/back/methods/item-shelving-sale/itemShelvingSaleByCollection.js @@ -1,5 +1,5 @@ module.exports = Self => { - Self.remoteMethod('itemShelvingSaleByCollection', { + Self.remoteMethodCtx('itemShelvingSaleByCollection', { description: 'Insert sales of the collection in itemShelvingSale', accessType: 'WRITE', accepts: [ @@ -17,7 +17,12 @@ module.exports = Self => { } }); - Self.itemShelvingSaleByCollection = async id => { - await Self.rawSql(`CALL vn.itemShelvingSale_addByCollection(?)`, [id]); + Self.itemShelvingSaleByCollection = async(ctx, id, options) => { + const myOptions = {userId: ctx.req.accessToken.userId}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + await Self.rawSql(`CALL vn.itemShelvingSale_addByCollection(?)`, [id], myOptions); }; }; diff --git a/modules/item/back/methods/item-shelving-sale/itemShelvingSaleSetQuantity.js b/modules/item/back/methods/item-shelving-sale/itemShelvingSaleSetQuantity.js index 6fe0e28a0..90e66c066 100644 --- a/modules/item/back/methods/item-shelving-sale/itemShelvingSaleSetQuantity.js +++ b/modules/item/back/methods/item-shelving-sale/itemShelvingSaleSetQuantity.js @@ -1,5 +1,5 @@ module.exports = Self => { - Self.remoteMethod('itemShelvingSaleSetQuantity', { + Self.remoteMethodCtx('itemShelvingSaleSetQuantity', { description: 'Set quanitity of a sale in itemShelvingSale', accessType: 'WRITE', accepts: [ @@ -28,7 +28,14 @@ module.exports = Self => { } }); - Self.itemShelvingSaleSetQuantity = async(id, quantity, isItemShelvingSaleEmpty) => { - await Self.rawSql(`CALL vn.itemShelvingSale_setQuantity(?, ?, ? )`, [id, quantity, isItemShelvingSaleEmpty]); + Self.itemShelvingSaleSetQuantity = async(ctx, id, quantity, isItemShelvingSaleEmpty, options) => { + const myOptions = {userId: ctx.req.accessToken.userId}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + await Self.rawSql(`CALL vn.itemShelvingSale_setQuantity(?, ?, ? )`, + [id, quantity, isItemShelvingSaleEmpty], + myOptions); }; }; From 28dfb895ca485ae5a43cbd738e92564f0fe42bab Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 28 Sep 2023 13:49:58 +0200 Subject: [PATCH 162/427] refs #6224 deploy: correct sql folder and fix sql --- db/changes/233801/01-deviceLog_acl.sql | 6 +++--- .../00-item_setVisibleDiscard.sql | 0 db/changes/{233801 => 234001}/00-ticketConfig.sql | 0 db/changes/234001/01-deliveryAssistantACL.sql | 15 ++++++++++----- db/changes/234001/02-roleSync.sql | 2 ++ db/dump/dumpedFixtures.sql | 4 ++-- .../item/back/methods/item/setVisibleDiscard.js | 2 +- 7 files changed, 18 insertions(+), 11 deletions(-) rename db/changes/{233801 => 234001}/00-item_setVisibleDiscard.sql (100%) rename db/changes/{233801 => 234001}/00-ticketConfig.sql (100%) create mode 100644 db/changes/234001/02-roleSync.sql diff --git a/db/changes/233801/01-deviceLog_acl.sql b/db/changes/233801/01-deviceLog_acl.sql index ebe3f8ed5..2b646a6a3 100644 --- a/db/changes/233801/01-deviceLog_acl.sql +++ b/db/changes/233801/01-deviceLog_acl.sql @@ -1,6 +1,6 @@ -ALTER TABLE `vn`.`deviceLog` ADD serialNumber varchar(45) DEFAULT NULL NULL; +-- ALTER TABLE `vn`.`deviceLog` ADD serialNumber varchar(45) DEFAULT NULL NULL; -INSERT INTO `salix`.`ACL` ( model, property, accessType, permission, principalType, principalId) -VALUES( 'DeviceLog', 'create', 'WRITE', 'ALLOW', 'ROLE', 'employee'); +-- INSERT INTO `salix`.`ACL` ( model, property, accessType, permission, principalType, principalId) +-- VALUES( 'DeviceLog', 'create', 'WRITE', 'ALLOW', 'ROLE', 'employee'); diff --git a/db/changes/233801/00-item_setVisibleDiscard.sql b/db/changes/234001/00-item_setVisibleDiscard.sql similarity index 100% rename from db/changes/233801/00-item_setVisibleDiscard.sql rename to db/changes/234001/00-item_setVisibleDiscard.sql diff --git a/db/changes/233801/00-ticketConfig.sql b/db/changes/234001/00-ticketConfig.sql similarity index 100% rename from db/changes/233801/00-ticketConfig.sql rename to db/changes/234001/00-ticketConfig.sql diff --git a/db/changes/234001/01-deliveryAssistantACL.sql b/db/changes/234001/01-deliveryAssistantACL.sql index 504760d6f..0f273325f 100644 --- a/db/changes/234001/01-deliveryAssistantACL.sql +++ b/db/changes/234001/01-deliveryAssistantACL.sql @@ -4,13 +4,18 @@ INSERT INTO `account`.`role` (name, description) INSERT INTO `account`.`roleInherit` (role, inheritsFrom) SELECT (SELECT id FROM account.role r1 WHERE r1.name = 'deliveryAssistant'), ri.inheritsFrom -FROM account.roleInherit ri - JOIN account.role r2 ON r2.id = ri.`role` -WHERE r2.name = 'deliveryBoss'; + FROM account.roleInherit ri + JOIN account.role r2 ON r2.id = ri.`role` + WHERE r2.name = 'deliveryBoss'; + +DELETE `account`.`roleInherit` FROM `account`.`roleInherit` + JOIN `account`.`role` r ON `account`.`roleInherit`.role = r.id + WHERE r.name = 'deliveryBoss'; INSERT INTO `account`.`roleInherit` (role, inheritsFrom) SELECT (SELECT id FROM account.role WHERE name = 'deliveryBoss') role, (SELECT id FROM account.role WHERE name = 'deliveryAssistant') roleInherit; - -CALL `account`.`role_syncPrivileges`(); +UPDATE `salix`.`ACL` + SET principalId='deliveryAssistant' + WHERE principalId='deliveryBoss'; diff --git a/db/changes/234001/02-roleSync.sql b/db/changes/234001/02-roleSync.sql new file mode 100644 index 000000000..6fe47f691 --- /dev/null +++ b/db/changes/234001/02-roleSync.sql @@ -0,0 +1,2 @@ +-- Locally it fails because it is executed before the fixtures and the roleConfig table is empty +CALL `account`.`role_syncPrivileges`(); diff --git a/db/dump/dumpedFixtures.sql b/db/dump/dumpedFixtures.sql index 383cc4722..2e1511b59 100644 --- a/db/dump/dumpedFixtures.sql +++ b/db/dump/dumpedFixtures.sql @@ -78,7 +78,7 @@ USE `account`; LOCK TABLES `role` WRITE; /*!40000 ALTER TABLE `role` DISABLE KEYS */; -INSERT INTO `role` VALUES (1,'employee','Empleado básico',1,'2017-05-19 07:04:58','2023-06-08 16:47:57',NULL),(2,'customer','Privilegios básicos de un cliente',1,'2017-05-19 07:04:58','2023-06-02 20:33:28',NULL),(3,'agency','Consultar tablas de predicciones de bultos',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(5,'administrative','Tareas relacionadas con la contabilidad',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(6,'guest','Privilegios para usuarios sin cuenta',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(9,'developer','Desarrolladores del sistema',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(11,'account','Privilegios relacionados con el login',0,'2017-05-19 07:04:58','2017-09-20 17:06:35',NULL),(13,'teamBoss','Jefe de equipo/departamento',1,'2017-05-19 07:04:58','2021-06-30 13:29:30',NULL),(15,'logistic','Departamento de compras, responsables de la logistica',1,'2017-05-19 07:04:58','2018-02-12 10:50:10',NULL),(16,'logisticBoss','Jefe del departamento de logística',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(17,'adminBoss','Jefe del departamento de administración',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(18,'salesPerson','Departamento de ventas',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(19,'salesBoss','Jefe del departamento de ventas',1,'2017-05-19 07:04:58','2017-08-16 12:38:27',NULL),(20,'manager','Gerencia',1,'2017-06-01 14:57:02','2022-07-29 07:36:15',NULL),(21,'salesAssistant','Jefe auxiliar de ventas',1,'2017-08-16 12:40:52','2017-08-16 12:40:52',NULL),(22,'teamManager','Jefe de departamento con privilegios de auxiliar de venta.',1,'2017-09-07 09:08:12','2017-09-07 09:08:12',NULL),(30,'financialBoss','Director finaciero',1,'2017-09-21 11:05:36','2017-09-21 11:05:36',NULL),(31,'freelancer','Trabajadores por cuenta ajena',1,'2017-10-10 12:57:26','2017-10-10 12:59:27',NULL),(32,'ett','Trabajadores de empresa temporal',1,'2017-10-10 12:58:58','2017-10-10 12:59:20',NULL),(33,'invoicing','Personal con acceso a facturación',0,'2018-01-29 16:43:34','2018-01-29 16:43:34',NULL),(34,'agencyBoss','Jefe/a del departamento de agencias',1,'2018-01-29 16:44:39','2018-02-23 07:58:53',NULL),(35,'buyer','Departamento de compras',1,'2018-02-12 10:35:42','2018-02-12 10:35:42',NULL),(36,'replenisher','Trabajadores de camara',1,'2018-02-16 14:07:10','2019-04-12 05:38:08',NULL),(37,'hr','Gestor/a de recursos humanos',1,'2018-02-22 17:34:53','2018-02-22 17:34:53',NULL),(38,'hrBoss','Jefe/a de recursos humanos',1,'2018-02-22 17:35:09','2018-02-22 17:35:09',NULL),(39,'adminAssistant','Jefe auxiliar administrativo',1,'2018-02-23 10:37:36','2018-02-23 10:38:41',NULL),(40,'handmade','Departamento de confección',1,'2018-02-23 11:14:53','2018-02-23 11:39:12',NULL),(41,'handmadeBoss','Jefe de departamento de confección',1,'2018-02-23 11:15:09','2018-02-23 11:39:26',NULL),(42,'artificial','Departamento de artificial',1,'2018-02-23 11:39:59','2018-02-23 11:39:59',NULL),(43,'artificialBoss','Jefe del departamento de artificial',1,'2018-02-23 11:40:16','2018-02-23 11:40:16',NULL),(44,'accessory','Departamento de complementos',1,'2018-02-23 11:41:12','2018-02-23 11:41:12',NULL),(45,'accessoryBoss','Jefe del departamento de complementos',1,'2018-02-23 11:41:23','2018-02-23 11:41:23',NULL),(47,'cooler','Empleados de cámara',1,'2018-02-23 13:08:18','2018-02-23 13:08:18',NULL),(48,'coolerBoss','Jefe de cámara',1,'2018-02-23 13:12:01','2023-03-13 08:49:43',NULL),(49,'production','Empleado de producción',1,'2018-02-26 15:28:23','2021-02-12 09:42:35',NULL),(50,'productionBoss','Jefe de producción',1,'2018-02-26 15:34:12','2018-02-26 15:34:12',NULL),(51,'marketing','Departamento de marketing',1,'2018-03-01 07:28:39','2018-03-01 07:28:39',NULL),(52,'marketingBoss','Jefe del departamento de marketing',1,'2018-03-01 07:28:57','2018-03-01 07:28:57',NULL),(53,'insurance','Gestor de seguros de cambio',0,'2018-03-05 07:44:35','2019-02-01 13:47:57',NULL),(54,'itemPicker','Sacador en cámara',1,'2018-03-05 12:08:17','2018-03-05 12:08:17',NULL),(55,'itemPickerBoss','Jefe de sacadores',1,'2018-03-05 12:08:31','2018-03-05 12:08:31',NULL),(56,'delivery','Personal de reparto',1,'2018-05-30 06:07:02','2018-05-30 06:07:02',NULL),(57,'deliveryAssistant','Jefe de personal de reparto',1,'2018-05-30 06:07:19','2018-05-30 06:07:19',NULL),(58,'packager','Departamento encajadores',1,'2019-01-21 12:43:45','2019-01-21 12:43:45',NULL),(59,'packagerBoss','Jefe departamento encajadores',1,'2019-01-21 12:44:10','2019-01-21 12:44:10',NULL),(60,'productionAssi','Tareas relacionadas con producción y administración',1,'2019-01-29 13:29:01','2019-01-29 13:29:01',NULL),(61,'replenisherBos','Jefe de Complementos/Camara',1,'2019-07-01 06:44:07','2019-07-01 06:44:07',NULL),(62,'noLogin','Role without login access to MySQL',0,'2019-07-01 06:50:19','2019-07-02 13:42:05',NULL),(64,'balanceSheet','Consulta de Balance',0,'2019-07-16 12:12:08','2019-07-16 12:12:08',NULL),(65,'officeBoss','Jefe de filial',1,'2019-08-02 06:54:26','2019-08-02 06:54:26',NULL),(66,'sysadmin','Administrador de sistema',1,'2019-08-08 06:58:56','2019-08-08 06:58:56',NULL),(67,'adminOfficer','categoria profesional oficial de administración',1,'2020-01-03 08:09:23','2020-01-03 08:09:23',NULL),(69,'coolerAssist','Asistente de cámara con permiso compras',1,'2020-02-05 12:36:09','2023-03-13 08:50:07',NULL),(70,'trainee','Alumno de prácticas',1,'2020-03-04 11:00:25','2020-03-04 11:00:25',NULL),(71,'checker','Rol de revisor con privilegios de itemPicker',1,'2020-10-02 10:50:07','2020-10-02 10:50:07',NULL),(72,'claimManager','Personal de reclamaciones',1,'2020-10-13 10:01:32','2020-10-26 07:29:46',NULL),(73,'financial','Departamento de finanzas',1,'2020-11-16 09:30:27','2020-11-16 09:30:27',NULL),(74,'userPhotos','Privilegios para subir fotos de usuario',1,'2021-02-03 10:24:27','2021-02-03 10:24:27',NULL),(75,'catalogPhotos','Privilegios para subir fotos del catálogo',1,'2021-02-03 10:24:27','2021-02-03 10:24:27',NULL),(76,'chat','Rol para utilizar el rocket chat',1,'2020-11-27 13:06:50','2020-12-17 07:49:41',NULL),(100,'root','Rol con todos los privilegios',0,'2018-04-23 14:33:36','2020-11-12 06:50:07',NULL),(101,'buyerBoss','Jefe del departamento de compras',1,'2021-06-16 09:53:17','2021-06-16 09:53:17',NULL),(102,'preservedBoss','Responsable preservado',1,'2021-09-14 13:45:37','2021-09-14 13:45:37',NULL),(103,'it','Departamento de informática',1,'2021-11-11 09:48:22','2021-11-11 09:48:22',NULL),(104,'itBoss','Jefe de departamento de informática',1,'2021-11-11 09:48:49','2021-11-11 09:48:49',NULL),(105,'grant','Adjudicar roles a usuarios',1,'2021-11-11 12:41:09','2021-11-11 12:41:09',NULL),(106,'ext','Usuarios externos de la Base de datos',1,'2021-11-23 14:51:16','2021-11-23 14:51:16',NULL),(107,'productionPlus','Creado para pepe por orden de Juanvi',1,'2022-02-08 06:47:10','2022-02-08 06:47:10',NULL),(108,'system','System user',1,'2022-05-16 08:09:51','2022-05-16 08:09:51',NULL),(109,'salesTeamBoss','Jefe de equipo de comerciales',1,'2022-06-14 13:45:56','2022-06-14 13:45:56',NULL),(110,'palletizer','Paletizadores',1,'2022-12-02 12:56:22','2022-12-02 12:56:30',NULL),(111,'entryEditor','Entry editor',1,'2023-01-13 11:21:55','2023-01-13 11:21:55',NULL),(112,'maintenance','Personal de mantenimiento',1,'2023-01-19 06:23:35','2023-01-19 06:23:35',NULL),(114,'maintenanceBos','Jefe de mantenimiento',1,'2023-01-19 06:31:16','2023-05-17 11:07:21',NULL),(115,'itManagement','TI management',1,'2023-03-29 07:27:55','2023-03-29 07:28:04',NULL),(119,'palletizerBoss','Jefe de paletizadores',1,'2023-06-07 11:51:54','2023-06-07 11:51:54',NULL),(120,'developerBoss','Jefe de proyecto de desarrollo',1,'2023-06-19 07:07:21','2023-06-19 07:07:21',21709),(121,'buyerSalesAssistant','Rol para compradores que también son responsables de ventas',1,'2023-06-23 14:48:19','2023-06-23 14:48:19',NULL),(122,'logisticAssistant','Jefe auxiliar de logística',1,'2023-06-26 07:21:15','2023-06-26 07:21:15',NULL); +INSERT INTO `role` VALUES (1,'employee','Empleado básico',1,'2017-05-19 07:04:58','2023-06-08 16:47:57',NULL),(2,'customer','Privilegios básicos de un cliente',1,'2017-05-19 07:04:58','2023-06-02 20:33:28',NULL),(3,'agency','Consultar tablas de predicciones de bultos',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(5,'administrative','Tareas relacionadas con la contabilidad',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(6,'guest','Privilegios para usuarios sin cuenta',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(9,'developer','Desarrolladores del sistema',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(11,'account','Privilegios relacionados con el login',0,'2017-05-19 07:04:58','2017-09-20 17:06:35',NULL),(13,'teamBoss','Jefe de equipo/departamento',1,'2017-05-19 07:04:58','2021-06-30 13:29:30',NULL),(15,'logistic','Departamento de compras, responsables de la logistica',1,'2017-05-19 07:04:58','2018-02-12 10:50:10',NULL),(16,'logisticBoss','Jefe del departamento de logística',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(17,'adminBoss','Jefe del departamento de administración',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(18,'salesPerson','Departamento de ventas',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(19,'salesBoss','Jefe del departamento de ventas',1,'2017-05-19 07:04:58','2017-08-16 12:38:27',NULL),(20,'manager','Gerencia',1,'2017-06-01 14:57:02','2022-07-29 07:36:15',NULL),(21,'salesAssistant','Jefe auxiliar de ventas',1,'2017-08-16 12:40:52','2017-08-16 12:40:52',NULL),(22,'teamManager','Jefe de departamento con privilegios de auxiliar de venta.',1,'2017-09-07 09:08:12','2017-09-07 09:08:12',NULL),(30,'financialBoss','Director finaciero',1,'2017-09-21 11:05:36','2017-09-21 11:05:36',NULL),(31,'freelancer','Trabajadores por cuenta ajena',1,'2017-10-10 12:57:26','2017-10-10 12:59:27',NULL),(32,'ett','Trabajadores de empresa temporal',1,'2017-10-10 12:58:58','2017-10-10 12:59:20',NULL),(33,'invoicing','Personal con acceso a facturación',0,'2018-01-29 16:43:34','2018-01-29 16:43:34',NULL),(34,'agencyBoss','Jefe/a del departamento de agencias',1,'2018-01-29 16:44:39','2018-02-23 07:58:53',NULL),(35,'buyer','Departamento de compras',1,'2018-02-12 10:35:42','2018-02-12 10:35:42',NULL),(36,'replenisher','Trabajadores de camara',1,'2018-02-16 14:07:10','2019-04-12 05:38:08',NULL),(37,'hr','Gestor/a de recursos humanos',1,'2018-02-22 17:34:53','2018-02-22 17:34:53',NULL),(38,'hrBoss','Jefe/a de recursos humanos',1,'2018-02-22 17:35:09','2018-02-22 17:35:09',NULL),(39,'adminAssistant','Jefe auxiliar administrativo',1,'2018-02-23 10:37:36','2018-02-23 10:38:41',NULL),(40,'handmade','Departamento de confección',1,'2018-02-23 11:14:53','2018-02-23 11:39:12',NULL),(41,'handmadeBoss','Jefe de departamento de confección',1,'2018-02-23 11:15:09','2018-02-23 11:39:26',NULL),(42,'artificial','Departamento de artificial',1,'2018-02-23 11:39:59','2018-02-23 11:39:59',NULL),(43,'artificialBoss','Jefe del departamento de artificial',1,'2018-02-23 11:40:16','2018-02-23 11:40:16',NULL),(44,'accessory','Departamento de complementos',1,'2018-02-23 11:41:12','2018-02-23 11:41:12',NULL),(45,'accessoryBoss','Jefe del departamento de complementos',1,'2018-02-23 11:41:23','2018-02-23 11:41:23',NULL),(47,'cooler','Empleados de cámara',1,'2018-02-23 13:08:18','2018-02-23 13:08:18',NULL),(48,'coolerBoss','Jefe de cámara',1,'2018-02-23 13:12:01','2023-03-13 08:49:43',NULL),(49,'production','Empleado de producción',1,'2018-02-26 15:28:23','2021-02-12 09:42:35',NULL),(50,'productionBoss','Jefe de producción',1,'2018-02-26 15:34:12','2018-02-26 15:34:12',NULL),(51,'marketing','Departamento de marketing',1,'2018-03-01 07:28:39','2018-03-01 07:28:39',NULL),(52,'marketingBoss','Jefe del departamento de marketing',1,'2018-03-01 07:28:57','2018-03-01 07:28:57',NULL),(53,'insurance','Gestor de seguros de cambio',0,'2018-03-05 07:44:35','2019-02-01 13:47:57',NULL),(54,'itemPicker','Sacador en cámara',1,'2018-03-05 12:08:17','2018-03-05 12:08:17',NULL),(55,'itemPickerBoss','Jefe de sacadores',1,'2018-03-05 12:08:31','2018-03-05 12:08:31',NULL),(56,'delivery','Personal de reparto',1,'2018-05-30 06:07:02','2018-05-30 06:07:02',NULL),(57,'deliveryBoss','Jefe de personal de reparto',1,'2018-05-30 06:07:19','2018-05-30 06:07:19',NULL),(58,'packager','Departamento encajadores',1,'2019-01-21 12:43:45','2019-01-21 12:43:45',NULL),(59,'packagerBoss','Jefe departamento encajadores',1,'2019-01-21 12:44:10','2019-01-21 12:44:10',NULL),(60,'productionAssi','Tareas relacionadas con producción y administración',1,'2019-01-29 13:29:01','2019-01-29 13:29:01',NULL),(61,'replenisherBos','Jefe de Complementos/Camara',1,'2019-07-01 06:44:07','2019-07-01 06:44:07',NULL),(62,'noLogin','Role without login access to MySQL',0,'2019-07-01 06:50:19','2019-07-02 13:42:05',NULL),(64,'balanceSheet','Consulta de Balance',0,'2019-07-16 12:12:08','2019-07-16 12:12:08',NULL),(65,'officeBoss','Jefe de filial',1,'2019-08-02 06:54:26','2019-08-02 06:54:26',NULL),(66,'sysadmin','Administrador de sistema',1,'2019-08-08 06:58:56','2019-08-08 06:58:56',NULL),(67,'adminOfficer','categoria profesional oficial de administración',1,'2020-01-03 08:09:23','2020-01-03 08:09:23',NULL),(69,'coolerAssist','Asistente de cámara con permiso compras',1,'2020-02-05 12:36:09','2023-03-13 08:50:07',NULL),(70,'trainee','Alumno de prácticas',1,'2020-03-04 11:00:25','2020-03-04 11:00:25',NULL),(71,'checker','Rol de revisor con privilegios de itemPicker',1,'2020-10-02 10:50:07','2020-10-02 10:50:07',NULL),(72,'claimManager','Personal de reclamaciones',1,'2020-10-13 10:01:32','2020-10-26 07:29:46',NULL),(73,'financial','Departamento de finanzas',1,'2020-11-16 09:30:27','2020-11-16 09:30:27',NULL),(74,'userPhotos','Privilegios para subir fotos de usuario',1,'2021-02-03 10:24:27','2021-02-03 10:24:27',NULL),(75,'catalogPhotos','Privilegios para subir fotos del catálogo',1,'2021-02-03 10:24:27','2021-02-03 10:24:27',NULL),(76,'chat','Rol para utilizar el rocket chat',1,'2020-11-27 13:06:50','2020-12-17 07:49:41',NULL),(100,'root','Rol con todos los privilegios',0,'2018-04-23 14:33:36','2020-11-12 06:50:07',NULL),(101,'buyerBoss','Jefe del departamento de compras',1,'2021-06-16 09:53:17','2021-06-16 09:53:17',NULL),(102,'preservedBoss','Responsable preservado',1,'2021-09-14 13:45:37','2021-09-14 13:45:37',NULL),(103,'it','Departamento de informática',1,'2021-11-11 09:48:22','2021-11-11 09:48:22',NULL),(104,'itBoss','Jefe de departamento de informática',1,'2021-11-11 09:48:49','2021-11-11 09:48:49',NULL),(105,'grant','Adjudicar roles a usuarios',1,'2021-11-11 12:41:09','2021-11-11 12:41:09',NULL),(106,'ext','Usuarios externos de la Base de datos',1,'2021-11-23 14:51:16','2021-11-23 14:51:16',NULL),(107,'productionPlus','Creado para pepe por orden de Juanvi',1,'2022-02-08 06:47:10','2022-02-08 06:47:10',NULL),(108,'system','System user',1,'2022-05-16 08:09:51','2022-05-16 08:09:51',NULL),(109,'salesTeamBoss','Jefe de equipo de comerciales',1,'2022-06-14 13:45:56','2022-06-14 13:45:56',NULL),(110,'palletizer','Paletizadores',1,'2022-12-02 12:56:22','2022-12-02 12:56:30',NULL),(111,'entryEditor','Entry editor',1,'2023-01-13 11:21:55','2023-01-13 11:21:55',NULL),(112,'maintenance','Personal de mantenimiento',1,'2023-01-19 06:23:35','2023-01-19 06:23:35',NULL),(114,'maintenanceBos','Jefe de mantenimiento',1,'2023-01-19 06:31:16','2023-05-17 11:07:21',NULL),(115,'itManagement','TI management',1,'2023-03-29 07:27:55','2023-03-29 07:28:04',NULL),(119,'palletizerBoss','Jefe de paletizadores',1,'2023-06-07 11:51:54','2023-06-07 11:51:54',NULL),(120,'developerBoss','Jefe de proyecto de desarrollo',1,'2023-06-19 07:07:21','2023-06-19 07:07:21',21709),(121,'buyerSalesAssistant','Rol para compradores que también son responsables de ventas',1,'2023-06-23 14:48:19','2023-06-23 14:48:19',NULL),(122,'logisticAssistant','Jefe auxiliar de logística',1,'2023-06-26 07:21:15','2023-06-26 07:21:15',NULL); /*!40000 ALTER TABLE `role` ENABLE KEYS */; UNLOCK TABLES; @@ -164,7 +164,7 @@ USE `salix`; LOCK TABLES `ACL` WRITE; /*!40000 ALTER TABLE `ACL` DISABLE KEYS */; -INSERT INTO `ACL` VALUES (3,'Address','*','*','ALLOW','ROLE','employee'),(5,'AgencyService','*','READ','ALLOW','ROLE','employee'),(9,'ClientObservation','*','*','ALLOW','ROLE','employee'),(11,'ContactChannel','*','READ','ALLOW','ROLE','trainee'),(13,'Employee','*','READ','ALLOW','ROLE','employee'),(14,'PayMethod','*','READ','ALLOW','ROLE','trainee'),(16,'FakeProduction','*','READ','ALLOW','ROLE','employee'),(17,'Warehouse','* ','READ','ALLOW','ROLE','trainee'),(20,'TicketState','*','*','ALLOW','ROLE','employee'),(24,'Delivery','*','READ','ALLOW','ROLE','employee'),(25,'Zone','*','READ','ALLOW','ROLE','employee'),(26,'ClientCredit','*','*','ALLOW','ROLE','employee'),(27,'ClientCreditLimit','*','READ','ALLOW','ROLE','trainee'),(30,'GreugeType','*','READ','ALLOW','ROLE','trainee'),(31,'Mandate','*','READ','ALLOW','ROLE','trainee'),(32,'MandateType','*','READ','ALLOW','ROLE','trainee'),(33,'Company','*','READ','ALLOW','ROLE','trainee'),(34,'Greuge','*','READ','ALLOW','ROLE','trainee'),(35,'AddressObservation','*','*','ALLOW','ROLE','employee'),(36,'ObservationType','*','*','ALLOW','ROLE','employee'),(37,'Greuge','*','WRITE','ALLOW','ROLE','employee'),(38,'AgencyMode','*','READ','ALLOW','ROLE','employee'),(39,'ItemTag','*','WRITE','ALLOW','ROLE','buyer'),(40,'ItemBotanical','*','WRITE','ALLOW','ROLE','buyer'),(41,'ItemBotanical','*','READ','ALLOW','ROLE','employee'),(42,'ItemPlacement','*','WRITE','ALLOW','ROLE','buyer'),(43,'ItemPlacement','*','WRITE','ALLOW','ROLE','replenisher'),(44,'ItemPlacement','*','READ','ALLOW','ROLE','employee'),(45,'ItemBarcode','*','READ','ALLOW','ROLE','employee'),(46,'ItemBarcode','*','WRITE','ALLOW','ROLE','buyer'),(47,'ItemBarcode','*','WRITE','ALLOW','ROLE','replenisher'),(51,'ItemTag','*','READ','ALLOW','ROLE','employee'),(53,'Item','*','READ','ALLOW','ROLE','employee'),(54,'Item','*','WRITE','ALLOW','ROLE','buyer'),(55,'Recovery','*','READ','ALLOW','ROLE','trainee'),(56,'Recovery','*','WRITE','ALLOW','ROLE','administrative'),(58,'CreditClassification','*','*','ALLOW','ROLE','insurance'),(60,'CreditInsurance','*','*','ALLOW','ROLE','insurance'),(61,'InvoiceOut','*','READ','ALLOW','ROLE','employee'),(63,'TicketObservation','*','*','ALLOW','ROLE','employee'),(64,'Route','*','READ','ALLOW','ROLE','employee'),(65,'Sale','*','READ','ALLOW','ROLE','employee'),(66,'TicketTracking','*','READ','ALLOW','ROLE','employee'),(68,'TicketPackaging','*','*','ALLOW','ROLE','employee'),(69,'Packaging','*','READ','ALLOW','ROLE','employee'),(70,'Packaging','*','WRITE','ALLOW','ROLE','logistic'),(72,'SaleComponent','*','READ','ALLOW','ROLE','employee'),(73,'Expedition','*','READ','ALLOW','ROLE','employee'),(74,'Expedition','*','WRITE','ALLOW','ROLE','deliveryAssistant'),(75,'Expedition','*','WRITE','ALLOW','ROLE','production'),(76,'AnnualAverageInvoiced','*','READ','ALLOW','ROLE','employee'),(77,'WorkerMana','*','READ','ALLOW','ROLE','employee'),(78,'TicketTracking','*','WRITE','ALLOW','ROLE','production'),(79,'TicketTracking','changeState','*','ALLOW','ROLE','employee'),(80,'Sale','deleteSales','*','ALLOW','ROLE','employee'),(81,'Sale','moveToTicket','*','ALLOW','ROLE','employee'),(82,'Sale','updateQuantity','*','ALLOW','ROLE','employee'),(83,'Sale','updatePrice','*','ALLOW','ROLE','employee'),(84,'Sale','updateDiscount','*','ALLOW','ROLE','employee'),(85,'SaleTracking','*','READ','ALLOW','ROLE','employee'),(86,'Order','*','*','ALLOW','ROLE','employee'),(87,'OrderRow','*','*','ALLOW','ROLE','employee'),(88,'ClientContact','*','*','ALLOW','ROLE','employee'),(89,'Sale','moveToNewTicket','*','ALLOW','ROLE','employee'),(90,'Sale','reserve','*','ALLOW','ROLE','employee'),(91,'TicketWeekly','*','READ','ALLOW','ROLE','employee'),(94,'Agency','landsThatDay','*','ALLOW','ROLE','employee'),(96,'ClaimEnd','*','READ','ALLOW','ROLE','employee'),(97,'ClaimEnd','*','WRITE','ALLOW','ROLE','claimManager'),(98,'ClaimBeginning','*','*','ALLOW','ROLE','employee'),(99,'ClaimDevelopment','*','READ','ALLOW','ROLE','employee'),(100,'ClaimDevelopment','*','WRITE','ALLOW','ROLE','claimManager'),(102,'Claim','createFromSales','*','ALLOW','ROLE','employee'),(104,'Item','*','WRITE','ALLOW','ROLE','marketingBoss'),(105,'ItemBarcode','*','WRITE','ALLOW','ROLE','marketingBoss'),(106,'ItemBotanical','*','WRITE','ALLOW','ROLE','marketingBoss'),(108,'ItemPlacement','*','WRITE','ALLOW','ROLE','marketingBoss'),(109,'UserConfig','*','*','ALLOW','ROLE','employee'),(110,'Bank','*','READ','ALLOW','ROLE','trainee'),(111,'ClientLog','*','READ','ALLOW','ROLE','trainee'),(112,'Defaulter','*','READ','ALLOW','ROLE','employee'),(113,'ClientRisk','*','READ','ALLOW','ROLE','trainee'),(114,'Receipt','*','READ','ALLOW','ROLE','trainee'),(115,'Receipt','*','WRITE','ALLOW','ROLE','administrative'),(116,'BankEntity','*','*','ALLOW','ROLE','employee'),(117,'ClientSample','*','*','ALLOW','ROLE','employee'),(118,'WorkerTeam','*','*','ALLOW','ROLE','salesPerson'),(119,'Travel','*','READ','ALLOW','ROLE','employee'),(120,'Travel','*','WRITE','ALLOW','ROLE','buyer'),(121,'Item','regularize','*','ALLOW','ROLE','employee'),(122,'TicketRequest','*','*','ALLOW','ROLE','employee'),(124,'Client','confirmTransaction','WRITE','ALLOW','ROLE','administrative'),(125,'Agency','getAgenciesWithWarehouse','*','ALLOW','ROLE','employee'),(126,'Client','activeWorkersWithRole','*','ALLOW','ROLE','employee'),(127,'TicketLog','*','READ','ALLOW','ROLE','employee'),(129,'TicketService','*','*','ALLOW','ROLE','employee'),(130,'Expedition','*','WRITE','ALLOW','ROLE','packager'),(131,'CreditInsurance','*','READ','ALLOW','ROLE','trainee'),(132,'CreditClassification','*','READ','ALLOW','ROLE','trainee'),(133,'ItemTag','*','WRITE','ALLOW','ROLE','marketingBoss'),(135,'ZoneGeo','*','READ','ALLOW','ROLE','employee'),(136,'ZoneCalendar','*','READ','ALLOW','ROLE','employee'),(137,'ZoneIncluded','*','READ','ALLOW','ROLE','employee'),(138,'LabourHoliday','*','READ','ALLOW','ROLE','employee'),(139,'LabourHolidayLegend','*','READ','ALLOW','ROLE','employee'),(140,'LabourHolidayType','*','READ','ALLOW','ROLE','employee'),(141,'Zone','*','*','ALLOW','ROLE','logisticBoss'),(142,'ZoneCalendar','*','WRITE','ALLOW','ROLE','deliveryAssistant'),(143,'ZoneIncluded','*','*','ALLOW','ROLE','deliveryAssistant'),(144,'Stowaway','*','*','ALLOW','ROLE','employee'),(145,'Ticket','getPossibleStowaways','READ','ALLOW','ROLE','employee'),(147,'UserConfigView','*','*','ALLOW','ROLE','employee'),(148,'UserConfigView','*','*','ALLOW','ROLE','employee'),(149,'Sip','*','READ','ALLOW','ROLE','employee'),(150,'Sip','*','WRITE','ALLOW','ROLE','hr'),(151,'Department','*','READ','ALLOW','ROLE','employee'),(152,'Department','*','WRITE','ALLOW','ROLE','hr'),(153,'Route','*','READ','ALLOW','ROLE','employee'),(154,'Route','*','WRITE','ALLOW','ROLE','delivery'),(155,'Calendar','*','READ','ALLOW','ROLE','hr'),(156,'WorkerLabour','*','READ','ALLOW','ROLE','hr'),(157,'Calendar','absences','READ','ALLOW','ROLE','employee'),(158,'ItemTag','*','WRITE','ALLOW','ROLE','accessory'),(160,'TicketServiceType','*','READ','ALLOW','ROLE','employee'),(161,'TicketConfig','*','READ','ALLOW','ROLE','employee'),(162,'InvoiceOut','delete','WRITE','ALLOW','ROLE','invoicing'),(163,'InvoiceOut','book','WRITE','ALLOW','ROLE','invoicing'),(165,'TicketDms','*','*','ALLOW','ROLE','employee'),(167,'Worker','isSubordinate','READ','ALLOW','ROLE','employee'),(168,'Worker','mySubordinates','READ','ALLOW','ROLE','employee'),(169,'WorkerTimeControl','filter','READ','ALLOW','ROLE','employee'),(170,'WorkerTimeControl','addTime','WRITE','ALLOW','ROLE','employee'),(171,'TicketServiceType','*','WRITE','ALLOW','ROLE','administrative'),(172,'Sms','*','READ','ALLOW','ROLE','employee'),(173,'Sms','send','WRITE','ALLOW','ROLE','employee'),(176,'Device','*','*','ALLOW','ROLE','employee'),(177,'Device','*','*','ALLOW','ROLE','employee'),(178,'WorkerTimeControl','*','*','ALLOW','ROLE','employee'),(179,'ItemLog','*','READ','ALLOW','ROLE','employee'),(180,'RouteLog','*','READ','ALLOW','ROLE','employee'),(181,'Dms','removeFile','WRITE','ALLOW','ROLE','employee'),(182,'Dms','uploadFile','WRITE','ALLOW','ROLE','employee'),(183,'Dms','downloadFile','READ','ALLOW','ROLE','employee'),(184,'Client','uploadFile','WRITE','ALLOW','ROLE','employee'),(185,'ClientDms','removeFile','WRITE','ALLOW','ROLE','employee'),(186,'ClientDms','*','READ','ALLOW','ROLE','trainee'),(187,'Ticket','uploadFile','WRITE','ALLOW','ROLE','employee'),(190,'Route','updateVolume','WRITE','ALLOW','ROLE','deliveryAssistant'),(191,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(192,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(194,'Postcode','*','WRITE','ALLOW','ROLE','deliveryAssistant'),(195,'Ticket','addSale','WRITE','ALLOW','ROLE','employee'),(196,'Dms','updateFile','WRITE','ALLOW','ROLE','employee'),(197,'Dms','*','READ','ALLOW','ROLE','trainee'),(198,'ClaimDms','removeFile','WRITE','ALLOW','ROLE','employee'),(199,'ClaimDms','*','READ','ALLOW','ROLE','employee'),(200,'Claim','uploadFile','WRITE','ALLOW','ROLE','employee'),(201,'Sale','updateConcept','WRITE','ALLOW','ROLE','employee'),(202,'Claim','updateClaimAction','WRITE','ALLOW','ROLE','claimManager'),(203,'UserPhone','*','*','ALLOW','ROLE','employee'),(204,'WorkerDms','removeFile','WRITE','ALLOW','ROLE','hr'),(205,'WorkerDms','*','READ','ALLOW','ROLE','hr'),(206,'Chat','*','*','ALLOW','ROLE','employee'),(207,'Chat','sendMessage','*','ALLOW','ROLE','employee'),(208,'Sale','recalculatePrice','WRITE','ALLOW','ROLE','employee'),(209,'Ticket','recalculateComponents','WRITE','ALLOW','ROLE','employee'),(211,'TravelLog','*','READ','ALLOW','ROLE','buyer'),(212,'Thermograph','*','*','ALLOW','ROLE','buyer'),(213,'TravelThermograph','*','WRITE','ALLOW','ROLE','buyer'),(214,'Entry','*','*','ALLOW','ROLE','buyer'),(215,'TicketWeekly','*','WRITE','ALLOW','ROLE','buyer'),(216,'TravelThermograph','*','READ','ALLOW','ROLE','employee'),(218,'Intrastat','*','*','ALLOW','ROLE','buyer'),(221,'UserConfig','getUserConfig','READ','ALLOW','ROLE','account'),(222,'Client','*','READ','ALLOW','ROLE','trainee'),(226,'ClientObservation','*','READ','ALLOW','ROLE','trainee'),(227,'Address','*','READ','ALLOW','ROLE','trainee'),(228,'AddressObservation','*','READ','ALLOW','ROLE','trainee'),(230,'ClientCredit','*','READ','ALLOW','ROLE','trainee'),(231,'ClientContact','*','READ','ALLOW','ROLE','trainee'),(232,'ClientSample','*','READ','ALLOW','ROLE','trainee'),(233,'EntryLog','*','READ','ALLOW','ROLE','buyer'),(234,'WorkerLog','find','READ','ALLOW','ROLE','hr'),(235,'CustomsAgent','*','*','ALLOW','ROLE','employee'),(236,'Buy','*','*','ALLOW','ROLE','buyer'),(237,'WorkerDms','filter','*','ALLOW','ROLE','employee'),(238,'Town','*','WRITE','ALLOW','ROLE','deliveryAssistant'),(239,'Province','*','WRITE','ALLOW','ROLE','deliveryAssistant'),(240,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(241,'SupplierContact','*','WRITE','ALLOW','ROLE','administrative'),(242,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(244,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(248,'RoleMapping','*','READ','ALLOW','ROLE','account'),(249,'UserPassword','*','READ','ALLOW','ROLE','account'),(250,'Town','*','WRITE','ALLOW','ROLE','deliveryAssistant'),(251,'Province','*','WRITE','ALLOW','ROLE','deliveryAssistant'),(252,'Supplier','*','READ','ALLOW','ROLE','employee'),(253,'Supplier','*','WRITE','ALLOW','ROLE','administrative'),(254,'SupplierLog','*','READ','ALLOW','ROLE','employee'),(256,'Image','*','WRITE','ALLOW','ROLE','employee'),(257,'FixedPrice','*','*','ALLOW','ROLE','buyer'),(258,'PayDem','*','READ','ALLOW','ROLE','employee'),(259,'Client','createReceipt','*','ALLOW','ROLE','salesAssistant'),(260,'PrintServerQueue','*','WRITE','ALLOW','ROLE','employee'),(261,'SupplierAccount','*','*','ALLOW','ROLE','administrative'),(262,'Entry','*','*','ALLOW','ROLE','administrative'),(263,'InvoiceIn','*','*','ALLOW','ROLE','administrative'),(264,'StarredModule','*','*','ALLOW','ROLE','employee'),(265,'ItemBotanical','*','WRITE','ALLOW','ROLE','logisticBoss'),(266,'ZoneLog','*','READ','ALLOW','ROLE','employee'),(267,'Genus','*','WRITE','ALLOW','ROLE','logisticBoss'),(268,'Specie','*','WRITE','ALLOW','ROLE','logisticBoss'),(269,'InvoiceOut','createPdf','WRITE','ALLOW','ROLE','employee'),(270,'SupplierAddress','*','*','ALLOW','ROLE','employee'),(271,'SalesMonitor','*','*','ALLOW','ROLE','employee'),(272,'InvoiceInLog','*','READ','ALLOW','ROLE','employee'),(273,'InvoiceInTax','*','*','ALLOW','ROLE','administrative'),(274,'InvoiceInLog','*','READ','ALLOW','ROLE','administrative'),(275,'InvoiceOut','createManualInvoice','WRITE','ALLOW','ROLE','invoicing'),(276,'InvoiceOut','globalInvoicing','WRITE','ALLOW','ROLE','invoicing'),(278,'RoleInherit','*','WRITE','ALLOW','ROLE','grant'),(279,'MailAlias','*','*','ALLOW','ROLE','marketing'),(283,'EntryObservation','*','*','ALLOW','ROLE','buyer'),(284,'LdapConfig','*','*','ALLOW','ROLE','sysadmin'),(285,'SambaConfig','*','*','ALLOW','ROLE','sysadmin'),(286,'ACL','*','*','ALLOW','ROLE','developer'),(287,'AccessToken','*','*','ALLOW','ROLE','developer'),(293,'RoleInherit','*','*','ALLOW','ROLE','it'),(294,'RoleRole','*','*','ALLOW','ROLE','it'),(295,'AccountConfig','*','*','ALLOW','ROLE','sysadmin'),(296,'Collection','*','READ','ALLOW','ROLE','employee'),(297,'Sale','refund','WRITE','ALLOW','ROLE','invoicing'),(298,'InvoiceInDueDay','*','*','ALLOW','ROLE','administrative'),(299,'Collection','setSaleQuantity','*','ALLOW','ROLE','employee'),(302,'AgencyTerm','*','*','ALLOW','ROLE','administrative'),(303,'ClaimLog','*','READ','ALLOW','ROLE','claimManager'),(304,'Edi','updateData','WRITE','ALLOW','ROLE','employee'),(305,'EducationLevel','*','*','ALLOW','ROLE','employee'),(306,'InvoiceInIntrastat','*','*','ALLOW','ROLE','employee'),(307,'SupplierAgencyTerm','*','*','ALLOW','ROLE','administrative'),(308,'InvoiceInIntrastat','*','*','ALLOW','ROLE','employee'),(309,'Zone','getZoneClosing','*','ALLOW','ROLE','employee'),(310,'ExpeditionState','*','READ','ALLOW','ROLE','employee'),(311,'Expense','*','READ','ALLOW','ROLE','employee'),(312,'Expense','*','WRITE','ALLOW','ROLE','administrative'),(314,'SupplierActivity','*','READ','ALLOW','ROLE','employee'),(315,'SupplierActivity','*','WRITE','ALLOW','ROLE','administrative'),(316,'Dms','deleteTrashFiles','WRITE','ALLOW','ROLE','employee'),(317,'ClientUnpaid','*','*','ALLOW','ROLE','administrative'),(318,'MdbVersion','*','*','ALLOW','ROLE','developer'),(319,'ItemType','*','READ','ALLOW','ROLE','employee'),(320,'ItemType','*','WRITE','ALLOW','ROLE','buyer'),(321,'InvoiceOut','refund','WRITE','ALLOW','ROLE','invoicing'),(322,'InvoiceOut','refund','WRITE','ALLOW','ROLE','salesAssistant'),(323,'InvoiceOut','refund','WRITE','ALLOW','ROLE','claimManager'),(324,'Ticket','refund','WRITE','ALLOW','ROLE','invoicing'),(325,'Ticket','refund','WRITE','ALLOW','ROLE','salesAssistant'),(326,'Ticket','refund','WRITE','ALLOW','ROLE','claimManager'),(327,'Sale','refund','WRITE','ALLOW','ROLE','salesAssistant'),(328,'Sale','refund','WRITE','ALLOW','ROLE','claimManager'),(329,'TicketRefund','*','WRITE','ALLOW','ROLE','invoicing'),(330,'ClaimObservation','*','WRITE','ALLOW','ROLE','salesPerson'),(331,'ClaimObservation','*','READ','ALLOW','ROLE','salesPerson'),(332,'Client','setPassword','WRITE','ALLOW','ROLE','salesPerson'),(333,'Client','updateUser','WRITE','ALLOW','ROLE','salesPerson'),(334,'ShelvingLog','*','READ','ALLOW','ROLE','employee'),(335,'ZoneExclusionGeo','*','READ','ALLOW','ROLE','employee'),(336,'ZoneExclusionGeo','*','WRITE','ALLOW','ROLE','deliveryAssistant'),(337,'Parking','*','*','ALLOW','ROLE','employee'),(338,'Shelving','*','*','ALLOW','ROLE','employee'),(339,'OsTicket','*','*','ALLOW','ROLE','employee'),(340,'OsTicketConfig','*','*','ALLOW','ROLE','it'),(341,'ClientConsumptionQueue','*','WRITE','ALLOW','ROLE','employee'),(342,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','employee'),(343,'Ticket','deliveryNoteEmail','WRITE','ALLOW','ROLE','employee'),(344,'Ticket','deliveryNoteCsvPdf','READ','ALLOW','ROLE','employee'),(345,'Ticket','deliveryNoteCsvEmail','READ','ALLOW','ROLE','employee'),(346,'Client','campaignMetricsPdf','READ','ALLOW','ROLE','employee'),(347,'Client','campaignMetricsEmail','WRITE','ALLOW','ROLE','employee'),(348,'Client','clientWelcomeHtml','READ','ALLOW','ROLE','employee'),(349,'Client','clientWelcomeEmail','WRITE','ALLOW','ROLE','employee'),(350,'Client','creditRequestPdf','READ','ALLOW','ROLE','employee'),(351,'Client','creditRequestHtml','READ','ALLOW','ROLE','employee'),(352,'Client','creditRequestEmail','WRITE','ALLOW','ROLE','employee'),(353,'Client','printerSetupHtml','READ','ALLOW','ROLE','employee'),(354,'Client','printerSetupEmail','WRITE','ALLOW','ROLE','employee'),(355,'Client','sepaCoreEmail','WRITE','ALLOW','ROLE','employee'),(356,'Client','letterDebtorPdf','READ','ALLOW','ROLE','employee'),(357,'Client','letterDebtorStHtml','READ','ALLOW','ROLE','employee'),(358,'Client','letterDebtorStEmail','WRITE','ALLOW','ROLE','employee'),(359,'Client','letterDebtorNdHtml','READ','ALLOW','ROLE','employee'),(360,'Client','letterDebtorNdEmail','WRITE','ALLOW','ROLE','employee'),(361,'Client','clientDebtStatementPdf','READ','ALLOW','ROLE','employee'),(362,'Client','clientDebtStatementHtml','READ','ALLOW','ROLE','employee'),(363,'Client','clientDebtStatementEmail','WRITE','ALLOW','ROLE','employee'),(364,'Client','incotermsAuthorizationPdf','READ','ALLOW','ROLE','employee'),(365,'Client','incotermsAuthorizationHtml','READ','ALLOW','ROLE','employee'),(366,'Client','incotermsAuthorizationEmail','WRITE','ALLOW','ROLE','employee'),(367,'Client','consumptionSendQueued','WRITE','ALLOW','ROLE','system'),(368,'InvoiceOut','invoiceEmail','WRITE','ALLOW','ROLE','employee'),(369,'InvoiceOut','exportationPdf','READ','ALLOW','ROLE','employee'),(370,'InvoiceOut','sendQueued','WRITE','ALLOW','ROLE','system'),(371,'Ticket','invoiceCsvPdf','READ','ALLOW','ROLE','employee'),(372,'Ticket','invoiceCsvEmail','WRITE','ALLOW','ROLE','employee'),(373,'Supplier','campaignMetricsPdf','READ','ALLOW','ROLE','employee'),(374,'Supplier','campaignMetricsEmail','WRITE','ALLOW','ROLE','employee'),(375,'Travel','extraCommunityPdf','READ','ALLOW','ROLE','employee'),(376,'Travel','extraCommunityEmail','WRITE','ALLOW','ROLE','employee'),(377,'Entry','entryOrderPdf','READ','ALLOW','ROLE','employee'),(378,'OsTicket','osTicketReportEmail','WRITE','ALLOW','ROLE','system'),(379,'Item','buyerWasteEmail','WRITE','ALLOW','ROLE','system'),(380,'Claim','claimPickupPdf','READ','ALLOW','ROLE','employee'),(381,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','claimManager'),(382,'Item','labelPdf','READ','ALLOW','ROLE','employee'),(383,'Sector','*','READ','ALLOW','ROLE','employee'),(384,'Sector','*','WRITE','ALLOW','ROLE','employee'),(385,'Route','driverRoutePdf','READ','ALLOW','ROLE','employee'),(386,'Route','driverRouteEmail','WRITE','ALLOW','ROLE','employee'),(387,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','customer'),(388,'Supplier','newSupplier','WRITE','ALLOW','ROLE','administrative'),(389,'ClaimRma','*','READ','ALLOW','ROLE','claimManager'),(390,'ClaimRma','*','WRITE','ALLOW','ROLE','claimManager'),(391,'Notification','*','WRITE','ALLOW','ROLE','system'),(392,'Boxing','*','*','ALLOW','ROLE','employee'),(393,'Url','*','READ','ALLOW','ROLE','employee'),(394,'Url','*','WRITE','ALLOW','ROLE','it'),(395,'ItemShelving','*','READ','ALLOW','ROLE','employee'),(396,'ItemShelving','*','WRITE','ALLOW','ROLE','production'),(397,'ItemShelvingPlacementSupplyStock','*','READ','ALLOW','ROLE','employee'),(398,'NotificationQueue','*','*','ALLOW','ROLE','employee'),(399,'InvoiceOut','clientsToInvoice','WRITE','ALLOW','ROLE','invoicing'),(400,'InvoiceOut','invoiceClient','WRITE','ALLOW','ROLE','invoicing'),(401,'Sale','editTracked','WRITE','ALLOW','ROLE','production'),(402,'Sale','editFloramondo','WRITE','ALLOW','ROLE','salesAssistant'),(403,'Receipt','balanceCompensationEmail','WRITE','ALLOW','ROLE','employee'),(404,'Receipt','balanceCompensationPdf','READ','ALLOW','ROLE','employee'),(405,'Ticket','getTicketsFuture','READ','ALLOW','ROLE','employee'),(406,'Ticket','merge','WRITE','ALLOW','ROLE','employee'),(407,'Sale','editFloramondo','WRITE','ALLOW','ROLE','logistic'),(408,'ZipConfig','*','*','ALLOW','ROLE','employee'),(409,'Item','*','WRITE','ALLOW','ROLE','administrative'),(410,'Sale','editCloned','WRITE','ALLOW','ROLE','buyer'),(411,'Sale','editCloned','WRITE','ALLOW','ROLE','salesAssistant'),(414,'MdbVersion','*','READ','ALLOW','ROLE','$everyone'),(416,'TicketLog','getChanges','READ','ALLOW','ROLE','employee'),(417,'Ticket','getTicketsAdvance','READ','ALLOW','ROLE','employee'),(418,'EntryLog','*','READ','ALLOW','ROLE','administrative'),(419,'Sale','editTracked','WRITE','ALLOW','ROLE','buyer'),(420,'MdbBranch','*','READ','ALLOW','ROLE','$everyone'),(421,'ItemShelvingSale','*','*','ALLOW','ROLE','employee'),(422,'Docuware','checkFile','READ','ALLOW','ROLE','employee'),(423,'Docuware','download','READ','ALLOW','ROLE','salesPerson'),(424,'Docuware','upload','WRITE','ALLOW','ROLE','productionAssi'),(425,'Docuware','deliveryNoteEmail','WRITE','ALLOW','ROLE','salesPerson'),(426,'TpvTransaction','confirm','WRITE','ALLOW','ROLE','$everyone'),(427,'TpvTransaction','start','WRITE','ALLOW','ROLE','$authenticated'),(428,'TpvTransaction','end','WRITE','ALLOW','ROLE','$authenticated'),(429,'ItemConfig','*','READ','ALLOW','ROLE','employee'),(431,'Tag','onSubmit','WRITE','ALLOW','ROLE','employee'),(432,'Worker','updateAttributes','WRITE','ALLOW','ROLE','hr'),(433,'Worker','createAbsence','*','ALLOW','ROLE','employee'),(434,'Worker','updateAbsence','WRITE','ALLOW','ROLE','employee'),(435,'Worker','deleteAbsence','*','ALLOW','ROLE','employee'),(436,'Worker','new','WRITE','ALLOW','ROLE','hr'),(438,'Client','getClientOrSupplierReference','READ','ALLOW','ROLE','employee'),(439,'NotificationSubscription','*','*','ALLOW','ROLE','employee'),(440,'NotificationAcl','*','READ','ALLOW','ROLE','employee'),(441,'MdbApp','*','READ','ALLOW','ROLE','$everyone'),(442,'MdbApp','*','*','ALLOW','ROLE','developer'),(443,'ItemConfig','*','*','ALLOW','ROLE','employee'),(444,'DeviceProduction','*','*','ALLOW','ROLE','hr'),(445,'DeviceProductionModels','*','*','ALLOW','ROLE','hr'),(446,'DeviceProductionState','*','*','ALLOW','ROLE','hr'),(447,'DeviceProductionUser','*','*','ALLOW','ROLE','hr'),(448,'DeviceProduction','*','*','ALLOW','ROLE','productionAssi'),(449,'DeviceProductionModels','*','*','ALLOW','ROLE','productionAssi'),(450,'DeviceProductionState','*','*','ALLOW','ROLE','productionAssi'),(451,'DeviceProductionUser','*','*','ALLOW','ROLE','productionAssi'),(452,'Worker','deallocatePDA','*','ALLOW','ROLE','hr'),(453,'Worker','allocatePDA','*','ALLOW','ROLE','hr'),(454,'Worker','deallocatePDA','*','ALLOW','ROLE','productionAssi'),(455,'Worker','allocatePDA','*','ALLOW','ROLE','productionAssi'),(456,'Zone','*','*','ALLOW','ROLE','deliveryAssistant'),(457,'Account','setPassword','WRITE','ALLOW','ROLE','itManagement'),(458,'Operator','*','READ','ALLOW','ROLE','employee'),(459,'Operator','*','WRITE','ALLOW','ROLE','employee'),(460,'InvoiceIn','getSerial','READ','ALLOW','ROLE','administrative'),(461,'Ticket','saveSign','WRITE','ALLOW','ROLE','employee'),(462,'InvoiceOut','negativeBases','READ','ALLOW','ROLE','administrative'),(463,'InvoiceOut','negativeBasesCsv','READ','ALLOW','ROLE','administrative'),(464,'WorkerObservation','*','*','ALLOW','ROLE','hr'),(465,'ClientInforma','*','READ','ALLOW','ROLE','employee'),(466,'ClientInforma','*','WRITE','ALLOW','ROLE','financial'),(467,'Receipt','receiptEmail','*','ALLOW','ROLE','salesAssistant'),(468,'Client','setRating','WRITE','ALLOW','ROLE','financial'),(469,'Client','*','READ','ALLOW','ROLE','employee'),(470,'Client','addressesPropagateRe','*','ALLOW','ROLE','employee'),(471,'Client','canBeInvoiced','*','ALLOW','ROLE','employee'),(472,'Client','canCreateTicket','*','ALLOW','ROLE','employee'),(473,'Client','consumption','*','ALLOW','ROLE','employee'),(474,'Client','createAddress','*','ALLOW','ROLE','employee'),(475,'Client','createWithUser','*','ALLOW','ROLE','employee'),(476,'Client','extendedListFilter','*','ALLOW','ROLE','employee'),(477,'Client','getAverageInvoiced','*','ALLOW','ROLE','employee'),(478,'Client','getCard','*','ALLOW','ROLE','employee'),(479,'Client','getDebt','*','ALLOW','ROLE','employee'),(480,'Client','getMana','*','ALLOW','ROLE','employee'),(481,'Client','transactions','*','ALLOW','ROLE','employee'),(482,'Client','hasCustomerRole','*','ALLOW','ROLE','employee'),(483,'Client','isValidClient','*','ALLOW','ROLE','employee'),(484,'Client','lastActiveTickets','*','ALLOW','ROLE','employee'),(485,'Client','sendSms','*','ALLOW','ROLE','employee'),(486,'Client','setPassword','*','ALLOW','ROLE','employee'),(487,'Client','summary','*','ALLOW','ROLE','employee'),(488,'Client','updateAddress','*','ALLOW','ROLE','employee'),(489,'Client','updateFiscalData','*','ALLOW','ROLE','employee'),(491,'Client','uploadFile','*','ALLOW','ROLE','employee'),(492,'Client','campaignMetricsPdf','*','ALLOW','ROLE','employee'),(493,'Client','campaignMetricsEmail','*','ALLOW','ROLE','employee'),(494,'Client','clientWelcomeHtml','*','ALLOW','ROLE','employee'),(495,'Client','clientWelcomeEmail','*','ALLOW','ROLE','employee'),(496,'Client','printerSetupHtml','*','ALLOW','ROLE','employee'),(497,'Client','printerSetupEmail','*','ALLOW','ROLE','employee'),(498,'Client','sepaCoreEmail','*','ALLOW','ROLE','employee'),(499,'Client','letterDebtorPdf','*','ALLOW','ROLE','employee'),(500,'Client','letterDebtorStHtml','*','ALLOW','ROLE','employee'),(501,'Client','letterDebtorStEmail','*','ALLOW','ROLE','employee'),(502,'Client','letterDebtorNdHtml','*','ALLOW','ROLE','employee'),(503,'Client','letterDebtorNdEmail','*','ALLOW','ROLE','employee'),(504,'Client','clientDebtStatementPdf','*','ALLOW','ROLE','employee'),(505,'Client','clientDebtStatementHtml','*','ALLOW','ROLE','employee'),(506,'Client','clientDebtStatementEmail','*','ALLOW','ROLE','employee'),(507,'Client','creditRequestPdf','*','ALLOW','ROLE','employee'),(508,'Client','creditRequestHtml','*','ALLOW','ROLE','employee'),(509,'Client','creditRequestEmail','*','ALLOW','ROLE','employee'),(510,'Client','incotermsAuthorizationPdf','*','ALLOW','ROLE','employee'),(511,'Client','incotermsAuthorizationHtml','*','ALLOW','ROLE','employee'),(512,'Client','incotermsAuthorizationEmail','*','ALLOW','ROLE','employee'),(513,'Client','consumptionSendQueued','*','ALLOW','ROLE','employee'),(514,'Client','filter','*','ALLOW','ROLE','employee'),(515,'Client','getClientOrSupplierReference','*','ALLOW','ROLE','employee'),(516,'Client','upsert','*','ALLOW','ROLE','employee'),(517,'Client','create','*','ALLOW','ROLE','employee'),(518,'Client','replaceById','*','ALLOW','ROLE','employee'),(519,'Client','updateAttributes','*','ALLOW','ROLE','employee'),(520,'Client','updateAttributes','*','ALLOW','ROLE','employee'),(521,'Client','deleteById','*','ALLOW','ROLE','employee'),(522,'Client','replaceOrCreate','*','ALLOW','ROLE','employee'),(523,'Client','updateAll','*','ALLOW','ROLE','employee'),(524,'Client','upsertWithWhere','*','ALLOW','ROLE','employee'),(525,'Defaulter','observationEmail','WRITE','ALLOW','ROLE','employee'),(527,'VnUser','acl','READ','ALLOW','ROLE','account'),(528,'VnUser','getCurrentUserData','READ','ALLOW','ROLE','account'),(530,'Account','exists','READ','ALLOW','ROLE','account'),(531,'Account','exists','READ','ALLOW','ROLE','account'),(532,'UserLog','*','READ','ALLOW','ROLE','employee'),(533,'RoleLog','*','READ','ALLOW','ROLE','employee'),(534,'WagonType','*','*','ALLOW','ROLE','productionAssi'),(535,'WagonTypeColor','*','*','ALLOW','ROLE','productionAssi'),(536,'WagonTypeTray','*','*','ALLOW','ROLE','productionAssi'),(537,'WagonConfig','*','*','ALLOW','ROLE','productionAssi'),(538,'CollectionWagon','*','*','ALLOW','ROLE','productionAssi'),(539,'CollectionWagonTicket','*','*','ALLOW','ROLE','productionAssi'),(540,'Wagon','*','*','ALLOW','ROLE','productionAssi'),(541,'WagonType','createWagonType','*','ALLOW','ROLE','productionAssi'),(542,'WagonType','deleteWagonType','*','ALLOW','ROLE','productionAssi'),(543,'WagonType','editWagonType','*','ALLOW','ROLE','productionAssi'),(544,'Docuware','deliveryNoteEmail','WRITE','ALLOW','ROLE','employee'),(545,'Agency','find','READ','ALLOW','ROLE','employee'),(546,'Agency','seeExpired','READ','ALLOW','ROLE','coolerAssist'),(547,'WorkerLog','models','READ','ALLOW','ROLE','hr'),(548,'Ticket','editDiscount','WRITE','ALLOW','ROLE','claimManager'),(549,'Ticket','editDiscount','WRITE','ALLOW','ROLE','salesPerson'),(550,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','salesAssistant'),(551,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','deliveryAssistant'),(552,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','buyer'),(553,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','claimManager'),(554,'Ticket','deleteTicketWithPartPrepared','WRITE','ALLOW','ROLE','salesAssistant'),(555,'Ticket','editZone','WRITE','ALLOW','ROLE','deliveryAssistant'),(556,'State','editableStates','READ','ALLOW','ROLE','employee'),(557,'State','seeEditableStates','READ','ALLOW','ROLE','administrative'),(558,'State','seeEditableStates','READ','ALLOW','ROLE','production'),(559,'State','isSomeEditable','READ','ALLOW','ROLE','salesPerson'),(560,'State','isAllEditable','READ','ALLOW','ROLE','production'),(561,'State','isAllEditable','READ','ALLOW','ROLE','administrative'),(562,'Agency','seeExpired','READ','ALLOW','ROLE','administrative'),(563,'Agency','seeExpired','READ','ALLOW','ROLE','productionBoss'),(564,'Claim','createAfterDeadline','WRITE','ALLOW','ROLE','claimManager'),(565,'Client','editAddressLogifloraAllowed','WRITE','ALLOW','ROLE','salesAssistant'),(566,'Client','editFiscalDataWithoutTaxDataCheck','WRITE','ALLOW','ROLE','salesAssistant'),(567,'Client','editVerifiedDataWithoutTaxDataCheck','WRITE','ALLOW','ROLE','salesAssistant'),(568,'Client','editCredit','WRITE','ALLOW','ROLE','financialBoss'),(569,'Client','zeroCreditEditor','WRITE','ALLOW','ROLE','financialBoss'),(570,'InvoiceOut','canCreatePdf','WRITE','ALLOW','ROLE','invoicing'),(571,'Supplier','editPayMethodCheck','WRITE','ALLOW','ROLE','financial'),(572,'Worker','isTeamBoss','WRITE','ALLOW','ROLE','teamBoss'),(573,'Worker','forceIsSubordinate','READ','ALLOW','ROLE','hr'),(574,'Claim','editState','WRITE','ALLOW','ROLE','claimManager'),(575,'Claim','find','READ','ALLOW','ROLE','salesPerson'),(576,'Claim','findById','READ','ALLOW','ROLE','salesPerson'),(577,'Claim','findOne','READ','ALLOW','ROLE','salesPerson'),(578,'Claim','getSummary','READ','ALLOW','ROLE','salesPerson'),(579,'Claim','updateClaim','WRITE','ALLOW','ROLE','salesPerson'),(580,'Claim','regularizeClaim','WRITE','ALLOW','ROLE','claimManager'),(581,'Claim','updateClaimDestination','WRITE','ALLOW','ROLE','claimManager'),(582,'Claim','downloadFile','READ','ALLOW','ROLE','claimManager'),(583,'Claim','deleteById','WRITE','ALLOW','ROLE','claimManager'),(584,'Claim','filter','READ','ALLOW','ROLE','salesPerson'),(585,'Claim','logs','READ','ALLOW','ROLE','claimManager'),(586,'Ticket','find','READ','ALLOW','ROLE','employee'),(587,'Ticket','findById','READ','ALLOW','ROLE','employee'),(588,'Ticket','findOne','READ','ALLOW','ROLE','employee'),(589,'Ticket','getVolume','READ','ALLOW','ROLE','employee'),(590,'Ticket','getTotalVolume','READ','ALLOW','ROLE','employee'),(591,'Ticket','summary','READ','ALLOW','ROLE','employee'),(592,'Ticket','priceDifference','READ','ALLOW','ROLE','employee'),(593,'Ticket','componentUpdate','WRITE','ALLOW','ROLE','employee'),(594,'Ticket','new','WRITE','ALLOW','ROLE','employee'),(595,'Ticket','isEditable','READ','ALLOW','ROLE','employee'),(596,'Ticket','setDeleted','WRITE','ALLOW','ROLE','salesPerson'),(597,'Ticket','restore','WRITE','ALLOW','ROLE','employee'),(598,'Ticket','getSales','READ','ALLOW','ROLE','employee'),(599,'Ticket','getSalesPersonMana','READ','ALLOW','ROLE','employee'),(600,'Ticket','filter','READ','ALLOW','ROLE','employee'),(601,'Ticket','makeInvoice','WRITE','ALLOW','ROLE','employee'),(602,'Ticket','updateEditableTicket','WRITE','ALLOW','ROLE','employee'),(603,'Ticket','updateDiscount','WRITE','ALLOW','ROLE','employee'),(604,'Ticket','transferSales','WRITE','ALLOW','ROLE','employee'),(605,'Ticket','sendSms','WRITE','ALLOW','ROLE','employee'),(606,'Ticket','isLocked','READ','ALLOW','ROLE','employee'),(607,'Ticket','freightCost','READ','ALLOW','ROLE','employee'),(608,'Ticket','getComponentsSum','READ','ALLOW','ROLE','employee'),(609,'Ticket','updateAttributes','WRITE','ALLOW','ROLE','delivery'),(610,'Ticket','deliveryNoteCsv','READ','ALLOW','ROLE','employee'),(611,'State','find','READ','ALLOW','ROLE','employee'),(612,'State','findById','READ','ALLOW','ROLE','employee'),(613,'State','findOne','READ','ALLOW','ROLE','employee'),(614,'Worker','find','READ','ALLOW','ROLE','employee'),(615,'Worker','findById','READ','ALLOW','ROLE','employee'),(616,'Worker','findOne','READ','ALLOW','ROLE','employee'),(617,'Worker','filter','READ','ALLOW','ROLE','employee'),(618,'Worker','getWorkedHours','READ','ALLOW','ROLE','employee'),(619,'Worker','active','READ','ALLOW','ROLE','employee'),(620,'Worker','activeWithRole','READ','ALLOW','ROLE','employee'),(621,'Worker','uploadFile','WRITE','ALLOW','ROLE','hr'),(622,'Worker','contracts','READ','ALLOW','ROLE','employee'),(623,'Worker','holidays','READ','ALLOW','ROLE','employee'),(624,'Worker','activeContract','READ','ALLOW','ROLE','employee'),(625,'Worker','activeWithInheritedRole','READ','ALLOW','ROLE','employee'),(626,'Ticket','collectionLabel','READ','ALLOW','ROLE','employee'),(628,'Ticket','expeditionPalletLabel','READ','ALLOW','ROLE','employee'),(629,'Ticket','editDiscount','WRITE','ALLOW','ROLE','artificialBoss'),(630,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','salesTeamBoss'),(635,'Ticket','updateAttributes','WRITE','ALLOW','ROLE','administrative'),(636,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','salesPerson'),(637,'Claim','downloadFile','READ','ALLOW','ROLE','salesPerson'),(638,'Agency','seeExpired','READ','ALLOW','ROLE','artificialBoss'),(639,'Agency','seeExpired','READ','ALLOW','ROLE','logisticAssistant'),(640,'Claim','filter','READ','ALLOW','ROLE','buyer'),(641,'Claim','find','READ','ALLOW','ROLE','buyer'),(642,'Claim','findById','READ','ALLOW','ROLE','buyer'),(643,'Claim','getSummary','READ','ALLOW','ROLE','buyer'),(644,'Claim','filter','READ','ALLOW','ROLE','handmadeBoss'),(645,'Claim','find','READ','ALLOW','ROLE','handmadeBoss'),(646,'Claim','findById','READ','ALLOW','ROLE','handmadeBoss'),(647,'Claim','getSummary','READ','ALLOW','ROLE','handmadeBoss'),(648,'Claim','__get__lines','READ','ALLOW','ROLE','claimManager'),(649,'Claim','__get__lines','READ','ALLOW','ROLE','salesPerson'),(650,'Claim','getSummary','READ','ALLOW','ROLE','deliveryAssistant'),(651,'Claim','findById','READ','ALLOW','ROLE','deliveryAssistant'),(652,'Claim','find','READ','ALLOW','ROLE','deliveryAssistant'),(653,'Claim','filter','READ','ALLOW','ROLE','deliveryAssistant'),(654,'Ticket','editZone','WRITE','ALLOW','ROLE','logisticAssistant'),(655,'Entry','addFromPackaging','WRITE','ALLOW','ROLE','production'),(656,'Entry','addFromBuy','WRITE','ALLOW','ROLE','production'),(657,'Supplier','getItemsPackaging','READ','ALLOW','ROLE','production'),(658,'Ticket','closeAll','WRITE','ALLOW','ROLE','system'),(659,'Account','*','*','ALLOW','ROLE','itManagement'),(660,'Account','*','READ','ALLOW','ROLE','employee'),(664,'MailForward','*','*','ALLOW','ROLE','itManagement'),(665,'Role','*','READ','ALLOW','ROLE','employee'),(666,'Role','*','WRITE','ALLOW','ROLE','it'),(667,'VnUser','*','*','ALLOW','ROLE','itManagement'),(668,'VnUser','__get__preview','READ','ALLOW','ROLE','employee'),(669,'VnUser','preview','*','ALLOW','ROLE','employee'),(670,'VnUser','create','*','ALLOW','ROLE','itManagement'),(671,'VnUser','renewToken','WRITE','ALLOW','ROLE','employee'),(672,'PackingSiteAdvanced','*','*','ALLOW','ROLE','production'),(673,'InvoiceOut','makePdfAndNotify','WRITE','ALLOW','ROLE','invoicing'),(674,'InvoiceOutConfig','*','READ','ALLOW','ROLE','invoicing'),(676,'Ticket','invoiceTickets','WRITE','ALLOW','ROLE','employee'),(680,'MailAliasAccount','*','READ','ALLOW','ROLE','employee'),(681,'MailAliasAccount','create','WRITE','ALLOW','ROLE','employee'),(682,'MailAliasAccount','deleteById','WRITE','ALLOW','ROLE','employee'),(683,'MailAliasAccount','canEditAlias','WRITE','ALLOW','ROLE','itManagement'),(684,'WorkerDisableExcluded','*','READ','ALLOW','ROLE','itManagement'),(685,'WorkerDisableExcluded','*','WRITE','ALLOW','ROLE','itManagement'),(686,'MailForward','*','*','ALLOW','ROLE','hr'),(687,'ClientSms','find','READ','ALLOW','ROLE','employee'),(688,'ClientSms','create','WRITE','ALLOW','ROLE','employee'),(689,'Vehicle','sorted','WRITE','ALLOW','ROLE','employee'),(690,'Roadmap','*','*','ALLOW','ROLE','palletizerBoss'),(691,'Roadmap','*','*','ALLOW','ROLE','productionBoss'),(692,'ExpeditionTruck','*','*','ALLOW','ROLE','palletizerBoss'),(693,'ExpeditionTruck','*','*','ALLOW','ROLE','productionBoss'),(694,'MailAliasAccount','canEditAlias','WRITE','ALLOW','ROLE','marketingBoss'),(695,'ViaexpressConfig','internationalExpedition','WRITE','ALLOW','ROLE','employee'),(696,'ViaexpressConfig','renderer','READ','ALLOW','ROLE','employee'),(697,'Ticket','transferClient','WRITE','ALLOW','ROLE','administrative'),(698,'Ticket','canEditWeekly','WRITE','ALLOW','ROLE','buyer'),(699,'TicketSms','find','READ','ALLOW','ROLE','salesPerson'),(701,'Docuware','upload','WRITE','ALLOW','ROLE','deliveryAssistant'),(702,'Ticket','docuwareDownload','READ','ALLOW','ROLE','salesPerson'); +INSERT INTO `ACL` VALUES (3,'Address','*','*','ALLOW','ROLE','employee'),(5,'AgencyService','*','READ','ALLOW','ROLE','employee'),(9,'ClientObservation','*','*','ALLOW','ROLE','employee'),(11,'ContactChannel','*','READ','ALLOW','ROLE','trainee'),(13,'Employee','*','READ','ALLOW','ROLE','employee'),(14,'PayMethod','*','READ','ALLOW','ROLE','trainee'),(16,'FakeProduction','*','READ','ALLOW','ROLE','employee'),(17,'Warehouse','* ','READ','ALLOW','ROLE','trainee'),(20,'TicketState','*','*','ALLOW','ROLE','employee'),(24,'Delivery','*','READ','ALLOW','ROLE','employee'),(25,'Zone','*','READ','ALLOW','ROLE','employee'),(26,'ClientCredit','*','*','ALLOW','ROLE','employee'),(27,'ClientCreditLimit','*','READ','ALLOW','ROLE','trainee'),(30,'GreugeType','*','READ','ALLOW','ROLE','trainee'),(31,'Mandate','*','READ','ALLOW','ROLE','trainee'),(32,'MandateType','*','READ','ALLOW','ROLE','trainee'),(33,'Company','*','READ','ALLOW','ROLE','trainee'),(34,'Greuge','*','READ','ALLOW','ROLE','trainee'),(35,'AddressObservation','*','*','ALLOW','ROLE','employee'),(36,'ObservationType','*','*','ALLOW','ROLE','employee'),(37,'Greuge','*','WRITE','ALLOW','ROLE','employee'),(38,'AgencyMode','*','READ','ALLOW','ROLE','employee'),(39,'ItemTag','*','WRITE','ALLOW','ROLE','buyer'),(40,'ItemBotanical','*','WRITE','ALLOW','ROLE','buyer'),(41,'ItemBotanical','*','READ','ALLOW','ROLE','employee'),(42,'ItemPlacement','*','WRITE','ALLOW','ROLE','buyer'),(43,'ItemPlacement','*','WRITE','ALLOW','ROLE','replenisher'),(44,'ItemPlacement','*','READ','ALLOW','ROLE','employee'),(45,'ItemBarcode','*','READ','ALLOW','ROLE','employee'),(46,'ItemBarcode','*','WRITE','ALLOW','ROLE','buyer'),(47,'ItemBarcode','*','WRITE','ALLOW','ROLE','replenisher'),(51,'ItemTag','*','READ','ALLOW','ROLE','employee'),(53,'Item','*','READ','ALLOW','ROLE','employee'),(54,'Item','*','WRITE','ALLOW','ROLE','buyer'),(55,'Recovery','*','READ','ALLOW','ROLE','trainee'),(56,'Recovery','*','WRITE','ALLOW','ROLE','administrative'),(58,'CreditClassification','*','*','ALLOW','ROLE','insurance'),(60,'CreditInsurance','*','*','ALLOW','ROLE','insurance'),(61,'InvoiceOut','*','READ','ALLOW','ROLE','employee'),(63,'TicketObservation','*','*','ALLOW','ROLE','employee'),(64,'Route','*','READ','ALLOW','ROLE','employee'),(65,'Sale','*','READ','ALLOW','ROLE','employee'),(66,'TicketTracking','*','READ','ALLOW','ROLE','employee'),(68,'TicketPackaging','*','*','ALLOW','ROLE','employee'),(69,'Packaging','*','READ','ALLOW','ROLE','employee'),(70,'Packaging','*','WRITE','ALLOW','ROLE','logistic'),(72,'SaleComponent','*','READ','ALLOW','ROLE','employee'),(73,'Expedition','*','READ','ALLOW','ROLE','employee'),(74,'Expedition','*','WRITE','ALLOW','ROLE','deliveryBoss'),(75,'Expedition','*','WRITE','ALLOW','ROLE','production'),(76,'AnnualAverageInvoiced','*','READ','ALLOW','ROLE','employee'),(77,'WorkerMana','*','READ','ALLOW','ROLE','employee'),(78,'TicketTracking','*','WRITE','ALLOW','ROLE','production'),(79,'TicketTracking','changeState','*','ALLOW','ROLE','employee'),(80,'Sale','deleteSales','*','ALLOW','ROLE','employee'),(81,'Sale','moveToTicket','*','ALLOW','ROLE','employee'),(82,'Sale','updateQuantity','*','ALLOW','ROLE','employee'),(83,'Sale','updatePrice','*','ALLOW','ROLE','employee'),(84,'Sale','updateDiscount','*','ALLOW','ROLE','employee'),(85,'SaleTracking','*','READ','ALLOW','ROLE','employee'),(86,'Order','*','*','ALLOW','ROLE','employee'),(87,'OrderRow','*','*','ALLOW','ROLE','employee'),(88,'ClientContact','*','*','ALLOW','ROLE','employee'),(89,'Sale','moveToNewTicket','*','ALLOW','ROLE','employee'),(90,'Sale','reserve','*','ALLOW','ROLE','employee'),(91,'TicketWeekly','*','READ','ALLOW','ROLE','employee'),(94,'Agency','landsThatDay','*','ALLOW','ROLE','employee'),(96,'ClaimEnd','*','READ','ALLOW','ROLE','employee'),(97,'ClaimEnd','*','WRITE','ALLOW','ROLE','claimManager'),(98,'ClaimBeginning','*','*','ALLOW','ROLE','employee'),(99,'ClaimDevelopment','*','READ','ALLOW','ROLE','employee'),(100,'ClaimDevelopment','*','WRITE','ALLOW','ROLE','claimManager'),(102,'Claim','createFromSales','*','ALLOW','ROLE','employee'),(104,'Item','*','WRITE','ALLOW','ROLE','marketingBoss'),(105,'ItemBarcode','*','WRITE','ALLOW','ROLE','marketingBoss'),(106,'ItemBotanical','*','WRITE','ALLOW','ROLE','marketingBoss'),(108,'ItemPlacement','*','WRITE','ALLOW','ROLE','marketingBoss'),(109,'UserConfig','*','*','ALLOW','ROLE','employee'),(110,'Bank','*','READ','ALLOW','ROLE','trainee'),(111,'ClientLog','*','READ','ALLOW','ROLE','trainee'),(112,'Defaulter','*','READ','ALLOW','ROLE','employee'),(113,'ClientRisk','*','READ','ALLOW','ROLE','trainee'),(114,'Receipt','*','READ','ALLOW','ROLE','trainee'),(115,'Receipt','*','WRITE','ALLOW','ROLE','administrative'),(116,'BankEntity','*','*','ALLOW','ROLE','employee'),(117,'ClientSample','*','*','ALLOW','ROLE','employee'),(118,'WorkerTeam','*','*','ALLOW','ROLE','salesPerson'),(119,'Travel','*','READ','ALLOW','ROLE','employee'),(120,'Travel','*','WRITE','ALLOW','ROLE','buyer'),(121,'Item','regularize','*','ALLOW','ROLE','employee'),(122,'TicketRequest','*','*','ALLOW','ROLE','employee'),(124,'Client','confirmTransaction','WRITE','ALLOW','ROLE','administrative'),(125,'Agency','getAgenciesWithWarehouse','*','ALLOW','ROLE','employee'),(126,'Client','activeWorkersWithRole','*','ALLOW','ROLE','employee'),(127,'TicketLog','*','READ','ALLOW','ROLE','employee'),(129,'TicketService','*','*','ALLOW','ROLE','employee'),(130,'Expedition','*','WRITE','ALLOW','ROLE','packager'),(131,'CreditInsurance','*','READ','ALLOW','ROLE','trainee'),(132,'CreditClassification','*','READ','ALLOW','ROLE','trainee'),(133,'ItemTag','*','WRITE','ALLOW','ROLE','marketingBoss'),(135,'ZoneGeo','*','READ','ALLOW','ROLE','employee'),(136,'ZoneCalendar','*','READ','ALLOW','ROLE','employee'),(137,'ZoneIncluded','*','READ','ALLOW','ROLE','employee'),(138,'LabourHoliday','*','READ','ALLOW','ROLE','employee'),(139,'LabourHolidayLegend','*','READ','ALLOW','ROLE','employee'),(140,'LabourHolidayType','*','READ','ALLOW','ROLE','employee'),(141,'Zone','*','*','ALLOW','ROLE','logisticBoss'),(142,'ZoneCalendar','*','WRITE','ALLOW','ROLE','deliveryBoss'),(143,'ZoneIncluded','*','*','ALLOW','ROLE','deliveryBoss'),(144,'Stowaway','*','*','ALLOW','ROLE','employee'),(145,'Ticket','getPossibleStowaways','READ','ALLOW','ROLE','employee'),(147,'UserConfigView','*','*','ALLOW','ROLE','employee'),(148,'UserConfigView','*','*','ALLOW','ROLE','employee'),(149,'Sip','*','READ','ALLOW','ROLE','employee'),(150,'Sip','*','WRITE','ALLOW','ROLE','hr'),(151,'Department','*','READ','ALLOW','ROLE','employee'),(152,'Department','*','WRITE','ALLOW','ROLE','hr'),(153,'Route','*','READ','ALLOW','ROLE','employee'),(154,'Route','*','WRITE','ALLOW','ROLE','delivery'),(155,'Calendar','*','READ','ALLOW','ROLE','hr'),(156,'WorkerLabour','*','READ','ALLOW','ROLE','hr'),(157,'Calendar','absences','READ','ALLOW','ROLE','employee'),(158,'ItemTag','*','WRITE','ALLOW','ROLE','accessory'),(160,'TicketServiceType','*','READ','ALLOW','ROLE','employee'),(161,'TicketConfig','*','READ','ALLOW','ROLE','employee'),(162,'InvoiceOut','delete','WRITE','ALLOW','ROLE','invoicing'),(163,'InvoiceOut','book','WRITE','ALLOW','ROLE','invoicing'),(165,'TicketDms','*','*','ALLOW','ROLE','employee'),(167,'Worker','isSubordinate','READ','ALLOW','ROLE','employee'),(168,'Worker','mySubordinates','READ','ALLOW','ROLE','employee'),(169,'WorkerTimeControl','filter','READ','ALLOW','ROLE','employee'),(170,'WorkerTimeControl','addTime','WRITE','ALLOW','ROLE','employee'),(171,'TicketServiceType','*','WRITE','ALLOW','ROLE','administrative'),(172,'Sms','*','READ','ALLOW','ROLE','employee'),(173,'Sms','send','WRITE','ALLOW','ROLE','employee'),(176,'Device','*','*','ALLOW','ROLE','employee'),(177,'Device','*','*','ALLOW','ROLE','employee'),(178,'WorkerTimeControl','*','*','ALLOW','ROLE','employee'),(179,'ItemLog','*','READ','ALLOW','ROLE','employee'),(180,'RouteLog','*','READ','ALLOW','ROLE','employee'),(181,'Dms','removeFile','WRITE','ALLOW','ROLE','employee'),(182,'Dms','uploadFile','WRITE','ALLOW','ROLE','employee'),(183,'Dms','downloadFile','READ','ALLOW','ROLE','employee'),(184,'Client','uploadFile','WRITE','ALLOW','ROLE','employee'),(185,'ClientDms','removeFile','WRITE','ALLOW','ROLE','employee'),(186,'ClientDms','*','READ','ALLOW','ROLE','trainee'),(187,'Ticket','uploadFile','WRITE','ALLOW','ROLE','employee'),(190,'Route','updateVolume','WRITE','ALLOW','ROLE','deliveryBoss'),(191,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(192,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(194,'Postcode','*','WRITE','ALLOW','ROLE','deliveryBoss'),(195,'Ticket','addSale','WRITE','ALLOW','ROLE','employee'),(196,'Dms','updateFile','WRITE','ALLOW','ROLE','employee'),(197,'Dms','*','READ','ALLOW','ROLE','trainee'),(198,'ClaimDms','removeFile','WRITE','ALLOW','ROLE','employee'),(199,'ClaimDms','*','READ','ALLOW','ROLE','employee'),(200,'Claim','uploadFile','WRITE','ALLOW','ROLE','employee'),(201,'Sale','updateConcept','WRITE','ALLOW','ROLE','employee'),(202,'Claim','updateClaimAction','WRITE','ALLOW','ROLE','claimManager'),(203,'UserPhone','*','*','ALLOW','ROLE','employee'),(204,'WorkerDms','removeFile','WRITE','ALLOW','ROLE','hr'),(205,'WorkerDms','*','READ','ALLOW','ROLE','hr'),(206,'Chat','*','*','ALLOW','ROLE','employee'),(207,'Chat','sendMessage','*','ALLOW','ROLE','employee'),(208,'Sale','recalculatePrice','WRITE','ALLOW','ROLE','employee'),(209,'Ticket','recalculateComponents','WRITE','ALLOW','ROLE','employee'),(211,'TravelLog','*','READ','ALLOW','ROLE','buyer'),(212,'Thermograph','*','*','ALLOW','ROLE','buyer'),(213,'TravelThermograph','*','WRITE','ALLOW','ROLE','buyer'),(214,'Entry','*','*','ALLOW','ROLE','buyer'),(215,'TicketWeekly','*','WRITE','ALLOW','ROLE','buyer'),(216,'TravelThermograph','*','READ','ALLOW','ROLE','employee'),(218,'Intrastat','*','*','ALLOW','ROLE','buyer'),(221,'UserConfig','getUserConfig','READ','ALLOW','ROLE','account'),(222,'Client','*','READ','ALLOW','ROLE','trainee'),(226,'ClientObservation','*','READ','ALLOW','ROLE','trainee'),(227,'Address','*','READ','ALLOW','ROLE','trainee'),(228,'AddressObservation','*','READ','ALLOW','ROLE','trainee'),(230,'ClientCredit','*','READ','ALLOW','ROLE','trainee'),(231,'ClientContact','*','READ','ALLOW','ROLE','trainee'),(232,'ClientSample','*','READ','ALLOW','ROLE','trainee'),(233,'EntryLog','*','READ','ALLOW','ROLE','buyer'),(234,'WorkerLog','find','READ','ALLOW','ROLE','hr'),(235,'CustomsAgent','*','*','ALLOW','ROLE','employee'),(236,'Buy','*','*','ALLOW','ROLE','buyer'),(237,'WorkerDms','filter','*','ALLOW','ROLE','employee'),(238,'Town','*','WRITE','ALLOW','ROLE','deliveryBoss'),(239,'Province','*','WRITE','ALLOW','ROLE','deliveryBoss'),(240,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(241,'SupplierContact','*','WRITE','ALLOW','ROLE','administrative'),(242,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(244,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(248,'RoleMapping','*','READ','ALLOW','ROLE','account'),(249,'UserPassword','*','READ','ALLOW','ROLE','account'),(250,'Town','*','WRITE','ALLOW','ROLE','deliveryBoss'),(251,'Province','*','WRITE','ALLOW','ROLE','deliveryBoss'),(252,'Supplier','*','READ','ALLOW','ROLE','employee'),(253,'Supplier','*','WRITE','ALLOW','ROLE','administrative'),(254,'SupplierLog','*','READ','ALLOW','ROLE','employee'),(256,'Image','*','WRITE','ALLOW','ROLE','employee'),(257,'FixedPrice','*','*','ALLOW','ROLE','buyer'),(258,'PayDem','*','READ','ALLOW','ROLE','employee'),(259,'Client','createReceipt','*','ALLOW','ROLE','salesAssistant'),(260,'PrintServerQueue','*','WRITE','ALLOW','ROLE','employee'),(261,'SupplierAccount','*','*','ALLOW','ROLE','administrative'),(262,'Entry','*','*','ALLOW','ROLE','administrative'),(263,'InvoiceIn','*','*','ALLOW','ROLE','administrative'),(264,'StarredModule','*','*','ALLOW','ROLE','employee'),(265,'ItemBotanical','*','WRITE','ALLOW','ROLE','logisticBoss'),(266,'ZoneLog','*','READ','ALLOW','ROLE','employee'),(267,'Genus','*','WRITE','ALLOW','ROLE','logisticBoss'),(268,'Specie','*','WRITE','ALLOW','ROLE','logisticBoss'),(269,'InvoiceOut','createPdf','WRITE','ALLOW','ROLE','employee'),(270,'SupplierAddress','*','*','ALLOW','ROLE','employee'),(271,'SalesMonitor','*','*','ALLOW','ROLE','employee'),(272,'InvoiceInLog','*','READ','ALLOW','ROLE','employee'),(273,'InvoiceInTax','*','*','ALLOW','ROLE','administrative'),(274,'InvoiceInLog','*','READ','ALLOW','ROLE','administrative'),(275,'InvoiceOut','createManualInvoice','WRITE','ALLOW','ROLE','invoicing'),(276,'InvoiceOut','globalInvoicing','WRITE','ALLOW','ROLE','invoicing'),(278,'RoleInherit','*','WRITE','ALLOW','ROLE','grant'),(279,'MailAlias','*','*','ALLOW','ROLE','marketing'),(283,'EntryObservation','*','*','ALLOW','ROLE','buyer'),(284,'LdapConfig','*','*','ALLOW','ROLE','sysadmin'),(285,'SambaConfig','*','*','ALLOW','ROLE','sysadmin'),(286,'ACL','*','*','ALLOW','ROLE','developer'),(287,'AccessToken','*','*','ALLOW','ROLE','developer'),(293,'RoleInherit','*','*','ALLOW','ROLE','it'),(294,'RoleRole','*','*','ALLOW','ROLE','it'),(295,'AccountConfig','*','*','ALLOW','ROLE','sysadmin'),(296,'Collection','*','READ','ALLOW','ROLE','employee'),(297,'Sale','refund','WRITE','ALLOW','ROLE','invoicing'),(298,'InvoiceInDueDay','*','*','ALLOW','ROLE','administrative'),(299,'Collection','setSaleQuantity','*','ALLOW','ROLE','employee'),(302,'AgencyTerm','*','*','ALLOW','ROLE','administrative'),(303,'ClaimLog','*','READ','ALLOW','ROLE','claimManager'),(304,'Edi','updateData','WRITE','ALLOW','ROLE','employee'),(305,'EducationLevel','*','*','ALLOW','ROLE','employee'),(306,'InvoiceInIntrastat','*','*','ALLOW','ROLE','employee'),(307,'SupplierAgencyTerm','*','*','ALLOW','ROLE','administrative'),(308,'InvoiceInIntrastat','*','*','ALLOW','ROLE','employee'),(309,'Zone','getZoneClosing','*','ALLOW','ROLE','employee'),(310,'ExpeditionState','*','READ','ALLOW','ROLE','employee'),(311,'Expense','*','READ','ALLOW','ROLE','employee'),(312,'Expense','*','WRITE','ALLOW','ROLE','administrative'),(314,'SupplierActivity','*','READ','ALLOW','ROLE','employee'),(315,'SupplierActivity','*','WRITE','ALLOW','ROLE','administrative'),(316,'Dms','deleteTrashFiles','WRITE','ALLOW','ROLE','employee'),(317,'ClientUnpaid','*','*','ALLOW','ROLE','administrative'),(318,'MdbVersion','*','*','ALLOW','ROLE','developer'),(319,'ItemType','*','READ','ALLOW','ROLE','employee'),(320,'ItemType','*','WRITE','ALLOW','ROLE','buyer'),(321,'InvoiceOut','refund','WRITE','ALLOW','ROLE','invoicing'),(322,'InvoiceOut','refund','WRITE','ALLOW','ROLE','salesAssistant'),(323,'InvoiceOut','refund','WRITE','ALLOW','ROLE','claimManager'),(324,'Ticket','refund','WRITE','ALLOW','ROLE','invoicing'),(325,'Ticket','refund','WRITE','ALLOW','ROLE','salesAssistant'),(326,'Ticket','refund','WRITE','ALLOW','ROLE','claimManager'),(327,'Sale','refund','WRITE','ALLOW','ROLE','salesAssistant'),(328,'Sale','refund','WRITE','ALLOW','ROLE','claimManager'),(329,'TicketRefund','*','WRITE','ALLOW','ROLE','invoicing'),(330,'ClaimObservation','*','WRITE','ALLOW','ROLE','salesPerson'),(331,'ClaimObservation','*','READ','ALLOW','ROLE','salesPerson'),(332,'Client','setPassword','WRITE','ALLOW','ROLE','salesPerson'),(333,'Client','updateUser','WRITE','ALLOW','ROLE','salesPerson'),(334,'ShelvingLog','*','READ','ALLOW','ROLE','employee'),(335,'ZoneExclusionGeo','*','READ','ALLOW','ROLE','employee'),(336,'ZoneExclusionGeo','*','WRITE','ALLOW','ROLE','deliveryBoss'),(337,'Parking','*','*','ALLOW','ROLE','employee'),(338,'Shelving','*','*','ALLOW','ROLE','employee'),(339,'OsTicket','*','*','ALLOW','ROLE','employee'),(340,'OsTicketConfig','*','*','ALLOW','ROLE','it'),(341,'ClientConsumptionQueue','*','WRITE','ALLOW','ROLE','employee'),(342,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','employee'),(343,'Ticket','deliveryNoteEmail','WRITE','ALLOW','ROLE','employee'),(344,'Ticket','deliveryNoteCsvPdf','READ','ALLOW','ROLE','employee'),(345,'Ticket','deliveryNoteCsvEmail','READ','ALLOW','ROLE','employee'),(346,'Client','campaignMetricsPdf','READ','ALLOW','ROLE','employee'),(347,'Client','campaignMetricsEmail','WRITE','ALLOW','ROLE','employee'),(348,'Client','clientWelcomeHtml','READ','ALLOW','ROLE','employee'),(349,'Client','clientWelcomeEmail','WRITE','ALLOW','ROLE','employee'),(350,'Client','creditRequestPdf','READ','ALLOW','ROLE','employee'),(351,'Client','creditRequestHtml','READ','ALLOW','ROLE','employee'),(352,'Client','creditRequestEmail','WRITE','ALLOW','ROLE','employee'),(353,'Client','printerSetupHtml','READ','ALLOW','ROLE','employee'),(354,'Client','printerSetupEmail','WRITE','ALLOW','ROLE','employee'),(355,'Client','sepaCoreEmail','WRITE','ALLOW','ROLE','employee'),(356,'Client','letterDebtorPdf','READ','ALLOW','ROLE','employee'),(357,'Client','letterDebtorStHtml','READ','ALLOW','ROLE','employee'),(358,'Client','letterDebtorStEmail','WRITE','ALLOW','ROLE','employee'),(359,'Client','letterDebtorNdHtml','READ','ALLOW','ROLE','employee'),(360,'Client','letterDebtorNdEmail','WRITE','ALLOW','ROLE','employee'),(361,'Client','clientDebtStatementPdf','READ','ALLOW','ROLE','employee'),(362,'Client','clientDebtStatementHtml','READ','ALLOW','ROLE','employee'),(363,'Client','clientDebtStatementEmail','WRITE','ALLOW','ROLE','employee'),(364,'Client','incotermsAuthorizationPdf','READ','ALLOW','ROLE','employee'),(365,'Client','incotermsAuthorizationHtml','READ','ALLOW','ROLE','employee'),(366,'Client','incotermsAuthorizationEmail','WRITE','ALLOW','ROLE','employee'),(367,'Client','consumptionSendQueued','WRITE','ALLOW','ROLE','system'),(368,'InvoiceOut','invoiceEmail','WRITE','ALLOW','ROLE','employee'),(369,'InvoiceOut','exportationPdf','READ','ALLOW','ROLE','employee'),(370,'InvoiceOut','sendQueued','WRITE','ALLOW','ROLE','system'),(371,'Ticket','invoiceCsvPdf','READ','ALLOW','ROLE','employee'),(372,'Ticket','invoiceCsvEmail','WRITE','ALLOW','ROLE','employee'),(373,'Supplier','campaignMetricsPdf','READ','ALLOW','ROLE','employee'),(374,'Supplier','campaignMetricsEmail','WRITE','ALLOW','ROLE','employee'),(375,'Travel','extraCommunityPdf','READ','ALLOW','ROLE','employee'),(376,'Travel','extraCommunityEmail','WRITE','ALLOW','ROLE','employee'),(377,'Entry','entryOrderPdf','READ','ALLOW','ROLE','employee'),(378,'OsTicket','osTicketReportEmail','WRITE','ALLOW','ROLE','system'),(379,'Item','buyerWasteEmail','WRITE','ALLOW','ROLE','system'),(380,'Claim','claimPickupPdf','READ','ALLOW','ROLE','employee'),(381,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','claimManager'),(382,'Item','labelPdf','READ','ALLOW','ROLE','employee'),(383,'Sector','*','READ','ALLOW','ROLE','employee'),(384,'Sector','*','WRITE','ALLOW','ROLE','employee'),(385,'Route','driverRoutePdf','READ','ALLOW','ROLE','employee'),(386,'Route','driverRouteEmail','WRITE','ALLOW','ROLE','employee'),(387,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','customer'),(388,'Supplier','newSupplier','WRITE','ALLOW','ROLE','administrative'),(389,'ClaimRma','*','READ','ALLOW','ROLE','claimManager'),(390,'ClaimRma','*','WRITE','ALLOW','ROLE','claimManager'),(391,'Notification','*','WRITE','ALLOW','ROLE','system'),(392,'Boxing','*','*','ALLOW','ROLE','employee'),(393,'Url','*','READ','ALLOW','ROLE','employee'),(394,'Url','*','WRITE','ALLOW','ROLE','it'),(395,'ItemShelving','*','READ','ALLOW','ROLE','employee'),(396,'ItemShelving','*','WRITE','ALLOW','ROLE','production'),(397,'ItemShelvingPlacementSupplyStock','*','READ','ALLOW','ROLE','employee'),(398,'NotificationQueue','*','*','ALLOW','ROLE','employee'),(399,'InvoiceOut','clientsToInvoice','WRITE','ALLOW','ROLE','invoicing'),(400,'InvoiceOut','invoiceClient','WRITE','ALLOW','ROLE','invoicing'),(401,'Sale','editTracked','WRITE','ALLOW','ROLE','production'),(402,'Sale','editFloramondo','WRITE','ALLOW','ROLE','salesAssistant'),(403,'Receipt','balanceCompensationEmail','WRITE','ALLOW','ROLE','employee'),(404,'Receipt','balanceCompensationPdf','READ','ALLOW','ROLE','employee'),(405,'Ticket','getTicketsFuture','READ','ALLOW','ROLE','employee'),(406,'Ticket','merge','WRITE','ALLOW','ROLE','employee'),(407,'Sale','editFloramondo','WRITE','ALLOW','ROLE','logistic'),(408,'ZipConfig','*','*','ALLOW','ROLE','employee'),(409,'Item','*','WRITE','ALLOW','ROLE','administrative'),(410,'Sale','editCloned','WRITE','ALLOW','ROLE','buyer'),(411,'Sale','editCloned','WRITE','ALLOW','ROLE','salesAssistant'),(414,'MdbVersion','*','READ','ALLOW','ROLE','$everyone'),(416,'TicketLog','getChanges','READ','ALLOW','ROLE','employee'),(417,'Ticket','getTicketsAdvance','READ','ALLOW','ROLE','employee'),(418,'EntryLog','*','READ','ALLOW','ROLE','administrative'),(419,'Sale','editTracked','WRITE','ALLOW','ROLE','buyer'),(420,'MdbBranch','*','READ','ALLOW','ROLE','$everyone'),(421,'ItemShelvingSale','*','*','ALLOW','ROLE','employee'),(422,'Docuware','checkFile','READ','ALLOW','ROLE','employee'),(423,'Docuware','download','READ','ALLOW','ROLE','salesPerson'),(424,'Docuware','upload','WRITE','ALLOW','ROLE','productionAssi'),(425,'Docuware','deliveryNoteEmail','WRITE','ALLOW','ROLE','salesPerson'),(426,'TpvTransaction','confirm','WRITE','ALLOW','ROLE','$everyone'),(427,'TpvTransaction','start','WRITE','ALLOW','ROLE','$authenticated'),(428,'TpvTransaction','end','WRITE','ALLOW','ROLE','$authenticated'),(429,'ItemConfig','*','READ','ALLOW','ROLE','employee'),(431,'Tag','onSubmit','WRITE','ALLOW','ROLE','employee'),(432,'Worker','updateAttributes','WRITE','ALLOW','ROLE','hr'),(433,'Worker','createAbsence','*','ALLOW','ROLE','employee'),(434,'Worker','updateAbsence','WRITE','ALLOW','ROLE','employee'),(435,'Worker','deleteAbsence','*','ALLOW','ROLE','employee'),(436,'Worker','new','WRITE','ALLOW','ROLE','hr'),(438,'Client','getClientOrSupplierReference','READ','ALLOW','ROLE','employee'),(439,'NotificationSubscription','*','*','ALLOW','ROLE','employee'),(440,'NotificationAcl','*','READ','ALLOW','ROLE','employee'),(441,'MdbApp','*','READ','ALLOW','ROLE','$everyone'),(442,'MdbApp','*','*','ALLOW','ROLE','developer'),(443,'ItemConfig','*','*','ALLOW','ROLE','employee'),(444,'DeviceProduction','*','*','ALLOW','ROLE','hr'),(445,'DeviceProductionModels','*','*','ALLOW','ROLE','hr'),(446,'DeviceProductionState','*','*','ALLOW','ROLE','hr'),(447,'DeviceProductionUser','*','*','ALLOW','ROLE','hr'),(448,'DeviceProduction','*','*','ALLOW','ROLE','productionAssi'),(449,'DeviceProductionModels','*','*','ALLOW','ROLE','productionAssi'),(450,'DeviceProductionState','*','*','ALLOW','ROLE','productionAssi'),(451,'DeviceProductionUser','*','*','ALLOW','ROLE','productionAssi'),(452,'Worker','deallocatePDA','*','ALLOW','ROLE','hr'),(453,'Worker','allocatePDA','*','ALLOW','ROLE','hr'),(454,'Worker','deallocatePDA','*','ALLOW','ROLE','productionAssi'),(455,'Worker','allocatePDA','*','ALLOW','ROLE','productionAssi'),(456,'Zone','*','*','ALLOW','ROLE','deliveryBoss'),(457,'Account','setPassword','WRITE','ALLOW','ROLE','itManagement'),(458,'Operator','*','READ','ALLOW','ROLE','employee'),(459,'Operator','*','WRITE','ALLOW','ROLE','employee'),(460,'InvoiceIn','getSerial','READ','ALLOW','ROLE','administrative'),(461,'Ticket','saveSign','WRITE','ALLOW','ROLE','employee'),(462,'InvoiceOut','negativeBases','READ','ALLOW','ROLE','administrative'),(463,'InvoiceOut','negativeBasesCsv','READ','ALLOW','ROLE','administrative'),(464,'WorkerObservation','*','*','ALLOW','ROLE','hr'),(465,'ClientInforma','*','READ','ALLOW','ROLE','employee'),(466,'ClientInforma','*','WRITE','ALLOW','ROLE','financial'),(467,'Receipt','receiptEmail','*','ALLOW','ROLE','salesAssistant'),(468,'Client','setRating','WRITE','ALLOW','ROLE','financial'),(469,'Client','*','READ','ALLOW','ROLE','employee'),(470,'Client','addressesPropagateRe','*','ALLOW','ROLE','employee'),(471,'Client','canBeInvoiced','*','ALLOW','ROLE','employee'),(472,'Client','canCreateTicket','*','ALLOW','ROLE','employee'),(473,'Client','consumption','*','ALLOW','ROLE','employee'),(474,'Client','createAddress','*','ALLOW','ROLE','employee'),(475,'Client','createWithUser','*','ALLOW','ROLE','employee'),(476,'Client','extendedListFilter','*','ALLOW','ROLE','employee'),(477,'Client','getAverageInvoiced','*','ALLOW','ROLE','employee'),(478,'Client','getCard','*','ALLOW','ROLE','employee'),(479,'Client','getDebt','*','ALLOW','ROLE','employee'),(480,'Client','getMana','*','ALLOW','ROLE','employee'),(481,'Client','transactions','*','ALLOW','ROLE','employee'),(482,'Client','hasCustomerRole','*','ALLOW','ROLE','employee'),(483,'Client','isValidClient','*','ALLOW','ROLE','employee'),(484,'Client','lastActiveTickets','*','ALLOW','ROLE','employee'),(485,'Client','sendSms','*','ALLOW','ROLE','employee'),(486,'Client','setPassword','*','ALLOW','ROLE','employee'),(487,'Client','summary','*','ALLOW','ROLE','employee'),(488,'Client','updateAddress','*','ALLOW','ROLE','employee'),(489,'Client','updateFiscalData','*','ALLOW','ROLE','employee'),(491,'Client','uploadFile','*','ALLOW','ROLE','employee'),(492,'Client','campaignMetricsPdf','*','ALLOW','ROLE','employee'),(493,'Client','campaignMetricsEmail','*','ALLOW','ROLE','employee'),(494,'Client','clientWelcomeHtml','*','ALLOW','ROLE','employee'),(495,'Client','clientWelcomeEmail','*','ALLOW','ROLE','employee'),(496,'Client','printerSetupHtml','*','ALLOW','ROLE','employee'),(497,'Client','printerSetupEmail','*','ALLOW','ROLE','employee'),(498,'Client','sepaCoreEmail','*','ALLOW','ROLE','employee'),(499,'Client','letterDebtorPdf','*','ALLOW','ROLE','employee'),(500,'Client','letterDebtorStHtml','*','ALLOW','ROLE','employee'),(501,'Client','letterDebtorStEmail','*','ALLOW','ROLE','employee'),(502,'Client','letterDebtorNdHtml','*','ALLOW','ROLE','employee'),(503,'Client','letterDebtorNdEmail','*','ALLOW','ROLE','employee'),(504,'Client','clientDebtStatementPdf','*','ALLOW','ROLE','employee'),(505,'Client','clientDebtStatementHtml','*','ALLOW','ROLE','employee'),(506,'Client','clientDebtStatementEmail','*','ALLOW','ROLE','employee'),(507,'Client','creditRequestPdf','*','ALLOW','ROLE','employee'),(508,'Client','creditRequestHtml','*','ALLOW','ROLE','employee'),(509,'Client','creditRequestEmail','*','ALLOW','ROLE','employee'),(510,'Client','incotermsAuthorizationPdf','*','ALLOW','ROLE','employee'),(511,'Client','incotermsAuthorizationHtml','*','ALLOW','ROLE','employee'),(512,'Client','incotermsAuthorizationEmail','*','ALLOW','ROLE','employee'),(513,'Client','consumptionSendQueued','*','ALLOW','ROLE','employee'),(514,'Client','filter','*','ALLOW','ROLE','employee'),(515,'Client','getClientOrSupplierReference','*','ALLOW','ROLE','employee'),(516,'Client','upsert','*','ALLOW','ROLE','employee'),(517,'Client','create','*','ALLOW','ROLE','employee'),(518,'Client','replaceById','*','ALLOW','ROLE','employee'),(519,'Client','updateAttributes','*','ALLOW','ROLE','employee'),(520,'Client','updateAttributes','*','ALLOW','ROLE','employee'),(521,'Client','deleteById','*','ALLOW','ROLE','employee'),(522,'Client','replaceOrCreate','*','ALLOW','ROLE','employee'),(523,'Client','updateAll','*','ALLOW','ROLE','employee'),(524,'Client','upsertWithWhere','*','ALLOW','ROLE','employee'),(525,'Defaulter','observationEmail','WRITE','ALLOW','ROLE','employee'),(527,'VnUser','acl','READ','ALLOW','ROLE','account'),(528,'VnUser','getCurrentUserData','READ','ALLOW','ROLE','account'),(530,'Account','exists','READ','ALLOW','ROLE','account'),(531,'Account','exists','READ','ALLOW','ROLE','account'),(532,'UserLog','*','READ','ALLOW','ROLE','employee'),(533,'RoleLog','*','READ','ALLOW','ROLE','employee'),(534,'WagonType','*','*','ALLOW','ROLE','productionAssi'),(535,'WagonTypeColor','*','*','ALLOW','ROLE','productionAssi'),(536,'WagonTypeTray','*','*','ALLOW','ROLE','productionAssi'),(537,'WagonConfig','*','*','ALLOW','ROLE','productionAssi'),(538,'CollectionWagon','*','*','ALLOW','ROLE','productionAssi'),(539,'CollectionWagonTicket','*','*','ALLOW','ROLE','productionAssi'),(540,'Wagon','*','*','ALLOW','ROLE','productionAssi'),(541,'WagonType','createWagonType','*','ALLOW','ROLE','productionAssi'),(542,'WagonType','deleteWagonType','*','ALLOW','ROLE','productionAssi'),(543,'WagonType','editWagonType','*','ALLOW','ROLE','productionAssi'),(544,'Docuware','deliveryNoteEmail','WRITE','ALLOW','ROLE','employee'),(545,'Agency','find','READ','ALLOW','ROLE','employee'),(546,'Agency','seeExpired','READ','ALLOW','ROLE','coolerAssist'),(547,'WorkerLog','models','READ','ALLOW','ROLE','hr'),(548,'Ticket','editDiscount','WRITE','ALLOW','ROLE','claimManager'),(549,'Ticket','editDiscount','WRITE','ALLOW','ROLE','salesPerson'),(550,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','salesAssistant'),(551,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','deliveryBoss'),(552,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','buyer'),(553,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','claimManager'),(554,'Ticket','deleteTicketWithPartPrepared','WRITE','ALLOW','ROLE','salesAssistant'),(555,'Ticket','editZone','WRITE','ALLOW','ROLE','deliveryBoss'),(556,'State','editableStates','READ','ALLOW','ROLE','employee'),(557,'State','seeEditableStates','READ','ALLOW','ROLE','administrative'),(558,'State','seeEditableStates','READ','ALLOW','ROLE','production'),(559,'State','isSomeEditable','READ','ALLOW','ROLE','salesPerson'),(560,'State','isAllEditable','READ','ALLOW','ROLE','production'),(561,'State','isAllEditable','READ','ALLOW','ROLE','administrative'),(562,'Agency','seeExpired','READ','ALLOW','ROLE','administrative'),(563,'Agency','seeExpired','READ','ALLOW','ROLE','productionBoss'),(564,'Claim','createAfterDeadline','WRITE','ALLOW','ROLE','claimManager'),(565,'Client','editAddressLogifloraAllowed','WRITE','ALLOW','ROLE','salesAssistant'),(566,'Client','editFiscalDataWithoutTaxDataCheck','WRITE','ALLOW','ROLE','salesAssistant'),(567,'Client','editVerifiedDataWithoutTaxDataCheck','WRITE','ALLOW','ROLE','salesAssistant'),(568,'Client','editCredit','WRITE','ALLOW','ROLE','financialBoss'),(569,'Client','zeroCreditEditor','WRITE','ALLOW','ROLE','financialBoss'),(570,'InvoiceOut','canCreatePdf','WRITE','ALLOW','ROLE','invoicing'),(571,'Supplier','editPayMethodCheck','WRITE','ALLOW','ROLE','financial'),(572,'Worker','isTeamBoss','WRITE','ALLOW','ROLE','teamBoss'),(573,'Worker','forceIsSubordinate','READ','ALLOW','ROLE','hr'),(574,'Claim','editState','WRITE','ALLOW','ROLE','claimManager'),(575,'Claim','find','READ','ALLOW','ROLE','salesPerson'),(576,'Claim','findById','READ','ALLOW','ROLE','salesPerson'),(577,'Claim','findOne','READ','ALLOW','ROLE','salesPerson'),(578,'Claim','getSummary','READ','ALLOW','ROLE','salesPerson'),(579,'Claim','updateClaim','WRITE','ALLOW','ROLE','salesPerson'),(580,'Claim','regularizeClaim','WRITE','ALLOW','ROLE','claimManager'),(581,'Claim','updateClaimDestination','WRITE','ALLOW','ROLE','claimManager'),(582,'Claim','downloadFile','READ','ALLOW','ROLE','claimManager'),(583,'Claim','deleteById','WRITE','ALLOW','ROLE','claimManager'),(584,'Claim','filter','READ','ALLOW','ROLE','salesPerson'),(585,'Claim','logs','READ','ALLOW','ROLE','claimManager'),(586,'Ticket','find','READ','ALLOW','ROLE','employee'),(587,'Ticket','findById','READ','ALLOW','ROLE','employee'),(588,'Ticket','findOne','READ','ALLOW','ROLE','employee'),(589,'Ticket','getVolume','READ','ALLOW','ROLE','employee'),(590,'Ticket','getTotalVolume','READ','ALLOW','ROLE','employee'),(591,'Ticket','summary','READ','ALLOW','ROLE','employee'),(592,'Ticket','priceDifference','READ','ALLOW','ROLE','employee'),(593,'Ticket','componentUpdate','WRITE','ALLOW','ROLE','employee'),(594,'Ticket','new','WRITE','ALLOW','ROLE','employee'),(595,'Ticket','isEditable','READ','ALLOW','ROLE','employee'),(596,'Ticket','setDeleted','WRITE','ALLOW','ROLE','salesPerson'),(597,'Ticket','restore','WRITE','ALLOW','ROLE','employee'),(598,'Ticket','getSales','READ','ALLOW','ROLE','employee'),(599,'Ticket','getSalesPersonMana','READ','ALLOW','ROLE','employee'),(600,'Ticket','filter','READ','ALLOW','ROLE','employee'),(601,'Ticket','makeInvoice','WRITE','ALLOW','ROLE','employee'),(602,'Ticket','updateEditableTicket','WRITE','ALLOW','ROLE','employee'),(603,'Ticket','updateDiscount','WRITE','ALLOW','ROLE','employee'),(604,'Ticket','transferSales','WRITE','ALLOW','ROLE','employee'),(605,'Ticket','sendSms','WRITE','ALLOW','ROLE','employee'),(606,'Ticket','isLocked','READ','ALLOW','ROLE','employee'),(607,'Ticket','freightCost','READ','ALLOW','ROLE','employee'),(608,'Ticket','getComponentsSum','READ','ALLOW','ROLE','employee'),(609,'Ticket','updateAttributes','WRITE','ALLOW','ROLE','delivery'),(610,'Ticket','deliveryNoteCsv','READ','ALLOW','ROLE','employee'),(611,'State','find','READ','ALLOW','ROLE','employee'),(612,'State','findById','READ','ALLOW','ROLE','employee'),(613,'State','findOne','READ','ALLOW','ROLE','employee'),(614,'Worker','find','READ','ALLOW','ROLE','employee'),(615,'Worker','findById','READ','ALLOW','ROLE','employee'),(616,'Worker','findOne','READ','ALLOW','ROLE','employee'),(617,'Worker','filter','READ','ALLOW','ROLE','employee'),(618,'Worker','getWorkedHours','READ','ALLOW','ROLE','employee'),(619,'Worker','active','READ','ALLOW','ROLE','employee'),(620,'Worker','activeWithRole','READ','ALLOW','ROLE','employee'),(621,'Worker','uploadFile','WRITE','ALLOW','ROLE','hr'),(622,'Worker','contracts','READ','ALLOW','ROLE','employee'),(623,'Worker','holidays','READ','ALLOW','ROLE','employee'),(624,'Worker','activeContract','READ','ALLOW','ROLE','employee'),(625,'Worker','activeWithInheritedRole','READ','ALLOW','ROLE','employee'),(626,'Ticket','collectionLabel','READ','ALLOW','ROLE','employee'),(628,'Ticket','expeditionPalletLabel','READ','ALLOW','ROLE','employee'),(629,'Ticket','editDiscount','WRITE','ALLOW','ROLE','artificialBoss'),(630,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','salesTeamBoss'),(635,'Ticket','updateAttributes','WRITE','ALLOW','ROLE','administrative'),(636,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','salesPerson'),(637,'Claim','downloadFile','READ','ALLOW','ROLE','salesPerson'),(638,'Agency','seeExpired','READ','ALLOW','ROLE','artificialBoss'),(639,'Agency','seeExpired','READ','ALLOW','ROLE','logisticAssistant'),(640,'Claim','filter','READ','ALLOW','ROLE','buyer'),(641,'Claim','find','READ','ALLOW','ROLE','buyer'),(642,'Claim','findById','READ','ALLOW','ROLE','buyer'),(643,'Claim','getSummary','READ','ALLOW','ROLE','buyer'),(644,'Claim','filter','READ','ALLOW','ROLE','handmadeBoss'),(645,'Claim','find','READ','ALLOW','ROLE','handmadeBoss'),(646,'Claim','findById','READ','ALLOW','ROLE','handmadeBoss'),(647,'Claim','getSummary','READ','ALLOW','ROLE','handmadeBoss'),(648,'Claim','__get__lines','READ','ALLOW','ROLE','claimManager'),(649,'Claim','__get__lines','READ','ALLOW','ROLE','salesPerson'),(650,'Claim','getSummary','READ','ALLOW','ROLE','deliveryBoss'),(651,'Claim','findById','READ','ALLOW','ROLE','deliveryBoss'),(652,'Claim','find','READ','ALLOW','ROLE','deliveryBoss'),(653,'Claim','filter','READ','ALLOW','ROLE','deliveryBoss'),(654,'Ticket','editZone','WRITE','ALLOW','ROLE','logisticAssistant'),(655,'Entry','addFromPackaging','WRITE','ALLOW','ROLE','production'),(656,'Entry','addFromBuy','WRITE','ALLOW','ROLE','production'),(657,'Supplier','getItemsPackaging','READ','ALLOW','ROLE','production'),(658,'Ticket','closeAll','WRITE','ALLOW','ROLE','system'),(659,'Account','*','*','ALLOW','ROLE','itManagement'),(660,'Account','*','READ','ALLOW','ROLE','employee'),(664,'MailForward','*','*','ALLOW','ROLE','itManagement'),(665,'Role','*','READ','ALLOW','ROLE','employee'),(666,'Role','*','WRITE','ALLOW','ROLE','it'),(667,'VnUser','*','*','ALLOW','ROLE','itManagement'),(668,'VnUser','__get__preview','READ','ALLOW','ROLE','employee'),(669,'VnUser','preview','*','ALLOW','ROLE','employee'),(670,'VnUser','create','*','ALLOW','ROLE','itManagement'),(671,'VnUser','renewToken','WRITE','ALLOW','ROLE','employee'),(672,'PackingSiteAdvanced','*','*','ALLOW','ROLE','production'),(673,'InvoiceOut','makePdfAndNotify','WRITE','ALLOW','ROLE','invoicing'),(674,'InvoiceOutConfig','*','READ','ALLOW','ROLE','invoicing'),(676,'Ticket','invoiceTickets','WRITE','ALLOW','ROLE','employee'),(680,'MailAliasAccount','*','READ','ALLOW','ROLE','employee'),(681,'MailAliasAccount','create','WRITE','ALLOW','ROLE','employee'),(682,'MailAliasAccount','deleteById','WRITE','ALLOW','ROLE','employee'),(683,'MailAliasAccount','canEditAlias','WRITE','ALLOW','ROLE','itManagement'),(684,'WorkerDisableExcluded','*','READ','ALLOW','ROLE','itManagement'),(685,'WorkerDisableExcluded','*','WRITE','ALLOW','ROLE','itManagement'),(686,'MailForward','*','*','ALLOW','ROLE','hr'),(687,'ClientSms','find','READ','ALLOW','ROLE','employee'),(688,'ClientSms','create','WRITE','ALLOW','ROLE','employee'),(689,'Vehicle','sorted','WRITE','ALLOW','ROLE','employee'),(690,'Roadmap','*','*','ALLOW','ROLE','palletizerBoss'),(691,'Roadmap','*','*','ALLOW','ROLE','productionBoss'),(692,'ExpeditionTruck','*','*','ALLOW','ROLE','palletizerBoss'),(693,'ExpeditionTruck','*','*','ALLOW','ROLE','productionBoss'),(694,'MailAliasAccount','canEditAlias','WRITE','ALLOW','ROLE','marketingBoss'),(695,'ViaexpressConfig','internationalExpedition','WRITE','ALLOW','ROLE','employee'),(696,'ViaexpressConfig','renderer','READ','ALLOW','ROLE','employee'),(697,'Ticket','transferClient','WRITE','ALLOW','ROLE','administrative'),(698,'Ticket','canEditWeekly','WRITE','ALLOW','ROLE','buyer'),(699,'TicketSms','find','READ','ALLOW','ROLE','salesPerson'),(701,'Docuware','upload','WRITE','ALLOW','ROLE','deliveryBoss'),(702,'Ticket','docuwareDownload','READ','ALLOW','ROLE','salesPerson'); /*!40000 ALTER TABLE `ACL` ENABLE KEYS */; UNLOCK TABLES; diff --git a/modules/item/back/methods/item/setVisibleDiscard.js b/modules/item/back/methods/item/setVisibleDiscard.js index bcdda1ced..08cc507c3 100644 --- a/modules/item/back/methods/item/setVisibleDiscard.js +++ b/modules/item/back/methods/item/setVisibleDiscard.js @@ -32,6 +32,6 @@ module.exports = Self => { Self.setVisibleDiscard = async(ctx, itemFk, warehouseFk, quantity, addressFk) => { const query = `CALL vn.item_setVisibleDiscard(?, ?, ?, ?)`; - await Self.rawSql(query, [itemFk, warehouseFk, quantity, addressFk]); + await Self.rawSql(query, [itemFk, warehouseFk, quantity, addressFk], {userId: ctx.req.accessToken.userId}); }; }; From 204770c2de88d1e6251c2bc339a7d0426b508f8d Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 28 Sep 2023 13:53:46 +0200 Subject: [PATCH 163/427] refs #6224 deploy: init version 234201 --- CHANGELOG.md | 5 +++++ db/changes/234201/.gitkeep | 0 package-lock.json | 4 ++-- package.json | 2 +- 4 files changed, 8 insertions(+), 3 deletions(-) create mode 100644 db/changes/234201/.gitkeep diff --git a/CHANGELOG.md b/CHANGELOG.md index 79688cb56..e95ac0f64 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,11 @@ 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). +## [2342.01] - 2023-10-19 + +### Added +### Changed +### Fixed ## [2340.01] - 2023-10-05 diff --git a/db/changes/234201/.gitkeep b/db/changes/234201/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/package-lock.json b/package-lock.json index 10b5e6b02..c3f88bc2c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "salix-back", - "version": "23.32.02", + "version": "23.42.01", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "salix-back", - "version": "23.26.01", + "version": "23.42.01", "license": "GPL-3.0", "dependencies": { "axios": "^1.2.2", diff --git a/package.json b/package.json index d250071a6..3320705f5 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "salix-back", - "version": "23.40.01", + "version": "23.42.01", "author": "Verdnatura Levante SL", "description": "Salix backend", "license": "GPL-3.0", From f3c55cdee989fa8256bc7c19d83f3bc70d511b27 Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 28 Sep 2023 16:00:09 +0200 Subject: [PATCH 164/427] refs #5929 fix(isEditable): can edit if is weekly --- db/dump/fixtures.sql | 2 -- modules/ticket/back/methods/ticket/isEditableOrThrow.js | 2 +- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 9187e2871..c10b5665a 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -1409,10 +1409,8 @@ INSERT INTO `cache`.`cache_calc`(`id`, `cache_id`, `cacheName`, `params`, `last_ INSERT INTO `vn`.`ticketWeekly`(`ticketFk`, `weekDay`) VALUES - (1, 0), (2, 1), (3, 2), - (4, 4), (5, 6), (15, 6); diff --git a/modules/ticket/back/methods/ticket/isEditableOrThrow.js b/modules/ticket/back/methods/ticket/isEditableOrThrow.js index 6a8bafa2c..f8285cecd 100644 --- a/modules/ticket/back/methods/ticket/isEditableOrThrow.js +++ b/modules/ticket/back/methods/ticket/isEditableOrThrow.js @@ -40,7 +40,7 @@ module.exports = Self => { if (!isEditable && !isRoleAdvanced) throw new ForbiddenError(`This ticket is not editable.`); - if (isLocked) + if (isLocked && !isWeekly) throw new ForbiddenError(`This ticket is locked.`); if (isWeekly && !canEditWeeklyTicket) From 542119983b303a093e8cec7caaad2c9818ddce42 Mon Sep 17 00:00:00 2001 From: alexm Date: Fri, 29 Sep 2023 09:28:23 +0200 Subject: [PATCH 165/427] refs #5929 test: fix test after fix ticket_isEditable --- e2e/helpers/selectors.js | 3 +-- e2e/paths/05-ticket/09_weekly.spec.js | 10 ++++++---- .../methods/ticket-request/specs/filter.spec.js | 10 +++++----- .../methods/ticket-weekly/specs/filter.spec.js | 14 +++++++------- .../back/methods/ticket/specs/isEditable.spec.js | 2 +- 5 files changed, 20 insertions(+), 19 deletions(-) diff --git a/e2e/helpers/selectors.js b/e2e/helpers/selectors.js index 1b18eb866..6f78d7c4e 100644 --- a/e2e/helpers/selectors.js +++ b/e2e/helpers/selectors.js @@ -520,8 +520,7 @@ export default { searchResultDate: 'vn-ticket-summary [label=Landed] span', topbarSearch: 'vn-searchbar', moreMenu: 'vn-ticket-index vn-icon-button[icon=more_vert]', - fourthWeeklyTicket: 'vn-ticket-weekly-index vn-card smart-table slot-table tr:nth-child(5)', - fiveWeeklyTicket: 'vn-ticket-weekly-index vn-card smart-table slot-table tr:nth-child(6)', + thirdWeeklyTicket: 'vn-ticket-weekly-index vn-card smart-table slot-table tr:nth-child(4)', weeklyTicket: 'vn-ticket-weekly-index vn-card smart-table slot-table table tbody tr', firstWeeklyTicketDeleteIcon: 'vn-ticket-weekly-index vn-card smart-table slot-table tr:nth-child(2) vn-icon-button[icon="delete"]', firstWeeklyTicketAgency: 'vn-ticket-weekly-index vn-card smart-table slot-table tr:nth-child(2) [ng-model="weekly.agencyModeFk"]', diff --git a/e2e/paths/05-ticket/09_weekly.spec.js b/e2e/paths/05-ticket/09_weekly.spec.js index a9cce2ead..74febfd01 100644 --- a/e2e/paths/05-ticket/09_weekly.spec.js +++ b/e2e/paths/05-ticket/09_weekly.spec.js @@ -19,7 +19,7 @@ describe('Ticket descriptor path', () => { it('should count the amount of tickets in the turns section', async() => { const result = await page.countElement(selectors.ticketsIndex.weeklyTicket); - expect(result).toEqual(7); + expect(result).toEqual(5); }); it('should go back to the ticket index then search and access a ticket summary', async() => { @@ -45,7 +45,7 @@ describe('Ticket descriptor path', () => { it('should confirm the ticket 11 was added to thursday', async() => { await page.accessToSection('ticket.weekly.index'); - const result = await page.waitToGetProperty(selectors.ticketsIndex.fourthWeeklyTicket, 'value'); + const result = await page.waitToGetProperty(selectors.ticketsIndex.thirdWeeklyTicket, 'value'); expect(result).toEqual('Thursday'); }); @@ -80,7 +80,9 @@ describe('Ticket descriptor path', () => { it('should confirm the ticket 11 was added on saturday', async() => { await page.accessToSection('ticket.weekly.index'); - const result = await page.waitToGetProperty(selectors.ticketsIndex.fiveWeeklyTicket, 'value'); + await page.waitForTimeout(5000); + + const result = await page.waitToGetProperty(selectors.ticketsIndex.thirdWeeklyTicket, 'value'); expect(result).toEqual('Saturday'); }); @@ -104,7 +106,7 @@ describe('Ticket descriptor path', () => { await page.doSearch(); const nResults = await page.countElement(selectors.ticketsIndex.searchWeeklyResult); - expect(nResults).toEqual(7); + expect(nResults).toEqual(5); }); it('should update the agency then remove it afterwards', async() => { diff --git a/modules/ticket/back/methods/ticket-request/specs/filter.spec.js b/modules/ticket/back/methods/ticket-request/specs/filter.spec.js index ae004a024..9ab89f009 100644 --- a/modules/ticket/back/methods/ticket-request/specs/filter.spec.js +++ b/modules/ticket/back/methods/ticket-request/specs/filter.spec.js @@ -14,7 +14,7 @@ describe('ticket-request filter()', () => { const result = await models.TicketRequest.filter(ctx, options); - expect(result.length).toEqual(3); + expect(result.length).toEqual(5); await tx.rollback(); } catch (e) { @@ -93,7 +93,7 @@ describe('ticket-request filter()', () => { const result = await models.TicketRequest.filter(ctx, options); const requestId = result[0].id; - expect(requestId).toEqual(3); + expect(requestId).toEqual(1); await tx.rollback(); } catch (e) { @@ -113,7 +113,7 @@ describe('ticket-request filter()', () => { const result = await models.TicketRequest.filter(ctx, options); const requestId = result[0].id; - expect(requestId).toEqual(3); + expect(requestId).toEqual(1); await tx.rollback(); } catch (e) { @@ -153,7 +153,7 @@ describe('ticket-request filter()', () => { const result = await models.TicketRequest.filter(ctx, {order: 'id'}, options); const requestId = result[0].id; - expect(requestId).toEqual(3); + expect(requestId).toEqual(1); await tx.rollback(); } catch (e) { @@ -173,7 +173,7 @@ describe('ticket-request filter()', () => { const result = await models.TicketRequest.filter(ctx, options); const requestId = result[0].id; - expect(requestId).toEqual(3); + expect(requestId).toEqual(1); await tx.rollback(); } catch (e) { diff --git a/modules/ticket/back/methods/ticket-weekly/specs/filter.spec.js b/modules/ticket/back/methods/ticket-weekly/specs/filter.spec.js index 2587b6657..453b7924f 100644 --- a/modules/ticket/back/methods/ticket-weekly/specs/filter.spec.js +++ b/modules/ticket/back/methods/ticket-weekly/specs/filter.spec.js @@ -16,8 +16,8 @@ describe('ticket-weekly filter()', () => { const firstRow = result[0]; - expect(firstRow.ticketFk).toEqual(1); - expect(result.length).toEqual(6); + expect(firstRow.ticketFk).toEqual(2); + expect(result.length).toEqual(4); await tx.rollback(); } catch (e) { @@ -52,12 +52,12 @@ describe('ticket-weekly filter()', () => { try { const options = {transaction: tx}; - const ctx = {req: {accessToken: {userId: authUserId}}, args: {search: 'bruce'}}; + const ctx = {req: {accessToken: {userId: authUserId}}, args: {search: 'max'}}; const result = await models.TicketWeekly.filter(ctx, null, options); const firstRow = result[0]; - expect(firstRow.clientName).toEqual('Bruce Wayne'); + expect(firstRow.clientName).toEqual('Max Eisenhardt'); await tx.rollback(); } catch (e) { @@ -72,13 +72,13 @@ describe('ticket-weekly filter()', () => { try { const options = {transaction: tx}; - const ctx = {req: {accessToken: {userId: authUserId}}, args: {search: 1101}}; + const ctx = {req: {accessToken: {userId: authUserId}}, args: {search: 1105}}; const result = await models.TicketWeekly.filter(ctx, null, options); const firstRow = result[0]; - expect(firstRow.clientFk).toEqual(1101); - expect(firstRow.clientName).toEqual('Bruce Wayne'); + expect(firstRow.clientFk).toEqual(1105); + expect(firstRow.clientName).toEqual('Max Eisenhardt'); await tx.rollback(); } catch (e) { diff --git a/modules/ticket/back/methods/ticket/specs/isEditable.spec.js b/modules/ticket/back/methods/ticket/specs/isEditable.spec.js index 301745ed3..9dd1f8544 100644 --- a/modules/ticket/back/methods/ticket/specs/isEditable.spec.js +++ b/modules/ticket/back/methods/ticket/specs/isEditable.spec.js @@ -8,7 +8,7 @@ describe('isEditable()', () => { try { const options = {transaction: tx}; const ctx = {req: {accessToken: {userId: 35}}}; - result = await models.Ticket.isEditable(ctx, 5, options); + result = await models.Ticket.isEditable(ctx, 19, options); await tx.rollback(); } catch (error) { await tx.rollback(); From 0fa56149d7b03697fe60c1efdefb1531c57452d5 Mon Sep 17 00:00:00 2001 From: pablone Date: Fri, 29 Sep 2023 09:47:22 +0200 Subject: [PATCH 166/427] refs #6266 smsfix --- modules/ticket/front/descriptor-menu/index.js | 2 +- modules/ticket/front/descriptor/locale/en.yml | 2 +- modules/ticket/front/descriptor/locale/es.yml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/ticket/front/descriptor-menu/index.js b/modules/ticket/front/descriptor-menu/index.js index d1f39fd19..18db8c147 100644 --- a/modules/ticket/front/descriptor-menu/index.js +++ b/modules/ticket/front/descriptor-menu/index.js @@ -201,7 +201,7 @@ class Controller extends Section { sendImportSms() { const params = { ticketId: this.id, - created: this.ticket.updated + shipped: this.ticket.shipped }; this.showSMSDialog({ message: this.$t('Minimum is needed', params) diff --git a/modules/ticket/front/descriptor/locale/en.yml b/modules/ticket/front/descriptor/locale/en.yml index 8eed2265d..698d699d7 100644 --- a/modules/ticket/front/descriptor/locale/en.yml +++ b/modules/ticket/front/descriptor/locale/en.yml @@ -1,3 +1,3 @@ Make a payment: "Verdnatura communicates:\rYour order is pending of payment.\rPlease, enter the web page and make the payment with card.\rThank you." -Minimum is needed: "Verdnatura communicates:\rA minimum import of 50€ (Without BAT) is needed for your order {{ticketId}} from date {{created | date: 'dd/MM/yyyy'}} to receive it with no extra fees." +Minimum is needed: "Verdnatura communicates:\rA minimum import of 50€ (Without BAT) is needed for your order {{ticketId}} from date {{shipped | date: 'dd/MM/yyyy'}} to receive it with no extra fees." Send changes: "Verdnatura communicates:\rOrder {{ticketId}} date {{created | date: 'dd/MM/yyyy'}}\r{{changes}}" diff --git a/modules/ticket/front/descriptor/locale/es.yml b/modules/ticket/front/descriptor/locale/es.yml index 86b1a6b57..8e3b5e473 100644 --- a/modules/ticket/front/descriptor/locale/es.yml +++ b/modules/ticket/front/descriptor/locale/es.yml @@ -4,7 +4,7 @@ Show pallet report: Ver hoja de pallet Change shipped hour: Cambiar hora de envío Shipped hour: Hora de envío Make a payment: "Verdnatura le comunica:\rSu pedido está pendiente de pago.\rPor favor, entre en la página web y efectue el pago con tarjeta.\rMuchas gracias." -Minimum is needed: "Verdnatura le recuerda:\rEs necesario un importe mínimo de 50€ (Sin IVA) en su pedido {{ticketId}} del día {{created | date: 'dd/MM/yyyy'}} para recibirlo sin portes adicionales." +Minimum is needed: "Verdnatura le recuerda:\rEs necesario un importe mínimo de 50€ (Sin IVA) en su pedido {{ticketId}} del día {{shipped | date: 'dd/MM/yyyy'}} para recibirlo sin portes adicionales." Ticket invoiced: Ticket facturado Make invoice: Crear factura Regenerate invoice PDF: Regenerar PDF factura From a0a59b672f81ec0a58224da567375829cd28ff15 Mon Sep 17 00:00:00 2001 From: alexm Date: Fri, 29 Sep 2023 10:04:57 +0200 Subject: [PATCH 167/427] =?UTF-8?q?refs=20#6271=20hotFix(email):=20clientC?= =?UTF-8?q?reditEmail=20=E2=86=92=20creditRequestEmail?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- modules/client/back/methods/client/creditRequestEmail.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/client/back/methods/client/creditRequestEmail.js b/modules/client/back/methods/client/creditRequestEmail.js index 0255949e0..60047de77 100644 --- a/modules/client/back/methods/client/creditRequestEmail.js +++ b/modules/client/back/methods/client/creditRequestEmail.js @@ -1,5 +1,5 @@ module.exports = Self => { - Self.remoteMethodCtx('clientCreditEmail', { + Self.remoteMethodCtx('creditRequestEmail', { description: 'Sends the credit request email with an attached PDF', accessType: 'WRITE', accepts: [ @@ -40,5 +40,5 @@ module.exports = Self => { }, }); - Self.clientCreditEmail = ctx => Self.sendTemplate(ctx, 'credit-request'); + Self.creditRequestEmail = ctx => Self.sendTemplate(ctx, 'credit-request'); }; From 9536fdba583decd85c81809814edaa5ee935737e Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 29 Sep 2023 10:10:58 +0200 Subject: [PATCH 168/427] ref #6119 refactor --- front/core/components/link-phone/index.html | 27 ++++++++++--------- front/core/components/link-phone/index.js | 4 --- modules/client/front/summary/index.html | 4 +-- modules/order/front/summary/index.html | 1 - .../route/front/roadmap/summary/index.html | 1 - modules/ticket/front/summary/index.html | 4 --- modules/worker/front/descriptor/index.html | 2 -- modules/worker/front/summary/index.html | 3 --- 8 files changed, 16 insertions(+), 30 deletions(-) diff --git a/front/core/components/link-phone/index.html b/front/core/components/link-phone/index.html index fc520cefd..2789ab75c 100644 --- a/front/core/components/link-phone/index.html +++ b/front/core/components/link-phone/index.html @@ -1,13 +1,14 @@ - - - - \ No newline at end of file + + {{$ctrl.phoneNumber}} + + + + + +- diff --git a/front/core/components/link-phone/index.js b/front/core/components/link-phone/index.js index d5c828f21..6f3eec5b1 100644 --- a/front/core/components/link-phone/index.js +++ b/front/core/components/link-phone/index.js @@ -3,8 +3,6 @@ import './style.scss'; class Controller { constructor() { this.phoneNumber = null; - this.icon = true; - this.showNumber = true; } } @@ -13,7 +11,5 @@ ngModule.vnComponent('vnLinkPhone', { controller: Controller, bindings: { phoneNumber: '<', - icon: ' - {{$ctrl.summary.phone | dashIfEmpty}} + - {{$ctrl.summary.mobile | dashIfEmpty}} + diff --git a/modules/order/front/summary/index.html b/modules/order/front/summary/index.html index e9bdf33b2..218359992 100644 --- a/modules/order/front/summary/index.html +++ b/modules/order/front/summary/index.html @@ -49,7 +49,6 @@ value="{{$ctrl.summary.landed | date: 'dd/MM/yyyy HH:mm'}}"> - {{$ctrl.summary.address.phone | dashIfEmpty}} diff --git a/modules/route/front/roadmap/summary/index.html b/modules/route/front/roadmap/summary/index.html index aea7e717b..9fab0bf87 100644 --- a/modules/route/front/roadmap/summary/index.html +++ b/modules/route/front/roadmap/summary/index.html @@ -26,7 +26,6 @@ - {{summary.phone | dashIfEmpty}} diff --git a/modules/ticket/front/summary/index.html b/modules/ticket/front/summary/index.html index 4a92daa39..3c60352a7 100644 --- a/modules/ticket/front/summary/index.html +++ b/modules/ticket/front/summary/index.html @@ -84,7 +84,6 @@ - {{$ctrl.summary.address.phone | dashIfEmpty}} @@ -92,21 +91,18 @@ - {{$ctrl.summary.address.mobile | dashIfEmpty}} - {{$ctrl.summary.client.phone | dashIfEmpty}} - {{$ctrl.summary.client.mobile | dashIfEmpty}} diff --git a/modules/worker/front/descriptor/index.html b/modules/worker/front/descriptor/index.html index 4a5fb894e..2dfa41ee3 100644 --- a/modules/worker/front/descriptor/index.html +++ b/modules/worker/front/descriptor/index.html @@ -38,7 +38,6 @@ - {{$ctrl.worker.phone | dashIfEmpty}} @@ -46,7 +45,6 @@ - {{$ctrl.worker.sip.extension | dashIfEmpty}} diff --git a/modules/worker/front/summary/index.html b/modules/worker/front/summary/index.html index 1826f30a8..2372634bc 100644 --- a/modules/worker/front/summary/index.html +++ b/modules/worker/front/summary/index.html @@ -43,20 +43,17 @@ - {{worker.mobileExtension | dashIfEmpty}} - {{worker.phone | dashIfEmpty}} - {{worker.client.phone | dashIfEmpty}} From 934b4c4b364d74b5e00d46af3159e85fe3000406 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Fri, 29 Sep 2023 10:53:06 +0200 Subject: [PATCH 169/427] refs #5890 --- db/changes/234002/.gitkeep | 0 .../01-itemShelvingSale.sql | 48 ++++++++----------- 2 files changed, 20 insertions(+), 28 deletions(-) create mode 100644 db/changes/234002/.gitkeep rename db/changes/{234001 => 234002}/01-itemShelvingSale.sql (90%) diff --git a/db/changes/234002/.gitkeep b/db/changes/234002/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/db/changes/234001/01-itemShelvingSale.sql b/db/changes/234002/01-itemShelvingSale.sql similarity index 90% rename from db/changes/234001/01-itemShelvingSale.sql rename to db/changes/234002/01-itemShelvingSale.sql index b98004bc5..817c6317a 100644 --- a/db/changes/234001/01-itemShelvingSale.sql +++ b/db/changes/234002/01-itemShelvingSale.sql @@ -1,13 +1,20 @@ +ALTER TABLE `vn`.`itemShelvingSale` DROP COLUMN IF EXISTS isPicked; -ALTER TABLE `vn`.`itemShelvingSale` ADD isPicked TINYINT(1) DEFAULT FALSE NOT NULL; +ALTER TABLE`vn`.`itemShelvingSale` + ADD isPicked TINYINT(1) DEFAULT FALSE NOT NULL; + +ALTER TABLE `vn`.`productionConfig` DROP COLUMN IF EXISTS orderMode; + +ALTER TABLE `vn`.`productionConfig` + ADD orderMode ENUM('Location', 'Age') NOT NULL DEFAULT 'Location'; DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_addByCollection`( +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_reserveByCollection`( vCollectionFk INT(11) ) BEGIN /** - * Guarda la ubicación para el contenido de una colección + * Reserva cantidades con ubicaciones para el contenido de una colección * * @param vCollectionFk Identificador de collection */ @@ -27,7 +34,7 @@ BEGIN AND st.saleFk IS NULL AND NOT s.isPicked; - CALL itemShelvingSale_addNew(); + CALL itemShelvingSale_reserve(); END$$ DELIMITER ; @@ -87,9 +94,6 @@ BEGIN SET visible = IF(vIsItemShelvingSaleEmpty, 0, GREATEST(0,visible - vQuantity)) WHERE id = vItemShelvingFk; - /*Se podría preguntar por la cantidad correcta de la ubicació o insertar en una tabla - para que lo tenga en cuenta la gente que está haciendo inventario*/ - IF vIsItemShelvingSaleEmpty THEN OPEN vSales; l: LOOP @@ -104,7 +108,7 @@ l: LOOP ENGINE = MEMORY SELECT vCursorSaleFk, vUserFk; - CALL itemShelvingSale_addNewWhitUser(); + CALL itemShelvingSale_reserveWhitUser(); DROP TEMPORARY TABLE tmp.sale; END LOOP; @@ -124,7 +128,7 @@ l: LOOP AND NOT isPicked; IF vRemainingQuantity THEN - CALL itemShelvingSale_addBySale (vSaleFk, vRemainingQuantity, NULL); + CALL itemShelvingSale_reserveBySale (vSaleFk, vRemainingQuantity, NULL); SELECT SUM(quantity) INTO vRemainingQuantity FROM itemShelvingSale @@ -156,10 +160,10 @@ DELIMITER ; DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_addNew`() +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_reserve`() BEGIN /** - * Guarda la ubicacion para un conjunto de sales del mismo wareHouse + * Reserva cantidades con ubicaciones para un conjunto de sales del mismo wareHouse * * @table tmp.sale(saleFk, userFk) */ @@ -227,12 +231,10 @@ BEGIN ish.visible >= s.quantity DESC, s.quantity MOD ish.grouping = 0 DESC, ish.grouping DESC, - IF(pc.orderMode = 'Location', p.pickingOrder, ish.created) - LIMIT 100000000000000000 + IF(pc.orderMode = 'Location', p.pickingOrder, ish.created) )sub )sub2 - WHERE quantityToReserve > 0 - ; + WHERE quantityToReserve > 0; INSERT INTO itemShelvingSale( itemShelvingFk, @@ -252,14 +254,14 @@ DELIMITER ; DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_addBySale`( +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_reserveBySale`( vSelf INT , vQuantity INT, vUserFk INT ) BEGIN /** - * Reserva la ubicación para una saleFk + * Reserva cantida y ubicación para una saleFk * * @param vSelf Identificador de la venta * @param vQuantity Cantidad a reservar @@ -269,7 +271,7 @@ BEGIN ENGINE = MEMORY SELECT vSelf saleFk, vUserFk userFk; - CALL itemShelvingSale_addNew(); + CALL itemShelvingSale_reserve(); END$$ DELIMITER ; @@ -287,13 +289,3 @@ BEGIN END$$ DELIMITER ; - -ALTER TABLE `vn`.`itemShelvingSale` DROP COLUMN IF EXISTS isPicked; - -ALTER TABLE`vn`.`itemShelvingSale` - ADD isPicked TINYINT(1) DEFAULT FALSE NOT NULL; - -ALTER TABLE `vn`.`productionConfig` DROP COLUMN IF EXISTS orderMode; - -ALTER TABLE `vn`.`productionConfig` - ADD orderMode ENUM('Location', 'Age') NOT NULL DEFAULT 'Location'; \ No newline at end of file From 6691cbf32f1285240b093f3ed24c720f3e380c98 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 29 Sep 2023 11:24:24 +0200 Subject: [PATCH 170/427] ref #5914 changes moved --- db/changes/{234001 => 234201}/00-transferInvoice.sql | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename db/changes/{234001 => 234201}/00-transferInvoice.sql (100%) diff --git a/db/changes/234001/00-transferInvoice.sql b/db/changes/234201/00-transferInvoice.sql similarity index 100% rename from db/changes/234001/00-transferInvoice.sql rename to db/changes/234201/00-transferInvoice.sql From b33700abc93d568d554e5715d05a192b62f226e5 Mon Sep 17 00:00:00 2001 From: alexm Date: Fri, 29 Sep 2023 11:57:25 +0200 Subject: [PATCH 171/427] refs #6216 feat(ticket_sale): open filtered ticketLog --- db/dump/fixtures.sql | 18 ++++++++-------- front/salix/components/index.js | 1 - .../salix/components/instance-log/index.html | 12 ----------- front/salix/components/instance-log/index.js | 21 ------------------- .../salix/components/instance-log/style.scss | 9 -------- front/salix/components/log/index.js | 9 ++++++++ modules/ticket/front/log/index.html | 7 ++++++- modules/ticket/front/routes.json | 2 +- modules/ticket/front/sale/index.html | 9 +------- modules/ticket/front/sale/index.js | 8 +++++++ 10 files changed, 34 insertions(+), 62 deletions(-) delete mode 100644 front/salix/components/instance-log/index.html delete mode 100644 front/salix/components/instance-log/index.js delete mode 100644 front/salix/components/instance-log/style.scss diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index eb28c4a01..4b726a833 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -2834,24 +2834,24 @@ UPDATE `account`.`user` INSERT INTO `vn`.`ticketLog` (`originFk`, userFk, `action`, changedModel, oldInstance, newInstance, changedModelId, `description`) VALUES - (7, 18, 'update', 'Sale', '{"quantity":1}', '{"quantity":10}', 1, NULL), - (7, 18, 'update', 'Ticket', '{"quantity":1,"concept":"Chest ammo box"}', '{"quantity":10,"concept":"Chest ammo box"}', 1, NULL), - (7, 18, 'update', 'Sale', '{"price":3}', '{"price":5}', 1, NULL), + (7, 18, 'update', 'Sale', '{"quantity":1}', '{"quantity":10}', 22, NULL), + (7, 18, 'update', 'Ticket', '{"quantity":1,"concept":"Chest ammo box"}', '{"quantity":10,"concept":"Chest ammo box"}', 22, NULL), + (7, 18, 'update', 'Sale', '{"price":3}', '{"price":5}', 22, NULL), (7, 18, 'update', NULL, NULL, NULL, NULL, "Cambio cantidad Melee weapon heavy shield 100cm de '5' a '10'"), - (16, 9, 'update', 'Sale', '{"quantity":10,"concept":"Shield", "price": 10.5, "itemFk": 1}', '{"quantity":8,"concept":"Shield", "price": 10.5, "itemFk": 1}' , 5689, 'Shield'); + (16, 9, 'update', 'Sale', '{"quantity":10,"concept":"Shield", "price": 10.5, "itemFk": 1}', '{"quantity":8,"concept":"Shield", "price": 10.5, "itemFk": 1}' , 12, 'Shield'); INSERT INTO `vn`.`ticketLog` (originFk, userFk, `action`, creationDate, changedModel, changedModelId, changedModelValue, oldInstance, newInstance, description) VALUES (1, NULL, 'delete', '2001-06-09 11:00:04', 'Ticket', 45, 'Spider Man' , NULL, NULL, NULL), (1, 18, 'select', '2001-06-09 11:00:03', 'Ticket', 45, 'Spider Man' , NULL, NULL, NULL), - (1, NULL, 'update', '2001-05-09 10:00:02', 'Sale', 69854, 'Armor' , '{"isPicked": false}','{"isPicked": true}', NULL), - (1, 18, 'update', '2001-01-01 10:05:01', 'Sale', 69854, 'Armor' , NULL, NULL, 'Armor quantity changed from ''15'' to ''10'''), - (1, NULL, 'delete', '2001-01-01 10:00:10', 'Sale', 5689, 'Shield' , '{"quantity":10,"concept":"Shield"}', NULL, NULL), - (1, 18, 'insert', '2000-12-31 15:00:05', 'Sale', 69854, 'Armor' , NULL,'{"quantity":15,"concept":"Armor", "price": 345.99, "itemFk": 2}', NULL), + (1, NULL, 'update', '2001-05-09 10:00:02', 'Sale', 5, 'Armor' , '{"isPicked": false}','{"isPicked": true}', NULL), + (1, 18, 'update', '2001-01-01 10:05:01', 'Sale', 5, 'Armor' , NULL, NULL, 'Armor quantity changed from ''15'' to ''10'''), + (1, NULL, 'delete', '2001-01-01 10:00:10', 'Sale', 4, 'Shield' , '{"quantity":10,"concept":"Shield"}', NULL, NULL), + (1, 18, 'insert', '2000-12-31 15:00:05', 'Sale', 1, 'Armor' , NULL,'{"quantity":15,"concept":"Armor", "price": 345.99, "itemFk": 2}', NULL), (1, 18, 'update', '2000-12-28 08:40:45', 'Ticket', 45, 'Spider Man' , '{"warehouseFk":60,"shipped":"2023-05-16T22:00:00.000Z","nickname":"Super Man","isSigned":true,"isLabeled":true,"isPrinted":true,"packages":0,"hour":0,"isBlocked":false,"hasPriority":false,"companyFk":442,"landed":"2023-05-17T22:00:00.000Z","isBoxed":true,"isDeleted":true,"zoneFk":713,"zonePrice":13,"zoneBonus":0}','{"warehouseFk":61,"shipped":"2023-05-17T22:00:00.000Z","nickname":"Spider Man","isSigned":false,"isLabeled":false,"isPrinted":false,"packages":1,"hour":0,"isBlocked":true,"hasPriority":true,"companyFk":443,"landed":"2023-05-18T22:00:00.000Z","isBoxed":false,"isDeleted":false,"zoneFk":713,"zonePrice":13,"zoneBonus":1}', NULL), (1, 18, 'select', '2000-12-27 03:40:30', 'Ticket', 45, NULL , NULL, NULL, NULL), - (1, 18, 'insert', '2000-04-10 09:40:15', 'Sale', 5689, 'Shield' , NULL, '{"quantity":10,"concept":"Shield", "price": 10.5, "itemFk": 1}', NULL), + (1, 18, 'insert', '2000-04-10 09:40:15', 'Sale', 4, 'Shield' , NULL, '{"quantity":10,"concept":"Shield", "price": 10.5, "itemFk": 1}', NULL), (1, 18, 'insert', '1999-05-09 10:00:00', 'Ticket', 45, 'Super Man' , NULL, '{"id":45,"clientFk":8608,"warehouseFk":60,"shipped":"2023-05-16T22:00:00.000Z","nickname":"Super Man","addressFk":48637,"isSigned":true,"isLabeled":true,"isPrinted":true,"packages":0,"hour":0,"created":"2023-05-16T11:42:56.000Z","isBlocked":false,"hasPriority":false,"companyFk":442,"agencyModeFk":639,"landed":"2023-05-17T22:00:00.000Z","isBoxed":true,"isDeleted":true,"zoneFk":713,"zonePrice":13,"zoneBonus":0}', NULL); INSERT INTO `vn`.`osTicketConfig` (`id`, `host`, `user`, `password`, `oldStatus`, `newStatusId`, `day`, `comment`, `hostDb`, `userDb`, `passwordDb`, `portDb`, `responseType`, `fromEmailId`, `replyTo`) VALUES diff --git a/front/salix/components/index.js b/front/salix/components/index.js index 555a18450..9addc23c8 100644 --- a/front/salix/components/index.js +++ b/front/salix/components/index.js @@ -21,5 +21,4 @@ import './user-popover'; import './upload-photo'; import './bank-entity'; import './log'; -import './instance-log'; import './sendSms'; diff --git a/front/salix/components/instance-log/index.html b/front/salix/components/instance-log/index.html deleted file mode 100644 index 9794f75c2..000000000 --- a/front/salix/components/instance-log/index.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - diff --git a/front/salix/components/instance-log/index.js b/front/salix/components/instance-log/index.js deleted file mode 100644 index 6d8497c2d..000000000 --- a/front/salix/components/instance-log/index.js +++ /dev/null @@ -1,21 +0,0 @@ -import ngModule from '../../module'; -import Section from '../section'; -import './style.scss'; - -export default class Controller extends Section { - open() { - this.$.instanceLog.show(); - } -} - -ngModule.vnComponent('vnInstanceLog', { - controller: Controller, - template: require('./index.html'), - bindings: { - model: '<', - originId: '<', - changedModelId: '<', - changedModel: '@', - url: '@' - } -}); diff --git a/front/salix/components/instance-log/style.scss b/front/salix/components/instance-log/style.scss deleted file mode 100644 index f355e0ac8..000000000 --- a/front/salix/components/instance-log/style.scss +++ /dev/null @@ -1,9 +0,0 @@ -vn-log.vn-instance-log { - vn-card { - width: 900px; - visibility: hidden; - & > * { - visibility: visible; - } - } -} diff --git a/front/salix/components/log/index.js b/front/salix/components/log/index.js index 176815eef..790b7fbb8 100644 --- a/front/salix/components/log/index.js +++ b/front/salix/components/log/index.js @@ -72,6 +72,7 @@ export default class Controller extends Section { $postLink() { this.resetFilter(); + this.defaultFilter(); this.$.$watch( () => this.$.filter, () => this.applyFilter(), @@ -79,6 +80,14 @@ export default class Controller extends Section { ); } + defaultFilter() { + const defaultFilters = ['changedModel', 'changedModelId']; + for (const defaultFilter of defaultFilters) { + if (this[defaultFilter]) + this.$.filter[defaultFilter] = this[defaultFilter]; + } + } + get logs() { return this._logs; } diff --git a/modules/ticket/front/log/index.html b/modules/ticket/front/log/index.html index 91109d3eb..c36b0aa52 100644 --- a/modules/ticket/front/log/index.html +++ b/modules/ticket/front/log/index.html @@ -1 +1,6 @@ - \ No newline at end of file + + diff --git a/modules/ticket/front/routes.json b/modules/ticket/front/routes.json index e403ab02d..da39fbbf7 100644 --- a/modules/ticket/front/routes.json +++ b/modules/ticket/front/routes.json @@ -187,7 +187,7 @@ } }, { - "url" : "/log", + "url" : "/log?changedModel&changedModelId", "state": "ticket.card.log", "component": "vn-ticket-log", "description": "Log" diff --git a/modules/ticket/front/sale/index.html b/modules/ticket/front/sale/index.html index be9e81964..b10df317b 100644 --- a/modules/ticket/front/sale/index.html +++ b/modules/ticket/front/sale/index.html @@ -212,16 +212,9 @@ vn-none vn-tooltip="History" icon="history" - ng-click="log.open()" + ng-click="$ctrl.goToLog(sale.id)" ng-show="sale.$hasLogs"> - - diff --git a/modules/ticket/front/sale/index.js b/modules/ticket/front/sale/index.js index b68db6dc0..f946d0a25 100644 --- a/modules/ticket/front/sale/index.js +++ b/modules/ticket/front/sale/index.js @@ -558,6 +558,14 @@ class Controller extends Section { cancel() { this.$.editDiscount.hide(); } + + goToLog(saleId) { + this.$state.go('ticket.card.log', { + originId: this.$params.id, + changedModel: 'Sale', + changedModelId: saleId + }); + } } ngModule.vnComponent('vnTicketSale', { From 9a7cb3ef7b7074f1a6316197a3894b72406fb0bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Fri, 29 Sep 2023 12:30:05 +0200 Subject: [PATCH 172/427] refs #6254 collection_getTickets --- back/methods/collection/getTickets.js | 155 ++++++++++---------------- loopback/locale/es.json | 3 +- 2 files changed, 62 insertions(+), 96 deletions(-) diff --git a/back/methods/collection/getTickets.js b/back/methods/collection/getTickets.js index 1d0daa43a..f39a71cdb 100644 --- a/back/methods/collection/getTickets.js +++ b/back/methods/collection/getTickets.js @@ -30,46 +30,37 @@ module.exports = Self => { const $t = ctx.req.__; // $translate const myOptions = {}; - let tx; - if (typeof options == 'object') Object.assign(myOptions, options); - if (!myOptions.transaction) { - tx = await Self.beginTransaction({}); - myOptions.transaction = tx; - } myOptions.userId = userId; const promises = []; - try { - const [tickets] = await Self.rawSql(`CALL vn.collection_getTickets(?)`, [id], myOptions); - const sales = await Self.rawSql(` - SELECT - s.ticketFk, + + const [tickets] = await Self.rawSql(`CALL vn.collection_getTickets(?)`, [id], myOptions); + const sales = await Self.rawSql(` + SELECT s.ticketFk, sgd.saleGroupFk, s.id saleFk, s.itemFk, i.longName, i.size, - IFNULL(sub2.semaphore,st.semaphore) semaphore, ic.color, - ip.productor, o.code origin, - s.concept, - b.packing, - b.grouping, + ish.packing, + ish.grouping, s.isAdded, - c.workerFk, - i.packingShelve, - sm.id hasMistake, - s.originalQuantity, + s.originalQuantity, s.quantity saleQuantity, - IF(p2.code IS NOT NULL, s.quantity, iss.quantity) reservedQuantity, + iss.quantity reservedQuantity, + SUM(iss.quantity) OVER (PARTITION BY s.id ORDER BY ish.id) accumulatedQuantity, + ROW_NUMBER () OVER (PARTITION BY s.id ORDER BY pickingOrder) currentItemShelving, + COUNT(*) OVER (PARTITION BY s.id ORDER BY s.id) totalItemShelving, sh.code, IFNULL(p2.code, p.code) parkingCode, IFNULL(p2.pickingOrder, p.pickingOrder) pickingOrder, iss.id itemShelvingSaleFk + iss.isChecked FROM ticketCollection tc LEFT JOIN collection c ON c.id = tc.collectionFk JOIN ticket t ON t.id = tc.ticketFk @@ -77,103 +68,79 @@ module.exports = Self => { LEFT JOIN saleGroupDetail sgd ON sgd.saleFk = s.id LEFT JOIN saleGroup sg ON sg.id = sgd.saleGroupFk LEFT JOIN parking p2 ON p2.id = sg.parkingFk - LEFT JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND lb.warehouse_id = t.warehouseFk - LEFT JOIN buy b ON b.id = lb.buy_id JOIN item i ON i.id = s.itemFk LEFT JOIN itemShelvingSale iss ON iss.saleFk = s.id LEFT JOIN itemShelving ish ON ish.id = iss.itemShelvingFk LEFT JOIN shelving sh ON sh.code = ish.shelvingFk LEFT JOIN parking p ON p.id = sh.parkingFk - LEFT JOIN ( - SELECT sub.saleFk, sub.isChecked, sub.stateFk, sub.originalQuantity, sub.semaphore - FROM ( - SELECT DISTINCT st.id, - st.saleFk, st.isChecked, st.stateFk, st.originalQuantity ,sta.semaphore - FROM ticketCollection tc - JOIN sale s ON s.ticketFk = tc.ticketFk - JOIN saleTracking st ON st.saleFk = s.id - JOIN state sta ON sta.id = st.stateFk - WHERE tc.collectionFk = ? - ORDER BY st.id DESC - LIMIT 10000000000000000000) sub - GROUP BY sub.saleFk, sub.stateFK - ) sub2 ON sub2.saleFk = s.id AND sub2.isChecked = 1 - LEFT JOIN state st ON st.id = sub2.stateFk LEFT JOIN itemColor ic ON ic.itemFk = s.itemFk - LEFT JOIN itemProductor ip ON ip.itemFk = s.itemFk LEFT JOIN origin o ON o.id = i.originFk - LEFT JOIN saleMistake sm ON sm.saleFk = s.id WHERE tc.collectionFk = ? - GROUP BY s.id, p.code, p2.code - ORDER BY pickingOrder`, [id, id], myOptions); + GROUP BY ish.id, p.code, p2.code + ORDER BY pickingOrder;`, [id], myOptions); - if (print) - await Self.rawSql(`CALL vn.collection_printSticker(?, ?)`, [id, null], myOptions); + if (print) + await Self.rawSql(`CALL vn.collection_printSticker(?, ?)`, [id, null], myOptions); - const collection = {collectionFk: id, tickets: []}; - if (tickets && tickets.length) { - for (const ticket of tickets) { - const ticketId = ticket.ticketFk; + const collection = {collectionFk: id, tickets: []}; + if (tickets && tickets.length) { + for (const ticket of tickets) { + const ticketId = ticket.ticketFk; - // SEND ROCKET - if (ticket.observaciones != '') { - for (observation of ticket.observaciones.split(' ')) { - if (['#', '@'].includes(observation.charAt(0))) { - promises.push(Self.app.models.Chat.send(ctx, observation, - $t('The ticket is in preparation', { - ticketId: ticketId, - ticketUrl: `${origin}/#!/ticket/${ticketId}/summary`, - salesPersonId: ticket.salesPersonFk - }))); - } + // SEND ROCKET + if (ticket.observaciones != '') { + for (observation of ticket.observaciones.split(' ')) { + if (['#', '@'].includes(observation.charAt(0))) { + promises.push(Self.app.models.Chat.send(ctx, observation, + $t('The ticket is in preparation', { + ticketId: ticketId, + ticketUrl: `${origin}/#!/ticket/${ticketId}/summary`, + salesPersonId: ticket.salesPersonFk + }))); } } + } - // SET COLLECTION - if (sales && sales.length) { - // GET BARCODES - const barcodes = await Self.rawSql(` - SELECT s.id saleFk, b.code, c.id - FROM vn.sale s - LEFT JOIN vn.itemBarcode b ON b.itemFk = s.itemFk - LEFT JOIN vn.buy c ON c.itemFk = s.itemFk - LEFT JOIN vn.entry e ON e.id = c.entryFk - LEFT JOIN vn.travel tr ON tr.id = e.travelFk - WHERE s.ticketFk = ? AND tr.landed >= DATE_SUB(util.VN_CURDATE(), INTERVAL 1 YEAR)`, - [ticketId], myOptions); + // SET COLLECTION + if (sales && sales.length) { + // GET BARCODES + const barcodes = await Self.rawSql(` + SELECT s.id saleFk, b.code, c.id + FROM vn.sale s + LEFT JOIN vn.itemBarcode b ON b.itemFk = s.itemFk + LEFT JOIN vn.buy c ON c.itemFk = s.itemFk + LEFT JOIN vn.entry e ON e.id = c.entryFk + LEFT JOIN vn.travel tr ON tr.id = e.travelFk + WHERE s.ticketFk = ? + AND tr.landed >= util.VN_CURDATE() - INTERVAL 1 YEAR`, + [ticketId], myOptions); - // BINDINGS - ticket.sales = []; - for (const sale of sales) { - if (sale.ticketFk === ticketId) { - sale.Barcodes = []; + // BINDINGS + ticket.sales = []; + for (const sale of sales) { + if (sale.ticketFk === ticketId) { + sale.Barcodes = []; - if (barcodes && barcodes.length) { - for (const barcode of barcodes) { - if (barcode.saleFk === sale.saleFk) { - for (let prop in barcode) { - if (['id', 'code'].includes(prop) && barcode[prop]) - sale.Barcodes.push(barcode[prop].toString(), '0' + barcode[prop]); - } + if (barcodes && barcodes.length) { + for (const barcode of barcodes) { + if (barcode.saleFk === sale.saleFk) { + for (const prop in barcode) { + if (['id', 'code'].includes(prop) && barcode[prop]) + sale.Barcodes.push(barcode[prop].toString(), '0' + barcode[prop]); } } } - - ticket.sales.push(sale); } + + ticket.sales.push(sale); } } - collection.tickets.push(ticket); } + collection.tickets.push(ticket); } - - if (tx) await tx.commit(); - await Promise.all(promises); - - return collection; - } catch (e) { - if (tx) await tx.rollback(); - throw e; } + await Promise.all(promises); + + return collection; }; }; diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 71a01f91a..87a41fcf6 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -318,6 +318,5 @@ "Street should be uppercase": "La dirección fiscal debe ir en mayúscula", "The response is not a PDF": "La respuesta no es un PDF", "Ticket without Route": "Ticket sin ruta", - "The ticket is in preparation": "El ticket [{{ticketId}}]({{{ticketUrl}}}) del comercial {{salesPersonId}} està en preparación", - "Invalid collection or ticket": "Invalid collection or ticket" + "The ticket is in preparation": "El ticket [{{ticketId}}]({{{ticketUrl}}}) del comercial {{salesPersonId}} està en preparación" } \ No newline at end of file From 6e06d21f9eb6e29f15e2b773b8d7dd759a40f231 Mon Sep 17 00:00:00 2001 From: alexm Date: Fri, 29 Sep 2023 12:36:36 +0200 Subject: [PATCH 173/427] refs #5890 deploy: merge dev in test 234002 --- db/changes/234201/.gitkeep | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 db/changes/234201/.gitkeep diff --git a/db/changes/234201/.gitkeep b/db/changes/234201/.gitkeep deleted file mode 100644 index e69de29bb..000000000 From 10de00ea45392ce1dc9b8383daf4795aceff1853 Mon Sep 17 00:00:00 2001 From: alexm Date: Fri, 29 Sep 2023 12:37:53 +0200 Subject: [PATCH 174/427] refs #5890 deploy: test to dev --- db/changes/234201/.gitkeep | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 db/changes/234201/.gitkeep diff --git a/db/changes/234201/.gitkeep b/db/changes/234201/.gitkeep new file mode 100644 index 000000000..e69de29bb From 1d440d5c02557a4273379746ea42b6fa7f591b72 Mon Sep 17 00:00:00 2001 From: alexm Date: Fri, 29 Sep 2023 12:40:11 +0200 Subject: [PATCH 175/427] refs #5890 correct version 234002 --- CHANGELOG.md | 7 ------- package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 3 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e95ac0f64..bc31f0579 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,17 +5,10 @@ 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). -## [2342.01] - 2023-10-19 - -### Added -### Changed -### Fixed - ## [2340.01] - 2023-10-05 ### Added ### Changed - ### Fixed ## [2338.01] - 2023-09-21 diff --git a/package-lock.json b/package-lock.json index c3f88bc2c..feb7e7165 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "salix-back", - "version": "23.42.01", + "version": "23.40.02", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "salix-back", - "version": "23.42.01", + "version": "23.40.02", "license": "GPL-3.0", "dependencies": { "axios": "^1.2.2", diff --git a/package.json b/package.json index 3320705f5..f142d7179 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "salix-back", - "version": "23.42.01", + "version": "23.40.02", "author": "Verdnatura Levante SL", "description": "Salix backend", "license": "GPL-3.0", From 5797398cf2df712771022b654170501bfe770128 Mon Sep 17 00:00:00 2001 From: alexm Date: Fri, 29 Sep 2023 12:41:23 +0200 Subject: [PATCH 176/427] refs #5890 correct version 234201 in dev --- CHANGELOG.md | 6 ++++++ package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bc31f0579..64333df48 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). +## [2342.01] - 2023-10-19 + +### Added +### Changed +### Fixed + ## [2340.01] - 2023-10-05 ### Added diff --git a/package-lock.json b/package-lock.json index feb7e7165..c3f88bc2c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "salix-back", - "version": "23.40.02", + "version": "23.42.01", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "salix-back", - "version": "23.40.02", + "version": "23.42.01", "license": "GPL-3.0", "dependencies": { "axios": "^1.2.2", diff --git a/package.json b/package.json index f142d7179..3320705f5 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "salix-back", - "version": "23.40.02", + "version": "23.42.01", "author": "Verdnatura Levante SL", "description": "Salix backend", "license": "GPL-3.0", From 17e6cffa3d1970462c43d6cf3961ca3e4b2e0395 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Fri, 29 Sep 2023 13:47:29 +0200 Subject: [PATCH 177/427] refs #6254 collection getTickets --- back/methods/collection/getTickets.js | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/back/methods/collection/getTickets.js b/back/methods/collection/getTickets.js index 70c3eb351..445fc070d 100644 --- a/back/methods/collection/getTickets.js +++ b/back/methods/collection/getTickets.js @@ -27,7 +27,7 @@ module.exports = Self => { Self.getTickets = async(ctx, id, print, options) => { const userId = ctx.req.accessToken.userId; const origin = ctx.req.headers.origin; - const $t = ctx.req.__; // $translate + const $t = ctx.req.__; const myOptions = {}; if (typeof options == 'object') @@ -59,11 +59,7 @@ module.exports = Self => { sh.code, IFNULL(p2.code, p.code) parkingCode, IFNULL(p2.pickingOrder, p.pickingOrder) pickingOrder, -<<<<<<< Updated upstream - iss.id itemShelvingSaleFk -======= iss.id itemShelvingSaleFk, ->>>>>>> Stashed changes iss.isPicked FROM ticketCollection tc LEFT JOIN collection c ON c.id = tc.collectionFk From 0e5a7bbb85e55bd4c9ad8634ba528a325835a853 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Fri, 29 Sep 2023 14:11:11 +0200 Subject: [PATCH 178/427] refs #6254 --- loopback/locale/en.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/loopback/locale/en.json b/loopback/locale/en.json index 3380d3dde..3ce4761a1 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -187,6 +187,6 @@ "This ticket is not editable.": "This ticket is not editable.", "The ticket doesn't exist.": "The ticket doesn't exist.", "The sales do not exists": "The sales do not exists", - "Ticket without Route": "Ticket sin ruta", + "Ticket without Route": "Ticket without route", "The ticket is in preparation": "The ticket [{{ticketId}}]({{{ticketUrl}}}) of the sales person {{salesPersonId}} is in preparation" } From c469a221c711dc055d93e051b73a7a70361ffb40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Fri, 29 Sep 2023 14:16:35 +0200 Subject: [PATCH 179/427] refs #6254 --- loopback/locale/en.json | 1 + 1 file changed, 1 insertion(+) diff --git a/loopback/locale/en.json b/loopback/locale/en.json index 3ce4761a1..645a874e8 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -188,5 +188,6 @@ "The ticket doesn't exist.": "The ticket doesn't exist.", "The sales do not exists": "The sales do not exists", "Ticket without Route": "Ticket without route", + "Booking completed": "Booking complete", "The ticket is in preparation": "The ticket [{{ticketId}}]({{{ticketUrl}}}) of the sales person {{salesPersonId}} is in preparation" } From 6f4a12e50f37fff49c009e3d1a8cc08d34b85f92 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 29 Sep 2023 14:42:47 +0200 Subject: [PATCH 180/427] ref #5417 date filters added --- .../methods/client/specs/transactions.spec.js | 23 +++++++++++++++++++ .../back/methods/client/transactions.js | 20 ++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/modules/client/back/methods/client/specs/transactions.spec.js b/modules/client/back/methods/client/specs/transactions.spec.js index 45fffc1de..679eb196c 100644 --- a/modules/client/back/methods/client/specs/transactions.spec.js +++ b/modules/client/back/methods/client/specs/transactions.spec.js @@ -63,4 +63,27 @@ describe('Client transactions', () => { throw e; } }); + + it('should call transactions() method filtering by date', async() => { + const tx = await models.Client.beginTransaction({}); + + try { + const options = {transaction: tx}; + const ctx = {args: {from: '2000/12/31'}}; + const filter = {}; + const withResults = await models.Client.transactions(ctx, filter, options); + + expect(withResults.length).toEqual(6); + + ctx.args.from = '2099/12/31'; + const noResults = await models.Client.transactions(ctx, filter, options); + + expect(noResults.length).toEqual(0); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); }); diff --git a/modules/client/back/methods/client/transactions.js b/modules/client/back/methods/client/transactions.js index 691910721..3ef61dd83 100644 --- a/modules/client/back/methods/client/transactions.js +++ b/modules/client/back/methods/client/transactions.js @@ -28,6 +28,16 @@ module.exports = Self => { arg: 'amount', type: 'number', http: {source: 'query'} + }, + { + arg: 'from', + type: 'date', + http: {source: 'query'} + }, + { + arg: 'to', + type: 'date', + http: {source: 'query'} } ], returns: { @@ -47,6 +57,11 @@ module.exports = Self => { if (typeof options == 'object') Object.assign(myOptions, options); + if (ctx.args && args.to) { + const dateTo = args.to; + dateTo.setHours(23, 59, 0, 0); + } + const where = buildFilter(args, (param, value) => { switch (param) { case 'orderFk': @@ -55,6 +70,11 @@ module.exports = Self => { return {'t.clientFk': value}; case 'amount': return {'t.amount': (value * 100)}; + case 'from': + return {'t.created': {gte: value}}; + + case 'to': + return {'t.created': {lte: value}}; } }); From a7128b8187d1c8d5c006dfe25de6398342ea882c Mon Sep 17 00:00:00 2001 From: jorgep Date: Mon, 2 Oct 2023 09:04:43 +0200 Subject: [PATCH 181/427] ref #5417 fix transactions --- modules/client/back/methods/client/transactions.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/modules/client/back/methods/client/transactions.js b/modules/client/back/methods/client/transactions.js index 3ef61dd83..174ca4c4e 100644 --- a/modules/client/back/methods/client/transactions.js +++ b/modules/client/back/methods/client/transactions.js @@ -59,7 +59,7 @@ module.exports = Self => { if (ctx.args && args.to) { const dateTo = args.to; - dateTo.setHours(23, 59, 0, 0); + dateTo.setHours(23, 59, 59, 999); } const where = buildFilter(args, (param, value) => { @@ -72,7 +72,6 @@ module.exports = Self => { return {'t.amount': (value * 100)}; case 'from': return {'t.created': {gte: value}}; - case 'to': return {'t.created': {lte: value}}; } From 3ba349b74ab50d3449a1c7a373a09e3b37e6b3db Mon Sep 17 00:00:00 2001 From: sergiodt Date: Mon, 2 Oct 2023 09:14:30 +0200 Subject: [PATCH 182/427] refs #5890 feat: itemShelvingSaleAsignado more calls --- db/changes/234002/.gitkeep | 0 db/changes/234002/00-aclClient.sql | 3 +++ modules/item/back/models/item-shelving.json | 5 +++++ modules/ticket/back/models/ticket-collection.json | 3 +++ modules/worker/back/models/worker.json | 3 +++ 5 files changed, 14 insertions(+) create mode 100644 db/changes/234002/.gitkeep create mode 100644 db/changes/234002/00-aclClient.sql diff --git a/db/changes/234002/.gitkeep b/db/changes/234002/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/db/changes/234002/00-aclClient.sql b/db/changes/234002/00-aclClient.sql new file mode 100644 index 000000000..3df9522cf --- /dev/null +++ b/db/changes/234002/00-aclClient.sql @@ -0,0 +1,3 @@ + +INSERT INTO `salix`.`ACL` ( model, property, accessType, permission, principalType, principalId) + VALUES('TicketCollection', '*', 'WRITE', 'ALLOW', 'ROLE', 'production'); diff --git a/modules/item/back/models/item-shelving.json b/modules/item/back/models/item-shelving.json index 34773e34c..61d05539e 100644 --- a/modules/item/back/models/item-shelving.json +++ b/modules/item/back/models/item-shelving.json @@ -47,6 +47,11 @@ "type": "belongsTo", "model": "VnUser", "foreignKey": "userFk" + }, + "shelving": { + "type": "belongsTo", + "model": "Shelving", + "foreignKey": "shelvingFk" } } } diff --git a/modules/ticket/back/models/ticket-collection.json b/modules/ticket/back/models/ticket-collection.json index e941ac2ce..4bd34f08e 100644 --- a/modules/ticket/back/models/ticket-collection.json +++ b/modules/ticket/back/models/ticket-collection.json @@ -10,6 +10,9 @@ "id": { "id": true, "type": "number" + }, + "usedShelves": { + "type": "number" } }, "relations": { diff --git a/modules/worker/back/models/worker.json b/modules/worker/back/models/worker.json index dbb3ed23f..ea4aecf67 100644 --- a/modules/worker/back/models/worker.json +++ b/modules/worker/back/models/worker.json @@ -47,6 +47,9 @@ }, "locker": { "type" : "number" + }, + "isF11Allowed": { + "type" : "boolean" } }, "relations": { From c59b119a4a2b04b2a0e37ef996802e5a9bdad08b Mon Sep 17 00:00:00 2001 From: jorgep Date: Mon, 2 Oct 2023 10:06:04 +0200 Subject: [PATCH 183/427] ref #5417 fix transactions --- modules/client/back/methods/client/transactions.js | 2 -- 1 file changed, 2 deletions(-) diff --git a/modules/client/back/methods/client/transactions.js b/modules/client/back/methods/client/transactions.js index 174ca4c4e..d08df4ab6 100644 --- a/modules/client/back/methods/client/transactions.js +++ b/modules/client/back/methods/client/transactions.js @@ -32,12 +32,10 @@ module.exports = Self => { { arg: 'from', type: 'date', - http: {source: 'query'} }, { arg: 'to', type: 'date', - http: {source: 'query'} } ], returns: { From 99d65804e8ff9717d7813736864510d65fe54fe9 Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 2 Oct 2023 13:29:39 +0200 Subject: [PATCH 184/427] refs #6278 fixFilter --- .../234201/00-alterTableTicketRequest.sql | 1 + modules/item/front/request/index.html | 8 ++++++ .../back/methods/ticket-request/filter.js | 25 +++++++++++-------- 3 files changed, 24 insertions(+), 10 deletions(-) create mode 100644 db/changes/234201/00-alterTableTicketRequest.sql diff --git a/db/changes/234201/00-alterTableTicketRequest.sql b/db/changes/234201/00-alterTableTicketRequest.sql new file mode 100644 index 000000000..2a08137b9 --- /dev/null +++ b/db/changes/234201/00-alterTableTicketRequest.sql @@ -0,0 +1 @@ +ALTER TABLE `vn`.`ticketRequest` MODIFY COLUMN `itemFk` double DEFAULT NULL NOT NULL; diff --git a/modules/item/front/request/index.html b/modules/item/front/request/index.html index c505b3a09..571ad49af 100644 --- a/modules/item/front/request/index.html +++ b/modules/item/front/request/index.html @@ -26,6 +26,7 @@ Ticket ID Shipped Description + Requester Requested Price Atender @@ -51,6 +52,13 @@ {{::request.description}} + + + {{::request.requesterName}} + + {{::request.quantity}} {{::request.price | currency: 'EUR':2}} diff --git a/modules/ticket/back/methods/ticket-request/filter.js b/modules/ticket/back/methods/ticket-request/filter.js index f27ea5018..47e571988 100644 --- a/modules/ticket/back/methods/ticket-request/filter.js +++ b/modules/ticket/back/methods/ticket-request/filter.js @@ -99,6 +99,8 @@ module.exports = Self => { switch (value) { case 'pending': return {'tr.isOk': null}; + case 'accepted': + return {'tr.isOk': 1}; default: return {'tr.isOk': value}; } @@ -122,8 +124,7 @@ module.exports = Self => { filter = mergeFilters(filter, {where}); const stmt = new ParameterizedSQL( - `SELECT - tr.id, + `SELECT tr.id, tr.ticketFk, tr.quantity, tr.price, @@ -133,18 +134,19 @@ module.exports = Self => { tr.saleFk, tr.requesterFk, tr.isOk, - s.quantity AS saleQuantity, + s.quantity saleQuantity, s.itemFk, - i.name AS itemDescription, + i.name itemDescription, t.shipped, - DATE(t.shipped) AS shippedDate, + DATE(t.shipped) shippedDate, t.nickname, t.warehouseFk, t.clientFk, - w.name AS warehouse, - u.nickname AS salesPersonNickname, - ua.name AS attenderName, - c.salesPersonFk + w.name warehouse, + u.nickname salesPersonNickname, + ua.name attenderName, + c.salesPersonFk, + ua2.name requesterName FROM ticketRequest tr LEFT JOIN ticketWeekly tw on tw.ticketFk = tr.ticketFk LEFT JOIN ticket t ON t.id = tr.ticketFk @@ -155,9 +157,12 @@ module.exports = Self => { LEFT JOIN worker wk ON wk.id = c.salesPersonFk LEFT JOIN account.user u ON u.id = wk.id LEFT JOIN worker wka ON wka.id = tr.attenderFk - LEFT JOIN account.user ua ON ua.id = wka.id`); + LEFT JOIN account.user ua ON ua.id = wka.id + LEFT JOIN account.user ua2 ON ua2.id = tr.requesterFk`); stmt.merge(conn.makeSuffix(filter)); + console.log(stmt); + return conn.executeStmt(stmt, myOptions); }; }; From 4545a6321455c8d3acdef0eac2320dd840b602e0 Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 2 Oct 2023 14:51:19 +0200 Subject: [PATCH 185/427] refs #6067 feat(vnUser): verifyEmail redirect to lilium --- back/methods/vn-user/update-user.js | 6 ++--- back/models/specs/vn-user.spec.js | 3 ++- back/models/vn-user.js | 27 ++++++++++++++----- db/changes/234201/00-aclUrlHedera.sql | 4 +++ db/dump/fixtures.sql | 1 + modules/account/back/models/mail-forward.js | 10 ------- modules/account/back/models/mail-forward.json | 13 ++++++++- modules/worker/back/methods/worker/new.js | 1 + 8 files changed, 43 insertions(+), 22 deletions(-) create mode 100644 db/changes/234201/00-aclUrlHedera.sql delete mode 100644 modules/account/back/models/mail-forward.js diff --git a/back/methods/vn-user/update-user.js b/back/methods/vn-user/update-user.js index 85f6df762..ddaae8548 100644 --- a/back/methods/vn-user/update-user.js +++ b/back/methods/vn-user/update-user.js @@ -32,10 +32,8 @@ module.exports = Self => { } }); - Self.updateUser = async(ctx, id) => { + Self.updateUser = async(ctx, id, name, nickname, email, lang) => { await Self.userSecurity(ctx, id); - const user = await Self.app.models.VnUser.findById(id, - {fields: ['id', 'name', 'nickname', 'email', 'lang', 'password']}); - await user.updateAttributes(ctx.args); + await Self.upsertWithWhere({id}, {name, nickname, email, lang}); }; }; diff --git a/back/models/specs/vn-user.spec.js b/back/models/specs/vn-user.spec.js index 5638942fb..8689a7854 100644 --- a/back/models/specs/vn-user.spec.js +++ b/back/models/specs/vn-user.spec.js @@ -1,4 +1,5 @@ const models = require('vn-loopback/server/server').models; +const ForbiddenError = require('vn-loopback/util/forbiddenError'); describe('loopback model VnUser', () => { it('should return true if the user has the given role', async() => { @@ -46,7 +47,7 @@ describe('loopback model VnUser', () => { } catch (error) { await tx.rollback(); - expect(error.message).toEqual(`You don't have enough privileges`); + expect(error).toEqual(new ForbiddenError()); } }); }); diff --git a/back/models/vn-user.js b/back/models/vn-user.js index 6aac21561..e910ee33c 100644 --- a/back/models/vn-user.js +++ b/back/models/vn-user.js @@ -1,7 +1,7 @@ const vnModel = require('vn-loopback/common/models/vn-model'); const LoopBackContext = require('loopback-context'); const {Email} = require('vn-print'); -const UserError = require('vn-loopback/util/user-error'); +const ForbiddenError = require('vn-loopback/util/forbiddenError'); module.exports = function(Self) { vnModel(Self); @@ -198,11 +198,12 @@ module.exports = function(Self) { const user = await models.VnUser.findById(userId, {fields: ['id', 'emailVerified']}, myOptions); if (!user.emailVerified && hasMediumPrivileges) return; - throw new UserError(`You don't have enough privileges`); + throw new ForbiddenError(); }; Self.observe('after save', async ctx => { - const newEmail = ctx?.instance?.email; + const instance = ctx?.instance; + const newEmail = instance?.email; const oldEmail = ctx?.hookState?.oldInstance?.email; if (!ctx.isNewInstance && (!newEmail || !oldEmail || newEmail == oldEmail)) return; @@ -213,6 +214,21 @@ module.exports = function(Self) { const origin = headers.origin; const url = origin.split(':'); + const env = process.env.NODE_ENV; + const liliumUrl = await Self.app.models.Url.findOne({ + where: {and: [ + {appName: 'lilium'}, + {environment: env} + ]} + }); + const hederaUrl = await Self.app.models.Url.findOne({ + where: {and: [ + {appName: 'hedera'}, + {environment: env} + ]} + }); + + const isWorker = instance.isWorker || await Self.app.models.Account.findById(instance.id, null, ctx.options); class Mailer { async send(verifyOptions, cb) { const params = { @@ -226,12 +242,11 @@ module.exports = function(Self) { cb(null, verifyOptions.to); } } - const options = { type: 'email', to: newEmail, from: {}, - redirect: `${origin}/#!/account/${ctx.instance.id}/basic-data?emailConfirmed`, + redirect: `${liliumUrl.url}verifyEmail?isWorker=${!!isWorker}&url=${hederaUrl.url}`, template: false, mailer: new Mailer, host: url[1].split('/')[2], @@ -240,6 +255,6 @@ module.exports = function(Self) { user: Self }; - await ctx.instance.verify(options, ctx.options); + await instance.verify(options, ctx.options); }); }; diff --git a/db/changes/234201/00-aclUrlHedera.sql b/db/changes/234201/00-aclUrlHedera.sql new file mode 100644 index 000000000..438f58178 --- /dev/null +++ b/db/changes/234201/00-aclUrlHedera.sql @@ -0,0 +1,4 @@ +INSERT INTO `salix`.`url` (`appName`, `environment`, `url`) + VALUES + ('hedera', 'test', 'https://test-shop.verdnatura.es/'), + ('hedera', 'production', 'https://shop.verdnatura.es/'); diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index eb28c4a01..41f999daf 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -2869,6 +2869,7 @@ INSERT INTO `vn`.`profileType` (`id`, `name`) INSERT INTO `salix`.`url` (`appName`, `environment`, `url`) VALUES ('lilium', 'development', 'http://localhost:9000/#/'), + ('hedera', 'development', 'http://localhost:9090/'), ('salix', 'development', 'http://localhost:5000/#!/'); INSERT INTO `vn`.`report` (`id`, `name`, `paperSizeFk`, `method`) diff --git a/modules/account/back/models/mail-forward.js b/modules/account/back/models/mail-forward.js deleted file mode 100644 index adc282155..000000000 --- a/modules/account/back/models/mail-forward.js +++ /dev/null @@ -1,10 +0,0 @@ - -module.exports = Self => { - Self.observe('before save', async ctx => { - const instance = ctx.currentInstance || ctx.instance; - await Self.app.models.VnUser.userSecurity(ctx, instance.account); - }); - Self.observe('before delete', async ctx => { - await Self.app.models.VnUser.userSecurity(ctx, ctx.where.account); - }); -}; diff --git a/modules/account/back/models/mail-forward.json b/modules/account/back/models/mail-forward.json index edef1bf08..874810b7a 100644 --- a/modules/account/back/models/mail-forward.json +++ b/modules/account/back/models/mail-forward.json @@ -21,5 +21,16 @@ "model": "VnUser", "foreignKey": "account" } - } + }, + "acls": [{ + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$owner", + "permission": "ALLOW" + }, { + "accessType": "WRITE", + "principalType": "ROLE", + "principalId": "$owner", + "permission": "ALLOW" + }] } diff --git a/modules/worker/back/methods/worker/new.js b/modules/worker/back/methods/worker/new.js index 199a3be62..7c8978ec6 100644 --- a/modules/worker/back/methods/worker/new.js +++ b/modules/worker/back/methods/worker/new.js @@ -155,6 +155,7 @@ module.exports = Self => { password: randomPassword.password, email: args.email, roleFk: workerConfig.roleFk, + isWorker: true // to verifyEmail }, myOptions ); From 96769d9ff9b178a01679329d87f84d0032bb71cc Mon Sep 17 00:00:00 2001 From: pablone Date: Tue, 3 Oct 2023 08:57:59 +0200 Subject: [PATCH 186/427] refs #6213 fixIntermitentError --- .../{234001 => 234201}/00-supplierAccountCheckLength.sql | 0 e2e/helpers/tests.js | 9 +++++++++ .../back/methods/supplier/specs/newSupplier.spec.js | 1 + modules/supplier/back/models/specs/supplier.spec.js | 4 ++-- 4 files changed, 12 insertions(+), 2 deletions(-) rename db/changes/{234001 => 234201}/00-supplierAccountCheckLength.sql (100%) diff --git a/db/changes/234001/00-supplierAccountCheckLength.sql b/db/changes/234201/00-supplierAccountCheckLength.sql similarity index 100% rename from db/changes/234001/00-supplierAccountCheckLength.sql rename to db/changes/234201/00-supplierAccountCheckLength.sql diff --git a/e2e/helpers/tests.js b/e2e/helpers/tests.js index 992ec051f..718b49834 100644 --- a/e2e/helpers/tests.js +++ b/e2e/helpers/tests.js @@ -52,6 +52,15 @@ async function test() { await backendStatus(); jasmine.jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000; + const myReporter = { + specDone: function(result) { + for (const expectation of result.failedExpectations) { + console.warn('SpecFailed: ' + result.description); + console.warn('Failure: ' + expectation.message); + } + } + }; + jasmine.addReporter(myReporter); await jasmine.execute(); } diff --git a/modules/supplier/back/methods/supplier/specs/newSupplier.spec.js b/modules/supplier/back/methods/supplier/specs/newSupplier.spec.js index c368ec1b8..5fc2ea752 100644 --- a/modules/supplier/back/methods/supplier/specs/newSupplier.spec.js +++ b/modules/supplier/back/methods/supplier/specs/newSupplier.spec.js @@ -32,6 +32,7 @@ describe('Supplier newSupplier()', () => { const result = await models.Supplier.newSupplier(ctx, options); expect(result.name).toEqual('newSupplier'); + await tx.rollback(); } catch (e) { await tx.rollback(); throw e; diff --git a/modules/supplier/back/models/specs/supplier.spec.js b/modules/supplier/back/models/specs/supplier.spec.js index 3db273a95..fbd3a00db 100644 --- a/modules/supplier/back/models/specs/supplier.spec.js +++ b/modules/supplier/back/models/specs/supplier.spec.js @@ -129,10 +129,10 @@ describe('loopback model Supplier', () => { const options = {transaction: tx}; try { - const newSupplier = await models.Supplier.create({id: '9999', name: 'Alfred Pennyworth'}, options); + const newSupplier = await models.Supplier.create({name: 'Alfred Pennyworth'}, options); const fetchedSupplier = await models.Supplier.findById(newSupplier.id, null, options); - expect(fetchedSupplier.account).toEqual('4100009999'); + expect(Number(fetchedSupplier.account)).toEqual(4100000000 + newSupplier.id); await tx.rollback(); } catch (e) { await tx.rollback(); From 8c39f65dc31f0658ac1e692693c59117699e2f61 Mon Sep 17 00:00:00 2001 From: alexm Date: Tue, 3 Oct 2023 09:36:11 +0200 Subject: [PATCH 187/427] refs #6067 feat: url model to everyone --- back/models/url.json | 9 ++++++++- back/models/vn-user.js | 8 +------- db/changes/{234001 => 234201}/00-account_acl.sql | 0 db/changes/234201/00-aclUrlHedera.sql | 5 +++++ 4 files changed, 14 insertions(+), 8 deletions(-) rename db/changes/{234001 => 234201}/00-account_acl.sql (100%) diff --git a/back/models/url.json b/back/models/url.json index 8610ff28b..13f50b099 100644 --- a/back/models/url.json +++ b/back/models/url.json @@ -21,5 +21,12 @@ "type": "string", "required": true } - } + }, + "acls": [{ + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + }] + } diff --git a/back/models/vn-user.js b/back/models/vn-user.js index e910ee33c..8e9b59aab 100644 --- a/back/models/vn-user.js +++ b/back/models/vn-user.js @@ -221,12 +221,6 @@ module.exports = function(Self) { {environment: env} ]} }); - const hederaUrl = await Self.app.models.Url.findOne({ - where: {and: [ - {appName: 'hedera'}, - {environment: env} - ]} - }); const isWorker = instance.isWorker || await Self.app.models.Account.findById(instance.id, null, ctx.options); class Mailer { @@ -246,7 +240,7 @@ module.exports = function(Self) { type: 'email', to: newEmail, from: {}, - redirect: `${liliumUrl.url}verifyEmail?isWorker=${!!isWorker}&url=${hederaUrl.url}`, + redirect: `${liliumUrl.url}verifyEmail?isWorker=${!!isWorker}`, template: false, mailer: new Mailer, host: url[1].split('/')[2], diff --git a/db/changes/234001/00-account_acl.sql b/db/changes/234201/00-account_acl.sql similarity index 100% rename from db/changes/234001/00-account_acl.sql rename to db/changes/234201/00-account_acl.sql diff --git a/db/changes/234201/00-aclUrlHedera.sql b/db/changes/234201/00-aclUrlHedera.sql index 438f58178..0d38a2ae8 100644 --- a/db/changes/234201/00-aclUrlHedera.sql +++ b/db/changes/234201/00-aclUrlHedera.sql @@ -2,3 +2,8 @@ INSERT INTO `salix`.`url` (`appName`, `environment`, `url`) VALUES ('hedera', 'test', 'https://test-shop.verdnatura.es/'), ('hedera', 'production', 'https://shop.verdnatura.es/'); + +DELETE FROM `salix`.`ACL` + WHERE model = 'Url' + AND 'accessType' = 'READ' + AND principalId = 'employee'; From bd46a77cb7160325f373d141720f53bccd9b60cd Mon Sep 17 00:00:00 2001 From: carlossa Date: Tue, 3 Oct 2023 10:15:16 +0200 Subject: [PATCH 188/427] refs #5768 incoterms addressFk --- modules/client/front/sample/create/index.html | 29 ++++++++-- modules/client/front/sample/create/index.js | 56 ++++++++++++++++++- .../incoterms-authorization.html | 5 +- .../incoterms-authorization.js | 5 +- .../incoterms-authorization/locale/es.yml | 2 +- .../incoterms-authorization/sql/address.sql | 9 +++ .../incoterms-authorization/sql/company.sql | 4 +- 7 files changed, 95 insertions(+), 15 deletions(-) create mode 100644 print/templates/reports/incoterms-authorization/sql/address.sql diff --git a/modules/client/front/sample/create/index.html b/modules/client/front/sample/create/index.html index 134c097e8..f9db03036 100644 --- a/modules/client/front/sample/create/index.html +++ b/modules/client/front/sample/create/index.html @@ -13,6 +13,7 @@ 'description', 'model', 'hasCompany', + 'hasAddress', 'hasPreview', 'datepickerEnabled' ]" @@ -69,15 +70,31 @@ ng-if="sampleType.selection.hasCompany" required="true"> - + ng-model="$ctrl.addressId" + model="ClientSample.addressFk" + order="isActive DESC"> + + {{::!isActive ? '(Inactive)' : ''}} + {{::nickname}} + + , {{::street}}, {{::city}}, {{::province.name}} - {{::agencyMode.name}} + + + + + + + { + if (res.data) + this.addresses = res.data; + }); + } + + getClientDefaultAddress(value) { + let query = `Clients/${value}`; + this.$http.get(query).then(res => { + if (res.data) + this.addressId = res.data.defaultAddressFk; + }); + } } Controller.$inject = ['$element', '$scope', 'vnEmail']; diff --git a/print/templates/reports/incoterms-authorization/incoterms-authorization.html b/print/templates/reports/incoterms-authorization/incoterms-authorization.html index 5b4e7829b..e4e4635f3 100644 --- a/print/templates/reports/incoterms-authorization/incoterms-authorization.html +++ b/print/templates/reports/incoterms-authorization/incoterms-authorization.html @@ -5,7 +5,7 @@ v-html="$t('description', { socialName: client.socialName, name: client.name, - address: client.street, + addressId: address.street, country: client.country, fiscalID: client.fi })" @@ -21,8 +21,7 @@ companyName: company.name, companyCity: company.city, socialName: client.socialName, - destinationCountry: client.country, - incotermsFk: address.incotermsFk + destinationCountry: client.country })" >

diff --git a/print/templates/reports/incoterms-authorization/incoterms-authorization.js b/print/templates/reports/incoterms-authorization/incoterms-authorization.js index 0fbbd10d2..e50cd99ec 100755 --- a/print/templates/reports/incoterms-authorization/incoterms-authorization.js +++ b/print/templates/reports/incoterms-authorization/incoterms-authorization.js @@ -7,6 +7,7 @@ module.exports = { this.client = await this.findOneFromDef('client', [this.id]); this.checkMainEntity(this.client); this.company = await this.findOneFromDef('company', [this.companyId]); + this.address = await this.findOneFromDef('address', [this.addressId]); }, props: { id: { @@ -18,8 +19,8 @@ module.exports = { type: Number, required: true }, - address: { - type: String + addressId: { + type: Number } } }; diff --git a/print/templates/reports/incoterms-authorization/locale/es.yml b/print/templates/reports/incoterms-authorization/locale/es.yml index 8bdce7085..ef63e9e3c 100644 --- a/print/templates/reports/incoterms-authorization/locale/es.yml +++ b/print/templates/reports/incoterms-authorization/locale/es.yml @@ -6,7 +6,7 @@ issued: 'En {0}, a {1} de {2} de {3}' client: 'Cliente {0}' declaration: '{socialName} declara por la presente que:' declarations: - - 'Todas las compras realizadas por {socialName} con {companyName} se entregan según las condiciones definidas en el incoterm {incotermsFk} ({Incoterm description}).' + - 'Todas las compras realizadas por {socialName} con {companyName} se entregan según las condiciones definidas en el incoterm.' - '{socialName} reconoce que es importante para {companyName} tener comprobante de la entrega intracomunitaria de la mercancía a {destinationCountry} para poder facturar con 0% de IVA.' diff --git a/print/templates/reports/incoterms-authorization/sql/address.sql b/print/templates/reports/incoterms-authorization/sql/address.sql new file mode 100644 index 000000000..a432c5e53 --- /dev/null +++ b/print/templates/reports/incoterms-authorization/sql/address.sql @@ -0,0 +1,9 @@ +SELECT + a.nickname, + a.street, + a.postalCode, + a.city, + p.name province +FROM address a + LEFT JOIN province p ON p.id = a.provinceFk +WHERE a.id = ? diff --git a/print/templates/reports/incoterms-authorization/sql/company.sql b/print/templates/reports/incoterms-authorization/sql/company.sql index 39c3290d1..8d94859e1 100644 --- a/print/templates/reports/incoterms-authorization/sql/company.sql +++ b/print/templates/reports/incoterms-authorization/sql/company.sql @@ -1,8 +1,8 @@ -SELECT +SELECT s.name, s.city, cl.name AS manager FROM company c JOIN supplier s ON s.id = c.id JOIN client cl ON cl.id = c.workerManagerFk -WHERE c.id = ? \ No newline at end of file +WHERE c.id = ? From 45e41de9a9a47ebdc0e75577763795b1f38b24bf Mon Sep 17 00:00:00 2001 From: alexm Date: Tue, 3 Oct 2023 14:03:52 +0200 Subject: [PATCH 189/427] refs #5918 fix(worker_time-control): isMailSended --- .../00-ACL_workerDepartment.sql | 0 .../updateWorkerTimeControlMail.js | 16 ++++++++-------- modules/worker/front/time-control/index.js | 11 ++++++----- 3 files changed, 14 insertions(+), 13 deletions(-) rename db/changes/{233601 => 234201}/00-ACL_workerDepartment.sql (100%) diff --git a/db/changes/233601/00-ACL_workerDepartment.sql b/db/changes/234201/00-ACL_workerDepartment.sql similarity index 100% rename from db/changes/233601/00-ACL_workerDepartment.sql rename to db/changes/234201/00-ACL_workerDepartment.sql diff --git a/modules/worker/back/methods/worker-time-control/updateWorkerTimeControlMail.js b/modules/worker/back/methods/worker-time-control/updateWorkerTimeControlMail.js index 6fe30de91..e12cf9c59 100644 --- a/modules/worker/back/methods/worker-time-control/updateWorkerTimeControlMail.js +++ b/modules/worker/back/methods/worker-time-control/updateWorkerTimeControlMail.js @@ -37,9 +37,8 @@ module.exports = Self => { } }); - Self.updateWorkerTimeControlMail = async(ctx, options) => { + Self.updateWorkerTimeControlMail = async(ctx, workerId, year, week, state, reason, options) => { const models = Self.app.models; - const args = ctx.args; const myOptions = {}; @@ -48,20 +47,21 @@ module.exports = Self => { const workerTimeControlMail = await models.WorkerTimeControlMail.findOne({ where: { - workerFk: args.workerId, - year: args.year, - week: args.week + workerFk: workerId, + year, + week } }, myOptions); + console.log('workerTimeControlMail: ', workerTimeControlMail); if (!workerTimeControlMail) throw new UserError(`There aren't records for this week`); await workerTimeControlMail.updateAttributes({ - state: args.state, - reason: args.reason || null + state, + reason: reason || null }, myOptions); - if (args.state == 'SENDED') { + if (state == 'SENDED') { await workerTimeControlMail.updateAttributes({ sendedCounter: workerTimeControlMail.sendedCounter + 1 }, myOptions); diff --git a/modules/worker/front/time-control/index.js b/modules/worker/front/time-control/index.js index 0b427a10d..4bf25886f 100644 --- a/modules/worker/front/time-control/index.js +++ b/modules/worker/front/time-control/index.js @@ -143,21 +143,22 @@ class Controller extends Section { } isMailSended() { - const filterTimeControl = { + const filter = { where: { year: this._date.getFullYear(), week: this.getWeekNumber(this._date) }, limit: 1 }; - this.$http.get('WorkerTimeControlMails', {filterTimeControl}) + // no repeat request + this.$http.get('WorkerTimeControlMails', {filter}) .then(res => { if (!res.data.length) { this.canResend = false; return; } - const filterDepartment = { + const filter = { where: { workerFk: this.$params.id }, @@ -165,9 +166,9 @@ class Controller extends Section { relation: 'department' } }; - this.$http.get('WorkerDepartments', {filterDepartment}) + this.$http.get('WorkerDepartments/findOne', {filter}) .then(res => { - const department = res.data[0].department; + const department = res.data.department; if (department.isTeleworking) this.canResend = true; }); }); From ed3871f75c3c793d7e1b0dc4ec6603ff5eed1365 Mon Sep 17 00:00:00 2001 From: carlossa Date: Tue, 3 Oct 2023 14:03:59 +0200 Subject: [PATCH 190/427] refs #5861 edit css --- print/templates/reports/invoice/assets/css/style.css | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/print/templates/reports/invoice/assets/css/style.css b/print/templates/reports/invoice/assets/css/style.css index d4526ce56..f9f6f220f 100644 --- a/print/templates/reports/invoice/assets/css/style.css +++ b/print/templates/reports/invoice/assets/css/style.css @@ -44,3 +44,7 @@ h2 { .phytosanitary-info { margin-top: 10px } + +.panel { + margin-bottom: 0px; +} From e14049a082b485bce185797318704a415d2f67f6 Mon Sep 17 00:00:00 2001 From: pablone Date: Wed, 4 Oct 2023 07:48:00 +0200 Subject: [PATCH 191/427] refs #6213 fixJasmineConfiguration --- e2e/helpers/tests.js | 9 --------- 1 file changed, 9 deletions(-) diff --git a/e2e/helpers/tests.js b/e2e/helpers/tests.js index 718b49834..992ec051f 100644 --- a/e2e/helpers/tests.js +++ b/e2e/helpers/tests.js @@ -52,15 +52,6 @@ async function test() { await backendStatus(); jasmine.jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000; - const myReporter = { - specDone: function(result) { - for (const expectation of result.failedExpectations) { - console.warn('SpecFailed: ' + result.description); - console.warn('Failure: ' + expectation.message); - } - } - }; - jasmine.addReporter(myReporter); await jasmine.execute(); } From df6d10e514b4b1a54b382392b32fc6458ef7d2ab Mon Sep 17 00:00:00 2001 From: alexm Date: Wed, 4 Oct 2023 12:17:24 +0200 Subject: [PATCH 192/427] refs #5918 fix(workerTimeControl): resend mail --- .../updateWorkerTimeControlMail.js | 37 +++++++---- .../weeklyHourRecordEmail.js | 5 +- modules/worker/front/time-control/index.html | 2 +- modules/worker/front/time-control/index.js | 64 +++++++------------ 4 files changed, 49 insertions(+), 59 deletions(-) diff --git a/modules/worker/back/methods/worker-time-control/updateWorkerTimeControlMail.js b/modules/worker/back/methods/worker-time-control/updateWorkerTimeControlMail.js index e12cf9c59..4e41a5bdd 100644 --- a/modules/worker/back/methods/worker-time-control/updateWorkerTimeControlMail.js +++ b/modules/worker/back/methods/worker-time-control/updateWorkerTimeControlMail.js @@ -37,31 +37,40 @@ module.exports = Self => { } }); - Self.updateWorkerTimeControlMail = async(ctx, workerId, year, week, state, reason, options) => { + Self.updateWorkerTimeControlMail = async(ctx, options) => { const models = Self.app.models; - + const args = ctx.args; const myOptions = {}; if (typeof options == 'object') Object.assign(myOptions, options); - const workerTimeControlMail = await models.WorkerTimeControlMail.findOne({ + const [sent] = await models.WorkerTimeControlMail.find({ where: { - workerFk: workerId, - year, - week - } + year: args.year, + week: args.week, + }, + limit: 1 }, myOptions); - console.log('workerTimeControlMail: ', workerTimeControlMail); - if (!workerTimeControlMail) throw new UserError(`There aren't records for this week`); + if (!sent) throw new UserError(`There aren't records for this week`); - await workerTimeControlMail.updateAttributes({ - state, - reason: reason || null - }, myOptions); + const workerTimeControlMail = await models.WorkerTimeControlMail.upsertWithWhere( + { + year: args.year, + week: args.week, + workerFk: args.workerId + }, + { + state: args.state, + reason: args.workerId, + year: args.year, + week: args.week, + workerFk: args.workerId + }, + myOptions); - if (state == 'SENDED') { + if (args.state == 'SENDED') { await workerTimeControlMail.updateAttributes({ sendedCounter: workerTimeControlMail.sendedCounter + 1 }, myOptions); diff --git a/modules/worker/back/methods/worker-time-control/weeklyHourRecordEmail.js b/modules/worker/back/methods/worker-time-control/weeklyHourRecordEmail.js index 3203dea82..816a1d22b 100644 --- a/modules/worker/back/methods/worker-time-control/weeklyHourRecordEmail.js +++ b/modules/worker/back/methods/worker-time-control/weeklyHourRecordEmail.js @@ -61,9 +61,8 @@ module.exports = Self => { const url = `${salix.url}worker/${args.workerId}/time-control?timestamp=${timestamp}`; ctx.args.url = url; - await Self.sendTemplate(ctx, 'weekly-hour-record'); - - return models.WorkerTimeControl.updateWorkerTimeControlMail(ctx, myOptions); + await models.WorkerTimeControl.updateWorkerTimeControlMail(ctx, myOptions); + return Self.sendTemplate(ctx, 'weekly-hour-record'); }; function getMondayDateFromYearWeek(yearNumber, weekNumber) { diff --git a/modules/worker/front/time-control/index.html b/modules/worker/front/time-control/index.html index 847eb9505..ce8a66356 100644 --- a/modules/worker/front/time-control/index.html +++ b/modules/worker/front/time-control/index.html @@ -102,7 +102,7 @@ ng-click="sendEmailConfirmation.show()" class="right" vn-tooltip="Resend email of this week to the user" - ng-show="$ctrl.isHr && $ctrl.canResend"> + ng-show="$ctrl.isHr && $ctrl.state != 'CONFIRMED' && $ctrl.canResend"> diff --git a/modules/worker/front/time-control/index.js b/modules/worker/front/time-control/index.js index 4bf25886f..9137d7839 100644 --- a/modules/worker/front/time-control/index.js +++ b/modules/worker/front/time-control/index.js @@ -53,6 +53,8 @@ class Controller extends Section { set worker(value) { this._worker = value; this.fetchHours(); + if (this.date) + this.getWeekData(); } /** @@ -110,8 +112,8 @@ class Controller extends Section { } if (!this.weekTotalHours) this.fetchHours(); - this.getWeekData(); - this.isMailSended(); + if (this.worker) + this.getWeekData(); } set weekTotalHours(totalHours) { @@ -128,21 +130,23 @@ class Controller extends Section { workerFk: this.$params.id, year: this._date.getFullYear(), week: this.getWeekNumber(this._date) - } + }, }; this.$http.get('WorkerTimeControlMails', {filter}) .then(res => { - const mail = res.data; - if (!mail.length) { + if (!res.data.length) { this.state = null; return; } - this.state = mail[0].state; - this.reason = mail[0].reason; + const [mail] = res.data; + this.state = mail.state; + this.reason = mail.reason; }); + this.canBeResend(); } - isMailSended() { + canBeResend() { + this.canResend = false; const filter = { where: { year: this._date.getFullYear(), @@ -150,27 +154,10 @@ class Controller extends Section { }, limit: 1 }; - // no repeat request this.$http.get('WorkerTimeControlMails', {filter}) .then(res => { - if (!res.data.length) { - this.canResend = false; - return; - } - - const filter = { - where: { - workerFk: this.$params.id - }, - include: { - relation: 'department' - } - }; - this.$http.get('WorkerDepartments/findOne', {filter}) - .then(res => { - const department = res.data.department; - if (department.isTeleworking) this.canResend = true; - }); + if (res.data.length) + this.canResend = true; }); } @@ -389,30 +376,25 @@ class Controller extends Section { } isSatisfied() { - const params = { - workerId: this.worker.id, - year: this.date.getFullYear(), - week: this.weekNumber, - state: 'CONFIRMED' - }; - const query = `WorkerTimeControls/updateWorkerTimeControlMail`; - this.$http.post(query, params).then(() => { - this.getMailStates(this.date); - this.getWeekData(); - this.vnApp.showSuccess(this.$t('Data saved!')); - }); + this.updateWorkerTimeControlMail('CONFIRMED'); } isUnsatisfied() { if (!this.reason) throw new UserError(`You must indicate a reason`); + this.updateWorkerTimeControlMail('REVISE', this.reason); + } + updateWorkerTimeControlMail(state, reason) { const params = { workerId: this.worker.id, year: this.date.getFullYear(), week: this.weekNumber, - state: 'REVISE', - reason: this.reason + state }; + + if (reason) + params.reason = reason; + const query = `WorkerTimeControls/updateWorkerTimeControlMail`; this.$http.post(query, params).then(() => { this.getMailStates(this.date); From f8a510b330e6dc331ab986bbc7bfc79ce68530d4 Mon Sep 17 00:00:00 2001 From: alexm Date: Wed, 4 Oct 2023 12:31:46 +0200 Subject: [PATCH 193/427] refs #5918 fix(workerTimeControl): update(workerTimeControl --- .../methods/worker-time-control/updateWorkerTimeControlMail.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/worker/back/methods/worker-time-control/updateWorkerTimeControlMail.js b/modules/worker/back/methods/worker-time-control/updateWorkerTimeControlMail.js index 4e41a5bdd..3594f05fe 100644 --- a/modules/worker/back/methods/worker-time-control/updateWorkerTimeControlMail.js +++ b/modules/worker/back/methods/worker-time-control/updateWorkerTimeControlMail.js @@ -72,7 +72,7 @@ module.exports = Self => { if (args.state == 'SENDED') { await workerTimeControlMail.updateAttributes({ - sendedCounter: workerTimeControlMail.sendedCounter + 1 + sendedCounter: workerTimeControlMail.sendedCounter ? workerTimeControlMail.sendedCounter + 1 : 1 }, myOptions); } }; From 8d7eda5af3307004d6dc2bdc9f42d585032282a5 Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 5 Oct 2023 09:12:54 +0200 Subject: [PATCH 194/427] refs #5673 fix: add development translation --- modules/claim/front/locale/es.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/modules/claim/front/locale/es.yml b/modules/claim/front/locale/es.yml index f6dac2b83..83ccf1e7b 100644 --- a/modules/claim/front/locale/es.yml +++ b/modules/claim/front/locale/es.yml @@ -17,6 +17,7 @@ Search claim by id or client name: Buscar reclamaciones por identificador o nomb Claim deleted!: Reclamación eliminada! claim: reclamación Photos: Fotos +Development: Trazabilidad Go to the claim: Ir a la reclamación Sale tracking: Líneas preparadas Ticket tracking: Estados del ticket From 726bc26a7529434b574cda5dc6c08f08b064b38e Mon Sep 17 00:00:00 2001 From: jgallego Date: Thu, 5 Oct 2023 09:40:05 +0200 Subject: [PATCH 195/427] fixes #6260 vn-user quito campos redundantes --- back/models/vn-user.json | 7 ------- 1 file changed, 7 deletions(-) diff --git a/back/models/vn-user.json b/back/models/vn-user.json index 9e3f8df89..f5eb3ae0f 100644 --- a/back/models/vn-user.json +++ b/back/models/vn-user.json @@ -23,10 +23,6 @@ "columnName": "name" } }, - "password": { - "type": "string", - "required": true - }, "roleFk": { "type": "number", "mysql": { @@ -42,9 +38,6 @@ "active": { "type": "boolean" }, - "email": { - "type": "string" - }, "created": { "type": "date" }, From 5b6eb0a2a62a9d481db230c3ffb966272b522026 Mon Sep 17 00:00:00 2001 From: carlossa Date: Thu, 5 Oct 2023 14:01:07 +0200 Subject: [PATCH 196/427] refs #5768 add address, nickname, pdf, email --- .../back/methods/client/incotermsAuthorizationEmail.js | 6 ++++++ .../back/methods/client/incotermsAuthorizationHtml.js | 6 ++++++ .../back/methods/client/incotermsAuthorizationPdf.js | 6 ++++++ modules/client/front/sample/create/index.html | 1 + .../incoterms-authorization/incoterms-authorization.js | 4 ++++ .../incoterms-authorization/incoterms-authorization.html | 8 ++++---- .../incoterms-authorization/incoterms-authorization.js | 3 ++- 7 files changed, 29 insertions(+), 5 deletions(-) diff --git a/modules/client/back/methods/client/incotermsAuthorizationEmail.js b/modules/client/back/methods/client/incotermsAuthorizationEmail.js index 4a21f20b0..9b3686b07 100644 --- a/modules/client/back/methods/client/incotermsAuthorizationEmail.js +++ b/modules/client/back/methods/client/incotermsAuthorizationEmail.js @@ -33,6 +33,12 @@ module.exports = Self => { type: 'number', description: 'The company id', required: true + }, + { + arg: 'addressId', + type: 'number', + description: 'The address id', + required: true } ], returns: { diff --git a/modules/client/back/methods/client/incotermsAuthorizationHtml.js b/modules/client/back/methods/client/incotermsAuthorizationHtml.js index 0a6bba0a8..af585b1ae 100644 --- a/modules/client/back/methods/client/incotermsAuthorizationHtml.js +++ b/modules/client/back/methods/client/incotermsAuthorizationHtml.js @@ -21,6 +21,12 @@ module.exports = Self => { type: 'number', description: 'The company id', required: true + }, + { + arg: 'addressId', + type: 'number', + description: 'The address id', + required: true } ], returns: [ diff --git a/modules/client/back/methods/client/incotermsAuthorizationPdf.js b/modules/client/back/methods/client/incotermsAuthorizationPdf.js index d37e473f1..ffe17c72f 100644 --- a/modules/client/back/methods/client/incotermsAuthorizationPdf.js +++ b/modules/client/back/methods/client/incotermsAuthorizationPdf.js @@ -21,6 +21,12 @@ module.exports = Self => { type: 'number', description: 'The company id', required: true + }, + { + arg: 'addressId', + type: 'number', + description: 'The address id', + required: true } ], returns: [ diff --git a/modules/client/front/sample/create/index.html b/modules/client/front/sample/create/index.html index f9db03036..9dce7ec72 100644 --- a/modules/client/front/sample/create/index.html +++ b/modules/client/front/sample/create/index.html @@ -71,6 +71,7 @@ required="true">

diff --git a/print/templates/reports/incoterms-authorization/incoterms-authorization.js b/print/templates/reports/incoterms-authorization/incoterms-authorization.js index e50cd99ec..22ae13167 100755 --- a/print/templates/reports/incoterms-authorization/incoterms-authorization.js +++ b/print/templates/reports/incoterms-authorization/incoterms-authorization.js @@ -20,7 +20,8 @@ module.exports = { required: true }, addressId: { - type: Number + type: Number, + required: true } } }; From 3b81b511c2d40262ed569ab746c5f5e8c5c45dbd Mon Sep 17 00:00:00 2001 From: carlossa Date: Thu, 5 Oct 2023 14:01:53 +0200 Subject: [PATCH 197/427] remove consolelog --- modules/client/front/sample/create/index.js | 2 -- 1 file changed, 2 deletions(-) diff --git a/modules/client/front/sample/create/index.js b/modules/client/front/sample/create/index.js index 305591511..6a249e84e 100644 --- a/modules/client/front/sample/create/index.js +++ b/modules/client/front/sample/create/index.js @@ -80,8 +80,6 @@ class Controller extends Section { if (this.clientSample.addressId) params.addressId = this.clientSample.addressId; - - console.log(this.clientSample); } preview() { From f40185c2d4577dc61e792d5c69cd0942c28a3ecb Mon Sep 17 00:00:00 2001 From: pablone Date: Thu, 5 Oct 2023 14:24:52 +0200 Subject: [PATCH 198/427] refs #4764 hotfix --- modules/ticket/front/services/index.html | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/modules/ticket/front/services/index.html b/modules/ticket/front/services/index.html index bc288a8a2..5128873c4 100644 --- a/modules/ticket/front/services/index.html +++ b/modules/ticket/front/services/index.html @@ -29,7 +29,7 @@ disabled="watcher.dataChanged() || !$ctrl.checkeds.length" label="Pay" ng-click="$ctrl.createRefund()" - vn-acl="invoicing, claimManager, salesAssistant" + vn-acl="invoicing, claimManager, salesAssistant, buyer" vn-acl-action="remove"> @@ -37,7 +37,9 @@ + disabled="!service.id" + vn-acl="invoicing, claimManager, salesAssistant, buyer" + vn-acl-action="remove"> + step="0.01" + min="0"> Date: Thu, 5 Oct 2023 15:04:39 +0200 Subject: [PATCH 199/427] refs #4764 fixReport --- print/templates/reports/delivery-note/delivery-note.html | 2 +- print/templates/reports/delivery-note/sql/services.sql | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/print/templates/reports/delivery-note/delivery-note.html b/print/templates/reports/delivery-note/delivery-note.html index 0be5a30f0..92dd1b126 100644 --- a/print/templates/reports/delivery-note/delivery-note.html +++ b/print/templates/reports/delivery-note/delivery-note.html @@ -117,7 +117,7 @@ {{service.price | currency('EUR', $i18n.locale)}} {{service.taxDescription}} - {{service.price | currency('EUR', $i18n.locale)}} + {{service.total | currency('EUR', $i18n.locale)}} diff --git a/print/templates/reports/delivery-note/sql/services.sql b/print/templates/reports/delivery-note/sql/services.sql index d64e8dc26..ec8a3e7ac 100644 --- a/print/templates/reports/delivery-note/sql/services.sql +++ b/print/templates/reports/delivery-note/sql/services.sql @@ -1,8 +1,9 @@ SELECT tc.code taxDescription, ts.description, - ts.quantity, - ts.price + ts.quantity, + ts.price, + ts.quantity * ts.price total FROM ticketService ts JOIN taxClass tc ON tc.id = ts.taxClassFk WHERE ts.ticketFk = ? \ No newline at end of file From 2c2fa97631466ebd06e52955b5507071d392b569 Mon Sep 17 00:00:00 2001 From: pablone Date: Thu, 5 Oct 2023 15:35:59 +0200 Subject: [PATCH 200/427] refs #4764 ticketRefound --- db/changes/234002/00-saleRefundACL.sql | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 db/changes/234002/00-saleRefundACL.sql diff --git a/db/changes/234002/00-saleRefundACL.sql b/db/changes/234002/00-saleRefundACL.sql new file mode 100644 index 000000000..62a8113d3 --- /dev/null +++ b/db/changes/234002/00-saleRefundACL.sql @@ -0,0 +1,2 @@ +INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId) + VALUES ('Sale','refund','WRITE','ALLOW','ROLE','buyer'); From 674fefeab5eabc02f8371fe7296cbbeb93e19fc8 Mon Sep 17 00:00:00 2001 From: pablone Date: Thu, 5 Oct 2023 15:43:02 +0200 Subject: [PATCH 201/427] refs #4764 ticket --- db/changes/234002/00-saleRefundACL.sql | 2 -- 1 file changed, 2 deletions(-) delete mode 100644 db/changes/234002/00-saleRefundACL.sql diff --git a/db/changes/234002/00-saleRefundACL.sql b/db/changes/234002/00-saleRefundACL.sql deleted file mode 100644 index 62a8113d3..000000000 --- a/db/changes/234002/00-saleRefundACL.sql +++ /dev/null @@ -1,2 +0,0 @@ -INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId) - VALUES ('Sale','refund','WRITE','ALLOW','ROLE','buyer'); From 62c7dc9db567160d2e750e18dca3ca266b8d6732 Mon Sep 17 00:00:00 2001 From: carlossa Date: Fri, 6 Oct 2023 06:16:42 +0200 Subject: [PATCH 202/427] hotfix-change minus --- modules/ticket/back/methods/sale/refund.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/ticket/back/methods/sale/refund.js b/modules/ticket/back/methods/sale/refund.js index 3c41aab1e..67172f3ac 100644 --- a/modules/ticket/back/methods/sale/refund.js +++ b/modules/ticket/back/methods/sale/refund.js @@ -114,8 +114,8 @@ module.exports = Self => { for (const service of services) { await models.TicketService.create({ description: service.description, - quantity: service.quantity, - price: - service.price, + quantity: - service.quantity, + price: service.price, taxClassFk: service.taxClassFk, ticketFk: refundTicket.id, ticketServiceTypeFk: service.ticketServiceTypeFk, From 05812c3f35dab91bc898bd57a592e15f3634c456 Mon Sep 17 00:00:00 2001 From: carlossa Date: Fri, 6 Oct 2023 07:14:30 +0200 Subject: [PATCH 203/427] refs #6282 left join --- modules/worker/back/methods/worker/search.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/worker/back/methods/worker/search.js b/modules/worker/back/methods/worker/search.js index cd0a466ea..7fe9e0666 100644 --- a/modules/worker/back/methods/worker/search.js +++ b/modules/worker/back/methods/worker/search.js @@ -46,7 +46,7 @@ module.exports = Self => { SELECT DISTINCT w.id, w.code, u.name, u.nickname, u.active, b.departmentFk FROM worker w JOIN account.user u ON u.id = w.id - JOIN business b ON b.workerFk = w.id + LEFT JOIN business b ON b.workerFk = w.id ) w`); stmt.merge(conn.makeSuffix(filter)); From 90fe65acc244fabd2c910bfe109ac00b408d6afc Mon Sep 17 00:00:00 2001 From: pablone Date: Fri, 6 Oct 2023 08:03:37 +0200 Subject: [PATCH 204/427] refs #6213 fixChanges --- db/changes/234201/00-supplierAccountCheckLength.sql | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/db/changes/234201/00-supplierAccountCheckLength.sql b/db/changes/234201/00-supplierAccountCheckLength.sql index 30ff739b8..55a68e37b 100644 --- a/db/changes/234201/00-supplierAccountCheckLength.sql +++ b/db/changes/234201/00-supplierAccountCheckLength.sql @@ -1,7 +1,6 @@ - UPDATE `vn`.`supplier` SET account = LPAD(id,10,'0') WHERE account IS NULL; ALTER TABLE `vn`.`supplier` ADD CONSTRAINT supplierAccountTooShort CHECK (LENGTH(account) = 10); -ALTER TABLE vn.supplier MODIFY COLUMN account varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT 4100000000 NOT NULL COMMENT 'Default accounting code for suppliers.'; +ALTER TABLE `vn`.`supplier` MODIFY COLUMN account varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT 4100000000 NOT NULL COMMENT 'Default accounting code for suppliers.'; From 1adfa33a9a893b8ed17b3a815290598249e3ce0b Mon Sep 17 00:00:00 2001 From: carlossa Date: Fri, 6 Oct 2023 14:52:30 +0200 Subject: [PATCH 205/427] hotfix length sales --- modules/ticket/back/methods/sale/refund.js | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/modules/ticket/back/methods/sale/refund.js b/modules/ticket/back/methods/sale/refund.js index 67172f3ac..03302550e 100644 --- a/modules/ticket/back/methods/sale/refund.js +++ b/modules/ticket/back/methods/sale/refund.js @@ -55,7 +55,7 @@ module.exports = Self => { const refoundZoneId = refundAgencyMode.zones()[0].id; - if (salesIds) { + if (salesIds.length) { const salesFilter = { where: {id: {inq: salesIds}}, include: { @@ -91,16 +91,14 @@ module.exports = Self => { await models.SaleComponent.create(components, myOptions); } } - if (!refundTicket) { const servicesFilter = { where: {id: {inq: servicesIds}} }; const services = await models.TicketService.find(servicesFilter, myOptions); - const ticketsIds = [...new Set(services.map(service => service.ticketFk))]; + const firstTicketId = services[0].ticketFk; const now = Date.vnNew(); - const [firstTicketId] = ticketsIds; // eslint-disable-next-line max-len refundTicket = await createTicketRefund(firstTicketId, now, refundAgencyMode, refoundZoneId, withWarehouse, myOptions); From 03afea3b8e633ed668a7d38bb299054bf4f056f1 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 10 Oct 2023 10:51:02 +0200 Subject: [PATCH 206/427] refs #6199 Added minQuantity in item --- modules/item/back/models/item.json | 3 +++ modules/item/front/basic-data/index.html | 9 +++++++++ modules/item/front/summary/index.html | 3 +++ 3 files changed, 15 insertions(+) diff --git a/modules/item/back/models/item.json b/modules/item/back/models/item.json index e99dcd996..8a635ea7e 100644 --- a/modules/item/back/models/item.json +++ b/modules/item/back/models/item.json @@ -131,6 +131,9 @@ "nonRecycledPlastic": { "type": "number" }, + "minQuantity": { + "type": "number" + }, "packingOut": { "type": "number" }, diff --git a/modules/item/front/basic-data/index.html b/modules/item/front/basic-data/index.html index fba4d679c..d3b30a7c2 100644 --- a/modules/item/front/basic-data/index.html +++ b/modules/item/front/basic-data/index.html @@ -183,6 +183,15 @@ rule> + + + +
+ +

From 4adee11c63f9a673468cba4dbe9cdc149791f59e Mon Sep 17 00:00:00 2001 From: carlossa Date: Tue, 10 Oct 2023 12:35:34 +0200 Subject: [PATCH 207/427] refs #5768 remove comment --- modules/client/front/sample/create/index.js | 3 --- 1 file changed, 3 deletions(-) diff --git a/modules/client/front/sample/create/index.js b/modules/client/front/sample/create/index.js index 6a249e84e..5370aa8a8 100644 --- a/modules/client/front/sample/create/index.js +++ b/modules/client/front/sample/create/index.js @@ -142,9 +142,6 @@ class Controller extends Section { }); } - /* - * Autocompletes address on client change - */ clientAddressesList(value) { let filter = { include: [ From d2ce920f13ea8aa2e7857de2951b43a38654fad3 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 10 Oct 2023 13:49:11 +0200 Subject: [PATCH 208/427] refs #6199 Added minQuantity in catalog and more --- modules/item/front/basic-data/index.html | 2 +- modules/item/front/basic-data/locale/es.yml | 3 +- modules/item/front/summary/locale/es.yml | 1 + .../order/back/methods/order/catalogFilter.js | 43 ++++++++++--------- modules/order/front/catalog-view/index.html | 13 ++++++ .../order/front/catalog-view/locale/es.yml | 1 + 6 files changed, 40 insertions(+), 23 deletions(-) diff --git a/modules/item/front/basic-data/index.html b/modules/item/front/basic-data/index.html index d3b30a7c2..f412626bf 100644 --- a/modules/item/front/basic-data/index.html +++ b/modules/item/front/basic-data/index.html @@ -185,7 +185,7 @@ { )); stmt = new ParameterizedSQL(` - SELECT - i.id, - i.name, - i.subName, - i.image, - i.tag5, - i.value5, - i.tag6, - i.value6, - i.tag7, - i.value7, - i.tag8, - i.value8, - i.stars, - tci.price, - tci.available, - w.lastName AS lastName, - w.firstName, - tci.priceKg, - ink.hex + SELECT i.id, + i.name, + i.subName, + i.image, + i.tag5, + i.value5, + i.tag6, + i.value6, + i.tag7, + i.value7, + i.tag8, + i.value8, + i.stars, + tci.price, + tci.available, + w.lastName lastName, + w.firstName, + tci.priceKg, + ink.hex, + i.minQuantity FROM tmp.ticketCalculateItem tci JOIN vn.item i ON i.id = tci.itemFk JOIN vn.itemType it ON it.id = i.typeFk JOIN vn.worker w on w.id = it.workerFk - LEFT JOIN vn.ink ON ink.id = i.inkFk`); + LEFT JOIN vn.ink ON ink.id = i.inkFk + `); // Apply order by tag if (orderBy.isTag) { diff --git a/modules/order/front/catalog-view/index.html b/modules/order/front/catalog-view/index.html index fca728855..9333e923b 100644 --- a/modules/order/front/catalog-view/index.html +++ b/modules/order/front/catalog-view/index.html @@ -37,6 +37,19 @@ value="{{::item.value7}}"> +
+ + + {{::item.minQuantity}} +
diff --git a/modules/order/front/catalog-view/locale/es.yml b/modules/order/front/catalog-view/locale/es.yml index 82fe5e9e8..8fb3c7896 100644 --- a/modules/order/front/catalog-view/locale/es.yml +++ b/modules/order/front/catalog-view/locale/es.yml @@ -1 +1,2 @@ Order created: Orden creada +Minimal quantity: Cantidad mínima \ No newline at end of file From 2b41bf7eb14744a618119e878f9ca302633e7c74 Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 11 Oct 2023 07:39:41 +0200 Subject: [PATCH 209/427] refs #6199 Requested changes --- modules/item/front/basic-data/locale/es.yml | 2 +- modules/order/back/methods/order/catalogFilter.js | 2 +- modules/order/front/catalog-view/index.html | 12 +++++------- modules/order/front/catalog-view/style.scss | 10 ++++++++++ 4 files changed, 17 insertions(+), 9 deletions(-) diff --git a/modules/item/front/basic-data/locale/es.yml b/modules/item/front/basic-data/locale/es.yml index 51cbdabd9..fc490e448 100644 --- a/modules/item/front/basic-data/locale/es.yml +++ b/modules/item/front/basic-data/locale/es.yml @@ -15,5 +15,5 @@ Generic: Genérico This item does need a photo: Este artículo necesita una foto Do photo: Hacer foto Recycled Plastic: Plástico reciclado -Non recycled plastic: Plástico no +Non recycled plastic: Plástico no reciclado Minimum sales quantity: Cantidad mínima de venta diff --git a/modules/order/back/methods/order/catalogFilter.js b/modules/order/back/methods/order/catalogFilter.js index dca82322a..722f3e096 100644 --- a/modules/order/back/methods/order/catalogFilter.js +++ b/modules/order/back/methods/order/catalogFilter.js @@ -115,7 +115,7 @@ module.exports = Self => { i.stars, tci.price, tci.available, - w.lastName lastName, + w.lastName, w.firstName, tci.priceKg, ink.hex, diff --git a/modules/order/front/catalog-view/index.html b/modules/order/front/catalog-view/index.html index 9333e923b..c9375aab5 100644 --- a/modules/order/front/catalog-view/index.html +++ b/modules/order/front/catalog-view/index.html @@ -37,16 +37,14 @@ value="{{::item.value7}}"> -
+
+ ng-class="'min-quantity-icon'"> {{::item.minQuantity}}
diff --git a/modules/order/front/catalog-view/style.scss b/modules/order/front/catalog-view/style.scss index 87f70cde5..8288855a4 100644 --- a/modules/order/front/catalog-view/style.scss +++ b/modules/order/front/catalog-view/style.scss @@ -44,4 +44,14 @@ vn-order-catalog { height: 30px; position: relative; } + .text-caption-reduced { + display: flex; + align-items: center; + justify-content: flex-end; + color: tomato; + } + .min-quantity-icon { + font-size: 18px; + margin-right: 3px; + } } \ No newline at end of file From d41233efaf9da5fb7b8065085ede26fe38c4ecee Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 11 Oct 2023 07:59:05 +0200 Subject: [PATCH 210/427] refs #6199 Requested change, name of color --- modules/order/front/catalog-view/style.scss | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/order/front/catalog-view/style.scss b/modules/order/front/catalog-view/style.scss index 8288855a4..abfde3589 100644 --- a/modules/order/front/catalog-view/style.scss +++ b/modules/order/front/catalog-view/style.scss @@ -48,7 +48,7 @@ vn-order-catalog { display: flex; align-items: center; justify-content: flex-end; - color: tomato; + color: $color-alert; } .min-quantity-icon { font-size: 18px; From 6b1dded2225645da60e45cda1a8be567af8cb4a1 Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 11 Oct 2023 08:28:52 +0200 Subject: [PATCH 211/427] refs #6199 Requested change, position of input --- modules/item/front/basic-data/index.html | 66 ++++++++++++------------ 1 file changed, 33 insertions(+), 33 deletions(-) diff --git a/modules/item/front/basic-data/index.html b/modules/item/front/basic-data/index.html index f412626bf..426c17800 100644 --- a/modules/item/front/basic-data/index.html +++ b/modules/item/front/basic-data/index.html @@ -33,6 +33,8 @@ rule info="Full name calculates based on tags 1-3. Is not recommended to change it manually"> + + + + +
{{::name}}
+
+ #{{::id}} +
+
+ + + + +
- - -
{{::name}}
-
- #{{::id}} -
-
- - - - -
+ +
- - - - Date: Wed, 11 Oct 2023 12:04:12 +0200 Subject: [PATCH 212/427] =?UTF-8?q?refs=20#6293=20traducci=C3=B3n?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- modules/ticket/front/index/locale/es.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/modules/ticket/front/index/locale/es.yml b/modules/ticket/front/index/locale/es.yml index afa3d654e..89828d4d9 100644 --- a/modules/ticket/front/index/locale/es.yml +++ b/modules/ticket/front/index/locale/es.yml @@ -18,3 +18,4 @@ Multiple invoice: Factura múltiple Make invoice...: Crear factura... Invoice selected tickets: Facturar tickets seleccionados Are you sure to invoice tickets: ¿Seguro que quieres facturar {{ticketsAmount}} tickets? +Rounding: Redondeo From df9d6fd6f82d1700e4e6e323c2856d91861fefd0 Mon Sep 17 00:00:00 2001 From: jgallego Date: Wed, 11 Oct 2023 14:06:28 +0200 Subject: [PATCH 213/427] efectue con acento --- modules/ticket/front/descriptor/locale/es.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/ticket/front/descriptor/locale/es.yml b/modules/ticket/front/descriptor/locale/es.yml index 86b1a6b57..e1006bed4 100644 --- a/modules/ticket/front/descriptor/locale/es.yml +++ b/modules/ticket/front/descriptor/locale/es.yml @@ -3,7 +3,7 @@ Are you sure you want to send it?: ¿Seguro que quieres enviarlo? Show pallet report: Ver hoja de pallet Change shipped hour: Cambiar hora de envío Shipped hour: Hora de envío -Make a payment: "Verdnatura le comunica:\rSu pedido está pendiente de pago.\rPor favor, entre en la página web y efectue el pago con tarjeta.\rMuchas gracias." +Make a payment: "Verdnatura le comunica:\rSu pedido está pendiente de pago.\rPor favor, entre en la página web y efectúe el pago con tarjeta.\rMuchas gracias." Minimum is needed: "Verdnatura le recuerda:\rEs necesario un importe mínimo de 50€ (Sin IVA) en su pedido {{ticketId}} del día {{created | date: 'dd/MM/yyyy'}} para recibirlo sin portes adicionales." Ticket invoiced: Ticket facturado Make invoice: Crear factura From 0028dd150a806c5befc148f058d154a84473bdab Mon Sep 17 00:00:00 2001 From: sergiodt Date: Wed, 11 Oct 2023 17:12:55 +0200 Subject: [PATCH 214/427] refs #5134 feat:models --- db/changes/234201/.gitkeep | 0 db/changes/234201/00-aclClient.sql | 3 +++ 2 files changed, 3 insertions(+) create mode 100644 db/changes/234201/.gitkeep create mode 100644 db/changes/234201/00-aclClient.sql diff --git a/db/changes/234201/.gitkeep b/db/changes/234201/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/db/changes/234201/00-aclClient.sql b/db/changes/234201/00-aclClient.sql new file mode 100644 index 000000000..3df9522cf --- /dev/null +++ b/db/changes/234201/00-aclClient.sql @@ -0,0 +1,3 @@ + +INSERT INTO `salix`.`ACL` ( model, property, accessType, permission, principalType, principalId) + VALUES('TicketCollection', '*', 'WRITE', 'ALLOW', 'ROLE', 'production'); From 1a7f7b6a00a8eaaa3b55ac4cd8db41cccbce0b3c Mon Sep 17 00:00:00 2001 From: sergiodt Date: Fri, 13 Oct 2023 08:02:00 +0200 Subject: [PATCH 215/427] refs #5134 feat:models --- db/changes/234002/00-aclClient.sql | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 db/changes/234002/00-aclClient.sql diff --git a/db/changes/234002/00-aclClient.sql b/db/changes/234002/00-aclClient.sql deleted file mode 100644 index 3df9522cf..000000000 --- a/db/changes/234002/00-aclClient.sql +++ /dev/null @@ -1,3 +0,0 @@ - -INSERT INTO `salix`.`ACL` ( model, property, accessType, permission, principalType, principalId) - VALUES('TicketCollection', '*', 'WRITE', 'ALLOW', 'ROLE', 'production'); From 104d11ac3c1d3a2c39174782c1bc0b7f76847a78 Mon Sep 17 00:00:00 2001 From: pablone Date: Fri, 13 Oct 2023 08:52:28 +0200 Subject: [PATCH 216/427] refs #3126 procReplace --- db/.archive/231001/03-packagingFkProc.sql | 669 -------- .../234001}/00-packagingFk.sql | 0 .../234001}/00-packagingFkviews.sql | 0 .../234001}/02-packagingFktrigger.sql | 0 db/changes/234001/03-packagingFkProc.sql | 1381 +++++++++++++++++ 5 files changed, 1381 insertions(+), 669 deletions(-) delete mode 100644 db/.archive/231001/03-packagingFkProc.sql rename db/{.archive/231001 => changes/234001}/00-packagingFk.sql (100%) rename db/{.archive/231001 => changes/234001}/00-packagingFkviews.sql (100%) rename db/{.archive/231001 => changes/234001}/02-packagingFktrigger.sql (100%) create mode 100644 db/changes/234001/03-packagingFkProc.sql diff --git a/db/.archive/231001/03-packagingFkProc.sql b/db/.archive/231001/03-packagingFkProc.sql deleted file mode 100644 index acbf54a76..000000000 --- a/db/.archive/231001/03-packagingFkProc.sql +++ /dev/null @@ -1,669 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`travelVolume`(vTravelFk INT) -BEGIN - - SELECT w1.name AS ORI, - w2.name AS DES, - tr.shipped shipment, - tr.landed landing, - a.name Agencia, - s.name Proveedor, - e.id Id_Entrada, - e.invoiceNumber Referencia, - CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) * - vn.item_getVolume(b.itemFk ,b.packagingFk)) / vc.trolleyM3 / 1000000 ,1) AS DECIMAL(10,2)) AS CC, - CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) * - vn.item_getVolume(b.itemFk ,b.packagingFk)) / vc.palletM3 / 1000000,1) AS DECIMAL(10,2)) AS espais - FROM vn.buy b - JOIN vn.entry e ON e.id = b.entryFk - JOIN vn.supplier s ON s.id = e.supplierFk - JOIN vn.travel tr ON tr.id = e.travelFk - JOIN vn.agencyMode a ON a.id = tr.agencyModeFk - JOIN vn.warehouse w1 ON w1.id = tr.warehouseInFk - JOIN vn.warehouse w2 ON w2.id = tr.warehouseOutFk - JOIN vn.volumeConfig vc - JOIN vn.item i ON i.id = b.itemFk - JOIN vn.itemType it ON it.id = i.typeFk - WHERE tr.id = vTravelFk; - -END$$ -DELIMITER ; - -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`travelVolume_get`(vFromDated DATE, vToDated DATE, vWarehouseFk INT) -BEGIN - SELECT tr.landed Fecha, - a.name Agencia, - count(DISTINCT e.id) numEntradas, - FLOOR(sum(item_getVolume(b.itemFk, b.packagingFk) * b.stickers / 1000000 )) AS m3 - FROM vn.travel tr - JOIN vn.agencyMode a ON a.id = tr.agencyModeFk - JOIN vn.entry e ON e.travelFk = tr.id - JOIN vn.buy b ON b.entryFk = e.id - WHERE tr.landed BETWEEN vFromDated AND vToDated - AND e.isRaid = FALSE - AND tr.warehouseInFk = vWarehouseFk - GROUP BY tr.landed , a.name ; -END$$ -DELIMITER ; - -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`travel_getEntriesMissingPackage`(vSelf INT) -BEGIN - DECLARE vpackageOrPackingNull INT; - DECLARE vTravelFk INT; - - SELECT travelfk INTO vTravelFk - FROM entry - WHERE id = vSelf; - - SELECT e.id entryFk - FROM travel t - JOIN entry e ON e.travelFk = t.id - JOIN buy b ON b.entryFk = e.id - WHERE t.id = vTravelFk - AND (b.packing IS NULL OR b.packagingFk IS NULL); -END$$ -DELIMITER ; - -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketBoxesView`(IN vTicketFk INT) -BEGIN - - SELECT s.id, - s.itemFk, - s.concept, - floor(s.quantity / b.packing) as Cajas, - b.packing, - s.isPicked, - i.size - FROM ticket t - JOIN sale s ON s.ticketFk = t.id - JOIN item i ON i.id = s.itemFk - JOIN cache.last_buy lb on lb.warehouse_id = t.warehouseFk AND lb.item_id = s.itemFk - JOIN buy b on b.id = lb.buy_id - JOIN packaging p on p.id = b.packagingFk - WHERE s.quantity >= b.packing - AND t.id = vTicketFk - AND p.isBox - GROUP BY s.itemFk; - - -END$$ -DELIMITER ; - -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`stockBuyedByWorker`( - vDate DATE, - vWorker INT) -BEGIN -/** - * Calculates the space reserved by buyers of the same container - * - * @param vdate date of container delivery - * @param vWorker buyer reserving space in the container - */ - DECLARE vVolume DECIMAL(10, 2); - DECLARE vWarehouseFk INT; - DECLARE vCompressionRatio DECIMAL(1, 1); - - CALL stockTraslation(vDate); - - SELECT warehouseFk, conversionCoefficient INTO vWarehouseFk, vCompressionRatio - FROM auctionConfig; - - SELECT volume INTO vVolume - FROM vn.packaging WHERE id = 'cc'; - - SELECT b.entryFk Id_Entrada, - i.id Id_Article, - i.name Article, - ti.amount Cantidad, - (vCompressionRatio * (ti.amount / b.packing) * vn.buy_getVolume(b.id)) - / vVolume buyed, - b.packagingFk id_cubo, - b.packing - FROM tmp.item ti - JOIN item i ON i.id = ti.item_id - JOIN itemType it ON i.typeFk = it.id - JOIN itemCategory ic ON ic.id = it.categoryFk - JOIN worker w ON w.id = it.workerFk - JOIN tmp.buyUltimate bu ON bu.itemFk = i.id - AND bu.warehouseFk = vWarehouseFk - JOIN buy b ON b.id = bu.buyFk - WHERE ic.display AND w.id = vWorker; - - DROP TEMPORARY TABLE - tmp.buyUltimate, - tmp.item; -END$$ -DELIMITER ; - -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingMakeFromDate`(IN `vShelvingFk` VARCHAR(8), IN `vBarcode` VARCHAR(22), IN `vQuantity` INT, IN `vPackagingFk` VARCHAR(10), IN `vGrouping` INT, IN `vPacking` INT, IN `vWarehouseFk` INT, `vCreated` VARCHAR(22)) -BEGIN - - DECLARE vItemFk INT; - - SELECT vn.barcodeToItem(vBarcode) INTO vItemFk; - - SELECT itemFk INTO vItemFk - FROM vn.buy b - WHERE b.id = vItemFk; - - IF (SELECT COUNT(*) FROM vn.shelving WHERE code = vShelvingFk COLLATE utf8_unicode_ci) = 0 THEN - - INSERT IGNORE INTO vn.parking(`code`) VALUES(vShelvingFk); - INSERT INTO vn.shelving(`code`, parkingFk) - SELECT vShelvingFk, id - FROM vn.parking - WHERE `code` = vShelvingFk COLLATE utf8_unicode_ci; - - END IF; - - IF (SELECT COUNT(*) FROM vn.itemShelving - WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk - AND itemFk = vItemFk - AND packing = vPacking) = 1 THEN - - UPDATE vn.itemShelving - SET visible = visible+vQuantity, - created = vCreated - WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk - AND itemFk = vItemFk - AND packing = vPacking; - - ELSE - CALL cache.last_buy_refresh(FALSE); - INSERT INTO itemShelving( itemFk, - shelvingFk, - visible, - created, - `grouping`, - packing, - packagingFk) - SELECT vItemFk, - vShelvingFk, - vQuantity, - vCreated, - IF(vGrouping = 0, IFNULL(b.packing, vPacking), vGrouping) `grouping`, - IF(vPacking = 0, b.packing, vPacking) packing, - IF(vPackagingFk = '', b.packagingFk, vPackagingFk) packaging - FROM vn.item i - LEFT JOIN cache.last_buy lb ON i.id = lb.item_id AND lb.warehouse_id = vWarehouseFk - LEFT JOIN vn.buy b ON b.id = lb.buy_id - WHERE i.id = vItemFk; - END IF; - -END$$ -DELIMITER ; - -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelving_add`(IN vShelvingFk VARCHAR(8), IN vBarcode VARCHAR(22), IN vQuantity INT, IN vPackagingFk VARCHAR(10), IN vGrouping INT, IN vPacking INT, IN vWarehouseFk INT) -BEGIN - - -/** - * Añade registro o lo actualiza si ya existe. - * - * @param vShelvingFk matrícula del carro - * @param vBarcode el id del registro - * @param vQuantity indica la cantidad del producto - * @param vPackagingFk el packaging del producto en itemShelving, NULL para coger el de la ultima compra - * @param vGrouping el grouping del producto en itemShelving, NULL para coger el de la ultima compra - * @param vPacking el packing del producto, NULL para coger el de la ultima compra - * @param vWarehouseFk indica el sector - * - **/ - - DECLARE vItemFk INT; - - SELECT barcodeToItem(vBarcode) INTO vItemFk; - - IF (SELECT COUNT(*) FROM shelving WHERE code = vShelvingFk COLLATE utf8_unicode_ci) = 0 THEN - - INSERT IGNORE INTO parking(code) VALUES(vShelvingFk); - INSERT INTO shelving(code, parkingFk) - SELECT vShelvingFk, id - FROM parking - WHERE `code` = vShelvingFk COLLATE utf8_unicode_ci; - - END IF; - - IF (SELECT COUNT(*) FROM itemShelving - WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk - AND itemFk = vItemFk - AND packing = vPacking) = 1 THEN - - UPDATE itemShelving - SET visible = visible+vQuantity - WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk AND itemFk = vItemFk AND packing = vPacking; - - ELSE - CALL cache.last_buy_refresh(FALSE); - INSERT INTO itemShelving( itemFk, - shelvingFk, - visible, - grouping, - packing, - packagingFk) - - SELECT vItemFk, - vShelvingFk, - vQuantity, - IFNULL(vGrouping, b.grouping), - IFNULL(vPacking, b.packing), - IFNULL(vPackagingFk, b.packagingFk) - FROM item i - LEFT JOIN cache.last_buy lb ON i.id = lb.item_id AND lb.warehouse_id = vWarehouseFk - LEFT JOIN buy b ON b.id = lb.buy_id - WHERE i.id = vItemFk; - END IF; -END$$ -DELIMITER ; - -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemFreight_Show`(vItemFk INT, vWarehouseFk INT) -BEGIN - - SELECT cm3 Volumen_Entrada, - cm3delivery Volumen_Salida, - p.volume Volumen_del_embalaje, - p.width Ancho_del_embalaje, - p.`depth` Largo_del_embalaje, - b.packagingFk , - IFNULL(p.height, i.`size`) + 10 Altura, - b.packing Packing_Entrada, - i.packingOut Packing_Salida, - i.id itemFk, - b.id buyFk, - b.entryFk, - w.name warehouseFk - FROM vn.itemCost ic - JOIN vn.item i ON i.id = ic.itemFk - LEFT JOIN cache.last_buy lb ON lb.item_id = ic.itemFk AND lb.warehouse_id = ic.warehouseFk - LEFT JOIN vn.buy b ON b.id = lb.buy_id - LEFT JOIN vn.packaging p ON p.id = b.packagingFk - LEFT JOIN vn.warehouse w ON w.id = ic.warehouseFk - WHERE ic.itemFk = vItemFk - AND ic.warehouseFk = vWarehouseFk; -END$$ -DELIMITER ; - -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`inventoryMake`(vDate DATE, vWh INT) -proc: BEGIN -/** -* Recalcula los inventarios de todos los almacenes, si vWh = 0 -* -* @param vDate Fecha de los nuevos inventarios -* @param vWh almacen al cual hacer el inventario -*/ - - DECLARE vDone BOOL; - DECLARE vEntryFk INT; - DECLARE vTravelFk INT; - DECLARE vDateLastInventory DATE; - DECLARE vDateYesterday DATETIME DEFAULT vDate - INTERVAL 1 SECOND; - DECLARE vWarehouseOutFkInventory INT; - DECLARE vInventorySupplierFk INT; - DECLARE vAgencyModeFkInventory INT; - - DECLARE cWarehouses CURSOR FOR - SELECT id - FROM warehouse - WHERE isInventory - AND vWh IN (0,id); - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - OPEN cWarehouses; - SET @isModeInventory := TRUE; - l: LOOP - - SET vDone = FALSE; - FETCH cWarehouses INTO vWh; - - IF vDone THEN - LEAVE l; - END IF; - - SELECT w.id INTO vWarehouseOutFkInventory - FROM warehouse w - WHERE w.code = 'inv'; - - SELECT inventorySupplierFk INTO vInventorySupplierFk - FROM entryConfig; - - SELECT am.id INTO vAgencyModeFkInventory - FROM agencyMode am - where code = 'inv'; - - SELECT MAX(landed) INTO vDateLastInventory - FROM travel tr - JOIN entry e ON e.travelFk = tr.id - JOIN buy b ON b.entryFk = e.id - WHERE warehouseOutFk = vWarehouseOutFkInventory - AND landed < vDate - AND e.supplierFk = vInventorySupplierFk - AND warehouseInFk = vWh - AND NOT isRaid; - - IF vDateLastInventory IS NULL THEN - SELECT inventoried INTO vDateLastInventory FROM config; - END IF; - - -- Generamos travel, si no existe. - SET vTravelFK = 0; - - SELECT id INTO vTravelFk - FROM travel - WHERE warehouseOutFk = vWarehouseOutFkInventory - AND warehouseInFk = vWh - AND landed = vDate - AND agencyModeFk = vAgencyModeFkInventory - AND ref = 'inventario' - LIMIT 1; - - IF NOT vTravelFK THEN - - INSERT INTO travel SET - warehouseOutFk = vWarehouseOutFkInventory, - warehouseInFk = vWh, - shipped = vDate, - landed = vDate, - agencyModeFk = vAgencyModeFkInventory, - ref = 'inventario', - isDelivered = TRUE, - isReceived = TRUE; - - SELECT LAST_INSERT_ID() INTO vTravelFk; - - END IF; - - -- Generamos entrada si no existe, o la vaciamos. - SET vEntryFk = 0; - - SELECT id INTO vEntryFk - FROM entry - WHERE supplierFk = vInventorySupplierFk - AND travelFk = vTravelFk; - - IF NOT vEntryFk THEN - - INSERT INTO entry SET - supplierFk = vInventorySupplierFk, - isConfirmed = TRUE, - isOrdered = TRUE, - travelFk = vTravelFk; - - SELECT LAST_INSERT_ID() INTO vEntryFk; - - ELSE - - DELETE FROM buy WHERE entryFk = vEntryFk; - - END IF; - - -- Preparamos tabla auxilar - CREATE OR REPLACE TEMPORARY TABLE tmp.inventory ( - itemFk INT(11) NOT NULL PRIMARY KEY, - quantity int(11) DEFAULT '0', - buyingValue decimal(10,3) DEFAULT '0.000', - freightValue decimal(10,3) DEFAULT '0.000', - packing int(11) DEFAULT '0', - `grouping` smallint(5) unsigned NOT NULL DEFAULT '1', - groupingMode tinyint(4) NOT NULL DEFAULT 0 , - comissionValue decimal(10,3) DEFAULT '0.000', - packageValue decimal(10,3) DEFAULT '0.000', - packageFk varchar(10) COLLATE utf8_unicode_ci DEFAULT '--', - price1 decimal(10,2) DEFAULT '0.00', - price2 decimal(10,2) DEFAULT '0.00', - price3 decimal(10,2) DEFAULT '0.00', - minPrice decimal(10,2) DEFAULT '0.00', - producer varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, - INDEX (itemFK)) ENGINE = MEMORY; - - -- Compras - INSERT INTO tmp.inventory(itemFk,quantity) - SELECT b.itemFk, SUM(b.quantity) - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel tr ON tr.id = e.travelFk - WHERE tr.warehouseInFk = vWh - AND tr.landed BETWEEN vDateLastInventory - AND vDateYesterday - AND NOT isRaid - GROUP BY b.itemFk; - SELECT vDateLastInventory , vDateYesterday; - - -- Traslados - INSERT INTO tmp.inventory(itemFk, quantity) - SELECT itemFk, quantityOut - FROM ( - SELECT b.itemFk,- SUM(b.quantity) quantityOut - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel tr ON tr.id = e.travelFk - WHERE tr.warehouseOutFk = vWh - AND tr.shipped BETWEEN vDateLastInventory - AND vDateYesterday - AND NOT isRaid - GROUP BY b.itemFk - ) sub - ON DUPLICATE KEY UPDATE quantity = IFNULL(quantity, 0) + sub.quantityOut; - - -- Ventas - INSERT INTO tmp.inventory(itemFk,quantity) - SELECT itemFk, saleOut - FROM ( - SELECT s.itemFk, - SUM(s.quantity) saleOut - FROM sale s - JOIN ticket t ON t.id = s.ticketFk - WHERE t.warehouseFk = vWh - AND t.shipped BETWEEN vDateLastInventory AND vDateYesterday - GROUP BY s.itemFk - ) sub - ON DUPLICATE KEY UPDATE quantity = IFNULL(quantity,0) + sub.saleOut; - - -- Actualiza valores de la ultima compra - UPDATE tmp.inventory inv - JOIN cache.last_buy lb ON lb.item_id = inv.itemFk AND lb.warehouse_id = vWh - JOIN buy b ON b.id = lb.buy_id - JOIN item i ON i.id = b.itemFk - LEFT JOIN producer p ON p.id = i.producerFk - SET inv.buyingValue = b.buyingValue, - inv.freightValue = b.freightValue, - inv.packing = b.packing, - inv.`grouping`= b.`grouping`, - inv.groupingMode = b.groupingMode, - inv.comissionValue = b.comissionValue, - inv.packageValue = b.packageValue, - inv.packageFk = b.packagingFk, - inv.price1 = b.price1, - inv.price2 = b.price2, - inv.price3 = b.price3, - inv.minPrice = b.minPrice, - inv.producer = p.name; - - INSERT INTO buy( itemFk, - quantity, - buyingValue, - freightValue, - packing, - `grouping`, - groupingMode, - comissionValue, - packageValue, - packagingFk, - price1, - price2, - price3, - minPrice, - entryFk) - SELECT itemFk, - GREATEST(quantity, 0), - buyingValue, - freightValue, - packing, - `grouping`, - groupingMode, - comissionValue, - packageValue, - packagingFk, - price1, - price2, - price3, - minPrice, - vEntryFk - FROM tmp.inventory; - - SELECT vWh, COUNT(*), util.VN_NOW() FROM tmp.inventory; - - -- Actualizamos el campo lastUsed de item - UPDATE item i - JOIN tmp.inventory i2 ON i2.itemFk = i.id - SET i.lastUsed = NOW() - WHERE i2.quantity; - - -- DROP TEMPORARY TABLE tmp.inventory; - - END LOOP; - - CLOSE cWarehouses; - - UPDATE config SET inventoried = vDate; - SET @isModeInventory := FALSE; - - DROP TEMPORARY TABLE IF EXISTS tmp.entryToDelete; - CREATE TEMPORARY TABLE tmp.entryToDelete - (INDEX(entryId) USING BTREE) ENGINE = MEMORY - SELECT e.id as entryId, - t.id as travelId - FROM travel t - JOIN `entry` e ON e.travelFk = t.id - WHERE e.supplierFk = vInventorySupplierFk - AND t.shipped <= util.VN_CURDATE() - INTERVAL 12 DAY - AND (DAY(t.shipped) <> 1 OR shipped < util.VN_CURDATE() - INTERVAL 12 DAY); - - DELETE e - FROM `entry` e - JOIN tmp.entryToDelete tmp ON tmp.entryId = e.id; - - DELETE IGNORE t - FROM travel t - JOIN tmp.entryToDelete tmp ON tmp.travelId = t.id; -END$$ -DELIMITER ; - -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`inventory_repair`() -BEGIN - - DROP TEMPORARY TABLE IF EXISTS tmp.lastEntry; - CREATE TEMPORARY TABLE tmp.lastEntry - (PRIMARY KEY (buyFk)) - SELECT - i.id AS itemFk, - w.id AS warehouseFk, - w.name AS warehouse, - tr.landed, - b.id AS buyFk, - b.entryFk, - b.isIgnored, - b.price2, - b.price3, - b.stickers, - b.packing, - b.grouping, - b.groupingMode, - b.weight, - i.stems, - b.quantity, - b.buyingValue, - b.packagingFk , - s.id AS supplierFk, - s.name AS supplier - FROM itemType it - RIGHT JOIN (entry e - LEFT JOIN supplier s ON s.id = e.supplierFk - RIGHT JOIN buy b ON b.entryFk = e.id - LEFT JOIN item i ON i.id = b.itemFk - LEFT JOIN ink ON ink.id = i.inkFk - LEFT JOIN travel tr ON tr.id = e.travelFk - LEFT JOIN warehouse w ON w.id = tr.warehouseInFk - LEFT JOIN origin o ON o.id = i.originFk - ) ON it.id = i.typeFk - LEFT JOIN edi.ekt ek ON b.ektFk = ek.id - WHERE (b.packagingFk = "--" OR b.price2 = 0 OR b.packing = 0 OR b.buyingValue = 0) AND tr.landed > util.firstDayOfMonth(TIMESTAMPADD(MONTH,-1,util.VN_CURDATE())) AND s.name = 'INVENTARIO'; - - DROP TEMPORARY TABLE IF EXISTS tmp.lastEntryOk; - CREATE TEMPORARY TABLE tmp.lastEntryOk - (PRIMARY KEY (buyFk)) - SELECT - i.id AS itemFk, - w.id AS warehouseFk, - w.name AS warehouse, - tr.landed, - b.id AS buyFk, - b.entryFk, - b.isIgnored, - b.price2, - b.price3, - b.stickers, - b.packing, - b.grouping, - b.groupingMode, - b.weight, - i.stems, - b.quantity, - b.buyingValue, - b.packagingFk, - s.id AS supplierFk, - s.name AS supplier - FROM itemType it - RIGHT JOIN (entry e - LEFT JOIN supplier s ON s.id = e.supplierFk - RIGHT JOIN buy b ON b.entryFk = e.id - LEFT JOIN item i ON i.id = b.itemFk - LEFT JOIN ink ON ink.id = i.inkFk - LEFT JOIN travel tr ON tr.id = e.travelFk - LEFT JOIN warehouse w ON w.id = tr.warehouseInFk - LEFT JOIN origin o ON o.id = i.originFk - ) ON it.id = i.typeFk - LEFT JOIN edi.ekt ek ON b.ektFk = ek.id - WHERE b.packagingFk != "--" AND b.price2 != 0 AND b.packing != 0 AND b.buyingValue > 0 AND tr.landed > util.firstDayOfMonth(TIMESTAMPADD(MONTH,-2,util.VN_CURDATE())) - ORDER BY tr.landed DESC; - - DROP TEMPORARY TABLE IF EXISTS tmp.lastEntryOkGroup; - CREATE TEMPORARY TABLE tmp.lastEntryOkGroup - (INDEX (warehouseFk,itemFk)) - SELECT * - FROM tmp.lastEntryOk tmp - GROUP BY tmp.itemFk,tmp.warehouseFk; - - UPDATE buy b - JOIN tmp.lastEntry lt ON lt.buyFk = b.id - JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk - SET b.packagingFk = eo.packagingFk WHERE b.packagingFk = "--"; - - UPDATE buy b - JOIN tmp.lastEntry lt ON lt.buyFk = b.id - JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk - SET b.price2 = eo.price2 WHERE b.price2 = 0 ; - - UPDATE buy b - JOIN tmp.lastEntry lt ON lt.buyFk = b.id - JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk - SET b.packing = eo.packing WHERE b.packing = 0; - - UPDATE buy b - JOIN tmp.lastEntry lt ON lt.buyFk = b.id - JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk - SET b.buyingValue = eo.buyingValue WHERE b.buyingValue = 0; - - DROP TEMPORARY TABLE tmp.lastEntry; - DROP TEMPORARY TABLE tmp.lastEntryOk; - DROP TEMPORARY TABLE tmp.lastEntryOkGroup; -END$$ -DELIMITER ; \ No newline at end of file diff --git a/db/.archive/231001/00-packagingFk.sql b/db/changes/234001/00-packagingFk.sql similarity index 100% rename from db/.archive/231001/00-packagingFk.sql rename to db/changes/234001/00-packagingFk.sql diff --git a/db/.archive/231001/00-packagingFkviews.sql b/db/changes/234001/00-packagingFkviews.sql similarity index 100% rename from db/.archive/231001/00-packagingFkviews.sql rename to db/changes/234001/00-packagingFkviews.sql diff --git a/db/.archive/231001/02-packagingFktrigger.sql b/db/changes/234001/02-packagingFktrigger.sql similarity index 100% rename from db/.archive/231001/02-packagingFktrigger.sql rename to db/changes/234001/02-packagingFktrigger.sql diff --git a/db/changes/234001/03-packagingFkProc.sql b/db/changes/234001/03-packagingFkProc.sql new file mode 100644 index 000000000..4876c270e --- /dev/null +++ b/db/changes/234001/03-packagingFkProc.sql @@ -0,0 +1,1381 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`travelVolume`(vTravelFk INT) +BEGIN + + SELECT w1.name AS ORI, + w2.name AS DES, + tr.shipped shipment, + tr.landed landing, + a.name Agencia, + s.name Proveedor, + e.id Id_Entrada, + e.invoiceNumber Referencia, + CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) * + vn.item_getVolume(b.itemFk ,b.packagingFk)) / vc.trolleyM3 / 1000000 ,1) AS DECIMAL(10,2)) AS CC, + CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) * + vn.item_getVolume(b.itemFk ,b.packagingFk)) / vc.palletM3 / 1000000,1) AS DECIMAL(10,2)) AS espais + FROM vn.buy b + JOIN vn.entry e ON e.id = b.entryFk + JOIN vn.supplier s ON s.id = e.supplierFk + JOIN vn.travel tr ON tr.id = e.travelFk + JOIN vn.agencyMode a ON a.id = tr.agencyModeFk + JOIN vn.warehouse w1 ON w1.id = tr.warehouseInFk + JOIN vn.warehouse w2 ON w2.id = tr.warehouseOutFk + JOIN vn.volumeConfig vc + JOIN vn.item i ON i.id = b.itemFk + JOIN vn.itemType it ON it.id = i.typeFk + WHERE tr.id = vTravelFk; + +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`travelVolume_get`(vFromDated DATE, vToDated DATE, vWarehouseFk INT) +BEGIN + SELECT tr.landed Fecha, + a.name Agencia, + count(DISTINCT e.id) numEntradas, + FLOOR(sum(item_getVolume(b.itemFk, b.packagingFk) * b.stickers / 1000000 )) AS m3 + FROM vn.travel tr + JOIN vn.agencyMode a ON a.id = tr.agencyModeFk + JOIN vn.entry e ON e.travelFk = tr.id + JOIN vn.buy b ON b.entryFk = e.id + WHERE tr.landed BETWEEN vFromDated AND vToDated + AND e.isRaid = FALSE + AND tr.warehouseInFk = vWarehouseFk + GROUP BY tr.landed , a.name ; +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`travel_getEntriesMissingPackage`(vSelf INT) +BEGIN + DECLARE vpackageOrPackingNull INT; + DECLARE vTravelFk INT; + + SELECT travelfk INTO vTravelFk + FROM entry + WHERE id = vSelf; + + SELECT e.id entryFk + FROM travel t + JOIN entry e ON e.travelFk = t.id + JOIN buy b ON b.entryFk = e.id + WHERE t.id = vTravelFk + AND (b.packing IS NULL OR b.packagingFk IS NULL); +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketBoxesView`(IN vTicketFk INT) +BEGIN + + SELECT s.id, + s.itemFk, + s.concept, + floor(s.quantity / b.packing) as Cajas, + b.packing, + s.isPicked, + i.size + FROM ticket t + JOIN sale s ON s.ticketFk = t.id + JOIN item i ON i.id = s.itemFk + JOIN cache.last_buy lb on lb.warehouse_id = t.warehouseFk AND lb.item_id = s.itemFk + JOIN buy b on b.id = lb.buy_id + JOIN packaging p on p.id = b.packagingFk + WHERE s.quantity >= b.packing + AND t.id = vTicketFk + AND p.isBox + GROUP BY s.itemFk; + + +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`stockBuyedByWorker`( + vDated DATE, + vWorker INT +) +BEGIN +/** + * Inserta el volumen de compra de un comprador + * en stockBuyed de acuerdo con la fecha. + * + * @param vDated Fecha de compra + * @param vWorker Id de trabajador + */ + CREATE OR REPLACE TEMPORARY TABLE tStockBuyed + (INDEX (userFk)) + ENGINE = MEMORY + SELECT requested, reserved, userFk + FROM stockBuyed + WHERE dated = vDated + AND userFk = vWorker; + + DELETE FROM stockBuyed + WHERE dated = vDated + AND userFk = vWorker; + + CALL stockTraslation(vDated); + + INSERT INTO stockBuyed(userFk, buyed, `dated`, reserved, requested, description) + SELECT it.workerFk, + SUM((ti.quantity / b.packing) * buy_getVolume(b.id)) / vc.palletM3 / 1000000, + vDated, + sb.reserved, + sb.requested, + u.name + FROM itemType it + JOIN item i ON i.typeFk = it.id + LEFT JOIN tmp.item ti ON ti.itemFk = i.id + JOIN itemCategory ic ON ic.id = it.categoryFk + JOIN warehouse wh ON wh.code = 'VNH' + JOIN tmp.buyUltimate bu ON bu.itemFk = i.id + AND bu.warehouseFk = wh.id + JOIN buy b ON b.id = bu.buyFk + JOIN volumeConfig vc + JOIN account.`user` u ON u.id = it.workerFk + LEFT JOIN tStockBuyed sb ON sb.userFk = it.workerFk + WHERE ic.display + AND it.workerFk = vWorker; + + SELECT b.entryFk Id_Entrada, + i.id Id_Article, + i.name Article, + ti.quantity Cantidad, + (ac.conversionCoefficient * (ti.quantity / b.packing) * buy_getVolume(b.id)) + / (vc.trolleyM3 * 1000000) buyed, + b.packagingFk id_cubo, + b.packing + FROM tmp.item ti + JOIN item i ON i.id = ti.itemFk + JOIN itemType it ON i.typeFk = it.id + JOIN itemCategory ic ON ic.id = it.categoryFk + JOIN worker w ON w.id = it.workerFk + JOIN auctionConfig ac + JOIN tmp.buyUltimate bu ON bu.itemFk = i.id + AND bu.warehouseFk = ac.warehouseFk + JOIN buy b ON b.id = bu.buyFk + JOIN volumeConfig vc + WHERE ic.display + AND w.id = vWorker; + + DROP TEMPORARY TABLE tmp.buyUltimate, + tmp.item, + tStockBuyed; +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingMakeFromDate`(IN `vShelvingFk` VARCHAR(8), IN `vBarcode` VARCHAR(22), IN `vQuantity` INT, IN `vPackagingFk` VARCHAR(10), IN `vGrouping` INT, IN `vPacking` INT, IN `vWarehouseFk` INT, `vCreated` VARCHAR(22)) +BEGIN + + DECLARE vItemFk INT; + + SELECT vn.barcodeToItem(vBarcode) INTO vItemFk; + + SELECT itemFk INTO vItemFk + FROM vn.buy b + WHERE b.id = vItemFk; + + IF (SELECT COUNT(*) FROM vn.shelving WHERE code = vShelvingFk COLLATE utf8_unicode_ci) = 0 THEN + + INSERT IGNORE INTO vn.parking(`code`) VALUES(vShelvingFk); + INSERT INTO vn.shelving(`code`, parkingFk) + SELECT vShelvingFk, id + FROM vn.parking + WHERE `code` = vShelvingFk COLLATE utf8_unicode_ci; + + END IF; + + IF (SELECT COUNT(*) FROM vn.itemShelving + WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk + AND itemFk = vItemFk + AND packing = vPacking) = 1 THEN + + UPDATE vn.itemShelving + SET visible = visible+vQuantity, + created = vCreated + WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk + AND itemFk = vItemFk + AND packing = vPacking; + + ELSE + CALL cache.last_buy_refresh(FALSE); + INSERT INTO itemShelving( itemFk, + shelvingFk, + visible, + created, + `grouping`, + packing, + packagingFk) + SELECT vItemFk, + vShelvingFk, + vQuantity, + vCreated, + IF(vGrouping = 0, IFNULL(b.packing, vPacking), vGrouping) `grouping`, + IF(vPacking = 0, b.packing, vPacking) packing, + IF(vPackagingFk = '', b.packagingFk, vPackagingFk) packaging + FROM vn.item i + LEFT JOIN cache.last_buy lb ON i.id = lb.item_id AND lb.warehouse_id = vWarehouseFk + LEFT JOIN vn.buy b ON b.id = lb.buy_id + WHERE i.id = vItemFk; + END IF; + +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelving_add`(IN vShelvingFk VARCHAR(8), IN vBarcode VARCHAR(22), IN vQuantity INT, IN vPackagingFk VARCHAR(10), IN vGrouping INT, IN vPacking INT, IN vWarehouseFk INT) +BEGIN + + +/** + * Añade registro o lo actualiza si ya existe. + * + * @param vShelvingFk matrícula del carro + * @param vBarcode el id del registro + * @param vQuantity indica la cantidad del producto + * @param vPackagingFk el packaging del producto en itemShelving, NULL para coger el de la ultima compra + * @param vGrouping el grouping del producto en itemShelving, NULL para coger el de la ultima compra + * @param vPacking el packing del producto, NULL para coger el de la ultima compra + * @param vWarehouseFk indica el sector + * + **/ + + DECLARE vItemFk INT; + + SELECT barcodeToItem(vBarcode) INTO vItemFk; + + IF (SELECT COUNT(*) FROM shelving WHERE code = vShelvingFk COLLATE utf8_unicode_ci) = 0 THEN + + INSERT IGNORE INTO parking(code) VALUES(vShelvingFk); + INSERT INTO shelving(code, parkingFk) + SELECT vShelvingFk, id + FROM parking + WHERE `code` = vShelvingFk COLLATE utf8_unicode_ci; + + END IF; + + IF (SELECT COUNT(*) FROM itemShelving + WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk + AND itemFk = vItemFk + AND packing = vPacking) = 1 THEN + + UPDATE itemShelving + SET visible = visible+vQuantity + WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk AND itemFk = vItemFk AND packing = vPacking; + + ELSE + CALL cache.last_buy_refresh(FALSE); + INSERT INTO itemShelving( itemFk, + shelvingFk, + visible, + grouping, + packing, + packagingFk) + + SELECT vItemFk, + vShelvingFk, + vQuantity, + IFNULL(vGrouping, b.grouping), + IFNULL(vPacking, b.packing), + IFNULL(vPackagingFk, b.packagingFk) + FROM item i + LEFT JOIN cache.last_buy lb ON i.id = lb.item_id AND lb.warehouse_id = vWarehouseFk + LEFT JOIN buy b ON b.id = lb.buy_id + WHERE i.id = vItemFk; + END IF; +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemFreight_Show`(vItemFk INT, vWarehouseFk INT) +BEGIN + + SELECT cm3 Volumen_Entrada, + cm3delivery Volumen_Salida, + p.volume Volumen_del_embalaje, + p.width Ancho_del_embalaje, + p.`depth` Largo_del_embalaje, + b.packagingFk , + IFNULL(p.height, i.`size`) + 10 Altura, + b.packing Packing_Entrada, + i.packingOut Packing_Salida, + i.id itemFk, + b.id buyFk, + b.entryFk, + w.name warehouseFk + FROM vn.itemCost ic + JOIN vn.item i ON i.id = ic.itemFk + LEFT JOIN cache.last_buy lb ON lb.item_id = ic.itemFk AND lb.warehouse_id = ic.warehouseFk + LEFT JOIN vn.buy b ON b.id = lb.buy_id + LEFT JOIN vn.packaging p ON p.id = b.packagingFk + LEFT JOIN vn.warehouse w ON w.id = ic.warehouseFk + WHERE ic.itemFk = vItemFk + AND ic.warehouseFk = vWarehouseFk; +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`inventoryMake`(vDate DATE, vWh INT) +proc: BEGIN +/** +* Recalcula los inventarios de todos los almacenes, si vWh = 0 +* +* @param vDate Fecha de los nuevos inventarios +* @param vWh almacen al cual hacer el inventario +*/ + + DECLARE vDone BOOL; + DECLARE vEntryFk INT; + DECLARE vTravelFk INT; + DECLARE vDateLastInventory DATE; + DECLARE vDateYesterday DATETIME DEFAULT vDate - INTERVAL 1 SECOND; + DECLARE vWarehouseOutFkInventory INT; + DECLARE vInventorySupplierFk INT; + DECLARE vAgencyModeFkInventory INT; + + DECLARE cWarehouses CURSOR FOR + SELECT id + FROM warehouse + WHERE isInventory + AND vWh IN (0,id); + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + OPEN cWarehouses; + SET @isModeInventory := TRUE; + l: LOOP + + SET vDone = FALSE; + FETCH cWarehouses INTO vWh; + + IF vDone THEN + LEAVE l; + END IF; + + SELECT w.id INTO vWarehouseOutFkInventory + FROM warehouse w + WHERE w.code = 'inv'; + + SELECT inventorySupplierFk INTO vInventorySupplierFk + FROM entryConfig; + + SELECT am.id INTO vAgencyModeFkInventory + FROM agencyMode am + where code = 'inv'; + + SELECT MAX(landed) INTO vDateLastInventory + FROM travel tr + JOIN entry e ON e.travelFk = tr.id + JOIN buy b ON b.entryFk = e.id + WHERE warehouseOutFk = vWarehouseOutFkInventory + AND landed < vDate + AND e.supplierFk = vInventorySupplierFk + AND warehouseInFk = vWh + AND NOT isRaid; + + IF vDateLastInventory IS NULL THEN + SELECT inventoried INTO vDateLastInventory FROM config; + END IF; + + -- Generamos travel, si no existe. + SET vTravelFK = 0; + + SELECT id INTO vTravelFk + FROM travel + WHERE warehouseOutFk = vWarehouseOutFkInventory + AND warehouseInFk = vWh + AND landed = vDate + AND agencyModeFk = vAgencyModeFkInventory + AND ref = 'inventario' + LIMIT 1; + + IF NOT vTravelFK THEN + + INSERT INTO travel SET + warehouseOutFk = vWarehouseOutFkInventory, + warehouseInFk = vWh, + shipped = vDate, + landed = vDate, + agencyModeFk = vAgencyModeFkInventory, + ref = 'inventario', + isDelivered = TRUE, + isReceived = TRUE; + + SELECT LAST_INSERT_ID() INTO vTravelFk; + + END IF; + + -- Generamos entrada si no existe, o la vaciamos. + SET vEntryFk = 0; + + SELECT id INTO vEntryFk + FROM entry + WHERE supplierFk = vInventorySupplierFk + AND travelFk = vTravelFk; + + IF NOT vEntryFk THEN + + INSERT INTO entry SET + supplierFk = vInventorySupplierFk, + isConfirmed = TRUE, + isOrdered = TRUE, + travelFk = vTravelFk; + + SELECT LAST_INSERT_ID() INTO vEntryFk; + + ELSE + + DELETE FROM buy WHERE entryFk = vEntryFk; + + END IF; + + -- Preparamos tabla auxilar + CREATE OR REPLACE TEMPORARY TABLE tmp.inventory ( + itemFk INT(11) NOT NULL PRIMARY KEY, + quantity int(11) DEFAULT '0', + buyingValue decimal(10,3) DEFAULT '0.000', + freightValue decimal(10,3) DEFAULT '0.000', + packing int(11) DEFAULT '0', + `grouping` smallint(5) unsigned NOT NULL DEFAULT '1', + groupingMode tinyint(4) NOT NULL DEFAULT 0 , + comissionValue decimal(10,3) DEFAULT '0.000', + packageValue decimal(10,3) DEFAULT '0.000', + packageFk varchar(10) COLLATE utf8_unicode_ci DEFAULT '--', + price1 decimal(10,2) DEFAULT '0.00', + price2 decimal(10,2) DEFAULT '0.00', + price3 decimal(10,2) DEFAULT '0.00', + minPrice decimal(10,2) DEFAULT '0.00', + producer varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + INDEX (itemFK)) ENGINE = MEMORY; + + -- Compras + INSERT INTO tmp.inventory(itemFk,quantity) + SELECT b.itemFk, SUM(b.quantity) + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel tr ON tr.id = e.travelFk + WHERE tr.warehouseInFk = vWh + AND tr.landed BETWEEN vDateLastInventory + AND vDateYesterday + AND NOT isRaid + GROUP BY b.itemFk; + SELECT vDateLastInventory , vDateYesterday; + + -- Traslados + INSERT INTO tmp.inventory(itemFk, quantity) + SELECT itemFk, quantityOut + FROM ( + SELECT b.itemFk,- SUM(b.quantity) quantityOut + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel tr ON tr.id = e.travelFk + WHERE tr.warehouseOutFk = vWh + AND tr.shipped BETWEEN vDateLastInventory + AND vDateYesterday + AND NOT isRaid + GROUP BY b.itemFk + ) sub + ON DUPLICATE KEY UPDATE quantity = IFNULL(quantity, 0) + sub.quantityOut; + + -- Ventas + INSERT INTO tmp.inventory(itemFk,quantity) + SELECT itemFk, saleOut + FROM ( + SELECT s.itemFk, - SUM(s.quantity) saleOut + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + WHERE t.warehouseFk = vWh + AND t.shipped BETWEEN vDateLastInventory AND vDateYesterday + GROUP BY s.itemFk + ) sub + ON DUPLICATE KEY UPDATE quantity = IFNULL(quantity,0) + sub.saleOut; + + -- Actualiza valores de la ultima compra + UPDATE tmp.inventory inv + JOIN cache.last_buy lb ON lb.item_id = inv.itemFk AND lb.warehouse_id = vWh + JOIN buy b ON b.id = lb.buy_id + JOIN item i ON i.id = b.itemFk + LEFT JOIN producer p ON p.id = i.producerFk + SET inv.buyingValue = b.buyingValue, + inv.freightValue = b.freightValue, + inv.packing = b.packing, + inv.`grouping`= b.`grouping`, + inv.groupingMode = b.groupingMode, + inv.comissionValue = b.comissionValue, + inv.packageValue = b.packageValue, + inv.packageFk = b.packagingFk, + inv.price1 = b.price1, + inv.price2 = b.price2, + inv.price3 = b.price3, + inv.minPrice = b.minPrice, + inv.producer = p.name; + + INSERT INTO buy( itemFk, + quantity, + buyingValue, + freightValue, + packing, + `grouping`, + groupingMode, + comissionValue, + packageValue, + packagingFk, + price1, + price2, + price3, + minPrice, + entryFk) + SELECT itemFk, + GREATEST(quantity, 0), + buyingValue, + freightValue, + packing, + `grouping`, + groupingMode, + comissionValue, + packageValue, + packagingFk, + price1, + price2, + price3, + minPrice, + vEntryFk + FROM tmp.inventory; + + SELECT vWh, COUNT(*), util.VN_NOW() FROM tmp.inventory; + + -- Actualizamos el campo lastUsed de item + UPDATE item i + JOIN tmp.inventory i2 ON i2.itemFk = i.id + SET i.lastUsed = NOW() + WHERE i2.quantity; + + -- DROP TEMPORARY TABLE tmp.inventory; + + END LOOP; + + CLOSE cWarehouses; + + UPDATE config SET inventoried = vDate; + SET @isModeInventory := FALSE; + + DROP TEMPORARY TABLE IF EXISTS tmp.entryToDelete; + CREATE TEMPORARY TABLE tmp.entryToDelete + (INDEX(entryId) USING BTREE) ENGINE = MEMORY + SELECT e.id as entryId, + t.id as travelId + FROM travel t + JOIN `entry` e ON e.travelFk = t.id + WHERE e.supplierFk = vInventorySupplierFk + AND t.shipped <= util.VN_CURDATE() - INTERVAL 12 DAY + AND (DAY(t.shipped) <> 1 OR shipped < util.VN_CURDATE() - INTERVAL 12 DAY); + + DELETE e + FROM `entry` e + JOIN tmp.entryToDelete tmp ON tmp.entryId = e.id; + + DELETE IGNORE t + FROM travel t + JOIN tmp.entryToDelete tmp ON tmp.travelId = t.id; +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`inventory_repair`() +BEGIN + + DROP TEMPORARY TABLE IF EXISTS tmp.lastEntry; + CREATE TEMPORARY TABLE tmp.lastEntry + (PRIMARY KEY (buyFk)) + SELECT + i.id AS itemFk, + w.id AS warehouseFk, + w.name AS warehouse, + tr.landed, + b.id AS buyFk, + b.entryFk, + b.isIgnored, + b.price2, + b.price3, + b.stickers, + b.packing, + b.grouping, + b.groupingMode, + b.weight, + i.stems, + b.quantity, + b.buyingValue, + b.packagingFk , + s.id AS supplierFk, + s.name AS supplier + FROM itemType it + RIGHT JOIN (entry e + LEFT JOIN supplier s ON s.id = e.supplierFk + RIGHT JOIN buy b ON b.entryFk = e.id + LEFT JOIN item i ON i.id = b.itemFk + LEFT JOIN ink ON ink.id = i.inkFk + LEFT JOIN travel tr ON tr.id = e.travelFk + LEFT JOIN warehouse w ON w.id = tr.warehouseInFk + LEFT JOIN origin o ON o.id = i.originFk + ) ON it.id = i.typeFk + LEFT JOIN edi.ekt ek ON b.ektFk = ek.id + WHERE (b.packagingFk = "--" OR b.price2 = 0 OR b.packing = 0 OR b.buyingValue = 0) AND tr.landed > util.firstDayOfMonth(TIMESTAMPADD(MONTH,-1,util.VN_CURDATE())) AND s.name = 'INVENTARIO'; + + DROP TEMPORARY TABLE IF EXISTS tmp.lastEntryOk; + CREATE TEMPORARY TABLE tmp.lastEntryOk + (PRIMARY KEY (buyFk)) + SELECT + i.id AS itemFk, + w.id AS warehouseFk, + w.name AS warehouse, + tr.landed, + b.id AS buyFk, + b.entryFk, + b.isIgnored, + b.price2, + b.price3, + b.stickers, + b.packing, + b.grouping, + b.groupingMode, + b.weight, + i.stems, + b.quantity, + b.buyingValue, + b.packagingFk, + s.id AS supplierFk, + s.name AS supplier + FROM itemType it + RIGHT JOIN (entry e + LEFT JOIN supplier s ON s.id = e.supplierFk + RIGHT JOIN buy b ON b.entryFk = e.id + LEFT JOIN item i ON i.id = b.itemFk + LEFT JOIN ink ON ink.id = i.inkFk + LEFT JOIN travel tr ON tr.id = e.travelFk + LEFT JOIN warehouse w ON w.id = tr.warehouseInFk + LEFT JOIN origin o ON o.id = i.originFk + ) ON it.id = i.typeFk + LEFT JOIN edi.ekt ek ON b.ektFk = ek.id + WHERE b.packagingFk != "--" AND b.price2 != 0 AND b.packing != 0 AND b.buyingValue > 0 AND tr.landed > util.firstDayOfMonth(TIMESTAMPADD(MONTH,-2,util.VN_CURDATE())) + ORDER BY tr.landed DESC; + + DROP TEMPORARY TABLE IF EXISTS tmp.lastEntryOkGroup; + CREATE TEMPORARY TABLE tmp.lastEntryOkGroup + (INDEX (warehouseFk,itemFk)) + SELECT * + FROM tmp.lastEntryOk tmp + GROUP BY tmp.itemFk,tmp.warehouseFk; + + UPDATE buy b + JOIN tmp.lastEntry lt ON lt.buyFk = b.id + JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk + SET b.packagingFk = eo.packagingFk WHERE b.packagingFk = "--"; + + UPDATE buy b + JOIN tmp.lastEntry lt ON lt.buyFk = b.id + JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk + SET b.price2 = eo.price2 WHERE b.price2 = 0 ; + + UPDATE buy b + JOIN tmp.lastEntry lt ON lt.buyFk = b.id + JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk + SET b.packing = eo.packing WHERE b.packing = 0; + + UPDATE buy b + JOIN tmp.lastEntry lt ON lt.buyFk = b.id + JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk + SET b.buyingValue = eo.buyingValue WHERE b.buyingValue = 0; + + DROP TEMPORARY TABLE tmp.lastEntry; + DROP TEMPORARY TABLE tmp.lastEntryOk; + DROP TEMPORARY TABLE tmp.lastEntryOkGroup; +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buy_afterUpsert`(vSelf INT) +BEGIN +/** + * Triggered actions when a buy is updated or inserted. + * + * @param vSelf The buy reference + */ + DECLARE vEntryFk INT; + DECLARE vItemFk INT; + DECLARE vPackingOut DECIMAL(10,2); + DECLARE vWarehouse INT; + DECLARE vStandardFlowerBox INT; + DECLARE vWarehouseOut INT; + DECLARE vIsMerchandise BOOL; + DECLARE vIsFeedStock BOOL; + DECLARE vWeight DECIMAL(10,2); + DECLARE vPacking INT; + + SELECT b.entryFk, + b.itemFk, + i.packingOut, + ic.merchandise, + vc.standardFlowerBox, + b.weight, + b.packing + INTO + vEntryFk, + vItemFk, + vPackingOut, + vIsMerchandise, + vStandardFlowerBox, + vWeight, + vPacking + FROM buy b + LEFT JOIN item i ON i.id = b.itemFk + LEFT JOIN itemType it ON it.id = i.typeFk + LEFT JOIN itemCategory ic ON ic.id = it.categoryFk + LEFT JOIN packaging p ON p.id = b.packagingFk AND NOT p.isBox + JOIN volumeConfig vc ON TRUE + WHERE b.id = vSelf; + + SELECT t.warehouseInFk, t.warehouseOutFk + INTO vWarehouse, vWarehouseOut + FROM entry e + JOIN travel t ON t.id = e.travelFk + WHERE e.id = vEntryFk; + + IF vIsMerchandise THEN + + REPLACE itemCost SET + itemFk = vItemFk, + warehouseFk = vWarehouse, + cm3 = buy_getUnitVolume(vSelf), + cm3Delivery = IFNULL((vStandardFlowerBox * 1000) / vPackingOut, buy_getUnitVolume(vSelf)); + + IF vWeight AND vPacking THEN + UPDATE itemCost SET + grams = vWeight * 1000 / vPacking + WHERE itemFk = vItemFk + AND warehouseFk = vWarehouse; + END IF; + END IF; + + SELECT isFeedStock INTO vIsFeedStock + FROM warehouse WHERE id = vWarehouseOut; + + IF vIsFeedStock THEN + INSERT IGNORE INTO producer(`name`) + SELECT es.company_name + FROM buy b + JOIN edi.ekt be ON be.id = b.ektFk + JOIN edi.supplier es ON es.supplier_id = be.pro + WHERE b.id = vSelf; + + END IF; + +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`buy_getUnitVolume`(vSelf INT) + RETURNS int(11) + DETERMINISTIC +BEGIN +/** + * Calculates the unit volume occupied by a buy. + * + * @param vSelf The buy id + * @return The unit volume in cubic centimeters + */ + DECLARE vItem INT; + DECLARE vPackaging VARCHAR(10); + DECLARE vPacking INT; + + SELECT itemFk, packagingFk, packing + INTO vItem, vPackaging, vPacking + FROM buy + WHERE id = vSelf; + + RETURN IFNULL(ROUND(item_getVolume(vItem, vPackaging) / vPacking), 0); +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buy_recalcPrices`() +BEGIN +/** + * Recalcula los precios para las compras insertadas en tmp.buyRecalc + * + * @param tmp.buyRecalc (id) + */ + DECLARE vLanded DATE; + DECLARE vWarehouseFk INT; + DECLARE vHasNotPrice BOOL; + DECLARE vBuyingValue DECIMAL(10,3); + DECLARE vPackagingFk VARCHAR(10); + DECLARE vIsWarehouseFloramondo BOOL; + + SELECT t.landed, t.warehouseInFk, (w.`name` = 'Floramondo') + INTO vLanded, vWarehouseFk, vIsWarehouseFloramondo + FROM tmp.buyRecalc br + JOIN buy b ON b.id = br.id + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseInFk + LIMIT 1; + + CALL rate_getPrices(vLanded, vWarehouseFk); + + UPDATE buy b + JOIN tmp.buyRecalc br ON br.id = b.id AND (@buyId := b.id) + LEFT JOIN packaging p ON p.id = b.packagingFk + JOIN item i ON i.id = b.itemFk + JOIN entry e ON e.id = b.entryFk + JOIN itemType it ON it.id = i.typeFk + JOIN travel tr ON tr.id = e.travelFk + JOIN agencyMode am ON am.id = tr.agencyModeFk + JOIN tmp.rate r + JOIN volumeConfig vc + SET b.freightValue = @PF:= IFNULL(((am.m3 * @m3:= item_getVolume(b.itemFk, b.packagingFk) / 1000000) + / b.packing) * IF(am.hasWeightVolumetric, GREATEST(b.weight / @m3 / vc.aerealVolumetricDensity, 1), 1), 0), + b.comissionValue = @CF:= ROUND(IFNULL(e.commission * b.buyingValue / 100, 0), 3), + b.packageValue = @EF:= IF(vIsWarehouseFloramondo, 0, IFNULL(ROUND(IF(p.isPackageReturnable, p.returnCost / b.packing , p.`value` / b.packing), 3),0)), + b.price3 = @t3:= IF(r.rate3 = 0, b.buyingValue,ROUND((b.buyingValue + @CF + @EF + @PF) / ((100 - r.rate3 - it.promo ) /100) ,2)), -- He añadido que el coste sea igual a tarifa3 si t3 = 0 + b.price2 = @t2:= round(@t3 * (1 + ((r.rate2 - r.rate3)/100)),2), + b.price2 = @t2:= IF(@t2 <= @t3,@t3 , @t2); + + SELECT (b.buyingValue = b.price2), b.buyingValue, b.packagingFk + INTO vHasNotPrice, vBuyingValue, vPackagingFk + FROM vn.buy b + WHERE b.id = @buyId AND b.buyingValue <> 0.01; + + DROP TEMPORARY TABLE tmp.rate; +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `edi`.`ekt_load`(IN `vSelf` INT) +proc:BEGIN + + DECLARE vRef INT; + DECLARE vBuy INT; + DECLARE vItem INT; + DECLARE vQty INT; + DECLARE vPackage INT; + DECLARE vPutOrderFk INT; + DECLARE vIsLot BOOLEAN; + DECLARE vForceToPacking INT DEFAULT 2; + DECLARE vEntryFk INT; + DECLARE vHasToChangePackagingFk BOOLEAN; + DECLARE vIsFloramondoDirect BOOLEAN; + DECLARE vTicketFk INT; + DECLARE vHasItemGroup BOOL; + DECLARE vDescription VARCHAR(255); + DECLARE vSaleFk INT; + + -- Carga los datos necesarios del EKT + + SELECT e.ref, qty, package, putOrderFk MOD 1000000, i2.id , NOT ISNULL(eea.addressFk), NOT ISNULL(igto.group_code), + CONCAT(e.`ref`, ' ', e.item, ' ', e.sub, ' EktFk:', e.id) + INTO vRef, vQty, vPackage, vPutOrderFk, vItem, vIsFloramondoDirect, vHasItemGroup, vDescription + FROM edi.ekt e + LEFT JOIN edi.item i ON e.ref = i.id + LEFT JOIN edi.putOrder po ON po.id = e.putOrderFk + LEFT JOIN vn.item i2 ON i2.supplyResponseFk = po.supplyResponseID + LEFT JOIN vn.ektEntryAssign eea ON eea.sub = e.sub + LEFT JOIN edi.item_groupToOffer igto ON igto.group_code = i.group_id + WHERE e.id = vSelf + LIMIT 1; + + IF NOT vHasItemGroup THEN + + CALL vn.mail_insert('logistica@verdnatura.es', 'nocontestar@verdnatura.es', 'Nuevo grupo en Floramondo', vDescription); + + CALL vn.mail_insert('pako@verdnatura.es', 'nocontestar@verdnatura.es', CONCAT('Nuevo grupo en Floramondo: ', vDescription), vDescription); + + LEAVE proc; + + END IF; + + -- Asigna la entrada + SELECT vn.ekt_getEntry(vSelf) INTO vEntryFk; + + -- Inserta el cubo si no existe + + IF vPackage = 800 THEN + + SET vHasToChangePackagingFk = TRUE; + + IF vItem THEN + + SELECT vn.item_getPackage(vItem) INTO vPackage ; + + ELSE + + SET vPackage = 8000 + vQty; + + INSERT IGNORE INTO vn.packaging(id, width, `depth`) + SELECT vPackage, vc.ccLength / vQty, vc.ccWidth + FROM vn.volumeConfig vc; + + END IF; + + ELSE + + INSERT IGNORE INTO vn2008.Cubos (Id_Cubo, X, Y, Z) + SELECT bucket_id, ROUND(x_size/10), ROUND(y_size/10), ROUND(z_size/10) + FROM bucket WHERE bucket_id = vPackage; + + IF ROW_COUNT() > 0 + THEN + INSERT INTO vn2008.mail SET + `subject` = 'Cubo añadido', + `text` = CONCAT('Se ha añadido el cubo: ', vPackage), + `to` = 'ekt@verdnatura.es'; + END IF; + END IF; + + -- Si es una compra de Logiflora obtiene el articulo + IF vPutOrderFk THEN + + SELECT i.id INTO vItem + FROM edi.putOrder po + JOIN vn.item i ON i.supplyResponseFk = po.supplyResponseID + WHERE po.id = vPutOrderFk + LIMIT 1; + + END IF; + + INSERT IGNORE INTO item_track SET + item_id = vRef; + + IF IFNULL(vItem,0) = 0 THEN + + -- Intenta obtener el artículo en base a los atributos holandeses + + SELECT b.id, IFNULL(b.itemOriginalFk ,b.itemFk) INTO vBuy, vItem + FROM edi.ekt e + JOIN edi.item_track t ON t.item_id = e.ref + LEFT JOIN edi.ekt l ON l.ref = e.ref + LEFT JOIN vn.buy b ON b.ektFk = l.id + LEFT JOIN vn.item i ON i.id = b.itemFk + JOIN vn2008.config cfg + WHERE e.id = vSelf + AND l.id != vSelf + AND b.itemFk != cfg.generic_item + AND IF(t.s1, l.s1 = e.s1, TRUE) + AND IF(t.s2, l.s2 = e.s2, TRUE) + AND IF(t.s3, l.s3 = e.s3, TRUE) + AND IF(t.s4, l.s4 = e.s4, TRUE) + AND IF(t.s5, l.s5 = e.s5, TRUE) + AND IF(t.s6, l.s6 = e.s6, TRUE) + AND IF(t.pac, l.pac = e.pac, TRUE) + AND IF(t.cat, l.cat = e.cat, TRUE) + AND IF(t.ori, l.ori = e.ori, TRUE) + AND IF(t.pro, l.pro = e.pro, TRUE) + AND IF(t.package, l.package = e.package, TRUE) + AND IF(t.item, l.item = e.item, TRUE) + AND i.isFloramondo = vIsFloramondoDirect + ORDER BY l.now DESC, b.id ASC + LIMIT 1; + + END IF; + + -- Si no encuentra el articulo lo crea en el caso de las compras directas en Floramondo + IF ISNULL(vItem) AND vIsFloramondoDirect THEN + + CALL edi.item_getNewByEkt(vSelf, vItem); + + END IF; + + INSERT INTO vn.buy + ( + entryFk + ,ektFk + ,buyingValue + ,itemFk + ,stickers + ,packing + ,`grouping` + ,quantity + ,groupingMode + ,packagingFk + ,weight + ) + SELECT + vEntryFk + ,vSelf + ,(@t := IF(i.stems, i.stems, 1)) * e.pri / IFNULL(i.stemMultiplier, 1) buyingValue + ,IFNULL(vItem, cfg.generic_item) itemFk + ,e.qty stickers + ,@pac := IFNULL(i.stemMultiplier, 1) * e.pac / @t packing + ,IFNULL(b.`grouping`, e.pac) + ,@pac * e.qty + ,vForceToPacking + ,IF(vHasToChangePackagingFk OR ISNULL(b.packagingFk), vPackage, b.packagingFk) + ,(IFNULL(i.weightByPiece,0) * @pac)/1000 + FROM edi.ekt e + LEFT JOIN vn.buy b ON b.id = vBuy + LEFT JOIN vn.item i ON i.id = b.itemFk + LEFT JOIN vn.supplier s ON e.pro = s.id + JOIN vn2008.config cfg + WHERE e.id = vSelf + LIMIT 1; + + DROP TEMPORARY TABLE IF EXISTS tmp.buyRecalc; + + CREATE TEMPORARY TABLE tmp.buyRecalc + SELECT buy.id + FROM vn.buy + WHERE ektFk = vSelf; + + CALL vn.buy_recalcPrices(); + + -- Si es una compra de Logiflora hay que informar la tabla vn.saleBuy + IF vPutOrderFk THEN + + REPLACE vn.saleBuy(saleFk, buyFk, workerFk) + SELECT po.saleFk, b.id, account.myUser_getId() + FROM edi.putOrder po + JOIN vn.buy b ON b.ektFk = vSelf + WHERE po.id = vPutOrderFk; + + END IF; + -- Si es una compra directa en Floramondo hay que añadirlo al ticket + + IF vIsFloramondoDirect THEN + + SELECT t.id INTO vTicketFk + FROM vn.ticket t + JOIN vn.ektEntryAssign eea + ON eea.addressFk = t.addressFk + AND t.warehouseFk = eea.warehouseInFk + JOIN edi.ekt e + ON e.sub = eea.sub + AND e.id = vSelf + WHERE e.fec = t.shipped + LIMIT 1; + + IF ISNULL(vTicketFk) THEN + + INSERT INTO vn.ticket ( + clientFk, + shipped, + addressFk, + agencyModeFk, + nickname, + warehouseFk, + companyFk, + landed, + zoneFk, + zonePrice, + zoneBonus + ) + SELECT + a.clientFk, + e.fec, + a.id, + a.agencyModeFk, + a.nickname, + eea.warehouseInFk, + c.id, + e.fec, + z.id, + z.price, + z.bonus + FROM edi.ekt e + JOIN vn.ektEntryAssign eea ON eea.sub = e.sub + JOIN vn.address a ON a.id = eea.addressFk + JOIN vn.company c ON c.code = 'VNL' + JOIN vn.`zone` z ON z.code = 'FLORAMONDO' + WHERE e.id = vSelf + LIMIT 1; + + SET vTicketFk = LAST_INSERT_ID(); + + INSERT INTO vn.ticketLog + SET originFk = vTicketFk, + userFk = account.myUser_getId(), + `action` = 'insert', + description = CONCAT('EktLoad ha creado el ticket:', ' ', vTicketFk); + + END IF; + + INSERT INTO vn.sale (itemFk, ticketFk, concept, quantity, price) + SELECT vItem, vTicketFk, e.item, e.qty * e.pac, e.pri * ( 1 + fhc.floramondoMargin ) + FROM edi.ekt e + JOIN edi.floraHollandConfig fhc + WHERE e.id = vSelf; + + SELECT LAST_INSERT_ID() INTO vSaleFk; + + REPLACE vn.saleBuy(saleFk, buyFk, workerFk) + SELECT vSaleFk, b.id, account.myUser_getId() + FROM vn.buy b + WHERE b.ektFk = vSelf; + + INSERT INTO vn.saleComponent(saleFk, componentFk, value) + SELECT vSaleFk, c.id, e.pri + FROM edi.ekt e + JOIN vn.component c ON c.code = 'purchaseValue' + WHERE e.id = vSelf; + + INSERT INTO vn.saleComponent(saleFk, componentFk, value) + SELECT vSaleFk, c.id, e.pri * fhc.floramondoMargin + FROM edi.ekt e + JOIN edi.floraHollandConfig fhc + JOIN vn.component c ON c.code = 'margin' + WHERE e.id = vSelf; + END IF; + DROP TEMPORARY TABLE tmp.buyRecalc; +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `hedera`.`item_getVisible`( + vWarehouse TINYINT, + vDate DATE, + vType INT, + vPrefix VARCHAR(255)) +BEGIN + +/** + * Gets visible items of the specified type at specified date. + * + * @param vWarehouse The warehouse id + * @param vDate The visible date + * @param vType The type id + * @param vPrefix The article prefix to filter or %NULL for all + * @return tmp.itemVisible Visible items + */ + DECLARE vPrefixLen SMALLINT; + DECLARE vFilter VARCHAR(255) DEFAULT NULL; + DECLARE vDateInv DATE DEFAULT vn2008.date_inv(); + DECLARE EXIT HANDLER FOR 1114 + BEGIN + GET DIAGNOSTICS CONDITION 1 + @message = MESSAGE_TEXT; + CALL vn.mail_insert( + 'cau@verdnatura.es', + NULL, + CONCAT('hedera.item_getVisible error: ', @message), + CONCAT( + 'warehouse: ', IFNULL(vWarehouse, ''), + ', Fecha:', IFNULL(vDate, ''), + ', tipo: ', IFNULL(vType,''), + ', prefijo: ', IFNULL(vPrefix,''))); + RESIGNAL; + END; + SET vPrefixLen = IFNULL(LENGTH(vPrefix), 0) + 1; + + IF vPrefixLen > 1 THEN + SET vFilter = CONCAT(vPrefix, '%'); + END IF; + + DROP TEMPORARY TABLE IF EXISTS `filter`; + CREATE TEMPORARY TABLE `filter` + (INDEX (itemFk)) + ENGINE = MEMORY + SELECT id itemFk FROM vn.item + WHERE typeFk = vType + AND (vFilter IS NULL OR `name` LIKE vFilter); + + DROP TEMPORARY TABLE IF EXISTS currentStock; + CREATE TEMPORARY TABLE currentStock + (INDEX (itemFk)) + ENGINE = MEMORY + SELECT itemFk, SUM(quantity) quantity + FROM ( + SELECT b.itemFk, b.quantity + FROM vn.buy b + JOIN vn.entry e ON e.id = b.entryFk + JOIN vn.travel t ON t.id = e.travelFk + WHERE t.landed BETWEEN vDateInv AND vDate + AND t.warehouseInFk = vWarehouse + AND NOT e.isRaid + UNION ALL + SELECT b.itemFk, -b.quantity + FROM vn.buy b + JOIN vn.entry e ON e.id = b.entryFk + JOIN vn.travel t ON t.id = e.travelFk + WHERE t.shipped BETWEEN vDateInv AND util.VN_CURDATE() + AND t.warehouseOutFk = vWarehouse + AND NOT e.isRaid + AND t.isDelivered + UNION ALL + SELECT m.itemFk, -m.quantity + FROM vn.sale m + JOIN vn.ticket t ON t.id = m.ticketFk + JOIN vn.ticketState s ON s.ticket = t.id + WHERE t.shipped BETWEEN vDateInv AND util.VN_CURDATE() + AND t.warehouseFk = vWarehouse + AND s.alertLevel = 3 + ) t + GROUP BY itemFk + HAVING quantity > 0; + + DROP TEMPORARY TABLE IF EXISTS tmp; + CREATE TEMPORARY TABLE tmp + (INDEX (itemFk)) + ENGINE = MEMORY + SELECT * + FROM ( + SELECT b.itemFk, b.packagingFk, b.packing + FROM vn.buy b + JOIN vn.entry e ON e.id = b.entryFk + JOIN vn.travel t ON t.id = e.travelFk + WHERE t.landed BETWEEN vDateInv AND vDate + AND NOT b.isIgnored + AND b.price2 >= 0 + AND b.packagingFk IS NOT NULL + ORDER BY t.warehouseInFk = vWarehouse DESC, t.landed DESC + LIMIT 10000000000000000000 + ) t GROUP BY itemFk; + + DROP TEMPORARY TABLE IF EXISTS tmp.itemVisible; + CREATE TEMPORARY TABLE tmp.itemVisible + ENGINE = MEMORY + SELECT i.id Id_Article, + SUBSTRING(i.`name`, vPrefixLen) Article, + t.packing, p.id Id_Cubo, + IF(p.depth > 0, p.depth, 0) depth, p.width, p.height, + CEIL(s.quantity / t.packing) etiquetas + FROM vn.item i + JOIN `filter` f ON f.itemFk = i.id + JOIN currentStock s ON s.itemFk = i.id + LEFT JOIN tmp t ON t.itemFk = i.id + LEFT JOIN vn.packaging p ON p.id = t.packagingFk + WHERE CEIL(s.quantity / t.packing) > 0 + -- FIXME: Column Cubos.box not included in view vn.packaging + /* AND p.box */; + + DROP TEMPORARY TABLE + `filter`, + currentStock, + tmp; +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buy_getVolume`() +BEGIN +/** + * Cálculo de volumen en líneas de compra + * @table tmp.buy(buyFk) + */ + SELECT t.name Temp, + CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) * + item_getVolume(b.itemFk, b.packagingFk)) / vc.trolleyM3 / 1000000 ,1) AS DECIMAL(10,2)) carros , + CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) * + item_getVolume(b.itemFk, b.packagingFk)) / vc.palletM3 / 1000000,1) AS DECIMAL(10,2)) espais + FROM buy b + JOIN tmp.buy tb ON tb.buyFk = b.id + JOIN volumeConfig vc + JOIN item i ON i.id = b.itemFk + JOIN itemType it ON it.id = i.typeFk + LEFT JOIN temperature t ON t.code = it.temperatureFk + GROUP BY Temp; +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`entry_checkPackaging`(vEntryFk INT) +BEGIN +/** + * Comprueba que los campos package y packaging no sean nulos + * + * @param vEntryFk Id de entrada + */ + DECLARE vpackageOrPackingNull INT; + + SELECT count(*) INTO vpackageOrPackingNull + FROM buy b + WHERE b.entryFk = vEntryFk + AND (b.packing IS NULL OR b.packagingFk IS NULL); + + IF vpackageOrPackingNull THEN + CALL util.throw("packageOrPackingNull"); + END IF; +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`fustControl`(vFromDated DATE, vToDated DATE) +BEGIN + + DECLARE vSijsnerClientFk INT DEFAULT 19752; + + DECLARE vDateStart DATETIME; + DECLARE vDateEnd DATETIME; + + SET vDateStart = vFromDated; + SET vDateEnd = util.Dayend(vToDated); + + SELECT p.id FustCode, + CAST(sent.stucks AS DECIMAL(10,0)) FH, + CAST(tp.stucks AS DECIMAL(10,0)) Tickets, + CAST(-sj.stucks AS DECIMAL(10,0)) Sijsner, + CAST(IFNULL(sent.stucks,0) - IFNULL(tp.stucks,0) + IFNULL(sj.stucks,0) AS DECIMAL(10,0)) saldo + FROM vn.packaging p + LEFT JOIN ( + SELECT FustCode, sum(fustQuantity) stucks + FROM ( + SELECT IFNULL(pe.equivalentFk ,b.packagingFk) FustCode, s.quantity / b.packing AS fustQuantity + FROM vn.sale s + JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.warehouse w ON w.id = t.warehouseFk + JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk + JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND lb.warehouse_id = t.warehouseFk + JOIN vn.buy b ON b.id = lb.buy_id + JOIN vn.packaging p ON p.id = b.packagingFk + LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id + JOIN vn.address a ON a.id = t.addressFk + JOIN vn.province p2 ON p2.id = a.provinceFk + JOIN vn.country c ON c.id = p2.countryFk + WHERE t.shipped BETWEEN vDateStart AND vDateEnd + AND wa.name = 'VNH' + AND p.isPackageReturnable + AND c.country = 'FRANCIA') sub + GROUP BY FustCode) sent ON sent.FustCode = p.id + LEFT JOIN ( + SELECT FustCode, sum(quantity) stucks + FROM ( + SELECT IFNULL(pe.equivalentFk ,tp.packagingFk) FustCode, tp.quantity + FROM vn.ticketPackaging tp + JOIN vn.ticket t ON t.id = tp.ticketFk + JOIN vn.warehouse w ON w.id = t.warehouseFk + JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk + JOIN vn.packaging p ON p.id = tp.packagingFk + LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id + JOIN vn.address a ON a.id = t.addressFk + JOIN vn.province p2 ON p2.id = a.provinceFk + JOIN vn.country c ON c.id = p2.countryFk + WHERE t.shipped BETWEEN vDateStart AND vDateEnd + AND wa.name = 'VNH' + AND p.isPackageReturnable + AND c.country = 'FRANCIA' + AND t.clientFk != vSijsnerClientFk + AND tp.quantity > 0) sub + GROUP BY FustCode) tp ON tp.FustCode = p.id + LEFT JOIN ( + SELECT FustCode, sum(quantity) stucks + FROM ( + SELECT IFNULL(pe.equivalentFk ,tp.packagingFk) FustCode, tp.quantity + FROM vn.ticketPackaging tp + JOIN vn.ticket t ON t.id = tp.ticketFk + JOIN vn.warehouse w ON w.id = t.warehouseFk + JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk + JOIN vn.packaging p ON p.id = tp.packagingFk + LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id + WHERE t.shipped BETWEEN TIMESTAMPADD(DAY, 1, vDateStart ) AND TIMESTAMPADD(DAY, 1, vDateEnd ) + AND wa.name = 'VNH' + AND p.isPackageReturnable + AND t.clientFk = vSijsnerClientFk) sub + GROUP BY FustCode) sj ON sj.FustCode = p.id + WHERE sent.stucks + OR tp.stucks + OR sj.stucks; + +END$$ +DELIMITER ; + From 7367656a354d7e1e53305782d62b59f1b2c861f2 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 13 Oct 2023 09:02:40 +0200 Subject: [PATCH 217/427] refs #6199 Requested changes --- modules/order/front/catalog-view/index.html | 21 +++++++++++---------- modules/order/front/catalog-view/style.scss | 6 +----- 2 files changed, 12 insertions(+), 15 deletions(-) diff --git a/modules/order/front/catalog-view/index.html b/modules/order/front/catalog-view/index.html index c9375aab5..907882a06 100644 --- a/modules/order/front/catalog-view/index.html +++ b/modules/order/front/catalog-view/index.html @@ -37,17 +37,18 @@ value="{{::item.value7}}">
-
- - - {{::item.minQuantity}} -
+ ng-if="::item.minQuantity"> +
+ + + {{::item.minQuantity}} +
+
diff --git a/modules/order/front/catalog-view/style.scss b/modules/order/front/catalog-view/style.scss index abfde3589..a7a2a815c 100644 --- a/modules/order/front/catalog-view/style.scss +++ b/modules/order/front/catalog-view/style.scss @@ -45,13 +45,9 @@ vn-order-catalog { position: relative; } .text-caption-reduced { + color: $color-alert; display: flex; align-items: center; justify-content: flex-end; - color: $color-alert; - } - .min-quantity-icon { - font-size: 18px; - margin-right: 3px; } } \ No newline at end of file From fa901329347b91d04c5c430aae6fdbe4eb424c2a Mon Sep 17 00:00:00 2001 From: alexm Date: Fri, 13 Oct 2023 10:23:48 +0200 Subject: [PATCH 218/427] refs #6199 fix(orderCatalogView): html and css --- modules/order/front/catalog-view/index.html | 41 +++++++++++---------- modules/order/front/catalog-view/style.scss | 7 +--- 2 files changed, 24 insertions(+), 24 deletions(-) diff --git a/modules/order/front/catalog-view/index.html b/modules/order/front/catalog-view/index.html index 907882a06..5d60211ed 100644 --- a/modules/order/front/catalog-view/index.html +++ b/modules/order/front/catalog-view/index.html @@ -8,12 +8,12 @@
- @@ -37,25 +37,28 @@ value="{{::item.value7}}">
- -
- - - {{::item.minQuantity}} -
+ + + + + + + + + + {{::item.minQuantity}} + - - @@ -81,4 +84,4 @@ - \ No newline at end of file + diff --git a/modules/order/front/catalog-view/style.scss b/modules/order/front/catalog-view/style.scss index a7a2a815c..1e48745ca 100644 --- a/modules/order/front/catalog-view/style.scss +++ b/modules/order/front/catalog-view/style.scss @@ -44,10 +44,7 @@ vn-order-catalog { height: 30px; position: relative; } - .text-caption-reduced { + .alert { color: $color-alert; - display: flex; - align-items: center; - justify-content: flex-end; } -} \ No newline at end of file +} From 9c0334619d628ff419780642c77b335231f1c9e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Fri, 13 Oct 2023 11:56:50 +0200 Subject: [PATCH 219/427] refs #6199 --- loopback/locale/es.json | 3 ++- modules/item/back/models/item.json | 4 ++++ modules/ticket/back/methods/sale/updateQuantity.js | 9 +++++++++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 8c50cd9d8..d34c97d21 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -319,5 +319,6 @@ "The response is not a PDF": "La respuesta no es un PDF", "Ticket without Route": "Ticket sin ruta", "Booking completed": "Reserva completada", - "The ticket is in preparation": "El ticket [{{ticketId}}]({{{ticketUrl}}}) del comercial {{salesPersonId}} está en preparación" + "The ticket is in preparation": "El ticket [{{ticketId}}]({{{ticketUrl}}}) del comercial {{salesPersonId}} está en preparación", + "The amount cannot be less than the minimum": "La cantidad no puede ser menor que la cantidad mímina" } diff --git a/modules/item/back/models/item.json b/modules/item/back/models/item.json index e99dcd996..28f9648fb 100644 --- a/modules/item/back/models/item.json +++ b/modules/item/back/models/item.json @@ -154,6 +154,10 @@ "mysql":{ "columnName": "doPhoto" } + }, + "minQuantity": { + "type": "number", + "description": "Min quantity" } }, "relations": { diff --git a/modules/ticket/back/methods/sale/updateQuantity.js b/modules/ticket/back/methods/sale/updateQuantity.js index edbc34e42..375928506 100644 --- a/modules/ticket/back/methods/sale/updateQuantity.js +++ b/modules/ticket/back/methods/sale/updateQuantity.js @@ -72,6 +72,15 @@ module.exports = Self => { where: {refundTicketFk: sale.ticketFk}, fields: ['id']} , myOptions); + + const item = await models.Item.findOne({ + where: {id: sale.itemFk}, + fields: ['minQuantity']} + , myOptions); + + if (newQuantity < item.minQuantity && !ticketRefund) + throw new UserError('The amount cannot be less than the minimum'); + if (newQuantity < 0 && !ticketRefund) throw new UserError('You can only add negative amounts in refund tickets'); From e1c1d1a556e62ebcf94e9e62026e45e772697910 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 13 Oct 2023 12:33:39 +0200 Subject: [PATCH 220/427] refs #6199 Fixed tests --- db/dump/structure.sql | 1 + 1 file changed, 1 insertion(+) diff --git a/db/dump/structure.sql b/db/dump/structure.sql index 08df0541c..b242821fc 100644 --- a/db/dump/structure.sql +++ b/db/dump/structure.sql @@ -30434,6 +30434,7 @@ CREATE TABLE `item` ( `editorFk` int(10) unsigned DEFAULT NULL, `recycledPlastic` int(11) DEFAULT NULL, `nonRecycledPlastic` int(11) DEFAULT NULL, + `minQuantity` int(10) unsigned DEFAULT NULL COMMENT 'Cantidad mínima para una línea de venta', PRIMARY KEY (`id`), UNIQUE KEY `item_supplyResponseFk_idx` (`supplyResponseFk`), KEY `Color` (`inkFk`), From 03687cb48279acf4777b6554ba59bc4cd09838f7 Mon Sep 17 00:00:00 2001 From: alexm Date: Fri, 13 Oct 2023 14:56:56 +0200 Subject: [PATCH 221/427] hotFix: delete getCurrentWorkerMana --- modules/ticket/front/sale/index.html | 2 +- modules/ticket/front/sale/index.js | 8 ------ modules/ticket/front/sale/index.spec.js | 2 -- .../worker-mana/getCurrentWorkerMana.js | 26 ------------------- .../specs/getCurrentWorkerMana.spec.js | 15 ----------- modules/worker/back/models/worker-mana.js | 3 --- 6 files changed, 1 insertion(+), 55 deletions(-) delete mode 100644 modules/worker/back/methods/worker-mana/getCurrentWorkerMana.js delete mode 100644 modules/worker/back/methods/worker-mana/specs/getCurrentWorkerMana.spec.js delete mode 100644 modules/worker/back/models/worker-mana.js diff --git a/modules/ticket/front/sale/index.html b/modules/ticket/front/sale/index.html index be9e81964..b8e64cf28 100644 --- a/modules/ticket/front/sale/index.html +++ b/modules/ticket/front/sale/index.html @@ -318,7 +318,7 @@ clear-disabled="true" suffix="%"> - + { - this.currentWorkerMana = res.data; - }); } getUsesMana() { diff --git a/modules/ticket/front/sale/index.spec.js b/modules/ticket/front/sale/index.spec.js index 9da8e6e7c..b36e78893 100644 --- a/modules/ticket/front/sale/index.spec.js +++ b/modules/ticket/front/sale/index.spec.js @@ -120,12 +120,10 @@ describe('Ticket', () => { const expectedAmount = 250; $httpBackend.expect('GET', 'Tickets/1/getSalesPersonMana').respond(200, expectedAmount); $httpBackend.expect('GET', 'Sales/usesMana').respond(200); - $httpBackend.expect('GET', 'WorkerManas/getCurrentWorkerMana').respond(200, expectedAmount); controller.getMana(); $httpBackend.flush(); expect(controller.edit.mana).toEqual(expectedAmount); - expect(controller.currentWorkerMana).toEqual(expectedAmount); }); }); diff --git a/modules/worker/back/methods/worker-mana/getCurrentWorkerMana.js b/modules/worker/back/methods/worker-mana/getCurrentWorkerMana.js deleted file mode 100644 index fa34af475..000000000 --- a/modules/worker/back/methods/worker-mana/getCurrentWorkerMana.js +++ /dev/null @@ -1,26 +0,0 @@ -module.exports = Self => { - Self.remoteMethodCtx('getCurrentWorkerMana', { - description: 'Returns the mana of the logged worker', - accessType: 'READ', - accepts: [], - returns: { - type: 'number', - root: true - }, - http: { - path: `/getCurrentWorkerMana`, - verb: 'GET' - } - }); - - Self.getCurrentWorkerMana = async ctx => { - let userId = ctx.req.accessToken.userId; - - let workerMana = await Self.app.models.WorkerMana.findOne({ - where: {workerFk: userId}, - fields: 'amount' - }); - - return workerMana ? workerMana.amount : 0; - }; -}; diff --git a/modules/worker/back/methods/worker-mana/specs/getCurrentWorkerMana.spec.js b/modules/worker/back/methods/worker-mana/specs/getCurrentWorkerMana.spec.js deleted file mode 100644 index 8d626e720..000000000 --- a/modules/worker/back/methods/worker-mana/specs/getCurrentWorkerMana.spec.js +++ /dev/null @@ -1,15 +0,0 @@ -const app = require('vn-loopback/server/server'); - -describe('workerMana getCurrentWorkerMana()', () => { - it('should get the mana of the logged worker', async() => { - let mana = await app.models.WorkerMana.getCurrentWorkerMana({req: {accessToken: {userId: 18}}}); - - expect(mana).toEqual(124); - }); - - it('should return 0 if the user doesnt uses mana', async() => { - let mana = await app.models.WorkerMana.getCurrentWorkerMana({req: {accessToken: {userId: 9}}}); - - expect(mana).toEqual(0); - }); -}); diff --git a/modules/worker/back/models/worker-mana.js b/modules/worker/back/models/worker-mana.js deleted file mode 100644 index 99a0f7694..000000000 --- a/modules/worker/back/models/worker-mana.js +++ /dev/null @@ -1,3 +0,0 @@ -module.exports = Self => { - require('../methods/worker-mana/getCurrentWorkerMana')(Self); -}; From ab1cc34015686624bcb53a8b7eac620191cd52ca Mon Sep 17 00:00:00 2001 From: alexm Date: Fri, 13 Oct 2023 15:14:48 +0200 Subject: [PATCH 222/427] refs #6199 feat(sale): best quantity restriction --- .../back/methods/sale/updateQuantity.js | 22 +--------- modules/ticket/back/models/sale.js | 41 +++++++++++++++++++ 2 files changed, 42 insertions(+), 21 deletions(-) diff --git a/modules/ticket/back/methods/sale/updateQuantity.js b/modules/ticket/back/methods/sale/updateQuantity.js index 375928506..ce7db5ffd 100644 --- a/modules/ticket/back/methods/sale/updateQuantity.js +++ b/modules/ticket/back/methods/sale/updateQuantity.js @@ -1,4 +1,4 @@ -let UserError = require('vn-loopback/util/user-error'); +const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethodCtx('updateQuantity', { @@ -64,26 +64,6 @@ module.exports = Self => { const sale = await models.Sale.findById(id, filter, myOptions); - const isRoleAdvanced = await models.ACL.checkAccessAcl(ctx, 'Ticket', 'isRoleAdvanced', '*'); - if (newQuantity > sale.quantity && !isRoleAdvanced) - throw new UserError('The new quantity should be smaller than the old one'); - - const ticketRefund = await models.TicketRefund.findOne({ - where: {refundTicketFk: sale.ticketFk}, - fields: ['id']} - , myOptions); - - const item = await models.Item.findOne({ - where: {id: sale.itemFk}, - fields: ['minQuantity']} - , myOptions); - - if (newQuantity < item.minQuantity && !ticketRefund) - throw new UserError('The amount cannot be less than the minimum'); - - if (newQuantity < 0 && !ticketRefund) - throw new UserError('You can only add negative amounts in refund tickets'); - const oldQuantity = sale.quantity; const result = await sale.updateAttributes({quantity: newQuantity}, myOptions); diff --git a/modules/ticket/back/models/sale.js b/modules/ticket/back/models/sale.js index ae247fc24..556f35d60 100644 --- a/modules/ticket/back/models/sale.js +++ b/modules/ticket/back/models/sale.js @@ -1,3 +1,5 @@ +const UserError = require('vn-loopback/util/user-error'); + module.exports = Self => { require('../methods/sale/getClaimableFromTicket')(Self); require('../methods/sale/reserve')(Self); @@ -13,4 +15,43 @@ module.exports = Self => { Self.validatesPresenceOf('concept', { message: `Concept cannot be blank` }); + + Self.observe('before save', async ctx => { + const models = Self.app.models; + const changes = ctx.data || ctx.instance; + const instance = ctx.currentInstance; + console.log(ctx?.req?.accessToken, instance, changes); + const newQuantity = changes?.quantity; + if (newQuantity === null) return; + + const canEditQuantity = await models.ACL.checkAccessAcl(ctx, 'Sale', 'canForceQuantity', 'WRITE'); + if (canEditQuantity) return; + + const ticketId = changes?.ticketFk || instance?.ticketFk; + const itemId = changes?.itemFk || instance?.itemFk; + + const ticketRefund = await models.TicketRefund.findOne({ + where: {refundTicketFk: ticketId}, + fields: ['id']} + , ctx.options); + + const item = await models.Item.findOne({ + where: {id: itemId}, + fields: ['minQuantity']} + , ctx.options); + + if (newQuantity < item.minQuantity && !ticketRefund) + throw new UserError('The amount cannot be less than the minimum'); + + if (newQuantity < 0 && !ticketRefund) + throw new UserError('You can only add negative amounts in refund tickets'); + + const oldQuantity = instance?.quantity; + if (oldQuantity === null) return; + + const isRoleAdvanced = await models.ACL.checkAccessAcl(ctx, 'Ticket', 'isRoleAdvanced', '*'); + if (newQuantity > oldQuantity && !isRoleAdvanced) + throw new UserError('The new quantity should be smaller than the old one'); + }); }; + From f832c1d9eceba58e63530197e54a6716809f2a09 Mon Sep 17 00:00:00 2001 From: pablone Date: Sun, 15 Oct 2023 11:08:33 +0200 Subject: [PATCH 223/427] refs #5979 getUrl --- back/methods/collection/getTickets.js | 21 ++++---------- loopback/common/methods/application/getUrl.js | 29 +++++++++++++++++++ loopback/common/models/application.js | 1 + loopback/common/models/application.json | 8 ++++- .../back/methods/claim/claimPickupEmail.js | 7 ++--- .../claim/back/methods/claim/updateClaim.js | 9 +++--- .../back/methods/sale/updateQuantity.js | 7 +++-- 7 files changed, 54 insertions(+), 28 deletions(-) create mode 100644 loopback/common/methods/application/getUrl.js diff --git a/back/methods/collection/getTickets.js b/back/methods/collection/getTickets.js index 445fc070d..8509edadf 100644 --- a/back/methods/collection/getTickets.js +++ b/back/methods/collection/getTickets.js @@ -26,7 +26,7 @@ module.exports = Self => { Self.getTickets = async(ctx, id, print, options) => { const userId = ctx.req.accessToken.userId; - const origin = ctx.req.headers.origin; + const url = Self.app.models.Application.getUrl(); const $t = ctx.req.__; const myOptions = {}; @@ -36,7 +36,6 @@ module.exports = Self => { myOptions.userId = userId; const promises = []; - const [tickets] = await Self.rawSql(`CALL vn.collection_getTickets(?)`, [id], myOptions); const sales = await Self.rawSql(` SELECT s.ticketFk, @@ -46,11 +45,11 @@ module.exports = Self => { i.longName, i.size, ic.color, - o.code origin, + o.code url, ish.packing, ish.grouping, s.isAdded, - s.originalQuantity, + s.urlalQuantity, s.quantity saleQuantity, iss.quantity reservedQuantity, SUM(iss.quantity) OVER (PARTITION BY s.id ORDER BY ish.id) accumulatedQuantity, @@ -74,7 +73,7 @@ module.exports = Self => { LEFT JOIN shelving sh ON sh.code = ish.shelvingFk LEFT JOIN parking p ON p.id = sh.parkingFk LEFT JOIN itemColor ic ON ic.itemFk = s.itemFk - LEFT JOIN origin o ON o.id = i.originFk + LEFT JOIN url o ON o.id = i.urlFk WHERE tc.collectionFk = ? GROUP BY ish.id, p.code, p2.code ORDER BY pickingOrder;`, [id], myOptions); @@ -86,24 +85,19 @@ module.exports = Self => { if (tickets && tickets.length) { for (const ticket of tickets) { const ticketId = ticket.ticketFk; - - // SEND ROCKET if (ticket.observaciones != '') { for (observation of ticket.observaciones.split(' ')) { if (['#', '@'].includes(observation.charAt(0))) { promises.push(Self.app.models.Chat.send(ctx, observation, $t('The ticket is in preparation', { ticketId: ticketId, - ticketUrl: `${origin}/#!/ticket/${ticketId}/summary`, + ticketUrl: `${url}/#!/ticket/${ticketId}/summary`, salesPersonId: ticket.salesPersonFk }))); } } } - - // SET COLLECTION if (sales && sales.length) { - // GET BARCODES const barcodes = await Self.rawSql(` SELECT s.id saleFk, b.code, c.id FROM vn.sale s @@ -114,13 +108,10 @@ module.exports = Self => { WHERE s.ticketFk = ? AND tr.landed >= util.VN_CURDATE() - INTERVAL 1 YEAR`, [ticketId], myOptions); - - // BINDINGS ticket.sales = []; for (const sale of sales) { if (sale.ticketFk === ticketId) { sale.Barcodes = []; - if (barcodes && barcodes.length) { for (const barcode of barcodes) { if (barcode.saleFk === sale.saleFk) { @@ -131,7 +122,6 @@ module.exports = Self => { } } } - ticket.sales.push(sale); } } @@ -140,7 +130,6 @@ module.exports = Self => { } } await Promise.all(promises); - return collection; }; }; diff --git a/loopback/common/methods/application/getUrl.js b/loopback/common/methods/application/getUrl.js new file mode 100644 index 000000000..57aed0b84 --- /dev/null +++ b/loopback/common/methods/application/getUrl.js @@ -0,0 +1,29 @@ +module.exports = Self => { + Self.remoteMethodCtx('getUrl', { + description: 'Returns the colling app name', + accepts: [ + { + arg: 'appName', + type: 'string', + required: false + } + ], + returns: { + type: 'object', + root: true + }, + http: { + path: `/getUrl`, + verb: 'get' + } + }); + Self.getUrl = async(appName = 'salix') => { + const {url} = Self.app.models.Url.findOne({ + where: { + appName, + enviroment: process.env.NODE_ENV || 'development' + } + }); + return url; + }; +}; diff --git a/loopback/common/models/application.js b/loopback/common/models/application.js index 5e767fdc1..b3841d34a 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/getUrl')(Self); }; diff --git a/loopback/common/models/application.json b/loopback/common/models/application.json index bc72df315..6343c3421 100644 --- a/loopback/common/models/application.json +++ b/loopback/common/models/application.json @@ -13,6 +13,12 @@ "principalType": "ROLE", "principalId": "$everyone", "permission": "ALLOW" - } + }, + { + "property": "getUrl", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + } ] } diff --git a/modules/claim/back/methods/claim/claimPickupEmail.js b/modules/claim/back/methods/claim/claimPickupEmail.js index 1fd8eb99e..f4cd0fc20 100644 --- a/modules/claim/back/methods/claim/claimPickupEmail.js +++ b/modules/claim/back/methods/claim/claimPickupEmail.js @@ -43,9 +43,8 @@ module.exports = Self => { Self.claimPickupEmail = async ctx => { const models = Self.app.models; - const userId = ctx.req.accessToken.userId; const $t = ctx.req.__; // $translate - const origin = ctx.req.headers.origin; + const url = await Self.app.models.Application.getUrl(); const args = Object.assign({}, ctx.args); const params = { @@ -70,9 +69,9 @@ module.exports = Self => { const message = $t('Claim pickup order sent', { claimId: args.id, clientName: claim.client().name, - claimUrl: `${origin}/#!/claim/${args.id}/summary`, + claimUrl: `${url}/claim/${args.id}/summary`, }); - + console.log(message); const salesPersonId = claim.client().salesPersonFk; if (salesPersonId) await models.Chat.sendCheckingPresence(ctx, salesPersonId, message); diff --git a/modules/claim/back/methods/claim/updateClaim.js b/modules/claim/back/methods/claim/updateClaim.js index 5486b8eff..b7ffa9ff5 100644 --- a/modules/claim/back/methods/claim/updateClaim.js +++ b/modules/claim/back/methods/claim/updateClaim.js @@ -115,27 +115,28 @@ module.exports = Self => { async function notifyStateChange(ctx, workerId, claim, state) { const models = Self.app.models; - const origin = ctx.req.headers.origin; + const url = await models.Application.getUrl(); const $t = ctx.req.__; // $translate const message = $t(`Claim state has changed to ${state}`, { claimId: claim.id, clientName: claim.client().name, - claimUrl: `${origin}/#!/claim/${claim.id}/summary` + claimUrl: `${url}/claim/${claim.id}/summary` }); await models.Chat.sendCheckingPresence(ctx, workerId, message); } async function notifyPickUp(ctx, workerId, claim) { - const origin = ctx.req.headers.origin; const models = Self.app.models; + const url = await models.Application.getUrl(); const $t = ctx.req.__; // $translate const message = $t('Claim will be picked', { claimId: claim.id, clientName: claim.client().name, - claimUrl: `${origin}/#!/claim/${claim.id}/summary` + claimUrl: `${url}/claim/${claim.id}/summary` }); + console.log(message); await models.Chat.sendCheckingPresence(ctx, workerId, message); } }; diff --git a/modules/ticket/back/methods/sale/updateQuantity.js b/modules/ticket/back/methods/sale/updateQuantity.js index edbc34e42..3cbd9255f 100644 --- a/modules/ticket/back/methods/sale/updateQuantity.js +++ b/modules/ticket/back/methods/sale/updateQuantity.js @@ -80,16 +80,17 @@ module.exports = Self => { const salesPerson = sale.ticket().client().salesPersonUser(); if (salesPerson) { - const origin = ctx.req.headers.origin; + const url = await models.Application.getUrl(); const message = $t('Changed sale quantity', { ticketId: sale.ticket().id, itemId: sale.itemFk, concept: sale.concept, oldQuantity: oldQuantity, newQuantity: newQuantity, - ticketUrl: `${origin}/#!/ticket/${sale.ticket().id}/sale`, - itemUrl: `${origin}/#!/item/${sale.itemFk}/summary` + ticketUrl: `${url}/ticket/${sale.ticket().id}/sale`, + itemUrl: `${url}/item/${sale.itemFk}/summary` }); + await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message, myOptions); } From b769fa9bcf5ad8c99d2365742c78918783758c0d Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 16 Oct 2023 10:10:57 +0200 Subject: [PATCH 224/427] refs #6199 fix(sale_updateQuantity): if clientType is loses skip test: fix updateQuantity activeCtx and add test for minQuantity --- loopback/locale/en.json | 5 +- .../claim/specs/regularizeClaim.spec.js | 2 +- .../methods/sale/specs/updateQuantity.spec.js | 62 ++++++++++++++----- .../back/methods/sale/updateQuantity.js | 1 - modules/ticket/back/models/sale.js | 35 +++++++++-- 5 files changed, 81 insertions(+), 24 deletions(-) diff --git a/loopback/locale/en.json b/loopback/locale/en.json index 645a874e8..f61226e9e 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -189,5 +189,6 @@ "The sales do not exists": "The sales do not exists", "Ticket without Route": "Ticket without route", "Booking completed": "Booking complete", - "The ticket is in preparation": "The ticket [{{ticketId}}]({{{ticketUrl}}}) of the sales person {{salesPersonId}} is in preparation" -} + "The ticket is in preparation": "The ticket [{{ticketId}}]({{{ticketUrl}}}) of the sales person {{salesPersonId}} is in preparation", + "You can only add negative amounts in refund tickets": "You can only add negative amounts in refund tickets" +} \ No newline at end of file diff --git a/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js b/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js index 276843c32..95c356374 100644 --- a/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js +++ b/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js @@ -64,7 +64,7 @@ describe('claim regularizeClaim()', () => { claimEnds = await importTicket(ticketId, claimId, userId, options); - for (claimEnd of claimEnds) + for (const claimEnd of claimEnds) await claimEnd.updateAttributes({claimDestinationFk: trashDestination}, options); let claimBefore = await models.Claim.findById(claimId, null, options); diff --git a/modules/ticket/back/methods/sale/specs/updateQuantity.spec.js b/modules/ticket/back/methods/sale/specs/updateQuantity.spec.js index 8064ea30b..bb58780e3 100644 --- a/modules/ticket/back/methods/sale/specs/updateQuantity.spec.js +++ b/modules/ticket/back/methods/sale/specs/updateQuantity.spec.js @@ -2,20 +2,6 @@ const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); describe('sale updateQuantity()', () => { - beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); - const ctx = { req: { accessToken: {userId: 9}, @@ -23,6 +9,18 @@ describe('sale updateQuantity()', () => { __: () => {} } }; + function getActiveCtx(userId) { + return { + active: { + accessToken: {userId}, + http: { + req: { + headers: {origin: 'http://localhost'} + } + } + } + }; + } it('should throw an error if the quantity is greater than it should be', async() => { const ctx = { @@ -32,6 +30,8 @@ describe('sale updateQuantity()', () => { __: () => {} } }; + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); + const tx = await models.Sale.beginTransaction({}); let error; @@ -50,6 +50,8 @@ describe('sale updateQuantity()', () => { }); it('should add quantity if the quantity is greater than it should be and is role advanced', async() => { + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(9)); + const tx = await models.Sale.beginTransaction({}); const saleId = 17; const buyerId = 35; @@ -87,6 +89,8 @@ describe('sale updateQuantity()', () => { }); it('should update the quantity of a given sale current line', async() => { + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(9)); + const tx = await models.Sale.beginTransaction({}); const saleId = 25; const newQuantity = 4; @@ -119,6 +123,8 @@ describe('sale updateQuantity()', () => { __: () => {} } }; + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); + const saleId = 17; const newQuantity = -10; @@ -140,6 +146,8 @@ describe('sale updateQuantity()', () => { }); it('should update a negative quantity when is a ticket refund', async() => { + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(9)); + const tx = await models.Sale.beginTransaction({}); const saleId = 13; const newQuantity = -10; @@ -159,4 +167,30 @@ describe('sale updateQuantity()', () => { throw e; } }); + + it('should throw an error if the quantity is less than the minimum quantity of the item', async() => { + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(9)); + + const tx = await models.Sale.beginTransaction({}); + const itemId = 2; + const saleId = 17; + const newQuantity = 29; + + let error; + try { + const options = {transaction: tx}; + + const item = await models.Item.findById(itemId, null, options); + await item.updateAttribute('minQuantity', 30, options); + + await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error).toEqual(new Error('The amount cannot be less than the minimum')); + }); }); diff --git a/modules/ticket/back/methods/sale/updateQuantity.js b/modules/ticket/back/methods/sale/updateQuantity.js index ce7db5ffd..55106f053 100644 --- a/modules/ticket/back/methods/sale/updateQuantity.js +++ b/modules/ticket/back/methods/sale/updateQuantity.js @@ -1,4 +1,3 @@ -const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethodCtx('updateQuantity', { diff --git a/modules/ticket/back/models/sale.js b/modules/ticket/back/models/sale.js index 556f35d60..bacc5ef44 100644 --- a/modules/ticket/back/models/sale.js +++ b/modules/ticket/back/models/sale.js @@ -1,4 +1,5 @@ const UserError = require('vn-loopback/util/user-error'); +const LoopBackContext = require('loopback-context'); module.exports = Self => { require('../methods/sale/getClaimableFromTicket')(Self); @@ -20,21 +21,46 @@ module.exports = Self => { const models = Self.app.models; const changes = ctx.data || ctx.instance; const instance = ctx.currentInstance; - console.log(ctx?.req?.accessToken, instance, changes); - const newQuantity = changes?.quantity; - if (newQuantity === null) return; + const newQuantity = changes?.quantity; + if (newQuantity == null) return; + + const loopBackContext = LoopBackContext.getCurrentContext(); + ctx.req = loopBackContext.active; const canEditQuantity = await models.ACL.checkAccessAcl(ctx, 'Sale', 'canForceQuantity', 'WRITE'); if (canEditQuantity) return; const ticketId = changes?.ticketFk || instance?.ticketFk; const itemId = changes?.itemFk || instance?.itemFk; + const ticket = await models.Ticket.findById( + ticketId, + { + fields: ['id', 'clientFk'], + include: { + relation: 'client', + scope: { + fields: ['id', 'clientTypeFk'], + include: { + relation: 'type', + scope: { + fields: ['code', 'description'] + } + } + } + } + }, + ctx.options); + if (ticket.client().type().code === 'loses') return; + const ticketRefund = await models.TicketRefund.findOne({ where: {refundTicketFk: ticketId}, fields: ['id']} , ctx.options); + if (newQuantity < 0 && !ticketRefund) + throw new UserError('You can only add negative amounts in refund tickets'); + const item = await models.Item.findOne({ where: {id: itemId}, fields: ['minQuantity']} @@ -43,9 +69,6 @@ module.exports = Self => { if (newQuantity < item.minQuantity && !ticketRefund) throw new UserError('The amount cannot be less than the minimum'); - if (newQuantity < 0 && !ticketRefund) - throw new UserError('You can only add negative amounts in refund tickets'); - const oldQuantity = instance?.quantity; if (oldQuantity === null) return; From f79e71161744cce480b88b1e07ec3cd1946ebe17 Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 16 Oct 2023 10:19:33 +0200 Subject: [PATCH 225/427] refs #6199 test: updateQuantity refactor --- .../ticket/back/methods/sale/specs/updateQuantity.spec.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/modules/ticket/back/methods/sale/specs/updateQuantity.spec.js b/modules/ticket/back/methods/sale/specs/updateQuantity.spec.js index bb58780e3..6bf0a0d7e 100644 --- a/modules/ticket/back/methods/sale/specs/updateQuantity.spec.js +++ b/modules/ticket/back/methods/sale/specs/updateQuantity.spec.js @@ -174,14 +174,15 @@ describe('sale updateQuantity()', () => { const tx = await models.Sale.beginTransaction({}); const itemId = 2; const saleId = 17; - const newQuantity = 29; + const minQuantity = 30; + const newQuantity = minQuantity - 1; let error; try { const options = {transaction: tx}; const item = await models.Item.findById(itemId, null, options); - await item.updateAttribute('minQuantity', 30, options); + await item.updateAttribute('minQuantity', minQuantity, options); await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); From 9e39e96cf4c43cf6e3810e2e85771947103bd94a Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 16 Oct 2023 15:22:33 +0200 Subject: [PATCH 226/427] hotFix: workerTimeControl --- .../methods/worker-time-control/sendMail.js | 64 ++++++++----------- 1 file changed, 27 insertions(+), 37 deletions(-) diff --git a/modules/worker/back/methods/worker-time-control/sendMail.js b/modules/worker/back/methods/worker-time-control/sendMail.js index 2c5143612..6f67bbea3 100644 --- a/modules/worker/back/methods/worker-time-control/sendMail.js +++ b/modules/worker/back/methods/worker-time-control/sendMail.js @@ -66,46 +66,36 @@ module.exports = Self => { stmts.push('DROP TEMPORARY TABLE IF EXISTS tmp.timeControlCalculate'); stmts.push('DROP TEMPORARY TABLE IF EXISTS tmp.timeBusinessCalculate'); + const destroyAllWhere = { + timed: {between: [started, ended]}, + isSendMail: true + }; + const updateAllWhere = { + year: args.year, + week: args.week + }; + + const tmpUserSQL = ` + CREATE OR REPLACE TEMPORARY TABLE tmp.user + SELECT id as userFk + FROM vn.worker`; + let tmpUser = new ParameterizedSQL(tmpUserSQL); + if (args.workerId) { - await models.WorkerTimeControl.destroyAll({ - userFk: args.workerId, - timed: {between: [started, ended]}, - isSendMail: true - }, myOptions); - - const where = { - workerFk: args.workerId, - year: args.year, - week: args.week - }; - await models.WorkerTimeControlMail.updateAll(where, { - updated: Date.vnNew(), state: 'SENDED' - }, myOptions); - - stmt = new ParameterizedSQL('DROP TEMPORARY TABLE IF EXISTS tmp.`user`'); - stmts.push(stmt); - stmt = new ParameterizedSQL('CREATE TEMPORARY TABLE tmp.`user` SELECT id userFk FROM account.user WHERE id = ?', [args.workerId]); - stmts.push(stmt); - } else { - await models.WorkerTimeControl.destroyAll({ - timed: {between: [started, ended]}, - isSendMail: true - }, myOptions); - - const where = { - year: args.year, - week: args.week - }; - await models.WorkerTimeControlMail.updateAll(where, { - updated: Date.vnNew(), state: 'SENDED' - }, myOptions); - - stmt = new ParameterizedSQL('DROP TEMPORARY TABLE IF EXISTS tmp.`user`'); - stmts.push(stmt); - stmt = new ParameterizedSQL('CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` SELECT id as userFk FROM vn.worker w JOIN account.`user` u ON u.id = w.id WHERE id IS NOT NULL'); - stmts.push(stmt); + destroyAllWhere.userFk = args.workerId; + updateAllWhere.workerFk = args.workerId; + tmpUser = new ParameterizedSQL(tmpUserSQL + ' WHERE id = ?', [args.workerId]); } + await models.WorkerTimeControl.destroyAll(destroyAllWhere, myOptions); + + await models.WorkerTimeControlMail.updateAll(updateAllWhere, { + updated: Date.vnNew(), + state: 'SENDED' + }, myOptions); + + stmts.push(tmpUser); + stmt = new ParameterizedSQL( `CALL vn.timeControl_calculate(?, ?) `, [started, ended]); From 093431ecdfb84f306e4a833c7b908782452130fd Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 16 Oct 2023 15:27:10 +0200 Subject: [PATCH 227/427] refs #6119 fix(sale_hook): fix quantity case --- modules/ticket/back/methods/ticket/addSale.js | 11 ----- modules/ticket/back/models/sale.js | 44 ++++++++++++------- 2 files changed, 28 insertions(+), 27 deletions(-) diff --git a/modules/ticket/back/methods/ticket/addSale.js b/modules/ticket/back/methods/ticket/addSale.js index cbf884273..21fea1c81 100644 --- a/modules/ticket/back/methods/ticket/addSale.js +++ b/modules/ticket/back/methods/ticket/addSale.js @@ -63,17 +63,6 @@ module.exports = Self => { } }, myOptions); - const itemInfo = await models.Item.getVisibleAvailable( - itemId, - ticket.warehouseFk, - ticket.shipped, - myOptions - ); - - const isPackaging = item.family == 'EMB'; - if (!isPackaging && itemInfo.available < quantity) - throw new UserError(`This item is not available`); - const newSale = await models.Sale.create({ ticketFk: id, itemFk: item.id, diff --git a/modules/ticket/back/models/sale.js b/modules/ticket/back/models/sale.js index bacc5ef44..378ff3490 100644 --- a/modules/ticket/back/models/sale.js +++ b/modules/ticket/back/models/sale.js @@ -27,8 +27,7 @@ module.exports = Self => { const loopBackContext = LoopBackContext.getCurrentContext(); ctx.req = loopBackContext.active; - const canEditQuantity = await models.ACL.checkAccessAcl(ctx, 'Sale', 'canForceQuantity', 'WRITE'); - if (canEditQuantity) return; + if (await models.ACL.checkAccessAcl(ctx, 'Sale', 'canForceQuantity', 'WRITE')) return; const ticketId = changes?.ticketFk || instance?.ticketFk; const itemId = changes?.itemFk || instance?.itemFk; @@ -36,7 +35,7 @@ module.exports = Self => { const ticket = await models.Ticket.findById( ticketId, { - fields: ['id', 'clientFk'], + fields: ['id', 'clientFk', 'warehouseFk', 'shipped'], include: { relation: 'client', scope: { @@ -51,29 +50,42 @@ module.exports = Self => { } }, ctx.options); - if (ticket.client().type().code === 'loses') return; + if (ticket?.client()?.type()?.code === 'loses') return; - const ticketRefund = await models.TicketRefund.findOne({ - where: {refundTicketFk: ticketId}, - fields: ['id']} - , ctx.options); + const isRefund = await models.TicketRefund.findOne({ + fields: ['id'], + where: {refundTicketFk: ticketId} + }, ctx.options); + if (isRefund) return; - if (newQuantity < 0 && !ticketRefund) + if (newQuantity < 0) throw new UserError('You can only add negative amounts in refund tickets'); const item = await models.Item.findOne({ + fields: ['family', 'minQuantity'], where: {id: itemId}, - fields: ['minQuantity']} - , ctx.options); + }, ctx.options); - if (newQuantity < item.minQuantity && !ticketRefund) - throw new UserError('The amount cannot be less than the minimum'); + if (item.family == 'EMB') return; + + const itemInfo = await models.Item.getVisibleAvailable( + itemId, + ticket.warehouseFk, + ticket.shipped, + ctx.options + ); const oldQuantity = instance?.quantity; - if (oldQuantity === null) return; + const quantityAdded = newQuantity - oldQuantity; + if (itemInfo.available < quantityAdded) + throw new UserError(`This item is not available`); - const isRoleAdvanced = await models.ACL.checkAccessAcl(ctx, 'Ticket', 'isRoleAdvanced', '*'); - if (newQuantity > oldQuantity && !isRoleAdvanced) + if (await models.ACL.checkAccessAcl(ctx, 'Ticket', 'isRoleAdvanced', '*')) return; + + if (newQuantity < item.minQuantity && itemInfo.available != newQuantity) + throw new UserError('The amount cannot be less than the minimum'); + + if (!ctx.isNewInstance && newQuantity > oldQuantity) throw new UserError('The new quantity should be smaller than the old one'); }); }; From bd535374d8bf197066a2a3949acbf5e3e6b5644a Mon Sep 17 00:00:00 2001 From: jorgep Date: Mon, 16 Oct 2023 15:58:25 +0200 Subject: [PATCH 228/427] ref #6138 setPasword created --- back/models/vn-user.json | 6 +- db/changes/234201/00-aclSetPassword.sql | 4 ++ .../worker/back/methods/worker/setPassword.js | 48 +++++++++++++++ .../methods/worker/specs/setPassword.spec.js | 61 +++++++++++++++++++ modules/worker/back/models/worker.js | 1 + modules/worker/front/card/index.js | 2 +- modules/worker/front/descriptor/index.html | 30 ++++++++- modules/worker/front/descriptor/index.js | 29 ++++++++- modules/worker/front/descriptor/index.spec.js | 20 ++++++ 9 files changed, 195 insertions(+), 6 deletions(-) create mode 100644 db/changes/234201/00-aclSetPassword.sql create mode 100644 modules/worker/back/methods/worker/setPassword.js create mode 100644 modules/worker/back/methods/worker/specs/setPassword.spec.js diff --git a/back/models/vn-user.json b/back/models/vn-user.json index 9e3f8df89..01d83e421 100644 --- a/back/models/vn-user.json +++ b/back/models/vn-user.json @@ -45,6 +45,9 @@ "email": { "type": "string" }, + "emailVerified": { + "type": "boolean" + }, "created": { "type": "date" }, @@ -144,7 +147,8 @@ "image", "hasGrant", "realm", - "email" + "email", + "emailVerified" ] } } diff --git a/db/changes/234201/00-aclSetPassword.sql b/db/changes/234201/00-aclSetPassword.sql new file mode 100644 index 000000000..44b3e9de0 --- /dev/null +++ b/db/changes/234201/00-aclSetPassword.sql @@ -0,0 +1,4 @@ +INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId) + VALUES ('Worker','setPassword','*','ALLOW','ROLE','employee'); + + diff --git a/modules/worker/back/methods/worker/setPassword.js b/modules/worker/back/methods/worker/setPassword.js new file mode 100644 index 000000000..fcfb5e733 --- /dev/null +++ b/modules/worker/back/methods/worker/setPassword.js @@ -0,0 +1,48 @@ +const UserError = require('vn-loopback/util/user-error'); +module.exports = Self => { + Self.remoteMethodCtx('setPassword', { + description: 'Set a new password', + accepts: [ + { + arg: 'workerFk', + type: 'number', + required: true, + description: 'The worker id', + }, + { + arg: 'newPass', + type: 'String', + required: true, + description: 'The new worker password' + } + ], + http: { + path: `/:id/setPassword`, + verb: 'PATCH' + } + }); + Self.setPassword = async(ctx, options) => { + const models = Self.app.models; + const myOptions = {}; + const {args} = ctx; + let tx; + if (typeof options == 'object') + Object.assign(myOptions, options); + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + try { + const isSubordinate = await models.Worker.isSubordinate(ctx, args.workerFk, myOptions); + if (!isSubordinate) throw new UserError('You don\'t have enough privileges.'); + + await models.VnUser.setPassword(args.workerFk, args.newPass, myOptions); + await models.VnUser.updateAll({id: args.workerFk}, {emailVerified: 1}, myOptions); + + if (tx) await tx.commit(); + } catch (e) { + if (tx) await tx.rollback(); + throw e; + } + }; +}; diff --git a/modules/worker/back/methods/worker/specs/setPassword.spec.js b/modules/worker/back/methods/worker/specs/setPassword.spec.js new file mode 100644 index 000000000..fbb403b24 --- /dev/null +++ b/modules/worker/back/methods/worker/specs/setPassword.spec.js @@ -0,0 +1,61 @@ +const UserError = require('vn-loopback/util/user-error'); + +const models = require('vn-loopback/server/server').models; + +describe('worker setPassword()', () => { + let ctx; + beforeAll(() => { + ctx = { + req: { + accessToken: {}, + headers: {origin: 'http://localhost'} + }, + args: {workerFk: 9} + }; + }); + + beforeEach(() => { + ctx.req.accessToken.userId = 20; + ctx.args.newPass = 'H3rn4d3z#'; + }); + + it('should change the password', async() => { + const tx = await models.Worker.beginTransaction({}); + + try { + const options = {transaction: tx}; + await models.Worker.setPassword(ctx, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('should throw an error: Password does not meet requirements', async() => { + const tx = await models.Collection.beginTransaction({}); + ctx.args.newPass = 'Hi'; + try { + const options = {transaction: tx}; + await models.Worker.setPassword(ctx, options); + await tx.rollback(); + } catch (e) { + expect(e.sqlMessage).toEqual('Password does not meet requirements'); + await tx.rollback(); + } + }); + + it('should throw an error: You don\'t have enough privileges.', async() => { + ctx.req.accessToken.userId = 5; + const tx = await models.Collection.beginTransaction({}); + try { + const options = {transaction: tx}; + await models.Worker.setPassword(ctx, options); + await tx.rollback(); + } catch (e) { + expect(e).toEqual(new UserError(`You don't have enough privileges.`)); + await tx.rollback(); + } + }); +}); diff --git a/modules/worker/back/models/worker.js b/modules/worker/back/models/worker.js index ccae3a6e6..985d83e9f 100644 --- a/modules/worker/back/models/worker.js +++ b/modules/worker/back/models/worker.js @@ -18,6 +18,7 @@ module.exports = Self => { require('../methods/worker/allocatePDA')(Self); require('../methods/worker/search')(Self); require('../methods/worker/isAuthorized')(Self); + require('../methods/worker/setPassword')(Self); Self.validatesUniquenessOf('locker', { message: 'This locker has already been assigned' diff --git a/modules/worker/front/card/index.js b/modules/worker/front/card/index.js index b8b533c5d..9a40e31c2 100644 --- a/modules/worker/front/card/index.js +++ b/modules/worker/front/card/index.js @@ -8,7 +8,7 @@ class Controller extends ModuleCard { { relation: 'user', scope: { - fields: ['name'], + fields: ['name', 'emailVerified'], include: { relation: 'emailUser', scope: { diff --git a/modules/worker/front/descriptor/index.html b/modules/worker/front/descriptor/index.html index 758f639ff..aa6b80300 100644 --- a/modules/worker/front/descriptor/index.html +++ b/modules/worker/front/descriptor/index.html @@ -11,6 +11,9 @@ ? 'Click to allow the user to be disabled' : 'Click to exclude the user from getting disabled'}} + + Change password +
@@ -72,4 +75,29 @@ - + + + + + + + + + + + + diff --git a/modules/worker/front/descriptor/index.js b/modules/worker/front/descriptor/index.js index 07e16c0d6..fe337974c 100644 --- a/modules/worker/front/descriptor/index.js +++ b/modules/worker/front/descriptor/index.js @@ -1,5 +1,6 @@ import ngModule from '../module'; import Descriptor from 'salix/components/descriptor'; +const UserError = require('vn-loopback/util/user-error'); class Controller extends Descriptor { constructor($element, $, $rootScope) { super($element, $); @@ -12,9 +13,11 @@ class Controller extends Descriptor { set worker(value) { this.entity = value; - if (value) this.getIsExcluded(); + + if (this.entity && !this.entity.user.emailVerified) + this.getPassRequirements(); } getIsExcluded() { @@ -38,7 +41,7 @@ class Controller extends Descriptor { { relation: 'user', scope: { - fields: ['name'], + fields: ['name', 'emailVerified'], include: { relation: 'emailUser', scope: { @@ -66,10 +69,30 @@ class Controller extends Descriptor { } ] }; - + // Añadir filter para sacar user return this.getData(`Workers/${this.id}`, {filter}) .then(res => this.entity = res.data); } + + getPassRequirements() { + this.$http.get('UserPasswords/findOne') + .then(res => { + this.passRequirements = res.data; + }); + } + + setPassword() { + if (!this.newPassword) + throw new UserError(`You must enter a new password`); + if (this.newPassword != this.repeatPassword) + throw new UserError(`Passwords don't match`); + this.$http.patch( + `Workers/${this.entity.id}/setPassword`, + {workerFk: this.entity.id, newPass: this.newPassword} + ) .then(() => { + this.vnApp.showSuccess(this.$translate.instant('Password changed!')); + }); + } } Controller.$inject = ['$element', '$scope', '$rootScope']; diff --git a/modules/worker/front/descriptor/index.spec.js b/modules/worker/front/descriptor/index.spec.js index dfb800415..d158a9e8e 100644 --- a/modules/worker/front/descriptor/index.spec.js +++ b/modules/worker/front/descriptor/index.spec.js @@ -23,4 +23,24 @@ describe('vnWorkerDescriptor', () => { expect(controller.worker).toEqual(response); }); }); + + describe('setPassword()', () => { + it('should throw an error: You must enter a new password', () => { + try { + controller.setPassword(); + } catch (error) { + expect(error.message).toEqual('You must enter a new password'); + } + }); + + it('should throw an error: Passwords don\'t match', () => { + controller.newPassword = 'aaa'; + controller.repeatPassword = 'bbb'; + try { + controller.setPassword(); + } catch (error) { + expect(error.message).toEqual('Passwords don\'t match'); + } + }); + }); }); From 033c02750b48106e25000fb77a35b7b48db7da77 Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 16 Oct 2023 18:24:58 +0200 Subject: [PATCH 229/427] refactor(origin): .origin por getUrl() --- back/methods/collection/getTickets.js | 8 +-- back/models/vn-user.js | 51 +------------------ db/tests/vn/ticketCalculateClon.spec.js | 3 +- loopback/common/methods/application/getUrl.js | 3 +- .../back/methods/claim/createFromSales.js | 6 +-- .../back/methods/claim/regularizeClaim.js | 6 +-- modules/client/back/models/client.js | 21 +++++--- .../client/back/models/credit-insurance.js | 4 +- .../methods/invoiceOut/makePdfAndNotify.js | 4 +- .../ticket/back/methods/sale/deleteSales.js | 6 +-- modules/ticket/back/methods/sale/reserve.js | 10 ++-- .../ticket/back/methods/sale/updatePrice.js | 8 ++- .../back/methods/sale/updateQuantity.js | 7 +-- .../back/methods/ticket-request/confirm.js | 6 +-- .../back/methods/ticket-request/deny.js | 4 +- modules/ticket/back/methods/ticket/addSale.js | 4 +- .../back/methods/ticket/componentUpdate.js | 4 +- modules/ticket/back/methods/ticket/merge.js | 6 +-- modules/ticket/back/methods/ticket/restore.js | 4 +- .../ticket/back/methods/ticket/setDeleted.js | 7 +-- .../back/methods/ticket/updateDiscount.js | 5 +- .../back/methods/worker/createAbsence.js | 4 +- .../back/methods/worker/deleteAbsence.js | 4 +- 23 files changed, 70 insertions(+), 115 deletions(-) diff --git a/back/methods/collection/getTickets.js b/back/methods/collection/getTickets.js index 8509edadf..dbb286b4f 100644 --- a/back/methods/collection/getTickets.js +++ b/back/methods/collection/getTickets.js @@ -45,11 +45,11 @@ module.exports = Self => { i.longName, i.size, ic.color, - o.code url, + o.code origin, ish.packing, ish.grouping, s.isAdded, - s.urlalQuantity, + s.originalQuantity, s.quantity saleQuantity, iss.quantity reservedQuantity, SUM(iss.quantity) OVER (PARTITION BY s.id ORDER BY ish.id) accumulatedQuantity, @@ -73,7 +73,7 @@ module.exports = Self => { LEFT JOIN shelving sh ON sh.code = ish.shelvingFk LEFT JOIN parking p ON p.id = sh.parkingFk LEFT JOIN itemColor ic ON ic.itemFk = s.itemFk - LEFT JOIN url o ON o.id = i.urlFk + LEFT JOIN origin o ON o.id = i.originFk WHERE tc.collectionFk = ? GROUP BY ish.id, p.code, p2.code ORDER BY pickingOrder;`, [id], myOptions); @@ -91,7 +91,7 @@ module.exports = Self => { promises.push(Self.app.models.Chat.send(ctx, observation, $t('The ticket is in preparation', { ticketId: ticketId, - ticketUrl: `${url}/#!/ticket/${ticketId}/summary`, + ticketUrl: `${url}ticket/${ticketId}/summary`, salesPersonId: ticket.salesPersonFk }))); } diff --git a/back/models/vn-user.js b/back/models/vn-user.js index cf210b61b..a38139bc7 100644 --- a/back/models/vn-user.js +++ b/back/models/vn-user.js @@ -1,5 +1,4 @@ const vnModel = require('vn-loopback/common/models/vn-model'); -const LoopBackContext = require('loopback-context'); const {Email} = require('vn-print'); module.exports = function(Self) { @@ -90,11 +89,7 @@ module.exports = function(Self) { }; Self.on('resetPasswordRequest', async function(info) { - const loopBackContext = LoopBackContext.getCurrentContext(); - const httpCtx = {req: loopBackContext.active}; - const httpRequest = httpCtx.req.http.req; - const headers = httpRequest.headers; - const origin = headers.origin; + const url = await Self.app.models.Application.getUrl(); const defaultHash = '/reset-password?access_token=$token$'; const recoverHashes = { @@ -110,7 +105,7 @@ module.exports = function(Self) { const params = { recipient: info.email, lang: user.lang, - url: origin + '/#!' + recoverHash + url: url.slice(0, -1) + recoverHash }; const options = Object.assign({}, info.options); @@ -177,46 +172,4 @@ module.exports = function(Self) { Self.sharedClass._methods.find(method => method.name == 'changePassword').ctor.settings.acls = Self.sharedClass._methods.find(method => method.name == 'changePassword').ctor.settings.acls .filter(acl => acl.property != 'changePassword'); - - // FIXME: https://redmine.verdnatura.es/issues/5761 - // Self.afterRemote('prototype.patchAttributes', async(ctx, instance) => { - // if (!ctx.args || !ctx.args.data.email) return; - - // const loopBackContext = LoopBackContext.getCurrentContext(); - // const httpCtx = {req: loopBackContext.active}; - // const httpRequest = httpCtx.req.http.req; - // const headers = httpRequest.headers; - // const origin = headers.origin; - // const url = origin.split(':'); - - // class Mailer { - // async send(verifyOptions, cb) { - // const params = { - // url: verifyOptions.verifyHref, - // recipient: verifyOptions.to, - // lang: ctx.req.getLocale() - // }; - - // const email = new Email('email-verify', params); - // email.send(); - - // cb(null, verifyOptions.to); - // } - // } - - // const options = { - // type: 'email', - // to: instance.email, - // from: {}, - // redirect: `${origin}/#!/account/${instance.id}/basic-data?emailConfirmed`, - // template: false, - // mailer: new Mailer, - // host: url[1].split('/')[2], - // port: url[2], - // protocol: url[0], - // user: Self - // }; - - // await instance.verify(options); - // }); }; diff --git a/db/tests/vn/ticketCalculateClon.spec.js b/db/tests/vn/ticketCalculateClon.spec.js index 9116d805f..665d52ed0 100644 --- a/db/tests/vn/ticketCalculateClon.spec.js +++ b/db/tests/vn/ticketCalculateClon.spec.js @@ -53,7 +53,8 @@ describe('ticket ticketCalculateClon()', () => { expect(result[orderIndex][0].ticketFk).toBeGreaterThan(newestTicketIdInFixtures); }); - it('should add the ticket to the order containing the original ticket and generate landed value if it was null', async() => { + it('should add the ticket to the order containing the original ' + + 'ticket and generate landed value if it was null', async() => { let stmts = []; let stmt; diff --git a/loopback/common/methods/application/getUrl.js b/loopback/common/methods/application/getUrl.js index 57aed0b84..4e51b0776 100644 --- a/loopback/common/methods/application/getUrl.js +++ b/loopback/common/methods/application/getUrl.js @@ -18,7 +18,8 @@ module.exports = Self => { } }); Self.getUrl = async(appName = 'salix') => { - const {url} = Self.app.models.Url.findOne({ + const {url} = await Self.app.models.Url.findOne({ + where: { appName, enviroment: process.env.NODE_ENV || 'development' diff --git a/modules/claim/back/methods/claim/createFromSales.js b/modules/claim/back/methods/claim/createFromSales.js index 07bdb30aa..7ea26f9cc 100644 --- a/modules/claim/back/methods/claim/createFromSales.js +++ b/modules/claim/back/methods/claim/createFromSales.js @@ -94,13 +94,13 @@ module.exports = Self => { const salesPerson = ticket.client().salesPersonUser(); if (salesPerson) { - const origin = ctx.req.headers.origin; + const url = await Self.app.models.Application.getUrl(); const message = $t('Created claim', { claimId: newClaim.id, ticketId: ticketId, - ticketUrl: `${origin}/#!/ticket/${ticketId}/sale`, - claimUrl: `${origin}/#!/claim/${newClaim.id}/summary`, + ticketUrl: `${url}/ticket/${ticketId}/sale`, + claimUrl: `${url}/claim/${newClaim.id}/summary`, changes: changesMade }); await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message); diff --git a/modules/claim/back/methods/claim/regularizeClaim.js b/modules/claim/back/methods/claim/regularizeClaim.js index 672c94947..4ac500e2f 100644 --- a/modules/claim/back/methods/claim/regularizeClaim.js +++ b/modules/claim/back/methods/claim/regularizeClaim.js @@ -56,15 +56,15 @@ module.exports = Self => { const salesPerson = sale.ticket().client().salesPersonUser(); if (salesPerson) { const nickname = address && address.nickname || destination.description; - const origin = ctx.req.headers.origin; + const url = await Self.app.models.Application.getUrl(); const message = $t('Sent units from ticket', { quantity: sale.quantity, concept: sale.concept, itemId: sale.itemFk, ticketId: sale.ticketFk, nickname: nickname, - ticketUrl: `${origin}/#!/ticket/${sale.ticketFk}/sale`, - itemUrl: `${origin}/#!/item/${sale.itemFk}/summary` + ticketUrl: `${url}ticket/${sale.ticketFk}/sale`, + itemUrl: `${url}item/${sale.itemFk}/summary` }); await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message); } diff --git a/modules/client/back/models/client.js b/modules/client/back/models/client.js index 8e720484f..1b60b1329 100644 --- a/modules/client/back/models/client.js +++ b/modules/client/back/models/client.js @@ -250,7 +250,12 @@ module.exports = Self => { const loopBackContext = LoopBackContext.getCurrentContext(); const accessToken = {req: loopBackContext.active.accessToken}; - const editVerifiedDataWithoutTaxDataChecked = models.ACL.checkAccessAcl(accessToken, 'Client', 'editVerifiedDataWithoutTaxDataCheck', 'WRITE'); + const editVerifiedDataWithoutTaxDataChecked = models.ACL.checkAccessAcl( + accessToken, + 'Client', + 'editVerifiedDataWithoutTaxDataCheck', + 'WRITE' + ); const hasChanges = orgData && changes; const isTaxDataChecked = hasChanges && (changes.isTaxDataChecked || orgData.isTaxDataChecked); @@ -263,7 +268,9 @@ module.exports = Self => { const sageTransactionTypeChanged = hasChanges && orgData.sageTransactionTypeFk != sageTransactionType; const cantEditVerifiedData = isTaxDataCheckedChanged && !editVerifiedDataWithoutTaxDataChecked; - const cantChangeSageData = (sageTaxTypeChanged || sageTransactionTypeChanged) && !editVerifiedDataWithoutTaxDataChecked; + const cantChangeSageData = (sageTaxTypeChanged || + sageTransactionTypeChanged + ) && !editVerifiedDataWithoutTaxDataChecked; if (cantEditVerifiedData || cantChangeSageData) throw new UserError(`You don't have enough privileges`); @@ -346,8 +353,7 @@ module.exports = Self => { const httpCtx = {req: loopBackContext.active}; const httpRequest = httpCtx.req.http.req; const $t = httpRequest.__; - const headers = httpRequest.headers; - const origin = headers.origin; + const url = await Self.app.models.Application.getUrl(); const salesPersonId = instance.salesPersonFk; @@ -366,7 +372,7 @@ module.exports = Self => { await email.send(); } - const fullUrl = `${origin}/#!/client/${instance.id}/billing-data`; + const fullUrl = `${url}client/${instance.id}/billing-data`; const message = $t('Changed client paymethod', { clientId: instance.id, clientName: instance.name, @@ -389,8 +395,7 @@ module.exports = Self => { const httpCtx = {req: loopBackContext.active}; const httpRequest = httpCtx.req.http.req; const $t = httpRequest.__; - const headers = httpRequest.headers; - const origin = headers.origin; + const url = await Self.app.models.Application.getUrl(); const models = Self.app.models; let previousWorker = {name: $t('None')}; @@ -411,7 +416,7 @@ module.exports = Self => { currentWorker.name = worker && worker.user().nickname; } - const fullUrl = `${origin}/#!/client/${client.id}/basic-data`; + const fullUrl = `${url}client/${client.id}/basic-data`; const message = $t('Client assignment has changed', { clientId: client.id, clientName: client.name, diff --git a/modules/client/back/models/credit-insurance.js b/modules/client/back/models/credit-insurance.js index 6f656d382..619904612 100644 --- a/modules/client/back/models/credit-insurance.js +++ b/modules/client/back/models/credit-insurance.js @@ -57,8 +57,8 @@ module.exports = function(Self) { const httpRequest = httpCtx.req.http.req; const $t = httpRequest.__; - const origin = httpRequest.headers.origin; - const fullPath = `${origin}/#!/client/${client.id}/credit-insurance/index`; + const url = await Self.app.models.Application.getUrl(); + const fullPath = `${url}client/${client.id}/credit-insurance/index`; const message = $t('MESSAGE_INSURANCE_CHANGE', { clientId: client.id, clientName: client.name, diff --git a/modules/invoiceOut/back/methods/invoiceOut/makePdfAndNotify.js b/modules/invoiceOut/back/methods/invoiceOut/makePdfAndNotify.js index a48664b30..49c785013 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/makePdfAndNotify.js +++ b/modules/invoiceOut/back/methods/invoiceOut/makePdfAndNotify.js @@ -59,10 +59,10 @@ module.exports = Self => { }; await Self.invoiceEmail(ctx, ref); } catch (err) { - const origin = ctx.req.headers.origin; + const url = await Self.app.models.Application.getUrl(); const message = ctx.req.__('Mail not sent', { clientId: client.id, - clientUrl: `${origin}/#!/claim/${id}/summary` + clientUrl: `${url}claim/${id}/summary` }); const salesPersonId = client.salesPersonFk; diff --git a/modules/ticket/back/methods/sale/deleteSales.js b/modules/ticket/back/methods/sale/deleteSales.js index 5d1463a66..c71f8d5e1 100644 --- a/modules/ticket/back/methods/sale/deleteSales.js +++ b/modules/ticket/back/methods/sale/deleteSales.js @@ -1,5 +1,3 @@ -let UserError = require('vn-loopback/util/user-error'); - module.exports = Self => { Self.remoteMethodCtx('deleteSales', { description: 'Deletes the selected sales', @@ -70,11 +68,11 @@ module.exports = Self => { const salesPerson = ticket.client().salesPersonUser(); if (salesPerson) { - const origin = ctx.req.headers.origin; + const url = await Self.app.models.Application.getUrl(); const message = $t('Deleted sales from ticket', { ticketId: ticketId, - ticketUrl: `${origin}/#!/ticket/${ticketId}/sale`, + ticketUrl: `${url}ticket/${ticketId}/sale`, deletions: deletions }); await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message, myOptions); diff --git a/modules/ticket/back/methods/sale/reserve.js b/modules/ticket/back/methods/sale/reserve.js index 2dc368af6..b111a0458 100644 --- a/modules/ticket/back/methods/sale/reserve.js +++ b/modules/ticket/back/methods/sale/reserve.js @@ -1,6 +1,3 @@ - -let UserError = require('vn-loopback/util/user-error'); - module.exports = Self => { Self.remoteMethodCtx('reserve', { description: 'Change the state of a ticket', @@ -65,7 +62,8 @@ module.exports = Self => { promises.push(reservedSale); - changesMade += `\r\n-${sale.itemFk}: ${sale.concept} (${sale.quantity}) ${$t('State')}: ${$t(oldState)} ➔ *${$t(newState)}*`; + changesMade += `\r\n-${sale.itemFk}: ${sale.concept} (${sale.quantity}) + ${$t('State')}: ${$t(oldState)} ➔ *${$t(newState)}*`; } } @@ -87,11 +85,11 @@ module.exports = Self => { const salesPerson = ticket.client().salesPersonUser(); if (salesPerson) { - const origin = ctx.req.headers.origin; + const url = await Self.app.models.Application.getUrl(); const message = $t('Changed sale reserved state', { ticketId: ticketId, - ticketUrl: `${origin}/#!/ticket/${ticketId}/sale`, + ticketUrl: `${url}ticket/${ticketId}/sale`, changes: changesMade }); await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message, myOptions); diff --git a/modules/ticket/back/methods/sale/updatePrice.js b/modules/ticket/back/methods/sale/updatePrice.js index 62e4ebd42..3cae2a333 100644 --- a/modules/ticket/back/methods/sale/updatePrice.js +++ b/modules/ticket/back/methods/sale/updatePrice.js @@ -1,5 +1,3 @@ -let UserError = require('vn-loopback/util/user-error'); - module.exports = Self => { Self.remoteMethodCtx('updatePrice', { description: 'Changes the price of a sale', @@ -100,7 +98,7 @@ module.exports = Self => { const salesPerson = sale.ticket().client().salesPersonUser(); if (salesPerson) { - const origin = ctx.req.headers.origin; + const url = await Self.app.models.Application.getUrl(); const message = $t('Changed sale price', { ticketId: sale.ticket().id, itemId: sale.itemFk, @@ -108,8 +106,8 @@ module.exports = Self => { quantity: sale.quantity, oldPrice: oldPrice, newPrice: newPrice, - ticketUrl: `${origin}/#!/ticket/${sale.ticket().id}/sale`, - itemUrl: `${origin}/#!/item/${sale.itemFk}/summary` + ticketUrl: `${url}ticket/${sale.ticket().id}/sale`, + itemUrl: `${url}item/${sale.itemFk}/summary` }); await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message, myOptions); } diff --git a/modules/ticket/back/methods/sale/updateQuantity.js b/modules/ticket/back/methods/sale/updateQuantity.js index 3cbd9255f..27c1f529e 100644 --- a/modules/ticket/back/methods/sale/updateQuantity.js +++ b/modules/ticket/back/methods/sale/updateQuantity.js @@ -80,15 +80,16 @@ module.exports = Self => { const salesPerson = sale.ticket().client().salesPersonUser(); if (salesPerson) { - const url = await models.Application.getUrl(); + const url = await Self.app.models.Application.getUrl(); + console.log(url); const message = $t('Changed sale quantity', { ticketId: sale.ticket().id, itemId: sale.itemFk, concept: sale.concept, oldQuantity: oldQuantity, newQuantity: newQuantity, - ticketUrl: `${url}/ticket/${sale.ticket().id}/sale`, - itemUrl: `${url}/item/${sale.itemFk}/summary` + ticketUrl: `${url}ticket/${sale.ticket().id}/sale`, + itemUrl: `${url}item/${sale.itemFk}/summary` }); await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message, myOptions); diff --git a/modules/ticket/back/methods/ticket-request/confirm.js b/modules/ticket/back/methods/ticket-request/confirm.js index 9cd7f4d68..a69fc7fd7 100644 --- a/modules/ticket/back/methods/ticket-request/confirm.js +++ b/modules/ticket/back/methods/ticket-request/confirm.js @@ -84,7 +84,7 @@ module.exports = Self => { const query = `CALL vn.sale_calculateComponent(?, NULL)`; await Self.rawSql(query, [sale.id], myOptions); - const origin = ctx.req.headers.origin; + const url = await Self.app.models.Application.getUrl(); const requesterId = request.requesterFk; const message = $t('Bought units from buy request', { @@ -92,8 +92,8 @@ module.exports = Self => { concept: sale.concept, itemId: sale.itemFk, ticketId: sale.ticketFk, - url: `${origin}/#!/ticket/${sale.ticketFk}/summary`, - urlItem: `${origin}/#!/item/${sale.itemFk}/summary` + url: `${url}ticket/${sale.ticketFk}/summary`, + urlItem: `${url}item/${sale.itemFk}/summary` }); await models.Chat.sendCheckingPresence(ctx, requesterId, message, myOptions); diff --git a/modules/ticket/back/methods/ticket-request/deny.js b/modules/ticket/back/methods/ticket-request/deny.js index 92f020083..9ec11d755 100644 --- a/modules/ticket/back/methods/ticket-request/deny.js +++ b/modules/ticket/back/methods/ticket-request/deny.js @@ -50,12 +50,12 @@ module.exports = Self => { const request = await Self.app.models.TicketRequest.findById(ctx.args.id, null, myOptions); await request.updateAttributes(params, myOptions); - const origin = ctx.req.headers.origin; + const url = await Self.app.models.Application.getUrl(); const requesterId = request.requesterFk; const message = $t('Deny buy request', { ticketId: request.ticketFk, - url: `${origin}/#!/ticket/${request.ticketFk}/request/index`, + url: `${url}ticket/${request.ticketFk}/request/index`, observation: params.response }); diff --git a/modules/ticket/back/methods/ticket/addSale.js b/modules/ticket/back/methods/ticket/addSale.js index cbf884273..29e49d8e6 100644 --- a/modules/ticket/back/methods/ticket/addSale.js +++ b/modules/ticket/back/methods/ticket/addSale.js @@ -94,11 +94,11 @@ module.exports = Self => { const salesPerson = ticket.client().salesPersonUser(); if (salesPerson) { - const origin = ctx.req.headers.origin; + const url = await Self.app.models.Application.getUrl(); const message = $t('Added sale to ticket', { ticketId: id, - ticketUrl: `${origin}/#!/ticket/${id}/sale`, + ticketUrl: `${url}ticket/${id}/sale`, addition: addition }); await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message); diff --git a/modules/ticket/back/methods/ticket/componentUpdate.js b/modules/ticket/back/methods/ticket/componentUpdate.js index 8aad8959b..fc8b3a40c 100644 --- a/modules/ticket/back/methods/ticket/componentUpdate.js +++ b/modules/ticket/back/methods/ticket/componentUpdate.js @@ -237,7 +237,7 @@ module.exports = Self => { const salesPersonId = originalTicket.client().salesPersonFk; if (salesPersonId) { - const origin = ctx.req.headers.origin; + const url = await Self.app.models.Application.getUrl(); let changesMade = ''; for (let change in newProperties) { @@ -249,7 +249,7 @@ module.exports = Self => { const message = $t('Changed this data from the ticket', { ticketId: args.id, - ticketUrl: `${origin}/#!/ticket/${args.id}/sale`, + ticketUrl: `${url}ticket/${args.id}/sale`, changes: changesMade }); await models.Chat.sendCheckingPresence(ctx, salesPersonId, message); diff --git a/modules/ticket/back/methods/ticket/merge.js b/modules/ticket/back/methods/ticket/merge.js index 3c0da077f..19c7f9fa0 100644 --- a/modules/ticket/back/methods/ticket/merge.js +++ b/modules/ticket/back/methods/ticket/merge.js @@ -25,7 +25,7 @@ module.exports = Self => { Self.merge = async(ctx, tickets, options) => { const httpRequest = ctx.req; const $t = httpRequest.__; - const origin = httpRequest.headers.origin; + const url = await Self.app.models.Application.getUrl(); const models = Self.app.models; const myOptions = {}; let tx; @@ -40,8 +40,8 @@ module.exports = Self => { try { for (let ticket of tickets) { - const originFullPath = `${origin}/#!/ticket/${ticket.originId}/summary`; - const destinationFullPath = `${origin}/#!/ticket/${ticket.destinationId}/summary`; + const originFullPath = `${url}ticket/${ticket.originId}/summary`; + const destinationFullPath = `${url}ticket/${ticket.destinationId}/summary`; const message = $t('Ticket merged', { originDated: dateUtil.toString(new Date(ticket.originShipped)), destinationDated: dateUtil.toString(new Date(ticket.destinationShipped)), diff --git a/modules/ticket/back/methods/ticket/restore.js b/modules/ticket/back/methods/ticket/restore.js index 722c3294e..0aaef0418 100644 --- a/modules/ticket/back/methods/ticket/restore.js +++ b/modules/ticket/back/methods/ticket/restore.js @@ -48,10 +48,10 @@ module.exports = Self => { // Send notification to salesPerson const salesPersonId = ticket.client().salesPersonFk; if (salesPersonId) { - const origin = ctx.req.headers.origin; + const url = await Self.app.models.Application.getUrl(); const message = $t(`I have restored the ticket id`, { id: id, - url: `${origin}/#!/ticket/${id}/summary` + url: `${url}ticket/${id}/summary` }); await models.Chat.sendCheckingPresence(ctx, salesPersonId, message); } diff --git a/modules/ticket/back/methods/ticket/setDeleted.js b/modules/ticket/back/methods/ticket/setDeleted.js index fcd9972fe..a6fd295f1 100644 --- a/modules/ticket/back/methods/ticket/setDeleted.js +++ b/modules/ticket/back/methods/ticket/setDeleted.js @@ -119,10 +119,10 @@ module.exports = Self => { // Send notification to salesPerson const salesPersonUser = ticket.client().salesPersonUser(); if (salesPersonUser && sales.length) { - const origin = ctx.req.headers.origin; + const url = await Self.app.models.Application.getUrl(); const message = $t(`I have deleted the ticket id`, { id: id, - url: `${origin}/#!/ticket/${id}/summary` + url: `${url}ticket/${id}/summary` }); await models.Chat.send(ctx, `@${salesPersonUser.name}`, message); } @@ -146,7 +146,8 @@ module.exports = Self => { JOIN vn.sectorCollection sc ON sc.id = scsg.sectorCollectionFk JOIN vn.saleGroupDetail sgd ON sgd.saleGroupFk = sg.id JOIN vn.sale s ON s.id = sgd.saleFk - WHERE s.ticketFk = ?;`, [ticket.id], myOptions); + WHERE s.ticketFk = ?;`, [ticket.id], myOptions + ); if (tx) await tx.commit(); diff --git a/modules/ticket/back/methods/ticket/updateDiscount.js b/modules/ticket/back/methods/ticket/updateDiscount.js index e092ee4ed..05ade4f01 100644 --- a/modules/ticket/back/methods/ticket/updateDiscount.js +++ b/modules/ticket/back/methods/ticket/updateDiscount.js @@ -165,11 +165,10 @@ module.exports = Self => { const salesPerson = ticket.client().salesPersonUser(); if (salesPerson) { - const origin = ctx.req.headers.origin; - + const url = await Self.app.models.Application.getUrl(); const message = $t('Changed sale discount', { ticketId: id, - ticketUrl: `${origin}/#!/ticket/${id}/sale`, + ticketUrl: `${url}ticket/${id}/sale`, changes: changesMade }); await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message, myOptions); diff --git a/modules/worker/back/methods/worker/createAbsence.js b/modules/worker/back/methods/worker/createAbsence.js index cb2cf8330..10992f91f 100644 --- a/modules/worker/back/methods/worker/createAbsence.js +++ b/modules/worker/back/methods/worker/createAbsence.js @@ -109,13 +109,13 @@ module.exports = Self => { const absenceType = await models.AbsenceType.findById(args.absenceTypeId, null, myOptions); const account = await models.VnUser.findById(userId, null, myOptions); const subordinated = await models.VnUser.findById(id, null, myOptions); - const origin = ctx.req.headers.origin; + const url = await Self.app.models.Application.getUrl(); const body = $t('Created absence', { author: account.nickname, employee: subordinated.nickname, absenceType: absenceType.name, dated: formatDate(args.dated), - workerUrl: `${origin}/#!/worker/${id}/calendar` + workerUrl: `${url}worker/${id}/calendar` }); await models.Mail.create({ subject: $t('Absence change notification on the labour calendar'), diff --git a/modules/worker/back/methods/worker/deleteAbsence.js b/modules/worker/back/methods/worker/deleteAbsence.js index c315f5178..2912e6db4 100644 --- a/modules/worker/back/methods/worker/deleteAbsence.js +++ b/modules/worker/back/methods/worker/deleteAbsence.js @@ -60,13 +60,13 @@ module.exports = Self => { const absenceType = await models.AbsenceType.findById(absence.dayOffTypeFk, null, myOptions); const account = await models.VnUser.findById(userId, null, myOptions); const subordinated = await models.VnUser.findById(labour.workerFk, null, myOptions); - const origin = ctx.req.headers.origin; + const url = await Self.app.models.Application.getUrl(); const body = $t('Deleted absence', { author: account.nickname, employee: subordinated.nickname, absenceType: absenceType.name, dated: formatDate(absence.dated), - workerUrl: `${origin}/#!/worker/${id}/calendar` + workerUrl: `${url}worker/${id}/calendar` }); await models.Mail.create({ subject: $t('Absence change notification on the labour calendar'), From afe4c676fc0a254f26795d15477fa1059b99891d Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 16 Oct 2023 18:38:33 +0200 Subject: [PATCH 230/427] =?UTF-8?q?fix(url):=20la=20ulr=20termina=20con=20?= =?UTF-8?q?/=20no=20es=20necesario=20a=C3=B1adir=20el=20texto?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- modules/claim/back/methods/claim/claimPickupEmail.js | 2 +- modules/claim/back/methods/claim/createFromSales.js | 4 ++-- modules/claim/back/methods/claim/updateClaim.js | 7 +++---- 3 files changed, 6 insertions(+), 7 deletions(-) diff --git a/modules/claim/back/methods/claim/claimPickupEmail.js b/modules/claim/back/methods/claim/claimPickupEmail.js index f4cd0fc20..5f3326099 100644 --- a/modules/claim/back/methods/claim/claimPickupEmail.js +++ b/modules/claim/back/methods/claim/claimPickupEmail.js @@ -69,7 +69,7 @@ module.exports = Self => { const message = $t('Claim pickup order sent', { claimId: args.id, clientName: claim.client().name, - claimUrl: `${url}/claim/${args.id}/summary`, + claimUrl: `${url}claim/${args.id}/summary`, }); console.log(message); const salesPersonId = claim.client().salesPersonFk; diff --git a/modules/claim/back/methods/claim/createFromSales.js b/modules/claim/back/methods/claim/createFromSales.js index 7ea26f9cc..24ba74c6d 100644 --- a/modules/claim/back/methods/claim/createFromSales.js +++ b/modules/claim/back/methods/claim/createFromSales.js @@ -99,8 +99,8 @@ module.exports = Self => { const message = $t('Created claim', { claimId: newClaim.id, ticketId: ticketId, - ticketUrl: `${url}/ticket/${ticketId}/sale`, - claimUrl: `${url}/claim/${newClaim.id}/summary`, + ticketUrl: `${url}ticket/${ticketId}/sale`, + claimUrl: `${url}claim/${newClaim.id}/summary`, changes: changesMade }); await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message); diff --git a/modules/claim/back/methods/claim/updateClaim.js b/modules/claim/back/methods/claim/updateClaim.js index b7ffa9ff5..b5c576440 100644 --- a/modules/claim/back/methods/claim/updateClaim.js +++ b/modules/claim/back/methods/claim/updateClaim.js @@ -121,22 +121,21 @@ module.exports = Self => { const message = $t(`Claim state has changed to ${state}`, { claimId: claim.id, clientName: claim.client().name, - claimUrl: `${url}/claim/${claim.id}/summary` + claimUrl: `${url}claim/${claim.id}/summary` }); await models.Chat.sendCheckingPresence(ctx, workerId, message); } async function notifyPickUp(ctx, workerId, claim) { const models = Self.app.models; - const url = await models.Application.getUrl(); + const url = await models.Application.getUrl('lilium'); const $t = ctx.req.__; // $translate const message = $t('Claim will be picked', { claimId: claim.id, clientName: claim.client().name, - claimUrl: `${url}/claim/${claim.id}/summary` + claimUrl: `${url}claim/${claim.id}/summary` }); - console.log(message); await models.Chat.sendCheckingPresence(ctx, workerId, message); } }; From 4f911e644c4f03086cfcb03469fc10096b8edaa8 Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 16 Oct 2023 18:43:03 +0200 Subject: [PATCH 231/427] fix: remove console.log refs #5979 --- modules/claim/back/methods/claim/claimPickupEmail.js | 1 - modules/ticket/back/methods/sale/updateQuantity.js | 1 - 2 files changed, 2 deletions(-) diff --git a/modules/claim/back/methods/claim/claimPickupEmail.js b/modules/claim/back/methods/claim/claimPickupEmail.js index 5f3326099..aea571a61 100644 --- a/modules/claim/back/methods/claim/claimPickupEmail.js +++ b/modules/claim/back/methods/claim/claimPickupEmail.js @@ -71,7 +71,6 @@ module.exports = Self => { clientName: claim.client().name, claimUrl: `${url}claim/${args.id}/summary`, }); - console.log(message); const salesPersonId = claim.client().salesPersonFk; if (salesPersonId) await models.Chat.sendCheckingPresence(ctx, salesPersonId, message); diff --git a/modules/ticket/back/methods/sale/updateQuantity.js b/modules/ticket/back/methods/sale/updateQuantity.js index 27c1f529e..acccc6c2f 100644 --- a/modules/ticket/back/methods/sale/updateQuantity.js +++ b/modules/ticket/back/methods/sale/updateQuantity.js @@ -81,7 +81,6 @@ module.exports = Self => { const salesPerson = sale.ticket().client().salesPersonUser(); if (salesPerson) { const url = await Self.app.models.Application.getUrl(); - console.log(url); const message = $t('Changed sale quantity', { ticketId: sale.ticket().id, itemId: sale.itemFk, From 48003b5d03541ef7e19a8e703dc5609bbc3647b2 Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 17 Oct 2023 08:28:15 +0200 Subject: [PATCH 232/427] ref #6138 --- modules/worker/front/descriptor/index.js | 1 - 1 file changed, 1 deletion(-) diff --git a/modules/worker/front/descriptor/index.js b/modules/worker/front/descriptor/index.js index fe337974c..13ffa6f2f 100644 --- a/modules/worker/front/descriptor/index.js +++ b/modules/worker/front/descriptor/index.js @@ -69,7 +69,6 @@ class Controller extends Descriptor { } ] }; - // Añadir filter para sacar user return this.getData(`Workers/${this.id}`, {filter}) .then(res => this.entity = res.data); } From d4770c525ef1d0e27095cbe46e64fca3c58b7c7d Mon Sep 17 00:00:00 2001 From: alexm Date: Tue, 17 Oct 2023 11:00:41 +0200 Subject: [PATCH 233/427] refs #6199 test(sale): fix test --- .../collection/spec/setSaleQuantity.spec.js | 1 + .../methods/sale/specs/updateQuantity.spec.js | 52 +++++++++++++++++-- modules/ticket/back/models/sale.js | 2 +- 3 files changed, 49 insertions(+), 6 deletions(-) diff --git a/back/methods/collection/spec/setSaleQuantity.spec.js b/back/methods/collection/spec/setSaleQuantity.spec.js index fdc1bce1a..8cd73205f 100644 --- a/back/methods/collection/spec/setSaleQuantity.spec.js +++ b/back/methods/collection/spec/setSaleQuantity.spec.js @@ -18,6 +18,7 @@ describe('setSaleQuantity()', () => { it('should change quantity sale', async() => { const tx = await models.Ticket.beginTransaction({}); + spyOn(models.Item, 'getVisibleAvailable').and.returnValue((new Promise(resolve => resolve({available: 100})))); try { const options = {transaction: tx}; diff --git a/modules/ticket/back/methods/sale/specs/updateQuantity.spec.js b/modules/ticket/back/methods/sale/specs/updateQuantity.spec.js index 6bf0a0d7e..0fde997fa 100644 --- a/modules/ticket/back/methods/sale/specs/updateQuantity.spec.js +++ b/modules/ticket/back/methods/sale/specs/updateQuantity.spec.js @@ -1,3 +1,5 @@ +/* eslint max-len: ["error", { "code": 150 }]*/ + const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); @@ -31,6 +33,7 @@ describe('sale updateQuantity()', () => { } }; spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); + spyOn(models.Item, 'getVisibleAvailable').and.returnValue((new Promise(resolve => resolve({available: 100})))); const tx = await models.Sale.beginTransaction({}); @@ -38,7 +41,7 @@ describe('sale updateQuantity()', () => { try { const options = {transaction: tx}; - await models.Sale.updateQuantity(ctx, 17, 99, options); + await models.Sale.updateQuantity(ctx, 17, 31, options); await tx.rollback(); } catch (e) { @@ -50,9 +53,6 @@ describe('sale updateQuantity()', () => { }); it('should add quantity if the quantity is greater than it should be and is role advanced', async() => { - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(9)); - - const tx = await models.Sale.beginTransaction({}); const saleId = 17; const buyerId = 35; const ctx = { @@ -62,6 +62,9 @@ describe('sale updateQuantity()', () => { __: () => {} } }; + const tx = await models.Sale.beginTransaction({}); + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(buyerId)); + spyOn(models.Item, 'getVisibleAvailable').and.returnValue((new Promise(resolve => resolve({available: 100})))); try { const options = {transaction: tx}; @@ -169,7 +172,14 @@ describe('sale updateQuantity()', () => { }); it('should throw an error if the quantity is less than the minimum quantity of the item', async() => { - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(9)); + const ctx = { + req: { + accessToken: {userId: 1}, + headers: {origin: 'localhost:5000'}, + __: () => {} + } + }; + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); const tx = await models.Sale.beginTransaction({}); const itemId = 2; @@ -194,4 +204,36 @@ describe('sale updateQuantity()', () => { expect(error).toEqual(new Error('The amount cannot be less than the minimum')); }); + + it('should change quantity if has minimum quantity and new quantity is equal than item available', async() => { + const ctx = { + req: { + accessToken: {userId: 1}, + headers: {origin: 'localhost:5000'}, + __: () => {} + } + }; + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); + + const tx = await models.Sale.beginTransaction({}); + const itemId = 2; + const saleId = 17; + const minQuantity = 30; + const newQuantity = minQuantity - 1; + + try { + const options = {transaction: tx}; + + const item = await models.Item.findById(itemId, null, options); + await item.updateAttribute('minQuantity', minQuantity, options); + spyOn(models.Item, 'getVisibleAvailable').and.returnValue((new Promise(resolve => resolve({available: newQuantity})))); + + await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); }); diff --git a/modules/ticket/back/models/sale.js b/modules/ticket/back/models/sale.js index 378ff3490..fe6307270 100644 --- a/modules/ticket/back/models/sale.js +++ b/modules/ticket/back/models/sale.js @@ -75,7 +75,7 @@ module.exports = Self => { ctx.options ); - const oldQuantity = instance?.quantity; + const oldQuantity = instance?.quantity ?? null; const quantityAdded = newQuantity - oldQuantity; if (itemInfo.available < quantityAdded) throw new UserError(`This item is not available`); From 9870a0e60adfd6bb82bfeece882a706087a5b810 Mon Sep 17 00:00:00 2001 From: pablone Date: Tue, 17 Oct 2023 13:56:49 +0200 Subject: [PATCH 234/427] feat(origin): create method url_/geturl redf #5979 --- back/methods/chat/sendCheckingPresence.js | 24 +++++++++++-------- back/models/chat.js | 9 +++++-- loopback/common/models/application.json | 5 ++++ .../methods/claim/specs/updateClaim.spec.js | 9 +++---- .../claim/back/methods/claim/updateClaim.js | 5 +++- 5 files changed, 35 insertions(+), 17 deletions(-) diff --git a/back/methods/chat/sendCheckingPresence.js b/back/methods/chat/sendCheckingPresence.js index 274ec3a5b..0bae87a35 100644 --- a/back/methods/chat/sendCheckingPresence.js +++ b/back/methods/chat/sendCheckingPresence.js @@ -25,22 +25,24 @@ module.exports = Self => { }); Self.sendCheckingPresence = async(ctx, recipientId, message) => { + console.log('recipientId: ', recipientId); if (!recipientId) return false; - const models = Self.app.models; - const userId = ctx.req.accessToken.userId; - const sender = await models.VnUser.findById(userId, {fields: ['id']}); - const recipient = await models.VnUser.findById(recipientId, null); + console.log('sender: ', ctx.req.accessToken.userId); + const sender = ctx.req.accessToken.userId; + console.log('sender: ', sender); + const recipient = recipientId; + console.log('recipient: ', recipient); + + console.log('recipientId == sender: ', recipientId == sender); // Prevent sending messages to yourself - if (recipientId == userId) return false; - + if (recipientId == sender) return false; if (!recipient) - throw new Error(`Could not send message "${message}" to worker id ${recipientId} from user ${userId}`); - + throw new Error(`Could not send message "${message}" to worker id ${recipientId} from user ${sender}`); if (process.env.NODE_ENV == 'test') - message = `[Test:Environment to user ${userId}] ` + message; - + message = `[Test:Environment to user ${sender}] ` + message; + console.log('chat create'); const chat = await models.Chat.create({ senderFk: sender.id, recipient: `@${recipient.name}`, @@ -51,6 +53,8 @@ module.exports = Self => { attempts: 0 }); + console.log('chat: '); + try { await Self.sendCheckingUserStatus(chat); await Self.updateChat(chat, 'sent'); diff --git a/back/models/chat.js b/back/models/chat.js index a18edbd3f..240ec2c26 100644 --- a/back/models/chat.js +++ b/back/models/chat.js @@ -6,6 +6,10 @@ module.exports = Self => { require('../methods/chat/sendQueued')(Self); Self.observe('before save', async function(ctx) { + console.log('chat start 1'); + + console.log('ctx.isNewInstance: ', ctx.isNewInstance); + console.log('message: ', ctx.instance); if (!ctx.isNewInstance) return; let {message} = ctx.instance; @@ -13,14 +17,15 @@ module.exports = Self => { const parts = message.match(/(?<=\[)[a-zA-Z0-9_\-+!@#$%^&*()={};':"\\|,.<>/?\s]*(?=])/g); if (!parts) return; - + console.log('chat start 2'); const replacedParts = parts.map(part => { return part.replace(/[!$%^&*()={};':"\\,.<>/?]/g, ''); }); - + console.log('chat start 3'); for (const [index, part] of parts.entries()) message = message.replace(part, replacedParts[index]); ctx.instance.message = message; + console.log('chat end'); }); }; diff --git a/loopback/common/models/application.json b/loopback/common/models/application.json index 6343c3421..cf0653fbb 100644 --- a/loopback/common/models/application.json +++ b/loopback/common/models/application.json @@ -19,6 +19,11 @@ "principalType": "ROLE", "principalId": "$everyone", "permission": "ALLOW" + },{ + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" } ] } diff --git a/modules/claim/back/methods/claim/specs/updateClaim.spec.js b/modules/claim/back/methods/claim/specs/updateClaim.spec.js index d367fb89f..e7be8e9c6 100644 --- a/modules/claim/back/methods/claim/specs/updateClaim.spec.js +++ b/modules/claim/back/methods/claim/specs/updateClaim.spec.js @@ -2,7 +2,9 @@ const app = require('vn-loopback/server/server'); const LoopBackContext = require('loopback-context'); describe('Update Claim', () => { + let url; beforeAll(async() => { + url = await app.models.Application.getUrl(); const activeCtx = { accessToken: {userId: 9}, http: { @@ -29,7 +31,6 @@ describe('Update Claim', () => { it(`should throw an error as the user doesn't have rights`, async() => { const tx = await app.models.Claim.beginTransaction({}); - let error; try { @@ -61,7 +62,7 @@ describe('Update Claim', () => { expect(error.message).toEqual(`You don't have enough privileges to change that field`); }); - it(`should success to update the claimState to 'canceled' and send a rocket message`, async() => { + fit(`should success to update the claimState to 'canceled' and send a rocket message`, async() => { const tx = await app.models.Claim.beginTransaction({}); try { @@ -77,7 +78,7 @@ describe('Update Claim', () => { const ctx = { req: { accessToken: {userId: claimManagerId}, - headers: {origin: 'http://localhost'} + headers: {origin: url} }, args: { observation: 'valid observation', @@ -118,7 +119,7 @@ describe('Update Claim', () => { const ctx = { req: { accessToken: {userId: claimManagerId}, - headers: {origin: 'http://localhost'} + headers: {origin: url} }, args: { observation: 'valid observation', diff --git a/modules/claim/back/methods/claim/updateClaim.js b/modules/claim/back/methods/claim/updateClaim.js index b5c576440..534f0c7ab 100644 --- a/modules/claim/back/methods/claim/updateClaim.js +++ b/modules/claim/back/methods/claim/updateClaim.js @@ -92,7 +92,6 @@ module.exports = Self => { // When hasToPickUp has been changed if (salesPerson && changedHasToPickUp && updatedClaim.hasToPickUp) notifyPickUp(ctx, salesPerson.id, claim); - // When claimState has been changed if (args.claimStateFk) { const newState = await models.ClaimState.findById(args.claimStateFk, null, myOptions); @@ -123,6 +122,7 @@ module.exports = Self => { clientName: claim.client().name, claimUrl: `${url}claim/${claim.id}/summary` }); + console.log(`${url}claim/${claim.id}/summary`); await models.Chat.sendCheckingPresence(ctx, workerId, message); } @@ -136,6 +136,9 @@ module.exports = Self => { clientName: claim.client().name, claimUrl: `${url}claim/${claim.id}/summary` }); + console.log('url', `${url}claim/${claim.id}/summary`); + console.log('claim client', claim.client().name); + console.log('claim id', claim.id); await models.Chat.sendCheckingPresence(ctx, workerId, message); } }; From 69a54be1a9fe4e6e858f1837d249b8dc1d92cb4b Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 17 Oct 2023 14:02:08 +0200 Subject: [PATCH 235/427] ref #5947 refactorWorkerCreate --- modules/worker/back/methods/worker/new.js | 23 ++++++++++------------- modules/worker/back/models/worker.json | 6 ++++++ 2 files changed, 16 insertions(+), 13 deletions(-) diff --git a/modules/worker/back/methods/worker/new.js b/modules/worker/back/methods/worker/new.js index 199a3be62..5316daf01 100644 --- a/modules/worker/back/methods/worker/new.js +++ b/modules/worker/back/methods/worker/new.js @@ -223,19 +223,16 @@ module.exports = Self => { const user = await models.VnUser.findById(client.id, null, myOptions); await user.updateAttribute('email', args.email, myOptions); - await models.Worker.rawSql( - 'CALL vn.workerCreate(?, ?, ?, ?, ?, ?, ?)', - [ - args.firstName, - args.lastNames, - args.code, - args.bossFk, - client.id, - args.fi, - args.birth, - ], - myOptions - ); + await models.Worker.create({ + id: client.id, + code: args.code, + firstName: args.firstName, + lastName: args.lastNames, + bossFk: args.bossFk, + fi: args.fi, + birth: args.birth, + + }, myOptions); if (tx) await tx.commit(); } catch (error) { diff --git a/modules/worker/back/models/worker.json b/modules/worker/back/models/worker.json index ea4aecf67..1a777fffe 100644 --- a/modules/worker/back/models/worker.json +++ b/modules/worker/back/models/worker.json @@ -48,6 +48,12 @@ "locker": { "type" : "number" }, + "fi": { + "type" : "string" + }, + "birth": { + "type" : "date" + }, "isF11Allowed": { "type" : "boolean" } From fdfa481d212eccb7eb28891e3fcdcabbc0a86193 Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 17 Oct 2023 14:52:47 +0200 Subject: [PATCH 236/427] ref #5947 drop procedure --- db/changes/234201/00-dropWorkerCreate.sql | 1 + 1 file changed, 1 insertion(+) create mode 100644 db/changes/234201/00-dropWorkerCreate.sql diff --git a/db/changes/234201/00-dropWorkerCreate.sql b/db/changes/234201/00-dropWorkerCreate.sql new file mode 100644 index 000000000..be2761c3d --- /dev/null +++ b/db/changes/234201/00-dropWorkerCreate.sql @@ -0,0 +1 @@ +DROP PROCEDURE IF EXISTS vn.workerCreate; \ No newline at end of file From 8d44bb8867f159f3cc3d648d0025e112a6f79fe4 Mon Sep 17 00:00:00 2001 From: pablone Date: Tue, 17 Oct 2023 15:05:48 +0200 Subject: [PATCH 237/427] =?UTF-8?q?refactor(toggleIsIcluded):=20actualizo?= =?UTF-8?q?=20la=20versi=C3=B3n=20y=20modifico=20el=20proc=20refs=20#5749?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../{232401 => 234201}/00-zoneIncluded.sql | 7 +++--- .../back/methods/zone/toggleIsIncluded.js | 24 +++++++++---------- 2 files changed, 14 insertions(+), 17 deletions(-) rename db/changes/{232401 => 234201}/00-zoneIncluded.sql (83%) diff --git a/db/changes/232401/00-zoneIncluded.sql b/db/changes/234201/00-zoneIncluded.sql similarity index 83% rename from db/changes/232401/00-zoneIncluded.sql rename to db/changes/234201/00-zoneIncluded.sql index 592350629..12d4058cf 100644 --- a/db/changes/232401/00-zoneIncluded.sql +++ b/db/changes/234201/00-zoneIncluded.sql @@ -13,15 +13,14 @@ DROP TRIGGER IF EXISTS `vn`.`zoneIncluded_afterDelete`; USE `vn`; DELIMITER $$ -$$ -CREATE DEFINER=`root`@`localhost` TRIGGER `vn`.`zoneIncluded_afterDelete` +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`zoneIncluded_afterDelete` AFTER DELETE ON `zoneIncluded` FOR EACH ROW BEGIN INSERT INTO zoneLog SET `action` = 'delete', - `changedModel` = 'ZoneIncluded', - `changedModelId` = OLD.id, + `changedModel` = 'zoneIncluded', + `changedModelId` = OLD.zoneFk, `userFk` = account.myUser_getId(); END$$ DELIMITER ; diff --git a/modules/zone/back/methods/zone/toggleIsIncluded.js b/modules/zone/back/methods/zone/toggleIsIncluded.js index 06532e5c0..98c64c4a0 100644 --- a/modules/zone/back/methods/zone/toggleIsIncluded.js +++ b/modules/zone/back/methods/zone/toggleIsIncluded.js @@ -30,23 +30,21 @@ module.exports = Self => { Self.toggleIsIncluded = async(id, geoId, isIncluded, options) => { const models = Self.app.models; const myOptions = {}; - if (typeof options == 'object') Object.assign(myOptions, options); if (isIncluded === undefined) return models.ZoneIncluded.destroyAll({zoneFk: id, geoFk: geoId}, myOptions); - else { - const zoneIncluded = await models.ZoneIncluded.findOne({where: {zoneFk: id, geoFk: geoId}}, myOptions); - if (zoneIncluded) - return zoneIncluded.updateAttribute('isIncluded', isIncluded, myOptions); - else { - return models.ZoneIncluded.create({ - zoneFk: id, - geoFk: geoId, - isIncluded: isIncluded - }, myOptions); - } - } + + const zoneIncluded = await models.ZoneIncluded.findOne({where: {zoneFk: id, geoFk: geoId}}, myOptions); + + if (zoneIncluded) + return zoneIncluded.updateAttribute('isIncluded', isIncluded, myOptions); + + return models.ZoneIncluded.create({ + zoneFk: id, + geoFk: geoId, + isIncluded: isIncluded + }, myOptions); }; }; From b3c7511e59277a081e8cc2480ed36bf6aeff1fc8 Mon Sep 17 00:00:00 2001 From: alexm Date: Wed, 18 Oct 2023 08:52:06 +0200 Subject: [PATCH 238/427] refs #6067 feat(url): getByUser --- back/methods/url/getByUser.js | 40 +++++++++++++++++++++++ back/methods/url/specs/getByUser.spec.js | 19 +++++++++++ back/models/url.js | 3 ++ back/models/url.json | 9 +---- back/models/vn-user.js | 4 +-- db/changes/234201/00-aclUrlHedera.sql | 6 ++-- modules/worker/back/methods/worker/new.js | 1 - 7 files changed, 67 insertions(+), 15 deletions(-) create mode 100644 back/methods/url/getByUser.js create mode 100644 back/methods/url/specs/getByUser.spec.js create mode 100644 back/models/url.js diff --git a/back/methods/url/getByUser.js b/back/methods/url/getByUser.js new file mode 100644 index 000000000..dd4805182 --- /dev/null +++ b/back/methods/url/getByUser.js @@ -0,0 +1,40 @@ +module.exports = function(Self) { + Self.remoteMethod('getByUser', { + description: 'returns the starred modules for the current user', + accessType: 'READ', + accepts: [{ + arg: 'userId', + type: 'number', + description: 'The user id', + required: true, + http: {source: 'path'} + }], + returns: { + type: 'object', + root: true + }, + http: { + path: `/:userId/get-by-user`, + verb: 'GET' + } + }); + + Self.getByUser = async userId => { + const models = Self.app.models; + const appNames = ['hedera']; + const filter = { + fields: ['appName', 'url'], + where: { + appName: {inq: appNames}, + environment: process.env.NODE_ENV ?? 'development', + } + }; + + const isWorker = await models.Account.findById(userId, {fields: ['id']}); + if (!isWorker) + return models.Url.find(filter); + + appNames.push('salix'); + return models.Url.find(filter); + }; +}; diff --git a/back/methods/url/specs/getByUser.spec.js b/back/methods/url/specs/getByUser.spec.js new file mode 100644 index 000000000..f6af6ec00 --- /dev/null +++ b/back/methods/url/specs/getByUser.spec.js @@ -0,0 +1,19 @@ +const {models} = require('vn-loopback/server/server'); + +describe('getByUser()', () => { + const worker = 1; + const notWorker = 2; + it(`should return only hedera url if not is worker`, async() => { + const urls = await models.Url.getByUser(notWorker); + + expect(urls.length).toEqual(1); + expect(urls[0].appName).toEqual('hedera'); + }); + + it(`should return more than hedera url`, async() => { + const urls = await models.Url.getByUser(worker); + + expect(urls.length).toBeGreaterThan(1); + expect(urls.find(url => url.appName == 'salix').appName).toEqual('salix'); + }); +}); diff --git a/back/models/url.js b/back/models/url.js new file mode 100644 index 000000000..216d149ba --- /dev/null +++ b/back/models/url.js @@ -0,0 +1,3 @@ +module.exports = Self => { + require('../methods/url/getByUser')(Self); +}; diff --git a/back/models/url.json b/back/models/url.json index 13f50b099..8610ff28b 100644 --- a/back/models/url.json +++ b/back/models/url.json @@ -21,12 +21,5 @@ "type": "string", "required": true } - }, - "acls": [{ - "accessType": "READ", - "principalType": "ROLE", - "principalId": "$everyone", - "permission": "ALLOW" - }] - + } } diff --git a/back/models/vn-user.js b/back/models/vn-user.js index 8e9b59aab..66af807b8 100644 --- a/back/models/vn-user.js +++ b/back/models/vn-user.js @@ -222,7 +222,6 @@ module.exports = function(Self) { ]} }); - const isWorker = instance.isWorker || await Self.app.models.Account.findById(instance.id, null, ctx.options); class Mailer { async send(verifyOptions, cb) { const params = { @@ -236,11 +235,12 @@ module.exports = function(Self) { cb(null, verifyOptions.to); } } + console.log('instance.id', instance.id); const options = { type: 'email', to: newEmail, from: {}, - redirect: `${liliumUrl.url}verifyEmail?isWorker=${!!isWorker}`, + redirect: `${liliumUrl.url}verifyEmail?userId=${instance.id}`, template: false, mailer: new Mailer, host: url[1].split('/')[2], diff --git a/db/changes/234201/00-aclUrlHedera.sql b/db/changes/234201/00-aclUrlHedera.sql index 0d38a2ae8..79d9fb4c8 100644 --- a/db/changes/234201/00-aclUrlHedera.sql +++ b/db/changes/234201/00-aclUrlHedera.sql @@ -3,7 +3,5 @@ INSERT INTO `salix`.`url` (`appName`, `environment`, `url`) ('hedera', 'test', 'https://test-shop.verdnatura.es/'), ('hedera', 'production', 'https://shop.verdnatura.es/'); -DELETE FROM `salix`.`ACL` - WHERE model = 'Url' - AND 'accessType' = 'READ' - AND principalId = 'employee'; +INSERT INTO `salix`.`ACL` ( model, property, accessType, permission, principalType, principalId) + VALUES('Url', 'getByUser', 'READ', 'ALLOW', 'ROLE', '$everyone'); diff --git a/modules/worker/back/methods/worker/new.js b/modules/worker/back/methods/worker/new.js index 7c8978ec6..199a3be62 100644 --- a/modules/worker/back/methods/worker/new.js +++ b/modules/worker/back/methods/worker/new.js @@ -155,7 +155,6 @@ module.exports = Self => { password: randomPassword.password, email: args.email, roleFk: workerConfig.roleFk, - isWorker: true // to verifyEmail }, myOptions ); From b1c931a510674e856731a2f0409f856c8a1a7188 Mon Sep 17 00:00:00 2001 From: alexm Date: Wed, 18 Oct 2023 08:52:17 +0200 Subject: [PATCH 239/427] remove console.log --- back/models/vn-user.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/back/models/vn-user.js b/back/models/vn-user.js index 66af807b8..d7f54521f 100644 --- a/back/models/vn-user.js +++ b/back/models/vn-user.js @@ -235,7 +235,7 @@ module.exports = function(Self) { cb(null, verifyOptions.to); } } - console.log('instance.id', instance.id); + const options = { type: 'email', to: newEmail, From d1cb2a1d9a0ca13861b7c704391a789ebe39db35 Mon Sep 17 00:00:00 2001 From: alexm Date: Wed, 18 Oct 2023 10:30:36 +0200 Subject: [PATCH 240/427] refs #5918 test: add updateWorkerTimeControlMail --- .../specs/updateWorkerTimeControlMail.spec.js | 103 ++++++++++++++++++ modules/worker/front/time-control/index.html | 6 +- 2 files changed, 106 insertions(+), 3 deletions(-) create mode 100644 modules/worker/back/methods/worker-time-control/specs/updateWorkerTimeControlMail.spec.js diff --git a/modules/worker/back/methods/worker-time-control/specs/updateWorkerTimeControlMail.spec.js b/modules/worker/back/methods/worker-time-control/specs/updateWorkerTimeControlMail.spec.js new file mode 100644 index 000000000..e51021024 --- /dev/null +++ b/modules/worker/back/methods/worker-time-control/specs/updateWorkerTimeControlMail.spec.js @@ -0,0 +1,103 @@ +const models = require('vn-loopback/server/server').models; + +describe('workerTimeControl getMailStates()', () => { + it('should update WorkerTimeControlMail if exist record', async() => { + const tx = await models.WorkerTimeControlMail.beginTransaction({}); + const args = { + workerId: 9, + week: 50, + year: 2000, + state: 'CONFIRMED' + }; + const ctx = {args}; + + try { + const options = {transaction: tx}; + const beforeMail = await models.WorkerTimeControlMail.findOne({ + where: { + workerFk: args.workerId, + year: args.year, + week: args.week, + } + }, options); + await models.WorkerTimeControl.updateWorkerTimeControlMail(ctx, options); + const afterMail = await models.WorkerTimeControlMail.findOne({ + where: { + workerFk: args.workerId, + year: args.year, + week: args.week, + } + }, options); + + expect(beforeMail.state).toEqual('SENDED'); + expect(afterMail.state).toEqual(args.state); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('should insert WorkerTimeControlMail if exist record', async() => { + const tx = await models.WorkerTimeControlMail.beginTransaction({}); + const args = { + workerId: 1, + week: 51, + year: 2000, + state: 'SENDED' + }; + const ctx = {args}; + + try { + const options = {transaction: tx}; + const beforeMail = await models.WorkerTimeControlMail.find({ + where: { + workerFk: args.workerId, + year: args.year, + week: args.week, + } + }, options); + await models.WorkerTimeControl.updateWorkerTimeControlMail(ctx, options); + const afterMail = await models.WorkerTimeControlMail.find({ + where: { + workerFk: args.workerId, + year: args.year, + week: args.week, + } + }, options); + + expect(beforeMail).toEqual([]); + expect(afterMail.length).toEqual(1); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('should throw error if not exist any record in this week', async() => { + const tx = await models.WorkerTimeControlMail.beginTransaction({}); + const ctx = {args: { + workerId: 1, + week: 1, + year: 0, + state: 'SENDED' + }}; + + let error; + try { + const options = {transaction: tx}; + await models.WorkerTimeControl.updateWorkerTimeControlMail(ctx, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error.message).toEqual(`There aren't records for this week`); + }); +}); + diff --git a/modules/worker/front/time-control/index.html b/modules/worker/front/time-control/index.html index ce8a66356..f147b759b 100644 --- a/modules/worker/front/time-control/index.html +++ b/modules/worker/front/time-control/index.html @@ -98,11 +98,11 @@ ng-click="reason.show()"> + vn-tooltip="{{$ctrl.state ? 'Resend' : 'Send'}} email of this week to the user" + ng-if="$ctrl.isHr && $ctrl.state != 'CONFIRMED' && $ctrl.canResend">
From 4300b24c1437a7fe78c20e2919da755720eae276 Mon Sep 17 00:00:00 2001 From: alexm Date: Wed, 18 Oct 2023 10:45:15 +0200 Subject: [PATCH 241/427] refs #5918 refactor(worker_timeControl): simplify ng-show --- .../specs/updateWorkerTimeControlMail.spec.js | 2 +- modules/worker/front/time-control/index.html | 36 ++++++++++--------- 2 files changed, 20 insertions(+), 18 deletions(-) diff --git a/modules/worker/back/methods/worker-time-control/specs/updateWorkerTimeControlMail.spec.js b/modules/worker/back/methods/worker-time-control/specs/updateWorkerTimeControlMail.spec.js index e51021024..3b5b2b73f 100644 --- a/modules/worker/back/methods/worker-time-control/specs/updateWorkerTimeControlMail.spec.js +++ b/modules/worker/back/methods/worker-time-control/specs/updateWorkerTimeControlMail.spec.js @@ -1,6 +1,6 @@ const models = require('vn-loopback/server/server').models; -describe('workerTimeControl getMailStates()', () => { +describe('updateWorkerTimeControlMail()', () => { it('should update WorkerTimeControlMail if exist record', async() => { const tx = await models.WorkerTimeControlMail.beginTransaction({}); const args = { diff --git a/modules/worker/front/time-control/index.html b/modules/worker/front/time-control/index.html index f147b759b..c34a1e3ca 100644 --- a/modules/worker/front/time-control/index.html +++ b/modules/worker/front/time-control/index.html @@ -80,23 +80,25 @@ - - - - - - +
+ + + + + + +
Date: Wed, 18 Oct 2023 12:04:37 +0200 Subject: [PATCH 242/427] refs 6199 add quantityLessThanMin translation --- loopback/locale/es.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/loopback/locale/es.json b/loopback/locale/es.json index d34c97d21..dd3c92378 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -320,5 +320,6 @@ "Ticket without Route": "Ticket sin ruta", "Booking completed": "Reserva completada", "The ticket is in preparation": "El ticket [{{ticketId}}]({{{ticketUrl}}}) del comercial {{salesPersonId}} está en preparación", - "The amount cannot be less than the minimum": "La cantidad no puede ser menor que la cantidad mímina" + "The amount cannot be less than the minimum": "La cantidad no puede ser menor que la cantidad mímina", + "quantityLessThanMin": "La cantidad no puede ser menor que la cantidad mímina" } From 251d71a437e37f32380e56f12573b191012ed728 Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 18 Oct 2023 12:05:33 +0200 Subject: [PATCH 243/427] ref #5417 refactor transactions --- modules/client/back/methods/client/transactions.js | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) diff --git a/modules/client/back/methods/client/transactions.js b/modules/client/back/methods/client/transactions.js index d08df4ab6..a643d69f4 100644 --- a/modules/client/back/methods/client/transactions.js +++ b/modules/client/back/methods/client/transactions.js @@ -12,22 +12,18 @@ module.exports = Self => { arg: 'filter', type: 'object', description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string', - http: {source: 'query'} }, { arg: 'orderFk', type: 'number', - http: {source: 'query'} }, { arg: 'clientFk', type: 'number', - http: {source: 'query'} }, { arg: 'amount', type: 'number', - http: {source: 'query'} }, { arg: 'from', @@ -48,19 +44,15 @@ module.exports = Self => { } }); - Self.transactions = async(ctx, filter, options) => { - const args = ctx.args; + Self.transactions = async(ctx, filter, orderFk, clientFk, amount, from, to, options) => { const myOptions = {}; if (typeof options == 'object') Object.assign(myOptions, options); - if (ctx.args && args.to) { - const dateTo = args.to; - dateTo.setHours(23, 59, 59, 999); - } + if (to) to.setHours(23, 59, 59, 999); - const where = buildFilter(args, (param, value) => { + const where = buildFilter({orderFk, clientFk, amount, from, to}, (param, value) => { switch (param) { case 'orderFk': return {'t.id': value}; From 5f49a4fe1d3e8eb9b5edca9c33515c7aa189aa6b Mon Sep 17 00:00:00 2001 From: pablone Date: Wed, 18 Oct 2023 12:24:35 +0200 Subject: [PATCH 244/427] fix: created -> shipped refs #6266 --- modules/ticket/front/descriptor/locale/es.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/ticket/front/descriptor/locale/es.yml b/modules/ticket/front/descriptor/locale/es.yml index e1006bed4..b809c1b83 100644 --- a/modules/ticket/front/descriptor/locale/es.yml +++ b/modules/ticket/front/descriptor/locale/es.yml @@ -4,7 +4,7 @@ Show pallet report: Ver hoja de pallet Change shipped hour: Cambiar hora de envío Shipped hour: Hora de envío Make a payment: "Verdnatura le comunica:\rSu pedido está pendiente de pago.\rPor favor, entre en la página web y efectúe el pago con tarjeta.\rMuchas gracias." -Minimum is needed: "Verdnatura le recuerda:\rEs necesario un importe mínimo de 50€ (Sin IVA) en su pedido {{ticketId}} del día {{created | date: 'dd/MM/yyyy'}} para recibirlo sin portes adicionales." +Minimum is needed: "Verdnatura le recuerda:\rEs necesario un importe mínimo de 50€ (Sin IVA) en su pedido {{ticketId}} del día {{shipped | date: 'dd/MM/yyyy'}} para recibirlo sin portes adicionales." Ticket invoiced: Ticket facturado Make invoice: Crear factura Regenerate invoice PDF: Regenerar PDF factura From 2bb4300e1b26d3a344e58b3ab39d1e8dabb8bc54 Mon Sep 17 00:00:00 2001 From: pablone Date: Wed, 18 Oct 2023 12:35:45 +0200 Subject: [PATCH 245/427] remove: se quita el console log refs #6278 --- db/changes/234201/00-alterTableTicketRequest.sql | 1 - modules/ticket/back/methods/ticket-request/filter.js | 2 -- 2 files changed, 3 deletions(-) delete mode 100644 db/changes/234201/00-alterTableTicketRequest.sql diff --git a/db/changes/234201/00-alterTableTicketRequest.sql b/db/changes/234201/00-alterTableTicketRequest.sql deleted file mode 100644 index 2a08137b9..000000000 --- a/db/changes/234201/00-alterTableTicketRequest.sql +++ /dev/null @@ -1 +0,0 @@ -ALTER TABLE `vn`.`ticketRequest` MODIFY COLUMN `itemFk` double DEFAULT NULL NOT NULL; diff --git a/modules/ticket/back/methods/ticket-request/filter.js b/modules/ticket/back/methods/ticket-request/filter.js index 47e571988..10aaf02e5 100644 --- a/modules/ticket/back/methods/ticket-request/filter.js +++ b/modules/ticket/back/methods/ticket-request/filter.js @@ -161,8 +161,6 @@ module.exports = Self => { LEFT JOIN account.user ua2 ON ua2.id = tr.requesterFk`); stmt.merge(conn.makeSuffix(filter)); - console.log(stmt); - return conn.executeStmt(stmt, myOptions); }; }; From 330fb08aac7ca8578bcdcd86e41930f911701f01 Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 18 Oct 2023 13:23:00 +0200 Subject: [PATCH 246/427] ref #5417 fix back test --- .../methods/client/specs/transactions.spec.js | 64 +++++++++++++++---- 1 file changed, 52 insertions(+), 12 deletions(-) diff --git a/modules/client/back/methods/client/specs/transactions.spec.js b/modules/client/back/methods/client/specs/transactions.spec.js index 679eb196c..54e088929 100644 --- a/modules/client/back/methods/client/specs/transactions.spec.js +++ b/modules/client/back/methods/client/specs/transactions.spec.js @@ -1,15 +1,24 @@ const models = require('vn-loopback/server/server').models; describe('Client transactions', () => { + const ctx = {}; + it('should call transactions() method to receive a list of Web Payments from BRUCE WAYNE', async() => { const tx = await models.Client.beginTransaction({}); - try { const options = {transaction: tx}; - const ctx = {}; const filter = {where: {clientFk: 1101}}; - const result = await models.Client.transactions(ctx, filter, options); + const result = await models.Client.transactions( + ctx, + filter, + undefined, + undefined, + undefined, + undefined, + undefined, + options + ); expect(result[1].id).toBeTruthy(); @@ -26,9 +35,17 @@ describe('Client transactions', () => { try { const options = {transaction: tx}; - const ctx = {args: {orderFk: 6}}; const filter = {}; - const result = await models.Client.transactions(ctx, filter, options); + const result = await models.Client.transactions( + ctx, + filter, + 6, + undefined, + undefined, + undefined, + undefined, + options + ); const firstRow = result[0]; @@ -47,10 +64,17 @@ describe('Client transactions', () => { try { const options = {transaction: tx}; - - const ctx = {args: {amount: 40}}; const filter = {}; - const result = await models.Client.transactions(ctx, filter, options); + const result = await models.Client.transactions( + ctx, + filter, + undefined, + undefined, + 40, + undefined, + undefined, + options + ); const randomIndex = Math.floor(Math.random() * result.length); const transaction = result[randomIndex]; @@ -69,14 +93,30 @@ describe('Client transactions', () => { try { const options = {transaction: tx}; - const ctx = {args: {from: '2000/12/31'}}; const filter = {}; - const withResults = await models.Client.transactions(ctx, filter, options); + const withResults = await models.Client.transactions( + ctx, + filter, + undefined, + undefined, + undefined, + '2000/12/31', + undefined, + options + ); expect(withResults.length).toEqual(6); - ctx.args.from = '2099/12/31'; - const noResults = await models.Client.transactions(ctx, filter, options); + const noResults = await models.Client.transactions( + ctx, + filter, + undefined, + undefined, + undefined, + '2099/12/31', + undefined, + options + ); expect(noResults.length).toEqual(0); From 44ce0a87304a2d1e83c31890482ff343d9e2a8eb Mon Sep 17 00:00:00 2001 From: jgallego Date: Wed, 18 Oct 2023 13:46:41 +0200 Subject: [PATCH 247/427] refs #6312 no inserta el originalquantity --- modules/ticket/back/methods/ticket/transferSales.js | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/modules/ticket/back/methods/ticket/transferSales.js b/modules/ticket/back/methods/ticket/transferSales.js index 1124f7ec7..a2e92d524 100644 --- a/modules/ticket/back/methods/ticket/transferSales.js +++ b/modules/ticket/back/methods/ticket/transferSales.js @@ -138,14 +138,15 @@ module.exports = Self => { // Update original sale const rest = originalSale.quantity - sale.quantity; query = `UPDATE sale - SET quantity = ? + SET quantity = ?, + originalQuantity = ? WHERE id = ?`; - await Self.rawSql(query, [rest, sale.id], options); + await Self.rawSql(query, [rest, rest, sale.id], options); // Clone sale with new quantity - query = `INSERT INTO sale (itemFk, ticketFk, concept, quantity, originalQuantity, price, discount, priceFixed, + query = `INSERT INTO sale (itemFk, ticketFk, concept, quantity, price, discount, priceFixed, reserved, isPicked, isPriceFixed, isAdded) - SELECT itemFk, ?, concept, ?, originalQuantity, price, discount, priceFixed, + SELECT itemFk, ?, concept, ?, price, discount, priceFixed, reserved, isPicked, isPriceFixed, isAdded FROM sale WHERE id = ?`; From da20697052b71c724ab99abf1d798246288a4435 Mon Sep 17 00:00:00 2001 From: alexm Date: Wed, 18 Oct 2023 15:19:26 +0200 Subject: [PATCH 248/427] refs #6199 feat(sale_updateQuantity): can upload --- .../05-ticket/01-sale/02_edit_sale.spec.js | 2 +- loopback/locale/en.json | 4 +- loopback/locale/es.json | 2 +- .../methods/sale/specs/updateQuantity.spec.js | 2 +- modules/ticket/back/models/sale.js | 47 ++++++++++++++----- 5 files changed, 39 insertions(+), 18 deletions(-) diff --git a/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js b/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js index 6264073f6..b89254dda 100644 --- a/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js +++ b/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js @@ -139,7 +139,7 @@ describe('Ticket Edit sale path', () => { await page.type(selectors.ticketSales.firstSaleQuantity, '11\u000d'); const message = await page.waitForSnackbar(); - expect(message.text).toContain('The new quantity should be smaller than the old one'); + expect(message.text).toContain('The price of the item changed'); }); it('should remove 1 from the first sale quantity', async() => { diff --git a/loopback/locale/en.json b/loopback/locale/en.json index f61226e9e..8dfed66f6 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -14,7 +14,7 @@ "The default consignee can not be unchecked": "The default consignee can not be unchecked", "Enter an integer different to zero": "Enter an integer different to zero", "Package cannot be blank": "Package cannot be blank", - "The new quantity should be smaller than the old one": "The new quantity should be smaller than the old one", + "The price of the item changed": "The price of the item changed", "The sales of this ticket can't be modified": "The sales of this ticket can't be modified", "Cannot check Equalization Tax in this NIF/CIF": "Cannot check Equalization Tax in this NIF/CIF", "You can't create an order for a frozen client": "You can't create an order for a frozen client", @@ -191,4 +191,4 @@ "Booking completed": "Booking complete", "The ticket is in preparation": "The ticket [{{ticketId}}]({{{ticketUrl}}}) of the sales person {{salesPersonId}} is in preparation", "You can only add negative amounts in refund tickets": "You can only add negative amounts in refund tickets" -} \ No newline at end of file +} diff --git a/loopback/locale/es.json b/loopback/locale/es.json index dd3c92378..525e3806f 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -35,7 +35,7 @@ "The grade must be an integer greater than or equal to zero": "El grade debe ser un entero mayor o igual a cero", "Sample type cannot be blank": "El tipo de plantilla no puede quedar en blanco", "Description cannot be blank": "Se debe rellenar el campo de texto", - "The new quantity should be smaller than the old one": "La nueva cantidad debe de ser menor que la anterior", + "The price of the item changed": "El precio del artículo cambió", "The value should not be greater than 100%": "El valor no debe de ser mayor de 100%", "The value should be a number": "El valor debe ser un numero", "This order is not editable": "Esta orden no se puede modificar", diff --git a/modules/ticket/back/methods/sale/specs/updateQuantity.spec.js b/modules/ticket/back/methods/sale/specs/updateQuantity.spec.js index 0fde997fa..74be352d1 100644 --- a/modules/ticket/back/methods/sale/specs/updateQuantity.spec.js +++ b/modules/ticket/back/methods/sale/specs/updateQuantity.spec.js @@ -49,7 +49,7 @@ describe('sale updateQuantity()', () => { error = e; } - expect(error).toEqual(new Error('The new quantity should be smaller than the old one')); + expect(error).toEqual(new Error('The price of the item changed')); }); it('should add quantity if the quantity is greater than it should be and is role advanced', async() => { diff --git a/modules/ticket/back/models/sale.js b/modules/ticket/back/models/sale.js index fe6307270..c1b3f3990 100644 --- a/modules/ticket/back/models/sale.js +++ b/modules/ticket/back/models/sale.js @@ -35,7 +35,7 @@ module.exports = Self => { const ticket = await models.Ticket.findById( ticketId, { - fields: ['id', 'clientFk', 'warehouseFk', 'shipped'], + fields: ['id', 'clientFk', 'warehouseFk', 'addressFk', 'agencyModeFk', 'shipped', 'landed'], include: { relation: 'client', scope: { @@ -68,25 +68,46 @@ module.exports = Self => { if (item.family == 'EMB') return; - const itemInfo = await models.Item.getVisibleAvailable( - itemId, - ticket.warehouseFk, - ticket.shipped, - ctx.options - ); + if (newQuantity < item.minQuantity) + throw new UserError('The amount cannot be less than the minimum'); const oldQuantity = instance?.quantity ?? null; const quantityAdded = newQuantity - oldQuantity; - if (itemInfo.available < quantityAdded) - throw new UserError(`This item is not available`); if (await models.ACL.checkAccessAcl(ctx, 'Ticket', 'isRoleAdvanced', '*')) return; - if (newQuantity < item.minQuantity && itemInfo.available != newQuantity) - throw new UserError('The amount cannot be less than the minimum'); + if (ctx.isNewInstance || newQuantity <= oldQuantity) return; - if (!ctx.isNewInstance && newQuantity > oldQuantity) - throw new UserError('The new quantity should be smaller than the old one'); + await Self.rawSql(`CALL catalog_calcFromItem(?,?,?,?)`, [ + ticket.landed, + ticket.addressFk, + ticket.agencyModeFk, + itemId + ], + ctx.options); + + const [itemInfo] = await Self.rawSql(`SELECT available FROM tmp.ticketCalculateItem`, null, ctx.options); + if (itemInfo?.available < quantityAdded) + throw new UserError(`This item is not available`); + + const [saleGrouping] = await Self.rawSql(` + SELECT MAX(t.grouping), t.price newPrice + FROM tmp.ticketComponentPrice t + WHERE t.grouping <= ?`, + [quantityAdded], + ctx.options); + + await Self.rawSql(` + DROP TEMPORARY TABLE + tmp.ticketCalculateItem, + tmp.ticketComponentPrice, + tmp.ticketComponent, + tmp.ticketLot, + tmp.zoneGetShipped; + `, null, ctx.options); + + if (!saleGrouping?.newPrice || instance.price < saleGrouping.newPrice) + throw new UserError('The price of the item changed'); }); }; From 4d3d38ebe301bdd62a7cc252ab7bbbb8cba7a3ce Mon Sep 17 00:00:00 2001 From: alexm Date: Wed, 18 Oct 2023 15:22:04 +0200 Subject: [PATCH 249/427] 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 488181e1b63593ba03de4a1adb15dcbf9a0ce9e1 Mon Sep 17 00:00:00 2001 From: pablone Date: Thu, 19 Oct 2023 08:37:28 +0200 Subject: [PATCH 250/427] =?UTF-8?q?feat(getUrl):=20se=20a=C3=B1ade=20el=20?= =?UTF-8?q?metodo=20getUrl=20refs=20#5979?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- back/methods/collection/getTickets.js | 2 +- .../methods/application => back/methods/url}/getUrl.js | 8 +++++--- back/models/url.js | 3 +++ back/models/vn-user.js | 2 +- loopback/common/models/application.js | 1 - modules/claim/back/methods/claim/claimPickupEmail.js | 2 +- modules/claim/back/methods/claim/createFromSales.js | 2 +- modules/claim/back/methods/claim/regularizeClaim.js | 2 +- .../claim/back/methods/claim/specs/updateClaim.spec.js | 2 +- modules/claim/back/methods/claim/updateClaim.js | 4 ++-- modules/client/back/models/client.js | 4 ++-- modules/client/back/models/credit-insurance.js | 2 +- .../back/methods/invoiceOut/makePdfAndNotify.js | 2 +- modules/ticket/back/methods/sale/deleteSales.js | 2 +- modules/ticket/back/methods/sale/reserve.js | 2 +- modules/ticket/back/methods/sale/updatePrice.js | 2 +- modules/ticket/back/methods/sale/updateQuantity.js | 2 +- modules/ticket/back/methods/ticket-request/confirm.js | 2 +- modules/ticket/back/methods/ticket-request/deny.js | 2 +- modules/ticket/back/methods/ticket/addSale.js | 2 +- modules/ticket/back/methods/ticket/componentUpdate.js | 2 +- modules/ticket/back/methods/ticket/merge.js | 2 +- modules/ticket/back/methods/ticket/restore.js | 2 +- modules/ticket/back/methods/ticket/setDeleted.js | 2 +- modules/ticket/back/methods/ticket/updateDiscount.js | 2 +- modules/worker/back/methods/worker/createAbsence.js | 2 +- modules/worker/back/methods/worker/deleteAbsence.js | 2 +- 27 files changed, 34 insertions(+), 30 deletions(-) rename {loopback/common/methods/application => back/methods/url}/getUrl.js (79%) create mode 100644 back/models/url.js diff --git a/back/methods/collection/getTickets.js b/back/methods/collection/getTickets.js index dbb286b4f..82fbaf8b8 100644 --- a/back/methods/collection/getTickets.js +++ b/back/methods/collection/getTickets.js @@ -26,7 +26,7 @@ module.exports = Self => { Self.getTickets = async(ctx, id, print, options) => { const userId = ctx.req.accessToken.userId; - const url = Self.app.models.Application.getUrl(); + const url = Self.app.models.Url.getUrl(); const $t = ctx.req.__; const myOptions = {}; diff --git a/loopback/common/methods/application/getUrl.js b/back/methods/url/getUrl.js similarity index 79% rename from loopback/common/methods/application/getUrl.js rename to back/methods/url/getUrl.js index 4e51b0776..f258503b1 100644 --- a/loopback/common/methods/application/getUrl.js +++ b/back/methods/url/getUrl.js @@ -1,9 +1,10 @@ module.exports = Self => { - Self.remoteMethodCtx('getUrl', { + Self.remoteMethod('getUrl', { description: 'Returns the colling app name', + accessType: 'READ', accepts: [ { - arg: 'appName', + arg: 'app', type: 'string', required: false } @@ -18,13 +19,14 @@ module.exports = Self => { } }); Self.getUrl = async(appName = 'salix') => { + console.log('appName: ', appName); const {url} = await Self.app.models.Url.findOne({ - where: { appName, enviroment: process.env.NODE_ENV || 'development' } }); + console.log('url: ', url); return url; }; }; diff --git a/back/models/url.js b/back/models/url.js new file mode 100644 index 000000000..af71ec1c4 --- /dev/null +++ b/back/models/url.js @@ -0,0 +1,3 @@ +module.exports = Self => { + require('../methods/url/getUrl')(Self); +}; diff --git a/back/models/vn-user.js b/back/models/vn-user.js index a38139bc7..c65c62590 100644 --- a/back/models/vn-user.js +++ b/back/models/vn-user.js @@ -89,7 +89,7 @@ module.exports = function(Self) { }; Self.on('resetPasswordRequest', async function(info) { - const url = await Self.app.models.Application.getUrl(); + const url = await Self.app.models.Url.getUrl(); const defaultHash = '/reset-password?access_token=$token$'; const recoverHashes = { diff --git a/loopback/common/models/application.js b/loopback/common/models/application.js index b3841d34a..5e767fdc1 100644 --- a/loopback/common/models/application.js +++ b/loopback/common/models/application.js @@ -2,5 +2,4 @@ module.exports = function(Self) { require('../methods/application/status')(Self); require('../methods/application/post')(Self); - require('../methods/application/getUrl')(Self); }; diff --git a/modules/claim/back/methods/claim/claimPickupEmail.js b/modules/claim/back/methods/claim/claimPickupEmail.js index aea571a61..596102a24 100644 --- a/modules/claim/back/methods/claim/claimPickupEmail.js +++ b/modules/claim/back/methods/claim/claimPickupEmail.js @@ -44,7 +44,7 @@ module.exports = Self => { Self.claimPickupEmail = async ctx => { const models = Self.app.models; const $t = ctx.req.__; // $translate - const url = await Self.app.models.Application.getUrl(); + const url = await Self.app.models.Url.getUrl(); const args = Object.assign({}, ctx.args); const params = { diff --git a/modules/claim/back/methods/claim/createFromSales.js b/modules/claim/back/methods/claim/createFromSales.js index 24ba74c6d..30093e43d 100644 --- a/modules/claim/back/methods/claim/createFromSales.js +++ b/modules/claim/back/methods/claim/createFromSales.js @@ -94,7 +94,7 @@ module.exports = Self => { const salesPerson = ticket.client().salesPersonUser(); if (salesPerson) { - const url = await Self.app.models.Application.getUrl(); + const url = await Self.app.models.Url.getUrl(); const message = $t('Created claim', { claimId: newClaim.id, diff --git a/modules/claim/back/methods/claim/regularizeClaim.js b/modules/claim/back/methods/claim/regularizeClaim.js index 4ac500e2f..a51b114ef 100644 --- a/modules/claim/back/methods/claim/regularizeClaim.js +++ b/modules/claim/back/methods/claim/regularizeClaim.js @@ -56,7 +56,7 @@ module.exports = Self => { const salesPerson = sale.ticket().client().salesPersonUser(); if (salesPerson) { const nickname = address && address.nickname || destination.description; - const url = await Self.app.models.Application.getUrl(); + const url = await Self.app.models.Url.getUrl(); const message = $t('Sent units from ticket', { quantity: sale.quantity, concept: sale.concept, diff --git a/modules/claim/back/methods/claim/specs/updateClaim.spec.js b/modules/claim/back/methods/claim/specs/updateClaim.spec.js index e7be8e9c6..fff4d7ac6 100644 --- a/modules/claim/back/methods/claim/specs/updateClaim.spec.js +++ b/modules/claim/back/methods/claim/specs/updateClaim.spec.js @@ -4,7 +4,7 @@ const LoopBackContext = require('loopback-context'); describe('Update Claim', () => { let url; beforeAll(async() => { - url = await app.models.Application.getUrl(); + url = await app.models.Url.getUrl(); const activeCtx = { accessToken: {userId: 9}, http: { diff --git a/modules/claim/back/methods/claim/updateClaim.js b/modules/claim/back/methods/claim/updateClaim.js index 534f0c7ab..e418af950 100644 --- a/modules/claim/back/methods/claim/updateClaim.js +++ b/modules/claim/back/methods/claim/updateClaim.js @@ -114,7 +114,7 @@ module.exports = Self => { async function notifyStateChange(ctx, workerId, claim, state) { const models = Self.app.models; - const url = await models.Application.getUrl(); + const url = await models.Url.getUrl(); const $t = ctx.req.__; // $translate const message = $t(`Claim state has changed to ${state}`, { @@ -128,7 +128,7 @@ module.exports = Self => { async function notifyPickUp(ctx, workerId, claim) { const models = Self.app.models; - const url = await models.Application.getUrl('lilium'); + const url = await models.Url.getUrl('lilium'); const $t = ctx.req.__; // $translate const message = $t('Claim will be picked', { diff --git a/modules/client/back/models/client.js b/modules/client/back/models/client.js index 1b60b1329..e16e884cc 100644 --- a/modules/client/back/models/client.js +++ b/modules/client/back/models/client.js @@ -353,7 +353,7 @@ module.exports = Self => { const httpCtx = {req: loopBackContext.active}; const httpRequest = httpCtx.req.http.req; const $t = httpRequest.__; - const url = await Self.app.models.Application.getUrl(); + const url = await Self.app.models.Url.getUrl(); const salesPersonId = instance.salesPersonFk; @@ -395,7 +395,7 @@ module.exports = Self => { const httpCtx = {req: loopBackContext.active}; const httpRequest = httpCtx.req.http.req; const $t = httpRequest.__; - const url = await Self.app.models.Application.getUrl(); + const url = await Self.app.models.Url.getUrl(); const models = Self.app.models; let previousWorker = {name: $t('None')}; diff --git a/modules/client/back/models/credit-insurance.js b/modules/client/back/models/credit-insurance.js index 619904612..84bd90424 100644 --- a/modules/client/back/models/credit-insurance.js +++ b/modules/client/back/models/credit-insurance.js @@ -57,7 +57,7 @@ module.exports = function(Self) { const httpRequest = httpCtx.req.http.req; const $t = httpRequest.__; - const url = await Self.app.models.Application.getUrl(); + const url = await Self.app.models.Url.getUrl(); const fullPath = `${url}client/${client.id}/credit-insurance/index`; const message = $t('MESSAGE_INSURANCE_CHANGE', { clientId: client.id, diff --git a/modules/invoiceOut/back/methods/invoiceOut/makePdfAndNotify.js b/modules/invoiceOut/back/methods/invoiceOut/makePdfAndNotify.js index 49c785013..1de15b666 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/makePdfAndNotify.js +++ b/modules/invoiceOut/back/methods/invoiceOut/makePdfAndNotify.js @@ -59,7 +59,7 @@ module.exports = Self => { }; await Self.invoiceEmail(ctx, ref); } catch (err) { - const url = await Self.app.models.Application.getUrl(); + const url = await Self.app.models.Url.getUrl(); const message = ctx.req.__('Mail not sent', { clientId: client.id, clientUrl: `${url}claim/${id}/summary` diff --git a/modules/ticket/back/methods/sale/deleteSales.js b/modules/ticket/back/methods/sale/deleteSales.js index c71f8d5e1..0207815a9 100644 --- a/modules/ticket/back/methods/sale/deleteSales.js +++ b/modules/ticket/back/methods/sale/deleteSales.js @@ -68,7 +68,7 @@ module.exports = Self => { const salesPerson = ticket.client().salesPersonUser(); if (salesPerson) { - const url = await Self.app.models.Application.getUrl(); + const url = await Self.app.models.Url.getUrl(); const message = $t('Deleted sales from ticket', { ticketId: ticketId, diff --git a/modules/ticket/back/methods/sale/reserve.js b/modules/ticket/back/methods/sale/reserve.js index b111a0458..36db791fc 100644 --- a/modules/ticket/back/methods/sale/reserve.js +++ b/modules/ticket/back/methods/sale/reserve.js @@ -85,7 +85,7 @@ module.exports = Self => { const salesPerson = ticket.client().salesPersonUser(); if (salesPerson) { - const url = await Self.app.models.Application.getUrl(); + const url = await Self.app.models.Url.getUrl(); const message = $t('Changed sale reserved state', { ticketId: ticketId, diff --git a/modules/ticket/back/methods/sale/updatePrice.js b/modules/ticket/back/methods/sale/updatePrice.js index 3cae2a333..191fd09e3 100644 --- a/modules/ticket/back/methods/sale/updatePrice.js +++ b/modules/ticket/back/methods/sale/updatePrice.js @@ -98,7 +98,7 @@ module.exports = Self => { const salesPerson = sale.ticket().client().salesPersonUser(); if (salesPerson) { - const url = await Self.app.models.Application.getUrl(); + const url = await Self.app.models.Url.getUrl(); const message = $t('Changed sale price', { ticketId: sale.ticket().id, itemId: sale.itemFk, diff --git a/modules/ticket/back/methods/sale/updateQuantity.js b/modules/ticket/back/methods/sale/updateQuantity.js index acccc6c2f..28754e50c 100644 --- a/modules/ticket/back/methods/sale/updateQuantity.js +++ b/modules/ticket/back/methods/sale/updateQuantity.js @@ -80,7 +80,7 @@ module.exports = Self => { const salesPerson = sale.ticket().client().salesPersonUser(); if (salesPerson) { - const url = await Self.app.models.Application.getUrl(); + const url = await Self.app.models.Url.getUrl(); const message = $t('Changed sale quantity', { ticketId: sale.ticket().id, itemId: sale.itemFk, diff --git a/modules/ticket/back/methods/ticket-request/confirm.js b/modules/ticket/back/methods/ticket-request/confirm.js index a69fc7fd7..00310f33c 100644 --- a/modules/ticket/back/methods/ticket-request/confirm.js +++ b/modules/ticket/back/methods/ticket-request/confirm.js @@ -84,7 +84,7 @@ module.exports = Self => { const query = `CALL vn.sale_calculateComponent(?, NULL)`; await Self.rawSql(query, [sale.id], myOptions); - const url = await Self.app.models.Application.getUrl(); + const url = await Self.app.models.Url.getUrl(); const requesterId = request.requesterFk; const message = $t('Bought units from buy request', { diff --git a/modules/ticket/back/methods/ticket-request/deny.js b/modules/ticket/back/methods/ticket-request/deny.js index 9ec11d755..44f1e48a1 100644 --- a/modules/ticket/back/methods/ticket-request/deny.js +++ b/modules/ticket/back/methods/ticket-request/deny.js @@ -50,7 +50,7 @@ module.exports = Self => { const request = await Self.app.models.TicketRequest.findById(ctx.args.id, null, myOptions); await request.updateAttributes(params, myOptions); - const url = await Self.app.models.Application.getUrl(); + const url = await Self.app.models.Url.getUrl(); const requesterId = request.requesterFk; const message = $t('Deny buy request', { diff --git a/modules/ticket/back/methods/ticket/addSale.js b/modules/ticket/back/methods/ticket/addSale.js index 29e49d8e6..59f1190fa 100644 --- a/modules/ticket/back/methods/ticket/addSale.js +++ b/modules/ticket/back/methods/ticket/addSale.js @@ -94,7 +94,7 @@ module.exports = Self => { const salesPerson = ticket.client().salesPersonUser(); if (salesPerson) { - const url = await Self.app.models.Application.getUrl(); + const url = await Self.app.models.Url.getUrl(); const message = $t('Added sale to ticket', { ticketId: id, diff --git a/modules/ticket/back/methods/ticket/componentUpdate.js b/modules/ticket/back/methods/ticket/componentUpdate.js index fc8b3a40c..f7c36f108 100644 --- a/modules/ticket/back/methods/ticket/componentUpdate.js +++ b/modules/ticket/back/methods/ticket/componentUpdate.js @@ -237,7 +237,7 @@ module.exports = Self => { const salesPersonId = originalTicket.client().salesPersonFk; if (salesPersonId) { - const url = await Self.app.models.Application.getUrl(); + const url = await Self.app.models.Url.getUrl(); let changesMade = ''; for (let change in newProperties) { diff --git a/modules/ticket/back/methods/ticket/merge.js b/modules/ticket/back/methods/ticket/merge.js index 19c7f9fa0..1106cef06 100644 --- a/modules/ticket/back/methods/ticket/merge.js +++ b/modules/ticket/back/methods/ticket/merge.js @@ -25,7 +25,7 @@ module.exports = Self => { Self.merge = async(ctx, tickets, options) => { const httpRequest = ctx.req; const $t = httpRequest.__; - const url = await Self.app.models.Application.getUrl(); + const url = await Self.app.models.Url.getUrl(); const models = Self.app.models; const myOptions = {}; let tx; diff --git a/modules/ticket/back/methods/ticket/restore.js b/modules/ticket/back/methods/ticket/restore.js index 0aaef0418..e268c3891 100644 --- a/modules/ticket/back/methods/ticket/restore.js +++ b/modules/ticket/back/methods/ticket/restore.js @@ -48,7 +48,7 @@ module.exports = Self => { // Send notification to salesPerson const salesPersonId = ticket.client().salesPersonFk; if (salesPersonId) { - const url = await Self.app.models.Application.getUrl(); + const url = await Self.app.models.Url.getUrl(); const message = $t(`I have restored the ticket id`, { id: id, url: `${url}ticket/${id}/summary` diff --git a/modules/ticket/back/methods/ticket/setDeleted.js b/modules/ticket/back/methods/ticket/setDeleted.js index a6fd295f1..9a9fd9056 100644 --- a/modules/ticket/back/methods/ticket/setDeleted.js +++ b/modules/ticket/back/methods/ticket/setDeleted.js @@ -119,7 +119,7 @@ module.exports = Self => { // Send notification to salesPerson const salesPersonUser = ticket.client().salesPersonUser(); if (salesPersonUser && sales.length) { - const url = await Self.app.models.Application.getUrl(); + const url = await Self.app.models.Url.getUrl(); const message = $t(`I have deleted the ticket id`, { id: id, url: `${url}ticket/${id}/summary` diff --git a/modules/ticket/back/methods/ticket/updateDiscount.js b/modules/ticket/back/methods/ticket/updateDiscount.js index 05ade4f01..2e8bec27a 100644 --- a/modules/ticket/back/methods/ticket/updateDiscount.js +++ b/modules/ticket/back/methods/ticket/updateDiscount.js @@ -165,7 +165,7 @@ module.exports = Self => { const salesPerson = ticket.client().salesPersonUser(); if (salesPerson) { - const url = await Self.app.models.Application.getUrl(); + const url = await Self.app.models.Url.getUrl(); const message = $t('Changed sale discount', { ticketId: id, ticketUrl: `${url}ticket/${id}/sale`, diff --git a/modules/worker/back/methods/worker/createAbsence.js b/modules/worker/back/methods/worker/createAbsence.js index 10992f91f..d628d0a2b 100644 --- a/modules/worker/back/methods/worker/createAbsence.js +++ b/modules/worker/back/methods/worker/createAbsence.js @@ -109,7 +109,7 @@ module.exports = Self => { const absenceType = await models.AbsenceType.findById(args.absenceTypeId, null, myOptions); const account = await models.VnUser.findById(userId, null, myOptions); const subordinated = await models.VnUser.findById(id, null, myOptions); - const url = await Self.app.models.Application.getUrl(); + const url = await Self.app.models.Url.getUrl(); const body = $t('Created absence', { author: account.nickname, employee: subordinated.nickname, diff --git a/modules/worker/back/methods/worker/deleteAbsence.js b/modules/worker/back/methods/worker/deleteAbsence.js index 2912e6db4..b71d077a4 100644 --- a/modules/worker/back/methods/worker/deleteAbsence.js +++ b/modules/worker/back/methods/worker/deleteAbsence.js @@ -60,7 +60,7 @@ module.exports = Self => { const absenceType = await models.AbsenceType.findById(absence.dayOffTypeFk, null, myOptions); const account = await models.VnUser.findById(userId, null, myOptions); const subordinated = await models.VnUser.findById(labour.workerFk, null, myOptions); - const url = await Self.app.models.Application.getUrl(); + const url = await Self.app.models.Url.getUrl(); const body = $t('Deleted absence', { author: account.nickname, employee: subordinated.nickname, From f8889df90354660fbeb3160e4f1a4e6416bc9a40 Mon Sep 17 00:00:00 2001 From: pablone Date: Thu, 19 Oct 2023 08:40:25 +0200 Subject: [PATCH 251/427] remove(console.log): se quitan console.log que se utilizaron para dbuggear refs #5979 --- back/methods/chat/sendCheckingPresence.js | 9 --------- back/methods/url/getUrl.js | 2 -- back/models/chat.js | 8 -------- modules/claim/back/methods/claim/updateClaim.js | 3 --- 4 files changed, 22 deletions(-) diff --git a/back/methods/chat/sendCheckingPresence.js b/back/methods/chat/sendCheckingPresence.js index 0bae87a35..7bba96d59 100644 --- a/back/methods/chat/sendCheckingPresence.js +++ b/back/methods/chat/sendCheckingPresence.js @@ -25,16 +25,10 @@ module.exports = Self => { }); Self.sendCheckingPresence = async(ctx, recipientId, message) => { - console.log('recipientId: ', recipientId); if (!recipientId) return false; const models = Self.app.models; - console.log('sender: ', ctx.req.accessToken.userId); const sender = ctx.req.accessToken.userId; - console.log('sender: ', sender); const recipient = recipientId; - console.log('recipient: ', recipient); - - console.log('recipientId == sender: ', recipientId == sender); // Prevent sending messages to yourself if (recipientId == sender) return false; @@ -42,7 +36,6 @@ module.exports = Self => { throw new Error(`Could not send message "${message}" to worker id ${recipientId} from user ${sender}`); if (process.env.NODE_ENV == 'test') message = `[Test:Environment to user ${sender}] ` + message; - console.log('chat create'); const chat = await models.Chat.create({ senderFk: sender.id, recipient: `@${recipient.name}`, @@ -53,8 +46,6 @@ module.exports = Self => { attempts: 0 }); - console.log('chat: '); - try { await Self.sendCheckingUserStatus(chat); await Self.updateChat(chat, 'sent'); diff --git a/back/methods/url/getUrl.js b/back/methods/url/getUrl.js index f258503b1..f30719b9f 100644 --- a/back/methods/url/getUrl.js +++ b/back/methods/url/getUrl.js @@ -19,14 +19,12 @@ module.exports = Self => { } }); Self.getUrl = async(appName = 'salix') => { - console.log('appName: ', appName); const {url} = await Self.app.models.Url.findOne({ where: { appName, enviroment: process.env.NODE_ENV || 'development' } }); - console.log('url: ', url); return url; }; }; diff --git a/back/models/chat.js b/back/models/chat.js index 240ec2c26..882db747e 100644 --- a/back/models/chat.js +++ b/back/models/chat.js @@ -6,26 +6,18 @@ module.exports = Self => { require('../methods/chat/sendQueued')(Self); Self.observe('before save', async function(ctx) { - console.log('chat start 1'); - - console.log('ctx.isNewInstance: ', ctx.isNewInstance); - console.log('message: ', ctx.instance); if (!ctx.isNewInstance) return; - let {message} = ctx.instance; if (!message) return; const parts = message.match(/(?<=\[)[a-zA-Z0-9_\-+!@#$%^&*()={};':"\\|,.<>/?\s]*(?=])/g); if (!parts) return; - console.log('chat start 2'); const replacedParts = parts.map(part => { return part.replace(/[!$%^&*()={};':"\\,.<>/?]/g, ''); }); - console.log('chat start 3'); for (const [index, part] of parts.entries()) message = message.replace(part, replacedParts[index]); ctx.instance.message = message; - console.log('chat end'); }); }; diff --git a/modules/claim/back/methods/claim/updateClaim.js b/modules/claim/back/methods/claim/updateClaim.js index e418af950..8210f7a83 100644 --- a/modules/claim/back/methods/claim/updateClaim.js +++ b/modules/claim/back/methods/claim/updateClaim.js @@ -136,9 +136,6 @@ module.exports = Self => { clientName: claim.client().name, claimUrl: `${url}claim/${claim.id}/summary` }); - console.log('url', `${url}claim/${claim.id}/summary`); - console.log('claim client', claim.client().name); - console.log('claim id', claim.id); await models.Chat.sendCheckingPresence(ctx, workerId, message); } }; From d3a7b4ecb996aff3f9eaae374a96ab42366aeada Mon Sep 17 00:00:00 2001 From: pablone Date: Thu, 19 Oct 2023 08:41:26 +0200 Subject: [PATCH 252/427] remove: console.log from updateClaim refs #5979 --- modules/claim/back/methods/claim/updateClaim.js | 1 - 1 file changed, 1 deletion(-) diff --git a/modules/claim/back/methods/claim/updateClaim.js b/modules/claim/back/methods/claim/updateClaim.js index 8210f7a83..7f7ccb299 100644 --- a/modules/claim/back/methods/claim/updateClaim.js +++ b/modules/claim/back/methods/claim/updateClaim.js @@ -122,7 +122,6 @@ module.exports = Self => { clientName: claim.client().name, claimUrl: `${url}claim/${claim.id}/summary` }); - console.log(`${url}claim/${claim.id}/summary`); await models.Chat.sendCheckingPresence(ctx, workerId, message); } From 52b14cf8b4fb8c4f0f19337c4ef56148b403c8c6 Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 19 Oct 2023 09:51:10 +0200 Subject: [PATCH 253/427] ref #6138 fix emailVerified --- modules/worker/back/methods/worker/setPassword.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/worker/back/methods/worker/setPassword.js b/modules/worker/back/methods/worker/setPassword.js index fcfb5e733..43d3d946f 100644 --- a/modules/worker/back/methods/worker/setPassword.js +++ b/modules/worker/back/methods/worker/setPassword.js @@ -37,7 +37,7 @@ module.exports = Self => { if (!isSubordinate) throw new UserError('You don\'t have enough privileges.'); await models.VnUser.setPassword(args.workerFk, args.newPass, myOptions); - await models.VnUser.updateAll({id: args.workerFk}, {emailVerified: 1}, myOptions); + await models.VnUser.updateAll({id: args.workerFk}, {emailVerified: true}, myOptions); if (tx) await tx.commit(); } catch (e) { From a5b6921592ac1f24c66a60c524dd924d34ad5dee Mon Sep 17 00:00:00 2001 From: pablone Date: Thu, 19 Oct 2023 10:44:34 +0200 Subject: [PATCH 254/427] refactor(changes): se mueven los sql a la ultima carpeta refs #3126 --- db/changes/{234001 => 234201}/00-packagingFk.sql | 0 db/changes/{234001 => 234201}/00-packagingFkviews.sql | 0 db/changes/{234001 => 234201}/02-packagingFktrigger.sql | 0 db/changes/{234001 => 234201}/03-packagingFkProc.sql | 0 4 files changed, 0 insertions(+), 0 deletions(-) rename db/changes/{234001 => 234201}/00-packagingFk.sql (100%) rename db/changes/{234001 => 234201}/00-packagingFkviews.sql (100%) rename db/changes/{234001 => 234201}/02-packagingFktrigger.sql (100%) rename db/changes/{234001 => 234201}/03-packagingFkProc.sql (100%) diff --git a/db/changes/234001/00-packagingFk.sql b/db/changes/234201/00-packagingFk.sql similarity index 100% rename from db/changes/234001/00-packagingFk.sql rename to db/changes/234201/00-packagingFk.sql diff --git a/db/changes/234001/00-packagingFkviews.sql b/db/changes/234201/00-packagingFkviews.sql similarity index 100% rename from db/changes/234001/00-packagingFkviews.sql rename to db/changes/234201/00-packagingFkviews.sql diff --git a/db/changes/234001/02-packagingFktrigger.sql b/db/changes/234201/02-packagingFktrigger.sql similarity index 100% rename from db/changes/234001/02-packagingFktrigger.sql rename to db/changes/234201/02-packagingFktrigger.sql diff --git a/db/changes/234001/03-packagingFkProc.sql b/db/changes/234201/03-packagingFkProc.sql similarity index 100% rename from db/changes/234001/03-packagingFkProc.sql rename to db/changes/234201/03-packagingFkProc.sql From 1b8f227c473152f02dd6ce0c673292838183b5c6 Mon Sep 17 00:00:00 2001 From: guillermo Date: Thu, 19 Oct 2023 11:58:15 +0200 Subject: [PATCH 255/427] ticket #125321 filter advance tickets fix --- .../ticket/front/advance-search-panel/index.js | 4 ++-- modules/ticket/front/advance/index.js | 18 ++++-------------- 2 files changed, 6 insertions(+), 16 deletions(-) diff --git a/modules/ticket/front/advance-search-panel/index.js b/modules/ticket/front/advance-search-panel/index.js index 8ddbe78d4..218fb14d3 100644 --- a/modules/ticket/front/advance-search-panel/index.js +++ b/modules/ticket/front/advance-search-panel/index.js @@ -16,8 +16,8 @@ class Controller extends SearchPanel { this.$http.get('ItemPackingTypes', {filter}).then(res => { for (let ipt of res.data) { itemPackingTypes.push({ - code: ipt.code, - description: this.$t(ipt.description) + description: this.$t(ipt.description), + code: ipt.code }); } this.itemPackingTypes = itemPackingTypes; diff --git a/modules/ticket/front/advance/index.js b/modules/ticket/front/advance/index.js index 0cec41227..6f8a92ebe 100644 --- a/modules/ticket/front/advance/index.js +++ b/modules/ticket/front/advance/index.js @@ -163,26 +163,16 @@ export default class Controller extends Section { return {'futureId': value}; case 'liters': return {'liters': value}; - case 'lines': - return {'lines': value}; case 'futureLiters': return {'futureLiters': value}; + case 'lines': + return {'lines': value}; case 'futureLines': return {'futureLines': value}; case 'ipt': - return {or: - [ - {'ipt': {like: `%${value}%`}}, - {'ipt': null} - ] - }; + return {'ipt': {like: `%${value}%`}}; case 'futureIpt': - return {or: - [ - {'futureIpt': {like: `%${value}%`}}, - {'futureIpt': null} - ] - }; + return {'futureIpt': {like: `%${value}%`}}; case 'totalWithVat': return {'totalWithVat': value}; case 'futureTotalWithVat': From d9ab607126385e9cf99bab9529b8f0bfdb2a7954 Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 19 Oct 2023 13:03:11 +0200 Subject: [PATCH 256/427] refs #6199 feat(sale): increase quantity if newPrice is higher --- .../collection/spec/setSaleQuantity.spec.js | 9 +- .../05-ticket/01-sale/02_edit_sale.spec.js | 8 - .../methods/sale/specs/updateQuantity.spec.js | 138 ++++++++++++++---- modules/ticket/back/models/sale.js | 35 +++-- 4 files changed, 133 insertions(+), 57 deletions(-) diff --git a/back/methods/collection/spec/setSaleQuantity.spec.js b/back/methods/collection/spec/setSaleQuantity.spec.js index 8cd73205f..b563f5b19 100644 --- a/back/methods/collection/spec/setSaleQuantity.spec.js +++ b/back/methods/collection/spec/setSaleQuantity.spec.js @@ -18,7 +18,14 @@ describe('setSaleQuantity()', () => { it('should change quantity sale', async() => { const tx = await models.Ticket.beginTransaction({}); - spyOn(models.Item, 'getVisibleAvailable').and.returnValue((new Promise(resolve => resolve({available: 100})))); + spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { + if (sqlStatement.includes('catalog_calcFromItem')) { + sqlStatement = `CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY + SELECT 100 as available;`; + params = null; + } + return models.Ticket.rawSql(sqlStatement, params, options); + }); try { const options = {transaction: tx}; diff --git a/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js b/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js index b89254dda..23983a9c8 100644 --- a/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js +++ b/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js @@ -134,14 +134,6 @@ describe('Ticket Edit sale path', () => { await page.accessToSection('ticket.card.sale'); }); - it('should try to add a higher quantity value and then receive an error', async() => { - await page.waitToClick(selectors.ticketSales.firstSaleQuantityCell); - await page.type(selectors.ticketSales.firstSaleQuantity, '11\u000d'); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('The price of the item changed'); - }); - it('should remove 1 from the first sale quantity', async() => { await page.waitToClick(selectors.ticketSales.firstSaleQuantityCell); await page.waitForSelector(selectors.ticketSales.firstSaleQuantity); diff --git a/modules/ticket/back/methods/sale/specs/updateQuantity.spec.js b/modules/ticket/back/methods/sale/specs/updateQuantity.spec.js index 74be352d1..34c58ef98 100644 --- a/modules/ticket/back/methods/sale/specs/updateQuantity.spec.js +++ b/modules/ticket/back/methods/sale/specs/updateQuantity.spec.js @@ -24,34 +24,6 @@ describe('sale updateQuantity()', () => { }; } - it('should throw an error if the quantity is greater than it should be', async() => { - const ctx = { - req: { - accessToken: {userId: 1}, - headers: {origin: 'localhost:5000'}, - __: () => {} - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); - spyOn(models.Item, 'getVisibleAvailable').and.returnValue((new Promise(resolve => resolve({available: 100})))); - - const tx = await models.Sale.beginTransaction({}); - - let error; - try { - const options = {transaction: tx}; - - await models.Sale.updateQuantity(ctx, 17, 31, options); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - error = e; - } - - expect(error).toEqual(new Error('The price of the item changed')); - }); - it('should add quantity if the quantity is greater than it should be and is role advanced', async() => { const saleId = 17; const buyerId = 35; @@ -64,7 +36,14 @@ describe('sale updateQuantity()', () => { }; const tx = await models.Sale.beginTransaction({}); spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(buyerId)); - spyOn(models.Item, 'getVisibleAvailable').and.returnValue((new Promise(resolve => resolve({available: 100})))); + spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { + if (sqlStatement.includes('catalog_calcFromItem')) { + sqlStatement = `CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY + SELECT 100 as available;`; + params = null; + } + return models.Ticket.rawSql(sqlStatement, params, options); + }); try { const options = {transaction: tx}; @@ -193,6 +172,14 @@ describe('sale updateQuantity()', () => { const item = await models.Item.findById(itemId, null, options); await item.updateAttribute('minQuantity', minQuantity, options); + spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { + if (sqlStatement.includes('catalog_calcFromItem')) { + sqlStatement = `CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY + SELECT 100 as available;`; + params = null; + } + return models.Ticket.rawSql(sqlStatement, params, options); + }); await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); @@ -226,7 +213,15 @@ describe('sale updateQuantity()', () => { const item = await models.Item.findById(itemId, null, options); await item.updateAttribute('minQuantity', minQuantity, options); - spyOn(models.Item, 'getVisibleAvailable').and.returnValue((new Promise(resolve => resolve({available: newQuantity})))); + + spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { + if (sqlStatement.includes('catalog_calcFromItem')) { + sqlStatement = `CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY + SELECT ${newQuantity} as available;`; + params = null; + } + return models.Ticket.rawSql(sqlStatement, params, options); + }); await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); @@ -236,4 +231,87 @@ describe('sale updateQuantity()', () => { throw e; } }); + + it('should increase quantity if you have enough available and the new price is the same as the previous one', async() => { + const ctx = { + req: { + accessToken: {userId: 1}, + headers: {origin: 'localhost:5000'}, + __: () => {} + } + }; + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); + + const tx = await models.Sale.beginTransaction({}); + const itemId = 2; + const saleId = 17; + const minQuantity = 30; + const newQuantity = 31; + + try { + const options = {transaction: tx}; + + const item = await models.Item.findById(itemId, null, options); + await item.updateAttribute('minQuantity', minQuantity, options); + spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { + if (sqlStatement.includes('catalog_calcFromItem')) { + sqlStatement = ` + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY SELECT ${newQuantity} as available; + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentPrice ENGINE = MEMORY SELECT 1 as grouping, 8 as price;`; + params = null; + } + return models.Ticket.rawSql(sqlStatement, params, options); + }); + + await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('should throw error when increase quantity and the new price is lower than the previous one', async() => { + const ctx = { + req: { + accessToken: {userId: 1}, + headers: {origin: 'localhost:5000'}, + __: () => {} + } + }; + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); + + const tx = await models.Sale.beginTransaction({}); + const itemId = 2; + const saleId = 17; + const minQuantity = 30; + const newQuantity = 31; + + let error; + try { + const options = {transaction: tx}; + + const item = await models.Item.findById(itemId, null, options); + await item.updateAttribute('minQuantity', minQuantity, options); + spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { + if (sqlStatement.includes('catalog_calcFromItem')) { + sqlStatement = ` + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY SELECT ${newQuantity} as available; + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentPrice ENGINE = MEMORY SELECT 1 as grouping, 1 as price;`; + params = null; + } + return models.Ticket.rawSql(sqlStatement, params, options); + }); + + await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error).toEqual(new Error('The price of the item changed')); + }); }); diff --git a/modules/ticket/back/models/sale.js b/modules/ticket/back/models/sale.js index c1b3f3990..23cf90353 100644 --- a/modules/ticket/back/models/sale.js +++ b/modules/ticket/back/models/sale.js @@ -31,6 +31,8 @@ module.exports = Self => { const ticketId = changes?.ticketFk || instance?.ticketFk; const itemId = changes?.itemFk || instance?.itemFk; + const oldQuantity = instance?.quantity ?? null; + const quantityAdded = newQuantity - oldQuantity; const ticket = await models.Ticket.findById( ticketId, @@ -65,20 +67,9 @@ module.exports = Self => { fields: ['family', 'minQuantity'], where: {id: itemId}, }, ctx.options); - if (item.family == 'EMB') return; - if (newQuantity < item.minQuantity) - throw new UserError('The amount cannot be less than the minimum'); - - const oldQuantity = instance?.quantity ?? null; - const quantityAdded = newQuantity - oldQuantity; - - if (await models.ACL.checkAccessAcl(ctx, 'Ticket', 'isRoleAdvanced', '*')) return; - - if (ctx.isNewInstance || newQuantity <= oldQuantity) return; - - await Self.rawSql(`CALL catalog_calcFromItem(?,?,?,?)`, [ + await models.Sale.rawSql(`CALL catalog_calcFromItem(?,?,?,?)`, [ ticket.landed, ticket.addressFk, ticket.agencyModeFk, @@ -86,19 +77,27 @@ module.exports = Self => { ], ctx.options); - const [itemInfo] = await Self.rawSql(`SELECT available FROM tmp.ticketCalculateItem`, null, ctx.options); - if (itemInfo?.available < quantityAdded) + const [itemInfo] = await models.Sale.rawSql(`SELECT available FROM tmp.ticketCalculateItem`, null, ctx.options); + + if (!itemInfo?.available || itemInfo.available < quantityAdded) throw new UserError(`This item is not available`); - const [saleGrouping] = await Self.rawSql(` + if (await models.ACL.checkAccessAcl(ctx, 'Ticket', 'isRoleAdvanced', '*')) return; + + if (newQuantity < item.minQuantity && newQuantity != itemInfo?.available) + throw new UserError('The amount cannot be less than the minimum'); + + if (ctx.isNewInstance || newQuantity <= oldQuantity) return; + + const [saleGrouping] = await models.Sale.rawSql(` SELECT MAX(t.grouping), t.price newPrice FROM tmp.ticketComponentPrice t WHERE t.grouping <= ?`, [quantityAdded], ctx.options); - await Self.rawSql(` - DROP TEMPORARY TABLE + await models.Sale.rawSql(` + DROP TEMPORARY TABLE IF EXISTS tmp.ticketCalculateItem, tmp.ticketComponentPrice, tmp.ticketComponent, @@ -106,7 +105,7 @@ module.exports = Self => { tmp.zoneGetShipped; `, null, ctx.options); - if (!saleGrouping?.newPrice || instance.price < saleGrouping.newPrice) + if (!saleGrouping?.newPrice || saleGrouping.newPrice < instance.price) throw new UserError('The price of the item changed'); }); }; From 37209a223a8f7cd116356cf6d645ef9703afe558 Mon Sep 17 00:00:00 2001 From: pablone Date: Thu, 19 Oct 2023 15:05:19 +0200 Subject: [PATCH 257/427] feat(db): packagefk virtual column refs #3126 --- db/changes/234201/00-packagingFk.sql | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/db/changes/234201/00-packagingFk.sql b/db/changes/234201/00-packagingFk.sql index 5ed1d9512..9a775ada9 100644 --- a/db/changes/234201/00-packagingFk.sql +++ b/db/changes/234201/00-packagingFk.sql @@ -1,2 +1,5 @@ - ALTER TABLE vn.buy CHANGE packageFk packagingFk varchar(10) - CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT '--' NULL; \ No newline at end of file +ALTER TABLE `vn`.`buy` CHANGE `packageFk` `packagingFk` varchar(10) +CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT '--' NULL; + +ALTER TABLE `vn`.`buy` +ADD COLUMN `packageFk` varchar(10) AS (`packagingFk`) VIRTUAL; \ No newline at end of file From 16f20cea70c278cc1112b6c66a77efe0022c91fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Thu, 19 Oct 2023 15:12:06 +0200 Subject: [PATCH 258/427] refs #6199 fix(sale): get minim price without grouping --- modules/ticket/back/models/sale.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/modules/ticket/back/models/sale.js b/modules/ticket/back/models/sale.js index 23cf90353..ef3dd8ef7 100644 --- a/modules/ticket/back/models/sale.js +++ b/modules/ticket/back/models/sale.js @@ -90,9 +90,10 @@ module.exports = Self => { if (ctx.isNewInstance || newQuantity <= oldQuantity) return; const [saleGrouping] = await models.Sale.rawSql(` - SELECT MAX(t.grouping), t.price newPrice + SELECT t.price newPrice FROM tmp.ticketComponentPrice t - WHERE t.grouping <= ?`, + ORDER BY (t.grouping <= ?) DESC, t.grouping ASC + LIMIT 1`, [quantityAdded], ctx.options); From 07fa01103524ddfd35dc3adaca540641a8fb4af7 Mon Sep 17 00:00:00 2001 From: pablone Date: Thu, 19 Oct 2023 18:24:03 +0200 Subject: [PATCH 259/427] fix(updateClaim): el spec daba error refs #5979 --- modules/claim/back/methods/claim/specs/updateClaim.spec.js | 2 +- modules/claim/back/methods/claim/updateClaim.js | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/modules/claim/back/methods/claim/specs/updateClaim.spec.js b/modules/claim/back/methods/claim/specs/updateClaim.spec.js index fff4d7ac6..85ada869a 100644 --- a/modules/claim/back/methods/claim/specs/updateClaim.spec.js +++ b/modules/claim/back/methods/claim/specs/updateClaim.spec.js @@ -62,7 +62,7 @@ describe('Update Claim', () => { expect(error.message).toEqual(`You don't have enough privileges to change that field`); }); - fit(`should success to update the claimState to 'canceled' and send a rocket message`, async() => { + it(`should success to update the claimState to 'canceled' and send a rocket message`, async() => { const tx = await app.models.Claim.beginTransaction({}); try { diff --git a/modules/claim/back/methods/claim/updateClaim.js b/modules/claim/back/methods/claim/updateClaim.js index 7f7ccb299..f18e3a812 100644 --- a/modules/claim/back/methods/claim/updateClaim.js +++ b/modules/claim/back/methods/claim/updateClaim.js @@ -92,6 +92,7 @@ module.exports = Self => { // When hasToPickUp has been changed if (salesPerson && changedHasToPickUp && updatedClaim.hasToPickUp) notifyPickUp(ctx, salesPerson.id, claim); + // When claimState has been changed if (args.claimStateFk) { const newState = await models.ClaimState.findById(args.claimStateFk, null, myOptions); @@ -114,7 +115,7 @@ module.exports = Self => { async function notifyStateChange(ctx, workerId, claim, state) { const models = Self.app.models; - const url = await models.Url.getUrl(); + const url = models.Url.getUrl(); const $t = ctx.req.__; // $translate const message = $t(`Claim state has changed to ${state}`, { @@ -127,7 +128,7 @@ module.exports = Self => { async function notifyPickUp(ctx, workerId, claim) { const models = Self.app.models; - const url = await models.Url.getUrl('lilium'); + const url = models.Url.getUrl(); const $t = ctx.req.__; // $translate const message = $t('Claim will be picked', { From d5f98700e7da329dd24501902cd70c0d7bb57c9a Mon Sep 17 00:00:00 2001 From: alexm Date: Fri, 20 Oct 2023 08:32:35 +0200 Subject: [PATCH 260/427] refs #6287 fix: ticket new correct return type --- modules/ticket/back/methods/ticket/new.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/ticket/back/methods/ticket/new.js b/modules/ticket/back/methods/ticket/new.js index b461fb26d..0f5c323ed 100644 --- a/modules/ticket/back/methods/ticket/new.js +++ b/modules/ticket/back/methods/ticket/new.js @@ -48,7 +48,7 @@ module.exports = Self => { description: `The route id filter` }], returns: { - type: 'number', + type: 'object', root: true }, http: { From 84aed7ca21c5523ea0441a46c96b7ce037080036 Mon Sep 17 00:00:00 2001 From: alexm Date: Fri, 20 Oct 2023 09:26:56 +0200 Subject: [PATCH 261/427] refs #6257 fix(saleQuantity): newPrice correct restricction --- .../methods/sale/specs/updateQuantity.spec.js | 180 +++++++++++------- modules/ticket/back/models/sale.js | 2 +- 2 files changed, 112 insertions(+), 70 deletions(-) diff --git a/modules/ticket/back/methods/sale/specs/updateQuantity.spec.js b/modules/ticket/back/methods/sale/specs/updateQuantity.spec.js index 34c58ef98..0669711e7 100644 --- a/modules/ticket/back/methods/sale/specs/updateQuantity.spec.js +++ b/modules/ticket/back/methods/sale/specs/updateQuantity.spec.js @@ -232,86 +232,128 @@ describe('sale updateQuantity()', () => { } }); - it('should increase quantity if you have enough available and the new price is the same as the previous one', async() => { - const ctx = { - req: { - accessToken: {userId: 1}, - headers: {origin: 'localhost:5000'}, - __: () => {} - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); + describe('newPrice', () => { + it('should increase quantity if you have enough available and the new price is the same as the previous one', async() => { + const ctx = { + req: { + accessToken: {userId: 1}, + headers: {origin: 'localhost:5000'}, + __: () => {} + } + }; + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); - const tx = await models.Sale.beginTransaction({}); - const itemId = 2; - const saleId = 17; - const minQuantity = 30; - const newQuantity = 31; + const tx = await models.Sale.beginTransaction({}); + const itemId = 2; + const saleId = 17; + const minQuantity = 30; + const newQuantity = 31; - try { - const options = {transaction: tx}; + try { + const options = {transaction: tx}; - const item = await models.Item.findById(itemId, null, options); - await item.updateAttribute('minQuantity', minQuantity, options); - spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { - if (sqlStatement.includes('catalog_calcFromItem')) { - sqlStatement = ` + const item = await models.Item.findById(itemId, null, options); + await item.updateAttribute('minQuantity', minQuantity, options); + spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { + if (sqlStatement.includes('catalog_calcFromItem')) { + sqlStatement = ` CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY SELECT ${newQuantity} as available; - CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentPrice ENGINE = MEMORY SELECT 1 as grouping, 8 as price;`; - params = null; - } - return models.Ticket.rawSql(sqlStatement, params, options); - }); + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentPrice ENGINE = MEMORY SELECT 1 as grouping, 7.07 as price;`; + params = null; + } + return models.Ticket.rawSql(sqlStatement, params, options); + }); - await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); + await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } - }); - - it('should throw error when increase quantity and the new price is lower than the previous one', async() => { - const ctx = { - req: { - accessToken: {userId: 1}, - headers: {origin: 'localhost:5000'}, - __: () => {} + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); + }); - const tx = await models.Sale.beginTransaction({}); - const itemId = 2; - const saleId = 17; - const minQuantity = 30; - const newQuantity = 31; - - let error; - try { - const options = {transaction: tx}; - - const item = await models.Item.findById(itemId, null, options); - await item.updateAttribute('minQuantity', minQuantity, options); - spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { - if (sqlStatement.includes('catalog_calcFromItem')) { - sqlStatement = ` - CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY SELECT ${newQuantity} as available; - CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentPrice ENGINE = MEMORY SELECT 1 as grouping, 1 as price;`; - params = null; + it('should increase quantity when the new price is lower than the previous one', async() => { + const ctx = { + req: { + accessToken: {userId: 1}, + headers: {origin: 'localhost:5000'}, + __: () => {} } - return models.Ticket.rawSql(sqlStatement, params, options); - }); + }; + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); - await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); + const tx = await models.Sale.beginTransaction({}); + const itemId = 2; + const saleId = 17; + const minQuantity = 30; + const newQuantity = 31; - await tx.rollback(); - } catch (e) { - await tx.rollback(); - error = e; - } + try { + const options = {transaction: tx}; - expect(error).toEqual(new Error('The price of the item changed')); + const item = await models.Item.findById(itemId, null, options); + await item.updateAttribute('minQuantity', minQuantity, options); + spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { + if (sqlStatement.includes('catalog_calcFromItem')) { + sqlStatement = ` + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY SELECT ${newQuantity} as available; + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentPrice ENGINE = MEMORY SELECT 1 as grouping, 1 as price;`; + params = null; + } + return models.Ticket.rawSql(sqlStatement, params, options); + }); + + await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('should throw error when increase quantity and the new price is higher than the previous one', async() => { + const ctx = { + req: { + accessToken: {userId: 1}, + headers: {origin: 'localhost:5000'}, + __: () => {} + } + }; + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); + + const tx = await models.Sale.beginTransaction({}); + const itemId = 2; + const saleId = 17; + const minQuantity = 30; + const newQuantity = 31; + + let error; + try { + const options = {transaction: tx}; + + const item = await models.Item.findById(itemId, null, options); + await item.updateAttribute('minQuantity', minQuantity, options); + spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { + if (sqlStatement.includes('catalog_calcFromItem')) { + sqlStatement = ` + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY SELECT ${newQuantity} as available; + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentPrice ENGINE = MEMORY SELECT 1 as grouping, 100000 as price;`; + params = null; + } + return models.Ticket.rawSql(sqlStatement, params, options); + }); + + await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error).toEqual(new Error('The price of the item changed')); + }); }); }); diff --git a/modules/ticket/back/models/sale.js b/modules/ticket/back/models/sale.js index ef3dd8ef7..4b7ed1043 100644 --- a/modules/ticket/back/models/sale.js +++ b/modules/ticket/back/models/sale.js @@ -106,7 +106,7 @@ module.exports = Self => { tmp.zoneGetShipped; `, null, ctx.options); - if (!saleGrouping?.newPrice || saleGrouping.newPrice < instance.price) + if (!saleGrouping?.newPrice || saleGrouping.newPrice > instance.price) throw new UserError('The price of the item changed'); }); }; From 243a32dff553fa4422b26391d04f9c569fc6b01f Mon Sep 17 00:00:00 2001 From: pablone Date: Fri, 20 Oct 2023 11:36:11 +0200 Subject: [PATCH 262/427] remove(expand): quito expand de la columna requester refs #6278 --- modules/item/front/request/index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/item/front/request/index.html b/modules/item/front/request/index.html index 571ad49af..200ce3902 100644 --- a/modules/item/front/request/index.html +++ b/modules/item/front/request/index.html @@ -26,7 +26,7 @@ Ticket ID Shipped Description - Requester + Requester Requested Price Atender From 1eabad7f4b21ea358dce4cc39a5ea94b93666d3f Mon Sep 17 00:00:00 2001 From: alexm Date: Fri, 20 Oct 2023 12:37:44 +0200 Subject: [PATCH 263/427] refs #6257 fix(saleQuantity): add isInPreparing restriction --- .../methods/sale/specs/updateQuantity.spec.js | 359 ----------------- modules/ticket/back/models/sale.js | 2 + modules/ticket/back/models/specs/sale.spec.js | 361 ++++++++++++++++++ 3 files changed, 363 insertions(+), 359 deletions(-) delete mode 100644 modules/ticket/back/methods/sale/specs/updateQuantity.spec.js create mode 100644 modules/ticket/back/models/specs/sale.spec.js diff --git a/modules/ticket/back/methods/sale/specs/updateQuantity.spec.js b/modules/ticket/back/methods/sale/specs/updateQuantity.spec.js deleted file mode 100644 index 0669711e7..000000000 --- a/modules/ticket/back/methods/sale/specs/updateQuantity.spec.js +++ /dev/null @@ -1,359 +0,0 @@ -/* eslint max-len: ["error", { "code": 150 }]*/ - -const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); - -describe('sale updateQuantity()', () => { - const ctx = { - req: { - accessToken: {userId: 9}, - headers: {origin: 'localhost:5000'}, - __: () => {} - } - }; - function getActiveCtx(userId) { - return { - active: { - accessToken: {userId}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - } - }; - } - - it('should add quantity if the quantity is greater than it should be and is role advanced', async() => { - const saleId = 17; - const buyerId = 35; - const ctx = { - req: { - accessToken: {userId: buyerId}, - headers: {origin: 'localhost:5000'}, - __: () => {} - } - }; - const tx = await models.Sale.beginTransaction({}); - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(buyerId)); - spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { - if (sqlStatement.includes('catalog_calcFromItem')) { - sqlStatement = `CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY - SELECT 100 as available;`; - params = null; - } - return models.Ticket.rawSql(sqlStatement, params, options); - }); - - try { - const options = {transaction: tx}; - - const isRoleAdvanced = await models.ACL.checkAccessAcl(ctx, 'Ticket', 'isRoleAdvanced', '*'); - - expect(isRoleAdvanced).toEqual(true); - - const originalLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, options); - - expect(originalLine.quantity).toEqual(30); - - const newQuantity = originalLine.quantity + 1; - await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); - - const modifiedLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, options); - - expect(modifiedLine.quantity).toEqual(newQuantity); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } - }); - - it('should update the quantity of a given sale current line', async() => { - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(9)); - - const tx = await models.Sale.beginTransaction({}); - const saleId = 25; - const newQuantity = 4; - - try { - const options = {transaction: tx}; - - const originalLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, options); - - expect(originalLine.quantity).toEqual(20); - - await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); - - const modifiedLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, options); - - expect(modifiedLine.quantity).toEqual(newQuantity); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } - }); - - it('should throw an error if the quantity is negative and it is not a refund ticket', async() => { - const ctx = { - req: { - accessToken: {userId: 1}, - headers: {origin: 'localhost:5000'}, - __: () => {} - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); - - const saleId = 17; - const newQuantity = -10; - - const tx = await models.Sale.beginTransaction({}); - - let error; - try { - const options = {transaction: tx}; - - await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - error = e; - } - - expect(error).toEqual(new Error('You can only add negative amounts in refund tickets')); - }); - - it('should update a negative quantity when is a ticket refund', async() => { - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(9)); - - const tx = await models.Sale.beginTransaction({}); - const saleId = 13; - const newQuantity = -10; - - try { - const options = {transaction: tx}; - - await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); - - const modifiedLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, options); - - expect(modifiedLine.quantity).toEqual(newQuantity); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } - }); - - it('should throw an error if the quantity is less than the minimum quantity of the item', async() => { - const ctx = { - req: { - accessToken: {userId: 1}, - headers: {origin: 'localhost:5000'}, - __: () => {} - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); - - const tx = await models.Sale.beginTransaction({}); - const itemId = 2; - const saleId = 17; - const minQuantity = 30; - const newQuantity = minQuantity - 1; - - let error; - try { - const options = {transaction: tx}; - - const item = await models.Item.findById(itemId, null, options); - await item.updateAttribute('minQuantity', minQuantity, options); - spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { - if (sqlStatement.includes('catalog_calcFromItem')) { - sqlStatement = `CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY - SELECT 100 as available;`; - params = null; - } - return models.Ticket.rawSql(sqlStatement, params, options); - }); - - await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - error = e; - } - - expect(error).toEqual(new Error('The amount cannot be less than the minimum')); - }); - - it('should change quantity if has minimum quantity and new quantity is equal than item available', async() => { - const ctx = { - req: { - accessToken: {userId: 1}, - headers: {origin: 'localhost:5000'}, - __: () => {} - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); - - const tx = await models.Sale.beginTransaction({}); - const itemId = 2; - const saleId = 17; - const minQuantity = 30; - const newQuantity = minQuantity - 1; - - try { - const options = {transaction: tx}; - - const item = await models.Item.findById(itemId, null, options); - await item.updateAttribute('minQuantity', minQuantity, options); - - spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { - if (sqlStatement.includes('catalog_calcFromItem')) { - sqlStatement = `CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY - SELECT ${newQuantity} as available;`; - params = null; - } - return models.Ticket.rawSql(sqlStatement, params, options); - }); - - await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } - }); - - describe('newPrice', () => { - it('should increase quantity if you have enough available and the new price is the same as the previous one', async() => { - const ctx = { - req: { - accessToken: {userId: 1}, - headers: {origin: 'localhost:5000'}, - __: () => {} - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); - - const tx = await models.Sale.beginTransaction({}); - const itemId = 2; - const saleId = 17; - const minQuantity = 30; - const newQuantity = 31; - - try { - const options = {transaction: tx}; - - const item = await models.Item.findById(itemId, null, options); - await item.updateAttribute('minQuantity', minQuantity, options); - spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { - if (sqlStatement.includes('catalog_calcFromItem')) { - sqlStatement = ` - CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY SELECT ${newQuantity} as available; - CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentPrice ENGINE = MEMORY SELECT 1 as grouping, 7.07 as price;`; - params = null; - } - return models.Ticket.rawSql(sqlStatement, params, options); - }); - - await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } - }); - - it('should increase quantity when the new price is lower than the previous one', async() => { - const ctx = { - req: { - accessToken: {userId: 1}, - headers: {origin: 'localhost:5000'}, - __: () => {} - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); - - const tx = await models.Sale.beginTransaction({}); - const itemId = 2; - const saleId = 17; - const minQuantity = 30; - const newQuantity = 31; - - try { - const options = {transaction: tx}; - - const item = await models.Item.findById(itemId, null, options); - await item.updateAttribute('minQuantity', minQuantity, options); - spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { - if (sqlStatement.includes('catalog_calcFromItem')) { - sqlStatement = ` - CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY SELECT ${newQuantity} as available; - CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentPrice ENGINE = MEMORY SELECT 1 as grouping, 1 as price;`; - params = null; - } - return models.Ticket.rawSql(sqlStatement, params, options); - }); - - await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } - }); - - it('should throw error when increase quantity and the new price is higher than the previous one', async() => { - const ctx = { - req: { - accessToken: {userId: 1}, - headers: {origin: 'localhost:5000'}, - __: () => {} - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); - - const tx = await models.Sale.beginTransaction({}); - const itemId = 2; - const saleId = 17; - const minQuantity = 30; - const newQuantity = 31; - - let error; - try { - const options = {transaction: tx}; - - const item = await models.Item.findById(itemId, null, options); - await item.updateAttribute('minQuantity', minQuantity, options); - spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { - if (sqlStatement.includes('catalog_calcFromItem')) { - sqlStatement = ` - CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY SELECT ${newQuantity} as available; - CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentPrice ENGINE = MEMORY SELECT 1 as grouping, 100000 as price;`; - params = null; - } - return models.Ticket.rawSql(sqlStatement, params, options); - }); - - await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - error = e; - } - - expect(error).toEqual(new Error('The price of the item changed')); - }); - }); -}); diff --git a/modules/ticket/back/models/sale.js b/modules/ticket/back/models/sale.js index 4b7ed1043..1c86ddc0c 100644 --- a/modules/ticket/back/models/sale.js +++ b/modules/ticket/back/models/sale.js @@ -69,6 +69,8 @@ module.exports = Self => { }, ctx.options); if (item.family == 'EMB') return; + if (await models.ACL.checkAccessAcl(ctx, 'Sale', 'isInPreparing', '*')) return; + await models.Sale.rawSql(`CALL catalog_calcFromItem(?,?,?,?)`, [ ticket.landed, ticket.addressFk, diff --git a/modules/ticket/back/models/specs/sale.spec.js b/modules/ticket/back/models/specs/sale.spec.js new file mode 100644 index 000000000..4af44c991 --- /dev/null +++ b/modules/ticket/back/models/specs/sale.spec.js @@ -0,0 +1,361 @@ +/* eslint max-len: ["error", { "code": 150 }]*/ + +const models = require('vn-loopback/server/server').models; +const LoopBackContext = require('loopback-context'); + +describe('sale model ', () => { + const ctx = { + req: { + accessToken: {userId: 9}, + headers: {origin: 'localhost:5000'}, + __: () => {} + } + }; + function getActiveCtx(userId) { + return { + active: { + accessToken: {userId}, + http: { + req: { + headers: {origin: 'http://localhost'} + } + } + } + }; + } + + describe('quantity field ', () => { + it('should add quantity if the quantity is greater than it should be and is role advanced', async() => { + const saleId = 17; + const buyerId = 35; + const ctx = { + req: { + accessToken: {userId: buyerId}, + headers: {origin: 'localhost:5000'}, + __: () => {} + } + }; + const tx = await models.Sale.beginTransaction({}); + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(buyerId)); + spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { + if (sqlStatement.includes('catalog_calcFromItem')) { + sqlStatement = `CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY + SELECT 100 as available;`; + params = null; + } + return models.Ticket.rawSql(sqlStatement, params, options); + }); + + try { + const options = {transaction: tx}; + + const isRoleAdvanced = await models.ACL.checkAccessAcl(ctx, 'Ticket', 'isRoleAdvanced', '*'); + + expect(isRoleAdvanced).toEqual(true); + + const originalLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, options); + + expect(originalLine.quantity).toEqual(30); + + const newQuantity = originalLine.quantity + 1; + await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); + + const modifiedLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, options); + + expect(modifiedLine.quantity).toEqual(newQuantity); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('should update the quantity of a given sale current line', async() => { + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(9)); + + const tx = await models.Sale.beginTransaction({}); + const saleId = 25; + const newQuantity = 4; + + try { + const options = {transaction: tx}; + + const originalLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, options); + + expect(originalLine.quantity).toEqual(20); + + await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); + + const modifiedLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, options); + + expect(modifiedLine.quantity).toEqual(newQuantity); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('should throw an error if the quantity is negative and it is not a refund ticket', async() => { + const ctx = { + req: { + accessToken: {userId: 1}, + headers: {origin: 'localhost:5000'}, + __: () => {} + } + }; + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); + + const saleId = 17; + const newQuantity = -10; + + const tx = await models.Sale.beginTransaction({}); + + let error; + try { + const options = {transaction: tx}; + + await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error).toEqual(new Error('You can only add negative amounts in refund tickets')); + }); + + it('should update a negative quantity when is a ticket refund', async() => { + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(9)); + + const tx = await models.Sale.beginTransaction({}); + const saleId = 13; + const newQuantity = -10; + + try { + const options = {transaction: tx}; + + await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); + + const modifiedLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, options); + + expect(modifiedLine.quantity).toEqual(newQuantity); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('should throw an error if the quantity is less than the minimum quantity of the item', async() => { + const ctx = { + req: { + accessToken: {userId: 1}, + headers: {origin: 'localhost:5000'}, + __: () => {} + } + }; + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); + + const tx = await models.Sale.beginTransaction({}); + const itemId = 2; + const saleId = 17; + const minQuantity = 30; + const newQuantity = minQuantity - 1; + + let error; + try { + const options = {transaction: tx}; + + const item = await models.Item.findById(itemId, null, options); + await item.updateAttribute('minQuantity', minQuantity, options); + spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { + if (sqlStatement.includes('catalog_calcFromItem')) { + sqlStatement = `CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY + SELECT 100 as available;`; + params = null; + } + return models.Ticket.rawSql(sqlStatement, params, options); + }); + + await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error).toEqual(new Error('The amount cannot be less than the minimum')); + }); + + it('should change quantity if has minimum quantity and new quantity is equal than item available', async() => { + const ctx = { + req: { + accessToken: {userId: 1}, + headers: {origin: 'localhost:5000'}, + __: () => {} + } + }; + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); + + const tx = await models.Sale.beginTransaction({}); + const itemId = 2; + const saleId = 17; + const minQuantity = 30; + const newQuantity = minQuantity - 1; + + try { + const options = {transaction: tx}; + + const item = await models.Item.findById(itemId, null, options); + await item.updateAttribute('minQuantity', minQuantity, options); + + spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { + if (sqlStatement.includes('catalog_calcFromItem')) { + sqlStatement = `CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY + SELECT ${newQuantity} as available;`; + params = null; + } + return models.Ticket.rawSql(sqlStatement, params, options); + }); + + await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + describe('newPrice', () => { + it('should increase quantity if you have enough available and the new price is the same as the previous one', async() => { + const ctx = { + req: { + accessToken: {userId: 1}, + headers: {origin: 'localhost:5000'}, + __: () => {} + } + }; + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); + + const tx = await models.Sale.beginTransaction({}); + const itemId = 2; + const saleId = 17; + const minQuantity = 30; + const newQuantity = 31; + + try { + const options = {transaction: tx}; + + const item = await models.Item.findById(itemId, null, options); + await item.updateAttribute('minQuantity', minQuantity, options); + spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { + if (sqlStatement.includes('catalog_calcFromItem')) { + sqlStatement = ` + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY SELECT ${newQuantity} as available; + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentPrice ENGINE = MEMORY SELECT 1 as grouping, 7.07 as price;`; + params = null; + } + return models.Ticket.rawSql(sqlStatement, params, options); + }); + + await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('should increase quantity when the new price is lower than the previous one', async() => { + const ctx = { + req: { + accessToken: {userId: 1}, + headers: {origin: 'localhost:5000'}, + __: () => {} + } + }; + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); + + const tx = await models.Sale.beginTransaction({}); + const itemId = 2; + const saleId = 17; + const minQuantity = 30; + const newQuantity = 31; + + try { + const options = {transaction: tx}; + + const item = await models.Item.findById(itemId, null, options); + await item.updateAttribute('minQuantity', minQuantity, options); + spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { + if (sqlStatement.includes('catalog_calcFromItem')) { + sqlStatement = ` + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY SELECT ${newQuantity} as available; + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentPrice ENGINE = MEMORY SELECT 1 as grouping, 1 as price;`; + params = null; + } + return models.Ticket.rawSql(sqlStatement, params, options); + }); + + await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('should throw error when increase quantity and the new price is higher than the previous one', async() => { + const ctx = { + req: { + accessToken: {userId: 1}, + headers: {origin: 'localhost:5000'}, + __: () => {} + } + }; + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); + + const tx = await models.Sale.beginTransaction({}); + const itemId = 2; + const saleId = 17; + const minQuantity = 30; + const newQuantity = 31; + + let error; + try { + const options = {transaction: tx}; + + const item = await models.Item.findById(itemId, null, options); + await item.updateAttribute('minQuantity', minQuantity, options); + spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { + if (sqlStatement.includes('catalog_calcFromItem')) { + sqlStatement = ` + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY SELECT ${newQuantity} as available; + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentPrice ENGINE = MEMORY SELECT 1 as grouping, 100000 as price;`; + params = null; + } + return models.Ticket.rawSql(sqlStatement, params, options); + }); + + await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error).toEqual(new Error('The price of the item changed')); + }); + }); + }); +}); From 5c69d9c7f01e38c1e8e07e4abb9e27efc383fbe5 Mon Sep 17 00:00:00 2001 From: pablone Date: Fri, 20 Oct 2023 12:53:54 +0200 Subject: [PATCH 264/427] fix: add await in async functions refs #5979 --- back/methods/collection/getTickets.js | 2 +- loopback/common/models/application.json | 6 ------ modules/claim/back/methods/claim/updateClaim.js | 10 +++++----- 3 files changed, 6 insertions(+), 12 deletions(-) diff --git a/back/methods/collection/getTickets.js b/back/methods/collection/getTickets.js index 82fbaf8b8..f04822697 100644 --- a/back/methods/collection/getTickets.js +++ b/back/methods/collection/getTickets.js @@ -26,7 +26,7 @@ module.exports = Self => { Self.getTickets = async(ctx, id, print, options) => { const userId = ctx.req.accessToken.userId; - const url = Self.app.models.Url.getUrl(); + const url = await Self.app.models.Url.getUrl(); const $t = ctx.req.__; const myOptions = {}; diff --git a/loopback/common/models/application.json b/loopback/common/models/application.json index cf0653fbb..3e6a742e2 100644 --- a/loopback/common/models/application.json +++ b/loopback/common/models/application.json @@ -13,12 +13,6 @@ "principalType": "ROLE", "principalId": "$everyone", "permission": "ALLOW" - }, - { - "property": "getUrl", - "principalType": "ROLE", - "principalId": "$everyone", - "permission": "ALLOW" },{ "accessType": "READ", "principalType": "ROLE", diff --git a/modules/claim/back/methods/claim/updateClaim.js b/modules/claim/back/methods/claim/updateClaim.js index f18e3a812..d99528413 100644 --- a/modules/claim/back/methods/claim/updateClaim.js +++ b/modules/claim/back/methods/claim/updateClaim.js @@ -91,16 +91,16 @@ module.exports = Self => { // When hasToPickUp has been changed if (salesPerson && changedHasToPickUp && updatedClaim.hasToPickUp) - notifyPickUp(ctx, salesPerson.id, claim); + await notifyPickUp(ctx, salesPerson.id, claim); // When claimState has been changed if (args.claimStateFk) { const newState = await models.ClaimState.findById(args.claimStateFk, null, myOptions); if (newState.hasToNotify) { if (newState.code == 'incomplete') - notifyStateChange(ctx, salesPerson.id, claim, newState.code); + await notifyStateChange(ctx, salesPerson.id, claim, newState.code); if (newState.code == 'canceled') - notifyStateChange(ctx, claim.workerFk, claim, newState.code); + await notifyStateChange(ctx, claim.workerFk, claim, newState.code); } } @@ -115,7 +115,7 @@ module.exports = Self => { async function notifyStateChange(ctx, workerId, claim, state) { const models = Self.app.models; - const url = models.Url.getUrl(); + const url = await models.Url.getUrl(); const $t = ctx.req.__; // $translate const message = $t(`Claim state has changed to ${state}`, { @@ -128,7 +128,7 @@ module.exports = Self => { async function notifyPickUp(ctx, workerId, claim) { const models = Self.app.models; - const url = models.Url.getUrl(); + const url = await models.Url.getUrl(); const $t = ctx.req.__; // $translate const message = $t('Claim will be picked', { From 4df39272d69b78930e2cb019baf959e6c186e9d8 Mon Sep 17 00:00:00 2001 From: pablone Date: Fri, 20 Oct 2023 13:08:39 +0200 Subject: [PATCH 265/427] remove: appiclation config refs #5979 --- loopback/common/models/application.json | 5 ----- 1 file changed, 5 deletions(-) diff --git a/loopback/common/models/application.json b/loopback/common/models/application.json index 3e6a742e2..f79001585 100644 --- a/loopback/common/models/application.json +++ b/loopback/common/models/application.json @@ -13,11 +13,6 @@ "principalType": "ROLE", "principalId": "$everyone", "permission": "ALLOW" - },{ - "accessType": "READ", - "principalType": "ROLE", - "principalId": "$everyone", - "permission": "ALLOW" } ] } From 2edfacb91c4c14e3120b82e9c84fe10a3e995577 Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 23 Oct 2023 07:33:52 +0200 Subject: [PATCH 266/427] refs #5979 fix(sendCheckingPresence)! --- back/methods/chat/sendCheckingPresence.js | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/back/methods/chat/sendCheckingPresence.js b/back/methods/chat/sendCheckingPresence.js index 7bba96d59..85b66e94b 100644 --- a/back/methods/chat/sendCheckingPresence.js +++ b/back/methods/chat/sendCheckingPresence.js @@ -27,15 +27,19 @@ module.exports = Self => { Self.sendCheckingPresence = async(ctx, recipientId, message) => { if (!recipientId) return false; const models = Self.app.models; - const sender = ctx.req.accessToken.userId; - const recipient = recipientId; + + const userId = ctx.req.accessToken.userId; + const sender = await models.VnUser.findById(userId, {fields: ['id']}); + const recipient = await models.VnUser.findById(recipientId, null); // Prevent sending messages to yourself - if (recipientId == sender) return false; + if (recipientId == userId) return false; if (!recipient) - throw new Error(`Could not send message "${message}" to worker id ${recipientId} from user ${sender}`); + throw new Error(`Could not send message "${message}" to worker id ${recipientId} from user ${userId}`); + if (process.env.NODE_ENV == 'test') - message = `[Test:Environment to user ${sender}] ` + message; + message = `[Test:Environment to user ${userId}] ` + message; + const chat = await models.Chat.create({ senderFk: sender.id, recipient: `@${recipient.name}`, From cf856a585bba1be47c63e66794df6ffef4f5467a Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 23 Oct 2023 09:50:00 +0200 Subject: [PATCH 267/427] refs #6199 fix(sale_quantity): add isReduction --- modules/ticket/back/models/sale.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/modules/ticket/back/models/sale.js b/modules/ticket/back/models/sale.js index 1c86ddc0c..cce6343ec 100644 --- a/modules/ticket/back/models/sale.js +++ b/modules/ticket/back/models/sale.js @@ -33,6 +33,7 @@ module.exports = Self => { const itemId = changes?.itemFk || instance?.itemFk; const oldQuantity = instance?.quantity ?? null; const quantityAdded = newQuantity - oldQuantity; + const isReduction = oldQuantity && newQuantity <= oldQuantity; const ticket = await models.Ticket.findById( ticketId, @@ -81,7 +82,7 @@ module.exports = Self => { const [itemInfo] = await models.Sale.rawSql(`SELECT available FROM tmp.ticketCalculateItem`, null, ctx.options); - if (!itemInfo?.available || itemInfo.available < quantityAdded) + if ((!isReduction && !itemInfo?.available) || itemInfo.available < quantityAdded) throw new UserError(`This item is not available`); if (await models.ACL.checkAccessAcl(ctx, 'Ticket', 'isRoleAdvanced', '*')) return; @@ -89,7 +90,7 @@ module.exports = Self => { if (newQuantity < item.minQuantity && newQuantity != itemInfo?.available) throw new UserError('The amount cannot be less than the minimum'); - if (ctx.isNewInstance || newQuantity <= oldQuantity) return; + if (ctx.isNewInstance || isReduction) return; const [saleGrouping] = await models.Sale.rawSql(` SELECT t.price newPrice From 247aa5af2a9a1ffd4ba829d1ecfe776ceb8feb48 Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 23 Oct 2023 09:52:06 +0200 Subject: [PATCH 268/427] refs #6199 fix(sale_quantity): add isReduction --- modules/ticket/back/models/sale.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/modules/ticket/back/models/sale.js b/modules/ticket/back/models/sale.js index cce6343ec..99cfeeeea 100644 --- a/modules/ticket/back/models/sale.js +++ b/modules/ticket/back/models/sale.js @@ -81,13 +81,14 @@ module.exports = Self => { ctx.options); const [itemInfo] = await models.Sale.rawSql(`SELECT available FROM tmp.ticketCalculateItem`, null, ctx.options); + const available = itemInfo?.available; - if ((!isReduction && !itemInfo?.available) || itemInfo.available < quantityAdded) + if ((!isReduction && !available) || available < quantityAdded) throw new UserError(`This item is not available`); if (await models.ACL.checkAccessAcl(ctx, 'Ticket', 'isRoleAdvanced', '*')) return; - if (newQuantity < item.minQuantity && newQuantity != itemInfo?.available) + if (newQuantity < item.minQuantity && newQuantity != available) throw new UserError('The amount cannot be less than the minimum'); if (ctx.isNewInstance || isReduction) return; From ae27aa5b1e61c74bfbbc1b7b8af63642072acc6d Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 23 Oct 2023 10:08:26 +0200 Subject: [PATCH 269/427] fix: test to dev --- back/models/vn-user.js | 1 + 1 file changed, 1 insertion(+) diff --git a/back/models/vn-user.js b/back/models/vn-user.js index ccc60fe86..de5bf7b63 100644 --- a/back/models/vn-user.js +++ b/back/models/vn-user.js @@ -1,6 +1,7 @@ const vnModel = require('vn-loopback/common/models/vn-model'); const {Email} = require('vn-print'); const ForbiddenError = require('vn-loopback/util/forbiddenError'); +const LoopBackContext = require('loopback-context'); module.exports = function(Self) { vnModel(Self); From 6e3517b40f3e3e0ae7162b10a4616622b93c25e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Mon, 23 Oct 2023 14:51:09 +0200 Subject: [PATCH 270/427] refs #4707 fix: problemas fichadas y test --- db/changes/234003/.gitkeep | 0 db/changes/234003/00-workerTimeControl.sql | 42 ++ .../234003/01-timeControl_calculate.sql | 194 ++++++ .../234003/02-workerTimeControl_clockIn.sql | 286 +++++++++ db/dump/fixtures.sql | 40 +- .../vn/timeControl_calculateByUser.spec.js | 91 --- db/tests/vn/workerTimeControlCheck.spec.js | 580 ------------------ .../specs/timeEntry.spec.js | 443 ++++++++----- 8 files changed, 844 insertions(+), 832 deletions(-) create mode 100644 db/changes/234003/.gitkeep create mode 100644 db/changes/234003/00-workerTimeControl.sql create mode 100644 db/changes/234003/01-timeControl_calculate.sql create mode 100644 db/changes/234003/02-workerTimeControl_clockIn.sql delete mode 100644 db/tests/vn/timeControl_calculateByUser.spec.js delete mode 100644 db/tests/vn/workerTimeControlCheck.spec.js diff --git a/db/changes/234003/.gitkeep b/db/changes/234003/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/db/changes/234003/00-workerTimeControl.sql b/db/changes/234003/00-workerTimeControl.sql new file mode 100644 index 000000000..7b41278b0 --- /dev/null +++ b/db/changes/234003/00-workerTimeControl.sql @@ -0,0 +1,42 @@ +UPDATE `vn`.`workerTimeControlConfig` + SET `timeToBreakTime` = 18000; + +ALTER TABLE `vn`.`workerTimeControlConfig` + DROP COLUMN IF EXISTS `maxTimeToBreak`; +ALTER TABLE `vn`.`workerTimeControlConfig` + ADD COLUMN maxTimeToBreak INT DEFAULT 3600 NULL; + +ALTER TABLE `vn`.`workerTimeControlConfig` + DROP COLUMN IF EXISTS `maxWorkShortCycle`; + +ALTER TABLE `vn`.`workerTimeControlConfig` + ADD COLUMN `maxWorkShortCycle` INT(10) UNSIGNED DEFAULT 561600 + COMMENT 'Máximo tiempo que un trabajador puede estar trabajando con el que adquirirá el derecho a un descando semanal corto'; + +ALTER TABLE `vn`.`workerTimeControlConfig` + DROP COLUMN IF EXISTS `maxWorkLongCycle`; + +ALTER TABLE `vn`.`workerTimeControlConfig` + ADD COLUMN `maxWorkLongCycle` INT(10) UNSIGNED DEFAULT 950400 + COMMENT 'Máximo tiempo que un trabajador puede estar trabajando con el que adquirirá el derecho a un descando semanal largo'; + +CREATE TABLE IF NOT EXISTS `vn`.`workerTimeControlError` ( + `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, + `code` char(35) NOT NULL, + `description` varchar(255) NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `code` (`code`) +) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; + + +INSERT IGNORE INTO `vn`.`workerTimeControlError` (`code`, `description`) + VALUES + ('IS_NOT_ALLOWED_FUTURE', 'No se permite fichar a futuro'), + ('INACTIVE_BUSINESS', 'No hay un contrato en vigor'), + ('IS_NOT_ALLOWED_WORK', 'No está permitido trabajar'), + ('ODD_WORKERTIMECONTROL', 'Fichadas impares'), + ('DAY_MAX_TIME', 'Superado el tiempo máximo entre entrada y salida'), + ('BREAK_DAY', 'Descanso diario'), + ('BREAK_WEEK', 'Descanso semanal'), + ('WRONG_DIRECTION', 'Dirección incorrecta'), + ('UNDEFINED_ERROR', 'Error sin definir'); \ No newline at end of file diff --git a/db/changes/234003/01-timeControl_calculate.sql b/db/changes/234003/01-timeControl_calculate.sql new file mode 100644 index 000000000..93d88c047 --- /dev/null +++ b/db/changes/234003/01-timeControl_calculate.sql @@ -0,0 +1,194 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`timeControl_calculate`( + vDatedFrom DATETIME, + vDatedTo DATETIME) +BEGIN +/* + * Agrupa por trabajador y día, el tiempo de trabajo y descanso retribuido(si tiene). + * Los registros horarios incorrectos (tmp.timeControlError) no se considerarán. + * Si un trabajador ha trabajado más de un cierto umbral de tiempo (vTimeToBreakTime) + * y no ha tenido descansos que superen un parámetro determinado(vMaxTimeToBreak), + * se le añadirá un tiempo de descanso (vBreakTime) a sus horas trabajadas. + * El tiempo de descanso solo se añade si el trabajador realmente disfrutó del descanso. + * Si disfrutó de menos tiempo de descanso, solo se añade el tiempo que disfrutó. + * + * @param vDatedFrom + * @param vDatedTo + * + * @return tmp.timeControlCalculate + * (workerFk, dated, timeWorkSeconds, timeWorkSexagesimal, timeWorkDecimal, timed) + */ + DECLARE vHourSeconds INTEGER; + DECLARE vDatedFromYesterday DATETIME; + DECLARE vDatedToTomorrow DATETIME; + DECLARE vTimeToBreakTime INT; + DECLARE vBreakTime INT; + DECLARE vMaxTimeToBreak INT; + + SELECT DATE_SUB(vDatedFrom, INTERVAL 1 DAY), DATE_ADD(vDatedTo, INTERVAL 1 DAY) + INTO vDatedFromYesterday, vDatedToTomorrow; + + SELECT timeToBreakTime, breakTime, maxTimeToBreak, TIME_TO_SEC('01:00:00') + INTO vTimeToBreakTime, vBreakTime, vMaxTimeToBreak, vHourSeconds + FROM workerTimeControlConfig + LIMIT 1; + + CALL timeControl_getError(vDatedFromYesterday, vDatedToTomorrow); + + CREATE OR REPLACE TEMPORARY TABLE tmp.workerTimeControl + (INDEX(userFk, timed), INDEX(timed), INDEX(direction)) + ENGINE = MEMORY + SELECT wtc.userFk, + wtc.timed, + DATE(wtc.timed) dated, + wtc.direction, + TRUE isReal + FROM workerTimeControl wtc + JOIN tmp.`user` u ON u.userFk = wtc.userFk + LEFT JOIN ( + SELECT wtc.userFk, MIN(wtc.timed) firstIn + FROM workerTimeControl wtc + JOIN tmp.`user` u ON u.userFk = wtc.userFk + LEFT JOIN tmp.timeControlError tce ON tce.id = wtc.id + WHERE wtc.timed BETWEEN vDatedFromYesterday AND vDatedToTomorrow + AND wtc.direction = 'in' + AND tce.id IS NULL + GROUP BY userFk + ) fi ON wtc.userFk = fi.userFk + LEFT JOIN ( + SELECT wtc.userFk, MAX(wtc.timed) lastOut + FROM workerTimeControl wtc + JOIN tmp.`user` u ON u.userFk = wtc.userFk + LEFT JOIN tmp.timeControlError tce ON tce.id = wtc.id + WHERE wtc.timed BETWEEN vDatedFromYesterday AND vDatedToTomorrow + AND wtc.direction = 'out' + AND tce.id IS NULL + GROUP BY userFk + ) lo ON wtc.userFk = lo.userFk + LEFT JOIN tmp.timeControlError tce ON tce.id = wtc.id + WHERE wtc.timed BETWEEN fi.firstIn AND lo.lastOut + AND tce.id IS NULL + ORDER BY wtc.userFk, wtc.timed; + + CREATE OR REPLACE TEMPORARY TABLE tmp.wtcToinsert + (INDEX(timed)) + ENGINE = MEMORY + WITH wtc AS( + SELECT timed, + userFk, + dated, + direction, + LEAD(dated) OVER + (PARTITION BY userFk, dated ORDER BY timed) nextDay, + LEAD(userFk) OVER + (PARTITION BY userFk ORDER BY timed) nextUserFk, + ROW_NUMBER() OVER (ORDER BY userFk, timed) MOD 2 isOdd + FROM tmp.workerTimeControl + WHERE timed BETWEEN vDatedFromYesterday AND vDatedToTomorrow + ORDER BY userFk, timed + ), wtcToinsert AS( + SELECT userFk, + dated, + IF(userFk = nextUserFk + AND nextDay IS NULL + AND isOdd + AND direction <> 'out', TRUE, FALSE) outNextDay, + IF(userFk = nextUserFk + AND nextDay IS NULL + AND NOT isOdd + AND direction <> 'out', TRUE, FALSE) outNextDayWhitBreak + FROM wtc + HAVING outNextDay OR outNextDayWhitBreak + )SELECT userFk, util.dayEnd(dated) timed, 'out' direction + FROM wtcToinsert + WHERE outNextDay + UNION ALL + SELECT userFk, dated + INTERVAL 1 DAY, 'in' + FROM wtcToinsert + WHERE outNextDay + UNION ALL + SELECT userFk, util.dayEnd(dated) - INTERVAL 1 SECOND, 'middle' + FROM wtcToinsert + WHERE outNextDayWhitBreak + UNION ALL + SELECT userFk, util.dayEnd(dated), 'out' + FROM wtcToinsert + WHERE outNextDayWhitBreak + UNION ALL + SELECT userFk, dated + INTERVAL 1 DAY, 'in' + FROM wtcToinsert + WHERE outNextDayWhitBreak + UNION ALL + SELECT userFk, dated + INTERVAL 1 DAY + INTERVAL 1 SECOND, 'middle' + FROM wtcToinsert + WHERE outNextDayWhitBreak; + + INSERT INTO tmp.workerTimeControl (userFk, timed, dated, direction, isReal) + SELECT userFk, timed, DATE(timed), direction, FALSE + FROM tmp.wtcToinsert; + + SET @accumulatedForBreakTime = 0; + SET @oldrealDay = NULL; + CREATE OR REPLACE TEMPORARY TABLE tmp.timeControlCalculate + WITH workerTimed AS ( + SELECT + userFk, + dated, + timed, + (direction ='in' AND isReal) breakPoint, + SUM(CASE WHEN (direction ='in' AND isReal) THEN TRUE ELSE FALSE END) + OVER (ORDER BY userFk, timed) AS realDay, + TIMESTAMPDIFF(SECOND, LAG(timed) + OVER (PARTITION BY userFk, dated ORDER BY timed), timed) gapTime, + ROW_NUMBER() + OVER (PARTITION BY userFk, dated ORDER BY timed) MOD 2 isOdd + FROM tmp.workerTimeControl + WHERE timed BETWEEN vDatedFromYesterday AND vDatedToTomorrow + ), accumulated AS ( + SELECT SUM(IF(isOdd, 0, gapTime)) + OVER (PARTITION BY userFk,dated ORDER BY userFk,timed) accumulatedWorkTime, + SUM(IF(NOT isOdd OR breakPoint, 0, IFNULL(gapTime, 0))) + OVER (PARTITION BY realDay ORDER BY realDay,timed) accumulatedBreakTime, + IF(realDay <> @oldrealDay OR (isOdd AND gapTime >= vMaxTimeToBreak), + @accumulatedForBreakTime := 0, + @accumulatedForBreakTime := @accumulatedForBreakTime + + IF(isOdd, 0, gapTime )) accumulatedForBreakTime, + @oldrealDay := realDay, + userFk, + dated, + realDay + FROM workerTimed + ), totalWorked AS ( + SELECT userFk, + dated, + MAX(accumulatedWorkTime) + + IF(MAX(accumulatedForBreakTime) >= vTimeToBreakTime, + LEAST(vBreakTime, MAX(accumulatedBreakTime)), + 0) timeWorkSeconds + FROM accumulated + GROUP BY userFk, dated + )SELECT tw.userFk, + tw.dated, + timeWorkSeconds, + SEC_TO_TIME(timeWorkSeconds) timeWorkSexagesimal, + timeWorkSeconds / vHourSeconds timeWorkDecimal, + sub.tableTimed + FROM totalWorked tw + JOIN ( + SELECT userFk, + dated, + GROUP_CONCAT(DATE_FORMAT(timed, "%H:%i") ORDER BY timed ASC + SEPARATOR ' - ')tableTimed + FROM tmp.workerTimeControl + WHERE timed BETWEEN vDatedFromYesterday AND vDatedToTomorrow + AND isReal + GROUP BY userFk, dated + )sub ON sub.dated = tw.dated + AND sub.userFk = tw.userFk + WHERE tw.dated BETWEEN vDatedFrom AND vDatedTo; + + DROP TEMPORARY TABLE tmp.timeControlError; + DROP TEMPORARY TABLE tmp.wtcToinsert; + DROP TEMPORARY TABLE tmp.workerTimeControl; +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/changes/234003/02-workerTimeControl_clockIn.sql b/db/changes/234003/02-workerTimeControl_clockIn.sql new file mode 100644 index 000000000..7cc9e7831 --- /dev/null +++ b/db/changes/234003/02-workerTimeControl_clockIn.sql @@ -0,0 +1,286 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`workerTimeControl_clockIn`( + vWorkerFk INT, + vTimed DATETIME, + vDirection VARCHAR(10) +) +BEGIN +/** + * Verifica si el empleado puede fichar + * @param vWorkerFk Identificador del trabajador + * @param vTimed valor de la fichada, IF vTimed IS NULL vTimed = NOW + * @param vDirection solo se pueden pasa los valores del campo + * workerTimeControl.direction ENUM('in', 'out', 'middle') + * @return Si todo es correcto, retorna el número de id la tabla workerTimeControl. + * Si hay algún problema, devuelve el mesaje a que se debe mostrar al usuario + * Solo retorna el primer problema, en caso de no ocurrir ningún error se añadirá + * fichada a la tabla vn.workerTimeControl + */ + + DECLARE vLastIn DATETIME; + DECLARE vLastOut DATETIME; + DECLARE vNextIn DATETIME; + DECLARE vNextOut DATETIME; + DECLARE vNextDirection ENUM('in', 'out'); + DECLARE vLastDirection ENUM('in', 'out'); + DECLARE vDayMaxTime INTEGER; + DECLARE vDayBreak INT; + DECLARE vShortWeekBreak INT; + DECLARE vLongWeekBreak INT; + DECLARE vWeekScope INT; + DECLARE vMailTo VARCHAR(50) DEFAULT NULL; + DECLARE vUserName VARCHAR(50) DEFAULT NULL; + DECLARE vIsError BOOLEAN DEFAULT FALSE; + DECLARE vErrorMessage VARCHAR(255) DEFAULT NULL; + DECLARE vErrorCode VARCHAR(50); + DECLARE vDated DATE; + DECLARE vIsAllowedToWork VARCHAR(50); + DECLARE vIsManual BOOLEAN DEFAULT TRUE; + DECLARE vMaxWorkShortCycle INT; + DECLARE vMaxWorkLongCycle INT; + + DECLARE EXIT HANDLER FOR SQLSTATE '45000' + BEGIN + + SELECT CONCAT(u.name, '@verdnatura.es'), + CONCAT(w.firstName, ' ', w.lastName) + INTO vMailTo, vUserName + FROM account.user u + JOIN worker w ON w.bossFk = u.id + WHERE w.id = vWorkerFk; + + SELECT `description` INTO vErrorMessage + FROM workerTimeControlError + WHERE `code` = vErrorCode; + + IF vErrorMessage IS NULL THEN + SET vErrorMessage = 'Error sin definir'; + END IF; + + SELECT vErrorMessage `error`; + SELECT CONCAT(vUserName, + ' no ha podido fichar por el siguiente problema: ', + vErrorMessage) + INTO vErrorMessage; + + CALL mail_insert( vMailTo, vMailTo, 'Error al fichar', vErrorMessage); + END; + + IF (vTimed IS NULL) THEN + SET vTimed = util.VN_NOW(); + SET vIsManual = FALSE; + END IF; + + SET vDated = DATE(vTimed); + + SELECT IF(pc.name = 'Conductor +3500kg', + wc.dayBreakDriver, + wc.dayBreak), + wc.shortWeekBreak, + wc.longWeekBreak, + wc.weekScope, + wc.dayMaxTime, + wc.maxWorkShortCycle, + wc.maxWorkLongCycle + INTO vDayBreak, + vShortWeekBreak, + vLongWeekBreak, + vWeekScope, + vDayMaxTime, + vMaxWorkShortCycle, + vMaxWorkLongCycle + FROM business b + JOIN professionalCategory pc + ON pc.id = b.workerBusinessProfessionalCategoryFk + JOIN workerTimeControlConfig wc + WHERE b.workerFk = vWorkerFk + AND vDated BETWEEN b.started AND IFNULL(b.ended, vDated); + + -- CONTRATO EN VIGOR + IF vDayBreak IS NULL THEN + SET vErrorCode = 'INACTIVE_BUSINESS'; + CALL util.throw(vErrorCode); + END IF; + + -- FICHADAS A FUTURO + IF vTimed > util.VN_NOW() + INTERVAL 1 MINUTE THEN + SET vErrorCode = 'IS_NOT_ALLOWED_FUTURE'; + CALL util.throw(vErrorCode); + END IF; + + -- VERIFICAR SI ESTÁ PERMITIDO TRABAJAR + CALL timeBusiness_calculateByWorker(vWorkerFk, vDated, vDated); + SELECT isAllowedToWork INTO vIsAllowedToWork + FROM tmp.timeBusinessCalculate; + DROP TEMPORARY TABLE tmp.timeBusinessCalculate; + + IF NOT vIsAllowedToWork THEN + SET vErrorCode = 'IS_NOT_ALLOWED_WORK'; + CALL util.throw(vErrorCode); + END IF; + + -- DIRECCION CORRECTA + CALL workerTimeControl_direction(vWorkerFk, vTimed); + IF (SELECT + IF(IF(option1 IN ('inMiddle', 'outMiddle'), + 'middle', + option1) <> vDirection + AND IF(option2 IN ('inMiddle', 'outMiddle'), + 'middle', + IFNULL(option2, '')) <> vDirection, + TRUE , + FALSE) + FROM tmp.workerTimeControlDirection + ) THEN + SET vIsError = TRUE; + END IF; + + DROP TEMPORARY TABLE tmp.workerTimeControlDirection; + IF vIsError THEN + SET vErrorCode = 'WRONG_DIRECTION'; + CALL util.throw(vErrorCode); + END IF; + + -- FICHADAS IMPARES + SELECT timed INTO vLastIn + FROM workerTimeControl + WHERE userFk = vWorkerFk + AND direction = 'in' + AND timed < vTimed + ORDER BY timed DESC + LIMIT 1; + + IF (SELECT IF(vDirection = 'in', + MOD(COUNT(*), 2) , + IF (vDirection = 'out', NOT MOD(COUNT(*), 2), FALSE)) + FROM workerTimeControl + WHERE userFk = vWorkerFk + AND timed BETWEEN vLastIn AND vTimed + ) THEN + SET vErrorCode = 'ODD_WORKERTIMECONTROL'; + CALL util.throw(vErrorCode); + END IF; + + -- DESCANSO DIARIO + SELECT timed INTO vLastOut + FROM workerTimeControl + WHERE userFk = vWorkerFk + AND direction = 'out' + AND timed < vTimed + ORDER BY timed DESC + LIMIT 1; + + SELECT timed INTO vNextIn + FROM workerTimeControl + WHERE userFk = vWorkerFk + AND direction = 'in' + AND timed > vTimed + ORDER BY timed ASC + LIMIT 1; + + CASE vDirection + WHEN 'in' THEN + IF UNIX_TIMESTAMP(vTimed) - UNIX_TIMESTAMP(vLastOut) <= vDayBreak THEN + SET vIsError = TRUE; + END IF; + WHEN 'out' THEN + IF UNIX_TIMESTAMP(vNextIn) - UNIX_TIMESTAMP(vTimed) <= vDayBreak THEN + SET vIsError = TRUE; + END IF; + ELSE BEGIN END; + END CASE; + + IF vIsError THEN + SET vErrorCode = 'BREAK_DAY'; + CALL util.throw(vErrorCode); + END IF; + + + + IF (vDirection IN('in', 'out')) THEN + -- VERIFICA MAXIMO TIEMPO DESDE ENTRADA HASTA LA SALIDA + + SELECT timed INTO vNextOut + FROM workerTimeControl + WHERE userFk = vWorkerFk + AND direction = 'out' + AND timed > vTimed + ORDER BY timed ASC + LIMIT 1; + + SELECT direction INTO vNextDirection + FROM workerTimeControl + WHERE userFk = vWorkerFk + AND direction IN('in','out') + AND timed > vTimed + ORDER BY timed ASC + LIMIT 1; + + SELECT direction INTO vLastDirection + FROM workerTimeControl + WHERE userFk = vWorkerFk + AND direction IN('in', 'out') + AND timed < vTimed + ORDER BY timed ASC + LIMIT 1; + + IF (vDirection ='in' + AND vNextDirection = 'out' + AND UNIX_TIMESTAMP(vNextOut) - UNIX_TIMESTAMP(vTimed) > vDayMaxTime) OR + (vDirection ='out' + AND vLastDirection = 'in' + AND UNIX_TIMESTAMP(vTimed) -UNIX_TIMESTAMP(vLastIn) > vDayMaxTime) THEN + SET vErrorCode = 'DAY_MAX_TIME'; + CALL util.throw(vErrorCode); + END IF; + + -- VERIFICA DESCANSO SEMANAL + + WITH wtc AS( + (SELECT timed + FROM vn.workerTimeControl + WHERE userFk = vWorkerFk + AND direction IN ('in', 'out') + AND timed BETWEEN vTimed - INTERVAL (vWeekScope * 2) SECOND + AND vTimed + INTERVAL (vWeekScope * 2) SECOND ) + UNION + (SELECT vTimed) + ), wtcGap AS( + SELECT timed, + TIMESTAMPDIFF(SECOND, LAG(timed) OVER (ORDER BY timed), timed) gap + FROM wtc + ORDER BY timed + ), wtcBreak AS( + SELECT timed, + IF(IFNULL(gap, 0) > vShortWeekBreak, TRUE, FALSE) hasShortBreak, + IF(IFNULL(gap, 0) > vLongWeekBreak, TRUE, FALSE) hasLongBreak + FROM wtcGap + ORDER BY timed + ), wtcBreakCounter AS( + SELECT timed, + SUM(hasShortBreak) OVER (ORDER BY timed) breakCounter , + LEAD(hasLongBreak) OVER (ORDER BY timed) nextHasLongBreak + FROM wtcBreak + )SELECT TIMESTAMPDIFF(SECOND, MIN(timed), MAX(timed)) > vMaxWorkLongCycle OR + (TIMESTAMPDIFF(SECOND, MIN(timed), MAX(timed))> vMaxWorkShortCycle + AND NOT SUM(IFNULL(nextHasLongBreak, 1))) + hasError INTO vIsError + FROM wtcBreakCounter + GROUP BY breakCounter + HAVING hasError + LIMIT 1; + + IF vIsError THEN + SET vErrorCode = 'BREAK_WEEK'; + CALL util.throw(vErrorCode); + END IF; + END IF; + + -- SE PERMITE FICHAR + INSERT INTO workerTimeControl(userFk, timed, direction, `manual`) + VALUES(vWorkerFk, vTimed, vDirection, vIsManual); + + SELECT LAST_INSERT_ID() id; + +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index ab7615591..ee13234fa 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -2003,6 +2003,10 @@ UPDATE `vn`.`business` b SET b.`departmentFk` = 43 WHERE b.id IN(18, 19); +UPDATE `vn`.`business` b + SET b.`started` = b.`started` - INTERVAL 100 DAY + WHERE b.id = 1107; + INSERT INTO `vn`.`workCenterHoliday` (`workCenterFk`, `days`, `year`) VALUES ('1', '27.5', YEAR(util.VN_CURDATE())), @@ -2051,22 +2055,22 @@ INSERT INTO `vn`.`absenceType` (`id`, `name`, `rgb`, `code`, `holidayEntitlement INSERT INTO `vn`.`calendar` (`businessFk`, `dayOffTypeFk`, `dated`) VALUES - (1, 6, IF(MONTH(util.VN_CURDATE()) = 12 AND DAY(util.VN_CURDATE()) > 10, DATE_ADD(util.VN_CURDATE(), INTERVAL -10 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL 10 DAY))), - (1106, 1, IF(MONTH(util.VN_CURDATE()) = 12 AND DAY(util.VN_CURDATE()) > 10, DATE_ADD(util.VN_CURDATE(), INTERVAL -10 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL 10 DAY))), - (1106, 1, IF(MONTH(util.VN_CURDATE()) = 12 AND DAY(util.VN_CURDATE()) > 10, DATE_ADD(util.VN_CURDATE(), INTERVAL -11 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL 11 DAY))), - (1106, 1, IF(MONTH(util.VN_CURDATE()) = 12 AND DAY(util.VN_CURDATE()) > 10, DATE_ADD(util.VN_CURDATE(), INTERVAL -12 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL 12 DAY))), - (1106, 1, IF(MONTH(util.VN_CURDATE()) = 12 AND DAY(util.VN_CURDATE()) > 10, DATE_ADD(util.VN_CURDATE(), INTERVAL -20 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL 20 DAY))), - (1106, 2, IF(MONTH(util.VN_CURDATE()) >= 1 AND DAY(util.VN_CURDATE()) > 20, DATE_ADD(util.VN_CURDATE(), INTERVAL -13 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL 8 DAY))), - (1106, 1, IF(MONTH(util.VN_CURDATE()) >= 1 AND DAY(util.VN_CURDATE()) > 20, DATE_ADD(util.VN_CURDATE(), INTERVAL -14 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL 9 DAY))), - (1106, 2, IF(MONTH(util.VN_CURDATE()) >= 1 AND DAY(util.VN_CURDATE()) > 20, DATE_ADD(util.VN_CURDATE(), INTERVAL -15 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL 7 DAY))), - (1107, 1, IF(MONTH(util.VN_CURDATE()) = 12 AND DAY(util.VN_CURDATE()) > 10, DATE_ADD(util.VN_CURDATE(), INTERVAL -10 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL 10 DAY))), - (1107, 1, IF(MONTH(util.VN_CURDATE()) = 12 AND DAY(util.VN_CURDATE()) > 10, DATE_ADD(util.VN_CURDATE(), INTERVAL -11 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL 11 DAY))), - (1107, 1, IF(MONTH(util.VN_CURDATE()) = 12 AND DAY(util.VN_CURDATE()) > 10, DATE_ADD(util.VN_CURDATE(), INTERVAL -12 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL 12 DAY))), - (1107, 1, IF(MONTH(util.VN_CURDATE()) = 12 AND DAY(util.VN_CURDATE()) > 10, DATE_ADD(util.VN_CURDATE(), INTERVAL -20 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL 20 DAY))), - (1107, 2, IF(MONTH(util.VN_CURDATE()) >= 1 AND DAY(util.VN_CURDATE()) > 20, DATE_ADD(util.VN_CURDATE(), INTERVAL -13 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL 8 DAY))), - (1107, 1, IF(MONTH(util.VN_CURDATE()) >= 1 AND DAY(util.VN_CURDATE()) > 20, DATE_ADD(util.VN_CURDATE(), INTERVAL -14 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL 9 DAY))), - (1107, 2, IF(MONTH(util.VN_CURDATE()) >= 1 AND DAY(util.VN_CURDATE()) > 20, DATE_ADD(util.VN_CURDATE(), INTERVAL -15 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL 7 DAY))), - (1107, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL - 16 DAY)); + (1, 6, IF(MONTH(util.VN_CURDATE()) = 12 AND DAY(util.VN_CURDATE()) > 10, util.VN_CURDATE() - INTERVAL 10 DAY, util.VN_CURDATE() + INTERVAL 10 DAY)), + (1106, 1, IF(MONTH(util.VN_CURDATE()) = 12 AND DAY(util.VN_CURDATE()) > 10, util.VN_CURDATE() - INTERVAL 10 DAY, util.VN_CURDATE() + INTERVAL 10 DAY)), + (1106, 1, IF(MONTH(util.VN_CURDATE()) = 12 AND DAY(util.VN_CURDATE()) > 10, util.VN_CURDATE() - INTERVAL 11 DAY, util.VN_CURDATE() + INTERVAL 11 DAY)), + (1106, 1, IF(MONTH(util.VN_CURDATE()) = 12 AND DAY(util.VN_CURDATE()) > 10, util.VN_CURDATE() - INTERVAL 12 DAY, util.VN_CURDATE() + INTERVAL 12 DAY)), + (1106, 1, IF(MONTH(util.VN_CURDATE()) = 12 AND DAY(util.VN_CURDATE()) > 10, util.VN_CURDATE() - INTERVAL 20 DAY, util.VN_CURDATE() + INTERVAL 20 DAY)), + (1106, 2, IF(MONTH(util.VN_CURDATE()) >= 1 AND DAY(util.VN_CURDATE()) > 20, util.VN_CURDATE() - INTERVAL 13 DAY, util.VN_CURDATE() + INTERVAL 8 DAY)), + (1106, 1, IF(MONTH(util.VN_CURDATE()) >= 1 AND DAY(util.VN_CURDATE()) > 20, util.VN_CURDATE() - INTERVAL 14 DAY, util.VN_CURDATE() + INTERVAL 9 DAY)), + (1106, 2, IF(MONTH(util.VN_CURDATE()) >= 1 AND DAY(util.VN_CURDATE()) > 20, util.VN_CURDATE() - INTERVAL 15 DAY, util.VN_CURDATE() + INTERVAL 7 DAY)), + (1107, 1, IF(MONTH(util.VN_CURDATE()) = 12 AND DAY(util.VN_CURDATE()) > 10, util.VN_CURDATE() - INTERVAL 10 DAY, util.VN_CURDATE() + INTERVAL 10 DAY)), + (1107, 1, IF(MONTH(util.VN_CURDATE()) = 12 AND DAY(util.VN_CURDATE()) > 10, util.VN_CURDATE() - INTERVAL 11 DAY, util.VN_CURDATE() + INTERVAL 11 DAY)), + (1107, 1, IF(MONTH(util.VN_CURDATE()) = 12 AND DAY(util.VN_CURDATE()) > 10, util.VN_CURDATE() - INTERVAL 12 DAY, util.VN_CURDATE() + INTERVAL 12 DAY)), + (1107, 1, IF(MONTH(util.VN_CURDATE()) = 12 AND DAY(util.VN_CURDATE()) > 10, util.VN_CURDATE() - INTERVAL 20 DAY, util.VN_CURDATE() + INTERVAL 20 DAY)), + (1107, 2, IF(MONTH(util.VN_CURDATE()) >= 1 AND DAY(util.VN_CURDATE()) > 20, util.VN_CURDATE() - INTERVAL 13 DAY, util.VN_CURDATE() + INTERVAL 8 DAY)), + (1107, 1, IF(MONTH(util.VN_CURDATE()) >= 1 AND DAY(util.VN_CURDATE()) > 20, util.VN_CURDATE() - INTERVAL 14 DAY, util.VN_CURDATE() + INTERVAL 9 DAY)), + (1107, 2, IF(MONTH(util.VN_CURDATE()) >= 1 AND DAY(util.VN_CURDATE()) > 20, util.VN_CURDATE() - INTERVAL 15 DAY, util.VN_CURDATE() + INTERVAL 7 DAY)), + (1107, 2, util.VN_CURDATE() - INTERVAL 16 DAY); INSERT INTO `vn`.`smsConfig` (`id`, `uri`, `title`, `apiKey`) VALUES @@ -2754,9 +2758,9 @@ 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`) +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, 604800, '', '', 'Leidos.exito', 'Leidos.error', 'timeControl', 5.33, 0.33, 40, '22:00:00', '06:00:00', 57600, 1200, 18000, 57600, 6, 13, 28800, 32400); + (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); INSERT INTO `vn`.`host` (`id`, `code`, `description`, `warehouseFk`, `bankFk`) VALUES diff --git a/db/tests/vn/timeControl_calculateByUser.spec.js b/db/tests/vn/timeControl_calculateByUser.spec.js deleted file mode 100644 index 0b385d2c9..000000000 --- a/db/tests/vn/timeControl_calculateByUser.spec.js +++ /dev/null @@ -1,91 +0,0 @@ -const app = require('vn-loopback/server/server'); -const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; - -describe('timeControl_calculateByUser()', () => { - it(`should return today's worked hours`, async() => { - let start = Date.vnNew(); - start.setHours(0, 0, 0, 0); - start.setDate(start.getDate() - 1); - - let end = Date.vnNew(); - end.setHours(0, 0, 0, 0); - end.setDate(end.getDate() + 1); - - let stmts = []; - let stmt; - - let params = { - workerID: 1106, - start: start, - end: end - }; - - stmt = new ParameterizedSQL('CALL vn.timeControl_calculateByUser(?, ?, ?)', [ - params.workerID, - params.start, - params.end - ]); - stmts.push(stmt); - - let tableIndex = stmts.push('SELECT * FROM tmp.timeControlCalculate') - 1; - - let sql = ParameterizedSQL.join(stmts, ';'); - let result = await app.models.Ticket.rawStmt(sql); - - let [timeControlCalculateTable] = result[tableIndex]; - - expect(timeControlCalculateTable.timeWorkSeconds).toEqual(28200); - }); - // #2261 - xit(`should return the worked hours between last sunday and monday`, async() => { - let lastSunday = Date.vnNew(); - let daysSinceSunday = lastSunday.getDay(); - if (daysSinceSunday === 0) // this means today is sunday but you need the previous sunday :) - daysSinceSunday = 7; - lastSunday.setHours(23, 0, 0, 0); - lastSunday.setDate(lastSunday.getDate() - daysSinceSunday); - - let monday = Date.vnNew(); - let daysSinceMonday = daysSinceSunday - 1; // aiming for monday (today could be monday) - monday.setHours(7, 0, 0, 0); - monday.setDate(monday.getDate() - daysSinceMonday); - - let stmts = []; - let stmt; - - stmts.push('START TRANSACTION'); - - const workerID = 1108; - - stmt = new ParameterizedSQL(` - INSERT INTO vn.workerTimeControl(userFk, timed, manual, direction) - VALUES - (?, ?, 1, 'in'), - (?, ?, 1, 'out') - `, [ - workerID, - lastSunday, - workerID, - monday - ]); - stmts.push(stmt); - - stmt = new ParameterizedSQL('CALL vn.timeControl_calculateByUser(?, ?, ?)', [ - workerID, - lastSunday, - monday - ]); - stmts.push(stmt); - - let tableIndex = stmts.push('SELECT * FROM tmp.timeControlCalculate') - 1; - - stmts.push('ROLLBACK'); - - let sql = ParameterizedSQL.join(stmts, ';'); - let result = await app.models.Ticket.rawStmt(sql); - - let [timeControlCalculateTable] = result[tableIndex]; - - expect(timeControlCalculateTable.timeWorkSeconds).toEqual(30000); - }); -}); diff --git a/db/tests/vn/workerTimeControlCheck.spec.js b/db/tests/vn/workerTimeControlCheck.spec.js deleted file mode 100644 index 0ca1429d4..000000000 --- a/db/tests/vn/workerTimeControlCheck.spec.js +++ /dev/null @@ -1,580 +0,0 @@ -const app = require('vn-loopback/server/server'); -const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; - -// #2261 xdescribe dbtest workerTimeControl_check() -xdescribe('worker workerTimeControl_check()', () => { - it(`should throw an error if the worker can't sign on that tablet`, async() => { - let stmts = []; - let stmt; - const workerId = 1110; - const tabletId = 2; - let err; - stmts.push('START TRANSACTION'); - try { - stmt = new ParameterizedSQL('CALL vn.workerTimeControl_check(?, ?, NULL)', [ - workerId, - tabletId - ]); - stmts.push(stmt); - - stmts.push('ROLLBACK'); - - let sql = ParameterizedSQL.join(stmts, ';'); - await app.models.Worker.rawStmt(sql); - } catch (e) { - err = e; - } - - expect(err.sqlMessage).toEqual('No perteneces a este departamento.'); - }); - - it('should check that the worker can sign on that tablet', async() => { - let stmts = []; - let stmt; - const workerId = 1110; - const tabletId = 1; - let err; - stmts.push('START TRANSACTION'); - try { - stmt = new ParameterizedSQL('CALL vn.workerTimeControl_check(?, ?, NULL)', [ - workerId, - tabletId - ]); - stmts.push(stmt); - - stmts.push('ROLLBACK'); - - let sql = ParameterizedSQL.join(stmts, ';'); - await app.models.Worker.rawStmt(sql); - } catch (e) { - err = e; - } - - expect(err).not.toBeDefined(); - }); - - it('should throw an error if the worker with a special category has not finished the 9h break', async() => { - const workerId = 1110; - const tabletId = 1; - let stmts = []; - let stmt; - let sql; - let error; - - stmts.push('START TRANSACTION'); - stmt = new ParameterizedSQL(`INSERT INTO vn.workerTimeControl(userFk,timed,manual,direction) - VALUES - (?,TIMESTAMPADD(HOUR,-17,NOW()),0,"in"), - (?,TIMESTAMPADD(SECOND,-32399,NOW()),0,"out")`, [ - workerId, - workerId - ]); - stmts.push(stmt); - - stmt = new ParameterizedSQL('CALL vn.workerTimeControl_check(?, ?, NULL)', [ - workerId, - tabletId - ]); - stmts.push(stmt); - stmts.push('ROLLBACK'); - sql = ParameterizedSQL.join(stmts, ';'); - - try { - await app.models.Worker.rawStmt(sql); - } catch (e) { - await app.models.Worker.rawSql('ROLLBACK'); - error = e; - } - - expect(error.sqlMessage).toEqual('Descansos 9 h'); - }); - - it('should check f the worker with a special category has finished the 9h break', async() => { - const workerId = 1110; - const tabletId = 1; - let stmts = []; - let stmt; - let err; - stmts.push('START TRANSACTION'); - stmt = new ParameterizedSQL(`INSERT INTO vn.workerTimeControl(userFk,timed,manual,direction) - VALUES - (?,TIMESTAMPADD(HOUR,-17,NOW()),0,"in"), - (?,TIMESTAMPADD(SECOND,-32401,NOW()),0,"out")`, [ - workerId, - workerId - ]); - stmts.push(stmt); - - stmt = new ParameterizedSQL('CALL vn.workerTimeControl_check(?, ?, NULL)', [ - workerId, - tabletId - ]); - stmts.push(stmt); - stmts.push('ROLLBACK'); - - let sql = ParameterizedSQL.join(stmts, ';'); - - try { - await app.models.Worker.rawStmt(sql); - } catch (e) { - await app.models.Worker.rawSql('ROLLBACK'); - err = e; - } - - expect(err).not.toBeDefined(); - }); - - it('should throw an error if the worker has not finished the 12h break', async() => { - const workerId = 1109; - const tabletId = 1; - let stmts = []; - let stmt; - let sql; - let error; - - stmts.push('START TRANSACTION'); - stmt = new ParameterizedSQL(`INSERT INTO vn.workerTimeControl(userFk,timed,manual,direction) - VALUES - (?,TIMESTAMPADD(HOUR,-20,NOW()),0,"in"), - (?,TIMESTAMPADD(SECOND,-43199,NOW()),0,"out")`, [ - workerId, - workerId - ]); - stmts.push(stmt); - - stmt = new ParameterizedSQL('CALL vn.workerTimeControl_check(?, ?, NULL)', [ - workerId, - tabletId - ]); - stmts.push(stmt); - stmts.push('ROLLBACK'); - sql = ParameterizedSQL.join(stmts, ';'); - - try { - await app.models.Worker.rawStmt(sql); - } catch (e) { - await app.models.Worker.rawSql('ROLLBACK'); - error = e; - } - - expect(error.sqlMessage).toEqual('Descansos 12 h'); - }); - - it('should throw an error if the worker has finished the 12h break', async() => { - const workerId = 1109; - const tabletId = 1; - let stmts = []; - let stmt; - let err; - stmts.push('START TRANSACTION'); - stmt = new ParameterizedSQL(`INSERT INTO vn.workerTimeControl(userFk,timed,manual,direction) - VALUES - (?,TIMESTAMPADD(HOUR,-20,NOW()),0,"in"), - (?,TIMESTAMPADD(SECOND,-43201,NOW()),0,"out")`, [ - workerId, - workerId - ]); - stmts.push(stmt); - - stmt = new ParameterizedSQL('CALL vn.workerTimeControl_check(?, ?, NULL)', [ - workerId, - tabletId - ]); - stmts.push(stmt); - stmts.push('ROLLBACK'); - - let sql = ParameterizedSQL.join(stmts, ';'); - - try { - await app.models.Worker.rawStmt(sql); - } catch (e) { - await app.models.Worker.rawSql('ROLLBACK'); - err = e; - } - - expect(err).not.toBeDefined(); - }); - - it('should throw an error if the worker has odd entry records', async() => { - const workerId = 1109; - const tabletId = 1; - let stmts = []; - let stmt; - let err; - stmts.push('START TRANSACTION'); - stmt = new ParameterizedSQL(`INSERT INTO vn.workerTimeControl(userFk,timed,manual,direction) - VALUES - (?,TIMESTAMPADD(HOUR,-24,NOW()),0,"in")`, [ - workerId - ]); - stmts.push(stmt); - - stmt = new ParameterizedSQL('CALL vn.workerTimeControl_check(?, ?, NULL)', [ - workerId, - tabletId - ]); - stmts.push(stmt); - stmts.push('ROLLBACK'); - - let sql = ParameterizedSQL.join(stmts, ';'); - - try { - await app.models.Worker.rawStmt(sql); - } catch (e) { - await app.models.Worker.rawSql('ROLLBACK'); - err = e; - } - - expect(err.sqlMessage).toEqual('Dias con fichadas impares'); - }); - - it('should throw an error if the worker try to sign on a holiday day', async() => { - const workerId = 1109; - const tabletId = 1; - let stmts = []; - let stmt; - let err; - - stmts.push('START TRANSACTION'); - - stmt = new ParameterizedSQL(`INSERT INTO vn.workerTimeControl(userFk,timed,manual,direction) - VALUES - (?,TIMESTAMPADD(HOUR,-24,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-20,NOW()),0,"out")`, [ - workerId, - workerId - ]); - stmts.push(stmt); - - stmt = new ParameterizedSQL('CALL vn.workerTimeControl_check(?, ?, NULL)', [ - workerId, - tabletId - ]); - stmts.push(stmt); - stmts.push('ROLLBACK'); - - let sql = ParameterizedSQL.join(stmts, ';'); - - try { - await app.models.Worker.rawStmt(sql); - } catch (e) { - await app.models.Worker.rawSql('ROLLBACK'); - err = e; - } - - expect(err.sqlMessage).toEqual('Holidays'); - }); - - it('should throw an error if the worker try to sign with your contract ended', async() => { - const workerId = 1109; - const tabletId = 1; - let stmts = []; - let stmt; - let err; - - stmts.push('START TRANSACTION'); - - stmt = new ParameterizedSQL(`UPDATE vn.business SET ended = DATE_ADD(CURDATE(), INTERVAL -1 DAY) WHERE id = ?`, [ - workerId - ]); - stmts.push(stmt); - - stmt = new ParameterizedSQL(`INSERT INTO vn.workerTimeControl(userFk,timed,manual,direction) - VALUES - (?,TIMESTAMPADD(HOUR,-24,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-20,NOW()),0,"out")`, [ - workerId, - workerId - ]); - stmts.push(stmt); - - stmt = new ParameterizedSQL('CALL vn.workerTimeControl_check(?, ?, NULL)', [ - workerId, - tabletId - ]); - stmts.push(stmt); - stmts.push('ROLLBACK'); - - let sql = ParameterizedSQL.join(stmts, ';'); - - try { - await app.models.Worker.rawStmt(sql); - } catch (e) { - await app.models.Worker.rawSql('ROLLBACK'); - err = e; - } - - expect(err.sqlMessage).toEqual('No hay un contrato en vigor'); - }); - - it('should throw an error if the worker has not finished the 36h weekly break', async() => { - const workerId = 1109; - const tabletId = 1; - let stmts = []; - let stmt; - - stmts.push('SET @warn := NULL'); - - stmts.push('START TRANSACTION'); - - stmt = new ParameterizedSQL(`INSERT INTO vn.workerTimeControl(userFk,timed,manual,direction) - VALUES - (?,TIMESTAMPADD(HOUR,-24,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-16,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-48,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-40,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-72,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-64,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-96,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-88,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-120,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-112,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-144,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-136,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-168,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-160,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-192,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-184,NOW()),0,"out")`, [ - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId - ]); - stmts.push(stmt); - - stmt = new ParameterizedSQL('CALL vn.workerTimeControl_check(?, ?, NULL)', [ - workerId, - tabletId - ]); - stmts.push(stmt); - - let warningMessageIndex = stmts.push('SELECT @warn AS warning') - 1; - stmts.push('ROLLBACK'); - let sql = ParameterizedSQL.join(stmts, ';'); - let result = await app.models.Worker.rawStmt(sql); - - expect(result[warningMessageIndex][0].warning).toEqual('Descansos 36 h'); - }); - - it('should check if the worker has finished the 36h weekly break', async() => { - const workerId = 1109; - const tabletId = 1; - let stmts = []; - let stmt; - - stmts.push('SET @warn := NULL'); - - stmts.push('START TRANSACTION'); - - stmt = new ParameterizedSQL(`INSERT INTO vn.workerTimeControl(userFk,timed,manual,direction) - VALUES - (?,TIMESTAMPADD(HOUR,-24,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-16,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-48,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-40,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-72,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-64,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-96,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-88,NOW()),0,"out")`, [ - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId - ]); - stmts.push(stmt); - - stmt = new ParameterizedSQL('CALL vn.workerTimeControl_check(?, ?, NULL)', [ - workerId, - tabletId - ]); - stmts.push(stmt); - stmts.push('ROLLBACK'); - - let warningMessageIndex = stmts.push('SELECT @warn AS warning') - 1; - - let sql = ParameterizedSQL.join(stmts, ';'); - let result = await app.models.Worker.rawStmt(sql); - - expect(result[warningMessageIndex][0].warning).toBe(null); - }); - - it('should throw an error if the worker has not finished the 72h biweekly break', async() => { - const workerId = 1109; - const tabletId = 1; - let stmts = []; - let stmt; - let err; - stmts.push('START TRANSACTION'); - - stmt = new ParameterizedSQL(`INSERT INTO vn.workerTimeControl(userFk,timed,manual,direction) - VALUES - (?,TIMESTAMPADD(HOUR,-24,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-16,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-48,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-40,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-72,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-64,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-96,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-88,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-120,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-112,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-144,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-136,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-168,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-160,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-192,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-184,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-216,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-208,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-240,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-232,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-264,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-256,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-289,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-280,NOW()),0,"out")`, [ - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId - ]); - stmts.push(stmt); - - stmt = new ParameterizedSQL('CALL vn.workerTimeControl_check(?, ?, NULL)', [ - workerId, - tabletId - ]); - stmts.push(stmt); - stmts.push('ROLLBACK'); - - stmts.push('SELECT @warn AS warning') - 1; - - let sql = ParameterizedSQL.join(stmts, ';'); - - try { - await app.models.Worker.rawStmt(sql); - } catch (e) { - await app.models.Worker.rawSql('ROLLBACK'); - err = e; - } - - expect(err.sqlMessage).toEqual('Descansos 72 h'); - }); - - it('should check if the worker has finished the 72h biweekly break', async() => { - const workerId = 1109; - const tabletId = 1; - let stmts = []; - let stmt; - let err; - stmts.push('START TRANSACTION'); - - stmt = new ParameterizedSQL(`INSERT INTO vn.workerTimeControl(userFk,timed,manual,direction) - VALUES - (?,TIMESTAMPADD(HOUR,-24,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-16,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-48,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-40,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-72,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-64,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-96,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-88,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-120,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-112,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-144,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-136,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-168,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-160,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-192,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-184,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-216,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-208,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-240,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-232,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-264,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-256,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-288,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-280,NOW()),0,"out")`, [ - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId - ]); - stmts.push(stmt); - - stmt = new ParameterizedSQL('CALL vn.workerTimeControl_check(?, ?, NULL)', [ - workerId, - tabletId - ]); - stmts.push(stmt); - stmts.push('ROLLBACK'); - - stmts.push('SELECT @warn AS warning') - 1; - - let sql = ParameterizedSQL.join(stmts, ';'); - - try { - await app.models.Worker.rawStmt(sql); - } catch (e) { - await app.models.Worker.rawSql('ROLLBACK'); - err = e; - } - - expect(err).not.toBeDefined(); - }); -}); diff --git a/modules/worker/back/methods/worker-time-control/specs/timeEntry.spec.js b/modules/worker/back/methods/worker-time-control/specs/timeEntry.spec.js index e90c849b7..42ec6290a 100644 --- a/modules/worker/back/methods/worker-time-control/specs/timeEntry.spec.js +++ b/modules/worker/back/methods/worker-time-control/specs/timeEntry.spec.js @@ -14,7 +14,6 @@ describe('workerTimeControl add/delete timeEntry()', () => { const tuesday = 2; const thursday = 4; const friday = 5; - const saturday = 6; const sunday = 7; const activeCtx = { accessToken: {userId: 50}, @@ -200,15 +199,15 @@ describe('workerTimeControl add/delete timeEntry()', () => { }); describe('WorkerTimeControl_clockIn calls', () => { - it('should fail to add a time entry if the target user has an absence that day', async() => { - pending('https://redmine.verdnatura.es/issues/4707'); + let workerId; + beforeEach(() => { activeCtx.accessToken.userId = salesBossId; - const workerId = hankPymId; + workerId = hankPymId; + }); + it('should fail to add a time entry if the target user has an absence that day', async() => { const date = Date.vnNew(); - date.setDate(date.getDate() - 16); date.setHours(8, 0, 0); - let error; - + date.setDate(date.getDate() - 16); const tx = await models.WorkerTimeControl.beginTransaction({}); const options = {transaction: tx}; try { @@ -225,15 +224,12 @@ describe('workerTimeControl add/delete timeEntry()', () => { }); it('should fail to add a time entry for a worker without an existing contract', async() => { - activeCtx.accessToken.userId = salesBossId; - const workerId = hankPymId; const date = Date.vnNew(); date.setFullYear(date.getFullYear() - 2); - let error; const tx = await models.WorkerTimeControl.beginTransaction({}); + const options = {transaction: tx}; try { - const options = {transaction: tx}; ctx.args = {timed: date, direction: 'in'}; await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); @@ -246,19 +242,39 @@ describe('workerTimeControl add/delete timeEntry()', () => { expect(error.message).toBe(`No hay un contrato en vigor`); }); + it('should fail to add a time entry for a worker without an existing contract', async() => { + let date = Date.vnNew(); + date.setDate(date.getDate() - 2); + let error; + + const tx = await models.WorkerTimeControl.beginTransaction({}); + const options = {transaction: tx}; + date.setHours(0, 0, 0); + ctx.args = {timed: date, direction: 'in'}; + await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + + try { + date.setHours(20,0, 1); + ctx.args = {timed: date, direction: 'out'}; + await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error.message).toBe(`Superado el tiempo máximo entre entrada y salida`); + }); + describe('direction errors', () => { + let date = Date.vnNew(); + date.setDate(date.getDate() - 1); + let error; it('should throw an error when trying "in" direction twice', async() => { - pending('https://redmine.verdnatura.es/issues/4707'); - activeCtx.accessToken.userId = salesBossId; - const workerId = hankPymId; - - let date = Date.vnNew(); - date.setDate(date.getDate() - 21); - date = weekDay(date, monday); - let error; - const tx = await models.WorkerTimeControl.beginTransaction({}); const options = {transaction: tx}; + date.setHours(8, 0, 0); ctx.args = {timed: date, direction: 'in'}; await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); @@ -278,21 +294,13 @@ describe('workerTimeControl add/delete timeEntry()', () => { }); it('should throw an error when trying "in" direction after insert "in" and "middle"', async() => { - pending('https://redmine.verdnatura.es/issues/4707'); - activeCtx.accessToken.userId = salesBossId; - const workerId = hankPymId; - - let date = Date.vnNew(); - date.setDate(date.getDate() - 21); - date = weekDay(date, monday); - let error; - const tx = await models.WorkerTimeControl.beginTransaction({}); const options = {transaction: tx}; date.setHours(8, 0, 0); ctx.args = {timed: date, direction: 'in'}; await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + date.setHours(9, 0, 0); ctx.args = {timed: date, direction: 'middle'}; await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); @@ -312,15 +320,6 @@ describe('workerTimeControl add/delete timeEntry()', () => { }); it('Should throw an error when trying "out" before closing a "middle" couple', async() => { - pending('https://redmine.verdnatura.es/issues/4707'); - activeCtx.accessToken.userId = salesBossId; - const workerId = hankPymId; - - let date = Date.vnNew(); - date.setDate(date.getDate() - 21); - date = weekDay(date, monday); - let error; - const tx = await models.WorkerTimeControl.beginTransaction({}); const options = {transaction: tx}; @@ -346,15 +345,6 @@ describe('workerTimeControl add/delete timeEntry()', () => { }); it('should throw an error when trying "middle" after "out"', async() => { - pending('https://redmine.verdnatura.es/issues/4707'); - activeCtx.accessToken.userId = salesBossId; - const workerId = hankPymId; - - let date = Date.vnNew(); - date.setDate(date.getDate() - 21); - date = weekDay(date, monday); - let error; - const tx = await models.WorkerTimeControl.beginTransaction({}); const options = {transaction: tx}; @@ -380,15 +370,6 @@ describe('workerTimeControl add/delete timeEntry()', () => { }); it('should throw an error when trying "out" direction twice', async() => { - pending('https://redmine.verdnatura.es/issues/4707'); - activeCtx.accessToken.userId = salesBossId; - const workerId = hankPymId; - - let date = Date.vnNew(); - date.setDate(date.getDate() - 21); - date = weekDay(date, monday); - let error; - const tx = await models.WorkerTimeControl.beginTransaction({}); const options = {transaction: tx}; @@ -415,14 +396,12 @@ describe('workerTimeControl add/delete timeEntry()', () => { }); describe('12h rest', () => { + activeCtx.accessToken.userId = salesBossId; + const workerId = hankPymId; it('should throw an error when the 12h rest is not fulfilled yet', async() => { - pending('https://redmine.verdnatura.es/issues/4707'); - - activeCtx.accessToken.userId = salesBossId; - const workerId = hankPymId; let date = Date.vnNew(); - date.setDate(date.getDate() - 21); + date.setDate(date.getDate() - 2); date = weekDay(date, monday); let error; @@ -448,16 +427,12 @@ describe('workerTimeControl add/delete timeEntry()', () => { error = e; } - expect(error.message).toBe(`Descanso diario 12h.`); + expect(error.message).toBe(`Descanso diario`); }); it('should not fail as the 12h rest is fulfilled', async() => { - pending('https://redmine.verdnatura.es/issues/4707'); - activeCtx.accessToken.userId = salesBossId; - const workerId = hankPymId; - let date = Date.vnNew(); - date.setDate(date.getDate() - 21); + date.setDate(date.getDate() - 2); date = weekDay(date, monday); let error; @@ -488,13 +463,12 @@ describe('workerTimeControl add/delete timeEntry()', () => { }); describe('for 3500kg drivers with enforced 9h rest', () => { + activeCtx.accessToken.userId = salesBossId; + const workerId = jessicaJonesId; it('should throw an error when the 9h enforced rest is not fulfilled', async() => { - pending('https://redmine.verdnatura.es/issues/4707'); - activeCtx.accessToken.userId = salesBossId; - const workerId = jessicaJonesId; let date = Date.vnNew(); - date.setDate(date.getDate() - 21); + date.setDate(date.getDate() - 2); date = weekDay(date, monday); let error; @@ -520,16 +494,13 @@ describe('workerTimeControl add/delete timeEntry()', () => { error = e; } - expect(error.message).toBe(`Descanso diario 9h.`); + expect(error.message).toBe(`Descanso diario`); }); it('should not fail when the 9h enforced rest is fulfilled', async() => { - pending('https://redmine.verdnatura.es/issues/4707'); - activeCtx.accessToken.userId = salesBossId; - const workerId = jessicaJonesId; - + let date = Date.vnNew(); - date.setDate(date.getDate() - 21); + date.setDate(date.getDate() - 2); date = weekDay(date, monday); let error; @@ -559,14 +530,11 @@ describe('workerTimeControl add/delete timeEntry()', () => { }); }); - describe('for 36h weekly rest', () => { - it('should throw an error when the 36h weekly rest is not fulfilled', async() => { - pending('https://redmine.verdnatura.es/issues/4707'); - activeCtx.accessToken.userId = salesBossId; - const workerId = hankPymId; - + describe('for 72h weekly rest', () => { + + it('should throw an error when work 11 consecutive days', async() => { let date = Date.vnNew(); - date.setMonth(date.getMonth() - 2); + date.setMonth(date.getMonth() - 1); date.setDate(1); let error; @@ -576,66 +544,24 @@ describe('workerTimeControl add/delete timeEntry()', () => { await populateWeek(date, monday, sunday, ctx, workerId, options); date = nextWeek(date); await populateWeek(date, monday, thursday, ctx, workerId, options); - date = weekDay(date, friday); - date.setHours(7, 59, 0); - ctx.args = {timed: date, direction: 'in'}; - await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - try { - date.setHours(8, 1, 0); - ctx.args = {timed: date, direction: 'out'}; - await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - error = e; - } - - expect(error.message).toBe(`Descanso semanal 36h. / 72h.`); - }); - - it('should throw an error when the 36h weekly rest is not fulfilled again', async() => { - pending('https://redmine.verdnatura.es/issues/4707'); - activeCtx.accessToken.userId = salesBossId; - const workerId = hankPymId; - - let date = Date.vnNew(); - date.setMonth(date.getMonth() - 2); - date.setDate(1); - let error; - - const tx = await models.WorkerTimeControl.beginTransaction({}); - const options = {transaction: tx}; - - await populateWeek(date, monday, sunday, ctx, workerId, options); - date = nextWeek(date); - await populateWeek(date, monday, thursday, ctx, workerId, options); - - try { - date = weekDay(date, saturday); - date.setHours(3, 59, 0); + date = weekDay(date, friday); + date.setHours(10, 0, 1); ctx.args = {timed: date, direction: 'in'}; await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - await tx.rollback(); } catch (e) { await tx.rollback(); error = e; } - expect(error.message).toBe(`Descanso semanal 36h. / 72h.`); + expect(error.message).toBe(`Descanso semanal`); }); - }); - describe('for 72h weekly rest', () => { - it('should throw when the 72h weekly rest is not fulfilled yet', async() => { - pending('https://redmine.verdnatura.es/issues/4707'); - activeCtx.accessToken.userId = salesBossId; - const workerId = hankPymId; + it('should throw an error when the 72h weekly rest is not fulfilled', async() => { let date = Date.vnNew(); - date.setMonth(date.getMonth() - 2); + date.setMonth(date.getMonth() - 1); date.setDate(1); let error; @@ -645,32 +571,263 @@ describe('workerTimeControl add/delete timeEntry()', () => { await populateWeek(date, monday, sunday, ctx, workerId, options); date = nextWeek(date); await populateWeek(date, monday, thursday, ctx, workerId, options); - date = nextWeek(date); - await populateWeek(date, monday, friday, ctx, workerId, options); - date = nextWeek(date); - await populateWeek(date, monday, saturday, ctx, workerId, options); - date = nextWeek(date); - await populateWeek(date, monday, saturday, ctx, workerId, options); - date = lastWeek(date); try { date = weekDay(date, sunday); - date.setHours(8, 0, 0); + date.setHours(17, 59, 0); ctx.args = {timed: date, direction: 'in'}; await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - await tx.rollback(); } catch (e) { await tx.rollback(); error = e; } - expect(error.message).toBe(`Descanso semanal 36h. / 72h.`); + expect(error.message).toBe(`Descanso semanal`); + }); + + it('should throw an error when the 72h weekly rest is fulfilled', async() => { + + let date = Date.vnNew(); + date.setMonth(date.getMonth() - 1); + date.setDate(1); + let error; + + const tx = await models.WorkerTimeControl.beginTransaction({}); + const options = {transaction: tx}; + + await populateWeek(date, monday, sunday, ctx, workerId, options); + date = nextWeek(date); + await populateWeek(date, monday, thursday, ctx, workerId, options); + + try { + date = weekDay(date, sunday); + date.setHours(18, 00, 0); + ctx.args = {timed: date, direction: 'in'}; + await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error).not.toBeDefined; + }); + }); + + describe('WorkerTimeControl_calculate calls', () => { + let dated = Date.vnNew(); + dated.setDate(dated.getDate() - 7); + dated = new Date(weekDay(dated, monday)); + const end = new Date(dated); + end.setDate(end.getDate() + 1); + + it(`should return today's worked 8 hours without break`, async() => { + const tx = await models.WorkerTimeControl.beginTransaction({}); + const options = {transaction: tx}; + + try { + await populateWeek(dated, monday, monday, ctx, hankPymId, options); + const start = new Date(dated - 1); + start.setHours(0, 0, 0); + await models.WorkerTimeControl.rawSql('CALL vn.timeControl_calculateByUser(?, ?, ?)', [ + hankPymId, + start, + end + ], options); + + let [timeControlCalculateTable] = await models.WorkerTimeControl.rawSql('SELECT * FROM tmp.timeControlCalculate', null, options); + + expect(timeControlCalculateTable.timeWorkSeconds).toEqual(28800); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it(`should return today's worked hours with 15min break and work time consecutive less than 5h`, async() => { + const tx = await models.WorkerTimeControl.beginTransaction({}); + const options = {transaction: tx}; + + try { + await populateWeek(dated, monday, monday, ctx, hankPymId, options); + dated.setHours(14, 59, 0); + await addTimeEntry(ctx, dated, 'middle', hankPymId, options); + dated.setHours(15, 14, 0); + await addTimeEntry(ctx, dated, 'middle', hankPymId, options); + + const start = new Date(dated - 1); + start.setHours(0, 0, 0); + await models.WorkerTimeControl.rawSql('CALL vn.timeControl_calculateByUser(?, ?, ?)', [ + hankPymId, + start, + end + ], options); + + let [timeControlCalculateTable] = await models.WorkerTimeControl.rawSql('SELECT * FROM tmp.timeControlCalculate', null, options); + + expect(timeControlCalculateTable.timeWorkSeconds).toEqual(28800); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it(`should return today's worked hours with 15min break and work time consecutive greater than 5h`, async() => { + const tx = await models.WorkerTimeControl.beginTransaction({}); + const options = {transaction: tx}; + + try { + await populateWeek(dated, monday, monday, ctx, hankPymId, options); + dated.setHours(15, 0, 0); + await addTimeEntry(ctx, dated, 'middle', hankPymId, options); + dated.setHours(15, 15, 0); + await addTimeEntry(ctx, dated, 'middle', hankPymId, options); + + const start = new Date(dated - 1); + start.setHours(0, 0, 0); + await models.WorkerTimeControl.rawSql('CALL vn.timeControl_calculateByUser(?, ?, ?)', [ + hankPymId, + start, + end + ], options); + + let [timeControlCalculateTable] = await models.WorkerTimeControl.rawSql('SELECT * FROM tmp.timeControlCalculate', null, options); + + expect(timeControlCalculateTable.timeWorkSeconds).toEqual(28800); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it(`should return today's worked hours with 25min break and work time consecutive less than 5h`, async() => { + const tx = await models.WorkerTimeControl.beginTransaction({}); + const options = {transaction: tx}; + + try { + await populateWeek(dated, monday, monday, ctx, hankPymId, options); + dated.setHours(14, 59, 0); + await addTimeEntry(ctx, dated, 'middle', hankPymId, options); + dated.setHours(15, 24, 0); + await addTimeEntry(ctx, dated, 'middle', hankPymId, options); + + const start = new Date(dated - 1); + start.setHours(0, 0, 0); + await models.WorkerTimeControl.rawSql('CALL vn.timeControl_calculateByUser(?, ?, ?)', [ + hankPymId, + start, + end + ], options); + + let [timeControlCalculateTable] = await models.WorkerTimeControl.rawSql('SELECT * FROM tmp.timeControlCalculate', null, options); + + expect(timeControlCalculateTable.timeWorkSeconds).toEqual(28500); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it(`should return today's worked hours with 25min break and work time consecutive greater than 5h`, async() => { + const tx = await models.WorkerTimeControl.beginTransaction({}); + const options = {transaction: tx}; + + try { + await populateWeek(dated, monday, monday, ctx, hankPymId, options); + dated.setHours(15, 0, 0); + await addTimeEntry(ctx, dated, 'middle', hankPymId, options); + dated.setHours(15, 25, 0); + await addTimeEntry(ctx, dated, 'middle', hankPymId, options); + + const start = new Date(dated - 1); + start.setHours(0, 0, 0); + await models.WorkerTimeControl.rawSql('CALL vn.timeControl_calculateByUser(?, ?, ?)', [ + hankPymId, + start, + end + ], options); + + let [timeControlCalculateTable] = await models.WorkerTimeControl.rawSql('SELECT * FROM tmp.timeControlCalculate', null, options); + + expect(timeControlCalculateTable.timeWorkSeconds).toEqual(28500); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it(`should return today's worked hours with 60min break and work time consecutive less than 5h`, async() => { + const tx = await models.WorkerTimeControl.beginTransaction({}); + const options = {transaction: tx}; + + try { + await populateWeek(dated, monday, monday, ctx, hankPymId, options); + dated.setHours(14, 59, 0); + await addTimeEntry(ctx, dated, 'middle', hankPymId, options); + dated.setHours(15, 59, 0); + await addTimeEntry(ctx, dated, 'middle', hankPymId, options); + + const start = new Date(dated - 1); + start.setHours(0, 0, 0); + await models.WorkerTimeControl.rawSql('CALL vn.timeControl_calculateByUser(?, ?, ?)', [ + hankPymId, + start, + end + ], options); + + let [timeControlCalculateTable] = await models.WorkerTimeControl.rawSql('SELECT * FROM tmp.timeControlCalculate', null, options); + + expect(timeControlCalculateTable.timeWorkSeconds).toEqual(25200); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it(`should return today's worked hours with 60min break and work time consecutive greater than 5h`, async() => { + const tx = await models.WorkerTimeControl.beginTransaction({}); + const options = {transaction: tx}; + + try { + await populateWeek(dated, monday, monday, ctx, hankPymId, options); + dated.setHours(15, 0, 0); + await addTimeEntry(ctx, dated, 'middle', hankPymId, options); + dated.setHours(16, 0, 0); + await addTimeEntry(ctx, dated, 'middle', hankPymId, options); + + const start = new Date(dated - 1); + start.setHours(0, 0, 0); + await models.WorkerTimeControl.rawSql('CALL vn.timeControl_calculateByUser(?, ?, ?)', [ + hankPymId, + start, + end + ], options); + + let [timeControlCalculateTable] = await models.WorkerTimeControl.rawSql('SELECT * FROM tmp.timeControlCalculate', null, options); + + expect(timeControlCalculateTable.timeWorkSeconds).toEqual(26400); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); }); }); +async function addTimeEntry(ctx, dated, direction, userId, option) { + ctx.args = {timed: dated, direction}; + await models.WorkerTimeControl.addTimeEntry(ctx, userId, option); +} + function weekDay(date, dayToSet) { const currentDay = date.getDay(); const distance = dayToSet - currentDay; @@ -704,10 +861,10 @@ async function populateWeek(date, dayStart, dayEnd, ctx, workerId, options) { dateEnd.setDate(dateStart.getDate() + dayEnd); for (let i = dayStart; i <= dayEnd; i++) { - dateStart.setHours(8, 0, 0); + dateStart.setHours(10, 0, 0); ctx.args = {timed: dateStart, direction: 'in'}; await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - dateStart.setHours(16, 0, 0); + dateStart.setHours(18, 0, 0); ctx.args = {timed: dateStart, direction: 'out'}; await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); dateStart.setDate(dateStart.getDate() + 1); From 483526c9702fe03ddd2fcc18586cb6b62cc36102 Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 23 Oct 2023 15:03:05 +0200 Subject: [PATCH 271/427] 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 0055abc0a8064f8a0fbc12473243a566e727590d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Mon, 23 Oct 2023 15:52:05 +0200 Subject: [PATCH 272/427] refs #4707 fix: problemas fichadas y test --- db/changes/234003/00-workerTimeControl.sql | 4 ++-- db/changes/234003/02-workerTimeControl_clockIn.sql | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/db/changes/234003/00-workerTimeControl.sql b/db/changes/234003/00-workerTimeControl.sql index 7b41278b0..73d57d1db 100644 --- a/db/changes/234003/00-workerTimeControl.sql +++ b/db/changes/234003/00-workerTimeControl.sql @@ -11,14 +11,14 @@ ALTER TABLE `vn`.`workerTimeControlConfig` ALTER TABLE `vn`.`workerTimeControlConfig` ADD COLUMN `maxWorkShortCycle` INT(10) UNSIGNED DEFAULT 561600 - COMMENT 'Máximo tiempo que un trabajador puede estar trabajando con el que adquirirá el derecho a un descando semanal corto'; + COMMENT 'Máximo tiempo que un trabajador puede estar trabajando con el que adquirirá el derecho a un descando'; ALTER TABLE `vn`.`workerTimeControlConfig` DROP COLUMN IF EXISTS `maxWorkLongCycle`; ALTER TABLE `vn`.`workerTimeControlConfig` ADD COLUMN `maxWorkLongCycle` INT(10) UNSIGNED DEFAULT 950400 - COMMENT 'Máximo tiempo que un trabajador puede estar trabajando con el que adquirirá el derecho a un descando semanal largo'; + COMMENT 'Máximo tiempo que un trabajador puede estar trabajando con el que adquirirá el derecho a un descando'; CREATE TABLE IF NOT EXISTS `vn`.`workerTimeControlError` ( `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, diff --git a/db/changes/234003/02-workerTimeControl_clockIn.sql b/db/changes/234003/02-workerTimeControl_clockIn.sql index 7cc9e7831..69091e51c 100644 --- a/db/changes/234003/02-workerTimeControl_clockIn.sql +++ b/db/changes/234003/02-workerTimeControl_clockIn.sql @@ -12,7 +12,7 @@ BEGIN * @param vDirection solo se pueden pasa los valores del campo * workerTimeControl.direction ENUM('in', 'out', 'middle') * @return Si todo es correcto, retorna el número de id la tabla workerTimeControl. - * Si hay algún problema, devuelve el mesaje a que se debe mostrar al usuario + * Si hay algún problema, devuelve el mesaje que se debe mostrar al usuario * Solo retorna el primer problema, en caso de no ocurrir ningún error se añadirá * fichada a la tabla vn.workerTimeControl */ From 4ff0bb94c08759a624af93202a7ba06ede0300ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Mon, 23 Oct 2023 16:58:56 +0200 Subject: [PATCH 273/427] refs #4707 --- db/changes/234003/00-workerTimeControl.sql | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/db/changes/234003/00-workerTimeControl.sql b/db/changes/234003/00-workerTimeControl.sql index 73d57d1db..c96fafcdd 100644 --- a/db/changes/234003/00-workerTimeControl.sql +++ b/db/changes/234003/00-workerTimeControl.sql @@ -11,14 +11,14 @@ ALTER TABLE `vn`.`workerTimeControlConfig` ALTER TABLE `vn`.`workerTimeControlConfig` ADD COLUMN `maxWorkShortCycle` INT(10) UNSIGNED DEFAULT 561600 - COMMENT 'Máximo tiempo que un trabajador puede estar trabajando con el que adquirirá el derecho a un descando'; + COMMENT 'Máximo tiempo que un trabajador puede estar trabajando con el que adquirirá el derecho a un descanso semanal corto'; ALTER TABLE `vn`.`workerTimeControlConfig` DROP COLUMN IF EXISTS `maxWorkLongCycle`; ALTER TABLE `vn`.`workerTimeControlConfig` ADD COLUMN `maxWorkLongCycle` INT(10) UNSIGNED DEFAULT 950400 - COMMENT 'Máximo tiempo que un trabajador puede estar trabajando con el que adquirirá el derecho a un descando'; + COMMENT 'Máximo tiempo que un trabajador puede estar trabajando con el que adquirirá el derecho a un descanso semanal largo'; CREATE TABLE IF NOT EXISTS `vn`.`workerTimeControlError` ( `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, From 5529f08ce6f949a922954e67f52157e52547cca3 Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 24 Oct 2023 08:35:45 +0200 Subject: [PATCH 274/427] ref #5914 fix locale --- loopback/locale/en.json | 5 ----- 1 file changed, 5 deletions(-) diff --git a/loopback/locale/en.json b/loopback/locale/en.json index fec1c8566..26650175d 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -188,19 +188,14 @@ "The ticket doesn't exist.": "The ticket doesn't exist.", "The sales do not exists": "The sales do not exists", "Ticket without Route": "Ticket without route", -<<<<<<< HEAD "Select a different client": "Select a different client", "Fill all the fields": "Fill all the fields", "Error while generating PDF": "Error while generating PDF", "Can't invoice to future": "Can't invoice to future", "This ticket is already invoiced": "This ticket is already invoiced", "Negative basis of tickets: 23": "Negative basis of tickets: 23", - "Booking completed": "Booking completed", - "The ticket is in preparation": "The ticket [{{ticketId}}]({{{ticketUrl}}}) of the sales person {{salesPersonId}} is in preparation" -======= "Booking completed": "Booking complete", "The ticket is in preparation": "The ticket [{{ticketId}}]({{{ticketUrl}}}) of the sales person {{salesPersonId}} is in preparation", "You can only add negative amounts in refund tickets": "You can only add negative amounts in refund tickets" ->>>>>>> ae27aa5b1e61c74bfbbc1b7b8af63642072acc6d } From 22b7c5981294dcf5573c4f23b92a7f3010f5e98c Mon Sep 17 00:00:00 2001 From: alexm Date: Tue, 24 Oct 2023 09:23:03 +0200 Subject: [PATCH 275/427] refs #6335 feat(ticketAdvance): add zone field --- .../234003/00-ticket_canAdvance_zone.sql | 132 ++++++++++++++++++ .../back/methods/ticket/getTicketsAdvance.js | 15 +- modules/ticket/front/advance/index.html | 4 + modules/ticket/front/advance/index.js | 44 +++--- 4 files changed, 159 insertions(+), 36 deletions(-) create mode 100644 db/changes/234003/00-ticket_canAdvance_zone.sql diff --git a/db/changes/234003/00-ticket_canAdvance_zone.sql b/db/changes/234003/00-ticket_canAdvance_zone.sql new file mode 100644 index 000000000..c11cdc49a --- /dev/null +++ b/db/changes/234003/00-ticket_canAdvance_zone.sql @@ -0,0 +1,132 @@ +DELIMITER $$ +$$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_canAdvance`(vDateFuture DATE, vDateToAdvance DATE, vWarehouseFk INT) +BEGIN +/** + * Devuelve los tickets y la cantidad de lineas de venta que se pueden adelantar. + * + * @param vDateFuture Fecha de los tickets que se quieren adelantar. + * @param vDateToAdvance Fecha a cuando se quiere adelantar. + * @param vWarehouseFk Almacén + */ + DECLARE vDateInventory DATE; + + SELECT inventoried INTO vDateInventory FROM config; + + DROP TEMPORARY TABLE IF EXISTS tmp.stock; + CREATE TEMPORARY TABLE tmp.stock + (itemFk INT PRIMARY KEY, + amount INT) + ENGINE = MEMORY; + + INSERT INTO tmp.stock(itemFk, amount) + SELECT itemFk, SUM(quantity) amount FROM + ( + SELECT itemFk, quantity + FROM itemTicketOut + WHERE shipped >= vDateInventory + AND shipped < vDateFuture + AND warehouseFk = vWarehouseFk + UNION ALL + SELECT itemFk, quantity + FROM itemEntryIn + WHERE landed >= vDateInventory + AND landed < vDateFuture + AND isVirtualStock = FALSE + AND warehouseInFk = vWarehouseFk + UNION ALL + SELECT itemFk, quantity + FROM itemEntryOut + WHERE shipped >= vDateInventory + AND shipped < vDateFuture + AND warehouseOutFk = vWarehouseFk + ) t + GROUP BY itemFk HAVING amount != 0; + + CREATE OR REPLACE TEMPORARY TABLE tmp.filter + (INDEX (id)) + SELECT + origin.ticketFk futureId, + dest.ticketFk id, + dest.state, + origin.futureState, + origin.futureIpt, + dest.ipt, + origin.workerFk, + origin.futureLiters, + origin.futureLines, + dest.shipped, + origin.shipped futureShipped, + dest.totalWithVat, + origin.totalWithVat futureTotalWithVat, + dest.agency, + origin.futureAgency, + dest.lines, + dest.liters, + origin.futureLines - origin.hasStock AS notMovableLines, + (origin.futureLines = origin.hasStock) AS isFullMovable, + origin.futureZoneFk, + origin.futureZoneName, + origin.classColor futureClassColor, + dest.classColor + FROM ( + SELECT + s.ticketFk, + t.workerFk, + t.shipped, + t.totalWithVat, + st.name futureState, + t.addressFk, + am.name futureAgency, + count(s.id) futureLines, + GROUP_CONCAT(DISTINCT ipt.code ORDER BY ipt.code) futureIpt, + CAST(SUM(litros) AS DECIMAL(10,0)) futureLiters, + SUM((s.quantity <= IFNULL(st.amount,0))) hasStock, + z.id futureZoneFk, + z.name futureZoneName, + st.classColor + FROM ticket t + JOIN sale s ON s.ticketFk = t.id + JOIN saleVolume sv ON sv.saleFk = s.id + JOIN item i ON i.id = s.itemFk + JOIN ticketState ts ON ts.ticketFk = t.id + JOIN state st ON st.id = ts.stateFk + JOIN agencyMode am ON t.agencyModeFk = am.id + JOIN zone z ON t.zoneFk = z.id + LEFT JOIN itemPackingType ipt ON ipt.code = i.itemPackingTypeFk + LEFT JOIN tmp.stock st ON st.itemFk = i.id + WHERE t.shipped BETWEEN vDateFuture AND util.dayend(vDateFuture) + AND t.warehouseFk = vWarehouseFk + GROUP BY t.id + ) origin + JOIN ( + SELECT + t.id ticketFk, + t.addressFk, + st.name state, + GROUP_CONCAT(DISTINCT ipt.code ORDER BY ipt.code) ipt, + t.shipped, + t.totalWithVat, + am.name agency, + CAST(SUM(litros) AS DECIMAL(10,0)) liters, + CAST(COUNT(*) AS DECIMAL(10,0)) `lines`, + st.classColor + FROM ticket t + JOIN sale s ON s.ticketFk = t.id + JOIN saleVolume sv ON sv.saleFk = s.id + JOIN item i ON i.id = s.itemFk + JOIN ticketState ts ON ts.ticketFk = t.id + JOIN state st ON st.id = ts.stateFk + JOIN agencyMode am ON t.agencyModeFk = am.id + LEFT JOIN itemPackingType ipt ON ipt.code = i.itemPackingTypeFk + WHERE t.shipped BETWEEN vDateToAdvance AND util.dayend(vDateToAdvance) + AND t.warehouseFk = vWarehouseFk + AND st.order <= 5 + GROUP BY t.id + ) dest ON dest.addressFk = origin.addressFk + WHERE origin.hasStock != 0; + + DROP TEMPORARY TABLE tmp.stock; +END$$ +DELIMITER ; + diff --git a/modules/ticket/back/methods/ticket/getTicketsAdvance.js b/modules/ticket/back/methods/ticket/getTicketsAdvance.js index ec9314db2..ab40b9559 100644 --- a/modules/ticket/back/methods/ticket/getTicketsAdvance.js +++ b/modules/ticket/back/methods/ticket/getTicketsAdvance.js @@ -28,32 +28,27 @@ module.exports = Self => { { arg: 'ipt', type: 'string', - description: 'Origin Item Packaging Type', - required: false + description: 'Origin Item Packaging Type' }, { arg: 'futureIpt', type: 'string', - description: 'Destination Item Packaging Type', - required: false + description: 'Destination Item Packaging Type' }, { arg: 'id', type: 'number', - description: 'Origin id', - required: false + description: 'Origin id' }, { arg: 'futureId', type: 'number', - description: 'Destination id', - required: false + description: 'Destination id' }, { arg: 'isFullMovable', type: 'boolean', - description: 'True when lines and stock of origin are equal', - required: false + description: 'True when lines and stock of origin are equal' }, { arg: 'filter', diff --git a/modules/ticket/front/advance/index.html b/modules/ticket/front/advance/index.html index e6f16c965..a6cf8face 100644 --- a/modules/ticket/front/advance/index.html +++ b/modules/ticket/front/advance/index.html @@ -81,6 +81,9 @@ Liters + + Zone + Not Movable @@ -155,6 +158,7 @@ {{::ticket.futureLiters | dashIfEmpty}} + {{::ticket.futureZoneName | dashIfEmpty}} {{::ticket.notMovableLines | dashIfEmpty}} {{::ticket.futureLines | dashIfEmpty}} diff --git a/modules/ticket/front/advance/index.js b/modules/ticket/front/advance/index.js index 6f8a92ebe..389bcdf14 100644 --- a/modules/ticket/front/advance/index.js +++ b/modules/ticket/front/advance/index.js @@ -15,28 +15,22 @@ export default class Controller extends Section { { field: 'state', searchable: false - }, - { + }, { field: 'futureState', searchable: false - }, - { + }, { field: 'totalWithVat', searchable: false - }, - { + }, { field: 'futureTotalWithVat', searchable: false - }, - { + }, { field: 'shipped', searchable: false - }, - { + }, { field: 'futureShipped', searchable: false - }, - { + }, { field: 'ipt', autocomplete: { url: 'ItemPackingTypes', @@ -44,8 +38,7 @@ export default class Controller extends Section { showField: 'description', valueField: 'code' } - }, - { + }, { field: 'futureIpt', autocomplete: { url: 'ItemPackingTypes', @@ -53,6 +46,11 @@ export default class Controller extends Section { showField: 'description', valueField: 'code' } + }, { + field: 'futureZoneFk', + autocomplete: { + url: 'Zones', + } }, ] }; @@ -158,27 +156,21 @@ export default class Controller extends Section { exprBuilder(param, value) { switch (param) { case 'id': - return {'id': value}; case 'futureId': - return {'futureId': value}; case 'liters': - return {'liters': value}; case 'futureLiters': - return {'futureLiters': value}; case 'lines': - return {'lines': value}; case 'futureLines': - return {'futureLines': value}; + case 'totalWithVat': + case 'futureTotalWithVat': + case 'futureZone': + case 'notMovableLines': + case 'futureZoneFk': + return {[param]: value}; case 'ipt': return {'ipt': {like: `%${value}%`}}; case 'futureIpt': return {'futureIpt': {like: `%${value}%`}}; - case 'totalWithVat': - return {'totalWithVat': value}; - case 'futureTotalWithVat': - return {'futureTotalWithVat': value}; - case 'notMovableLines': - return {'notMovableLines': value}; } } } From f1deeb69cabfc11210f24173a8d683e9e99ab27c Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 24 Oct 2023 09:34:04 +0200 Subject: [PATCH 276/427] ref #5914 add ticketrefund and fix text --- .../invoiceOut/specs/transferinvoice.spec.js | 22 ++++++++++++++++--- modules/ticket/back/methods/sale/clone.js | 8 ++++++- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js index 75bf649ec..04f6df299 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js @@ -1,14 +1,30 @@ + const models = require('vn-loopback/server/server').models; +const LoopBackContext = require('loopback-context'); describe('InvoiceOut tranferInvoice()', () => { - const userId = 5; - const ctx = {req: {accessToken: userId}}; + const activeCtx = { + accessToken: {userId: 5}, + http: { + req: { + headers: {origin: 'http://localhost'} + } + } + }; + const ctx = {req: activeCtx}; + + beforeEach(() => { + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ + active: activeCtx + }); + }); + it('should return the id of the created issued invoice', async() => { const tx = await models.InvoiceOut.beginTransaction({}); const options = {transaction: tx}; const args = { id: '1', - ref: 'T1111111', + ref: 'T4444444', newClientFk: 1, cplusRectificationId: 1, cplusInvoiceType477Id: 1, diff --git a/modules/ticket/back/methods/sale/clone.js b/modules/ticket/back/methods/sale/clone.js index dd1b108b2..a72f17af6 100644 --- a/modules/ticket/back/methods/sale/clone.js +++ b/modules/ticket/back/methods/sale/clone.js @@ -105,7 +105,13 @@ module.exports = Self => { ctx.args.companyId = ticket.companyFk; ctx.args.addressId = ticket.addressFk; - return models.Ticket.new(ctx, myOptions); + const newTicket = await models.Ticket.new(ctx, myOptions); + await models.TicketRefund.create({ + originalTicketFk: ticketId, + refundTicketFk: newTicket.id + }, myOptions); + + return newTicket; } }; }; From 9f141238bc13223f6b760625e3e1985de71ceac5 Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 24 Oct 2023 11:47:54 +0200 Subject: [PATCH 277/427] ref #5216 add userFk --- .../methods/expedition-state/addExpeditionState.js | 10 ++++------ .../expedition-state/specs/addExpeditionState.spec.js | 8 ++++---- 2 files changed, 8 insertions(+), 10 deletions(-) diff --git a/modules/ticket/back/methods/expedition-state/addExpeditionState.js b/modules/ticket/back/methods/expedition-state/addExpeditionState.js index f1199f188..8eab1a838 100644 --- a/modules/ticket/back/methods/expedition-state/addExpeditionState.js +++ b/modules/ticket/back/methods/expedition-state/addExpeditionState.js @@ -1,7 +1,7 @@ const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { - Self.remoteMethod('addExpeditionState', { + Self.remoteMethodCtx('addExpeditionState', { description: 'Update an expedition state', accessType: 'WRITE', accepts: [ @@ -12,18 +12,15 @@ module.exports = Self => { description: 'Array of objects containing expeditionFk and stateCode' } ], - returns: { - type: 'boolean', - root: true - }, http: { path: `/addExpeditionState`, verb: 'post' } }); - Self.addExpeditionState = async(expeditions, options) => { + Self.addExpeditionState = async(ctx, expeditions, options) => { const models = Self.app.models; + const userId = ctx.req.accessToken.userId; let tx; const myOptions = {}; if (typeof options == 'object') @@ -51,6 +48,7 @@ module.exports = Self => { await models.ExpeditionState.create({ expeditionFk: expedition.expeditionFk, typeFk, + userFk: userId, }, myOptions); } diff --git a/modules/ticket/back/methods/expedition-state/specs/addExpeditionState.spec.js b/modules/ticket/back/methods/expedition-state/specs/addExpeditionState.spec.js index 819a43a60..6c7739006 100644 --- a/modules/ticket/back/methods/expedition-state/specs/addExpeditionState.spec.js +++ b/modules/ticket/back/methods/expedition-state/specs/addExpeditionState.spec.js @@ -1,9 +1,9 @@ const models = require('vn-loopback/server/server').models; describe('expeditionState addExpeditionState()', () => { + const ctx = {req: {accessToken: {userId: 9}}}; it('should update the expedition states', async() => { const tx = await models.ExpeditionState.beginTransaction({}); - try { const options = {transaction: tx}; const payload = [ @@ -13,7 +13,7 @@ describe('expeditionState addExpeditionState()', () => { }, ]; - await models.ExpeditionState.addExpeditionState(payload, options); + await models.ExpeditionState.addExpeditionState(ctx, payload, options); const expeditionState = await models.ExpeditionState.findOne({ where: {id: 5} @@ -39,7 +39,7 @@ describe('expeditionState addExpeditionState()', () => { stateCode: 'DUMMY' } ]; - await models.ExpeditionState.addExpeditionState(payload, options); + await models.ExpeditionState.addExpeditionState(ctx, payload, options); await tx.rollback(); } catch (e) { @@ -62,7 +62,7 @@ describe('expeditionState addExpeditionState()', () => { } ]; - await models.ExpeditionState.addExpeditionState(payload, options); + await models.ExpeditionState.addExpeditionState(ctx, payload, options); await tx.rollback(); } catch (e) { From 589d7cbbb82dce802cf30096ed1e47e85dd157e0 Mon Sep 17 00:00:00 2001 From: alexm Date: Tue, 24 Oct 2023 12:02:21 +0200 Subject: [PATCH 278/427] fix: ticket_canAdvance correct worker. fix(dockerFIle)! dockerFile debian version --- Dockerfile | 2 +- db/changes/234003/00-ticket_canAdvance_zone.sql | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/Dockerfile b/Dockerfile index e1173ad73..c82b20b31 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM debian:bullseye-slim +FROM debian:bookworm-slim ENV TZ Europe/Madrid ARG DEBIAN_FRONTEND=noninteractive diff --git a/db/changes/234003/00-ticket_canAdvance_zone.sql b/db/changes/234003/00-ticket_canAdvance_zone.sql index c11cdc49a..ee07ce978 100644 --- a/db/changes/234003/00-ticket_canAdvance_zone.sql +++ b/db/changes/234003/00-ticket_canAdvance_zone.sql @@ -72,7 +72,7 @@ BEGIN FROM ( SELECT s.ticketFk, - t.workerFk, + c.salesPersonFk workerFk, t.shipped, t.totalWithVat, st.name futureState, @@ -86,6 +86,7 @@ BEGIN z.name futureZoneName, st.classColor FROM ticket t + JOIN client c ON c.id = t.clientFk JOIN sale s ON s.ticketFk = t.id JOIN saleVolume sv ON sv.saleFk = s.id JOIN item i ON i.id = s.itemFk From 22fdcef7bb2faa0f9737d6fa01d3e51487924607 Mon Sep 17 00:00:00 2001 From: alexm Date: Tue, 24 Oct 2023 14:07:05 +0200 Subject: [PATCH 279/427] fix(dockerFIle)! front debian version --- Dockerfile | 2 +- front/Dockerfile | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Dockerfile b/Dockerfile index c82b20b31..e1173ad73 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM debian:bookworm-slim +FROM debian:bullseye-slim ENV TZ Europe/Madrid ARG DEBIAN_FRONTEND=noninteractive diff --git a/front/Dockerfile b/front/Dockerfile index 098ee161e..d0ee26904 100644 --- a/front/Dockerfile +++ b/front/Dockerfile @@ -1,4 +1,4 @@ -FROM debian:stretch-slim +FROM debian:bookworm-slim EXPOSE 80 ENV TZ Europe/Madrid From efa9f1645213124f7575c9d3be6e6d2216d8c4e1 Mon Sep 17 00:00:00 2001 From: alexm Date: Wed, 25 Oct 2023 09:22:44 +0200 Subject: [PATCH 280/427] fix: remove unnecessary UserError --- modules/ticket/back/methods/ticket/addSale.js | 2 -- 1 file changed, 2 deletions(-) diff --git a/modules/ticket/back/methods/ticket/addSale.js b/modules/ticket/back/methods/ticket/addSale.js index 3455ec2c4..826de6e12 100644 --- a/modules/ticket/back/methods/ticket/addSale.js +++ b/modules/ticket/back/methods/ticket/addSale.js @@ -1,5 +1,3 @@ -const UserError = require('vn-loopback/util/user-error'); - module.exports = Self => { Self.remoteMethodCtx('addSale', { description: 'Inserts a new sale for the current ticket', From b461f63e2cd9c2d64a96513960336b32b06eb97e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Wed, 25 Oct 2023 11:02:53 +0200 Subject: [PATCH 281/427] refs #4707 fix: correct sqlVersion --- db/changes/{234003 => 234004}/.gitkeep | 0 db/changes/{234003 => 234004}/00-workerTimeControl.sql | 1 - db/changes/{234003 => 234004}/01-timeControl_calculate.sql | 0 db/changes/{234003 => 234004}/02-workerTimeControl_clockIn.sql | 0 4 files changed, 1 deletion(-) rename db/changes/{234003 => 234004}/.gitkeep (100%) rename db/changes/{234003 => 234004}/00-workerTimeControl.sql (97%) rename db/changes/{234003 => 234004}/01-timeControl_calculate.sql (100%) rename db/changes/{234003 => 234004}/02-workerTimeControl_clockIn.sql (100%) diff --git a/db/changes/234003/.gitkeep b/db/changes/234004/.gitkeep similarity index 100% rename from db/changes/234003/.gitkeep rename to db/changes/234004/.gitkeep diff --git a/db/changes/234003/00-workerTimeControl.sql b/db/changes/234004/00-workerTimeControl.sql similarity index 97% rename from db/changes/234003/00-workerTimeControl.sql rename to db/changes/234004/00-workerTimeControl.sql index c96fafcdd..8f6263533 100644 --- a/db/changes/234003/00-workerTimeControl.sql +++ b/db/changes/234004/00-workerTimeControl.sql @@ -28,7 +28,6 @@ CREATE TABLE IF NOT EXISTS `vn`.`workerTimeControlError` ( UNIQUE KEY `code` (`code`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; - INSERT IGNORE INTO `vn`.`workerTimeControlError` (`code`, `description`) VALUES ('IS_NOT_ALLOWED_FUTURE', 'No se permite fichar a futuro'), diff --git a/db/changes/234003/01-timeControl_calculate.sql b/db/changes/234004/01-timeControl_calculate.sql similarity index 100% rename from db/changes/234003/01-timeControl_calculate.sql rename to db/changes/234004/01-timeControl_calculate.sql diff --git a/db/changes/234003/02-workerTimeControl_clockIn.sql b/db/changes/234004/02-workerTimeControl_clockIn.sql similarity index 100% rename from db/changes/234003/02-workerTimeControl_clockIn.sql rename to db/changes/234004/02-workerTimeControl_clockIn.sql From 26bdbabff5c7b4f6720214715b14d19ac7cc0888 Mon Sep 17 00:00:00 2001 From: alexm Date: Wed, 25 Oct 2023 15:48:19 +0200 Subject: [PATCH 282/427] refs #6335 feat(ticketAdvanced): show all tickets --- .../234201/00-ticket_canAdvance_leftJoin.sql | 132 ++++++++++++++++++ loopback/server/boot/date.js | 4 +- modules/ticket/front/advance/index.html | 10 +- 3 files changed, 142 insertions(+), 4 deletions(-) create mode 100644 db/changes/234201/00-ticket_canAdvance_leftJoin.sql diff --git a/db/changes/234201/00-ticket_canAdvance_leftJoin.sql b/db/changes/234201/00-ticket_canAdvance_leftJoin.sql new file mode 100644 index 000000000..b26c3a102 --- /dev/null +++ b/db/changes/234201/00-ticket_canAdvance_leftJoin.sql @@ -0,0 +1,132 @@ +DELIMITER $$ +$$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_canAdvance`(vDateFuture DATE, vDateToAdvance DATE, vWarehouseFk INT) +BEGIN +/** + * Devuelve los tickets y la cantidad de lineas de venta que se pueden adelantar. + * + * @param vDateFuture Fecha de los tickets que se quieren adelantar. + * @param vDateToAdvance Fecha a cuando se quiere adelantar. + * @param vWarehouseFk Almacén + */ + DECLARE vDateInventory DATE; + + SELECT inventoried INTO vDateInventory FROM config; + + DROP TEMPORARY TABLE IF EXISTS tmp.stock; + CREATE TEMPORARY TABLE tmp.stock + (itemFk INT PRIMARY KEY, + amount INT) + ENGINE = MEMORY; + + INSERT INTO tmp.stock(itemFk, amount) + SELECT itemFk, SUM(quantity) amount FROM + ( + SELECT itemFk, quantity + FROM itemTicketOut + WHERE shipped >= vDateInventory + AND shipped < vDateFuture + AND warehouseFk = vWarehouseFk + UNION ALL + SELECT itemFk, quantity + FROM itemEntryIn + WHERE landed >= vDateInventory + AND landed < vDateFuture + AND isVirtualStock = FALSE + AND warehouseInFk = vWarehouseFk + UNION ALL + SELECT itemFk, quantity + FROM itemEntryOut + WHERE shipped >= vDateInventory + AND shipped < vDateFuture + AND warehouseOutFk = vWarehouseFk + ) t + GROUP BY itemFk HAVING amount != 0; + + CREATE OR REPLACE TEMPORARY TABLE tmp.filter + (INDEX (id)) + SELECT + origin.ticketFk futureId, + dest.ticketFk id, + dest.state, + origin.futureState, + origin.futureIpt, + dest.ipt, + origin.workerFk, + origin.futureLiters, + origin.futureLines, + dest.shipped, + origin.shipped futureShipped, + dest.totalWithVat, + origin.totalWithVat futureTotalWithVat, + dest.agency, + origin.futureAgency, + dest.lines, + dest.liters, + origin.futureLines - origin.hasStock AS notMovableLines, + (origin.futureLines = origin.hasStock) AS isFullMovable, + origin.futureZoneFk, + origin.futureZoneName, + origin.classColor futureClassColor, + dest.classColor + FROM ( + SELECT + s.ticketFk, + c.salesPersonFk workerFk, + t.shipped, + t.totalWithVat, + st.name futureState, + t.addressFk, + am.name futureAgency, + count(s.id) futureLines, + GROUP_CONCAT(DISTINCT ipt.code ORDER BY ipt.code) futureIpt, + CAST(SUM(litros) AS DECIMAL(10,0)) futureLiters, + SUM((s.quantity <= IFNULL(st.amount,0))) hasStock, + z.id futureZoneFk, + z.name futureZoneName, + st.classColor + FROM ticket t + JOIN client c ON c.id = t.clientFk + JOIN sale s ON s.ticketFk = t.id + JOIN saleVolume sv ON sv.saleFk = s.id + JOIN item i ON i.id = s.itemFk + JOIN ticketState ts ON ts.ticketFk = t.id + JOIN state st ON st.id = ts.stateFk + JOIN agencyMode am ON t.agencyModeFk = am.id + JOIN zone z ON t.zoneFk = z.id + LEFT JOIN itemPackingType ipt ON ipt.code = i.itemPackingTypeFk + LEFT JOIN tmp.stock st ON st.itemFk = i.id + WHERE t.shipped BETWEEN vDateFuture AND util.dayend(vDateFuture) + AND t.warehouseFk = vWarehouseFk + GROUP BY t.id + ) origin + LEFT JOIN ( + SELECT + t.id ticketFk, + t.addressFk, + st.name state, + GROUP_CONCAT(DISTINCT ipt.code ORDER BY ipt.code) ipt, + t.shipped, + t.totalWithVat, + am.name agency, + CAST(SUM(litros) AS DECIMAL(10,0)) liters, + CAST(COUNT(*) AS DECIMAL(10,0)) `lines`, + st.classColor + FROM ticket t + JOIN sale s ON s.ticketFk = t.id + JOIN saleVolume sv ON sv.saleFk = s.id + JOIN item i ON i.id = s.itemFk + JOIN ticketState ts ON ts.ticketFk = t.id + JOIN state st ON st.id = ts.stateFk + JOIN agencyMode am ON t.agencyModeFk = am.id + LEFT JOIN itemPackingType ipt ON ipt.code = i.itemPackingTypeFk + WHERE t.shipped BETWEEN vDateToAdvance AND util.dayend(vDateToAdvance) + AND t.warehouseFk = vWarehouseFk + AND st.order <= 5 + GROUP BY t.id + ) dest ON dest.addressFk = origin.addressFk + WHERE origin.hasStock != 0; + + DROP TEMPORARY TABLE tmp.stock; +END$$ +DELIMITER ; diff --git a/loopback/server/boot/date.js b/loopback/server/boot/date.js index 810745562..88505cf62 100644 --- a/loopback/server/boot/date.js +++ b/loopback/server/boot/date.js @@ -1,8 +1,8 @@ module.exports = () => { Date.vnUTC = () => { const env = process.env.NODE_ENV; - if (!env || env === 'development') - return new Date(Date.UTC(2001, 0, 1, 11)); + // if (!env || env === 'development') + // return new Date(Date.UTC(2001, 0, 1, 11)); return new Date(); }; diff --git a/modules/ticket/front/advance/index.html b/modules/ticket/front/advance/index.html index a6cf8face..af5b8f704 100644 --- a/modules/ticket/front/advance/index.html +++ b/modules/ticket/front/advance/index.html @@ -105,7 +105,7 @@ @@ -159,7 +159,13 @@ {{::ticket.futureLiters | dashIfEmpty}} {{::ticket.futureZoneName | dashIfEmpty}} - {{::ticket.notMovableLines | dashIfEmpty}} + + + {{::ticket.notMovableLines | dashIfEmpty}} + + {{::ticket.futureLines | dashIfEmpty}} Date: Thu, 26 Oct 2023 07:56:57 +0200 Subject: [PATCH 283/427] refs #6278 test(itemRequest): fix e2e, correct selector --- e2e/helpers/selectors.js | 10 +++++----- modules/item/front/request/index.html | 28 +++++++++++++-------------- 2 files changed, 19 insertions(+), 19 deletions(-) diff --git a/e2e/helpers/selectors.js b/e2e/helpers/selectors.js index 5e071911e..cec0545a0 100644 --- a/e2e/helpers/selectors.js +++ b/e2e/helpers/selectors.js @@ -409,11 +409,11 @@ export default { inactiveIcon: 'vn-item-descriptor vn-icon[icon="icon-unavailable"]' }, itemRequest: { - firstRequestItemID: 'vn-item-request vn-tbody > vn-tr:nth-child(1) > vn-td-editable:nth-child(7)', - firstRequestQuantity: 'vn-item-request vn-tbody > vn-tr:nth-child(1) > vn-td-editable:nth-child(8)', - firstRequestConcept: 'vn-item-request vn-tbody > vn-tr:nth-child(1) > vn-td:nth-child(9)', - firstRequestStatus: 'vn-item-request vn-tbody > vn-tr:nth-child(1) > vn-td:nth-child(10)', - secondRequestStatus: 'vn-item-request vn-tbody > vn-tr:nth-child(2) > vn-td:nth-child(10)', + firstRequestItemID: 'vn-item-request vn-tbody > vn-tr:nth-child(1) > vn-td-editable:nth-child(8)', + firstRequestQuantity: 'vn-item-request vn-tbody > vn-tr:nth-child(1) > vn-td-editable:nth-child(9)', + firstRequestConcept: 'vn-item-request vn-tbody > vn-tr:nth-child(1) > vn-td:nth-child(10)', + firstRequestStatus: 'vn-item-request vn-tbody > vn-tr:nth-child(1) > vn-td:nth-child(11)', + secondRequestStatus: 'vn-item-request vn-tbody > vn-tr:nth-child(2) > vn-td:nth-child(11)', secondRequestDecline: 'vn-item-request vn-tr:nth-child(2) vn-icon-button[icon="thumb_down"]', declineReason: 'vn-textarea[ng-model="$ctrl.denyObservation"]' }, diff --git a/modules/item/front/request/index.html b/modules/item/front/request/index.html index 200ce3902..03c8db8ec 100644 --- a/modules/item/front/request/index.html +++ b/modules/item/front/request/index.html @@ -26,7 +26,7 @@ Ticket ID Shipped Description - Requester + Requester Requested Price Atender @@ -86,8 +86,8 @@ - {{request.itemDescription}} @@ -114,13 +114,13 @@ - - - @@ -149,24 +149,24 @@ ng-click="contextmenu.filterBySelection()"> Filter by selection - Exclude selection - Remove filter - Remove all filters - Copy value - \ No newline at end of file + From 83cff374227dc893ddd5e7ae405260ab8411079e Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 26 Oct 2023 08:23:18 +0200 Subject: [PATCH 284/427] refs #6350 fix: 00-dropWorkerCreate.sql --- db/changes/234201/00-dropWorkerCreate.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/changes/234201/00-dropWorkerCreate.sql b/db/changes/234201/00-dropWorkerCreate.sql index be2761c3d..b903909b6 100644 --- a/db/changes/234201/00-dropWorkerCreate.sql +++ b/db/changes/234201/00-dropWorkerCreate.sql @@ -1 +1 @@ -DROP PROCEDURE IF EXISTS vn.workerCreate; \ No newline at end of file +DROP PROCEDURE IF EXISTS `vn`.`workerCreate`; From 3a1227bdc225545d46c3ee47191759e2ba4d9bba Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 26 Oct 2023 09:20:25 +0200 Subject: [PATCH 285/427] ref #5914 fix ticketrefund --- modules/ticket/back/methods/sale/clone.js | 33 +++++++++++++---------- 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/modules/ticket/back/methods/sale/clone.js b/modules/ticket/back/methods/sale/clone.js index a72f17af6..a5ccb6de4 100644 --- a/modules/ticket/back/methods/sale/clone.js +++ b/modules/ticket/back/methods/sale/clone.js @@ -3,7 +3,7 @@ module.exports = Self => { const models = Self.app.models; const myOptions = {}; let tx; - const refundTickets = []; + const newTickets = []; if (typeof options == 'object') Object.assign(myOptions, options); @@ -31,21 +31,22 @@ module.exports = Self => { if (group) ticketsIds = [ticketsIds[0]]; for (let ticketId of ticketsIds) { - const ticketRefund = await createTicketRefund( + const newTicket = await createTicket( ctx, ticketId, withWarehouse, + negative, myOptions ); - refundTickets.push(ticketRefund); - mappedTickets.set(ticketId, ticketRefund.id); + newTickets.push(newTicket); + mappedTickets.set(ticketId, newTicket.id); } for (const sale of sales) { - const refundTicketId = mappedTickets.get(sale.ticketFk); + const newTicketId = mappedTickets.get(sale.ticketFk); const createdSale = await models.Sale.create({ - ticketFk: refundTicketId, + ticketFk: newTicketId, itemFk: sale.itemFk, quantity: negative ? - sale.quantity : sale.quantity, concept: sale.concept, @@ -67,14 +68,14 @@ module.exports = Self => { const services = await models.TicketService.find(servicesFilter, myOptions); for (const service of services) { - const refundTicketId = mappedTickets.get(service.ticketFk); + const newTicketId = mappedTickets.get(service.ticketFk); await models.TicketService.create({ description: service.description, quantity: negative ? - service.quantity : service.quantity, price: service.price, taxClassFk: service.taxClassFk, - ticketFk: refundTicketId, + ticketFk: newTicketId, ticketServiceTypeFk: service.ticketServiceTypeFk, }, myOptions); } @@ -82,16 +83,17 @@ module.exports = Self => { if (tx) await tx.commit(); - return refundTickets; + return newTickets; } catch (e) { if (tx) await tx.rollback(); throw e; } - async function createTicketRefund( + async function createTicket( ctx, ticketId, withWarehouse, + negative, myOptions ) { const models = Self.app.models; @@ -106,10 +108,13 @@ module.exports = Self => { ctx.args.addressId = ticket.addressFk; const newTicket = await models.Ticket.new(ctx, myOptions); - await models.TicketRefund.create({ - originalTicketFk: ticketId, - refundTicketFk: newTicket.id - }, myOptions); + + if (negative) { + await models.TicketRefund.create({ + originalTicketFk: ticketId, + refundTicketFk: newTicket.id + }, myOptions); + } return newTicket; } From cecdf8633cea829928b37608f14ea7e97e29184f Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 26 Oct 2023 09:27:32 +0200 Subject: [PATCH 286/427] refs #6350 deploy: init version 23.46 --- CHANGELOG.md | 8 +++++++- db/{changes => .archive}/231201/00-ACL.sql | 0 db/{changes => .archive}/231201/00-chatRefactor.sql | 0 db/{changes => .archive}/231201/00-invoiceInSerial.sql | 0 db/{changes => .archive}/231201/00-itemType_isFragile.sql | 0 db/{changes => .archive}/231201/00-mailACL.sql | 0 db/{changes => .archive}/231201/00-operator.sql | 0 .../231201/00-supplierAccount_deleteTriggers.sql | 0 db/{changes => .archive}/231201/00-ticket_getWarnings.sql | 0 db/{changes => .archive}/231201/00-wagon.sql | 0 db/{changes => .archive}/231202/00-delivery.sql | 0 db/{changes => .archive}/231203/00-delivery.sql | 0 db/{changes => .archive}/231204/00-rollbackDelivery.sql | 0 db/{changes => .archive}/231205/00-printQueueArgs.sql | 0 .../231401/00-claimBeginningAfterInsert.sql | 0 db/{changes => .archive}/231401/00-clientBeforeUpdate.sql | 0 db/{changes => .archive}/231401/00-hotfixDelivery.sql | 0 .../231401/00-invoiceOutAfterInsert.sql | 0 db/{changes => .archive}/231401/00-negativeBases.sql | 0 db/{changes => .archive}/231401/00-workerNotes.sql | 0 db/{changes => .archive}/231402/00-negativeBases.sql | 0 db/{changes => .archive}/231801/00-aclClientInforma.sql | 0 db/{changes => .archive}/231801/00-acl_receiptEmail.sql | 0 db/{changes => .archive}/231801/00-clientInforma.sql | 0 .../231801/00-client_setRatingAcl.sql | 0 db/{changes => .archive}/231801/00-deleteProcs_refund.sql | 0 db/{changes => .archive}/231801/00-deviceProduction.sql | 0 db/{changes => .archive}/231801/00-kkearEntryNotes.sql | 0 db/{changes => .archive}/231801/00-newCompanyI18n.sql | 0 db/{changes => .archive}/231801/00-newTableWeb.sql | 0 .../231801/00-observationEmailACL.sql | 0 .../231801/00-optimiceZoneEstimatedDelivery.sql | 0 db/{changes => .archive}/231801/00-saleTracking.sql | 0 db/{changes => .archive}/231801/00-ticketConfig.sql | 0 db/{changes => .archive}/231801/00-updateIsVies.sql | 0 db/{changes => .archive}/231801/00-updateisViesClient.sql | 0 db/{changes => .archive}/231801/00-userAcl.sql | 0 db/{changes => .archive}/231801/00-userRoleLog.sql | 0 db/{changes => .archive}/231801/01-viewCompany10L.sql | 0 db/{changes => .archive}/232001/00-clientWorkerName.sql | 0 db/{changes => .archive}/232001/00-createWorker.sql | 0 db/{changes => .archive}/232001/00-invoiceOut_new.sql | 0 db/{changes => .archive}/232001/00-wagon.sql | 0 db/{changes => .archive}/232201/00-defaulterView.sql | 0 .../232201/00-procedurecanAdvance.sql | 0 .../232201/00-procedurecanbePostponed.sql | 0 .../232201/00-workerConfigPayMethod.sql | 0 .../232202/00-procedurecanAdvance.sql | 0 .../232202/00-procedurecanbePostponed.sql | 0 db/{changes => .archive}/232401/.gitkeep | 0 .../232401/00-buyConfig_travelConfig.sql | 0 db/{changes => .archive}/232401/00-printer.sql | 0 db/{changes => .archive}/232401/00-ticket_warehouse.sql | 0 db/{changes => .archive}/232401/00-userPassExpired.sql | 0 .../232402/00-hotFix_travelConfig.sql | 0 db/{changes => .archive}/232601/00-aclAccount.sql | 0 db/{changes => .archive}/232601/00-aclInvoiceTickets.sql | 0 .../232601/00-aclMailAliasAccount.sql | 0 db/{changes => .archive}/232601/00-aclMailForward.sql | 0 db/{changes => .archive}/232601/00-aclRole.sql | 0 db/{changes => .archive}/232601/00-aclVnUser.sql | 0 .../232601/00-aclVnUser_renewToken.sql | 0 .../232601/00-entry_updateComission.sql | 0 .../232601/00-packingSiteAdvanced.sql | 0 db/{changes => .archive}/232601/00-salix.sql | 0 db/{changes => .archive}/232601/00-useSpecificsAcls.sql | 0 db/{changes => .archive}/232601/01-invoiceOutPdf.sql | 0 db/{changes => .archive}/232602/01-aclAddAlias.sql | 0 db/{changes => .archive}/232801/00-authCode.sql | 0 db/{changes => .archive}/232801/00-client_create.sql | 0 db/{changes => .archive}/232801/00-client_create2.sql | 0 db/{changes => .archive}/232801/00-department.sql | 0 db/{changes => .archive}/232801/00-fix_editCredit.sql | 0 db/{changes => .archive}/232801/00-user.sql | 0 db/{changes => .archive}/232802/01-aclWorkerDisable.sql | 0 db/changes/234601/.gitkeep | 0 package-lock.json | 4 ++-- package.json | 2 +- 78 files changed, 10 insertions(+), 4 deletions(-) rename db/{changes => .archive}/231201/00-ACL.sql (100%) rename db/{changes => .archive}/231201/00-chatRefactor.sql (100%) rename db/{changes => .archive}/231201/00-invoiceInSerial.sql (100%) rename db/{changes => .archive}/231201/00-itemType_isFragile.sql (100%) rename db/{changes => .archive}/231201/00-mailACL.sql (100%) rename db/{changes => .archive}/231201/00-operator.sql (100%) rename db/{changes => .archive}/231201/00-supplierAccount_deleteTriggers.sql (100%) rename db/{changes => .archive}/231201/00-ticket_getWarnings.sql (100%) rename db/{changes => .archive}/231201/00-wagon.sql (100%) rename db/{changes => .archive}/231202/00-delivery.sql (100%) rename db/{changes => .archive}/231203/00-delivery.sql (100%) rename db/{changes => .archive}/231204/00-rollbackDelivery.sql (100%) rename db/{changes => .archive}/231205/00-printQueueArgs.sql (100%) rename db/{changes => .archive}/231401/00-claimBeginningAfterInsert.sql (100%) rename db/{changes => .archive}/231401/00-clientBeforeUpdate.sql (100%) rename db/{changes => .archive}/231401/00-hotfixDelivery.sql (100%) rename db/{changes => .archive}/231401/00-invoiceOutAfterInsert.sql (100%) rename db/{changes => .archive}/231401/00-negativeBases.sql (100%) rename db/{changes => .archive}/231401/00-workerNotes.sql (100%) rename db/{changes => .archive}/231402/00-negativeBases.sql (100%) rename db/{changes => .archive}/231801/00-aclClientInforma.sql (100%) rename db/{changes => .archive}/231801/00-acl_receiptEmail.sql (100%) rename db/{changes => .archive}/231801/00-clientInforma.sql (100%) rename db/{changes => .archive}/231801/00-client_setRatingAcl.sql (100%) rename db/{changes => .archive}/231801/00-deleteProcs_refund.sql (100%) rename db/{changes => .archive}/231801/00-deviceProduction.sql (100%) rename db/{changes => .archive}/231801/00-kkearEntryNotes.sql (100%) rename db/{changes => .archive}/231801/00-newCompanyI18n.sql (100%) rename db/{changes => .archive}/231801/00-newTableWeb.sql (100%) rename db/{changes => .archive}/231801/00-observationEmailACL.sql (100%) rename db/{changes => .archive}/231801/00-optimiceZoneEstimatedDelivery.sql (100%) rename db/{changes => .archive}/231801/00-saleTracking.sql (100%) rename db/{changes => .archive}/231801/00-ticketConfig.sql (100%) rename db/{changes => .archive}/231801/00-updateIsVies.sql (100%) rename db/{changes => .archive}/231801/00-updateisViesClient.sql (100%) rename db/{changes => .archive}/231801/00-userAcl.sql (100%) rename db/{changes => .archive}/231801/00-userRoleLog.sql (100%) rename db/{changes => .archive}/231801/01-viewCompany10L.sql (100%) rename db/{changes => .archive}/232001/00-clientWorkerName.sql (100%) rename db/{changes => .archive}/232001/00-createWorker.sql (100%) rename db/{changes => .archive}/232001/00-invoiceOut_new.sql (100%) rename db/{changes => .archive}/232001/00-wagon.sql (100%) rename db/{changes => .archive}/232201/00-defaulterView.sql (100%) rename db/{changes => .archive}/232201/00-procedurecanAdvance.sql (100%) rename db/{changes => .archive}/232201/00-procedurecanbePostponed.sql (100%) rename db/{changes => .archive}/232201/00-workerConfigPayMethod.sql (100%) rename db/{changes => .archive}/232202/00-procedurecanAdvance.sql (100%) rename db/{changes => .archive}/232202/00-procedurecanbePostponed.sql (100%) rename db/{changes => .archive}/232401/.gitkeep (100%) rename db/{changes => .archive}/232401/00-buyConfig_travelConfig.sql (100%) rename db/{changes => .archive}/232401/00-printer.sql (100%) rename db/{changes => .archive}/232401/00-ticket_warehouse.sql (100%) rename db/{changes => .archive}/232401/00-userPassExpired.sql (100%) rename db/{changes => .archive}/232402/00-hotFix_travelConfig.sql (100%) rename db/{changes => .archive}/232601/00-aclAccount.sql (100%) rename db/{changes => .archive}/232601/00-aclInvoiceTickets.sql (100%) rename db/{changes => .archive}/232601/00-aclMailAliasAccount.sql (100%) rename db/{changes => .archive}/232601/00-aclMailForward.sql (100%) rename db/{changes => .archive}/232601/00-aclRole.sql (100%) rename db/{changes => .archive}/232601/00-aclVnUser.sql (100%) rename db/{changes => .archive}/232601/00-aclVnUser_renewToken.sql (100%) rename db/{changes => .archive}/232601/00-entry_updateComission.sql (100%) rename db/{changes => .archive}/232601/00-packingSiteAdvanced.sql (100%) rename db/{changes => .archive}/232601/00-salix.sql (100%) rename db/{changes => .archive}/232601/00-useSpecificsAcls.sql (100%) rename db/{changes => .archive}/232601/01-invoiceOutPdf.sql (100%) rename db/{changes => .archive}/232602/01-aclAddAlias.sql (100%) rename db/{changes => .archive}/232801/00-authCode.sql (100%) rename db/{changes => .archive}/232801/00-client_create.sql (100%) rename db/{changes => .archive}/232801/00-client_create2.sql (100%) rename db/{changes => .archive}/232801/00-department.sql (100%) rename db/{changes => .archive}/232801/00-fix_editCredit.sql (100%) rename db/{changes => .archive}/232801/00-user.sql (100%) rename db/{changes => .archive}/232802/01-aclWorkerDisable.sql (100%) create mode 100644 db/changes/234601/.gitkeep diff --git a/CHANGELOG.md b/CHANGELOG.md index d677b80e3..cd6ed4522 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,13 @@ 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). -## [2342.01] - 2023-10-19 +## [2346.01] - 2023-11-16 + +### Added +### Changed +### Fixed + +## [2342.01] - 2023-11-02 ### Added ### Changed diff --git a/db/changes/231201/00-ACL.sql b/db/.archive/231201/00-ACL.sql similarity index 100% rename from db/changes/231201/00-ACL.sql rename to db/.archive/231201/00-ACL.sql diff --git a/db/changes/231201/00-chatRefactor.sql b/db/.archive/231201/00-chatRefactor.sql similarity index 100% rename from db/changes/231201/00-chatRefactor.sql rename to db/.archive/231201/00-chatRefactor.sql diff --git a/db/changes/231201/00-invoiceInSerial.sql b/db/.archive/231201/00-invoiceInSerial.sql similarity index 100% rename from db/changes/231201/00-invoiceInSerial.sql rename to db/.archive/231201/00-invoiceInSerial.sql diff --git a/db/changes/231201/00-itemType_isFragile.sql b/db/.archive/231201/00-itemType_isFragile.sql similarity index 100% rename from db/changes/231201/00-itemType_isFragile.sql rename to db/.archive/231201/00-itemType_isFragile.sql diff --git a/db/changes/231201/00-mailACL.sql b/db/.archive/231201/00-mailACL.sql similarity index 100% rename from db/changes/231201/00-mailACL.sql rename to db/.archive/231201/00-mailACL.sql diff --git a/db/changes/231201/00-operator.sql b/db/.archive/231201/00-operator.sql similarity index 100% rename from db/changes/231201/00-operator.sql rename to db/.archive/231201/00-operator.sql diff --git a/db/changes/231201/00-supplierAccount_deleteTriggers.sql b/db/.archive/231201/00-supplierAccount_deleteTriggers.sql similarity index 100% rename from db/changes/231201/00-supplierAccount_deleteTriggers.sql rename to db/.archive/231201/00-supplierAccount_deleteTriggers.sql diff --git a/db/changes/231201/00-ticket_getWarnings.sql b/db/.archive/231201/00-ticket_getWarnings.sql similarity index 100% rename from db/changes/231201/00-ticket_getWarnings.sql rename to db/.archive/231201/00-ticket_getWarnings.sql diff --git a/db/changes/231201/00-wagon.sql b/db/.archive/231201/00-wagon.sql similarity index 100% rename from db/changes/231201/00-wagon.sql rename to db/.archive/231201/00-wagon.sql diff --git a/db/changes/231202/00-delivery.sql b/db/.archive/231202/00-delivery.sql similarity index 100% rename from db/changes/231202/00-delivery.sql rename to db/.archive/231202/00-delivery.sql diff --git a/db/changes/231203/00-delivery.sql b/db/.archive/231203/00-delivery.sql similarity index 100% rename from db/changes/231203/00-delivery.sql rename to db/.archive/231203/00-delivery.sql diff --git a/db/changes/231204/00-rollbackDelivery.sql b/db/.archive/231204/00-rollbackDelivery.sql similarity index 100% rename from db/changes/231204/00-rollbackDelivery.sql rename to db/.archive/231204/00-rollbackDelivery.sql diff --git a/db/changes/231205/00-printQueueArgs.sql b/db/.archive/231205/00-printQueueArgs.sql similarity index 100% rename from db/changes/231205/00-printQueueArgs.sql rename to db/.archive/231205/00-printQueueArgs.sql diff --git a/db/changes/231401/00-claimBeginningAfterInsert.sql b/db/.archive/231401/00-claimBeginningAfterInsert.sql similarity index 100% rename from db/changes/231401/00-claimBeginningAfterInsert.sql rename to db/.archive/231401/00-claimBeginningAfterInsert.sql diff --git a/db/changes/231401/00-clientBeforeUpdate.sql b/db/.archive/231401/00-clientBeforeUpdate.sql similarity index 100% rename from db/changes/231401/00-clientBeforeUpdate.sql rename to db/.archive/231401/00-clientBeforeUpdate.sql diff --git a/db/changes/231401/00-hotfixDelivery.sql b/db/.archive/231401/00-hotfixDelivery.sql similarity index 100% rename from db/changes/231401/00-hotfixDelivery.sql rename to db/.archive/231401/00-hotfixDelivery.sql diff --git a/db/changes/231401/00-invoiceOutAfterInsert.sql b/db/.archive/231401/00-invoiceOutAfterInsert.sql similarity index 100% rename from db/changes/231401/00-invoiceOutAfterInsert.sql rename to db/.archive/231401/00-invoiceOutAfterInsert.sql diff --git a/db/changes/231401/00-negativeBases.sql b/db/.archive/231401/00-negativeBases.sql similarity index 100% rename from db/changes/231401/00-negativeBases.sql rename to db/.archive/231401/00-negativeBases.sql diff --git a/db/changes/231401/00-workerNotes.sql b/db/.archive/231401/00-workerNotes.sql similarity index 100% rename from db/changes/231401/00-workerNotes.sql rename to db/.archive/231401/00-workerNotes.sql diff --git a/db/changes/231402/00-negativeBases.sql b/db/.archive/231402/00-negativeBases.sql similarity index 100% rename from db/changes/231402/00-negativeBases.sql rename to db/.archive/231402/00-negativeBases.sql diff --git a/db/changes/231801/00-aclClientInforma.sql b/db/.archive/231801/00-aclClientInforma.sql similarity index 100% rename from db/changes/231801/00-aclClientInforma.sql rename to db/.archive/231801/00-aclClientInforma.sql diff --git a/db/changes/231801/00-acl_receiptEmail.sql b/db/.archive/231801/00-acl_receiptEmail.sql similarity index 100% rename from db/changes/231801/00-acl_receiptEmail.sql rename to db/.archive/231801/00-acl_receiptEmail.sql diff --git a/db/changes/231801/00-clientInforma.sql b/db/.archive/231801/00-clientInforma.sql similarity index 100% rename from db/changes/231801/00-clientInforma.sql rename to db/.archive/231801/00-clientInforma.sql diff --git a/db/changes/231801/00-client_setRatingAcl.sql b/db/.archive/231801/00-client_setRatingAcl.sql similarity index 100% rename from db/changes/231801/00-client_setRatingAcl.sql rename to db/.archive/231801/00-client_setRatingAcl.sql diff --git a/db/changes/231801/00-deleteProcs_refund.sql b/db/.archive/231801/00-deleteProcs_refund.sql similarity index 100% rename from db/changes/231801/00-deleteProcs_refund.sql rename to db/.archive/231801/00-deleteProcs_refund.sql diff --git a/db/changes/231801/00-deviceProduction.sql b/db/.archive/231801/00-deviceProduction.sql similarity index 100% rename from db/changes/231801/00-deviceProduction.sql rename to db/.archive/231801/00-deviceProduction.sql diff --git a/db/changes/231801/00-kkearEntryNotes.sql b/db/.archive/231801/00-kkearEntryNotes.sql similarity index 100% rename from db/changes/231801/00-kkearEntryNotes.sql rename to db/.archive/231801/00-kkearEntryNotes.sql diff --git a/db/changes/231801/00-newCompanyI18n.sql b/db/.archive/231801/00-newCompanyI18n.sql similarity index 100% rename from db/changes/231801/00-newCompanyI18n.sql rename to db/.archive/231801/00-newCompanyI18n.sql diff --git a/db/changes/231801/00-newTableWeb.sql b/db/.archive/231801/00-newTableWeb.sql similarity index 100% rename from db/changes/231801/00-newTableWeb.sql rename to db/.archive/231801/00-newTableWeb.sql diff --git a/db/changes/231801/00-observationEmailACL.sql b/db/.archive/231801/00-observationEmailACL.sql similarity index 100% rename from db/changes/231801/00-observationEmailACL.sql rename to db/.archive/231801/00-observationEmailACL.sql diff --git a/db/changes/231801/00-optimiceZoneEstimatedDelivery.sql b/db/.archive/231801/00-optimiceZoneEstimatedDelivery.sql similarity index 100% rename from db/changes/231801/00-optimiceZoneEstimatedDelivery.sql rename to db/.archive/231801/00-optimiceZoneEstimatedDelivery.sql diff --git a/db/changes/231801/00-saleTracking.sql b/db/.archive/231801/00-saleTracking.sql similarity index 100% rename from db/changes/231801/00-saleTracking.sql rename to db/.archive/231801/00-saleTracking.sql diff --git a/db/changes/231801/00-ticketConfig.sql b/db/.archive/231801/00-ticketConfig.sql similarity index 100% rename from db/changes/231801/00-ticketConfig.sql rename to db/.archive/231801/00-ticketConfig.sql diff --git a/db/changes/231801/00-updateIsVies.sql b/db/.archive/231801/00-updateIsVies.sql similarity index 100% rename from db/changes/231801/00-updateIsVies.sql rename to db/.archive/231801/00-updateIsVies.sql diff --git a/db/changes/231801/00-updateisViesClient.sql b/db/.archive/231801/00-updateisViesClient.sql similarity index 100% rename from db/changes/231801/00-updateisViesClient.sql rename to db/.archive/231801/00-updateisViesClient.sql diff --git a/db/changes/231801/00-userAcl.sql b/db/.archive/231801/00-userAcl.sql similarity index 100% rename from db/changes/231801/00-userAcl.sql rename to db/.archive/231801/00-userAcl.sql diff --git a/db/changes/231801/00-userRoleLog.sql b/db/.archive/231801/00-userRoleLog.sql similarity index 100% rename from db/changes/231801/00-userRoleLog.sql rename to db/.archive/231801/00-userRoleLog.sql diff --git a/db/changes/231801/01-viewCompany10L.sql b/db/.archive/231801/01-viewCompany10L.sql similarity index 100% rename from db/changes/231801/01-viewCompany10L.sql rename to db/.archive/231801/01-viewCompany10L.sql diff --git a/db/changes/232001/00-clientWorkerName.sql b/db/.archive/232001/00-clientWorkerName.sql similarity index 100% rename from db/changes/232001/00-clientWorkerName.sql rename to db/.archive/232001/00-clientWorkerName.sql diff --git a/db/changes/232001/00-createWorker.sql b/db/.archive/232001/00-createWorker.sql similarity index 100% rename from db/changes/232001/00-createWorker.sql rename to db/.archive/232001/00-createWorker.sql diff --git a/db/changes/232001/00-invoiceOut_new.sql b/db/.archive/232001/00-invoiceOut_new.sql similarity index 100% rename from db/changes/232001/00-invoiceOut_new.sql rename to db/.archive/232001/00-invoiceOut_new.sql diff --git a/db/changes/232001/00-wagon.sql b/db/.archive/232001/00-wagon.sql similarity index 100% rename from db/changes/232001/00-wagon.sql rename to db/.archive/232001/00-wagon.sql diff --git a/db/changes/232201/00-defaulterView.sql b/db/.archive/232201/00-defaulterView.sql similarity index 100% rename from db/changes/232201/00-defaulterView.sql rename to db/.archive/232201/00-defaulterView.sql diff --git a/db/changes/232201/00-procedurecanAdvance.sql b/db/.archive/232201/00-procedurecanAdvance.sql similarity index 100% rename from db/changes/232201/00-procedurecanAdvance.sql rename to db/.archive/232201/00-procedurecanAdvance.sql diff --git a/db/changes/232201/00-procedurecanbePostponed.sql b/db/.archive/232201/00-procedurecanbePostponed.sql similarity index 100% rename from db/changes/232201/00-procedurecanbePostponed.sql rename to db/.archive/232201/00-procedurecanbePostponed.sql diff --git a/db/changes/232201/00-workerConfigPayMethod.sql b/db/.archive/232201/00-workerConfigPayMethod.sql similarity index 100% rename from db/changes/232201/00-workerConfigPayMethod.sql rename to db/.archive/232201/00-workerConfigPayMethod.sql diff --git a/db/changes/232202/00-procedurecanAdvance.sql b/db/.archive/232202/00-procedurecanAdvance.sql similarity index 100% rename from db/changes/232202/00-procedurecanAdvance.sql rename to db/.archive/232202/00-procedurecanAdvance.sql diff --git a/db/changes/232202/00-procedurecanbePostponed.sql b/db/.archive/232202/00-procedurecanbePostponed.sql similarity index 100% rename from db/changes/232202/00-procedurecanbePostponed.sql rename to db/.archive/232202/00-procedurecanbePostponed.sql diff --git a/db/changes/232401/.gitkeep b/db/.archive/232401/.gitkeep similarity index 100% rename from db/changes/232401/.gitkeep rename to db/.archive/232401/.gitkeep diff --git a/db/changes/232401/00-buyConfig_travelConfig.sql b/db/.archive/232401/00-buyConfig_travelConfig.sql similarity index 100% rename from db/changes/232401/00-buyConfig_travelConfig.sql rename to db/.archive/232401/00-buyConfig_travelConfig.sql diff --git a/db/changes/232401/00-printer.sql b/db/.archive/232401/00-printer.sql similarity index 100% rename from db/changes/232401/00-printer.sql rename to db/.archive/232401/00-printer.sql diff --git a/db/changes/232401/00-ticket_warehouse.sql b/db/.archive/232401/00-ticket_warehouse.sql similarity index 100% rename from db/changes/232401/00-ticket_warehouse.sql rename to db/.archive/232401/00-ticket_warehouse.sql diff --git a/db/changes/232401/00-userPassExpired.sql b/db/.archive/232401/00-userPassExpired.sql similarity index 100% rename from db/changes/232401/00-userPassExpired.sql rename to db/.archive/232401/00-userPassExpired.sql diff --git a/db/changes/232402/00-hotFix_travelConfig.sql b/db/.archive/232402/00-hotFix_travelConfig.sql similarity index 100% rename from db/changes/232402/00-hotFix_travelConfig.sql rename to db/.archive/232402/00-hotFix_travelConfig.sql diff --git a/db/changes/232601/00-aclAccount.sql b/db/.archive/232601/00-aclAccount.sql similarity index 100% rename from db/changes/232601/00-aclAccount.sql rename to db/.archive/232601/00-aclAccount.sql diff --git a/db/changes/232601/00-aclInvoiceTickets.sql b/db/.archive/232601/00-aclInvoiceTickets.sql similarity index 100% rename from db/changes/232601/00-aclInvoiceTickets.sql rename to db/.archive/232601/00-aclInvoiceTickets.sql diff --git a/db/changes/232601/00-aclMailAliasAccount.sql b/db/.archive/232601/00-aclMailAliasAccount.sql similarity index 100% rename from db/changes/232601/00-aclMailAliasAccount.sql rename to db/.archive/232601/00-aclMailAliasAccount.sql diff --git a/db/changes/232601/00-aclMailForward.sql b/db/.archive/232601/00-aclMailForward.sql similarity index 100% rename from db/changes/232601/00-aclMailForward.sql rename to db/.archive/232601/00-aclMailForward.sql diff --git a/db/changes/232601/00-aclRole.sql b/db/.archive/232601/00-aclRole.sql similarity index 100% rename from db/changes/232601/00-aclRole.sql rename to db/.archive/232601/00-aclRole.sql diff --git a/db/changes/232601/00-aclVnUser.sql b/db/.archive/232601/00-aclVnUser.sql similarity index 100% rename from db/changes/232601/00-aclVnUser.sql rename to db/.archive/232601/00-aclVnUser.sql diff --git a/db/changes/232601/00-aclVnUser_renewToken.sql b/db/.archive/232601/00-aclVnUser_renewToken.sql similarity index 100% rename from db/changes/232601/00-aclVnUser_renewToken.sql rename to db/.archive/232601/00-aclVnUser_renewToken.sql diff --git a/db/changes/232601/00-entry_updateComission.sql b/db/.archive/232601/00-entry_updateComission.sql similarity index 100% rename from db/changes/232601/00-entry_updateComission.sql rename to db/.archive/232601/00-entry_updateComission.sql diff --git a/db/changes/232601/00-packingSiteAdvanced.sql b/db/.archive/232601/00-packingSiteAdvanced.sql similarity index 100% rename from db/changes/232601/00-packingSiteAdvanced.sql rename to db/.archive/232601/00-packingSiteAdvanced.sql diff --git a/db/changes/232601/00-salix.sql b/db/.archive/232601/00-salix.sql similarity index 100% rename from db/changes/232601/00-salix.sql rename to db/.archive/232601/00-salix.sql diff --git a/db/changes/232601/00-useSpecificsAcls.sql b/db/.archive/232601/00-useSpecificsAcls.sql similarity index 100% rename from db/changes/232601/00-useSpecificsAcls.sql rename to db/.archive/232601/00-useSpecificsAcls.sql diff --git a/db/changes/232601/01-invoiceOutPdf.sql b/db/.archive/232601/01-invoiceOutPdf.sql similarity index 100% rename from db/changes/232601/01-invoiceOutPdf.sql rename to db/.archive/232601/01-invoiceOutPdf.sql diff --git a/db/changes/232602/01-aclAddAlias.sql b/db/.archive/232602/01-aclAddAlias.sql similarity index 100% rename from db/changes/232602/01-aclAddAlias.sql rename to db/.archive/232602/01-aclAddAlias.sql diff --git a/db/changes/232801/00-authCode.sql b/db/.archive/232801/00-authCode.sql similarity index 100% rename from db/changes/232801/00-authCode.sql rename to db/.archive/232801/00-authCode.sql diff --git a/db/changes/232801/00-client_create.sql b/db/.archive/232801/00-client_create.sql similarity index 100% rename from db/changes/232801/00-client_create.sql rename to db/.archive/232801/00-client_create.sql diff --git a/db/changes/232801/00-client_create2.sql b/db/.archive/232801/00-client_create2.sql similarity index 100% rename from db/changes/232801/00-client_create2.sql rename to db/.archive/232801/00-client_create2.sql diff --git a/db/changes/232801/00-department.sql b/db/.archive/232801/00-department.sql similarity index 100% rename from db/changes/232801/00-department.sql rename to db/.archive/232801/00-department.sql diff --git a/db/changes/232801/00-fix_editCredit.sql b/db/.archive/232801/00-fix_editCredit.sql similarity index 100% rename from db/changes/232801/00-fix_editCredit.sql rename to db/.archive/232801/00-fix_editCredit.sql diff --git a/db/changes/232801/00-user.sql b/db/.archive/232801/00-user.sql similarity index 100% rename from db/changes/232801/00-user.sql rename to db/.archive/232801/00-user.sql diff --git a/db/changes/232802/01-aclWorkerDisable.sql b/db/.archive/232802/01-aclWorkerDisable.sql similarity index 100% rename from db/changes/232802/01-aclWorkerDisable.sql rename to db/.archive/232802/01-aclWorkerDisable.sql diff --git a/db/changes/234601/.gitkeep b/db/changes/234601/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/package-lock.json b/package-lock.json index c3f88bc2c..5bf7a2cb1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "salix-back", - "version": "23.42.01", + "version": "23.46.01", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "salix-back", - "version": "23.42.01", + "version": "23.46.01", "license": "GPL-3.0", "dependencies": { "axios": "^1.2.2", diff --git a/package.json b/package.json index 3320705f5..b1539f9a0 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "salix-back", - "version": "23.42.01", + "version": "23.46.01", "author": "Verdnatura Levante SL", "description": "Salix backend", "license": "GPL-3.0", From e0b4ac733e32e44225931b38d2f0a16236dfc12c Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 26 Oct 2023 09:30:48 +0200 Subject: [PATCH 287/427] ref #5914 move changes --- db/changes/{234201 => 234601}/00-transferInvoice.sql | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename db/changes/{234201 => 234601}/00-transferInvoice.sql (100%) diff --git a/db/changes/234201/00-transferInvoice.sql b/db/changes/234601/00-transferInvoice.sql similarity index 100% rename from db/changes/234201/00-transferInvoice.sql rename to db/changes/234601/00-transferInvoice.sql From 55d80458ccf644085d471080de1bd4c7957a8e09 Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 26 Oct 2023 14:37:42 +0200 Subject: [PATCH 288/427] refs #6065 warmFix(workerTimeControl): set date --- modules/worker/front/time-control/index.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/modules/worker/front/time-control/index.js b/modules/worker/front/time-control/index.js index 9137d7839..a60c71589 100644 --- a/modules/worker/front/time-control/index.js +++ b/modules/worker/front/time-control/index.js @@ -111,9 +111,10 @@ class Controller extends Section { dayIndex.setDate(dayIndex.getDate() + 1); } - if (!this.weekTotalHours) this.fetchHours(); - if (this.worker) + if (this.worker) { + this.fetchHours(); this.getWeekData(); + } } set weekTotalHours(totalHours) { From 9708f66cefa8cc23fee424202a1659810041d51a Mon Sep 17 00:00:00 2001 From: pablone Date: Fri, 27 Oct 2023 12:36:28 +0200 Subject: [PATCH 289/427] merge(dev): refs #4131 merge dev move sql files --- .../00-ACLticketTrackingState.sql | 0 .../00-ticketSetStateRefactor.sql | 18 ++---------------- 2 files changed, 2 insertions(+), 16 deletions(-) rename db/changes/{233801 => 234601}/00-ACLticketTrackingState.sql (100%) rename db/changes/{233801 => 234601}/00-ticketSetStateRefactor.sql (73%) diff --git a/db/changes/233801/00-ACLticketTrackingState.sql b/db/changes/234601/00-ACLticketTrackingState.sql similarity index 100% rename from db/changes/233801/00-ACLticketTrackingState.sql rename to db/changes/234601/00-ACLticketTrackingState.sql diff --git a/db/changes/233801/00-ticketSetStateRefactor.sql b/db/changes/234601/00-ticketSetStateRefactor.sql similarity index 73% rename from db/changes/233801/00-ticketSetStateRefactor.sql rename to db/changes/234601/00-ticketSetStateRefactor.sql index 1ad453299..9078ffb0e 100644 --- a/db/changes/233801/00-ticketSetStateRefactor.sql +++ b/db/changes/234601/00-ticketSetStateRefactor.sql @@ -14,37 +14,23 @@ BEGIN DECLARE vTicketStateCode VARCHAR(255); DECLARE vCanChangeState BOOL; DECLARE vPackedAlertLevel INT; - DECLARE vOnPreparationAlertLevel INT; - DECLARE vNextAlertLevel INT; DECLARE vZoneFk INT; - SELECT s.alertLevel, s.`code`, s2.alertLevel, t.zoneFk - INTO vticketAlertLevel, vTicketStateCode, vNextAlertLevel , vZoneFk + SELECT s.alertLevel, s.`code`, t.zoneFk + INTO vticketAlertLevel, vTicketStateCode, vZoneFk FROM state s JOIN ticketTracking tt ON tt.stateFk = s.id - JOIN state s2 ON s2.code = vStateCode JOIN ticket t ON t.id = tt.ticketFk WHERE tt.ticketFk = vSelf ORDER BY tt.created DESC LIMIT 1; SELECT id INTO vPackedAlertLevel FROM alertLevel WHERE code = 'PACKED'; - SELECT id INTO vOnPreparationAlertLevel - FROM alertLevel - WHERE code = 'ON_PREPARATION'; IF vStateCode = 'OK' AND vZoneFk IS NULL THEN CALL util.throw('ASSIGN_ZONE_FIRST'); END IF; - IF vNextAlertLevel > vticketAlertLevel && - vticketAlertLevel < vOnPreparationAlertLevel - THEN - UPDATE sale - SET originalQuantity = quantity - WHERE ticketFk = vSelf; - END IF; - SET vCanChangeState = ( vStateCode <> 'ON_CHECKING' OR vticketAlertLevel < vPackedAlertLevel From 42bbdf9814b8b3593c15616dff1f69d8e2cc405b Mon Sep 17 00:00:00 2001 From: pablone Date: Fri, 27 Oct 2023 13:41:32 +0200 Subject: [PATCH 290/427] feat(ticket.state): refs #4131 convert changeState to State --- .../back/methods/ticket-tracking/setDelivered.js | 2 +- .../specs/state.spec.js} | 14 ++++++++------ .../methods/{ticket-tracking => ticket}/state.js | 0 modules/ticket/back/models/ticket-tracking.js | 1 - modules/ticket/back/models/ticket.js | 1 + 5 files changed, 10 insertions(+), 8 deletions(-) rename modules/ticket/back/methods/{ticket-tracking/specs/changeState.spec.js => ticket/specs/state.spec.js} (89%) rename modules/ticket/back/methods/{ticket-tracking => ticket}/state.js (100%) diff --git a/modules/ticket/back/methods/ticket-tracking/setDelivered.js b/modules/ticket/back/methods/ticket-tracking/setDelivered.js index ac267eb1a..d3cdb192f 100644 --- a/modules/ticket/back/methods/ticket-tracking/setDelivered.js +++ b/modules/ticket/back/methods/ticket-tracking/setDelivered.js @@ -47,7 +47,7 @@ module.exports = Self => { const promises = []; for (const id of ticketIds) { - const promise = models.TicketTracking.state(ctx, { + const promise = await models.Ticket.state(ctx, { stateFk: state.id, workerFk: worker.id, ticketFk: id diff --git a/modules/ticket/back/methods/ticket-tracking/specs/changeState.spec.js b/modules/ticket/back/methods/ticket/specs/state.spec.js similarity index 89% rename from modules/ticket/back/methods/ticket-tracking/specs/changeState.spec.js rename to modules/ticket/back/methods/ticket/specs/state.spec.js index b01d02389..9b5e80165 100644 --- a/modules/ticket/back/methods/ticket-tracking/specs/changeState.spec.js +++ b/modules/ticket/back/methods/ticket/specs/state.spec.js @@ -47,7 +47,7 @@ describe('ticket state()', () => { activeCtx.accessToken.userId = salesPersonId; const params = {ticketFk: 2, stateFk: 3}; - await models.TicketTracking.state(ctx, params, options); + await models.Ticket.state(ctx, params, options); await tx.rollback(); } catch (e) { @@ -69,7 +69,7 @@ describe('ticket state()', () => { activeCtx.accessToken.userId = employeeId; const params = {ticketFk: 11, stateFk: 13}; - await models.TicketTracking.state(ctx, params, options); + await models.Ticket.state(ctx, params, options); await tx.rollback(); } catch (e) { @@ -80,7 +80,8 @@ describe('ticket state()', () => { expect(error.code).toBe('ACCESS_DENIED'); }); - it('should be able to create a ticket tracking line for a not editable ticket if the user has the production role', async() => { + it('should be able to create a ticket tracking line for a not' + + ' editable ticket if the user has the production role', async() => { const tx = await models.TicketTracking.beginTransaction({}); try { @@ -91,7 +92,7 @@ describe('ticket state()', () => { activeCtx.accessToken.userId = productionId; const params = {ticketFk: ticket.id, stateFk: 3}; - const ticketTracking = await models.TicketTracking.state(ctx, params, options); + const ticketTracking = await models.Ticket.state(ctx, params, options); expect(ticketTracking.__data.ticketFk).toBe(params.ticketFk); expect(ticketTracking.__data.stateFk).toBe(params.stateFk); @@ -105,7 +106,8 @@ describe('ticket state()', () => { } }); - it('should update the ticket tracking line when the user is salesperson, uses the state assigned and a valid worker id', async() => { + it('should update the ticket tracking line when the user is salesperson,' + + ' uses the state assigned and a valid worker id', async() => { const tx = await models.TicketTracking.beginTransaction({}); try { @@ -115,7 +117,7 @@ describe('ticket state()', () => { const ctx = {req: {accessToken: {userId: 18}}}; const assignedState = await models.State.findOne({where: {code: 'PICKER_DESIGNED'}}, options); const params = {ticketFk: ticket.id, stateFk: assignedState.id, workerFk: 1}; - const res = await models.TicketTracking.state(ctx, params, options); + const res = await models.Ticket.state(ctx, params, options); expect(res.__data.ticketFk).toBe(params.ticketFk); expect(res.__data.stateFk).toBe(params.stateFk); diff --git a/modules/ticket/back/methods/ticket-tracking/state.js b/modules/ticket/back/methods/ticket/state.js similarity index 100% rename from modules/ticket/back/methods/ticket-tracking/state.js rename to modules/ticket/back/methods/ticket/state.js diff --git a/modules/ticket/back/models/ticket-tracking.js b/modules/ticket/back/models/ticket-tracking.js index 48e4c93d7..92e046d3e 100644 --- a/modules/ticket/back/models/ticket-tracking.js +++ b/modules/ticket/back/models/ticket-tracking.js @@ -1,5 +1,4 @@ module.exports = function(Self) { - require('../methods/ticket-tracking/state')(Self); require('../methods/ticket-tracking/setDelivered')(Self); Self.validatesPresenceOf('stateFk', {message: 'State cannot be blank'}); diff --git a/modules/ticket/back/models/ticket.js b/modules/ticket/back/models/ticket.js index ea068ef8a..a265c9cbb 100644 --- a/modules/ticket/back/models/ticket.js +++ b/modules/ticket/back/models/ticket.js @@ -1,4 +1,5 @@ module.exports = Self => { // Methods require('./ticket-methods')(Self); + require('../methods/ticket/state')(Self); }; From ae160890a8a3badfaf86f2af7ad428f451d88d6d Mon Sep 17 00:00:00 2001 From: alexm Date: Fri, 27 Oct 2023 15:06:20 +0200 Subject: [PATCH 291/427] refs #6335 feat(ticketAdvance): use componentUpdate --- .../00-ticket_canAdvance_leftJoin.sql | 30 +++++-- .../back/methods/ticket/componentUpdate.js | 76 ++++++++++------ .../ticket/specs/componentUpdate.spec.js | 2 +- modules/ticket/front/advance/index.html | 67 +++++++++----- modules/ticket/front/advance/index.js | 87 +++++++++++++++---- .../ticket/front/basic-data/step-two/index.js | 4 +- 6 files changed, 198 insertions(+), 68 deletions(-) rename db/changes/{234201 => 234601}/00-ticket_canAdvance_leftJoin.sql (85%) diff --git a/db/changes/234201/00-ticket_canAdvance_leftJoin.sql b/db/changes/234601/00-ticket_canAdvance_leftJoin.sql similarity index 85% rename from db/changes/234201/00-ticket_canAdvance_leftJoin.sql rename to db/changes/234601/00-ticket_canAdvance_leftJoin.sql index b26c3a102..31472afd8 100644 --- a/db/changes/234201/00-ticket_canAdvance_leftJoin.sql +++ b/db/changes/234601/00-ticket_canAdvance_leftJoin.sql @@ -68,7 +68,15 @@ BEGIN origin.futureZoneFk, origin.futureZoneName, origin.classColor futureClassColor, - dest.classColor + dest.classColor, + IFNULL(dest.clientFk, origin.clientFk) clientFk, + IFNULL(dest.nickname, origin.nickname) nickname, + IFNULL(dest.addressFk, origin.addressFk) addressFk, + IFNULL(dest.zoneFk, origin.futureZoneFk) zoneFk, + IFNULL(dest.warehouseFk, origin.warehouseFk) warehouseFk, + IFNULL(dest.companyFk, origin.companyFk) companyFk, + IFNULL(dest.agencyModeFk, origin.agencyModeFk) agencyModeFk, + dest.landed FROM ( SELECT s.ticketFk, @@ -76,7 +84,6 @@ BEGIN t.shipped, t.totalWithVat, st.name futureState, - t.addressFk, am.name futureAgency, count(s.id) futureLines, GROUP_CONCAT(DISTINCT ipt.code ORDER BY ipt.code) futureIpt, @@ -84,7 +91,13 @@ BEGIN SUM((s.quantity <= IFNULL(st.amount,0))) hasStock, z.id futureZoneFk, z.name futureZoneName, - st.classColor + st.classColor, + t.clientFk, + t.nickname, + t.addressFk, + t.warehouseFk, + t.companyFk, + t.agencyModeFk FROM ticket t JOIN client c ON c.id = t.clientFk JOIN sale s ON s.ticketFk = t.id @@ -103,7 +116,6 @@ BEGIN LEFT JOIN ( SELECT t.id ticketFk, - t.addressFk, st.name state, GROUP_CONCAT(DISTINCT ipt.code ORDER BY ipt.code) ipt, t.shipped, @@ -111,7 +123,15 @@ BEGIN am.name agency, CAST(SUM(litros) AS DECIMAL(10,0)) liters, CAST(COUNT(*) AS DECIMAL(10,0)) `lines`, - st.classColor + st.classColor, + t.clientFk, + t.nickname, + t.addressFk, + t.zoneFk, + t.warehouseFk, + t.companyFk, + t.landed, + t.agencyModeFk FROM ticket t JOIN sale s ON s.ticketFk = t.id JOIN saleVolume sv ON sv.saleFk = s.id diff --git a/modules/ticket/back/methods/ticket/componentUpdate.js b/modules/ticket/back/methods/ticket/componentUpdate.js index f7c36f108..483afdaee 100644 --- a/modules/ticket/back/methods/ticket/componentUpdate.js +++ b/modules/ticket/back/methods/ticket/componentUpdate.js @@ -75,8 +75,7 @@ module.exports = Self => { { arg: 'option', type: 'number', - description: 'Action id', - required: true + description: 'Action id' }, { arg: 'isWithoutNegatives', @@ -88,7 +87,18 @@ module.exports = Self => { arg: 'withWarningAccept', type: 'boolean', description: 'Has pressed in confirm message', - }], + }, + { + arg: 'newTicket', + type: 'number', + description: 'Ticket id you want to move the lines to, if applicable', + }, + { + arg: 'keepPrice', + type: 'boolean', + description: 'If prices should be maintained', + } + ], returns: { type: ['object'], root: true @@ -101,6 +111,7 @@ module.exports = Self => { Self.componentUpdate = async(ctx, options) => { const args = ctx.args; + const originalTicketId = args.id; const myOptions = {userId: ctx.req.accessToken.userId}; let tx; @@ -141,7 +152,13 @@ module.exports = Self => { const salesNewTicketLength = salesNewTicket.length; if (salesNewTicketLength && sales.length != salesNewTicketLength) { - const newTicket = await models.Ticket.transferSales(ctx, args.id, null, salesNewTicket, myOptions); + const newTicket = await models.Ticket.transferSales( + ctx, + args.id, + args.newTicket, + salesNewTicket, + myOptions + ); args.id = newTicket.id; } } @@ -186,24 +203,32 @@ module.exports = Self => { delete updatedTicket.ctx; delete updatedTicket.option; - // Force to unroute ticket - const hasToBeUnrouted = true; - const query = 'CALL vn.ticket_componentMakeUpdate(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'; - const res = await Self.rawSql(query, [ - args.id, - args.clientFk, - args.nickname, - args.agencyModeFk, - args.addressFk, - args.zoneFk, - args.warehouseFk, - args.companyFk, - args.shipped, - args.landed, - args.isDeleted, - hasToBeUnrouted, - args.option - ], myOptions); + const ticketChages = { + clientFk: args.clientFk, + nickname: args.nickname, + agencyModeFk: args.agencyModeFk, + addressFk: args.addressFk, + zoneFk: args.zoneFk, + warehouseFk: args.warehouseFk, + companyFk: args.companyFk, + shipped: args.shipped, + landed: args.landed, + isDeleted: args.isDeleted + }; + + let response; + if (args.keepPrice) { + ticketChages.routeFk = null; + response = await originalTicket.updateAttributes(ticketChages, myOptions); + } else { + const hasToBeUnrouted = true; + const query = 'CALL vn.ticket_componentMakeUpdate(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'; + response = await Self.rawSql( + query, + [args.id].concat(Object.values(ticketChages), [hasToBeUnrouted, args.option]), + myOptions + ); + } if (originalTicket.addressFk != updatedTicket.addressFk && args.id) { await models.TicketObservation.destroyAll({ @@ -256,10 +281,11 @@ module.exports = Self => { } } - res.id = args.id; - if (tx) await tx.commit(); + response.id = args.id; + console.log(originalTicketId, args.newTicket ? ` TRANSFER TO → ` : ` CREATE NEW TICKET → `, args.id); + if (tx) await tx.rollback(); - return res; + return response; } catch (e) { if (tx) await tx.rollback(); throw e; diff --git a/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js b/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js index ef6422be2..b51e1b47b 100644 --- a/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js +++ b/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); -describe('ticket componentUpdate()', () => { +fdescribe('ticket componentUpdate()', () => { const userID = 1101; const ticketID = 11; const today = Date.vnNew(); diff --git a/modules/ticket/front/advance/index.html b/modules/ticket/front/advance/index.html index af5b8f704..25664782e 100644 --- a/modules/ticket/front/advance/index.html +++ b/modules/ticket/front/advance/index.html @@ -21,10 +21,17 @@ expr-builder="$ctrl.exprBuilder(param, value)" > - + vn-tooltip="Advance tickets with negatives"> + + @@ -32,8 +39,14 @@ - Destination - Origin + + Destination + {{model.userParams.dateToAdvance| date: 'dd/MM/yyyy'}} + + + Origin + {{model.userParams.dateFuture | date: 'dd/MM/yyyy'}} + @@ -48,9 +61,6 @@ ID - - Date - IPT @@ -69,9 +79,6 @@ ID - - Date - IPT @@ -117,11 +124,6 @@ {{::ticket.id | dashIfEmpty}} - - - {{::ticket.shipped | date: 'dd/MM/yyyy'}} - - {{::ticket.ipt | dashIfEmpty}} - - - {{::ticket.futureShipped | date: 'dd/MM/yyyy'}} - - {{::ticket.futureIpt | dashIfEmpty}} + + + + + + + + + + + + + + + + + + diff --git a/modules/ticket/front/advance/index.js b/modules/ticket/front/advance/index.js index 389bcdf14..f98d0a6a9 100644 --- a/modules/ticket/front/advance/index.js +++ b/modules/ticket/front/advance/index.js @@ -75,20 +75,6 @@ export default class Controller extends Section { }); } - compareDate(date) { - let today = Date.vnNew(); - today.setHours(0, 0, 0, 0); - let timeTicket = new Date(date); - timeTicket.setHours(0, 0, 0, 0); - - let comparation = today - timeTicket; - - if (comparation == 0) - return 'warning'; - if (comparation < 0) - return 'success'; - } - get checked() { const tickets = this.$.model.data || []; const checkedLines = []; @@ -136,7 +122,8 @@ export default class Controller extends Section { moveTicketsAdvance() { let ticketsToMove = []; - this.checked.forEach(ticket => { + // falta ver que hacer con los nulls + for (ticket of this.checked) { ticketsToMove.push({ originId: ticket.futureId, destinationId: ticket.id, @@ -144,7 +131,8 @@ export default class Controller extends Section { destinationShipped: ticket.shipped, workerFk: ticket.workerFk }); - }); + } + const params = {tickets: ticketsToMove}; return this.$http.post('Tickets/merge', params) .then(() => { @@ -152,6 +140,73 @@ export default class Controller extends Section { this.vnApp.showSuccess(this.$t('Success')); }); } + async getLanded(params) { + const query = `Agencies/getLanded`; + return this.$http.get(query, {params}).then(res => { + if (res.data) + return res.data; + else { + return this.vnApp.showError( + this.$t(`No delivery zone available for this landing date`) + ); + } + }); + } + + async splitTickets() { + this.progress = []; + this.splitErrors = []; + this.$.splitTickets.hide(); + this.$.splitProgress.enable = true; + this.$.splitProgress.cancel = false; + this.$.splitProgress.show(); + for (const ticket of this.checked) { + if (this.$.splitProgress.cancel) break; + try { + if (!ticket.landed) { + const newLanded = await this.getLanded({ + shipped: this.$.model.userParams.dateToAdvance, + addressFk: ticket.addressFk, + agencyModeFk: ticket.agencyModeFk, + warehouseFk: ticket.warehouseFk + }); + ticket.landed = newLanded?.landed; + ticket.zoneFk = newLanded?.zoneFk; + } + const query = `tickets/${ticket.futureId}/componentUpdate`; + const params = { + clientFk: ticket.clientFk, + nickname: ticket.nickname, + agencyModeFk: ticket.agencyModeFk, + addressFk: ticket.addressFk, + zoneFk: ticket.zoneFk, + warehouseFk: ticket.warehouseFk, + companyFk: ticket.companyFk, + shipped: this.$.model.userParams.dateToAdvance, + landed: ticket.landed, + isDeleted: false, + isWithoutNegatives: true, + withWarningAccept: false, + newTicket: ticket.id ?? undefined, + keepPrice: true + }; + + this.$http.post(query, params) + .catch(e => { + this.splitErrors.push({id: ticket.futureId, reason: e.message}); + }) + .finally(() => { + this.progress.push(ticket.futureId); + if (this.progress.length == this.checked.length) { + this.$.splitProgress.enable = false; + this.$.model.refresh(); + this.vnApp.showSuccess(this.$t('Success')); + this.$checkAll = null; + } + }); + } catch (e) {} + } + } exprBuilder(param, value) { switch (param) { diff --git a/modules/ticket/front/basic-data/step-two/index.js b/modules/ticket/front/basic-data/step-two/index.js index 74e2df074..8ca9f053d 100644 --- a/modules/ticket/front/basic-data/step-two/index.js +++ b/modules/ticket/front/basic-data/step-two/index.js @@ -114,7 +114,9 @@ class Controller extends Component { isDeleted: this.ticket.isDeleted, option: parseInt(this.ticket.option), isWithoutNegatives: this.ticket.withoutNegatives, - withWarningAccept: this.ticket.withWarningAccept + withWarningAccept: this.ticket.withWarningAccept, + newTicket: null, + keepPrice: false }; this.$http.post(query, params) From 7ae12327f5e8b81cae9a8c48f82dc938b9df8ed0 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Fri, 27 Oct 2023 16:16:22 +0200 Subject: [PATCH 292/427] refs #5134 fix: model ExpeditionScan --- modules/ticket/back/models/expeditionScan.json | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/modules/ticket/back/models/expeditionScan.json b/modules/ticket/back/models/expeditionScan.json index 1db2c1238..7b95eff1e 100644 --- a/modules/ticket/back/models/expeditionScan.json +++ b/modules/ticket/back/models/expeditionScan.json @@ -8,17 +8,16 @@ "properties": { "id": { "type": "number", - "description": "Identifier" + "description": "Identifier", + "id": true }, "expeditionFk": { "type": "number", - "description": "Identifier", - "id": true + "description": "Identifier" }, "palletFk": { "type": "number", - "description": "Identifier", - "id": true + "description": "Identifier" }, "scanned": { "type": "date", From 65a1d052dc0662da7d2a1004f9c7ed6493a3ac81 Mon Sep 17 00:00:00 2001 From: pablone Date: Fri, 27 Oct 2023 18:03:40 +0200 Subject: [PATCH 293/427] feat(ticket.state): refs #4131 to state --- .../234601/00-ACLticketTrackingState.sql | 3 +- .../ticket/back/methods/ticket/saveSign.js | 68 ++++++++++--------- modules/ticket/back/models/ticket.js | 1 - modules/ticket/front/sale/index.js | 2 +- modules/ticket/front/sale/index.spec.js | 17 +++-- modules/ticket/front/summary/index.js | 4 +- modules/ticket/front/summary/index.spec.js | 2 +- modules/ticket/front/tracking/edit/index.html | 2 +- modules/ticket/front/tracking/edit/index.js | 2 +- .../ticket/front/tracking/edit/index.spec.js | 2 +- 10 files changed, 55 insertions(+), 48 deletions(-) diff --git a/db/changes/234601/00-ACLticketTrackingState.sql b/db/changes/234601/00-ACLticketTrackingState.sql index ddd838e7e..f84128b16 100644 --- a/db/changes/234601/00-ACLticketTrackingState.sql +++ b/db/changes/234601/00-ACLticketTrackingState.sql @@ -1,5 +1,6 @@ UPDATE `salix`.`ACL` - SET property = 'state' + SET property = 'state', + model = 'Ticket' WHERE property = 'changeState'; REVOKE INSERT, UPDATE, DELETE ON `vn`.`ticketTracking` FROM 'productionboss'@; diff --git a/modules/ticket/back/methods/ticket/saveSign.js b/modules/ticket/back/methods/ticket/saveSign.js index 9888328e7..9667847d2 100644 --- a/modules/ticket/back/methods/ticket/saveSign.js +++ b/modules/ticket/back/methods/ticket/saveSign.js @@ -44,6 +44,40 @@ module.exports = Self => { myOptions.transaction = tx; } + try { + for (const ticketId of tickets) { + const ticketState = await models.TicketState.findOne( + {where: {ticketFk: ticketId}, + fields: ['alertLevel'] + }, myOptions); + + const packedAlertLevel = await models.AlertLevel.findOne({where: {code: 'PACKED'}, + fields: ['id'] + }, myOptions); + + if (!ticketState) + throw new UserError('Ticket does not exist'); + if (ticketState.alertLevel < packedAlertLevel.id) + throw new UserError('This ticket cannot be signed because it has not been boxed'); + if (await gestDocExists(ticketId)) + throw new UserError('Ticket is already signed'); + + if (location) setLocation(ticketId); + if (!gestDocCreated) await createGestDoc(ticketId); + await models.TicketDms.create({ticketFk: ticketId, dmsFk: dms[0].id}, myOptions); + const ticket = await models.Ticket.findById(ticketId, null, myOptions); + await ticket.updateAttribute('isSigned', true, myOptions); + const params = {ticketFk: ticketId, code: 'DELIVERED'}; + await models.Ticket.state(ctx, params, options); + } + + if (tx) await tx.commit(); + return; + } catch (e) { + if (tx) await tx.rollback(); + throw e; + } + async function setLocation(ticketId) { await models.Delivery.create({ ticketFk: ticketId, @@ -103,41 +137,9 @@ module.exports = Self => { description: `Firma del cliente - Ruta ${ticket.route().id}`, hasFile: false }; + dms = await models.Dms.uploadFile(ctxUploadFile, myOptions); gestDocCreated = true; } - - try { - for (const ticketId of tickets) { - const ticketState = await models.TicketState.findOne( - {where: {ticketFk: ticketId}, - fields: ['alertLevel'] - }, myOptions); - - const packedAlertLevel = await models.AlertLevel.findOne({where: {code: 'PACKED'}, - fields: ['id'] - }, myOptions); - - if (!ticketState) - throw new UserError('Ticket does not exist'); - if (ticketState.alertLevel < packedAlertLevel.id) - throw new UserError('This ticket cannot be signed because it has not been boxed'); - if (await gestDocExists(ticketId)) - throw new UserError('Ticket is already signed'); - - if (location) setLocation(ticketId); - if (!gestDocCreated) await createGestDoc(ticketId); - await models.TicketDms.create({ticketFk: ticketId, dmsFk: dms[0].id}, myOptions); - const ticket = await models.Ticket.findById(ticketId, null, myOptions); - await ticket.updateAttribute('isSigned', true, myOptions); - await Self.rawSql(`CALL vn.ticket_setState(?, ?)`, [ticketId, 'DELIVERED'], myOptions); - } - - if (tx) await tx.commit(); - return; - } catch (e) { - if (tx) await tx.rollback(); - throw e; - } }; }; diff --git a/modules/ticket/back/models/ticket.js b/modules/ticket/back/models/ticket.js index a265c9cbb..1930765fb 100644 --- a/modules/ticket/back/models/ticket.js +++ b/modules/ticket/back/models/ticket.js @@ -1,5 +1,4 @@ module.exports = Self => { - // Methods require('./ticket-methods')(Self); require('../methods/ticket/state')(Self); }; diff --git a/modules/ticket/front/sale/index.js b/modules/ticket/front/sale/index.js index 1dd700b53..4f6a9e757 100644 --- a/modules/ticket/front/sale/index.js +++ b/modules/ticket/front/sale/index.js @@ -173,7 +173,7 @@ class Controller extends Section { state(value) { const params = {ticketFk: this.$params.id, code: value}; - return this.$http.post('TicketTrackings/state', params).then(() => { + return this.$http.post('Tickets/state', params).then(() => { this.vnApp.showSuccess(this.$t('Data saved!')); this.card.reload(); }).finally(() => this.resetChanges()); diff --git a/modules/ticket/front/sale/index.spec.js b/modules/ticket/front/sale/index.spec.js index 3ed18c0f1..70781eb58 100644 --- a/modules/ticket/front/sale/index.spec.js +++ b/modules/ticket/front/sale/index.spec.js @@ -229,13 +229,14 @@ describe('Ticket', () => { }); describe('state()', () => { - it('should make an HTTP post query, then call the showSuccess(), reload() and resetChanges() methods', () => { + it('should make an HTTP post query, then call the showSuccess(),' + + ' reload() and resetChanges() methods', () => { jest.spyOn(controller.card, 'reload').mockReturnThis(); jest.spyOn(controller.vnApp, 'showSuccess').mockReturnThis(); jest.spyOn(controller, 'resetChanges').mockReturnThis(); const expectedParams = {ticketFk: 1, code: 'OK'}; - $httpBackend.expect('POST', `TicketTrackings/state`, expectedParams).respond(200); + $httpBackend.expect('POST', `Tickets/state`, expectedParams).respond(200); controller.state('OK'); $httpBackend.flush(); @@ -246,7 +247,8 @@ describe('Ticket', () => { }); describe('removeSales()', () => { - it('should make an HTTP post query, then call the showSuccess(), removeSelectedSales() and resetChanges() methods', () => { + it('should make an HTTP post query, then call the showSuccess(),' + + ' removeSelectedSales() and resetChanges() methods', () => { jest.spyOn(controller.vnApp, 'showSuccess').mockReturnThis(); jest.spyOn(controller, 'removeSelectedSales').mockReturnThis(); jest.spyOn(controller, 'resetChanges').mockReturnThis(); @@ -352,7 +354,8 @@ describe('Ticket', () => { }); describe('updatePrice()', () => { - it('should make an HTTP POST query, update the sale price and then call to the resetChanges() method', () => { + it('should make an HTTP POST query, update the sale price ' + + 'and then call to the resetChanges() method', () => { jest.spyOn(controller.vnApp, 'showSuccess').mockReturnThis(); jest.spyOn(controller, 'resetChanges').mockReturnThis(); @@ -418,7 +421,8 @@ describe('Ticket', () => { expect(controller.$.editDiscount.hide).toHaveBeenCalledWith(); }); - it('should not call to the updateDiscount() method and then to the editDiscountDialog hide() method', () => { + it('should not call to the updateDiscount() method and then' + + ' to the editDiscountDialog hide() method', () => { jest.spyOn(controller, 'updateDiscount').mockReturnThis(); const firstSelectedSale = controller.sales[0]; @@ -444,7 +448,8 @@ describe('Ticket', () => { }); describe('updateDiscount()', () => { - it('should make an HTTP POST query, update the sales discount and then call to the resetChanges() method', () => { + it('should make an HTTP POST query, update the sales discount ' + + 'and then call to the resetChanges() method', () => { jest.spyOn(controller, 'resetChanges').mockReturnThis(); jest.spyOn(controller.vnApp, 'showSuccess').mockReturnThis(); diff --git a/modules/ticket/front/summary/index.js b/modules/ticket/front/summary/index.js index f4f36c3ed..68718aaf2 100644 --- a/modules/ticket/front/summary/index.js +++ b/modules/ticket/front/summary/index.js @@ -64,8 +64,8 @@ class Controller extends Summary { ticketFk: 'id' in this.ticket ? this.ticket.id : this.$params.id, code: value }; - - this.$http.post(`TicketTrackings/state`, params) + console.log('entra'); + this.$http.post(`Tickets/state`, params) .then(() => { if ('id' in this.$params) this.reload(); }) diff --git a/modules/ticket/front/summary/index.spec.js b/modules/ticket/front/summary/index.spec.js index b8c6f0513..6837bfd54 100644 --- a/modules/ticket/front/summary/index.spec.js +++ b/modules/ticket/front/summary/index.spec.js @@ -50,7 +50,7 @@ describe('Ticket', () => { let res = {id: 1, nickname: 'myNickname'}; $httpBackend.when('GET', `Tickets/1/summary`).respond(200, res); - $httpBackend.expectPOST(`TicketTrackings/state`).respond(200, 'ok'); + $httpBackend.expectPOST(`Tickets/state`).respond(200, 'ok'); controller.state(value); $httpBackend.flush(); diff --git a/modules/ticket/front/tracking/edit/index.html b/modules/ticket/front/tracking/edit/index.html index 90f045813..47f367007 100644 --- a/modules/ticket/front/tracking/edit/index.html +++ b/modules/ticket/front/tracking/edit/index.html @@ -1,4 +1,4 @@ - + { + this.$http.post(`Tickets/state`, this.params).then(() => { this.$.watcher.updateOriginalData(); this.card.reload(); this.vnApp.showSuccess(this.$t('Data saved!')); diff --git a/modules/ticket/front/tracking/edit/index.spec.js b/modules/ticket/front/tracking/edit/index.spec.js index e97dc1337..9d9aa7983 100644 --- a/modules/ticket/front/tracking/edit/index.spec.js +++ b/modules/ticket/front/tracking/edit/index.spec.js @@ -61,7 +61,7 @@ describe('Ticket', () => { jest.spyOn(controller.vnApp, 'showSuccess'); jest.spyOn(controller.$state, 'go'); - $httpBackend.expectPOST(`TicketTrackings/state`, controller.params).respond({}); + $httpBackend.expectPOST(`Tickets/state`, controller.params).respond({}); controller.onSubmit(); $httpBackend.flush(); From 14753212bb09984c3bf465f6ab4960017c60946e Mon Sep 17 00:00:00 2001 From: pablone Date: Fri, 27 Oct 2023 18:07:17 +0200 Subject: [PATCH 294/427] fix(saveSign): refs #4131 remove call state on saveSign --- .../ticket/back/methods/ticket/saveSign.js | 68 +++++++++---------- 1 file changed, 33 insertions(+), 35 deletions(-) diff --git a/modules/ticket/back/methods/ticket/saveSign.js b/modules/ticket/back/methods/ticket/saveSign.js index 9667847d2..9888328e7 100644 --- a/modules/ticket/back/methods/ticket/saveSign.js +++ b/modules/ticket/back/methods/ticket/saveSign.js @@ -44,40 +44,6 @@ module.exports = Self => { myOptions.transaction = tx; } - try { - for (const ticketId of tickets) { - const ticketState = await models.TicketState.findOne( - {where: {ticketFk: ticketId}, - fields: ['alertLevel'] - }, myOptions); - - const packedAlertLevel = await models.AlertLevel.findOne({where: {code: 'PACKED'}, - fields: ['id'] - }, myOptions); - - if (!ticketState) - throw new UserError('Ticket does not exist'); - if (ticketState.alertLevel < packedAlertLevel.id) - throw new UserError('This ticket cannot be signed because it has not been boxed'); - if (await gestDocExists(ticketId)) - throw new UserError('Ticket is already signed'); - - if (location) setLocation(ticketId); - if (!gestDocCreated) await createGestDoc(ticketId); - await models.TicketDms.create({ticketFk: ticketId, dmsFk: dms[0].id}, myOptions); - const ticket = await models.Ticket.findById(ticketId, null, myOptions); - await ticket.updateAttribute('isSigned', true, myOptions); - const params = {ticketFk: ticketId, code: 'DELIVERED'}; - await models.Ticket.state(ctx, params, options); - } - - if (tx) await tx.commit(); - return; - } catch (e) { - if (tx) await tx.rollback(); - throw e; - } - async function setLocation(ticketId) { await models.Delivery.create({ ticketFk: ticketId, @@ -137,9 +103,41 @@ module.exports = Self => { description: `Firma del cliente - Ruta ${ticket.route().id}`, hasFile: false }; - dms = await models.Dms.uploadFile(ctxUploadFile, myOptions); gestDocCreated = true; } + + try { + for (const ticketId of tickets) { + const ticketState = await models.TicketState.findOne( + {where: {ticketFk: ticketId}, + fields: ['alertLevel'] + }, myOptions); + + const packedAlertLevel = await models.AlertLevel.findOne({where: {code: 'PACKED'}, + fields: ['id'] + }, myOptions); + + if (!ticketState) + throw new UserError('Ticket does not exist'); + if (ticketState.alertLevel < packedAlertLevel.id) + throw new UserError('This ticket cannot be signed because it has not been boxed'); + if (await gestDocExists(ticketId)) + throw new UserError('Ticket is already signed'); + + if (location) setLocation(ticketId); + if (!gestDocCreated) await createGestDoc(ticketId); + await models.TicketDms.create({ticketFk: ticketId, dmsFk: dms[0].id}, myOptions); + const ticket = await models.Ticket.findById(ticketId, null, myOptions); + await ticket.updateAttribute('isSigned', true, myOptions); + await Self.rawSql(`CALL vn.ticket_setState(?, ?)`, [ticketId, 'DELIVERED'], myOptions); + } + + if (tx) await tx.commit(); + return; + } catch (e) { + if (tx) await tx.rollback(); + throw e; + } }; }; From f250c084f797195258debd7e7e90f27e72971510 Mon Sep 17 00:00:00 2001 From: jorgep Date: Mon, 30 Oct 2023 09:11:52 +0100 Subject: [PATCH 295/427] ref #5216 refactor expeditionState BeforeInsert --- .../234601/00-expeditionStateBeforeInsert.sql | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 db/changes/234601/00-expeditionStateBeforeInsert.sql diff --git a/db/changes/234601/00-expeditionStateBeforeInsert.sql b/db/changes/234601/00-expeditionStateBeforeInsert.sql new file mode 100644 index 000000000..565b3ded3 --- /dev/null +++ b/db/changes/234601/00-expeditionStateBeforeInsert.sql @@ -0,0 +1,13 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`expeditionState_BeforeInsert` + BEFORE INSERT ON `expeditionState` + FOR EACH ROW +BEGIN + + SET NEW.userFk = IFNULL(NEW.userFk, account.myUser_getId()); + +END$$ +DELIMITER ; + + + From a80715583c0a7b7fae1c17f501cb178251d68253 Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 30 Oct 2023 14:16:25 +0100 Subject: [PATCH 296/427] refs #6335 feat(ticketAdvance): change the date if you can --- CHANGELOG.md | 5 + loopback/locale/es.json | 14 ++- .../back/methods/ticket/componentUpdate.js | 32 ++--- modules/ticket/front/advance/index.html | 24 ++-- modules/ticket/front/advance/index.js | 116 +++++++++++------- modules/ticket/front/advance/locale/es.yml | 6 +- 6 files changed, 123 insertions(+), 74 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cd6ed4522..e236dc239 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,8 +8,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [2346.01] - 2023-11-16 ### Added +- (Ticket -> Adelantar) Permite mover lineas sin generar negativos +- (Ticket -> Adelantar) Permite modificar la fecha de los tickets + ### Changed ### Fixed +- (Ticket -> RocketChat) Arreglada detección de cambios + ## [2342.01] - 2023-11-02 diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 3cc9a9627..a796c44a7 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -224,7 +224,9 @@ "date in the future": "Fecha en el futuro", "reference duplicated": "Referencia duplicada", "This ticket is already a refund": "Este ticket ya es un abono", - "isWithoutNegatives": "isWithoutNegatives", + "isWithoutNegatives": "Sin negativos", + "newTicket": "Nuevo ticket", + "keepPrice": "Mantener precios", "routeFk": "routeFk", "Can't change the password of another worker": "No se puede cambiar la contraseña de otro trabajador", "No hay un contrato en vigor": "No hay un contrato en vigor", @@ -321,9 +323,13 @@ "Select a different client": "Seleccione un cliente distinto", "Fill all the fields": "Rellene todos los campos", "The response is not a PDF": "La respuesta no es un PDF", - "Ticket without Route": "Ticket sin ruta", "Booking completed": "Reserva completada", "The ticket is in preparation": "El ticket [{{ticketId}}]({{{ticketUrl}}}) del comercial {{salesPersonId}} está en preparación", "The amount cannot be less than the minimum": "La cantidad no puede ser menor que la cantidad mímina", - "quantityLessThanMin": "La cantidad no puede ser menor que la cantidad mímina" -} + "quantityLessThanMin": "La cantidad no puede ser menor que la cantidad mímina", + "__cachedRelations": "__cachedRelations", + "__data": "__data", + "__strict": "__strict", + "__persisted": "__persisted", + "client": "client" +} \ No newline at end of file diff --git a/modules/ticket/back/methods/ticket/componentUpdate.js b/modules/ticket/back/methods/ticket/componentUpdate.js index 483afdaee..536166d7d 100644 --- a/modules/ticket/back/methods/ticket/componentUpdate.js +++ b/modules/ticket/back/methods/ticket/componentUpdate.js @@ -163,7 +163,7 @@ module.exports = Self => { } } - const originalTicket = await models.Ticket.findOne({ + const ticketToChange = await models.Ticket.findOne({ where: {id: args.id}, fields: [ 'id', @@ -196,13 +196,7 @@ module.exports = Self => { }, ] }, myOptions); - - args.routeFk = null; - if (args.isWithoutNegatives === false) delete args.isWithoutNegatives; - const updatedTicket = Object.assign({}, args); - delete updatedTicket.ctx; - delete updatedTicket.option; - + const originalTicket = JSON.parse(JSON.stringify(ticketToChange)); const ticketChages = { clientFk: args.clientFk, nickname: args.nickname, @@ -219,18 +213,21 @@ module.exports = Self => { let response; if (args.keepPrice) { ticketChages.routeFk = null; - response = await originalTicket.updateAttributes(ticketChages, myOptions); + response = await ticketToChange.updateAttributes(ticketChages, myOptions); } else { const hasToBeUnrouted = true; - const query = 'CALL vn.ticket_componentMakeUpdate(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'; response = await Self.rawSql( - query, + 'CALL vn.ticket_componentMakeUpdate(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', [args.id].concat(Object.values(ticketChages), [hasToBeUnrouted, args.option]), myOptions ); } + if (args.isWithoutNegatives === false) delete args.isWithoutNegatives; + const updatedTicket = Object.assign({}, args, JSON.parse(JSON.stringify(ticketToChange))); + delete updatedTicket.ctx; + delete updatedTicket.option; - if (originalTicket.addressFk != updatedTicket.addressFk && args.id) { + if (ticketToChange.addressFk != updatedTicket.addressFk && args.id) { await models.TicketObservation.destroyAll({ ticketFk: args.id }, myOptions); @@ -252,15 +249,20 @@ module.exports = Self => { await models.TicketObservation.create(clonedObservations, myOptions); } } - const changes = loggable.getChanges(originalTicket, updatedTicket); + const hasChanges = Object.keys(changes.old).length > 0 || Object.keys(changes.new).length > 0; if (hasChanges) { + delete changes.old.client; + delete changes.old.address; + delete changes.new.client; + delete changes.new.address; + const oldProperties = await loggable.translateValues(Self, changes.old); const newProperties = await loggable.translateValues(Self, changes.new); - const salesPersonId = originalTicket.client().salesPersonFk; + const salesPersonId = ticketToChange.client().salesPersonFk; if (salesPersonId) { const url = await Self.app.models.Url.getUrl(); @@ -283,7 +285,7 @@ module.exports = Self => { response.id = args.id; console.log(originalTicketId, args.newTicket ? ` TRANSFER TO → ` : ` CREATE NEW TICKET → `, args.id); - if (tx) await tx.rollback(); + if (tx) await tx.commit(); return response; } catch (e) { diff --git a/modules/ticket/front/advance/index.html b/modules/ticket/front/advance/index.html index 25664782e..395fe7078 100644 --- a/modules/ticket/front/advance/index.html +++ b/modules/ticket/front/advance/index.html @@ -29,7 +29,7 @@ @@ -121,7 +121,7 @@ - {{::ticket.id | dashIfEmpty}} + {{::ticket.id}} {{::ticket.ipt | dashIfEmpty}} @@ -137,7 +137,7 @@ - {{::(ticket.totalWithVat ? ticket.totalWithVat : 0) | currency: 'EUR': 2}} + {{::ticket.totalWithVat | currency: 'EUR': 2}} @@ -193,21 +193,23 @@ + message="Progress"> - - + label="Total progress" + value="[{{$ctrl.progress.length}}/{{::$ctrl.checked.length}}]"> + Error list + + + + diff --git a/modules/ticket/front/advance/index.js b/modules/ticket/front/advance/index.js index f98d0a6a9..5e41f0f23 100644 --- a/modules/ticket/front/advance/index.js +++ b/modules/ticket/front/advance/index.js @@ -120,10 +120,16 @@ export default class Controller extends Section { '\n' + this.$t(`Destination agency`, {agency: agency}); } - moveTicketsAdvance() { + async moveTicketsAdvance() { let ticketsToMove = []; - // falta ver que hacer con los nulls - for (ticket of this.checked) { + for (const ticket of this.checked) { + if (!ticket.id) { + try { + const {query, params} = await this.requestComponentUpdate(ticket, false); + this.$http.post(query, params); + } catch (e) {} + continue; + } ticketsToMove.push({ originId: ticket.futureId, destinationId: ticket.id, @@ -136,10 +142,12 @@ export default class Controller extends Section { const params = {tickets: ticketsToMove}; return this.$http.post('Tickets/merge', params) .then(() => { - this.$.model.refresh(); - this.vnApp.showSuccess(this.$t('Success')); + this.refresh(); + if (ticketsToMove.length) + this.vnApp.showSuccess(this.$t('Success', {tickets: ticketsToMove.length})); }); } + async getLanded(params) { const query = `Agencies/getLanded`; return this.$http.get(query, {params}).then(res => { @@ -160,54 +168,76 @@ export default class Controller extends Section { this.$.splitProgress.enable = true; this.$.splitProgress.cancel = false; this.$.splitProgress.show(); + for (const ticket of this.checked) { if (this.$.splitProgress.cancel) break; try { - if (!ticket.landed) { - const newLanded = await this.getLanded({ - shipped: this.$.model.userParams.dateToAdvance, - addressFk: ticket.addressFk, - agencyModeFk: ticket.agencyModeFk, - warehouseFk: ticket.warehouseFk - }); - ticket.landed = newLanded?.landed; - ticket.zoneFk = newLanded?.zoneFk; - } - const query = `tickets/${ticket.futureId}/componentUpdate`; - const params = { - clientFk: ticket.clientFk, - nickname: ticket.nickname, - agencyModeFk: ticket.agencyModeFk, - addressFk: ticket.addressFk, - zoneFk: ticket.zoneFk, - warehouseFk: ticket.warehouseFk, - companyFk: ticket.companyFk, - shipped: this.$.model.userParams.dateToAdvance, - landed: ticket.landed, - isDeleted: false, - isWithoutNegatives: true, - withWarningAccept: false, - newTicket: ticket.id ?? undefined, - keepPrice: true - }; - + const {query, params} = await this.requestComponentUpdate(ticket, true); this.$http.post(query, params) .catch(e => { this.splitErrors.push({id: ticket.futureId, reason: e.message}); }) - .finally(() => { - this.progress.push(ticket.futureId); - if (this.progress.length == this.checked.length) { - this.$.splitProgress.enable = false; - this.$.model.refresh(); - this.vnApp.showSuccess(this.$t('Success')); - this.$checkAll = null; - } - }); - } catch (e) {} + .finally(() => this.progressAdd(ticket.futureId)); + } catch (e) { + this.splitErrors.push({id: ticket.futureId, reason: e.message}); + this.progressAdd(ticket.futureId); + } } } + progressAdd(ticketId) { + this.progress.push(ticketId); + if (this.progress.length == this.checked.length) { + this.$.splitProgress.enable = false; + this.refresh(); + if ((this.progress.length - this.splitErrors.length) > 0) { + this.vnApp.showSuccess(this.$t('Success', { + tickets: this.progress.length - this.splitErrors.length + })); + } + } + } + + async requestComponentUpdate(ticket, isWithoutNegatives) { + const query = `tickets/${ticket.futureId}/componentUpdate`; + if (!ticket.landed) { + console.log(ticket); + const newLanded = await this.getLanded({ + shipped: this.$.model.userParams.dateToAdvance, + addressFk: ticket.addressFk, + agencyModeFk: ticket.agencyModeFk, + warehouseFk: ticket.warehouseFk + }); + if (!newLanded) + throw new Error(this.$t(`No delivery zone available for this landing date`)); + + ticket.landed = newLanded.landed; + ticket.zoneFk = newLanded.zoneFk; + } + const params = { + clientFk: ticket.clientFk, + nickname: ticket.nickname, + agencyModeFk: ticket.agencyModeFk, + addressFk: ticket.addressFk, + zoneFk: ticket.zoneFk, + warehouseFk: ticket.warehouseFk, + companyFk: ticket.companyFk, + shipped: this.$.model.userParams.dateToAdvance, + landed: ticket.landed, + isDeleted: false, + isWithoutNegatives, + newTicket: ticket.id ?? undefined, + keepPrice: true + }; + console.log(params); + return {query, params}; + } + + refresh() { + this.$.model.refresh(); + this.$checkAll = null; + } + exprBuilder(param, value) { switch (param) { case 'id': diff --git a/modules/ticket/front/advance/locale/es.yml b/modules/ticket/front/advance/locale/es.yml index 3111d9afd..520e82009 100644 --- a/modules/ticket/front/advance/locale/es.yml +++ b/modules/ticket/front/advance/locale/es.yml @@ -1,7 +1,7 @@ Advance tickets: Adelantar tickets Search advance tickets by date: Busca tickets para adelantar por fecha Advance confirmation: ¿Desea adelantar {{checked}} tickets? -Success: Tickets movidos correctamente +Success: "{{tickets}} Tickets movidos correctamente" Lines: Líneas Liters: Litros Item Packing Type: Encajado @@ -9,3 +9,7 @@ Origin agency: "Agencia origen: {{agency}}" Destination agency: "Agencia destino: {{agency}}" Less than 50€: Menor a 50€ Not Movable: No movibles +Error list: Lista de errores +Progress: Progreso +Total progress: Progreso total +Advance tickets (without negatives): Adelantar tickets (sin negativos) From e504ad313c06747bd01a9365c6437ccaec59a3cd Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 30 Oct 2023 14:56:33 +0100 Subject: [PATCH 297/427] remove(console.log): refs #4131 quitar console log --- modules/ticket/front/summary/index.js | 1 - 1 file changed, 1 deletion(-) diff --git a/modules/ticket/front/summary/index.js b/modules/ticket/front/summary/index.js index 68718aaf2..9d161f63e 100644 --- a/modules/ticket/front/summary/index.js +++ b/modules/ticket/front/summary/index.js @@ -64,7 +64,6 @@ class Controller extends Summary { ticketFk: 'id' in this.ticket ? this.ticket.id : this.$params.id, code: value }; - console.log('entra'); this.$http.post(`Tickets/state`, params) .then(() => { if ('id' in this.$params) this.reload(); From 37dce9944790dc1b2c6c342629a50e8ad52f2546 Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 30 Oct 2023 15:00:05 +0100 Subject: [PATCH 298/427] refs #6335 test(ticketAdvance): add test to keep price --- loopback/locale/es.json | 9 +- loopback/server/boot/date.js | 4 +- .../back/methods/ticket/componentUpdate.js | 4 +- .../ticket/specs/componentUpdate.spec.js | 110 +++++++++++++++++- 4 files changed, 115 insertions(+), 12 deletions(-) diff --git a/loopback/locale/es.json b/loopback/locale/es.json index a796c44a7..7e2000344 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -326,10 +326,5 @@ "Booking completed": "Reserva completada", "The ticket is in preparation": "El ticket [{{ticketId}}]({{{ticketUrl}}}) del comercial {{salesPersonId}} está en preparación", "The amount cannot be less than the minimum": "La cantidad no puede ser menor que la cantidad mímina", - "quantityLessThanMin": "La cantidad no puede ser menor que la cantidad mímina", - "__cachedRelations": "__cachedRelations", - "__data": "__data", - "__strict": "__strict", - "__persisted": "__persisted", - "client": "client" -} \ No newline at end of file + "quantityLessThanMin": "La cantidad no puede ser menor que la cantidad mímina" +} diff --git a/loopback/server/boot/date.js b/loopback/server/boot/date.js index 88505cf62..810745562 100644 --- a/loopback/server/boot/date.js +++ b/loopback/server/boot/date.js @@ -1,8 +1,8 @@ module.exports = () => { Date.vnUTC = () => { const env = process.env.NODE_ENV; - // if (!env || env === 'development') - // return new Date(Date.UTC(2001, 0, 1, 11)); + if (!env || env === 'development') + return new Date(Date.UTC(2001, 0, 1, 11)); return new Date(); }; diff --git a/modules/ticket/back/methods/ticket/componentUpdate.js b/modules/ticket/back/methods/ticket/componentUpdate.js index 536166d7d..1b02fd201 100644 --- a/modules/ticket/back/methods/ticket/componentUpdate.js +++ b/modules/ticket/back/methods/ticket/componentUpdate.js @@ -223,7 +223,7 @@ module.exports = Self => { ); } if (args.isWithoutNegatives === false) delete args.isWithoutNegatives; - const updatedTicket = Object.assign({}, args, JSON.parse(JSON.stringify(ticketToChange))); + const updatedTicket = Object.assign({}, args); delete updatedTicket.ctx; delete updatedTicket.option; @@ -249,8 +249,8 @@ module.exports = Self => { await models.TicketObservation.create(clonedObservations, myOptions); } } - const changes = loggable.getChanges(originalTicket, updatedTicket); + const changes = loggable.getChanges(originalTicket, updatedTicket); const hasChanges = Object.keys(changes.old).length > 0 || Object.keys(changes.new).length > 0; if (hasChanges) { diff --git a/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js b/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js index b51e1b47b..e124999c9 100644 --- a/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js +++ b/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); -fdescribe('ticket componentUpdate()', () => { +describe('ticket componentUpdate()', () => { const userID = 1101; const ticketID = 11; const today = Date.vnNew(); @@ -209,4 +209,112 @@ fdescribe('ticket componentUpdate()', () => { throw e; } }); + + describe('ticket componentUpdate()', () => { + it('should change shipped and keep price', async() => { + const tx = await models.Ticket.beginTransaction({}); + + try { + const options = {transaction: tx}; + + const saleId = 27; + const originDate = today; + const newDate = tomorrow; + const ticketID = 14; + newDate.setHours(0, 0, 0, 0, 0); + originDate.setHours(0, 0, 0, 0, 0); + + const args = { + id: ticketID, + clientFk: 1104, + agencyModeFk: 2, + addressFk: 4, + zoneFk: 9, + warehouseFk: 1, + companyFk: 442, + shipped: newDate, + landed: tomorrow, + isDeleted: false, + option: 1, + isWithoutNegatives: false, + keepPrice: true + }; + + const ctx = { + args: args, + req: { + accessToken: {userId: 9}, + headers: {origin: 'http://localhost'}, + __: value => { + return value; + } + } + }; + + const beforeSale = await models.Sale.findById(saleId, null, options); + await models.Ticket.componentUpdate(ctx, options); + const afterSale = await models.Sale.findById(saleId, null, options); + + expect(beforeSale.price).toEqual(afterSale.price); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('should change shipped and not keep price', async() => { + const tx = await models.Ticket.beginTransaction({}); + + try { + const options = {transaction: tx}; + + const saleId = 27; + const originDate = today; + const newDate = tomorrow; + const ticketID = 14; + newDate.setHours(0, 0, 0, 0, 0); + originDate.setHours(0, 0, 0, 0, 0); + + const args = { + id: ticketID, + clientFk: 1104, + agencyModeFk: 2, + addressFk: 4, + zoneFk: 9, + warehouseFk: 1, + companyFk: 442, + shipped: newDate, + landed: tomorrow, + isDeleted: false, + option: 1, + isWithoutNegatives: false, + keepPrice: false + }; + + const ctx = { + args: args, + req: { + accessToken: {userId: 9}, + headers: {origin: 'http://localhost'}, + __: value => { + return value; + } + } + }; + + const beforeSale = await models.Sale.findById(saleId, null, options); + await models.Ticket.componentUpdate(ctx, options); + const afterSale = await models.Sale.findById(saleId, null, options); + + expect(beforeSale.price).not.toEqual(afterSale.price); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + }); }); From e7da093fc1e647e3c8c322f47b8ca4472b72a3b7 Mon Sep 17 00:00:00 2001 From: pablone Date: Tue, 31 Oct 2023 07:49:27 +0100 Subject: [PATCH 299/427] =?UTF-8?q?fix(acl.sql):=20refs=20#4131=20=C3=B2ne?= =?UTF-8?q?r=20comillas=20en=20el=20sql?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- db/changes/234601/00-ACLticketTrackingState.sql | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/db/changes/234601/00-ACLticketTrackingState.sql b/db/changes/234601/00-ACLticketTrackingState.sql index f84128b16..0f7bd4f44 100644 --- a/db/changes/234601/00-ACLticketTrackingState.sql +++ b/db/changes/234601/00-ACLticketTrackingState.sql @@ -1,7 +1,7 @@ UPDATE `salix`.`ACL` - SET property = 'state', - model = 'Ticket' - WHERE property = 'changeState'; + 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'@; From 6112c7ba5f234cd3ceb7727018c167231b7ed5f4 Mon Sep 17 00:00:00 2001 From: robert Date: Tue, 31 Oct 2023 09:59:34 +0100 Subject: [PATCH 300/427] refs #5637 saleGroup traducciones --- modules/ticket/back/locale/sale-group/en.yml | 10 ++++++++++ modules/ticket/back/locale/sale-group/es.yml | 10 ++++++++++ 2 files changed, 20 insertions(+) create mode 100644 modules/ticket/back/locale/sale-group/en.yml create mode 100644 modules/ticket/back/locale/sale-group/es.yml diff --git a/modules/ticket/back/locale/sale-group/en.yml b/modules/ticket/back/locale/sale-group/en.yml new file mode 100644 index 000000000..d88231647 --- /dev/null +++ b/modules/ticket/back/locale/sale-group/en.yml @@ -0,0 +1,10 @@ +name: saleGroup +columns: + id: id + created: created + userFk: user + parkingFk: parking + sectorFk: sector + ticketFk: ticket + editorFk: editor + diff --git a/modules/ticket/back/locale/sale-group/es.yml b/modules/ticket/back/locale/sale-group/es.yml new file mode 100644 index 000000000..9efbe7148 --- /dev/null +++ b/modules/ticket/back/locale/sale-group/es.yml @@ -0,0 +1,10 @@ +name: saleGroup +columns: + id: id + created: creado + userFk: usuario + parkingFk: parking + sectorFk: sector + ticketFk: ticket + editorFk: editor + From d7542bcbb4c9c491a532b2345a0c8dda462ab4a2 Mon Sep 17 00:00:00 2001 From: alexm Date: Tue, 31 Oct 2023 15:11:03 +0100 Subject: [PATCH 301/427] refs #6335 fix(ticketAdvance): procedure --- ..._canAdvance_leftJoin.sql => 00-ticket_canAdvance_update.sql} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename db/changes/234601/{00-ticket_canAdvance_leftJoin.sql => 00-ticket_canAdvance_update.sql} (99%) diff --git a/db/changes/234601/00-ticket_canAdvance_leftJoin.sql b/db/changes/234601/00-ticket_canAdvance_update.sql similarity index 99% rename from db/changes/234601/00-ticket_canAdvance_leftJoin.sql rename to db/changes/234601/00-ticket_canAdvance_update.sql index 31472afd8..272a0618a 100644 --- a/db/changes/234601/00-ticket_canAdvance_leftJoin.sql +++ b/db/changes/234601/00-ticket_canAdvance_update.sql @@ -31,7 +31,7 @@ BEGIN SELECT itemFk, quantity FROM itemEntryIn WHERE landed >= vDateInventory - AND landed < vDateFuture + AND landed <= vDateToAdvance AND isVirtualStock = FALSE AND warehouseInFk = vWarehouseFk UNION ALL From bf84863237e64040ebaec4b4fa933bd7bff88b72 Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 2 Nov 2023 08:42:53 +0100 Subject: [PATCH 302/427] refs #6376 fix: changelog --- CHANGELOG.md | 7 +-- db/changes/234201/00-packagingFkviews.sql | 74 ++++++++++++----------- 2 files changed, 41 insertions(+), 40 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d677b80e3..69f9f63b6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,20 +5,19 @@ 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). -## [2342.01] - 2023-10-19 +## [2342.01] - 2023-11-02 ### Added +- (Usuarios -> Foto) Se muestra la foto del trabajador ### Changed ### Fixed +- (Usuarios -> Historial) Abre el descriptor del usuario correctamente ## [2340.01] - 2023-10-05 ### Added -- (Usuarios -> Foto) Se muestra la foto del trabajador - ### Changed ### Fixed -- (Usuarios -> Historial) Abre el descriptor del usuario correctamente ## [2338.01] - 2023-09-21 diff --git a/db/changes/234201/00-packagingFkviews.sql b/db/changes/234201/00-packagingFkviews.sql index f355325f3..abc7dc004 100644 --- a/db/changes/234201/00-packagingFkviews.sql +++ b/db/changes/234201/00-packagingFkviews.sql @@ -1,3 +1,41 @@ +CREATE OR REPLACE DEFINER=`root`@`localhost` + SQL SECURITY DEFINER + VIEW `vn`.`awbVolume` +AS SELECT `d`.`awbFk` AS `awbFk`, + `b`.`stickers` * `i`.`density` * IF( + `p`.`volume` > 0, + `p`.`volume`, + `p`.`width` * `p`.`depth` * IF(`p`.`height` = 0, `i`.`size` + 10, `p`.`height`) + ) / (`vc`.`aerealVolumetricDensity` * 1000) AS `volume`, + `b`.`id` AS `buyFk` +FROM ( + ( + ( + ( + ( + ( + ( + ( + `vn`.`buy` `b` + JOIN `vn`.`item` `i` ON(`b`.`itemFk` = `i`.`id`) + ) + JOIN `vn`.`itemType` `it` ON(`i`.`typeFk` = `it`.`id`) + ) + JOIN `vn`.`packaging` `p` ON(`p`.`id` = `b`.`packagingFk`) + ) + JOIN `vn`.`entry` `e` ON(`b`.`entryFk` = `e`.`id`) + ) + JOIN `vn`.`travel` `t` ON(`t`.`id` = `e`.`travelFk`) + ) + JOIN `vn`.`duaEntry` `de` ON(`de`.`entryFk` = `e`.`id`) + ) + JOIN `vn`.`dua` `d` ON(`d`.`id` = `de`.`duaFk`) + ) + JOIN `vn`.`volumeConfig` `vc` + ) +WHERE `t`.`shipped` > makedate(year(`util`.`VN_CURDATE`()) - 1, 1); + + CREATE OR REPLACE DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `vn2008`.`Compres` @@ -108,39 +146,3 @@ FROM ( LEFT JOIN `edi`.`supplier` `s` ON(`e`.`pro` = `s`.`supplier_id`) ); -CREATE OR REPLACE DEFINER=`root`@`localhost` - SQL SECURITY DEFINER - VIEW `vn`.`awbVolume` -AS SELECT `d`.`awbFk` AS `awbFk`, - `b`.`stickers` * `i`.`density` * IF( - `p`.`volume` > 0, - `p`.`volume`, - `p`.`width` * `p`.`depth` * IF(`p`.`height` = 0, `i`.`size` + 10, `p`.`height`) - ) / (`vc`.`aerealVolumetricDensity` * 1000) AS `volume`, - `b`.`id` AS `buyFk` -FROM ( - ( - ( - ( - ( - ( - ( - ( - `vn`.`buy` `b` - JOIN `vn`.`item` `i` ON(`b`.`itemFk` = `i`.`id`) - ) - JOIN `vn`.`itemType` `it` ON(`i`.`typeFk` = `it`.`id`) - ) - JOIN `vn`.`packaging` `p` ON(`p`.`id` = `b`.`packagingFk`) - ) - JOIN `vn`.`entry` `e` ON(`b`.`entryFk` = `e`.`id`) - ) - JOIN `vn`.`travel` `t` ON(`t`.`id` = `e`.`travelFk`) - ) - JOIN `vn`.`duaEntry` `de` ON(`de`.`entryFk` = `e`.`id`) - ) - JOIN `vn`.`dua` `d` ON(`d`.`id` = `de`.`duaFk`) - ) - JOIN `vn`.`volumeConfig` `vc` - ) -WHERE `t`.`shipped` > makedate(year(`util`.`VN_CURDATE`()) - 1, 1); \ No newline at end of file From 03e2f5730621e6ca2f481e455a6f693b450f7469 Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 2 Nov 2023 10:57:50 +0100 Subject: [PATCH 303/427] refs #6067 fix: emailVerify url --- back/models/vn-user.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/back/models/vn-user.js b/back/models/vn-user.js index de5bf7b63..970497e4e 100644 --- a/back/models/vn-user.js +++ b/back/models/vn-user.js @@ -220,8 +220,11 @@ module.exports = function(Self) { class Mailer { async send(verifyOptions, cb) { + const url = new URL(verifyOptions.verifyHref); + if (process.env.NODE_ENV) url.port = ''; + const params = { - url: verifyOptions.verifyHref, + url: url.href, recipient: verifyOptions.to }; From 175e73e5659169d8ea79af2f76b5443f4b08800c Mon Sep 17 00:00:00 2001 From: pablone Date: Thu, 2 Nov 2023 14:05:14 +0100 Subject: [PATCH 304/427] 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 728838334cf427806ae42acaccbcd7e5944f1065 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Thu, 2 Nov 2023 14:42:22 +0100 Subject: [PATCH 305/427] hotFix_6312 fix originalQuantity --- modules/ticket/back/methods/sale/updateQuantity.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/modules/ticket/back/methods/sale/updateQuantity.js b/modules/ticket/back/methods/sale/updateQuantity.js index 1a497da24..610826283 100644 --- a/modules/ticket/back/methods/sale/updateQuantity.js +++ b/modules/ticket/back/methods/sale/updateQuantity.js @@ -64,7 +64,10 @@ module.exports = Self => { const sale = await models.Sale.findById(id, filter, myOptions); const oldQuantity = sale.quantity; - const result = await sale.updateAttributes({quantity: newQuantity}, myOptions); + const result = await sale.updateAttributes({ + quantity: newQuantity, + originalQuantity: newQuantity + }, myOptions); const salesPerson = sale.ticket().client().salesPersonUser(); if (salesPerson) { From a523e323735587a8192c4814b646440f5a93a5e7 Mon Sep 17 00:00:00 2001 From: alexm Date: Fri, 3 Nov 2023 07:57:53 +0100 Subject: [PATCH 306/427] refs #6335 style(ticketAdvance): fix with split-progress --- e2e/helpers/selectors.js | 2 +- loopback/locale/en.json | 5 ++-- .../back/methods/ticket/componentUpdate.js | 2 -- .../ticket/specs/componentUpdate.spec.js | 2 +- modules/ticket/front/advance/index.html | 10 ++------ modules/ticket/front/advance/index.js | 12 ++++----- modules/ticket/front/advance/index.spec.js | 25 ------------------- modules/ticket/front/advance/locale/es.yml | 2 ++ modules/ticket/front/advance/style.scss | 9 +++++++ .../ticket/front/basic-data/step-two/index.js | 1 - 10 files changed, 23 insertions(+), 47 deletions(-) diff --git a/e2e/helpers/selectors.js b/e2e/helpers/selectors.js index cec0545a0..b5dbd42ac 100644 --- a/e2e/helpers/selectors.js +++ b/e2e/helpers/selectors.js @@ -722,7 +722,7 @@ export default { isFullMovable: 'vn-check[ng-model="filter.isFullMovable"]', warehouseFk: 'vn-autocomplete[label="Warehouse"]', tableButtonSearch: 'vn-button[vn-tooltip="Search"]', - moveButton: 'vn-button[vn-tooltip="Advance tickets"]', + moveButton: 'vn-button[vn-tooltip="Advance tickets with negatives"]', acceptButton: '.vn-confirm.shown button[response="accept"]', firstCheck: 'tbody > tr:nth-child(2) > td > vn-check', tableId: 'vn-textfield[name="id"]', diff --git a/loopback/locale/en.json b/loopback/locale/en.json index 26650175d..9305c7f09 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -196,6 +196,7 @@ "Negative basis of tickets: 23": "Negative basis of tickets: 23", "Booking completed": "Booking complete", "The ticket is in preparation": "The ticket [{{ticketId}}]({{{ticketUrl}}}) of the sales person {{salesPersonId}} is in preparation", - "You can only add negative amounts in refund tickets": "You can only add negative amounts in refund tickets" + "You can only add negative amounts in refund tickets": "You can only add negative amounts in refund tickets", + "newTicket": "New ticket", + "keepPrice": "Keep prices" } - diff --git a/modules/ticket/back/methods/ticket/componentUpdate.js b/modules/ticket/back/methods/ticket/componentUpdate.js index 1b02fd201..d8d1163da 100644 --- a/modules/ticket/back/methods/ticket/componentUpdate.js +++ b/modules/ticket/back/methods/ticket/componentUpdate.js @@ -111,7 +111,6 @@ module.exports = Self => { Self.componentUpdate = async(ctx, options) => { const args = ctx.args; - const originalTicketId = args.id; const myOptions = {userId: ctx.req.accessToken.userId}; let tx; @@ -284,7 +283,6 @@ module.exports = Self => { } response.id = args.id; - console.log(originalTicketId, args.newTicket ? ` TRANSFER TO → ` : ` CREATE NEW TICKET → `, args.id); if (tx) await tx.commit(); return response; diff --git a/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js b/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js index e124999c9..40be4161c 100644 --- a/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js +++ b/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js @@ -210,7 +210,7 @@ describe('ticket componentUpdate()', () => { } }); - describe('ticket componentUpdate()', () => { + describe('componentUpdate() keepPrice', () => { it('should change shipped and keep price', async() => { const tx = await models.Ticket.beginTransaction({}); diff --git a/modules/ticket/front/advance/index.html b/modules/ticket/front/advance/index.html index 395fe7078..ca4d994d0 100644 --- a/modules/ticket/front/advance/index.html +++ b/modules/ticket/front/advance/index.html @@ -156,13 +156,7 @@ {{::ticket.futureLiters | dashIfEmpty}} {{::ticket.futureZoneName | dashIfEmpty}} - - - {{::ticket.notMovableLines | dashIfEmpty}} - - + {{::ticket.notMovableLines | dashIfEmpty}} {{::ticket.futureLines | dashIfEmpty}} - + diff --git a/modules/ticket/front/advance/index.js b/modules/ticket/front/advance/index.js index 5e41f0f23..5ab663256 100644 --- a/modules/ticket/front/advance/index.js +++ b/modules/ticket/front/advance/index.js @@ -153,11 +153,10 @@ export default class Controller extends Section { return this.$http.get(query, {params}).then(res => { if (res.data) return res.data; - else { - return this.vnApp.showError( - this.$t(`No delivery zone available for this landing date`) - ); - } + + return this.vnApp.showError( + this.$t(`No delivery zone available for this landing date`) + ); }); } @@ -201,7 +200,6 @@ export default class Controller extends Section { async requestComponentUpdate(ticket, isWithoutNegatives) { const query = `tickets/${ticket.futureId}/componentUpdate`; if (!ticket.landed) { - console.log(ticket); const newLanded = await this.getLanded({ shipped: this.$.model.userParams.dateToAdvance, addressFk: ticket.addressFk, @@ -229,7 +227,7 @@ export default class Controller extends Section { newTicket: ticket.id ?? undefined, keepPrice: true }; - console.log(params); + return {query, params}; } diff --git a/modules/ticket/front/advance/index.spec.js b/modules/ticket/front/advance/index.spec.js index da8614ca5..883993c1c 100644 --- a/modules/ticket/front/advance/index.spec.js +++ b/modules/ticket/front/advance/index.spec.js @@ -24,31 +24,6 @@ describe('Component vnTicketAdvance', () => { }]; })); - describe('compareDate()', () => { - it('should return warning when the date is the present', () => { - let today = Date.vnNew(); - let result = controller.compareDate(today); - - expect(result).toEqual('warning'); - }); - - it('should return sucess when the date is in the future', () => { - let futureDate = Date.vnNew(); - futureDate = futureDate.setDate(futureDate.getDate() + 10); - let result = controller.compareDate(futureDate); - - expect(result).toEqual('success'); - }); - - it('should return undefined when the date is in the past', () => { - let pastDate = Date.vnNew(); - pastDate = pastDate.setDate(pastDate.getDate() - 10); - let result = controller.compareDate(pastDate); - - expect(result).toEqual(undefined); - }); - }); - describe('checked()', () => { it('should return an array of checked tickets', () => { const result = controller.checked; diff --git a/modules/ticket/front/advance/locale/es.yml b/modules/ticket/front/advance/locale/es.yml index 520e82009..e42e65b6e 100644 --- a/modules/ticket/front/advance/locale/es.yml +++ b/modules/ticket/front/advance/locale/es.yml @@ -1,4 +1,6 @@ Advance tickets: Adelantar tickets +Advance tickets with negatives: Adelantar tickets con negativos +Advance tickets without negatives: Adelantar tickets sin negativos Search advance tickets by date: Busca tickets para adelantar por fecha Advance confirmation: ¿Desea adelantar {{checked}} tickets? Success: "{{tickets}} Tickets movidos correctamente" diff --git a/modules/ticket/front/advance/style.scss b/modules/ticket/front/advance/style.scss index 8fa9de438..82ae901cd 100644 --- a/modules/ticket/front/advance/style.scss +++ b/modules/ticket/front/advance/style.scss @@ -5,3 +5,12 @@ vn-ticket-advance{ color: #f7931e } } +.split-progress { + width: 40em; +} + +@media screen and (max-width: 600px) { + .split-progress { + width: 100%; + } +} diff --git a/modules/ticket/front/basic-data/step-two/index.js b/modules/ticket/front/basic-data/step-two/index.js index 8ca9f053d..8c8a3a079 100644 --- a/modules/ticket/front/basic-data/step-two/index.js +++ b/modules/ticket/front/basic-data/step-two/index.js @@ -115,7 +115,6 @@ class Controller extends Component { option: parseInt(this.ticket.option), isWithoutNegatives: this.ticket.withoutNegatives, withWarningAccept: this.ticket.withWarningAccept, - newTicket: null, keepPrice: false }; From 8c5e40c27fb8477027294feefb65cb6076e02a80 Mon Sep 17 00:00:00 2001 From: alexm Date: Fri, 3 Nov 2023 15:16:03 +0100 Subject: [PATCH 307/427] 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 99c88e6f5ddea89ac38bc385ee47bae4cef0b445 Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Sun, 5 Nov 2023 09:33:18 +0100 Subject: [PATCH 308/427] fix: refs #6390 Loggable set as base for ItemShelving --- modules/item/back/models/item-shelving.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/item/back/models/item-shelving.json b/modules/item/back/models/item-shelving.json index 61d05539e..bb1a141c4 100644 --- a/modules/item/back/models/item-shelving.json +++ b/modules/item/back/models/item-shelving.json @@ -1,6 +1,6 @@ { "name": "ItemShelving", - "base": "VnModel", + "base": "Loggable", "options": { "mysql": { "table": "itemShelving" From 7ca3ea156cc1937564056c350da526fc121f7d4d Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 6 Nov 2023 09:16:10 +0100 Subject: [PATCH 309/427] 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 310/427] 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 311/427] 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 312/427] 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 313/427] 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 314/427] 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 9d5461862026731a490f6a04aa11219e994379b0 Mon Sep 17 00:00:00 2001 From: jgallego Date: Wed, 8 Nov 2023 10:01:02 +0100 Subject: [PATCH 315/427] fix: refs: #6207 impide facturar si no tienes incoterm --- db/dump/fixtures.sql | 8 +++--- loopback/locale/es.json | 4 +-- .../ticket/back/methods/ticket/makeInvoice.js | 13 ++++++--- .../methods/ticket/specs/makeInvoice.spec.js | 27 +++++++++++++++++++ .../invoice-incoterms/sql/incoterms.sql | 4 +-- 5 files changed, 44 insertions(+), 12 deletions(-) diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index faf58fd78..164723de1 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -367,7 +367,7 @@ INSERT INTO `vn`.`client`(`id`,`name`,`fi`,`socialName`,`contact`,`street`,`city (1105, 'Max Eisenhardt', '251628698', 'MAGNETO', 'Rogue', 'UNKNOWN WHEREABOUTS', 'Gotham', 46460, 1111111111, 222222222, 1, 'MaxEisenhardt@mydomain.com', NULL, 0, 1234567890, 0, 3, 1, 300, 8, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 1, NULL, 0, 0, 18, 0, 1, 'florist','normal'), (1106, 'DavidCharlesHaller', '53136686Q', 'LEGION', 'Charles Xavier', 'CITY OF NEW YORK, NEW YORK, USA', 'Gotham', 46460, 1111111111, 222222222, 1, 'DavidCharlesHaller@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 0, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 0, NULL, 0, 0, 19, 0, 1, 'florist','normal'), (1107, 'Hank Pym', '09854837G', 'ANT MAN', 'Hawk', 'ANTHILL, SAN FRANCISCO, CALIFORNIA', 'Gotham', 46460, 1111111111, 222222222, 1, 'HankPym@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, 0, NULL, 0, 0, 19, 0, 1, 'florist','normal'), - (1108, 'Charles Xavier', '22641921P', 'PROFESSOR X', 'Beast', '3800 VICTORY PKWY, CINCINNATI, OH 45207, USA', 'Gotham', 46460, 1111111111, 222222222, 1, 'CharlesXavier@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 1, NULL, 0, 0, 19, 0, 1, 'florist','normal'), + (1108, 'Charles Xavier', '22641921P', 'PROFESSOR X', 'Beast', '3800 VICTORY PKWY, CINCINNATI, OH 45207, USA', 'Gotham', 46460, 1111111111, 222222222, 1, 'CharlesXavier@mydomain.com', NULL, 0, 1234567890, 0, 5, 1, 300, 13, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 1, NULL, 0, 0, 19, 0, 1, 'florist','normal'), (1109, 'Bruce Banner', '16104829E', 'HULK', 'Black widow', 'SOMEWHERE IN NEW YORK', 'Gotham', 46460, 1111111111, 222222222, 1, 'BruceBanner@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, 0, NULL, 0, 0, 9, 0, 1, 'florist','normal'), (1110, 'Jessica Jones', '58282869H', 'JESSICA JONES', 'Luke Cage', 'NYCC 2015 POSTER', 'Gotham', 46460, 1111111111, 222222222, 1, 'JessicaJones@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, 0, NULL, 0, 0, NULL, 0, 1, 'florist','normal'), (1111, 'Missing', NULL, 'MISSING MAN', 'Anton', 'THE SPACE, UNIVERSE FAR AWAY', 'Gotham', 46460, 1111111111, 222222222, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 4, 0, 1, 0, NULL, 1, 0, NULL, 0, 1, 'others','normal'), @@ -405,7 +405,7 @@ INSERT INTO `vn`.`address`(`id`, `nickname`, `street`, `city`, `postalCode`, `pr (5, 'Max Eisenhardt', 'Unknown Whereabouts', 'Gotham', 46460, 1, 1111111111, 222222222, 1, 1105, 2, NULL, NULL, 0, 1), (6, 'DavidCharlesHaller', 'Evil hideout', 'Gotham', 46460, 1, 1111111111, 222222222, 1, 1106, 2, NULL, NULL, 0, 1), (7, 'Hank Pym', 'Anthill', 'Gotham', 46460, 1, 1111111111, 222222222, 1, 1107, 2, NULL, NULL, 0, 1), - (8, 'Charles Xavier', '3800 Victory Pkwy, Cincinnati, OH 45207, USA', 'Gotham', 46460, 1, 1111111111, 222222222, 1, 1108, 2, NULL, NULL, 0, 1), + (8, 'Charles Xavier', '3800 Victory Pkwy, Cincinnati, OH 45207, USA', 'Gotham', 46460, 5, 1111111111, 222222222, 1, 1108, 2, NULL, NULL, 0, 1), (9, 'Bruce Banner', 'Somewhere in New York', 'Gotham', 46460, 1, 1111111111, 222222222, 1, 1109, 2, NULL, NULL, 0, 1), (10, 'Jessica Jones', 'NYCC 2015 Poster', 'Gotham', 46460, 1, 1111111111, 222222222, 1, 1110, 2, NULL, NULL, 0, 1), (11, 'Missing', 'The space', 'Gotham', 46460, 1, 1111111111, 222222222, 1, 1111, 10, NULL, NULL, 0, 1), @@ -437,7 +437,7 @@ INSERT INTO `vn`.`address`(`id`, `nickname`, `street`, `city`, `postalCode`, `pr (125, 'The plastic cell', 'address 25', 'Gotham', 46460, 1, 1111111111, 222222222, 1, 1105, 2, NULL, NULL, 0, 0), (126, 'Many places', 'address 26', 'Gotham', 46460, 1, 1111111111, 222222222, 1, 1106, 2, NULL, NULL, 0, 0), (127, 'Your pocket', 'address 27', 'Gotham', 46460, 1, 1111111111, 222222222, 1, 1107, 2, NULL, NULL, 0, 0), - (128, 'Cerebro', 'address 28', 'Gotham', 46460, 1, 1111111111, 222222222, 1, 1108, 2, NULL, NULL, 0, 0), + (128, 'Cerebro', 'address 28', 'Gotham', 46460, 5, 1111111111, 222222222, 1, 1108, 2, NULL, NULL, 0, 0), (129, 'Luke Cages Bar', 'address 29', 'Gotham', 'EC170150', 1, 1111111111, 222222222, 1, 1110, 2, NULL, NULL, 0, 0), (130, 'Non valid address', 'address 30', 'Gotham', 46460, 1, 1111111111, 222222222, 0, 1101, 2, NULL, NULL, 0, 0); @@ -2982,4 +2982,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'); diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 3cc9a9627..e3e19d7e8 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -321,9 +321,9 @@ "Select a different client": "Seleccione un cliente distinto", "Fill all the fields": "Rellene todos los campos", "The response is not a PDF": "La respuesta no es un PDF", - "Ticket without Route": "Ticket sin ruta", "Booking completed": "Reserva completada", "The ticket is in preparation": "El ticket [{{ticketId}}]({{{ticketUrl}}}) del comercial {{salesPersonId}} está en preparación", "The amount cannot be less than the minimum": "La cantidad no puede ser menor que la cantidad mímina", - "quantityLessThanMin": "La cantidad no puede ser menor que la cantidad mímina" + "quantityLessThanMin": "La cantidad no puede ser menor que la cantidad mímina", + "Incoterms data for consignee is missing": "Faltan los datos de los Incoterms para el consignatario" } diff --git a/modules/ticket/back/methods/ticket/makeInvoice.js b/modules/ticket/back/methods/ticket/makeInvoice.js index e18e58e0b..e7ee806c7 100644 --- a/modules/ticket/back/methods/ticket/makeInvoice.js +++ b/modules/ticket/back/methods/ticket/makeInvoice.js @@ -49,7 +49,6 @@ module.exports = function(Self) { myOptions.transaction = tx; } - let serial; try { const ticketToInvoice = await Self.rawSql(` SELECT id @@ -60,7 +59,7 @@ module.exports = function(Self) { where: { id: {inq: ticketsIds} }, - fields: ['id', 'clientFk'] + fields: ['id', 'clientFk', 'addressFk'] }, myOptions); await models.Ticket.canBeInvoiced(ctx, ticketsIds, myOptions); @@ -72,13 +71,19 @@ module.exports = function(Self) { throw new UserError(`This client can't be invoiced`); const query = `SELECT vn.invoiceSerial(?, ?, ?) AS serial`; - const [result] = await Self.rawSql(query, [ + const [{serial}] = await Self.rawSql(query, [ clientId, companyFk, invoiceType, ], myOptions); - serial = result.serial; + const invoiceOutSerial = await models.InvoiceOutSerial.findById(serial); + if (invoiceOutSerial?.taxAreaFk == 'WORLD') { + const address = await models.Address.findById(firstTicket.addressFk); + + if (!address || !address.customsAgentFk || !address.incotermsFk) + throw new UserError('Incoterms data for consignee is missing'); + } await Self.rawSql('CALL invoiceOut_new(?, ?, null, @invoiceId)', [serial, invoiceDate], myOptions); const [resultInvoice] = await Self.rawSql('SELECT @invoiceId id', [], myOptions); diff --git a/modules/ticket/back/methods/ticket/specs/makeInvoice.spec.js b/modules/ticket/back/methods/ticket/specs/makeInvoice.spec.js index 9af6ad557..9b1fd8f6f 100644 --- a/modules/ticket/back/methods/ticket/specs/makeInvoice.spec.js +++ b/modules/ticket/back/methods/ticket/specs/makeInvoice.spec.js @@ -52,4 +52,31 @@ describe('ticket makeInvoice()', () => { throw e; } }); + + it('should throw an error when invoicing a client without incoterms', async() => { + const tx = await models.Ticket.beginTransaction({}); + let error; + try { + const options = {transaction: tx}; + + const ticketsId = [18]; + await models.Ticket.rawSql(` + DROP TEMPORARY TABLE IF EXISTS tmp.ticketToInvoice; + CREATE TEMPORARY TABLE tmp.ticketToInvoice + (PRIMARY KEY (id)) + ENGINE = MEMORY + SELECT id + FROM vn.ticket + WHERE id IN (?) + `, [ticketsId], options); + + await models.Ticket.makeInvoice(ctx, invoiceType, companyFk, invoiceDate, options); + await tx.rollback(); + } catch (e) { + error = e; + await tx.rollback(); + } + + expect(error.message).toEqual(`Incoterms data for consignee is missing`); + }); }); diff --git a/print/templates/reports/invoice-incoterms/sql/incoterms.sql b/print/templates/reports/invoice-incoterms/sql/incoterms.sql index 435b3a51a..0c4af803d 100644 --- a/print/templates/reports/invoice-incoterms/sql/incoterms.sql +++ b/print/templates/reports/invoice-incoterms/sql/incoterms.sql @@ -1,7 +1,7 @@ SELECT io.issued, c.socialName, c.street postalAddress, - IF (ios.taxAreaFk IS NOT NULL, CONCAT(cty.code, c.fi), c.fi) fi, + c.fi, io.clientFk, c.postcode, c.city, @@ -50,7 +50,7 @@ SELECT io.issued, ) sub2 ON TRUE JOIN vn.itemTaxCountry itc ON itc.countryFk = su.countryFk AND itc.itemFk = s.itemFk JOIN vn.taxClass tc ON tc.id = itc.taxClassFk - LEFT JOIN vn.invoiceOutSerial ios ON ios.code = io.serial AND ios.taxAreaFk = 'CEE' + JOIN vn.invoiceOutSerial ios ON ios.code = io.serial AND ios.taxAreaFk = 'WORLD' JOIN vn.country cty ON cty.id = c.countryFk JOIN vn.payMethod pm ON pm.id = c .payMethodFk JOIN vn.company co ON co.id=io.companyFk From 5751065e6a0f14d27314ec1cad944b52ddc57d83 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Wed, 8 Nov 2023 11:50:04 +0100 Subject: [PATCH 316/427] 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 317/427] 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 318/427] 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 319/427] 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 320/427] 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 321/427] 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 322/427] 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 01d3c23cf0bcb3d716be9e7a8a7b90fdfe75968b Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 9 Nov 2023 11:57:52 +0100 Subject: [PATCH 323/427] ref #5914 renameTable --- db/changes/234601/00-transferInvoice.sql | 2 +- .../invoiceOut/back/methods/invoiceOut/transferInvoice.js | 4 ++-- modules/invoiceOut/back/model-config.json | 2 +- ...us-invoice-type-477.json => sii-type-invoice-out.json} | 7 +++++-- modules/invoiceOut/front/descriptor-menu/index.html | 8 ++++---- modules/invoiceOut/front/descriptor-menu/index.js | 2 +- 6 files changed, 14 insertions(+), 11 deletions(-) rename modules/invoiceOut/back/models/{cplus-invoice-type-477.json => sii-type-invoice-out.json} (68%) diff --git a/db/changes/234601/00-transferInvoice.sql b/db/changes/234601/00-transferInvoice.sql index 7a9890ae4..d9ae39464 100644 --- a/db/changes/234601/00-transferInvoice.sql +++ b/db/changes/234601/00-transferInvoice.sql @@ -1,6 +1,6 @@ INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) VALUES ('CplusRectificationType', '*', 'READ', 'ALLOW', 'ROLE', 'administrative'), - ('CplusInvoiceType477', '*', 'READ', 'ALLOW', 'ROLE', 'administrative'), + ('SiiTypeInvoiceOut', '*', 'READ', 'ALLOW', 'ROLE', 'administrative'), ('InvoiceCorrectionType', '*', 'READ', 'ALLOW', 'ROLE', 'administrative'), ('InvoiceOut', 'transferInvoice', 'WRITE', 'ALLOW', 'ROLE', 'administrative'); diff --git a/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js b/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js index 8a0609b8d..dde535c99 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js +++ b/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js @@ -27,7 +27,7 @@ module.exports = Self => { required: true }, { - arg: 'cplusInvoiceType477Id', + arg: 'siiTypeInvoiceOutId', type: 'number', required: true }, @@ -93,7 +93,7 @@ module.exports = Self => { correctingFk: invoiceId, correctedFk: args.id, cplusRectificationTypeFk: args.cplusRectificationId, - cplusInvoiceType477Fk: args.cplusInvoiceType477Id, + siiTypeInvoiceOutFk: args.siiTypeInvoiceOutId, invoiceCorrectionTypeFk: args.invoiceCorrectionTypeId }, myOptions); diff --git a/modules/invoiceOut/back/model-config.json b/modules/invoiceOut/back/model-config.json index 23246893b..9c7512429 100644 --- a/modules/invoiceOut/back/model-config.json +++ b/modules/invoiceOut/back/model-config.json @@ -41,7 +41,7 @@ "InvoiceCorrection": { "dataSource": "vn" }, - "CplusInvoiceType477": { + "SiiTypeInvoiceOut": { "dataSource": "vn" } } diff --git a/modules/invoiceOut/back/models/cplus-invoice-type-477.json b/modules/invoiceOut/back/models/sii-type-invoice-out.json similarity index 68% rename from modules/invoiceOut/back/models/cplus-invoice-type-477.json rename to modules/invoiceOut/back/models/sii-type-invoice-out.json index 840a9a7e4..89f01bd74 100644 --- a/modules/invoiceOut/back/models/cplus-invoice-type-477.json +++ b/modules/invoiceOut/back/models/sii-type-invoice-out.json @@ -1,9 +1,9 @@ { - "name": "CplusInvoiceType477", + "name": "SiiTypeInvoiceOut", "base": "VnModel", "options": { "mysql": { - "table": "cplusInvoiceType477" + "table": "siiTypeInvoiceOut" } }, "properties": { @@ -12,6 +12,9 @@ "type": "number", "description": "Identifier" }, + "code": { + "type": "string" + }, "description": { "type": "string" } diff --git a/modules/invoiceOut/front/descriptor-menu/index.html b/modules/invoiceOut/front/descriptor-menu/index.html index 7d465f4ea..d7537bc0a 100644 --- a/modules/invoiceOut/front/descriptor-menu/index.html +++ b/modules/invoiceOut/front/descriptor-menu/index.html @@ -6,8 +6,8 @@ + url="SiiTypeInvoiceOuts" + data="siiTypeInvoiceOuts"> diff --git a/modules/invoiceOut/front/descriptor-menu/index.js b/modules/invoiceOut/front/descriptor-menu/index.js index 7d2644158..d3862a753 100644 --- a/modules/invoiceOut/front/descriptor-menu/index.js +++ b/modules/invoiceOut/front/descriptor-menu/index.js @@ -132,7 +132,7 @@ class Controller extends Section { ref: this.invoiceOut.ref, newClientFk: this.invoiceOut.client.id, cplusRectificationId: this.cplusRectificationType, - cplusInvoiceType477Id: this.cplusInvoiceType477, + siiTypeInvoiceOutId: this.siiTypeInvoiceOut, invoiceCorrectionTypeId: this.invoiceCorrectionType }; this.$http.post(`InvoiceOuts/transferInvoice`, params).then(res => { From b07858fddbaf04dc79f96799468cff2e528a2c6c Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 9 Nov 2023 14:33:46 +0100 Subject: [PATCH 324/427] ref #5914 replace name --- db/.archive/225201/00-invoiceOut_new.sql | 2 +- db/.archive/231001/02-invoiceOut_new.sql | 2 +- db/.archive/232001/00-invoiceOut_new.sql | 2 +- db/dump/dumpedFixtures.sql | 10 ++++---- db/dump/structure.sql | 25 +++++++++---------- db/export-data.sh | 2 +- .../invoiceOut/specs/transferinvoice.spec.js | 8 +++--- .../back/models/invoice-correction.json | 2 +- .../back/models/sii-type-invoice-out.json | 3 --- 9 files changed, 26 insertions(+), 30 deletions(-) diff --git a/db/.archive/225201/00-invoiceOut_new.sql b/db/.archive/225201/00-invoiceOut_new.sql index 4c60b50bc..8e23fb43b 100644 --- a/db/.archive/225201/00-invoiceOut_new.sql +++ b/db/.archive/225201/00-invoiceOut_new.sql @@ -74,7 +74,7 @@ BEGIN clientFk, dued, companyFk, - cplusInvoiceType477Fk + siiTypeInvoiceOutFk ) SELECT 1, diff --git a/db/.archive/231001/02-invoiceOut_new.sql b/db/.archive/231001/02-invoiceOut_new.sql index d2b96eff7..d570dfb72 100644 --- a/db/.archive/231001/02-invoiceOut_new.sql +++ b/db/.archive/231001/02-invoiceOut_new.sql @@ -96,7 +96,7 @@ BEGIN clientFk, dued, companyFk, - cplusInvoiceType477Fk + siiTypeInvoiceOutFk ) SELECT 1, diff --git a/db/.archive/232001/00-invoiceOut_new.sql b/db/.archive/232001/00-invoiceOut_new.sql index b4fc5c824..b497dffda 100644 --- a/db/.archive/232001/00-invoiceOut_new.sql +++ b/db/.archive/232001/00-invoiceOut_new.sql @@ -96,7 +96,7 @@ BEGIN clientFk, dued, companyFk, - cplusInvoiceType477Fk + siiTypeInvoiceOutFk ) SELECT 1, diff --git a/db/dump/dumpedFixtures.sql b/db/dump/dumpedFixtures.sql index 2e1511b59..43eba7f24 100644 --- a/db/dump/dumpedFixtures.sql +++ b/db/dump/dumpedFixtures.sql @@ -275,13 +275,13 @@ INSERT INTO `cplusInvoiceType472` VALUES (1,'F1 - Factura'),(2,'F2 - Factura sim UNLOCK TABLES; -- --- Dumping data for table `cplusInvoiceType477` +-- Dumping data for table `siiTypeInvoiceOut` -- -LOCK TABLES `cplusInvoiceType477` WRITE; -/*!40000 ALTER TABLE `cplusInvoiceType477` DISABLE KEYS */; -INSERT INTO `cplusInvoiceType477` VALUES (1,'F1 - Factura'),(2,'F2 - Factura simplificada (ticket)'),(3,'F3 - Factura emitida en sustitución de facturas simplificadas facturadas y declaradas'),(4,'F4 - Asiento resumen de facturas'),(5,'R1 - Factura rectificativa (Art. 80.1, 80.2 y error fundado en derecho)'),(6,'R2 - Factura rectificativa (Art. 80.3)'),(7,'R3 - Factura rectificativa (Art. 80.4)'),(8,'R4 - Factura rectificativa (Resto)'),(9,'R5 - Factura rectificativa en facturas simplificadas'); -/*!40000 ALTER TABLE `cplusInvoiceType477` ENABLE KEYS */; +LOCK TABLES `siiTypeInvoiceOut` WRITE; +/*!40000 ALTER TABLE `siiTypeInvoiceOut` DISABLE KEYS */; +INSERT INTO `siiTypeInvoiceOut` VALUES (1,'F1 - Factura'),(2,'F2 - Factura simplificada (ticket)'),(3,'F3 - Factura emitida en sustitución de facturas simplificadas facturadas y declaradas'),(4,'F4 - Asiento resumen de facturas'),(5,'R1 - Factura rectificativa (Art. 80.1, 80.2 y error fundado en derecho)'),(6,'R2 - Factura rectificativa (Art. 80.3)'),(7,'R3 - Factura rectificativa (Art. 80.4)'),(8,'R4 - Factura rectificativa (Resto)'),(9,'R5 - Factura rectificativa en facturas simplificadas'); +/*!40000 ALTER TABLE `siiTypeInvoiceOut` ENABLE KEYS */; UNLOCK TABLES; -- diff --git a/db/dump/structure.sql b/db/dump/structure.sql index b242821fc..f50868b19 100644 --- a/db/dump/structure.sql +++ b/db/dump/structure.sql @@ -25993,13 +25993,12 @@ CREATE TABLE `cplusInvoiceType472` ( /*!40101 SET character_set_client = @saved_cs_client */; -- --- Table structure for table `cplusInvoiceType477` +-- Table structure for table `siiTypeInvoiceOut` -- - -DROP TABLE IF EXISTS `cplusInvoiceType477`; +DROP TABLE IF EXISTS `siiTypeInvoiceOut`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; -CREATE TABLE `cplusInvoiceType477` ( +CREATE TABLE `siiTypeInvoiceOut` ( `id` int(10) unsigned NOT NULL, `description` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, PRIMARY KEY (`id`) @@ -29450,16 +29449,16 @@ CREATE TABLE `invoiceCorrection` ( `correctingFk` int(10) unsigned NOT NULL COMMENT 'Factura rectificativa', `correctedFk` int(10) unsigned NOT NULL COMMENT 'Factura rectificada', `cplusRectificationTypeFk` int(10) unsigned NOT NULL, - `cplusInvoiceType477Fk` int(10) unsigned NOT NULL, + `siiTypeInvoiceOutFk` int(10) unsigned NOT NULL, `invoiceCorrectionTypeFk` int(11) NOT NULL DEFAULT 3, PRIMARY KEY (`correctingFk`), KEY `correctedFk_idx` (`correctedFk`), KEY `invoiceCorrection_ibfk_1_idx` (`cplusRectificationTypeFk`), - KEY `cplusInvoiceTyoeFk_idx` (`cplusInvoiceType477Fk`), + KEY `cplusInvoiceTyoeFk_idx` (`siiTypeInvoiceOutFk`), KEY `invoiceCorrectionTypeFk_idx` (`invoiceCorrectionTypeFk`), CONSTRAINT `corrected_fk` FOREIGN KEY (`correctedFk`) REFERENCES `invoiceOut` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `correcting_fk` FOREIGN KEY (`correctingFk`) REFERENCES `invoiceOut` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `cplusInvoiceTyoeFk` FOREIGN KEY (`cplusInvoiceType477Fk`) REFERENCES `cplusInvoiceType477` (`id`) ON UPDATE CASCADE, + CONSTRAINT `cplusInvoiceTyoeFk` FOREIGN KEY (`siiTypeInvoiceOutFk`) REFERENCES `siiTypeInvoiceOut` (`id`) ON UPDATE CASCADE, CONSTRAINT `invoiceCorrectionType_Fk33` FOREIGN KEY (`invoiceCorrectionTypeFk`) REFERENCES `invoiceCorrectionType` (`id`) ON UPDATE CASCADE, CONSTRAINT `invoiceCorrection_ibfk_1` FOREIGN KEY (`cplusRectificationTypeFk`) REFERENCES `cplusRectificationType` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Relacion entre las facturas rectificativas y las rectificadas.'; @@ -30130,7 +30129,7 @@ CREATE TABLE `invoiceOut` ( `companyFk` int(10) unsigned NOT NULL DEFAULT 442, `hasPdf` tinyint(3) unsigned NOT NULL DEFAULT 0, `booked` date DEFAULT NULL, - `cplusInvoiceType477Fk` int(10) unsigned NOT NULL DEFAULT 1, + `siiTypeInvoiceOutFk` int(10) unsigned NOT NULL DEFAULT 1, `cplusTaxBreakFk` int(10) unsigned NOT NULL DEFAULT 1, `cplusSubjectOpFk` int(10) unsigned NOT NULL DEFAULT 1, `cplusTrascendency477Fk` int(10) unsigned NOT NULL DEFAULT 1, @@ -30140,13 +30139,13 @@ CREATE TABLE `invoiceOut` ( KEY `Id_Cliente` (`clientFk`), KEY `empresa_id` (`companyFk`), KEY `Fecha` (`issued`), - KEY `Facturas_ibfk_2_idx` (`cplusInvoiceType477Fk`), + KEY `Facturas_ibfk_2_idx` (`siiTypeInvoiceOutFk`), KEY `Facturas_ibfk_3_idx` (`cplusSubjectOpFk`), KEY `Facturas_ibfk_4_idx` (`cplusTaxBreakFk`), KEY `Facturas_ibfk_5_idx` (`cplusTrascendency477Fk`), KEY `Facturas_idx_Vencimiento` (`dued`), KEY `invoiceOut_serial` (`serial`), - CONSTRAINT `invoiceOut_ibfk_2` FOREIGN KEY (`cplusInvoiceType477Fk`) REFERENCES `cplusInvoiceType477` (`id`) ON UPDATE CASCADE, + CONSTRAINT `invoiceOut_ibfk_2` FOREIGN KEY (`siiTypeInvoiceOutFk`) REFERENCES `siiTypeInvoiceOut` (`id`) ON UPDATE CASCADE, CONSTRAINT `invoiceOut_ibfk_3` FOREIGN KEY (`cplusSubjectOpFk`) REFERENCES `cplusSubjectOp` (`id`) ON UPDATE CASCADE, CONSTRAINT `invoiceOut_ibfk_4` FOREIGN KEY (`cplusTaxBreakFk`) REFERENCES `cplusTaxBreak` (`id`) ON UPDATE CASCADE, CONSTRAINT `invoiceOut_serial` FOREIGN KEY (`serial`) REFERENCES `invoiceOutSerial` (`code`), @@ -30308,7 +30307,7 @@ CREATE TABLE `invoiceOutSerial` ( `isTaxed` tinyint(1) NOT NULL DEFAULT 1, `taxAreaFk` varchar(15) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT 'NATIONAL', `isCEE` tinyint(1) NOT NULL DEFAULT 0, - `cplusInvoiceType477Fk` int(10) unsigned DEFAULT 1, + `siiTypeInvoiceOutFk` int(10) unsigned DEFAULT 1, `footNotes` longtext DEFAULT NULL, `isRefEditable` tinyint(4) NOT NULL DEFAULT 0, `type` enum('global','quick') DEFAULT NULL, @@ -58288,7 +58287,7 @@ BEGIN io.cplusTrascendency477Fk AS TIPOCLAVE, io.cplusTaxBreakFk AS TIPOEXENCI, io.cplusSubjectOpFk AS TIPONOSUJE, - io.cplusInvoiceType477Fk AS TIPOFACT, + io.siiTypeInvoiceOutFk AS TIPOFACT, ic.cplusRectificationTypeFk AS TIPORECTIF, io.companyFk, RIGHT(io.ref, LENGTH(io.ref) - 1) AS invoiceNum, @@ -58868,7 +58867,7 @@ BEGIN clientFk, dued, companyFk, - cplusInvoiceType477Fk + siiTypeInvoiceOutFk ) SELECT 1, diff --git a/db/export-data.sh b/db/export-data.sh index 7d346b235..a516992d3 100755 --- a/db/export-data.sh +++ b/db/export-data.sh @@ -46,7 +46,7 @@ TABLES=( bookingPlanner businessType cplusInvoiceType472 - cplusInvoiceType477 + siiTypeInvoiceOut cplusRectificationType cplusSubjectOp cplusTaxBreak diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js index 04f6df299..876948419 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js @@ -2,7 +2,7 @@ const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); -describe('InvoiceOut tranferInvoice()', () => { +fdescribe('InvoiceOut tranferInvoice()', () => { const activeCtx = { accessToken: {userId: 5}, http: { @@ -19,7 +19,7 @@ describe('InvoiceOut tranferInvoice()', () => { }); }); - it('should return the id of the created issued invoice', async() => { + fit('should return the id of the created issued invoice', async() => { const tx = await models.InvoiceOut.beginTransaction({}); const options = {transaction: tx}; const args = { @@ -27,7 +27,7 @@ describe('InvoiceOut tranferInvoice()', () => { ref: 'T4444444', newClientFk: 1, cplusRectificationId: 1, - cplusInvoiceType477Id: 1, + siiTypeInvoiceOutId: 1, invoiceCorrectionTypeId: 1 }; ctx.args = args; @@ -52,7 +52,7 @@ describe('InvoiceOut tranferInvoice()', () => { ref: 'T1111111', newClientFk: 1101, cplusRectificationId: 1, - cplusInvoiceType477Id: 1, + siiTypeInvoiceOutId: 1, invoiceCorrectionTypeId: 1 }; ctx.args = args; diff --git a/modules/invoiceOut/back/models/invoice-correction.json b/modules/invoiceOut/back/models/invoice-correction.json index 48bd172a6..7c6f01571 100644 --- a/modules/invoiceOut/back/models/invoice-correction.json +++ b/modules/invoiceOut/back/models/invoice-correction.json @@ -18,7 +18,7 @@ "cplusRectificationTypeFk": { "type": "number" }, - "cplusInvoiceType477Fk": { + "siiTypeInvoiceOutFk": { "type": "number" }, "invoiceCorrectionTypeFk": { diff --git a/modules/invoiceOut/back/models/sii-type-invoice-out.json b/modules/invoiceOut/back/models/sii-type-invoice-out.json index 89f01bd74..06934b1cc 100644 --- a/modules/invoiceOut/back/models/sii-type-invoice-out.json +++ b/modules/invoiceOut/back/models/sii-type-invoice-out.json @@ -12,9 +12,6 @@ "type": "number", "description": "Identifier" }, - "code": { - "type": "string" - }, "description": { "type": "string" } From 0baa9c5a983ad2660e66ef0570cde9e74d05deb7 Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 9 Nov 2023 14:34:53 +0100 Subject: [PATCH 325/427] ref #5914 fix summary --- modules/invoiceOut/front/descriptor-menu/index.html | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/invoiceOut/front/descriptor-menu/index.html b/modules/invoiceOut/front/descriptor-menu/index.html index d7537bc0a..09bb4a2ab 100644 --- a/modules/invoiceOut/front/descriptor-menu/index.html +++ b/modules/invoiceOut/front/descriptor-menu/index.html @@ -7,7 +7,7 @@ + data="siiTypeInvoiceOut"> Date: Thu, 9 Nov 2023 15:00:49 +0100 Subject: [PATCH 326/427] ref #5835 due day new and fixtures --- db/dump/fixtures.sql | 4 +- .../back/methods/invoice-in-due-day/new.js | 37 +++++++++++++++++++ .../back/models/invoice-in-due-day.js | 3 ++ 3 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 modules/invoiceIn/back/methods/invoice-in-due-day/new.js create mode 100644 modules/invoiceIn/back/models/invoice-in-due-day.js diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index d70279e7d..f57b302f3 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -2880,7 +2880,9 @@ INSERT INTO `vn`.`report` (`id`, `name`, `paperSizeFk`, `method`) INSERT INTO `vn`.`payDemDetail` (`id`, `detail`) VALUES - (1, 1); + (1, 1), + (2, 20), + (7, 1); INSERT INTO `vn`.`workerConfig` (`id`, `businessUpdated`, `roleFk`, `payMethodFk`, `businessTypeFk`) VALUES diff --git a/modules/invoiceIn/back/methods/invoice-in-due-day/new.js b/modules/invoiceIn/back/methods/invoice-in-due-day/new.js new file mode 100644 index 000000000..37d2f6d05 --- /dev/null +++ b/modules/invoiceIn/back/methods/invoice-in-due-day/new.js @@ -0,0 +1,37 @@ +module.exports = Self => { + Self.remoteMethodCtx('new', { + description: 'Creates a new invoiceIn due day', + accessType: 'WRITE', + accepts: { + arg: 'id', + type: 'number', + required: true, + description: 'The invoiceIn id', + }, + http: { + path: '/new', + verb: 'POST' + } + }); + + Self.new = async(ctx, id, options) => { + let tx; + const myOptions = {userId: ctx.req.accessToken.userId}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + try { + await Self.rawSql(`CALL vn.invoiceInDueDay_calculate(?)`, [id], myOptions); + if (tx) await tx.commit(); + } catch (e) { + if (tx) await tx.rollback(); + throw e; + } + }; +}; diff --git a/modules/invoiceIn/back/models/invoice-in-due-day.js b/modules/invoiceIn/back/models/invoice-in-due-day.js new file mode 100644 index 000000000..2375c6566 --- /dev/null +++ b/modules/invoiceIn/back/models/invoice-in-due-day.js @@ -0,0 +1,3 @@ +module.exports = Self => { + require('../methods/invoice-in-due-day/new')(Self); +}; From fd142b9f23ba6ef4ab4adaed693f47e95eed476f Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 9 Nov 2023 15:05:36 +0100 Subject: [PATCH 327/427] refs #5881 warmFix: roleSync --- db/changes/234602/00-roleSync.sql | 1 + 1 file changed, 1 insertion(+) create mode 100644 db/changes/234602/00-roleSync.sql diff --git a/db/changes/234602/00-roleSync.sql b/db/changes/234602/00-roleSync.sql new file mode 100644 index 000000000..7ce277748 --- /dev/null +++ b/db/changes/234602/00-roleSync.sql @@ -0,0 +1 @@ +CALL `account`.`role_sync`(); From 513562955b1d7b11aef24d4e348f83250c70490b Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 9 Nov 2023 15:53:41 +0100 Subject: [PATCH 328/427] ref #5835 test back --- .../invoice-in-due-day/specs/new.spec.js | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 modules/invoiceIn/back/methods/invoice-in-due-day/specs/new.spec.js diff --git a/modules/invoiceIn/back/methods/invoice-in-due-day/specs/new.spec.js b/modules/invoiceIn/back/methods/invoice-in-due-day/specs/new.spec.js new file mode 100644 index 000000000..f2f04b993 --- /dev/null +++ b/modules/invoiceIn/back/methods/invoice-in-due-day/specs/new.spec.js @@ -0,0 +1,51 @@ +const LoopBackContext = require('loopback-context'); +const models = require('vn-loopback/server/server').models; + +describe('invoiceInDueDay new()', () => { + beforeAll(async() => { + const activeCtx = { + accessToken: {userId: 9}, + http: { + req: { + headers: {origin: 'http://localhost'} + } + } + }; + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ + active: activeCtx + }); + }); + + it('should correctly create a new due day', async() => { + const userId = 9; + const invoiceInFk = 6; + + const ctx = { + req: { + + accessToken: {userId: userId}, + headers: {origin: 'http://localhost:5000'}, + } + }; + + const tx = await models.InvoiceIn.beginTransaction({}); + const options = {transaction: tx}; + + try { + await models.InvoiceInDueDay.destroyAll({ + invoiceInFk + }, options); + + await models.InvoiceInDueDay.new(ctx, invoiceInFk, options); + + const result = await models.InvoiceInDueDay.find({where: {invoiceInFk}}, options); + + expect(result).toBeDefined(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); +}); From 8d94a94e14f1396cd79737d0304c1af1b98ff7d0 Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 9 Nov 2023 15:56:50 +0100 Subject: [PATCH 329/427] ref #5914 fix test back --- .../back/methods/invoiceOut/specs/transferinvoice.spec.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js index 876948419..800a4ea83 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js @@ -2,7 +2,7 @@ const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); -fdescribe('InvoiceOut tranferInvoice()', () => { +describe('InvoiceOut tranferInvoice()', () => { const activeCtx = { accessToken: {userId: 5}, http: { @@ -19,7 +19,7 @@ fdescribe('InvoiceOut tranferInvoice()', () => { }); }); - fit('should return the id of the created issued invoice', async() => { + it('should return the id of the created issued invoice', async() => { const tx = await models.InvoiceOut.beginTransaction({}); const options = {transaction: tx}; const args = { From 2eacf7391ea1d03fdf441277b0c73ac37ddf54ce Mon Sep 17 00:00:00 2001 From: alexm Date: Fri, 10 Nov 2023 08:46:49 +0100 Subject: [PATCH 330/427] refs #6335 fix(db_ticket_canAdvance): not use unnecessary ifnulls --- CHANGELOG.md | 12 ++++++------ .../00-ticket_canAdvance_update.sql | 18 +++++++++--------- .../back/methods/ticket/componentUpdate.js | 8 ++++---- modules/ticket/front/advance/index.js | 4 ++-- 4 files changed, 21 insertions(+), 21 deletions(-) rename db/changes/{234601 => 234801}/00-ticket_canAdvance_update.sql (90%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 09379e91c..08a62f044 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,12 +7,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [2348.01] - 2023-11-30 -### Added -### Changed -### Fixed - -## [2346.01] - 2023-11-16 - ### Added - (Ticket -> Adelantar) Permite mover lineas sin generar negativos - (Ticket -> Adelantar) Permite modificar la fecha de los tickets @@ -22,6 +16,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - (Ticket -> RocketChat) Arreglada detección de cambios +## [2346.01] - 2023-11-16 + +### Added +### Changed +### Fixed + ## [2342.01] - 2023-11-02 diff --git a/db/changes/234601/00-ticket_canAdvance_update.sql b/db/changes/234801/00-ticket_canAdvance_update.sql similarity index 90% rename from db/changes/234601/00-ticket_canAdvance_update.sql rename to db/changes/234801/00-ticket_canAdvance_update.sql index 272a0618a..afe0a4dc6 100644 --- a/db/changes/234601/00-ticket_canAdvance_update.sql +++ b/db/changes/234801/00-ticket_canAdvance_update.sql @@ -13,8 +13,7 @@ BEGIN SELECT inventoried INTO vDateInventory FROM config; - DROP TEMPORARY TABLE IF EXISTS tmp.stock; - CREATE TEMPORARY TABLE tmp.stock + CREATE OR REPLACE TEMPORARY TABLE tmp.stock (itemFk INT PRIMARY KEY, amount INT) ENGINE = MEMORY; @@ -60,22 +59,23 @@ BEGIN dest.totalWithVat, origin.totalWithVat futureTotalWithVat, dest.agency, + dest.agencyModeFk, origin.futureAgency, + origin.agencyModeFk futureAgencyModeFk, dest.lines, dest.liters, origin.futureLines - origin.hasStock AS notMovableLines, (origin.futureLines = origin.hasStock) AS isFullMovable, + dest.zoneFk, origin.futureZoneFk, origin.futureZoneName, origin.classColor futureClassColor, dest.classColor, - IFNULL(dest.clientFk, origin.clientFk) clientFk, + origin.clientFk futureClientFk, + origin.addressFk futureAddressFk, + origin.warehouseFk futureWarehouseFk, + origin.companyFk futureCompanyFk, IFNULL(dest.nickname, origin.nickname) nickname, - IFNULL(dest.addressFk, origin.addressFk) addressFk, - IFNULL(dest.zoneFk, origin.futureZoneFk) zoneFk, - IFNULL(dest.warehouseFk, origin.warehouseFk) warehouseFk, - IFNULL(dest.companyFk, origin.companyFk) companyFk, - IFNULL(dest.agencyModeFk, origin.agencyModeFk) agencyModeFk, dest.landed FROM ( SELECT @@ -145,7 +145,7 @@ BEGIN AND st.order <= 5 GROUP BY t.id ) dest ON dest.addressFk = origin.addressFk - WHERE origin.hasStock != 0; + WHERE origin.hasStock; DROP TEMPORARY TABLE tmp.stock; END$$ diff --git a/modules/ticket/back/methods/ticket/componentUpdate.js b/modules/ticket/back/methods/ticket/componentUpdate.js index d8d1163da..3acd68cfb 100644 --- a/modules/ticket/back/methods/ticket/componentUpdate.js +++ b/modules/ticket/back/methods/ticket/componentUpdate.js @@ -196,7 +196,7 @@ module.exports = Self => { ] }, myOptions); const originalTicket = JSON.parse(JSON.stringify(ticketToChange)); - const ticketChages = { + const ticketChanges = { clientFk: args.clientFk, nickname: args.nickname, agencyModeFk: args.agencyModeFk, @@ -211,13 +211,13 @@ module.exports = Self => { let response; if (args.keepPrice) { - ticketChages.routeFk = null; - response = await ticketToChange.updateAttributes(ticketChages, myOptions); + ticketChanges.routeFk = null; + response = await ticketToChange.updateAttributes(ticketChanges, myOptions); } else { const hasToBeUnrouted = true; response = await Self.rawSql( 'CALL vn.ticket_componentMakeUpdate(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', - [args.id].concat(Object.values(ticketChages), [hasToBeUnrouted, args.option]), + [args.id].concat(Object.values(ticketChanges), [hasToBeUnrouted, args.option]), myOptions ); } diff --git a/modules/ticket/front/advance/index.js b/modules/ticket/front/advance/index.js index 5ab663256..fb539311f 100644 --- a/modules/ticket/front/advance/index.js +++ b/modules/ticket/front/advance/index.js @@ -215,9 +215,9 @@ export default class Controller extends Section { const params = { clientFk: ticket.clientFk, nickname: ticket.nickname, - agencyModeFk: ticket.agencyModeFk, + agencyModeFk: ticket.agencyModeFk ?? ticket.futureAgencyModeFk, addressFk: ticket.addressFk, - zoneFk: ticket.zoneFk, + zoneFk: ticket.zoneFk ?? ticket.futureZoneFk, warehouseFk: ticket.warehouseFk, companyFk: ticket.companyFk, shipped: this.$.model.userParams.dateToAdvance, From 69255fe2fcacd1dc716b26dcf0c60b8face6882d Mon Sep 17 00:00:00 2001 From: alexm Date: Fri, 10 Nov 2023 10:58:58 +0100 Subject: [PATCH 331/427] 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 a1c8bba4a56e3d0d2907755e6060be55237f24fd Mon Sep 17 00:00:00 2001 From: carlossa Date: Fri, 10 Nov 2023 11:29:18 +0100 Subject: [PATCH 332/427] hotfix addressId --- modules/ticket/back/methods/ticket/closure.js | 289 +++++++++--------- 1 file changed, 145 insertions(+), 144 deletions(-) diff --git a/modules/ticket/back/methods/ticket/closure.js b/modules/ticket/back/methods/ticket/closure.js index 9f9aec9bd..1d04679d3 100644 --- a/modules/ticket/back/methods/ticket/closure.js +++ b/modules/ticket/back/methods/ticket/closure.js @@ -5,177 +5,178 @@ const config = require('vn-print/core/config'); const storage = require('vn-print/core/storage'); module.exports = async function(ctx, Self, tickets, reqArgs = {}) { - const userId = ctx.req.accessToken.userId; - if (tickets.length == 0) return; + const userId = ctx.req.accessToken.userId; + if (tickets.length == 0) return; - const failedtickets = []; - for (const ticket of tickets) { - try { - await Self.rawSql(`CALL vn.ticket_closeByTicket(?)`, [ticket.id], {userId}); + const failedtickets = []; + for (const ticket of tickets) { + try { + await Self.rawSql(`CALL vn.ticket_closeByTicket(?)`, [ticket.id], {userId}); - const [invoiceOut] = await Self.rawSql(` - SELECT io.id, io.ref, io.serial, cny.code companyCode, io.issued - FROM ticket t - JOIN invoiceOut io ON io.ref = t.refFk - JOIN company cny ON cny.id = io.companyFk - WHERE t.id = ? - `, [ticket.id]); + const [invoiceOut] = await Self.rawSql(` + SELECT io.id, io.ref, io.serial, cny.code companyCode, io.issued + FROM ticket t + JOIN invoiceOut io ON io.ref = t.refFk + JOIN company cny ON cny.id = io.companyFk + WHERE t.id = ? + `, [ticket.id]); - const mailOptions = { - overrideAttachments: true, - attachments: [] - }; + const mailOptions = { + overrideAttachments: true, + attachments: [] + }; - const isToBeMailed = ticket.recipient && ticket.salesPersonFk && ticket.isToBeMailed; + const isToBeMailed = ticket.recipient && ticket.salesPersonFk && ticket.isToBeMailed; - if (invoiceOut) { - const args = { - reference: invoiceOut.ref, - recipientId: ticket.clientFk, - recipient: ticket.recipient, - replyTo: ticket.salesPersonEmail - }; + if (invoiceOut) { + const args = { + reference: invoiceOut.ref, + recipientId: ticket.clientFk, + recipient: ticket.recipient, + replyTo: ticket.salesPersonEmail + }; - const invoiceReport = new Report('invoice', args); - const stream = await invoiceReport.toPdfStream(); + const invoiceReport = new Report('invoice', args); + const stream = await invoiceReport.toPdfStream(); - const issued = invoiceOut.issued; - const year = issued.getFullYear().toString(); - const month = (issued.getMonth() + 1).toString(); - const day = issued.getDate().toString(); + const issued = invoiceOut.issued; + const year = issued.getFullYear().toString(); + const month = (issued.getMonth() + 1).toString(); + const day = issued.getDate().toString(); - const fileName = `${year}${invoiceOut.ref}.pdf`; + const fileName = `${year}${invoiceOut.ref}.pdf`; - // Store invoice - await storage.write(stream, { - type: 'invoice', - path: `${year}/${month}/${day}`, - fileName: fileName - }); + // Store invoice + await storage.write(stream, { + type: 'invoice', + path: `${year}/${month}/${day}`, + fileName: fileName + }); - await Self.rawSql('UPDATE invoiceOut SET hasPdf = true WHERE id = ?', [invoiceOut.id], {userId}); + await Self.rawSql('UPDATE invoiceOut SET hasPdf = true WHERE id = ?', [invoiceOut.id], {userId}); - if (isToBeMailed) { - const invoiceAttachment = { - filename: fileName, - content: stream - }; + if (isToBeMailed) { + const invoiceAttachment = { + filename: fileName, + content: stream + }; - if (invoiceOut.serial == 'E' && invoiceOut.companyCode == 'VNL') { - const exportation = new Report('exportation', args); - const stream = await exportation.toPdfStream(); - const fileName = `CITES-${invoiceOut.ref}.pdf`; + if (invoiceOut.serial == 'E' && invoiceOut.companyCode == 'VNL') { + const exportation = new Report('exportation', args); + const stream = await exportation.toPdfStream(); + const fileName = `CITES-${invoiceOut.ref}.pdf`; - mailOptions.attachments.push({ - filename: fileName, - content: stream - }); - } + mailOptions.attachments.push({ + filename: fileName, + content: stream + }); + } - mailOptions.attachments.push(invoiceAttachment); + mailOptions.attachments.push(invoiceAttachment); - const email = new Email('invoice', args); - await email.send(mailOptions); - } - } else if (isToBeMailed) { - const args = { - id: ticket.id, - recipientId: ticket.clientFk, - recipient: ticket.recipient, - replyTo: ticket.salesPersonEmail - }; + const email = new Email('invoice', args); + await email.send(mailOptions); + } + } else if (isToBeMailed) { + const args = { + id: ticket.id, + recipientId: ticket.clientFk, + recipient: ticket.recipient, + replyTo: ticket.salesPersonEmail + }; - const email = new Email('delivery-note-link', args); - await email.send(); - } + const email = new Email('delivery-note-link', args); + await email.send(); + } - // Incoterms authorization - const [{firstOrder}] = await Self.rawSql(` - SELECT COUNT(*) as firstOrder - FROM ticket t - JOIN client c ON c.id = t.clientFk - WHERE t.clientFk = ? - AND NOT t.isDeleted - AND c.isVies - `, [ticket.clientFk]); + // Incoterms authorization + const [{firstOrder}] = await Self.rawSql(` + SELECT COUNT(*) as firstOrder + FROM ticket t + JOIN client c ON c.id = t.clientFk + WHERE t.clientFk = ? + AND NOT t.isDeleted + AND c.isVies + `, [ticket.clientFk]); - if (firstOrder == 1) { - const args = { - id: ticket.clientFk, - companyId: ticket.companyFk, - recipientId: ticket.clientFk, - recipient: ticket.recipient, - replyTo: ticket.salesPersonEmail - }; + if (firstOrder == 1) { + const args = { + id: ticket.clientFk, + companyId: ticket.companyFk, + recipientId: ticket.clientFk, + recipient: ticket.recipient, + replyTo: ticket.salesPersonEmail, + addressId: ticket.addressFk + }; - const email = new Email('incoterms-authorization', args); - await email.send(); + const email = new Email('incoterms-authorization', args); + await email.send(); - const [sample] = await Self.rawSql( - `SELECT id - FROM sample - WHERE code = 'incoterms-authorization' - `); + const [sample] = await Self.rawSql( + `SELECT id + FROM sample + WHERE code = 'incoterms-authorization' + `); - await Self.rawSql(` - INSERT INTO clientSample (clientFk, typeFk, companyFk) VALUES(?, ?, ?) - `, [ticket.clientFk, sample.id, ticket.companyFk], {userId}); - }; - } catch (error) { - // Domain not found - if (error.responseCode == 450) - return invalidEmail(ticket); + await Self.rawSql(` + INSERT INTO clientSample (clientFk, typeFk, companyFk) VALUES(?, ?, ?) + `, [ticket.clientFk, sample.id, ticket.companyFk], {userId}); + } + } catch (error) { + // Domain not found + if (error.responseCode == 450) + return invalidEmail(ticket); - // Save tickets on a list of failed ids - failedtickets.push({ - id: ticket.id, - stacktrace: error - }); - } - } + // Save tickets on a list of failed ids + failedtickets.push({ + id: ticket.id, + stacktrace: error + }); + } + } - // Send email with failed tickets - if (failedtickets.length > 0) { - let body = 'This following tickets have failed:

'; + // Send email with failed tickets + if (failedtickets.length > 0) { + let body = 'This following tickets have failed:

'; - for (const ticket of failedtickets) { - body += `Ticket: ${ticket.id} -
${ticket.stacktrace}

`; - } + for (const ticket of failedtickets) { + body += `Ticket: ${ticket.id} +
${ticket.stacktrace}

`; + } - smtp.send({ - to: config.app.reportEmail, - subject: '[API] Nightly ticket closure report', - html: body - }); - } + smtp.send({ + to: config.app.reportEmail, + subject: '[API] Nightly ticket closure report', + html: body + }); + } - async function invalidEmail(ticket) { - await Self.rawSql(`UPDATE client SET email = NULL WHERE id = ?`, [ - ticket.clientFk - ], {userId}); + async function invalidEmail(ticket) { + await Self.rawSql(`UPDATE client SET email = NULL WHERE id = ?`, [ + ticket.clientFk + ], {userId}); - const oldInstance = `{"email": "${ticket.recipient}"}`; - const newInstance = `{"email": ""}`; - await Self.rawSql(` - INSERT INTO clientLog (originFk, userFk, action, changedModel, oldInstance, newInstance) - VALUES (?, NULL, 'UPDATE', 'Client', ?, ?)`, [ - ticket.clientFk, - oldInstance, - newInstance - ], {userId}); + const oldInstance = `{"email": "${ticket.recipient}"}`; + const newInstance = `{"email": ""}`; + await Self.rawSql(` + INSERT INTO clientLog (originFk, userFk, action, changedModel, oldInstance, newInstance) + VALUES (?, NULL, 'UPDATE', 'Client', ?, ?)`, [ + ticket.clientFk, + oldInstance, + newInstance + ], {userId}); - const body = `No se ha podido enviar el albarán ${ticket.id} - al cliente ${ticket.clientFk} - ${ticket.clientName} - porque la dirección de email "${ticket.recipient}" no es correcta - o no está disponible.

- Para evitar que se repita este error, se ha eliminado la dirección de email de la ficha del cliente. - Actualiza la dirección de email con una correcta.`; + const body = `No se ha podido enviar el albarán ${ticket.id} + al cliente ${ticket.clientFk} - ${ticket.clientName} + porque la dirección de email "${ticket.recipient}" no es correcta + o no está disponible.

+ Para evitar que se repita este error, se ha eliminado la dirección de email de la ficha del cliente. + Actualiza la dirección de email con una correcta.`; - smtp.send({ - to: ticket.salesPersonEmail, - subject: 'No se ha podido enviar el albarán', - html: body - }); - } + smtp.send({ + to: ticket.salesPersonEmail, + subject: 'No se ha podido enviar el albarán', + html: body + }); + } }; From 9f92bc4b4c5e72bc63385605a115f6d464416dac Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 10 Nov 2023 11:43:42 +0100 Subject: [PATCH 333/427] fix: refs #6023 Rollback privileges.js --- back/methods/vn-user/privileges.js | 66 ++++++++++++------------------ 1 file changed, 27 insertions(+), 39 deletions(-) diff --git a/back/methods/vn-user/privileges.js b/back/methods/vn-user/privileges.js index 0520fd5c2..08cfaaae8 100644 --- a/back/methods/vn-user/privileges.js +++ b/back/methods/vn-user/privileges.js @@ -40,56 +40,44 @@ module.exports = Self => { const userId = ctx.req.accessToken.userId; const myOptions = {}; - let tx; if (typeof options == 'object') Object.assign(myOptions, options); - if (!myOptions.transaction) { - tx = await Self.beginTransaction({}); - myOptions.transaction = tx; - }; + const user = await Self.findById(userId, {fields: ['hasGrant']}, myOptions); - try { - const user = await Self.findById(userId, {fields: ['hasGrant']}, myOptions); - - const userToUpdate = await Self.findById(id, { - fields: ['id', 'name', 'hasGrant', 'roleFk', 'password', 'email'], - include: { - relation: 'role', - scope: { - fields: ['name'] - } + const userToUpdate = await Self.findById(id, { + fields: ['id', 'name', 'hasGrant', 'roleFk', 'password', 'email'], + include: { + relation: 'role', + scope: { + fields: ['name'] } - }, myOptions); + } + }, myOptions); - if (!user.hasGrant) - throw new UserError(`You don't have grant privilege`); + if (!user.hasGrant) + throw new UserError(`You don't have grant privilege`); - const hasRoleFromUser = await Self.hasRole(userId, userToUpdate.role().name, myOptions); + const hasRoleFromUser = await Self.hasRole(userId, userToUpdate.role().name, myOptions); - if (!hasRoleFromUser) + if (!hasRoleFromUser) + throw new UserError(`You don't own the role and you can't assign it to another user`); + + if (hasGrant != null) + userToUpdate.hasGrant = hasGrant; + + if (roleFk) { + const role = await models.Role.findById(roleFk, {fields: ['name']}, myOptions); + const hasRole = await Self.hasRole(userId, role.name, myOptions); + + if (!hasRole) throw new UserError(`You don't own the role and you can't assign it to another user`); - if (hasGrant != null) - userToUpdate.hasGrant = hasGrant; + userToUpdate.roleFk = roleFk; + } - if (roleFk) { - const role = await models.Role.findById(roleFk, {fields: ['name']}, myOptions); - const hasRole = await Self.hasRole(userId, role.name, myOptions); - - if (!hasRole) - throw new UserError(`You don't own the role and you can't assign it to another user`); - - userToUpdate.roleFk = roleFk; - } - - await userToUpdate.save(myOptions); - await models.Account.sync(userToUpdate.name, null, null, myOptions); - if (tx) await tx.commit(); - } catch (err) { - if (tx) await tx.rollback(); - throw err; - }; + await userToUpdate.save(userToUpdate); + await models.Account.sync(userToUpdate.name); }; }; From b7da144967c5c34cdcd937ae39169fcae8001df1 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 10 Nov 2023 11:55:37 +0100 Subject: [PATCH 334/427] feat: refs #6023 Added SELECT FOR UPDATE --- modules/account/back/methods/account/sync.js | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/modules/account/back/methods/account/sync.js b/modules/account/back/methods/account/sync.js index c4f9cb181..8548e71f3 100644 --- a/modules/account/back/methods/account/sync.js +++ b/modules/account/back/methods/account/sync.js @@ -48,6 +48,13 @@ module.exports = Self => { if (tx) await tx.rollback(); return; } + + await Self.rawSql(` + SELECT id + FROM account.user + WHERE id = ? + FOR UPDATE`, [user.id], myOptions); + await models.AccountConfig.syncUser(userName, password); await models.UserSync.destroyById(userName, myOptions); if (tx) await tx.commit(); From 59d2da24eb6d5329b0700453abaabb3215105f79 Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 13 Nov 2023 09:36:20 +0100 Subject: [PATCH 335/427] 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 1a66987cd0ff298ff392ad27d43a81bed410eb14 Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 13 Nov 2023 12:26:31 +0100 Subject: [PATCH 336/427] refs #5979 fix(vn-user): resetPassword url --- back/models/vn-user.js | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/back/models/vn-user.js b/back/models/vn-user.js index 970497e4e..712ed7d16 100644 --- a/back/models/vn-user.js +++ b/back/models/vn-user.js @@ -92,7 +92,11 @@ module.exports = function(Self) { }; Self.on('resetPasswordRequest', async function(info) { - const url = await Self.app.models.Url.getUrl(); + const loopBackContext = LoopBackContext.getCurrentContext(); + const httpCtx = {req: loopBackContext.active}; + const httpRequest = httpCtx.req.http.req; + const headers = httpRequest.headers; + const origin = headers.origin; const defaultHash = '/reset-password?access_token=$token$'; const recoverHashes = { @@ -108,7 +112,7 @@ module.exports = function(Self) { const params = { recipient: info.email, lang: user.lang, - url: url.slice(0, -1) + recoverHash + url: origin + '/#!' + recoverHash }; const options = Object.assign({}, info.options); From 47d85c4c616f7decd460e4f8a3fca755f9e2587f Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 13 Nov 2023 12:54:02 +0100 Subject: [PATCH 337/427] refs #6335 fix: remove unnecessary translations --- loopback/locale/en.json | 4 +--- loopback/locale/es.json | 2 -- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/loopback/locale/en.json b/loopback/locale/en.json index 9305c7f09..82cf5b40b 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -196,7 +196,5 @@ "Negative basis of tickets: 23": "Negative basis of tickets: 23", "Booking completed": "Booking complete", "The ticket is in preparation": "The ticket [{{ticketId}}]({{{ticketUrl}}}) of the sales person {{salesPersonId}} is in preparation", - "You can only add negative amounts in refund tickets": "You can only add negative amounts in refund tickets", - "newTicket": "New ticket", - "keepPrice": "Keep prices" + "You can only add negative amounts in refund tickets": "You can only add negative amounts in refund tickets" } diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 933a35468..0ee6194e4 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -225,8 +225,6 @@ "reference duplicated": "Referencia duplicada", "This ticket is already a refund": "Este ticket ya es un abono", "isWithoutNegatives": "Sin negativos", - "newTicket": "Nuevo ticket", - "keepPrice": "Mantener precios", "routeFk": "routeFk", "Can't change the password of another worker": "No se puede cambiar la contraseña de otro trabajador", "No hay un contrato en vigor": "No hay un contrato en vigor", From cce61ae8ccf9b7d747a0f934a187b9adcfb8bc59 Mon Sep 17 00:00:00 2001 From: alexm Date: Tue, 14 Nov 2023 09:17:46 +0100 Subject: [PATCH 338/427] 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 ); From aec1c9d4475bfb0605145b3617af9acf4ec522f2 Mon Sep 17 00:00:00 2001 From: alexm Date: Tue, 14 Nov 2023 09:54:07 +0100 Subject: [PATCH 339/427] fix: correct align --- modules/ticket/back/methods/ticket/closure.js | 288 +++++++++--------- 1 file changed, 144 insertions(+), 144 deletions(-) diff --git a/modules/ticket/back/methods/ticket/closure.js b/modules/ticket/back/methods/ticket/closure.js index 9f9aec9bd..7a2825a4d 100644 --- a/modules/ticket/back/methods/ticket/closure.js +++ b/modules/ticket/back/methods/ticket/closure.js @@ -5,177 +5,177 @@ const config = require('vn-print/core/config'); const storage = require('vn-print/core/storage'); module.exports = async function(ctx, Self, tickets, reqArgs = {}) { - const userId = ctx.req.accessToken.userId; - if (tickets.length == 0) return; + const userId = ctx.req.accessToken.userId; + if (tickets.length == 0) return; - const failedtickets = []; - for (const ticket of tickets) { - try { - await Self.rawSql(`CALL vn.ticket_closeByTicket(?)`, [ticket.id], {userId}); + const failedtickets = []; + for (const ticket of tickets) { + try { + await Self.rawSql(`CALL vn.ticket_closeByTicket(?)`, [ticket.id], {userId}); - const [invoiceOut] = await Self.rawSql(` - SELECT io.id, io.ref, io.serial, cny.code companyCode, io.issued - FROM ticket t - JOIN invoiceOut io ON io.ref = t.refFk - JOIN company cny ON cny.id = io.companyFk - WHERE t.id = ? - `, [ticket.id]); + const [invoiceOut] = await Self.rawSql(` + SELECT io.id, io.ref, io.serial, cny.code companyCode, io.issued + FROM ticket t + JOIN invoiceOut io ON io.ref = t.refFk + JOIN company cny ON cny.id = io.companyFk + WHERE t.id = ? + `, [ticket.id]); - const mailOptions = { - overrideAttachments: true, - attachments: [] - }; + const mailOptions = { + overrideAttachments: true, + attachments: [] + }; - const isToBeMailed = ticket.recipient && ticket.salesPersonFk && ticket.isToBeMailed; + const isToBeMailed = ticket.recipient && ticket.salesPersonFk && ticket.isToBeMailed; - if (invoiceOut) { - const args = { - reference: invoiceOut.ref, - recipientId: ticket.clientFk, - recipient: ticket.recipient, - replyTo: ticket.salesPersonEmail - }; + if (invoiceOut) { + const args = { + reference: invoiceOut.ref, + recipientId: ticket.clientFk, + recipient: ticket.recipient, + replyTo: ticket.salesPersonEmail + }; - const invoiceReport = new Report('invoice', args); - const stream = await invoiceReport.toPdfStream(); + const invoiceReport = new Report('invoice', args); + const stream = await invoiceReport.toPdfStream(); - const issued = invoiceOut.issued; - const year = issued.getFullYear().toString(); - const month = (issued.getMonth() + 1).toString(); - const day = issued.getDate().toString(); + const issued = invoiceOut.issued; + const year = issued.getFullYear().toString(); + const month = (issued.getMonth() + 1).toString(); + const day = issued.getDate().toString(); - const fileName = `${year}${invoiceOut.ref}.pdf`; + const fileName = `${year}${invoiceOut.ref}.pdf`; - // Store invoice - await storage.write(stream, { - type: 'invoice', - path: `${year}/${month}/${day}`, - fileName: fileName - }); + // Store invoice + await storage.write(stream, { + type: 'invoice', + path: `${year}/${month}/${day}`, + fileName: fileName + }); - await Self.rawSql('UPDATE invoiceOut SET hasPdf = true WHERE id = ?', [invoiceOut.id], {userId}); + await Self.rawSql('UPDATE invoiceOut SET hasPdf = true WHERE id = ?', [invoiceOut.id], {userId}); - if (isToBeMailed) { - const invoiceAttachment = { - filename: fileName, - content: stream - }; + if (isToBeMailed) { + const invoiceAttachment = { + filename: fileName, + content: stream + }; - if (invoiceOut.serial == 'E' && invoiceOut.companyCode == 'VNL') { - const exportation = new Report('exportation', args); - const stream = await exportation.toPdfStream(); - const fileName = `CITES-${invoiceOut.ref}.pdf`; + if (invoiceOut.serial == 'E' && invoiceOut.companyCode == 'VNL') { + const exportation = new Report('exportation', args); + const stream = await exportation.toPdfStream(); + const fileName = `CITES-${invoiceOut.ref}.pdf`; - mailOptions.attachments.push({ - filename: fileName, - content: stream - }); - } + mailOptions.attachments.push({ + filename: fileName, + content: stream + }); + } - mailOptions.attachments.push(invoiceAttachment); + mailOptions.attachments.push(invoiceAttachment); - const email = new Email('invoice', args); - await email.send(mailOptions); - } - } else if (isToBeMailed) { - const args = { - id: ticket.id, - recipientId: ticket.clientFk, - recipient: ticket.recipient, - replyTo: ticket.salesPersonEmail - }; + const email = new Email('invoice', args); + await email.send(mailOptions); + } + } else if (isToBeMailed) { + const args = { + id: ticket.id, + recipientId: ticket.clientFk, + recipient: ticket.recipient, + replyTo: ticket.salesPersonEmail + }; - const email = new Email('delivery-note-link', args); - await email.send(); - } + const email = new Email('delivery-note-link', args); + await email.send(); + } - // Incoterms authorization - const [{firstOrder}] = await Self.rawSql(` - SELECT COUNT(*) as firstOrder - FROM ticket t - JOIN client c ON c.id = t.clientFk - WHERE t.clientFk = ? - AND NOT t.isDeleted - AND c.isVies - `, [ticket.clientFk]); + // Incoterms authorization + const [{firstOrder}] = await Self.rawSql(` + SELECT COUNT(*) as firstOrder + FROM ticket t + JOIN client c ON c.id = t.clientFk + WHERE t.clientFk = ? + AND NOT t.isDeleted + AND c.isVies + `, [ticket.clientFk]); - if (firstOrder == 1) { - const args = { - id: ticket.clientFk, - companyId: ticket.companyFk, - recipientId: ticket.clientFk, - recipient: ticket.recipient, - replyTo: ticket.salesPersonEmail - }; + if (firstOrder == 1) { + const args = { + id: ticket.clientFk, + companyId: ticket.companyFk, + recipientId: ticket.clientFk, + recipient: ticket.recipient, + replyTo: ticket.salesPersonEmail + }; - const email = new Email('incoterms-authorization', args); - await email.send(); + const email = new Email('incoterms-authorization', args); + await email.send(); - const [sample] = await Self.rawSql( - `SELECT id - FROM sample - WHERE code = 'incoterms-authorization' - `); + const [sample] = await Self.rawSql( + `SELECT id + FROM sample + WHERE code = 'incoterms-authorization' + `); - await Self.rawSql(` - INSERT INTO clientSample (clientFk, typeFk, companyFk) VALUES(?, ?, ?) - `, [ticket.clientFk, sample.id, ticket.companyFk], {userId}); - }; - } catch (error) { - // Domain not found - if (error.responseCode == 450) - return invalidEmail(ticket); + await Self.rawSql(` + INSERT INTO clientSample (clientFk, typeFk, companyFk) VALUES(?, ?, ?) + `, [ticket.clientFk, sample.id, ticket.companyFk], {userId}); + } + } catch (error) { + // Domain not found + if (error.responseCode == 450) + return invalidEmail(ticket); - // Save tickets on a list of failed ids - failedtickets.push({ - id: ticket.id, - stacktrace: error - }); - } - } + // Save tickets on a list of failed ids + failedtickets.push({ + id: ticket.id, + stacktrace: error + }); + } + } - // Send email with failed tickets - if (failedtickets.length > 0) { - let body = 'This following tickets have failed:

'; + // Send email with failed tickets + if (failedtickets.length > 0) { + let body = 'This following tickets have failed:

'; - for (const ticket of failedtickets) { - body += `Ticket: ${ticket.id} -
${ticket.stacktrace}

`; - } + for (const ticket of failedtickets) { + body += `Ticket: ${ticket.id} +
${ticket.stacktrace}

`; + } - smtp.send({ - to: config.app.reportEmail, - subject: '[API] Nightly ticket closure report', - html: body - }); - } + smtp.send({ + to: config.app.reportEmail, + subject: '[API] Nightly ticket closure report', + html: body + }); + } - async function invalidEmail(ticket) { - await Self.rawSql(`UPDATE client SET email = NULL WHERE id = ?`, [ - ticket.clientFk - ], {userId}); + async function invalidEmail(ticket) { + await Self.rawSql(`UPDATE client SET email = NULL WHERE id = ?`, [ + ticket.clientFk + ], {userId}); - const oldInstance = `{"email": "${ticket.recipient}"}`; - const newInstance = `{"email": ""}`; - await Self.rawSql(` - INSERT INTO clientLog (originFk, userFk, action, changedModel, oldInstance, newInstance) - VALUES (?, NULL, 'UPDATE', 'Client', ?, ?)`, [ - ticket.clientFk, - oldInstance, - newInstance - ], {userId}); + const oldInstance = `{"email": "${ticket.recipient}"}`; + const newInstance = `{"email": ""}`; + await Self.rawSql(` + INSERT INTO clientLog (originFk, userFk, action, changedModel, oldInstance, newInstance) + VALUES (?, NULL, 'UPDATE', 'Client', ?, ?)`, [ + ticket.clientFk, + oldInstance, + newInstance + ], {userId}); - const body = `No se ha podido enviar el albarán ${ticket.id} - al cliente ${ticket.clientFk} - ${ticket.clientName} - porque la dirección de email "${ticket.recipient}" no es correcta - o no está disponible.

- Para evitar que se repita este error, se ha eliminado la dirección de email de la ficha del cliente. - Actualiza la dirección de email con una correcta.`; + const body = `No se ha podido enviar el albarán ${ticket.id} + al cliente ${ticket.clientFk} - ${ticket.clientName} + porque la dirección de email "${ticket.recipient}" no es correcta + o no está disponible.

+ Para evitar que se repita este error, se ha eliminado la dirección de email de la ficha del cliente. + Actualiza la dirección de email con una correcta.`; - smtp.send({ - to: ticket.salesPersonEmail, - subject: 'No se ha podido enviar el albarán', - html: body - }); - } + smtp.send({ + to: ticket.salesPersonEmail, + subject: 'No se ha podido enviar el albarán', + html: body + }); + } }; From f3faf37e1a0e77227402a2c41fa54b5fdd2f5f7c Mon Sep 17 00:00:00 2001 From: carlossa Date: Tue, 14 Nov 2023 12:34:00 +0100 Subject: [PATCH 340/427] hotfix addressFk --- .../ticket/back/methods/ticket/closeAll.js | 49 +++++++++---------- 1 file changed, 24 insertions(+), 25 deletions(-) diff --git a/modules/ticket/back/methods/ticket/closeAll.js b/modules/ticket/back/methods/ticket/closeAll.js index 660c16893..46c45aa92 100644 --- a/modules/ticket/back/methods/ticket/closeAll.js +++ b/modules/ticket/back/methods/ticket/closeAll.js @@ -32,31 +32,30 @@ module.exports = Self => { throw new UserError('You cannot close tickets for today'); const tickets = await Self.rawSql(` - SELECT - t.id, - t.clientFk, - t.companyFk, - c.name clientName, - c.email recipient, - c.salesPersonFk, - c.isToBeMailed, - c.hasToInvoice, - co.hasDailyInvoice, - eu.email salesPersonEmail - FROM ticket t - JOIN agencyMode am ON am.id = t.agencyModeFk - JOIN warehouse wh ON wh.id = t.warehouseFk AND wh.hasComission - JOIN ticketState ts ON ts.ticketFk = t.id - JOIN alertLevel al ON al.id = ts.alertLevel - JOIN client c ON c.id = t.clientFk - JOIN province p ON p.id = c.provinceFk - JOIN country co ON co.id = p.countryFk - LEFT JOIN account.emailUser eu ON eu.userFk = c.salesPersonFk - WHERE (al.code = 'PACKED' OR (am.code = 'refund' AND al.code != 'delivered')) - AND DATE(t.shipped) BETWEEN DATE_ADD(?, INTERVAL -2 DAY) - AND util.dayEnd(?) - AND t.refFk IS NULL - GROUP BY t.id + SELECT t.id, + t.clientFk, + t.companyFk, + c.name clientName, + c.email recipient, + c.salesPersonFk, + c.isToBeMailed, + c.hasToInvoice, + co.hasDailyInvoice, + eu.email salesPersonEmail, + t.addressFk + FROM ticket t + JOIN agencyMode am ON am.id = t.agencyModeFk + JOIN warehouse wh ON wh.id = t.warehouseFk AND wh.hasComission + JOIN ticketState ts ON ts.ticketFk = t.id + JOIN alertLevel al ON al.id = ts.alertLevel + JOIN client c ON c.id = t.clientFk + JOIN province p ON p.id = c.provinceFk + JOIN country co ON co.id = p.countryFk + LEFT JOIN account.emailUser eu ON eu.userFk = c.salesPersonFk + WHERE (al.code = 'PACKED' OR (am.code = 'refund' AND al.code != 'delivered')) + AND DATE(t.shipped) BETWEEN DATE_ADD(?, INTERVAL -2 DAY) AND util.dayEnd(?) + AND t.refFk IS NULL + GROUP BY t.id `, [toDate, toDate]); await closure(ctx, Self, tickets); From 2bec1a2bed8fb261fe85ecf898467d78542de2ab Mon Sep 17 00:00:00 2001 From: sergiodt Date: Tue, 14 Nov 2023 14:02:40 +0100 Subject: [PATCH 341/427] refs #6014 fix: response type. fix: accessType EXECUTE --- loopback/common/methods/application/execute.js | 5 +++-- loopback/common/methods/application/executeFunc.js | 2 +- loopback/common/methods/application/executeProc.js | 2 +- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/loopback/common/methods/application/execute.js b/loopback/common/methods/application/execute.js index 7995b12e3..a468dcd70 100644 --- a/loopback/common/methods/application/execute.js +++ b/loopback/common/methods/application/execute.js @@ -21,7 +21,8 @@ module.exports = Self => { const argString = params.map(() => '?').join(','); - const [response] = await models.ProcsPriv.rawSql(query + `(${argString})`, params, myOptions); - return response; + const response = await models.ProcsPriv.rawSql(query + `(${argString})`, params, myOptions); + if (!Array.isArray(response)) return; + return response[0]; }; }; diff --git a/loopback/common/methods/application/executeFunc.js b/loopback/common/methods/application/executeFunc.js index f915f4482..a42fdae67 100644 --- a/loopback/common/methods/application/executeFunc.js +++ b/loopback/common/methods/application/executeFunc.js @@ -1,7 +1,7 @@ module.exports = Self => { Self.remoteMethodCtx('executeFunc', { description: 'Return result of function', - accessType: '*', + accessType: 'EXECUTE', accepts: [ { arg: 'routine', diff --git a/loopback/common/methods/application/executeProc.js b/loopback/common/methods/application/executeProc.js index 5859611d9..a8825da0f 100644 --- a/loopback/common/methods/application/executeProc.js +++ b/loopback/common/methods/application/executeProc.js @@ -1,7 +1,7 @@ module.exports = Self => { Self.remoteMethodCtx('executeProc', { description: 'Return result of procedure', - accessType: '*', + accessType: 'EXECUTE', accepts: [ { arg: 'routine', From a5682e9a0d663637c6f5b726569cd364e8b8a933 Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Tue, 14 Nov 2023 15:39:50 +0100 Subject: [PATCH 342/427] doc: refs #6062 README abbreviation --- README.md | 40 ++-------------------------------------- 1 file changed, 2 insertions(+), 38 deletions(-) diff --git a/README.md b/README.md index 59f5dbcf7..b420bc44f 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ Salix is also the scientific name of a beautifull tree! :) Required applications. -* Node.js >= 16.x LTS +* Node.js * Docker * Git @@ -17,20 +17,7 @@ You will need to install globally the following items. $ sudo npm install -g jest gulp-cli ``` -For the usage of jest --watch on macOs. -``` -$ brew install watchman -``` -* [watchman](https://facebook.github.io/watchman/) - -## Linux Only Prerequisites - -Your user must be on the docker group to use it so you will need to run this command: -``` -$ sudo usermod -a -G docker yourusername -``` - -## Getting Started // Installing +## Installing dependencies and launching Pull from repository. @@ -76,29 +63,6 @@ In Visual Studio Code we use the ESLint extension. ext install dbaeumer.vscode-eslint ``` -Gitlens for visualization of code authorship -``` -ext install eamodio.gitlens -``` - -Spanish language pack -``` -ext install ms-ceintl.vscode-language-pack-es -``` - -### Recommended extensions - -Material icon Theme -``` -ext install pkief.material-icon-theme -``` - -Material UI Themes -``` -ext install equinusocio.vsc-material-theme -``` - - ## Built With * [angularjs](https://angularjs.org/) From 88ec0f24c3cf61c5b160ab4351c4519406fa4857 Mon Sep 17 00:00:00 2001 From: alexm Date: Tue, 14 Nov 2023 15:45:52 +0100 Subject: [PATCH 343/427] ref #5914 rename table --- db/.archive/225201/00-invoiceOut_new.sql | 2 +- db/.archive/231001/02-invoiceOut_new.sql | 2 +- db/.archive/232001/00-invoiceOut_new.sql | 2 +- db/changes/234601/00-transferInvoice.sql | 2 +- db/dump/dumpedFixtures.sql | 10 ++++---- db/dump/structure.sql | 24 +++++++++---------- db/export-data.sh | 2 +- .../invoiceOut/specs/transferinvoice.spec.js | 4 ++-- .../methods/invoiceOut/transferInvoice.js | 4 ++-- modules/invoiceOut/back/model-config.json | 2 +- .../back/models/cplus-invoice-type-477.json | 6 ++--- .../back/models/invoice-correction.json | 4 ++-- .../front/descriptor-menu/index.html | 14 +++++------ .../invoiceOut/front/descriptor-menu/index.js | 2 +- 14 files changed, 40 insertions(+), 40 deletions(-) diff --git a/db/.archive/225201/00-invoiceOut_new.sql b/db/.archive/225201/00-invoiceOut_new.sql index 4c60b50bc..8e23fb43b 100644 --- a/db/.archive/225201/00-invoiceOut_new.sql +++ b/db/.archive/225201/00-invoiceOut_new.sql @@ -74,7 +74,7 @@ BEGIN clientFk, dued, companyFk, - cplusInvoiceType477Fk + siiTypeInvoiceOutFk ) SELECT 1, diff --git a/db/.archive/231001/02-invoiceOut_new.sql b/db/.archive/231001/02-invoiceOut_new.sql index d2b96eff7..d570dfb72 100644 --- a/db/.archive/231001/02-invoiceOut_new.sql +++ b/db/.archive/231001/02-invoiceOut_new.sql @@ -96,7 +96,7 @@ BEGIN clientFk, dued, companyFk, - cplusInvoiceType477Fk + siiTypeInvoiceOutFk ) SELECT 1, diff --git a/db/.archive/232001/00-invoiceOut_new.sql b/db/.archive/232001/00-invoiceOut_new.sql index b4fc5c824..b497dffda 100644 --- a/db/.archive/232001/00-invoiceOut_new.sql +++ b/db/.archive/232001/00-invoiceOut_new.sql @@ -96,7 +96,7 @@ BEGIN clientFk, dued, companyFk, - cplusInvoiceType477Fk + siiTypeInvoiceOutFk ) SELECT 1, diff --git a/db/changes/234601/00-transferInvoice.sql b/db/changes/234601/00-transferInvoice.sql index 7a9890ae4..d9ae39464 100644 --- a/db/changes/234601/00-transferInvoice.sql +++ b/db/changes/234601/00-transferInvoice.sql @@ -1,6 +1,6 @@ INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) VALUES ('CplusRectificationType', '*', 'READ', 'ALLOW', 'ROLE', 'administrative'), - ('CplusInvoiceType477', '*', 'READ', 'ALLOW', 'ROLE', 'administrative'), + ('SiiTypeInvoiceOut', '*', 'READ', 'ALLOW', 'ROLE', 'administrative'), ('InvoiceCorrectionType', '*', 'READ', 'ALLOW', 'ROLE', 'administrative'), ('InvoiceOut', 'transferInvoice', 'WRITE', 'ALLOW', 'ROLE', 'administrative'); diff --git a/db/dump/dumpedFixtures.sql b/db/dump/dumpedFixtures.sql index 2e1511b59..43eba7f24 100644 --- a/db/dump/dumpedFixtures.sql +++ b/db/dump/dumpedFixtures.sql @@ -275,13 +275,13 @@ INSERT INTO `cplusInvoiceType472` VALUES (1,'F1 - Factura'),(2,'F2 - Factura sim UNLOCK TABLES; -- --- Dumping data for table `cplusInvoiceType477` +-- Dumping data for table `siiTypeInvoiceOut` -- -LOCK TABLES `cplusInvoiceType477` WRITE; -/*!40000 ALTER TABLE `cplusInvoiceType477` DISABLE KEYS */; -INSERT INTO `cplusInvoiceType477` VALUES (1,'F1 - Factura'),(2,'F2 - Factura simplificada (ticket)'),(3,'F3 - Factura emitida en sustitución de facturas simplificadas facturadas y declaradas'),(4,'F4 - Asiento resumen de facturas'),(5,'R1 - Factura rectificativa (Art. 80.1, 80.2 y error fundado en derecho)'),(6,'R2 - Factura rectificativa (Art. 80.3)'),(7,'R3 - Factura rectificativa (Art. 80.4)'),(8,'R4 - Factura rectificativa (Resto)'),(9,'R5 - Factura rectificativa en facturas simplificadas'); -/*!40000 ALTER TABLE `cplusInvoiceType477` ENABLE KEYS */; +LOCK TABLES `siiTypeInvoiceOut` WRITE; +/*!40000 ALTER TABLE `siiTypeInvoiceOut` DISABLE KEYS */; +INSERT INTO `siiTypeInvoiceOut` VALUES (1,'F1 - Factura'),(2,'F2 - Factura simplificada (ticket)'),(3,'F3 - Factura emitida en sustitución de facturas simplificadas facturadas y declaradas'),(4,'F4 - Asiento resumen de facturas'),(5,'R1 - Factura rectificativa (Art. 80.1, 80.2 y error fundado en derecho)'),(6,'R2 - Factura rectificativa (Art. 80.3)'),(7,'R3 - Factura rectificativa (Art. 80.4)'),(8,'R4 - Factura rectificativa (Resto)'),(9,'R5 - Factura rectificativa en facturas simplificadas'); +/*!40000 ALTER TABLE `siiTypeInvoiceOut` ENABLE KEYS */; UNLOCK TABLES; -- diff --git a/db/dump/structure.sql b/db/dump/structure.sql index b242821fc..3dab0c5a4 100644 --- a/db/dump/structure.sql +++ b/db/dump/structure.sql @@ -25993,13 +25993,13 @@ CREATE TABLE `cplusInvoiceType472` ( /*!40101 SET character_set_client = @saved_cs_client */; -- --- Table structure for table `cplusInvoiceType477` +-- Table structure for table `siiTypeInvoiceOut` -- -DROP TABLE IF EXISTS `cplusInvoiceType477`; +DROP TABLE IF EXISTS `siiTypeInvoiceOut`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; -CREATE TABLE `cplusInvoiceType477` ( +CREATE TABLE `siiTypeInvoiceOut` ( `id` int(10) unsigned NOT NULL, `description` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, PRIMARY KEY (`id`) @@ -29450,16 +29450,16 @@ CREATE TABLE `invoiceCorrection` ( `correctingFk` int(10) unsigned NOT NULL COMMENT 'Factura rectificativa', `correctedFk` int(10) unsigned NOT NULL COMMENT 'Factura rectificada', `cplusRectificationTypeFk` int(10) unsigned NOT NULL, - `cplusInvoiceType477Fk` int(10) unsigned NOT NULL, + `siiTypeInvoiceOutFk` int(10) unsigned NOT NULL, `invoiceCorrectionTypeFk` int(11) NOT NULL DEFAULT 3, PRIMARY KEY (`correctingFk`), KEY `correctedFk_idx` (`correctedFk`), KEY `invoiceCorrection_ibfk_1_idx` (`cplusRectificationTypeFk`), - KEY `cplusInvoiceTyoeFk_idx` (`cplusInvoiceType477Fk`), + KEY `cplusInvoiceTyoeFk_idx` (`siiTypeInvoiceOutFk`), KEY `invoiceCorrectionTypeFk_idx` (`invoiceCorrectionTypeFk`), CONSTRAINT `corrected_fk` FOREIGN KEY (`correctedFk`) REFERENCES `invoiceOut` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `correcting_fk` FOREIGN KEY (`correctingFk`) REFERENCES `invoiceOut` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `cplusInvoiceTyoeFk` FOREIGN KEY (`cplusInvoiceType477Fk`) REFERENCES `cplusInvoiceType477` (`id`) ON UPDATE CASCADE, + CONSTRAINT `cplusInvoiceTyoeFk` FOREIGN KEY (`siiTypeInvoiceOutFk`) REFERENCES `siiTypeInvoiceOut` (`id`) ON UPDATE CASCADE, CONSTRAINT `invoiceCorrectionType_Fk33` FOREIGN KEY (`invoiceCorrectionTypeFk`) REFERENCES `invoiceCorrectionType` (`id`) ON UPDATE CASCADE, CONSTRAINT `invoiceCorrection_ibfk_1` FOREIGN KEY (`cplusRectificationTypeFk`) REFERENCES `cplusRectificationType` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Relacion entre las facturas rectificativas y las rectificadas.'; @@ -30130,7 +30130,7 @@ CREATE TABLE `invoiceOut` ( `companyFk` int(10) unsigned NOT NULL DEFAULT 442, `hasPdf` tinyint(3) unsigned NOT NULL DEFAULT 0, `booked` date DEFAULT NULL, - `cplusInvoiceType477Fk` int(10) unsigned NOT NULL DEFAULT 1, + `siiTypeInvoiceOutFk` int(10) unsigned NOT NULL DEFAULT 1, `cplusTaxBreakFk` int(10) unsigned NOT NULL DEFAULT 1, `cplusSubjectOpFk` int(10) unsigned NOT NULL DEFAULT 1, `cplusTrascendency477Fk` int(10) unsigned NOT NULL DEFAULT 1, @@ -30140,13 +30140,13 @@ CREATE TABLE `invoiceOut` ( KEY `Id_Cliente` (`clientFk`), KEY `empresa_id` (`companyFk`), KEY `Fecha` (`issued`), - KEY `Facturas_ibfk_2_idx` (`cplusInvoiceType477Fk`), + KEY `Facturas_ibfk_2_idx` (`siiTypeInvoiceOutFk`), KEY `Facturas_ibfk_3_idx` (`cplusSubjectOpFk`), KEY `Facturas_ibfk_4_idx` (`cplusTaxBreakFk`), KEY `Facturas_ibfk_5_idx` (`cplusTrascendency477Fk`), KEY `Facturas_idx_Vencimiento` (`dued`), KEY `invoiceOut_serial` (`serial`), - CONSTRAINT `invoiceOut_ibfk_2` FOREIGN KEY (`cplusInvoiceType477Fk`) REFERENCES `cplusInvoiceType477` (`id`) ON UPDATE CASCADE, + CONSTRAINT `invoiceOut_ibfk_2` FOREIGN KEY (`siiTypeInvoiceOutFk`) REFERENCES `siiTypeInvoiceOut` (`id`) ON UPDATE CASCADE, CONSTRAINT `invoiceOut_ibfk_3` FOREIGN KEY (`cplusSubjectOpFk`) REFERENCES `cplusSubjectOp` (`id`) ON UPDATE CASCADE, CONSTRAINT `invoiceOut_ibfk_4` FOREIGN KEY (`cplusTaxBreakFk`) REFERENCES `cplusTaxBreak` (`id`) ON UPDATE CASCADE, CONSTRAINT `invoiceOut_serial` FOREIGN KEY (`serial`) REFERENCES `invoiceOutSerial` (`code`), @@ -30308,7 +30308,7 @@ CREATE TABLE `invoiceOutSerial` ( `isTaxed` tinyint(1) NOT NULL DEFAULT 1, `taxAreaFk` varchar(15) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT 'NATIONAL', `isCEE` tinyint(1) NOT NULL DEFAULT 0, - `cplusInvoiceType477Fk` int(10) unsigned DEFAULT 1, + `siiTypeInvoiceOutFk` int(10) unsigned DEFAULT 1, `footNotes` longtext DEFAULT NULL, `isRefEditable` tinyint(4) NOT NULL DEFAULT 0, `type` enum('global','quick') DEFAULT NULL, @@ -58288,7 +58288,7 @@ BEGIN io.cplusTrascendency477Fk AS TIPOCLAVE, io.cplusTaxBreakFk AS TIPOEXENCI, io.cplusSubjectOpFk AS TIPONOSUJE, - io.cplusInvoiceType477Fk AS TIPOFACT, + io.siiTypeInvoiceOutFk AS TIPOFACT, ic.cplusRectificationTypeFk AS TIPORECTIF, io.companyFk, RIGHT(io.ref, LENGTH(io.ref) - 1) AS invoiceNum, @@ -58868,7 +58868,7 @@ BEGIN clientFk, dued, companyFk, - cplusInvoiceType477Fk + siiTypeInvoiceOutFk ) SELECT 1, diff --git a/db/export-data.sh b/db/export-data.sh index 7d346b235..a516992d3 100755 --- a/db/export-data.sh +++ b/db/export-data.sh @@ -46,7 +46,7 @@ TABLES=( bookingPlanner businessType cplusInvoiceType472 - cplusInvoiceType477 + siiTypeInvoiceOut cplusRectificationType cplusSubjectOp cplusTaxBreak diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js index 04f6df299..800a4ea83 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js @@ -27,7 +27,7 @@ describe('InvoiceOut tranferInvoice()', () => { ref: 'T4444444', newClientFk: 1, cplusRectificationId: 1, - cplusInvoiceType477Id: 1, + siiTypeInvoiceOutId: 1, invoiceCorrectionTypeId: 1 }; ctx.args = args; @@ -52,7 +52,7 @@ describe('InvoiceOut tranferInvoice()', () => { ref: 'T1111111', newClientFk: 1101, cplusRectificationId: 1, - cplusInvoiceType477Id: 1, + siiTypeInvoiceOutId: 1, invoiceCorrectionTypeId: 1 }; ctx.args = args; diff --git a/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js b/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js index 8a0609b8d..dde535c99 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js +++ b/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js @@ -27,7 +27,7 @@ module.exports = Self => { required: true }, { - arg: 'cplusInvoiceType477Id', + arg: 'siiTypeInvoiceOutId', type: 'number', required: true }, @@ -93,7 +93,7 @@ module.exports = Self => { correctingFk: invoiceId, correctedFk: args.id, cplusRectificationTypeFk: args.cplusRectificationId, - cplusInvoiceType477Fk: args.cplusInvoiceType477Id, + siiTypeInvoiceOutFk: args.siiTypeInvoiceOutId, invoiceCorrectionTypeFk: args.invoiceCorrectionTypeId }, myOptions); diff --git a/modules/invoiceOut/back/model-config.json b/modules/invoiceOut/back/model-config.json index 23246893b..9c7512429 100644 --- a/modules/invoiceOut/back/model-config.json +++ b/modules/invoiceOut/back/model-config.json @@ -41,7 +41,7 @@ "InvoiceCorrection": { "dataSource": "vn" }, - "CplusInvoiceType477": { + "SiiTypeInvoiceOut": { "dataSource": "vn" } } diff --git a/modules/invoiceOut/back/models/cplus-invoice-type-477.json b/modules/invoiceOut/back/models/cplus-invoice-type-477.json index 840a9a7e4..17b312617 100644 --- a/modules/invoiceOut/back/models/cplus-invoice-type-477.json +++ b/modules/invoiceOut/back/models/cplus-invoice-type-477.json @@ -1,9 +1,9 @@ { - "name": "CplusInvoiceType477", + "name": "SiiTypeInvoiceOut", "base": "VnModel", "options": { "mysql": { - "table": "cplusInvoiceType477" + "table": "siiTypeInvoiceOut" } }, "properties": { @@ -16,4 +16,4 @@ "type": "string" } } -} \ No newline at end of file +} diff --git a/modules/invoiceOut/back/models/invoice-correction.json b/modules/invoiceOut/back/models/invoice-correction.json index 48bd172a6..43e4f07ef 100644 --- a/modules/invoiceOut/back/models/invoice-correction.json +++ b/modules/invoiceOut/back/models/invoice-correction.json @@ -18,11 +18,11 @@ "cplusRectificationTypeFk": { "type": "number" }, - "cplusInvoiceType477Fk": { + "siiTypeInvoiceOutFk": { "type": "number" }, "invoiceCorrectionTypeFk": { "type": "number" } } -} \ No newline at end of file +} diff --git a/modules/invoiceOut/front/descriptor-menu/index.html b/modules/invoiceOut/front/descriptor-menu/index.html index 7d465f4ea..0052f0c03 100644 --- a/modules/invoiceOut/front/descriptor-menu/index.html +++ b/modules/invoiceOut/front/descriptor-menu/index.html @@ -6,8 +6,8 @@
+ url="SiiTypeInvoiceOuts" + data="siiTypeInvoiceOut"> Transfer invoice to... @@ -223,15 +223,15 @@ - - \ No newline at end of file + diff --git a/modules/invoiceOut/front/descriptor-menu/index.js b/modules/invoiceOut/front/descriptor-menu/index.js index 7d2644158..d3862a753 100644 --- a/modules/invoiceOut/front/descriptor-menu/index.js +++ b/modules/invoiceOut/front/descriptor-menu/index.js @@ -132,7 +132,7 @@ class Controller extends Section { ref: this.invoiceOut.ref, newClientFk: this.invoiceOut.client.id, cplusRectificationId: this.cplusRectificationType, - cplusInvoiceType477Id: this.cplusInvoiceType477, + siiTypeInvoiceOutId: this.siiTypeInvoiceOut, invoiceCorrectionTypeId: this.invoiceCorrectionType }; this.$http.post(`InvoiceOuts/transferInvoice`, params).then(res => { From 4061241650352d430082a5fdf1f29000df51df96 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Wed, 15 Nov 2023 09:37:03 +0100 Subject: [PATCH 344/427] refs #6434 feat: create signInLog table --- db/changes/234801/00-createSignInLogTable.sql | 19 ++++++++++ modules/account/back/model-config.json | 3 ++ modules/account/back/models/sign_in-log.json | 35 +++++++++++++++++++ 3 files changed, 57 insertions(+) create mode 100644 db/changes/234801/00-createSignInLogTable.sql create mode 100644 modules/account/back/models/sign_in-log.json diff --git a/db/changes/234801/00-createSignInLogTable.sql b/db/changes/234801/00-createSignInLogTable.sql new file mode 100644 index 000000000..977de4646 --- /dev/null +++ b/db/changes/234801/00-createSignInLogTable.sql @@ -0,0 +1,19 @@ + + +-- +-- Table structure for table `signInLog` +-- + +DROP TABLE IF EXISTS `account`.`signInLog`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `account`.`signInLog` ( + `id` varchar(10) NOT NULL , + `userFk` int(10) unsigned DEFAULT NULL, + `creationDate` timestamp NULL DEFAULT current_timestamp(), + `ip` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, + PRIMARY KEY (`id`), + KEY `userFk` (`userFk`), + CONSTRAINT `signInLog_ibfk_1` FOREIGN KEY (`userFk`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +); + diff --git a/modules/account/back/model-config.json b/modules/account/back/model-config.json index a4eb9fa57..b4bd6dbaf 100644 --- a/modules/account/back/model-config.json +++ b/modules/account/back/model-config.json @@ -35,6 +35,9 @@ "SambaConfig": { "dataSource": "vn" }, + "SignInLog": { + "dataSource": "vn" + }, "Sip": { "dataSource": "vn" }, diff --git a/modules/account/back/models/sign_in-log.json b/modules/account/back/models/sign_in-log.json new file mode 100644 index 000000000..df9ad8153 --- /dev/null +++ b/modules/account/back/models/sign_in-log.json @@ -0,0 +1,35 @@ +{ + "name": "SignInLog", + "base": "VnModel", + "options": { + "mysql": { + "table": "account.signInLog" + } + }, + "properties": { + "id": { + "id": true, + "type": "string", + "forceId": false + }, + "creationDate": { + "type": "date" + }, + "userFk": { + "type": "number" + }, + "ip": { + "type": "string" + } + }, + "relations": { + "user": { + "type": "belongsTo", + "model": "VnUser", + "foreignKey": "userFk" + } + }, + "scope": { + "order": ["creationDate DESC", "id DESC"] + } +} From e25b7d0a12638801f7ab21eb80b70c252fdff668 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Wed, 15 Nov 2023 09:39:51 +0100 Subject: [PATCH 345/427] refs #6434 feat: show error for wrong login --- back/models/vn-user.js | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/back/models/vn-user.js b/back/models/vn-user.js index de5bf7b63..00f5cd0b8 100644 --- a/back/models/vn-user.js +++ b/back/models/vn-user.js @@ -2,6 +2,7 @@ const vnModel = require('vn-loopback/common/models/vn-model'); const {Email} = require('vn-print'); const ForbiddenError = require('vn-loopback/util/forbiddenError'); const LoopBackContext = require('loopback-context'); +const UserError = require('vn-loopback/util/user-error'); module.exports = function(Self) { vnModel(Self); @@ -121,10 +122,16 @@ module.exports = function(Self) { }); Self.validateLogin = async function(user, password) { - let loginInfo = Object.assign({password}, Self.userUses(user)); - token = await Self.login(loginInfo, 'user'); + const loginInfo = Object.assign({password}, Self.userUses(user)); + const token = await Self.login(loginInfo, 'user'); const userToken = await token.user.get(); + + if (userToken.username !== user) { + console.error('ERROR!!! - Signin with other user', userToken, user); + throw new UserError('Try again'); + } + try { await Self.app.models.Account.sync(userToken.name, password); } catch (err) { From 11352798f09da689ab275f670ce2c55e426f00b1 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Wed, 15 Nov 2023 09:41:12 +0100 Subject: [PATCH 346/427] refs #6434 feat: save token in db for each login --- back/methods/vn-user/sign-in.js | 9 +++++++-- loopback/locale/es.json | 5 +++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/back/methods/vn-user/sign-in.js b/back/methods/vn-user/sign-in.js index b9e0d2f70..25f708b8e 100644 --- a/back/methods/vn-user/sign-in.js +++ b/back/methods/vn-user/sign-in.js @@ -49,8 +49,13 @@ module.exports = Self => { if (vnUser.twoFactor) throw new ForbiddenError(null, 'REQUIRES_2FA'); } - - return Self.validateLogin(user, password); + const validateLogin = await Self.validateLogin(user, password); + await Self.app.models.SignInLog.create({ + id: validateLogin.token, + userFk: vnUser.id, + ip: ctx.req.ip + }); + return validateLogin; }; Self.passExpired = async vnUser => { diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 3cc9a9627..da37d4005 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -321,9 +321,10 @@ "Select a different client": "Seleccione un cliente distinto", "Fill all the fields": "Rellene todos los campos", "The response is not a PDF": "La respuesta no es un PDF", - "Ticket without Route": "Ticket sin ruta", "Booking completed": "Reserva completada", "The ticket is in preparation": "El ticket [{{ticketId}}]({{{ticketUrl}}}) del comercial {{salesPersonId}} está en preparación", "The amount cannot be less than the minimum": "La cantidad no puede ser menor que la cantidad mímina", - "quantityLessThanMin": "La cantidad no puede ser menor que la cantidad mímina" + "quantityLessThanMin": "La cantidad no puede ser menor que la cantidad mímina", + "The notification subscription of this worker cant be modified": "La subscripción a la notificación de este trabajador no puede ser modificada", + "User disabled": "Usuario desactivado" } From 4d677ccc899faec445f423339e937e71e4014d25 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Wed, 15 Nov 2023 10:02:48 +0100 Subject: [PATCH 347/427] refs #6434 perf: rename folder db/changes version --- db/changes/{234801 => 234603}/00-createSignInLogTable.sql | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename db/changes/{234801 => 234603}/00-createSignInLogTable.sql (100%) diff --git a/db/changes/234801/00-createSignInLogTable.sql b/db/changes/234603/00-createSignInLogTable.sql similarity index 100% rename from db/changes/234801/00-createSignInLogTable.sql rename to db/changes/234603/00-createSignInLogTable.sql From f7b088297874d1a15aeb0175bb5cd1cf486da70e Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Wed, 15 Nov 2023 11:50:56 +0100 Subject: [PATCH 348/427] refs #6434 feat: remove forceId property --- modules/account/back/models/sign_in-log.json | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/modules/account/back/models/sign_in-log.json b/modules/account/back/models/sign_in-log.json index df9ad8153..44575b013 100644 --- a/modules/account/back/models/sign_in-log.json +++ b/modules/account/back/models/sign_in-log.json @@ -9,8 +9,7 @@ "properties": { "id": { "id": true, - "type": "string", - "forceId": false + "type": "string" }, "creationDate": { "type": "date" From 692c5eb164279ae0a964bbceb70007f61db46fbc Mon Sep 17 00:00:00 2001 From: sergiodt Date: Wed, 15 Nov 2023 12:38:08 +0100 Subject: [PATCH 349/427] refs #5652 fix: setVisibleDiscard add parameter null --- modules/item/back/methods/item/setVisibleDiscard.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/modules/item/back/methods/item/setVisibleDiscard.js b/modules/item/back/methods/item/setVisibleDiscard.js index 08cc507c3..16cef6baf 100644 --- a/modules/item/back/methods/item/setVisibleDiscard.js +++ b/modules/item/back/methods/item/setVisibleDiscard.js @@ -20,8 +20,7 @@ module.exports = Self => { }, { arg: 'addressFk', - type: 'Number', - required: true, + type: 'Any', description: 'The address id' }], http: { From 89967b85383fd53c5232b1a0cfc92b670ab6bf56 Mon Sep 17 00:00:00 2001 From: alexm Date: Wed, 15 Nov 2023 13:16:31 +0100 Subject: [PATCH 350/427] fix(workerDescriptor): show account button --- modules/worker/front/descriptor/index.html | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/modules/worker/front/descriptor/index.html b/modules/worker/front/descriptor/index.html index aa6b80300..8290e2a15 100644 --- a/modules/worker/front/descriptor/index.html +++ b/modules/worker/front/descriptor/index.html @@ -38,7 +38,7 @@ + > @@ -61,8 +61,6 @@
@@ -75,13 +73,13 @@ - - Date: Wed, 15 Nov 2023 13:49:41 +0100 Subject: [PATCH 351/427] refs #6434 feat: create signInLog table --- db/changes/234202/00-createSignInLogTable.sql | 19 +++++++++++ modules/account/back/model-config.json | 3 ++ modules/account/back/models/sign_in-log.json | 34 +++++++++++++++++++ 3 files changed, 56 insertions(+) create mode 100644 db/changes/234202/00-createSignInLogTable.sql create mode 100644 modules/account/back/models/sign_in-log.json diff --git a/db/changes/234202/00-createSignInLogTable.sql b/db/changes/234202/00-createSignInLogTable.sql new file mode 100644 index 000000000..977de4646 --- /dev/null +++ b/db/changes/234202/00-createSignInLogTable.sql @@ -0,0 +1,19 @@ + + +-- +-- Table structure for table `signInLog` +-- + +DROP TABLE IF EXISTS `account`.`signInLog`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `account`.`signInLog` ( + `id` varchar(10) NOT NULL , + `userFk` int(10) unsigned DEFAULT NULL, + `creationDate` timestamp NULL DEFAULT current_timestamp(), + `ip` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, + PRIMARY KEY (`id`), + KEY `userFk` (`userFk`), + CONSTRAINT `signInLog_ibfk_1` FOREIGN KEY (`userFk`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +); + diff --git a/modules/account/back/model-config.json b/modules/account/back/model-config.json index a4eb9fa57..b4bd6dbaf 100644 --- a/modules/account/back/model-config.json +++ b/modules/account/back/model-config.json @@ -35,6 +35,9 @@ "SambaConfig": { "dataSource": "vn" }, + "SignInLog": { + "dataSource": "vn" + }, "Sip": { "dataSource": "vn" }, diff --git a/modules/account/back/models/sign_in-log.json b/modules/account/back/models/sign_in-log.json new file mode 100644 index 000000000..44575b013 --- /dev/null +++ b/modules/account/back/models/sign_in-log.json @@ -0,0 +1,34 @@ +{ + "name": "SignInLog", + "base": "VnModel", + "options": { + "mysql": { + "table": "account.signInLog" + } + }, + "properties": { + "id": { + "id": true, + "type": "string" + }, + "creationDate": { + "type": "date" + }, + "userFk": { + "type": "number" + }, + "ip": { + "type": "string" + } + }, + "relations": { + "user": { + "type": "belongsTo", + "model": "VnUser", + "foreignKey": "userFk" + } + }, + "scope": { + "order": ["creationDate DESC", "id DESC"] + } +} From 0a31968cc7ad7b6883ec184dd5e3457760072807 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Wed, 15 Nov 2023 13:49:54 +0100 Subject: [PATCH 352/427] refs #6434 feat: show error for wrong login --- back/models/vn-user.js | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/back/models/vn-user.js b/back/models/vn-user.js index 712ed7d16..62bdfa2da 100644 --- a/back/models/vn-user.js +++ b/back/models/vn-user.js @@ -2,6 +2,7 @@ const vnModel = require('vn-loopback/common/models/vn-model'); const {Email} = require('vn-print'); const ForbiddenError = require('vn-loopback/util/forbiddenError'); const LoopBackContext = require('loopback-context'); +const UserError = require('vn-loopback/util/user-error'); module.exports = function(Self) { vnModel(Self); @@ -125,10 +126,16 @@ module.exports = function(Self) { }); Self.validateLogin = async function(user, password) { - let loginInfo = Object.assign({password}, Self.userUses(user)); - token = await Self.login(loginInfo, 'user'); + const loginInfo = Object.assign({password}, Self.userUses(user)); + const token = await Self.login(loginInfo, 'user'); const userToken = await token.user.get(); + + if (userToken.username !== user) { + console.error('ERROR!!! - Signin with other user', userToken, user); + throw new UserError('Try again'); + } + try { await Self.app.models.Account.sync(userToken.name, password); } catch (err) { From 58edcb9055c56b84f08384aa135119b608158518 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Wed, 15 Nov 2023 13:50:06 +0100 Subject: [PATCH 353/427] refs #6434 feat: save token in db for each login --- back/methods/vn-user/sign-in.js | 9 +++++++-- loopback/locale/es.json | 5 +++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/back/methods/vn-user/sign-in.js b/back/methods/vn-user/sign-in.js index b9e0d2f70..25f708b8e 100644 --- a/back/methods/vn-user/sign-in.js +++ b/back/methods/vn-user/sign-in.js @@ -49,8 +49,13 @@ module.exports = Self => { if (vnUser.twoFactor) throw new ForbiddenError(null, 'REQUIRES_2FA'); } - - return Self.validateLogin(user, password); + const validateLogin = await Self.validateLogin(user, password); + await Self.app.models.SignInLog.create({ + id: validateLogin.token, + userFk: vnUser.id, + ip: ctx.req.ip + }); + return validateLogin; }; Self.passExpired = async vnUser => { diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 4b297144f..ce56a6729 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -318,9 +318,10 @@ "Social name should be uppercase": "La razón social debe ir en mayúscula", "Street should be uppercase": "La dirección fiscal debe ir en mayúscula", "The response is not a PDF": "La respuesta no es un PDF", - "Ticket without Route": "Ticket sin ruta", "Booking completed": "Reserva completada", "The ticket is in preparation": "El ticket [{{ticketId}}]({{{ticketUrl}}}) del comercial {{salesPersonId}} está en preparación", "The amount cannot be less than the minimum": "La cantidad no puede ser menor que la cantidad mímina", - "quantityLessThanMin": "La cantidad no puede ser menor que la cantidad mímina" + "quantityLessThanMin": "La cantidad no puede ser menor que la cantidad mímina", + "The notification subscription of this worker cant be modified": "La subscripción a la notificación de este trabajador no puede ser modificada", + "User disabled": "Usuario desactivado" } From 13720291b2802826ba55a06c2dc8ee0aa778e6d4 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Wed, 15 Nov 2023 15:18:02 +0100 Subject: [PATCH 354/427] refs #6434 perf: remove unique in token column --- modules/account/back/models/sign_in-log.json | 1 - 1 file changed, 1 deletion(-) diff --git a/modules/account/back/models/sign_in-log.json b/modules/account/back/models/sign_in-log.json index 44575b013..3cd971cb8 100644 --- a/modules/account/back/models/sign_in-log.json +++ b/modules/account/back/models/sign_in-log.json @@ -8,7 +8,6 @@ }, "properties": { "id": { - "id": true, "type": "string" }, "creationDate": { From 4896be51ef6516cf8ef430fa0d4ae475b5c6e250 Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 16 Nov 2023 07:27:42 +0100 Subject: [PATCH 355/427] fix: translation --- loopback/locale/es.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 4b297144f..74dc2f15a 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -321,6 +321,6 @@ "Ticket without Route": "Ticket sin ruta", "Booking completed": "Reserva completada", "The ticket is in preparation": "El ticket [{{ticketId}}]({{{ticketUrl}}}) del comercial {{salesPersonId}} está en preparación", - "The amount cannot be less than the minimum": "La cantidad no puede ser menor que la cantidad mímina", - "quantityLessThanMin": "La cantidad no puede ser menor que la cantidad mímina" + "The amount cannot be less than the minimum": "La cantidad no puede ser menor que la cantidad mínima", + "quantityLessThanMin": "La cantidad no puede ser menor que la cantidad mínima" } From bfd6e1f39843abb02694fa2ebdb52e95df4f2bd4 Mon Sep 17 00:00:00 2001 From: guillermo Date: Thu, 16 Nov 2023 08:29:00 +0100 Subject: [PATCH 356/427] refactor: refs #4502 Deleted zoneEstimatedDelivery --- .../back/methods/sales-monitor/salesFilter.js | 71 ++++++++----- modules/order/back/methods/order/filter.js | 99 ++++++++++++------- modules/zone/back/model-config.json | 3 - .../back/models/zone-estimated-delivery.json | 44 --------- 4 files changed, 112 insertions(+), 105 deletions(-) delete mode 100644 modules/zone/back/models/zone-estimated-delivery.json diff --git a/modules/monitor/back/methods/sales-monitor/salesFilter.js b/modules/monitor/back/methods/sales-monitor/salesFilter.js index 693ae122f..85945a57d 100644 --- a/modules/monitor/back/methods/sales-monitor/salesFilter.js +++ b/modules/monitor/back/methods/sales-monitor/salesFilter.js @@ -163,17 +163,14 @@ module.exports = Self => { const stmts = []; let stmt; - stmts.push('DROP TEMPORARY TABLE IF EXISTS tmp.filter'); - stmts.push(`SET @_optimizer_search_depth = @@optimizer_search_depth`); stmts.push(`SET SESSION optimizer_search_depth = 0`); - stmt = new ParameterizedSQL( - `CREATE TEMPORARY TABLE tmp.filter + stmt = new ParameterizedSQL(` + CREATE OR REPLACE TEMPORARY TABLE tmp.filter (PRIMARY KEY (id)) ENGINE = MEMORY - SELECT - t.id, + SELECT t.id, t.shipped, CAST(DATE(t.shipped) AS CHAR) AS shippedDate, t.nickname, @@ -183,27 +180,27 @@ module.exports = Self => { t.clientFk, t.totalWithoutVat, t.totalWithVat, - io.id AS invoiceOutId, + io.id invoiceOutId, a.provinceFk, - p.name AS province, - w.name AS warehouse, - am.name AS agencyMode, - am.id AS agencyModeFk, - st.name AS state, - wk.lastName AS salesPerson, - ts.stateFk AS stateFk, - ts.alertLevel AS alertLevel, - ts.code AS alertLevelCode, - u.name AS userName, + p.name province, + w.name warehouse, + am.name agencyMode, + am.id agencyModeFk, + st.name state, + wk.lastName salesPerson, + ts.stateFk stateFk, + ts.alertLevel alertLevel, + ts.code alertLevelCode, + u.name userName, c.salesPersonFk, c.credit, - z.hour AS zoneLanding, - z.name AS zoneName, - z.id AS zoneFk, + z.hour zoneLanding, + z.name zoneName, + z.id zoneFk, st.classColor, - TIME_FORMAT(t.shipped, '%H:%i') AS preparationHour, - TIME_FORMAT(z.hour, '%H:%i') AS theoreticalhour, - TIME_FORMAT(zed.etc, '%H:%i') AS practicalHour + TIME_FORMAT(t.shipped, '%H:%i') preparationHour, + TIME_FORMAT(z.hour, '%H:%i') theoreticalhour, + TIME_FORMAT(zed.etc, '%H:%i') practicalHour FROM ticket t LEFT JOIN invoiceOut io ON t.refFk = io.ref LEFT JOIN zone z ON z.id = t.zoneFk @@ -216,7 +213,33 @@ module.exports = Self => { LEFT JOIN client c ON c.id = t.clientFk LEFT JOIN worker wk ON wk.id = c.salesPersonFk LEFT JOIN account.user u ON u.id = wk.id - LEFT JOIN zoneEstimatedDelivery zed ON zed.zoneFk = t.zoneFk`); + LEFT JOIN ( + SELECT zoneFk, + CAST(zoneHour + remainingVolume * 60 / speed AS time) etc + FROM ( + SELECT t.zoneFk, + IFNULL(zc.hour, z.hour) zoneHour, + SUM(IF(al.hasToRecalcPrice, sv.volume, 0)) remainingVolume, + GREATEST(IFNULL(lhp.m3, 0), IFNULL(dl.minSpeed, 0)) speed + FROM ticket t + JOIN ticketStateToday tst ON tst.ticket = t.id + JOIN state s ON s.id = tst.state + JOIN saleVolume sv ON sv.ticketFk = t.id + LEFT JOIN lastHourProduction lhp ON lhp.warehouseFk = t.warehouseFk + JOIN warehouse w ON w.id = t.warehouseFk + JOIN warehouseAlias wa ON wa.id = w.aliasFk + STRAIGHT_JOIN zone z ON z.id = t.zoneFk + LEFT JOIN zoneClosure zc ON zc.zoneFk = t.zoneFk + AND zc.dated = util.VN_CURDATE() + LEFT JOIN cache.departure_limit dl ON dl.warehouse_id = t.warehouseFk + AND dl.fecha = util.VN_CURDATE() + JOIN alertLevel al ON al.id = s.alertLevel + WHERE w.hasProduction + AND DATE(t.shipped) = util.VN_CURDATE() + GROUP BY t.zoneFk + ) sub + ) zed ON zed.zoneFk = t.zoneFk` + ); if (args.orderFk) { stmt.merge({ diff --git a/modules/order/back/methods/order/filter.js b/modules/order/back/methods/order/filter.js index 44d8ccb10..27484acb9 100644 --- a/modules/order/back/methods/order/filter.js +++ b/modules/order/back/methods/order/filter.js @@ -140,40 +140,71 @@ module.exports = Self => { const stmts = []; let stmt; - stmt = new ParameterizedSQL( - `CREATE OR REPLACE TEMPORARY TABLE tmp.filter - (INDEX (id)) - ENGINE = MEMORY - SELECT - o.id, - o.total, - o.date_send landed, - o.date_make created, - o.customer_id clientFk, - o.agency_id agencyModeFk, - o.address_id addressFk, - o.company_id companyFk, - o.source_app sourceApp, - o.confirmed isConfirmed, - c.name clientName, - c.salesPersonFk, - u.nickname workerNickname, - u.name name, - co.code companyCode, - zed.zoneFk, - zed.hourTheoretical, - zed.hourEffective, - am.name AS agencyName - FROM hedera.order o - LEFT JOIN address a ON a.id = o.address_id - LEFT JOIN agencyMode am ON am.id = o.agency_id - LEFT JOIN client c ON c.id = o.customer_id - LEFT JOIN worker wk ON wk.id = c.salesPersonFk - LEFT JOIN account.user u ON u.id = wk.id - LEFT JOIN company co ON co.id = o.company_id - LEFT JOIN orderTicket ot ON ot.orderFk = o.id - LEFT JOIN ticket t ON t.id = ot.ticketFk - LEFT JOIN zoneEstimatedDelivery zed ON zed.zoneFk = t.zoneFk`); + stmt = new ParameterizedSQL(` + CREATE OR REPLACE TEMPORARY TABLE tmp.filter + (INDEX (id)) + ENGINE = MEMORY + SELECT o.id, + o.total, + o.date_send landed, + o.date_make created, + o.customer_id clientFk, + o.agency_id agencyModeFk, + o.address_id addressFk, + o.company_id companyFk, + o.source_app sourceApp, + o.confirmed isConfirmed, + c.name clientName, + c.salesPersonFk, + u.nickname workerNickname, + u.name name, + co.code companyCode, + zed.zoneFk, + zed.hourTheoretical, + zed.hourEffective, + am.name agencyName + FROM hedera.order o + LEFT JOIN address a ON a.id = o.address_id + LEFT JOIN agencyMode am ON am.id = o.agency_id + LEFT JOIN client c ON c.id = o.customer_id + LEFT JOIN worker wk ON wk.id = c.salesPersonFk + LEFT JOIN account.user u ON u.id = wk.id + LEFT JOIN company co ON co.id = o.company_id + LEFT JOIN orderTicket ot ON ot.orderFk = o.id + LEFT JOIN ticket t ON t.id = ot.ticketFk + LEFT JOIN ( + SELECT zoneFk, + CAST( + util.VN_CURDATE() + + INTERVAL HOUR(zoneHour) * 60 + MINUTE(zoneHour) MINUTE + AS time + ) hourTheoretical, + CAST(zoneHour + remainingVolume * 60 / speed AS time) hourEffective + FROM ( + SELECT t.zoneFk, + IFNULL(zc.hour, z.hour) zoneHour, + CAST(SUM(sv.volume) AS DECIMAL(5, 1)) totalVolume, + SUM(IF(al.hasToRecalcPrice, sv.volume, 0)) remainingVolume, + GREATEST(IFNULL(lhp.m3, 0), IFNULL(dl.minSpeed, 0)) speed + FROM ticket t + JOIN ticketStateToday tst ON tst.ticket = t.id + JOIN state s ON s.id = tst.state + JOIN saleVolume sv ON sv.ticketFk = t.id + LEFT JOIN lastHourProduction lhp ON lhp.warehouseFk = t.warehouseFk + JOIN warehouse w ON w.id = t.warehouseFk + JOIN warehouseAlias wa ON wa.id = w.aliasFk + STRAIGHT_JOIN zone z ON z.id = t.zoneFk + LEFT JOIN zoneClosure zc ON zc.zoneFk = t.zoneFk + AND zc.dated = util.VN_CURDATE() + LEFT JOIN cache.departure_limit dl ON dl.warehouse_id = t.warehouseFk + AND dl.fecha = util.VN_CURDATE() + JOIN alertLevel al ON al.id = s.alertLevel + WHERE w.hasProduction + AND DATE(t.shipped) = util.VN_CURDATE() + GROUP BY t.zoneFk + ) sub + ) zed ON zed.zoneFk = t.zoneFk + `); stmt.merge(conn.makeWhere(filter.where)); stmt.merge(`GROUP BY id`); diff --git a/modules/zone/back/model-config.json b/modules/zone/back/model-config.json index 261a89902..43d2cb570 100644 --- a/modules/zone/back/model-config.json +++ b/modules/zone/back/model-config.json @@ -35,9 +35,6 @@ "ZoneWarehouse": { "dataSource": "vn" }, - "ZoneEstimatedDelivery": { - "dataSource": "vn" - }, "ZoneLog": { "dataSource": "vn" } diff --git a/modules/zone/back/models/zone-estimated-delivery.json b/modules/zone/back/models/zone-estimated-delivery.json deleted file mode 100644 index 399de8f58..000000000 --- a/modules/zone/back/models/zone-estimated-delivery.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "name": "ZoneEstimatedDelivery", - "base": "VnModel", - "options": { - "mysql": { - "table": "zoneEstimatedDelivery" - } - }, - "properties": { - "zoneFk": { - "id": true, - "type": "number" - }, - "hourTheoretical": { - "type": "date" - }, - "totalVolume": { - "type": "number" - }, - "remainingVolume": { - "type": "number" - }, - "speed": { - "type": "number" - }, - "hourEffective": { - "type": "date" - }, - "minutesLess": { - "type": "date" - }, - "etc": { - "type": "date" - } - - }, - "relations": { - "zone": { - "type": "belongsTo", - "model": "Zone", - "foreignKey": "zoneFk" - } - } -} \ No newline at end of file From c6b5d7f5a4a291dbfbcdc4d6187fb92bb0052912 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Thu, 16 Nov 2023 08:30:01 +0100 Subject: [PATCH 357/427] refs #6434 feat: rename id key by token --- back/methods/vn-user/sign-in.js | 2 +- db/changes/234202/00-createSignInLogTable.sql | 2 +- modules/account/back/models/sign_in-log.json | 9 ++++++--- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/back/methods/vn-user/sign-in.js b/back/methods/vn-user/sign-in.js index 25f708b8e..9c2d568f4 100644 --- a/back/methods/vn-user/sign-in.js +++ b/back/methods/vn-user/sign-in.js @@ -51,7 +51,7 @@ module.exports = Self => { } const validateLogin = await Self.validateLogin(user, password); await Self.app.models.SignInLog.create({ - id: validateLogin.token, + token: validateLogin.token, userFk: vnUser.id, ip: ctx.req.ip }); diff --git a/db/changes/234202/00-createSignInLogTable.sql b/db/changes/234202/00-createSignInLogTable.sql index 977de4646..6a648bb51 100644 --- a/db/changes/234202/00-createSignInLogTable.sql +++ b/db/changes/234202/00-createSignInLogTable.sql @@ -8,7 +8,7 @@ DROP TABLE IF EXISTS `account`.`signInLog`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `account`.`signInLog` ( - `id` varchar(10) NOT NULL , + `token` varchar(255) NOT NULL , `userFk` int(10) unsigned DEFAULT NULL, `creationDate` timestamp NULL DEFAULT current_timestamp(), `ip` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, diff --git a/modules/account/back/models/sign_in-log.json b/modules/account/back/models/sign_in-log.json index 3cd971cb8..9e6df2da5 100644 --- a/modules/account/back/models/sign_in-log.json +++ b/modules/account/back/models/sign_in-log.json @@ -7,13 +7,16 @@ } }, "properties": { - "id": { - "type": "string" + "token": { + "required": true, + "type": "string", + "description": "Token's user" }, "creationDate": { - "type": "date" + "type": "date" }, "userFk": { + "required": true, "type": "number" }, "ip": { From 3c8ed3ff51c7d80551cb068095f86d044fb3037d Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Thu, 16 Nov 2023 08:30:27 +0100 Subject: [PATCH 358/427] refs #6434 feat: username.toLowerCase() --- back/models/vn-user.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/back/models/vn-user.js b/back/models/vn-user.js index 62bdfa2da..5845c2192 100644 --- a/back/models/vn-user.js +++ b/back/models/vn-user.js @@ -131,7 +131,7 @@ module.exports = function(Self) { const userToken = await token.user.get(); - if (userToken.username !== user) { + if (userToken.username.toLowerCase() !== user.toLowerCase()) { console.error('ERROR!!! - Signin with other user', userToken, user); throw new UserError('Try again'); } From e73836cbdb551ee1f850955a7d99c768ede44d7c Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Thu, 16 Nov 2023 08:31:01 +0100 Subject: [PATCH 359/427] refs #6434 feat: remove primary key constraint --- db/changes/234202/00-createSignInLogTable.sql | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/db/changes/234202/00-createSignInLogTable.sql b/db/changes/234202/00-createSignInLogTable.sql index 6a648bb51..168c7b33f 100644 --- a/db/changes/234202/00-createSignInLogTable.sql +++ b/db/changes/234202/00-createSignInLogTable.sql @@ -12,8 +12,7 @@ CREATE TABLE `account`.`signInLog` ( `userFk` int(10) unsigned DEFAULT NULL, `creationDate` timestamp NULL DEFAULT current_timestamp(), `ip` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, - PRIMARY KEY (`id`), - KEY `userFk` (`userFk`), + CONSTRAINT `signInLog_ibfk_1` FOREIGN KEY (`userFk`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ); From d032b3a527da098541818cde90cb600188ec4189 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Thu, 16 Nov 2023 08:42:17 +0100 Subject: [PATCH 360/427] refs #6434 perf: add description to signInLog table --- db/changes/234202/00-createSignInLogTable.sql | 1 + 1 file changed, 1 insertion(+) diff --git a/db/changes/234202/00-createSignInLogTable.sql b/db/changes/234202/00-createSignInLogTable.sql index 168c7b33f..918b87137 100644 --- a/db/changes/234202/00-createSignInLogTable.sql +++ b/db/changes/234202/00-createSignInLogTable.sql @@ -2,6 +2,7 @@ -- -- Table structure for table `signInLog` +-- Description: log to debug cross-login error -- DROP TABLE IF EXISTS `account`.`signInLog`; From 144b26cf4cd8f9fe17f5d4e435247930250c343c Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Thu, 16 Nov 2023 08:47:08 +0100 Subject: [PATCH 361/427] refs #6434 perf: signInLog table id column AI --- db/changes/234202/00-createSignInLogTable.sql | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/db/changes/234202/00-createSignInLogTable.sql b/db/changes/234202/00-createSignInLogTable.sql index 918b87137..525348135 100644 --- a/db/changes/234202/00-createSignInLogTable.sql +++ b/db/changes/234202/00-createSignInLogTable.sql @@ -9,11 +9,12 @@ DROP TABLE IF EXISTS `account`.`signInLog`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `account`.`signInLog` ( + id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, `token` varchar(255) NOT NULL , `userFk` int(10) unsigned DEFAULT NULL, `creationDate` timestamp NULL DEFAULT current_timestamp(), `ip` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, - + KEY `userFk` (`userFk`), CONSTRAINT `signInLog_ibfk_1` FOREIGN KEY (`userFk`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ); From 54e8e6a27d60884a86b58256a722b08ccb0f7a21 Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 16 Nov 2023 09:10:45 +0100 Subject: [PATCH 362/427] refs #6417 fix(vnUser): toLowerCase --- back/models/vn-user.js | 2 +- loopback/locale/en.json | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/back/models/vn-user.js b/back/models/vn-user.js index 62bdfa2da..5845c2192 100644 --- a/back/models/vn-user.js +++ b/back/models/vn-user.js @@ -131,7 +131,7 @@ module.exports = function(Self) { const userToken = await token.user.get(); - if (userToken.username !== user) { + if (userToken.username.toLowerCase() !== user.toLowerCase()) { console.error('ERROR!!! - Signin with other user', userToken, user); throw new UserError('Try again'); } diff --git a/loopback/locale/en.json b/loopback/locale/en.json index 26650175d..9f9961f57 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -196,6 +196,6 @@ "Negative basis of tickets: 23": "Negative basis of tickets: 23", "Booking completed": "Booking complete", "The ticket is in preparation": "The ticket [{{ticketId}}]({{{ticketUrl}}}) of the sales person {{salesPersonId}} is in preparation", - "You can only add negative amounts in refund tickets": "You can only add negative amounts in refund tickets" -} - + "You can only add negative amounts in refund tickets": "You can only add negative amounts in refund tickets", + "Try again": "Try again" +} \ No newline at end of file From 67f5be474d44956fd3e7c2f7088cf7845d855559 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Thu, 16 Nov 2023 09:21:22 +0100 Subject: [PATCH 363/427] refs #6434 perf: rename db/changes current folder --- db/changes/234603/00-createSignInLogTable.sql | 5 +++-- db/changes/{234202 => 234604}/00-createSignInLogTable.sql | 0 2 files changed, 3 insertions(+), 2 deletions(-) rename db/changes/{234202 => 234604}/00-createSignInLogTable.sql (100%) diff --git a/db/changes/234603/00-createSignInLogTable.sql b/db/changes/234603/00-createSignInLogTable.sql index 977de4646..525348135 100644 --- a/db/changes/234603/00-createSignInLogTable.sql +++ b/db/changes/234603/00-createSignInLogTable.sql @@ -2,17 +2,18 @@ -- -- Table structure for table `signInLog` +-- Description: log to debug cross-login error -- DROP TABLE IF EXISTS `account`.`signInLog`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `account`.`signInLog` ( - `id` varchar(10) NOT NULL , + id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, + `token` varchar(255) NOT NULL , `userFk` int(10) unsigned DEFAULT NULL, `creationDate` timestamp NULL DEFAULT current_timestamp(), `ip` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, - PRIMARY KEY (`id`), KEY `userFk` (`userFk`), CONSTRAINT `signInLog_ibfk_1` FOREIGN KEY (`userFk`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ); diff --git a/db/changes/234202/00-createSignInLogTable.sql b/db/changes/234604/00-createSignInLogTable.sql similarity index 100% rename from db/changes/234202/00-createSignInLogTable.sql rename to db/changes/234604/00-createSignInLogTable.sql From 9c6b59442684085d6ab3a519de1afadcb4571fb3 Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 16 Nov 2023 10:04:34 +0100 Subject: [PATCH 364/427] hotFix: comment error logIn --- back/models/vn-user.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/back/models/vn-user.js b/back/models/vn-user.js index 5845c2192..2ab97fce6 100644 --- a/back/models/vn-user.js +++ b/back/models/vn-user.js @@ -131,10 +131,10 @@ module.exports = function(Self) { const userToken = await token.user.get(); - if (userToken.username.toLowerCase() !== user.toLowerCase()) { - console.error('ERROR!!! - Signin with other user', userToken, user); - throw new UserError('Try again'); - } + // if (userToken.username.toLowerCase() !== user.toLowerCase()) { + // console.error('ERROR!!! - Signin with other user', userToken, user); + // throw new UserError('Try again'); + // } try { await Self.app.models.Account.sync(userToken.name, password); From 386b556216ec86e4c91a756b9f2c1e3f835c3c31 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Thu, 16 Nov 2023 10:29:57 +0100 Subject: [PATCH 365/427] refs #6434 feat: new test user signIn with email --- back/methods/vn-user/specs/sign-in.spec.js | 10 ++++++++++ back/models/vn-user.js | 13 ++++++++----- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/back/methods/vn-user/specs/sign-in.spec.js b/back/methods/vn-user/specs/sign-in.spec.js index f4cad88b9..26abe7eda 100644 --- a/back/methods/vn-user/specs/sign-in.spec.js +++ b/back/methods/vn-user/specs/sign-in.spec.js @@ -14,6 +14,16 @@ describe('VnUser Sign-in()', () => { }; const {VnUser, AccessToken} = models; describe('when credentials are correct', () => { + it('should return the token if user uses email', async() => { + let login = await VnUser.signIn(unauthCtx, 'salesAssistant@mydomain.com', 'nightmare'); + let accessToken = await AccessToken.findById(login.token); + let ctx = {req: {accessToken: accessToken}}; + + expect(login.token).toBeDefined(); + + await VnUser.logout(ctx.req.accessToken.id); + }); + it('should return the token', async() => { let login = await VnUser.signIn(unauthCtx, 'salesAssistant', 'nightmare'); let accessToken = await AccessToken.findById(login.token); diff --git a/back/models/vn-user.js b/back/models/vn-user.js index 2ab97fce6..bbfee4c51 100644 --- a/back/models/vn-user.js +++ b/back/models/vn-user.js @@ -124,17 +124,20 @@ module.exports = function(Self) { return email.send(); }); + Self.signInValidate = (user, userToken) => { + const [[key, value]] = Object.entries(Self.userUses(user)); + if (userToken[key].toLowerCase() !== value.toLowerCase()) { + console.error('ERROR!!! - Signin with other user', _userToken, _user); + throw new UserError('Try again'); + } + }; Self.validateLogin = async function(user, password) { const loginInfo = Object.assign({password}, Self.userUses(user)); const token = await Self.login(loginInfo, 'user'); const userToken = await token.user.get(); - - // if (userToken.username.toLowerCase() !== user.toLowerCase()) { - // console.error('ERROR!!! - Signin with other user', userToken, user); - // throw new UserError('Try again'); - // } + Self.signInValidate(user, userToken); try { await Self.app.models.Account.sync(userToken.name, password); From abf772ae870e238a4df0b42bfb082724ebf76dd1 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Thu, 16 Nov 2023 10:43:00 +0100 Subject: [PATCH 366/427] refs #6434 feat: check if signIn inserts signInLog --- back/methods/vn-user/specs/sign-in.spec.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/back/methods/vn-user/specs/sign-in.spec.js b/back/methods/vn-user/specs/sign-in.spec.js index 26abe7eda..ac2dfe2b2 100644 --- a/back/methods/vn-user/specs/sign-in.spec.js +++ b/back/methods/vn-user/specs/sign-in.spec.js @@ -12,13 +12,16 @@ describe('VnUser Sign-in()', () => { }, args: {} }; - const {VnUser, AccessToken} = models; + const {VnUser, AccessToken, SignInLog} = models; describe('when credentials are correct', () => { it('should return the token if user uses email', async() => { let login = await VnUser.signIn(unauthCtx, 'salesAssistant@mydomain.com', 'nightmare'); let accessToken = await AccessToken.findById(login.token); let ctx = {req: {accessToken: accessToken}}; + let signInLog = await SignInLog.find({where: {token: accessToken.id}}); + expect(signInLog.length).toEqual(1); + expect(signInLog[0].userFk).toEqual(accessToken.userId); expect(login.token).toBeDefined(); await VnUser.logout(ctx.req.accessToken.id); From 9e649398101ffff980ff7471fa375d885e8c5972 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Thu, 16 Nov 2023 11:56:48 +0100 Subject: [PATCH 367/427] refs #6434 feat: add Id property in model --- modules/account/back/models/sign_in-log.json | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/modules/account/back/models/sign_in-log.json b/modules/account/back/models/sign_in-log.json index 9e6df2da5..c5c014e60 100644 --- a/modules/account/back/models/sign_in-log.json +++ b/modules/account/back/models/sign_in-log.json @@ -7,6 +7,11 @@ } }, "properties": { + "id": { + "type": "number", + "id": true, + "description": "Identifier" + }, "token": { "required": true, "type": "string", From a73453e9ed29736cbb35fd370ad29ae38068d071 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Thu, 16 Nov 2023 11:56:59 +0100 Subject: [PATCH 368/427] refs #6434 feat: remove old sql file --- db/changes/234603/00-createSignInLogTable.sql | 20 ------------------- 1 file changed, 20 deletions(-) delete mode 100644 db/changes/234603/00-createSignInLogTable.sql diff --git a/db/changes/234603/00-createSignInLogTable.sql b/db/changes/234603/00-createSignInLogTable.sql deleted file mode 100644 index 525348135..000000000 --- a/db/changes/234603/00-createSignInLogTable.sql +++ /dev/null @@ -1,20 +0,0 @@ - - --- --- Table structure for table `signInLog` --- Description: log to debug cross-login error --- - -DROP TABLE IF EXISTS `account`.`signInLog`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `account`.`signInLog` ( - id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, - `token` varchar(255) NOT NULL , - `userFk` int(10) unsigned DEFAULT NULL, - `creationDate` timestamp NULL DEFAULT current_timestamp(), - `ip` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, - KEY `userFk` (`userFk`), - CONSTRAINT `signInLog_ibfk_1` FOREIGN KEY (`userFk`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -); - From 83ae0379b5feeb7922075fbbba14c7c1406a09de Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 16 Nov 2023 12:28:35 +0100 Subject: [PATCH 369/427] refs #6434 fix: console.log --- back/models/vn-user.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/back/models/vn-user.js b/back/models/vn-user.js index bbfee4c51..e73c04bc0 100644 --- a/back/models/vn-user.js +++ b/back/models/vn-user.js @@ -127,7 +127,7 @@ module.exports = function(Self) { Self.signInValidate = (user, userToken) => { const [[key, value]] = Object.entries(Self.userUses(user)); if (userToken[key].toLowerCase() !== value.toLowerCase()) { - console.error('ERROR!!! - Signin with other user', _userToken, _user); + console.error('ERROR!!! - Signin with other user', userToken, user); throw new UserError('Try again'); } }; From aea3f7b2b9bbecaa6f16d0ff241c57a0c766ba32 Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 16 Nov 2023 15:10:47 +0100 Subject: [PATCH 370/427] refs #6434 fix: use trim --- back/models/vn-user.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/back/models/vn-user.js b/back/models/vn-user.js index e73c04bc0..719e96cbf 100644 --- a/back/models/vn-user.js +++ b/back/models/vn-user.js @@ -126,7 +126,7 @@ module.exports = function(Self) { }); Self.signInValidate = (user, userToken) => { const [[key, value]] = Object.entries(Self.userUses(user)); - if (userToken[key].toLowerCase() !== value.toLowerCase()) { + if (userToken[key].toLowerCase().trim() !== value.toLowerCase().trim()) { console.error('ERROR!!! - Signin with other user', userToken, user); throw new UserError('Try again'); } From 4f5242e3ae30d0e9b2ef35d7368ce0aab1052595 Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Thu, 16 Nov 2023 23:07:26 +0100 Subject: [PATCH 371/427] fix: refs #6432 account sync fixes --- Dockerfile | 10 +- db/changes/234604/00-sambaConfigUserDn.sql | 2 + modules/account/back/methods/account/sync.js | 8 +- modules/account/back/models/ldap-config.js | 3 +- modules/account/back/models/role-config.js | 20 ++- modules/account/back/models/samba-config.js | 149 +++++++++++------- modules/account/back/models/samba-config.json | 4 + modules/account/front/accounts/index.html | 40 +---- modules/account/front/accounts/index.js | 18 --- modules/account/front/accounts/locale/es.yml | 2 - modules/account/front/descriptor/index.html | 35 ++++ modules/account/front/descriptor/index.js | 14 ++ .../account/front/descriptor/locale/es.yml | 4 + 13 files changed, 186 insertions(+), 123 deletions(-) create mode 100644 db/changes/234604/00-sambaConfigUserDn.sql diff --git a/Dockerfile b/Dockerfile index e1173ad73..814a5e1d8 100644 --- a/Dockerfile +++ b/Dockerfile @@ -17,15 +17,19 @@ RUN apt-get update \ # Puppeteer -RUN apt-get update \ - && apt-get install -y --no-install-recommends \ +RUN apt-get install -y --no-install-recommends \ libfontconfig lftp xvfb gconf-service libasound2 libatk1.0-0 libc6 \ libcairo2 libcups2 libdbus-1-3 libexpat1 libfontconfig1 libgbm1 \ libgcc1 libgconf-2-4 libgdk-pixbuf2.0-0 libglib2.0-0 libgtk-3-0 \ libnspr4 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 \ libx11-xcb1 libxcb1 libxcomposite1 libxcursor1 libxdamage1 libxext6 \ libxfixes3 libxi6 libxrandr2 libxrender1 libxss1 libxtst6 \ - fonts-liberation libappindicator1 libnss3 lsb-release xdg-utils wget \ + fonts-liberation libappindicator1 libnss3 lsb-release xdg-utils wget + +# Extra dependencies + +RUN apt-get install -y --no-install-recommends \ + samba-common-bin \ && rm -rf /var/lib/apt/lists/* \ && npm -g install pm2 diff --git a/db/changes/234604/00-sambaConfigUserDn.sql b/db/changes/234604/00-sambaConfigUserDn.sql new file mode 100644 index 000000000..cacb30e97 --- /dev/null +++ b/db/changes/234604/00-sambaConfigUserDn.sql @@ -0,0 +1,2 @@ +ALTER TABLE account.sambaConfig + ADD userDn varchar(255) NOT NULL COMMENT 'Base DN for users without domain DN part'; diff --git a/modules/account/back/methods/account/sync.js b/modules/account/back/methods/account/sync.js index a5befc22c..0eab0ef63 100644 --- a/modules/account/back/methods/account/sync.js +++ b/modules/account/back/methods/account/sync.js @@ -1,3 +1,4 @@ +const ForbiddenError = require('vn-loopback/util/forbiddenError'); module.exports = Self => { Self.remoteMethod('sync', { @@ -32,9 +33,13 @@ module.exports = Self => { const models = Self.app.models; const user = await models.VnUser.findOne({ - fields: ['id'], + fields: ['id', 'password'], where: {name: userName} }, myOptions); + + if (user && password && !await user.hasPassword(password)) + throw new ForbiddenError('Wrong password'); + const isSync = !await models.UserSync.exists(userName, myOptions); if (!force && isSync && user) return; @@ -42,4 +47,3 @@ module.exports = Self => { await models.UserSync.destroyById(userName, myOptions); }; }; - diff --git a/modules/account/back/models/ldap-config.js b/modules/account/back/models/ldap-config.js index f9ae7562b..9dcc4136d 100644 --- a/modules/account/back/models/ldap-config.js +++ b/modules/account/back/models/ldap-config.js @@ -5,7 +5,7 @@ const crypto = require('crypto'); const nthash = require('smbhash').nthash; module.exports = Self => { - const shouldSync = process.env.NODE_ENV === 'production'; + const shouldSync = process.env.NODE_ENV !== 'test'; Self.getSynchronizer = async function() { return await Self.findOne({ @@ -140,6 +140,7 @@ module.exports = Self => { try { if (shouldSync) await client.del(dn); + // eslint-disable-next-line no-console console.log(` -> User '${userName}' removed from LDAP`); } catch (e) { if (e.name !== 'NoSuchObjectError') throw e; diff --git a/modules/account/back/models/role-config.js b/modules/account/back/models/role-config.js index ba7bf9d52..b90ef75fb 100644 --- a/modules/account/back/models/role-config.js +++ b/modules/account/back/models/role-config.js @@ -27,8 +27,7 @@ module.exports = Self => { const [row] = await Self.rawSql( `SELECT COUNT(*) AS nRows FROM mysql.user - WHERE User = ? - AND Host = ?`, + WHERE User = ? AND Host = ?`, [mysqlUser, this.userHost] ); let userExists = row.nRows > 0; @@ -38,8 +37,7 @@ module.exports = Self => { const [row] = await Self.rawSql( `SELECT Priv AS priv FROM mysql.global_priv - WHERE User = ? - AND Host = ?`, + WHERE User = ? AND Host = ?`, [mysqlUser, this.userHost] ); const priv = row && JSON.parse(row.priv); @@ -88,10 +86,18 @@ module.exports = Self => { else throw err; } - await Self.rawSql('GRANT ? TO ?@?', - [role, mysqlUser, this.userHost]); - if (role) { + const [row] = await Self.rawSql( + `SELECT COUNT(*) AS nRows + FROM mysql.user + WHERE User = ? AND Host = ''`, + [role] + ); + const roleExists = row.nRows > 0; + + if (roleExists) { + await Self.rawSql('GRANT ? TO ?@?', + [role, mysqlUser, this.userHost]); await Self.rawSql('SET DEFAULT ROLE ? FOR ?@?', [role, mysqlUser, this.userHost]); } else { diff --git a/modules/account/back/models/samba-config.js b/modules/account/back/models/samba-config.js index 168b5ffb4..1abac489c 100644 --- a/modules/account/back/models/samba-config.js +++ b/modules/account/back/models/samba-config.js @@ -1,6 +1,6 @@ const ldap = require('../util/ldapjs-extra'); -const ssh = require('node-ssh'); +const execFile = require('child_process').execFile; /** * Summary of userAccountControl flags: @@ -11,6 +11,8 @@ const UserAccountControlFlags = { }; module.exports = Self => { + const shouldSync = process.env.NODE_ENV !== 'test'; + Self.getSynchronizer = async function() { return await Self.findOne({ fields: [ @@ -19,6 +21,7 @@ module.exports = Self => { 'adController', 'adUser', 'adPassword', + 'userDn', 'verifyCert' ] }); @@ -26,88 +29,119 @@ module.exports = Self => { Object.assign(Self.prototype, { async init() { - let sshClient = new ssh.NodeSSH(); - await sshClient.connect({ - host: this.adController, - username: this.adUser, - password: this.adPassword - }); + const baseDn = this.adDomain + .split('.') + .map(part => `dc=${part}`) + .join(','); + const ldapUser = `cn=${this.adUser},cn=Users,${baseDn}`; - let adUser = `cn=${this.adUser},${this.usersDn()}`; - - let adClient = ldap.createClient({ + const adClient = ldap.createClient({ url: `ldaps://${this.adController}:636`, tlsOptions: {rejectUnauthorized: this.verifyCert} }); - await adClient.bind(adUser, this.adPassword); - + await adClient.bind(ldapUser, this.adPassword); Object.assign(this, { - sshClient, - adClient + adClient, + fullUsersDn: `${this.userDn},${baseDn}` }); }, async deinit() { - await this.sshClient.dispose(); await this.adClient.unbind(); }, - usersDn() { - let dnBase = this.adDomain - .split('.') - .map(part => `dc=${part}`) - .join(','); - return `cn=Users,${dnBase}`; + async sambaTool(command, args = []) { + const authArgs = [ + '--URL', `ldap://${this.adController}`, + '--username', this.adUser, + '--password', this.adPassword + ]; + const allArgs = [command].concat( + args, authArgs + ); + + if (!shouldSync) return; + return await new Promise((resolve, reject) => { + execFile('samba-tool', allArgs, (err, stdout, stderr) => { + if (err) + reject(err); + else + resolve({stdout, stderr}); + }); + }); }, - async syncUser(userName, info, password) { - let {sshClient} = this; - - let sambaUser = await this.adClient.searchOne(this.usersDn(), { + async getAdUser(userName) { + const sambaUser = await this.adClient.searchOne(this.fullUsersDn, { scope: 'sub', - attributes: ['userAccountControl'], + attributes: [ + 'dn', + 'userAccountControl', + 'uidNumber', + 'accountExpires', + 'mail' + ], filter: `(&(objectClass=user)(sAMAccountName=${userName}))` }); - let isEnabled = sambaUser - && !(sambaUser.userAccountControl & UserAccountControlFlags.ACCOUNTDISABLE); - - if (process.env.NODE_ENV === 'test') - return; + if (sambaUser) { + for (const intProp of ['uidNumber', 'userAccountControl']) { + if (sambaUser[intProp] != null) + sambaUser[intProp] = parseInt(sambaUser[intProp]); + } + } + return sambaUser; + }, + + async syncUser(userName, info, password) { + let sambaUser = await this.getAdUser(userName); + let entry; if (info.hasAccount) { if (!sambaUser) { - await sshClient.exec('samba-tool user create', [ - userName, - '--uid-number', `${info.uidNumber}`, - '--mail-address', info.corporateMail, + await this.sambaTool('user', [ + 'create', userName, + '--userou', this.userDn, '--random-password' ]); - await sshClient.exec('samba-tool user setexpiry', [ - userName, - '--noexpiry' - ]); - await sshClient.exec('mkhomedir_helper', [ - userName, - '0027' - ]); - } - if (!isEnabled) { - await sshClient.exec('samba-tool user enable', [ - userName - ]); + sambaUser = await this.getAdUser(userName); } if (password) { - await sshClient.exec('samba-tool user setpassword', [ - userName, + await this.sambaTool('user', [ + 'setpassword', userName, '--newpassword', password ]); } - } else if (isEnabled) { - await sshClient.exec('samba-tool user disable', [ - userName - ]); + + entry = { + userAccountControl: sambaUser.userAccountControl + & ~UserAccountControlFlags.ACCOUNTDISABLE, + uidNumber: info.uidNumber, + accountExpires: 0, + mail: info.corporateMail + }; + } else if (sambaUser) { + entry = { + userAccountControl: sambaUser.userAccountControl + | UserAccountControlFlags.ACCOUNTDISABLE + }; + // eslint-disable-next-line no-console console.log(` -> User '${userName}' disabled on Samba`); } + + if (sambaUser && entry) { + const changes = []; + for (const prop in entry) { + if (sambaUser[prop] == entry[prop]) continue; + changes.push(new ldap.Change({ + operation: 'replace', + modification: { + [prop]: entry[prop] + } + })); + } + if (changes.length) + await this.adClient.modify(sambaUser.dn, changes); + } }, /** @@ -117,14 +151,15 @@ module.exports = Self => { */ async getUsers(usersToSync) { const LDAP_MATCHING_RULE_BIT_AND = '1.2.840.113556.1.4.803'; - let filter = `!(userAccountControl:${LDAP_MATCHING_RULE_BIT_AND}:=${UserAccountControlFlags.ACCOUNTDISABLE})`; + // eslint-disable-next-line max-len + const filter = `!(userAccountControl:${LDAP_MATCHING_RULE_BIT_AND}:=${UserAccountControlFlags.ACCOUNTDISABLE})`; - let opts = { + const opts = { scope: 'sub', attributes: ['sAMAccountName'], filter: `(&(objectClass=user)(${filter}))` }; - await this.adClient.searchForeach(this.usersDn(), opts, + await this.adClient.searchForeach(this.fullUsersDn, opts, o => usersToSync.add(o.sAMAccountName)); } }); diff --git a/modules/account/back/models/samba-config.json b/modules/account/back/models/samba-config.json index 732c9b071..28cbb2689 100644 --- a/modules/account/back/models/samba-config.json +++ b/modules/account/back/models/samba-config.json @@ -28,6 +28,10 @@ "adPassword": { "type": "string" }, + "userDn": { + "type": "string", + "required": true + }, "verifyCert": { "type": "boolean" } diff --git a/modules/account/front/accounts/index.html b/modules/account/front/accounts/index.html index 6941bb15b..6847e68d1 100644 --- a/modules/account/front/accounts/index.html +++ b/modules/account/front/accounts/index.html @@ -12,40 +12,40 @@ @@ -61,10 +61,6 @@ label="Synchronize all" ng-click="$ctrl.onSynchronizeAll()"> - - @@ -77,25 +73,3 @@ - - - - - - - - - - - - diff --git a/modules/account/front/accounts/index.js b/modules/account/front/accounts/index.js index 0e78ab8d6..ab19126a1 100644 --- a/modules/account/front/accounts/index.js +++ b/modules/account/front/accounts/index.js @@ -1,6 +1,5 @@ import ngModule from '../module'; import Section from 'salix/components/section'; -import UserError from 'core/lib/user-error'; export default class Controller extends Section { onSynchronizeAll() { @@ -8,27 +7,10 @@ export default class Controller extends Section { this.$http.patch(`Accounts/syncAll`); } - onUserSync() { - if (!this.syncUser) - throw new UserError('Please enter the username'); - - let params = { - password: this.syncPassword, - force: true - }; - return this.$http.patch(`Accounts/${this.syncUser}/sync`, params) - .then(() => this.vnApp.showSuccess(this.$t('User synchronized!'))); - } - onSynchronizeRoles() { this.$http.patch(`RoleInherits/sync`) .then(() => this.vnApp.showSuccess(this.$t('Roles synchronized!'))); } - - onSyncClose() { - this.syncUser = ''; - this.syncPassword = ''; - } } ngModule.component('vnAccountAccounts', { diff --git a/modules/account/front/accounts/locale/es.yml b/modules/account/front/accounts/locale/es.yml index 9a6bb5073..614ade3eb 100644 --- a/modules/account/front/accounts/locale/es.yml +++ b/modules/account/front/accounts/locale/es.yml @@ -3,7 +3,6 @@ Homedir base: Directorio base para carpetas de usuario Shell: Intérprete de línea de comandos User and role base id: Id base usuarios y roles Synchronize all: Sincronizar todo -Synchronize user: Sincronizar usuario Synchronize roles: Sincronizar roles If password is not specified, just user attributes are synchronized: >- Si la contraseña no se especifica solo se sincronizarán lo atributos del usuario @@ -12,5 +11,4 @@ Users synchronized!: ¡Usuarios sincronizados! Username: Nombre de usuario Synchronize: Sincronizar Please enter the username: Por favor introduce el nombre de usuario -User synchronized!: ¡Usuario sincronizado! Roles synchronized!: ¡Roles sincronizados! diff --git a/modules/account/front/descriptor/index.html b/modules/account/front/descriptor/index.html index 94497aaa9..b0a70edd1 100644 --- a/modules/account/front/descriptor/index.html +++ b/modules/account/front/descriptor/index.html @@ -67,6 +67,15 @@ translate> Deactivate user + + Synchronize +
@@ -153,6 +162,32 @@ + + + Do you want to synchronize user? + + + + + + + + + + + + diff --git a/modules/account/front/descriptor/index.js b/modules/account/front/descriptor/index.js index 786870d36..c327b0836 100644 --- a/modules/account/front/descriptor/index.js +++ b/modules/account/front/descriptor/index.js @@ -120,6 +120,20 @@ class Controller extends Descriptor { this.vnApp.showSuccess(this.$t(message)); }); } + + onSync() { + let params = { + password: this.syncPassword, + force: true + }; + return this.$http.patch(`Accounts/${this.user.name}/sync`, params) + .then(() => this.vnApp.showSuccess(this.$t('User synchronized!'))); + } + + onSyncClose() { + this.shouldSyncPassword = false; + this.syncPassword = undefined; + } } ngModule.component('vnUserDescriptor', { diff --git a/modules/account/front/descriptor/locale/es.yml b/modules/account/front/descriptor/locale/es.yml index 5e8242819..98ced7694 100644 --- a/modules/account/front/descriptor/locale/es.yml +++ b/modules/account/front/descriptor/locale/es.yml @@ -22,6 +22,10 @@ Old password: Contraseña antigua New password: Nueva contraseña Repeat password: Repetir contraseña Password changed succesfully!: ¡Contraseña modificada correctamente! +Synchronize: Sincronizar +Do you want to synchronize user?: ¿Quieres sincronizar el usuario? +Synchronize password: Sincronizar contraseña +User synchronized!: ¡Usuario sincronizado! Role changed succesfully!: ¡Rol modificado correctamente! Password requirements: > La contraseña debe tener al menos {{ length }} caracteres de longitud, From ea5a881d1f4f35473e3984d161908fd3029f9000 Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Thu, 16 Nov 2023 23:10:30 +0100 Subject: [PATCH 372/427] fix: refs #6432 account sync fixes --- modules/account/back/models/samba-config.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/account/back/models/samba-config.js b/modules/account/back/models/samba-config.js index 1abac489c..b6692be02 100644 --- a/modules/account/back/models/samba-config.js +++ b/modules/account/back/models/samba-config.js @@ -139,7 +139,7 @@ module.exports = Self => { } })); } - if (changes.length) + if (changes.length && shouldSync) await this.adClient.modify(sambaUser.dn, changes); } }, From 6930c2d52e1e068e1437ed89f511e9d1b8d616d1 Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Thu, 16 Nov 2023 23:13:16 +0100 Subject: [PATCH 373/427] fix: #6432 account sync fixes --- Dockerfile | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Dockerfile b/Dockerfile index 814a5e1d8..d46a1a84c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -17,7 +17,8 @@ RUN apt-get update \ # Puppeteer -RUN apt-get install -y --no-install-recommends \ +RUN apt-get update \ + && apt-get install -y --no-install-recommends \ libfontconfig lftp xvfb gconf-service libasound2 libatk1.0-0 libc6 \ libcairo2 libcups2 libdbus-1-3 libexpat1 libfontconfig1 libgbm1 \ libgcc1 libgconf-2-4 libgdk-pixbuf2.0-0 libglib2.0-0 libgtk-3-0 \ @@ -28,7 +29,8 @@ RUN apt-get install -y --no-install-recommends \ # Extra dependencies -RUN apt-get install -y --no-install-recommends \ +RUN apt-get update \ + && apt-get install -y --no-install-recommends \ samba-common-bin \ && rm -rf /var/lib/apt/lists/* \ && npm -g install pm2 From 14eb14ad3f2540fd89fc4172e85d90f3b34bf8ae Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Fri, 17 Nov 2023 00:00:36 +0100 Subject: [PATCH 374/427] fix: refs #6432 bookworm upgrade --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index d46a1a84c..ce63da8ab 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM debian:bullseye-slim +FROM debian:bookworm-slim ENV TZ Europe/Madrid ARG DEBIAN_FRONTEND=noninteractive From c2e295f777026ae621864b1d31936a228997b2ce Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Fri, 17 Nov 2023 00:08:29 +0100 Subject: [PATCH 375/427] fix: refs #6432 account sync fixes --- modules/account/front/descriptor/index.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/modules/account/front/descriptor/index.js b/modules/account/front/descriptor/index.js index c327b0836..18d93b924 100644 --- a/modules/account/front/descriptor/index.js +++ b/modules/account/front/descriptor/index.js @@ -122,10 +122,10 @@ class Controller extends Descriptor { } onSync() { - let params = { - password: this.syncPassword, - force: true - }; + const params = {force: true}; + if (this.shouldSyncPassword) + params.password = this.syncPassword; + return this.$http.patch(`Accounts/${this.user.name}/sync`, params) .then(() => this.vnApp.showSuccess(this.$t('User synchronized!'))); } From 2f611391b98c39e3d5b0480dbc634f659d961535 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 17 Nov 2023 07:17:29 +0100 Subject: [PATCH 376/427] Revert "refactor: refs #4502 Deleted zoneEstimatedDelivery" This reverts commit bfd6e1f39843abb02694fa2ebdb52e95df4f2bd4. --- .../back/methods/sales-monitor/salesFilter.js | 71 +++++-------- modules/order/back/methods/order/filter.js | 99 +++++++------------ modules/zone/back/model-config.json | 3 + .../back/models/zone-estimated-delivery.json | 44 +++++++++ 4 files changed, 105 insertions(+), 112 deletions(-) create mode 100644 modules/zone/back/models/zone-estimated-delivery.json diff --git a/modules/monitor/back/methods/sales-monitor/salesFilter.js b/modules/monitor/back/methods/sales-monitor/salesFilter.js index 85945a57d..693ae122f 100644 --- a/modules/monitor/back/methods/sales-monitor/salesFilter.js +++ b/modules/monitor/back/methods/sales-monitor/salesFilter.js @@ -163,14 +163,17 @@ module.exports = Self => { const stmts = []; let stmt; + stmts.push('DROP TEMPORARY TABLE IF EXISTS tmp.filter'); + stmts.push(`SET @_optimizer_search_depth = @@optimizer_search_depth`); stmts.push(`SET SESSION optimizer_search_depth = 0`); - stmt = new ParameterizedSQL(` - CREATE OR REPLACE TEMPORARY TABLE tmp.filter + stmt = new ParameterizedSQL( + `CREATE TEMPORARY TABLE tmp.filter (PRIMARY KEY (id)) ENGINE = MEMORY - SELECT t.id, + SELECT + t.id, t.shipped, CAST(DATE(t.shipped) AS CHAR) AS shippedDate, t.nickname, @@ -180,27 +183,27 @@ module.exports = Self => { t.clientFk, t.totalWithoutVat, t.totalWithVat, - io.id invoiceOutId, + io.id AS invoiceOutId, a.provinceFk, - p.name province, - w.name warehouse, - am.name agencyMode, - am.id agencyModeFk, - st.name state, - wk.lastName salesPerson, - ts.stateFk stateFk, - ts.alertLevel alertLevel, - ts.code alertLevelCode, - u.name userName, + p.name AS province, + w.name AS warehouse, + am.name AS agencyMode, + am.id AS agencyModeFk, + st.name AS state, + wk.lastName AS salesPerson, + ts.stateFk AS stateFk, + ts.alertLevel AS alertLevel, + ts.code AS alertLevelCode, + u.name AS userName, c.salesPersonFk, c.credit, - z.hour zoneLanding, - z.name zoneName, - z.id zoneFk, + z.hour AS zoneLanding, + z.name AS zoneName, + z.id AS zoneFk, st.classColor, - TIME_FORMAT(t.shipped, '%H:%i') preparationHour, - TIME_FORMAT(z.hour, '%H:%i') theoreticalhour, - TIME_FORMAT(zed.etc, '%H:%i') practicalHour + TIME_FORMAT(t.shipped, '%H:%i') AS preparationHour, + TIME_FORMAT(z.hour, '%H:%i') AS theoreticalhour, + TIME_FORMAT(zed.etc, '%H:%i') AS practicalHour FROM ticket t LEFT JOIN invoiceOut io ON t.refFk = io.ref LEFT JOIN zone z ON z.id = t.zoneFk @@ -213,33 +216,7 @@ module.exports = Self => { LEFT JOIN client c ON c.id = t.clientFk LEFT JOIN worker wk ON wk.id = c.salesPersonFk LEFT JOIN account.user u ON u.id = wk.id - LEFT JOIN ( - SELECT zoneFk, - CAST(zoneHour + remainingVolume * 60 / speed AS time) etc - FROM ( - SELECT t.zoneFk, - IFNULL(zc.hour, z.hour) zoneHour, - SUM(IF(al.hasToRecalcPrice, sv.volume, 0)) remainingVolume, - GREATEST(IFNULL(lhp.m3, 0), IFNULL(dl.minSpeed, 0)) speed - FROM ticket t - JOIN ticketStateToday tst ON tst.ticket = t.id - JOIN state s ON s.id = tst.state - JOIN saleVolume sv ON sv.ticketFk = t.id - LEFT JOIN lastHourProduction lhp ON lhp.warehouseFk = t.warehouseFk - JOIN warehouse w ON w.id = t.warehouseFk - JOIN warehouseAlias wa ON wa.id = w.aliasFk - STRAIGHT_JOIN zone z ON z.id = t.zoneFk - LEFT JOIN zoneClosure zc ON zc.zoneFk = t.zoneFk - AND zc.dated = util.VN_CURDATE() - LEFT JOIN cache.departure_limit dl ON dl.warehouse_id = t.warehouseFk - AND dl.fecha = util.VN_CURDATE() - JOIN alertLevel al ON al.id = s.alertLevel - WHERE w.hasProduction - AND DATE(t.shipped) = util.VN_CURDATE() - GROUP BY t.zoneFk - ) sub - ) zed ON zed.zoneFk = t.zoneFk` - ); + LEFT JOIN zoneEstimatedDelivery zed ON zed.zoneFk = t.zoneFk`); if (args.orderFk) { stmt.merge({ diff --git a/modules/order/back/methods/order/filter.js b/modules/order/back/methods/order/filter.js index 27484acb9..44d8ccb10 100644 --- a/modules/order/back/methods/order/filter.js +++ b/modules/order/back/methods/order/filter.js @@ -140,71 +140,40 @@ module.exports = Self => { const stmts = []; let stmt; - stmt = new ParameterizedSQL(` - CREATE OR REPLACE TEMPORARY TABLE tmp.filter - (INDEX (id)) - ENGINE = MEMORY - SELECT o.id, - o.total, - o.date_send landed, - o.date_make created, - o.customer_id clientFk, - o.agency_id agencyModeFk, - o.address_id addressFk, - o.company_id companyFk, - o.source_app sourceApp, - o.confirmed isConfirmed, - c.name clientName, - c.salesPersonFk, - u.nickname workerNickname, - u.name name, - co.code companyCode, - zed.zoneFk, - zed.hourTheoretical, - zed.hourEffective, - am.name agencyName - FROM hedera.order o - LEFT JOIN address a ON a.id = o.address_id - LEFT JOIN agencyMode am ON am.id = o.agency_id - LEFT JOIN client c ON c.id = o.customer_id - LEFT JOIN worker wk ON wk.id = c.salesPersonFk - LEFT JOIN account.user u ON u.id = wk.id - LEFT JOIN company co ON co.id = o.company_id - LEFT JOIN orderTicket ot ON ot.orderFk = o.id - LEFT JOIN ticket t ON t.id = ot.ticketFk - LEFT JOIN ( - SELECT zoneFk, - CAST( - util.VN_CURDATE() + - INTERVAL HOUR(zoneHour) * 60 + MINUTE(zoneHour) MINUTE - AS time - ) hourTheoretical, - CAST(zoneHour + remainingVolume * 60 / speed AS time) hourEffective - FROM ( - SELECT t.zoneFk, - IFNULL(zc.hour, z.hour) zoneHour, - CAST(SUM(sv.volume) AS DECIMAL(5, 1)) totalVolume, - SUM(IF(al.hasToRecalcPrice, sv.volume, 0)) remainingVolume, - GREATEST(IFNULL(lhp.m3, 0), IFNULL(dl.minSpeed, 0)) speed - FROM ticket t - JOIN ticketStateToday tst ON tst.ticket = t.id - JOIN state s ON s.id = tst.state - JOIN saleVolume sv ON sv.ticketFk = t.id - LEFT JOIN lastHourProduction lhp ON lhp.warehouseFk = t.warehouseFk - JOIN warehouse w ON w.id = t.warehouseFk - JOIN warehouseAlias wa ON wa.id = w.aliasFk - STRAIGHT_JOIN zone z ON z.id = t.zoneFk - LEFT JOIN zoneClosure zc ON zc.zoneFk = t.zoneFk - AND zc.dated = util.VN_CURDATE() - LEFT JOIN cache.departure_limit dl ON dl.warehouse_id = t.warehouseFk - AND dl.fecha = util.VN_CURDATE() - JOIN alertLevel al ON al.id = s.alertLevel - WHERE w.hasProduction - AND DATE(t.shipped) = util.VN_CURDATE() - GROUP BY t.zoneFk - ) sub - ) zed ON zed.zoneFk = t.zoneFk - `); + stmt = new ParameterizedSQL( + `CREATE OR REPLACE TEMPORARY TABLE tmp.filter + (INDEX (id)) + ENGINE = MEMORY + SELECT + o.id, + o.total, + o.date_send landed, + o.date_make created, + o.customer_id clientFk, + o.agency_id agencyModeFk, + o.address_id addressFk, + o.company_id companyFk, + o.source_app sourceApp, + o.confirmed isConfirmed, + c.name clientName, + c.salesPersonFk, + u.nickname workerNickname, + u.name name, + co.code companyCode, + zed.zoneFk, + zed.hourTheoretical, + zed.hourEffective, + am.name AS agencyName + FROM hedera.order o + LEFT JOIN address a ON a.id = o.address_id + LEFT JOIN agencyMode am ON am.id = o.agency_id + LEFT JOIN client c ON c.id = o.customer_id + LEFT JOIN worker wk ON wk.id = c.salesPersonFk + LEFT JOIN account.user u ON u.id = wk.id + LEFT JOIN company co ON co.id = o.company_id + LEFT JOIN orderTicket ot ON ot.orderFk = o.id + LEFT JOIN ticket t ON t.id = ot.ticketFk + LEFT JOIN zoneEstimatedDelivery zed ON zed.zoneFk = t.zoneFk`); stmt.merge(conn.makeWhere(filter.where)); stmt.merge(`GROUP BY id`); diff --git a/modules/zone/back/model-config.json b/modules/zone/back/model-config.json index 43d2cb570..261a89902 100644 --- a/modules/zone/back/model-config.json +++ b/modules/zone/back/model-config.json @@ -35,6 +35,9 @@ "ZoneWarehouse": { "dataSource": "vn" }, + "ZoneEstimatedDelivery": { + "dataSource": "vn" + }, "ZoneLog": { "dataSource": "vn" } diff --git a/modules/zone/back/models/zone-estimated-delivery.json b/modules/zone/back/models/zone-estimated-delivery.json new file mode 100644 index 000000000..399de8f58 --- /dev/null +++ b/modules/zone/back/models/zone-estimated-delivery.json @@ -0,0 +1,44 @@ +{ + "name": "ZoneEstimatedDelivery", + "base": "VnModel", + "options": { + "mysql": { + "table": "zoneEstimatedDelivery" + } + }, + "properties": { + "zoneFk": { + "id": true, + "type": "number" + }, + "hourTheoretical": { + "type": "date" + }, + "totalVolume": { + "type": "number" + }, + "remainingVolume": { + "type": "number" + }, + "speed": { + "type": "number" + }, + "hourEffective": { + "type": "date" + }, + "minutesLess": { + "type": "date" + }, + "etc": { + "type": "date" + } + + }, + "relations": { + "zone": { + "type": "belongsTo", + "model": "Zone", + "foreignKey": "zoneFk" + } + } +} \ No newline at end of file From 3d1c69be5618abd37848dee6d20986840d193806 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 17 Nov 2023 07:43:32 +0100 Subject: [PATCH 377/427] refactor: refs #4502 zoneEstimatedDelivery --- .../back/methods/sales-monitor/salesFilter.js | 104 ++++++++++-------- modules/order/back/methods/order/filter.js | 84 ++++++++------ .../back/models/zone-estimated-delivery.json | 24 ++-- 3 files changed, 117 insertions(+), 95 deletions(-) diff --git a/modules/monitor/back/methods/sales-monitor/salesFilter.js b/modules/monitor/back/methods/sales-monitor/salesFilter.js index 693ae122f..2c62977f3 100644 --- a/modules/monitor/back/methods/sales-monitor/salesFilter.js +++ b/modules/monitor/back/methods/sales-monitor/salesFilter.js @@ -168,55 +168,65 @@ module.exports = Self => { stmts.push(`SET @_optimizer_search_depth = @@optimizer_search_depth`); stmts.push(`SET SESSION optimizer_search_depth = 0`); - stmt = new ParameterizedSQL( - `CREATE TEMPORARY TABLE tmp.filter + stmt = new ParameterizedSQL(` + CREATE TEMPORARY TABLE tmp.filter (PRIMARY KEY (id)) ENGINE = MEMORY - SELECT - t.id, - t.shipped, - CAST(DATE(t.shipped) AS CHAR) AS shippedDate, - t.nickname, - t.refFk, - t.routeFk, - t.warehouseFk, - t.clientFk, - t.totalWithoutVat, - t.totalWithVat, - io.id AS invoiceOutId, - a.provinceFk, - p.name AS province, - w.name AS warehouse, - am.name AS agencyMode, - am.id AS agencyModeFk, - st.name AS state, - wk.lastName AS salesPerson, - ts.stateFk AS stateFk, - ts.alertLevel AS alertLevel, - ts.code AS alertLevelCode, - u.name AS userName, - c.salesPersonFk, - c.credit, - z.hour AS zoneLanding, - z.name AS zoneName, - z.id AS zoneFk, - st.classColor, - TIME_FORMAT(t.shipped, '%H:%i') AS preparationHour, - TIME_FORMAT(z.hour, '%H:%i') AS theoreticalhour, - TIME_FORMAT(zed.etc, '%H:%i') AS practicalHour - FROM ticket t - LEFT JOIN invoiceOut io ON t.refFk = io.ref - LEFT JOIN zone z ON z.id = t.zoneFk - LEFT JOIN address a ON a.id = t.addressFk - LEFT JOIN province p ON p.id = a.provinceFk - LEFT JOIN warehouse w ON w.id = t.warehouseFk - LEFT JOIN agencyMode am ON am.id = t.agencyModeFk - LEFT JOIN ticketState ts ON ts.ticketFk = t.id - LEFT JOIN state st ON st.id = ts.stateFk - LEFT JOIN client c ON c.id = t.clientFk - LEFT JOIN worker wk ON wk.id = c.salesPersonFk - LEFT JOIN account.user u ON u.id = wk.id - LEFT JOIN zoneEstimatedDelivery zed ON zed.zoneFk = t.zoneFk`); + SELECT t.id, + t.shipped, + CAST(DATE(t.shipped) AS CHAR) shippedDate, + t.nickname, + t.refFk, + t.routeFk, + t.warehouseFk, + t.clientFk, + t.totalWithoutVat, + t.totalWithVat, + io.id invoiceOutId, + a.provinceFk, + p.name province, + w.name warehouse, + am.name agencyMode, + am.id agencyModeFk, + st.name state, + wk.lastName salesPerson, + ts.stateFk stateFk, + ts.alertLevel alertLevel, + ts.code alertLevelCode, + u.name userName, + c.salesPersonFk, + c.credit, + z.hour zoneLanding, + z.name zoneName, + z.id zoneFk, + st.classColor, + TIME_FORMAT(t.shipped, '%H:%i') preparationHour, + TIME_FORMAT(z.hour, '%H:%i') theoreticalhour, + TIME_FORMAT(zed.etc, '%H:%i') practicalHour + FROM ticket t + LEFT JOIN invoiceOut io ON t.refFk = io.ref + LEFT JOIN zone z ON z.id = t.zoneFk + LEFT JOIN address a ON a.id = t.addressFk + LEFT JOIN province p ON p.id = a.provinceFk + LEFT JOIN warehouse w ON w.id = t.warehouseFk + LEFT JOIN agencyMode am ON am.id = t.agencyModeFk + LEFT JOIN ticketState ts ON ts.ticketFk = t.id + LEFT JOIN state st ON st.id = ts.stateFk + LEFT JOIN client c ON c.id = t.clientFk + LEFT JOIN worker wk ON wk.id = c.salesPersonFk + LEFT JOIN account.user u ON u.id = wk.id + LEFT JOIN ( + SELECT zoneFk, + CAST( + IFNULL(zoneClosureHour, zoneHour) + + SUM(IF(hasToRecalcPrice, volume, 0)) * 60 / + GREATEST(IFNULL(m3, 0), IFNULL(minSpeed, 0)) + AS time + ) etc + FROM zoneEstimatedDelivery + GROUP BY zoneFk + ) zed ON zed.zoneFk = t.zoneFk + `); if (args.orderFk) { stmt.merge({ diff --git a/modules/order/back/methods/order/filter.js b/modules/order/back/methods/order/filter.js index 44d8ccb10..97fca5c10 100644 --- a/modules/order/back/methods/order/filter.js +++ b/modules/order/back/methods/order/filter.js @@ -140,40 +140,56 @@ module.exports = Self => { const stmts = []; let stmt; - stmt = new ParameterizedSQL( - `CREATE OR REPLACE TEMPORARY TABLE tmp.filter - (INDEX (id)) - ENGINE = MEMORY - SELECT - o.id, - o.total, - o.date_send landed, - o.date_make created, - o.customer_id clientFk, - o.agency_id agencyModeFk, - o.address_id addressFk, - o.company_id companyFk, - o.source_app sourceApp, - o.confirmed isConfirmed, - c.name clientName, - c.salesPersonFk, - u.nickname workerNickname, - u.name name, - co.code companyCode, - zed.zoneFk, - zed.hourTheoretical, - zed.hourEffective, - am.name AS agencyName - FROM hedera.order o - LEFT JOIN address a ON a.id = o.address_id - LEFT JOIN agencyMode am ON am.id = o.agency_id - LEFT JOIN client c ON c.id = o.customer_id - LEFT JOIN worker wk ON wk.id = c.salesPersonFk - LEFT JOIN account.user u ON u.id = wk.id - LEFT JOIN company co ON co.id = o.company_id - LEFT JOIN orderTicket ot ON ot.orderFk = o.id - LEFT JOIN ticket t ON t.id = ot.ticketFk - LEFT JOIN zoneEstimatedDelivery zed ON zed.zoneFk = t.zoneFk`); + stmt = new ParameterizedSQL(` + CREATE OR REPLACE TEMPORARY TABLE tmp.filter + (INDEX (id)) + ENGINE = MEMORY + SELECT o.id, + o.total, + o.date_send landed, + o.date_make created, + o.customer_id clientFk, + o.agency_id agencyModeFk, + o.address_id addressFk, + o.company_id companyFk, + o.source_app sourceApp, + o.confirmed isConfirmed, + c.name clientName, + c.salesPersonFk, + u.nickname workerNickname, + u.name name, + co.code companyCode, + zed.zoneFk, + zed.hourTheoretical, + zed.hourEffective, + am.name agencyName + FROM hedera.order o + LEFT JOIN address a ON a.id = o.address_id + LEFT JOIN agencyMode am ON am.id = o.agency_id + LEFT JOIN client c ON c.id = o.customer_id + LEFT JOIN worker wk ON wk.id = c.salesPersonFk + LEFT JOIN account.user u ON u.id = wk.id + LEFT JOIN company co ON co.id = o.company_id + LEFT JOIN orderTicket ot ON ot.orderFk = o.id + LEFT JOIN ticket t ON t.id = ot.ticketFk + LEFT JOIN ( + SELECT zoneFk, + CAST( + util.VN_CURDATE() + + INTERVAL HOUR(IFNULL(zoneClosureHour, zoneHour)) * 60 + + MINUTE(IFNULL(zoneClosureHour, zoneHour)) MINUTE + AS time + ) hourTheoretical, + CAST( + IFNULL(zoneClosureHour, zoneHour) + + SUM(IF(hasToRecalcPrice, volume, 0)) * 60 / + GREATEST(IFNULL(m3, 0), IFNULL(minSpeed, 0)) + AS time + ) hourEffective + FROM zoneEstimatedDelivery + GROUP BY zoneFk + ) zed ON zed.zoneFk = t.zoneFk + `); stmt.merge(conn.makeWhere(filter.where)); stmt.merge(`GROUP BY id`); diff --git a/modules/zone/back/models/zone-estimated-delivery.json b/modules/zone/back/models/zone-estimated-delivery.json index 399de8f58..a01754484 100644 --- a/modules/zone/back/models/zone-estimated-delivery.json +++ b/modules/zone/back/models/zone-estimated-delivery.json @@ -11,28 +11,24 @@ "id": true, "type": "number" }, - "hourTheoretical": { + "zoneClosureHour": { "type": "date" }, - "totalVolume": { + "zoneHour": { + "type": "date" + }, + "volume": { "type": "number" }, - "remainingVolume": { + "hasToRecalcPrice": { + "type": "boolean" + }, + "m3": { "type": "number" }, - "speed": { + "minSpeed": { "type": "number" - }, - "hourEffective": { - "type": "date" - }, - "minutesLess": { - "type": "date" - }, - "etc": { - "type": "date" } - }, "relations": { "zone": { From 8da36569f77ca87810a97d7cf2b3e742a4265c45 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 17 Nov 2023 07:44:43 +0100 Subject: [PATCH 378/427] refactor: refs #4502 zoneEstimatedDelivery --- modules/monitor/back/methods/sales-monitor/salesFilter.js | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/modules/monitor/back/methods/sales-monitor/salesFilter.js b/modules/monitor/back/methods/sales-monitor/salesFilter.js index 2c62977f3..301e4ac35 100644 --- a/modules/monitor/back/methods/sales-monitor/salesFilter.js +++ b/modules/monitor/back/methods/sales-monitor/salesFilter.js @@ -162,14 +162,12 @@ module.exports = Self => { const stmts = []; let stmt; - - stmts.push('DROP TEMPORARY TABLE IF EXISTS tmp.filter'); - + stmts.push(`SET @_optimizer_search_depth = @@optimizer_search_depth`); stmts.push(`SET SESSION optimizer_search_depth = 0`); stmt = new ParameterizedSQL(` - CREATE TEMPORARY TABLE tmp.filter + CREATE OR REPLACE TEMPORARY TABLE tmp.filter (PRIMARY KEY (id)) ENGINE = MEMORY SELECT t.id, From bb6f3b4cfde1f3bf7608384d8987371c39bcb9ee Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Fri, 17 Nov 2023 08:56:25 +0100 Subject: [PATCH 379/427] fix: refs #6432 account sync fixes --- Dockerfile | 2 +- modules/account/back/models/samba-config.js | 20 ++++++++++++-------- modules/account/front/samba/index.html | 19 ++++++++++++------- modules/account/front/samba/locale/es.yml | 1 + 4 files changed, 26 insertions(+), 16 deletions(-) diff --git a/Dockerfile b/Dockerfile index ce63da8ab..61dd758b8 100644 --- a/Dockerfile +++ b/Dockerfile @@ -31,7 +31,7 @@ RUN apt-get update \ RUN apt-get update \ && apt-get install -y --no-install-recommends \ - samba-common-bin \ + samba-common-bin samba-dsdb-modules\ && rm -rf /var/lib/apt/lists/* \ && npm -g install pm2 diff --git a/modules/account/back/models/samba-config.js b/modules/account/back/models/samba-config.js index b6692be02..7714fb01c 100644 --- a/modules/account/back/models/samba-config.js +++ b/modules/account/back/models/samba-config.js @@ -33,16 +33,17 @@ module.exports = Self => { .split('.') .map(part => `dc=${part}`) .join(','); - const ldapUser = `cn=${this.adUser},cn=Users,${baseDn}`; + const bindDn = `cn=${this.adUser},cn=Users,${baseDn}`; const adClient = ldap.createClient({ url: `ldaps://${this.adController}:636`, tlsOptions: {rejectUnauthorized: this.verifyCert} }); - await adClient.bind(ldapUser, this.adPassword); + await adClient.bind(bindDn, this.adPassword); Object.assign(this, { adClient, - fullUsersDn: `${this.userDn},${baseDn}` + fullUsersDn: `${this.userDn},${baseDn}`, + bindDn }); }, @@ -51,11 +52,14 @@ module.exports = Self => { }, async sambaTool(command, args = []) { - const authArgs = [ - '--URL', `ldap://${this.adController}`, - '--username', this.adUser, + let authArgs = [ + '--URL', `ldaps://${this.adController}`, + '--simple-bind-dn', this.bindDn, '--password', this.adPassword ]; + if (!this.verifyCert) + authArgs.push('--option', 'tls verify peer = no_check'); + const allArgs = [command].concat( args, authArgs ); @@ -151,8 +155,8 @@ module.exports = Self => { */ async getUsers(usersToSync) { const LDAP_MATCHING_RULE_BIT_AND = '1.2.840.113556.1.4.803'; - // eslint-disable-next-line max-len - const filter = `!(userAccountControl:${LDAP_MATCHING_RULE_BIT_AND}:=${UserAccountControlFlags.ACCOUNTDISABLE})`; + const filter = `!(userAccountControl:${LDAP_MATCHING_RULE_BIT_AND}` + + `:=${UserAccountControlFlags.ACCOUNTDISABLE})`; const opts = { scope: 'sub', diff --git a/modules/account/front/samba/index.html b/modules/account/front/samba/index.html index 4379f10a2..0186cac7c 100644 --- a/modules/account/front/samba/index.html +++ b/modules/account/front/samba/index.html @@ -12,7 +12,7 @@ @@ -20,28 +20,33 @@ ng-if="watcher.hasData" class="vn-mt-md"> + + @@ -63,4 +68,4 @@ ng-click="watcher.loadOriginalData()"> - \ No newline at end of file + diff --git a/modules/account/front/samba/locale/es.yml b/modules/account/front/samba/locale/es.yml index d098a4fbe..efa3b1597 100644 --- a/modules/account/front/samba/locale/es.yml +++ b/modules/account/front/samba/locale/es.yml @@ -3,6 +3,7 @@ Domain controller: Controlador de dominio AD domain: Dominio AD AD user: Usuario AD AD password: Contraseña AD +User DN (without domain part): DN usuarios (sin la parte del dominio) Verify certificate: Verificar certificado Test connection: Probar conexión Samba connection established!: ¡Conexión con Samba establecida! From dc100f795989f449c60344040ec96eecb715963c Mon Sep 17 00:00:00 2001 From: pablone Date: Fri, 17 Nov 2023 11:29:57 +0100 Subject: [PATCH 380/427] fix(filter): refs #6461 now is mockDate in local --- modules/invoiceOut/front/negative-bases/index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/invoiceOut/front/negative-bases/index.js b/modules/invoiceOut/front/negative-bases/index.js index f60668b20..7ce610513 100644 --- a/modules/invoiceOut/front/negative-bases/index.js +++ b/modules/invoiceOut/front/negative-bases/index.js @@ -7,7 +7,7 @@ export default class Controller extends Section { super($element, $); this.vnReport = vnReport; - const now = new Date(); + const now = Date.vnNew(); const firstDayOfMonth = new Date(now.getFullYear(), now.getMonth(), 1); const lastDayOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0); this.params = { From 61b2d4c5fdc06d0e7fdb312a3b1e3d71de51d9dc Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 20 Nov 2023 09:47:57 +0100 Subject: [PATCH 381/427] refactor: refs #4502 zoneEstimatedDelivery --- db/dump/structure.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/dump/structure.sql b/db/dump/structure.sql index 3d6156580..e90367682 100644 --- a/db/dump/structure.sql +++ b/db/dump/structure.sql @@ -82151,7 +82151,7 @@ USE `vn`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `zoneEstimatedDelivery` AS select `t`.`zoneFk` AS `zoneFk`,cast(`util`.`VN_CURDATE`() + interval hour(ifnull(`zc`.`hour`,`z`.`hour`)) * 60 + minute(ifnull(`zc`.`hour`,`z`.`hour`)) minute as time) AS `hourTheoretical`,cast(sum(`sv`.`volume`) as decimal(5,1)) AS `totalVolume`,cast(sum(if(`s`.`alertLevel` < 2,`sv`.`volume`,0)) as decimal(5,1)) AS `remainingVolume`,greatest(ifnull(`lhp`.`m3`,0),ifnull(`dl`.`minSpeed`,0)) AS `speed`,cast(`zc`.`hour` + interval -sum(if(`s`.`alertLevel` < 2,`sv`.`volume`,0)) * 60 / greatest(ifnull(`lhp`.`m3`,0),ifnull(`dl`.`minSpeed`,0)) minute as time) AS `hourEffective`,floor(-sum(if(`s`.`alertLevel` < 2,`sv`.`volume`,0)) * 60 / greatest(ifnull(`lhp`.`m3`,0),ifnull(`dl`.`minSpeed`,0))) AS `minutesLess`,cast(`zc`.`hour` + interval -sum(if(`s`.`alertLevel` < 2,`sv`.`volume`,0)) * 60 / greatest(ifnull(`lhp`.`m3`,0),ifnull(`dl`.`minSpeed`,0)) minute as time) AS `etc` from (((((((((`vn`.`ticket` `t` join `vn`.`ticketStateToday` `tst` on(`tst`.`ticket` = `t`.`id`)) join `vn`.`state` `s` on(`s`.`id` = `tst`.`state`)) join `vn`.`saleVolume` `sv` on(`sv`.`ticketFk` = `t`.`id`)) left join `vn`.`lastHourProduction` `lhp` on(`lhp`.`warehouseFk` = `t`.`warehouseFk`)) join `vn`.`warehouse` `w` on(`w`.`id` = `t`.`warehouseFk`)) join `vn`.`warehouseAlias` `wa` on(`wa`.`id` = `w`.`aliasFk`)) straight_join `vn`.`zone` `z` on(`z`.`id` = `t`.`zoneFk`)) left join `vn`.`zoneClosure` `zc` on(`zc`.`zoneFk` = `t`.`zoneFk` and `zc`.`dated` = `util`.`VN_CURDATE`())) left join `cache`.`departure_limit` `dl` on(`dl`.`warehouse_id` = `t`.`warehouseFk` and `dl`.`fecha` = `util`.`VN_CURDATE`())) where `w`.`hasProduction` <> 0 and cast(`t`.`shipped` as date) = `util`.`VN_CURDATE`() group by `t`.`zoneFk` */; +/*!50001 VIEW `zoneEstimatedDelivery` AS SELECT `t`.`zoneFk` AS `zoneFk`, `zc`.`hour` AS `zoneClosureHour`, `z`.`hour` AS `zoneHour`, `sv`.`volume` AS `volume`, `al`.`hasToRecalcPrice` AS `hasToRecalcPrice`, `lhp`.`m3` AS `m3`, `dl`.`minSpeed` AS `minSpeed` FROM ((((((((((`vn`.`ticket` `t` JOIN `vn`.`ticketStateToday` `tst` ON (`tst`.`ticket` = `t`.`id`)) JOIN `vn`.`state` `s` ON (`s`.`id` = `tst`.`state`)) JOIN `vn`.`saleVolume` `sv` ON (`sv`.`ticketFk` = `t`.`id`)) LEFT JOIN `vn`.`lastHourProduction` `lhp` ON (`lhp`.`warehouseFk` = `t`.`warehouseFk`)) JOIN `vn`.`warehouse` `w` ON (`w`.`id` = `t`.`warehouseFk`)) JOIN `vn`.`warehouseAlias` `wa` ON (`wa`.`id` = `w`.`aliasFk`)) STRAIGHT_JOIN `vn`.`zone` `z` ON (`z`.`id` = `t`.`zoneFk`)) LEFT JOIN `vn`.`zoneClosure` `zc` ON (`zc`.`zoneFk` = `t`.`zoneFk` AND `zc`.`dated` = `util`.`VN_CURDATE`())) LEFT JOIN `cache`.`departure_limit` `dl` ON (`dl`.`warehouse_id` = `t`.`warehouseFk` AND `dl`.`fecha` = `util`.`VN_CURDATE`())) JOIN `vn`.`alertLevel` `al` ON (`al`.`id` = `s`.`alertLevel`)) WHERE `w`.`hasProduction` <> 0 AND CAST(`t`.`shipped` AS date) = `util`.`VN_CURDATE`() */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; From ee1a0c15eeb615463dd7ae86aa4d0cf6a7cacb42 Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 20 Nov 2023 15:09:55 +0100 Subject: [PATCH 382/427] refs #6454 feat: dump db --- db/dump/dumpedFixtures.sql | 84 +- db/dump/fixtures.sql | 36 +- db/dump/structure.sql | 6508 ++++++++++------- db/export-data.sh | 6 +- loopback/locale/en.json | 6 +- modules/client/back/methods/client/filter.js | 9 +- .../ticket/specs/getSalespersonMana.spec.js | 2 +- 7 files changed, 3867 insertions(+), 2784 deletions(-) diff --git a/db/dump/dumpedFixtures.sql b/db/dump/dumpedFixtures.sql index 43eba7f24..3e46c8e04 100644 --- a/db/dump/dumpedFixtures.sql +++ b/db/dump/dumpedFixtures.sql @@ -22,7 +22,7 @@ USE `util`; LOCK TABLES `config` WRITE; /*!40000 ALTER TABLE `config` DISABLE KEYS */; -INSERT INTO `config` VALUES (1,'233401',0,'production',NULL,'2001-01-01 11:00:00',NULL,0); +INSERT INTO `config` VALUES (1,'234604',0,'production',NULL,'2001-01-01 11:00:00',NULL,0); /*!40000 ALTER TABLE `config` ENABLE KEYS */; UNLOCK TABLES; @@ -32,7 +32,7 @@ UNLOCK TABLES; LOCK TABLES `version` WRITE; /*!40000 ALTER TABLE `version` DISABLE KEYS */; -INSERT INTO `version` VALUES ('salix','10230','53f69ae8e526a4a5d827c237a5b076d38507b392','2020-11-09 11:06:43',NULL),('vn-database','10714','aeb89a7b54f62398ddbcf3a48c8d387f275fee47','2023-08-29 12:49:52','10716'); +INSERT INTO `version` VALUES ('salix','10230','53f69ae8e526a4a5d827c237a5b076d38507b392','2020-11-09 11:06:43',NULL),('vn-database','10761','6c1146271aa71f7c3332e11d50d6812752391ea4','2023-11-20 11:55:47','10778'); /*!40000 ALTER TABLE `version` ENABLE KEYS */; UNLOCK TABLES; @@ -42,7 +42,7 @@ UNLOCK TABLES; LOCK TABLES `versionLog` WRITE; /*!40000 ALTER TABLE `versionLog` DISABLE KEYS */; -INSERT INTO `versionLog` VALUES ('vn-database','00001','00-test.sql','juan@10.5.1.3','2022-01-31 10:12:26',NULL,NULL),('vn-database','00003','00-sage.sql','juan@10.5.1.3','2022-01-31 10:12:26',NULL,NULL),('vn-database','10008','00-alterRoleConfig.sql','juan@10.5.1.3','2022-01-31 10:12:26',NULL,NULL),('vn-database','10014','00-rolePrefix.sql','jenkins@10.0.2.68','2022-02-11 00:13:25',NULL,NULL),('vn-database','10017','01-firstScript.sql','jenkins@10.0.2.70','2022-03-09 11:36:54',NULL,NULL),('vn-database','10021','00-bankAccount.sql','jenkins@10.0.2.69','2022-03-16 14:11:22',NULL,NULL),('vn-database','10023','00-firstScript.sql','jenkins@10.0.2.69','2022-03-16 15:05:29',NULL,NULL),('vn-database','10026','00-invoiceInIntrastat.sql','jenkins@10.0.2.69','2022-03-21 15:10:53',NULL,NULL),('vn-database','10027','00-Clientes_cedidos.sql','jenkins@10.0.2.69','2022-03-22 15:58:12',NULL,NULL),('vn-database','10028','00-item_last_buy_.sql','jenkins@10.0.2.69','2022-03-22 15:58:12',NULL,NULL),('vn-database','10029','00-bankToViewAccountingToTable.sql','jenkins@10.0.2.69','2022-03-22 15:58:12',NULL,NULL),('vn-database','10030','00-KkejarNiche.sql','jenkins@10.0.2.69','2022-03-22 15:58:12',NULL,NULL),('vn-database','10036','00-updateBuyConfig.sql','jenkins@10.0.2.69','2022-03-29 12:36:54',NULL,NULL),('vn-database','10037','00-firstScript.sql','jenkins@10.0.2.69','2022-03-28 11:14:26',NULL,NULL),('vn-database','10038','00-printServerQueue.sql','jenkins@10.0.2.69','2022-03-29 08:13:24',NULL,NULL),('vn-database','10048','00-firstScript.sql','jenkins@10.0.2.69','2022-03-30 12:29:06',NULL,NULL),('vn-database','10058','00-vehicleAddFields.sql','jenkins@10.0.2.69','2022-04-06 08:48:34',NULL,NULL),('vn-database','10060','00-firstScript.sql','jenkins@10.0.2.69','2022-04-07 08:50:11',NULL,NULL),('vn-database','10062','00-firstScript.sql','jenkins@10.0.2.69','2022-04-06 10:51:45',NULL,NULL),('vn-database','10064','00-firstScript.sql','jenkins@10.0.2.69','2022-04-06 13:57:11',NULL,NULL),('vn-database','10066','00-firstScript.sql','jenkins@10.0.2.69','2022-04-07 08:50:12',NULL,NULL),('vn-database','10067','00-firstScript.sql','jenkins@10.0.2.69','2022-04-08 10:18:20',NULL,NULL),('vn-database','10071','00-packingSiteLog.sql','jenkins@10.0.2.69','2022-04-08 09:37:30',NULL,NULL),('vn-database','10072','00-firstScript.sql','jenkins@10.0.2.69','2022-04-08 11:01:46',NULL,NULL),('vn-database','10073','00-firstScript.sql','jenkins@10.0.2.69','2022-04-08 13:40:56',NULL,NULL),('vn-database','10074','00-firstScript.sql','jenkins@10.0.2.69','2022-04-10 13:15:05',NULL,NULL),('vn-database','10077','00-firstScript.sql','jenkins@10.0.2.69','2022-04-12 08:07:15',NULL,NULL),('vn-database','10078','00-firstScript.sql','jenkins@10.0.2.69','2022-04-13 07:44:21',NULL,NULL),('vn-database','10079','00-firstScript.sql','jenkins@10.0.2.69','2022-04-12 12:01:37',NULL,NULL),('vn-database','10086','00-firstScript.sql','jenkins@10.0.2.69','2022-04-13 08:58:34',NULL,NULL),('vn-database','10087','00-firstScript.sql','jenkins@10.0.2.69','2022-04-13 09:39:49',NULL,NULL),('vn-database','10088','00-firstScript.sql','jenkins@10.0.2.69','2022-04-13 15:05:12',NULL,NULL),('vn-database','10089','00-firstScript.sql','jenkins@10.0.2.69','2022-04-18 14:12:52',NULL,NULL),('vn-database','10090','00-firstScript.sql','jenkins@10.0.2.69','2022-04-18 14:34:46',NULL,NULL),('vn-database','10092','00-firstScript.sql','jenkins@10.0.2.69','2022-04-19 14:45:46',NULL,NULL),('vn-database','10093','00-autoradioConfig.sql','jenkins@10.0.2.69','2022-05-03 09:16:47',NULL,NULL),('vn-database','10094','00-firstScript.sql','jenkins@10.0.2.69','2022-04-20 10:57:30',NULL,NULL),('vn-database','10097','00-firstScript.sql','jenkins@10.0.2.69','2022-05-05 10:12:59',NULL,NULL),('vn-database','10099','00-firstScript.sql','jenkins@10.0.2.69','2022-04-20 14:35:27',NULL,NULL),('vn-database','10100','00-firstScript.sql','jenkins@10.0.2.69','2022-04-20 14:35:27',NULL,NULL),('vn-database','10101','00-firstScript.sql','jenkins@10.0.2.69','2022-04-21 14:59:31',NULL,NULL),('vn-database','10103','00-awbVolume.sql','jenkins@10.0.2.69','2022-05-05 10:12:59',NULL,NULL),('vn-database','10104','00-firstScript.sql','jenkins@10.0.2.69','2022-05-05 10:12:59',NULL,NULL),('vn-database','10105','00-firstScript.sql','jenkins@10.0.2.69','2022-05-05 10:13:00',NULL,NULL),('vn-database','10107','00-firstScript.sql','jenkins@10.0.2.69','2022-04-23 10:53:53',NULL,NULL),('vn-database','10112','00-firstScript.sql','jenkins@10.0.2.69','2022-05-09 09:14:53',NULL,NULL),('vn-database','10113','00-firstScript.sql','jenkins@10.0.2.69','2022-05-05 10:13:00',NULL,NULL),('vn-database','10114','00-updateConfig.sql','jenkins@10.0.2.69','2022-04-27 13:37:25',NULL,NULL),('vn-database','10116','00-firstScript.sql','jenkins@10.0.2.69','2022-04-28 11:10:14',NULL,NULL),('vn-database','10118','00-firstScript.sql','jenkins@10.0.2.69','2022-04-29 08:10:15',NULL,NULL),('vn-database','10119','00-AfegirFKPart1.sql','jenkins@10.0.2.69','2022-05-05 10:13:00',NULL,NULL),('vn-database','10119','01-AfegirFkPart2.sql','jenkins@10.0.2.69','2022-05-05 10:22:25',NULL,NULL),('vn-database','10125','00-firstScript.sql','jenkins@10.0.2.68','2022-05-18 18:44:30',NULL,NULL),('vn-database','10127','00-firstScript.sql','jenkins@10.0.2.69','2022-05-02 11:04:46',NULL,NULL),('vn-database','10128','00-firstScript.sql','jenkins@10.0.2.69','2022-05-02 13:04:31',NULL,NULL),('vn-database','10129','00-firstScript.sql','jenkins@10.0.2.69','2022-05-03 08:21:01',NULL,NULL),('vn-database','10132','00-firstScript.sql','jenkins@10.0.2.69','2022-05-05 10:22:25',NULL,NULL),('vn-database','10133','00-firstScript.sql','jenkins@10.0.2.69','2022-05-05 14:32:30',NULL,NULL),('vn-database','10134','00-firstScript.sql','jenkins@10.0.2.69','2022-05-06 07:45:25',NULL,NULL),('vn-database','10135','00-firstScript.sql','jenkins@10.0.2.69','2022-06-17 08:46:17',NULL,NULL),('vn-database','10136','00-workerTimeControl.sql','jenkins@10.0.2.69','2022-05-09 13:51:12',NULL,NULL),('vn-database','10138','00-firstScript.sql','jenkins@10.0.2.69','2022-05-10 13:58:05',NULL,NULL),('vn-database','10139','00-firstScript.sql','jenkins@10.0.2.68','2022-05-16 14:32:37',NULL,NULL),('vn-database','10139','01-secondScript.sql','jenkins@10.0.2.68','2022-05-17 12:16:13',NULL,NULL),('vn-database','10141','00-firstScript.sql','jenkins@10.0.2.70','2022-05-12 08:27:31',NULL,NULL),('vn-database','10142','00-firstScript.sql','jenkins@10.0.2.68','2022-05-20 09:20:31',NULL,NULL),('vn-database','10143','00-firstScript.sql','jenkins@10.0.2.68','2022-05-20 09:20:31',NULL,NULL),('vn-database','10144','00-AfegirFKPArt1.sql','jenkins@10.0.2.68','2022-05-20 09:22:33',NULL,NULL),('vn-database','10144','00-firstScript.sql','jenkins@10.0.2.68','2022-05-13 09:44:25',NULL,NULL),('vn-database','10147','00-firstScript.sql','jenkins@10.0.2.68','2022-05-20 09:22:33',NULL,NULL),('vn-database','10149','00-firstScript.sql','jenkins@10.0.2.68','2022-05-20 09:22:33',NULL,NULL),('vn-database','10150','00-firstScript.sql','jenkins@10.0.2.68','2022-05-17 09:57:16',NULL,NULL),('vn-database','10152','00-firstScript.sql','jenkins@10.0.2.68','2022-05-20 09:22:34',NULL,NULL),('vn-database','10153','00-firstScript.sql','jenkins@10.0.2.68','2022-05-20 09:22:34',NULL,NULL),('vn-database','10154','00-compressionKk.sql','jenkins@10.0.2.68','2022-05-20 09:22:34',NULL,NULL),('vn-database','10157','00-firstScript.sql','jenkins@10.0.2.68','2022-05-20 09:22:35',NULL,NULL),('vn-database','10158','00-firstScript.sql','jenkins@10.0.2.68','2022-06-02 12:47:21',NULL,NULL),('vn-database','10160','00-firstScript.sql','jenkins@10.0.2.69','2022-06-30 09:30:50',NULL,NULL),('vn-database','10163','00-firstScript.sql','jenkins@10.0.2.68','2022-05-23 08:17:14',NULL,NULL),('vn-database','10164','00-borrarSectorsDesus.sql','jenkins@10.0.2.68','2022-06-02 12:47:21',NULL,NULL),('vn-database','10165','00-firstScript.sql','jenkins@10.0.2.68','2022-06-02 12:47:22',NULL,NULL),('vn-database','10166','00-firstScript.sql','jenkins@10.0.2.68','2022-05-24 16:11:21',NULL,NULL),('vn-database','10167','00-renameVnActiveContrat.sql','jenkins@10.0.2.68','2022-06-02 12:47:22',NULL,NULL),('vn-database','10168','00-firstScript.sql','jenkins@10.0.2.68','2022-06-02 12:47:22',NULL,NULL),('vn-database','10169','00-createTableBankEntityConfig.sql','jenkins@10.0.2.68','2022-06-02 12:47:22',NULL,NULL),('vn-database','10169','02-addNotNullToBankEntityBic.sql','jenkins@10.0.2.68','2022-06-02 12:47:22',NULL,NULL),('vn-database','10171','00-volumeConfig.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-18 14:11:11',NULL,NULL),('vn-database','10171','01-itemWeight.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-18 16:01:34',NULL,NULL),('vn-database','10171','02-agencymode.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-18 16:01:34',NULL,NULL),('vn-database','10172','00-firstScript.sql','jenkins@10.0.2.68','2022-06-02 12:47:22',NULL,NULL),('vn-database','10174','00-firstScript.sql','jenkins@10.0.2.69','2022-06-17 08:46:17',NULL,NULL),('vn-database','10175','00-firstScript.sql','jenkins@10.0.2.69','2022-06-17 09:03:41',NULL,NULL),('vn-database','10177','00-crearTablaSpecialLabels.sql','jenkins@10.0.2.68','2022-06-02 12:47:22',NULL,NULL),('vn-database','10178','00-firstScript.sql','jenkins@10.0.2.68','2022-06-02 12:47:24',NULL,NULL),('vn-database','10179','00-firstScript.sql','jenkins@10.0.2.68','2022-06-02 12:47:24',NULL,NULL),('vn-database','10183','00-firstScript.sql','jenkins@10.0.2.68','2022-06-02 12:47:24',NULL,NULL),('vn-database','10184','00-firstScript.sql','jenkins@10.0.2.68','2022-06-03 08:05:34',NULL,NULL),('vn-database','10185','00-firstScript.sql','jenkins@10.0.2.68','2022-06-06 09:07:45',NULL,NULL),('vn-database','10186','00-desactivar_trigger.sql','jenkins@10.0.2.68','2022-06-07 09:31:23',NULL,NULL),('vn-database','10186','01-alter_Table_buy.sql','jenkins@10.0.2.68','2022-06-07 09:34:47',NULL,NULL),('vn-database','10186','02-alter_table_entryConfig.sql','jenkins@10.0.2.68','2022-06-07 09:34:47',NULL,NULL),('vn-database','10186','04-regularizar_Sticker_Inventario.sql','jenkins@10.0.2.68','2022-06-07 09:34:51',NULL,NULL),('vn-database','10186','09-reactivar_trigger.sql','jenkins@10.0.2.68','2022-06-07 09:34:51',NULL,NULL),('vn-database','10187','00-firstScript.sql','jenkins@10.0.2.68','2022-06-06 12:37:31',NULL,NULL),('vn-database','10188','00-firstScript.sql','jenkins@10.0.2.68','2022-06-06 14:03:36',NULL,NULL),('vn-database','10189','00-firstScript.sql','jenkins@10.0.2.69','2022-06-17 09:03:41',NULL,NULL),('vn-database','10191','00-firstScript.sql','jenkins@10.0.2.69','2022-06-17 09:03:41',NULL,NULL),('vn-database','10193','00-delete.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-15 12:14:35',NULL,NULL),('vn-database','10193','01-botanicExport.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-15 12:14:43',NULL,NULL),('vn-database','10193','02-item.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-15 12:14:44',NULL,NULL),('vn-database','10193','03-autonomy.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-15 12:14:44',NULL,NULL),('vn-database','10193','03-turn.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-15 12:14:44',NULL,NULL),('vn-database','10193','04-country.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-15 12:14:44',NULL,NULL),('vn-database','10194','00-firstScript.sql','jenkins@10.0.2.69','2022-06-17 09:03:41',NULL,NULL),('vn-database','10195','00-firstScript.sql','jenkins@10.0.2.69','2022-06-17 09:03:41',NULL,NULL),('vn-database','10200','00-firstScript.sql','jenkins@10.0.2.69','2022-06-17 09:04:00',NULL,NULL),('vn-database','10201','00-firstScript.sql','jenkins@10.0.2.69','2022-06-17 09:04:00',NULL,NULL),('vn-database','10202','00-Remove_FK_to_ediGenus.sql','jenkins@10.0.2.69','2022-06-17 09:04:00',NULL,NULL),('vn-database','10203','00-firstScript.sql','jenkins@10.0.2.69','2022-06-17 09:04:01',NULL,NULL),('vn-database','10204','00-firstScript.sql','jenkins@10.0.2.69','2022-06-17 09:04:01',NULL,NULL),('vn-database','10205','00-firstScript.sql','jenkins@10.0.2.69','2022-06-17 09:04:21',NULL,NULL),('vn-database','10207','00-Alter_table_entry.sql','jenkins@10.0.2.69','2022-06-16 07:22:50',NULL,NULL),('vn-database','10207','01-Update_invoiceAmount.sql','jenkins@10.0.2.69','2022-06-16 07:23:00',NULL,NULL),('vn-database','10208','00-firstScript.sql','jenkins@10.0.2.69','2022-06-30 09:31:26',NULL,NULL),('vn-database','10209','00-firstScript.sql','jenkins@10.0.2.69','2022-06-16 08:47:40',NULL,NULL),('vn-database','10210','00-firstScript.sql','jenkins@10.0.2.69','2022-06-16 17:39:17',1046,'Base de datos no seleccionada'),('vn-database','10211','01-firstScript.sql','jenkins@10.0.2.69','2022-06-17 07:11:27',NULL,NULL),('vn-database','10215','00-renameIsInventory.sql','jenkins@10.0.2.69','2022-06-30 09:31:26',NULL,NULL),('vn-database','10216','00-firstScript.sql','jenkins@10.0.2.69','2022-06-23 11:15:28',NULL,NULL),('vn-database','10216','01-batchIndex.sql','jenkins@10.0.2.70','2022-06-27 18:10:55',NULL,NULL),('vn-database','10219','00-AddCollectionFkOnPackingSite.sql','jenkins@10.0.2.70','2022-06-29 09:23:42',NULL,NULL),('vn-database','10219','01-AddFkToCollectionFk.sql','jenkins@10.0.2.70','2022-06-29 09:23:43',NULL,NULL),('vn-database','10220','00-createPersonalProtectionEquipment.sql','jenkins@10.0.2.69','2022-06-30 09:31:26',NULL,NULL),('vn-database','10222','00-firstScript.sql','jenkins@10.0.2.69','2022-07-14 09:12:40',NULL,NULL),('vn-database','10223','00-firstScript.sql','jenkins@10.0.2.69','2022-07-14 09:13:52',NULL,NULL),('vn-database','10224','00-cosetes.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-07-21 12:03:45',NULL,NULL),('vn-database','10229','00-firstScript.sql','jenkins@10.0.2.69','2022-07-01 11:59:34',NULL,NULL),('vn-database','10231','01-tablaEktConfig.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-11 09:25:39',NULL,NULL),('vn-database','10233','00-firstScript.sql','jenkins@10.0.2.69','2022-07-14 09:13:53',NULL,NULL),('vn-database','10235','00-firstScript.sql','jenkins@10.0.2.69','2022-07-14 09:13:53',NULL,NULL),('vn-database','10236','00-firstScript.sql','jenkins@10.0.2.69','2022-07-05 12:11:40',NULL,NULL),('vn-database','10237','00-firstScript.sql','jenkins@10.0.2.69','2022-07-14 09:13:53',NULL,NULL),('vn-database','10238','00-worker_mobileExtension.sql','jenkins@10.0.2.69','2022-07-14 09:14:09',NULL,NULL),('vn-database','10239','00-firstScript.sql','jenkins@10.0.2.69','2022-07-07 21:51:58',NULL,NULL),('vn-database','10241','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-07-29 08:14:01',NULL,NULL),('vn-database','10242','00-firstScript.sql','jenkins@10.0.2.69','2022-07-14 09:14:32',NULL,NULL),('vn-database','10243','00-firstScript.sql','jenkins@10.0.2.69','2022-07-14 09:14:32',NULL,NULL),('vn-database','10245','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-07-28 08:34:51',NULL,NULL),('vn-database','10247','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-07-28 08:34:51',NULL,NULL),('vn-database','10248','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-07-20 17:27:51',NULL,NULL),('vn-database','10250','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-07-28 08:36:40',NULL,NULL),('vn-database','10253','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-07-28 08:36:57',NULL,NULL),('vn-database','10254','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-07-28 08:38:48',NULL,NULL),('vn-database','10256','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-07-28 08:38:48',NULL,NULL),('vn-database','10258','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-12-16 09:14:48',NULL,NULL),('vn-database','10259','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-02 08:54:56',NULL,NULL),('vn-database','10261','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-07-22 08:42:20',NULL,NULL),('vn-database','10262','00-createTablepackagingWithFreight.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:22:13',NULL,NULL),('vn-database','10262','01-alterTablePackagingConfig.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:22:13',NULL,NULL),('vn-database','10262','02-insertsInicials.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:22:13',NULL,NULL),('vn-database','10262','03-createTablepackingWithoutFreight.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:22:14',NULL,NULL),('vn-database','10263','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-07-28 08:38:48',NULL,NULL),('vn-database','10265','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-07-28 08:38:48',NULL,NULL),('vn-database','10267','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-11 09:34:17',NULL,NULL),('vn-database','10267','01-fixMerge.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-11 09:34:17',NULL,NULL),('vn-database','10275','00-improvedGeneralLog.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-01 09:55:56',NULL,NULL),('vn-database','10277','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-08 10:26:32',NULL,NULL),('vn-database','10278','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-01 17:51:41',NULL,NULL),('vn-database','10279','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-11 09:34:17',NULL,NULL),('vn-database','10281','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-11 09:34:18',NULL,NULL),('vn-database','10282','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-11 09:34:18',NULL,NULL),('vn-database','10283','00-alterTable.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-11 09:34:18',NULL,NULL),('vn-database','10284','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-04 16:59:08',NULL,NULL),('vn-database','10285','00-firstScript.sql','jenkins@swarm-worker3.static.verdnatura.es','2022-08-05 09:19:33',NULL,NULL),('vn-database','10287','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-11 09:35:24',NULL,NULL),('vn-database','10288','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-11 09:35:24',NULL,NULL),('vn-database','10289','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:29:36',NULL,NULL),('vn-database','10291','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-10 14:19:34',NULL,NULL),('vn-database','10293','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-08 10:26:32',NULL,NULL),('vn-database','10297','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-16 12:43:36',NULL,NULL),('vn-database','10298','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-13 21:04:13',NULL,NULL),('vn-database','10299','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:22:14',NULL,NULL),('vn-database','10301','00-productionConfig.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:22:14',NULL,NULL),('vn-database','10301','01-drop.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:22:14',NULL,NULL),('vn-database','10301','02-collection.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:22:15',NULL,NULL),('vn-database','10302','00-CreateTableEntryType.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:22:15',NULL,NULL),('vn-database','10302','01-insertDataEntryType.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:22:15',NULL,NULL),('vn-database','10302','02-alterTableEntry.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:22:22',NULL,NULL),('vn-database','10303','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:22:23',NULL,NULL),('vn-database','10304','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:23:48',NULL,NULL),('vn-database','10304','01-altertableticket.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:23:51',NULL,NULL),('vn-database','10305','00-ektAssign.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:24:52',NULL,NULL),('vn-database','10306','00-deliveryInformation.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:25:25',NULL,NULL),('vn-database','10307','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:25:26',NULL,NULL),('vn-database','10308','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:26:43',NULL,NULL),('vn-database','10309','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-06 11:37:54',NULL,NULL),('vn-database','10310','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-08 10:26:33',NULL,NULL),('vn-database','10311','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-06 11:37:55',NULL,NULL),('vn-database','10312','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-08 10:26:33',NULL,NULL),('vn-database','10313','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-08 10:27:21',NULL,NULL),('vn-database','10314','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-20 12:37:19',NULL,NULL),('vn-database','10315','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-08 10:31:43',NULL,NULL),('vn-database','10317','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-08 10:31:43',NULL,NULL),('vn-database','10318','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-08 10:31:43',NULL,NULL),('vn-database','10319','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-20 12:37:41',NULL,NULL),('vn-database','10320','00-operator.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:29:37',NULL,NULL),('vn-database','10320','01-collection.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:29:37',NULL,NULL),('vn-database','10320','02-productionConfig.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:29:38',NULL,NULL),('vn-database','10321','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-08 11:11:12',NULL,NULL),('vn-database','10322','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-09 09:19:05',NULL,NULL),('vn-database','10326','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:29:38',NULL,NULL),('vn-database','10328','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:29:38',NULL,NULL),('vn-database','10329','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:29:38',NULL,NULL),('vn-database','10330','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:34:30',NULL,NULL),('vn-database','10332','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:34:30',NULL,NULL),('vn-database','10334','00-collectionHotbed.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:34:30',NULL,NULL),('vn-database','10334','01-saleGroupDetail.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:34:32',NULL,NULL),('vn-database','10335','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-10-06 09:52:38',NULL,NULL),('vn-database','10336','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:34:32',NULL,NULL),('vn-database','10337','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:34:32',NULL,NULL),('vn-database','10339','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-19 09:41:19',NULL,NULL),('vn-database','10340','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-29 11:08:03',NULL,NULL),('vn-database','10341','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:34:32',NULL,NULL),('vn-database','10342','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-29 11:08:03',NULL,NULL),('vn-database','10343','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:35:30',NULL,NULL),('vn-database','10345','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-11-04 08:25:16',NULL,NULL),('vn-database','10347','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-29 11:08:03',NULL,NULL),('vn-database','10347','01-addVirtualField.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-29 11:08:03',NULL,NULL),('vn-database','10349','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-10-06 09:52:38',NULL,NULL),('vn-database','10350','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-30 10:11:56',NULL,NULL),('vn-database','10352','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-11-04 08:25:16',NULL,NULL),('vn-database','10353','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-10-06 09:52:38',NULL,NULL),('vn-database','10354','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-10-06 09:52:38',NULL,NULL),('vn-database','10356','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-10 22:35:00',NULL,NULL),('vn-database','10356','01-orderConfigFk.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-10 22:35:00',NULL,NULL),('vn-database','10356','02-orderConfigDrop.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-10 22:35:00',NULL,NULL),('vn-database','10357','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-10-06 09:52:38',NULL,NULL),('vn-database','10359','00-improvedGeneralLog_collate.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-10-06 09:52:39',NULL,NULL),('vn-database','10360','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-10-06 09:52:39',NULL,NULL),('vn-database','10361','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-10-06 11:16:07',NULL,NULL),('vn-database','10362','00-dropUdfs.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-10-10 11:01:15',NULL,NULL),('vn-database','10363','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-11-04 08:25:17',NULL,NULL),('vn-database','10365','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-10-13 19:30:46',NULL,NULL),('vn-database','10368','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-11-04 08:25:17',NULL,NULL),('vn-database','10369','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-10-14 13:38:06',NULL,NULL),('vn-database','10370','00-deleteForeignKey.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-17 14:32:41',NULL,NULL),('vn-database','10370','01-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-17 14:32:47',NULL,NULL),('vn-database','10370','02-deleteTable.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-17 14:32:49',NULL,NULL),('vn-database','10370','03-accion.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-17 14:32:49',NULL,NULL),('vn-database','10370','04-inter.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-17 14:32:53',NULL,NULL),('vn-database','10371','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-12 10:56:23',NULL,NULL),('vn-database','10372','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-12-16 09:14:48',NULL,NULL),('vn-database','10373','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-10-19 08:31:58',NULL,NULL),('vn-database','10378','00-rename_routeUserPercentage.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-11-04 08:25:17',NULL,NULL),('vn-database','10379','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-09 08:40:16',NULL,NULL),('vn-database','10382','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-12-01 08:47:20',NULL,NULL),('vn-database','10383','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-17 14:32:53',NULL,NULL),('vn-database','10384','00-business_workcenterFk.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:18:01',NULL,NULL),('vn-database','10385','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-17 14:32:54',NULL,NULL),('vn-database','10386','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-17 14:32:54',NULL,NULL),('vn-database','10387','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-16 14:05:33',NULL,NULL),('vn-database','10388','00-resizeUtilVerionLogCode.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-12-01 08:47:20',NULL,NULL),('vn-database','10388','01-resizeUtilVersionCode.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-12-01 08:47:20',NULL,NULL),('vn-database','10390','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-12-01 08:50:16',NULL,NULL),('vn-database','10391','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-12 10:56:23',NULL,NULL),('vn-database','10394','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-12-01 08:50:24',NULL,NULL),('vn-database','10395','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-12-01 08:50:29',NULL,NULL),('vn-database','10396','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-17 15:36:38',NULL,NULL),('vn-database','10397','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-12-01 08:50:29',NULL,NULL),('vn-database','10399','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-12-01 08:50:29',NULL,NULL),('vn-database','10400','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-12-01 08:50:29',NULL,NULL),('vn-database','10402','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-21 14:11:31',NULL,NULL),('vn-database','10404','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-12-01 08:50:29',NULL,NULL),('vn-database','10405','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-16 09:58:22',NULL,NULL),('vn-database','10407','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-12-16 09:14:49',NULL,NULL),('vn-database','10408','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-12 10:56:23',NULL,NULL),('vn-database','10409','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-12-16 09:14:49',NULL,NULL),('vn-database','10412','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-30 12:45:44',NULL,NULL),('vn-database','10413','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-12 10:56:24',NULL,NULL),('vn-database','10416','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-12 10:56:24',NULL,NULL),('vn-database','10420','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-12 10:56:25',NULL,NULL),('vn-database','10421','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-12 10:56:26',NULL,NULL),('vn-database','10426','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-20 09:07:40',NULL,NULL),('vn-database','10428','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-26 13:27:05',NULL,NULL),('vn-database','10431','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-23 09:09:22',NULL,NULL),('vn-database','10433','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-26 13:27:05',NULL,NULL),('vn-database','10434','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-26 13:27:05',NULL,NULL),('vn-database','10435','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-13 07:30:10',NULL,NULL),('vn-database','10436','00-createFkWorker.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-16 09:58:59',NULL,NULL),('vn-database','10436','01-addStateToWorkerProductivity.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-16 09:59:00',NULL,NULL),('vn-database','10436','02-DeprecateVnSaleTrackingState.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-16 09:59:00',NULL,NULL),('vn-database','10436','03-DeprecateColumnVnSaleTrackingActionFk.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-16 09:59:01',NULL,NULL),('vn-database','10436','04-DropSchemaVnControl.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-16 09:59:01',NULL,NULL),('vn-database','10436','05-RemoveFkWorkerProductivity.sql','jenkins@db-proxy2.static.verdnatura.es','2023-02-17 14:51:19',NULL,NULL),('vn-database','10439','00-fixRole.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-25 09:13:26',NULL,NULL),('vn-database','10440','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-23 10:28:41',NULL,NULL),('vn-database','10444','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-16 09:59:01',NULL,NULL),('vn-database','10445','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-16 09:59:31',NULL,NULL),('vn-database','10448','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-16 09:59:31',NULL,NULL),('vn-database','10450','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-27 08:28:04',NULL,NULL),('vn-database','10451','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-06 08:08:32',NULL,NULL),('vn-database','10452','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-31 12:30:04',NULL,NULL),('vn-database','10453','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-31 14:04:37',NULL,NULL),('vn-database','10454','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-31 12:30:04',NULL,NULL),('vn-database','10455','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-31 12:30:04',NULL,NULL),('vn-database','10456','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-31 12:00:30',NULL,NULL),('vn-database','10457','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-31 12:00:33',NULL,NULL),('vn-database','10458','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-09 08:40:17',NULL,NULL),('vn-database','10459','00-alterTableUtilConfig.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-23 10:28:41',NULL,NULL),('vn-database','10459','01-createFunctionCurdate.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-23 10:28:41',NULL,NULL),('vn-database','10459','02-createFunctionMockTime.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-23 10:28:41',NULL,NULL),('vn-database','10459','03-createFunctionMockTimeBase.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-23 10:28:41',NULL,NULL),('vn-database','10459','04-createFunctionNow.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-23 10:28:41',NULL,NULL),('vn-database','10460','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-16 09:59:31',NULL,NULL),('vn-database','10461','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-16 09:59:31',NULL,NULL),('vn-database','10463','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-03 12:59:26',NULL,NULL),('vn-database','10468','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-16 09:59:31',NULL,NULL),('vn-database','10469','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-16 09:59:31',NULL,NULL),('vn-database','10470','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-23 10:28:54',NULL,NULL),('vn-database','10471','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-23 10:28:54',NULL,NULL),('vn-database','10472','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-23 10:28:54',NULL,NULL),('vn-database','10477','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-23 09:09:31',NULL,NULL),('vn-database','10478','00-dropBasket.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-23 10:28:54',NULL,NULL),('vn-database','10478','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-23 10:28:54',NULL,NULL),('vn-database','10478','01-orderConfigured.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-23 10:29:16',NULL,NULL),('vn-database','10478','02-configuredUpdate.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-23 10:29:53',NULL,NULL),('vn-database','10478','99-privileges.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-23 10:29:53',NULL,NULL),('vn-database','10480','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-17 15:09:26',NULL,NULL),('vn-database','10481','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-17 16:37:22',NULL,NULL),('vn-database','10482','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-02-21 10:00:28',NULL,NULL),('vn-database','10485','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-09 08:40:17',NULL,NULL),('vn-database','10488','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-09 08:40:17',NULL,NULL),('vn-database','10491','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-09 08:40:18',NULL,NULL),('vn-database','10492','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-09 08:40:18',NULL,NULL),('vn-database','10493','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:18:01',NULL,NULL),('vn-database','10495','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-09 08:40:19',NULL,NULL),('vn-database','10498','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-23 09:09:38',NULL,NULL),('vn-database','10500','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-03-03 07:06:03',NULL,NULL),('vn-database','10501','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-03-03 10:52:24',NULL,NULL),('vn-database','10502','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-23 09:09:48',NULL,NULL),('vn-database','10504','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-25 09:13:27',NULL,NULL),('vn-database','10506','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-23 09:09:48',NULL,NULL),('vn-database','10506','01-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-15 12:30:18',NULL,NULL),('vn-database','10506','02-secondScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-15 12:30:18',NULL,NULL),('vn-database','10506','03-thirdScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-15 12:30:18',NULL,NULL),('vn-database','10507','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-05 10:35:23',NULL,NULL),('vn-database','10508','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-05 10:36:43',NULL,NULL),('vn-database','10510','00-dropBusinessFk.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-05 10:36:47',NULL,NULL),('vn-database','10510','01-createTableProfessionalCategory.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-05 10:36:47',NULL,NULL),('vn-database','10510','02-exportToNewTable.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-05 10:36:47',NULL,NULL),('vn-database','10510','03-RecreateFK.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-05 10:36:51',NULL,NULL),('vn-database','10510','04-kkPostgresqlTable.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-05 10:36:51',NULL,NULL),('vn-database','10511','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-20 09:07:41',NULL,NULL),('vn-database','10512','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-05 10:36:52',NULL,NULL),('vn-database','10513','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-05 10:36:56',NULL,NULL),('vn-database','10514','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-20 09:07:41',NULL,NULL),('vn-database','10516','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-23 09:09:48',NULL,NULL),('vn-database','10521','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-21 06:58:13',NULL,NULL),('vn-database','10522','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-20 09:07:41',NULL,NULL),('vn-database','10523','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-20 09:07:41',NULL,NULL),('vn-database','10524','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-08-10 11:50:12',NULL,NULL),('vn-database','10524','01-rateEditorFk.sql','jenkins@db-proxy2.static.verdnatura.es','2023-08-10 11:50:12',NULL,NULL),('vn-database','10525','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-21 12:42:50',NULL,NULL),('vn-database','10526','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-05 10:36:57',NULL,NULL),('vn-database','10528','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-05 10:37:00',NULL,NULL),('vn-database','10530','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-03-23 14:49:30',NULL,NULL),('vn-database','10531','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-24 11:47:10',NULL,NULL),('vn-database','10532','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-24 11:17:38',NULL,NULL),('vn-database','10533','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-05 10:37:04',NULL,NULL),('vn-database','10537','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-29 15:18:36',NULL,NULL),('vn-database','10538','00-createChronopostConfig.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-20 09:07:41',NULL,NULL),('vn-database','10538','01-createChronopostService.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-20 09:07:41',NULL,NULL),('vn-database','10538','02-createChronopostExpedition.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-20 09:07:41',NULL,NULL),('vn-database','10538','03-createChronopostSenderAddress.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-20 09:07:41',NULL,NULL),('vn-database','10538','04-addgrantPrivilegies.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-20 09:07:41',NULL,NULL),('vn-database','10538','05-updateChronopostConfig.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-21 11:54:57',NULL,NULL),('vn-database','10539','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-05 10:37:07',NULL,NULL),('vn-database','10540','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:18:01',NULL,NULL),('vn-database','10545','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-11 08:31:03',NULL,NULL),('vn-database','10546','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-20 09:08:10',NULL,NULL),('vn-database','10547','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:21:58',NULL,NULL),('vn-database','10549','00-updateUpdateLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-21 07:29:22',NULL,NULL),('vn-database','10549','01-updateInsertLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-21 07:30:11',NULL,NULL),('vn-database','10549','02-updateDeleteLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-21 07:30:51',NULL,NULL),('vn-database','10549','03-deleteEmptyLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-21 07:31:34',NULL,NULL),('vn-database','10549','04-optimizeLogTables.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-21 07:33:58',NULL,NULL),('vn-database','10550','00-editorFk.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:42:33',NULL,NULL),('vn-database','10550','01-originFk.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:28',NULL,NULL),('vn-database','10552','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-13 08:25:10',NULL,NULL),('vn-database','10554','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-20 09:08:10',NULL,NULL),('vn-database','10557','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-17 07:45:56',NULL,NULL),('vn-database','10559','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-18 10:53:50',NULL,NULL),('vn-database','10560','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-17 09:19:31',NULL,NULL),('vn-database','10562','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:28',NULL,NULL),('vn-database','10563','00-delivery_ticketFk.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-20 09:30:53',NULL,NULL),('vn-database','10566','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-20 10:08:41',NULL,NULL),('vn-database','10567','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-20 10:18:06',NULL,NULL),('vn-database','10568','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:28',NULL,NULL),('vn-database','10569','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-24 09:14:35',NULL,NULL),('vn-database','10570','00-createSendingConfig.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:28',NULL,NULL),('vn-database','10570','01-createSendingServiceWeekday.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:28',NULL,NULL),('vn-database','10570','02-createSendingService.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:28',NULL,NULL),('vn-database','10570','03-permisos.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:28',NULL,NULL),('vn-database','10571','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-25 09:13:27',NULL,NULL),('vn-database','10573','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-27 09:17:23',NULL,NULL),('vn-database','10575','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-26 11:27:32',NULL,NULL),('vn-database','10577','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-27 14:00:12',NULL,NULL),('vn-database','10578','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:28',NULL,NULL),('vn-database','10579','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-28 11:27:36',NULL,NULL),('vn-database','10580','00-itemTypeDropConstraint.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-28 18:18:52',NULL,NULL),('vn-database','10580','01-itemTypeAddConstraint.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-28 18:19:10',NULL,NULL),('vn-database','10581','00-itemTypeAutoIncrement.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-28 19:06:46',NULL,NULL),('vn-database','10582','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:28',NULL,NULL),('vn-database','10583','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:28',NULL,NULL),('vn-database','10584','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:28',NULL,NULL),('vn-database','10585','00-ticketLog.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-25 09:20:10',NULL,NULL),('vn-database','10585','01-entryLog.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-25 09:21:12',NULL,NULL),('vn-database','10585','02-claimLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:28:36',NULL,NULL),('vn-database','10585','03-clientLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:28:54',NULL,NULL),('vn-database','10585','04-invoiceInLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:28:55',NULL,NULL),('vn-database','10585','05-itemLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:29:46',NULL,NULL),('vn-database','10585','06-routeLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:30:18',NULL,NULL),('vn-database','10585','07-shelvingLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:30:32',NULL,NULL),('vn-database','10585','08-supplierLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:30:32',NULL,NULL),('vn-database','10585','09-travelLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:30:41',NULL,NULL),('vn-database','10585','10-workerLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:30:42',NULL,NULL),('vn-database','10585','11-zoneLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:30:43',NULL,NULL),('vn-database','10585','12-userLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:30:44',NULL,NULL),('vn-database','10585','13-roleLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:30:44',NULL,NULL),('vn-database','10587','00-arcRead_addMinimum.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-16 13:13:15',NULL,NULL),('vn-database','10593','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:30:44',NULL,NULL),('vn-database','10596','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:30:44',NULL,NULL),('vn-database','10597','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:30:44',NULL,NULL),('vn-database','10598','00-workerLog.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:29',NULL,NULL),('vn-database','10598','01-supplierLog.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:29',NULL,NULL),('vn-database','10598','02-workerTimeControlLog.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:29',NULL,NULL),('vn-database','10598','03-workerClockLog.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:29',NULL,NULL),('vn-database','10599','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:30:44',NULL,NULL),('vn-database','10601','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-17 09:26:26',NULL,NULL),('vn-database','10602','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-18 08:52:15',NULL,NULL),('vn-database','10606','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-18 09:26:00',NULL,NULL),('vn-database','10608','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-18 12:36:31',NULL,NULL),('vn-database','10609','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-01 08:28:07',NULL,NULL),('vn-database','10610','00-updateCompanyId.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-01 09:11:07',NULL,NULL),('vn-database','10610','01-updateSupplierId.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-01 09:11:39',NULL,NULL),('vn-database','10610','02-invoiceOutCompany.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-01 09:49:55',NULL,NULL),('vn-database','10611','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-19 14:39:41',NULL,NULL),('vn-database','10613','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-15 12:30:18',NULL,NULL),('vn-database','10614','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-01 09:11:40',NULL,NULL),('vn-database','10615','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-01 09:11:40',NULL,NULL),('vn-database','10616','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-13 11:18:55',NULL,NULL),('vn-database','10616','01-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-13 11:18:55',NULL,NULL),('vn-database','10617','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-01 09:11:41',NULL,NULL),('vn-database','10618','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 12:55:56',NULL,NULL),('vn-database','10619','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-15 12:30:18',NULL,NULL),('vn-database','10620','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-13 11:20:53',NULL,NULL),('vn-database','10624','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-30 19:01:10',NULL,NULL),('vn-database','10626','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-29 13:32:32',NULL,NULL),('vn-database','10628','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-15 12:30:18',NULL,NULL),('vn-database','10630','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-02 13:30:58',NULL,NULL),('vn-database','10631','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-05 08:37:25',NULL,NULL),('vn-database','10632','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-15 12:30:18',NULL,NULL),('vn-database','10633','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-15 12:30:18',NULL,NULL),('vn-database','10634','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-06 12:15:55',NULL,NULL),('vn-database','10637','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-15 12:30:19',NULL,NULL),('vn-database','10640','00-companyFkDrop.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-07 14:43:23',NULL,NULL),('vn-database','10640','00-updateCompany.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-07 14:22:13',1205,'Tiempo de espera de bloqueo excedido; intente rearrancar la transacción'),('vn-database','10640','01-companyFkAi.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-07 14:43:23',NULL,NULL),('vn-database','10640','02-companyFkCreate.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-07 14:47:04',NULL,NULL),('vn-database','10640','04-supplierFkDrop.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-07 14:48:30',NULL,NULL),('vn-database','10640','05-supplierFkAi.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-07 14:53:17',NULL,NULL),('vn-database','10640','06-supplierFkCreate.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-07 15:06:00',NULL,NULL),('vn-database','10642','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-29 14:04:13',NULL,NULL),('vn-database','10643','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-09 15:04:35',NULL,NULL),('vn-database','10644','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-13 11:22:18',NULL,NULL),('vn-database','10647','00-renombrarTabla.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-29 14:04:13',NULL,NULL),('vn-database','10648','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-27 09:17:24',NULL,NULL),('vn-database','10649','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-16 10:59:06',NULL,NULL),('vn-database','10652','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-29 14:04:13',NULL,NULL),('vn-database','10653','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-13 11:22:20',NULL,NULL),('vn-database','10655','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-13 11:22:24',NULL,NULL),('vn-database','10656','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-27 09:17:24',NULL,NULL),('vn-database','10658','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-13 11:22:27',NULL,NULL),('vn-database','10659','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-27 09:17:24',NULL,NULL),('vn-database','10662','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-13 11:22:33',NULL,NULL),('vn-database','10663','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-13 11:22:34',NULL,NULL),('vn-database','10665','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-30 08:52:51',NULL,NULL),('vn-database','10666','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-13 11:22:34',NULL,NULL),('vn-database','10667','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-27 09:17:24',NULL,NULL),('vn-database','10668','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-08-10 11:50:13',NULL,NULL),('vn-database','10671','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-25 14:56:50',NULL,NULL),('vn-database','10675','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-27 09:17:24',NULL,NULL),('vn-database','10676','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-27 09:17:24',NULL,NULL),('vn-database','10679','00-tables.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-27 09:17:24',NULL,NULL),('vn-database','10680','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-07-18 14:58:36',NULL,NULL),('vn-database','10682','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-08-10 11:50:13',NULL,NULL),('vn-database','10690','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-07-27 10:52:26',NULL,NULL),('vn-database','10691','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-07-31 13:37:21',NULL,NULL),('vn-database','10692','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-08-10 11:50:13',NULL,NULL),('vn-database','10693','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-08-10 11:50:13',NULL,NULL),('vn-database','10694','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-08-02 09:50:53',NULL,NULL),('vn-database','10695','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-08-02 13:40:16',NULL,NULL),('vn-database','10696','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-08-03 16:54:57',NULL,NULL),('vn-database','10698','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-08-03 08:53:12',NULL,NULL),('vn-database','10699','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-08-03 15:24:30',NULL,NULL),('vn-database','10700','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-08-29 09:42:11',NULL,NULL),('vn-database','10702','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-08-10 12:50:46',NULL,NULL),('vn-database','10704','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-08-29 09:42:14',NULL,NULL),('vn-database','10705','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-08-16 14:16:05',NULL,NULL),('vn-database','10707','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-08-21 12:31:18',NULL,NULL),('vn-database','10714','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-08-28 13:01:45',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','00001','00-test.sql','juan@10.5.1.3','2022-01-31 10:12:26',NULL,NULL),('vn-database','00003','00-sage.sql','juan@10.5.1.3','2022-01-31 10:12:26',NULL,NULL),('vn-database','10008','00-alterRoleConfig.sql','juan@10.5.1.3','2022-01-31 10:12:26',NULL,NULL),('vn-database','10014','00-rolePrefix.sql','jenkins@10.0.2.68','2022-02-11 00:13:25',NULL,NULL),('vn-database','10017','01-firstScript.sql','jenkins@10.0.2.70','2022-03-09 11:36:54',NULL,NULL),('vn-database','10021','00-bankAccount.sql','jenkins@10.0.2.69','2022-03-16 14:11:22',NULL,NULL),('vn-database','10023','00-firstScript.sql','jenkins@10.0.2.69','2022-03-16 15:05:29',NULL,NULL),('vn-database','10026','00-invoiceInIntrastat.sql','jenkins@10.0.2.69','2022-03-21 15:10:53',NULL,NULL),('vn-database','10027','00-Clientes_cedidos.sql','jenkins@10.0.2.69','2022-03-22 15:58:12',NULL,NULL),('vn-database','10028','00-item_last_buy_.sql','jenkins@10.0.2.69','2022-03-22 15:58:12',NULL,NULL),('vn-database','10029','00-bankToViewAccountingToTable.sql','jenkins@10.0.2.69','2022-03-22 15:58:12',NULL,NULL),('vn-database','10030','00-KkejarNiche.sql','jenkins@10.0.2.69','2022-03-22 15:58:12',NULL,NULL),('vn-database','10036','00-updateBuyConfig.sql','jenkins@10.0.2.69','2022-03-29 12:36:54',NULL,NULL),('vn-database','10037','00-firstScript.sql','jenkins@10.0.2.69','2022-03-28 11:14:26',NULL,NULL),('vn-database','10038','00-printServerQueue.sql','jenkins@10.0.2.69','2022-03-29 08:13:24',NULL,NULL),('vn-database','10048','00-firstScript.sql','jenkins@10.0.2.69','2022-03-30 12:29:06',NULL,NULL),('vn-database','10058','00-vehicleAddFields.sql','jenkins@10.0.2.69','2022-04-06 08:48:34',NULL,NULL),('vn-database','10060','00-firstScript.sql','jenkins@10.0.2.69','2022-04-07 08:50:11',NULL,NULL),('vn-database','10062','00-firstScript.sql','jenkins@10.0.2.69','2022-04-06 10:51:45',NULL,NULL),('vn-database','10064','00-firstScript.sql','jenkins@10.0.2.69','2022-04-06 13:57:11',NULL,NULL),('vn-database','10066','00-firstScript.sql','jenkins@10.0.2.69','2022-04-07 08:50:12',NULL,NULL),('vn-database','10067','00-firstScript.sql','jenkins@10.0.2.69','2022-04-08 10:18:20',NULL,NULL),('vn-database','10071','00-packingSiteLog.sql','jenkins@10.0.2.69','2022-04-08 09:37:30',NULL,NULL),('vn-database','10072','00-firstScript.sql','jenkins@10.0.2.69','2022-04-08 11:01:46',NULL,NULL),('vn-database','10073','00-firstScript.sql','jenkins@10.0.2.69','2022-04-08 13:40:56',NULL,NULL),('vn-database','10074','00-firstScript.sql','jenkins@10.0.2.69','2022-04-10 13:15:05',NULL,NULL),('vn-database','10077','00-firstScript.sql','jenkins@10.0.2.69','2022-04-12 08:07:15',NULL,NULL),('vn-database','10078','00-firstScript.sql','jenkins@10.0.2.69','2022-04-13 07:44:21',NULL,NULL),('vn-database','10079','00-firstScript.sql','jenkins@10.0.2.69','2022-04-12 12:01:37',NULL,NULL),('vn-database','10086','00-firstScript.sql','jenkins@10.0.2.69','2022-04-13 08:58:34',NULL,NULL),('vn-database','10087','00-firstScript.sql','jenkins@10.0.2.69','2022-04-13 09:39:49',NULL,NULL),('vn-database','10088','00-firstScript.sql','jenkins@10.0.2.69','2022-04-13 15:05:12',NULL,NULL),('vn-database','10089','00-firstScript.sql','jenkins@10.0.2.69','2022-04-18 14:12:52',NULL,NULL),('vn-database','10090','00-firstScript.sql','jenkins@10.0.2.69','2022-04-18 14:34:46',NULL,NULL),('vn-database','10092','00-firstScript.sql','jenkins@10.0.2.69','2022-04-19 14:45:46',NULL,NULL),('vn-database','10093','00-autoradioConfig.sql','jenkins@10.0.2.69','2022-05-03 09:16:47',NULL,NULL),('vn-database','10094','00-firstScript.sql','jenkins@10.0.2.69','2022-04-20 10:57:30',NULL,NULL),('vn-database','10097','00-firstScript.sql','jenkins@10.0.2.69','2022-05-05 10:12:59',NULL,NULL),('vn-database','10099','00-firstScript.sql','jenkins@10.0.2.69','2022-04-20 14:35:27',NULL,NULL),('vn-database','10100','00-firstScript.sql','jenkins@10.0.2.69','2022-04-20 14:35:27',NULL,NULL),('vn-database','10101','00-firstScript.sql','jenkins@10.0.2.69','2022-04-21 14:59:31',NULL,NULL),('vn-database','10103','00-awbVolume.sql','jenkins@10.0.2.69','2022-05-05 10:12:59',NULL,NULL),('vn-database','10104','00-firstScript.sql','jenkins@10.0.2.69','2022-05-05 10:12:59',NULL,NULL),('vn-database','10105','00-firstScript.sql','jenkins@10.0.2.69','2022-05-05 10:13:00',NULL,NULL),('vn-database','10107','00-firstScript.sql','jenkins@10.0.2.69','2022-04-23 10:53:53',NULL,NULL),('vn-database','10112','00-firstScript.sql','jenkins@10.0.2.69','2022-05-09 09:14:53',NULL,NULL),('vn-database','10113','00-firstScript.sql','jenkins@10.0.2.69','2022-05-05 10:13:00',NULL,NULL),('vn-database','10114','00-updateConfig.sql','jenkins@10.0.2.69','2022-04-27 13:37:25',NULL,NULL),('vn-database','10116','00-firstScript.sql','jenkins@10.0.2.69','2022-04-28 11:10:14',NULL,NULL),('vn-database','10118','00-firstScript.sql','jenkins@10.0.2.69','2022-04-29 08:10:15',NULL,NULL),('vn-database','10119','00-AfegirFKPart1.sql','jenkins@10.0.2.69','2022-05-05 10:13:00',NULL,NULL),('vn-database','10119','01-AfegirFkPart2.sql','jenkins@10.0.2.69','2022-05-05 10:22:25',NULL,NULL),('vn-database','10125','00-firstScript.sql','jenkins@10.0.2.68','2022-05-18 18:44:30',NULL,NULL),('vn-database','10127','00-firstScript.sql','jenkins@10.0.2.69','2022-05-02 11:04:46',NULL,NULL),('vn-database','10128','00-firstScript.sql','jenkins@10.0.2.69','2022-05-02 13:04:31',NULL,NULL),('vn-database','10129','00-firstScript.sql','jenkins@10.0.2.69','2022-05-03 08:21:01',NULL,NULL),('vn-database','10132','00-firstScript.sql','jenkins@10.0.2.69','2022-05-05 10:22:25',NULL,NULL),('vn-database','10133','00-firstScript.sql','jenkins@10.0.2.69','2022-05-05 14:32:30',NULL,NULL),('vn-database','10134','00-firstScript.sql','jenkins@10.0.2.69','2022-05-06 07:45:25',NULL,NULL),('vn-database','10135','00-firstScript.sql','jenkins@10.0.2.69','2022-06-17 08:46:17',NULL,NULL),('vn-database','10136','00-workerTimeControl.sql','jenkins@10.0.2.69','2022-05-09 13:51:12',NULL,NULL),('vn-database','10138','00-firstScript.sql','jenkins@10.0.2.69','2022-05-10 13:58:05',NULL,NULL),('vn-database','10139','00-firstScript.sql','jenkins@10.0.2.68','2022-05-16 14:32:37',NULL,NULL),('vn-database','10139','01-secondScript.sql','jenkins@10.0.2.68','2022-05-17 12:16:13',NULL,NULL),('vn-database','10141','00-firstScript.sql','jenkins@10.0.2.70','2022-05-12 08:27:31',NULL,NULL),('vn-database','10142','00-firstScript.sql','jenkins@10.0.2.68','2022-05-20 09:20:31',NULL,NULL),('vn-database','10143','00-firstScript.sql','jenkins@10.0.2.68','2022-05-20 09:20:31',NULL,NULL),('vn-database','10144','00-AfegirFKPArt1.sql','jenkins@10.0.2.68','2022-05-20 09:22:33',NULL,NULL),('vn-database','10144','00-firstScript.sql','jenkins@10.0.2.68','2022-05-13 09:44:25',NULL,NULL),('vn-database','10147','00-firstScript.sql','jenkins@10.0.2.68','2022-05-20 09:22:33',NULL,NULL),('vn-database','10149','00-firstScript.sql','jenkins@10.0.2.68','2022-05-20 09:22:33',NULL,NULL),('vn-database','10150','00-firstScript.sql','jenkins@10.0.2.68','2022-05-17 09:57:16',NULL,NULL),('vn-database','10152','00-firstScript.sql','jenkins@10.0.2.68','2022-05-20 09:22:34',NULL,NULL),('vn-database','10153','00-firstScript.sql','jenkins@10.0.2.68','2022-05-20 09:22:34',NULL,NULL),('vn-database','10154','00-compressionKk.sql','jenkins@10.0.2.68','2022-05-20 09:22:34',NULL,NULL),('vn-database','10157','00-firstScript.sql','jenkins@10.0.2.68','2022-05-20 09:22:35',NULL,NULL),('vn-database','10158','00-firstScript.sql','jenkins@10.0.2.68','2022-06-02 12:47:21',NULL,NULL),('vn-database','10160','00-firstScript.sql','jenkins@10.0.2.69','2022-06-30 09:30:50',NULL,NULL),('vn-database','10163','00-firstScript.sql','jenkins@10.0.2.68','2022-05-23 08:17:14',NULL,NULL),('vn-database','10164','00-borrarSectorsDesus.sql','jenkins@10.0.2.68','2022-06-02 12:47:21',NULL,NULL),('vn-database','10165','00-firstScript.sql','jenkins@10.0.2.68','2022-06-02 12:47:22',NULL,NULL),('vn-database','10166','00-firstScript.sql','jenkins@10.0.2.68','2022-05-24 16:11:21',NULL,NULL),('vn-database','10167','00-renameVnActiveContrat.sql','jenkins@10.0.2.68','2022-06-02 12:47:22',NULL,NULL),('vn-database','10168','00-firstScript.sql','jenkins@10.0.2.68','2022-06-02 12:47:22',NULL,NULL),('vn-database','10169','00-createTableBankEntityConfig.sql','jenkins@10.0.2.68','2022-06-02 12:47:22',NULL,NULL),('vn-database','10169','02-addNotNullToBankEntityBic.sql','jenkins@10.0.2.68','2022-06-02 12:47:22',NULL,NULL),('vn-database','10171','00-volumeConfig.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-18 14:11:11',NULL,NULL),('vn-database','10171','01-itemWeight.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-18 16:01:34',NULL,NULL),('vn-database','10171','02-agencymode.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-18 16:01:34',NULL,NULL),('vn-database','10172','00-firstScript.sql','jenkins@10.0.2.68','2022-06-02 12:47:22',NULL,NULL),('vn-database','10174','00-firstScript.sql','jenkins@10.0.2.69','2022-06-17 08:46:17',NULL,NULL),('vn-database','10175','00-firstScript.sql','jenkins@10.0.2.69','2022-06-17 09:03:41',NULL,NULL),('vn-database','10177','00-crearTablaSpecialLabels.sql','jenkins@10.0.2.68','2022-06-02 12:47:22',NULL,NULL),('vn-database','10178','00-firstScript.sql','jenkins@10.0.2.68','2022-06-02 12:47:24',NULL,NULL),('vn-database','10179','00-firstScript.sql','jenkins@10.0.2.68','2022-06-02 12:47:24',NULL,NULL),('vn-database','10183','00-firstScript.sql','jenkins@10.0.2.68','2022-06-02 12:47:24',NULL,NULL),('vn-database','10184','00-firstScript.sql','jenkins@10.0.2.68','2022-06-03 08:05:34',NULL,NULL),('vn-database','10185','00-firstScript.sql','jenkins@10.0.2.68','2022-06-06 09:07:45',NULL,NULL),('vn-database','10186','00-desactivar_trigger.sql','jenkins@10.0.2.68','2022-06-07 09:31:23',NULL,NULL),('vn-database','10186','01-alter_Table_buy.sql','jenkins@10.0.2.68','2022-06-07 09:34:47',NULL,NULL),('vn-database','10186','02-alter_table_entryConfig.sql','jenkins@10.0.2.68','2022-06-07 09:34:47',NULL,NULL),('vn-database','10186','04-regularizar_Sticker_Inventario.sql','jenkins@10.0.2.68','2022-06-07 09:34:51',NULL,NULL),('vn-database','10186','09-reactivar_trigger.sql','jenkins@10.0.2.68','2022-06-07 09:34:51',NULL,NULL),('vn-database','10187','00-firstScript.sql','jenkins@10.0.2.68','2022-06-06 12:37:31',NULL,NULL),('vn-database','10188','00-firstScript.sql','jenkins@10.0.2.68','2022-06-06 14:03:36',NULL,NULL),('vn-database','10189','00-firstScript.sql','jenkins@10.0.2.69','2022-06-17 09:03:41',NULL,NULL),('vn-database','10191','00-firstScript.sql','jenkins@10.0.2.69','2022-06-17 09:03:41',NULL,NULL),('vn-database','10193','00-delete.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-15 12:14:35',NULL,NULL),('vn-database','10193','01-botanicExport.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-15 12:14:43',NULL,NULL),('vn-database','10193','02-item.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-15 12:14:44',NULL,NULL),('vn-database','10193','03-autonomy.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-15 12:14:44',NULL,NULL),('vn-database','10193','03-turn.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-15 12:14:44',NULL,NULL),('vn-database','10193','04-country.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-15 12:14:44',NULL,NULL),('vn-database','10194','00-firstScript.sql','jenkins@10.0.2.69','2022-06-17 09:03:41',NULL,NULL),('vn-database','10195','00-firstScript.sql','jenkins@10.0.2.69','2022-06-17 09:03:41',NULL,NULL),('vn-database','10200','00-firstScript.sql','jenkins@10.0.2.69','2022-06-17 09:04:00',NULL,NULL),('vn-database','10201','00-firstScript.sql','jenkins@10.0.2.69','2022-06-17 09:04:00',NULL,NULL),('vn-database','10202','00-Remove_FK_to_ediGenus.sql','jenkins@10.0.2.69','2022-06-17 09:04:00',NULL,NULL),('vn-database','10203','00-firstScript.sql','jenkins@10.0.2.69','2022-06-17 09:04:01',NULL,NULL),('vn-database','10204','00-firstScript.sql','jenkins@10.0.2.69','2022-06-17 09:04:01',NULL,NULL),('vn-database','10205','00-firstScript.sql','jenkins@10.0.2.69','2022-06-17 09:04:21',NULL,NULL),('vn-database','10207','00-Alter_table_entry.sql','jenkins@10.0.2.69','2022-06-16 07:22:50',NULL,NULL),('vn-database','10207','01-Update_invoiceAmount.sql','jenkins@10.0.2.69','2022-06-16 07:23:00',NULL,NULL),('vn-database','10208','00-firstScript.sql','jenkins@10.0.2.69','2022-06-30 09:31:26',NULL,NULL),('vn-database','10209','00-firstScript.sql','jenkins@10.0.2.69','2022-06-16 08:47:40',NULL,NULL),('vn-database','10210','00-firstScript.sql','jenkins@10.0.2.69','2022-06-16 17:39:17',1046,'Base de datos no seleccionada'),('vn-database','10211','01-firstScript.sql','jenkins@10.0.2.69','2022-06-17 07:11:27',NULL,NULL),('vn-database','10215','00-renameIsInventory.sql','jenkins@10.0.2.69','2022-06-30 09:31:26',NULL,NULL),('vn-database','10216','00-firstScript.sql','jenkins@10.0.2.69','2022-06-23 11:15:28',NULL,NULL),('vn-database','10216','01-batchIndex.sql','jenkins@10.0.2.70','2022-06-27 18:10:55',NULL,NULL),('vn-database','10219','00-AddCollectionFkOnPackingSite.sql','jenkins@10.0.2.70','2022-06-29 09:23:42',NULL,NULL),('vn-database','10219','01-AddFkToCollectionFk.sql','jenkins@10.0.2.70','2022-06-29 09:23:43',NULL,NULL),('vn-database','10220','00-createPersonalProtectionEquipment.sql','jenkins@10.0.2.69','2022-06-30 09:31:26',NULL,NULL),('vn-database','10222','00-firstScript.sql','jenkins@10.0.2.69','2022-07-14 09:12:40',NULL,NULL),('vn-database','10223','00-firstScript.sql','jenkins@10.0.2.69','2022-07-14 09:13:52',NULL,NULL),('vn-database','10224','00-cosetes.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-07-21 12:03:45',NULL,NULL),('vn-database','10229','00-firstScript.sql','jenkins@10.0.2.69','2022-07-01 11:59:34',NULL,NULL),('vn-database','10231','01-tablaEktConfig.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-11 09:25:39',NULL,NULL),('vn-database','10233','00-firstScript.sql','jenkins@10.0.2.69','2022-07-14 09:13:53',NULL,NULL),('vn-database','10235','00-firstScript.sql','jenkins@10.0.2.69','2022-07-14 09:13:53',NULL,NULL),('vn-database','10236','00-firstScript.sql','jenkins@10.0.2.69','2022-07-05 12:11:40',NULL,NULL),('vn-database','10237','00-firstScript.sql','jenkins@10.0.2.69','2022-07-14 09:13:53',NULL,NULL),('vn-database','10238','00-worker_mobileExtension.sql','jenkins@10.0.2.69','2022-07-14 09:14:09',NULL,NULL),('vn-database','10239','00-firstScript.sql','jenkins@10.0.2.69','2022-07-07 21:51:58',NULL,NULL),('vn-database','10241','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-07-29 08:14:01',NULL,NULL),('vn-database','10242','00-firstScript.sql','jenkins@10.0.2.69','2022-07-14 09:14:32',NULL,NULL),('vn-database','10243','00-firstScript.sql','jenkins@10.0.2.69','2022-07-14 09:14:32',NULL,NULL),('vn-database','10245','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-07-28 08:34:51',NULL,NULL),('vn-database','10247','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-07-28 08:34:51',NULL,NULL),('vn-database','10248','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-07-20 17:27:51',NULL,NULL),('vn-database','10250','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-07-28 08:36:40',NULL,NULL),('vn-database','10253','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-07-28 08:36:57',NULL,NULL),('vn-database','10254','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-07-28 08:38:48',NULL,NULL),('vn-database','10256','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-07-28 08:38:48',NULL,NULL),('vn-database','10258','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-12-16 09:14:48',NULL,NULL),('vn-database','10259','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-02 08:54:56',NULL,NULL),('vn-database','10261','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-07-22 08:42:20',NULL,NULL),('vn-database','10262','00-createTablepackagingWithFreight.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:22:13',NULL,NULL),('vn-database','10262','01-alterTablePackagingConfig.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:22:13',NULL,NULL),('vn-database','10262','02-insertsInicials.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:22:13',NULL,NULL),('vn-database','10262','03-createTablepackingWithoutFreight.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:22:14',NULL,NULL),('vn-database','10263','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-07-28 08:38:48',NULL,NULL),('vn-database','10265','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-07-28 08:38:48',NULL,NULL),('vn-database','10267','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-11 09:34:17',NULL,NULL),('vn-database','10267','01-fixMerge.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-11 09:34:17',NULL,NULL),('vn-database','10275','00-improvedGeneralLog.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-01 09:55:56',NULL,NULL),('vn-database','10277','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-08 10:26:32',NULL,NULL),('vn-database','10278','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-01 17:51:41',NULL,NULL),('vn-database','10279','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-11 09:34:17',NULL,NULL),('vn-database','10281','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-11 09:34:18',NULL,NULL),('vn-database','10282','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-11 09:34:18',NULL,NULL),('vn-database','10283','00-alterTable.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-11 09:34:18',NULL,NULL),('vn-database','10284','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-04 16:59:08',NULL,NULL),('vn-database','10285','00-firstScript.sql','jenkins@swarm-worker3.static.verdnatura.es','2022-08-05 09:19:33',NULL,NULL),('vn-database','10287','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-11 09:35:24',NULL,NULL),('vn-database','10288','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-11 09:35:24',NULL,NULL),('vn-database','10289','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:29:36',NULL,NULL),('vn-database','10291','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-10 14:19:34',NULL,NULL),('vn-database','10293','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-08 10:26:32',NULL,NULL),('vn-database','10297','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-16 12:43:36',NULL,NULL),('vn-database','10298','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-08-13 21:04:13',NULL,NULL),('vn-database','10299','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:22:14',NULL,NULL),('vn-database','10301','00-productionConfig.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:22:14',NULL,NULL),('vn-database','10301','01-drop.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:22:14',NULL,NULL),('vn-database','10301','02-collection.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:22:15',NULL,NULL),('vn-database','10302','00-CreateTableEntryType.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:22:15',NULL,NULL),('vn-database','10302','01-insertDataEntryType.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:22:15',NULL,NULL),('vn-database','10302','02-alterTableEntry.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:22:22',NULL,NULL),('vn-database','10303','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:22:23',NULL,NULL),('vn-database','10304','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:23:48',NULL,NULL),('vn-database','10304','01-altertableticket.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:23:51',NULL,NULL),('vn-database','10305','00-ektAssign.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:24:52',NULL,NULL),('vn-database','10306','00-deliveryInformation.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:25:25',NULL,NULL),('vn-database','10307','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:25:26',NULL,NULL),('vn-database','10308','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-02 17:26:43',NULL,NULL),('vn-database','10309','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-06 11:37:54',NULL,NULL),('vn-database','10310','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-08 10:26:33',NULL,NULL),('vn-database','10311','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-06 11:37:55',NULL,NULL),('vn-database','10312','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-08 10:26:33',NULL,NULL),('vn-database','10313','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-08 10:27:21',NULL,NULL),('vn-database','10314','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-20 12:37:19',NULL,NULL),('vn-database','10315','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-08 10:31:43',NULL,NULL),('vn-database','10317','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-08 10:31:43',NULL,NULL),('vn-database','10318','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-08 10:31:43',NULL,NULL),('vn-database','10319','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-20 12:37:41',NULL,NULL),('vn-database','10320','00-operator.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:29:37',NULL,NULL),('vn-database','10320','01-collection.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:29:37',NULL,NULL),('vn-database','10320','02-productionConfig.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:29:38',NULL,NULL),('vn-database','10321','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-08 11:11:12',NULL,NULL),('vn-database','10322','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-09 09:19:05',NULL,NULL),('vn-database','10326','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:29:38',NULL,NULL),('vn-database','10328','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:29:38',NULL,NULL),('vn-database','10329','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:29:38',NULL,NULL),('vn-database','10330','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:34:30',NULL,NULL),('vn-database','10332','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:34:30',NULL,NULL),('vn-database','10334','00-collectionHotbed.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:34:30',NULL,NULL),('vn-database','10334','01-saleGroupDetail.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:34:32',NULL,NULL),('vn-database','10335','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-10-06 09:52:38',NULL,NULL),('vn-database','10336','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:34:32',NULL,NULL),('vn-database','10337','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:34:32',NULL,NULL),('vn-database','10339','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-19 09:41:19',NULL,NULL),('vn-database','10340','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-29 11:08:03',NULL,NULL),('vn-database','10341','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:34:32',NULL,NULL),('vn-database','10342','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-29 11:08:03',NULL,NULL),('vn-database','10343','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-22 08:35:30',NULL,NULL),('vn-database','10345','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-11-04 08:25:16',NULL,NULL),('vn-database','10347','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-29 11:08:03',NULL,NULL),('vn-database','10347','01-addVirtualField.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-29 11:08:03',NULL,NULL),('vn-database','10349','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-10-06 09:52:38',NULL,NULL),('vn-database','10350','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-09-30 10:11:56',NULL,NULL),('vn-database','10352','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-11-04 08:25:16',NULL,NULL),('vn-database','10353','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-10-06 09:52:38',NULL,NULL),('vn-database','10354','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-10-06 09:52:38',NULL,NULL),('vn-database','10356','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-10 22:35:00',NULL,NULL),('vn-database','10356','01-orderConfigFk.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-10 22:35:00',NULL,NULL),('vn-database','10356','02-orderConfigDrop.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-10 22:35:00',NULL,NULL),('vn-database','10357','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-10-06 09:52:38',NULL,NULL),('vn-database','10359','00-improvedGeneralLog_collate.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-10-06 09:52:39',NULL,NULL),('vn-database','10360','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-10-06 09:52:39',NULL,NULL),('vn-database','10361','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-10-06 11:16:07',NULL,NULL),('vn-database','10362','00-dropUdfs.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-10-10 11:01:15',NULL,NULL),('vn-database','10363','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-11-04 08:25:17',NULL,NULL),('vn-database','10365','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-10-13 19:30:46',NULL,NULL),('vn-database','10368','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-11-04 08:25:17',NULL,NULL),('vn-database','10369','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-10-14 13:38:06',NULL,NULL),('vn-database','10370','00-deleteForeignKey.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-17 14:32:41',NULL,NULL),('vn-database','10370','01-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-17 14:32:47',NULL,NULL),('vn-database','10370','02-deleteTable.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-17 14:32:49',NULL,NULL),('vn-database','10370','03-accion.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-17 14:32:49',NULL,NULL),('vn-database','10370','04-inter.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-17 14:32:53',NULL,NULL),('vn-database','10371','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-12 10:56:23',NULL,NULL),('vn-database','10372','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-12-16 09:14:48',NULL,NULL),('vn-database','10373','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-10-19 08:31:58',NULL,NULL),('vn-database','10378','00-rename_routeUserPercentage.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-11-04 08:25:17',NULL,NULL),('vn-database','10379','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-09 08:40:16',NULL,NULL),('vn-database','10382','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-12-01 08:47:20',NULL,NULL),('vn-database','10383','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-17 14:32:53',NULL,NULL),('vn-database','10384','00-business_workcenterFk.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:18:01',NULL,NULL),('vn-database','10385','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-17 14:32:54',NULL,NULL),('vn-database','10386','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-17 14:32:54',NULL,NULL),('vn-database','10387','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-16 14:05:33',NULL,NULL),('vn-database','10388','00-resizeUtilVerionLogCode.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-12-01 08:47:20',NULL,NULL),('vn-database','10388','01-resizeUtilVersionCode.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-12-01 08:47:20',NULL,NULL),('vn-database','10390','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-12-01 08:50:16',NULL,NULL),('vn-database','10391','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-12 10:56:23',NULL,NULL),('vn-database','10394','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-12-01 08:50:24',NULL,NULL),('vn-database','10395','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-12-01 08:50:29',NULL,NULL),('vn-database','10396','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-17 15:36:38',NULL,NULL),('vn-database','10397','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-12-01 08:50:29',NULL,NULL),('vn-database','10399','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-12-01 08:50:29',NULL,NULL),('vn-database','10400','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-12-01 08:50:29',NULL,NULL),('vn-database','10402','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-21 14:11:31',NULL,NULL),('vn-database','10404','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-12-01 08:50:29',NULL,NULL),('vn-database','10405','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-16 09:58:22',NULL,NULL),('vn-database','10407','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-12-16 09:14:49',NULL,NULL),('vn-database','10408','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-12 10:56:23',NULL,NULL),('vn-database','10409','00-firstScript.sql','jenkins@swarm-worker2.static.verdnatura.es','2022-12-16 09:14:49',NULL,NULL),('vn-database','10412','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2022-11-30 12:45:44',NULL,NULL),('vn-database','10413','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-12 10:56:24',NULL,NULL),('vn-database','10416','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-12 10:56:24',NULL,NULL),('vn-database','10420','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-12 10:56:25',NULL,NULL),('vn-database','10421','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-12 10:56:26',NULL,NULL),('vn-database','10426','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-20 09:07:40',NULL,NULL),('vn-database','10428','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-26 13:27:05',NULL,NULL),('vn-database','10431','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-23 09:09:22',NULL,NULL),('vn-database','10433','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-26 13:27:05',NULL,NULL),('vn-database','10434','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-26 13:27:05',NULL,NULL),('vn-database','10435','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-13 07:30:10',NULL,NULL),('vn-database','10436','00-createFkWorker.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-16 09:58:59',NULL,NULL),('vn-database','10436','01-addStateToWorkerProductivity.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-16 09:59:00',NULL,NULL),('vn-database','10436','02-DeprecateVnSaleTrackingState.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-16 09:59:00',NULL,NULL),('vn-database','10436','03-DeprecateColumnVnSaleTrackingActionFk.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-16 09:59:01',NULL,NULL),('vn-database','10436','04-DropSchemaVnControl.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-16 09:59:01',NULL,NULL),('vn-database','10436','05-RemoveFkWorkerProductivity.sql','jenkins@db-proxy2.static.verdnatura.es','2023-02-17 14:51:19',NULL,NULL),('vn-database','10439','00-fixRole.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-25 09:13:26',NULL,NULL),('vn-database','10440','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-23 10:28:41',NULL,NULL),('vn-database','10444','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-16 09:59:01',NULL,NULL),('vn-database','10445','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-16 09:59:31',NULL,NULL),('vn-database','10448','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-16 09:59:31',NULL,NULL),('vn-database','10450','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-27 08:28:04',NULL,NULL),('vn-database','10451','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-06 08:08:32',NULL,NULL),('vn-database','10452','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-31 12:30:04',NULL,NULL),('vn-database','10453','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-31 14:04:37',NULL,NULL),('vn-database','10454','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-31 12:30:04',NULL,NULL),('vn-database','10455','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-31 12:30:04',NULL,NULL),('vn-database','10456','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-31 12:00:30',NULL,NULL),('vn-database','10457','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-01-31 12:00:33',NULL,NULL),('vn-database','10458','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-09 08:40:17',NULL,NULL),('vn-database','10459','00-alterTableUtilConfig.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-23 10:28:41',NULL,NULL),('vn-database','10459','01-createFunctionCurdate.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-23 10:28:41',NULL,NULL),('vn-database','10459','02-createFunctionMockTime.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-23 10:28:41',NULL,NULL),('vn-database','10459','03-createFunctionMockTimeBase.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-23 10:28:41',NULL,NULL),('vn-database','10459','04-createFunctionNow.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-23 10:28:41',NULL,NULL),('vn-database','10460','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-16 09:59:31',NULL,NULL),('vn-database','10461','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-16 09:59:31',NULL,NULL),('vn-database','10463','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-03 12:59:26',NULL,NULL),('vn-database','10468','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-16 09:59:31',NULL,NULL),('vn-database','10469','00-firstScript.sql','jenkins@swarm-worker1.static.verdnatura.es','2023-02-16 09:59:31',NULL,NULL),('vn-database','10470','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-23 10:28:54',NULL,NULL),('vn-database','10471','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-23 10:28:54',NULL,NULL),('vn-database','10472','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-23 10:28:54',NULL,NULL),('vn-database','10477','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-23 09:09:31',NULL,NULL),('vn-database','10478','00-dropBasket.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-23 10:28:54',NULL,NULL),('vn-database','10478','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-23 10:28:54',NULL,NULL),('vn-database','10478','01-orderConfigured.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-23 10:29:16',NULL,NULL),('vn-database','10478','02-configuredUpdate.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-23 10:29:53',NULL,NULL),('vn-database','10478','99-privileges.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-23 10:29:53',NULL,NULL),('vn-database','10480','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-17 15:09:26',NULL,NULL),('vn-database','10481','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-02-17 16:37:22',NULL,NULL),('vn-database','10482','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-02-21 10:00:28',NULL,NULL),('vn-database','10485','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-09 08:40:17',NULL,NULL),('vn-database','10488','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-09 08:40:17',NULL,NULL),('vn-database','10491','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-09 08:40:18',NULL,NULL),('vn-database','10492','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-09 08:40:18',NULL,NULL),('vn-database','10493','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:18:01',NULL,NULL),('vn-database','10495','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-09 08:40:19',NULL,NULL),('vn-database','10498','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-23 09:09:38',NULL,NULL),('vn-database','10500','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-03-03 07:06:03',NULL,NULL),('vn-database','10501','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-03-03 10:52:24',NULL,NULL),('vn-database','10502','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-23 09:09:48',NULL,NULL),('vn-database','10504','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-25 09:13:27',NULL,NULL),('vn-database','10506','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-23 09:09:48',NULL,NULL),('vn-database','10506','01-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-15 12:30:18',NULL,NULL),('vn-database','10506','02-secondScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-15 12:30:18',NULL,NULL),('vn-database','10506','03-thirdScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-15 12:30:18',NULL,NULL),('vn-database','10507','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-05 10:35:23',NULL,NULL),('vn-database','10508','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-05 10:36:43',NULL,NULL),('vn-database','10510','00-dropBusinessFk.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-05 10:36:47',NULL,NULL),('vn-database','10510','01-createTableProfessionalCategory.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-05 10:36:47',NULL,NULL),('vn-database','10510','02-exportToNewTable.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-05 10:36:47',NULL,NULL),('vn-database','10510','03-RecreateFK.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-05 10:36:51',NULL,NULL),('vn-database','10510','04-kkPostgresqlTable.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-05 10:36:51',NULL,NULL),('vn-database','10511','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-20 09:07:41',NULL,NULL),('vn-database','10512','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-05 10:36:52',NULL,NULL),('vn-database','10513','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-05 10:36:56',NULL,NULL),('vn-database','10514','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-20 09:07:41',NULL,NULL),('vn-database','10516','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-23 09:09:48',NULL,NULL),('vn-database','10521','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-21 06:58:13',NULL,NULL),('vn-database','10522','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-20 09:07:41',NULL,NULL),('vn-database','10523','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-20 09:07:41',NULL,NULL),('vn-database','10524','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-08-10 11:50:12',NULL,NULL),('vn-database','10524','01-rateEditorFk.sql','jenkins@db-proxy2.static.verdnatura.es','2023-08-10 11:50:12',NULL,NULL),('vn-database','10525','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-21 12:42:50',NULL,NULL),('vn-database','10526','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-05 10:36:57',NULL,NULL),('vn-database','10528','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-05 10:37:00',NULL,NULL),('vn-database','10530','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-03-23 14:49:30',NULL,NULL),('vn-database','10531','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-24 11:47:10',NULL,NULL),('vn-database','10532','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-24 11:17:38',NULL,NULL),('vn-database','10533','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-05 10:37:04',NULL,NULL),('vn-database','10537','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-03-29 15:18:36',NULL,NULL),('vn-database','10538','00-createChronopostConfig.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-20 09:07:41',NULL,NULL),('vn-database','10538','01-createChronopostService.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-20 09:07:41',NULL,NULL),('vn-database','10538','02-createChronopostExpedition.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-20 09:07:41',NULL,NULL),('vn-database','10538','03-createChronopostSenderAddress.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-20 09:07:41',NULL,NULL),('vn-database','10538','04-addgrantPrivilegies.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-20 09:07:41',NULL,NULL),('vn-database','10538','05-updateChronopostConfig.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-21 11:54:57',NULL,NULL),('vn-database','10539','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-05 10:37:07',NULL,NULL),('vn-database','10540','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:18:01',NULL,NULL),('vn-database','10545','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-11 08:31:03',NULL,NULL),('vn-database','10546','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-20 09:08:10',NULL,NULL),('vn-database','10547','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:21:58',NULL,NULL),('vn-database','10549','00-updateUpdateLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-21 07:29:22',NULL,NULL),('vn-database','10549','01-updateInsertLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-21 07:30:11',NULL,NULL),('vn-database','10549','02-updateDeleteLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-21 07:30:51',NULL,NULL),('vn-database','10549','03-deleteEmptyLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-21 07:31:34',NULL,NULL),('vn-database','10549','04-optimizeLogTables.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-21 07:33:58',NULL,NULL),('vn-database','10550','00-editorFk.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:42:33',NULL,NULL),('vn-database','10550','01-originFk.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:28',NULL,NULL),('vn-database','10552','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-13 08:25:10',NULL,NULL),('vn-database','10554','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-20 09:08:10',NULL,NULL),('vn-database','10557','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-17 07:45:56',NULL,NULL),('vn-database','10559','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-18 10:53:50',NULL,NULL),('vn-database','10560','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-17 09:19:31',NULL,NULL),('vn-database','10562','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:28',NULL,NULL),('vn-database','10563','00-delivery_ticketFk.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-20 09:30:53',NULL,NULL),('vn-database','10566','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-20 10:08:41',NULL,NULL),('vn-database','10567','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-20 10:18:06',NULL,NULL),('vn-database','10568','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:28',NULL,NULL),('vn-database','10569','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-24 09:14:35',NULL,NULL),('vn-database','10570','00-createSendingConfig.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:28',NULL,NULL),('vn-database','10570','01-createSendingServiceWeekday.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:28',NULL,NULL),('vn-database','10570','02-createSendingService.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:28',NULL,NULL),('vn-database','10570','03-permisos.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:28',NULL,NULL),('vn-database','10571','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-25 09:13:27',NULL,NULL),('vn-database','10573','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-27 09:17:23',NULL,NULL),('vn-database','10575','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-26 11:27:32',NULL,NULL),('vn-database','10577','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-27 14:00:12',NULL,NULL),('vn-database','10578','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:28',NULL,NULL),('vn-database','10579','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-04-28 11:27:36',NULL,NULL),('vn-database','10580','00-itemTypeDropConstraint.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-28 18:18:52',NULL,NULL),('vn-database','10580','01-itemTypeAddConstraint.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-28 18:19:10',NULL,NULL),('vn-database','10581','00-itemTypeAutoIncrement.sql','jenkins@db-proxy2.static.verdnatura.es','2023-04-28 19:06:46',NULL,NULL),('vn-database','10582','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:28',NULL,NULL),('vn-database','10583','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:28',NULL,NULL),('vn-database','10584','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:28',NULL,NULL),('vn-database','10585','00-ticketLog.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-25 09:20:10',NULL,NULL),('vn-database','10585','01-entryLog.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-25 09:21:12',NULL,NULL),('vn-database','10585','02-claimLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:28:36',NULL,NULL),('vn-database','10585','03-clientLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:28:54',NULL,NULL),('vn-database','10585','04-invoiceInLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:28:55',NULL,NULL),('vn-database','10585','05-itemLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:29:46',NULL,NULL),('vn-database','10585','06-routeLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:30:18',NULL,NULL),('vn-database','10585','07-shelvingLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:30:32',NULL,NULL),('vn-database','10585','08-supplierLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:30:32',NULL,NULL),('vn-database','10585','09-travelLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:30:41',NULL,NULL),('vn-database','10585','10-workerLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:30:42',NULL,NULL),('vn-database','10585','11-zoneLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:30:43',NULL,NULL),('vn-database','10585','12-userLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:30:44',NULL,NULL),('vn-database','10585','13-roleLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:30:44',NULL,NULL),('vn-database','10587','00-arcRead_addMinimum.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-16 13:13:15',NULL,NULL),('vn-database','10593','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:30:44',NULL,NULL),('vn-database','10596','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:30:44',NULL,NULL),('vn-database','10597','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:30:44',NULL,NULL),('vn-database','10598','00-workerLog.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:29',NULL,NULL),('vn-database','10598','01-supplierLog.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:29',NULL,NULL),('vn-database','10598','02-workerTimeControlLog.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:29',NULL,NULL),('vn-database','10598','03-workerClockLog.sql','jenkins@db-proxy2.static.verdnatura.es','2023-05-12 09:45:29',NULL,NULL),('vn-database','10599','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 09:30:44',NULL,NULL),('vn-database','10601','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-17 09:26:26',NULL,NULL),('vn-database','10602','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-18 08:52:15',NULL,NULL),('vn-database','10606','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-18 09:26:00',NULL,NULL),('vn-database','10608','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-18 12:36:31',NULL,NULL),('vn-database','10609','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-01 08:28:07',NULL,NULL),('vn-database','10610','00-updateCompanyId.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-01 09:11:07',NULL,NULL),('vn-database','10610','01-updateSupplierId.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-01 09:11:39',NULL,NULL),('vn-database','10610','02-invoiceOutCompany.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-01 09:49:55',NULL,NULL),('vn-database','10611','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-19 14:39:41',NULL,NULL),('vn-database','10613','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-15 12:30:18',NULL,NULL),('vn-database','10614','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-01 09:11:40',NULL,NULL),('vn-database','10615','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-01 09:11:40',NULL,NULL),('vn-database','10616','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-13 11:18:55',NULL,NULL),('vn-database','10616','01-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-13 11:18:55',NULL,NULL),('vn-database','10617','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-01 09:11:41',NULL,NULL),('vn-database','10618','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-25 12:55:56',NULL,NULL),('vn-database','10619','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-15 12:30:18',NULL,NULL),('vn-database','10620','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-13 11:20:53',NULL,NULL),('vn-database','10624','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-05-30 19:01:10',NULL,NULL),('vn-database','10625','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-02 09:13:26',NULL,NULL),('vn-database','10626','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-29 13:32:32',NULL,NULL),('vn-database','10628','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-15 12:30:18',NULL,NULL),('vn-database','10630','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-02 13:30:58',NULL,NULL),('vn-database','10631','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-05 08:37:25',NULL,NULL),('vn-database','10632','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-15 12:30:18',NULL,NULL),('vn-database','10633','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-15 12:30:18',NULL,NULL),('vn-database','10634','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-06 12:15:55',NULL,NULL),('vn-database','10637','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-15 12:30:19',NULL,NULL),('vn-database','10640','00-companyFkDrop.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-07 14:43:23',NULL,NULL),('vn-database','10640','00-updateCompany.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-07 14:22:13',1205,'Tiempo de espera de bloqueo excedido; intente rearrancar la transacción'),('vn-database','10640','01-companyFkAi.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-07 14:43:23',NULL,NULL),('vn-database','10640','02-companyFkCreate.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-07 14:47:04',NULL,NULL),('vn-database','10640','04-supplierFkDrop.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-07 14:48:30',NULL,NULL),('vn-database','10640','05-supplierFkAi.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-07 14:53:17',NULL,NULL),('vn-database','10640','06-supplierFkCreate.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-07 15:06:00',NULL,NULL),('vn-database','10642','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-29 14:04:13',NULL,NULL),('vn-database','10643','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-09 15:04:35',NULL,NULL),('vn-database','10644','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-13 11:22:18',NULL,NULL),('vn-database','10645','00-addNewFields.sql','jenkins@db-proxy2.static.verdnatura.es','2023-09-07 10:43:11',NULL,NULL),('vn-database','10645','01-updateCollectionWagonPrimaryKey.sql','jenkins@db-proxy2.static.verdnatura.es','2023-09-07 10:43:11',NULL,NULL),('vn-database','10645','02-updateWagonPrimaryKey.sql','jenkins@db-proxy2.static.verdnatura.es','2023-09-07 10:43:12',NULL,NULL),('vn-database','10645','03-addFieldToPackingSite.sql','jenkins@db-proxy2.static.verdnatura.es','2023-09-07 10:43:12',NULL,NULL),('vn-database','10647','00-renombrarTabla.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-29 14:04:13',NULL,NULL),('vn-database','10648','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-27 09:17:24',NULL,NULL),('vn-database','10649','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-16 10:59:06',NULL,NULL),('vn-database','10652','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-06-29 14:04:13',NULL,NULL),('vn-database','10653','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-13 11:22:20',NULL,NULL),('vn-database','10655','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-13 11:22:24',NULL,NULL),('vn-database','10656','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-27 09:17:24',NULL,NULL),('vn-database','10657','00-renameErrorProduction.sql','jenkins@db-proxy2.static.verdnatura.es','2023-09-07 10:43:12',NULL,NULL),('vn-database','10657','01-changeNightTask.sql','jenkins@db-proxy2.static.verdnatura.es','2023-09-07 10:43:12',NULL,NULL),('vn-database','10657','02-addCodeToClaimResponsible.sql','jenkins@db-proxy2.static.verdnatura.es','2023-09-07 10:43:12',NULL,NULL),('vn-database','10657','03-grantSelectGrafana.sql','jenkins@db-proxy2.static.verdnatura.es','2023-09-07 10:43:12',NULL,NULL),('vn-database','10658','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-13 11:22:27',NULL,NULL),('vn-database','10659','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-27 09:17:24',NULL,NULL),('vn-database','10661','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-16 09:27:50',NULL,NULL),('vn-database','10662','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-13 11:22:33',NULL,NULL),('vn-database','10663','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-13 11:22:34',NULL,NULL),('vn-database','10665','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-06-30 08:52:51',NULL,NULL),('vn-database','10666','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-13 11:22:34',NULL,NULL),('vn-database','10667','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-27 09:17:24',NULL,NULL),('vn-database','10668','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-08-10 11:50:13',NULL,NULL),('vn-database','10671','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-25 14:56:50',NULL,NULL),('vn-database','10675','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-27 09:17:24',NULL,NULL),('vn-database','10676','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-27 09:17:24',NULL,NULL),('vn-database','10677','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-09-21 09:42:22',NULL,NULL),('vn-database','10678','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-09-07 10:43:12',NULL,NULL),('vn-database','10679','00-tables.sql','jenkins@db-proxy2.static.verdnatura.es','2023-07-27 09:17:24',NULL,NULL),('vn-database','10680','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-07-18 14:58:36',NULL,NULL),('vn-database','10682','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-08-10 11:50:13',NULL,NULL),('vn-database','10683','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-09-07 10:43:12',NULL,NULL),('vn-database','10684','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-02 09:13:26',NULL,NULL),('vn-database','10685','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-10-05 09:53:55',NULL,NULL),('vn-database','10690','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-07-27 10:52:26',NULL,NULL),('vn-database','10691','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-07-31 13:37:21',NULL,NULL),('vn-database','10692','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-08-10 11:50:13',NULL,NULL),('vn-database','10693','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-08-10 11:50:13',NULL,NULL),('vn-database','10694','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-08-02 09:50:53',NULL,NULL),('vn-database','10695','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-08-02 13:40:16',NULL,NULL),('vn-database','10696','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-08-03 16:54:57',NULL,NULL),('vn-database','10698','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-08-03 08:53:12',NULL,NULL),('vn-database','10699','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-08-03 15:24:30',NULL,NULL),('vn-database','10700','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-08-29 09:42:11',NULL,NULL),('vn-database','10701','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-09-07 10:43:12',NULL,NULL),('vn-database','10702','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-08-10 12:50:46',NULL,NULL),('vn-database','10704','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-08-29 09:42:14',NULL,NULL),('vn-database','10705','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-08-16 14:16:05',NULL,NULL),('vn-database','10707','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-08-21 12:31:18',NULL,NULL),('vn-database','10708','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-09-07 10:43:13',NULL,NULL),('vn-database','10712','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-09-07 10:43:13',NULL,NULL),('vn-database','10714','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-08-28 13:01:45',NULL,NULL),('vn-database','10716','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-16 09:27:50',NULL,NULL),('vn-database','10717','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-16 09:28:54',NULL,NULL),('vn-database','10718','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-02 09:13:26',NULL,NULL),('vn-database','10719','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-09-01 12:53:30',NULL,NULL),('vn-database','10720','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-09-21 09:42:22',NULL,NULL),('vn-database','10721','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-09-21 09:42:29',NULL,NULL),('vn-database','10722','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-09 13:00:29',NULL,NULL),('vn-database','10725','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-09-12 14:15:14',NULL,NULL),('vn-database','10726','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-09-21 15:32:20',NULL,NULL),('vn-database','10727','00-addPrinterField.sql','jenkins@db-proxy1.static.verdnatura.es','2023-09-21 09:42:29',NULL,NULL),('vn-database','10727','01-createTableScreenModel.sql','jenkins@db-proxy1.static.verdnatura.es','2023-09-21 09:42:29',NULL,NULL),('vn-database','10727','02-createTableScreen.sql','jenkins@db-proxy1.static.verdnatura.es','2023-09-21 09:42:29',NULL,NULL),('vn-database','10727','03-createTableScreenModel.sql','jenkins@db-proxy1.static.verdnatura.es','2023-09-21 09:42:29',NULL,NULL),('vn-database','10727','04-createTableScanner.sql','jenkins@db-proxy1.static.verdnatura.es','2023-09-21 09:42:29',NULL,NULL),('vn-database','10727','05-createTablePackingSiteDeviceLog.sql','jenkins@db-proxy1.static.verdnatura.es','2023-09-21 09:42:29',NULL,NULL),('vn-database','10727','06-alterTablePrinterModel.sql','jenkins@db-proxy1.static.verdnatura.es','2023-09-21 09:42:29',NULL,NULL),('vn-database','10727','07-AddFieldsToPackingSite.sql','jenkins@db-proxy1.static.verdnatura.es','2023-09-21 09:42:30',NULL,NULL),('vn-database','10730','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-09-15 11:42:48',NULL,NULL),('vn-database','10733','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-10-05 09:54:00',NULL,NULL),('vn-database','10736','00-workerBossNull.sql','jenkins@db-proxy1.static.verdnatura.es','2023-09-22 00:02:05',NULL,NULL),('vn-database','10739','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-10-10 10:19:07',NULL,NULL),('vn-database','10740','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-02 09:13:26',NULL,NULL),('vn-database','10741','01-refactorCplusTrascendency472.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-02 09:13:27',NULL,NULL),('vn-database','10741','02-refactorCplusTrascendency477.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-02 09:13:27',NULL,NULL),('vn-database','10741','03-refactorCplusInvoiceType477.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-02 09:13:27',NULL,NULL),('vn-database','10741','04-refactorCplusInvoiceType472.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-02 09:13:27',NULL,NULL),('vn-database','10741','05-fixes.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-02 09:13:27',NULL,NULL),('vn-database','10744','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-10-13 09:23:19',NULL,NULL),('vn-database','10746','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-10-16 18:22:46',NULL,NULL),('vn-database','10747','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-02 09:13:32',NULL,NULL),('vn-database','10748','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-02 09:13:32',NULL,NULL),('vn-database','10748','01-SecondScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-02 09:13:34',NULL,NULL),('vn-database','10749','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-10-22 16:08:17',NULL,NULL),('vn-database','10750','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-10-23 13:04:17',NULL,NULL),('vn-database','10750','00-ticket_addGrants.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-02 09:13:34',NULL,NULL),('vn-database','10751','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-02 09:13:34',NULL,NULL),('vn-database','10752','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-10-24 14:07:54',NULL,NULL),('vn-database','10753','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-10-24 14:37:21',NULL,NULL),('vn-database','10754','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-02 09:13:34',NULL,NULL),('vn-database','10755','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-02 09:13:35',NULL,NULL),('vn-database','10756','00-firstScript.sql','jenkins@db-proxy2.static.verdnatura.es','2023-11-03 07:14:38',NULL,NULL),('vn-database','10757','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-16 09:30:57',NULL,NULL),('vn-database','10761','00-firstScript.sql','jenkins@db-proxy1.static.verdnatura.es','2023-11-16 09:30:58',NULL,NULL); /*!40000 ALTER TABLE `versionLog` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; @@ -54,7 +54,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2023-08-30 15:53:14 +-- Dump completed on 2023-11-20 12:26:42 USE `account`; -- MariaDB dump 10.19 Distrib 10.5.19-MariaDB, for debian-linux-gnu (x86_64) -- @@ -78,7 +78,7 @@ USE `account`; LOCK TABLES `role` WRITE; /*!40000 ALTER TABLE `role` DISABLE KEYS */; -INSERT INTO `role` VALUES (1,'employee','Empleado básico',1,'2017-05-19 07:04:58','2023-06-08 16:47:57',NULL),(2,'customer','Privilegios básicos de un cliente',1,'2017-05-19 07:04:58','2023-06-02 20:33:28',NULL),(3,'agency','Consultar tablas de predicciones de bultos',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(5,'administrative','Tareas relacionadas con la contabilidad',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(6,'guest','Privilegios para usuarios sin cuenta',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(9,'developer','Desarrolladores del sistema',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(11,'account','Privilegios relacionados con el login',0,'2017-05-19 07:04:58','2017-09-20 17:06:35',NULL),(13,'teamBoss','Jefe de equipo/departamento',1,'2017-05-19 07:04:58','2021-06-30 13:29:30',NULL),(15,'logistic','Departamento de compras, responsables de la logistica',1,'2017-05-19 07:04:58','2018-02-12 10:50:10',NULL),(16,'logisticBoss','Jefe del departamento de logística',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(17,'adminBoss','Jefe del departamento de administración',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(18,'salesPerson','Departamento de ventas',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(19,'salesBoss','Jefe del departamento de ventas',1,'2017-05-19 07:04:58','2017-08-16 12:38:27',NULL),(20,'manager','Gerencia',1,'2017-06-01 14:57:02','2022-07-29 07:36:15',NULL),(21,'salesAssistant','Jefe auxiliar de ventas',1,'2017-08-16 12:40:52','2017-08-16 12:40:52',NULL),(22,'teamManager','Jefe de departamento con privilegios de auxiliar de venta.',1,'2017-09-07 09:08:12','2017-09-07 09:08:12',NULL),(30,'financialBoss','Director finaciero',1,'2017-09-21 11:05:36','2017-09-21 11:05:36',NULL),(31,'freelancer','Trabajadores por cuenta ajena',1,'2017-10-10 12:57:26','2017-10-10 12:59:27',NULL),(32,'ett','Trabajadores de empresa temporal',1,'2017-10-10 12:58:58','2017-10-10 12:59:20',NULL),(33,'invoicing','Personal con acceso a facturación',0,'2018-01-29 16:43:34','2018-01-29 16:43:34',NULL),(34,'agencyBoss','Jefe/a del departamento de agencias',1,'2018-01-29 16:44:39','2018-02-23 07:58:53',NULL),(35,'buyer','Departamento de compras',1,'2018-02-12 10:35:42','2018-02-12 10:35:42',NULL),(36,'replenisher','Trabajadores de camara',1,'2018-02-16 14:07:10','2019-04-12 05:38:08',NULL),(37,'hr','Gestor/a de recursos humanos',1,'2018-02-22 17:34:53','2018-02-22 17:34:53',NULL),(38,'hrBoss','Jefe/a de recursos humanos',1,'2018-02-22 17:35:09','2018-02-22 17:35:09',NULL),(39,'adminAssistant','Jefe auxiliar administrativo',1,'2018-02-23 10:37:36','2018-02-23 10:38:41',NULL),(40,'handmade','Departamento de confección',1,'2018-02-23 11:14:53','2018-02-23 11:39:12',NULL),(41,'handmadeBoss','Jefe de departamento de confección',1,'2018-02-23 11:15:09','2018-02-23 11:39:26',NULL),(42,'artificial','Departamento de artificial',1,'2018-02-23 11:39:59','2018-02-23 11:39:59',NULL),(43,'artificialBoss','Jefe del departamento de artificial',1,'2018-02-23 11:40:16','2018-02-23 11:40:16',NULL),(44,'accessory','Departamento de complementos',1,'2018-02-23 11:41:12','2018-02-23 11:41:12',NULL),(45,'accessoryBoss','Jefe del departamento de complementos',1,'2018-02-23 11:41:23','2018-02-23 11:41:23',NULL),(47,'cooler','Empleados de cámara',1,'2018-02-23 13:08:18','2018-02-23 13:08:18',NULL),(48,'coolerBoss','Jefe de cámara',1,'2018-02-23 13:12:01','2023-03-13 08:49:43',NULL),(49,'production','Empleado de producción',1,'2018-02-26 15:28:23','2021-02-12 09:42:35',NULL),(50,'productionBoss','Jefe de producción',1,'2018-02-26 15:34:12','2018-02-26 15:34:12',NULL),(51,'marketing','Departamento de marketing',1,'2018-03-01 07:28:39','2018-03-01 07:28:39',NULL),(52,'marketingBoss','Jefe del departamento de marketing',1,'2018-03-01 07:28:57','2018-03-01 07:28:57',NULL),(53,'insurance','Gestor de seguros de cambio',0,'2018-03-05 07:44:35','2019-02-01 13:47:57',NULL),(54,'itemPicker','Sacador en cámara',1,'2018-03-05 12:08:17','2018-03-05 12:08:17',NULL),(55,'itemPickerBoss','Jefe de sacadores',1,'2018-03-05 12:08:31','2018-03-05 12:08:31',NULL),(56,'delivery','Personal de reparto',1,'2018-05-30 06:07:02','2018-05-30 06:07:02',NULL),(57,'deliveryBoss','Jefe de personal de reparto',1,'2018-05-30 06:07:19','2018-05-30 06:07:19',NULL),(58,'packager','Departamento encajadores',1,'2019-01-21 12:43:45','2019-01-21 12:43:45',NULL),(59,'packagerBoss','Jefe departamento encajadores',1,'2019-01-21 12:44:10','2019-01-21 12:44:10',NULL),(60,'productionAssi','Tareas relacionadas con producción y administración',1,'2019-01-29 13:29:01','2019-01-29 13:29:01',NULL),(61,'replenisherBos','Jefe de Complementos/Camara',1,'2019-07-01 06:44:07','2019-07-01 06:44:07',NULL),(62,'noLogin','Role without login access to MySQL',0,'2019-07-01 06:50:19','2019-07-02 13:42:05',NULL),(64,'balanceSheet','Consulta de Balance',0,'2019-07-16 12:12:08','2019-07-16 12:12:08',NULL),(65,'officeBoss','Jefe de filial',1,'2019-08-02 06:54:26','2019-08-02 06:54:26',NULL),(66,'sysadmin','Administrador de sistema',1,'2019-08-08 06:58:56','2019-08-08 06:58:56',NULL),(67,'adminOfficer','categoria profesional oficial de administración',1,'2020-01-03 08:09:23','2020-01-03 08:09:23',NULL),(69,'coolerAssist','Asistente de cámara con permiso compras',1,'2020-02-05 12:36:09','2023-03-13 08:50:07',NULL),(70,'trainee','Alumno de prácticas',1,'2020-03-04 11:00:25','2020-03-04 11:00:25',NULL),(71,'checker','Rol de revisor con privilegios de itemPicker',1,'2020-10-02 10:50:07','2020-10-02 10:50:07',NULL),(72,'claimManager','Personal de reclamaciones',1,'2020-10-13 10:01:32','2020-10-26 07:29:46',NULL),(73,'financial','Departamento de finanzas',1,'2020-11-16 09:30:27','2020-11-16 09:30:27',NULL),(74,'userPhotos','Privilegios para subir fotos de usuario',1,'2021-02-03 10:24:27','2021-02-03 10:24:27',NULL),(75,'catalogPhotos','Privilegios para subir fotos del catálogo',1,'2021-02-03 10:24:27','2021-02-03 10:24:27',NULL),(76,'chat','Rol para utilizar el rocket chat',1,'2020-11-27 13:06:50','2020-12-17 07:49:41',NULL),(100,'root','Rol con todos los privilegios',0,'2018-04-23 14:33:36','2020-11-12 06:50:07',NULL),(101,'buyerBoss','Jefe del departamento de compras',1,'2021-06-16 09:53:17','2021-06-16 09:53:17',NULL),(102,'preservedBoss','Responsable preservado',1,'2021-09-14 13:45:37','2021-09-14 13:45:37',NULL),(103,'it','Departamento de informática',1,'2021-11-11 09:48:22','2021-11-11 09:48:22',NULL),(104,'itBoss','Jefe de departamento de informática',1,'2021-11-11 09:48:49','2021-11-11 09:48:49',NULL),(105,'grant','Adjudicar roles a usuarios',1,'2021-11-11 12:41:09','2021-11-11 12:41:09',NULL),(106,'ext','Usuarios externos de la Base de datos',1,'2021-11-23 14:51:16','2021-11-23 14:51:16',NULL),(107,'productionPlus','Creado para pepe por orden de Juanvi',1,'2022-02-08 06:47:10','2022-02-08 06:47:10',NULL),(108,'system','System user',1,'2022-05-16 08:09:51','2022-05-16 08:09:51',NULL),(109,'salesTeamBoss','Jefe de equipo de comerciales',1,'2022-06-14 13:45:56','2022-06-14 13:45:56',NULL),(110,'palletizer','Paletizadores',1,'2022-12-02 12:56:22','2022-12-02 12:56:30',NULL),(111,'entryEditor','Entry editor',1,'2023-01-13 11:21:55','2023-01-13 11:21:55',NULL),(112,'maintenance','Personal de mantenimiento',1,'2023-01-19 06:23:35','2023-01-19 06:23:35',NULL),(114,'maintenanceBos','Jefe de mantenimiento',1,'2023-01-19 06:31:16','2023-05-17 11:07:21',NULL),(115,'itManagement','TI management',1,'2023-03-29 07:27:55','2023-03-29 07:28:04',NULL),(119,'palletizerBoss','Jefe de paletizadores',1,'2023-06-07 11:51:54','2023-06-07 11:51:54',NULL),(120,'developerBoss','Jefe de proyecto de desarrollo',1,'2023-06-19 07:07:21','2023-06-19 07:07:21',21709),(121,'buyerSalesAssistant','Rol para compradores que también son responsables de ventas',1,'2023-06-23 14:48:19','2023-06-23 14:48:19',NULL),(122,'logisticAssistant','Jefe auxiliar de logística',1,'2023-06-26 07:21:15','2023-06-26 07:21:15',NULL); +INSERT INTO `role` VALUES (1,'employee','Empleado básico',1,'2017-05-19 07:04:58','2023-06-08 16:47:57',NULL),(2,'customer','Privilegios básicos de un cliente',1,'2017-05-19 07:04:58','2023-06-02 20:33:28',NULL),(3,'agency','Consultar tablas de predicciones de bultos',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(5,'administrative','Tareas relacionadas con la contabilidad',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(6,'guest','Privilegios para usuarios sin cuenta',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(9,'developer','Desarrolladores del sistema',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(11,'account','Privilegios relacionados con el login',0,'2017-05-19 07:04:58','2017-09-20 17:06:35',NULL),(13,'teamBoss','Jefe de equipo/departamento',1,'2017-05-19 07:04:58','2021-06-30 13:29:30',NULL),(15,'logistic','Departamento de compras, responsables de la logistica',1,'2017-05-19 07:04:58','2018-02-12 10:50:10',NULL),(16,'logisticBoss','Jefe del departamento de logística',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(17,'adminBoss','Jefe del departamento de administración',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(18,'salesPerson','Departamento de ventas',1,'2017-05-19 07:04:58','2017-05-19 07:04:58',NULL),(19,'salesBoss','Jefe del departamento de ventas',1,'2017-05-19 07:04:58','2017-08-16 12:38:27',NULL),(20,'manager','Gerencia',1,'2017-06-01 14:57:02','2022-07-29 07:36:15',NULL),(21,'salesAssistant','Jefe auxiliar de ventas',1,'2017-08-16 12:40:52','2017-08-16 12:40:52',NULL),(22,'teamManager','Jefe de departamento con privilegios de auxiliar de venta.',1,'2017-09-07 09:08:12','2017-09-07 09:08:12',NULL),(30,'financialBoss','Director finaciero',1,'2017-09-21 11:05:36','2017-09-21 11:05:36',NULL),(31,'freelancer','Trabajadores por cuenta ajena',1,'2017-10-10 12:57:26','2017-10-10 12:59:27',NULL),(32,'ett','Trabajadores de empresa temporal',1,'2017-10-10 12:58:58','2017-10-10 12:59:20',NULL),(33,'invoicing','Personal con acceso a facturación',0,'2018-01-29 16:43:34','2018-01-29 16:43:34',NULL),(34,'agencyBoss','Jefe/a del departamento de agencias',1,'2018-01-29 16:44:39','2018-02-23 07:58:53',NULL),(35,'buyer','Departamento de compras',1,'2018-02-12 10:35:42','2018-02-12 10:35:42',NULL),(36,'replenisher','Trabajadores de camara',1,'2018-02-16 14:07:10','2019-04-12 05:38:08',NULL),(37,'hr','Gestor/a de recursos humanos',1,'2018-02-22 17:34:53','2018-02-22 17:34:53',NULL),(38,'hrBoss','Jefe/a de recursos humanos',1,'2018-02-22 17:35:09','2018-02-22 17:35:09',NULL),(39,'adminAssistant','Jefe auxiliar administrativo',1,'2018-02-23 10:37:36','2018-02-23 10:38:41',NULL),(40,'handmade','Departamento de confección',1,'2018-02-23 11:14:53','2018-02-23 11:39:12',NULL),(41,'handmadeBoss','Jefe de departamento de confección',1,'2018-02-23 11:15:09','2018-02-23 11:39:26',NULL),(42,'artificial','Departamento de artificial',1,'2018-02-23 11:39:59','2018-02-23 11:39:59',NULL),(43,'artificialBoss','Jefe del departamento de artificial',1,'2018-02-23 11:40:16','2018-02-23 11:40:16',NULL),(44,'accessory','Departamento de complementos',1,'2018-02-23 11:41:12','2018-02-23 11:41:12',NULL),(45,'accessoryBoss','Jefe del departamento de complementos',1,'2018-02-23 11:41:23','2018-02-23 11:41:23',NULL),(47,'cooler','Empleados de cámara',1,'2018-02-23 13:08:18','2018-02-23 13:08:18',NULL),(48,'coolerBoss','Jefe de cámara',1,'2018-02-23 13:12:01','2023-03-13 08:49:43',NULL),(49,'production','Empleado de producción',1,'2018-02-26 15:28:23','2021-02-12 09:42:35',NULL),(50,'productionBoss','Jefe de producción',1,'2018-02-26 15:34:12','2018-02-26 15:34:12',NULL),(51,'marketing','Departamento de marketing',1,'2018-03-01 07:28:39','2018-03-01 07:28:39',NULL),(52,'marketingBoss','Jefe del departamento de marketing',1,'2018-03-01 07:28:57','2018-03-01 07:28:57',NULL),(53,'insurance','Gestor de seguros de cambio',0,'2018-03-05 07:44:35','2019-02-01 13:47:57',NULL),(54,'itemPicker','Sacador en cámara',1,'2018-03-05 12:08:17','2018-03-05 12:08:17',NULL),(55,'itemPickerBoss','Jefe de sacadores',1,'2018-03-05 12:08:31','2018-03-05 12:08:31',NULL),(56,'delivery','Personal de reparto',1,'2018-05-30 06:07:02','2018-05-30 06:07:02',NULL),(57,'deliveryBoss','Jefe de personal de reparto',1,'2018-05-30 06:07:19','2018-05-30 06:07:19',NULL),(58,'packager','Departamento encajadores',1,'2019-01-21 12:43:45','2019-01-21 12:43:45',NULL),(59,'packagerBoss','Jefe departamento encajadores',1,'2019-01-21 12:44:10','2019-01-21 12:44:10',NULL),(60,'productionAssi','Tareas relacionadas con producción y administración',1,'2019-01-29 13:29:01','2019-01-29 13:29:01',NULL),(61,'replenisherBos','Jefe de Complementos/Camara',1,'2019-07-01 06:44:07','2019-07-01 06:44:07',NULL),(62,'noLogin','Role without login access to MySQL',0,'2019-07-01 06:50:19','2019-07-02 13:42:05',NULL),(64,'balanceSheet','Consulta de Balance',0,'2019-07-16 12:12:08','2019-07-16 12:12:08',NULL),(65,'officeBoss','Jefe de filial',1,'2019-08-02 06:54:26','2019-08-02 06:54:26',NULL),(66,'sysadmin','Administrador de sistema',1,'2019-08-08 06:58:56','2019-08-08 06:58:56',NULL),(67,'adminOfficer','categoria profesional oficial de administración',1,'2020-01-03 08:09:23','2020-01-03 08:09:23',NULL),(69,'coolerAssist','Asistente de cámara con permiso compras',1,'2020-02-05 12:36:09','2023-03-13 08:50:07',NULL),(70,'trainee','Alumno de prácticas',1,'2020-03-04 11:00:25','2020-03-04 11:00:25',NULL),(71,'checker','Rol de revisor con privilegios de itemPicker',1,'2020-10-02 10:50:07','2020-10-02 10:50:07',NULL),(72,'claimManager','Personal de reclamaciones',1,'2020-10-13 10:01:32','2020-10-26 07:29:46',NULL),(73,'financial','Departamento de finanzas',1,'2020-11-16 09:30:27','2020-11-16 09:30:27',NULL),(74,'userPhotos','Privilegios para subir fotos de usuario',1,'2021-02-03 10:24:27','2021-02-03 10:24:27',NULL),(75,'catalogPhotos','Privilegios para subir fotos del catálogo',1,'2021-02-03 10:24:27','2021-02-03 10:24:27',NULL),(76,'chat','Rol para utilizar el rocket chat',1,'2020-11-27 13:06:50','2020-12-17 07:49:41',NULL),(100,'root','Rol con todos los privilegios',0,'2018-04-23 14:33:36','2020-11-12 06:50:07',NULL),(101,'buyerBoss','Jefe del departamento de compras',1,'2021-06-16 09:53:17','2021-06-16 09:53:17',NULL),(102,'preservedBoss','Responsable preservado',1,'2021-09-14 13:45:37','2021-09-14 13:45:37',NULL),(103,'it','Departamento de informática',1,'2021-11-11 09:48:22','2021-11-11 09:48:22',NULL),(104,'itBoss','Jefe de departamento de informática',1,'2021-11-11 09:48:49','2021-11-11 09:48:49',NULL),(105,'grant','Adjudicar roles a usuarios',1,'2021-11-11 12:41:09','2021-11-11 12:41:09',NULL),(106,'ext','Usuarios externos de la Base de datos',1,'2021-11-23 14:51:16','2021-11-23 14:51:16',NULL),(107,'productionPlus','Creado para pepe por orden de Juanvi',1,'2022-02-08 06:47:10','2022-02-08 06:47:10',NULL),(108,'system','System user',1,'2022-05-16 08:09:51','2022-05-16 08:09:51',NULL),(109,'salesTeamBoss','Jefe de equipo de comerciales',1,'2022-06-14 13:45:56','2022-06-14 13:45:56',NULL),(110,'palletizer','Paletizadores',1,'2022-12-02 12:56:22','2022-12-02 12:56:30',NULL),(111,'entryEditor','Entry editor',1,'2023-01-13 11:21:55','2023-01-13 11:21:55',NULL),(112,'maintenance','Personal de mantenimiento',1,'2023-01-19 06:23:35','2023-01-19 06:23:35',NULL),(114,'maintenanceBos','Jefe de mantenimiento',1,'2023-01-19 06:31:16','2023-05-17 11:07:21',NULL),(115,'itManagement','TI management',1,'2023-03-29 07:27:55','2023-03-29 07:28:04',NULL),(119,'palletizerBoss','Jefe de paletizadores',1,'2023-06-07 11:51:54','2023-06-07 11:51:54',NULL),(120,'developerBoss','Jefe de proyecto de desarrollo',1,'2023-06-19 07:07:21','2023-06-19 07:07:21',21709),(121,'buyerSalesAssistant','Rol para compradores que también son responsables de ventas',1,'2023-06-23 14:48:19','2023-06-23 14:48:19',NULL),(122,'logisticAssistant','Jefe auxiliar de logística',1,'2023-06-26 07:21:15','2023-06-26 07:21:15',NULL),(123,'deliveryAssistant','Jefe auxiliar repartos',1,'2023-10-05 06:47:48','2023-10-05 06:47:48',10578),(124,'hrBuyer','Recursos Humanos con Buyer',1,'2023-10-23 11:50:43','2023-10-23 11:50:43',NULL),(125,'claimViewer','Trabajadores que consulta las reclamaciones ',1,'2023-11-16 08:14:46','2023-11-16 08:14:46',10578),(126,'greenhouseBoss','Jefe de invernadero',1,'2023-11-16 13:32:13','2023-11-16 13:32:13',NULL); /*!40000 ALTER TABLE `role` ENABLE KEYS */; UNLOCK TABLES; @@ -88,7 +88,7 @@ UNLOCK TABLES; LOCK TABLES `roleInherit` WRITE; /*!40000 ALTER TABLE `roleInherit` DISABLE KEYS */; -INSERT INTO `roleInherit` VALUES (1,1,2,NULL),(2,1,3,NULL),(3,1,70,NULL),(4,2,11,NULL),(5,3,11,NULL),(6,5,1,NULL),(8,5,33,NULL),(10,11,6,NULL),(11,13,1,NULL),(12,15,35,NULL),(16,17,20,NULL),(17,17,37,NULL),(18,17,39,NULL),(19,17,64,NULL),(20,18,1,NULL),(21,19,21,NULL),(22,20,13,NULL),(23,20,16,NULL),(24,20,65,NULL),(25,21,13,NULL),(26,21,18,NULL),(27,21,53,NULL),(28,22,13,NULL),(29,22,21,NULL),(30,30,5,NULL),(31,30,20,NULL),(32,30,22,NULL),(33,30,53,NULL),(34,30,64,NULL),(35,31,1,NULL),(36,32,1,NULL),(37,34,1,NULL),(38,34,13,NULL),(39,34,33,NULL),(40,35,1,NULL),(41,36,44,NULL),(42,36,47,NULL),(43,37,1,NULL),(44,38,37,NULL),(45,38,64,NULL),(46,39,5,NULL),(47,39,21,NULL),(48,39,57,NULL),(49,40,1,NULL),(50,40,49,NULL),(51,41,13,NULL),(52,41,35,NULL),(53,41,40,NULL),(54,42,35,NULL),(55,42,49,NULL),(56,43,13,NULL),(57,43,42,NULL),(58,44,1,NULL),(59,45,13,NULL),(60,45,44,NULL),(61,47,1,NULL),(62,48,13,NULL),(63,48,47,NULL),(64,49,36,NULL),(65,49,58,NULL),(66,50,13,NULL),(67,50,21,NULL),(68,50,35,NULL),(69,50,49,NULL),(70,50,57,NULL),(72,51,1,NULL),(73,52,13,NULL),(74,52,19,NULL),(76,52,51,NULL),(77,53,1,NULL),(78,54,1,NULL),(79,55,13,NULL),(80,55,54,NULL),(81,56,1,NULL),(82,57,13,NULL),(83,57,56,NULL),(84,58,1,NULL),(85,59,13,NULL),(87,60,5,NULL),(91,61,13,NULL),(92,61,36,NULL),(94,65,35,NULL),(97,67,5,NULL),(98,67,37,NULL),(99,69,35,NULL),(101,70,11,NULL),(102,71,1,NULL),(103,71,58,NULL),(105,72,18,NULL),(106,73,5,NULL),(107,73,64,NULL),(108,73,19,NULL),(109,59,50,NULL),(115,39,76,NULL),(117,65,76,NULL),(118,30,76,NULL),(124,5,76,NULL),(125,37,76,NULL),(126,38,76,NULL),(128,42,76,NULL),(129,35,76,NULL),(130,60,76,NULL),(131,21,76,NULL),(132,18,76,NULL),(133,50,76,NULL),(134,20,76,NULL),(135,41,76,NULL),(136,17,76,NULL),(137,52,76,NULL),(138,57,76,NULL),(139,37,74,NULL),(140,51,74,NULL),(141,51,75,NULL),(142,35,75,NULL),(143,15,49,NULL),(145,17,67,NULL),(146,38,13,NULL),(147,101,35,NULL),(148,101,13,NULL),(150,15,56,NULL),(152,69,47,NULL),(153,48,35,NULL),(154,102,1,NULL),(167,9,103,NULL),(168,66,9,NULL),(169,104,100,NULL),(172,103,76,NULL),(173,103,1,NULL),(174,103,44,NULL),(175,103,45,NULL),(176,103,11,NULL),(177,103,39,NULL),(178,103,17,NULL),(179,103,5,NULL),(180,103,67,NULL),(181,103,3,NULL),(182,103,34,NULL),(183,103,42,NULL),(184,103,43,NULL),(185,103,64,NULL),(186,103,35,NULL),(187,103,101,NULL),(188,103,75,NULL),(189,103,71,NULL),(190,103,72,NULL),(191,103,47,NULL),(192,103,69,NULL),(193,103,48,NULL),(194,103,2,NULL),(195,103,56,NULL),(196,103,57,NULL),(197,103,32,NULL),(198,103,73,NULL),(199,103,30,NULL),(200,103,31,NULL),(201,103,6,NULL),(202,103,40,NULL),(203,103,41,NULL),(204,103,37,NULL),(205,103,38,NULL),(206,103,53,NULL),(207,103,33,NULL),(210,103,54,NULL),(211,103,55,NULL),(212,103,15,NULL),(213,103,16,NULL),(215,103,51,NULL),(216,103,52,NULL),(218,103,65,NULL),(219,103,58,NULL),(220,103,59,NULL),(221,103,102,NULL),(222,103,49,NULL),(223,103,60,NULL),(224,103,50,NULL),(225,103,36,NULL),(226,103,61,NULL),(228,103,21,NULL),(229,103,19,NULL),(230,103,18,NULL),(231,103,13,NULL),(232,103,22,NULL),(233,103,70,NULL),(234,103,74,NULL),(237,66,103,NULL),(238,103,20,NULL),(239,106,11,NULL),(240,107,60,NULL),(241,21,72,NULL),(242,20,9,NULL),(245,57,33,NULL),(246,102,35,NULL),(247,108,1,NULL),(248,102,13,NULL),(249,109,18,NULL),(250,109,13,NULL),(251,51,21,NULL),(253,48,49,NULL),(254,110,1,NULL),(255,110,76,NULL),(256,48,69,NULL),(257,47,111,NULL),(258,43,111,NULL),(259,72,111,NULL),(260,35,111,NULL),(261,5,111,NULL),(262,112,1,NULL),(263,114,112,NULL),(264,51,35,NULL),(265,72,49,NULL),(266,101,18,NULL),(268,65,57,NULL),(269,65,59,NULL),(270,65,49,NULL),(271,65,18,NULL),(272,65,13,NULL),(273,60,35,NULL),(275,50,59,NULL),(276,60,49,NULL),(280,5,53,NULL),(281,5,18,NULL),(282,50,60,NULL),(283,5,21,NULL),(284,60,57,NULL),(285,58,76,NULL),(287,69,58,NULL),(288,115,66,NULL),(290,104,115,NULL),(291,115,103,NULL),(297,21,33,NULL),(298,49,54,NULL),(299,112,49,NULL),(300,114,13,NULL),(302,5,35,NULL),(303,69,49,NULL),(306,119,110,NULL),(307,1,76,NULL),(309,120,9,NULL),(310,120,66,NULL),(311,120,13,25508),(312,115,120,NULL),(314,43,18,NULL),(315,121,35,NULL),(316,121,21,NULL),(317,122,15,NULL),(318,16,122,NULL),(319,37,49,NULL),(320,37,18,NULL); +INSERT INTO `roleInherit` VALUES (1,1,2,NULL),(2,1,3,NULL),(3,1,70,NULL),(4,2,11,NULL),(5,3,11,NULL),(6,5,1,NULL),(8,5,33,NULL),(10,11,6,NULL),(11,13,1,NULL),(12,15,35,NULL),(16,17,20,NULL),(17,17,37,NULL),(18,17,39,NULL),(19,17,64,NULL),(20,18,1,NULL),(21,19,21,NULL),(22,20,13,NULL),(23,20,16,NULL),(24,20,65,NULL),(25,21,13,NULL),(26,21,18,NULL),(27,21,53,NULL),(28,22,13,NULL),(29,22,21,NULL),(30,30,5,NULL),(31,30,20,NULL),(32,30,22,NULL),(33,30,53,NULL),(34,30,64,NULL),(35,31,1,NULL),(36,32,1,NULL),(37,34,1,NULL),(38,34,13,NULL),(39,34,33,NULL),(40,35,1,NULL),(41,36,44,NULL),(42,36,47,NULL),(43,37,1,NULL),(44,38,37,NULL),(45,38,64,NULL),(46,39,5,NULL),(47,39,21,NULL),(48,39,57,NULL),(49,40,1,NULL),(50,40,49,NULL),(51,41,13,NULL),(52,41,35,NULL),(53,41,40,NULL),(54,42,35,NULL),(55,42,49,NULL),(56,43,13,NULL),(57,43,42,NULL),(58,44,1,NULL),(59,45,13,NULL),(60,45,44,NULL),(61,47,1,NULL),(62,48,13,NULL),(63,48,47,NULL),(64,49,36,NULL),(65,49,58,NULL),(66,50,13,NULL),(67,50,21,NULL),(70,50,57,NULL),(72,51,1,NULL),(73,52,13,NULL),(74,52,19,NULL),(76,52,51,NULL),(77,53,1,NULL),(78,54,1,NULL),(79,55,13,NULL),(80,55,54,NULL),(81,56,1,NULL),(84,58,1,NULL),(85,59,13,NULL),(87,60,5,NULL),(91,61,13,NULL),(92,61,36,NULL),(94,65,35,NULL),(97,67,5,NULL),(98,67,37,NULL),(99,69,35,NULL),(101,70,11,NULL),(102,71,1,NULL),(103,71,58,NULL),(105,72,18,NULL),(106,73,5,NULL),(107,73,64,NULL),(108,73,19,NULL),(109,59,50,NULL),(115,39,76,NULL),(117,65,76,NULL),(118,30,76,NULL),(124,5,76,NULL),(125,37,76,NULL),(126,38,76,NULL),(128,42,76,NULL),(129,35,76,NULL),(130,60,76,NULL),(131,21,76,NULL),(132,18,76,NULL),(133,50,76,NULL),(134,20,76,NULL),(135,41,76,NULL),(136,17,76,NULL),(137,52,76,NULL),(139,37,74,NULL),(140,51,74,NULL),(141,51,75,NULL),(142,35,75,NULL),(143,15,49,NULL),(145,17,67,NULL),(146,38,13,NULL),(147,101,35,NULL),(148,101,13,NULL),(150,15,56,NULL),(152,69,47,NULL),(153,48,35,NULL),(154,102,1,NULL),(167,9,103,NULL),(168,66,9,NULL),(169,104,100,NULL),(172,103,76,NULL),(173,103,1,NULL),(174,103,44,NULL),(175,103,45,NULL),(176,103,11,NULL),(177,103,39,NULL),(178,103,17,NULL),(179,103,5,NULL),(180,103,67,NULL),(181,103,3,NULL),(182,103,34,NULL),(183,103,42,NULL),(184,103,43,NULL),(185,103,64,NULL),(186,103,35,NULL),(187,103,101,NULL),(188,103,75,NULL),(189,103,71,NULL),(190,103,72,NULL),(191,103,47,NULL),(192,103,69,NULL),(193,103,48,NULL),(194,103,2,NULL),(195,103,56,NULL),(196,103,57,NULL),(197,103,32,NULL),(198,103,73,NULL),(199,103,30,NULL),(200,103,31,NULL),(201,103,6,NULL),(202,103,40,NULL),(203,103,41,NULL),(204,103,37,NULL),(205,103,38,NULL),(206,103,53,NULL),(207,103,33,NULL),(210,103,54,NULL),(211,103,55,NULL),(212,103,15,NULL),(213,103,16,NULL),(215,103,51,NULL),(216,103,52,NULL),(218,103,65,NULL),(219,103,58,NULL),(220,103,59,NULL),(221,103,102,NULL),(222,103,49,NULL),(223,103,60,NULL),(224,103,50,NULL),(225,103,36,NULL),(226,103,61,NULL),(228,103,21,NULL),(229,103,19,NULL),(230,103,18,NULL),(231,103,13,NULL),(232,103,22,NULL),(233,103,70,NULL),(234,103,74,NULL),(237,66,103,NULL),(238,103,20,NULL),(239,106,11,NULL),(240,107,60,NULL),(241,21,72,NULL),(242,20,9,NULL),(246,102,35,NULL),(247,108,1,NULL),(248,102,13,NULL),(249,109,18,NULL),(250,109,13,NULL),(251,51,21,NULL),(253,48,49,NULL),(254,110,1,NULL),(255,110,76,NULL),(256,48,69,NULL),(257,47,111,NULL),(258,43,111,NULL),(259,72,111,NULL),(260,35,111,NULL),(261,5,111,NULL),(262,112,1,NULL),(263,114,112,NULL),(264,51,35,NULL),(265,72,49,NULL),(266,101,18,NULL),(268,65,57,NULL),(269,65,59,NULL),(270,65,49,NULL),(271,65,18,NULL),(272,65,13,NULL),(273,60,35,NULL),(275,50,59,NULL),(276,60,49,NULL),(280,5,53,NULL),(281,5,18,NULL),(282,50,60,NULL),(283,5,21,NULL),(285,58,76,NULL),(287,69,58,NULL),(288,115,66,NULL),(290,104,115,NULL),(291,115,103,NULL),(297,21,33,NULL),(298,49,54,NULL),(299,112,49,NULL),(300,114,13,NULL),(302,5,35,NULL),(303,69,49,NULL),(306,119,110,NULL),(307,1,76,NULL),(309,120,9,NULL),(310,120,66,NULL),(311,120,13,25508),(312,115,120,NULL),(314,43,18,NULL),(315,121,35,NULL),(316,121,21,NULL),(317,122,15,NULL),(318,16,122,NULL),(319,37,49,NULL),(320,37,18,NULL),(328,57,123,10578),(329,123,33,NULL),(330,123,56,NULL),(332,103,112,NULL),(333,57,13,NULL),(334,60,123,NULL),(335,124,37,NULL),(336,124,35,NULL),(337,103,124,NULL),(338,35,125,10578),(339,57,125,10578),(340,41,125,10578),(341,18,125,10578),(346,126,15,NULL),(347,102,49,NULL); /*!40000 ALTER TABLE `roleInherit` ENABLE KEYS */; UNLOCK TABLES; @@ -98,7 +98,7 @@ UNLOCK TABLES; LOCK TABLES `roleRole` WRITE; /*!40000 ALTER TABLE `roleRole` DISABLE KEYS */; -INSERT INTO `roleRole` VALUES (285864,1,1),(285865,1,2),(285866,1,3),(285870,1,6),(285869,1,11),(285867,1,70),(285868,1,76),(285871,2,2),(285873,2,6),(285872,2,11),(285874,3,3),(285876,3,6),(285875,3,11),(285878,5,1),(285891,5,2),(285890,5,3),(285877,5,5),(285897,5,6),(285893,5,11),(285888,5,13),(285879,5,18),(285880,5,21),(285881,5,33),(285882,5,35),(285896,5,36),(285899,5,44),(285898,5,47),(285892,5,49),(285883,5,53),(285895,5,54),(285894,5,58),(285889,5,70),(285887,5,72),(285886,5,75),(285884,5,76),(285885,5,111),(285900,6,6),(285903,9,1),(285904,9,2),(285905,9,3),(285906,9,5),(285907,9,6),(285901,9,9),(285908,9,11),(285909,9,13),(285910,9,15),(285911,9,16),(285912,9,17),(285913,9,18),(285914,9,19),(285915,9,20),(285916,9,21),(285917,9,22),(285918,9,30),(285919,9,31),(285920,9,32),(285921,9,33),(285922,9,34),(285923,9,35),(285924,9,36),(285925,9,37),(285926,9,38),(285927,9,39),(285928,9,40),(285929,9,41),(285930,9,42),(285931,9,43),(285932,9,44),(285933,9,45),(285934,9,47),(285935,9,48),(285936,9,49),(285937,9,50),(285938,9,51),(285939,9,52),(285940,9,53),(285941,9,54),(285942,9,55),(285943,9,56),(285944,9,57),(285945,9,58),(285946,9,59),(285947,9,60),(285948,9,61),(285949,9,64),(285950,9,65),(285951,9,67),(285952,9,69),(285953,9,70),(285954,9,71),(285955,9,72),(285956,9,73),(285957,9,74),(285958,9,75),(285959,9,76),(285960,9,101),(285961,9,102),(285902,9,103),(285963,9,111),(285962,9,122),(285965,11,6),(285964,11,11),(285967,13,1),(285968,13,2),(285969,13,3),(285973,13,6),(285972,13,11),(285966,13,13),(285970,13,70),(285971,13,76),(285980,15,1),(285989,15,2),(285988,15,3),(285991,15,6),(285990,15,11),(285974,15,15),(285975,15,35),(285982,15,36),(285986,15,44),(285985,15,47),(285976,15,49),(285983,15,54),(285977,15,56),(285984,15,58),(285987,15,70),(285979,15,75),(285978,15,76),(285981,15,111),(286000,16,1),(286009,16,2),(286008,16,3),(286011,16,6),(286010,16,11),(285994,16,15),(285992,16,16),(285995,16,35),(286002,16,36),(286006,16,44),(286005,16,47),(285996,16,49),(286003,16,54),(285997,16,56),(286004,16,58),(286007,16,70),(285999,16,75),(285998,16,76),(286001,16,111),(285993,16,122),(286020,17,1),(286036,17,2),(286035,17,3),(286027,17,5),(286059,17,6),(286024,17,9),(286058,17,11),(286023,17,13),(286057,17,15),(286022,17,16),(286012,17,17),(286019,17,18),(286056,17,19),(286013,17,20),(286028,17,21),(286055,17,22),(286054,17,30),(286053,17,31),(286052,17,32),(286030,17,33),(286051,17,34),(286038,17,35),(286033,17,36),(286014,17,37),(286050,17,38),(286015,17,39),(286049,17,40),(286048,17,41),(286047,17,42),(286046,17,43),(286045,17,44),(286060,17,45),(286061,17,47),(286062,17,48),(286025,17,49),(286063,17,50),(286064,17,51),(286065,17,52),(286041,17,53),(286032,17,54),(286066,17,55),(286044,17,56),(286029,17,57),(286031,17,58),(286037,17,59),(286067,17,60),(286068,17,61),(286016,17,64),(286021,17,65),(286017,17,67),(286069,17,69),(286034,17,70),(286070,17,71),(286043,17,72),(286071,17,73),(286026,17,74),(286072,17,75),(286018,17,76),(286073,17,101),(286074,17,102),(286040,17,103),(286042,17,111),(286039,17,122),(286076,18,1),(286079,18,2),(286078,18,3),(286082,18,6),(286081,18,11),(286075,18,18),(286080,18,70),(286077,18,76),(286093,19,1),(286099,19,2),(286098,19,3),(286103,19,6),(286102,19,11),(286085,19,13),(286086,19,18),(286083,19,19),(286084,19,21),(286087,19,33),(286096,19,36),(286101,19,44),(286100,19,47),(286092,19,49),(286088,19,53),(286095,19,54),(286094,19,58),(286097,19,70),(286089,19,72),(286090,19,76),(286091,19,111),(286113,20,1),(286125,20,2),(286124,20,3),(286123,20,5),(286122,20,6),(286105,20,9),(286121,20,11),(286106,20,13),(286120,20,15),(286107,20,16),(286119,20,17),(286111,20,18),(286118,20,19),(286104,20,20),(286126,20,21),(286127,20,22),(286128,20,30),(286129,20,31),(286130,20,32),(286131,20,33),(286132,20,34),(286110,20,35),(286133,20,36),(286134,20,37),(286135,20,38),(286136,20,39),(286137,20,40),(286138,20,41),(286139,20,42),(286140,20,43),(286141,20,44),(286142,20,45),(286143,20,47),(286144,20,48),(286115,20,49),(286145,20,50),(286146,20,51),(286147,20,52),(286148,20,53),(286149,20,54),(286150,20,55),(286151,20,56),(286116,20,57),(286152,20,58),(286117,20,59),(286153,20,60),(286154,20,61),(286155,20,64),(286108,20,65),(286156,20,67),(286157,20,69),(286158,20,70),(286159,20,71),(286160,20,72),(286161,20,73),(286162,20,74),(286163,20,75),(286109,20,76),(286164,20,101),(286165,20,102),(286114,20,103),(286166,20,111),(286112,20,122),(286176,21,1),(286182,21,2),(286181,21,3),(286186,21,6),(286185,21,11),(286168,21,13),(286169,21,18),(286167,21,21),(286170,21,33),(286179,21,36),(286184,21,44),(286183,21,47),(286175,21,49),(286171,21,53),(286178,21,54),(286177,21,58),(286180,21,70),(286172,21,72),(286173,21,76),(286174,21,111),(286191,22,1),(286200,22,2),(286199,22,3),(286207,22,6),(286204,22,11),(286188,22,13),(286190,22,18),(286189,22,21),(286187,22,22),(286192,22,33),(286203,22,36),(286206,22,44),(286205,22,47),(286197,22,49),(286193,22,53),(286202,22,54),(286201,22,58),(286198,22,70),(286194,22,72),(286195,22,76),(286196,22,111),(286220,30,1),(286234,30,2),(286233,30,3),(286209,30,5),(286243,30,6),(286221,30,9),(286244,30,11),(286222,30,13),(286242,30,15),(286223,30,16),(286241,30,17),(286219,30,18),(286240,30,19),(286210,30,20),(286218,30,21),(286211,30,22),(286208,30,30),(286239,30,31),(286238,30,32),(286217,30,33),(286237,30,34),(286216,30,35),(286236,30,36),(286235,30,37),(286245,30,38),(286246,30,39),(286247,30,40),(286248,30,41),(286249,30,42),(286250,30,43),(286251,30,44),(286252,30,45),(286253,30,47),(286254,30,48),(286227,30,49),(286255,30,50),(286256,30,51),(286257,30,52),(286212,30,53),(286258,30,54),(286259,30,55),(286260,30,56),(286226,30,57),(286261,30,58),(286225,30,59),(286262,30,60),(286263,30,61),(286213,30,64),(286224,30,65),(286264,30,67),(286265,30,69),(286232,30,70),(286266,30,71),(286231,30,72),(286267,30,73),(286268,30,74),(286230,30,75),(286214,30,76),(286269,30,101),(286270,30,102),(286229,30,103),(286215,30,111),(286228,30,122),(286272,31,1),(286273,31,2),(286274,31,3),(286278,31,6),(286277,31,11),(286271,31,31),(286275,31,70),(286276,31,76),(286280,32,1),(286281,32,2),(286282,32,3),(286286,32,6),(286285,32,11),(286279,32,32),(286283,32,70),(286284,32,76),(286287,33,33),(286289,34,1),(286294,34,2),(286293,34,3),(286297,34,6),(286296,34,11),(286290,34,13),(286291,34,33),(286288,34,34),(286292,34,70),(286295,34,76),(286299,35,1),(286305,35,2),(286304,35,3),(286307,35,6),(286306,35,11),(286298,35,35),(286303,35,70),(286300,35,75),(286301,35,76),(286302,35,111),(286312,36,1),(286314,36,2),(286313,36,3),(286318,36,6),(286317,36,11),(286308,36,36),(286309,36,44),(286310,36,47),(286315,36,70),(286316,36,76),(286311,36,111),(286320,37,1),(286329,37,2),(286328,37,3),(286335,37,6),(286333,37,11),(286321,37,18),(286326,37,36),(286319,37,37),(286332,37,44),(286331,37,47),(286322,37,49),(286325,37,54),(286330,37,58),(286327,37,70),(286323,37,74),(286324,37,76),(286334,37,111),(286344,38,1),(286348,38,2),(286347,38,3),(286355,38,6),(286353,38,11),(286337,38,13),(286343,38,18),(286345,38,36),(286338,38,37),(286336,38,38),(286352,38,44),(286351,38,47),(286342,38,49),(286349,38,54),(286350,38,58),(286339,38,64),(286346,38,70),(286341,38,74),(286340,38,76),(286354,38,111),(286364,39,1),(286374,39,2),(286373,39,3),(286357,39,5),(286381,39,6),(286378,39,11),(286367,39,13),(286363,39,18),(286358,39,21),(286362,39,33),(286361,39,35),(286377,39,36),(286356,39,39),(286380,39,44),(286379,39,47),(286370,39,49),(286365,39,53),(286376,39,54),(286369,39,56),(286359,39,57),(286375,39,58),(286372,39,70),(286368,39,72),(286371,39,75),(286360,39,76),(286366,39,111),(286383,40,1),(286386,40,2),(286385,40,3),(286396,40,6),(286394,40,11),(286389,40,36),(286382,40,40),(286393,40,44),(286392,40,47),(286384,40,49),(286390,40,54),(286391,40,58),(286387,40,70),(286388,40,76),(286395,40,111),(286405,41,1),(286409,41,2),(286408,41,3),(286415,41,6),(286414,41,11),(286398,41,13),(286399,41,35),(286406,41,36),(286400,41,40),(286397,41,41),(286413,41,44),(286412,41,47),(286402,41,49),(286410,41,54),(286411,41,58),(286407,41,70),(286404,41,75),(286401,41,76),(286403,41,111),(286422,42,1),(286430,42,2),(286429,42,3),(286432,42,6),(286431,42,11),(286417,42,35),(286423,42,36),(286416,42,42),(286427,42,44),(286426,42,47),(286418,42,49),(286424,42,54),(286425,42,58),(286428,42,70),(286421,42,75),(286419,42,76),(286420,42,111),(286441,43,1),(286445,43,2),(286444,43,3),(286452,43,6),(286451,43,11),(286434,43,13),(286435,43,18),(286439,43,35),(286446,43,36),(286436,43,42),(286433,43,43),(286450,43,44),(286449,43,47),(286438,43,49),(286447,43,54),(286448,43,58),(286443,43,70),(286442,43,75),(286440,43,76),(286437,43,111),(286454,44,1),(286455,44,2),(286456,44,3),(286460,44,6),(286459,44,11),(286453,44,44),(286457,44,70),(286458,44,76),(286464,45,1),(286466,45,2),(286465,45,3),(286470,45,6),(286469,45,11),(286462,45,13),(286463,45,44),(286461,45,45),(286467,45,70),(286468,45,76),(286472,47,1),(286475,47,2),(286474,47,3),(286479,47,6),(286478,47,11),(286471,47,47),(286476,47,70),(286477,47,76),(286473,47,111),(286490,48,1),(286496,48,2),(286495,48,3),(286498,48,6),(286497,48,11),(286481,48,13),(286482,48,35),(286486,48,36),(286493,48,44),(286483,48,47),(286480,48,48),(286484,48,49),(286491,48,54),(286492,48,58),(286485,48,69),(286494,48,70),(286489,48,75),(286488,48,76),(286487,48,111),(286503,49,1),(286509,49,2),(286508,49,3),(286512,49,6),(286511,49,11),(286500,49,36),(286505,49,44),(286504,49,47),(286499,49,49),(286501,49,54),(286502,49,58),(286507,49,70),(286506,49,76),(286510,49,111),(286529,50,1),(286538,50,2),(286537,50,3),(286533,50,5),(286540,50,6),(286539,50,11),(286514,50,13),(286528,50,18),(286515,50,21),(286527,50,33),(286516,50,35),(286522,50,36),(286535,50,44),(286534,50,47),(286517,50,49),(286513,50,50),(286526,50,53),(286530,50,54),(286532,50,56),(286518,50,57),(286531,50,58),(286519,50,59),(286520,50,60),(286536,50,70),(286525,50,72),(286524,50,75),(286521,50,76),(286523,50,111),(286542,51,1),(286551,51,2),(286550,51,3),(286562,51,6),(286558,51,11),(286547,51,13),(286552,51,18),(286543,51,21),(286553,51,33),(286544,51,35),(286561,51,36),(286564,51,44),(286563,51,47),(286557,51,49),(286541,51,51),(286554,51,53),(286560,51,54),(286559,51,58),(286549,51,70),(286555,51,72),(286545,51,74),(286546,51,75),(286548,51,76),(286556,51,111),(286573,52,1),(286579,52,2),(286578,52,3),(286588,52,6),(286584,52,11),(286566,52,13),(286576,52,18),(286567,52,19),(286572,52,21),(286575,52,33),(286571,52,35),(286587,52,36),(286590,52,44),(286589,52,47),(286583,52,49),(286568,52,51),(286565,52,52),(286580,52,53),(286586,52,54),(286585,52,58),(286577,52,70),(286581,52,72),(286570,52,74),(286574,52,75),(286569,52,76),(286582,52,111),(286592,53,1),(286593,53,2),(286594,53,3),(286598,53,6),(286597,53,11),(286591,53,53),(286595,53,70),(286596,53,76),(286600,54,1),(286601,54,2),(286602,54,3),(286606,54,6),(286605,54,11),(286599,54,54),(286603,54,70),(286604,54,76),(286610,55,1),(286612,55,2),(286611,55,3),(286616,55,6),(286615,55,11),(286608,55,13),(286609,55,54),(286607,55,55),(286613,55,70),(286614,55,76),(286618,56,1),(286619,56,2),(286620,56,3),(286624,56,6),(286623,56,11),(286617,56,56),(286621,56,70),(286622,56,76),(286630,57,1),(286633,57,2),(286632,57,3),(286635,57,6),(286634,57,11),(286626,57,13),(286627,57,33),(286628,57,56),(286625,57,57),(286631,57,70),(286629,57,76),(286637,58,1),(286640,58,2),(286639,58,3),(286643,58,6),(286642,58,11),(286636,58,58),(286641,58,70),(286638,58,76),(286648,59,1),(286660,59,2),(286659,59,3),(286667,59,5),(286671,59,6),(286670,59,11),(286645,59,13),(286657,59,18),(286647,59,21),(286656,59,33),(286649,59,35),(286663,59,36),(286669,59,44),(286668,59,47),(286650,59,49),(286646,59,50),(286655,59,53),(286664,59,54),(286666,59,56),(286651,59,57),(286665,59,58),(286644,59,59),(286652,59,60),(286658,59,70),(286654,59,72),(286661,59,75),(286653,59,76),(286662,59,111),(286682,60,1),(286695,60,2),(286694,60,3),(286673,60,5),(286697,60,6),(286696,60,11),(286688,60,13),(286681,60,18),(286680,60,21),(286679,60,33),(286674,60,35),(286685,60,36),(286691,60,44),(286690,60,47),(286675,60,49),(286678,60,53),(286686,60,54),(286689,60,56),(286676,60,57),(286687,60,58),(286672,60,60),(286693,60,70),(286692,60,72),(286684,60,75),(286677,60,76),(286683,60,111),(286702,61,1),(286706,61,2),(286705,61,3),(286710,61,6),(286709,61,11),(286699,61,13),(286700,61,36),(286701,61,44),(286703,61,47),(286698,61,61),(286704,61,70),(286707,61,76),(286708,61,111),(286711,62,62),(286712,64,64),(286727,65,1),(286736,65,2),(286735,65,3),(286737,65,5),(286741,65,6),(286740,65,11),(286714,65,13),(286715,65,18),(286731,65,21),(286721,65,33),(286716,65,35),(286724,65,36),(286733,65,44),(286732,65,47),(286717,65,49),(286729,65,50),(286739,65,53),(286723,65,54),(286728,65,56),(286718,65,57),(286722,65,58),(286719,65,59),(286730,65,60),(286713,65,65),(286734,65,70),(286738,65,72),(286726,65,75),(286720,65,76),(286725,65,111),(286746,66,1),(286745,66,2),(286747,66,3),(286748,66,5),(286749,66,6),(286743,66,9),(286750,66,11),(286751,66,13),(286752,66,15),(286753,66,16),(286754,66,17),(286755,66,18),(286756,66,19),(286757,66,20),(286758,66,21),(286759,66,22),(286760,66,30),(286761,66,31),(286762,66,32),(286763,66,33),(286764,66,34),(286765,66,35),(286766,66,36),(286767,66,37),(286768,66,38),(286769,66,39),(286770,66,40),(286771,66,41),(286772,66,42),(286773,66,43),(286774,66,44),(286775,66,45),(286776,66,47),(286777,66,48),(286778,66,49),(286779,66,50),(286780,66,51),(286781,66,52),(286782,66,53),(286783,66,54),(286784,66,55),(286785,66,56),(286786,66,57),(286787,66,58),(286788,66,59),(286789,66,60),(286790,66,61),(286791,66,64),(286792,66,65),(286742,66,66),(286793,66,67),(286794,66,69),(286795,66,70),(286796,66,71),(286797,66,72),(286798,66,73),(286799,66,74),(286800,66,75),(286801,66,76),(286802,66,101),(286803,66,102),(286744,66,103),(286805,66,111),(286804,66,122),(286810,67,1),(286827,67,2),(286826,67,3),(286807,67,5),(286831,67,6),(286830,67,11),(286824,67,13),(286809,67,18),(286811,67,21),(286812,67,33),(286813,67,35),(286821,67,36),(286808,67,37),(286829,67,44),(286828,67,47),(286817,67,49),(286814,67,53),(286820,67,54),(286819,67,58),(286806,67,67),(286825,67,70),(286823,67,72),(286818,67,74),(286822,67,75),(286815,67,76),(286816,67,111),(286840,69,1),(286846,69,2),(286845,69,3),(286848,69,6),(286847,69,11),(286833,69,35),(286841,69,36),(286843,69,44),(286834,69,47),(286835,69,49),(286842,69,54),(286836,69,58),(286832,69,69),(286844,69,70),(286839,69,75),(286838,69,76),(286837,69,111),(286851,70,6),(286850,70,11),(286849,70,70),(286853,71,1),(286856,71,2),(286855,71,3),(286860,71,6),(286859,71,11),(286854,71,58),(286857,71,70),(286852,71,71),(286858,71,76),(286867,72,1),(286874,72,2),(286873,72,3),(286876,72,6),(286875,72,11),(286862,72,18),(286865,72,36),(286871,72,44),(286870,72,47),(286863,72,49),(286868,72,54),(286869,72,58),(286872,72,70),(286861,72,72),(286866,72,76),(286864,72,111),(286883,73,1),(286894,73,2),(286893,73,3),(286878,73,5),(286900,73,6),(286896,73,11),(286891,73,13),(286882,73,18),(286879,73,19),(286881,73,21),(286884,73,33),(286885,73,35),(286899,73,36),(286902,73,44),(286901,73,47),(286895,73,49),(286886,73,53),(286898,73,54),(286897,73,58),(286880,73,64),(286892,73,70),(286890,73,72),(286877,73,73),(286889,73,75),(286887,73,76),(286888,73,111),(286903,74,74),(286904,75,75),(286905,76,76),(286907,100,1),(286908,100,2),(286909,100,3),(286910,100,5),(286911,100,6),(286912,100,9),(286913,100,11),(286914,100,13),(286915,100,15),(286916,100,16),(286917,100,17),(286918,100,18),(286919,100,19),(286920,100,20),(286921,100,21),(286922,100,22),(286923,100,30),(286924,100,31),(286925,100,32),(286926,100,33),(286927,100,34),(286928,100,35),(286929,100,36),(286930,100,37),(286931,100,38),(286932,100,39),(286933,100,40),(286934,100,41),(286935,100,42),(286936,100,43),(286937,100,44),(286938,100,45),(286939,100,47),(286940,100,48),(286941,100,49),(286942,100,50),(286943,100,51),(286944,100,52),(286945,100,53),(286946,100,54),(286947,100,55),(286948,100,56),(286949,100,57),(286950,100,58),(286951,100,59),(286952,100,60),(286953,100,61),(286954,100,62),(286955,100,64),(286956,100,65),(286957,100,66),(286958,100,67),(286959,100,69),(286960,100,70),(286961,100,71),(286962,100,72),(286963,100,73),(286964,100,74),(286965,100,75),(286966,100,76),(286906,100,100),(286967,100,101),(286968,100,102),(286969,100,103),(286970,100,104),(286971,100,105),(286972,100,106),(286973,100,107),(286974,100,108),(286975,100,109),(286976,100,110),(286977,100,111),(286978,100,112),(286979,100,114),(286980,100,115),(286981,100,119),(286984,100,120),(286982,100,121),(286983,100,122),(286991,101,1),(286995,101,2),(286994,101,3),(286997,101,6),(286996,101,11),(286986,101,13),(286987,101,18),(286988,101,35),(286993,101,70),(286989,101,75),(286990,101,76),(286985,101,101),(286992,101,111),(286999,102,1),(287004,102,2),(287003,102,3),(287009,102,6),(287008,102,11),(287000,102,13),(287001,102,35),(287002,102,70),(287006,102,75),(287005,102,76),(286998,102,102),(287007,102,111),(287011,103,1),(287012,103,2),(287013,103,3),(287014,103,5),(287015,103,6),(287070,103,9),(287016,103,11),(287017,103,13),(287018,103,15),(287019,103,16),(287020,103,17),(287021,103,18),(287022,103,19),(287023,103,20),(287024,103,21),(287025,103,22),(287026,103,30),(287027,103,31),(287028,103,32),(287029,103,33),(287030,103,34),(287031,103,35),(287032,103,36),(287033,103,37),(287034,103,38),(287035,103,39),(287036,103,40),(287037,103,41),(287038,103,42),(287039,103,43),(287040,103,44),(287041,103,45),(287042,103,47),(287043,103,48),(287044,103,49),(287045,103,50),(287046,103,51),(287047,103,52),(287048,103,53),(287049,103,54),(287050,103,55),(287051,103,56),(287052,103,57),(287053,103,58),(287054,103,59),(287055,103,60),(287056,103,61),(287057,103,64),(287058,103,65),(287059,103,67),(287060,103,69),(287061,103,70),(287062,103,71),(287063,103,72),(287064,103,73),(287065,103,74),(287066,103,75),(287067,103,76),(287068,103,101),(287069,103,102),(287010,103,103),(287072,103,111),(287071,103,122),(287080,104,1),(287079,104,2),(287082,104,3),(287083,104,5),(287084,104,6),(287081,104,9),(287085,104,11),(287086,104,13),(287087,104,15),(287088,104,16),(287089,104,17),(287090,104,18),(287091,104,19),(287092,104,20),(287093,104,21),(287094,104,22),(287095,104,30),(287096,104,31),(287097,104,32),(287098,104,33),(287099,104,34),(287100,104,35),(287101,104,36),(287102,104,37),(287103,104,38),(287104,104,39),(287105,104,40),(287106,104,41),(287107,104,42),(287108,104,43),(287109,104,44),(287110,104,45),(287111,104,47),(287112,104,48),(287113,104,49),(287114,104,50),(287115,104,51),(287116,104,52),(287117,104,53),(287118,104,54),(287119,104,55),(287120,104,56),(287121,104,57),(287122,104,58),(287123,104,59),(287124,104,60),(287125,104,61),(287146,104,62),(287126,104,64),(287127,104,65),(287077,104,66),(287128,104,67),(287129,104,69),(287130,104,70),(287131,104,71),(287132,104,72),(287133,104,73),(287134,104,74),(287135,104,75),(287136,104,76),(287074,104,100),(287137,104,101),(287138,104,102),(287076,104,103),(287073,104,104),(287143,104,105),(287142,104,106),(287149,104,107),(287151,104,108),(287150,104,109),(287147,104,110),(287140,104,111),(287144,104,112),(287145,104,114),(287075,104,115),(287148,104,119),(287078,104,120),(287141,104,121),(287139,104,122),(287152,105,105),(287155,106,6),(287154,106,11),(287153,106,106),(287167,107,1),(287180,107,2),(287179,107,3),(287158,107,5),(287182,107,6),(287181,107,11),(287173,107,13),(287166,107,18),(287165,107,21),(287164,107,33),(287159,107,35),(287170,107,36),(287176,107,44),(287175,107,47),(287160,107,49),(287163,107,53),(287171,107,54),(287174,107,56),(287161,107,57),(287172,107,58),(287157,107,60),(287178,107,70),(287177,107,72),(287169,107,75),(287162,107,76),(287156,107,107),(287168,107,111),(287184,108,1),(287185,108,2),(287186,108,3),(287190,108,6),(287189,108,11),(287187,108,70),(287188,108,76),(287183,108,108),(287195,109,1),(287197,109,2),(287196,109,3),(287200,109,6),(287199,109,11),(287192,109,13),(287193,109,18),(287198,109,70),(287194,109,76),(287191,109,109),(287202,110,1),(287205,110,2),(287204,110,3),(287208,110,6),(287207,110,11),(287206,110,70),(287203,110,76),(287201,110,110),(287209,111,111),(287211,112,1),(287214,112,2),(287213,112,3),(287224,112,6),(287222,112,11),(287217,112,36),(287221,112,44),(287220,112,47),(287212,112,49),(287218,112,54),(287219,112,58),(287215,112,70),(287216,112,76),(287223,112,111),(287210,112,112),(287229,114,1),(287231,114,2),(287230,114,3),(287241,114,6),(287239,114,11),(287226,114,13),(287234,114,36),(287238,114,44),(287237,114,47),(287228,114,49),(287235,114,54),(287236,114,58),(287232,114,70),(287233,114,76),(287240,114,111),(287227,114,112),(287225,114,114),(287247,115,1),(287246,115,2),(287249,115,3),(287250,115,5),(287251,115,6),(287248,115,9),(287252,115,11),(287253,115,13),(287254,115,15),(287255,115,16),(287256,115,17),(287257,115,18),(287258,115,19),(287259,115,20),(287260,115,21),(287261,115,22),(287262,115,30),(287263,115,31),(287264,115,32),(287265,115,33),(287266,115,34),(287267,115,35),(287268,115,36),(287269,115,37),(287270,115,38),(287271,115,39),(287272,115,40),(287273,115,41),(287274,115,42),(287275,115,43),(287276,115,44),(287277,115,45),(287278,115,47),(287279,115,48),(287280,115,49),(287281,115,50),(287282,115,51),(287283,115,52),(287284,115,53),(287285,115,54),(287286,115,55),(287287,115,56),(287288,115,57),(287289,115,58),(287290,115,59),(287291,115,60),(287292,115,61),(287293,115,64),(287294,115,65),(287243,115,66),(287295,115,67),(287296,115,69),(287297,115,70),(287298,115,71),(287299,115,72),(287300,115,73),(287301,115,74),(287302,115,75),(287303,115,76),(287304,115,101),(287305,115,102),(287244,115,103),(287307,115,111),(287242,115,115),(287245,115,120),(287306,115,122),(287310,119,1),(287313,119,2),(287312,119,3),(287316,119,6),(287315,119,11),(287314,119,70),(287311,119,76),(287309,119,110),(287308,119,119),(287363,120,1),(287367,120,2),(287366,120,3),(287365,120,5),(287368,120,6),(287360,120,9),(287369,120,11),(287361,120,13),(287370,120,15),(287371,120,16),(287372,120,17),(287373,120,18),(287374,120,19),(287375,120,20),(287376,120,21),(287377,120,22),(287378,120,30),(287379,120,31),(287380,120,32),(287381,120,33),(287382,120,34),(287383,120,35),(287384,120,36),(287385,120,37),(287386,120,38),(287387,120,39),(287388,120,40),(287389,120,41),(287390,120,42),(287391,120,43),(287392,120,44),(287393,120,45),(287394,120,47),(287395,120,48),(287396,120,49),(287397,120,50),(287398,120,51),(287399,120,52),(287400,120,53),(287401,120,54),(287402,120,55),(287403,120,56),(287404,120,57),(287405,120,58),(287406,120,59),(287407,120,60),(287408,120,61),(287409,120,64),(287410,120,65),(287362,120,66),(287411,120,67),(287412,120,69),(287413,120,70),(287414,120,71),(287415,120,72),(287416,120,73),(287417,120,74),(287418,120,75),(287419,120,76),(287420,120,101),(287421,120,102),(287364,120,103),(287423,120,111),(287359,120,120),(287422,120,122),(287326,121,1),(287331,121,2),(287330,121,3),(287337,121,6),(287333,121,11),(287321,121,13),(287320,121,18),(287318,121,21),(287322,121,33),(287319,121,35),(287336,121,36),(287339,121,44),(287338,121,47),(287332,121,49),(287323,121,53),(287335,121,54),(287334,121,58),(287329,121,70),(287324,121,72),(287327,121,75),(287325,121,76),(287328,121,111),(287317,121,121),(287347,122,1),(287356,122,2),(287355,122,3),(287358,122,6),(287357,122,11),(287341,122,15),(287342,122,35),(287349,122,36),(287353,122,44),(287352,122,47),(287343,122,49),(287350,122,54),(287344,122,56),(287351,122,58),(287354,122,70),(287346,122,75),(287345,122,76),(287348,122,111),(287340,122,122); +INSERT INTO `roleRole` VALUES (326595,1,1),(326596,1,2),(326597,1,3),(326601,1,6),(326600,1,11),(326598,1,70),(326599,1,76),(326602,2,2),(326604,2,6),(326603,2,11),(326605,3,3),(326607,3,6),(326606,3,11),(326609,5,1),(326623,5,2),(326622,5,3),(326608,5,5),(326629,5,6),(326625,5,11),(326619,5,13),(326610,5,18),(326611,5,21),(326612,5,33),(326613,5,35),(326628,5,36),(326631,5,44),(326630,5,47),(326624,5,49),(326614,5,53),(326627,5,54),(326626,5,58),(326621,5,70),(326618,5,72),(326617,5,75),(326615,5,76),(326616,5,111),(326620,5,125),(326632,6,6),(326635,9,1),(326636,9,2),(326637,9,3),(326638,9,5),(326639,9,6),(326633,9,9),(326640,9,11),(326641,9,13),(326642,9,15),(326643,9,16),(326644,9,17),(326645,9,18),(326646,9,19),(326647,9,20),(326648,9,21),(326649,9,22),(326650,9,30),(326651,9,31),(326652,9,32),(326653,9,33),(326654,9,34),(326655,9,35),(326656,9,36),(326657,9,37),(326658,9,38),(326659,9,39),(326660,9,40),(326661,9,41),(326662,9,42),(326663,9,43),(326664,9,44),(326665,9,45),(326666,9,47),(326667,9,48),(326668,9,49),(326669,9,50),(326670,9,51),(326671,9,52),(326672,9,53),(326673,9,54),(326674,9,55),(326675,9,56),(326676,9,57),(326677,9,58),(326678,9,59),(326679,9,60),(326680,9,61),(326681,9,64),(326682,9,65),(326683,9,67),(326684,9,69),(326685,9,70),(326686,9,71),(326687,9,72),(326688,9,73),(326689,9,74),(326690,9,75),(326691,9,76),(326692,9,101),(326693,9,102),(326634,9,103),(326699,9,111),(326694,9,112),(326698,9,122),(326696,9,123),(326695,9,124),(326697,9,125),(326701,11,6),(326700,11,11),(326703,13,1),(326704,13,2),(326705,13,3),(326709,13,6),(326708,13,11),(326702,13,13),(326706,13,70),(326707,13,76),(326716,15,1),(326726,15,2),(326725,15,3),(326728,15,6),(326727,15,11),(326710,15,15),(326711,15,35),(326719,15,36),(326723,15,44),(326722,15,47),(326712,15,49),(326720,15,54),(326713,15,56),(326721,15,58),(326724,15,70),(326715,15,75),(326714,15,76),(326717,15,111),(326718,15,125),(326737,16,1),(326747,16,2),(326746,16,3),(326749,16,6),(326748,16,11),(326731,16,15),(326729,16,16),(326732,16,35),(326740,16,36),(326744,16,44),(326743,16,47),(326733,16,49),(326741,16,54),(326734,16,56),(326742,16,58),(326745,16,70),(326736,16,75),(326735,16,76),(326738,16,111),(326730,16,122),(326739,16,125),(326758,17,1),(326774,17,2),(326773,17,3),(326765,17,5),(326799,17,6),(326762,17,9),(326798,17,11),(326761,17,13),(326797,17,15),(326760,17,16),(326750,17,17),(326757,17,18),(326796,17,19),(326751,17,20),(326766,17,21),(326795,17,22),(326794,17,30),(326793,17,31),(326792,17,32),(326779,17,33),(326791,17,34),(326776,17,35),(326770,17,36),(326752,17,37),(326790,17,38),(326753,17,39),(326789,17,40),(326788,17,41),(326787,17,42),(326786,17,43),(326785,17,44),(326784,17,45),(326800,17,47),(326801,17,48),(326763,17,49),(326802,17,50),(326803,17,51),(326804,17,52),(326780,17,53),(326769,17,54),(326805,17,55),(326806,17,56),(326767,17,57),(326768,17,58),(326775,17,59),(326807,17,60),(326808,17,61),(326754,17,64),(326759,17,65),(326755,17,67),(326809,17,69),(326772,17,70),(326810,17,71),(326782,17,72),(326811,17,73),(326764,17,74),(326812,17,75),(326756,17,76),(326813,17,101),(326814,17,102),(326778,17,103),(326781,17,111),(326815,17,112),(326777,17,122),(326783,17,123),(326816,17,124),(326771,17,125),(326818,18,1),(326823,18,2),(326822,18,3),(326825,18,6),(326824,18,11),(326817,18,18),(326821,18,70),(326819,18,76),(326820,18,125),(326837,19,1),(326843,19,2),(326842,19,3),(326847,19,6),(326846,19,11),(326828,19,13),(326829,19,18),(326826,19,19),(326827,19,21),(326830,19,33),(326840,19,36),(326845,19,44),(326844,19,47),(326835,19,49),(326831,19,53),(326839,19,54),(326838,19,58),(326841,19,70),(326832,19,72),(326833,19,76),(326834,19,111),(326836,19,125),(326857,20,1),(326869,20,2),(326868,20,3),(326867,20,5),(326866,20,6),(326849,20,9),(326865,20,11),(326850,20,13),(326864,20,15),(326851,20,16),(326863,20,17),(326855,20,18),(326862,20,19),(326848,20,20),(326870,20,21),(326871,20,22),(326872,20,30),(326873,20,31),(326874,20,32),(326875,20,33),(326876,20,34),(326854,20,35),(326877,20,36),(326878,20,37),(326879,20,38),(326880,20,39),(326881,20,40),(326882,20,41),(326883,20,42),(326884,20,43),(326885,20,44),(326886,20,45),(326887,20,47),(326888,20,48),(326859,20,49),(326889,20,50),(326890,20,51),(326891,20,52),(326892,20,53),(326893,20,54),(326894,20,55),(326895,20,56),(326860,20,57),(326896,20,58),(326861,20,59),(326897,20,60),(326898,20,61),(326899,20,64),(326852,20,65),(326900,20,67),(326901,20,69),(326902,20,70),(326903,20,71),(326904,20,72),(326905,20,73),(326906,20,74),(326907,20,75),(326853,20,76),(326908,20,101),(326909,20,102),(326858,20,103),(326913,20,111),(326910,20,112),(326856,20,122),(326914,20,123),(326911,20,124),(326912,20,125),(326925,21,1),(326931,21,2),(326930,21,3),(326935,21,6),(326934,21,11),(326916,21,13),(326917,21,18),(326915,21,21),(326918,21,33),(326928,21,36),(326933,21,44),(326932,21,47),(326923,21,49),(326919,21,53),(326927,21,54),(326926,21,58),(326929,21,70),(326920,21,72),(326921,21,76),(326922,21,111),(326924,21,125),(326940,22,1),(326950,22,2),(326949,22,3),(326957,22,6),(326954,22,11),(326937,22,13),(326939,22,18),(326938,22,21),(326936,22,22),(326941,22,33),(326953,22,36),(326956,22,44),(326955,22,47),(326946,22,49),(326942,22,53),(326952,22,54),(326951,22,58),(326948,22,70),(326943,22,72),(326944,22,76),(326945,22,111),(326947,22,125),(326970,30,1),(326984,30,2),(326983,30,3),(326959,30,5),(326995,30,6),(326971,30,9),(326996,30,11),(326972,30,13),(326994,30,15),(326973,30,16),(326993,30,17),(326969,30,18),(326992,30,19),(326960,30,20),(326968,30,21),(326961,30,22),(326958,30,30),(326991,30,31),(326990,30,32),(326967,30,33),(326989,30,34),(326966,30,35),(326988,30,36),(326987,30,37),(326986,30,38),(326997,30,39),(326998,30,40),(326999,30,41),(327000,30,42),(327001,30,43),(327002,30,44),(327003,30,45),(327004,30,47),(327005,30,48),(326976,30,49),(327006,30,50),(327007,30,51),(327008,30,52),(326962,30,53),(327009,30,54),(327010,30,55),(327011,30,56),(326975,30,57),(327012,30,58),(326985,30,59),(327013,30,60),(327014,30,61),(326963,30,64),(326974,30,65),(327015,30,67),(327016,30,69),(326982,30,70),(327017,30,71),(326980,30,72),(327018,30,73),(327019,30,74),(326979,30,75),(326964,30,76),(327020,30,101),(327021,30,102),(326978,30,103),(326965,30,111),(327022,30,112),(326977,30,122),(327024,30,123),(327023,30,124),(326981,30,125),(327026,31,1),(327027,31,2),(327028,31,3),(327032,31,6),(327031,31,11),(327025,31,31),(327029,31,70),(327030,31,76),(327034,32,1),(327035,32,2),(327036,32,3),(327040,32,6),(327039,32,11),(327033,32,32),(327037,32,70),(327038,32,76),(327041,33,33),(327043,34,1),(327048,34,2),(327047,34,3),(327051,34,6),(327050,34,11),(327044,34,13),(327045,34,33),(327042,34,34),(327046,34,70),(327049,34,76),(327053,35,1),(327060,35,2),(327059,35,3),(327062,35,6),(327061,35,11),(327052,35,35),(327058,35,70),(327054,35,75),(327055,35,76),(327056,35,111),(327057,35,125),(327067,36,1),(327069,36,2),(327068,36,3),(327073,36,6),(327072,36,11),(327063,36,36),(327064,36,44),(327065,36,47),(327070,36,70),(327071,36,76),(327066,36,111),(327075,37,1),(327084,37,2),(327083,37,3),(327091,37,6),(327089,37,11),(327076,37,18),(327080,37,36),(327074,37,37),(327088,37,44),(327087,37,47),(327077,37,49),(327085,37,54),(327086,37,58),(327082,37,70),(327078,37,74),(327079,37,76),(327090,37,111),(327081,37,125),(327100,38,1),(327104,38,2),(327103,38,3),(327112,38,6),(327110,38,11),(327093,38,13),(327099,38,18),(327105,38,36),(327094,38,37),(327092,38,38),(327109,38,44),(327108,38,47),(327098,38,49),(327106,38,54),(327107,38,58),(327095,38,64),(327102,38,70),(327097,38,74),(327096,38,76),(327111,38,111),(327101,38,125),(327121,39,1),(327133,39,2),(327132,39,3),(327114,39,5),(327140,39,6),(327137,39,11),(327124,39,13),(327120,39,18),(327115,39,21),(327119,39,33),(327118,39,35),(327136,39,36),(327113,39,39),(327139,39,44),(327138,39,47),(327129,39,49),(327122,39,53),(327135,39,54),(327128,39,56),(327116,39,57),(327134,39,58),(327131,39,70),(327125,39,72),(327130,39,75),(327117,39,76),(327123,39,111),(327126,39,123),(327127,39,125),(327142,40,1),(327145,40,2),(327144,40,3),(327155,40,6),(327153,40,11),(327148,40,36),(327141,40,40),(327152,40,44),(327151,40,47),(327143,40,49),(327149,40,54),(327150,40,58),(327146,40,70),(327147,40,76),(327154,40,111),(327165,41,1),(327170,41,2),(327169,41,3),(327175,41,6),(327174,41,11),(327157,41,13),(327158,41,35),(327167,41,36),(327159,41,40),(327156,41,41),(327173,41,44),(327172,41,47),(327162,41,49),(327166,41,54),(327171,41,58),(327168,41,70),(327164,41,75),(327160,41,76),(327163,41,111),(327161,41,125),(327182,42,1),(327191,42,2),(327190,42,3),(327193,42,6),(327192,42,11),(327177,42,35),(327184,42,36),(327176,42,42),(327188,42,44),(327187,42,47),(327178,42,49),(327185,42,54),(327186,42,58),(327189,42,70),(327181,42,75),(327179,42,76),(327180,42,111),(327183,42,125),(327202,43,1),(327208,43,2),(327207,43,3),(327214,43,6),(327213,43,11),(327195,43,13),(327196,43,18),(327199,43,35),(327204,43,36),(327197,43,42),(327194,43,43),(327212,43,44),(327211,43,47),(327203,43,49),(327209,43,54),(327210,43,58),(327206,43,70),(327205,43,75),(327201,43,76),(327198,43,111),(327200,43,125),(327216,44,1),(327217,44,2),(327218,44,3),(327222,44,6),(327221,44,11),(327215,44,44),(327219,44,70),(327220,44,76),(327226,45,1),(327228,45,2),(327227,45,3),(327232,45,6),(327231,45,11),(327224,45,13),(327225,45,44),(327223,45,45),(327229,45,70),(327230,45,76),(327234,47,1),(327237,47,2),(327236,47,3),(327241,47,6),(327240,47,11),(327233,47,47),(327238,47,70),(327239,47,76),(327235,47,111),(327252,48,1),(327259,48,2),(327258,48,3),(327261,48,6),(327260,48,11),(327243,48,13),(327244,48,35),(327253,48,36),(327256,48,44),(327245,48,47),(327242,48,48),(327246,48,49),(327254,48,54),(327255,48,58),(327247,48,69),(327257,48,70),(327251,48,75),(327250,48,76),(327249,48,111),(327248,48,125),(327266,49,1),(327272,49,2),(327271,49,3),(327275,49,6),(327274,49,11),(327263,49,36),(327268,49,44),(327267,49,47),(327262,49,49),(327264,49,54),(327265,49,58),(327270,49,70),(327269,49,76),(327273,49,111),(327288,50,1),(327301,50,2),(327300,50,3),(327290,50,5),(327305,50,6),(327304,50,11),(327277,50,13),(327287,50,18),(327278,50,21),(327286,50,33),(327291,50,35),(327295,50,36),(327303,50,44),(327302,50,47),(327292,50,49),(327276,50,50),(327285,50,53),(327294,50,54),(327297,50,56),(327279,50,57),(327293,50,58),(327280,50,59),(327281,50,60),(327299,50,70),(327284,50,72),(327296,50,75),(327282,50,76),(327298,50,111),(327283,50,123),(327289,50,125),(327307,51,1),(327316,51,2),(327315,51,3),(327328,51,6),(327324,51,11),(327312,51,13),(327317,51,18),(327308,51,21),(327318,51,33),(327309,51,35),(327327,51,36),(327330,51,44),(327329,51,47),(327323,51,49),(327306,51,51),(327319,51,53),(327326,51,54),(327325,51,58),(327314,51,70),(327320,51,72),(327310,51,74),(327311,51,75),(327313,51,76),(327321,51,111),(327322,51,125),(327339,52,1),(327345,52,2),(327344,52,3),(327355,52,6),(327351,52,11),(327332,52,13),(327342,52,18),(327333,52,19),(327338,52,21),(327341,52,33),(327337,52,35),(327354,52,36),(327357,52,44),(327356,52,47),(327350,52,49),(327334,52,51),(327331,52,52),(327346,52,53),(327353,52,54),(327352,52,58),(327343,52,70),(327347,52,72),(327336,52,74),(327340,52,75),(327335,52,76),(327348,52,111),(327349,52,125),(327359,53,1),(327360,53,2),(327361,53,3),(327365,53,6),(327364,53,11),(327358,53,53),(327362,53,70),(327363,53,76),(327367,54,1),(327368,54,2),(327369,54,3),(327373,54,6),(327372,54,11),(327366,54,54),(327370,54,70),(327371,54,76),(327377,55,1),(327379,55,2),(327378,55,3),(327383,55,6),(327382,55,11),(327375,55,13),(327376,55,54),(327374,55,55),(327380,55,70),(327381,55,76),(327385,56,1),(327386,56,2),(327387,56,3),(327391,56,6),(327390,56,11),(327384,56,56),(327388,56,70),(327389,56,76),(327398,57,1),(327401,57,2),(327400,57,3),(327404,57,6),(327403,57,11),(327393,57,13),(327397,57,33),(327396,57,56),(327392,57,57),(327399,57,70),(327402,57,76),(327394,57,123),(327395,57,125),(327406,58,1),(327409,58,2),(327408,58,3),(327412,58,6),(327411,58,11),(327405,58,58),(327410,58,70),(327407,58,76),(327417,59,1),(327425,59,2),(327424,59,3),(327430,59,5),(327442,59,6),(327439,59,11),(327414,59,13),(327422,59,18),(327416,59,21),(327421,59,33),(327431,59,35),(327435,59,36),(327441,59,44),(327440,59,47),(327432,59,49),(327415,59,50),(327426,59,53),(327434,59,54),(327437,59,56),(327418,59,57),(327433,59,58),(327413,59,59),(327419,59,60),(327423,59,70),(327427,59,72),(327436,59,75),(327420,59,76),(327438,59,111),(327428,59,123),(327429,59,125),(327453,60,1),(327467,60,2),(327466,60,3),(327444,60,5),(327469,60,6),(327468,60,11),(327464,60,13),(327452,60,18),(327451,60,21),(327450,60,33),(327445,60,35),(327457,60,36),(327462,60,44),(327461,60,47),(327446,60,49),(327449,60,53),(327458,60,54),(327460,60,56),(327459,60,58),(327443,60,60),(327465,60,70),(327463,60,72),(327455,60,75),(327447,60,76),(327454,60,111),(327448,60,123),(327456,60,125),(327474,61,1),(327478,61,2),(327477,61,3),(327482,61,6),(327481,61,11),(327471,61,13),(327472,61,36),(327473,61,44),(327475,61,47),(327470,61,61),(327476,61,70),(327479,61,76),(327480,61,111),(327483,62,62),(327484,64,64),(327499,65,1),(327510,65,2),(327509,65,3),(327511,65,5),(327515,65,6),(327514,65,11),(327486,65,13),(327487,65,18),(327503,65,21),(327505,65,33),(327488,65,35),(327495,65,36),(327507,65,44),(327506,65,47),(327489,65,49),(327501,65,50),(327513,65,53),(327494,65,54),(327504,65,56),(327490,65,57),(327493,65,58),(327491,65,59),(327502,65,60),(327485,65,65),(327508,65,70),(327512,65,72),(327497,65,75),(327492,65,76),(327496,65,111),(327500,65,123),(327498,65,125),(327520,66,1),(327519,66,2),(327521,66,3),(327522,66,5),(327523,66,6),(327517,66,9),(327524,66,11),(327525,66,13),(327526,66,15),(327527,66,16),(327528,66,17),(327529,66,18),(327530,66,19),(327531,66,20),(327532,66,21),(327533,66,22),(327534,66,30),(327535,66,31),(327536,66,32),(327537,66,33),(327538,66,34),(327539,66,35),(327540,66,36),(327541,66,37),(327542,66,38),(327543,66,39),(327544,66,40),(327545,66,41),(327546,66,42),(327547,66,43),(327548,66,44),(327549,66,45),(327550,66,47),(327551,66,48),(327552,66,49),(327553,66,50),(327554,66,51),(327555,66,52),(327556,66,53),(327557,66,54),(327558,66,55),(327559,66,56),(327560,66,57),(327561,66,58),(327562,66,59),(327563,66,60),(327564,66,61),(327565,66,64),(327566,66,65),(327516,66,66),(327567,66,67),(327568,66,69),(327569,66,70),(327570,66,71),(327571,66,72),(327572,66,73),(327573,66,74),(327574,66,75),(327575,66,76),(327576,66,101),(327577,66,102),(327518,66,103),(327583,66,111),(327578,66,112),(327582,66,122),(327580,66,123),(327579,66,124),(327581,66,125),(327588,67,1),(327606,67,2),(327605,67,3),(327585,67,5),(327610,67,6),(327609,67,11),(327602,67,13),(327587,67,18),(327589,67,21),(327590,67,33),(327591,67,35),(327599,67,36),(327586,67,37),(327608,67,44),(327607,67,47),(327595,67,49),(327592,67,53),(327598,67,54),(327597,67,58),(327584,67,67),(327604,67,70),(327601,67,72),(327596,67,74),(327600,67,75),(327593,67,76),(327594,67,111),(327603,67,125),(327619,69,1),(327626,69,2),(327625,69,3),(327628,69,6),(327627,69,11),(327612,69,35),(327621,69,36),(327623,69,44),(327613,69,47),(327614,69,49),(327622,69,54),(327615,69,58),(327611,69,69),(327624,69,70),(327618,69,75),(327617,69,76),(327616,69,111),(327620,69,125),(327631,70,6),(327630,70,11),(327629,70,70),(327633,71,1),(327636,71,2),(327635,71,3),(327640,71,6),(327639,71,11),(327634,71,58),(327637,71,70),(327632,71,71),(327638,71,76),(327647,72,1),(327655,72,2),(327654,72,3),(327657,72,6),(327656,72,11),(327642,72,18),(327648,72,36),(327652,72,44),(327651,72,47),(327643,72,49),(327649,72,54),(327650,72,58),(327653,72,70),(327641,72,72),(327646,72,76),(327644,72,111),(327645,72,125),(327664,73,1),(327676,73,2),(327675,73,3),(327659,73,5),(327682,73,6),(327678,73,11),(327672,73,13),(327663,73,18),(327660,73,19),(327662,73,21),(327665,73,33),(327666,73,35),(327681,73,36),(327684,73,44),(327683,73,47),(327677,73,49),(327667,73,53),(327680,73,54),(327679,73,58),(327661,73,64),(327674,73,70),(327671,73,72),(327658,73,73),(327670,73,75),(327668,73,76),(327669,73,111),(327673,73,125),(327685,74,74),(327686,75,75),(327687,76,76),(327689,100,1),(327690,100,2),(327691,100,3),(327692,100,5),(327693,100,6),(327694,100,9),(327695,100,11),(327696,100,13),(327697,100,15),(327698,100,16),(327699,100,17),(327700,100,18),(327701,100,19),(327702,100,20),(327703,100,21),(327704,100,22),(327705,100,30),(327706,100,31),(327707,100,32),(327708,100,33),(327709,100,34),(327710,100,35),(327711,100,36),(327712,100,37),(327713,100,38),(327714,100,39),(327715,100,40),(327716,100,41),(327717,100,42),(327718,100,43),(327719,100,44),(327720,100,45),(327721,100,47),(327722,100,48),(327723,100,49),(327724,100,50),(327725,100,51),(327726,100,52),(327727,100,53),(327728,100,54),(327729,100,55),(327730,100,56),(327731,100,57),(327732,100,58),(327733,100,59),(327734,100,60),(327735,100,61),(327736,100,62),(327737,100,64),(327738,100,65),(327739,100,66),(327740,100,67),(327741,100,69),(327742,100,70),(327743,100,71),(327744,100,72),(327745,100,73),(327746,100,74),(327747,100,75),(327748,100,76),(327688,100,100),(327749,100,101),(327750,100,102),(327751,100,103),(327752,100,104),(327753,100,105),(327754,100,106),(327755,100,107),(327756,100,108),(327757,100,109),(327758,100,110),(327759,100,111),(327760,100,112),(327761,100,114),(327762,100,115),(327763,100,119),(327770,100,120),(327764,100,121),(327765,100,122),(327768,100,123),(327766,100,124),(327769,100,125),(327767,100,126),(327777,101,1),(327782,101,2),(327781,101,3),(327784,101,6),(327783,101,11),(327772,101,13),(327773,101,18),(327774,101,35),(327780,101,70),(327778,101,75),(327776,101,76),(327771,101,101),(327779,101,111),(327775,101,125),(327786,102,1),(327793,102,2),(327792,102,3),(327803,102,6),(327802,102,11),(327787,102,13),(327788,102,35),(327797,102,36),(327801,102,44),(327800,102,47),(327789,102,49),(327798,102,54),(327799,102,58),(327791,102,70),(327794,102,75),(327790,102,76),(327785,102,102),(327795,102,111),(327796,102,125),(327805,103,1),(327806,103,2),(327807,103,3),(327808,103,5),(327809,103,6),(327867,103,9),(327810,103,11),(327811,103,13),(327812,103,15),(327813,103,16),(327814,103,17),(327815,103,18),(327816,103,19),(327817,103,20),(327818,103,21),(327819,103,22),(327820,103,30),(327821,103,31),(327822,103,32),(327823,103,33),(327824,103,34),(327825,103,35),(327826,103,36),(327827,103,37),(327828,103,38),(327829,103,39),(327830,103,40),(327831,103,41),(327832,103,42),(327833,103,43),(327834,103,44),(327835,103,45),(327836,103,47),(327837,103,48),(327838,103,49),(327839,103,50),(327840,103,51),(327841,103,52),(327842,103,53),(327843,103,54),(327844,103,55),(327845,103,56),(327846,103,57),(327847,103,58),(327848,103,59),(327849,103,60),(327850,103,61),(327851,103,64),(327852,103,65),(327853,103,67),(327854,103,69),(327855,103,70),(327856,103,71),(327857,103,72),(327858,103,73),(327859,103,74),(327860,103,75),(327861,103,76),(327862,103,101),(327863,103,102),(327804,103,103),(327870,103,111),(327864,103,112),(327869,103,122),(327866,103,123),(327865,103,124),(327868,103,125),(327878,104,1),(327877,104,2),(327880,104,3),(327881,104,5),(327882,104,6),(327879,104,9),(327883,104,11),(327884,104,13),(327885,104,15),(327886,104,16),(327887,104,17),(327888,104,18),(327889,104,19),(327890,104,20),(327891,104,21),(327892,104,22),(327893,104,30),(327894,104,31),(327895,104,32),(327896,104,33),(327897,104,34),(327898,104,35),(327899,104,36),(327900,104,37),(327901,104,38),(327902,104,39),(327903,104,40),(327904,104,41),(327905,104,42),(327906,104,43),(327907,104,44),(327908,104,45),(327909,104,47),(327910,104,48),(327911,104,49),(327912,104,50),(327913,104,51),(327914,104,52),(327915,104,53),(327916,104,54),(327917,104,55),(327918,104,56),(327919,104,57),(327920,104,58),(327921,104,59),(327922,104,60),(327923,104,61),(327948,104,62),(327924,104,64),(327925,104,65),(327875,104,66),(327926,104,67),(327927,104,69),(327928,104,70),(327929,104,71),(327930,104,72),(327931,104,73),(327932,104,74),(327933,104,75),(327934,104,76),(327872,104,100),(327935,104,101),(327936,104,102),(327874,104,103),(327871,104,104),(327945,104,105),(327944,104,106),(327951,104,107),(327953,104,108),(327952,104,109),(327949,104,110),(327942,104,111),(327937,104,112),(327947,104,114),(327873,104,115),(327950,104,119),(327876,104,120),(327943,104,121),(327941,104,122),(327939,104,123),(327938,104,124),(327940,104,125),(327946,104,126),(327954,105,105),(327957,106,6),(327956,106,11),(327955,106,106),(327969,107,1),(327983,107,2),(327982,107,3),(327960,107,5),(327985,107,6),(327984,107,11),(327980,107,13),(327968,107,18),(327967,107,21),(327966,107,33),(327961,107,35),(327973,107,36),(327978,107,44),(327977,107,47),(327962,107,49),(327965,107,53),(327974,107,54),(327976,107,56),(327975,107,58),(327959,107,60),(327981,107,70),(327979,107,72),(327971,107,75),(327963,107,76),(327958,107,107),(327970,107,111),(327964,107,123),(327972,107,125),(327987,108,1),(327988,108,2),(327989,108,3),(327993,108,6),(327992,108,11),(327990,108,70),(327991,108,76),(327986,108,108),(327998,109,1),(328002,109,2),(328001,109,3),(328004,109,6),(328003,109,11),(327995,109,13),(327996,109,18),(328000,109,70),(327997,109,76),(327994,109,109),(327999,109,125),(328006,110,1),(328009,110,2),(328008,110,3),(328012,110,6),(328011,110,11),(328010,110,70),(328007,110,76),(328005,110,110),(328013,111,111),(328015,112,1),(328018,112,2),(328017,112,3),(328028,112,6),(328026,112,11),(328021,112,36),(328025,112,44),(328024,112,47),(328016,112,49),(328022,112,54),(328023,112,58),(328019,112,70),(328020,112,76),(328027,112,111),(328014,112,112),(328033,114,1),(328035,114,2),(328034,114,3),(328045,114,6),(328043,114,11),(328030,114,13),(328038,114,36),(328042,114,44),(328041,114,47),(328032,114,49),(328039,114,54),(328040,114,58),(328036,114,70),(328037,114,76),(328044,114,111),(328031,114,112),(328029,114,114),(328051,115,1),(328050,115,2),(328053,115,3),(328054,115,5),(328055,115,6),(328052,115,9),(328056,115,11),(328057,115,13),(328058,115,15),(328059,115,16),(328060,115,17),(328061,115,18),(328062,115,19),(328063,115,20),(328064,115,21),(328065,115,22),(328066,115,30),(328067,115,31),(328068,115,32),(328069,115,33),(328070,115,34),(328071,115,35),(328072,115,36),(328073,115,37),(328074,115,38),(328075,115,39),(328076,115,40),(328077,115,41),(328078,115,42),(328079,115,43),(328080,115,44),(328081,115,45),(328082,115,47),(328083,115,48),(328084,115,49),(328085,115,50),(328086,115,51),(328087,115,52),(328088,115,53),(328089,115,54),(328090,115,55),(328091,115,56),(328092,115,57),(328093,115,58),(328094,115,59),(328095,115,60),(328096,115,61),(328097,115,64),(328098,115,65),(328047,115,66),(328099,115,67),(328100,115,69),(328101,115,70),(328102,115,71),(328103,115,72),(328104,115,73),(328105,115,74),(328106,115,75),(328107,115,76),(328108,115,101),(328109,115,102),(328048,115,103),(328115,115,111),(328110,115,112),(328046,115,115),(328049,115,120),(328114,115,122),(328112,115,123),(328111,115,124),(328113,115,125),(328118,119,1),(328121,119,2),(328120,119,3),(328124,119,6),(328123,119,11),(328122,119,70),(328119,119,76),(328117,119,110),(328116,119,119),(328225,120,1),(328229,120,2),(328228,120,3),(328227,120,5),(328230,120,6),(328222,120,9),(328231,120,11),(328223,120,13),(328232,120,15),(328233,120,16),(328234,120,17),(328235,120,18),(328236,120,19),(328237,120,20),(328238,120,21),(328239,120,22),(328240,120,30),(328241,120,31),(328242,120,32),(328243,120,33),(328244,120,34),(328245,120,35),(328246,120,36),(328247,120,37),(328248,120,38),(328249,120,39),(328250,120,40),(328251,120,41),(328252,120,42),(328253,120,43),(328254,120,44),(328255,120,45),(328256,120,47),(328257,120,48),(328258,120,49),(328259,120,50),(328260,120,51),(328261,120,52),(328262,120,53),(328263,120,54),(328264,120,55),(328265,120,56),(328266,120,57),(328267,120,58),(328268,120,59),(328269,120,60),(328270,120,61),(328271,120,64),(328272,120,65),(328224,120,66),(328273,120,67),(328274,120,69),(328275,120,70),(328276,120,71),(328277,120,72),(328278,120,73),(328279,120,74),(328280,120,75),(328281,120,76),(328282,120,101),(328283,120,102),(328226,120,103),(328289,120,111),(328284,120,112),(328221,120,120),(328288,120,122),(328286,120,123),(328285,120,124),(328287,120,125),(328134,121,1),(328140,121,2),(328139,121,3),(328146,121,6),(328142,121,11),(328129,121,13),(328128,121,18),(328126,121,21),(328130,121,33),(328127,121,35),(328145,121,36),(328148,121,44),(328147,121,47),(328141,121,49),(328131,121,53),(328144,121,54),(328143,121,58),(328138,121,70),(328132,121,72),(328135,121,75),(328133,121,76),(328136,121,111),(328125,121,121),(328137,121,125),(328156,122,1),(328166,122,2),(328165,122,3),(328168,122,6),(328167,122,11),(328150,122,15),(328151,122,35),(328159,122,36),(328163,122,44),(328162,122,47),(328152,122,49),(328160,122,54),(328153,122,56),(328161,122,58),(328164,122,70),(328155,122,75),(328154,122,76),(328157,122,111),(328149,122,122),(328158,122,125),(328213,123,1),(328215,123,2),(328214,123,3),(328219,123,6),(328218,123,11),(328211,123,33),(328212,123,56),(328216,123,70),(328217,123,76),(328210,123,123),(328173,124,1),(328185,124,2),(328184,124,3),(328189,124,6),(328188,124,11),(328177,124,18),(328170,124,35),(328182,124,36),(328171,124,37),(328187,124,44),(328186,124,47),(328178,124,49),(328181,124,54),(328180,124,58),(328183,124,70),(328179,124,74),(328172,124,75),(328174,124,76),(328175,124,111),(328169,124,124),(328176,124,125),(328220,125,125),(328197,126,1),(328207,126,2),(328206,126,3),(328209,126,6),(328208,126,11),(328191,126,15),(328192,126,35),(328200,126,36),(328204,126,44),(328203,126,47),(328193,126,49),(328201,126,54),(328194,126,56),(328202,126,58),(328205,126,70),(328196,126,75),(328195,126,76),(328198,126,111),(328199,126,125),(328190,126,126); /*!40000 ALTER TABLE `roleRole` ENABLE KEYS */; UNLOCK TABLES; @@ -140,7 +140,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2023-08-30 15:53:15 +-- Dump completed on 2023-11-20 12:26:42 USE `salix`; -- MariaDB dump 10.19 Distrib 10.5.19-MariaDB, for debian-linux-gnu (x86_64) -- @@ -164,7 +164,7 @@ USE `salix`; LOCK TABLES `ACL` WRITE; /*!40000 ALTER TABLE `ACL` DISABLE KEYS */; -INSERT INTO `ACL` VALUES (3,'Address','*','*','ALLOW','ROLE','employee'),(5,'AgencyService','*','READ','ALLOW','ROLE','employee'),(9,'ClientObservation','*','*','ALLOW','ROLE','employee'),(11,'ContactChannel','*','READ','ALLOW','ROLE','trainee'),(13,'Employee','*','READ','ALLOW','ROLE','employee'),(14,'PayMethod','*','READ','ALLOW','ROLE','trainee'),(16,'FakeProduction','*','READ','ALLOW','ROLE','employee'),(17,'Warehouse','* ','READ','ALLOW','ROLE','trainee'),(20,'TicketState','*','*','ALLOW','ROLE','employee'),(24,'Delivery','*','READ','ALLOW','ROLE','employee'),(25,'Zone','*','READ','ALLOW','ROLE','employee'),(26,'ClientCredit','*','*','ALLOW','ROLE','employee'),(27,'ClientCreditLimit','*','READ','ALLOW','ROLE','trainee'),(30,'GreugeType','*','READ','ALLOW','ROLE','trainee'),(31,'Mandate','*','READ','ALLOW','ROLE','trainee'),(32,'MandateType','*','READ','ALLOW','ROLE','trainee'),(33,'Company','*','READ','ALLOW','ROLE','trainee'),(34,'Greuge','*','READ','ALLOW','ROLE','trainee'),(35,'AddressObservation','*','*','ALLOW','ROLE','employee'),(36,'ObservationType','*','*','ALLOW','ROLE','employee'),(37,'Greuge','*','WRITE','ALLOW','ROLE','employee'),(38,'AgencyMode','*','READ','ALLOW','ROLE','employee'),(39,'ItemTag','*','WRITE','ALLOW','ROLE','buyer'),(40,'ItemBotanical','*','WRITE','ALLOW','ROLE','buyer'),(41,'ItemBotanical','*','READ','ALLOW','ROLE','employee'),(42,'ItemPlacement','*','WRITE','ALLOW','ROLE','buyer'),(43,'ItemPlacement','*','WRITE','ALLOW','ROLE','replenisher'),(44,'ItemPlacement','*','READ','ALLOW','ROLE','employee'),(45,'ItemBarcode','*','READ','ALLOW','ROLE','employee'),(46,'ItemBarcode','*','WRITE','ALLOW','ROLE','buyer'),(47,'ItemBarcode','*','WRITE','ALLOW','ROLE','replenisher'),(51,'ItemTag','*','READ','ALLOW','ROLE','employee'),(53,'Item','*','READ','ALLOW','ROLE','employee'),(54,'Item','*','WRITE','ALLOW','ROLE','buyer'),(55,'Recovery','*','READ','ALLOW','ROLE','trainee'),(56,'Recovery','*','WRITE','ALLOW','ROLE','administrative'),(58,'CreditClassification','*','*','ALLOW','ROLE','insurance'),(60,'CreditInsurance','*','*','ALLOW','ROLE','insurance'),(61,'InvoiceOut','*','READ','ALLOW','ROLE','employee'),(63,'TicketObservation','*','*','ALLOW','ROLE','employee'),(64,'Route','*','READ','ALLOW','ROLE','employee'),(65,'Sale','*','READ','ALLOW','ROLE','employee'),(66,'TicketTracking','*','READ','ALLOW','ROLE','employee'),(68,'TicketPackaging','*','*','ALLOW','ROLE','employee'),(69,'Packaging','*','READ','ALLOW','ROLE','employee'),(70,'Packaging','*','WRITE','ALLOW','ROLE','logistic'),(72,'SaleComponent','*','READ','ALLOW','ROLE','employee'),(73,'Expedition','*','READ','ALLOW','ROLE','employee'),(74,'Expedition','*','WRITE','ALLOW','ROLE','deliveryBoss'),(75,'Expedition','*','WRITE','ALLOW','ROLE','production'),(76,'AnnualAverageInvoiced','*','READ','ALLOW','ROLE','employee'),(77,'WorkerMana','*','READ','ALLOW','ROLE','employee'),(78,'TicketTracking','*','WRITE','ALLOW','ROLE','production'),(79,'TicketTracking','changeState','*','ALLOW','ROLE','employee'),(80,'Sale','deleteSales','*','ALLOW','ROLE','employee'),(81,'Sale','moveToTicket','*','ALLOW','ROLE','employee'),(82,'Sale','updateQuantity','*','ALLOW','ROLE','employee'),(83,'Sale','updatePrice','*','ALLOW','ROLE','employee'),(84,'Sale','updateDiscount','*','ALLOW','ROLE','employee'),(85,'SaleTracking','*','READ','ALLOW','ROLE','employee'),(86,'Order','*','*','ALLOW','ROLE','employee'),(87,'OrderRow','*','*','ALLOW','ROLE','employee'),(88,'ClientContact','*','*','ALLOW','ROLE','employee'),(89,'Sale','moveToNewTicket','*','ALLOW','ROLE','employee'),(90,'Sale','reserve','*','ALLOW','ROLE','employee'),(91,'TicketWeekly','*','READ','ALLOW','ROLE','employee'),(94,'Agency','landsThatDay','*','ALLOW','ROLE','employee'),(96,'ClaimEnd','*','READ','ALLOW','ROLE','employee'),(97,'ClaimEnd','*','WRITE','ALLOW','ROLE','claimManager'),(98,'ClaimBeginning','*','*','ALLOW','ROLE','employee'),(99,'ClaimDevelopment','*','READ','ALLOW','ROLE','employee'),(100,'ClaimDevelopment','*','WRITE','ALLOW','ROLE','claimManager'),(102,'Claim','createFromSales','*','ALLOW','ROLE','employee'),(104,'Item','*','WRITE','ALLOW','ROLE','marketingBoss'),(105,'ItemBarcode','*','WRITE','ALLOW','ROLE','marketingBoss'),(106,'ItemBotanical','*','WRITE','ALLOW','ROLE','marketingBoss'),(108,'ItemPlacement','*','WRITE','ALLOW','ROLE','marketingBoss'),(109,'UserConfig','*','*','ALLOW','ROLE','employee'),(110,'Bank','*','READ','ALLOW','ROLE','trainee'),(111,'ClientLog','*','READ','ALLOW','ROLE','trainee'),(112,'Defaulter','*','READ','ALLOW','ROLE','employee'),(113,'ClientRisk','*','READ','ALLOW','ROLE','trainee'),(114,'Receipt','*','READ','ALLOW','ROLE','trainee'),(115,'Receipt','*','WRITE','ALLOW','ROLE','administrative'),(116,'BankEntity','*','*','ALLOW','ROLE','employee'),(117,'ClientSample','*','*','ALLOW','ROLE','employee'),(118,'WorkerTeam','*','*','ALLOW','ROLE','salesPerson'),(119,'Travel','*','READ','ALLOW','ROLE','employee'),(120,'Travel','*','WRITE','ALLOW','ROLE','buyer'),(121,'Item','regularize','*','ALLOW','ROLE','employee'),(122,'TicketRequest','*','*','ALLOW','ROLE','employee'),(124,'Client','confirmTransaction','WRITE','ALLOW','ROLE','administrative'),(125,'Agency','getAgenciesWithWarehouse','*','ALLOW','ROLE','employee'),(126,'Client','activeWorkersWithRole','*','ALLOW','ROLE','employee'),(127,'TicketLog','*','READ','ALLOW','ROLE','employee'),(129,'TicketService','*','*','ALLOW','ROLE','employee'),(130,'Expedition','*','WRITE','ALLOW','ROLE','packager'),(131,'CreditInsurance','*','READ','ALLOW','ROLE','trainee'),(132,'CreditClassification','*','READ','ALLOW','ROLE','trainee'),(133,'ItemTag','*','WRITE','ALLOW','ROLE','marketingBoss'),(135,'ZoneGeo','*','READ','ALLOW','ROLE','employee'),(136,'ZoneCalendar','*','READ','ALLOW','ROLE','employee'),(137,'ZoneIncluded','*','READ','ALLOW','ROLE','employee'),(138,'LabourHoliday','*','READ','ALLOW','ROLE','employee'),(139,'LabourHolidayLegend','*','READ','ALLOW','ROLE','employee'),(140,'LabourHolidayType','*','READ','ALLOW','ROLE','employee'),(141,'Zone','*','*','ALLOW','ROLE','logisticBoss'),(142,'ZoneCalendar','*','WRITE','ALLOW','ROLE','deliveryBoss'),(143,'ZoneIncluded','*','*','ALLOW','ROLE','deliveryBoss'),(144,'Stowaway','*','*','ALLOW','ROLE','employee'),(145,'Ticket','getPossibleStowaways','READ','ALLOW','ROLE','employee'),(147,'UserConfigView','*','*','ALLOW','ROLE','employee'),(148,'UserConfigView','*','*','ALLOW','ROLE','employee'),(149,'Sip','*','READ','ALLOW','ROLE','employee'),(150,'Sip','*','WRITE','ALLOW','ROLE','hr'),(151,'Department','*','READ','ALLOW','ROLE','employee'),(152,'Department','*','WRITE','ALLOW','ROLE','hr'),(153,'Route','*','READ','ALLOW','ROLE','employee'),(154,'Route','*','WRITE','ALLOW','ROLE','delivery'),(155,'Calendar','*','READ','ALLOW','ROLE','hr'),(156,'WorkerLabour','*','READ','ALLOW','ROLE','hr'),(157,'Calendar','absences','READ','ALLOW','ROLE','employee'),(158,'ItemTag','*','WRITE','ALLOW','ROLE','accessory'),(160,'TicketServiceType','*','READ','ALLOW','ROLE','employee'),(161,'TicketConfig','*','READ','ALLOW','ROLE','employee'),(162,'InvoiceOut','delete','WRITE','ALLOW','ROLE','invoicing'),(163,'InvoiceOut','book','WRITE','ALLOW','ROLE','invoicing'),(165,'TicketDms','*','*','ALLOW','ROLE','employee'),(167,'Worker','isSubordinate','READ','ALLOW','ROLE','employee'),(168,'Worker','mySubordinates','READ','ALLOW','ROLE','employee'),(169,'WorkerTimeControl','filter','READ','ALLOW','ROLE','employee'),(170,'WorkerTimeControl','addTime','WRITE','ALLOW','ROLE','employee'),(171,'TicketServiceType','*','WRITE','ALLOW','ROLE','administrative'),(172,'Sms','*','READ','ALLOW','ROLE','employee'),(173,'Sms','send','WRITE','ALLOW','ROLE','employee'),(176,'Device','*','*','ALLOW','ROLE','employee'),(177,'Device','*','*','ALLOW','ROLE','employee'),(178,'WorkerTimeControl','*','*','ALLOW','ROLE','employee'),(179,'ItemLog','*','READ','ALLOW','ROLE','employee'),(180,'RouteLog','*','READ','ALLOW','ROLE','employee'),(181,'Dms','removeFile','WRITE','ALLOW','ROLE','employee'),(182,'Dms','uploadFile','WRITE','ALLOW','ROLE','employee'),(183,'Dms','downloadFile','READ','ALLOW','ROLE','employee'),(184,'Client','uploadFile','WRITE','ALLOW','ROLE','employee'),(185,'ClientDms','removeFile','WRITE','ALLOW','ROLE','employee'),(186,'ClientDms','*','READ','ALLOW','ROLE','trainee'),(187,'Ticket','uploadFile','WRITE','ALLOW','ROLE','employee'),(190,'Route','updateVolume','WRITE','ALLOW','ROLE','deliveryBoss'),(191,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(192,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(194,'Postcode','*','WRITE','ALLOW','ROLE','deliveryBoss'),(195,'Ticket','addSale','WRITE','ALLOW','ROLE','employee'),(196,'Dms','updateFile','WRITE','ALLOW','ROLE','employee'),(197,'Dms','*','READ','ALLOW','ROLE','trainee'),(198,'ClaimDms','removeFile','WRITE','ALLOW','ROLE','employee'),(199,'ClaimDms','*','READ','ALLOW','ROLE','employee'),(200,'Claim','uploadFile','WRITE','ALLOW','ROLE','employee'),(201,'Sale','updateConcept','WRITE','ALLOW','ROLE','employee'),(202,'Claim','updateClaimAction','WRITE','ALLOW','ROLE','claimManager'),(203,'UserPhone','*','*','ALLOW','ROLE','employee'),(204,'WorkerDms','removeFile','WRITE','ALLOW','ROLE','hr'),(205,'WorkerDms','*','READ','ALLOW','ROLE','hr'),(206,'Chat','*','*','ALLOW','ROLE','employee'),(207,'Chat','sendMessage','*','ALLOW','ROLE','employee'),(208,'Sale','recalculatePrice','WRITE','ALLOW','ROLE','employee'),(209,'Ticket','recalculateComponents','WRITE','ALLOW','ROLE','employee'),(211,'TravelLog','*','READ','ALLOW','ROLE','buyer'),(212,'Thermograph','*','*','ALLOW','ROLE','buyer'),(213,'TravelThermograph','*','WRITE','ALLOW','ROLE','buyer'),(214,'Entry','*','*','ALLOW','ROLE','buyer'),(215,'TicketWeekly','*','WRITE','ALLOW','ROLE','buyer'),(216,'TravelThermograph','*','READ','ALLOW','ROLE','employee'),(218,'Intrastat','*','*','ALLOW','ROLE','buyer'),(221,'UserConfig','getUserConfig','READ','ALLOW','ROLE','account'),(222,'Client','*','READ','ALLOW','ROLE','trainee'),(226,'ClientObservation','*','READ','ALLOW','ROLE','trainee'),(227,'Address','*','READ','ALLOW','ROLE','trainee'),(228,'AddressObservation','*','READ','ALLOW','ROLE','trainee'),(230,'ClientCredit','*','READ','ALLOW','ROLE','trainee'),(231,'ClientContact','*','READ','ALLOW','ROLE','trainee'),(232,'ClientSample','*','READ','ALLOW','ROLE','trainee'),(233,'EntryLog','*','READ','ALLOW','ROLE','buyer'),(234,'WorkerLog','find','READ','ALLOW','ROLE','hr'),(235,'CustomsAgent','*','*','ALLOW','ROLE','employee'),(236,'Buy','*','*','ALLOW','ROLE','buyer'),(237,'WorkerDms','filter','*','ALLOW','ROLE','employee'),(238,'Town','*','WRITE','ALLOW','ROLE','deliveryBoss'),(239,'Province','*','WRITE','ALLOW','ROLE','deliveryBoss'),(240,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(241,'SupplierContact','*','WRITE','ALLOW','ROLE','administrative'),(242,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(244,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(248,'RoleMapping','*','READ','ALLOW','ROLE','account'),(249,'UserPassword','*','READ','ALLOW','ROLE','account'),(250,'Town','*','WRITE','ALLOW','ROLE','deliveryBoss'),(251,'Province','*','WRITE','ALLOW','ROLE','deliveryBoss'),(252,'Supplier','*','READ','ALLOW','ROLE','employee'),(253,'Supplier','*','WRITE','ALLOW','ROLE','administrative'),(254,'SupplierLog','*','READ','ALLOW','ROLE','employee'),(256,'Image','*','WRITE','ALLOW','ROLE','employee'),(257,'FixedPrice','*','*','ALLOW','ROLE','buyer'),(258,'PayDem','*','READ','ALLOW','ROLE','employee'),(259,'Client','createReceipt','*','ALLOW','ROLE','salesAssistant'),(260,'PrintServerQueue','*','WRITE','ALLOW','ROLE','employee'),(261,'SupplierAccount','*','*','ALLOW','ROLE','administrative'),(262,'Entry','*','*','ALLOW','ROLE','administrative'),(263,'InvoiceIn','*','*','ALLOW','ROLE','administrative'),(264,'StarredModule','*','*','ALLOW','ROLE','employee'),(265,'ItemBotanical','*','WRITE','ALLOW','ROLE','logisticBoss'),(266,'ZoneLog','*','READ','ALLOW','ROLE','employee'),(267,'Genus','*','WRITE','ALLOW','ROLE','logisticBoss'),(268,'Specie','*','WRITE','ALLOW','ROLE','logisticBoss'),(269,'InvoiceOut','createPdf','WRITE','ALLOW','ROLE','employee'),(270,'SupplierAddress','*','*','ALLOW','ROLE','employee'),(271,'SalesMonitor','*','*','ALLOW','ROLE','employee'),(272,'InvoiceInLog','*','READ','ALLOW','ROLE','employee'),(273,'InvoiceInTax','*','*','ALLOW','ROLE','administrative'),(274,'InvoiceInLog','*','READ','ALLOW','ROLE','administrative'),(275,'InvoiceOut','createManualInvoice','WRITE','ALLOW','ROLE','invoicing'),(276,'InvoiceOut','globalInvoicing','WRITE','ALLOW','ROLE','invoicing'),(278,'RoleInherit','*','WRITE','ALLOW','ROLE','grant'),(279,'MailAlias','*','*','ALLOW','ROLE','marketing'),(283,'EntryObservation','*','*','ALLOW','ROLE','buyer'),(284,'LdapConfig','*','*','ALLOW','ROLE','sysadmin'),(285,'SambaConfig','*','*','ALLOW','ROLE','sysadmin'),(286,'ACL','*','*','ALLOW','ROLE','developer'),(287,'AccessToken','*','*','ALLOW','ROLE','developer'),(293,'RoleInherit','*','*','ALLOW','ROLE','it'),(294,'RoleRole','*','*','ALLOW','ROLE','it'),(295,'AccountConfig','*','*','ALLOW','ROLE','sysadmin'),(296,'Collection','*','READ','ALLOW','ROLE','employee'),(297,'Sale','refund','WRITE','ALLOW','ROLE','invoicing'),(298,'InvoiceInDueDay','*','*','ALLOW','ROLE','administrative'),(299,'Collection','setSaleQuantity','*','ALLOW','ROLE','employee'),(302,'AgencyTerm','*','*','ALLOW','ROLE','administrative'),(303,'ClaimLog','*','READ','ALLOW','ROLE','claimManager'),(304,'Edi','updateData','WRITE','ALLOW','ROLE','employee'),(305,'EducationLevel','*','*','ALLOW','ROLE','employee'),(306,'InvoiceInIntrastat','*','*','ALLOW','ROLE','employee'),(307,'SupplierAgencyTerm','*','*','ALLOW','ROLE','administrative'),(308,'InvoiceInIntrastat','*','*','ALLOW','ROLE','employee'),(309,'Zone','getZoneClosing','*','ALLOW','ROLE','employee'),(310,'ExpeditionState','*','READ','ALLOW','ROLE','employee'),(311,'Expense','*','READ','ALLOW','ROLE','employee'),(312,'Expense','*','WRITE','ALLOW','ROLE','administrative'),(314,'SupplierActivity','*','READ','ALLOW','ROLE','employee'),(315,'SupplierActivity','*','WRITE','ALLOW','ROLE','administrative'),(316,'Dms','deleteTrashFiles','WRITE','ALLOW','ROLE','employee'),(317,'ClientUnpaid','*','*','ALLOW','ROLE','administrative'),(318,'MdbVersion','*','*','ALLOW','ROLE','developer'),(319,'ItemType','*','READ','ALLOW','ROLE','employee'),(320,'ItemType','*','WRITE','ALLOW','ROLE','buyer'),(321,'InvoiceOut','refund','WRITE','ALLOW','ROLE','invoicing'),(322,'InvoiceOut','refund','WRITE','ALLOW','ROLE','salesAssistant'),(323,'InvoiceOut','refund','WRITE','ALLOW','ROLE','claimManager'),(324,'Ticket','refund','WRITE','ALLOW','ROLE','invoicing'),(325,'Ticket','refund','WRITE','ALLOW','ROLE','salesAssistant'),(326,'Ticket','refund','WRITE','ALLOW','ROLE','claimManager'),(327,'Sale','refund','WRITE','ALLOW','ROLE','salesAssistant'),(328,'Sale','refund','WRITE','ALLOW','ROLE','claimManager'),(329,'TicketRefund','*','WRITE','ALLOW','ROLE','invoicing'),(330,'ClaimObservation','*','WRITE','ALLOW','ROLE','salesPerson'),(331,'ClaimObservation','*','READ','ALLOW','ROLE','salesPerson'),(332,'Client','setPassword','WRITE','ALLOW','ROLE','salesPerson'),(333,'Client','updateUser','WRITE','ALLOW','ROLE','salesPerson'),(334,'ShelvingLog','*','READ','ALLOW','ROLE','employee'),(335,'ZoneExclusionGeo','*','READ','ALLOW','ROLE','employee'),(336,'ZoneExclusionGeo','*','WRITE','ALLOW','ROLE','deliveryBoss'),(337,'Parking','*','*','ALLOW','ROLE','employee'),(338,'Shelving','*','*','ALLOW','ROLE','employee'),(339,'OsTicket','*','*','ALLOW','ROLE','employee'),(340,'OsTicketConfig','*','*','ALLOW','ROLE','it'),(341,'ClientConsumptionQueue','*','WRITE','ALLOW','ROLE','employee'),(342,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','employee'),(343,'Ticket','deliveryNoteEmail','WRITE','ALLOW','ROLE','employee'),(344,'Ticket','deliveryNoteCsvPdf','READ','ALLOW','ROLE','employee'),(345,'Ticket','deliveryNoteCsvEmail','READ','ALLOW','ROLE','employee'),(346,'Client','campaignMetricsPdf','READ','ALLOW','ROLE','employee'),(347,'Client','campaignMetricsEmail','WRITE','ALLOW','ROLE','employee'),(348,'Client','clientWelcomeHtml','READ','ALLOW','ROLE','employee'),(349,'Client','clientWelcomeEmail','WRITE','ALLOW','ROLE','employee'),(350,'Client','creditRequestPdf','READ','ALLOW','ROLE','employee'),(351,'Client','creditRequestHtml','READ','ALLOW','ROLE','employee'),(352,'Client','creditRequestEmail','WRITE','ALLOW','ROLE','employee'),(353,'Client','printerSetupHtml','READ','ALLOW','ROLE','employee'),(354,'Client','printerSetupEmail','WRITE','ALLOW','ROLE','employee'),(355,'Client','sepaCoreEmail','WRITE','ALLOW','ROLE','employee'),(356,'Client','letterDebtorPdf','READ','ALLOW','ROLE','employee'),(357,'Client','letterDebtorStHtml','READ','ALLOW','ROLE','employee'),(358,'Client','letterDebtorStEmail','WRITE','ALLOW','ROLE','employee'),(359,'Client','letterDebtorNdHtml','READ','ALLOW','ROLE','employee'),(360,'Client','letterDebtorNdEmail','WRITE','ALLOW','ROLE','employee'),(361,'Client','clientDebtStatementPdf','READ','ALLOW','ROLE','employee'),(362,'Client','clientDebtStatementHtml','READ','ALLOW','ROLE','employee'),(363,'Client','clientDebtStatementEmail','WRITE','ALLOW','ROLE','employee'),(364,'Client','incotermsAuthorizationPdf','READ','ALLOW','ROLE','employee'),(365,'Client','incotermsAuthorizationHtml','READ','ALLOW','ROLE','employee'),(366,'Client','incotermsAuthorizationEmail','WRITE','ALLOW','ROLE','employee'),(367,'Client','consumptionSendQueued','WRITE','ALLOW','ROLE','system'),(368,'InvoiceOut','invoiceEmail','WRITE','ALLOW','ROLE','employee'),(369,'InvoiceOut','exportationPdf','READ','ALLOW','ROLE','employee'),(370,'InvoiceOut','sendQueued','WRITE','ALLOW','ROLE','system'),(371,'Ticket','invoiceCsvPdf','READ','ALLOW','ROLE','employee'),(372,'Ticket','invoiceCsvEmail','WRITE','ALLOW','ROLE','employee'),(373,'Supplier','campaignMetricsPdf','READ','ALLOW','ROLE','employee'),(374,'Supplier','campaignMetricsEmail','WRITE','ALLOW','ROLE','employee'),(375,'Travel','extraCommunityPdf','READ','ALLOW','ROLE','employee'),(376,'Travel','extraCommunityEmail','WRITE','ALLOW','ROLE','employee'),(377,'Entry','entryOrderPdf','READ','ALLOW','ROLE','employee'),(378,'OsTicket','osTicketReportEmail','WRITE','ALLOW','ROLE','system'),(379,'Item','buyerWasteEmail','WRITE','ALLOW','ROLE','system'),(380,'Claim','claimPickupPdf','READ','ALLOW','ROLE','employee'),(381,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','claimManager'),(382,'Item','labelPdf','READ','ALLOW','ROLE','employee'),(383,'Sector','*','READ','ALLOW','ROLE','employee'),(384,'Sector','*','WRITE','ALLOW','ROLE','employee'),(385,'Route','driverRoutePdf','READ','ALLOW','ROLE','employee'),(386,'Route','driverRouteEmail','WRITE','ALLOW','ROLE','employee'),(387,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','customer'),(388,'Supplier','newSupplier','WRITE','ALLOW','ROLE','administrative'),(389,'ClaimRma','*','READ','ALLOW','ROLE','claimManager'),(390,'ClaimRma','*','WRITE','ALLOW','ROLE','claimManager'),(391,'Notification','*','WRITE','ALLOW','ROLE','system'),(392,'Boxing','*','*','ALLOW','ROLE','employee'),(393,'Url','*','READ','ALLOW','ROLE','employee'),(394,'Url','*','WRITE','ALLOW','ROLE','it'),(395,'ItemShelving','*','READ','ALLOW','ROLE','employee'),(396,'ItemShelving','*','WRITE','ALLOW','ROLE','production'),(397,'ItemShelvingPlacementSupplyStock','*','READ','ALLOW','ROLE','employee'),(398,'NotificationQueue','*','*','ALLOW','ROLE','employee'),(399,'InvoiceOut','clientsToInvoice','WRITE','ALLOW','ROLE','invoicing'),(400,'InvoiceOut','invoiceClient','WRITE','ALLOW','ROLE','invoicing'),(401,'Sale','editTracked','WRITE','ALLOW','ROLE','production'),(402,'Sale','editFloramondo','WRITE','ALLOW','ROLE','salesAssistant'),(403,'Receipt','balanceCompensationEmail','WRITE','ALLOW','ROLE','employee'),(404,'Receipt','balanceCompensationPdf','READ','ALLOW','ROLE','employee'),(405,'Ticket','getTicketsFuture','READ','ALLOW','ROLE','employee'),(406,'Ticket','merge','WRITE','ALLOW','ROLE','employee'),(407,'Sale','editFloramondo','WRITE','ALLOW','ROLE','logistic'),(408,'ZipConfig','*','*','ALLOW','ROLE','employee'),(409,'Item','*','WRITE','ALLOW','ROLE','administrative'),(410,'Sale','editCloned','WRITE','ALLOW','ROLE','buyer'),(411,'Sale','editCloned','WRITE','ALLOW','ROLE','salesAssistant'),(414,'MdbVersion','*','READ','ALLOW','ROLE','$everyone'),(416,'TicketLog','getChanges','READ','ALLOW','ROLE','employee'),(417,'Ticket','getTicketsAdvance','READ','ALLOW','ROLE','employee'),(418,'EntryLog','*','READ','ALLOW','ROLE','administrative'),(419,'Sale','editTracked','WRITE','ALLOW','ROLE','buyer'),(420,'MdbBranch','*','READ','ALLOW','ROLE','$everyone'),(421,'ItemShelvingSale','*','*','ALLOW','ROLE','employee'),(422,'Docuware','checkFile','READ','ALLOW','ROLE','employee'),(423,'Docuware','download','READ','ALLOW','ROLE','salesPerson'),(424,'Docuware','upload','WRITE','ALLOW','ROLE','productionAssi'),(425,'Docuware','deliveryNoteEmail','WRITE','ALLOW','ROLE','salesPerson'),(426,'TpvTransaction','confirm','WRITE','ALLOW','ROLE','$everyone'),(427,'TpvTransaction','start','WRITE','ALLOW','ROLE','$authenticated'),(428,'TpvTransaction','end','WRITE','ALLOW','ROLE','$authenticated'),(429,'ItemConfig','*','READ','ALLOW','ROLE','employee'),(431,'Tag','onSubmit','WRITE','ALLOW','ROLE','employee'),(432,'Worker','updateAttributes','WRITE','ALLOW','ROLE','hr'),(433,'Worker','createAbsence','*','ALLOW','ROLE','employee'),(434,'Worker','updateAbsence','WRITE','ALLOW','ROLE','employee'),(435,'Worker','deleteAbsence','*','ALLOW','ROLE','employee'),(436,'Worker','new','WRITE','ALLOW','ROLE','hr'),(438,'Client','getClientOrSupplierReference','READ','ALLOW','ROLE','employee'),(439,'NotificationSubscription','*','*','ALLOW','ROLE','employee'),(440,'NotificationAcl','*','READ','ALLOW','ROLE','employee'),(441,'MdbApp','*','READ','ALLOW','ROLE','$everyone'),(442,'MdbApp','*','*','ALLOW','ROLE','developer'),(443,'ItemConfig','*','*','ALLOW','ROLE','employee'),(444,'DeviceProduction','*','*','ALLOW','ROLE','hr'),(445,'DeviceProductionModels','*','*','ALLOW','ROLE','hr'),(446,'DeviceProductionState','*','*','ALLOW','ROLE','hr'),(447,'DeviceProductionUser','*','*','ALLOW','ROLE','hr'),(448,'DeviceProduction','*','*','ALLOW','ROLE','productionAssi'),(449,'DeviceProductionModels','*','*','ALLOW','ROLE','productionAssi'),(450,'DeviceProductionState','*','*','ALLOW','ROLE','productionAssi'),(451,'DeviceProductionUser','*','*','ALLOW','ROLE','productionAssi'),(452,'Worker','deallocatePDA','*','ALLOW','ROLE','hr'),(453,'Worker','allocatePDA','*','ALLOW','ROLE','hr'),(454,'Worker','deallocatePDA','*','ALLOW','ROLE','productionAssi'),(455,'Worker','allocatePDA','*','ALLOW','ROLE','productionAssi'),(456,'Zone','*','*','ALLOW','ROLE','deliveryBoss'),(457,'Account','setPassword','WRITE','ALLOW','ROLE','itManagement'),(458,'Operator','*','READ','ALLOW','ROLE','employee'),(459,'Operator','*','WRITE','ALLOW','ROLE','employee'),(460,'InvoiceIn','getSerial','READ','ALLOW','ROLE','administrative'),(461,'Ticket','saveSign','WRITE','ALLOW','ROLE','employee'),(462,'InvoiceOut','negativeBases','READ','ALLOW','ROLE','administrative'),(463,'InvoiceOut','negativeBasesCsv','READ','ALLOW','ROLE','administrative'),(464,'WorkerObservation','*','*','ALLOW','ROLE','hr'),(465,'ClientInforma','*','READ','ALLOW','ROLE','employee'),(466,'ClientInforma','*','WRITE','ALLOW','ROLE','financial'),(467,'Receipt','receiptEmail','*','ALLOW','ROLE','salesAssistant'),(468,'Client','setRating','WRITE','ALLOW','ROLE','financial'),(469,'Client','*','READ','ALLOW','ROLE','employee'),(470,'Client','addressesPropagateRe','*','ALLOW','ROLE','employee'),(471,'Client','canBeInvoiced','*','ALLOW','ROLE','employee'),(472,'Client','canCreateTicket','*','ALLOW','ROLE','employee'),(473,'Client','consumption','*','ALLOW','ROLE','employee'),(474,'Client','createAddress','*','ALLOW','ROLE','employee'),(475,'Client','createWithUser','*','ALLOW','ROLE','employee'),(476,'Client','extendedListFilter','*','ALLOW','ROLE','employee'),(477,'Client','getAverageInvoiced','*','ALLOW','ROLE','employee'),(478,'Client','getCard','*','ALLOW','ROLE','employee'),(479,'Client','getDebt','*','ALLOW','ROLE','employee'),(480,'Client','getMana','*','ALLOW','ROLE','employee'),(481,'Client','transactions','*','ALLOW','ROLE','employee'),(482,'Client','hasCustomerRole','*','ALLOW','ROLE','employee'),(483,'Client','isValidClient','*','ALLOW','ROLE','employee'),(484,'Client','lastActiveTickets','*','ALLOW','ROLE','employee'),(485,'Client','sendSms','*','ALLOW','ROLE','employee'),(486,'Client','setPassword','*','ALLOW','ROLE','employee'),(487,'Client','summary','*','ALLOW','ROLE','employee'),(488,'Client','updateAddress','*','ALLOW','ROLE','employee'),(489,'Client','updateFiscalData','*','ALLOW','ROLE','employee'),(491,'Client','uploadFile','*','ALLOW','ROLE','employee'),(492,'Client','campaignMetricsPdf','*','ALLOW','ROLE','employee'),(493,'Client','campaignMetricsEmail','*','ALLOW','ROLE','employee'),(494,'Client','clientWelcomeHtml','*','ALLOW','ROLE','employee'),(495,'Client','clientWelcomeEmail','*','ALLOW','ROLE','employee'),(496,'Client','printerSetupHtml','*','ALLOW','ROLE','employee'),(497,'Client','printerSetupEmail','*','ALLOW','ROLE','employee'),(498,'Client','sepaCoreEmail','*','ALLOW','ROLE','employee'),(499,'Client','letterDebtorPdf','*','ALLOW','ROLE','employee'),(500,'Client','letterDebtorStHtml','*','ALLOW','ROLE','employee'),(501,'Client','letterDebtorStEmail','*','ALLOW','ROLE','employee'),(502,'Client','letterDebtorNdHtml','*','ALLOW','ROLE','employee'),(503,'Client','letterDebtorNdEmail','*','ALLOW','ROLE','employee'),(504,'Client','clientDebtStatementPdf','*','ALLOW','ROLE','employee'),(505,'Client','clientDebtStatementHtml','*','ALLOW','ROLE','employee'),(506,'Client','clientDebtStatementEmail','*','ALLOW','ROLE','employee'),(507,'Client','creditRequestPdf','*','ALLOW','ROLE','employee'),(508,'Client','creditRequestHtml','*','ALLOW','ROLE','employee'),(509,'Client','creditRequestEmail','*','ALLOW','ROLE','employee'),(510,'Client','incotermsAuthorizationPdf','*','ALLOW','ROLE','employee'),(511,'Client','incotermsAuthorizationHtml','*','ALLOW','ROLE','employee'),(512,'Client','incotermsAuthorizationEmail','*','ALLOW','ROLE','employee'),(513,'Client','consumptionSendQueued','*','ALLOW','ROLE','employee'),(514,'Client','filter','*','ALLOW','ROLE','employee'),(515,'Client','getClientOrSupplierReference','*','ALLOW','ROLE','employee'),(516,'Client','upsert','*','ALLOW','ROLE','employee'),(517,'Client','create','*','ALLOW','ROLE','employee'),(518,'Client','replaceById','*','ALLOW','ROLE','employee'),(519,'Client','updateAttributes','*','ALLOW','ROLE','employee'),(520,'Client','updateAttributes','*','ALLOW','ROLE','employee'),(521,'Client','deleteById','*','ALLOW','ROLE','employee'),(522,'Client','replaceOrCreate','*','ALLOW','ROLE','employee'),(523,'Client','updateAll','*','ALLOW','ROLE','employee'),(524,'Client','upsertWithWhere','*','ALLOW','ROLE','employee'),(525,'Defaulter','observationEmail','WRITE','ALLOW','ROLE','employee'),(527,'VnUser','acl','READ','ALLOW','ROLE','account'),(528,'VnUser','getCurrentUserData','READ','ALLOW','ROLE','account'),(530,'Account','exists','READ','ALLOW','ROLE','account'),(531,'Account','exists','READ','ALLOW','ROLE','account'),(532,'UserLog','*','READ','ALLOW','ROLE','employee'),(533,'RoleLog','*','READ','ALLOW','ROLE','employee'),(534,'WagonType','*','*','ALLOW','ROLE','productionAssi'),(535,'WagonTypeColor','*','*','ALLOW','ROLE','productionAssi'),(536,'WagonTypeTray','*','*','ALLOW','ROLE','productionAssi'),(537,'WagonConfig','*','*','ALLOW','ROLE','productionAssi'),(538,'CollectionWagon','*','*','ALLOW','ROLE','productionAssi'),(539,'CollectionWagonTicket','*','*','ALLOW','ROLE','productionAssi'),(540,'Wagon','*','*','ALLOW','ROLE','productionAssi'),(541,'WagonType','createWagonType','*','ALLOW','ROLE','productionAssi'),(542,'WagonType','deleteWagonType','*','ALLOW','ROLE','productionAssi'),(543,'WagonType','editWagonType','*','ALLOW','ROLE','productionAssi'),(544,'Docuware','deliveryNoteEmail','WRITE','ALLOW','ROLE','employee'),(545,'Agency','find','READ','ALLOW','ROLE','employee'),(546,'Agency','seeExpired','READ','ALLOW','ROLE','coolerAssist'),(547,'WorkerLog','models','READ','ALLOW','ROLE','hr'),(548,'Ticket','editDiscount','WRITE','ALLOW','ROLE','claimManager'),(549,'Ticket','editDiscount','WRITE','ALLOW','ROLE','salesPerson'),(550,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','salesAssistant'),(551,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','deliveryBoss'),(552,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','buyer'),(553,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','claimManager'),(554,'Ticket','deleteTicketWithPartPrepared','WRITE','ALLOW','ROLE','salesAssistant'),(555,'Ticket','editZone','WRITE','ALLOW','ROLE','deliveryBoss'),(556,'State','editableStates','READ','ALLOW','ROLE','employee'),(557,'State','seeEditableStates','READ','ALLOW','ROLE','administrative'),(558,'State','seeEditableStates','READ','ALLOW','ROLE','production'),(559,'State','isSomeEditable','READ','ALLOW','ROLE','salesPerson'),(560,'State','isAllEditable','READ','ALLOW','ROLE','production'),(561,'State','isAllEditable','READ','ALLOW','ROLE','administrative'),(562,'Agency','seeExpired','READ','ALLOW','ROLE','administrative'),(563,'Agency','seeExpired','READ','ALLOW','ROLE','productionBoss'),(564,'Claim','createAfterDeadline','WRITE','ALLOW','ROLE','claimManager'),(565,'Client','editAddressLogifloraAllowed','WRITE','ALLOW','ROLE','salesAssistant'),(566,'Client','editFiscalDataWithoutTaxDataCheck','WRITE','ALLOW','ROLE','salesAssistant'),(567,'Client','editVerifiedDataWithoutTaxDataCheck','WRITE','ALLOW','ROLE','salesAssistant'),(568,'Client','editCredit','WRITE','ALLOW','ROLE','financialBoss'),(569,'Client','zeroCreditEditor','WRITE','ALLOW','ROLE','financialBoss'),(570,'InvoiceOut','canCreatePdf','WRITE','ALLOW','ROLE','invoicing'),(571,'Supplier','editPayMethodCheck','WRITE','ALLOW','ROLE','financial'),(572,'Worker','isTeamBoss','WRITE','ALLOW','ROLE','teamBoss'),(573,'Worker','forceIsSubordinate','READ','ALLOW','ROLE','hr'),(574,'Claim','editState','WRITE','ALLOW','ROLE','claimManager'),(575,'Claim','find','READ','ALLOW','ROLE','salesPerson'),(576,'Claim','findById','READ','ALLOW','ROLE','salesPerson'),(577,'Claim','findOne','READ','ALLOW','ROLE','salesPerson'),(578,'Claim','getSummary','READ','ALLOW','ROLE','salesPerson'),(579,'Claim','updateClaim','WRITE','ALLOW','ROLE','salesPerson'),(580,'Claim','regularizeClaim','WRITE','ALLOW','ROLE','claimManager'),(581,'Claim','updateClaimDestination','WRITE','ALLOW','ROLE','claimManager'),(582,'Claim','downloadFile','READ','ALLOW','ROLE','claimManager'),(583,'Claim','deleteById','WRITE','ALLOW','ROLE','claimManager'),(584,'Claim','filter','READ','ALLOW','ROLE','salesPerson'),(585,'Claim','logs','READ','ALLOW','ROLE','claimManager'),(586,'Ticket','find','READ','ALLOW','ROLE','employee'),(587,'Ticket','findById','READ','ALLOW','ROLE','employee'),(588,'Ticket','findOne','READ','ALLOW','ROLE','employee'),(589,'Ticket','getVolume','READ','ALLOW','ROLE','employee'),(590,'Ticket','getTotalVolume','READ','ALLOW','ROLE','employee'),(591,'Ticket','summary','READ','ALLOW','ROLE','employee'),(592,'Ticket','priceDifference','READ','ALLOW','ROLE','employee'),(593,'Ticket','componentUpdate','WRITE','ALLOW','ROLE','employee'),(594,'Ticket','new','WRITE','ALLOW','ROLE','employee'),(595,'Ticket','isEditable','READ','ALLOW','ROLE','employee'),(596,'Ticket','setDeleted','WRITE','ALLOW','ROLE','salesPerson'),(597,'Ticket','restore','WRITE','ALLOW','ROLE','employee'),(598,'Ticket','getSales','READ','ALLOW','ROLE','employee'),(599,'Ticket','getSalesPersonMana','READ','ALLOW','ROLE','employee'),(600,'Ticket','filter','READ','ALLOW','ROLE','employee'),(601,'Ticket','makeInvoice','WRITE','ALLOW','ROLE','employee'),(602,'Ticket','updateEditableTicket','WRITE','ALLOW','ROLE','employee'),(603,'Ticket','updateDiscount','WRITE','ALLOW','ROLE','employee'),(604,'Ticket','transferSales','WRITE','ALLOW','ROLE','employee'),(605,'Ticket','sendSms','WRITE','ALLOW','ROLE','employee'),(606,'Ticket','isLocked','READ','ALLOW','ROLE','employee'),(607,'Ticket','freightCost','READ','ALLOW','ROLE','employee'),(608,'Ticket','getComponentsSum','READ','ALLOW','ROLE','employee'),(609,'Ticket','updateAttributes','WRITE','ALLOW','ROLE','delivery'),(610,'Ticket','deliveryNoteCsv','READ','ALLOW','ROLE','employee'),(611,'State','find','READ','ALLOW','ROLE','employee'),(612,'State','findById','READ','ALLOW','ROLE','employee'),(613,'State','findOne','READ','ALLOW','ROLE','employee'),(614,'Worker','find','READ','ALLOW','ROLE','employee'),(615,'Worker','findById','READ','ALLOW','ROLE','employee'),(616,'Worker','findOne','READ','ALLOW','ROLE','employee'),(617,'Worker','filter','READ','ALLOW','ROLE','employee'),(618,'Worker','getWorkedHours','READ','ALLOW','ROLE','employee'),(619,'Worker','active','READ','ALLOW','ROLE','employee'),(620,'Worker','activeWithRole','READ','ALLOW','ROLE','employee'),(621,'Worker','uploadFile','WRITE','ALLOW','ROLE','hr'),(622,'Worker','contracts','READ','ALLOW','ROLE','employee'),(623,'Worker','holidays','READ','ALLOW','ROLE','employee'),(624,'Worker','activeContract','READ','ALLOW','ROLE','employee'),(625,'Worker','activeWithInheritedRole','READ','ALLOW','ROLE','employee'),(626,'Ticket','collectionLabel','READ','ALLOW','ROLE','employee'),(628,'Ticket','expeditionPalletLabel','READ','ALLOW','ROLE','employee'),(629,'Ticket','editDiscount','WRITE','ALLOW','ROLE','artificialBoss'),(630,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','salesTeamBoss'),(635,'Ticket','updateAttributes','WRITE','ALLOW','ROLE','administrative'),(636,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','salesPerson'),(637,'Claim','downloadFile','READ','ALLOW','ROLE','salesPerson'),(638,'Agency','seeExpired','READ','ALLOW','ROLE','artificialBoss'),(639,'Agency','seeExpired','READ','ALLOW','ROLE','logisticAssistant'),(640,'Claim','filter','READ','ALLOW','ROLE','buyer'),(641,'Claim','find','READ','ALLOW','ROLE','buyer'),(642,'Claim','findById','READ','ALLOW','ROLE','buyer'),(643,'Claim','getSummary','READ','ALLOW','ROLE','buyer'),(644,'Claim','filter','READ','ALLOW','ROLE','handmadeBoss'),(645,'Claim','find','READ','ALLOW','ROLE','handmadeBoss'),(646,'Claim','findById','READ','ALLOW','ROLE','handmadeBoss'),(647,'Claim','getSummary','READ','ALLOW','ROLE','handmadeBoss'),(648,'Claim','__get__lines','READ','ALLOW','ROLE','claimManager'),(649,'Claim','__get__lines','READ','ALLOW','ROLE','salesPerson'),(650,'Claim','getSummary','READ','ALLOW','ROLE','deliveryBoss'),(651,'Claim','findById','READ','ALLOW','ROLE','deliveryBoss'),(652,'Claim','find','READ','ALLOW','ROLE','deliveryBoss'),(653,'Claim','filter','READ','ALLOW','ROLE','deliveryBoss'),(654,'Ticket','editZone','WRITE','ALLOW','ROLE','logisticAssistant'),(655,'Entry','addFromPackaging','WRITE','ALLOW','ROLE','production'),(656,'Entry','addFromBuy','WRITE','ALLOW','ROLE','production'),(657,'Supplier','getItemsPackaging','READ','ALLOW','ROLE','production'),(658,'Ticket','closeAll','WRITE','ALLOW','ROLE','system'),(659,'Account','*','*','ALLOW','ROLE','itManagement'),(660,'Account','*','READ','ALLOW','ROLE','employee'),(664,'MailForward','*','*','ALLOW','ROLE','itManagement'),(665,'Role','*','READ','ALLOW','ROLE','employee'),(666,'Role','*','WRITE','ALLOW','ROLE','it'),(667,'VnUser','*','*','ALLOW','ROLE','itManagement'),(668,'VnUser','__get__preview','READ','ALLOW','ROLE','employee'),(669,'VnUser','preview','*','ALLOW','ROLE','employee'),(670,'VnUser','create','*','ALLOW','ROLE','itManagement'),(671,'VnUser','renewToken','WRITE','ALLOW','ROLE','employee'),(672,'PackingSiteAdvanced','*','*','ALLOW','ROLE','production'),(673,'InvoiceOut','makePdfAndNotify','WRITE','ALLOW','ROLE','invoicing'),(674,'InvoiceOutConfig','*','READ','ALLOW','ROLE','invoicing'),(676,'Ticket','invoiceTickets','WRITE','ALLOW','ROLE','employee'),(680,'MailAliasAccount','*','READ','ALLOW','ROLE','employee'),(681,'MailAliasAccount','create','WRITE','ALLOW','ROLE','employee'),(682,'MailAliasAccount','deleteById','WRITE','ALLOW','ROLE','employee'),(683,'MailAliasAccount','canEditAlias','WRITE','ALLOW','ROLE','itManagement'),(684,'WorkerDisableExcluded','*','READ','ALLOW','ROLE','itManagement'),(685,'WorkerDisableExcluded','*','WRITE','ALLOW','ROLE','itManagement'),(686,'MailForward','*','*','ALLOW','ROLE','hr'),(687,'ClientSms','find','READ','ALLOW','ROLE','employee'),(688,'ClientSms','create','WRITE','ALLOW','ROLE','employee'),(689,'Vehicle','sorted','WRITE','ALLOW','ROLE','employee'),(690,'Roadmap','*','*','ALLOW','ROLE','palletizerBoss'),(691,'Roadmap','*','*','ALLOW','ROLE','productionBoss'),(692,'ExpeditionTruck','*','*','ALLOW','ROLE','palletizerBoss'),(693,'ExpeditionTruck','*','*','ALLOW','ROLE','productionBoss'),(694,'MailAliasAccount','canEditAlias','WRITE','ALLOW','ROLE','marketingBoss'),(695,'ViaexpressConfig','internationalExpedition','WRITE','ALLOW','ROLE','employee'),(696,'ViaexpressConfig','renderer','READ','ALLOW','ROLE','employee'),(697,'Ticket','transferClient','WRITE','ALLOW','ROLE','administrative'),(698,'Ticket','canEditWeekly','WRITE','ALLOW','ROLE','buyer'),(699,'TicketSms','find','READ','ALLOW','ROLE','salesPerson'),(701,'Docuware','upload','WRITE','ALLOW','ROLE','deliveryBoss'),(702,'Ticket','docuwareDownload','READ','ALLOW','ROLE','salesPerson'); +INSERT INTO `ACL` VALUES (3,'Address','*','*','ALLOW','ROLE','employee'),(5,'AgencyService','*','READ','ALLOW','ROLE','employee'),(9,'ClientObservation','*','*','ALLOW','ROLE','employee'),(11,'ContactChannel','*','READ','ALLOW','ROLE','trainee'),(13,'Employee','*','READ','ALLOW','ROLE','employee'),(14,'PayMethod','*','READ','ALLOW','ROLE','trainee'),(16,'FakeProduction','*','READ','ALLOW','ROLE','employee'),(17,'Warehouse','* ','READ','ALLOW','ROLE','trainee'),(20,'TicketState','*','*','ALLOW','ROLE','employee'),(24,'Delivery','*','READ','ALLOW','ROLE','employee'),(25,'Zone','*','READ','ALLOW','ROLE','employee'),(26,'ClientCredit','*','*','ALLOW','ROLE','employee'),(27,'ClientCreditLimit','*','READ','ALLOW','ROLE','trainee'),(30,'GreugeType','*','READ','ALLOW','ROLE','trainee'),(31,'Mandate','*','READ','ALLOW','ROLE','trainee'),(32,'MandateType','*','READ','ALLOW','ROLE','trainee'),(33,'Company','*','READ','ALLOW','ROLE','trainee'),(34,'Greuge','*','READ','ALLOW','ROLE','trainee'),(35,'AddressObservation','*','*','ALLOW','ROLE','employee'),(36,'ObservationType','*','*','ALLOW','ROLE','employee'),(37,'Greuge','*','WRITE','ALLOW','ROLE','employee'),(38,'AgencyMode','*','READ','ALLOW','ROLE','employee'),(39,'ItemTag','*','WRITE','ALLOW','ROLE','buyer'),(40,'ItemBotanical','*','WRITE','ALLOW','ROLE','buyer'),(41,'ItemBotanical','*','READ','ALLOW','ROLE','employee'),(42,'ItemPlacement','*','WRITE','ALLOW','ROLE','buyer'),(43,'ItemPlacement','*','WRITE','ALLOW','ROLE','replenisher'),(44,'ItemPlacement','*','READ','ALLOW','ROLE','employee'),(45,'ItemBarcode','*','READ','ALLOW','ROLE','employee'),(46,'ItemBarcode','*','WRITE','ALLOW','ROLE','buyer'),(47,'ItemBarcode','*','WRITE','ALLOW','ROLE','replenisher'),(51,'ItemTag','*','READ','ALLOW','ROLE','employee'),(53,'Item','*','READ','ALLOW','ROLE','employee'),(54,'Item','*','WRITE','ALLOW','ROLE','buyer'),(55,'Recovery','*','READ','ALLOW','ROLE','trainee'),(56,'Recovery','*','WRITE','ALLOW','ROLE','administrative'),(58,'CreditClassification','*','*','ALLOW','ROLE','insurance'),(60,'CreditInsurance','*','*','ALLOW','ROLE','insurance'),(61,'InvoiceOut','*','READ','ALLOW','ROLE','employee'),(63,'TicketObservation','*','*','ALLOW','ROLE','employee'),(64,'Route','*','READ','ALLOW','ROLE','employee'),(65,'Sale','*','READ','ALLOW','ROLE','employee'),(66,'TicketTracking','*','READ','ALLOW','ROLE','employee'),(68,'TicketPackaging','*','*','ALLOW','ROLE','employee'),(69,'Packaging','*','READ','ALLOW','ROLE','employee'),(70,'Packaging','*','WRITE','ALLOW','ROLE','logistic'),(72,'SaleComponent','*','READ','ALLOW','ROLE','employee'),(73,'Expedition','*','READ','ALLOW','ROLE','employee'),(74,'Expedition','*','WRITE','ALLOW','ROLE','deliveryAssistant'),(75,'Expedition','*','WRITE','ALLOW','ROLE','production'),(76,'AnnualAverageInvoiced','*','READ','ALLOW','ROLE','employee'),(77,'WorkerMana','*','READ','ALLOW','ROLE','employee'),(78,'TicketTracking','*','WRITE','ALLOW','ROLE','production'),(79,'Ticket','state','*','ALLOW','ROLE','employee'),(80,'Sale','deleteSales','*','ALLOW','ROLE','employee'),(81,'Sale','moveToTicket','*','ALLOW','ROLE','employee'),(82,'Sale','updateQuantity','*','ALLOW','ROLE','employee'),(83,'Sale','updatePrice','*','ALLOW','ROLE','employee'),(84,'Sale','updateDiscount','*','ALLOW','ROLE','employee'),(85,'SaleTracking','*','READ','ALLOW','ROLE','employee'),(86,'Order','*','*','ALLOW','ROLE','employee'),(87,'OrderRow','*','*','ALLOW','ROLE','employee'),(88,'ClientContact','*','*','ALLOW','ROLE','employee'),(89,'Sale','moveToNewTicket','*','ALLOW','ROLE','employee'),(90,'Sale','reserve','*','ALLOW','ROLE','employee'),(91,'TicketWeekly','*','READ','ALLOW','ROLE','employee'),(94,'Agency','landsThatDay','*','ALLOW','ROLE','employee'),(96,'ClaimEnd','*','READ','ALLOW','ROLE','employee'),(97,'ClaimEnd','*','WRITE','ALLOW','ROLE','claimManager'),(98,'ClaimBeginning','*','*','ALLOW','ROLE','employee'),(99,'ClaimDevelopment','*','READ','ALLOW','ROLE','employee'),(100,'ClaimDevelopment','*','WRITE','ALLOW','ROLE','claimManager'),(102,'Claim','createFromSales','*','ALLOW','ROLE','employee'),(104,'Item','*','WRITE','ALLOW','ROLE','marketingBoss'),(105,'ItemBarcode','*','WRITE','ALLOW','ROLE','marketingBoss'),(106,'ItemBotanical','*','WRITE','ALLOW','ROLE','marketingBoss'),(108,'ItemPlacement','*','WRITE','ALLOW','ROLE','marketingBoss'),(109,'UserConfig','*','*','ALLOW','ROLE','employee'),(110,'Bank','*','READ','ALLOW','ROLE','trainee'),(111,'ClientLog','*','READ','ALLOW','ROLE','trainee'),(112,'Defaulter','*','READ','ALLOW','ROLE','employee'),(113,'ClientRisk','*','READ','ALLOW','ROLE','trainee'),(114,'Receipt','*','READ','ALLOW','ROLE','trainee'),(115,'Receipt','*','WRITE','ALLOW','ROLE','administrative'),(116,'BankEntity','*','*','ALLOW','ROLE','employee'),(117,'ClientSample','*','*','ALLOW','ROLE','employee'),(118,'WorkerTeam','*','*','ALLOW','ROLE','salesPerson'),(119,'Travel','*','READ','ALLOW','ROLE','employee'),(120,'Travel','*','WRITE','ALLOW','ROLE','buyer'),(121,'Item','regularize','*','ALLOW','ROLE','employee'),(122,'TicketRequest','*','*','ALLOW','ROLE','employee'),(124,'Client','confirmTransaction','WRITE','ALLOW','ROLE','administrative'),(125,'Agency','getAgenciesWithWarehouse','*','ALLOW','ROLE','employee'),(127,'TicketLog','*','READ','ALLOW','ROLE','employee'),(129,'TicketService','*','*','ALLOW','ROLE','employee'),(130,'Expedition','*','WRITE','ALLOW','ROLE','packager'),(131,'CreditInsurance','*','READ','ALLOW','ROLE','trainee'),(132,'CreditClassification','*','READ','ALLOW','ROLE','trainee'),(133,'ItemTag','*','WRITE','ALLOW','ROLE','marketingBoss'),(135,'ZoneGeo','*','READ','ALLOW','ROLE','employee'),(136,'ZoneCalendar','*','READ','ALLOW','ROLE','employee'),(137,'ZoneIncluded','*','READ','ALLOW','ROLE','employee'),(138,'LabourHoliday','*','READ','ALLOW','ROLE','employee'),(139,'LabourHolidayLegend','*','READ','ALLOW','ROLE','employee'),(140,'LabourHolidayType','*','READ','ALLOW','ROLE','employee'),(141,'Zone','*','*','ALLOW','ROLE','logisticBoss'),(142,'ZoneCalendar','*','WRITE','ALLOW','ROLE','deliveryAssistant'),(143,'ZoneIncluded','*','*','ALLOW','ROLE','deliveryAssistant'),(144,'Stowaway','*','*','ALLOW','ROLE','employee'),(145,'Ticket','getPossibleStowaways','READ','ALLOW','ROLE','employee'),(147,'UserConfigView','*','*','ALLOW','ROLE','employee'),(148,'UserConfigView','*','*','ALLOW','ROLE','employee'),(149,'Sip','*','READ','ALLOW','ROLE','employee'),(150,'Sip','*','WRITE','ALLOW','ROLE','hr'),(151,'Department','*','READ','ALLOW','ROLE','employee'),(152,'Department','*','WRITE','ALLOW','ROLE','hr'),(153,'Route','*','READ','ALLOW','ROLE','employee'),(154,'Route','*','WRITE','ALLOW','ROLE','delivery'),(155,'Calendar','*','READ','ALLOW','ROLE','hr'),(156,'WorkerLabour','*','READ','ALLOW','ROLE','hr'),(157,'Calendar','absences','READ','ALLOW','ROLE','employee'),(158,'ItemTag','*','WRITE','ALLOW','ROLE','accessory'),(160,'TicketServiceType','*','READ','ALLOW','ROLE','employee'),(161,'TicketConfig','*','READ','ALLOW','ROLE','employee'),(162,'InvoiceOut','delete','WRITE','ALLOW','ROLE','invoicing'),(163,'InvoiceOut','book','WRITE','ALLOW','ROLE','invoicing'),(165,'TicketDms','*','*','ALLOW','ROLE','employee'),(167,'Worker','isSubordinate','READ','ALLOW','ROLE','employee'),(168,'Worker','mySubordinates','READ','ALLOW','ROLE','employee'),(169,'WorkerTimeControl','filter','READ','ALLOW','ROLE','employee'),(170,'WorkerTimeControl','addTime','WRITE','ALLOW','ROLE','employee'),(171,'TicketServiceType','*','WRITE','ALLOW','ROLE','administrative'),(172,'Sms','*','READ','ALLOW','ROLE','employee'),(173,'Sms','send','WRITE','ALLOW','ROLE','employee'),(176,'Device','*','*','ALLOW','ROLE','employee'),(177,'Device','*','*','ALLOW','ROLE','employee'),(178,'WorkerTimeControl','*','*','ALLOW','ROLE','employee'),(179,'ItemLog','*','READ','ALLOW','ROLE','employee'),(180,'RouteLog','*','READ','ALLOW','ROLE','employee'),(181,'Dms','removeFile','WRITE','ALLOW','ROLE','employee'),(182,'Dms','uploadFile','WRITE','ALLOW','ROLE','employee'),(183,'Dms','downloadFile','READ','ALLOW','ROLE','employee'),(184,'Client','uploadFile','WRITE','ALLOW','ROLE','employee'),(185,'ClientDms','removeFile','WRITE','ALLOW','ROLE','employee'),(186,'ClientDms','*','READ','ALLOW','ROLE','trainee'),(187,'Ticket','uploadFile','WRITE','ALLOW','ROLE','employee'),(190,'Route','updateVolume','WRITE','ALLOW','ROLE','deliveryAssistant'),(191,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(192,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(194,'Postcode','*','WRITE','ALLOW','ROLE','deliveryAssistant'),(195,'Ticket','addSale','WRITE','ALLOW','ROLE','employee'),(196,'Dms','updateFile','WRITE','ALLOW','ROLE','employee'),(197,'Dms','*','READ','ALLOW','ROLE','trainee'),(198,'ClaimDms','removeFile','WRITE','ALLOW','ROLE','employee'),(199,'ClaimDms','*','READ','ALLOW','ROLE','employee'),(200,'Claim','uploadFile','WRITE','ALLOW','ROLE','employee'),(201,'Sale','updateConcept','WRITE','ALLOW','ROLE','employee'),(202,'Claim','updateClaimAction','WRITE','ALLOW','ROLE','claimManager'),(203,'UserPhone','*','*','ALLOW','ROLE','employee'),(204,'WorkerDms','removeFile','WRITE','ALLOW','ROLE','hr'),(205,'WorkerDms','*','READ','ALLOW','ROLE','hr'),(206,'Chat','*','*','ALLOW','ROLE','employee'),(207,'Chat','sendMessage','*','ALLOW','ROLE','employee'),(208,'Sale','recalculatePrice','WRITE','ALLOW','ROLE','employee'),(209,'Ticket','recalculateComponents','WRITE','ALLOW','ROLE','employee'),(211,'TravelLog','*','READ','ALLOW','ROLE','buyer'),(212,'Thermograph','*','*','ALLOW','ROLE','buyer'),(213,'TravelThermograph','*','WRITE','ALLOW','ROLE','buyer'),(214,'Entry','*','*','ALLOW','ROLE','buyer'),(215,'TicketWeekly','*','WRITE','ALLOW','ROLE','buyer'),(216,'TravelThermograph','*','READ','ALLOW','ROLE','employee'),(218,'Intrastat','*','*','ALLOW','ROLE','buyer'),(221,'UserConfig','getUserConfig','READ','ALLOW','ROLE','account'),(226,'ClientObservation','*','READ','ALLOW','ROLE','trainee'),(227,'Address','*','READ','ALLOW','ROLE','trainee'),(228,'AddressObservation','*','READ','ALLOW','ROLE','trainee'),(230,'ClientCredit','*','READ','ALLOW','ROLE','trainee'),(231,'ClientContact','*','READ','ALLOW','ROLE','trainee'),(232,'ClientSample','*','READ','ALLOW','ROLE','trainee'),(233,'EntryLog','*','READ','ALLOW','ROLE','buyer'),(234,'WorkerLog','find','READ','ALLOW','ROLE','hr'),(235,'CustomsAgent','*','*','ALLOW','ROLE','employee'),(236,'Buy','*','*','ALLOW','ROLE','buyer'),(237,'WorkerDms','filter','*','ALLOW','ROLE','employee'),(238,'Town','*','WRITE','ALLOW','ROLE','deliveryAssistant'),(239,'Province','*','WRITE','ALLOW','ROLE','deliveryAssistant'),(241,'SupplierContact','*','WRITE','ALLOW','ROLE','administrative'),(248,'RoleMapping','*','READ','ALLOW','ROLE','account'),(249,'UserPassword','*','READ','ALLOW','ROLE','account'),(250,'Town','*','WRITE','ALLOW','ROLE','deliveryAssistant'),(251,'Province','*','WRITE','ALLOW','ROLE','deliveryAssistant'),(252,'Supplier','*','READ','ALLOW','ROLE','employee'),(253,'Supplier','*','WRITE','ALLOW','ROLE','administrative'),(254,'SupplierLog','*','READ','ALLOW','ROLE','employee'),(256,'Image','*','WRITE','ALLOW','ROLE','employee'),(257,'FixedPrice','*','*','ALLOW','ROLE','buyer'),(258,'PayDem','*','READ','ALLOW','ROLE','employee'),(259,'Client','createReceipt','*','ALLOW','ROLE','salesAssistant'),(260,'PrintServerQueue','*','WRITE','ALLOW','ROLE','employee'),(261,'SupplierAccount','*','*','ALLOW','ROLE','administrative'),(262,'Entry','*','*','ALLOW','ROLE','administrative'),(263,'InvoiceIn','*','*','ALLOW','ROLE','administrative'),(264,'StarredModule','*','*','ALLOW','ROLE','employee'),(265,'ItemBotanical','*','WRITE','ALLOW','ROLE','logisticBoss'),(266,'ZoneLog','*','READ','ALLOW','ROLE','employee'),(267,'Genus','*','WRITE','ALLOW','ROLE','logisticBoss'),(268,'Specie','*','WRITE','ALLOW','ROLE','logisticBoss'),(269,'InvoiceOut','createPdf','WRITE','ALLOW','ROLE','employee'),(270,'SupplierAddress','*','*','ALLOW','ROLE','employee'),(271,'SalesMonitor','*','*','ALLOW','ROLE','employee'),(272,'InvoiceInLog','*','READ','ALLOW','ROLE','employee'),(273,'InvoiceInTax','*','*','ALLOW','ROLE','administrative'),(274,'InvoiceInLog','*','READ','ALLOW','ROLE','administrative'),(275,'InvoiceOut','createManualInvoice','WRITE','ALLOW','ROLE','invoicing'),(276,'InvoiceOut','globalInvoicing','WRITE','ALLOW','ROLE','invoicing'),(278,'RoleInherit','*','WRITE','ALLOW','ROLE','grant'),(279,'MailAlias','*','*','ALLOW','ROLE','marketing'),(283,'EntryObservation','*','*','ALLOW','ROLE','buyer'),(284,'LdapConfig','*','*','ALLOW','ROLE','sysadmin'),(285,'SambaConfig','*','*','ALLOW','ROLE','sysadmin'),(286,'ACL','*','*','ALLOW','ROLE','developer'),(287,'AccessToken','*','*','ALLOW','ROLE','developer'),(293,'RoleInherit','*','*','ALLOW','ROLE','it'),(294,'RoleRole','*','*','ALLOW','ROLE','it'),(295,'AccountConfig','*','*','ALLOW','ROLE','sysadmin'),(296,'Collection','*','READ','ALLOW','ROLE','employee'),(297,'Sale','refund','WRITE','ALLOW','ROLE','invoicing'),(298,'InvoiceInDueDay','*','*','ALLOW','ROLE','administrative'),(299,'Collection','setSaleQuantity','*','ALLOW','ROLE','employee'),(302,'AgencyTerm','*','*','ALLOW','ROLE','administrative'),(303,'ClaimLog','*','READ','ALLOW','ROLE','claimManager'),(304,'Edi','updateData','WRITE','ALLOW','ROLE','employee'),(305,'EducationLevel','*','*','ALLOW','ROLE','employee'),(306,'InvoiceInIntrastat','*','*','ALLOW','ROLE','employee'),(307,'SupplierAgencyTerm','*','*','ALLOW','ROLE','administrative'),(308,'InvoiceInIntrastat','*','*','ALLOW','ROLE','employee'),(309,'Zone','getZoneClosing','*','ALLOW','ROLE','employee'),(310,'ExpeditionState','*','READ','ALLOW','ROLE','employee'),(311,'Expense','*','READ','ALLOW','ROLE','employee'),(312,'Expense','*','WRITE','ALLOW','ROLE','administrative'),(314,'SupplierActivity','*','READ','ALLOW','ROLE','employee'),(315,'SupplierActivity','*','WRITE','ALLOW','ROLE','administrative'),(316,'Dms','deleteTrashFiles','WRITE','ALLOW','ROLE','employee'),(317,'ClientUnpaid','*','*','ALLOW','ROLE','administrative'),(318,'MdbVersion','*','*','ALLOW','ROLE','developer'),(319,'ItemType','*','READ','ALLOW','ROLE','employee'),(320,'ItemType','*','WRITE','ALLOW','ROLE','buyer'),(321,'InvoiceOut','refund','WRITE','ALLOW','ROLE','invoicing'),(322,'InvoiceOut','refund','WRITE','ALLOW','ROLE','salesAssistant'),(323,'InvoiceOut','refund','WRITE','ALLOW','ROLE','claimManager'),(324,'Ticket','refund','WRITE','ALLOW','ROLE','invoicing'),(325,'Ticket','refund','WRITE','ALLOW','ROLE','salesAssistant'),(326,'Ticket','refund','WRITE','ALLOW','ROLE','claimManager'),(327,'Sale','refund','WRITE','ALLOW','ROLE','salesAssistant'),(328,'Sale','refund','WRITE','ALLOW','ROLE','claimManager'),(329,'TicketRefund','*','WRITE','ALLOW','ROLE','invoicing'),(330,'ClaimObservation','*','WRITE','ALLOW','ROLE','salesPerson'),(331,'ClaimObservation','*','READ','ALLOW','ROLE','salesPerson'),(332,'Client','setPassword','WRITE','ALLOW','ROLE','salesPerson'),(333,'Client','updateUser','WRITE','ALLOW','ROLE','salesPerson'),(334,'ShelvingLog','*','READ','ALLOW','ROLE','employee'),(335,'ZoneExclusionGeo','*','READ','ALLOW','ROLE','employee'),(336,'ZoneExclusionGeo','*','WRITE','ALLOW','ROLE','deliveryAssistant'),(337,'Parking','*','*','ALLOW','ROLE','employee'),(338,'Shelving','*','*','ALLOW','ROLE','employee'),(339,'OsTicket','*','*','ALLOW','ROLE','employee'),(340,'OsTicketConfig','*','*','ALLOW','ROLE','it'),(341,'ClientConsumptionQueue','*','WRITE','ALLOW','ROLE','employee'),(342,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','employee'),(343,'Ticket','deliveryNoteEmail','WRITE','ALLOW','ROLE','employee'),(344,'Ticket','deliveryNoteCsvPdf','READ','ALLOW','ROLE','employee'),(345,'Ticket','deliveryNoteCsvEmail','READ','ALLOW','ROLE','employee'),(346,'Client','campaignMetricsPdf','READ','ALLOW','ROLE','employee'),(347,'Client','campaignMetricsEmail','WRITE','ALLOW','ROLE','employee'),(348,'Client','clientWelcomeHtml','READ','ALLOW','ROLE','employee'),(349,'Client','clientWelcomeEmail','WRITE','ALLOW','ROLE','employee'),(350,'Client','creditRequestPdf','READ','ALLOW','ROLE','employee'),(351,'Client','creditRequestHtml','READ','ALLOW','ROLE','employee'),(352,'Client','creditRequestEmail','WRITE','ALLOW','ROLE','employee'),(353,'Client','printerSetupHtml','READ','ALLOW','ROLE','employee'),(354,'Client','printerSetupEmail','WRITE','ALLOW','ROLE','employee'),(355,'Client','sepaCoreEmail','WRITE','ALLOW','ROLE','employee'),(356,'Client','letterDebtorPdf','READ','ALLOW','ROLE','employee'),(357,'Client','letterDebtorStHtml','READ','ALLOW','ROLE','employee'),(358,'Client','letterDebtorStEmail','WRITE','ALLOW','ROLE','employee'),(359,'Client','letterDebtorNdHtml','READ','ALLOW','ROLE','employee'),(360,'Client','letterDebtorNdEmail','WRITE','ALLOW','ROLE','employee'),(361,'Client','clientDebtStatementPdf','READ','ALLOW','ROLE','employee'),(362,'Client','clientDebtStatementHtml','READ','ALLOW','ROLE','employee'),(363,'Client','clientDebtStatementEmail','WRITE','ALLOW','ROLE','employee'),(364,'Client','incotermsAuthorizationPdf','READ','ALLOW','ROLE','employee'),(365,'Client','incotermsAuthorizationHtml','READ','ALLOW','ROLE','employee'),(366,'Client','incotermsAuthorizationEmail','WRITE','ALLOW','ROLE','employee'),(367,'Client','consumptionSendQueued','WRITE','ALLOW','ROLE','system'),(368,'InvoiceOut','invoiceEmail','WRITE','ALLOW','ROLE','employee'),(369,'InvoiceOut','exportationPdf','READ','ALLOW','ROLE','employee'),(370,'InvoiceOut','sendQueued','WRITE','ALLOW','ROLE','system'),(371,'Ticket','invoiceCsvPdf','READ','ALLOW','ROLE','employee'),(372,'Ticket','invoiceCsvEmail','WRITE','ALLOW','ROLE','employee'),(373,'Supplier','campaignMetricsPdf','READ','ALLOW','ROLE','employee'),(374,'Supplier','campaignMetricsEmail','WRITE','ALLOW','ROLE','employee'),(375,'Travel','extraCommunityPdf','READ','ALLOW','ROLE','employee'),(376,'Travel','extraCommunityEmail','WRITE','ALLOW','ROLE','employee'),(377,'Entry','entryOrderPdf','READ','ALLOW','ROLE','employee'),(378,'OsTicket','osTicketReportEmail','WRITE','ALLOW','ROLE','system'),(379,'Item','buyerWasteEmail','WRITE','ALLOW','ROLE','system'),(380,'Claim','claimPickupPdf','READ','ALLOW','ROLE','employee'),(381,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','claimManager'),(382,'Item','labelPdf','READ','ALLOW','ROLE','employee'),(383,'Sector','*','READ','ALLOW','ROLE','employee'),(384,'Sector','*','WRITE','ALLOW','ROLE','employee'),(385,'Route','driverRoutePdf','READ','ALLOW','ROLE','employee'),(386,'Route','driverRouteEmail','WRITE','ALLOW','ROLE','employee'),(387,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','customer'),(388,'Supplier','newSupplier','WRITE','ALLOW','ROLE','administrative'),(389,'ClaimRma','*','READ','ALLOW','ROLE','claimManager'),(390,'ClaimRma','*','WRITE','ALLOW','ROLE','claimManager'),(391,'Notification','*','WRITE','ALLOW','ROLE','system'),(392,'Boxing','*','*','ALLOW','ROLE','employee'),(393,'Url','*','READ','ALLOW','ROLE','employee'),(394,'Url','*','WRITE','ALLOW','ROLE','it'),(395,'ItemShelving','*','READ','ALLOW','ROLE','employee'),(396,'ItemShelving','*','WRITE','ALLOW','ROLE','production'),(397,'ItemShelvingPlacementSupplyStock','*','READ','ALLOW','ROLE','employee'),(398,'NotificationQueue','*','*','ALLOW','ROLE','employee'),(399,'InvoiceOut','clientsToInvoice','WRITE','ALLOW','ROLE','invoicing'),(400,'InvoiceOut','invoiceClient','WRITE','ALLOW','ROLE','invoicing'),(401,'Sale','editTracked','WRITE','ALLOW','ROLE','production'),(402,'Sale','editFloramondo','WRITE','ALLOW','ROLE','salesAssistant'),(403,'Receipt','balanceCompensationEmail','WRITE','ALLOW','ROLE','employee'),(404,'Receipt','balanceCompensationPdf','READ','ALLOW','ROLE','employee'),(405,'Ticket','getTicketsFuture','READ','ALLOW','ROLE','employee'),(406,'Ticket','merge','WRITE','ALLOW','ROLE','employee'),(407,'Sale','editFloramondo','WRITE','ALLOW','ROLE','logistic'),(408,'ZipConfig','*','*','ALLOW','ROLE','employee'),(409,'Item','*','WRITE','ALLOW','ROLE','administrative'),(410,'Sale','editCloned','WRITE','ALLOW','ROLE','buyer'),(411,'Sale','editCloned','WRITE','ALLOW','ROLE','salesAssistant'),(414,'MdbVersion','*','READ','ALLOW','ROLE','$everyone'),(416,'TicketLog','getChanges','READ','ALLOW','ROLE','employee'),(417,'Ticket','getTicketsAdvance','READ','ALLOW','ROLE','employee'),(418,'EntryLog','*','READ','ALLOW','ROLE','administrative'),(419,'Sale','editTracked','WRITE','ALLOW','ROLE','buyer'),(420,'MdbBranch','*','READ','ALLOW','ROLE','$everyone'),(421,'ItemShelvingSale','*','*','ALLOW','ROLE','employee'),(422,'Docuware','checkFile','READ','ALLOW','ROLE','employee'),(423,'Docuware','download','READ','ALLOW','ROLE','salesPerson'),(424,'Docuware','upload','WRITE','ALLOW','ROLE','productionAssi'),(425,'Docuware','deliveryNoteEmail','WRITE','ALLOW','ROLE','salesPerson'),(426,'TpvTransaction','confirm','WRITE','ALLOW','ROLE','$everyone'),(427,'TpvTransaction','start','WRITE','ALLOW','ROLE','$authenticated'),(428,'TpvTransaction','end','WRITE','ALLOW','ROLE','$authenticated'),(429,'ItemConfig','*','READ','ALLOW','ROLE','employee'),(431,'Tag','onSubmit','WRITE','ALLOW','ROLE','employee'),(432,'Worker','updateAttributes','WRITE','ALLOW','ROLE','hr'),(433,'Worker','createAbsence','*','ALLOW','ROLE','employee'),(434,'Worker','updateAbsence','WRITE','ALLOW','ROLE','employee'),(435,'Worker','deleteAbsence','*','ALLOW','ROLE','employee'),(436,'Worker','new','WRITE','ALLOW','ROLE','hr'),(438,'Client','getClientOrSupplierReference','READ','ALLOW','ROLE','employee'),(439,'NotificationSubscription','*','*','ALLOW','ROLE','employee'),(440,'NotificationAcl','*','READ','ALLOW','ROLE','employee'),(441,'MdbApp','*','READ','ALLOW','ROLE','$everyone'),(442,'MdbApp','*','*','ALLOW','ROLE','developer'),(443,'ItemConfig','*','*','ALLOW','ROLE','employee'),(444,'DeviceProduction','*','*','ALLOW','ROLE','hr'),(445,'DeviceProductionModels','*','*','ALLOW','ROLE','hr'),(446,'DeviceProductionState','*','*','ALLOW','ROLE','hr'),(447,'DeviceProductionUser','*','*','ALLOW','ROLE','hr'),(448,'DeviceProduction','*','*','ALLOW','ROLE','productionAssi'),(449,'DeviceProductionModels','*','*','ALLOW','ROLE','productionAssi'),(450,'DeviceProductionState','*','*','ALLOW','ROLE','productionAssi'),(451,'DeviceProductionUser','*','*','ALLOW','ROLE','productionAssi'),(452,'Worker','deallocatePDA','*','ALLOW','ROLE','hr'),(453,'Worker','allocatePDA','*','ALLOW','ROLE','hr'),(454,'Worker','deallocatePDA','*','ALLOW','ROLE','productionAssi'),(455,'Worker','allocatePDA','*','ALLOW','ROLE','productionAssi'),(456,'Zone','*','*','ALLOW','ROLE','deliveryAssistant'),(458,'Operator','*','READ','ALLOW','ROLE','employee'),(459,'Operator','*','WRITE','ALLOW','ROLE','employee'),(460,'InvoiceIn','getSerial','READ','ALLOW','ROLE','administrative'),(461,'Ticket','saveSign','WRITE','ALLOW','ROLE','employee'),(462,'InvoiceOut','negativeBases','READ','ALLOW','ROLE','administrative'),(463,'InvoiceOut','negativeBasesCsv','READ','ALLOW','ROLE','administrative'),(464,'WorkerObservation','*','*','ALLOW','ROLE','hr'),(465,'ClientInforma','*','READ','ALLOW','ROLE','employee'),(466,'ClientInforma','*','WRITE','ALLOW','ROLE','financial'),(467,'Receipt','receiptEmail','*','ALLOW','ROLE','salesAssistant'),(468,'Client','setRating','WRITE','ALLOW','ROLE','financial'),(470,'Client','addressesPropagateRe','*','ALLOW','ROLE','employee'),(471,'Client','canBeInvoiced','*','ALLOW','ROLE','employee'),(472,'Client','canCreateTicket','*','ALLOW','ROLE','employee'),(473,'Client','consumption','*','ALLOW','ROLE','employee'),(474,'Client','createAddress','*','ALLOW','ROLE','employee'),(475,'Client','createWithUser','*','ALLOW','ROLE','employee'),(476,'Client','extendedListFilter','*','ALLOW','ROLE','employee'),(477,'Client','getAverageInvoiced','*','ALLOW','ROLE','employee'),(478,'Client','getCard','*','ALLOW','ROLE','employee'),(479,'Client','getDebt','*','ALLOW','ROLE','employee'),(480,'Client','getMana','*','ALLOW','ROLE','employee'),(481,'Client','transactions','*','ALLOW','ROLE','employee'),(482,'Client','hasCustomerRole','*','ALLOW','ROLE','employee'),(483,'Client','isValidClient','*','ALLOW','ROLE','employee'),(484,'Client','lastActiveTickets','*','ALLOW','ROLE','employee'),(485,'Client','sendSms','*','ALLOW','ROLE','employee'),(486,'Client','setPassword','*','ALLOW','ROLE','employee'),(487,'Client','summary','*','ALLOW','ROLE','employee'),(488,'Client','updateAddress','*','ALLOW','ROLE','employee'),(489,'Client','updateFiscalData','*','ALLOW','ROLE','employee'),(491,'Client','uploadFile','*','ALLOW','ROLE','employee'),(492,'Client','campaignMetricsPdf','*','ALLOW','ROLE','employee'),(493,'Client','campaignMetricsEmail','*','ALLOW','ROLE','employee'),(494,'Client','clientWelcomeHtml','*','ALLOW','ROLE','employee'),(495,'Client','clientWelcomeEmail','*','ALLOW','ROLE','employee'),(496,'Client','printerSetupHtml','*','ALLOW','ROLE','employee'),(497,'Client','printerSetupEmail','*','ALLOW','ROLE','employee'),(498,'Client','sepaCoreEmail','*','ALLOW','ROLE','employee'),(499,'Client','letterDebtorPdf','*','ALLOW','ROLE','employee'),(500,'Client','letterDebtorStHtml','*','ALLOW','ROLE','employee'),(501,'Client','letterDebtorStEmail','*','ALLOW','ROLE','employee'),(502,'Client','letterDebtorNdHtml','*','ALLOW','ROLE','employee'),(503,'Client','letterDebtorNdEmail','*','ALLOW','ROLE','employee'),(504,'Client','clientDebtStatementPdf','*','ALLOW','ROLE','employee'),(505,'Client','clientDebtStatementHtml','*','ALLOW','ROLE','employee'),(506,'Client','clientDebtStatementEmail','*','ALLOW','ROLE','employee'),(507,'Client','creditRequestPdf','*','ALLOW','ROLE','employee'),(508,'Client','creditRequestHtml','*','ALLOW','ROLE','employee'),(509,'Client','creditRequestEmail','*','ALLOW','ROLE','employee'),(510,'Client','incotermsAuthorizationPdf','*','ALLOW','ROLE','employee'),(511,'Client','incotermsAuthorizationHtml','*','ALLOW','ROLE','employee'),(512,'Client','incotermsAuthorizationEmail','*','ALLOW','ROLE','employee'),(513,'Client','consumptionSendQueued','*','ALLOW','ROLE','employee'),(514,'Client','filter','*','ALLOW','ROLE','employee'),(515,'Client','getClientOrSupplierReference','*','ALLOW','ROLE','employee'),(516,'Client','upsert','*','ALLOW','ROLE','employee'),(518,'Client','replaceById','*','ALLOW','ROLE','employee'),(519,'Client','updateAttributes','*','ALLOW','ROLE','employee'),(520,'Client','updateAttributes','*','ALLOW','ROLE','employee'),(521,'Client','deleteById','*','ALLOW','ROLE','employee'),(522,'Client','replaceOrCreate','*','ALLOW','ROLE','employee'),(523,'Client','updateAll','*','ALLOW','ROLE','employee'),(524,'Client','upsertWithWhere','*','ALLOW','ROLE','employee'),(525,'Defaulter','observationEmail','WRITE','ALLOW','ROLE','employee'),(527,'VnUser','acl','READ','ALLOW','ROLE','account'),(528,'VnUser','getCurrentUserData','READ','ALLOW','ROLE','account'),(530,'Account','exists','READ','ALLOW','ROLE','account'),(531,'Account','exists','READ','ALLOW','ROLE','account'),(532,'UserLog','*','READ','ALLOW','ROLE','employee'),(533,'RoleLog','*','READ','ALLOW','ROLE','employee'),(534,'WagonType','*','*','ALLOW','ROLE','productionAssi'),(535,'WagonTypeColor','*','*','ALLOW','ROLE','productionAssi'),(536,'WagonTypeTray','*','*','ALLOW','ROLE','productionAssi'),(537,'WagonConfig','*','*','ALLOW','ROLE','productionAssi'),(538,'CollectionWagon','*','*','ALLOW','ROLE','productionAssi'),(539,'CollectionWagonTicket','*','*','ALLOW','ROLE','productionAssi'),(540,'Wagon','*','*','ALLOW','ROLE','productionAssi'),(541,'WagonType','createWagonType','*','ALLOW','ROLE','productionAssi'),(542,'WagonType','deleteWagonType','*','ALLOW','ROLE','productionAssi'),(543,'WagonType','editWagonType','*','ALLOW','ROLE','productionAssi'),(544,'Docuware','deliveryNoteEmail','WRITE','ALLOW','ROLE','employee'),(545,'Agency','find','READ','ALLOW','ROLE','employee'),(546,'Agency','seeExpired','READ','ALLOW','ROLE','coolerAssist'),(547,'WorkerLog','models','READ','ALLOW','ROLE','hr'),(548,'Ticket','editDiscount','WRITE','ALLOW','ROLE','claimManager'),(549,'Ticket','editDiscount','WRITE','ALLOW','ROLE','salesPerson'),(550,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','salesAssistant'),(551,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','deliveryAssistant'),(552,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','buyer'),(553,'Ticket','isRoleAdvanced','*','ALLOW','ROLE','claimManager'),(554,'Ticket','deleteTicketWithPartPrepared','WRITE','ALLOW','ROLE','salesAssistant'),(555,'Ticket','editZone','WRITE','ALLOW','ROLE','deliveryAssistant'),(556,'State','editableStates','READ','ALLOW','ROLE','employee'),(557,'State','seeEditableStates','READ','ALLOW','ROLE','administrative'),(558,'State','seeEditableStates','READ','ALLOW','ROLE','production'),(559,'State','isSomeEditable','READ','ALLOW','ROLE','salesPerson'),(560,'State','isAllEditable','READ','ALLOW','ROLE','production'),(561,'State','isAllEditable','READ','ALLOW','ROLE','administrative'),(562,'Agency','seeExpired','READ','ALLOW','ROLE','administrative'),(563,'Agency','seeExpired','READ','ALLOW','ROLE','productionBoss'),(564,'Claim','createAfterDeadline','WRITE','ALLOW','ROLE','claimManager'),(565,'Client','editAddressLogifloraAllowed','WRITE','ALLOW','ROLE','salesAssistant'),(566,'Client','editFiscalDataWithoutTaxDataCheck','WRITE','ALLOW','ROLE','salesAssistant'),(567,'Client','editVerifiedDataWithoutTaxDataCheck','WRITE','ALLOW','ROLE','salesAssistant'),(568,'Client','editCredit','WRITE','ALLOW','ROLE','financialBoss'),(569,'Client','zeroCreditEditor','WRITE','ALLOW','ROLE','financialBoss'),(570,'InvoiceOut','canCreatePdf','WRITE','ALLOW','ROLE','invoicing'),(571,'Supplier','editPayMethodCheck','WRITE','ALLOW','ROLE','financial'),(572,'Worker','isTeamBoss','WRITE','ALLOW','ROLE','teamBoss'),(573,'Worker','forceIsSubordinate','READ','ALLOW','ROLE','hr'),(574,'Claim','editState','WRITE','ALLOW','ROLE','claimManager'),(577,'Claim','findOne','READ','ALLOW','ROLE','salesPerson'),(579,'Claim','updateClaim','WRITE','ALLOW','ROLE','salesPerson'),(580,'Claim','regularizeClaim','WRITE','ALLOW','ROLE','claimManager'),(581,'Claim','updateClaimDestination','WRITE','ALLOW','ROLE','claimManager'),(582,'Claim','downloadFile','READ','ALLOW','ROLE','claimManager'),(583,'Claim','deleteById','WRITE','ALLOW','ROLE','claimManager'),(585,'Claim','logs','READ','ALLOW','ROLE','claimManager'),(586,'Ticket','find','READ','ALLOW','ROLE','employee'),(587,'Ticket','findById','READ','ALLOW','ROLE','employee'),(588,'Ticket','findOne','READ','ALLOW','ROLE','employee'),(589,'Ticket','getVolume','READ','ALLOW','ROLE','employee'),(590,'Ticket','getTotalVolume','READ','ALLOW','ROLE','employee'),(591,'Ticket','summary','READ','ALLOW','ROLE','employee'),(592,'Ticket','priceDifference','READ','ALLOW','ROLE','employee'),(593,'Ticket','componentUpdate','WRITE','ALLOW','ROLE','employee'),(594,'Ticket','new','WRITE','ALLOW','ROLE','employee'),(595,'Ticket','isEditable','READ','ALLOW','ROLE','employee'),(596,'Ticket','setDeleted','WRITE','ALLOW','ROLE','salesPerson'),(597,'Ticket','restore','WRITE','ALLOW','ROLE','employee'),(598,'Ticket','getSales','READ','ALLOW','ROLE','employee'),(599,'Ticket','getSalesPersonMana','READ','ALLOW','ROLE','employee'),(600,'Ticket','filter','READ','ALLOW','ROLE','employee'),(601,'Ticket','makeInvoice','WRITE','ALLOW','ROLE','employee'),(602,'Ticket','updateEditableTicket','WRITE','ALLOW','ROLE','employee'),(603,'Ticket','updateDiscount','WRITE','ALLOW','ROLE','employee'),(604,'Ticket','transferSales','WRITE','ALLOW','ROLE','employee'),(605,'Ticket','sendSms','WRITE','ALLOW','ROLE','employee'),(606,'Ticket','isLocked','READ','ALLOW','ROLE','employee'),(607,'Ticket','freightCost','READ','ALLOW','ROLE','employee'),(608,'Ticket','getComponentsSum','READ','ALLOW','ROLE','employee'),(609,'Ticket','updateAttributes','WRITE','ALLOW','ROLE','delivery'),(610,'Ticket','deliveryNoteCsv','READ','ALLOW','ROLE','employee'),(611,'State','find','READ','ALLOW','ROLE','employee'),(612,'State','findById','READ','ALLOW','ROLE','employee'),(613,'State','findOne','READ','ALLOW','ROLE','employee'),(614,'Worker','find','READ','ALLOW','ROLE','employee'),(615,'Worker','findById','READ','ALLOW','ROLE','employee'),(616,'Worker','findOne','READ','ALLOW','ROLE','employee'),(617,'Worker','filter','READ','ALLOW','ROLE','employee'),(618,'Worker','getWorkedHours','READ','ALLOW','ROLE','employee'),(619,'Worker','active','READ','ALLOW','ROLE','employee'),(620,'Worker','activeWithRole','READ','ALLOW','ROLE','employee'),(621,'Worker','uploadFile','WRITE','ALLOW','ROLE','hr'),(622,'Worker','contracts','READ','ALLOW','ROLE','employee'),(623,'Worker','holidays','READ','ALLOW','ROLE','employee'),(624,'Worker','activeContract','READ','ALLOW','ROLE','employee'),(625,'Worker','activeWithInheritedRole','READ','ALLOW','ROLE','employee'),(626,'Ticket','collectionLabel','READ','ALLOW','ROLE','employee'),(628,'Ticket','expeditionPalletLabel','READ','ALLOW','ROLE','employee'),(629,'Ticket','editDiscount','WRITE','ALLOW','ROLE','artificialBoss'),(630,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','salesTeamBoss'),(635,'Ticket','updateAttributes','WRITE','ALLOW','ROLE','administrative'),(636,'Claim','claimPickupEmail','WRITE','ALLOW','ROLE','salesPerson'),(637,'Claim','downloadFile','READ','ALLOW','ROLE','salesPerson'),(638,'Agency','seeExpired','READ','ALLOW','ROLE','artificialBoss'),(639,'Agency','seeExpired','READ','ALLOW','ROLE','logisticAssistant'),(654,'Ticket','editZone','WRITE','ALLOW','ROLE','logisticAssistant'),(655,'Entry','addFromPackaging','WRITE','ALLOW','ROLE','production'),(656,'Entry','addFromBuy','WRITE','ALLOW','ROLE','production'),(657,'Supplier','getItemsPackaging','READ','ALLOW','ROLE','production'),(658,'Ticket','closeAll','WRITE','ALLOW','ROLE','system'),(659,'Account','*','*','ALLOW','ROLE','developerBoss'),(664,'MailForward','*','*','ALLOW','ROLE','itManagement'),(665,'Role','*','READ','ALLOW','ROLE','employee'),(666,'Role','*','WRITE','ALLOW','ROLE','it'),(667,'VnUser','*','*','ALLOW','ROLE','itManagement'),(668,'VnUser','__get__preview','READ','ALLOW','ROLE','employee'),(669,'VnUser','preview','*','ALLOW','ROLE','employee'),(670,'VnUser','create','*','ALLOW','ROLE','itManagement'),(671,'VnUser','renewToken','WRITE','ALLOW','ROLE','employee'),(672,'PackingSiteAdvanced','*','*','ALLOW','ROLE','production'),(673,'InvoiceOut','makePdfAndNotify','WRITE','ALLOW','ROLE','invoicing'),(674,'InvoiceOutConfig','*','READ','ALLOW','ROLE','invoicing'),(676,'Ticket','invoiceTickets','WRITE','ALLOW','ROLE','employee'),(680,'MailAliasAccount','*','READ','ALLOW','ROLE','employee'),(681,'MailAliasAccount','create','WRITE','ALLOW','ROLE','employee'),(682,'MailAliasAccount','deleteById','WRITE','ALLOW','ROLE','employee'),(683,'MailAliasAccount','canEditAlias','WRITE','ALLOW','ROLE','itManagement'),(684,'WorkerDisableExcluded','*','READ','ALLOW','ROLE','itManagement'),(685,'WorkerDisableExcluded','*','WRITE','ALLOW','ROLE','itManagement'),(686,'MailForward','*','*','ALLOW','ROLE','hr'),(687,'ClientSms','find','READ','ALLOW','ROLE','employee'),(688,'ClientSms','create','WRITE','ALLOW','ROLE','employee'),(689,'Vehicle','sorted','WRITE','ALLOW','ROLE','employee'),(690,'Roadmap','*','*','ALLOW','ROLE','palletizerBoss'),(691,'Roadmap','*','*','ALLOW','ROLE','productionBoss'),(692,'ExpeditionTruck','*','*','ALLOW','ROLE','palletizerBoss'),(693,'ExpeditionTruck','*','*','ALLOW','ROLE','productionBoss'),(694,'MailAliasAccount','canEditAlias','WRITE','ALLOW','ROLE','marketingBoss'),(695,'ViaexpressConfig','internationalExpedition','WRITE','ALLOW','ROLE','employee'),(696,'ViaexpressConfig','renderer','READ','ALLOW','ROLE','employee'),(697,'Ticket','transferClient','WRITE','ALLOW','ROLE','administrative'),(698,'Ticket','canEditWeekly','WRITE','ALLOW','ROLE','buyer'),(699,'TicketSms','find','READ','ALLOW','ROLE','salesPerson'),(701,'Docuware','upload','WRITE','ALLOW','ROLE','deliveryAssistant'),(702,'Ticket','docuwareDownload','READ','ALLOW','ROLE','salesPerson'),(703,'Worker','search','READ','ALLOW','ROLE','employee'),(704,'ExpeditionState','addExpeditionState','WRITE','ALLOW','ROLE','delivery'),(705,'SaleGroupDetail','deleteById','WRITE','ALLOW','ROLE','employee'),(706,'Ticket','setDeleted','WRITE','ALLOW','ROLE','buyer'),(707,'DeviceLog','create','WRITE','ALLOW','ROLE','employee'),(708,'Collection','getTickets','WRITE','ALLOW','ROLE','employee'),(709,'Client','findOne','READ','ALLOW','ROLE','employee'),(710,'Client','findById','READ','ALLOW','ROLE','employee'),(711,'Client','find','READ','ALLOW','ROLE','employee'),(712,'Client','exists','READ','ALLOW','ROLE','employee'),(713,'Client','__get__addresses','READ','ALLOW','ROLE','employee'),(714,'ExpeditionMistakeType','*','READ','ALLOW','ROLE','employee'),(715,'WorkerMistakeType','*','READ','ALLOW','ROLE','employee'),(716,'ExpeditionMistake','*','WRITE','ALLOW','ROLE','employee'),(717,'WorkerMistake','*','WRITE','ALLOW','ROLE','coolerBoss'),(718,'MistakesTypes','*','WRITE','ALLOW','ROLE','coolerBoss'),(719,'MistakeType','*','READ','ALLOW','ROLE','employee'),(720,'MachineWorker','*','READ','ALLOW','ROLE','coolerAssist'),(721,'Printer','*','READ','ALLOW','ROLE','employee'),(722,'SaleMistake','*','WRITE','ALLOW','ROLE','production'),(723,'Item','setVisibleDiscard','WRITE','ALLOW','ROLE','employee'),(724,'Address','getAddress','READ','ALLOW','ROLE','employee'),(725,'Account','findOne','READ','ALLOW','ROLE','employee'),(726,'Account','findById','READ','ALLOW','ROLE','employee'),(727,'Account','find','READ','ALLOW','ROLE','employee'),(728,'Account','exists','READ','ALLOW','ROLE','employee'),(729,'Sale','refund','WRITE','ALLOW','ROLE','buyer'),(730,'Ticket','setDeleted','WRITE','ALLOW','ROLE','deliveryAssistant'),(732,'Sale','isInPreparing','*','ALLOW','ROLE','production'),(733,'Train','*','READ','ALLOW','ROLE','production'),(734,'WorkerDepartment','*','*','ALLOW','ROLE','employee'),(735,'VnUser','higherPrivileges','*','ALLOW','ROLE','itManagement'),(736,'VnUser','mediumPrivileges','*','ALLOW','ROLE','hr'),(737,'VnUser','updateUser','*','ALLOW','ROLE','employee'),(738,'TicketCollection','*','WRITE','ALLOW','ROLE','production'),(739,'Worker','setPassword','*','ALLOW','ROLE','employee'),(740,'Url','getByUser','READ','ALLOW','ROLE','$everyone'),(741,'Claim','__get__lines','READ','ALLOW','ROLE','claimViewer'),(742,'AddressShortage','*','READ','ALLOW','ROLE','production'),(743,'Claim','filter','READ','ALLOW','ROLE','claimViewer'),(744,'Claim','find','READ','ALLOW','ROLE','claimViewer'),(745,'Claim','findById','READ','ALLOW','ROLE','claimViewer'),(746,'Claim','getSummary','READ','ALLOW','ROLE','claimViewer'),(747,'CplusRectificationType','*','READ','ALLOW','ROLE','administrative'),(748,'SiiTypeInvoiceOut','*','READ','ALLOW','ROLE','administrative'),(749,'InvoiceCorrectionType','*','READ','ALLOW','ROLE','administrative'),(750,'InvoiceOut','transferInvoice','WRITE','ALLOW','ROLE','administrative'); /*!40000 ALTER TABLE `ACL` ENABLE KEYS */; UNLOCK TABLES; @@ -206,7 +206,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2023-08-30 15:53:15 +-- Dump completed on 2023-11-20 12:26:42 USE `vn`; -- MariaDB dump 10.19 Distrib 10.5.19-MariaDB, for debian-linux-gnu (x86_64) -- @@ -265,13 +265,13 @@ INSERT INTO `businessType` VALUES ('decoration','Decoración'),('events','Evento UNLOCK TABLES; -- --- Dumping data for table `cplusInvoiceType472` +-- Dumping data for table `siiTypeInvoiceIn` -- -LOCK TABLES `cplusInvoiceType472` WRITE; -/*!40000 ALTER TABLE `cplusInvoiceType472` DISABLE KEYS */; -INSERT INTO `cplusInvoiceType472` VALUES (1,'F1 - Factura'),(2,'F2 - Factura simplificada (ticket)'),(3,'F3 - Factura emitida en sustitución de facturas simplificadas facturadas y declaradas'),(4,'F4 - Asiento resumen de facturas'),(5,'F5 - Importaciones (DUA)'),(6,'F6 - Otros justificantes contables'),(7,'R1 - Factura rectificativa (Art. 80.1, 80.2 y error fundado en derecho)'),(8,'R2 - Factura rectificativa (Art. 80.3)'),(9,'R3 - Factura rectificativa (Art. 80.4)'),(10,'R4 - Factura rectificativa (Resto)'),(11,'R5 - Factura rectificativa en facturas simplificadas'); -/*!40000 ALTER TABLE `cplusInvoiceType472` ENABLE KEYS */; +LOCK TABLES `siiTypeInvoiceIn` WRITE; +/*!40000 ALTER TABLE `siiTypeInvoiceIn` DISABLE KEYS */; +INSERT INTO `siiTypeInvoiceIn` VALUES (1,'F1','Factura'),(2,'F2','Factura simplificada (ticket)'),(3,'F3','Factura emitida en sustitución de facturas simplificadas facturadas y declaradas'),(4,'F4','Asiento resumen de facturas'),(5,'F5','Importaciones (DUA)'),(6,'F6','Otros justificantes contables'),(7,'R1','Factura rectificativa (Art. 80.1, 80.2 y error fundado en derecho)'),(8,'R2','Factura rectificativa (Art. 80.3)'),(9,'R3','Factura rectificativa (Art. 80.4)'),(10,'R4','Factura rectificativa (Resto)'),(11,'R5','Factura rectificativa en facturas simplificadas'); +/*!40000 ALTER TABLE `siiTypeInvoiceIn` ENABLE KEYS */; UNLOCK TABLES; -- @@ -280,7 +280,7 @@ UNLOCK TABLES; LOCK TABLES `siiTypeInvoiceOut` WRITE; /*!40000 ALTER TABLE `siiTypeInvoiceOut` DISABLE KEYS */; -INSERT INTO `siiTypeInvoiceOut` VALUES (1,'F1 - Factura'),(2,'F2 - Factura simplificada (ticket)'),(3,'F3 - Factura emitida en sustitución de facturas simplificadas facturadas y declaradas'),(4,'F4 - Asiento resumen de facturas'),(5,'R1 - Factura rectificativa (Art. 80.1, 80.2 y error fundado en derecho)'),(6,'R2 - Factura rectificativa (Art. 80.3)'),(7,'R3 - Factura rectificativa (Art. 80.4)'),(8,'R4 - Factura rectificativa (Resto)'),(9,'R5 - Factura rectificativa en facturas simplificadas'); +INSERT INTO `siiTypeInvoiceOut` VALUES (1,'F1','Factura'),(2,'F2','Factura simplificada (ticket)'),(3,'F3','Factura emitida en sustitución de facturas simplificadas facturadas y declaradas'),(4,'F4','Asiento resumen de facturas'),(5,'R1','Factura rectificativa (Art. 80.1, 80.2 y error fundado en derecho)'),(6,'R2','Factura rectificativa (Art. 80.3)'),(7,'R3','Factura rectificativa (Art. 80.4)'),(8,'R4','Factura rectificativa (Resto)'),(9,'R5','Factura rectificativa en facturas simplificadas'); /*!40000 ALTER TABLE `siiTypeInvoiceOut` ENABLE KEYS */; UNLOCK TABLES; @@ -315,13 +315,13 @@ INSERT INTO `cplusTaxBreak` VALUES (1,'Campo vacio'),(2,'E1 - Exenta por el art UNLOCK TABLES; -- --- Dumping data for table `cplusTrascendency472` +-- Dumping data for table `siiTrascendencyInvoiceIn` -- -LOCK TABLES `cplusTrascendency472` WRITE; -/*!40000 ALTER TABLE `cplusTrascendency472` DISABLE KEYS */; -INSERT INTO `cplusTrascendency472` VALUES (1,'01 - Operación de régimen general'),(2,'02 - Operaciones por las que los empresarios satisfacen compensaciones REAGYP'),(3,'03 - Operaciones a las que se aplique el régimen especial de bienes usados, objetos de arte, antigüedades y objetos de colección (135 - 139 de LIVA)'),(4,'04 - Régimen especial oro de inversión'),(5,'05 - Régimen especial agencias de viajes'),(6,'06 - Régimen especial grupo de entidades en IVA (Nivel Avanzado)'),(7,'07 - Régimen especial criterio de caja'),(8,'08 - Operaciones sujetas al IPSI / IGIC'),(9,'09 - Adquisiciones intracomunitarias de bienes y prestaciones de servicios'),(10,'12 - Operaciones de arrendamiento de local de negocio'),(11,'13 - Factura correspondiente a una importación (informada sin asociar a un DUA)'),(12,'14 - Primer semestre 2017'); -/*!40000 ALTER TABLE `cplusTrascendency472` ENABLE KEYS */; +LOCK TABLES `siiTrascendencyInvoiceIn` WRITE; +/*!40000 ALTER TABLE `siiTrascendencyInvoiceIn` DISABLE KEYS */; +INSERT INTO `siiTrascendencyInvoiceIn` VALUES (1,'Operación de régimen general'),(2,'Operaciones por las que los empresarios satisfacen compensaciones REAGYP'),(3,'Operaciones a las que se aplique el régimen especial de bienes usados, objetos de arte, antigüedades y objetos de colección (135 - 139 de LIVA)'),(4,'Régimen especial oro de inversión'),(5,'Régimen especial agencias de viajes'),(6,'Régimen especial grupo de entidades en IVA (Nivel Avanzado)'),(7,'Régimen especial criterio de caja'),(8,'Operaciones sujetas al IPSI / IGIC'),(9,'Adquisiciones intracomunitarias de bienes y prestaciones de servicios'),(12,'Operaciones de arrendamiento de local de negocio'),(13,'Factura correspondiente a una importación (informada sin asociar a un DUA)'),(14,'Primer semestre 2017'); +/*!40000 ALTER TABLE `siiTrascendencyInvoiceIn` ENABLE KEYS */; UNLOCK TABLES; -- @@ -330,7 +330,7 @@ UNLOCK TABLES; LOCK TABLES `claimResponsible` WRITE; /*!40000 ALTER TABLE `claimResponsible` DISABLE KEYS */; -INSERT INTO `claimResponsible` VALUES (1,'Compradores',0),(2,'Proveedor',0),(3,'Entradores',0),(4,'Camareros',0),(6,'Sacadores',0),(7,'Revisadores',0),(8,'Calidad general',0),(9,'Encajadores',0),(10,'Clima',0),(11,'Comerciales',1),(12,'Clientes',1),(13,'Administración',0),(14,'Agencia',0),(15,'Repartidores',0),(16,'Informatica',0),(17,'Transp.origen',0),(18,'Confeccion',0),(19,'OTROS',0),(21,'Gerencia',0),(22,'Paletizadores',0),(23,'Preparación Previa',0),(24,'Almacén PCA',0),(25,'Huelga',0); +INSERT INTO `claimResponsible` VALUES (1,'Compradores',0,'buy'),(2,'Proveedor',0,'sup'),(3,'Entradores',0,'ent'),(4,'Camareros',0,'bar'),(6,'Sacadores',0,'pic'),(7,'Revisadores',0,'chk'),(8,'Calidad general',0,'qas'),(9,'Encajadores',0,'pck'),(10,'Clima',0,'wea'),(11,'Comerciales',1,'com'),(12,'Clientes',1,'cli'),(13,'Administración',0,'adm'),(14,'Agencia',0,'age'),(15,'Repartidores',0,'del'),(16,'Informatica',0,'ite'),(17,'Transp.origen',0,'tra'),(18,'Confeccion',0,'con'),(19,'OTROS',0,'oth'),(21,'Gerencia',0,'man'),(22,'Paletizadores',0,'pal'),(23,'Preparación Previa',0,'pre'),(24,'Almacén PCA',0,'war'),(25,'Huelga',0,'str'); /*!40000 ALTER TABLE `claimResponsible` ENABLE KEYS */; UNLOCK TABLES; @@ -400,7 +400,7 @@ UNLOCK TABLES; LOCK TABLES `department` WRITE; /*!40000 ALTER TABLE `department` DISABLE KEYS */; -INSERT INTO `department` VALUES (1,NULL,'VERDNATURA',1,104,763,0,0,0,0,30,NULL,'/',NULL,0,NULL,0,0,0,0,NULL,NULL),(22,'shopping','COMPRAS',2,3,NULL,72,0,0,1,0,1,'/1/',NULL,1,NULL,1,0,0,0,NULL,NULL),(23,'CMA','CAMARA',13,14,NULL,72,1,1,2,0,37,'/1/37/',NULL,0,NULL,0,1,1,1,NULL,NULL),(31,'it','INFORMATICA',4,5,NULL,72,0,0,1,0,1,'/1/','informatica-cau',1,NULL,1,0,0,0,NULL,NULL),(34,NULL,'CONTABILIDAD',6,7,NULL,0,0,0,1,0,1,'/1/',NULL,1,NULL,1,0,0,0,NULL,NULL),(35,NULL,'FINANZAS',8,9,NULL,0,0,0,1,0,1,'/1/',NULL,1,'begonya@verdnatura.es',1,0,0,0,NULL,NULL),(36,NULL,'LABORAL',10,11,NULL,0,0,0,1,0,1,'/1/',NULL,1,NULL,1,0,0,0,NULL,NULL),(37,'PROD','PRODUCCION',12,27,NULL,72,1,1,1,7,1,'/1/',NULL,0,NULL,0,1,1,1,NULL,NULL),(38,NULL,'SACADO',15,16,NULL,72,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,0,NULL,NULL),(39,NULL,'ENCAJADO',17,18,NULL,72,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,0,NULL,NULL),(41,NULL,'ADMINISTRACION',28,29,NULL,72,0,0,1,0,1,'/1/',NULL,1,NULL,1,0,0,0,NULL,NULL),(43,'VT','VENTAS',30,53,NULL,0,0,0,1,11,1,'/1/',NULL,1,'',1,0,0,0,NULL,NULL),(44,'management','GERENCIA',54,55,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL),(45,NULL,'LOGISTICA',56,57,NULL,72,0,0,1,0,1,'/1/',NULL,1,NULL,1,0,0,0,NULL,NULL),(46,'delivery','REPARTO',58,59,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,1,0,0,NULL,NULL),(48,NULL,'ALMACENAJE',60,61,NULL,0,1,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL),(49,NULL,'PROPIEDAD',62,63,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL),(52,NULL,'CARGA AEREA',64,65,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL),(53,NULL,'MARKETING Y COMUNICACIÓN',66,67,NULL,72,0,0,1,0,1,'/1/',NULL,1,NULL,1,0,0,0,NULL,NULL),(54,NULL,'ORNAMENTALES',68,69,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL),(55,NULL,'TALLER NATURAL',70,73,14548,72,0,0,1,1,1,'/1/',NULL,0,NULL,0,1,1,0,1118,NULL),(56,NULL,'TALLER ARTIFICIAL',71,72,8470,72,0,0,2,0,55,'/1/55/',NULL,0,NULL,0,1,1,0,1927,NULL),(58,'CMP','CAMPOS',74,77,NULL,72,0,0,1,1,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL),(59,NULL,'MANTENIMIENTO',78,79,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,1,0,0,NULL,NULL),(60,NULL,'RECLAMACIONES',80,81,NULL,72,0,0,1,0,1,'/1/',NULL,1,NULL,1,1,0,0,NULL,NULL),(61,NULL,'VNH',82,85,NULL,73,0,0,1,1,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL),(66,NULL,'VERDNAMADRID',86,87,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL),(68,NULL,'COMPLEMENTOS',19,20,NULL,72,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,1,0,0,NULL,NULL),(69,NULL,'VERDNABARNA',88,89,NULL,74,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL),(80,NULL,'EQUIPO J VALLES',31,32,4250,72,0,0,2,0,43,'/1/43/','jvp_equipo',1,'gestioncomercial@verdnatura.es',1,0,0,0,NULL,NULL),(86,NULL,'LIMPIEZA',90,91,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL),(89,NULL,'COORDINACION',92,93,NULL,0,1,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL),(90,NULL,'TRAILER',83,84,NULL,0,0,0,2,0,61,'/1/61/',NULL,0,NULL,0,0,0,0,NULL,NULL),(91,NULL,'ARTIFICIAL',21,22,NULL,0,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,0,NULL,NULL),(92,NULL,'EQUIPO SILVERIO',33,34,1203,0,0,0,2,0,43,'/1/43/','sdc_equipo',1,'gestioncomercial@verdnatura.es',1,0,0,0,NULL,NULL),(93,NULL,'CONFECCION',94,95,NULL,0,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,1,0,NULL,NULL),(94,NULL,'EQUIPO J BROCAL',35,36,3797,0,0,0,2,0,43,'/1/43/','jes_equipo',1,'gestioncomercial@verdnatura.es',1,0,0,0,NULL,NULL),(95,NULL,'EQUIPO C ZAMBRANO',37,38,4667,0,0,0,2,0,43,'/1/43/','czg_equipo',1,'gestioncomercial@verdnatura.es',1,0,0,0,NULL,NULL),(96,NULL,'EQUIPO C LOPEZ',39,40,4661,0,0,0,2,0,43,'/1/43/','cla_equipo',1,'gestioncomercial@verdnatura.es',1,0,0,0,NULL,NULL),(115,NULL,'EQUIPO CLAUDI',41,42,3810,0,0,0,2,0,43,'/1/43/','csr_equipo',1,'gestioncomercial@verdnatura.es',1,0,0,0,NULL,NULL),(123,NULL,'EQUIPO ELENA BASCUÑANA',43,44,7102,0,0,0,2,0,43,'/1/43/','ebt_equipo',1,'gestioncomercial@verdnatura.es',1,0,0,0,NULL,NULL),(124,NULL,'CONTROL INTERNO',96,97,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,1,0,0,0,NULL,NULL),(125,NULL,'EQUIPO MIRIAM MAR',45,46,1118,0,0,0,2,0,43,'/1/43/','mir_equipo',1,'gestioncomercial@verdnatura.es',1,0,0,0,NULL,NULL),(126,NULL,'PRESERVADO',98,99,NULL,0,0,0,1,0,1,'/1/',NULL,0,NULL,0,1,1,0,NULL,NULL),(128,NULL,'PALETIZADO',23,24,NULL,0,0,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,0,NULL,NULL),(130,NULL,'REVISION',25,26,NULL,0,0,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,0,NULL,NULL),(131,NULL,'INVERNADERO',75,76,NULL,0,0,0,2,0,58,'/1/58/',NULL,0,NULL,0,1,0,0,NULL,NULL),(132,NULL,'EQUIPO DC',47,48,1731,0,0,0,2,0,43,'/1/43/','dc_equipo',1,'gestioncomercial@verdnatura.es',1,0,0,0,NULL,NULL),(133,'franceTeam','EQUIPO FRANCIA',49,50,1731,72,0,0,2,0,43,'/1/43/','fra_equipo',1,'gestioncomercial@verdnatura.es',1,0,0,0,NULL,NULL),(134,NULL,'EQUIPO RODRI',51,52,6264,0,0,0,2,0,43,'/1/43/','rhr_equipo',1,'gestioncomercial@verdnatura.es',1,0,0,0,NULL,NULL),(135,'routers','ENRUTADORES',100,101,NULL,0,0,0,1,0,1,'/1/',NULL,1,NULL,0,0,0,0,NULL,NULL),(136,'heavyVehicles','VEHICULOS PESADOS',102,103,NULL,0,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL); +INSERT INTO `department` VALUES (1,'VN','VERDNATURA',1,106,763,0,0,0,0,31,NULL,'/',NULL,0,NULL,0,0,0,0,NULL,NULL),(22,'shopping','COMPRAS',2,3,NULL,72,0,0,1,0,1,'/1/',NULL,1,NULL,1,0,0,0,NULL,NULL),(23,'CMA','CAMARA',13,14,NULL,72,1,1,2,0,37,'/1/37/',NULL,0,NULL,0,1,1,1,NULL,NULL),(31,'it','INFORMATICA',4,5,NULL,72,0,0,1,0,1,'/1/','informatica-cau',1,NULL,1,0,0,0,NULL,NULL),(34,NULL,'CONTABILIDAD',6,7,NULL,0,0,0,1,0,1,'/1/',NULL,1,NULL,1,0,0,0,NULL,NULL),(35,NULL,'FINANZAS',8,9,NULL,0,0,0,1,0,1,'/1/',NULL,1,'begonya@verdnatura.es',1,0,0,0,NULL,NULL),(36,NULL,'LABORAL',10,11,NULL,0,0,0,1,0,1,'/1/',NULL,1,NULL,1,0,0,0,NULL,NULL),(37,'PROD','PRODUCCION',12,27,NULL,72,1,1,1,7,1,'/1/',NULL,0,NULL,0,1,1,1,NULL,NULL),(38,NULL,'SACADO',15,16,NULL,72,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,0,NULL,NULL),(39,NULL,'ENCAJADO',17,18,NULL,72,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,0,NULL,NULL),(41,NULL,'ADMINISTRACION',28,29,NULL,72,0,0,1,0,1,'/1/',NULL,1,NULL,1,0,0,0,NULL,NULL),(43,'VT','VENTAS',30,53,NULL,0,0,0,1,11,1,'/1/',NULL,1,'',1,0,0,0,NULL,NULL),(44,'management','GERENCIA',54,55,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL),(45,'logistic','LOGISTICA',56,57,NULL,72,0,0,1,0,1,'/1/',NULL,1,NULL,1,0,0,0,NULL,NULL),(46,'delivery','REPARTO',58,59,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,1,0,0,NULL,NULL),(48,NULL,'ALMACENAJE',60,61,NULL,0,1,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL),(49,NULL,'PROPIEDAD',62,63,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL),(52,NULL,'CARGA AEREA',64,65,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL),(53,NULL,'MARKETING Y COMUNICACIÓN',66,67,NULL,72,0,0,1,0,1,'/1/',NULL,1,NULL,1,0,0,0,NULL,NULL),(54,NULL,'ORNAMENTALES',68,69,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL),(55,NULL,'TALLER NATURAL',70,73,14548,72,0,0,1,1,1,'/1/',NULL,0,NULL,0,1,1,0,1118,NULL),(56,NULL,'TALLER ARTIFICIAL',71,72,8470,72,0,0,2,0,55,'/1/55/',NULL,0,NULL,0,1,1,0,1927,NULL),(58,'CMP','CAMPOS',74,77,NULL,72,0,0,1,1,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL),(59,NULL,'MANTENIMIENTO',78,79,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,1,0,0,NULL,NULL),(60,NULL,'RECLAMACIONES',80,81,NULL,72,0,0,1,0,1,'/1/',NULL,1,NULL,1,1,0,0,NULL,NULL),(61,NULL,'VNH',82,85,NULL,73,0,0,1,1,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL),(66,NULL,'VERDNAMADRID',86,87,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL),(68,NULL,'COMPLEMENTOS',19,20,NULL,72,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,1,0,0,NULL,NULL),(69,NULL,'VERDNABARNA',88,89,NULL,74,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL),(80,NULL,'EQUIPO J VALLES',31,32,4250,72,0,0,2,0,43,'/1/43/','jvp_equipo',1,'gestioncomercial@verdnatura.es',1,0,0,0,NULL,NULL),(86,NULL,'LIMPIEZA',90,91,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL),(89,NULL,'COORDINACION',92,93,NULL,0,1,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL),(90,NULL,'TRAILER',83,84,NULL,0,0,0,2,0,61,'/1/61/',NULL,0,NULL,0,0,0,0,NULL,NULL),(91,NULL,'ARTIFICIAL',21,22,NULL,0,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,0,NULL,NULL),(92,NULL,'EQUIPO SILVERIO',33,34,1203,0,0,0,2,0,43,'/1/43/','sdc_equipo',1,'gestioncomercial@verdnatura.es',1,0,0,0,NULL,NULL),(93,NULL,'CONFECCION',94,95,NULL,0,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,1,0,NULL,NULL),(94,NULL,'EQUIPO J BROCAL',35,36,3797,0,0,0,2,0,43,'/1/43/','jes_equipo',1,'gestioncomercial@verdnatura.es',1,0,0,0,NULL,NULL),(95,NULL,'EQUIPO C ZAMBRANO',37,38,4667,0,0,0,2,0,43,'/1/43/','czg_equipo',1,'gestioncomercial@verdnatura.es',1,0,0,0,NULL,NULL),(96,NULL,'EQUIPO C LOPEZ',39,40,4661,0,0,0,2,0,43,'/1/43/','cla_equipo',1,'gestioncomercial@verdnatura.es',1,0,0,0,NULL,NULL),(115,NULL,'EQUIPO CLAUDI',41,42,3810,0,0,0,2,0,43,'/1/43/','csr_equipo',1,'gestioncomercial@verdnatura.es',1,0,0,0,NULL,NULL),(123,NULL,'EQUIPO ELENA BASCUÑANA',43,44,7102,0,0,0,2,0,43,'/1/43/','ebt_equipo',1,'gestioncomercial@verdnatura.es',1,0,0,0,NULL,NULL),(124,NULL,'CONTROL INTERNO',96,97,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,1,0,0,0,NULL,NULL),(125,NULL,'EQUIPO MIRIAM MAR',45,46,1118,0,0,0,2,0,43,'/1/43/','mir_equipo',1,'gestioncomercial@verdnatura.es',1,0,0,0,NULL,NULL),(126,NULL,'PRESERVADO',98,99,NULL,0,0,0,1,0,1,'/1/',NULL,0,NULL,0,1,1,0,NULL,NULL),(128,NULL,'PALETIZADO',23,24,NULL,0,0,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,0,NULL,NULL),(130,NULL,'REVISION',25,26,NULL,0,0,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,0,NULL,NULL),(131,NULL,'INVERNADERO',75,76,NULL,0,0,0,2,0,58,'/1/58/',NULL,0,NULL,0,1,0,0,NULL,NULL),(132,NULL,'EQUIPO DC',47,48,1731,0,0,0,2,0,43,'/1/43/','dc_equipo',1,'gestioncomercial@verdnatura.es',1,0,0,0,NULL,NULL),(133,'franceTeam','EQUIPO FRANCIA',49,50,1731,72,0,0,2,0,43,'/1/43/','fra_equipo',1,'gestioncomercial@verdnatura.es',1,0,0,0,NULL,NULL),(134,NULL,'EQUIPO RODRI',51,52,6264,0,0,0,2,0,43,'/1/43/','rhr_equipo',1,'gestioncomercial@verdnatura.es',1,0,0,0,NULL,NULL),(135,'routers','ENRUTADORES',100,101,NULL,0,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL),(136,'heavyVehicles','VEHICULOS PESADOS',102,103,NULL,0,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL),(137,'sorter','SORTER',104,105,NULL,0,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL); /*!40000 ALTER TABLE `department` ENABLE KEYS */; UNLOCK TABLES; @@ -450,7 +450,7 @@ UNLOCK TABLES; LOCK TABLES `state` WRITE; /*!40000 ALTER TABLE `state` DISABLE KEYS */; -INSERT INTO `state` VALUES (1,'Arreglar',2,0,'FIXING',NULL,1,0,0,0,0,0,0,4,1,'alert'),(2,'Libre',2,0,'FREE',NULL,2,0,0,0,0,0,0,4,1,'notice'),(3,'OK',3,0,'OK',3,28,1,0,0,0,1,1,3,0,'success'),(4,'Impreso',4,0,'PRINTED',2,29,1,0,1,0,0,1,2,0,'success'),(5,'Preparación',6,1,'ON_PREPARATION',7,14,0,0,0,2,0,0,2,0,'warning'),(6,'En Revisión',7,1,'ON_CHECKING',NULL,6,0,1,0,3,0,0,1,0,'warning'),(7,'Sin Acabar',1,0,'NOT_READY',NULL,7,0,0,0,0,0,0,4,1,'alert'),(8,'Revisado',8,1,'CHECKED',NULL,8,0,1,0,3,0,0,1,0,'warning'),(9,'Encajando',9,2,'PACKING',NULL,9,0,1,0,0,0,0,1,0,NULL),(10,'Encajado',10,2,'PACKED',NULL,10,0,1,0,0,0,0,0,0,NULL),(11,'Facturado',0,3,'INVOICED',NULL,11,0,1,0,0,0,0,0,0,NULL),(12,'Bloqueado',0,0,'BLOCKED',NULL,12,0,0,0,0,0,0,4,1,'alert'),(13,'En Reparto',11,3,'ON_DELIVERY',NULL,13,0,1,0,0,0,0,0,0,NULL),(14,'Preparado',6,1,'PREPARED',NULL,14,0,1,0,2,0,0,1,0,'warning'),(15,'Pte Recogida',12,3,'WAITING_FOR_PICKUP',NULL,15,0,1,0,0,0,0,0,0,NULL),(16,'Entregado',13,3,'DELIVERED',NULL,16,0,1,0,0,0,0,0,0,NULL),(20,'Asignado',4,0,'PICKER_DESIGNED',NULL,20,1,0,0,0,0,0,2,0,'success'),(21,'Retornado',4,1,'PRINTED_BACK',6,21,0,0,0,0,0,0,2,0,'success'),(22,'Pte. Ampliar',2,0,'EXPANDABLE',NULL,22,0,0,0,0,0,0,4,1,'alert'),(23,'URGENTE',5,1,'LAST_CALL',NULL,23,1,0,1,0,0,0,4,1,'success'),(24,'Encadenado',4,0,'CHAINED',4,24,0,0,0,0,0,0,3,1,'success'),(25,'Embarcando',3,0,'BOARDING',5,25,1,0,0,0,0,0,3,0,'alert'),(26,'Prep Previa',5,1,'PREVIOUS_PREPARATION',1,28,1,0,0,1,0,0,2,0,'warning'),(27,'Prep Asistida',5,1,'ASSISTED_PREPARATION',7,27,0,0,0,0,0,0,2,0,'success'),(28,'Previa OK',3,0,'OK PREVIOUS',3,28,1,0,1,1,1,1,3,0,'warning'),(29,'Previa Impreso',4,0,'PRINTED PREVIOUS',2,29,1,0,1,0,0,1,2,0,'success'),(30,'Embarcado',4,1,'BOARD',5,30,0,0,0,2,0,0,3,0,'success'),(31,'Polizon Impreso',4,1,'PRINTED STOWAWAY',2,29,1,0,1,0,0,1,2,0,'success'),(32,'Polizon OK',3,1,'OK STOWAWAY',3,31,1,0,0,1,1,1,3,0,'warning'),(33,'Auto_Impreso',4,0,'PRINTED_AUTO',2,29,1,0,1,0,0,1,2,0,'success'),(34,'Pte Pago',3,0,'WAITING_FOR_PAYMENT',NULL,34,0,0,0,0,0,0,4,1,'alert'),(35,'Semi-Encajado',9,2,'HALF_PACKED',NULL,10,0,1,0,0,0,0,1,0,NULL),(36,'Previa Revisando',3,0,'PREVIOUS_CONTROL',2,37,1,0,0,4,0,1,2,0,'warning'),(37,'Previa Revisado',3,0,'PREVIOUS_CONTROLLED',2,29,1,0,1,0,0,1,2,0,'warning'),(38,'Prep Cámara',6,1,'COOLER_PREPARATION',7,14,0,0,0,2,0,0,2,0,'warning'),(41,'Prep Parcial',6,1,'PARTIAL_PREPARATION',7,14,0,0,0,2,0,0,2,0,'warning'); +INSERT INTO `state` VALUES (1,'Arreglar',2,0,'FIXING',NULL,1,0,0,0,0,0,0,4,1,'alert'),(2,'Libre',2,0,'FREE',NULL,2,0,0,0,0,0,0,4,1,'notice'),(3,'OK',3,0,'OK',3,28,1,0,0,0,1,1,3,0,'success'),(4,'Impreso',4,0,'PRINTED',2,29,1,0,1,0,0,1,2,0,'success'),(5,'Preparación',6,1,'ON_PREPARATION',7,14,0,0,0,2,0,0,2,0,'warning'),(6,'En Revisión',7,1,'ON_CHECKING',NULL,6,0,1,0,3,0,0,1,0,'warning'),(7,'Sin Acabar',1,0,'NOT_READY',NULL,7,0,0,0,0,0,0,4,1,'alert'),(8,'Revisado',8,1,'CHECKED',NULL,8,0,1,0,3,0,0,1,0,'warning'),(9,'Encajando',9,2,'PACKING',NULL,9,0,1,0,0,0,0,1,0,NULL),(10,'Encajado',10,2,'PACKED',NULL,10,0,1,0,0,0,0,0,0,NULL),(11,'Facturado',0,3,'INVOICED',NULL,11,0,1,0,0,0,0,0,0,NULL),(12,'Bloqueado',0,0,'BLOCKED',NULL,12,0,0,0,0,0,0,4,1,'alert'),(13,'En Reparto',11,3,'ON_DELIVERY',NULL,13,0,1,0,0,0,0,0,0,NULL),(14,'Preparado',6,1,'PREPARED',NULL,14,0,1,0,2,0,0,1,0,'warning'),(15,'Pte Recogida',12,3,'WAITING_FOR_PICKUP',NULL,15,0,1,0,0,0,0,0,0,NULL),(16,'Entregado',13,3,'DELIVERED',NULL,16,0,1,0,0,0,0,0,0,NULL),(20,'Asignado',4,0,'PICKER_DESIGNED',NULL,20,1,0,0,0,0,0,2,0,'success'),(21,'Retornado',4,1,'PRINTED_BACK',6,21,0,0,0,0,0,0,2,0,'success'),(22,'Pte. Ampliar',2,0,'EXPANDABLE',NULL,22,0,0,0,0,0,0,4,1,'alert'),(23,'URGENTE',5,1,'LAST_CALL',NULL,23,1,0,1,0,0,0,4,1,'success'),(24,'Encadenado',4,0,'CHAINED',4,24,0,0,0,0,0,0,3,1,'success'),(25,'Embarcando',3,0,'BOARDING',5,25,1,0,0,0,0,0,3,0,'alert'),(26,'Prep Previa',5,0,'PREVIOUS_PREPARATION',1,28,1,0,0,1,0,0,2,0,'warning'),(27,'Prep Asistida',5,1,'ASSISTED_PREPARATION',7,27,0,0,0,0,0,0,2,0,'success'),(28,'Previa OK',3,0,'OK PREVIOUS',3,28,1,0,1,1,1,1,3,0,'warning'),(29,'Previa Impreso',4,0,'PRINTED PREVIOUS',2,29,1,0,1,0,0,1,2,0,'success'),(30,'Embarcado',4,1,'BOARD',5,30,0,0,0,2,0,0,3,0,'success'),(31,'Polizon Impreso',4,1,'PRINTED STOWAWAY',2,29,1,0,1,0,0,1,2,0,'success'),(32,'Polizon OK',3,1,'OK STOWAWAY',3,31,1,0,0,1,1,1,3,0,'warning'),(33,'Auto_Impreso',4,0,'PRINTED_AUTO',2,29,1,0,1,0,0,1,2,0,'success'),(34,'Pte Pago',3,0,'WAITING_FOR_PAYMENT',NULL,34,0,0,0,0,0,0,4,1,'alert'),(35,'Semi-Encajado',9,2,'HALF_PACKED',NULL,10,0,1,0,0,0,0,1,0,NULL),(36,'Previa Revisando',3,0,'PREVIOUS_CONTROL',2,37,1,0,0,4,0,1,2,0,'warning'),(37,'Previa Revisado',3,0,'PREVIOUS_CONTROLLED',2,29,1,0,1,0,0,1,2,0,'warning'),(38,'Prep Cámara',6,1,'COOLER_PREPARATION',7,14,0,0,0,2,0,0,2,0,'warning'),(41,'Prep Parcial',6,1,'PARTIAL_PREPARATION',7,14,0,0,0,2,0,0,2,0,'warning'); /*!40000 ALTER TABLE `state` ENABLE KEYS */; UNLOCK TABLES; @@ -470,7 +470,7 @@ UNLOCK TABLES; LOCK TABLES `volumeConfig` WRITE; /*!40000 ALTER TABLE `volumeConfig` DISABLE KEYS */; -INSERT INTO `volumeConfig` VALUES (2.67,1.60,0.8,150,0.30,120,57,2.0,0,200,0,167.0); +INSERT INTO `volumeConfig` VALUES (2.67,1.60,0.8,150,0.30,120,57,2.0,50,200,10,167.0); /*!40000 ALTER TABLE `volumeConfig` ENABLE KEYS */; UNLOCK TABLES; @@ -480,7 +480,7 @@ UNLOCK TABLES; LOCK TABLES `workCenter` WRITE; /*!40000 ALTER TABLE `workCenter` DISABLE KEYS */; -INSERT INTO `workCenter` VALUES (1,'Silla',20,859,1,'Av espioca 100',552703,NULL),(2,'Mercaflor',19,NULL,NULL,NULL,NULL,NULL),(3,'Marjales',26,20008,NULL,NULL,NULL,NULL),(4,'VNH',NULL,NULL,NULL,NULL,NULL,NULL),(5,'Madrid',28,2869,5,'Av constitución 3',554145,0.50),(6,'Vilassar',88,88038,NULL,'Cami del Crist, 33',556412,NULL),(7,'Tenerife',NULL,NULL,NULL,NULL,NULL,NULL),(8,'Silla-Agrario',26,NULL,NULL,NULL,NULL,NULL),(9,'Algemesi',20,1354,60,'Fenollars, 2',523549,NULL); +INSERT INTO `workCenter` VALUES (1,'Silla',20,859,1,'Av espioca 100',552703,NULL),(2,'Mercaflor',19,NULL,NULL,NULL,NULL,NULL),(3,'Marjales',26,20008,NULL,NULL,NULL,NULL),(4,'VNH',NULL,NULL,NULL,NULL,NULL,NULL),(5,'Madrid',28,2869,5,'Av constitución 3',554145,0.50),(6,'Vilassar',88,88038,NULL,'Cami del Crist, 33',556412,NULL),(7,'Tenerife',NULL,NULL,NULL,NULL,NULL,NULL),(8,'Silla-Agrario',26,NULL,NULL,NULL,NULL,NULL),(9,'Algemesi',20,1354,60,'Fenollars, 2',523549,NULL),(10,'Rubi',88,NULL,84,'Av. de la Llana, 131',549722,0.50); /*!40000 ALTER TABLE `workCenter` ENABLE KEYS */; UNLOCK TABLES; @@ -493,6 +493,26 @@ LOCK TABLES `companyI18n` WRITE; INSERT INTO `companyI18n` VALUES (442,'en','In compliance with the provisions of Organic Law 15/1999, on the Protection of Personal Data, we inform you that the personal data you provide will be included in automated files of VERDNATURA LEVANTE SL, being able at all times to exercise the rights of access, rectification, cancellation and opposition, communicating it in writing to the registered office of the entity. The purpose of the file is administrative management, accounting, and billing.'),(442,'fr','Conformément aux dispositions de la loi organique 15/1999 sur la protection des données personnelles, nous vous informons que les données personnelles que vous fournissez seront incluses dans des dossiers. VERDNATURA LEVANTE S.L., vous pouvez à tout moment, exercer les droits d``accès, de rectification, d``annulation et d``opposition, en communiquant par écrit au siège social de la société. Le dossier a pour objet la gestion administrative, la comptabilité et la facturation.'),(442,'pt','Em cumprimento do disposto na lei Orgânica 15/1999, de Protecção de Dados de Carácter Pessoal, comunicamos que os dados pessoais que facilite se incluirão nos ficheiros automatizados de VERDNATURA LEVANTE S.L., podendo em todo momento exercer os direitos de acesso, rectificação, cancelação e oposição, comunicando por escrito ao domicílio social da entidade. A finalidade do ficheiro é a gestão administrativa, contabilidade e facturação.'); /*!40000 ALTER TABLE `companyI18n` ENABLE KEYS */; UNLOCK TABLES; + +-- +-- Dumping data for table `workerTimeControlError` +-- + +LOCK TABLES `workerTimeControlError` WRITE; +/*!40000 ALTER TABLE `workerTimeControlError` DISABLE KEYS */; +INSERT INTO `workerTimeControlError` VALUES (1,'IS_NOT_ALLOWED_FUTURE','No se permite fichar a futuro'),(2,'INACTIVE_BUSINESS','No hay un contrato en vigor'),(3,'IS_NOT_ALLOWED_WORK','No está permitido trabajar'),(4,'ODD_WORKERTIMECONTROL','Fichadas impares'),(5,'DAY_MAX_TIME','Superado el tiempo máximo entre entrada y salida'),(6,'BREAK_DAY','Descanso diario'),(7,'BREAK_WEEK','Descanso semanal'),(8,'WRONG_DIRECTION','Dirección incorrecta'),(9,'UNDEFINED_ERROR','Error sin definir'); +/*!40000 ALTER TABLE `workerTimeControlError` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Dumping data for table `silexACL` +-- + +LOCK TABLES `silexACL` WRITE; +/*!40000 ALTER TABLE `silexACL` DISABLE KEYS */; +INSERT INTO `silexACL` VALUES (1,'workerTimeControl','clockIn','$everyone'),(2,'workerTimeControl','getClockIn','$everyone'),(3,'workerTimeControl','login','$everyone'),(4,'security','device_checkLogin','employee'),(5,'security','getVersion','employee'),(6,'security','login','employee'),(7,'delivery','addNote','employee'),(8,'delivery','expeditionState_add','employee'),(9,'delivery','expeditionState_addByExpedition','employee'),(10,'delivery','expeditionState_addByExpeditionMulti','employee'),(11,'delivery','expeditionState_addByRoute','employee'),(12,'delivery','expedition_getLog','employee'),(13,'delivery','getExpeditionFromRoute','employee'),(14,'delivery','getInfo','employee'),(15,'delivery','getInfoCompany','employee'),(16,'delivery','getInfoFreelance','employee'),(17,'delivery','getWorkers','employee'),(18,'delivery','get_routes','employee'),(19,'delivery','get_tickets','employee'),(20,'delivery','get_version','employee'),(21,'delivery','saveLoadersWorkers','employee'),(22,'delivery','save_sign','employee'),(23,'delivery','setRouteOk','employee'),(24,'delivery','updateExpeditionChecked','employee'),(25,'delivery','update_routes','employee'),(26,'almacennew','barcodes_edit','employee'),(27,'almacennew','barcodeToItem','employee'),(28,'almacennew','buffer_setTypeByName','employee'),(29,'almacennew','buy_updateGrouping','employee'),(30,'almacennew','buy_updatePacking','employee'),(31,'almacennew','checkRouteExpeditionScanPut','employee'),(32,'almacennew','clearShelvingList','employee'),(33,'almacennew','collectionAddItem','employee'),(34,'almacennew','collectionGet','employee'),(35,'almacennew','collectionIncreaseQuantity','employee'),(36,'almacennew','collectionMissingTrash','employee'),(37,'almacennew','collectionNew','employee'),(38,'almacennew','collectionStickerPrint','employee'),(39,'almacennew','collection_getTickets','employee'),(40,'almacennew','collection_printSticker','employee'),(41,'almacennew','department_getHasMistake','employee'),(42,'almacennew','deviceLog_add','employee'),(43,'almacennew','deviceProductionUser_getWorker','employee'),(44,'almacennew','deviceProduction_getnameDevice','employee'),(45,'almacennew','expeditionLoading_add','employee'),(46,'almacennew','expeditionPalletDel','employee'),(47,'almacennew','expeditionPalletList','employee'),(48,'almacennew','expeditionPalletPrintSet','employee'),(49,'almacennew','expeditionPalletView','employee'),(50,'almacennew','expeditionScanAdd','employee'),(51,'almacennew','expeditionScanDel','employee'),(52,'almacennew','expeditionScanList','employee'),(53,'almacennew','expeditionScanPut','employee'),(54,'almacennew','expeditionState_addByPallet','employee'),(55,'almacennew','expeditionTruckAdd','employee'),(56,'almacennew','expeditionTruckList','employee'),(57,'almacennew','expedition_getState','employee'),(58,'almacennew','expedition_scan','employee'),(59,'almacennew','faultsReview','employee'),(60,'almacennew','faultsReview_isChecked','employee'),(61,'almacennew','getItemUbication','employee'),(62,'almacennew','get_ItemPackingType','employee'),(63,'almacennew','itemDiary','employee'),(64,'almacennew','itemPlacementSupplyAiming','employee'),(65,'almacennew','itemPlacementSupplyCloseOrder','employee'),(66,'almacennew','itemPlacementSupplyGetOrder','employee'),(68,'almacennew','itemShelvingBuyerGet','employee'),(69,'almacennew','itemShelvingBuyerTask','employee'),(70,'almacennew','itemShelvingDelete','employee'),(71,'almacennew','itemShelvingList','employee'),(72,'almacennew','itemShelvingLog_get','employee'),(73,'almacennew','itemShelvingMake','employee'),(74,'almacennew','itemShelvingMakeEdit','employee'),(75,'almacennew','itemShelvingMake_multi','employee'),(76,'almacennew','itemShelvingPlacementSupplyAdd','employee'),(77,'almacennew','itemShelvingSaleSupplyAdd','employee'),(78,'almacennew','itemShelvingStarsUpdate','employee'),(79,'almacennew','itemShelvingTransfer','employee'),(80,'almacennew','itemShelving_addByClaim','employee'),(81,'almacennew','itemShelving_filterBuyer','employee'),(82,'almacennew','itemShelving_getSaleDate','employee'),(83,'almacennew','itemTrash','employee'),(84,'almacennew','item_card','employee'),(85,'almacennew','item_getSimilar','employee'),(86,'almacennew','item_placement_save','employee'),(87,'almacennew','item_saveReference','employee'),(88,'almacennew','item_updatePackingShelve','employee'),(89,'almacennew','machineWorker_add','employee'),(90,'almacennew','machineWorker_getHistorical','employee'),(91,'almacennew','machineWorker_update','employee'),(92,'almacennew','machineWorker_Worker','employee'),(93,'almacennew','machine_checkPlate','employee'),(94,'almacennew','machine_getWorkerPlate','employee'),(95,'almacennew','mistakeType','employee'),(96,'almacennew','printer_get','employee'),(97,'almacennew','qr_getCall','developer'),(98,'almacennew','saleMistakeAdd','employee'),(99,'almacennew','saleMove','employee'),(100,'almacennew','saleParking_add','employee'),(101,'almacennew','saleTrackingDel','employee'),(102,'almacennew','saleTrackingReplace','employee'),(103,'almacennew','saleTracking_add','employee'),(104,'almacennew','saleTracking_addPrevOK','employee'),(105,'almacennew','saleTracking_updateIsChecked','employee'),(106,'almacennew','sectorCollectionSaleGroup_add','employee'),(107,'almacennew','sectorCollection_get','employee'),(108,'almacennew','sectorCollection_getSale','employee'),(109,'almacennew','sectorCollection_new','employee'),(110,'almacennew','sector_get','employee'),(111,'almacennew','shelvingChange','employee'),(112,'almacennew','shelvingLog_get','employee'),(113,'almacennew','shelvingPark','employee'),(114,'almacennew','shelvingParking_get','employee'),(115,'almacennew','shelvingPriorityUpdate','employee'),(116,'almacennew','sip_getExtension','employee'),(117,'almacennew','ticketCollection_setUsedShelves','employee'),(118,'almacennew','ticketOrCollection_checkFullyControlled','employee'),(119,'almacennew','ticketToPrePrepare','employee'),(120,'almacennew','ticket_checkFullyControlled','employee'),(121,'almacennew','ticket_setState','employee'),(122,'almacennew','update_ItemPackingType','employee'),(123,'almacennew','workerMachinery_isRegistered','employee'),(124,'almacennew','workerMistakeType_get','employee'),(125,'almacennew','workerMistake_Add','coolerBoss'),(126,'almacennew','workerShelving_add','employee'),(127,'almacennew','workerShelving_delete','employee'),(128,'almacennew','worker_getFromHasMistake','employee'),(129,'almacennew','worker_getId','employee'),(130,'almacennew','worker_getPrinter','employee'),(131,'almacennew','worker_getSector','employee'),(132,'almacennew','worker_updatePrinter','employee'),(133,'almacennew','worker_updateSector','employee'),(134,'almacennew','itemShelving_updateFromSale','employee'),(135,'almacennew','collection_getUncheckedTicket','employee'),(136,'almacennew','itemShelving_return','employee'),(137,'almacennew','itemShelving_merge','employee'),(139,'delivery','get_expeditionsSummary','employee'),(140,'almacennew','cmrExpeditionPallet_add','employee'),(141,'delivery','route_getExpeditionSummary','employee'),(142,'almacennew','item_saveStems','employee'),(143,'almacennew','debug_add','employee'),(144,'almacennew','operator_getNumberOfWagons','employee'),(145,'almacennew','operator_add','employee'),(146,'almacennew','expeditionPallet_get','employee'),(147,'almacennew','worker_isF11Allowed','employee'),(148,'almacennew','train_get','employee'),(149,'almacennew','saleTracking_mark','employee'),(150,'almacennew','operator_updateItemPackingType','employee'),(151,'almacennew','operator_updateTrain','employee'),(152,'almacennew','operator_getTrain','employee'),(153,'almacennew','operator_getItemPackingType','employee'),(154,'almacennew','collection_assign','employee'),(155,'almacennew','itemPacking_get','employee'),(156,'almacennew','shelvingLog_add','employee'),(157,'almacennew','collection_get','employee'),(158,'delivery','get_routesFromExpedition','employee'),(160,'almacennew','expeditionMistakeType_get','employee'),(161,'almacennew','expeditionMistake_add','employee'),(162,'almacennew','itemShelving_addList','employee'),(163,'almacennew','cmrPallet_add','employee'),(164,'almacennew','ticket_isOutClosureZone','employee'),(165,'almacennew','itemShelving_selfConsumption','employee'),(166,'almacennew','ticket_printLabelPrevious','employee'),(167,'almacennew','travel_updatePacking','employee'),(168,'app','status','$everyone'); +/*!40000 ALTER TABLE `silexACL` ENABLE KEYS */; +UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; @@ -502,7 +522,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2023-08-30 15:53:19 +-- Dump completed on 2023-11-20 12:26:42 USE `cache`; -- MariaDB dump 10.19 Distrib 10.5.19-MariaDB, for debian-linux-gnu (x86_64) -- @@ -538,7 +558,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2023-08-30 15:53:20 +-- Dump completed on 2023-11-20 12:26:42 USE `hedera`; -- MariaDB dump 10.19 Distrib 10.5.19-MariaDB, for debian-linux-gnu (x86_64) -- @@ -602,7 +622,7 @@ UNLOCK TABLES; LOCK TABLES `link` WRITE; /*!40000 ALTER TABLE `link` DISABLE KEYS */; -INSERT INTO `link` VALUES (16,'Printing server','Manage the CUPS printing server','http://printnatura.verdnatura.es','printer'),(20,'Webmail','Verdnatura webmail','https://webmail.verdnatura.es/','mail'),(23,'Verdnatura Beta','Trial version of the web page','https://test-shop.verdnatura.es/','vn'),(25,'Shared folder','Shared folder','https://cdn.verdnatura.es/share','backup'),(29,'phpMyAdmin','Manage MySQL database','https://pma.verdnatura.es/','pma'),(30,'Nagios','Monitoring system','https://nagios.verdnatura.es/','nagios'),(33,'Gitea','Version control system','https://gitea.verdnatura.es/','git'),(34,'Wiknatura','Verdnatura wiki page','https://wiki.verdnatura.es/','wiki'),(35,'phpLDAPadmin','Manage the LDAP database','https://pla.verdnatura.es/','pla'),(36,'Applications','Access applications repository','https://cdn.verdnatura.es/vn-access','access'),(37,'Jenkins','CI and CD system','https://jenkins.verdnatura.es','jenkins'),(38,'osTicket','User service center','https://cau.verdnatura.es','osticket'),(39,'Redmine','Flexible project management','https://redmine.verdnatura.es','redmine'),(40,'Grafana','Analytics & monitoring solution','https://grafana.verdnatura.es','grafana'),(41,'Rocket.Chat','Communications platform','https://chat.verdnatura.es','rocketchat'),(42,'Salix','ERP software','https://salix.verdnatura.es','salix'),(43,'Docker','Container management','https://docker.verdnatura.es','docker'),(44,'Proxmox','Virtual environment','https://proxmox.verdnatura.es','proxmox'),(45,'Shinobi','Network video recorder','https://shinobi.verdnatura.es','shinobi'),(46,'DokuWiki','Internal documentation','https://doku.verdnatura.es','dokuwiki'); +INSERT INTO `link` VALUES (16,'Printing server','Manage the CUPS printing server','http://printnatura.verdnatura.es','printer'),(20,'Webmail','Verdnatura webmail','https://webmail.verdnatura.es/','mail'),(23,'Verdnatura Beta','Trial version of the web page','https://test-shop.verdnatura.es/','vn'),(25,'Shared folder','Shared folder','https://cdn.verdnatura.es/share','backup'),(29,'phpMyAdmin','Manage MySQL database','https://pma.verdnatura.es/','pma'),(30,'Nagios','Monitoring system','https://nagios.verdnatura.es/','nagios'),(33,'Gitea','Version control system','https://gitea.verdnatura.es/','git'),(34,'Wiknatura','Verdnatura wiki page','https://wiki.verdnatura.es/','wiki'),(35,'phpLDAPadmin','Manage the LDAP database','https://pla.verdnatura.es/','pla'),(36,'Applications','Access applications repository','https://cdn.verdnatura.es/vn-access','access'),(37,'Jenkins','CI and CD system','https://jenkins.verdnatura.es','jenkins'),(38,'osTicket','User service center','https://cau.verdnatura.es','osticket'),(39,'Redmine','Flexible project management','https://redmine.verdnatura.es','redmine'),(40,'Grafana','Analytics & monitoring solution','https://grafana.verdnatura.es','grafana'),(41,'Rocket.Chat','Communications platform','https://chat.verdnatura.es','rocketchat'),(42,'Salix','ERP software','https://salix.verdnatura.es','salix'),(43,'Docker','Container management','https://docker.verdnatura.es','docker'),(44,'Proxmox','Virtual environment','https://mox.verdnatura.es','proxmox'),(45,'Shinobi','Network video recorder','https://shinobi.verdnatura.es','shinobi'),(46,'DokuWiki','Internal documentation','https://doku.verdnatura.es','dokuwiki'); /*!40000 ALTER TABLE `link` ENABLE KEYS */; UNLOCK TABLES; @@ -632,7 +652,7 @@ UNLOCK TABLES; LOCK TABLES `message` WRITE; /*!40000 ALTER TABLE `message` DISABLE KEYS */; -INSERT INTO `message` VALUES (1,'ORDER_DATE_HOLIDAY','No es posible realizar pedidos para días festivos'),(2,'ORDER_EMPTY','El pedido esta vacío'),(3,'ORDER_UNAVAILABLE','Algunos artículos ya no están disponibles, verifica las cantidades resaltadas en rojo'),(4,'SURVEY_MAX_ONE_VOTE','Solo es posible realizar un voto por encuesta'),(5,'ORDER_MAX_EXCEEDED','Has excedido el número máximo de pedidos por confirmar, por favor elimina o confirma los pedidos iniciados'),(6,'LOGIN_INCORRECT','Usuario o contraseña incorrectos. Recuerda que se hace distinción entre mayúsculas y minúsculas.'),(7,'ORDER_DATE_PAST','La fecha de su pedido debe ser mayor o igual al día de hoy'),(8,'ORDER_DATE_LAST','No es posible realizar más para hoy, por favor atrasa la fecha de tu pedido a mañana o días posteriores'),(9,'ORDER_DATE_SUNDAY','No es posible confirmar pedidos para Domingo'),(10,'ORDER_DATE_SATURATED','Estamos saturados de pedidos, por favor selecciona otra fecha de envío o recogida '),(11,'USER_DISCONNECTED','Has sido desconectado del servidor, por favor vuelve a iniciar sesión'),(12,'UNAUTH_ACTION','Acción no permitida'),(13,'ORDER_INVALID_AGENCY','La agencia de envío no es válida'),(14,'ORDER_EMPTY_ADDRESS','Selecciona una dirección de envío'),(15,'ORDER_AMOUNT_ROUNDED','Este artículo se vende agrupado y la cantidad ha sido redondeada'),(17,'orderOutdated','La configuración del pedido es incorrecta, por favor vuelve a configurarlo para continuar comprando'),(18,'orderNotOwnedByUser','El pedido pertenece a otro usuario'),(19,'orderConfirmed','El pedido ya ha sido confirmado y no puede modificarse'),(20,'clientNotVerified','Datos fiscales incompletos, por favor contacte con su comercial'); +INSERT INTO `message` VALUES (1,'ORDER_DATE_HOLIDAY','Orders for holidays are not possible'),(2,'ORDER_EMPTY','The order is empty'),(3,'ORDER_UNAVAILABLE','Some items are no longer available, please check the quantities highlighted in red'),(4,'SURVEY_MAX_ONE_VOTE','Only one vote per survey is possible'),(5,'ORDER_MAX_EXCEEDED','You have exceeded the maximum number of unconfirmed orders, please delete or confirm started orders'),(6,'LOGIN_INCORRECT','Incorrect username or password. Case-sensitive.'),(7,'ORDER_DATE_PAST','The order date must be today or later'),(8,'ORDER_DATE_LAST','No more orders can be made for today, please postpone your order for tomorrow or later'),(9,'ORDER_DATE_SUNDAY','Orders for Sunday cannot be confirmed'),(10,'ORDER_DATE_SATURATED','We are overwhelmed with orders, please select another delivery or pick-up date'),(11,'USER_DISCONNECTED','You have been disconnected from the server, please log in again'),(12,'UNAUTH_ACTION','Action not allowed'),(13,'ORDER_INVALID_AGENCY','The shipping agency is not valid'),(14,'ORDER_EMPTY_ADDRESS','Please select a shipping address'),(15,'ORDER_AMOUNT_ROUNDED','This item is sold in bundles, the quantity has been rounded'),(17,'orderOutdated','The order configuration is incorrect, please reconfigure it to continue shopping'),(18,'orderNotOwnedByUser','The order belongs to another user'),(19,'orderConfirmed','The order has already been confirmed and cannot be modified'),(20,'clientNotVerified','Incomplete tax data, please contact your sales representative'),(21,'quantityLessThanMin','The quantity cannot be less than the minimum'); /*!40000 ALTER TABLE `message` ENABLE KEYS */; UNLOCK TABLES; @@ -704,7 +724,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2023-08-30 15:53:22 +-- Dump completed on 2023-11-20 12:26:42 USE `sage`; -- MariaDB dump 10.19 Distrib 10.5.19-MariaDB, for debian-linux-gnu (x86_64) -- @@ -770,4 +790,4 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2023-08-30 15:53:22 +-- Dump completed on 2023-11-20 12:26:42 diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index a3791f9f5..307174f16 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -59,10 +59,6 @@ INSERT IGNORE INTO `vn`.`greugeConfig`(`id`, `freightPickUpPrice`) VALUES ('1', '11'); -INSERT INTO `vn`.`packagingConfig`(`upperGap`) - VALUES - ('10'); - UPDATE `account`.`role` SET id = 100 WHERE id = 0; INSERT INTO `account`.`roleConfig`(`id`, `mysqlPassword`, `rolePrefix`, `userPrefix`, `userHost`, `tplUser`) @@ -73,7 +69,7 @@ CALL `account`.`role_sync`; INSERT INTO `account`.`user`(`id`,`name`, `nickname`, `role`,`active`,`email`, `lang`, `image`, `password`) SELECT id, name, CONCAT(name, 'Nick'), id, 1, CONCAT(name, '@mydomain.com'), 'en', '4fa3ada0-3ac4-11eb-9ab8-27f6fc3b85fd', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2' - FROM `account`.`role` WHERE id <> 20 + FROM `account`.`role` ORDER BY id; INSERT INTO `account`.`account`(`id`) @@ -87,9 +83,15 @@ INSERT INTO `vn`.`educationLevel` (`id`, `name`) (1, 'ESTUDIOS PRIMARIOS COMPLETOS'), (2, 'ENSEÑANZAS DE BACHILLERATO'); +INSERT INTO `vn`.`worker`(`id`,`code`, `firstName`, `lastName`, `bossFk`) + SELECT id,UPPER(LPAD(role, 3, '0')), name, name, NULL + FROM `account`.`user` + WHERE `id` = 9; + INSERT INTO `vn`.`worker`(`id`,`code`, `firstName`, `lastName`, `bossFk`) SELECT id,UPPER(LPAD(role, 3, '0')), name, name, 9 - FROM `account`.`user`; + FROM `account`.`user` + WHERE `id` <> 9; UPDATE `vn`.`worker` SET bossFk = NULL WHERE id = 20; UPDATE `vn`.`worker` SET bossFk = 20 WHERE id = 1 OR id = 9; @@ -549,15 +551,6 @@ INSERT INTO `vn`.`supplierActivity`(`code`, `name`) ('flowerPlants', 'Wholesale of flowers and plants'), ('vegetablesFruits', 'Fruit and vegetable trade'); -INSERT INTO `vn`.`supplierAddress`(`id`, `supplierFk`, `nickname`, `street`, `provinceFk`, `postalCode`, `city`, `phone`, `mobile`) - VALUES - (1, 1, 'Ace Chemicals', 'The Midtown', 1, '46000', 'Gotham', '111111111', '222222222'), - (2, 1, 'Arkham Asylum', 'Grand Avenue', 1, '46000', 'Gotham', '111111111', '222222222'), - (3, 2, 'Wayne Tower', 'Grand Avenue', 1, '46000', 'Gotham', '111111111', '222222222'), - (4, 2, 'Bank of Gotham', 'Founders Island', 1, '46000', 'Gotham', '111111111', '222222222'), - (5, 442, 'GCR building', 'Bristol district', 1, '46000', 'Gotham', '111111111', '222222222'), - (6, 442, 'The Gotham Tonight building', 'Bristol district', 1, '46000', 'Gotham', '111111111', '222222222'); - INSERT INTO `vn`.`supplier`(`id`, `name`, `nickname`,`account`,`countryFk`,`nif`, `commission`, `created`, `isActive`, `street`, `city`, `provinceFk`, `postCode`, `payMethodFk`, `payDemFk`, `payDay`, `taxTypeSageFk`, `withholdingSageFk`, `transactionTypeSageFk`, `workerFk`, `supplierActivityFk`, `isPayMethodChecked`, `healthRegister`) VALUES (1, 'Plants SL', 'Plants nick', 4100000001, 1, '06089160W', 0, util.VN_CURDATE(), 1, 'supplier address 1', 'PONTEVEDRA', 1, 15214, 1, 1, 15, 4, 1, 1, 18, 'flowerPlants', 1, '400664487V'), @@ -568,6 +561,15 @@ INSERT INTO `vn`.`supplier`(`id`, `name`, `nickname`,`account`,`countryFk`,`nif` (791, 'Bros SL', 'Bros nick', 5115000791, 1, '37718083S', 0, util.VN_CURDATE(), 1, 'supplier address 7', 'ASGARD', 3, 46600, 1, 2, 15, 6, 9, 3, 18, 'complements', 1, '400664487V'), (1381, 'Ornamentales', 'Ornamentales', 7185001381, 1, '07972486L', 0, util.VN_CURDATE(), 1, 'supplier address 4', 'GOTHAM', 1, 43022, 1, 2, 15, 6, 9, 3, 18, 'complements', 1, '400664487V'); +INSERT INTO `vn`.`supplierAddress`(`id`, `supplierFk`, `nickname`, `street`, `provinceFk`, `postalCode`, `city`, `phone`, `mobile`) + VALUES + (1, 1, 'Ace Chemicals', 'The Midtown', 1, '46000', 'Gotham', '111111111', '222222222'), + (2, 1, 'Arkham Asylum', 'Grand Avenue', 1, '46000', 'Gotham', '111111111', '222222222'), + (3, 2, 'Wayne Tower', 'Grand Avenue', 1, '46000', 'Gotham', '111111111', '222222222'), + (4, 2, 'Bank of Gotham', 'Founders Island', 1, '46000', 'Gotham', '111111111', '222222222'), + (5, 442, 'GCR building', 'Bristol district', 1, '46000', 'Gotham', '111111111', '222222222'), + (6, 442, 'The Gotham Tonight building', 'Bristol district', 1, '46000', 'Gotham', '111111111', '222222222'); + INSERT INTO `vn`.`supplierContact`(`id`, `supplierFk`, `phone`, `mobile`, `email`, `observation`, `name`) VALUES (1, 1, 123121212, 654789123, 'supplier1@email.es', 'observation1', 'the boss'), @@ -966,6 +968,10 @@ INSERT INTO `vn`.`packaging`(`id`, `volume`, `width`, `height`, `depth`, `isPack ('cc', 1640038.00, 56.00, 220.00, 128.00, 1, util.VN_CURDATE(), 15, 90.00), ('pallet 100', 2745600.00, 100.00, 220.00, 120.00, 1, util.VN_CURDATE(), 16, 0.00); +INSERT INTO `vn`.`packagingConfig`(`upperGap`, `defaultSmallPackageFk`, `defaultBigPackageFk`) + VALUES + ('10', 1, 'pallet 100'); + INSERT INTO `vn`.`expeditionStateType`(`id`, `description`, `code`) VALUES (1, 'En reparto', 'ON DELIVERY'), diff --git a/db/dump/structure.sql b/db/dump/structure.sql index 3d6156580..f427519eb 100644 --- a/db/dump/structure.sql +++ b/db/dump/structure.sql @@ -315,20 +315,20 @@ CREATE TABLE `mailAliasAccount` ( /*!40101 SET character_set_client = @saved_cs_client */; -- --- Table structure for table `mailClientAccess` +-- Table structure for table `mailClientAccess__` -- -DROP TABLE IF EXISTS `mailClientAccess`; +DROP TABLE IF EXISTS `mailClientAccess__`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; -CREATE TABLE `mailClientAccess` ( +CREATE TABLE `mailClientAccess__` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `client` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL, `action` set('OK','REJECT') CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL DEFAULT 'REJECT', `description` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `mailFrom` (`client`) -) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci; +) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci COMMENT='@deprecated 2023-09-03'; /*!40101 SET character_set_client = @saved_cs_client */; -- @@ -428,20 +428,20 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; -- --- Table structure for table `mailSenderAccess` +-- Table structure for table `mailSenderAccess__` -- -DROP TABLE IF EXISTS `mailSenderAccess`; +DROP TABLE IF EXISTS `mailSenderAccess__`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; -CREATE TABLE `mailSenderAccess` ( +CREATE TABLE `mailSenderAccess__` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `sender` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL, `action` set('OK','REJECT') NOT NULL DEFAULT 'REJECT', `description` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `mailFrom` (`sender`) -) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci; +) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci COMMENT='@deprecated 2023-09-03'; /*!40101 SET character_set_client = @saved_cs_client */; -- @@ -727,10 +727,30 @@ CREATE TABLE `sambaConfig` ( `adUser` varchar(255) DEFAULT NULL COMMENT 'Active directory user', `adPassword` varchar(255) DEFAULT NULL COMMENT 'Active directory password', `verifyCert` tinyint(3) unsigned NOT NULL DEFAULT 1 COMMENT 'Whether to verify server certificate', + `userDn` varchar(255) NOT NULL COMMENT 'Base DN for users without domain DN part', PRIMARY KEY (`id`) ) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Global configuration parameters for accounts'; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `signInLog` +-- + +DROP TABLE IF EXISTS `signInLog`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `signInLog` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `token` varchar(255) NOT NULL, + `userFk` int(10) unsigned DEFAULT NULL, + `creationDate` timestamp NULL DEFAULT current_timestamp(), + `ip` varchar(100) NOT NULL, + PRIMARY KEY (`id`), + KEY `userFk` (`userFk`), + CONSTRAINT `signInLog_ibfk_1` FOREIGN KEY (`userFk`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `user` -- @@ -743,7 +763,7 @@ CREATE TABLE `user` ( `realm` varchar(512) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL, `name` varchar(30) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, `nickname` varchar(127) NOT NULL, - `password` varchar(512) DEFAULT NULL, + `password` varchar(512) NOT NULL, `role` int(10) unsigned NOT NULL DEFAULT 2, `active` tinyint(1) NOT NULL DEFAULT 1, `email` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL, @@ -761,6 +781,7 @@ CREATE TABLE `user` ( `editorFk` int(10) unsigned DEFAULT NULL, `passExpired` date DEFAULT NULL, `twoFactor` enum('email') DEFAULT NULL COMMENT 'Two-factor auth type', + `username` varchar(30) GENERATED ALWAYS AS (`name`) VIRTUAL, PRIMARY KEY (`id`), UNIQUE KEY `name` (`name`), UNIQUE KEY `mail` (`email`), @@ -984,6 +1005,27 @@ CREATE TABLE `userSync` ( -- -- Dumping events for database 'account' -- +/*!50106 SET @save_time_zone= @@TIME_ZONE */ ; +/*!50106 DROP EVENT IF EXISTS `role_sync` */; +DELIMITER ;; +/*!50003 SET @saved_cs_client = @@character_set_client */ ;; +/*!50003 SET @saved_cs_results = @@character_set_results */ ;; +/*!50003 SET @saved_col_connection = @@collation_connection */ ;; +/*!50003 SET character_set_client = utf8mb3 */ ;; +/*!50003 SET character_set_results = utf8mb3 */ ;; +/*!50003 SET collation_connection = utf8mb3_general_ci */ ;; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;; +/*!50003 SET @saved_time_zone = @@time_zone */ ;; +/*!50003 SET time_zone = 'SYSTEM' */ ;; +/*!50106 CREATE*/ /*!50117 DEFINER=`salix`@`10.0.%.%`*/ /*!50106 EVENT `role_sync` ON SCHEDULE AT '2023-11-16 14:32:48' ON COMPLETION NOT PRESERVE DISABLE ON SLAVE DO CALL role_sync */ ;; +/*!50003 SET time_zone = @saved_time_zone */ ;; +/*!50003 SET sql_mode = @saved_sql_mode */ ;; +/*!50003 SET character_set_client = @saved_cs_client */ ;; +/*!50003 SET character_set_results = @saved_cs_results */ ;; +/*!50003 SET collation_connection = @saved_col_connection */ ;; +DELIMITER ; +/*!50106 SET TIME_ZONE= @save_time_zone */ ; -- -- Dumping routines for database 'account' @@ -1100,6 +1142,35 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP FUNCTION IF EXISTS `myUser_hasPriv` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` FUNCTION `myUser_hasPriv`(vChain VARCHAR(100), + vPrivilege ENUM('SELECT','INSERT','UPDATE','DELETE') +) RETURNS tinyint(1) + READS SQL DATA +BEGIN +/** + * Search if my user has privileges on table or column + * + * @param vChain string passed with this syntax dbName.tableName[.columnName] + * @param vPrivilege privileges to check ('SELECT','INSERT','UPDATE','DELETE') + * @return vHasPrivilege + */ + RETURN user_hasPriv(vChain, vPrivilege, myUser_getId()); +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 */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP FUNCTION IF EXISTS `myUser_hasRole` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -1152,6 +1223,35 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP FUNCTION IF EXISTS `myUser_hasRoutinePriv` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` FUNCTION `myUser_hasRoutinePriv`(vType ENUM('PROCEDURE', 'FUNCTION'), + vChain VARCHAR(100) +) RETURNS tinyint(1) + READS SQL DATA +BEGIN +/** + * Search if my user has privileges on routines + * + * @param vType procedure or function + * @param vChain string passed with this syntax dbName.tableName + * @return vHasPrivilege + */ + RETURN user_hasRoutinePriv(vType, vChain, myUser_getId()); +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 */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP FUNCTION IF EXISTS `passwordGenerate` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -1309,6 +1409,122 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP FUNCTION IF EXISTS `user_hasPriv` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` FUNCTION `user_hasPriv`(vChain VARCHAR(100), + vPrivilege ENUM('SELECT','INSERT','UPDATE','DELETE'), + vUserFk INT +) RETURNS tinyint(1) + READS SQL DATA +BEGIN +/** + * Search if the user has privileges on table or column + * + * @param vChain string passed with this syntax dbName.tableName[.columnName] + * @param vPrivilege privileges to check('SELECT','INSERT','UPDATE','DELETE') + * @param vUserFk user to check + * @return vHasPrivilege + */ + DECLARE vHasPrivilege BOOL DEFAULT FALSE; + DECLARE vDb VARCHAR(50); + DECLARE vTableName VARCHAR(50); + DECLARE vColumnName VARCHAR(50); + DECLARE vPrivilegeFlag INT; + DECLARE vChainExists BOOL; + + SET vDb = SUBSTRING_INDEX(vChain, '.', 1); + SET vChain = SUBSTRING(vChain, LENGTH(vDb) + 2); + SET vTableName = SUBSTRING_INDEX(vChain, '.', 1); + SET vColumnName = SUBSTRING(vChain, LENGTH(vTableName) + 2); + + SELECT COUNT(*) INTO vChainExists + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = vDb + AND TABLE_NAME = vTableName + AND COLUMN_NAME = vColumnName + LIMIT 1; + + IF NOT vChainExists THEN + RETURN FALSE; + END IF; + + CASE vPrivilege + WHEN 'Select' THEN SET vPrivilegeFlag = 1; + WHEN 'Insert' THEN SET vPrivilegeFlag = 2; + WHEN 'Update' THEN SET vPrivilegeFlag = 4; + WHEN 'Delete' THEN SET vPrivilegeFlag = 8; + ELSE BEGIN END; + END CASE; + + 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 hasPrivilege INTO vHasPrivilege + FROM (SELECT JSON_VALUE(Priv, '$.access') & vPrivilegeFlag hasPrivilege + FROM mysql.global_priv gp + JOIN tRole tr ON CONCAT(tr.name) = gp.User + HAVING hasPrivilege + LIMIT 1)sub; + + IF NOT vHasPrivilege THEN + + SELECT sub.privilege = 'Y' INTO vHasPrivilege + FROM + (SELECT CASE vPrivilege + WHEN 'SELECT' THEN Select_priv + WHEN 'INSERT' THEN Insert_priv + WHEN 'UPDATE' THEN Update_priv + WHEN 'DELETE' THEN Delete_priv + END privilege + FROM mysql.db db + JOIN tRole tr ON tr.name = db.User + WHERE db.Db = vDb)sub; + + END IF; + + IF NOT vHasPrivilege THEN + + SELECT TRUE INTO vHasPrivilege + FROM tRole tr + LEFT JOIN ( + SELECT User, Table_priv privilege + FROM mysql.tables_priv + WHERE Db = vDb + AND Table_name = vTableName + UNION + SELECT User, Column_priv + FROM mysql.columns_priv + WHERE Db = vDb + AND Table_name = vTableName + AND Column_name = vColumnName + )sub ON sub.`User` = tr.name + WHERE sub.privilege = vPrivilege; + 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 */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP FUNCTION IF EXISTS `user_hasRole` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -1381,6 +1597,135 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP FUNCTION IF EXISTS `user_hasRoutinePriv` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` FUNCTION `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 */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `account_enable` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `account_enable`(vSelf INT) +BEGIN +/** + * Enables an account and sets up email configuration. + */ + UPDATE user + SET active = TRUE + WHERE id = vSelf; + + INSERT IGNORE INTO account + SET id = vSelf; + + INSERT IGNORE INTO mailAliasAccount (mailAlias, account) + SELECT id, vSelf + FROM mailAlias + WHERE alias = 'general'; + + INSERT IGNORE INTO mailForward (account, forwardTo) + SELECT vSelf, email + FROM user + WHERE id = vSelf; +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 */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `myUser_login` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -2352,90 +2697,6 @@ 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 */ ; @@ -2529,13 +2790,13 @@ DROP TABLE IF EXISTS `clientDied`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `clientDied` ( - `id` int(11) NOT NULL DEFAULT 0, - `clientName` varchar(50) NOT NULL, + `clientFk` int(11) NOT NULL DEFAULT 0, + `clientName__` varchar(50) NOT NULL COMMENT '@deprecated 2023-10-15', `lastInvoiced` date DEFAULT NULL, - `workerCode` varchar(3) NOT NULL, - `Boss` varchar(3) NOT NULL, - `Aviso` varchar(13) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL, - PRIMARY KEY (`id`) + `workerCode__` varchar(3) NOT NULL COMMENT '@deprecated 2023-10-15', + `Boss__` varchar(3) NOT NULL COMMENT '@deprecated 2023-10-15', + `warning` enum('first','second','third') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL, + PRIMARY KEY (`clientFk`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Clientes que no han comprado en los ultimos 3 meses, se actualiza con proceso nocturno el 3 de cada mes'; /*!40101 SET character_set_client = @saved_cs_client */; @@ -2598,13 +2859,13 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; -- --- Table structure for table `compradores` +-- Table structure for table `compradores__` -- -DROP TABLE IF EXISTS `compradores`; +DROP TABLE IF EXISTS `compradores__`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; -CREATE TABLE `compradores` ( +CREATE TABLE `compradores__` ( `Id_Trabajador` int(10) unsigned NOT NULL, `año` int(4) NOT NULL, `semana` int(2) NOT NULL, @@ -3058,17 +3319,17 @@ DROP TABLE IF EXISTS `salesByItemTypeDay`; CREATE TABLE `salesByItemTypeDay` ( `itemTypeFk` smallint(5) unsigned NOT NULL, `dated` date NOT NULL, - `netSale` int(11) NOT NULL DEFAULT 0, - `stems` int(11) NOT NULL DEFAULT 0, - `references` int(11) NOT NULL DEFAULT 0, - `trash` int(11) NOT NULL DEFAULT 0, - `faults` int(11) NOT NULL DEFAULT 0, - `claimed` decimal(10,2) NOT NULL DEFAULT 0.00, - `accepted` decimal(10,2) NOT NULL DEFAULT 0.00, - `sale` decimal(10,2) NOT NULL DEFAULT 0.00, - `buy` decimal(10,2) NOT NULL DEFAULT 0.00, - `costComponent` decimal(10,2) NOT NULL DEFAULT 0.00, - `marginComponent` decimal(10,2) NOT NULL DEFAULT 0.00, + `netSale__` int(11) NOT NULL DEFAULT 0 COMMENT '@deprecated 2023-08-31, Mismo valor que campo sale', + `stems` int(11) NOT NULL DEFAULT 0 COMMENT 'Número de tallos vendidos', + `references` int(11) NOT NULL DEFAULT 0 COMMENT 'Número de artículos distintos por tipo vendidos', + `trash` int(11) NOT NULL DEFAULT 0 COMMENT 'Tallos basura', + `faults` int(11) NOT NULL DEFAULT 0 COMMENT 'Tallos faltas', + `claimed` decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT 'Valor total de reclamaciones', + `accepted` decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT 'Valor total de reclamaciones aceptadas', + `sale` decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT 'Ventas totales', + `buy` decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT 'Valor de compras totales', + `costComponent` decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT 'Suma de componentes que son valor de compra', + `marginComponent` decimal(10,2) NOT NULL DEFAULT 0.00 COMMENT 'Suma de componentes que son márgen', PRIMARY KEY (`itemTypeFk`,`dated`), KEY `itemTypeSalesByweek_period_idx` (`dated`), CONSTRAINT `itemTypeSalesByweek_itemTypeFk` FOREIGN KEY (`itemTypeFk`) REFERENCES `vn`.`itemType` (`id`) @@ -3734,18 +3995,15 @@ BEGIN SELECT c.id FROM vn.client c JOIN vn.country co ON co.id = c.countryFk WHERE co.code = vCountryCode - ) sub ON sub.id = cd.id; + ) sub ON sub.id = cd.clientFk; - INSERT INTO clientDied (id, clientName, lastInvoiced, workerCode, Boss, Aviso) + INSERT INTO clientDied (clientFk, lastInvoiced, warning) SELECT c.id, - c.name, sub.lastShipped, - w.code, - b.code, CASE - WHEN lastShipped < vThridPeriod OR lastShipped IS NULL THEN 'Tercer Aviso' - WHEN lastShipped < vSecondPeriod THEN 'Segundo Aviso' - WHEN lastShipped < vFirstPeriod THEN 'Primer Aviso' + WHEN lastShipped < vThridPeriod OR lastShipped IS NULL THEN 'third' + WHEN lastShipped < vSecondPeriod THEN 'second' + WHEN lastShipped < vFirstPeriod THEN 'first' END FROM vn.client c JOIN vn.country co ON co .id = c.countryFk @@ -4006,95 +4264,6 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `compradores_add` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `compradores_add`(IN vYear INT, IN vWeekFrom INT, IN vWeekTo INT) -BEGIN -/** - * Sustituye los registros de "bs.compradores". - * - * @param vYear: año ventas - * @param vWeekFrom: semana desde - * @param vWeekTo: semana hasta - */ - REPLACE bs.compradores - SELECT it.workerFk AS Id_Trabajador, vYear AS año, tm.week AS semana, SUM(importe) AS importe, 0 AS comision - FROM bs.ventas v - JOIN vn.time tm ON tm.dated = v.fecha - JOIN vn.itemType it ON it.id = v.tipo_id - WHERE tm.year = vYear - AND tm.week BETWEEN vWeekFrom AND vWeekTo - AND it.categoryFk != 6 - GROUP BY it.workerFk, tm.week; -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 */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `compradores_add_launcher` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `compradores_add_launcher`() -BEGIN - - DECLARE vYear INT; - DECLARE vWeek INT; - DECLARE done BOOL DEFAULT FALSE; - - DECLARE rs CURSOR FOR - SELECT year, week - FROM vn.time - WHERE dated <= util.VN_CURDATE() - AND year = vYear - AND week >= vWeek; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - - SELECT MAX(año) INTO vYear - FROM compradores; - - SELECT MAX(semana) INTO vWeek - FROM compradores - WHERE año = vYear; - - OPEN rs; - - FETCH rs INTO vYear, vWeek; - - WHILE NOT done DO - - CALL compradores_add(vYear, vWeek, vWeek); - - FETCH rs INTO vYear, vWeek; - - END WHILE; - - CLOSE rs; - - CALL compradores_evolution_add; - -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 */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `compradores_evolution_add` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -4648,6 +4817,8 @@ BEGIN DECLARE vClaimManaId INT; DECLARE vManaBankId INT; DECLARE vManaGreugeTypeId INT; + DECLARE vManaFromDays INT; + DECLARE vManaToDays INT; SELECT id INTO vManaId FROM vn.component WHERE code = 'mana'; @@ -4664,23 +4835,32 @@ BEGIN SELECT id INTO vManaGreugeTypeId FROM vn.greugeType WHERE code = 'mana'; - SELECT IFNULL(MAX(dated), '2016-01-01') - INTO vFromDated + SELECT manaFromDays, manaToDays + INTO vManaFromDays, vManaToDays + FROM vn.salespersonConfig; + + SELECT MAX(dated) + INTO vFromDated FROM vn.clientManaCache; - DELETE - FROM vn.clientManaCache - WHERE dated = vFromDated; + DELETE + FROM vn.clientManaCache + WHERE dated = vFromDated; - SELECT IFNULL(MAX(dated), '2016-01-01') - INTO vFromDated + SELECT MAX(dated) + INTO vFromDated FROM vn.clientManaCache; - WHILE timestampadd(DAY,30,vFromDated) < util.VN_CURDATE() DO + IF ISNULL(vFromDated) THEN + SELECT manaDateFrom + INTO vFromDated + FROM vn.salespersonConfig; + END IF; + WHILE vFromDated + INTERVAL vManaToDays DAY < util.VN_CURDATE() DO SELECT - timestampadd(DAY,30,vFromDated), - timestampadd(DAY,-90,vFromDated) + vFromDated + INTERVAL vManaToDays DAY, + vFromDated - INTERVAL vManaFromDays DAY INTO vToDated, vForDeleteDated; @@ -4691,8 +4871,8 @@ BEGIN INSERT INTO vn.clientManaCache(clientFk, mana, dated) SELECT Id_Cliente, - cast(sum(mana) as decimal(10,2)) as mana, - vToDated as dated + SUM(mana), + vToDated FROM ( SELECT cs.Id_Cliente, Cantidad * Valor as mana @@ -4709,7 +4889,6 @@ BEGIN WHERE Id_Banco = vManaBankId AND Fechacobro > vFromDated AND Fechacobro <= vToDated - UNION ALL SELECT g.Id_Cliente, g.Importe FROM vn2008.Greuges g @@ -4725,9 +4904,7 @@ BEGIN HAVING Id_Cliente; SET vFromDated = vToDated; - END WHILE; - END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -4760,9 +4937,16 @@ BEGIN GROUP BY c.lastSalesPersonFk )avgPortfolioWeight ON avgPortfolioWeight.lastSalesPersonFk = wm.workerFk JOIN vn.salespersonConfig spc - SET wm.pricesModifierRate = GREATEST( - spc.manaMinRate, - LEAST(spc.manaMaxRate, ROUND( - wm.amount / avgPortfolioWeight.amount))); + SET wm.pricesModifierRate = + IFNULL( + GREATEST( + spc.manaMinRate, + LEAST( + spc.manaMaxRate, + ROUND( - wm.amount / avgPortfolioWeight.amount, 3) + ) + ) + ,0); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -4787,13 +4971,12 @@ BEGIN DECLARE vDone BOOL; DECLARE vError VARCHAR(255); DECLARE vErrorCode VARCHAR(255); - DECLARE vNErrors INT DEFAULT 0; DECLARE vSchema VARCHAR(255); DECLARE vProcedure VARCHAR(255); DECLARE vLogMail VARCHAR(255); - DECLARE vId INT; + DECLARE vNightTaskFk INT; - DECLARE rs CURSOR FOR + DECLARE vQueue CURSOR FOR SELECT id, `schema`, `procedure` FROM nightTask WHERE finished <= util.VN_CURDATE() @@ -4804,14 +4987,17 @@ BEGIN SET vDone = TRUE; SET max_sp_recursion_depth = 3; - OPEN rs; - myLoop: LOOP + SELECT logMail INTO vLogMail + FROM nightTaskConfig LIMIT 1; + + OPEN vQueue; + l: LOOP SET vDone = FALSE; - FETCH rs INTO vId, vSchema, vProcedure; + FETCH vQueue INTO vNightTaskFk, vSchema, vProcedure; IF vDone THEN - LEAVE myLoop; + LEAVE l; END IF; UPDATE nightTask @@ -4819,7 +5005,7 @@ BEGIN `finished` = NULL, `error` = NULL, `errorCode` = NULL - WHERE id = vId; + WHERE id = vNightTaskFk; SET vError = NULL; CALL nightTask_launchTask( @@ -4830,36 +5016,30 @@ BEGIN ); IF vError IS NOT NULL THEN - SET vNErrors = vNErrors + 1; + IF vLogMail IS NOT NULL THEN + CALL vn.mail_insert( + vLogMail, + NULL, + CONCAT('Nightly task failed (', vSchema, '.', vProcedure, ')'), + CONCAT( + '[', vErrorCode, '] ', vError, CHAR(13, 10), -- Line break + 'See ', SCHEMA(), '.nightTask table for more info.' + ) + ); + END IF; UPDATE nightTask SET `error` = vError, `errorCode` = vErrorCode - WHERE id = vId; + WHERE id = vNightTaskFk; ELSE UPDATE nightTask SET finished = util.VN_NOW(), lastFinished = util.VN_NOW() - WHERE id = vId; + WHERE id = vNightTaskFk; END IF; END LOOP; - - CLOSE rs; - - SELECT logMail INTO vLogMail - FROM nightTaskConfig LIMIT 1; - - IF vNErrors > 0 AND vLogMail IS NOT NULL THEN - CALL vn.mail_insert( - vLogMail, - NULL, - 'Nightly task failed', - CONCAT( - vNErrors, ' procedures of nightly tasks have failed. ', - 'Please, see `', SCHEMA() ,'`.`nightTask` table for more info.' - ) - ); - END IF; + CLOSE vQueue; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -5108,11 +5288,10 @@ BEGIN DELETE FROM salesByItemTypeDay WHERE dated BETWEEN vDateStart AND vDateEnd; - INSERT INTO salesByItemTypeDay (itemTypeFk, dated, `references`, netSale, stems) + INSERT INTO salesByItemTypeDay (itemTypeFk, dated, `references`, stems) SELECT it.id itemTypeFk, bs.dated, COUNT(DISTINCT(i.id)) `references`, - SUM(bs.amount) netSale, SUM(i.stems * s.quantity) stems FROM sale bs JOIN vn.itemType it ON it.id = bs.typeFk @@ -8530,9 +8709,9 @@ DELIMITER ;; /*!50003 SET @saved_cs_client = @@character_set_client */ ;; /*!50003 SET @saved_cs_results = @@character_set_results */ ;; /*!50003 SET @saved_col_connection = @@collation_connection */ ;; -/*!50003 SET character_set_client = utf8mb3 */ ;; -/*!50003 SET character_set_results = utf8mb3 */ ;; -/*!50003 SET collation_connection = utf8mb3_general_ci */ ;; +/*!50003 SET character_set_client = utf8mb4 */ ;; +/*!50003 SET character_set_results = utf8mb4 */ ;; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;; /*!50003 SET @saved_sql_mode = @@sql_mode */ ;; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;; /*!50003 SET @saved_time_zone = @@time_zone */ ;; @@ -8735,14 +8914,14 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `ekt_load` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET character_set_client = utf8mb3 */ ; +/*!50003 SET character_set_results = utf8mb3 */ ; +/*!50003 SET collation_connection = utf8mb3_general_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ekt_load`(IN `vSelf` INT) proc:BEGIN @@ -8889,7 +9068,7 @@ proc:BEGIN ,`grouping` ,quantity ,groupingMode - ,packageFk + ,packagingFk ,weight ) SELECT @@ -8902,7 +9081,7 @@ proc:BEGIN ,IFNULL(b.`grouping`, e.pac) ,@pac * e.qty ,vForceToPacking - ,IF(vHasToChangePackagingFk OR ISNULL(b.packageFk), vPackage, b.packageFk) + ,IF(vHasToChangePackagingFk OR ISNULL(b.packagingFk), vPackage, b.packagingFk) ,(IFNULL(i.weightByPiece,0) * @pac)/1000 FROM edi.ekt e LEFT JOIN vn.buy b ON b.id = vBuy @@ -11491,6 +11670,7 @@ CREATE TABLE `tpvTransaction` ( KEY `user_id` (`clientFk`), KEY `response` (`response`), KEY `error_code` (`errorCode`), + KEY `tpvTransaction_status_IDX` (`status`,`receiptFk`) USING BTREE, CONSTRAINT `receipt_id` FOREIGN KEY (`receiptFk`) REFERENCES `vn`.`receipt` (`Id`) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT `tpvTransaction_ibfk_1` FOREIGN KEY (`clientFk`) REFERENCES `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `tpvTransaction_ibfk_2` FOREIGN KEY (`merchantFk`) REFERENCES `tpvMerchant` (`id`) ON DELETE CASCADE ON UPDATE CASCADE @@ -11905,14 +12085,14 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `item_getVisible` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET character_set_client = utf8mb3 */ ; +/*!50003 SET character_set_results = utf8mb3 */ ; +/*!50003 SET collation_connection = utf8mb3_general_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getVisible`( vWarehouse TINYINT, @@ -12002,14 +12182,14 @@ BEGIN ENGINE = MEMORY SELECT * FROM ( - SELECT b.itemFk, b.packageFk, b.packing + SELECT b.itemFk, b.packagingFk, b.packing FROM vn.buy b JOIN vn.entry e ON e.id = b.entryFk JOIN vn.travel t ON t.id = e.travelFk WHERE t.landed BETWEEN vDateInv AND vDate AND NOT b.isIgnored AND b.price2 >= 0 - AND b.packageFk IS NOT NULL + AND b.packagingFk IS NOT NULL ORDER BY t.warehouseInFk = vWarehouse DESC, t.landed DESC LIMIT 10000000000000000000 ) t GROUP BY itemFk; @@ -12026,10 +12206,10 @@ BEGIN JOIN `filter` f ON f.itemFk = i.id JOIN currentStock s ON s.itemFk = i.id LEFT JOIN tmp t ON t.itemFk = i.id - LEFT JOIN vn.packaging p ON p.id = t.packageFk + LEFT JOIN vn.packaging p ON p.id = t.packagingFk WHERE CEIL(s.quantity / t.packing) > 0 -- FIXME: Column Cubos.box not included in view vn.packaging - /* AND p.box */; + /* AND p.box */ ; DROP TEMPORARY TABLE `filter`, @@ -12921,6 +13101,7 @@ BEGIN DECLARE vRow INT; DECLARE vAdd INT; DECLARE vAvailable INT; + DECLARE vMinQuantity INT; DECLARE vDone BOOL; DECLARE vGrouping INT; DECLARE vRate INT; @@ -12951,15 +13132,23 @@ BEGIN FROM tmp.zoneGetShipped WHERE warehouseFk = vWarehouse; - SELECT available INTO vAvailable + SELECT IFNULL(available, 0) INTO vAvailable FROM tmp.ticketLot WHERE warehouseFk = vWarehouse AND itemFk = vItem; - IF vAmount > IFNULL(vAvailable, 0) THEN + IF vAmount > vAvailable THEN CALL util.throw ('ORDER_ROW_UNAVAILABLE'); END IF; + SELECT IFNULL(minQuantity, 0) INTO vMinQuantity + FROM vn.item + WHERE id = vItem; + + IF vAmount < LEAST(vMinQuantity, vAvailable) THEN + CALL util.throw ('quantityLessThanMin'); + END IF; + OPEN cur; l: LOOP @@ -13474,18 +13663,25 @@ BEGIN END IF; -- Busca un ticket existente que coincida con los parametros - + WITH tPrevia AS + (SELECT DISTINCT s.ticketFk + FROM vn.sale s + JOIN vn.saleGroupDetail sgd ON sgd.saleFk = s.id + JOIN vn.ticket t ON t.id = s.ticketFk + WHERE t.shipped BETWEEN vShipment AND util.dayend(vShipment) + ) SELECT t.id INTO vTicket FROM vn.ticket t + LEFT JOIN tPrevia tp ON tp.ticketFk = t.id LEFT JOIN vn.ticketState tls on tls.ticket = t.id - JOIN `order` o + JOIN hedera.`order` o ON o.address_id = t.addressFk AND vWarehouse = t.warehouseFk - -- AND o.agency_id = t.agencyModeFk AND o.date_send = t.landed - AND vShipment = DATE(t.shipped) + AND DATE(t.shipped) = vShipment WHERE o.id = vSelf AND t.refFk IS NULL + AND tp.ticketFk IS NULL AND IFNULL(tls.alertLevel,0) = 0 LIMIT 1; @@ -13556,7 +13752,8 @@ BEGIN IF vSale THEN UPDATE vn.sale - SET quantity = quantity + vAmount + SET quantity = quantity + vAmount, + originalQuantity = quantity WHERE id = vSale; SELECT s.quantity INTO vNewQuantity @@ -15288,6 +15485,7 @@ SET character_set_client = utf8; /*!50001 CREATE VIEW `sipConf` AS SELECT 1 AS `id`, 1 AS `name`, + 1 AS `regexten`, 1 AS `callbackextension`, 1 AS `md5secret`, 1 AS `callerid`, @@ -15298,10 +15496,12 @@ SET character_set_client = utf8; 1 AS `context`, 1 AS `incominglimit`, 1 AS `pickupgroup`, - 1 AS `careinvite`, + 1 AS `directmedia`, 1 AS `insecure`, 1 AS `transport`, 1 AS `nat`, + 1 AS `disallow`, + 1 AS `allow`, 1 AS `ipaddr`, 1 AS `regseconds`, 1 AS `port`, @@ -15328,11 +15528,9 @@ CREATE TABLE `sipConfig` ( `context` varchar(80) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, `incomingLimit` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, `pickupGroup` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, - `careInvite` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, + `directMedia` enum('yes','no') DEFAULT NULL, `insecure` varchar(45) NOT NULL, `transport` varchar(255) DEFAULT NULL, - `avpf` varchar(255) DEFAULT NULL, - `icesupport` varchar(255) DEFAULT NULL, `encryption` varchar(255) DEFAULT NULL, `dtlsenable` varchar(255) DEFAULT NULL, `dtlverify` varchar(255) DEFAULT NULL, @@ -15340,6 +15538,9 @@ CREATE TABLE `sipConfig` ( `dtlsprivatekey` varchar(255) DEFAULT NULL, `dtlssetup` varchar(255) DEFAULT NULL, `nat` varchar(255) DEFAULT NULL, + `disallow` varchar(100) DEFAULT 'all', + `allow` varchar(100) DEFAULT 'g729;ilbc;gsm;ulaw;alaw', + `qualify` enum('yes','no') DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Default values for SIP accounts'; /*!40101 SET character_set_client = @saved_cs_client */; @@ -19499,6 +19700,20 @@ CREATE TABLE `version` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `versionConfig` +-- + +DROP TABLE IF EXISTS `versionConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `versionConfig` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `realm` varchar(16) DEFAULT NULL COMMENT 'Data set on which the project runs', + PRIMARY KEY (`id`) +) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `versionLog` -- @@ -21635,6 +21850,20 @@ CREATE TABLE `addressObservation` ( ) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Observaciones de los consignatarios'; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `addressShortage` +-- + +DROP TABLE IF EXISTS `addressShortage`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `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; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `agency` -- @@ -22301,52 +22530,6 @@ CREATE TABLE `bookingPlanner` ( ) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; --- --- Table structure for table `botanicExport` --- - -DROP TABLE IF EXISTS `botanicExport`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `botanicExport` ( - `id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `ediGenusFk` mediumint(8) unsigned NOT NULL, - `ediSpecieFk` mediumint(8) unsigned DEFAULT NULL, - `countryFk__` mediumint(8) unsigned DEFAULT NULL, - `restriction` enum('Sin restriccion','Importacion Prohibida','pasaporte fitosanitario','pasaporte individual','declaracion origen') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, - `description` varchar(45) DEFAULT NULL, - `isProtectedZone` tinyint(1) NOT NULL DEFAULT 0, - `code` enum('importProhibited','phytosanitaryPassport','individualPassport') DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `Id_Paises` (`countryFk__`), - KEY `botanicExport_ibfk_2_idx` (`ediGenusFk`), - KEY `botanicExport_ibfk_3_idx` (`ediSpecieFk`), - CONSTRAINT `botanicExport_ibfk_1` FOREIGN KEY (`countryFk__`) REFERENCES `country` (`id`) -) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Especifica los generos y especies prohibidos en paises'; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`botanicExport_beforeInsert` - BEFORE INSERT ON `botanicExport` - FOR EACH ROW -BEGIN - IF (SELECT botanicExport_isUpdatable (NEW.ediGenusFk, NEW.ediSpecieFk, NEW.restriction) ) > 0 THEN - CALL util.throw ('Datos duplicados'); - END IF; -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 */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; - -- -- Table structure for table `budget` -- @@ -22506,7 +22689,7 @@ CREATE TABLE `business` ( `workerBusinessProfessionalCategoryFk` int(11) DEFAULT NULL, `calendarTypeFk` int(11) DEFAULT 1, `isHourlyLabor` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Contrato por horas', - `workcenterFk` int(11) DEFAULT NULL, + `workcenterFk` int(11) NOT NULL DEFAULT 9, `rate` int(11) DEFAULT NULL, `workerBusinessCategoryFk` int(11) DEFAULT NULL, `workerBusinessTypeFk` int(11) DEFAULT NULL, @@ -22766,7 +22949,7 @@ CREATE TABLE `buy` ( `comissionValue` decimal(10,3) NOT NULL DEFAULT 0.000, `packageValue` decimal(10,3) NOT NULL DEFAULT 0.000, `location` varchar(5) DEFAULT NULL, - `packageFk` varchar(10) DEFAULT '--', + `packagingFk` varchar(10) DEFAULT '--', `price1` decimal(10,2) DEFAULT 0.00, `price2` decimal(10,2) DEFAULT 0.00, `price3` decimal(10,2) DEFAULT 0.00, @@ -22782,9 +22965,10 @@ CREATE TABLE `buy` ( `deliveryFk` int(11) DEFAULT NULL, `itemOriginalFk` int(11) DEFAULT NULL COMMENT 'Item original de la entrada', `editorFk` int(10) unsigned DEFAULT NULL, + `packageFk` varchar(10) GENERATED ALWAYS AS (`packagingFk`) VIRTUAL, PRIMARY KEY (`id`), KEY `CompresId_Trabajador` (`workerFk`), - KEY `Id_Cubo` (`packageFk`), + KEY `Id_Cubo` (`packagingFk`), KEY `Id_Entrada` (`entryFk`), KEY `container_id` (`containerFk`), KEY `buy_edi_id` (`ektFk`), @@ -22799,7 +22983,7 @@ CREATE TABLE `buy` ( CONSTRAINT `buy_fk_4` FOREIGN KEY (`deliveryFk`) REFERENCES `edi`.`deliveryInformation` (`ID`) ON DELETE SET NULL ON UPDATE SET NULL, CONSTRAINT `buy_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`), CONSTRAINT `buy_ibfk_1` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON UPDATE CASCADE, - CONSTRAINT `buy_ibfk_2` FOREIGN KEY (`packageFk`) REFERENCES `packaging` (`id`) ON UPDATE CASCADE, + CONSTRAINT `buy_ibfk_2` FOREIGN KEY (`packagingFk`) REFERENCES `packaging` (`id`) ON UPDATE CASCADE, CONSTRAINT `buy_id` FOREIGN KEY (`entryFk`) REFERENCES `entry` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE, CONSTRAINT `buy_itemfk` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci ROW_FORMAT=DYNAMIC; @@ -22994,11 +23178,11 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET character_set_client = utf8mb3 */ ; +/*!50003 SET character_set_results = utf8mb3 */ ; +/*!50003 SET collation_connection = utf8mb3_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`buy_afterUpdate` AFTER UPDATE ON `buy` @@ -23044,7 +23228,7 @@ trig: BEGIN !(NEW.quantity <=> OLD.quantity) OR !(NEW.packing <=> OLD.packing) OR !(NEW.grouping <=> OLD.grouping) OR - !(NEW.packageFk <=> OLD.packageFk) OR + !(NEW.packagingFk <=> OLD.packagingFk) OR !(NEW.weight <=> OLD.weight) THEN CALL vn.mail_insert( CONCAT(account.user_getNameFromId(vBuyerFk),'@verdnatura.es'), @@ -24029,7 +24213,9 @@ CREATE TABLE `claimResponsible` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `description` varchar(45) NOT NULL, `responsability` tinyint(4) NOT NULL DEFAULT 0 COMMENT 'if=1 >sensib >culpa', - PRIMARY KEY (`id`) + `code` varchar(3) NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `claimResponsible_UN` (`code`) ) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Responsables de las causas'; /*!40101 SET character_set_client = @saved_cs_client */; @@ -24178,7 +24364,7 @@ CREATE TABLE `client` ( `hasToInvoice` tinyint(1) NOT NULL DEFAULT 1, `isFreezed` tinyint(1) NOT NULL DEFAULT 0, `salesPersonFk` int(10) unsigned DEFAULT NULL, - `credit` decimal(10,2) NOT NULL DEFAULT 0.00, + `credit` decimal(10,2) unsigned NOT NULL DEFAULT 0.00, `countryFk` mediumint(8) unsigned NOT NULL DEFAULT 1, `isActive` tinyint(1) NOT NULL DEFAULT 1, `gestdocFk` int(11) DEFAULT NULL, @@ -24234,6 +24420,7 @@ CREATE TABLE `client` ( KEY `client_FK_3` (`transferorFk`), KEY `codpos` (`postcode`), KEY `client_fk_editor` (`editorFk`), + KEY `client_isTaxDataChecked_IDX` (`isTaxDataChecked`) USING BTREE, CONSTRAINT `canal_nuevo_cliente` FOREIGN KEY (`contactChannelFk`) REFERENCES `contactChannel` (`id`) ON UPDATE CASCADE, CONSTRAINT `client_FK` FOREIGN KEY (`businessTypeFk`) REFERENCES `businessType` (`code`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `client_FK_1` FOREIGN KEY (`bankEntityFk`) REFERENCES `bankEntity` (`id`) ON UPDATE CASCADE, @@ -24287,6 +24474,31 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb3 */ ; +/*!50003 SET character_set_results = utf8mb3 */ ; +/*!50003 SET collation_connection = utf8mb3_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`client_AfterInsert` + AFTER INSERT ON `client` + FOR EACH ROW +BEGIN + 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; +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 */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; /*!50003 SET character_set_client = utf8mb4 */ ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; @@ -24298,17 +24510,23 @@ DELIMITER ;; FOR EACH ROW BEGIN DECLARE vText VARCHAR(255) DEFAULT NULL; - DECLARE vPayMethodFk INT; + 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 + IF !(NEW.mobile <=> OLD.mobile) AND (NEW.mobile <> '')THEN CALL pbx.phone_isValid(NEW.mobile); END IF; @@ -24318,7 +24536,7 @@ BEGIN IF NEW.payMethodFk = vPayMethodFk AND NEW.dueDay = 0 THEN SET NEW.dueDay = 5; - END IF; + END IF; -- Avisar al comercial si ha llegado la documentación sepa/core @@ -24331,12 +24549,12 @@ BEGIN END IF; IF vText IS NOT NULL - THEN + 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), + '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 @@ -24344,10 +24562,10 @@ BEGIN WHERE w.id = NEW.salesPersonFk; END IF; - IF NEW.salespersonFk IS NULL AND OLD.salespersonFk IS NOT NULL THEN + IF NEW.salespersonFk IS NULL AND OLD.salespersonFk IS NOT NULL THEN IF (SELECT COUNT(clientFk) FROM clientProtected - WHERE clientFk = NEW.id + WHERE clientFk = NEW.id ) > 0 THEN CALL util.throw("HAS_CLIENT_PROTECTED"); END IF; @@ -24360,7 +24578,6 @@ BEGIN IF !(NEW.businessTypeFk <=> OLD.businessTypeFk) AND (NEW.businessTypeFk = 'individual' OR OLD.businessTypeFk = 'individual') THEN SET NEW.isTaxDataChecked = 0; END IF; - END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -24509,6 +24726,8 @@ CREATE TABLE `clientContact` ( `editorFk` int(10) unsigned DEFAULT NULL, PRIMARY KEY (`id`), KEY `clientContact_fk_editor` (`editorFk`), + KEY `clientContact_FK` (`clientFk`), + CONSTRAINT `clientContact_FK` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `clientContact_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`) ) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -24980,7 +25199,7 @@ DROP TABLE IF EXISTS `clientSample`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `clientSample` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `clientFk` int(10) unsigned NOT NULL, + `clientFk` int(11) NOT NULL, `typeFk` int(10) unsigned NOT NULL, `created` datetime NOT NULL DEFAULT current_timestamp(), `workerFk` int(10) unsigned NOT NULL, @@ -24991,7 +25210,9 @@ CREATE TABLE `clientSample` ( PRIMARY KEY (`id`), KEY `empresa_id` (`companyFk`), KEY `clientSample_fk_editor` (`editorFk`), + KEY `clientSample_FK` (`clientFk`), CONSTRAINT `clientSampleCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE, + CONSTRAINT `clientSample_FK` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `clientSample_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`) ) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -25138,7 +25359,7 @@ DROP TABLE IF EXISTS `cmr`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `cmr` ( `id` int(11) NOT NULL AUTO_INCREMENT, - `ticketFk` int(11) DEFAULT NULL COMMENT 'refs #6092 @toDeprecate 2023-08-02', + `ticketFk__` int(11) DEFAULT NULL COMMENT '@deprecated 2023-10-20 refs #6092', `truckPlate` varchar(30) DEFAULT NULL, `observations` varchar(255) DEFAULT NULL, `senderInstruccions` varchar(255) DEFAULT NULL, @@ -25155,14 +25376,14 @@ CREATE TABLE `cmr` ( `landed` datetime DEFAULT NULL COMMENT 'Hora de llegada a destino', `ead` datetime DEFAULT NULL COMMENT 'Estimated Arriving Date', PRIMARY KEY (`id`), - KEY `cmr_fk1_idx` (`ticketFk`), + KEY `cmr_fk1_idx` (`ticketFk__`), KEY `cmr_fk2_idx` (`companyFk`), KEY `cmr_fk3_idx` (`addressToFk`), KEY `cm_fk4_idx` (`supplierFk`), KEY `cmr_FK` (`addressFromFk`), CONSTRAINT `cmrCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT `cmr_FK` FOREIGN KEY (`addressFromFk`) REFERENCES `address` (`id`) ON UPDATE CASCADE, - CONSTRAINT `cmr_fk1` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`), + CONSTRAINT `cmr_fk1` FOREIGN KEY (`ticketFk__`) REFERENCES `ticket` (`id`), CONSTRAINT `cmr_fk3` FOREIGN KEY (`addressToFk`) REFERENCES `address` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT `cmr_supplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; @@ -25223,51 +25444,6 @@ CREATE TABLE `cmrPallet` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='relaciona los cmr con los pallets de expediciones'; /*!40101 SET character_set_client = @saved_cs_client */; --- --- Temporary table structure for view `cmr_list` --- - -DROP TABLE IF EXISTS `cmr_list`; -/*!50001 DROP VIEW IF EXISTS `cmr_list`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `cmr_list` AS SELECT - 1 AS `cmrFk`, - 1 AS `ticketFk`, - 1 AS `truckPlate`, - 1 AS `observations`, - 1 AS `senderInstruccions`, - 1 AS `paymentInstruccions`, - 1 AS `specialAgreements`, - 1 AS `created`, - 1 AS `packagesList`, - 1 AS `clientName`, - 1 AS `clientPostalCode`, - 1 AS `clientStreet`, - 1 AS `clientCity`, - 1 AS `clientProvince`, - 1 AS `clientCountry`, - 1 AS `companyName`, - 1 AS `companyStreet`, - 1 AS `companyPostCode`, - 1 AS `companyCity`, - 1 AS `companyCountry`, - 1 AS `warehouseAddress`, - 1 AS `shipped`, - 1 AS `clientOficialName`, - 1 AS `supplierFk`, - 1 AS `carrierName`, - 1 AS `carrierStreet`, - 1 AS `carrierPostCode`, - 1 AS `carrierCity`, - 1 AS `carrierCountry`, - 1 AS `phone`, - 1 AS `mobile`, - 1 AS `addressFk`, - 1 AS `stamp`, - 1 AS `merchandiseDetail` */; -SET character_set_client = @saved_cs_client; - -- -- Table structure for table `collection` -- @@ -25448,6 +25624,140 @@ CREATE TABLE `collectionVolumetry` ( CONSTRAINT `collectionVolumetry_FK_1` FOREIGN KEY (`trainFk`) REFERENCES `train` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`collectionVolumetry_afterInsert` + AFTER INSERT ON `collectionVolumetry` + FOR EACH ROW +BEGIN + DECLARE vJSON JSON DEFAULT JSON_OBJECT(); + DECLARE vUserFk INT DEFAULT account.myUser_getId(); + + SET vJSON = JSON_MERGE(JSON_OBJECT('id', NEW.id), vJSON); + SET vJSON = JSON_MERGE(JSON_OBJECT('level', NEW.level), vJSON); + SET vJSON = JSON_MERGE(JSON_OBJECT('lines', NEW.lines), vJSON); + SET vJSON = JSON_MERGE(JSON_OBJECT('liters', NEW.liters), vJSON); + SET vJSON = JSON_MERGE(JSON_OBJECT('height', NEW.height), vJSON); + SET vJSON = JSON_MERGE(JSON_OBJECT('itemPackingTypeFk', NEW.itemPackingTypeFk), vJSON); + SET vJSON = JSON_MERGE(JSON_OBJECT('trainFk', NEW.trainFk), vJSON); + + SET vJSON = JSON_MERGE(JSON_OBJECT('userFk', vUserFk), vJSON); + SET vJSON = JSON_MERGE(JSON_OBJECT('action', 'insert'), vJSON); + + SET vJSON = util.notification_send( + 'modified-collection-volumetry', + JSON_OBJECT('data', JSON_EXTRACT(vJSON, '$')), + vUserFk + ); +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 */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`collectionVolumetry_afterUpdate` + AFTER UPDATE ON `collectionVolumetry` + FOR EACH ROW +BEGIN + DECLARE vJSON JSON DEFAULT JSON_OBJECT(); + DECLARE vUserFk INT DEFAULT account.myUser_getId(); + + IF NOT (NEW.id <=> OLD.id) THEN + SET vJSON = JSON_MERGE(JSON_OBJECT('id', NEW.id), vJSON); + END IF; + + IF NOT (NEW.`level` <=> OLD.`level`) THEN + SET vJSON = JSON_MERGE(JSON_OBJECT('level', NEW.`level`), vJSON); + END IF; + + IF NOT (NEW.`lines` <=> OLD.`lines`) THEN + SET vJSON = JSON_MERGE(JSON_OBJECT('lines', NEW.`lines`), vJSON); + END IF; + + IF NOT (NEW.liters <=> OLD.liters) THEN + SET vJSON = JSON_MERGE(JSON_OBJECT('liters', NEW.liters), vJSON); + END IF; + + IF NOT (NEW.height <=> OLD.height) THEN + SET vJSON = JSON_MERGE(JSON_OBJECT('height', NEW.height), vJSON); + END IF; + + IF NOT (NEW.itemPackingTypeFk <=> OLD.itemPackingTypeFk) THEN + SET vJSON = JSON_MERGE(JSON_OBJECT('itemPackingTypeFk', NEW.itemPackingTypeFk), vJSON); + END IF; + + IF NOT (NEW.trainFk <=> OLD.trainFk) THEN + SET vJSON = JSON_MERGE(JSON_OBJECT('trainFk', NEW.trainFk), vJSON); + END IF; + + SET vJSON = JSON_MERGE(JSON_OBJECT('userFk', vUserFk), vJSON); + SET vJSON = JSON_MERGE(JSON_OBJECT('action', 'update'), vJSON); + + SET vJSON = util.notification_send( + 'modified-collection-volumetry', + JSON_OBJECT('data', JSON_EXTRACT(vJSON, '$')), + vUserFk + ); +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 */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`collectionVolumetry_afterDelete` + AFTER DELETE ON `collectionVolumetry` + FOR EACH ROW +BEGIN + DECLARE vJSON JSON DEFAULT JSON_OBJECT(); + DECLARE vUserFk INT DEFAULT account.myUser_getId(); + + SET vJSON = JSON_MERGE(JSON_OBJECT('id', OLD.id), vJSON); + SET vJSON = JSON_MERGE(JSON_OBJECT('level', OLD.level), vJSON); + SET vJSON = JSON_MERGE(JSON_OBJECT('lines', OLD.lines), vJSON); + SET vJSON = JSON_MERGE(JSON_OBJECT('liters', OLD.liters), vJSON); + SET vJSON = JSON_MERGE(JSON_OBJECT('height', OLD.height), vJSON); + SET vJSON = JSON_MERGE(JSON_OBJECT('itemPackingTypeFk', OLD.itemPackingTypeFk), vJSON); + SET vJSON = JSON_MERGE(JSON_OBJECT('trainFk', OLD.trainFk), vJSON); + + SET vJSON = JSON_MERGE(JSON_OBJECT('userFk', vUserFk), vJSON); + SET vJSON = JSON_MERGE(JSON_OBJECT('action', 'delete'), vJSON); + + SET vJSON = util.notification_send( + 'modified-collection-volumetry', + JSON_OBJECT('data', JSON_EXTRACT(vJSON, '$')), + vUserFk + ); +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 */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; -- -- Table structure for table `collectionWagon` @@ -25458,14 +25768,14 @@ DROP TABLE IF EXISTS `collectionWagon`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `collectionWagon` ( `collectionFk` int(11) NOT NULL, - `wagonFk` int(11) NOT NULL, + `wagonFk` varchar(6) NOT NULL, `position` int(11) unsigned NOT NULL, PRIMARY KEY (`collectionFk`,`position`), UNIQUE KEY `collectionWagon_unique` (`collectionFk`,`wagonFk`), - KEY `collectionWagon_wagon` (`wagonFk`), - CONSTRAINT `collectionWagon_collection` FOREIGN KEY (`collectionFk`) REFERENCES `collection` (`id`) ON UPDATE CASCADE, - CONSTRAINT `collectionWagon_wagon` FOREIGN KEY (`wagonFk`) REFERENCES `wagon` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci; + KEY `collectionWagon_FK_1` (`wagonFk`), + CONSTRAINT `collectionWagon_FK_1` FOREIGN KEY (`wagonFk`) REFERENCES `wagon` (`id`) ON UPDATE CASCADE, + CONSTRAINT `collectionWagon_collection` FOREIGN KEY (`collectionFk`) REFERENCES `collection` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; -- @@ -25477,16 +25787,18 @@ DROP TABLE IF EXISTS `collectionWagonTicket`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `collectionWagonTicket` ( `ticketFk` int(11) NOT NULL, - `wagonFk` int(11) NOT NULL, + `wagonFk` varchar(6) NOT NULL, `trayFk` int(11) unsigned NOT NULL, - `side` set('L','R') DEFAULT NULL, - PRIMARY KEY (`ticketFk`), - KEY `collectionWagonTicket_wagon` (`wagonFk`), + `side` set('L','R') CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL, + `rgb` varchar(30) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL COMMENT 'Color de la balda', + `height` int(11) DEFAULT NULL COMMENT 'altura de la balda', + PRIMARY KEY (`ticketFk`,`trayFk`), KEY `collectionWagonTicket_tray` (`trayFk`), - CONSTRAINT `collectionWagonTicket_ticket` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON UPDATE CASCADE, - CONSTRAINT `collectionWagonTicket_tray` FOREIGN KEY (`trayFk`) REFERENCES `wagonTypeTray` (`id`) ON UPDATE CASCADE, - CONSTRAINT `collectionWagonTicket_wagon` FOREIGN KEY (`wagonFk`) REFERENCES `wagon` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci; + KEY `collectionWagonTicket_FK_1` (`wagonFk`), + CONSTRAINT `collectionWagonTicket_FK` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON UPDATE CASCADE, + CONSTRAINT `collectionWagonTicket_FK_1` FOREIGN KEY (`wagonFk`) REFERENCES `wagon` (`id`) ON UPDATE CASCADE, + CONSTRAINT `collectionWagonTicket_tray` FOREIGN KEY (`trayFk`) REFERENCES `wagonTypeTray` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; -- @@ -25609,6 +25921,23 @@ SET character_set_client = utf8; 1 AS `footnotes` */; SET character_set_client = @saved_cs_client; +-- +-- Table structure for table `comparativeConfig` +-- + +DROP TABLE IF EXISTS `comparativeConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `comparativeConfig` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `defaultDayRange` int(10) unsigned DEFAULT NULL COMMENT 'Rango de días predeterminado si no se especifica', + `weekRange` int(10) unsigned DEFAULT NULL COMMENT 'La cantidad de semanas que se restarán y sumarán', + `maxDayRange` int(10) unsigned DEFAULT NULL COMMENT 'El rango máximo de días antes de utilizar el rango de días predeterminado', + `minDayRange` int(10) unsigned DEFAULT NULL COMMENT 'El rango mínimo de días antes de utilizar el rango de días predeterminado', + PRIMARY KEY (`id`) +) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `comparativeFilterType` -- @@ -26062,34 +26391,6 @@ CREATE TABLE `cplusCorrectingType` ( ) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; --- --- Table structure for table `cplusInvoiceType472` --- - -DROP TABLE IF EXISTS `cplusInvoiceType472`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `cplusInvoiceType472` ( - `id` int(10) unsigned NOT NULL, - `description` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='(*18) TIPO FACTURA (Asientos)SOPORTADO – DEDUCIBLE (472)'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `siiTypeInvoiceOut` --- - -DROP TABLE IF EXISTS `siiTypeInvoiceOut`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `siiTypeInvoiceOut` ( - `id` int(10) unsigned NOT NULL, - `description` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='(*18) TIPO FACTURA (Asientos)REPERCUTIDO - DEVENGADO (477)'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Table structure for table `cplusRectificationType` -- @@ -26146,34 +26447,6 @@ CREATE TABLE `cplusTerIdNif` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; --- --- Table structure for table `cplusTrascendency472` --- - -DROP TABLE IF EXISTS `cplusTrascendency472`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `cplusTrascendency472` ( - `id` int(10) unsigned NOT NULL, - `description` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='(*15) CLAVE DE RÉGIMEN ESPECIAL O TRASCENDENCIA(Asientos)SOPORTADO – DEDUCIBLE (472)'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `cplusTrascendency477` --- - -DROP TABLE IF EXISTS `cplusTrascendency477`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `cplusTrascendency477` ( - `id` int(10) unsigned NOT NULL, - `description` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='(*15) CLAVE DE RÉGIMEN ESPECIAL O TRASCENDENCIA(Asientos) REPERCUTIDO - DEVENGADO (477)'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Table structure for table `creditClassification` -- @@ -27340,18 +27613,15 @@ DROP TABLE IF EXISTS `duaTax`; CREATE TABLE `duaTax` ( `id` int(11) NOT NULL AUTO_INCREMENT, `duaFk` int(11) NOT NULL, - `supplierFk` int(10) unsigned NOT NULL, `taxClassFk` tinyint(3) unsigned NOT NULL, `base` decimal(10,2) NOT NULL, `rate` decimal(5,2) NOT NULL, `tax` decimal(10,2) NOT NULL, PRIMARY KEY (`id`), KEY `fk_dua_tax_awb_dua1_idx` (`duaFk`), - KEY `duaTax_fk2_idx` (`supplierFk`), KEY `duaTax_fk3_idx` (`taxClassFk`), CONSTRAINT `duaTax_fk1` FOREIGN KEY (`duaFk`) REFERENCES `dua` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `duaTax_fk3` FOREIGN KEY (`taxClassFk`) REFERENCES `taxClass` (`id`) ON UPDATE CASCADE, - CONSTRAINT `duaTax_supplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON UPDATE CASCADE + CONSTRAINT `duaTax_fk3` FOREIGN KEY (`taxClassFk`) REFERENCES `taxClass` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; @@ -28049,31 +28319,6 @@ CREATE TABLE `errorLogApp` ( ) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Guarda un registro de errores e la app de almacén'; /*!40101 SET character_set_client = @saved_cs_client */; --- --- Table structure for table `errorProduction` --- - -DROP TABLE IF EXISTS `errorProduction`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `errorProduction` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `userFk` int(11) DEFAULT NULL, - `firstname` varchar(100) DEFAULT NULL, - `lastname` varchar(100) DEFAULT NULL, - `rol` varchar(100) DEFAULT NULL, - `ticketNumber` int(11) DEFAULT NULL, - `lineNumber` int(11) DEFAULT NULL, - `error` int(11) DEFAULT NULL, - `volume` double DEFAULT NULL, - `hourStart` varchar(100) DEFAULT NULL, - `hourEnd` varchar(100) DEFAULT NULL, - `hourWorked` varchar(100) DEFAULT NULL, - `dated` date DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Table structure for table `erte` -- @@ -28197,6 +28442,10 @@ CREATE TABLE `expedition` ( `hasNewRoute` tinyint(1) NOT NULL DEFAULT 0, `isBox` int(11) GENERATED ALWAYS AS (`freightItemFk`) VIRTUAL COMMENT 'Columna virtual provisional para Salix', `editorFk` int(10) unsigned DEFAULT NULL, + `packingSiteFk` int(11) DEFAULT NULL, + `monitorId` varchar(255) DEFAULT NULL, + `started` timestamp NOT NULL, + `ended` timestamp NOT NULL, PRIMARY KEY (`id`), KEY `index1` (`agencyModeFk`), KEY `index2` (`freightItemFk`), @@ -28207,7 +28456,9 @@ CREATE TABLE `expedition` ( KEY `workerFk` (`workerFk`), KEY `expedition_FK` (`stateTypeFk`), KEY `expedition_fk_editor` (`editorFk`), + KEY `expedition_FK_1` (`packingSiteFk`), CONSTRAINT `expedition_FK` FOREIGN KEY (`stateTypeFk`) REFERENCES `expeditionStateType` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `expedition_FK_1` FOREIGN KEY (`packingSiteFk`) REFERENCES `packingSite` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT `expedition_fk1` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`) ON UPDATE CASCADE, CONSTRAINT `expedition_fk2` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `expedition_fk3` FOREIGN KEY (`packagingFk`) REFERENCES `packaging` (`id`) ON UPDATE CASCADE, @@ -28596,19 +28847,17 @@ CREATE TABLE `expeditionState` ( /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb3 */ ; -/*!50003 SET character_set_results = utf8mb3 */ ; -/*!50003 SET collation_connection = utf8mb3_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER expeditionState_BeforeInsert -BEFORE INSERT -ON expeditionState FOR EACH ROW +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`expeditionState_BeforeInsert` + BEFORE INSERT ON `expeditionState` + FOR EACH ROW BEGIN - - SET NEW.userFk = account.myUser_getId(); - + SET NEW.userFk = IFNULL(NEW.userFk, account.myUser_getId()); END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -29165,7 +29414,7 @@ DROP TABLE IF EXISTS `greuge`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `greuge` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `clientFk` int(10) unsigned NOT NULL, + `clientFk` int(11) NOT NULL, `description` varchar(45) NOT NULL, `amount` decimal(10,2) NOT NULL, `shipped` datetime NOT NULL DEFAULT current_timestamp(), @@ -29183,6 +29432,7 @@ CREATE TABLE `greuge` ( KEY `greuge_fk_editor` (`editorFk`), CONSTRAINT `Id_Ticket_Greuge_Ticket` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `greuge_FK` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `greuge_FK_1` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `greuge_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`), CONSTRAINT `greuges_type_fk` FOREIGN KEY (`greugeTypeFk`) REFERENCES `greugeType` (`id`) ON DELETE SET NULL ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci ROW_FORMAT=COMPACT; @@ -29604,11 +29854,11 @@ CREATE TABLE `invoiceIn` ( `docFk` int(11) DEFAULT NULL, `booked` date DEFAULT NULL COMMENT 'Fecha de contabilizacion', `operated` date DEFAULT NULL COMMENT 'Fecha de entrega de la mercancia o el suministro', - `cplusInvoiceType472Fk` int(10) unsigned DEFAULT 1, + `siiTypeInvoiceInFk` int(10) unsigned DEFAULT 1, `cplusRectificationTypeFk` int(10) unsigned DEFAULT 1, `cplusSubjectOpFk` int(10) unsigned DEFAULT 1, `cplusTaxBreakFk` int(10) unsigned DEFAULT 1, - `cplusTrascendency472Fk` int(10) unsigned DEFAULT 1, + `siiTrascendencyInvoiceInFk` int(10) unsigned DEFAULT 1, `bookEntried` date DEFAULT NULL COMMENT 'Fecha Asiento', `isVatDeductible` tinyint(1) NOT NULL DEFAULT 1, `withholdingSageFk` smallint(6) DEFAULT NULL COMMENT 'Tipos de retención SAGE', @@ -29623,9 +29873,9 @@ CREATE TABLE `invoiceIn` ( KEY `fecha` (`issued`), KEY `recibida_ibfk_3_idx` (`cplusSubjectOpFk`), KEY `recibida_ibfk_4_idx` (`cplusTaxBreakFk`), - KEY `recibida_ibfk_5_idx` (`cplusInvoiceType472Fk`), + KEY `recibida_ibfk_5_idx` (`siiTypeInvoiceInFk`), KEY `recibida_ibfk_6` (`cplusRectificationTypeFk`), - KEY `recibida_ibfk_7` (`cplusTrascendency472Fk`), + KEY `recibida_ibfk_7` (`siiTrascendencyInvoiceInFk`), KEY `invoiceIn_withholdingFk_idx` (`withholdingSageFk`), KEY `invoiceIn_expenceFkDeductible_idx` (`expenceFkDeductible`), KEY `invoiceIn_fk_editor` (`editorFk`), @@ -29636,9 +29886,9 @@ CREATE TABLE `invoiceIn` ( CONSTRAINT `invoiceIn_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`), CONSTRAINT `invoiceIn_ibfk_3` FOREIGN KEY (`cplusSubjectOpFk`) REFERENCES `cplusSubjectOp` (`id`) ON UPDATE CASCADE, CONSTRAINT `invoiceIn_ibfk_4` FOREIGN KEY (`cplusTaxBreakFk`) REFERENCES `cplusTaxBreak` (`id`) ON UPDATE CASCADE, - CONSTRAINT `invoiceIn_ibfk_5` FOREIGN KEY (`cplusInvoiceType472Fk`) REFERENCES `cplusInvoiceType472` (`id`) ON UPDATE CASCADE, + CONSTRAINT `invoiceIn_ibfk_5` FOREIGN KEY (`siiTypeInvoiceInFk`) REFERENCES `siiTypeInvoiceIn` (`id`) ON UPDATE CASCADE, CONSTRAINT `invoiceIn_ibfk_6` FOREIGN KEY (`cplusRectificationTypeFk`) REFERENCES `cplusRectificationType` (`id`) ON UPDATE CASCADE, - CONSTRAINT `invoiceIn_ibfk_7` FOREIGN KEY (`cplusTrascendency472Fk`) REFERENCES `cplusTrascendency472` (`id`) ON UPDATE CASCADE, + CONSTRAINT `invoiceIn_ibfk_7` FOREIGN KEY (`siiTrascendencyInvoiceInFk`) REFERENCES `siiTrascendencyInvoiceIn` (`id`) ON UPDATE CASCADE, CONSTRAINT `invoiceIn_supplierFk` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON UPDATE CASCADE, CONSTRAINT `invoiceIn_withholdingFk` FOREIGN KEY (`withholdingSageFk`) REFERENCES `sage`.`TiposRetencion` (`CodigoRetencion`) ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; @@ -29825,6 +30075,7 @@ CREATE TABLE `invoiceInConfig` ( `retentionName` varchar(25) NOT NULL, `sageWithholdingFk` smallint(6) NOT NULL, `daysAgo` int(10) unsigned DEFAULT 45 COMMENT 'Días en el pasado para mostrar facturas en invoiceIn series en salix', + `taxRowLimit` int(11) DEFAULT 4 COMMENT 'Número máximo de líneas de IVA que puede tener una factura', PRIMARY KEY (`id`), KEY `invoiceInConfig_sageWithholdingFk` (`sageWithholdingFk`), CONSTRAINT `invoiceInConfig_sageWithholdingFk` FOREIGN KEY (`sageWithholdingFk`) REFERENCES `sage`.`TiposRetencion` (`CodigoRetencion`) ON DELETE CASCADE ON UPDATE CASCADE @@ -30116,6 +30367,7 @@ DELIMITER ;; BEFORE INSERT ON `invoiceInTax` FOR EACH ROW BEGIN + CALL invoiceInTax_afterUpsert(NEW.invoiceInFk); SET NEW.editorFk = account.myUser_getId(); END */;; DELIMITER ; @@ -30136,6 +30388,10 @@ DELIMITER ;; BEFORE UPDATE ON `invoiceInTax` FOR EACH ROW BEGIN + IF NOT (NEW.invoiceInFk <=> OLD.invoiceInFk) THEN + CALL invoiceInTax_afterUpsert(NEW.invoiceInFk); + END IF; + SET NEW.editorFk = account.myUser_getId(); END */;; DELIMITER ; @@ -30217,7 +30473,7 @@ CREATE TABLE `invoiceOut` ( `siiTypeInvoiceOutFk` int(10) unsigned NOT NULL DEFAULT 1, `cplusTaxBreakFk` int(10) unsigned NOT NULL DEFAULT 1, `cplusSubjectOpFk` int(10) unsigned NOT NULL DEFAULT 1, - `cplusTrascendency477Fk` int(10) unsigned NOT NULL DEFAULT 1, + `siiTrascendencyInvoiceOutFk` int(10) unsigned NOT NULL DEFAULT 1, PRIMARY KEY (`id`,`ref`), UNIQUE KEY `Id_Factura` (`ref`), KEY `Id_Banco` (`bankFk`), @@ -30227,7 +30483,7 @@ CREATE TABLE `invoiceOut` ( KEY `Facturas_ibfk_2_idx` (`siiTypeInvoiceOutFk`), KEY `Facturas_ibfk_3_idx` (`cplusSubjectOpFk`), KEY `Facturas_ibfk_4_idx` (`cplusTaxBreakFk`), - KEY `Facturas_ibfk_5_idx` (`cplusTrascendency477Fk`), + KEY `Facturas_ibfk_5_idx` (`siiTrascendencyInvoiceOutFk`), KEY `Facturas_idx_Vencimiento` (`dued`), KEY `invoiceOut_serial` (`serial`), CONSTRAINT `invoiceOut_ibfk_2` FOREIGN KEY (`siiTypeInvoiceOutFk`) REFERENCES `siiTypeInvoiceOut` (`id`) ON UPDATE CASCADE, @@ -30392,7 +30648,7 @@ CREATE TABLE `invoiceOutSerial` ( `isTaxed` tinyint(1) NOT NULL DEFAULT 1, `taxAreaFk` varchar(15) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT 'NATIONAL', `isCEE` tinyint(1) NOT NULL DEFAULT 0, - `siiTypeInvoiceOutFk` int(10) unsigned DEFAULT 1, + `cplusInvoiceType477Fk` int(10) unsigned DEFAULT 1, `footNotes` longtext DEFAULT NULL, `isRefEditable` tinyint(4) NOT NULL DEFAULT 0, `type` enum('global','quick') DEFAULT NULL, @@ -30999,6 +31255,7 @@ CREATE TABLE `itemConfig` ( `validPriorities` varchar(50) NOT NULL DEFAULT '[1,2,3]', `defaultPriority` int(11) NOT NULL DEFAULT 2, `warehouseFk` smallint(6) unsigned DEFAULT NULL, + `downloadMaxAttempts` tinyint(3) DEFAULT NULL COMMENT 'Intentos máximos para que se borre', PRIMARY KEY (`id`), KEY `itemConfig_FK` (`defaultTag`), CONSTRAINT `itemConfig_FK` FOREIGN KEY (`defaultTag`) REFERENCES `tag` (`id`) @@ -31375,11 +31632,14 @@ CREATE TABLE `itemShelving` ( `packagingFk` varchar(10) DEFAULT NULL, `userFk` int(10) unsigned DEFAULT NULL, `isChecked` tinyint(1) DEFAULT NULL COMMENT 'Este valor cambia al escanear un carro. True: Existe. False: Nuevo. Null: No escaneado', + `buyFk` int(11) DEFAULT NULL, PRIMARY KEY (`id`), + UNIQUE KEY `itemShelving_UN` (`buyFk`,`shelvingFk`), KEY `itemShelving_fk1_idx` (`itemFk`), KEY `itemShelving_fk2_idx` (`shelvingFk`), KEY `itemShelving_fk3_idx` (`packagingFk`), KEY `itemShelving_fk3_idx1` (`userFk`), + CONSTRAINT `itemShelvingBuy_FK` FOREIGN KEY (`buyFk`) REFERENCES `buy` (`id`), CONSTRAINT `itemShelving_fk1` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `itemShelving_fk2` FOREIGN KEY (`shelvingFk`) REFERENCES `shelving` (`code`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `itemShelving_fk3` FOREIGN KEY (`packagingFk`) REFERENCES `packaging` (`id`) ON UPDATE CASCADE @@ -31476,23 +31736,16 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemShelving_AFTER_UPDATE` AFTER UPDATE ON `itemShelving` FOR EACH ROW -INSERT INTO vn.itemShelvingLog( itemShelvingFk, - workerFk, - accion, - itemFk, - shelvingFk, - visible, - `grouping`, - packing) - VALUES( NEW.id, - account.myUser_getId(), - 'CAMBIO', - NEW.itemFk, - NEW.shelvingFk, - NEW.visible, - NEW.`grouping`, - NEW.packing - ) */;; + + INSERT INTO itemShelvingLog + SET itemShelvingFk = NEW.id, + workerFk = account.myUser_getId(), + accion = 'CAMBIO', + itemFk = NEW.itemFk, + shelvingFk = NEW.shelvingFk, + visible = NEW.visible, + `grouping` = NEW.`grouping`, + packing = NEW.packing */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; /*!50003 SET character_set_client = @saved_cs_client */ ; @@ -31671,6 +31924,7 @@ CREATE TABLE `itemShelvingSale` ( `quantity` decimal(10,0) NOT NULL DEFAULT 0, `created` timestamp NOT NULL DEFAULT current_timestamp(), `userFk` int(11) unsigned NOT NULL, + `isPicked` tinyint(1) NOT NULL DEFAULT 0, PRIMARY KEY (`id`), KEY `itemShelvingSale_fk1_idx` (`itemShelvingFk`), KEY `itemShelvingSale_fk2_idx` (`saleFk`), @@ -31683,11 +31937,11 @@ CREATE TABLE `itemShelvingSale` ( /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET character_set_client = utf8mb3 */ ; +/*!50003 SET character_set_results = utf8mb3 */ ; +/*!50003 SET collation_connection = utf8mb3_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemShelvingSale_AFTER_INSERT` AFTER INSERT ON `itemShelvingSale` @@ -33385,7 +33639,13 @@ CREATE TABLE `packagingConfig` ( `palletPackaging` varchar(10) DEFAULT 'pallet USA', `carryPackaging` varchar(10) DEFAULT 'cc', `freightItemPackaging` int(11) DEFAULT 71, - PRIMARY KEY (`id`) + `defaultSmallPackageFk` varchar(10) NOT NULL DEFAULT '94p' COMMENT 'bulto pequeño', + `defaultBigPackageFk` varchar(10) NOT NULL DEFAULT '94m' COMMENT 'bulto grande', + PRIMARY KEY (`id`), + KEY `packagingConfig_FK` (`defaultSmallPackageFk`), + KEY `packagingConfig_FK_1` (`defaultBigPackageFk`), + CONSTRAINT `packagingConfig_FK` FOREIGN KEY (`defaultSmallPackageFk`) REFERENCES `packaging` (`id`) ON UPDATE CASCADE, + CONSTRAINT `packagingConfig_FK_1` FOREIGN KEY (`defaultBigPackageFk`) REFERENCES `packaging` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Altura mínima para preparar pedidos en preparacion previa'; /*!40101 SET character_set_client = @saved_cs_client */; @@ -33458,19 +33718,96 @@ CREATE TABLE `packingSite` ( `id` int(11) NOT NULL AUTO_INCREMENT, `code` varchar(10) DEFAULT NULL, `hostFk` int(11) DEFAULT NULL, + `printerRfidFk` tinyint(3) unsigned DEFAULT NULL, `printerFk` tinyint(3) unsigned DEFAULT NULL, `collectionFk` int(11) DEFAULT NULL COMMENT 'Last collection packed on this site', `monitorId` varchar(255) DEFAULT NULL, + `parkingFk` int(11) DEFAULT NULL, + `scannerFk` int(11) DEFAULT NULL, + `screenFk` int(11) DEFAULT NULL, + `editorFk` int(10) unsigned DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `packingSite_UN` (`code`), + UNIQUE KEY `printerRfidFk` (`printerRfidFk`), + UNIQUE KEY `scannerFk` (`scannerFk`), + UNIQUE KEY `screenFk` (`screenFk`), + UNIQUE KEY `packingSite_UNI` (`hostFk`), KEY `packingSite_FK_1` (`printerFk`), - KEY `packingSite_FK` (`hostFk`), KEY `packingSite_FK_2` (`collectionFk`), + KEY `packingSite_FK_3` (`parkingFk`), CONSTRAINT `packingSite_FK` FOREIGN KEY (`hostFk`) REFERENCES `host` (`id`), CONSTRAINT `packingSite_FK_1` FOREIGN KEY (`printerFk`) REFERENCES `printer` (`id`), - CONSTRAINT `packingSite_FK_2` FOREIGN KEY (`collectionFk`) REFERENCES `collection` (`id`) ON DELETE SET NULL ON UPDATE CASCADE + CONSTRAINT `packingSite_FK_2` FOREIGN KEY (`collectionFk`) REFERENCES `collection` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, + CONSTRAINT `packingSite_FK_3` FOREIGN KEY (`parkingFk`) REFERENCES `parking` (`id`) ON DELETE CASCADE ON UPDATE SET NULL, + CONSTRAINT `packingSite_FK_4` FOREIGN KEY (`printerRfidFk`) REFERENCES `printer` (`id`) ON UPDATE CASCADE, + CONSTRAINT `packingSite_FK_5` FOREIGN KEY (`scannerFk`) REFERENCES `scanner` (`id`) ON UPDATE CASCADE, + CONSTRAINT `packingSite_FK_6` FOREIGN KEY (`screenFk`) REFERENCES `screen` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`packingSite_beforeInsert` + BEFORE INSERT ON `packingSite` + FOR EACH ROW +BEGIN + SET NEW.editorFk = account.myUser_getId(); +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 */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`packingSite_beforeUpdate` + BEFORE UPDATE ON `packingSite` + FOR EACH ROW +BEGIN + SET NEW.editorFk = account.myUser_getId(); +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 */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`packingSite_afterDelete` + AFTER DELETE ON `packingSite` + FOR EACH ROW +BEGIN + INSERT INTO packingSiteDeviceLog + SET `action` = 'delete', + `changedModel` = 'PackingSite', + `changedModelId` = OLD.id, + `userFk` = account.myUser_getId(); +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 */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; -- -- Table structure for table `packingSiteAdvanced` @@ -33506,6 +33843,34 @@ CREATE TABLE `packingSiteConfig` ( ) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `packingSiteDeviceLog` +-- + +DROP TABLE IF EXISTS `packingSiteDeviceLog`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `packingSiteDeviceLog` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `originFk` int(11) DEFAULT NULL, + `userFk` int(10) unsigned DEFAULT NULL, + `action` set('insert','update','delete') NOT NULL, + `creationDate` timestamp NULL DEFAULT current_timestamp(), + `description` text CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL, + `changedModel` enum('PackingSite') NOT NULL DEFAULT 'PackingSite', + `oldInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`oldInstance`)), + `newInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`newInstance`)), + `changedModelId` int(11) NOT NULL, + `changedModelValue` varchar(45) DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `userFk` (`userFk`), + KEY `packingSiteDeviceLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`), + KEY `packingSiteDeviceLog_packingSiteDeviceLog` (`originFk`,`creationDate`), + CONSTRAINT `packingSiteDeviceLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `packingSiteDeviceLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `packingSiteLog` -- @@ -34014,13 +34379,13 @@ CREATE TABLE `pgc` ( `cplusTaxBreakFk` int(10) unsigned DEFAULT 1, `mod340` tinyint(1) NOT NULL DEFAULT 0, `mod347` tinyint(1) NOT NULL DEFAULT 0, - `cplusTrascendency477Fk` int(10) unsigned DEFAULT 1, + `siiTrascendencyInvoiceOutFk` int(10) unsigned DEFAULT 1, `isEqualizated` tinyint(1) DEFAULT 0, PRIMARY KEY (`code`), KEY `pgc_fk1_idx` (`cplusTaxBreakFk`), - KEY `pgc_fk2_idx` (`cplusTrascendency477Fk`), + KEY `pgc_fk2_idx` (`siiTrascendencyInvoiceOutFk`), CONSTRAINT `pgc_fk1` FOREIGN KEY (`cplusTaxBreakFk`) REFERENCES `cplusTaxBreak` (`id`) ON UPDATE CASCADE, - CONSTRAINT `pgc_fk2` FOREIGN KEY (`cplusTrascendency477Fk`) REFERENCES `cplusTrascendency477` (`id`) ON UPDATE CASCADE + CONSTRAINT `pgc_fk2` FOREIGN KEY (`siiTrascendencyInvoiceOutFk`) REFERENCES `siiTrascendencyInvoiceOut` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Plan General Contable'; /*!40101 SET character_set_client = @saved_cs_client */; @@ -34511,6 +34876,7 @@ CREATE TABLE `printer` ( `isLabeler` tinyint(1) DEFAULT 0 COMMENT 'Indica si es impresora de etiquetas', `sectorFk` int(11) DEFAULT NULL, `paperSizeFk` varchar(100) DEFAULT NULL, + `isRfid` tinyint(4) NOT NULL DEFAULT 0, PRIMARY KEY (`id`), UNIQUE KEY `printer_UN` (`reference`), UNIQUE KEY `printer_UN1` (`macWifi`), @@ -34596,10 +34962,40 @@ CREATE TABLE `productionConfig` ( `pendingCollectionsAge` tinyint(3) unsigned DEFAULT 6, `maxNotAssignedCollectionLifeTime` time NOT NULL DEFAULT '00:10:00' COMMENT 'Tiempo de vida de las colecciones sin asignar. Cuando se supera son eliminadas', `maxProductionScopeDays` int(11) NOT NULL DEFAULT 1 COMMENT 'maximo numero de dias en F11', - PRIMARY KEY (`id`) + `orderMode` enum('Location','Age') NOT NULL DEFAULT 'Location', + `stockScopeDays` int(11) DEFAULT 1 COMMENT 'Días a futuro al revisar el stock', + `shortageAddressFk` int(11) DEFAULT NULL COMMENT 'Consignatario por defecto para añadir un item de alta', + PRIMARY KEY (`id`), + KEY `productionConfig_FK` (`shortageAddressFk`), + CONSTRAINT `productionConfig_FK` FOREIGN KEY (`shortageAddressFk`) REFERENCES `address` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Recoge los parámetros que condicionan la producción'; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `productionError` +-- + +DROP TABLE IF EXISTS `productionError`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `productionError` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `userFk` int(11) DEFAULT NULL, + `firstname` varchar(100) DEFAULT NULL, + `lastname` varchar(100) DEFAULT NULL, + `rol` varchar(100) DEFAULT NULL, + `ticketNumber` int(11) DEFAULT NULL, + `lineNumber` int(11) DEFAULT NULL, + `error` int(11) DEFAULT NULL, + `volume` double DEFAULT NULL, + `hourStart` varchar(100) DEFAULT NULL, + `hourEnd` varchar(100) DEFAULT NULL, + `hourWorked` varchar(100) DEFAULT NULL, + `dated` date DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Temporary table structure for view `productionVolume` -- @@ -34867,6 +35263,7 @@ CREATE TABLE `province` ( `geoFk` int(11) DEFAULT NULL, `autonomyFk` int(11) DEFAULT NULL, PRIMARY KEY (`id`), + UNIQUE KEY `countryName_UN` (`countryFk`,`name`), KEY `Paises_Id` (`countryFk`), KEY `warehouse_Id` (`warehouseFk`), KEY `provicne_zone_fk_idx` (`zoneFk`), @@ -35150,7 +35547,7 @@ CREATE TABLE `rateLog` ( KEY `rateLog_originFk` (`originFk`,`creationDate`), CONSTRAINT `rateOriginFk` FOREIGN KEY (`originFk`) REFERENCES `rate` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `rateUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; +) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; -- @@ -35842,8 +36239,6 @@ DROP TABLE IF EXISTS `routeConfig`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `routeConfig` ( `id` int(10) unsigned NOT NULL, - `kmRate` decimal(10,4) DEFAULT NULL, - `kmTruckRate` decimal(10,4) DEFAULT NULL, `m3Distribution` decimal(10,4) DEFAULT NULL, `m3Management` decimal(10,2) DEFAULT NULL, `m3Palletization` decimal(10,2) DEFAULT NULL, @@ -36050,24 +36445,6 @@ CREATE TABLE `routesMonitor` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; --- --- Temporary table structure for view `routesReduced` --- - -DROP TABLE IF EXISTS `routesReduced`; -/*!50001 DROP VIEW IF EXISTS `routesReduced`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `routesReduced` AS SELECT - 1 AS `description`, - 1 AS `name`, - 1 AS `routeFk`, - 1 AS `eta`, - 1 AS `bufferFk`, - 1 AS `beachFk`, - 1 AS `itempackingTypeFk` */; -SET character_set_client = @saved_cs_client; - -- -- Table structure for table `sale` -- @@ -36081,7 +36458,7 @@ CREATE TABLE `sale` ( `ticketFk` int(11) NOT NULL, `concept` varchar(50) DEFAULT NULL, `quantity` decimal(10,2) NOT NULL DEFAULT 0.00, - `originalQuantity` double(9,1) DEFAULT NULL, + `originalQuantity` double(9,1) DEFAULT NULL COMMENT 'Se utiliza para notificar a través de rocket los cambios de quantity', `price` decimal(10,2) NOT NULL DEFAULT 0.00, `discount` tinyint(2) unsigned NOT NULL DEFAULT 0, `priceFixed` decimal(10,2) NOT NULL DEFAULT 0.00, @@ -36096,6 +36473,7 @@ CREATE TABLE `sale` ( KEY `Id_Ticket` (`ticketFk`), KEY `itemFk_ticketFk` (`itemFk`,`ticketFk`), KEY `sale_fk_editor` (`editorFk`), + KEY `sale_created_IDX` (`created`) USING BTREE, CONSTRAINT `movement_ticket_id` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `sale_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`), CONSTRAINT `sale_ibfk_1` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON UPDATE CASCADE @@ -36115,6 +36493,7 @@ DELIMITER ;; FOR EACH ROW BEGIN SET NEW.editorFk = account.myUser_getId(); + SET NEW.originalQuantity = NEW.quantity; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -36578,8 +36957,8 @@ CREATE TABLE `saleGroupDetail` ( `saleFk` int(11) NOT NULL, `saleGroupFk` int(11) NOT NULL, PRIMARY KEY (`id`), + UNIQUE KEY `saleGroupDetail_UN` (`saleFk`), KEY `saleGroupDetail_FK_1` (`saleGroupFk`), - KEY `saleFk` (`saleFk`), CONSTRAINT `saleGroupDetail_ibfk_1` FOREIGN KEY (`saleFk`) REFERENCES `sale` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='relaciona sale y saleGroup'; /*!40101 SET character_set_client = @saved_cs_client */; @@ -36916,6 +37295,9 @@ CREATE TABLE `salespersonConfig` ( `id` int(11) NOT NULL AUTO_INCREMENT, `manaMaxRate` decimal(3,2) DEFAULT 0.05 COMMENT 'Valor máximo a recficar en una línea por el maná de un comercial', `manaMinRate` decimal(3,2) DEFAULT -0.05 COMMENT 'Valor mínimo a recficar en una línea por el maná de un comercial', + `manaDateFrom` date NOT NULL DEFAULT '2023-01-01' COMMENT 'first date to count mana', + `manaFromDays` int(11) NOT NULL DEFAULT 90 COMMENT 'Range of days from mana calculation', + `manaToDays` int(11) NOT NULL DEFAULT 30 COMMENT 'Range of days to mana calculation', PRIMARY KEY (`id`) ) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -36940,6 +37322,66 @@ CREATE TABLE `sample` ( ) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `scanner` +-- + +DROP TABLE IF EXISTS `scanner`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `scanner` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(100) NOT NULL, + `modelFk` varchar(50) NOT NULL, + PRIMARY KEY (`id`), + KEY `scanner_FK` (`modelFk`), + CONSTRAINT `scanner_FK` FOREIGN KEY (`modelFk`) REFERENCES `scannerModel` (`code`) ON UPDATE CASCADE +) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `scannerModel` +-- + +DROP TABLE IF EXISTS `scannerModel`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `scannerModel` ( + `code` varchar(50) NOT NULL, + PRIMARY KEY (`code`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `screen` +-- + +DROP TABLE IF EXISTS `screen`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `screen` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(100) NOT NULL, + `modelFk` varchar(50) NOT NULL, + PRIMARY KEY (`id`), + KEY `screen_FK` (`modelFk`), + CONSTRAINT `screen_FK` FOREIGN KEY (`modelFk`) REFERENCES `screenModel` (`code`) ON UPDATE CASCADE +) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `screenModel` +-- + +DROP TABLE IF EXISTS `screenModel`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `screenModel` ( + `code` varchar(50) NOT NULL, + PRIMARY KEY (`code`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `sector` -- @@ -36963,13 +37405,12 @@ CREATE TABLE `sector` ( `isHideForPickers` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'sector a ocultar a los sacadores', `isReserve` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Sectores de reserva, como Albenfruit o Fuentes', `mainPrinterFk` tinyint(3) unsigned DEFAULT NULL, - PRIMARY KEY (`id`,`warehouseFk`), + PRIMARY KEY (`id`), UNIQUE KEY `code_UNIQUE` (`code`), KEY `sector_fk1_idx` (`warehouseFk`), KEY `sector_report` (`reportFk`), KEY `sector_FK` (`sonFk`,`warehouseFk`), KEY `sector_FK_1` (`mainPrinterFk`), - CONSTRAINT `sector_FK` FOREIGN KEY (`sonFk`, `warehouseFk`) REFERENCES `sector` (`id`, `warehouseFk`) ON UPDATE CASCADE, CONSTRAINT `sector_FK_1` FOREIGN KEY (`mainPrinterFk`) REFERENCES `printer` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `sector_fk1` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `sector_report` FOREIGN KEY (`reportFk`) REFERENCES `report` (`id`) @@ -37293,6 +37734,7 @@ CREATE TABLE `shelving` ( `isSpam` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'señala las matrículas con producto que se puede llevar a la reserva', `isRecyclable` tinyint(1) NOT NULL DEFAULT 1 COMMENT 'las matrículas marcadas como reciclables se liberan cada noche desde vn.shelving_clean para poder volver a utilizarlas', `editorFk` int(10) unsigned DEFAULT NULL, + `isMoving` tinyint(1) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `shelving_UN` (`code`), KEY `shelving_fk1_idx` (`parkingFk`), @@ -37347,6 +37789,9 @@ BEGIN CALL util.throw('NOT_EMPTY_CODE_ALLOWED'); END IF; + IF NOT(OLD.parkingFk <=> NEW.parkingFK) THEN + SET NEW.isMoving = FALSE; + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -37406,6 +37851,66 @@ CREATE TABLE `shelvingLog` ( ) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `siiTrascendencyInvoiceIn` +-- + +DROP TABLE IF EXISTS `siiTrascendencyInvoiceIn`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `siiTrascendencyInvoiceIn` ( + `id` int(10) unsigned NOT NULL, + `description` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Clave de régimen especial o trascendencia en facturas recibidas en el suministro de inmediato'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `siiTrascendencyInvoiceOut` +-- + +DROP TABLE IF EXISTS `siiTrascendencyInvoiceOut`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `siiTrascendencyInvoiceOut` ( + `id` int(10) unsigned NOT NULL, + `description` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Clave de régimen especial o trascendencia en facturas expedidas del suministro de inmediato'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `siiTypeInvoiceIn` +-- + +DROP TABLE IF EXISTS `siiTypeInvoiceIn`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `siiTypeInvoiceIn` ( + `id` int(10) unsigned NOT NULL, + `code` varchar(2) NOT NULL, + `description` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `code_UNIQUE` (`code`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tipo de Factura Recibidas en el suministro de inmediato'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `siiTypeInvoiceOut` +-- + +DROP TABLE IF EXISTS `siiTypeInvoiceOut`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `siiTypeInvoiceOut` ( + `id` int(10) unsigned NOT NULL, + `code` varchar(2) NOT NULL, + `description` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `code_UNIQUE` (`code`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tipo de Factura Emitidas en el suministro de inmediato'; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `silexACL` -- @@ -37909,7 +38414,7 @@ DROP TABLE IF EXISTS `supplier`; CREATE TABLE `supplier` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL, - `account` varchar(10) DEFAULT NULL, + `account` varchar(10) NOT NULL DEFAULT '4100000000' COMMENT 'Default accounting code for suppliers.', `street` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL, `city` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL, `provinceFk` smallint(5) unsigned DEFAULT NULL, @@ -37964,7 +38469,8 @@ CREATE TABLE `supplier` ( CONSTRAINT `supplier_transactionFk` FOREIGN KEY (`transactionTypeSageFk`) REFERENCES `sage`.`TiposTransacciones` (`CodigoTransaccion`) ON UPDATE CASCADE, CONSTRAINT `supplier_withholdingFk` FOREIGN KEY (`withholdingSageFk`) REFERENCES `sage`.`TiposRetencion` (`CodigoRetencion`) ON UPDATE CASCADE, CONSTRAINT `supplier_workerFk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE, - CONSTRAINT `suppplier_supplierActivityFk` FOREIGN KEY (`supplierActivityFk`) REFERENCES `supplierActivity` (`code`) ON UPDATE CASCADE + CONSTRAINT `suppplier_supplierActivityFk` FOREIGN KEY (`supplierActivityFk`) REFERENCES `supplierActivity` (`code`) ON UPDATE CASCADE, + CONSTRAINT `supplierAccountTooShort` CHECK (octet_length(`account`) = 10) ) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci; /*!40101 SET character_set_client = @saved_cs_client */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; @@ -38185,7 +38691,7 @@ DROP TABLE IF EXISTS `supplierAddress`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `supplierAddress` ( `id` int(11) NOT NULL AUTO_INCREMENT, - `supplierFk` int(11) DEFAULT NULL, + `supplierFk` int(10) unsigned DEFAULT NULL, `nickname` varchar(40) DEFAULT NULL, `street` varchar(255) DEFAULT NULL, `provinceFk` smallint(6) unsigned DEFAULT NULL, @@ -38197,6 +38703,8 @@ CREATE TABLE `supplierAddress` ( PRIMARY KEY (`id`), KEY `supplierAddress_province_fk` (`provinceFk`), KEY `supplierAddress_fk_editor` (`editorFk`), + KEY `supplierAddress_FK` (`supplierFk`), + CONSTRAINT `supplierAddress_FK` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `supplierAddress_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`), CONSTRAINT `supplierAddress_province_fk` FOREIGN KEY (`provinceFk`) REFERENCES `province` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; @@ -38883,7 +39391,7 @@ BEGIN SET NEW.editorFk = account.myUser_getId(); - IF !(NEW.routeFk <=> OLD.routeFk) THEN + IF NOT (NEW.routeFk <=> OLD.routeFk) THEN INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) SELECT r.id FROM vn.route r @@ -38893,7 +39401,7 @@ BEGIN GROUP BY r.id; END IF; - IF !(DATE(NEW.shipped) <=> DATE(OLD.shipped)) THEN + IF NOT (DATE(NEW.shipped) <=> DATE(OLD.shipped)) THEN IF YEAR(NEW.shipped) < 2000 THEN SIGNAL SQLSTATE '46000' SET MESSAGE_TEXT = 'Year cannot be lesser than 2000'; @@ -38905,7 +39413,7 @@ BEGIN END IF; - IF !(NEW.isDeleted <=> OLD.isDeleted) AND NEW.isDeleted THEN + IF NOT (NEW.isDeleted <=> OLD.isDeleted) AND NEW.isDeleted THEN INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) SELECT r.id FROM vn.ticket t @@ -38924,7 +39432,7 @@ BEGIN CALL util.throw ('This ticket is deleted'); END IF; - IF !(NEW.routeFk <=> OLD.routeFk) AND NEW.routeFk IS NOT NULL THEN + IF NOT (NEW.routeFk <=> OLD.routeFk) AND NEW.routeFk IS NOT NULL THEN SELECT MAX(TIME(shipped)) INTO vNewTime FROM vn.ticket WHERE routeFk = NEW.routeFk @@ -40178,7 +40686,7 @@ CREATE TABLE `ticketTracking` ( `notes` varchar(255) DEFAULT NULL, `created` timestamp NULL DEFAULT current_timestamp(), `ticketFk` int(11) DEFAULT NULL, - `workerFk` int(11) DEFAULT NULL, + `workerFk` int(10) unsigned DEFAULT NULL, `supervisorFk` int(10) unsigned DEFAULT NULL, `editorFk` int(10) unsigned DEFAULT NULL, PRIMARY KEY (`id`), @@ -40191,6 +40699,7 @@ CREATE TABLE `ticketTracking` ( KEY `ticketTracking_created_IDX` (`created`) USING BTREE, CONSTRAINT `inter_state` FOREIGN KEY (`stateFk`) REFERENCES `state` (`id`) ON UPDATE CASCADE, CONSTRAINT `responsable` FOREIGN KEY (`supervisorFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE, + CONSTRAINT `ticketTracking_FK3` FOREIGN KEY (`workerFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE, CONSTRAINT `ticketTracking_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`), CONSTRAINT `ticketTracking_ibfk_1` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; @@ -40499,7 +41008,7 @@ CREATE TABLE `till` ( `isAccountable` tinyint(1) NOT NULL DEFAULT 0, `serie` varchar(2) DEFAULT NULL, `number` int(11) DEFAULT NULL, - `concept` varchar(50) NOT NULL, + `concept` varchar(50) DEFAULT NULL, `in` decimal(10,2) DEFAULT NULL, `out` decimal(10,2) DEFAULT NULL, `bankFk` int(11) DEFAULT 1, @@ -40526,28 +41035,6 @@ CREATE TABLE `till` ( CONSTRAINT `till_ibfk_3` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`till_beforeInsert` - BEFORE INSERT ON `till` - FOR EACH ROW -BEGIN - IF NEW.concept IS NULL OR NEW.concept REGEXP '^[[:space:]]*$' THEN - SET NEW.concept = 'SIN DETALLE'; - END IF; -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 */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -- -- Table structure for table `tillConfig` @@ -40873,6 +41360,22 @@ CREATE TABLE `trainingCourseType` ( ) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Lista de las formaciones'; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `transitoryDuaUnified` +-- + +DROP TABLE IF EXISTS `transitoryDuaUnified`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `transitoryDuaUnified` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `supplierFk` int(10) unsigned DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `transitoryDuaUnified_FK` (`supplierFk`), + CONSTRAINT `transitoryDuaUnified_FK` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Transitarios que al contabilizar sus entradas sólo generan un único DUA para todos los proveedores'; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `travel` -- @@ -40965,6 +41468,14 @@ DELIMITER ;; BEGIN SET NEW.editorFk = account.myUser_getId(); + IF ((NOT NEW.shipped <=> OLD.shipped ) + OR (NOT NEW.landed <=> OLD.landed ) + OR (NOT NEW.warehouseInFk <=> OLD.warehouseInFk ) + OR (NOT NEW.warehouseOutFk <=> OLD.warehouseOutFk )) + AND (OLD.totalEntries AND OLD.landed < CURDATE()) THEN + CALL util.throw("Cannot past travels with entries"); + END IF; + IF NOT (NEW.landed <=> OLD.landed) OR NOT (NEW.shipped <=> OLD.shipped) THEN CALL travel_checkDates(NEW.shipped, NEW.landed); @@ -40983,7 +41494,9 @@ BEGIN CALL travel_checkPackaging(NEW.id); END IF; - CALL travel_checkWarehouseIsFeedStock(NEW.warehouseInFk); + IF NOT (NEW.warehouseInFk <=> OLD.warehouseInFk) THEN + CALL travel_checkWarehouseIsFeedStock(NEW.warehouseInFk); + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -41606,7 +42119,7 @@ DROP TABLE IF EXISTS `wagon`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `wagon` ( - `id` int(11) NOT NULL AUTO_INCREMENT, + `id` varchar(6) NOT NULL COMMENT '26 letras de alfabeto inglés', `volume` int(11) NOT NULL DEFAULT 150 COMMENT 'Volumen en litros', `plate` varchar(10) NOT NULL COMMENT 'Matrícula', `typeFk` int(11) unsigned NOT NULL, @@ -41614,7 +42127,7 @@ CREATE TABLE `wagon` ( PRIMARY KEY (`id`), KEY `wagon_type` (`typeFk`), CONSTRAINT `wagon_type` FOREIGN KEY (`typeFk`) REFERENCES `wagonType` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; -- @@ -41701,10 +42214,10 @@ CREATE TABLE `wagonVolumetry` ( `lines` int(10) unsigned NOT NULL DEFAULT 1, `liters` int(10) unsigned NOT NULL DEFAULT 0, `height` int(10) unsigned NOT NULL DEFAULT 20, - `wagonFk` int(11) NOT NULL, + `wagonFk` varchar(6) NOT NULL, PRIMARY KEY (`id`), - KEY `wagonVolumetry_FK` (`wagonFk`), - CONSTRAINT `wagonVolumetry_FK` FOREIGN KEY (`wagonFk`) REFERENCES `wagon` (`id`) ON DELETE CASCADE ON UPDATE CASCADE + KEY `wagonVolumetry_FK_1` (`wagonFk`), + CONSTRAINT `wagonVolumetry_FK_1` FOREIGN KEY (`wagonFk`) REFERENCES `wagon` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -41875,14 +42388,12 @@ CREATE TABLE `worker` ( `photo` blob DEFAULT NULL, `phone` varchar(9) DEFAULT NULL, `mobileExtension` int(4) DEFAULT NULL, - `userFk` int(10) unsigned DEFAULT NULL, - `bossFk` int(11) NOT NULL DEFAULT 103, + `bossFk` int(10) unsigned DEFAULT 103, `fiDueDate` datetime DEFAULT NULL, `hasMachineryAuthorized` tinyint(2) DEFAULT 0, `seniority` date DEFAULT NULL, `isTodayRelative` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Para el F11. Calcula los problemas de visiblidad en funcion del dia actual', `isF11Allowed` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Usuario autorizado para abrir el F11', - `sectorFk__` int(11) DEFAULT NULL COMMENT '@deprecated 2023-06-26', `maritalStatus` enum('S','M') NOT NULL, `labelerFk__` tinyint(3) unsigned DEFAULT NULL COMMENT '@deprecated 2023-06-26', `originCountryFk` mediumint(8) unsigned DEFAULT NULL COMMENT 'País de origen', @@ -41900,7 +42411,6 @@ CREATE TABLE `worker` ( `editorFk` int(10) unsigned DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `CodigoTrabajador_UNIQUE` (`code`), - UNIQUE KEY `user_id_UNIQUE` (`userFk`), UNIQUE KEY `worker_business` (`businessFk`), UNIQUE KEY `locker` (`locker`), KEY `sub` (`sub`), @@ -41912,6 +42422,7 @@ CREATE TABLE `worker` ( CONSTRAINT `worker_FK` FOREIGN KEY (`labelerFk__`) REFERENCES `printer` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `worker_FK_1` FOREIGN KEY (`originCountryFk`) REFERENCES `country` (`id`) ON UPDATE CASCADE, CONSTRAINT `worker_FK_2` FOREIGN KEY (`educationLevelFk`) REFERENCES `educationLevel` (`id`) ON UPDATE CASCADE, + CONSTRAINT `worker_FK_3` FOREIGN KEY (`bossFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE, CONSTRAINT `worker_businessFk` FOREIGN KEY (`businessFk`) REFERENCES `business` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT `worker_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`), CONSTRAINT `worker_ibfk_1` FOREIGN KEY (`id`) REFERENCES `account`.`user` (`id`) @@ -42762,10 +43273,29 @@ CREATE TABLE `workerTimeControlConfig` ( `longWeekDays` int(11) DEFAULT NULL COMMENT 'Días a tener en cuenta para calcular el descanso largo', `teleworkingStart` int(11) DEFAULT NULL COMMENT 'Hora comienzo jornada de los teletrabajdores expresada en segundos', `teleworkingStartBreakTime` int(11) DEFAULT NULL COMMENT 'Hora comienzo descanso de los teletrabjadores expresada en segundos', + `maxTimeToBreak` int(11) DEFAULT 3600, + `maxWorkShortCycle` int(10) unsigned DEFAULT 561600 COMMENT 'Máximo tiempo que un trabajador puede estar trabajando con el que adquirirá el derecho a un descanso semanal corto', + `maxWorkLongCycle` int(10) unsigned DEFAULT 950400 COMMENT 'Máximo tiempo que un trabajador puede estar trabajando con el que adquirirá el derecho a un descanso semanal largo', PRIMARY KEY (`id`) ) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_bin COMMENT='All values in seconds'; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `workerTimeControlError` +-- + +DROP TABLE IF EXISTS `workerTimeControlError`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `workerTimeControlError` ( + `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, + `code` char(35) NOT NULL, + `description` varchar(255) NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `code` (`code`) +) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `workerTimeControlLog` -- @@ -43439,17 +43969,19 @@ DROP TABLE IF EXISTS `zoneIncluded`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `zoneIncluded` ( + `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `zoneFk` int(11) NOT NULL, `geoFk` int(11) NOT NULL, `isIncluded` tinyint(1) DEFAULT NULL, `editorFk` int(10) unsigned DEFAULT NULL, - PRIMARY KEY (`zoneFk`,`geoFk`), - KEY `geoFk_idx` (`geoFk`), + PRIMARY KEY (`id`), + UNIQUE KEY `unique_zone_geo` (`zoneFk`,`geoFk`), KEY `zoneIncluded_fk_editor` (`editorFk`), - CONSTRAINT `zoneFk2` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `zoneGeoFk2` FOREIGN KEY (`geoFk`) REFERENCES `zoneGeo` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + KEY `zoneIncluded_FK_2` (`geoFk`), + CONSTRAINT `zoneIncluded_FK_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `zoneIncluded_FK_2` FOREIGN KEY (`geoFk`) REFERENCES `zoneGeo` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `zoneIncluded_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; +) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -43494,11 +44026,11 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET character_set_client = utf8mb3 */ ; +/*!50003 SET character_set_results = utf8mb3 */ ; +/*!50003 SET collation_connection = utf8mb3_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`zoneIncluded_afterDelete` AFTER DELETE ON `zoneIncluded` @@ -43803,6 +44335,27 @@ DELIMITER ;; /*!50003 SET character_set_client = @saved_cs_client */ ;; /*!50003 SET character_set_results = @saved_cs_results */ ;; /*!50003 SET collation_connection = @saved_col_connection */ ;; +/*!50106 DROP EVENT IF EXISTS `itemImageQueue_check` */;; +DELIMITER ;; +/*!50003 SET @saved_cs_client = @@character_set_client */ ;; +/*!50003 SET @saved_cs_results = @@character_set_results */ ;; +/*!50003 SET @saved_col_connection = @@collation_connection */ ;; +/*!50003 SET character_set_client = utf8mb4 */ ;; +/*!50003 SET character_set_results = utf8mb4 */ ;; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;; +/*!50003 SET @saved_time_zone = @@time_zone */ ;; +/*!50003 SET time_zone = 'SYSTEM' */ ;; +/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `itemImageQueue_check` ON SCHEDULE EVERY 1 HOUR STARTS '2023-07-28 00:00:00' ON COMPLETION PRESERVE DISABLE ON SLAVE DO BEGIN + DELETE FROM itemImageQueue + WHERE attempts >= (SELECT downloadMaxAttempts FROM itemConfig); +END */ ;; +/*!50003 SET time_zone = @saved_time_zone */ ;; +/*!50003 SET sql_mode = @saved_sql_mode */ ;; +/*!50003 SET character_set_client = @saved_cs_client */ ;; +/*!50003 SET character_set_results = @saved_cs_results */ ;; +/*!50003 SET collation_connection = @saved_col_connection */ ;; /*!50106 DROP EVENT IF EXISTS `mysqlConnectionsSorter_kill` */;; DELIMITER ;; /*!50003 SET @saved_cs_client = @@character_set_client */ ;; @@ -44056,6 +44609,24 @@ DELIMITER ;; /*!50003 SET character_set_client = @saved_cs_client */ ;; /*!50003 SET character_set_results = @saved_cs_results */ ;; /*!50003 SET collation_connection = @saved_col_connection */ ;; +/*!50106 DROP EVENT IF EXISTS `zoneClosure_doRecalc` */;; +DELIMITER ;; +/*!50003 SET @saved_cs_client = @@character_set_client */ ;; +/*!50003 SET @saved_cs_results = @@character_set_results */ ;; +/*!50003 SET @saved_col_connection = @@collation_connection */ ;; +/*!50003 SET character_set_client = utf8mb3 */ ;; +/*!50003 SET character_set_results = utf8mb3 */ ;; +/*!50003 SET collation_connection = utf8mb3_general_ci */ ;; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;; +/*!50003 SET @saved_time_zone = @@time_zone */ ;; +/*!50003 SET time_zone = 'SYSTEM' */ ;; +/*!50106 CREATE*/ /*!50117 DEFINER=`salix`@`10.0.%.%`*/ /*!50106 EVENT `zoneClosure_doRecalc` ON SCHEDULE AT '2023-11-13 07:15:54' ON COMPLETION NOT PRESERVE DISABLE ON SLAVE DO CALL zoneClosure_recalc */ ;; +/*!50003 SET time_zone = @saved_time_zone */ ;; +/*!50003 SET sql_mode = @saved_sql_mode */ ;; +/*!50003 SET character_set_client = @saved_cs_client */ ;; +/*!50003 SET character_set_results = @saved_cs_results */ ;; +/*!50003 SET collation_connection = @saved_col_connection */ ;; /*!50106 DROP EVENT IF EXISTS `zoneGeo_doCalc` */;; DELIMITER ;; /*!50003 SET @saved_cs_client = @@character_set_client */ ;; @@ -44221,42 +44792,14 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP FUNCTION IF EXISTS `botanicExport_isUpdatable` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` FUNCTION `botanicExport_isUpdatable`(vEdiGenusFk MEDIUMINT, - vEdiSpecieFk MEDIUMINT, - vRestriction MEDIUMINT) RETURNS int(11) - DETERMINISTIC -BEGIN - DECLARE vIsUpdatable INTEGER; - SELECT COUNT(*) INTO vIsUpdatable - FROM botanicExport - WHERE ediGenusFk = vEdiGenusFk - AND (vEdiSpecieFk = ediSpecieFk OR IFNULL(vEdiSpecieFk,ediSpecieFk) IS NULL) - AND vRestriction = restriction; -RETURN vIsUpdatable; -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 */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP FUNCTION IF EXISTS `buy_getUnitVolume` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET character_set_client = utf8mb3 */ ; +/*!50003 SET character_set_results = utf8mb3 */ ; +/*!50003 SET collation_connection = utf8mb3_general_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `buy_getUnitVolume`(vSelf INT) RETURNS int(11) DETERMINISTIC @@ -44271,7 +44814,7 @@ BEGIN DECLARE vPackaging VARCHAR(10); DECLARE vPacking INT; - SELECT itemFk, packageFk, packing + SELECT itemFk, packagingFk, packing INTO vItem, vPackaging, vPacking FROM buy WHERE id = vSelf; @@ -44443,63 +44986,19 @@ BEGIN * @return Mana del cliente */ DECLARE vMana DECIMAL(10,2); - DECLARE vFromDated DATE; - DECLARE vHasMana BOOLEAN; - DECLARE vManaComponent INT; - DECLARE vAutoManaComponent INT; - DECLARE vManaBank INT; - DECLARE vManaGreugeType INT; - SELECT id INTO vManaGreugeType FROM greugeType WHERE code = 'mana'; - SELECT id INTO vManaBank FROM bank WHERE code = 'mana'; - SELECT id INTO vManaComponent FROM component WHERE code = 'mana'; - SELECT id INTO vAutoManaComponent FROM component WHERE code = 'autoMana'; + CREATE OR REPLACE TEMPORARY TABLE tmp.client + SELECT vClient id; - SELECT COUNT(*) INTO vHasMana - FROM `client` c - WHERE c.id = vClient AND c.typeFk = 'normal'; + CALL client_getMana(); - IF NOT vHasMana THEN - RETURN 0; - END IF; + SET vMana = (SELECT mana + FROM tmp.clientMana); - SELECT max(dated) INTO vFromDated - FROM clientManaCache; + DROP TEMPORARY TABLE + tmp.client, + tmp.clientMana; - SELECT sum(mana) INTO vMana - FROM - ( - SELECT mana - FROM clientManaCache - WHERE clientFk = vClient - AND dated = vFromDated - UNION ALL - SELECT s.quantity * value - FROM ticket t - JOIN address a ON a.id = t.addressFk - JOIN sale s on s.ticketFk = t.id - JOIN saleComponent sc on sc.saleFk = s.id - WHERE sc.componentFk IN (vManaComponent, vAutoManaComponent) - AND t.shipped > vFromDated - AND t.shipped < TIMESTAMPADD(DAY,1,util.VN_CURDATE()) - AND a.clientFk = vClient - UNION ALL - SELECT - amountPaid - FROM receipt r - JOIN `client` c ON c.id = r.clientFk - WHERE r.bankFk = vManaBank - AND r.payed > vFromDated - AND r.payed <= util.VN_CURDATE() - AND c.id = vClient - UNION ALL - SELECT g.amount - FROM greuge g - JOIN `client` c ON c.id = g.clientFk - WHERE g.greugeTypeFk = vManaGreugeType - AND g.shipped > vFromDated - AND g.shipped <= util.VN_CURDATE() - AND c.id = vClient - ) sub; RETURN IFNULL(vMana,0); END ;; DELIMITER ; @@ -44583,7 +45082,7 @@ BEGIN * * @param vClient client id * @param vDate date to check the risk - * @return client risk + * @return Client risk */ DECLARE vDebt DECIMAL(10,2); DECLARE vHasDebt BOOLEAN; @@ -44603,6 +45102,10 @@ BEGIN SELECT risk INTO vDebt FROM tmp.risk; + DROP TEMPORARY TABLE + tmp.clientGetDebt, + tmp.risk; + RETURN vDebt; END ;; DELIMITER ; @@ -45010,27 +45513,25 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` FUNCTION `duaTax_getRate`(vDua INT, vTaxClass INT) RETURNS decimal(5,2) +CREATE DEFINER=`root`@`localhost` FUNCTION `duaTax_getRate`(vDuaFk INT, vTaxClassFk INT) RETURNS decimal(5,2) DETERMINISTIC BEGIN - DECLARE vCountryFk INTEGER; - - SELECT s.countryFk INTO vCountryFk - FROM dua d - JOIN supplier s ON s.id = d.companyFk - WHERE d.id = vDua; - - RETURN (SELECT rate - FROM - (SELECT taxClassFk, rate - FROM invoiceInTaxBookingAccount - WHERE effectived <= util.VN_CURDATE() - AND countryFk = vCountryFk - AND taxClassFk = vTaxClass - ORDER BY effectived DESC - LIMIT 10000000000000000000 - ) ba1 - GROUP BY taxClassFk); +/** + * Devuelve el rate para un Dua teniendo en cuenta la fecha de opreción del DUA + * + * @param vDuaFk Identificador de la tabla dua + * @param vTaxClassFk Identificador del IVA de la tabla invoiceInTaxBookingAccount + */ + RETURN ( + SELECT rate + FROM dua d + JOIN supplier s ON s.id = d.companyFk + JOIN invoiceInTaxBookingAccount iit ON iit.countryFk = s.countryFk + AND iit.taxClassFk = vTaxClassFk + AND iit.effectived <= IFNULL( d.operated, util.VN_CURDATE()) + WHERE d.id = vDuaFk + ORDER BY effectived DESC + LIMIT 1); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -46893,61 +47394,6 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP FUNCTION IF EXISTS `phytoPassport` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` FUNCTION `phytoPassport`(vRef VARCHAR(15)) RETURNS text CHARSET utf8mb3 COLLATE utf8mb3_general_ci - DETERMINISTIC -BEGIN -DECLARE vPhyto TEXT CHARSET utf8 COLLATE utf8_unicode_ci; -SELECT - GROUP_CONCAT(i.id, - ':', - ppa.denomination, - ' ', - pp.number, - CHAR(13,10) - SEPARATOR '') fitosanitario - INTO vPhyto -FROM - sale s - JOIN - ticket t ON t.id = s.ticketFk - JOIN - item i ON i.id = s.itemFk - JOIN - plantpassport pp ON pp.producerFk = i.producerFk - JOIN - plantpassportAuthority ppa ON ppa.id = pp.plantpassportAuthorityFk - JOIN - itemBotanicalWithGenus ib ON ib.itemFk = i.id - JOIN - botanicExport be ON be.`code` = 'phytosanitaryPassport' - LEFT JOIN - ediGenus eg ON eg.id = be.ediGenusFk - LEFT JOIN - ediSpecie es ON es.id = be.ediSpecieFk -WHERE - t.refFk = vRef - AND ib.ediBotanic LIKE CONCAT(IFNULL(eg.latinGenusName, ''), - IF(latinSpeciesName > '', - CONCAT(' ', latinSpeciesName), - ''), - '%'); -RETURN vPhyto; -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 */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP FUNCTION IF EXISTS `priceFixed_getRate2` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -49313,14 +49759,14 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `buy_afterUpsert` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET character_set_client = utf8mb3 */ ; +/*!50003 SET character_set_results = utf8mb3 */ ; +/*!50003 SET collation_connection = utf8mb3_general_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_afterUpsert`(vSelf INT) BEGIN @@ -49359,7 +49805,7 @@ BEGIN LEFT JOIN item i ON i.id = b.itemFk LEFT JOIN itemType it ON it.id = i.typeFk LEFT JOIN itemCategory ic ON ic.id = it.categoryFk - LEFT JOIN packaging p ON p.id = b.packageFk AND NOT p.isBox + LEFT JOIN packaging p ON p.id = b.packagingFk AND NOT p.isBox JOIN volumeConfig vc ON TRUE WHERE b.id = vSelf; @@ -49573,14 +50019,14 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `buy_getVolume` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET character_set_client = utf8mb3 */ ; +/*!50003 SET character_set_results = utf8mb3 */ ; +/*!50003 SET collation_connection = utf8mb3_general_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_getVolume`() BEGIN @@ -49590,9 +50036,9 @@ BEGIN */ SELECT t.name Temp, CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) * - item_getVolume(b.itemFk, b.packageFk)) / vc.trolleyM3 / 1000000 ,1) AS DECIMAL(10,2)) carros , + item_getVolume(b.itemFk, b.packagingFk)) / vc.trolleyM3 / 1000000 ,1) AS DECIMAL(10,2)) carros , CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) * - item_getVolume(b.itemFk, b.packageFk)) / vc.palletM3 / 1000000,1) AS DECIMAL(10,2)) espais + item_getVolume(b.itemFk, b.packagingFk)) / vc.palletM3 / 1000000,1) AS DECIMAL(10,2)) espais FROM buy b JOIN tmp.buy tb ON tb.buyFk = b.id JOIN volumeConfig vc @@ -49671,14 +50117,14 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `buy_recalcPrices` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET character_set_client = utf8mb3 */ ; +/*!50003 SET character_set_results = utf8mb3 */ ; +/*!50003 SET collation_connection = utf8mb3_general_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_recalcPrices`() BEGIN @@ -49691,7 +50137,7 @@ BEGIN DECLARE vWarehouseFk INT; DECLARE vHasNotPrice BOOL; DECLARE vBuyingValue DECIMAL(10,3); - DECLARE vPackageFk VARCHAR(10); + DECLARE vPackagingFk VARCHAR(10); DECLARE vIsWarehouseFloramondo BOOL; SELECT t.landed, t.warehouseInFk, (w.`name` = 'Floramondo') @@ -49707,7 +50153,7 @@ BEGIN UPDATE buy b JOIN tmp.buyRecalc br ON br.id = b.id AND (@buyId := b.id) - LEFT JOIN packaging p ON p.id = b.packageFk + LEFT JOIN packaging p ON p.id = b.packagingFk JOIN item i ON i.id = b.itemFk JOIN entry e ON e.id = b.entryFk JOIN itemType it ON it.id = i.typeFk @@ -49715,7 +50161,7 @@ BEGIN JOIN agencyMode am ON am.id = tr.agencyModeFk JOIN tmp.rate r JOIN volumeConfig vc - SET b.freightValue = @PF:= IFNULL(((am.m3 * @m3:= item_getVolume(b.itemFk, b.packageFk) / 1000000) + SET b.freightValue = @PF:= IFNULL(((am.m3 * @m3:= item_getVolume(b.itemFk, b.packagingFk) / 1000000) / b.packing) * IF(am.hasWeightVolumetric, GREATEST(b.weight / @m3 / vc.aerealVolumetricDensity, 1), 1), 0), b.comissionValue = @CF:= ROUND(IFNULL(e.commission * b.buyingValue / 100, 0), 3), b.packageValue = @EF:= IF(vIsWarehouseFloramondo, 0, IFNULL(ROUND(IF(p.isPackageReturnable, p.returnCost / b.packing , p.`value` / b.packing), 3),0)), @@ -49723,8 +50169,8 @@ BEGIN b.price2 = @t2:= round(@t3 * (1 + ((r.rate2 - r.rate3)/100)),2), b.price2 = @t2:= IF(@t2 <= @t3,@t3 , @t2); - SELECT (b.buyingValue = b.price2), b.buyingValue, b.packageFk - INTO vHasNotPrice, vBuyingValue, vPackageFk + SELECT (b.buyingValue = b.price2), b.buyingValue, b.packagingFk + INTO vHasNotPrice, vBuyingValue, vPackagingFk FROM vn.buy b WHERE b.id = @buyId AND b.buyingValue <> 0.01; @@ -50332,7 +50778,7 @@ BEGIN SELECT tcb.warehouseFk, tcb.itemFk, c2.id, - ROUND(base * (0.01 + wm.pricesModifierRate), 3) manaAuto + ROUND(base * wm.pricesModifierRate, 3) manaAuto FROM tmp.ticketComponentBase tcb JOIN `client` c on c.id = vClientFk JOIN workerMana wm ON c.salesPersonFk = wm.workerFk @@ -50615,7 +51061,12 @@ BEGIN DELETE FROM sharingCart where ended < vDateShort; DELETE FROM sharingClient where ended < vDateShort; DELETE tw.* FROM ticketWeekly tw - LEFT JOIN sale s ON s.ticketFk = tw.ticketFk WHERE s.itemFk IS NULL; + LEFT JOIN sale s ON s.ticketFk = tw.ticketFk + LEFT JOIN ticketRequest tr ON tr.ticketFk = tw.ticketFk + LEFT JOIN ticketService ts ON ts.ticketFk = tw.ticketFk + WHERE s.id IS NULL + AND tr.id IS NULL + AND ts.id IS NULL; DELETE FROM claim WHERE ticketCreated < vFourYearsAgo; DELETE FROM message WHERE sendDate < vDateShort; -- Robert ubicacion anterior de trevelLog comentario para debug @@ -50941,6 +51392,7 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.clientGetDebt; CREATE TEMPORARY TABLE tmp.clientGetDebt + (INDEX (clientFk)) SELECT clientFk FROM bs.defaulter WHERE created = util.VN_CURDATE() @@ -51368,14 +51820,14 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.clientGetDebt; CREATE TEMPORARY TABLE tmp.clientGetDebt - SELECT cd.id as clientFk + SELECT cd.clientFk FROM bs.clientDied cd - LEFT JOIN clientProtected cp ON cp.clientFk = cd.id - JOIN client c ON c.id = cd.id + LEFT JOIN clientProtected cp ON cp.clientFk = cd.clientFk + JOIN client c ON c.id = cd.clientFk JOIN province p ON p.id = c.provinceFk LEFT JOIN autonomy a ON a.id = p.autonomyFk JOIN country co ON co.id = p.countryFk - WHERE cd.Aviso = 'TERCER AVISO' + WHERE cd.warning = 'third' AND cp.clientFk IS NULL AND co.code NOT IN ('PT') AND a.name <> 'Canarias' @@ -51621,18 +52073,19 @@ BEGIN * Calculates the risk for active clients * * @table tmp.clientGetDebt(clientFk) - * @param vDate maximum date of records + * @param vDate Maximum date of records * @return tmp.risk */ DECLARE vStarted DATETIME; DECLARE vEnded DATETIME; - SELECT TIMESTAMPADD(MONTH, -riskScope, util.VN_CURDATE()) INTO vStarted FROM clientConfig; - SET vEnded = TIMESTAMP(IFNULL(vDate, util.VN_CURDATE()), '23:59:59'); + SELECT util.VN_CURDATE() - INTERVAL riskScope MONTH INTO vStarted + FROM clientConfig; - DROP TEMPORARY TABLE IF EXISTS tClientRisk; - CREATE TEMPORARY TABLE tClientRisk + SET vEnded = util.dayEnd(IFNULL(vDate, util.VN_CURDATE())); + + CREATE OR REPLACE TEMPORARY TABLE tClientRisk ENGINE = MEMORY SELECT cr.clientFk, SUM(cr.amount) amount FROM clientRisk cr @@ -51655,12 +52108,14 @@ BEGIN GROUP BY t.clientFk; INSERT INTO tClientRisk - SELECT t.clientFk, totalWithVat + SELECT t.clientFk, SUM(totalWithVat) FROM ticket t JOIN tmp.clientGetDebt c ON c.clientFk = t.clientFk WHERE refFk IS NULL - AND shipped BETWEEN vStarted AND vEnded; + AND shipped BETWEEN vStarted AND vEnded + GROUP BY t.clientFk; + -- refs #6351 BUG: No cambiar a CREATE OR REPLACE DROP TEMPORARY TABLE IF EXISTS tmp.risk; CREATE TEMPORARY TABLE tmp.risk (PRIMARY KEY (clientFk)) @@ -51679,6 +52134,75 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `client_getMana` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `client_getMana`() +BEGIN +/** + * Devuelve el mana de los clientes de la tabla tmp.client(id) + * @return tmp.clientMana(id, mana) + * + */ + DECLARE vFromDated DATE; + + DELETE tc FROM tmp.client tc + JOIN client c ON c.id = tc.id + WHERE c.typeFk <> 'normal'; + + SELECT MAX(dated) INTO vFromDated + FROM clientManaCache; + + CREATE OR REPLACE TEMPORARY TABLE tmp.clientMana + SELECT id, SUM(mana) mana + FROM + ( + SELECT tc.id, cmc.mana + FROM clientManaCache cmc + JOIN tmp.client tc ON tc.id = cmc.clientFk + WHERE cmc.dated = vFromDated + UNION ALL + SELECT tc.id, s.quantity * value + FROM ticket t + JOIN address a ON a.id = t.addressFk + JOIN tmp.client tc ON tc.id = a.clientFk + JOIN sale s on s.ticketFk = t.id + JOIN saleComponent sc on sc.saleFk = s.id + JOIN component comp ON sc.componentFk = comp.id + JOIN componentType ct ON ct.id = comp.typeFk AND ct.code = 'mana' + WHERE t.shipped > vFromDated + AND t.shipped < util.tomorrow() + UNION ALL + SELECT tc.id, -amountPaid + FROM receipt r + JOIN `client` c ON c.id = r.clientFk + JOIN tmp.client tc ON tc.id = c.id + JOIN bank b ON r.bankFk = b.id AND b.code = 'mana' + WHERE r.payed > vFromDated + AND r.payed <= util.VN_CURDATE() + UNION ALL + SELECT tc.id, g.amount + FROM greuge g + JOIN `client` c ON c.id = g.clientFk + JOIN tmp.client tc ON tc.id = c.id + JOIN greugeType gt ON gt.id = g.greugeTypeFk AND gt.code = 'mana' + WHERE g.shipped > vFromDated + AND g.shipped <= util.VN_CURDATE() + ) sub + GROUP BY id; +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 */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `client_RandomList` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -51778,7 +52302,7 @@ BEGIN DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; CREATE OR REPLACE TEMPORARY TABLE tClientList - SELECT c.id clientFk + SELECT c.clientFk FROM bs.clientDied cd JOIN client c ON c.id = cd.id LEFT JOIN clientProtected cp ON cp.clientFk = c.id @@ -51786,7 +52310,7 @@ BEGIN JOIN province p ON p.id = c.provinceFk LEFT JOIN autonomy a ON a.id = p.autonomyFk JOIN country co ON co.id = p.countryFk - WHERE cd.Aviso = 'TERCER AVISO' + WHERE cd.warning = 'third' AND cp.clientFk IS NULL AND sp.salesPersonFk IS NULL AND a.name <> 'Canarias' @@ -51865,127 +52389,6 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `cmr_getByTicket` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `cmr_getByTicket`(vTicketFk INT) -BEGIN - - DECLARE vLanded DATE; - - SELECT DATE_ADD(util.VN_CURDATE(), INTERVAL landingDays DAY) INTO vLanded - FROM vn.cmrConfig; - - IF vTicketFk THEN - - IF (SELECT count(ticketFk) FROM vn.cmr WHERE ticketFk = vTicketFk) THEN - - SELECT id FROM vn.cmr WHERE ticketFk = vTicketFk; - - ELSE - - INSERT INTO vn.cmr(ticketFk, companyFk, addressFromFk, addressToFk, ead) - SELECT vTicketFk, t.companyFk, a.id, t.addressFk, vLanded - FROM vn.ticket t - JOIN vn.warehouse w ON w.id = t.warehouseFk - JOIN vn.address a ON a.id = w.addressFk - WHERE t.id = vTicketFk; - - SELECT LAST_INSERT_ID(); - - END IF; - - ELSE - - INSERT INTO vn.cmr(ead) VALUES(vLanded); - - SELECT LAST_INSERT_ID(); - - END IF; -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 */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `cmr_sendOverview` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `cmr_sendOverview`() -BEGIN -/** - * Insert the monthly CMR summary in vn.mail on the 5th of each month. - */ - - SET SESSION group_concat_max_len = 1000000; --- IF (DAY(util.VN_CURDATE()) = 5) THEN - INSERT INTO - vn.mail (receiver, - replyTo, - subject, - body) - SELECT - c2.email, - 'cmr@verdnatura.es', - 'Resumen CMR', - CONCAT('
-

Resumen Mensual CMR

- - - - - - - - ' - , GROUP_CONCAT('' ORDER BY c.id SEPARATOR '' ), - '
- Estimado cliente,
- A continuación le enviamos el resumen menual de CMR ',UPPER(MONTHNAME(util.VN_CURDATE() - INTERVAL 1 MONTH)),' ', YEAR(util.VN_CURDATE() - INTERVAL 1 MONTH), '.

- Le rogamos que nos devuelva el resumen firmado a cmr@verdnatura.es
-

-
CMRTicket
', c.id, ' ', c.ticketFk, '
- -

- Saludos cordiales, Dpto administración. -

') - FROM vn.cmr c - JOIN vn.address a ON c.addressToFk = a.id - JOIN vn.client c2 ON a.clientFk = c2.id - WHERE c.state = 'Pending' - AND MONTH(c.created) = MONTH(util.VN_CURDATE() - INTERVAL 1 MONTH) - AND YEAR(c.created) = YEAR(util.VN_CURDATE() - INTERVAL 1 MONTH) - AND c2.email IS NOT NULL -- No cogemos los CMRs dirigidos a 'Verdnatura' - GROUP BY c2.id; - - -- Actualizamos el estado a 'Enviado' - UPDATE vn.cmr c - SET c.state = 'Sent' - WHERE c.state = 'Pending' - AND MONTH(c.created) = MONTH(util.VN_CURDATE() - INTERVAL 1 MONTH) - AND YEAR(c.created) = YEAR(util.VN_CURDATE() - INTERVAL 1 MONTH); --- END IF; -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 */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `collectionPlacement_get` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -54275,46 +54678,51 @@ BEGIN * Borra los valores de duaTax y los vuelve a crear en base a la tabla duaEntry * * @param vDuaFk Id del dua a recalcular -**/ + */ DELETE FROM duaTax WHERE duaFk = vDuaFk; - INSERT INTO duaTax(duaFk, supplierFk, taxClassFk, base) - SELECT vDuaFk, supplierFk, taxClassFk, sum(sub.Base) as Base + INSERT INTO duaTax(duaFk, taxClassFk, base) + SELECT vDuaFk, taxClassFk, SUM(sub.totalBase) FROM intrastat ist JOIN - (SELECT - e.supplierFk, - i.intrastatFk, - CAST(sum(b.quantity * b.buyingValue * de.customsValue / de.value) * di.amount/ tei.Base AS DECIMAL(10,2)) as Base + (SELECT i.intrastatFk, + CAST(SUM(b.quantity * + b.buyingValue * + de.customsValue / + de.value) + * di.totalAmount / + bi.totalAmount AS DECIMAL(10,2) + ) totalBase FROM buy b JOIN item i ON i.id = b.itemFk JOIN entry e ON e.id = b.entryFk JOIN duaEntry de ON de.entryFk = e.id - JOIN - ( - SELECT i.intrastatFk, - CAST(sum(b.quantity * b.buyingValue * de.customsValue / de.value) AS DECIMAL(10,2)) as Base - FROM buy b - JOIN item i ON i.id = b.itemFk - JOIN entry e ON e.id = b.entryFk - JOIN duaEntry de ON de.entryFk = e.id - WHERE de.duaFk = vDuaFk - GROUP BY i.intrastatFk - - ) tei ON tei.intrastatFk = i.intrastatFk - JOIN - ( - SELECT intrastatFk, sum(amount) as amount - FROM duaIntrastat - WHERE duaFk = vDuaFk - GROUP BY intrastatFK - ) di ON di.intrastatFk = i.intrastatFk + JOIN( + SELECT i.intrastatFk, + CAST(SUM(b.quantity * + b.buyingValue * + de.customsValue / + de.value) AS DECIMAL(10,2) + ) totalAmount + FROM buy b + JOIN item i ON i.id = b.itemFk + JOIN entry e ON e.id = b.entryFk + JOIN duaEntry de ON de.entryFk = e.id + WHERE de.duaFk = vDuaFk + GROUP BY i.intrastatFk + ) bi ON bi.intrastatFk = i.intrastatFk + JOIN( + SELECT intrastatFk, SUM(amount) totalAmount + FROM duaIntrastat + WHERE duaFk = vDuaFk + GROUP BY intrastatFK + ) di ON di.intrastatFk = i.intrastatFk WHERE de.duaFk = vDuaFk - GROUP BY e.supplierFk, i.intrastatFk - HAVING Base - ) sub ON ist.id = sub.intrastatFk - GROUP BY ist.taxClassFk, sub.supplierFk; + GROUP BY i.intrastatFk + HAVING totalBase + )sub ON ist.id = sub.intrastatFk + GROUP BY ist.taxClassFk; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -54617,14 +55025,14 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `entry_checkPackaging` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET character_set_client = utf8mb3 */ ; +/*!50003 SET character_set_results = utf8mb3 */ ; +/*!50003 SET collation_connection = utf8mb3_general_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_checkPackaging`(vEntryFk INT) BEGIN @@ -54638,7 +55046,7 @@ BEGIN SELECT count(*) INTO vpackageOrPackingNull FROM buy b WHERE b.entryFk = vEntryFk - AND (b.packing IS NULL OR b.packageFk IS NULL); + AND (b.packing IS NULL OR b.packagingFk IS NULL); IF vpackageOrPackingNull THEN CALL util.throw("packageOrPackingNull"); @@ -54714,7 +55122,8 @@ BEGIN commission, currencyFk, companyFk, - clonedFrom + clonedFrom, + typeFk ) SELECT IFNULL(vTravelFk, travelFk), supplierFk, @@ -54724,7 +55133,8 @@ BEGIN commission, currencyFk, companyFk, - vSelf + vSelf, + typeFk FROM entry WHERE id = vSelf; @@ -54801,7 +55211,7 @@ BEGIN containerFk, comissionValue, packageValue, - packageFk, + packagingFk, price1, price2, price3, @@ -54824,7 +55234,7 @@ BEGIN containerFk, comissionValue, packageValue, - packageFk, + packagingFk, price1, price2, price3, @@ -55000,6 +55410,7 @@ BEGIN * * @param vSelf Identificador de entry * @param vDays Número de dias a futuro que se quiere la nueva entrada + * @param vChangeEntry Si se modifica la entrada original * * @return vNewEntryFk Identificador de la nueva entrada */ @@ -55007,8 +55418,12 @@ BEGIN DECLARE vTravelFk INT; DECLARE vInvoiceAmountOldEntryFk DECIMAL(10,2); DECLARE vInvoiceAmountNewEntry DECIMAL(10,2); + DECLARE vIsOrdered BOOL; + DECLARE vIsConfirmed BOOL; + DECLARE vInvoiceNumber VARCHAR(50); + DECLARE vTypeFk VARCHAR(100); - SELECT travelFk INTO vTravelFk + SELECT travelFk, isOrdered, isConfirmed, invoiceNumber, typeFk INTO vTravelFk, vIsOrdered, vIsConfirmed, vInvoiceNumber, vTypeFk FROM entry WHERE id = vSelf; @@ -55017,7 +55432,11 @@ BEGIN UPDATE entry e SET e.travelFk = vNewTravelFk, - e.evaNotes = CONCAT('No impresas de: ', vSelf, ' ', IFNULL(e.evaNotes,'')) + e.evaNotes = CONCAT('No impresas de: ', vSelf, ' ', IFNULL(e.evaNotes,'')), + e.isOrdered = vIsOrdered, + e.isConfirmed = vIsConfirmed, + e.invoiceNumber = vInvoiceNumber, + e.typeFk = vTypeFk WHERE e.id = vNewEntryFk; IF vChangeEntry THEN @@ -55523,246 +55942,6 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `errorProduction_add` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `errorProduction_add`( - vAction VARCHAR(25), - vDatedFrom DATETIME, - vDatedTo DATETIME) -BEGIN -/** - * Rellena la tabla vn.errorProduction - * - * @param vAction Accion que se quiere añadir - * @param vDatedFrom Fecha desde - * @param vDatedTo Fecha hasta - */ - DECLARE vDepartment VARCHAR(255); - - CASE - WHEN vAction = 'SACAR' THEN - SET vDepartment = 'Sacadores'; - WHEN vAction = 'ENCAJAR' THEN - SET vDepartment = 'Encajadores'; - WHEN vAction = 'CONTROLAR' THEN - SET vDepartment = 'Revisadores'; - END CASE; - - IF (vDepartment = 'Encajadores') THEN - CREATE OR REPLACE TEMPORARY TABLE total - ENGINE = MEMORY - SELECT e.workerFk, - COUNT(DISTINCT t.id) ticketCount, - COUNT(s.id) lineCount - FROM expedition e - JOIN ticket t ON e.ticketFk = t.id - JOIN sale s ON s.ticketFk = t.id - WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo - GROUP BY e.workerFk; - ELSE - CREATE OR REPLACE TEMPORARY TABLE total - ENGINE = MEMORY - SELECT st.workerFk, - COUNT(DISTINCT t.id) ticketCount, - COUNT(s.id) lineCount - FROM saleTracking st - JOIN `state` s2 ON s2.id = st.stateFk - JOIN sale s ON s.id = st.saleFk - JOIN ticket t ON s.ticketFk = t.id - WHERE (t.shipped BETWEEN vDatedFrom AND vDatedTo) - AND s2.code IN ('OK','PREVIOUS_PREPARATION','PREPARED','CHECKED') - GROUP BY st.workerFk; - END IF; - - CALL timeControl_calculateAll(vDatedFrom, vDatedTo); - - CREATE OR REPLACE TEMPORARY TABLE errorsByClaim - ENGINE = MEMORY - SELECT COUNT(c.ticketFk) errors, - cd.workerFk - FROM claimDevelopment cd - JOIN claim c ON cd.claimFk = c.id - JOIN ticket t ON c.ticketFk = t.id - JOIN claimResponsible cr ON cd.claimResponsibleFk = cr.id - WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo - AND cr.description = vDepartment - GROUP BY cd.workerFk; - - CREATE OR REPLACE TEMPORARY TABLE volume - ENGINE = MEMORY - SELECT SUM(w.volume) volume, - w.workerFk - FROM bs.workerProductivity w - WHERE w.dated BETWEEN vDatedFrom AND vDatedTo - GROUP BY w.workerFk; - - CREATE OR REPLACE TEMPORARY TABLE errorsByChecker - ENGINE = MEMORY - SELECT sub1.workerFk, COUNT(id) errors - FROM ( - SELECT st.workerFk, - t.id - FROM saleMistake sm - JOIN saleTracking st ON sm.saleFk = st.saleFk - JOIN `state` s2 ON s2.id = st.stateFk - JOIN sale s ON s.id = sm.saleFk - JOIN ticket t on t.id = s.ticketFk - WHERE (t.shipped BETWEEN vDatedFrom AND vDatedTo) - AND s2.code IN ('OK','PREVIOUS_PREPARATION','PREPARED','CHECKED') - ) sub1 - GROUP BY sub1.workerFk; - - CREATE OR REPLACE TEMPORARY TABLE expeditionErrors - ENGINE = MEMORY - SELECT COUNT(t.id) errors, - e.workerFk - FROM vn.expeditionMistake pm - JOIN vn.expedition e ON e.id = pm.expeditionFk - JOIN vn.ticket t ON t.id = e.ticketFk - WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo - GROUP BY e.workerFk; - - IF (vDepartment = 'Sacadores') THEN - - INSERT INTO errorProduction(userFk, - firstname, - lastname, - rol, - ticketNumber, - lineNumber, - error, - volume, - hourStart, - hourEnd, - hourWorked, - dated) - SELECT w.id, - w.firstName, - w.lastName, - vDepartment, - t.ticketCount totalTickets, - t.lineCount, - IFNULL(ec.errors,0) + IFNULL(ec2.errors,0) errors, - IF(vDepartment = 'Revisadores', NULL, v.volume) volume, - SUBSTRING(tc.timed, 1, 5) hourStart, - SUBSTRING(tc.timed, LENGTH(tc.timed)-4, 5) hourEnd, - IFNULL(CAST(tc.timeWorkDecimal AS DECIMAL (10,2)) , 0) hourWorked, - vDatedFrom dated - FROM total t - LEFT JOIN worker w ON w.id = t.workerFk - LEFT JOIN tmp.timeControlCalculate tc ON tc.userFk = t.workerFk - LEFT JOIN errorsByClaim ec ON ec.workerFk = t.workerFk - LEFT JOIN volume v ON v.workerFk = t.workerFk - LEFT JOIN errorsByChecker ec2 ON ec2.workerFk = t.workerFk - JOIN (SELECT DISTINCT w.id -- Verificamos que son sacadores - FROM vn.collection c - JOIN vn.state s ON s.id = c.stateFk - JOIN vn.train tn ON tn.id = c.trainFk - JOIN vn.worker w ON w.id = c.workerFk - WHERE c.created BETWEEN vDatedFrom AND vDatedTo) sub ON sub.id = w.id - GROUP BY w.id; - - CREATE OR REPLACE TEMPORARY TABLE itemPickerErrors -- Errores de los sacadores, derivadores de los revisadores - ENGINE = MEMORY - SELECT COUNT(c.ticketFk) errors, - tt.workerFk - FROM claimDevelopment cd - JOIN claim c ON cd.claimFk = c.id - JOIN ticket t ON c.ticketFk = t.id - JOIN claimResponsible cr ON cd.claimResponsibleFk = cr.id - JOIN ticketTracking tt ON tt.ticketFk = t.id - JOIN `state` s ON s.id = tt.stateFk - WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo - AND cr.description = 'Revisadores' - AND s.code = 'ON_PREPARATION' - GROUP BY workerFk; - - UPDATE errorProduction ep - JOIN itemPickerErrors ipe ON ipe.workerFk = ep.userFk - SET ep.error = ep.error + ipe.errors - WHERE vDatedFrom = ep.dated AND ep.rol = 'Sacadores'; - - DROP TEMPORARY TABLE itemPickerErrors; - ELSE - INSERT INTO errorProduction(userFk, - firstname, - lastname, - rol, - ticketNumber, - lineNumber, - error, - volume, - hourStart, - hourEnd, - hourWorked, - dated) - SELECT w.id, - w.firstName, - w.lastName, - vDepartment, - t.ticketCount totalTickets, - t.lineCount, - IFNULL(ec.errors,0) + IFNULL(ec2.errors,0) + IFNULL(pe.errors,0) errors, - IF(vDepartment = 'Revisadores', NULL, v.volume) volume, - SUBSTRING(tc.timed, 1, 5) hourStart, - SUBSTRING(tc.timed, LENGTH(tc.timed)-4, 5) hourEnd, - IFNULL(CAST(tc.timeWorkDecimal AS DECIMAL (10,2)) , 0) hourWorked, - vDatedFrom dated - FROM total t - LEFT JOIN worker w ON w.id = t.workerFk - LEFT JOIN tmp.timeControlCalculate tc ON tc.userFk = t.workerFk - LEFT JOIN errorsByClaim ec ON ec.workerFk = t.workerFk - LEFT JOIN volume v ON v.workerFk = t.workerFk - LEFT JOIN errorsByChecker ec2 ON ec2.workerFk = t.workerFk - LEFT JOIN expeditionErrors pe ON pe.workerFk = t.workerFk - GROUP BY w.id; - END IF; - - DROP TEMPORARY TABLE total, - errorsByClaim, - volume, - errorsByChecker, - expeditionErrors; -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 */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `errorProduction_addLauncher` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `errorProduction_addLauncher`() -BEGIN - DECLARE vDatedFrom DATETIME; - DECLARE vDatedTo DATETIME; - - SELECT DATE_SUB(util.VN_CURDATE(),INTERVAL 1 DAY), CONCAT(DATE_SUB(util.VN_CURDATE(),INTERVAL 1 DAY),' 23:59:59') INTO vDatedFrom, vDatedTo; - - CALL vn.errorProduction_add('SACAR', vDatedFrom, vDatedTo); - CALL vn.errorProduction_add('ENCAJAR', vDatedFrom, vDatedTo); - CALL vn.errorProduction_add('CONTROLAR', vDatedFrom, vDatedTo); -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 */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `expeditionGetFromRoute` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -56627,14 +56806,14 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `fustControl` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET character_set_client = utf8mb3 */ ; +/*!50003 SET character_set_results = utf8mb3 */ ; +/*!50003 SET collation_connection = utf8mb3_general_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `fustControl`(vFromDated DATE, vToDated DATE) BEGIN @@ -56656,14 +56835,14 @@ BEGIN LEFT JOIN ( SELECT FustCode, sum(fustQuantity) stucks FROM ( - SELECT IFNULL(pe.equivalentFk ,b.packageFk) FustCode, s.quantity / b.packing AS fustQuantity + SELECT IFNULL(pe.equivalentFk ,b.packagingFk) FustCode, s.quantity / b.packing AS fustQuantity FROM vn.sale s JOIN vn.ticket t ON t.id = s.ticketFk JOIN vn.warehouse w ON w.id = t.warehouseFk JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND lb.warehouse_id = t.warehouseFk JOIN vn.buy b ON b.id = lb.buy_id - JOIN vn.packaging p ON p.id = b.packageFk + JOIN vn.packaging p ON p.id = b.packagingFk LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id JOIN vn.address a ON a.id = t.addressFk JOIN vn.province p2 ON p2.id = a.provinceFk @@ -57332,7 +57511,7 @@ proc: BEGIN inv.groupingMode = b.groupingMode, inv.comissionValue = b.comissionValue, inv.packageValue = b.packageValue, - inv.packageFk = b.packageFk, + inv.packageFk = b.packagingFk, inv.price1 = b.price1, inv.price2 = b.price2, inv.price3 = b.price3, @@ -57348,28 +57527,28 @@ proc: BEGIN groupingMode, comissionValue, packageValue, - packageFk, + packagingFk, price1, price2, price3, minPrice, entryFk) SELECT itemFk, - GREATEST(quantity, 0), - buyingValue, - freightValue, - packing, - `grouping`, - groupingMode, - comissionValue, - packageValue, - packageFk, - price1, - price2, - price3, - minPrice, - vEntryFk - FROM tmp.inventory; + GREATEST(quantity, 0), + buyingValue, + freightValue, + packing, + `grouping`, + groupingMode, + comissionValue, + packageValue, + packageFk, + price1, + price2, + price3, + minPrice, + vEntryFk + FROM tmp.inventory; SELECT vWh, COUNT(*), util.VN_NOW() FROM tmp.inventory; @@ -57437,14 +57616,14 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `inventory_repair` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET character_set_client = utf8mb3 */ ; +/*!50003 SET character_set_results = utf8mb3 */ ; +/*!50003 SET collation_connection = utf8mb3_general_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `inventory_repair`() BEGIN @@ -57470,7 +57649,7 @@ BEGIN i.stems, b.quantity, b.buyingValue, - b.packageFk , + b.packagingFk , s.id AS supplierFk, s.name AS supplier FROM itemType it @@ -57484,7 +57663,7 @@ BEGIN LEFT JOIN origin o ON o.id = i.originFk ) ON it.id = i.typeFk LEFT JOIN edi.ekt ek ON b.ektFk = ek.id - WHERE (b.packageFk = "--" OR b.price2 = 0 OR b.packing = 0 OR b.buyingValue = 0) AND tr.landed > util.firstDayOfMonth(TIMESTAMPADD(MONTH,-1,util.VN_CURDATE())) AND s.name = 'INVENTARIO'; + WHERE (b.packagingFk = "--" OR b.price2 = 0 OR b.packing = 0 OR b.buyingValue = 0) AND tr.landed > util.firstDayOfMonth(TIMESTAMPADD(MONTH,-1,util.VN_CURDATE())) AND s.name = 'INVENTARIO'; DROP TEMPORARY TABLE IF EXISTS tmp.lastEntryOk; CREATE TEMPORARY TABLE tmp.lastEntryOk @@ -57507,7 +57686,7 @@ BEGIN i.stems, b.quantity, b.buyingValue, - b.packageFk , + b.packagingFk, s.id AS supplierFk, s.name AS supplier FROM itemType it @@ -57521,7 +57700,7 @@ BEGIN LEFT JOIN origin o ON o.id = i.originFk ) ON it.id = i.typeFk LEFT JOIN edi.ekt ek ON b.ektFk = ek.id - WHERE b.packageFk != "--" AND b.price2 != 0 AND b.packing != 0 AND b.buyingValue > 0 AND tr.landed > util.firstDayOfMonth(TIMESTAMPADD(MONTH,-2,util.VN_CURDATE())) + WHERE b.packagingFk != "--" AND b.price2 != 0 AND b.packing != 0 AND b.buyingValue > 0 AND tr.landed > util.firstDayOfMonth(TIMESTAMPADD(MONTH,-2,util.VN_CURDATE())) ORDER BY tr.landed DESC; DROP TEMPORARY TABLE IF EXISTS tmp.lastEntryOkGroup; @@ -57534,7 +57713,7 @@ BEGIN UPDATE buy b JOIN tmp.lastEntry lt ON lt.buyFk = b.id JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk - SET b.packageFk = eo.packageFk WHERE b.packageFk = "--"; + SET b.packagingFk = eo.packagingFk WHERE b.packagingFk = "--"; UPDATE buy b JOIN tmp.lastEntry lt ON lt.buyFk = b.id @@ -57854,6 +58033,41 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `invoiceInTax_afterUpsert` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceInTax_afterUpsert`(vInvoiceInFk INT) +BEGIN +/** + * Triggered actions when a invoiceInTax is updated or inserted. + * + * @param vInvoiceInFk The invoiceIn id + */ + DECLARE vTaxRowLimit INT; + DECLARE vLines INT; + + SELECT taxRowLimit INTO vTaxRowLimit FROM invoiceInConfig; + + SELECT COUNT(*) INTO vLines + FROM invoiceInTax + WHERE invoiceInFk = vInvoiceInFk; + + IF vLines >= vTaxRowLimit THEN + CALL util.throw (CONCAT('The maximum number of lines is ', vTaxRowLimit)); + END IF; +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 */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `invoiceInTax_getFromDua` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -57981,10 +58195,10 @@ BEGIN ii.issued, ii.operated, ii.supplierRef, - ii.cplusTrascendency472Fk, + ii.siiTrascendencyInvoiceInFk, ii.cplusTaxBreakFk, ii.cplusSubjectOpFk, - ii.cplusInvoiceType472Fk, + ii.siiTypeInvoiceInFk, ii.cplusRectificationTypeFk, ii.booked, IFNULL(a.isUeeMember, c.isUeeMember) isUeeMember, @@ -58014,7 +58228,7 @@ BEGIN JOIN supplier sc ON sc.id = ii.companyFk JOIN country cc ON cc.id = sc.countryFk JOIN invoiceInSerial iis ON iis.code = ii.serial - JOIN cplusInvoiceType472 cit ON cit.id = ii.cplusInvoiceType472Fk + JOIN siiTypeInvoiceIn cit ON cit.id = ii.siiTypeInvoiceInFk LEFT JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id LEFT JOIN sage.TiposTransacciones ttr ON ttr.CodigoTransaccion = iit.transactionTypeSageFk LEFT JOIN expence e ON e.id = iit.expenceFk @@ -58137,10 +58351,10 @@ BEGIN tii.supplierRef FACTURAEX, TRUE L340, (tii.isSameCountry OR NOT tii.isUeeMember) LRECT349, - tii.cplusTrascendency472Fk TIPOCLAVE, + tii.siiTrascendencyInvoiceInFk TIPOCLAVE, tii.cplusTaxBreakFk TIPOEXENCI, tii.cplusSubjectOpFk TIPONOSUJE, - tii.cplusInvoiceType472Fk TIPOFACT, + tii.siiTypeInvoiceInFk TIPOFACT, tii.cplusRectificationTypeFk TIPORECTIF, tii.cplusTerIdNifFk TERIDNIF, tii.nif TERNIF, @@ -58209,7 +58423,7 @@ BEGIN 1 TIPOCLAVE, tii.cplusTaxBreakFk TIPOEXENCI, tii.cplusSubjectOpFk TIPONOSUJE, - tii.cplusInvoiceType472Fk TIPOFACT, + tii.siiTypeInvoiceInFk TIPOFACT, tii.cplusRectificationTypeFk TIPORECTIF, tii.cplusTerIdNifFk TERIDNIF, tii.nif TERNIF, @@ -58369,7 +58583,7 @@ BEGIN io.issued AS FECHA, 1 AS NFACTICK, IF(ic.correctingFk,'D','') AS TIPOOPE, - io.cplusTrascendency477Fk AS TIPOCLAVE, + io.siiTrascendencyInvoiceOutFk AS TIPOCLAVE, io.cplusTaxBreakFk AS TIPOEXENCI, io.cplusSubjectOpFk AS TIPONOSUJE, io.siiTypeInvoiceOutFk AS TIPOFACT, @@ -58505,7 +58719,7 @@ BEGIN rs.TERNIF, rs.TERNOM, pgc.mod340 AS L340, - pgc.cplusTrascendency477Fk AS TIPOCLAVE, + pgc.siiTrascendencyInvoiceOutFk AS TIPOCLAVE, pgc.cplusTaxBreakFk as TIPOEXENCI, rs.TIPONOSUJE, rs.TIPOFACT, @@ -58582,85 +58796,6 @@ BEGIN SELECT CONCAT(vContador, ' total') AS FACTURAS_ASENTADAS; -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 */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutDelete` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOutDelete`(vRef VARCHAR(15)) -BEGIN - DECLARE vAsien INTEGER; - DECLARE vSendMail BOOL; - DECLARE vBody TEXT; - - SELECT ASIEN INTO vAsien - FROM XDiario - WHERE SERIE = SUBSTRING(vRef, 1, 1) - AND FACTURA = SUBSTRING(vRef, 2, LENGTH(vRef)-1) - LIMIT 1; - - SELECT IF(enlazado OR enlazadoSage, TRUE, FALSE), - CONCAT( - ' - - - - - - - ', - GROUP_CONCAT( - CONCAT(' - - - - - - - ' - ) SEPARATOR ' ' - ), - '
FECHASUBCTACONTRACONCEPTOEURODEBEEUROHABER
', IFNULL(FECHA,''), '', IFNULL(SUBCTA,''), '', IFNULL(CONTRA,''), '', IFNULL(CONCEPTO,''), '', IFNULL(EURODEBE,''), '', IFNULL(EUROHABER,''), '
' - ) - INTO vSendMail, vBody - FROM XDiario - WHERE ASIEN = vAsien; - - DELETE FROM XDiario - WHERE ASIEN = vAsien; - - IF vSendMail THEN - CALL mail_insert( - 'administracion@verdnatura.es', - 'noreply@verdnatura.es', - CONCAT('Eliminada factura ' ,vRef), - CONCAT( - '
-

Se ha eliminado el asiento ', vAsien, ' que estaba enlazado en SAGE/CONTAPLUS, vinculado a la factura ', vRef ,'

- ', vBody, '
' - ) - ); - END IF; - - UPDATE ticket - SET refFk = NULL - WHERE refFk = vRef; - - DELETE - FROM invoiceOut - WHERE ref = vRef; - END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -59317,46 +59452,6 @@ ELSE INSERT INTO vn.itemBarcode(itemFk,code) VALUES (vItemFk,vCode); END IF; -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 */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `itemFreight_Show` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `itemFreight_Show`(vItemFk INT, vWarehouseFk INT) -BEGIN - - SELECT cm3 Volumen_Entrada, - cm3delivery Volumen_Salida, - p.volume Volumen_del_embalaje, - p.width Ancho_del_embalaje, - p.`depth` Largo_del_embalaje, - b.packageFk , - IFNULL(p.height, i.`size`) + 10 Altura, - b.packing Packing_Entrada, - i.packingOut Packing_Salida, - i.id itemFk, - b.id buyFk, - b.entryFk, - w.name warehouseFk - FROM vn.itemCost ic - JOIN vn.item i ON i.id = ic.itemFk - LEFT JOIN cache.last_buy lb ON lb.item_id = ic.itemFk AND lb.warehouse_id = ic.warehouseFk - LEFT JOIN vn.buy b ON b.id = lb.buy_id - LEFT JOIN vn.packaging p ON p.id = b.packageFk - LEFT JOIN vn.warehouse w ON w.id = ic.warehouseFk - WHERE ic.itemFk = vItemFk - AND ic.warehouseFk = vWarehouseFk; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -59649,7 +59744,7 @@ BEGIN AND ish.visible > 0 AND ish.itemFk = vItemFk GROUP BY ish.id - ORDER BY (sc.id = vSectorFk) DESC, sh.priority DESC; + ORDER BY (sc.id = vSectorFk) DESC, sh.priority DESC, ish.created, p.pickingOrder; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -59677,78 +59772,78 @@ BEGIN * @param vShowType mostrar tipos */ - DECLARE vWarehouseFk INT; - DECLARE vShipped DATE; - DECLARE vCalcFk INT; - DECLARE vTypeFk INT; + DECLARE vWarehouseFk INT; + DECLARE vShipped DATE; + DECLARE vCalcFk INT; + DECLARE vTypeFk INT; + DECLARE vTag1 VARCHAR(25); + DECLARE vTag5 VARCHAR(25); + DECLARE vTag6 VARCHAR(25); + DECLARE vTag7 VARCHAR(25); + DECLARE vTag8 VARCHAR(25); - DECLARE vTag1 VARCHAR(25); - DECLARE vTag5 VARCHAR(25); - DECLARE vTag6 VARCHAR(25); - DECLARE vTag7 VARCHAR(25); - DECLARE vTag8 VARCHAR(25); + DECLARE vValue1 VARCHAR(50); + DECLARE vValue5 VARCHAR(50); + DECLARE vValue6 VARCHAR(50); + DECLARE vValue7 VARCHAR(50); + DECLARE vValue8 VARCHAR(50); - DECLARE vValue1 VARCHAR(50); - DECLARE vValue5 VARCHAR(50); - DECLARE vValue6 VARCHAR(50); - DECLARE vValue7 VARCHAR(50); - DECLARE vValue8 VARCHAR(50); + SELECT warehouseFk, shipped INTO vWarehouseFk, vShipped + FROM vn.ticket + WHERE id = vTicketFk; - SELECT warehouseFk, shipped INTO vWarehouseFk, vShipped - FROM vn.ticket - WHERE id = vTicketFk; + SELECT typeFk, tag5, value5, tag6, value6, tag7, value7, tag8, value8, t1.name, it1.value + INTO vTypeFk, vTag5, vValue5, vTag6, vValue6, vTag7, vValue7, vTag8, vValue8, vTag1, vValue1 + FROM vn.item i + LEFT JOIN vn.itemTag it1 ON it1.itemFk = i.id AND it1.priority = 1 + LEFT JOIN vn.tag t1 ON t1.id = it1.tagFk + WHERE i.id = vItemFk; - SELECT typeFk, tag5, value5, tag6, value6, tag7, value7, tag8, value8, t1.name, it1.value - INTO vTypeFk, vTag5, vValue5, vTag6, vValue6, vTag7, vValue7, vTag8, vValue8, vTag1, vValue1 - FROM vn.item i - LEFT JOIN vn.itemTag it1 ON it1.itemFk = i.id AND it1.priority = 1 - LEFT JOIN vn.tag t1 ON t1.id = it1.tagFk - WHERE i.id = vItemFk; + CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, vShipped); - CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, vShipped); - - SELECT i.id itemFk, - i.longName, - i.subName, - i.tag5, - i.value5, - (i.value5 <=> vValue5 COLLATE utf8_general_ci) match5, - i.tag6, - i.value6, - (i.value6 <=> vValue6 COLLATE utf8_general_ci) match6, - i.tag7, - i.value7, - (i.value7 <=> vValue7 COLLATE utf8_general_ci) match7, - i.tag8, - i.value8, - (i.value8 <=> vValue8 COLLATE utf8_general_ci) match8, - a.available, - IFNULL(ip.counter,0) counter, - IF(b.groupingMode = 1, b.grouping, b.packing) as minQuantity - FROM vn.item i - JOIN cache.available a ON a.item_id = i.id - LEFT JOIN vn.itemProposal ip ON ip.mateFk = i.id AND ip.itemFk = vItemFk - LEFT JOIN vn.itemTag it1 ON it1.itemFk = i.id AND it1.priority = 1 - LEFT JOIN vn.tag t1 ON t1.id = it1.tagFk + SELECT i.id itemFk, + i.longName, + i.subName, + i.tag5, + i.value5, + (i.value5 <=> vValue5 COLLATE utf8_general_ci) match5, + i.tag6, + i.value6, + (i.value6 <=> vValue6 COLLATE utf8_general_ci) match6, + i.tag7, + i.value7, + (i.value7 <=> vValue7 COLLATE utf8_general_ci) match7, + i.tag8, + i.value8, + (i.value8 <=> vValue8 COLLATE utf8_general_ci) match8, + a.available, + IFNULL(ip.counter,0) counter, + IF(b.groupingMode = 1, b.grouping, b.packing) as minQuantity, + iss.visible located + FROM item i + JOIN cache.available a ON a.item_id = i.id + LEFT JOIN itemProposal ip ON ip.mateFk = i.id AND ip.itemFk = vItemFk + LEFT JOIN itemTag it1 ON it1.itemFk = i.id AND it1.priority = 1 + LEFT JOIN tag t1 ON t1.id = it1.tagFk LEFT JOIN cache.last_buy lb ON lb.item_id = i.id AND lb.warehouse_id = vWarehouseFk - LEFT JOIN vn.buy b ON b.id = lb.buy_id - WHERE a.calc_id = vCalcFk - AND available > 0 - AND IF(vShowType,i.typeFk = vTypeFk,true) - AND i.id != vItemFk - ORDER BY counter DESC, - (t1.name = vTag1 COLLATE utf8_general_ci) DESC, - (it1.value = vValue1 COLLATE utf8_general_ci) DESC, - (i.tag6 = vTag6 COLLATE utf8_general_ci) DESC, - (i.value6 = vValue6 COLLATE utf8_general_ci) DESC, - (i.tag5 = vTag5 COLLATE utf8_general_ci) DESC, - (i.value5 = vValue5 COLLATE utf8_general_ci) DESC, - (i.tag7 = vTag7 COLLATE utf8_general_ci) DESC, - (i.value7 = vValue7 COLLATE utf8_general_ci) DESC, - (i.tag8 = vTag8 COLLATE utf8_general_ci) DESC, - (i.value8 = vValue8 COLLATE utf8_general_ci) DESC; - + LEFT JOIN buy b ON b.id = lb.buy_id + LEFT JOIN itemShelvingStock iss ON iss.itemFk = i.id AND iss.warehouseFk = vWarehouseFk + WHERE a.calc_id = vCalcFk + AND available > 0 + AND IF(vShowType,i.typeFk = vTypeFk,true) + AND i.id != vItemFk + ORDER BY counter DESC, + (t1.name = vTag1 COLLATE utf8_general_ci) DESC, + (it1.value = vValue1 COLLATE utf8_general_ci) DESC, + (i.tag5 = vTag5 COLLATE utf8_general_ci) DESC, + (i.value5 = vValue5 COLLATE utf8_general_ci) DESC, + (i.tag6 = vTag6 COLLATE utf8_general_ci) DESC, + (i.value6 = vValue6 COLLATE utf8_general_ci) DESC, + (i.tag7 = vTag7 COLLATE utf8_general_ci) DESC, + (i.value7 = vValue7 COLLATE utf8_general_ci) DESC, + (i.tag8 = vTag8 COLLATE utf8_general_ci) DESC, + (i.value8 = vValue8 COLLATE utf8_general_ci) DESC; END ;; DELIMITER ; @@ -60126,14 +60221,14 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `itemShelvingMakeFromDate` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET character_set_client = utf8mb3 */ ; +/*!50003 SET character_set_results = utf8mb3 */ ; +/*!50003 SET collation_connection = utf8mb3_general_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingMakeFromDate`(IN `vShelvingFk` VARCHAR(8), IN `vBarcode` VARCHAR(22), IN `vQuantity` INT, IN `vPackagingFk` VARCHAR(10), IN `vGrouping` INT, IN `vPacking` INT, IN `vWarehouseFk` INT, `vCreated` VARCHAR(22)) BEGIN @@ -60183,7 +60278,7 @@ BEGIN vCreated, IF(vGrouping = 0, IFNULL(b.packing, vPacking), vGrouping) `grouping`, IF(vPacking = 0, b.packing, vPacking) packing, - IF(vPackagingFk = '', b.packageFk, vPackagingFk) packaging + IF(vPackagingFk = '', b.packagingFk, vPackagingFk) packaging FROM vn.item i LEFT JOIN cache.last_buy lb ON i.id = lb.item_id AND lb.warehouse_id = vWarehouseFk LEFT JOIN vn.buy b ON b.id = lb.buy_id @@ -60371,7 +60466,6 @@ proc:BEGIN WHERE s.warehouseFk = vWarehouseFk AND s.isMain; - SELECT COUNT(*) INTO hasFatherSector FROM vn.sector WHERE sonFk = vSectorFk; @@ -60386,52 +60480,49 @@ proc:BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.itemShelvingRadar; IF hasFatherSector THEN - CREATE TEMPORARY TABLE tmp.itemShelvingRadar (PRIMARY KEY (itemFk)) ENGINE = MEMORY - SELECT * FROM ( - SELECT iss.itemFk, - i.longName, - i.size, - i.subName producer, - IFNULL(a.available,0) available, - SUM(IF(s.sonFk = vSectorFk, IFNULL(iss.visible,0), 0)) upstairs, - SUM(IF(iss.sectorFk = vSectorFk, IFNULL(iss.visible,0), 0)) downstairs, - IF(it.isPackaging, null, IFNULL(v.visible,0)) as visible, - vSectorFk as sectorFk + SELECT * + FROM ( + SELECT iss.itemFk, + i.longName, + i.size, + i.subName producer, + IFNULL(a.available,0) available, + SUM(IF(s.sonFk = vSectorFk, IFNULL(iss.visible,0), 0)) upstairs, + SUM(IF(iss.sectorFk = vSectorFk, IFNULL(iss.visible,0), 0)) downstairs, + IF(it.isPackaging, NULL, IFNULL(v.visible,0)) as visible, + vSectorFk sectorFk + FROM vn.itemShelvingStock iss + JOIN vn.sector s ON s.id = iss.sectorFk + JOIN vn.item i on i.id = iss.itemFk + JOIN vn.itemType it ON it.id = i.typeFk AND vBuyerFk IN (0,it.workerFk) + LEFT JOIN cache.available a ON a.item_id = iss.itemFk AND a.calc_id = vCalcAvailableFk + LEFT JOIN cache.visible v ON v.item_id = iss.itemFk AND v.calc_id = vCalcVisibleFk + WHERE vSectorFk IN (iss.sectorFk, s.sonFk) + GROUP BY iss.itemFk - FROM vn.itemShelvingStock iss - JOIN vn.sector s ON s.id = iss.sectorFk - JOIN vn.item i on i.id = iss.itemFk - JOIN vn.itemType it ON it.id = i.typeFk AND vBuyerFk IN (0,it.workerFk) - LEFT JOIN cache.available a ON a.item_id = iss.itemFk AND a.calc_id = vCalcAvailableFk - LEFT JOIN cache.visible v ON v.item_id = iss.itemFk AND v.calc_id = vCalcVisibleFk - WHERE vSectorFk IN (iss.sectorFk, s.sonFk) - AND it.workerFk != 3366 + UNION ALL - GROUP BY iss.itemFk - - UNION ALL - - SELECT v.item_id, - i.longName, - i.size, - i.subName producer, - IFNULL(a.available,0) as available, - 0 upstairs, - 0 downstairs, - IF(it.isPackaging, NULL, v.visible) visible, - vSectorFk as sectorFk - FROM cache.visible v - JOIN vn.item i on i.id = v.item_id - JOIN vn.itemType it ON it.id = i.typeFk AND vBuyerFk IN (0,it.workerFk) - LEFT JOIN vn.itemShelvingStock iss ON iss.itemFk = v.item_id AND iss.warehouseFk = vWarehouseFk - LEFT JOIN cache.available a ON a.item_id = v.item_id AND a.calc_id = vCalcAvailableFk - WHERE v.calc_id = vCalcVisibleFk - AND iss.itemFk IS NULL - AND it.isInventory - ) sub GROUP BY itemFk; + SELECT v.item_id, + i.longName, + i.size, + i.subName producer, + IFNULL(a.available,0) as available, + 0 upstairs, + 0 downstairs, + IF(it.isPackaging, NULL, v.visible) visible, + vSectorFk as sectorFk + FROM cache.visible v + JOIN vn.item i on i.id = v.item_id + JOIN vn.itemType it ON it.id = i.typeFk AND vBuyerFk IN (0,it.workerFk) + LEFT JOIN vn.itemShelvingStock iss ON iss.itemFk = v.item_id AND iss.warehouseFk = vWarehouseFk + LEFT JOIN cache.available a ON a.item_id = v.item_id AND a.calc_id = vCalcAvailableFk + WHERE v.calc_id = vCalcVisibleFk + AND iss.itemFk IS NULL + AND it.isInventory + ) sub GROUP BY itemFk; SELECT ishr.*, CAST(visible - upstairs - downstairs AS DECIMAL(10,0)) AS nicho, @@ -60446,12 +60537,8 @@ proc:BEGIN AND tst.alertLevel = 0 GROUP BY s.itemFk ) sub ON sub.itemFk = ishr.itemFk - ORDER BY i.typeFk, i.longName - ; - - + ORDER BY i.typeFk, i.longName; ELSE - CREATE TEMPORARY TABLE tmp.itemShelvingRadar (PRIMARY KEY (itemFk)) ENGINE = MEMORY @@ -60473,32 +60560,25 @@ proc:BEGIN IFNULL(v.visible,0) visible, b.isPickedOff, iss.sectorFk - FROM vn.itemShelvingStock iss - JOIN vn.item i on i.id = iss.itemFk - LEFT JOIN cache.last_buy lb ON lb.item_id = iss.itemFk AND lb.warehouse_id = vWarehouseFk - LEFT JOIN vn.buy b ON b.id = lb.buy_id - LEFT JOIN cache.available a ON a.item_id = iss.itemFk AND a.calc_id = vCalcAvailableFk - LEFT JOIN cache.visible v ON v.item_id = iss.itemFk AND v.calc_id = vCalcVisibleFk - LEFT JOIN (SELECT itemFk, sum(saldo) as onTheWay - FROM vn.itemPlacementSupplyList - WHERE saldo > 0 - GROUP BY itemFk - ) ips ON ips.itemFk = i.id - WHERE IFNULL(iss.sectorFk,0) IN (0, vSectorFk) - OR iss.sectorFk = vSectorFk; - /* - UPDATE tmp.itemShelvingRadar isr - JOIN vn.itemShelvingStock iss ON iss.itemFk = isr.itemFk - SET isr.dayEndVisible = isr.dayEndVisible + iss.visible, - isr.firstNegative = isr.firstNegative + iss.visible, - isr.itemPlacementVisible = isr.itemPlacementVisible + iss.visible - WHERE iss.sectorFk = vSonSectorFk; - */ + FROM vn.itemShelvingStock iss + JOIN vn.item i on i.id = iss.itemFk + LEFT JOIN cache.last_buy lb ON lb.item_id = iss.itemFk AND lb.warehouse_id = vWarehouseFk + LEFT JOIN vn.buy b ON b.id = lb.buy_id + LEFT JOIN cache.available a ON a.item_id = iss.itemFk AND a.calc_id = vCalcAvailableFk + LEFT JOIN cache.visible v ON v.item_id = iss.itemFk AND v.calc_id = vCalcVisibleFk + LEFT JOIN (SELECT itemFk, sum(saldo) as onTheWay + FROM vn.itemPlacementSupplyList + WHERE saldo > 0 + GROUP BY itemFk + ) ips ON ips.itemFk = i.id + WHERE IFNULL(iss.sectorFk,0) IN (0, vSectorFk) + OR iss.sectorFk = vSectorFk; + DROP TEMPORARY TABLE IF EXISTS tmp.itemOutTime; CREATE TEMPORARY TABLE tmp.itemOutTime SELECT *,SUM(amount) quantity FROM - (SELECT item_id itemFk, + (SELECT item_id itemFk, amount, IF(HOUR(t.shipped), HOUR(t.shipped), HOUR(z.`hour`)) as hours, IF(MINUTE(t.shipped), MINUTE(t.shipped), MINUTE(z.`hour`)) as minutes @@ -60528,15 +60608,19 @@ proc:BEGIN firstNegative = if (firstNegative < 0, firstNegative, firstNegative + quantity), `hour` = ifnull(if (firstNegative > 0 , `hour`, hours),0), `minute` = ifnull(if (firstNegative > 0, `minute`, minutes),0); -/* - UPDATE tmp.itemShelvingRadar - SET itemPlacementVisible = 0, - dayEndVisible = 0, - firstNegative = 0 - WHERE itemPlacementVisible = - itemShelvingStock; -*/ - SELECT * FROM tmp.itemShelvingRadar; + UPDATE tmp.itemShelvingRadar isr + JOIN (SELECT s.itemFk, sum(s.quantity) amount + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + JOIN ticketLastState tls ON tls.ticketFk = t.id + WHERE t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE()) + AND tls.name = 'Prep Camara' + GROUP BY s.itemFk) sub ON sub.itemFk = isr.itemFk + SET isr.dayEndVisible = dayEndVisible + sub.amount, + firstNegative = firstNegative + sub.amount; + + SELECT * FROM tmp.itemShelvingRadar; END IF; DROP TEMPORARY TABLE tmp.itemShelvingRadar; @@ -60707,6 +60791,318 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_reserve` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_reserve`() +BEGIN +/** + * Reserva cantidades con ubicaciones para un conjunto de sales del mismo + * almacen. + * + * @table tmp.sale(saleFk, userFk) + */ + DECLARE vCalcFk INT; + DECLARE vWarehouseFk INT; + DECLARE vCurrentYear INT DEFAULT YEAR(util.VN_NOW()); + DECLARE vLastPickingOrder INT; + + SELECT t.warehouseFk, MAX(p.pickingOrder) + INTO vWarehouseFk, vLastPickingOrder + FROM ticket t + JOIN sale s ON s.ticketFk = t.id + JOIN tmp.sale ts ON ts.saleFk = s.id + LEFT JOIN itemShelvingSale iss ON iss.saleFk = ts.saleFk + LEFT JOIN itemShelving ish ON ish.id = iss.itemShelvingFk + LEFT JOIN shelving sh ON sh.code = ish.shelvingFk + LEFT JOIN parking p ON p.id = sh.parkingFk + WHERE t.warehouseFk IS NOT NULL; + + IF vWarehouseFk IS NULL THEN + CALL util.throw('Warehouse not set'); + END IF; + + CALL cache.visible_refresh(vCalcFk, FALSE, vWarehouseFk); + + SET @outstanding = 0; + SET @oldsaleFk = 0; + + CREATE OR REPLACE TEMPORARY TABLE tSalePlacementQuantity + (INDEX(saleFk)) + ENGINE = MEMORY + SELECT saleFk, userFk, quantityToReserve, itemShelvingFk + FROM( SELECT saleFk, + sub.userFk, + itemShelvingFk , + IF(saleFk <> @oldsaleFk, @outstanding := quantity, @outstanding), + @qtr := LEAST(@outstanding, available) quantityToReserve, + @outStanding := @outStanding - @qtr, + @oldsaleFk := saleFk + FROM( + SELECT ts.saleFk, + ts.userFk, + s.quantity, + ish.id itemShelvingFk, + ish.visible - IFNULL(ishr.reservedQuantity, 0) available + FROM tmp.sale ts + JOIN sale s ON s.id = ts.saleFk + JOIN itemShelving ish ON ish.itemFk = s.itemFk + LEFT JOIN ( + SELECT itemShelvingFk, SUM(quantity) reservedQuantity + FROM itemShelvingSale + WHERE NOT isPicked + GROUP BY itemShelvingFk) ishr ON ishr.itemShelvingFk = ish.id + JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN parking p ON p.id = sh.parkingFk + JOIN sector sc ON sc.id = p.sectorFk + JOIN warehouse w ON w.id = sc.warehouseFk + JOIN productionConfig pc + WHERE w.id = vWarehouseFk + AND NOT sc.isHideForPickers + ORDER BY + s.id, + p.pickingOrder >= vLastPickingOrder, + sh.priority DESC, + ish.visible >= s.quantity DESC, + s.quantity MOD ish.grouping = 0 DESC, + ish.grouping DESC, + IF(pc.orderMode = 'Location', p.pickingOrder, ish.created) + )sub + )sub2 + WHERE quantityToReserve > 0; + + INSERT INTO itemShelvingSale( + itemShelvingFk, + saleFk, + quantity, + userFk) + SELECT itemShelvingFk, + saleFk, + quantityToReserve, + IFNULL(userFk, getUser()) + FROM tSalePlacementQuantity spl; + + DROP TEMPORARY TABLE tmp.sale; +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 */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_reserveByCollection` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb3 */ ; +/*!50003 SET character_set_results = utf8mb3 */ ; +/*!50003 SET collation_connection = utf8mb3_general_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_reserveByCollection`( + vCollectionFk INT(11) +) +BEGIN +/** + * Reserva cantidades con ubicaciones para el contenido de una colección + * + * @param vCollectionFk Identificador de collection + */ + CREATE OR REPLACE TEMPORARY TABLE tmp.sale + (INDEX(saleFk)) + ENGINE = MEMORY + SELECT s.id saleFk, NULL userFk + FROM ticketCollection tc + JOIN sale s ON s.ticketFk = tc.ticketFk + LEFT JOIN ( + SELECT DISTINCT saleFk + FROM saleTracking st + JOIN state s ON s.id = st.stateFk + WHERE st.isChecked + AND s.semaphore = 1)st ON st.saleFk = s.id + WHERE tc.collectionFk = vCollectionFk + AND st.saleFk IS NULL + AND NOT s.isPicked; + + CALL itemShelvingSale_reserve(); +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 */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_reserveBySale` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb3 */ ; +/*!50003 SET character_set_results = utf8mb3 */ ; +/*!50003 SET collation_connection = utf8mb3_general_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_reserveBySale`( + vSelf INT , + vQuantity INT, + vUserFk INT +) +BEGIN +/** + * Reserva cantida y ubicación para una saleFk + * + * @param vSelf Identificador de la venta + * @param vQuantity Cantidad a reservar + * @param vUserFk Id de usuario que realiza la reserva + */ + CREATE OR REPLACE TEMPORARY TABLE tmp.sale + ENGINE = MEMORY + SELECT vSelf saleFk, vUserFk userFk; + + CALL itemShelvingSale_reserve(); +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 */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_setQuantity` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb3 */ ; +/*!50003 SET character_set_results = utf8mb3 */ ; +/*!50003 SET collation_connection = utf8mb3_general_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_setQuantity`( + vItemShelvingSaleFk INT(10), + vQuantity DECIMAL(10,0), + vIsItemShelvingSaleEmpty BOOLEAN +) +BEGIN +/** + * Gestiona la reserva de un itemShelvingFk, actualizando isPicked y quantity + * en vn.itemShelvingSale y vn.sale.isPicked en caso necesario. + * Si la reserva de la ubicación es fallida, se regulariza la situación + * + * @param vItemShelvingSaleFk Id itemShelvingSaleFK + * @param vQuantity Cantidad real que se ha cogido de la ubicación + * @param vIsItemShelvingSaleEmpty determina si ka ubicación itemShelvingSale se ha + * quedado vacio tras el movimiento + */ + DECLARE vSaleFk INT; + DECLARE vCursorSaleFk INT; + DECLARE vItemShelvingFk INT; + DECLARE vReservedQuantity INT; + DECLARE vRemainingQuantity INT; + DECLARE vItemFk INT; + DECLARE vUserFk INT; + DECLARE vDone BOOLEAN DEFAULT FALSE; + DECLARE vSales CURSOR FOR + SELECT iss.saleFk, iss.userFk + FROM itemShelvingSale iss + JOIN sale s ON s.id = iss.saleFk + WHERE iss.id = vItemShelvingSaleFk + AND s.itemFk = vItemFk + AND NOT iss.isPicked; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + IF (SELECT isPicked FROM itemShelvingSale WHERE id = vItemShelvingSaleFk) THEN + CALL util.throw('Booking completed'); + END IF; + + SELECT s.itemFk, iss.saleFk, iss.itemShelvingFk + INTO vItemFk, vSaleFk, vItemShelvingFk + FROM itemShelvingSale iss + JOIN sale s ON s.id = iss.saleFk + WHERE iss.id = vItemShelvingSaleFk + AND NOT iss.isPicked; + + UPDATE itemShelvingSale + SET isPicked = TRUE, + quantity = vQuantity + WHERE id = vItemShelvingSaleFk; + + UPDATE itemShelving + SET visible = IF(vIsItemShelvingSaleEmpty, 0, GREATEST(0,visible - vQuantity)) + WHERE id = vItemShelvingFk; + + IF vIsItemShelvingSaleEmpty THEN + OPEN vSales; +l: LOOP + SET vDone = FALSE; + FETCH vSales INTO vCursorSaleFk, vUserFk; + IF vDone THEN + LEAVE l; + END IF; + + CREATE OR REPLACE TEMPORARY TABLE tmp.sale + (INDEX(saleFk, userFk)) + ENGINE = MEMORY + SELECT vCursorSaleFk, vUserFk; + + CALL itemShelvingSale_reserveWhitUser(); + DROP TEMPORARY TABLE tmp.sale; + + END LOOP; + CLOSE vSales; + + DELETE iss + FROM itemShelvingSale iss + JOIN sale s ON s.id = iss.saleFk + WHERE iss.id = vItemShelvingSaleFk + AND s.itemFk = vItemFk + AND NOT iss.isPicked; + END IF; + + SELECT SUM(quantity) INTO vRemainingQuantity + FROM itemShelvingSale + WHERE saleFk = vSaleFk + AND NOT isPicked; + + IF vRemainingQuantity THEN + CALL itemShelvingSale_reserveBySale (vSaleFk, vRemainingQuantity, NULL); + + SELECT SUM(quantity) INTO vRemainingQuantity + FROM itemShelvingSale + WHERE saleFk = vSaleFk + AND NOT isPicked; + + IF NOT vRemainingQuantity <=> 0 THEN + SELECT SUM(iss.quantity) + INTO vReservedQuantity + FROM itemShelvingSale iss + WHERE iss.saleFk = vSaleFk; + + CALL saleTracking_new( + vSaleFk, + TRUE, + vReservedQuantity, + `account`.`myUser_getId`(), + NULL, + 'PREPARED', + TRUE); + + UPDATE sale s + SET s.quantity = vReservedQuantity + WHERE s.id = vSaleFk ; + END IF; + END IF; +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 */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `itemShelvingTransfer` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -60764,14 +61160,14 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `itemShelving_add` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET character_set_client = utf8mb3 */ ; +/*!50003 SET character_set_results = utf8mb3 */ ; +/*!50003 SET collation_connection = utf8mb3_general_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_add`(IN vShelvingFk VARCHAR(8), IN vBarcode VARCHAR(22), IN vQuantity INT, IN vPackagingFk VARCHAR(10), IN vGrouping INT, IN vPacking INT, IN vWarehouseFk INT) BEGIN @@ -60827,7 +61223,7 @@ BEGIN vQuantity, IFNULL(vGrouping, b.grouping), IFNULL(vPacking, b.packing), - IFNULL(vPackagingFk, b.packageFk) + IFNULL(vPackagingFk, b.packagingFk) FROM item i LEFT JOIN cache.last_buy lb ON i.id = lb.item_id AND lb.warehouse_id = vWarehouseFk LEFT JOIN buy b ON b.id = lb.buy_id @@ -60944,27 +61340,6 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `itemShelving_BuyerGet` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_BuyerGet`( ) -BEGIN - - SELECT * FROM vn.buyer; - -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 */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `itemShelving_filterBuyer` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -61185,90 +61560,165 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_getSaleDate`(vShelvingFk VARCHAR(3)) BEGIN - /* Devuelve la minima fecha en que se necesita cada producto en esa matricula. + /* Devuelve la mínima fecha en que se necesita cada producto en esa matrícula. * * @param vShelvingFk Matrícula del carro o pallet */ DECLARE vWarehouseFk INT; + DECLARE vStockScopeDays INT; - SELECT warehouseFk INTO vWarehouseFk - FROM shelving s - JOIN parking p ON s.parkingFk = p.id - JOIN sector st ON st.id = p.sectorFk - WHERE s.code = vShelvingFk COLLATE utf8_unicode_ci; + SELECT s.warehouseFk, stockScopeDays + INTO vWarehouseFk, vStockScopeDays + FROM sector s + JOIN operator o ON s.id = o.sectorFk + JOIN productionConfig pc + WHERE o.workerFk = account.myUser_getId(); - DROP TEMPORARY TABLE IF EXISTS tmp.itemShelvingDistinct; - CREATE TEMPORARY TABLE tmp.itemShelvingDistinct + IF vWarehouseFk IS NULL + THEN CALL util.throw('WarehouseFk not setted'); + END IF; + + IF vStockScopeDays IS NULL + THEN CALL util.throw('StockScopeDays not setted'); + END IF; + + CREATE OR REPLACE TEMPORARY TABLE tmp.tItems (PRIMARY KEY (itemFk)) ENGINE = MEMORY - SELECT itemFk, SUM(visible) visible - FROM vn.itemShelving - WHERE shelvingFk = vShelvingFk COLLATE utf8_unicode_ci - GROUP BY itemFk; + SELECT itemFk, SUM(visible) visible + FROM itemShelving + WHERE shelvingFk = vShelvingFk COLLATE utf8_unicode_ci + GROUP BY itemFk; - DROP TEMPORARY TABLE IF EXISTS tmp.item; - CREATE TEMPORARY TABLE tmp.item - (PRIMARY KEY (itemFk)) - ENGINE = MEMORY - SELECT * FROM tmp.itemShelvingDistinct; + CREATE OR REPLACE TEMPORARY TABLE tmp.tStockByDay + (INDEX (itemFk, dated)) + ENGINE = MEMORY + SELECT dated, + SUM(t3.amount) OVER (PARTITION BY t3.itemFk ORDER BY dated) stock, + t3.itemFk + FROM ( + SELECT t.itemFk, dated, SUM(amount) amount + FROM ( + SELECT t2.itemFk, t2.amount, t2.dated + FROM ( + SELECT item_id itemFk, amount, util.VN_CURDATE() dated + FROM cache.stock s + JOIN tmp.tItems i ON i.itemFk = s.item_id + WHERE s.warehouse_id = vWarehouseFk + UNION ALL + SELECT ish.itemFk, - SUM(ish.visible), util.VN_CURDATE() + FROM itemShelving ish + JOIN tmp.tItems i ON i.itemFk = ish.itemFk + JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN parking p ON sh.parkingFk = p.id + JOIN sector s ON s.id = p.sectorFk + WHERE s.isReserve + GROUP BY ish.itemFk + UNION ALL + SELECT iei.itemFk, SUM(quantity), landed + FROM itemEntryIn iei + JOIN tmp.tItems i ON i.itemFk = iei.itemFk + WHERE iei.landed BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY + AND iei.warehouseInFk = vWarehouseFk + AND NOT isVirtualStock + GROUP BY iei.itemFk, iei.landed + UNION ALL + SELECT ieo.itemFk, SUM(quantity), shipped + FROM itemEntryOut ieo + JOIN tmp.tItems i ON i.itemFk = ieo.itemFk + WHERE ieo.shipped BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY + AND ieo.warehouseOutFk = vWarehouseFk + GROUP BY ieo.itemFk, ieo.shipped + UNION ALL + SELECT i.itemFk, SUM(ito.quantity), DATE(ito.shipped) + FROM itemTicketOut ito + JOIN tmp.tItems i ON i.itemFk = ito.itemFk + WHERE ito.shipped BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY + AND ito.warehouseFk = vWarehouseFk + GROUP BY ito.itemFk, ito.shipped + ) t2 + JOIN tmp.tItems i ON i.itemFk = t2.itemFk)t + GROUP BY t.itemFk, dated + ) t3; - DROP TEMPORARY TABLE IF EXISTS tmp.stockByDay; - CREATE TEMPORARY TABLE tmp.stockByDay - (index (itemFk, dated)) - ENGINE = MEMORY - SELECT t3.amount, dated, - @stock := IF(@itemFk = t3.itemFk, @stock + t3.amount, t3.amount) stock, - @itemFk := t3.itemFk itemFk - FROM ( - SELECT * FROM ( - SELECT t2.* FROM ( - SELECT item_id itemFk, amount, util.VN_CURDATE() dated - FROM cache.stock - WHERE warehouse_id = vWarehouseFk - UNION ALL - SELECT ish.itemFk, - sum(visible), util.VN_CURDATE() - FROM vn.itemShelving ish + -- Se restan las entradas de hoy + UPDATE tmp.tStockByDay sbd + JOIN (SELECT iei.itemFk, SUM(quantity) todayEntry + FROM itemEntryIn iei + JOIN tmp.tItems i ON i.itemFk = iei.itemFk + WHERE iei.landed = util.VN_CURDATE() + AND iei.warehouseInFk = vWarehouseFk + AND NOT iei.isVirtualStock) sub ON sub.itemFk = sbd.itemFk + SET sbd.stock = sbd.stock - sub.todayEntry + WHERE sbd.dated = util.VN_CURDATE(); + + -- Se añaden las lineas de venta servidas + UPDATE tmp.tStockByDay sbd + JOIN (SELECT s.itemFK, SUM(quantity) amount + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + WHERE t.warehouseFk = vWarehouseFk + AND t.shipped BETWEEN util.VN_CURDATE() AND util.midnight() + AND s.isPicked + GROUP BY s.itemFk) sub ON sub.itemFk = sbd.itemFk + SET sbd.stock = sbd.stock + sub.amount; + + -- Se añaden los items ubicados hoy + UPDATE tmp.tStockByDay sbd + JOIN (SELECT ish.itemFK, SUM(ish.visible) amount + FROM itemShelving ish JOIN shelving sh ON sh.code = ish.shelvingFk - JOIN parking p ON sh.parkingFk = p.id + JOIN parking p ON p.id = sh.parkingFk JOIN sector s ON s.id = p.sectorFk - WHERE s.isReserve - GROUP BY ish.itemFk - UNION ALL - SELECT item_id, sum(iei.amount), dat - FROM vn2008.item_entry_in iei - WHERE dat >= util.VN_CURDATE() - AND warehouse_id = vWarehouseFk - AND isVirtualStock = FALSE - GROUP BY item_id, dat - UNION ALL - SELECT item_id, sum(ieo.amount), dat - FROM vn2008.item_entry_out ieo - WHERE dat >= util.VN_CURDATE() - AND warehouse_id = vWarehouseFk - GROUP BY item_id, dat - UNION ALL - SELECT i.itemFk, sum(io.amount), dat - FROM vn2008.item_out io - JOIN tmp.item i ON i.itemFk = io.item_id - WHERE io.dat >= util.VN_CURDATE() - AND io.warehouse_id = vWarehouseFk - GROUP BY io.item_id, io.dat - ) t2 - JOIN tmp.itemShelvingDistinct ish ON ish.itemFk = t2.itemFk) t - order by t.itemFk, DATE(t.dated), t.amount DESC) t3; + WHERE s.warehouseFk = vWarehouseFk + AND NOT s.isReserve + AND ish.created BETWEEN util.VN_CURDATE() AND util.midnight() + GROUP BY ish.itemFk) sub ON sub.itemFk = sbd.itemFk + SET sbd.stock = sbd.stock + sub.amount; - SELECT sbd.itemFk, i.longName, DATE(dated) dated, ish.visible amount, sbd.stock - FROM tmp.stockByDay sbd - JOIN vn.item i ON i.id = sbd.itemFk - JOIN tmp.itemShelvingDistinct ish ON ish.itemFk = sbd.itemFk - WHERE ish.visible >= sbd.stock - GROUP BY itemFk - ORDER BY dated; + SELECT ts.itemFk, + i.longName, + IF(ts.stock<=0, ts.dated, NULL) dated, + ts.stock, + sub4.visible, + sub4.shelvingFk + FROM( + SELECT IFNULL(sub2.minDated, sub.minDated) dated, + IFNULL(sub2.itemFk, sub.itemFk) itemFk + FROM(SELECT sbd.itemFk, + MIN(dated) minDated, + sbd.stock + FROM tmp.tItems ti + LEFT JOIN tmp.tStockByDay sbd ON sbd.itemFk = ti.itemFk + GROUP BY itemFk)sub + LEFT JOIN ( + SELECT sbd.itemFk, + MIN(dated) minDated, + sbd.stock + FROM tmp.tItems ti + LEFT JOIN tmp.tStockByDay sbd ON sbd.itemFk = ti.itemFk + WHERE sbd.stock <= 0 + GROUP BY itemFk)sub2 ON sub2.itemFk =sub.itemFk + WHERE sub2.itemFk IS NOT NULL + OR (sub2.itemFk IS NULL AND sub.itemFk IS NOT NULL)) sub3 + LEFT JOIN tmp.tStockByDay ts ON ts.itemFk = sub3.itemFk AND ts.dated = sub3.dated + JOIN (SELECT ish.itemFk, + ish.visible, + p.sectorFk, + ish.shelvingFk + FROM itemShelving ish + JOIN vn.shelving sh ON sh.code = ish.shelvingFk + LEFT JOIN parking p ON p.id = parkingFk + LEFT JOIN vn.sector s ON s.id = p.sectorFk + WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci + ) sub4 ON sub4.itemFk = ts.itemFk + LEFT JOIN sector s ON s.id = sub4.sectorFk + LEFT JOIN item i ON i.id = ts.itemFk + WHERE NOT s.isReserve; + + DROP TEMPORARY TABLE tmp.tStockByDay, tmp.tItems; - DROP TEMPORARY TABLE tmp.stockByDay, - tmp.itemShelvingDistinct, - tmp.item; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -62156,8 +62606,7 @@ BEGIN * @table tmp.itemCalc(itemFk, wareHouseFk, dated, quantity) * @return tmp.itemAtp(itemFk, warehouseFk, quantity) */ - DROP TEMPORARY TABLE IF EXISTS tItemOrdered; - CREATE TEMPORARY TABLE tItemOrdered + CREATE OR REPLACE TEMPORARY TABLE tItemOrdered (UNIQUE(itemFk, warehouseFk, dated)) ENGINE = MEMORY SELECT itemFk, warehouseFk, dated, SUM(quantity) quantity @@ -62175,8 +62624,8 @@ BEGIN SET @lastWareHouseFk := 0; SET @lastQuantity := 0; - DROP TEMPORARY TABLE IF EXISTS tmp.itemAtp; - CREATE TEMPORARY TABLE tmp.itemAtp + CREATE OR REPLACE TEMPORARY TABLE tmp.itemAtp + (INDEX (itemFk, wareHouseFk)) SELECT itemFk, wareHouseFk, MIN(quantityAccumulated) quantity FROM ( SELECT @@ -62542,6 +62991,7 @@ BEGIN CALL `cache`.stock_refresh(vForce); CALL item_getMinacum(NULL, util.VN_CURDATE(), vDays, NULL); CALL item_getMinETD(); + CALL item_zoneClosure(); SELECT i.id itemFk, i.longName, @@ -62552,7 +63002,8 @@ BEGIN w.name warehouse, SUM(IFNULL(sub.amount,0)) lack, i.inkFk, - IFNULL(im.timed, util.midnight()) timed + IFNULL(im.timed, util.midnight()) timed, + IFNULL(izc.timed, util.midnight()) minTimed FROM (SELECT item_id, warehouse_id, amount @@ -62570,14 +63021,16 @@ BEGIN JOIN itemType it ON it.id = i.typeFk JOIN itemCategory ic ON ic.id = it.categoryFk LEFT JOIN tmp.itemMinETD im ON im.itemFk = i.id + LEFT JOIN tmp.itemZoneClosure izc ON izc.itemFk = i.id WHERE w.isForTicket - AND ic.display <> 0 + AND ic.display AND it.code != 'GEN' GROUP BY i.id, w.id HAVING lack < 0; DROP TEMPORARY TABLE tmp.itemMinacum; DROP TEMPORARY TABLE tmp.itemMinETD; + DROP TEMPORARY TABLE tmp.itemZoneClosure; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -63000,7 +63453,7 @@ BEGIN ), i.subname = JSON_VALUE(vValues, '$.4'), i.size = JSON_VALUE(vOverwrites, '$.size'), - i.stems = JSON_VALUE(vOverwrites, '$.stems'), + i.stems = IFNULL(JSON_VALUE(vOverwrites, '$.stems'),i.stems), i.category = JSON_VALUE(vOverwrites, '$.category'), i.tag5 = JSON_VALUE(vTags, '$.5'), i.tag6 = JSON_VALUE(vTags, '$.6'), @@ -63170,6 +63623,97 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `item_setVisibleDiscard` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb3 */ ; +/*!50003 SET character_set_results = utf8mb3 */ ; +/*!50003 SET collation_connection = utf8mb3_general_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `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 vDefaultCompanyFk INT; + DECLARE vCalc INT; + DECLARE vAddressShortage INT; + + SELECT barcodeToItem(vItemFk) INTO vItemFk; + + SELECT DEFAULT(companyFk) INTO vDefaultCompanyFk + FROM vn.ticket LIMIT 1; + + IF vAddressFk IS NULL THEN + SELECT pc.shortageAddressFk INTO vAddressShortage + FROM productionConfig pc ; + 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, + vDefaultCompanyFk, + 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 ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `item_updatePackingShelve` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; @@ -63242,6 +63786,10 @@ BEGIN DECLARE vHasNotInventory BOOLEAN DEFAULT FALSE; DECLARE vInventoried2 DATE; DECLARE vDateDayEnd DATETIME; + DECLARE vInventorySupplierFk INT; + + SELECT inventorySupplierFk INTO vInventorySupplierFk + FROM entryConfig; SET vDateDayEnd = util.dayEnd(vDated); @@ -63249,7 +63797,7 @@ BEGIN FROM travel tr JOIN entry E ON E.travelFk = tr.id WHERE landed <= vDateDayEnd - AND E.supplierFk = 4 + AND E.supplierFk = vInventorySupplierFk ORDER BY landed DESC LIMIT 1; @@ -63261,7 +63809,7 @@ BEGIN FROM travel tr JOIN entry E ON E.travelFk = tr.id WHERE landed >= vDated - AND E.supplierFk = 4 + AND E.supplierFk = vInventorySupplierFk ORDER BY landed ASC LIMIT 1; @@ -63293,7 +63841,7 @@ BEGIN JOIN itemType t ON t.id = i.typeFk JOIN warehouse w ON w.id = warehouseInFk WHERE landed = vDateDayEnd - AND e.supplierFk = 4 + AND e.supplierFk = vInventorySupplierFk AND w.valuatedInventory AND t.isInventory GROUP BY tr.warehouseInFk, b.itemFk; @@ -63301,19 +63849,24 @@ BEGIN END IF; INSERT INTO inv(warehouseFk, Id_Article, cantidad, Almacen) - SELECT tr.warehouseInFk, b.itemFk, b.quantity * IF(vHasNotInventory,-1,1), w.`name` - FROM buy b - JOIN item i ON i.id = b.itemFk - JOIN entry e ON e.id = b.entryFk - JOIN travel tr ON tr.id = e.travelFk - JOIN itemType t ON t.id = i.typeFk - JOIN warehouse w ON w.id = tr.warehouseInFk - WHERE tr.landed BETWEEN vInventoried AND vDateDayEnd - AND IF(tr.landed = util.VN_CURDATE(), tr.isReceived, trUE) - AND NOT e.isRaid - AND w.valuatedInventory - AND t.isInventory - ON DUPLICATE KEY UPDATE inv.cantidad = inv.cantidad + (b.quantity * IF(vHasNotInventory,-1,1)); + SELECT tr.warehouseInFk, + b.itemFk, + b.quantity * IF(vHasNotInventory,-1,1), + w.`name` + FROM buy b + JOIN item i ON i.id = b.itemFk + JOIN entry e ON e.id = b.entryFk + JOIN travel tr ON tr.id = e.travelFk + JOIN itemType t ON t.id = i.typeFk + JOIN warehouse w ON w.id = tr.warehouseInFk + WHERE tr.landed BETWEEN vInventoried AND vDateDayEnd + AND IF(tr.landed = util.VN_CURDATE(), tr.isReceived, trUE) + AND NOT e.isRaid + AND w.valuatedInventory + AND t.isInventory + AND e.supplierFk <> vInventorySupplierFk + ON DUPLICATE KEY UPDATE inv.cantidad = + inv.cantidad + (b.quantity * IF(vHasNotInventory,-1,1)); INSERT INTO inv(warehouseFk, Id_Article, cantidad, Almacen) SELECT tr.warehouseOutFk, b.itemFk, b.quantity * IF(vHasNotInventory,1,-1), w.`name` @@ -63432,6 +63985,44 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `item_zoneClosure` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `item_zoneClosure`() +BEGIN + +/* Devuelve una tabla temporal con la hora minima de un ticket sino tiene el de la zoneClosure y + * si tampoco hay el de la zona , para todos los artículos con salida hoy. + * + * @return tmp.itemZoneClosure(itemFk, timed) + */ + + CREATE OR REPLACE TEMPORARY TABLE tmp.itemZoneClosure + (INDEX (itemFk)) + ENGINE = MEMORY + SELECT s.itemFk, + MIN(DATE_FORMAT(IF(HOUR(t.shipped),t.shipped, + IFNULL(zc.hour, z.HOUR)), '%H:%i') + )timed + FROM ticket t + JOIN sale s ON s.ticketFk = t.id + LEFT JOIN `zone` z ON z.id = t.zoneFk + LEFT JOIN vn.zoneClosure zc ON zc.zoneFk = t.zoneFk + WHERE t.shipped BETWEEN util.VN_CURDATE() AND CONCAT(util.VN_CURDATE(), ' 23:59:59') + GROUP BY s.itemFk; +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 */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `ledger_doCompensation` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -63932,74 +64523,244 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `manaSpellersRequery`(vWorkerFk INTEGER) +`whole_proc`: BEGIN /** - * Recalcula el mana consumido por un trabajador + * Guarda en workerMana el mana consumido por un trabajador * * @param vWorkerFk Id Trabajador */ DECLARE vWorkerIsExcluded BOOLEAN; - DECLARE vFromDated DATE; - DECLARE vToDated DATE DEFAULT TIMESTAMPADD(DAY,1,util.VN_CURDATE()); - DECLARE vMana INT; - DECLARE vAutoMana INT; - DECLARE vClaimMana INT; - DECLARE vManaBank INT; - DECLARE vManaGreugeType INT; SELECT COUNT(*) INTO vWorkerIsExcluded FROM workerManaExcluded WHERE workerFk = vWorkerFk; - IF NOT vWorkerIsExcluded THEN - SELECT id INTO vMana - FROM `component` WHERE code = 'mana'; - - SELECT id INTO vAutoMana - FROM `component` WHERE code = 'autoMana'; - - SELECT id INTO vClaimMana - FROM `component` WHERE code = 'manaClaim'; - - SELECT id INTO vManaBank - FROM `bank` WHERE code = 'mana'; - - SELECT id INTO vManaGreugeType - FROM `greugeType` WHERE code = 'mana'; - - SELECT max(dated) INTO vFromDated - FROM clientManaCache; - - REPLACE workerMana (workerFk, amount) - SELECT vWorkerFk, sum(mana) FROM - ( - SELECT s.quantity * sc.value as mana - FROM ticket t - JOIN address a ON a.id = t.addressFk - JOIN client c ON c.id = a.clientFk - JOIN sale s ON s.ticketFk = t.id - JOIN saleComponent sc ON sc.saleFk = s.id - WHERE c.salesPersonFk = vWorkerFk AND sc.componentFk IN (vMana, vAutoMana, vClaimMana) - AND t.shipped > vFromDated AND t.shipped < vToDated - UNION ALL - SELECT - r.amountPaid - FROM receipt r - JOIN client c ON c.id = r.clientFk - WHERE c.salesPersonFk = vWorkerFk AND bankFk = vManaBank - AND payed > vFromDated - UNION ALL - SELECT g.amount - FROM greuge g - JOIN client c ON c.id = g.clientFk - WHERE c.salesPersonFk = vWorkerFk AND g.greugeTypeFk = vManaGreugeType - AND g.shipped > vFromDated and g.shipped < util.VN_CURDATE() - UNION ALL - SELECT cc.mana - FROM clientManaCache cc - JOIN client c ON c.id = cc.clientFk - WHERE c.salesPersonFk = vWorkerFk AND cc.dated = vFromDated - ) sub; + IF vWorkerIsExcluded THEN + LEAVE whole_proc; END IF; + + CREATE OR REPLACE TEMPORARY TABLE tmp.client + SELECT id + FROM client + WHERE salesPersonFk = vWorkerFk; + + CALL client_getMana(); + + INSERT INTO workerMana (workerFk, amount) + SELECT vWorkerFk, sum(mana) + FROM tmp.clientMana + ON DUPLICATE KEY UPDATE amount = VALUES(amount); + + DROP TEMPORARY TABLE + tmp.client, + tmp.clientMana; +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 */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `multipleInventory` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `multipleInventory`( + vDate DATE, + vWarehouseFk TINYINT, + vMaxDays TINYINT +) +proc: BEGIN + DECLARE vDateTomorrow DATE DEFAULT vDate + INTERVAL 1 DAY; + DECLARE vDateFrom DATE DEFAULT vDate; + DECLARE vDateTo DATETIME; + DECLARE vDateToTomorrow DATETIME; + DECLARE vDefaultDayRange INT; + + IF vDate < util.VN_CURDATE() THEN + LEAVE proc; + END IF; + + IF vDate = util.VN_CURDATE() THEN + SELECT inventoried INTO vDateFrom + FROM config; + END IF; + + SELECT defaultDayRange INTO vDefaultDayRange + FROM comparativeConfig; + + SET vDateTo = vDate + INTERVAL IFNULL(vMaxDays, vDefaultDayRange) DAY; + SET vDateToTomorrow = vDateTo + INTERVAL 1 DAY; + + ALTER TABLE vn2008.article_inventory + ADD `avalaible` INT NOT NULL, + ADD `sd` INT NOT NULL, + ADD `rest` INT NOT NULL, + ADD `expected` INT NOT NULL, + ADD `inventory` INT NOT NULL, + ADD `visible` INT NOT NULL, + ADD `life` TINYINT NOT NULL DEFAULT '0'; + + -- Calculo del inventario + UPDATE vn2008.article_inventory ai + JOIN ( + SELECT itemFk Id_Article, SUM(quantity) Subtotal + FROM ( + SELECT s.itemFk, - s.quantity quantity + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + JOIN warehouse w ON w.id = t.warehouseFk + WHERE t.shipped BETWEEN vDateFrom AND util.dayEnd(vDate) + AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk + AND w.isComparative + UNION ALL + SELECT b.itemFk, b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseInFk + WHERE t.landed BETWEEN vDateFrom AND util.dayEnd(vDate) + AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk + AND w.isComparative + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + UNION ALL + SELECT b.itemFk, - b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseOutFk + WHERE t.shipped BETWEEN vDateFrom AND util.dayEnd(vDate) + AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk + AND w.isComparative + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + ) sub2 + GROUP BY itemFk + ) sub ON ai.article_id = sub.Id_Article + SET ai.inventory = sub.Subtotal, + ai.visible = sub.Subtotal, + ai.avalaible = sub.Subtotal, + ai.sd = sub.Subtotal; + + -- Cálculo del visible + UPDATE vn2008.article_inventory ai + JOIN ( + SELECT itemFk Id_Article, SUM(quantity) Subtotal + FROM ( + SELECT s.itemFk, s.quantity + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + JOIN warehouse w ON w.id = t.warehouseFk + WHERE t.shipped >= vDate + AND t.shipped < vDateTomorrow + AND (NOT isPicked AND NOT t.isLabeled AND t.refFk IS NULL) + AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk + AND w.isComparative + UNION ALL + SELECT b.itemFk, - b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseInFk + WHERE t.landed = vDate + AND NOT t.isReceived + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk + AND w.isComparative + UNION ALL + SELECT b.itemFk, b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseOutFk + WHERE t.shipped = vDate + AND NOT t.isReceived + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk + AND w.isComparative + ) sub2 + GROUP BY itemFk + ) sub ON ai.article_id = sub.Id_Article + SET ai.visible = ai.visible + sub.Subtotal; + + -- Calculo del disponible + CREATE OR REPLACE TEMPORARY TABLE tmp.itemCalc + (INDEX (itemFk, warehouseFk)) + ENGINE = MEMORY + SELECT sub.itemFk, + vWarehouseFk warehouseFk, + sub.dated, + SUM(sub.quantity) quantity + FROM ( + SELECT s.itemFk, + DATE(t.shipped) dated, + - s.quantity quantity + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + JOIN warehouse w ON w.id = t.warehouseFk + WHERE t.shipped BETWEEN vDateTomorrow AND vDateTo + AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk + AND w.isComparative + UNION ALL + SELECT b.itemFk, t.landed, b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseInFk + WHERE t.landed BETWEEN vDateTomorrow AND vDateTo + AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk + AND w.isComparative + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + UNION ALL + SELECT b.itemFk, t.shipped, - b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseOutFk + WHERE t.shipped BETWEEN vDateTomorrow AND vDateTo + AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk + AND w.isComparative + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + ) sub + GROUP BY sub.itemFk, sub.dated; + + CALL item_getAtp(vDate); + CALL vn2008.item_travel(vWarehouseFk, vDate); + UPDATE vn2008.article_inventory ai + JOIN ( + SELECT it.itemFk, + SUM(it.quantity) quantity, + im.quantity minQuantity + FROM tmp.itemCalc it + JOIN tmp.itemAtp im ON im.itemFk = it.itemFk + JOIN item i ON i.id = it.itemFk + LEFT JOIN origin o ON o.id = i.originFk + LEFT JOIN vn2008.item_travel t ON t.wh = o.warehouseFk + WHERE it.dated < IF(vMaxDays < 0 AND t.landing IS NOT NULL, + t.landing, + vDateToTomorrow) + GROUP BY it.itemFk + ) sub ON sub.itemFk = ai.article_id + SET ai.avalaible = IF(sub.minQuantity > 0, + ai.avalaible, + ai.avalaible + sub.minQuantity), + ai.sd = ai.inventory + sub.quantity; + + DROP TEMPORARY TABLE + vn2008.item_travel, + tmp.itemCalc, + tmp.itemAtp; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -64969,15 +65730,15 @@ proc: BEGIN DECLARE vEndingDate DATETIME; DECLARE vIsTodayRelative BOOLEAN; - SELECT TIMESTAMPADD(DAY, LEAST(vScopeDays, pc.maxProductionScopeDays), util.dayEnd(util.VN_CURDATE())) + SELECT util.dayEnd(util.VN_CURDATE()) + INTERVAL LEAST(vScopeDays, maxProductionScopeDays) DAY INTO vEndingDate - FROM productionConfig pc; + FROM productionConfig; SELECT isTodayRelative INTO vIsTodayRelative FROM worker - WHERE id = getUser(); + WHERE id = getUser(); -- Cambiar por account.myUser_getId(), falta dar permisos - CALL prepareTicketList( util.VN_CURDATE() - INTERVAL 1 DAY, vEndingDate); + CALL prepareTicketList(util.yesterday(), vEndingDate); CREATE OR REPLACE TEMPORARY TABLE tmp.ticket SELECT * FROM tmp.productionTicket; @@ -65046,7 +65807,7 @@ proc: BEGIN JOIN agency ag ON ag.id = am.agencyFk LEFT JOIN ticketState tls ON tls.ticket = tt.ticketFk LEFT JOIN ticketLastUpdated tlu ON tlu.ticketFk = tt.ticketFk - LEFT JOIN worker w on w.id = tls.worker + LEFT JOIN worker w ON w.id = tls.worker LEFT JOIN routesMonitor rm ON rm.routeFk = t.routeFk LEFT JOIN `zone` z ON z.id = t.zoneFk LEFT JOIN zoneClosure zc ON zc.zoneFk = t.zoneFk @@ -65106,31 +65867,33 @@ proc: BEGIN FROM tmp.productionTicket tt JOIN saleVolume sv ON sv.ticketFk = tt.ticketFk GROUP BY tt.ticketFk - ) m on m.ticketFk = pb.ticketFk + ) m ON m.ticketFk = pb.ticketFk SET pb.`lines` = m.`lines`, pb.m3 = m.m3, pb.preparationRate = m.rate; DELETE FROM tmp.productionBuffer - WHERE `lines`= 0; + WHERE NOT `lines`; -- Lineas por linea de encajado UPDATE tmp.productionBuffer pb - JOIN ( SELECT ticketFk, + JOIN ( + SELECT ticketFk, SUM(sub.H) H, SUM(sub.V) V, SUM(sub.N) N FROM ( - SELECT t.ticketFk, + SELECT t.ticketFk, SUM(i.itemPackingTypeFk = 'H') H, SUM(i.itemPackingTypeFk = 'V') V, SUM(i.itemPackingTypeFk IS NULL) N FROM tmp.productionTicket t JOIN sale s ON s.ticketFk = t.ticketFk JOIN item i ON i.id = s.itemFk - GROUP BY t.ticketFk, i.itemPackingTypeFk) sub + GROUP BY t.ticketFk, i.itemPackingTypeFk + ) sub GROUP BY ticketFk - ) sub2 ON sub2.ticketFk = pb.ticketFk + ) sub2 ON sub2.ticketFk = pb.ticketFk SET pb.H = sub2.H, pb.V = sub2.V, pb.N = sub2.N; @@ -65154,15 +65917,30 @@ proc: BEGIN -- Insertamos todos los tickets que tienen productos parkineados -- en sectores de previa, segun el sector + CREATE OR REPLACE TEMPORARY TABLE tItemShelvingStock + (PRIMARY KEY(itemFk, sectorFk)) + ENGINE = MEMORY + SELECT ish.itemFk, + p.sectorFk, + sc.isPreviousPrepared, + sc.itemPackingTypeFk + FROM itemShelving ish + JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN parking p ON p.id = sh.parkingFk + JOIN sector sc ON sc.id = p.sectorFk + WHERE p.sectorFk + AND ish.visible + GROUP BY ish.itemFk, p.sectorFk; + INSERT INTO tmp.ticketWithPrevia(ticketFk, salesCount) SELECT pb.ticketFk, COUNT(DISTINCT s.id) FROM tmp.productionBuffer pb JOIN sale s ON s.ticketFk = pb.ticketFk - JOIN itemShelvingStock iss ON iss.itemFk = s.itemFk + JOIN tItemShelvingStock iss ON iss.itemFk = s.itemFk JOIN sector sc ON sc.id = iss.sectorFk JOIN item i ON i.id = iss.itemFk WHERE iss.isPreviousPrepared - AND (sc.itemPackingTypeFk IS NULL + AND (sc.itemPackingTypeFk IS NULL OR (i.itemPackingTypeFk IS NULL AND NOT pb.V) OR sc.itemPackingTypeFk = i.itemPackingTypeFk) AND s.quantity > 0 @@ -65170,14 +65948,16 @@ proc: BEGIN -- Se calcula la cantidad de productos que estan ya preparados porque su saleGroup está aparcado UPDATE tmp.ticketWithPrevia twp - JOIN ( SELECT pb.ticketFk, COUNT(DISTINCT s.id) salesInParkingCount - FROM tmp.productionBuffer pb - JOIN sale s ON s.ticketFk = pb.ticketFk - JOIN saleGroupDetail sgd ON sgd.saleFk = s.id - JOIN saleGroup sg ON sg.id = sgd.saleGroupFk - WHERE sg.parkingFk IS NOT NULL - AND s.quantity > 0 - GROUP BY pb.ticketFk) sub ON twp.ticketFk = sub.ticketFk + JOIN ( + SELECT pb.ticketFk, COUNT(DISTINCT s.id) salesInParkingCount + FROM tmp.productionBuffer pb + JOIN sale s ON s.ticketFk = pb.ticketFk + JOIN saleGroupDetail sgd ON sgd.saleFk = s.id + JOIN saleGroup sg ON sg.id = sgd.saleGroupFk + WHERE sg.parkingFk IS NOT NULL + AND s.quantity > 0 + GROUP BY pb.ticketFk + ) sub ON twp.ticketFk = sub.ticketFk SET twp.salesInParkingCount = sub.salesInParkingCount; -- Marcamos como pendientes aquellos que no coinciden las cantidades @@ -65186,11 +65966,244 @@ proc: BEGIN SET pb.previousWithoutParking = TRUE WHERE twp.salesCount > twp.salesInParkingCount; - DROP TEMPORARY TABLE tmp.productionTicket; - DROP TEMPORARY TABLE tmp.ticket; - DROP TEMPORARY TABLE tmp.risk; - DROP TEMPORARY TABLE tmp.ticket_problems; - DROP TEMPORARY TABLE tmp.ticketWithPrevia; + DROP TEMPORARY TABLE + tmp.productionTicket, + tmp.ticket, + tmp.risk, + tmp.ticket_problems, + tmp.ticketWithPrevia, + tItemShelvingStock; +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 */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `productionError_add` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `productionError_add`() +BEGIN + DECLARE vDatedFrom DATETIME; + DECLARE vDatedTo DATETIME; +/** + * Rellena la tabla vn.productionError con estadisticas de encajadores, revisores y sacadores. Se ejecuta en el nightTask + */ + SELECT util.VN_CURDATE() - INTERVAL 1 DAY, util.dayend(util.VN_CURDATE() - INTERVAL 1 DAY) INTO vDatedFrom, vDatedTo; + CALL timeControl_calculateAll(vDatedFrom, vDatedTo); + + -- Rellena la tabla tmp.errorsByClaim con encajadores, revisores y sacadores + CREATE OR REPLACE TEMPORARY TABLE tmp.errorsByClaim + ENGINE = MEMORY + SELECT COUNT(c.ticketFk) errors, + cd.workerFk + FROM claimDevelopment cd + JOIN claim c ON cd.claimFk = c.id + JOIN ticket t ON c.ticketFk = t.id + JOIN claimResponsible cr ON cd.claimResponsibleFk = cr.id + WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo + AND cr.code IN ('pic', 'chk', 'pck') + GROUP BY cd.workerFk; + + -- Genera la tabla tmp.volume con encajadores, sacadores y revisores + CREATE OR REPLACE TEMPORARY TABLE tmp.volume + ENGINE = MEMORY + SELECT SUM(w.volume) volume, + w.workerFk + FROM bs.workerProductivity w + WHERE w.dated BETWEEN vDatedFrom AND vDatedTo + GROUP BY w.workerFk; + + -- Rellena la tabla tmp.errorsByChecker con fallos de revisores + CREATE OR REPLACE TEMPORARY TABLE tmp.errorsByChecker + ENGINE = MEMORY + SELECT st.workerFk, + COUNT(t.id) errors + FROM saleMistake sm + JOIN saleTracking st ON sm.saleFk = st.saleFk + JOIN `state` s2 ON s2.id = st.stateFk + JOIN sale s ON s.id = sm.saleFk + JOIN ticket t on t.id = s.ticketFk + WHERE (t.shipped BETWEEN vDatedFrom AND vDatedTo) + AND s2.code IN ('OK','PREVIOUS_PREPARATION','PREPARED','CHECKED') + GROUP BY st.workerFk; + + -- Rellena la tabla tmp.expeditionErrors con fallos de expediciones + CREATE OR REPLACE TEMPORARY TABLE tmp.expeditionErrors + ENGINE = MEMORY + SELECT COUNT(t.id) errors, + e.workerFk + FROM vn.expeditionMistake pm + JOIN vn.expedition e ON e.id = pm.expeditionFk + JOIN vn.ticket t ON t.id = e.ticketFk + WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo + GROUP BY e.workerFk; + + -- Genera la tabla tmp.total para sacadores y revisores + CREATE OR REPLACE TEMPORARY TABLE tmp.total + ENGINE = MEMORY + SELECT st.workerFk, + COUNT(DISTINCT t.id) ticketCount, + COUNT(s.id) lineCount + FROM saleTracking st + JOIN `state` s2 ON s2.id = st.stateFk + JOIN sale s ON s.id = st.saleFk + JOIN ticket t ON s.ticketFk = t.id + WHERE (t.shipped BETWEEN vDatedFrom AND vDatedTo) + AND s2.code IN ('OK','PREVIOUS_PREPARATION','PREPARED','CHECKED') + GROUP BY st.workerFk; + + -- Rellena la tabla vn.productionError con sacadores + INSERT INTO productionError(userFk, + firstname, + lastname, + rol, + ticketNumber, + lineNumber, + error, + volume, + hourStart, + hourEnd, + hourWorked, + dated) + SELECT w.id, + w.firstName, + w.lastName, + "Sacadores", + t.ticketCount totalTickets, + t.lineCount, + IFNULL(ec.errors,0) + IFNULL(ec2.errors,0) errors, + v.volume volume, + SUBSTRING(tc.tableTimed, 1, 5) hourStart, + SUBSTRING(tc.tableTimed, LENGTH(tc.tableTimed)-4, 5) hourEnd, + IFNULL(CAST(tc.timeWorkDecimal AS DECIMAL (10,2)) , 0) hourWorked, + vDatedFrom dated + FROM tmp.total t + LEFT JOIN worker w ON w.id = t.workerFk + LEFT JOIN tmp.timeControlCalculate tc ON tc.userFk = t.workerFk + LEFT JOIN tmp.errorsByClaim ec ON ec.workerFk = t.workerFk + LEFT JOIN tmp.volume v ON v.workerFk = t.workerFk + LEFT JOIN tmp.errorsByChecker ec2 ON ec2.workerFk = t.workerFk + JOIN (SELECT DISTINCT w.id -- Verificamos que son sacadores + FROM vn.collection c + JOIN vn.state s ON s.id = c.stateFk + JOIN vn.train tn ON tn.id = c.trainFk + JOIN vn.worker w ON w.id = c.workerFk + WHERE c.created BETWEEN vDatedFrom AND vDatedTo) sub ON sub.id = w.id + GROUP BY w.id; + + CREATE OR REPLACE TEMPORARY TABLE itemPickerErrors -- Errores de los sacadores, derivadores de los revisadores + ENGINE = MEMORY + SELECT COUNT(c.ticketFk) errors, + tt.workerFk + FROM claimDevelopment cd + JOIN claim c ON cd.claimFk = c.id + JOIN ticket t ON c.ticketFk = t.id + JOIN claimResponsible cr ON cd.claimResponsibleFk = cr.id + JOIN ticketTracking tt ON tt.ticketFk = t.id + JOIN `state` s ON s.id = tt.stateFk + WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo + AND cr.code = 'chk' + AND s.code = 'ON_PREPARATION' + GROUP BY workerFk; + + UPDATE productionError ep + JOIN itemPickerErrors ipe ON ipe.workerFk = ep.userFk + SET ep.error = ep.error + ipe.errors + WHERE vDatedFrom = ep.dated AND ep.rol = 'Sacadores'; + + DROP TEMPORARY TABLE itemPickerErrors; + + -- Rellena la tabla vn.productionError con revisores + CALL productionError_addCheckerPackager(vDatedFrom, vDatedTo, "Revisadores"); + + -- Genera la tabla tmp.total para encajadores + CREATE OR REPLACE TEMPORARY TABLE tmp.total + ENGINE = MEMORY + SELECT e.workerFk, + COUNT(DISTINCT t.id) ticketCount, + COUNT(s.id) lineCount + FROM expedition e + JOIN ticket t ON e.ticketFk = t.id + JOIN sale s ON s.ticketFk = t.id + WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo + GROUP BY e.workerFk; + + -- Rellena la tabla vn.productionError con encajadores + CALL productionError_addCheckerPackager(vDatedFrom, vDatedTo, "Encajadores"); + + DROP TEMPORARY TABLE tmp.errorsByClaim, + tmp.volume, + tmp.errorsByChecker, + tmp.expeditionErrors, + tmp.total; +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 */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `productionError_addCheckerPackager` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `productionError_addCheckerPackager`( + vDatedFrom DATETIME, + vDatedTo DATETIME, + vRol VARCHAR(50)) +BEGIN +/** + * Rellena la tabla vn.productionError con rol + * + * @param vDatedFrom Fecha desde + * @param vDatedTo Fecha hasta + * @param vRol rol a insertar + */ + INSERT INTO productionError(userFk, + firstname, + lastname, + rol, + ticketNumber, + lineNumber, + error, + volume, + hourStart, + hourEnd, + hourWorked, + dated) + SELECT w.id, + w.firstName, + w.lastName, + vRol, + t.ticketCount totalTickets, + t.lineCount, + IFNULL(ec.errors,0) + IFNULL(ec2.errors,0) + IFNULL(pe.errors,0) errors, + NULL volume, + SUBSTRING(tc.tableTimed, 1, 5) hourStart, + SUBSTRING(tc.tableTimed, LENGTH(tc.tableTimed)-4, 5) hourEnd, + IFNULL(CAST(tc.timeWorkDecimal AS DECIMAL (10,2)) , 0) hourWorked, + vDatedFrom dated + FROM tmp.total t + LEFT JOIN worker w ON w.id = t.workerFk + LEFT JOIN tmp.timeControlCalculate tc ON tc.userFk = t.workerFk + LEFT JOIN tmp.errorsByClaim ec ON ec.workerFk = t.workerFk + LEFT JOIN tmp.volume v ON v.workerFk = t.workerFk + LEFT JOIN tmp.errorsByChecker ec2 ON ec2.workerFk = t.workerFk + LEFT JOIN tmp.expeditionErrors pe ON pe.workerFk = t.workerFk + GROUP BY w.id; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -66163,6 +67176,40 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `route_checkDeliveryMethod` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `route_checkDeliveryMethod`(vSelf INT) +BEGIN +/** +* Comprueba si el deliveryMethod del agencyMode de la ruta es reparto +* +* @param vSelf Id de ruta +*/ + DECLARE vDeliveryMethod VARCHAR(45); + + SELECT dm.code INTO vDeliveryMethod + FROM route r + JOIN agencyMode am ON am.id = r.agencyModeFk + JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk + WHERE r.id = vSelf; + + IF vDeliveryMethod <> 'DELIVERY' THEN + CALL util.throw('Route tickets via delivery only'); + END IF; +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 */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `route_doRecalc` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -66241,63 +67288,66 @@ BEGIN * @param vRouteFk * @select Información de los tickets */ -SELECT * - FROM ( - SELECT t.id Id, - t.clientFk Client, - a.id Address, - a.nickname ClientName, - t.packages Packages, - a.street AddressName, - a.postalCode PostalCode, - a.city City, - sub2.itemPackingTypeFk PackingType, - c.phone ClientPhone, - c.mobile ClientMobile, - a.phone AddressPhone, - a.mobile AddressMobile, - d.longitude Longitude, - d.latitude Latitude, - wm.mediaValue SalePersonPhone, - tob.description Note, - t.isSigned Signed, - t.priority, - t.cmrFk - FROM ticket t - JOIN client c ON t.clientFk = c.id - JOIN address a ON t.addressFk = a.id - LEFT JOIN delivery d ON d.ticketFk = t.id - LEFT JOIN workerMedia wm ON wm.workerFk = c.salesPersonFk - LEFT JOIN( - SELECT tob.description, t.id - FROM ticketObservation tob - JOIN ticket t ON tob.ticketFk = t.id - JOIN observationType ot ON ot.id = tob.observationTypeFk - WHERE t.routeFk = vRouteFk - AND ot.code = 'delivery' - )tob ON tob.id = t.id - LEFT JOIN( - SELECT sub.ticketFk, - CONCAT('(', - GROUP_CONCAT(DISTINCT sub.itemPackingTypeFk - ORDER BY sub.items DESC SEPARATOR ','), - ') ') itemPackingTypeFk - FROM ( - SELECT s.ticketFk, i.itemPackingTypeFk, COUNT(*) items - FROM ticket t - JOIN sale s ON s.ticketFk = t.id - JOIN item i ON i.id = s.itemFk - WHERE t.routeFk = vRouteFk - GROUP BY t.id, i.itemPackingTypeFk - )sub - GROUP BY sub.ticketFk - )sub2 ON sub2.ticketFk = t.id - WHERE t.routeFk = vRouteFk - ORDER BY d.id DESC - LIMIT 10000000000000000000 - )sub3 - GROUP BY sub3.id - ORDER BY sub3.priority; +SELECT t.id Id, + t.clientFk Client, + a.id Address, + a.nickname ClientName, + t.packages Packages, + a.street AddressName, + a.postalCode PostalCode, + a.city City, + sub3.itemPackingTypeFk PackingType, + c.phone ClientPhone, + c.mobile ClientMobile, + a.phone AddressPhone, + a.mobile AddressMobile, + d.longitude Longitude, + d.latitude Latitude, + wm.mediaValue SalePersonPhone, + tob.description Note, + t.isSigned Signed, + t.priority, + t.cmrFk + FROM ticket t + JOIN client c ON t.clientFk = c.id + JOIN address a ON t.addressFk = a.id + LEFT JOIN workerMedia wm ON wm.workerFk = c.salesPersonFk + LEFT JOIN ( + SELECT t.addressFk, MAX(d.ticketFk) lastTicketFk + FROM ticket t + JOIN delivery d ON t.id = d.ticketFk + JOIN ticket ti ON ti.routeFk = vRouteFk + AND ti.id = t.id + AND ti.clientFk = t.clientFk + GROUP BY addressFk + )sub ON sub.addressFk = a.id + LEFT JOIN delivery d ON d.ticketFk = sub.lastTicketFk + LEFT JOIN( + SELECT t.id ticketFk, tob.description + FROM ticketObservation tob + JOIN ticket t ON tob.ticketFk = t.id + JOIN observationType ot ON ot.id = tob.observationTypeFk + WHERE t.routeFk = vRouteFk + AND ot.code = 'delivery' + )tob ON tob.ticketFk = t.id + LEFT JOIN( + SELECT sub2.ticketFk, + CONCAT('(', + GROUP_CONCAT(DISTINCT sub2.itemPackingTypeFk + ORDER BY sub2.items DESC SEPARATOR ','), + ') ') itemPackingTypeFk + FROM ( + SELECT s.ticketFk, i.itemPackingTypeFk, COUNT(*) items + FROM ticket t + JOIN sale s ON s.ticketFk = t.id + JOIN item i ON i.id = s.itemFk + WHERE t.routeFk = vRouteFk + GROUP BY t.id, i.itemPackingTypeFk + )sub2 + GROUP BY sub2.ticketFk + )sub3 ON sub3.ticketFk = t.id + WHERE t.routeFk = vRouteFk + ORDER BY priority, Id; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -66510,6 +67560,62 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `saleSplit` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `saleSplit`(vSaleFk INT, vQuantity INT) +BEGIN + + + DECLARE vNewSaleFk INT; + + INSERT INTO vn.sale(itemFk, + concept, + price, + discount, + quantity, + ticketFk, + isPriceFixed) + SELECT s.itemFk, + i.longName, + s.price, + s.discount, + vQuantity, + s.ticketFk, + s.isPriceFixed + FROM vn.sale s + JOIN vn.item i ON i.id = s.itemFk + WHERE s.id = vSaleFk; + + UPDATE vn.sale s + JOIN vn.item i ON i.id = s.itemFk + SET s.quantity = s.quantity - vQuantity, s.concept = i.longName + WHERE s.id = vSaleFk; + + SELECT LAST_INSERT_ID() INTO vNewSaleFk; + + INSERT INTO vn.saleComponent( saleFk, + componentFk, + value) + SELECT vNewSaleFk, + componentFk, + value + FROM vn.saleComponent + WHERE saleFk = vSaleFk; + +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 */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `sales_merge` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -67100,19 +68206,19 @@ BEGIN DECLARE vComponentCount INT; DECLARE vCursor CURSOR FOR - SELECT DISTINCT tt.warehouseFk, IF(vIsTodayRelative, util.VN_CURDATE(), date(tt.shipped)) + SELECT DISTINCT tt.warehouseFk, IF(vIsTodayRelative, util.VN_CURDATE(), DATE(tt.shipped)) FROM tmp.sale_getProblems tt WHERE DATE(tt.shipped) BETWEEN util.VN_CURDATE() - AND TIMESTAMPADD(DAY, IF(vIsTodayRelative, 9.9, 1.9), util.VN_CURDATE()); + AND util.VN_CURDATE() + INTERVAL IF(vIsTodayRelative, 9.9, 1.9) DAY; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; DELETE tt.* FROM tmp.sale_getProblems tt - JOIN vn.ticketObservation tto ON tto.ticketFk = tt.ticketFk - JOIN vn.observationType ot ON ot.id = tto.observationTypeFk - WHERE ot.code = 'administrative' - AND tto.description = 'Miriam'; + JOIN ticketObservation tto ON tto.ticketFk = tt.ticketFk + JOIN observationType ot ON ot.id = tto.observationTypeFk + WHERE ot.code = 'administrative' + AND tto.description = 'Miriam'; CREATE OR REPLACE TEMPORARY TABLE tmp.sale_problems ( ticketFk INT(11), @@ -67134,38 +68240,41 @@ BEGIN CREATE OR REPLACE TEMPORARY TABLE tmp.ticket_list (PRIMARY KEY (ticketFk)) ENGINE = MEMORY - SELECT tp.ticketFk, tp.clientFk - FROM tmp.sale_getProblems tp; + SELECT ticketFk, clientFk + FROM tmp.sale_getProblems; SELECT COUNT(*) INTO vComponentCount - FROM vn.component c - WHERE c.isRequired; + FROM component + WHERE isRequired; -- Too Little INSERT INTO tmp.sale_problems(ticketFk, isTooLittle) SELECT tp.ticketFk, TRUE FROM tmp.sale_getProblems tp - JOIN vn.ticket t ON t.id = tp.ticketFk - JOIN (SELECT t.addressFk, SUM(sv.litros) litros, t.totalWithoutVat + JOIN ticket t ON t.id = tp.ticketFk + JOIN ( + SELECT t.addressFk, SUM(sv.litros) litros, t.totalWithoutVat FROM tmp.ticket_list tl - JOIN vn.saleVolume sv ON sv.ticketFk = tl.ticketFk - JOIN vn.ticket t ON t.id = tl.ticketFk - JOIN vn.zoneClosure zc ON zc.zoneFk = t.zoneFk AND zc.dated = util.VN_CURDATE() - JOIN vn.agencyMode am ON am.id = t.agencyModeFk - JOIN vn.deliveryMethod dm ON dm.id = am.deliveryMethodFk - WHERE util.VN_NOW() < TIMESTAMPADD(MINUTE,MINUTE(zc.`hour`) ,TIMESTAMPADD(HOUR,HOUR(zc.`hour`),util.VN_CURDATE())) - AND dm.code IN('AGENCY','DELIVERY','PICKUP') + JOIN saleVolume sv ON sv.ticketFk = tl.ticketFk + JOIN ticket t ON t.id = tl.ticketFk + JOIN zoneClosure zc ON zc.zoneFk = t.zoneFk + AND zc.dated = util.VN_CURDATE() + JOIN agencyMode am ON am.id = t.agencyModeFk + JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk + WHERE util.VN_NOW() < (util.VN_CURDATE() + INTERVAL HOUR(zc.`hour`) HOUR) + INTERVAL MINUTE(zc.`hour`) MINUTE + AND dm.code IN ('AGENCY','DELIVERY','PICKUP') AND t.shipped BETWEEN util.VN_CURDATE() AND util.midnight() - GROUP BY t.addressFk) sub ON sub.addressFk = t.addressFk - JOIN vn.volumeConfig vc + GROUP BY t.addressFk + ) sub ON sub.addressFk = t.addressFk + JOIN volumeConfig vc WHERE sub.litros < vc.minTicketVolume - AND sub.totalWithoutVat < vc.minTicketValue; + AND sub.totalWithoutVat < vc.minTicketValue; -- Faltan componentes INSERT INTO tmp.sale_problems(ticketFk, hasComponentLack, saleFk) - SELECT sub.ticketFk, sub.hasComponentLack, sub.saleFk - FROM( - SELECT tl.ticketFk, (COUNT(DISTINCT s.id) * vComponentCount > COUNT(c.id)) hasComponentLack, s.id saleFk + SELECT ticketFk, (vComponentCount > nComp) hasComponentLack, saleFk + FROM ( + SELECT COUNT(s.id) nComp, tl.ticketFk, s.id saleFk FROM tmp.ticket_list tl JOIN vn.sale s ON s.ticketFk = tl.ticketFk LEFT JOIN vn.saleComponent sc ON sc.saleFk = s.id @@ -67173,17 +68282,17 @@ BEGIN JOIN vn.ticket t ON t.id = tl.ticketFk JOIN vn.agencyMode am ON am.id = t.agencyModeFk JOIN vn.deliveryMethod dm ON dm.id = am.deliveryMethodFk - WHERE dm.code IN('AGENCY','DELIVERY','PICKUP') + WHERE dm.code IN ('AGENCY','DELIVERY','PICKUP') AND s.quantity > 0 GROUP BY s.id - LIMIT 10000000000000000) sub - WHERE sub.hasComponentLack; + ) sub + HAVING hasComponentLack; -- Cliente congelado INSERT INTO tmp.sale_problems(ticketFk, isFreezed) SELECT DISTINCT tl.ticketFk, TRUE FROM tmp.ticket_list tl - JOIN vn.client c ON c.id = tl.clientFk + JOIN client c ON c.id = tl.clientFk WHERE c.isFreezed ON DUPLICATE KEY UPDATE isFreezed = c.isFreezed; @@ -67191,21 +68300,21 @@ BEGIN CREATE OR REPLACE TEMPORARY TABLE tmp.clientGetDebt (PRIMARY KEY (clientFk)) ENGINE = MEMORY - SELECT DISTINCT clientFk - FROM tmp.ticket_list; + SELECT DISTINCT clientFk + FROM tmp.ticket_list; CALL client_getDebt(util.VN_CURDATE()); INSERT INTO tmp.sale_problems(ticketFk, risk, hasHighRisk) SELECT DISTINCT tl.ticketFk, r.risk, ((r.risk - cc.riskTolerance) > c.credit + 10) FROM tmp.ticket_list tl - JOIN vn.ticket t ON t.id = tl.ticketFk - JOIN vn.agencyMode a ON t.agencyModeFk = a.id + JOIN ticket t ON t.id = tl.ticketFk + JOIN agencyMode a ON t.agencyModeFk = a.id JOIN tmp.risk r ON r.clientFk = t.clientFk - JOIN vn.client c ON c.id = t.clientFk - JOIN vn.clientConfig cc + JOIN client c ON c.id = t.clientFk + JOIN clientConfig cc WHERE r.risk > c.credit + 10 - AND a.isRiskFree = FALSE + AND NOT a.isRiskFree ON DUPLICATE KEY UPDATE risk = r.risk, hasHighRisk = ((r.risk - cc.riskTolerance) > c.credit + 10); @@ -67213,13 +68322,12 @@ BEGIN INSERT INTO tmp.sale_problems(ticketFk, hasTicketRequest) SELECT DISTINCT tl.ticketFk, TRUE FROM tmp.ticket_list tl - JOIN vn.ticketRequest tr ON tr.ticketFk = tl.ticketFk + JOIN ticketRequest tr ON tr.ticketFk = tl.ticketFk WHERE tr.isOK IS NULL ON DUPLICATE KEY UPDATE hasTicketRequest = TRUE; -- Disponible, Faltas, Inventario y Retrasos OPEN vCursor; - l: LOOP SET vDone = FALSE; FETCH vCursor INTO vWarehouseFk, vDate; @@ -67241,21 +68349,21 @@ BEGIN LEFT(CONCAT('F: ',GROUP_CONCAT(i.id, ' ', i.longName, ' ')),250) problem, s.id AS saleFk FROM tmp.ticket_list tl - JOIN vn.ticket t ON t.id = tl.ticketFk - JOIN vn.sale s ON s.ticketFk = t.id - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.itemType it on it.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk + JOIN ticket t ON t.id = tl.ticketFk + JOIN sale s ON s.ticketFk = t.id + JOIN item i ON i.id = s.itemFk + JOIN itemType it on it.id = i.typeFk + JOIN itemCategory ic ON ic.id = it.categoryFk LEFT JOIN cache.visible v ON v.item_id = i.id AND v.calc_id = vVisibleCache LEFT JOIN cache.available av ON av.item_id = i.id AND av.calc_id = vAvailableCache - LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk + LEFT JOIN itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk WHERE IFNULL(v.visible,0) < s.quantity AND IFNULL(av.available ,0) < s.quantity AND IFNULL(issw.visible, 0) < s.quantity - AND s.isPicked = FALSE - AND s.reserved = FALSE - AND ic.merchandise = TRUE - AND IF(vIsTodayRelative, TRUE, date(t.shipped) = vDate) + AND NOT s.isPicked + AND NOT s.reserved + AND ic.merchandise + AND IF(vIsTodayRelative, TRUE, DATE(t.shipped) = vDate) AND NOT i.generic AND util.VN_CURDATE() = vDate AND t.warehouseFk = vWarehouseFk @@ -67268,24 +68376,25 @@ BEGIN FROM ( SELECT tl.ticketFk, LEFT(GROUP_CONCAT('I: ',i.id, ' ', i.longName, ' '),250) problem, s.id AS saleFk FROM tmp.ticket_list tl - JOIN vn.ticket t ON t.id = tl.ticketFk - JOIN vn.sale s ON s.ticketFk = t.id - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.itemType it on it.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk + JOIN ticket t ON t.id = tl.ticketFk + JOIN sale s ON s.ticketFk = t.id + JOIN item i ON i.id = s.itemFk + JOIN itemType it on it.id = i.typeFk + JOIN itemCategory ic ON ic.id = it.categoryFk LEFT JOIN cache.visible v ON v.item_id = s.itemFk AND v.calc_id = vVisibleCache - LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk + LEFT JOIN itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk WHERE IFNULL(v.visible,0) >= s.quantity AND IFNULL(issw.visible, 0) < s.quantity AND s.quantity > 0 - AND s.isPicked = FALSE - AND s.reserved = FALSE - AND ic.merchandise = TRUE - AND IF(vIsTodayRelative, TRUE, date(t.shipped) = vDate) + AND NOT s.isPicked + AND NOT s.reserved + AND ic.merchandise + AND IF(vIsTodayRelative, TRUE, DATE(t.shipped) = vDate) AND NOT i.generic AND util.VN_CURDATE() = vDate AND t.warehouseFk = vWarehouseFk - GROUP BY tl.ticketFk) sub + GROUP BY tl.ticketFk + ) sub ON DUPLICATE KEY UPDATE itemDelay = sub.problem, saleFk = sub.saleFk; -- Retraso: Disponible suficiente, pero no visible ni ubicado @@ -67294,26 +68403,27 @@ BEGIN FROM ( SELECT tl.ticketFk, LEFT(GROUP_CONCAT('R: ',i.id, ' ', i.longName, ' '),250) problem, s.id AS saleFk FROM tmp.ticket_list tl - JOIN vn.ticket t ON t.id = tl.ticketFk - JOIN vn.sale s ON s.ticketFk = t.id - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.itemType it on it.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk + JOIN ticket t ON t.id = tl.ticketFk + JOIN sale s ON s.ticketFk = t.id + JOIN item i ON i.id = s.itemFk + JOIN itemType it on it.id = i.typeFk + JOIN itemCategory ic ON ic.id = it.categoryFk LEFT JOIN cache.visible v ON v.item_id = s.itemFk AND v.calc_id = vVisibleCache LEFT JOIN cache.available av ON av.item_id = i.id AND av.calc_id = vAvailableCache - LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk - WHERE IFNULL(v.visible,0) < s.quantity - AND IFNULL(av.available ,0) >= s.quantity + LEFT JOIN itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk + WHERE IFNULL(v.visible, 0) < s.quantity + AND IFNULL(av.available, 0) >= s.quantity AND IFNULL(issw.visible, 0) < s.quantity AND s.quantity > 0 - AND s.isPicked = FALSE - AND s.reserved = FALSE - AND ic.merchandise = TRUE - AND IF(vIsTodayRelative, TRUE, date(t.shipped) = vDate) + AND NOT s.isPicked + AND NOT s.reserved + AND ic.merchandise + AND IF(vIsTodayRelative, TRUE, DATE(t.shipped) = vDate) AND NOT i.generic AND util.VN_CURDATE() = vDate AND t.warehouseFk = vWarehouseFk - GROUP BY tl.ticketFk) sub + GROUP BY tl.ticketFk + ) sub ON DUPLICATE KEY UPDATE itemDelay = sub.problem, saleFk = sub.saleFk; -- Redondeo: Cantidad pedida incorrecta en al grouping de la última compra @@ -67321,11 +68431,10 @@ BEGIN INSERT INTO tmp.sale_problems(ticketFk, hasRounding, saleFk) SELECT ticketFk, problem, saleFk FROM ( - SELECT - tl.ticketFk, - s.id saleFk , - LEFT(GROUP_CONCAT('RE: ',i.id, ' ', IFNULL(i.longName,''), ' '), 250) problem, - MOD(s.quantity, b.`grouping`) hasRounding + SELECT tl.ticketFk, + s.id saleFk , + LEFT(GROUP_CONCAT('RE: ',i.id, ' ', IFNULL(i.longName,''), ' '), 250) problem, + MOD(s.quantity, b.`grouping`) hasRounding FROM tmp.ticket_list tl JOIN ticket t ON t.id = tl.ticketFk AND t.warehouseFk = vWarehouseFk @@ -67338,14 +68447,13 @@ BEGIN ) sub ON DUPLICATE KEY UPDATE hasRounding = sub.problem, saleFk = sub.saleFk; END LOOP; - CLOSE vCursor; INSERT INTO tmp.sale_problems(ticketFk, isTaxDataChecked) SELECT DISTINCT tl.ticketFk, FALSE FROM tmp.ticket_list tl - JOIN vn.client c ON c.id = tl.clientFk - WHERE c.isTaxDataChecked = FALSE + JOIN client c ON c.id = tl.clientFk + WHERE NOT c.isTaxDataChecked ON DUPLICATE KEY UPDATE isTaxDataChecked = FALSE; DROP TEMPORARY TABLE @@ -68066,30 +69174,36 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `shelving_clean`() BEGIN - DELETE FROM vn.shelving + DELETE FROM shelving WHERE length(code) > 3 AND parked < TIMESTAMPADD(WEEK,-1,util.VN_CURDATE()); - DELETE FROM vn.itemShelving + DELETE FROM itemShelving WHERE visible <= 0 AND created < TIMESTAMPADD(MONTH,-1,util.VN_CURDATE()); DELETE ish.* - FROM vn.itemShelving ish + FROM itemShelving ish JOIN vn.shelving sh ON sh.code = ish.shelvingFk WHERE sh.parkingFk IS NULL AND ish.created < TIMESTAMPADD(WEEK,-1,util.VN_CURDATE()); - UPDATE vn.shelving sh - LEFT JOIN vn.itemShelving its ON its.shelvingFk = sh.`code` +UPDATE shelving sh + LEFT JOIN itemShelving its ON its.shelvingFk = sh.`code` SET isPrinted = 0, - parkingFk = NULL - WHERE its.id IS NULL - AND sh.isRecyclable - AND ( sh.parked IS NULL - OR - sh.parked < TIMESTAMPADD(MONTH,-1,util.VN_CURDATE()) - ); + parkingFk = NULL + WHERE its.id IS NULL + AND sh.isRecyclable + AND ( + sh.parked IS NULL + OR + sh.parked < TIMESTAMPADD(MONTH,-1,util.VN_CURDATE()) + ) + AND IF(code REGEXP '^[A-Za-z]{2}[0-9]', LEFT (code, 2) NOT IN ( + SELECT DISTINCT LEFT(its.shelvingFk, 2) + FROM itemShelving its + WHERE its.shelvingFk REGEXP '^[A-Za-z]{2}[0-9]' + ), TRUE); END ;; DELIMITER ; @@ -68297,58 +69411,86 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `stockBuyedByWorker` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET character_set_client = utf8mb3 */ ; +/*!50003 SET character_set_results = utf8mb3 */ ; +/*!50003 SET collation_connection = utf8mb3_general_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `stockBuyedByWorker`( - vDate DATE, - vWorker INT) + vDated DATE, + vWorker INT +) BEGIN /** - * Calculates the space reserved by buyers of the same container + * Inserta el volumen de compra de un comprador + * en stockBuyed de acuerdo con la fecha. * - * @param vdate date of container delivery - * @param vWorker buyer reserving space in the container + * @param vDated Fecha de compra + * @param vWorker Id de trabajador */ - DECLARE vVolume DECIMAL(10, 2); - DECLARE vWarehouseFk INT; - DECLARE vCompressionRatio DECIMAL(1, 1); + CREATE OR REPLACE TEMPORARY TABLE tStockBuyed + (INDEX (userFk)) + ENGINE = MEMORY + SELECT requested, reserved, userFk + FROM stockBuyed + WHERE dated = vDated + AND userFk = vWorker; - CALL stockTraslation(vDate); + DELETE FROM stockBuyed + WHERE dated = vDated + AND userFk = vWorker; - SELECT warehouseFk, conversionCoefficient INTO vWarehouseFk, vCompressionRatio - FROM auctionConfig; + CALL stockTraslation(vDated); - SELECT volume INTO vVolume - FROM vn.packaging WHERE id = 'cc'; + INSERT INTO stockBuyed(userFk, buyed, `dated`, reserved, requested, description) + SELECT it.workerFk, + SUM((ti.quantity / b.packing) * buy_getVolume(b.id)) / vc.palletM3 / 1000000, + vDated, + sb.reserved, + sb.requested, + u.name + FROM itemType it + JOIN item i ON i.typeFk = it.id + LEFT JOIN tmp.item ti ON ti.itemFk = i.id + JOIN itemCategory ic ON ic.id = it.categoryFk + JOIN warehouse wh ON wh.code = 'VNH' + JOIN tmp.buyUltimate bu ON bu.itemFk = i.id + AND bu.warehouseFk = wh.id + JOIN buy b ON b.id = bu.buyFk + JOIN volumeConfig vc + JOIN account.`user` u ON u.id = it.workerFk + LEFT JOIN tStockBuyed sb ON sb.userFk = it.workerFk + WHERE ic.display + AND it.workerFk = vWorker; SELECT b.entryFk Id_Entrada, i.id Id_Article, i.name Article, - ti.amount Cantidad, - (vCompressionRatio * (ti.amount / b.packing) * vn.buy_getVolume(b.id)) - / vVolume buyed, - b.packageFk id_cubo, + ti.quantity Cantidad, + (ac.conversionCoefficient * (ti.quantity / b.packing) * buy_getVolume(b.id)) + / (vc.trolleyM3 * 1000000) buyed, + b.packagingFk id_cubo, b.packing FROM tmp.item ti - JOIN item i ON i.id = ti.item_id + JOIN item i ON i.id = ti.itemFk JOIN itemType it ON i.typeFk = it.id JOIN itemCategory ic ON ic.id = it.categoryFk JOIN worker w ON w.id = it.workerFk + JOIN auctionConfig ac JOIN tmp.buyUltimate bu ON bu.itemFk = i.id - AND bu.warehouseFk = vWarehouseFk + AND bu.warehouseFk = ac.warehouseFk JOIN buy b ON b.id = bu.buyFk - WHERE ic.display AND w.id = vWorker; + JOIN volumeConfig vc + WHERE ic.display + AND w.id = vWorker; - DROP TEMPORARY TABLE - tmp.buyUltimate, - tmp.item; + DROP TEMPORARY TABLE tmp.buyUltimate, + tmp.item, + tStockBuyed; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -68365,51 +69507,59 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `stockBuyed_add`(vDated DATE) +CREATE DEFINER=`root`@`localhost` PROCEDURE `stockBuyed_add`( + vDated DATE +) BEGIN /** - * Inserta el volumen de compra por comprador en stockBuyed de acuerdo con la fecha + * Inserta el volumen de compra por comprador + * en stockBuyed de acuerdo con la fecha. * * @param vDated Fecha de compra */ - - CREATE OR REPLACE TEMPORARY TABLE tStockBuyed + CREATE OR REPLACE TEMPORARY TABLE tStockBuyed (INDEX (userFk)) ENGINE = MEMORY SELECT requested, reserved, userFk FROM stockBuyed WHERE dated = vDated; + DELETE FROM stockBuyed WHERE dated = vDated; + CALL stockTraslation(vDated); INSERT INTO stockBuyed(userFk, buyed, `dated`, description) - SELECT it.workerFk, - SUM(( ti.amount / b.packing ) * buy_getVolume(b.id)) / vc.palletM3 / 1000000 buyed, + SELECT it.workerFk, + SUM((ti.quantity / b.packing) * buy_getVolume(b.id)) / vc.palletM3 / 1000000, vDated, u.name - FROM tmp.item ti - JOIN item i ON i.id = ti.item_id - JOIN itemType it ON it.id = i.typeFk + FROM itemType it + JOIN item i ON i.typeFk = it.id + LEFT JOIN tmp.item ti ON ti.itemFk = i.id JOIN itemCategory ic ON ic.id = it.categoryFk JOIN warehouse wh ON wh.code = 'VNH' JOIN tmp.buyUltimate bu ON bu.itemFk = i.id AND bu.warehouseFk = wh.id JOIN buy b ON b.id = bu.buyFk JOIN volumeConfig vc JOIN account.`user` u ON u.id = it.workerFk - WHERE ic.display <> 0 + JOIN workerDepartment wd ON wd.workerFk = u.id + JOIN department d ON d.id = wd.departmentFk + WHERE ic.display + AND d.code IN ('shopping', 'logistic', 'franceTeam') GROUP BY it.workerFk; INSERT INTO stockBuyed(buyed, dated, description) - SELECT SUM(ic.cm3 * ito.quantity / vc.palletM3 / 1000000), + SELECT SUM(ic.cm3 * ito.quantity / vc.palletM3 / 1000000), vDated, - IF(c.country = 'España',p.name,c.country) destiny + IF(c.code = 'ES', p.name, c.country) destiny FROM itemTicketOut ito JOIN ticket t ON t.id = ito.ticketFk JOIN `address` a ON a.id = t.addressFk JOIN province p ON p.id = a.provinceFk JOIN country c ON c.id = p.countryFk JOIN warehouse wh ON wh.id = t.warehouseFk - JOIN itemCost ic ON ic.itemFk = ito.itemFk AND ic.warehouseFk = t.warehouseFk + JOIN itemCost ic ON ic.itemFk = ito.itemFk + AND ic.warehouseFk = t.warehouseFk JOIN volumeConfig vc WHERE ito.shipped BETWEEN vDated AND util.dayend(vDated) AND wh.code = 'VNH' @@ -68421,8 +69571,7 @@ BEGIN s.reserved = ts.reserved WHERE s.dated = vDated; - DROP TEMPORARY TABLE - tmp.buyUltimate, + DROP TEMPORARY TABLE tmp.buyUltimate, tmp.item, tStockBuyed; END ;; @@ -68441,44 +69590,44 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `stockTraslation`(vDate DATE) +CREATE DEFINER=`root`@`localhost` PROCEDURE `stockTraslation`( + vDated DATE +) BEGIN /** - * Calcula el stock del almacén de subasta desde FechaInventario hasta vDate - * sin tener en cuenta las salidas del mismo dia vDate + * Calcula el stock del almacén de subasta desde FechaInventario hasta vDated + * sin tener en cuenta las salidas del mismo dia vDated * para ver el transporte a reservar - * @param vDate Fecha hasta la cual calcula el stock + * + * @param vDated Fecha hasta la cual calcula el stock + * @return tmp.item */ DECLARE vAuctionWarehouseFk INT; - DELETE FROM stockBuyed WHERE dated = vDate; - SELECT warehouseFk INTO vAuctionWarehouseFk FROM auctionConfig; - DROP TEMPORARY TABLE IF EXISTS tmp.item; - CREATE TEMPORARY TABLE tmp.item - (UNIQUE INDEX i USING HASH (item_id)) + CREATE OR REPLACE TEMPORARY TABLE tmp.item + (UNIQUE INDEX i USING HASH (itemFk)) ENGINE = MEMORY - SELECT item_id, SUM(amount) amount - FROM vn2008.item_entry_in - WHERE dat = vDate - AND vDate >= util.VN_CURDATE() - AND warehouse_id = vAuctionWarehouseFk - AND isVirtualStock is FALSE - GROUP BY item_id - HAVING amount != 0; + SELECT itemFk, SUM(quantity) quantity + FROM itemEntryIn + WHERE landed = vDated + AND vDated >= util.VN_CURDATE() + AND warehouseInFk = vAuctionWarehouseFk + AND NOT isVirtualStock + GROUP BY itemFk + HAVING quantity; - CALL `cache`.stock_refresh (FALSE); + CALL `cache`.stock_refresh(FALSE); - INSERT INTO tmp.item (item_id,amount) - SELECT item_id,s.amount - FROM `cache`.stock s + INSERT INTO tmp.item (itemFk, quantity) + SELECT item_id, amount + FROM `cache`.stock WHERE warehouse_id = vAuctionWarehouseFk - ON DUPLICATE KEY UPDATE amount = tmp.item.amount + VALUES(amount); - - CALL buyUltimate(vAuctionWarehouseFk, vDate); + ON DUPLICATE KEY UPDATE quantity = tmp.item.quantity + VALUES(quantity); + CALL buyUltimate(vAuctionWarehouseFk, vDated); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -68650,7 +69799,10 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `supplierPackaging_ReportSource`(vFromDated DATE, vSupplierFk INT) +CREATE DEFINER=`root`@`localhost` PROCEDURE `supplierPackaging_ReportSource`( + vFromDated DATE, + vSupplierFk INT +) BEGIN /** * Selecciona los embalajes de un proveedor a partir de una fecha @@ -68658,15 +69810,26 @@ BEGIN * @param vFromDated Fecha de la que partir * @param vSupplierFk Id del proveedor */ - DECLARE vCounter INT DEFAULT 0; - DECLARE vMaxRow INT DEFAULT 0; - DECLARE vItemFk INT DEFAULT 0; SET @vBalance = 0; + SET @vItemFk = NULL; - CREATE OR REPLACE TEMPORARY TABLE tSupplierPackagingList - SELECT ROW_NUMBER() OVER(ORDER BY landed) `row`, + CREATE OR REPLACE TEMPORARY TABLE tSupplierPackaging + SELECT supplierFk, itemFk, - entryFk + longName, + supplier, + entryFk, + landed, + `in`, + `out`, + warehouse, + buyingValue, + IF ( + NOT (@vItemFk <=> sub.itemFk), + @vBalance := (`in` - `out`), + @vBalance := (`in` - `out` + @vBalance) + ) balance, + @vItemFk := sub.itemFk previousItemFk FROM ( SELECT supplierFk, itemFk, @@ -68674,8 +69837,8 @@ BEGIN supplier, entryFk, landed, - `out`, `in`, + `out`, warehouse, buyingValue FROM supplierPackaging @@ -68688,103 +69851,33 @@ BEGIN supplier, 'previous', vFromDated, - SUM(`out`), SUM(`in`), + SUM(`out`), NULL, buyingValue FROM supplierPackaging WHERE supplierFk = vSupplierFk AND landed < vFromDated GROUP BY itemFk - ) sub - GROUP BY itemFk - HAVING entryFk <> 'previous' - ORDER BY landed; + ORDER BY itemFk, landed, entryFk + ) sub + WHERE `out` OR `in`; - SELECT MAX(`row`) INTO vMaxRow - FROM tSupplierPackagingList; - - CREATE OR REPLACE TEMPORARY TABLE tSupplierPackaging( - supplierFk INT, - itemFk INT, - longName VARCHAR(50), - supplier VARCHAR(50), - entryFk VARCHAR(50), - landed DATE, - `in` VARCHAR(50), - `out` VARCHAR(50), - warehouse INT, - buyingValue INT, - balance INT - ); - - l1: LOOP - SET @vBalance = 0; - IF vCounter = vMaxRow THEN - LEAVE l1; - ELSE - SET vCounter = vCounter + 1; - END IF; - - SELECT itemFk INTO vItemFk - FROM tSupplierPackagingList - WHERE `row` = vCounter; - - INSERT INTO tSupplierPackaging - SELECT supplierFk, - itemFk, - longName, - supplier, - entryFk, - landed, - `in`, - `out`, - warehouse, - buyingValue, - @vBalance:= (`in` - `out` + @vBalance) - FROM ( - SELECT supplierFk, - itemFk, - longName, - supplier, - entryFk, - landed, - `out`, - `in`, - warehouse, - buyingValue - FROM supplierPackaging - WHERE supplierFk = vSupplierFk - AND landed >= vFromDated - AND itemFk = vItemFk - UNION ALL - SELECT vSupplierFk, - itemFk, - longName, - supplier, - 'previous', - vFromDated, - SUM(`out`), - SUM(`in`), - NULL, - buyingValue - FROM supplierPackaging - WHERE supplierFk = vSupplierFk - AND landed < vFromDated - AND itemFk = vItemFk - GROUP BY itemFk - ORDER BY landed - ) sub - WHERE `out` OR `in`; - END LOOP l1; - - SELECT * + SELECT supplierFk, + itemFk, + longName, + supplier, + entryFk, + landed, + `in`, + `out`, + warehouse, + buyingValue, + balance FROM tSupplierPackaging - ORDER BY itemFk, landed; + WHERE NOT (NOT balance AND landed < CURDATE() - INTERVAL 1 YEAR); - DROP TEMPORARY TABLE IF EXISTS - tSupplierPackaging, - tSupplierPackagingList; + DROP TEMPORARY TABLE tSupplierPackaging; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -68929,9 +70022,11 @@ BEGIN UPDATE vn.supplier s JOIN ( SELECT p.supplierFk - FROM vn.payment p - LEFT JOIN vn.supplier s ON s.id = p.supplierFk - LEFT JOIN vn.payMethod pm ON pm.id = s.payMethodFk + FROM supplier s + JOIN payMethod pm ON pm.id = s.payMethodFk + JOIN (SELECT supplierFk,MAX(created) created + FROM payment + GROUP BY supplierFk) p ON p.supplierFk = s.id WHERE p.created < (util.VN_CURDATE() - INTERVAL pm.graceMonthsDisableChecked MONTH) AND pm.graceMonthsDisableChecked AND s.isPayMethodChecked @@ -68964,14 +70059,14 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `ticketBoxesView` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET character_set_client = utf8mb3 */ ; +/*!50003 SET character_set_results = utf8mb3 */ ; +/*!50003 SET collation_connection = utf8mb3_general_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketBoxesView`(IN vTicketFk INT) BEGIN @@ -68988,7 +70083,7 @@ BEGIN JOIN item i ON i.id = s.itemFk JOIN cache.last_buy lb on lb.warehouse_id = t.warehouseFk AND lb.item_id = s.itemFk JOIN buy b on b.id = lb.buy_id - JOIN packaging p on p.id = b.packageFk + JOIN packaging p on p.id = b.packagingFk WHERE s.quantity >= b.packing AND t.id = vTicketFk AND p.isBox @@ -70495,11 +71590,26 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_add`( ,vIsRequiredZone INT ,OUT vNewTicket INT) BEGIN +/** +* Crea un ticket, +* ¡¡NO se debe llamar directamente, llamar a salix que hace comprobaciones previas!! +* +* @param vClientId id del cliente +* @param vShipped dia preparacion +* @param vWarehouseFk id del warehouse +* @param vCompanyFk id la empresa +* @param vAddressFk id del consignatario +* @param vAgencyModeFk id de la agencia +* @param vRouteFk id de la ruta | NULL +* @param vlanded dia llegada +* @param vUserId que crea el ticket +* @param vIsRequiredZone Indica si tiene que tener zona valida para ser creado +* @return vNewTicket id del ticket creado +*/ DECLARE vZoneFk INT; DECLARE vPrice DECIMAL(10,2); DECLARE vBonus DECIMAL(10,2); DECLARE vIsActive BOOL; - DECLARE vNickname VARCHAR(100); IF vClientId IS NULL THEN CALL util.throw ('CLIENT_NOT_ESPECIFIED'); @@ -70565,10 +71675,6 @@ BEGIN JOIN agencyMode am ON am.id = a.agencyModeFk WHERE a.id = vAddressFk; - SELECT a.nickname INTO vNickname - FROM address a - WHERE a.id = vAddressFk; - SET vNewTicket = LAST_INSERT_ID(); INSERT INTO ticketObservation(ticketFk, observationTypeFk, description) @@ -70630,14 +71736,14 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `ticket_canAdvance` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET character_set_client = utf8mb3 */ ; +/*!50003 SET character_set_results = utf8mb3 */ ; +/*!50003 SET collation_connection = utf8mb3_general_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_canAdvance`(vDateFuture DATE, vDateToAdvance DATE, vWarehouseFk INT) BEGIN @@ -70704,12 +71810,14 @@ BEGIN dest.liters, origin.futureLines - origin.hasStock AS notMovableLines, (origin.futureLines = origin.hasStock) AS isFullMovable, + origin.futureZoneFk, + origin.futureZoneName, origin.classColor futureClassColor, dest.classColor FROM ( SELECT s.ticketFk, - t.workerFk, + c.salesPersonFk workerFk, t.shipped, t.totalWithVat, st.name futureState, @@ -70719,14 +71827,18 @@ BEGIN GROUP_CONCAT(DISTINCT ipt.code ORDER BY ipt.code) futureIpt, CAST(SUM(litros) AS DECIMAL(10,0)) futureLiters, SUM((s.quantity <= IFNULL(st.amount,0))) hasStock, + z.id futureZoneFk, + z.name futureZoneName, st.classColor FROM ticket t + JOIN client c ON c.id = t.clientFk JOIN sale s ON s.ticketFk = t.id JOIN saleVolume sv ON sv.saleFk = s.id JOIN item i ON i.id = s.itemFk JOIN ticketState ts ON ts.ticketFk = t.id JOIN state st ON st.id = ts.stateFk JOIN agencyMode am ON t.agencyModeFk = am.id + JOIN zone z ON t.zoneFk = z.id LEFT JOIN itemPackingType ipt ON ipt.code = i.itemPackingTypeFk LEFT JOIN tmp.stock st ON st.itemFk = i.id WHERE t.shipped BETWEEN vDateFuture AND util.dayend(vDateFuture) @@ -71009,22 +72121,22 @@ BEGIN DECLARE vStateFk INT; INSERT INTO ticket ( - clientFk, - shipped, - addressFk, - agencyModeFk, - nickname, - warehouseFk, - companyFk, - landed, - zoneFk, - zonePrice, - zoneBonus, - routeFk, - priority, - hasPriority, - clonedFrom - ) + clientFk, + shipped, + addressFk, + agencyModeFk, + nickname, + warehouseFk, + companyFk, + landed, + zoneFk, + zonePrice, + zoneBonus, + routeFk, + priority, + hasPriority, + clonedFrom + ) SELECT clientFk, shipped, @@ -71041,18 +72153,18 @@ BEGIN priority, hasPriority, vOriginalTicket - FROM ticket - WHERE id = vOriginalTicket; + FROM ticket + WHERE id = vOriginalTicket; SET vNewTicket = LAST_INSERT_ID(); INSERT INTO ticketObservation(ticketFk, observationTypeFk, description) - SELECT vNewTicket, o.observationTypeFk, o.description - FROM ticketObservation o - WHERE o.ticketFk = vOriginalTicket; + SELECT vNewTicket, observationTypeFk, description + FROM ticketObservation + WHERE ticketFk = vOriginalTicket; INSERT INTO ticketTracking(ticketFk, stateFk, workerFk, created) - SELECT vNewTicket, stateFk, workerFk , created + SELECT vNewTicket, stateFk, workerFk, created FROM ticketTracking WHERE ticketFk = vOriginalTicket ORDER BY created; @@ -72161,32 +73273,29 @@ BEGIN */ CALL sale_getProblems(vIsTodayRelative); - DROP TEMPORARY TABLE IF EXISTS tmp.ticket_problems; - CREATE TEMPORARY TABLE tmp.ticket_problems - (PRIMARY KEY (ticketFk)) - ENGINE = MEMORY - SELECT - ticketFk, - MAX(p.isFreezed) isFreezed, - MAX(p.risk) risk, - MAX(p.hasHighRisk) hasHighRisk, - MAX(p.hasTicketRequest) hasTicketRequest, - MAX(p.itemShortage) itemShortage, - MIN(p.isTaxDataChecked) isTaxDataChecked, - MAX(p.hasComponentLack) hasComponentLack, - MAX(p.isTooLittle) isTooLittle, - MAX(p.itemDelay) itemDelay, - MAX(p.hasRounding) hasRounding, - MAX(p.itemLost) itemLost, - 0 totalProblems - FROM tmp.sale_problems p - GROUP BY ticketFk; + CREATE OR REPLACE TEMPORARY TABLE tmp.ticket_problems + (PRIMARY KEY (ticketFk)) + ENGINE = MEMORY + SELECT ticketFk, + MAX(isFreezed) isFreezed, + MAX(risk) risk, + MAX(hasHighRisk) hasHighRisk, + MAX(hasTicketRequest) hasTicketRequest, + MAX(itemShortage) itemShortage, + MIN(isTaxDataChecked) isTaxDataChecked, + MAX(hasComponentLack) hasComponentLack, + MAX(isTooLittle) isTooLittle, + MAX(itemDelay) itemDelay, + MAX(hasRounding) hasRounding, + MAX(itemLost) itemLost, + 0 totalProblems + FROM tmp.sale_problems + GROUP BY ticketFk; UPDATE tmp.ticket_problems tp - SET tp.totalProblems = - ( + SET tp.totalProblems = ( (tp.isFreezed) + - IF(tp.risk, TRUE, FALSE) + + IF(tp.risk,TRUE, FALSE) + (tp.hasTicketRequest) + (tp.isTaxDataChecked = 0) + (tp.hasComponentLack) + @@ -72197,8 +73306,7 @@ BEGIN (tp.itemShortage) ); - DROP TEMPORARY TABLE - tmp.sale_problems; + DROP TEMPORARY TABLE tmp.sale_problems; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -72231,124 +73339,124 @@ BEGIN CALL cache.visible_refresh(vVisibleCache, FALSE, vWarehouseFk); CALL `vn`.`zoneClosure_recalc`(); - DROP TEMPORARY TABLE IF EXISTS tmp.salesToSplit; - - CREATE TEMPORARY TABLE tmp.salesToSplit + CREATE OR REPLACE TEMPORARY TABLE tmp.salesToSplit (saleFk INT PRIMARY KEY, ticketFk INT, - problem VARCHAR(1)) ENGINE = MEMORY; + problem VARCHAR(1), + INDEX(ticketFk)) ENGINE = MEMORY; INSERT INTO tmp.salesToSplit(saleFk, ticketFk, problem) - SELECT s.id, s.ticketFk, 'F' - FROM vn.ticket t - JOIN vn.sale s ON s.ticketFk = t.id - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.itemType it on it.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk - LEFT JOIN cache.visible v ON v.item_id = i.id AND v.calc_id = vVisibleCache - LEFT JOIN cache.available av ON av.item_id = i.id AND av.calc_id = vAvailableCache - LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk - WHERE IFNULL(v.visible,0) < s.quantity - AND IFNULL(av.available ,0) < s.quantity - AND IFNULL(issw.visible, 0) < s.quantity - AND s.isPicked = FALSE - AND s.reserved = FALSE - AND ic.merchandise = TRUE - AND t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE()) - AND NOT i.generic - AND t.warehouseFk = vWarehouseFk; + SELECT s.id, s.ticketFk, 'F' + FROM ticket t + JOIN sale s ON s.ticketFk = t.id + JOIN item i ON i.id = s.itemFk + JOIN itemType it on it.id = i.typeFk + JOIN itemCategory ic ON ic.id = it.categoryFk + LEFT JOIN cache.visible v ON v.item_id = i.id AND v.calc_id = vVisibleCache + LEFT JOIN cache.available av ON av.item_id = i.id AND av.calc_id = vAvailableCache + LEFT JOIN itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk + WHERE IFNULL(v.visible,0) < s.quantity + AND IFNULL(av.available ,0) < s.quantity + AND IFNULL(issw.visible, 0) < s.quantity + AND s.isPicked = FALSE + AND s.reserved = FALSE + AND ic.merchandise = TRUE + AND t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE()) + AND NOT i.generic + AND t.warehouseFk = vWarehouseFk; INSERT IGNORE INTO tmp.salesToSplit(saleFk, ticketFk, problem) - SELECT s.id, s.ticketFk, 'I' - FROM vn.ticket t - JOIN vn.sale s ON s.ticketFk = t.id - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.itemType it on it.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk - LEFT JOIN cache.visible v ON v.item_id = s.itemFk AND v.calc_id = vVisibleCache - LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk - WHERE IFNULL(v.visible,0) >= s.quantity - AND IFNULL(issw.visible, 0) < s.quantity - AND s.quantity > 0 - AND s.isPicked = FALSE - AND s.reserved = FALSE - AND ic.merchandise = TRUE - AND t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE()) - AND NOT i.generic - AND t.warehouseFk = vWarehouseFk; + SELECT s.id, s.ticketFk, 'I' + FROM ticket t + JOIN sale s ON s.ticketFk = t.id + JOIN item i ON i.id = s.itemFk + JOIN itemType it on it.id = i.typeFk + JOIN itemCategory ic ON ic.id = it.categoryFk + LEFT JOIN cache.visible v ON v.item_id = s.itemFk AND v.calc_id = vVisibleCache + LEFT JOIN itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk + WHERE IFNULL(v.visible,0) >= s.quantity + AND IFNULL(issw.visible, 0) < s.quantity + AND s.quantity > 0 + AND s.isPicked = FALSE + AND s.reserved = FALSE + AND ic.merchandise = TRUE + AND t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE()) + AND NOT i.generic + AND t.warehouseFk = vWarehouseFk; INSERT IGNORE INTO tmp.salesToSplit(saleFk, ticketFk, problem) - SELECT s.id, s.ticketFk, 'R' - FROM vn.ticket t - JOIN vn.sale s ON s.ticketFk = t.id - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.itemType it on it.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk - LEFT JOIN cache.visible v ON v.item_id = s.itemFk AND v.calc_id = vVisibleCache - LEFT JOIN cache.available av ON av.item_id = i.id AND av.calc_id = vAvailableCache - LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk - WHERE IFNULL(v.visible,0) < s.quantity - AND IFNULL(av.available ,0) >= s.quantity - AND IFNULL(issw.visible, 0) < s.quantity - AND s.quantity > 0 - AND s.isPicked = FALSE - AND s.reserved = FALSE - AND ic.merchandise = TRUE - AND t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE()) - AND NOT i.generic - AND t.warehouseFk = vWarehouseFk; + SELECT s.id, s.ticketFk, 'R' + FROM ticket t + JOIN sale s ON s.ticketFk = t.id + JOIN item i ON i.id = s.itemFk + JOIN itemType it on it.id = i.typeFk + JOIN itemCategory ic ON ic.id = it.categoryFk + LEFT JOIN cache.visible v ON v.item_id = s.itemFk AND v.calc_id = vVisibleCache + LEFT JOIN cache.available av ON av.item_id = i.id AND av.calc_id = vAvailableCache + LEFT JOIN itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk + WHERE IFNULL(v.visible,0) < s.quantity + AND IFNULL(av.available ,0) >= s.quantity + AND IFNULL(issw.visible, 0) < s.quantity + AND s.quantity > 0 + AND s.isPicked = FALSE + AND s.reserved = FALSE + AND ic.merchandise = TRUE + AND t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE()) + AND NOT i.generic + AND t.warehouseFk = vWarehouseFk; - DROP TEMPORARY TABLE IF EXISTS tmp.ticketsToSplit; - - CREATE TEMPORARY TABLE tmp.ticketsToSplit - (ticketFk INT PRIMARY KEY, + CREATE OR REPLACE TEMPORARY TABLE tTicketsToSplit( + ticketFk INT PRIMARY KEY, problems VARCHAR(100), addressFk INT, ipt VARCHAR(10), - etd TIME) ENGINE = MEMORY; + etd TIME, + INDEX(addressFk) + ) ENGINE = MEMORY; - INSERT INTO tmp.ticketsToSplit - SELECT - ss.ticketFk, - GROUP_CONCAT(DISTINCT ss.problem ORDER BY ss.problem) problems, - t.addressFk, - GROUP_CONCAT(DISTINCT i.itemPackingTypeFk ORDER BY i.itemPackingTypeFk) ipt, - zc.`hour` etd - FROM tmp.salesToSplit ss - JOIN vn.ticket t ON t.id = ss.ticketFk - JOIN vn.sale s ON s.id = ss.saleFk - JOIN vn.item i ON i.id = s.itemFk - LEFT JOIN vn.zoneClosure zc ON zc.zoneFk = t.zoneFk - GROUP BY ss.ticketFk; + INSERT INTO tTicketsToSplit + SELECT ss.ticketFk, + GROUP_CONCAT(DISTINCT ss.problem ORDER BY ss.problem) problems, + t.addressFk, + GROUP_CONCAT(DISTINCT i.itemPackingTypeFk ORDER BY i.itemPackingTypeFk) ipt, + DATE_FORMAT(IF(HOUR(t.shipped), + t.shipped, + IFNULL(zc.hour, z.HOUR)),'%H:%i') etd + FROM tmp.salesToSplit ss + JOIN ticket t ON t.id = ss.ticketFk + JOIN sale s ON s.id = ss.saleFk + JOIN item i ON i.id = s.itemFk + LEFT JOIN zoneClosure zc ON zc.zoneFk = t.zoneFk + LEFT JOIN zone z ON z.id = t.zoneFk + GROUP BY ss.ticketFk; - SELECT - ts.*, - t.id ticketFuture, - st.name state, - zc.`hour` tfEtd, - GROUP_CONCAT(DISTINCT i.itemPackingTypeFk ORDER BY i.itemPackingTypeFk) tfIpt, - st2.name tfState - FROM tmp.ticketsToSplit ts - LEFT JOIN vn.ticketState ts2 ON ts2.ticketFk = ts.ticketFk - LEFT JOIN vn.state st ON st.id = ts2.stateFk - LEFT JOIN vn.ticket t - ON t.id != ts.ticketFk - AND t.addressFk = ts.addressFk - AND t.shipped BETWEEN vDated AND util.dayend(vDated) - LEFT JOIN vn.zoneClosure zc ON zc.zoneFk = t.zoneFk AND zc.dated = vDated - LEFT JOIN vn.sale s ON s.ticketFk = t.id - LEFT JOIN vn.item i ON i.id = s.itemFk - LEFT JOIN vn.ticketState tst ON tst.ticketFk = t.id - LEFT JOIN vn.state st2 ON st2.id = tst.stateFk + SELECT ts.*, + t.id ticketFuture, + st.name state, + zc.`hour` tfEtd, + GROUP_CONCAT( + DISTINCT i.itemPackingTypeFk ORDER BY i.itemPackingTypeFk + ) tfIpt, + st2.name tfState + FROM tTicketsToSplit ts + LEFT JOIN ticketState ts2 ON ts2.ticketFk = ts.ticketFk + LEFT JOIN `state` st ON st.id = ts2.stateFk + LEFT JOIN ticket t ON t.id != ts.ticketFk + AND t.addressFk = ts.addressFk + AND t.shipped BETWEEN vDated AND util.dayend(vDated) + LEFT JOIN zoneClosure zc ON zc.zoneFk = t.zoneFk AND zc.dated = vDated + LEFT JOIN sale s ON s.ticketFk = t.id + LEFT JOIN item i ON i.id = s.itemFk + LEFT JOIN ticketState tst ON tst.ticketFk = t.id + LEFT JOIN state st2 ON st2.id = tst.stateFk WHERE (t.id IS NULL - OR (vDated > util.VN_CURDATE()) - OR (vDated = util.VN_CURDATE() AND vHour >= zc.`hour`)) + OR (vDated > util.VN_CURDATE()) + OR (vDated = util.VN_CURDATE() AND vHour >= zc.`hour`)) AND ts.etd <= vHour GROUP BY ts.ticketFk, t.id ORDER BY ts.etd, ts.ticketFk; - DROP TEMPORARY TABLE - tmp.ticketsToSplit; + DROP TEMPORARY TABLE tTicketsToSplit; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -72983,16 +74091,19 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `ticket_setState` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET character_set_client = utf8mb3 */ ; +/*!50003 SET character_set_results = utf8mb3 */ ; +/*!50003 SET collation_connection = utf8mb3_general_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_setState`(vSelf INT, vStateCode VARCHAR(255) COLLATE utf8_general_ci) +CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_setState`( + vSelf INT, + vStateCode VARCHAR(255) COLLATE utf8_general_ci +) BEGIN /** * Modifica el estado de un ticket si se cumplen las condiciones necesarias. @@ -73004,35 +74115,27 @@ BEGIN DECLARE vTicketStateCode VARCHAR(255); DECLARE vCanChangeState BOOL; DECLARE vPackedAlertLevel INT; - DECLARE vOnPreparationAlertLevel INT; - DECLARE vNextAlertLevel INT; DECLARE vZoneFk INT; - SELECT s.alertLevel, s.`code`, s2.alertLevel, t.zoneFk - INTO vticketAlertLevel, vTicketStateCode, vNextAlertLevel , vZoneFk + SELECT s.alertLevel, s.`code`, t.zoneFk + INTO vticketAlertLevel, vTicketStateCode, vZoneFk FROM state s JOIN ticketTracking tt ON tt.stateFk = s.id - JOIN state s2 ON s2.code = vStateCode JOIN ticket t ON t.id = tt.ticketFk WHERE tt.ticketFk = vSelf ORDER BY tt.created DESC LIMIT 1; SELECT id INTO vPackedAlertLevel FROM alertLevel WHERE code = 'PACKED'; - SELECT id INTO vOnPreparationAlertLevel FROM alertLevel WHERE code = 'ON_PREPARATION'; IF vStateCode = 'OK' AND vZoneFk IS NULL THEN CALL util.throw('ASSIGN_ZONE_FIRST'); END IF; - IF vNextAlertLevel > vticketAlertLevel && vticketAlertLevel < vOnPreparationAlertLevel THEN - UPDATE sale - SET originalQuantity = quantity - WHERE ticketFk = vSelf; - END IF; - - SET vCanChangeState = (vStateCode <> 'ON_CHECKING' OR vticketAlertLevel < vPackedAlertLevel) - AND NOT ( + SET vCanChangeState = ( + vStateCode <> 'ON_CHECKING' OR + vticketAlertLevel < vPackedAlertLevel + )AND NOT ( vTicketStateCode IN ('CHECKED', 'CHECKING') AND vStateCode IN ('PREPARED', 'ON_PREPARATION') ); @@ -73407,7 +74510,7 @@ BEGIN (INDEX (departmentFk)) SELECT dated, businessFk, - userFk, + sub.id userFk, departmentFk, hourStart, hourEnd, @@ -73435,8 +74538,7 @@ BEGIN at2.permissionRate, at2.discountRate, ct.hoursWeek hoursWeek, - at2.isAllowedToWork, - u.userFk + at2.isAllowedToWork FROM time t LEFT JOIN business b ON t.dated BETWEEN b.started AND IFNULL(b.ended, vDatedTo) LEFT JOIN worker w ON w.id = b.workerFk @@ -73622,212 +74724,205 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `timeControl_calculate` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET character_set_client = utf8mb3 */ ; +/*!50003 SET character_set_results = utf8mb3 */ ; +/*!50003 SET collation_connection = utf8mb3_general_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `timeControl_calculate`( vDatedFrom DATETIME, vDatedTo DATETIME) BEGIN /* + * Agrupa por trabajador y día, el tiempo de trabajo y descanso retribuido(si tiene). + * Los registros horarios incorrectos (tmp.timeControlError) no se considerarán. + * Si un trabajador ha trabajado más de un cierto umbral de tiempo (vTimeToBreakTime) + * y no ha tenido descansos que superen un parámetro determinado(vMaxTimeToBreak), + * se le añadirá un tiempo de descanso (vBreakTime) a sus horas trabajadas. + * El tiempo de descanso solo se añade si el trabajador realmente disfrutó del descanso. + * Si disfrutó de menos tiempo de descanso, solo se añade el tiempo que disfrutó. + * * @param vDatedFrom * @param vDatedTo - * Cálculo de horas trabajadas por empleado y día, - * sin tener en cuenta los días con fichadas incorrectas (tabla tmp.timeControlError) - * En el caso de haber hecho descanso y trabajado un mínimo de tiempo (vTimeToBreakTime), - * se añade al tiempo de trabajo efectivo el descanso (vBreakTime) + * * @return tmp.timeControlCalculate * (workerFk, dated, timeWorkSeconds, timeWorkSexagesimal, timeWorkDecimal, timed) */ - DECLARE vHourToSeconds INTEGER; + DECLARE vHourSeconds INTEGER; DECLARE vDatedFromYesterday DATETIME; DECLARE vDatedToTomorrow DATETIME; DECLARE vTimeToBreakTime INT; DECLARE vBreakTime INT; + DECLARE vMaxTimeToBreak INT; SELECT DATE_SUB(vDatedFrom, INTERVAL 1 DAY), DATE_ADD(vDatedTo, INTERVAL 1 DAY) INTO vDatedFromYesterday, vDatedToTomorrow; - SELECT timeToBreakTime, breakTime INTO vTimeToBreakTime, vBreakTime + SELECT timeToBreakTime, breakTime, maxTimeToBreak, TIME_TO_SEC('01:00:00') + INTO vTimeToBreakTime, vBreakTime, vMaxTimeToBreak, vHourSeconds FROM workerTimeControlConfig LIMIT 1; - CALL timeControl_getError(vDatedFrom, vDatedTo); + CALL timeControl_getError(vDatedFromYesterday, vDatedToTomorrow); - DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControl; - CREATE TEMPORARY TABLE tmp.workerTimeControl - (INDEX (userFk), INDEX (timed)) - ENGINE = MEMORY - SELECT DISTINCT(wtc.id), - wtc.userFk, + CREATE OR REPLACE TEMPORARY TABLE tmp.workerTimeControl + (INDEX(userFk, timed), INDEX(timed), INDEX(direction)) + ENGINE = MEMORY + SELECT wtc.userFk, wtc.timed, + DATE(wtc.timed) dated, wtc.direction, TRUE isReal FROM workerTimeControl wtc - JOIN tmp.`user` w ON w.userFk = wtc.userFk + JOIN tmp.`user` u ON u.userFk = wtc.userFk + LEFT JOIN ( + SELECT wtc.userFk, MIN(wtc.timed) firstIn + FROM workerTimeControl wtc + JOIN tmp.`user` u ON u.userFk = wtc.userFk + LEFT JOIN tmp.timeControlError tce ON tce.id = wtc.id + WHERE wtc.timed BETWEEN vDatedFromYesterday AND vDatedToTomorrow + AND wtc.direction = 'in' + AND tce.id IS NULL + GROUP BY userFk + ) fi ON wtc.userFk = fi.userFk + LEFT JOIN ( + SELECT wtc.userFk, MAX(wtc.timed) lastOut + FROM workerTimeControl wtc + JOIN tmp.`user` u ON u.userFk = wtc.userFk + LEFT JOIN tmp.timeControlError tce ON tce.id = wtc.id + WHERE wtc.timed BETWEEN vDatedFromYesterday AND vDatedToTomorrow + AND wtc.direction = 'out' + AND tce.id IS NULL + GROUP BY userFk + ) lo ON wtc.userFk = lo.userFk LEFT JOIN tmp.timeControlError tce ON tce.id = wtc.id - WHERE wtc.timed BETWEEN vDatedFromYesterday AND vDatedToTomorrow + WHERE wtc.timed BETWEEN fi.firstIn AND lo.lastOut AND tce.id IS NULL - ORDER BY wtc.userFk, wtc.timed ASC; + ORDER BY wtc.userFk, wtc.timed; - SELECT MAX(id) INTO @vCont - FROM tmp.workerTimeControl; + CREATE OR REPLACE TEMPORARY TABLE tmp.wtcToinsert + (INDEX(timed)) + ENGINE = MEMORY + WITH wtc AS( + SELECT timed, + userFk, + dated, + direction, + LEAD(dated) OVER + (PARTITION BY userFk, dated ORDER BY timed) nextDay, + LEAD(userFk) OVER + (PARTITION BY userFk ORDER BY timed) nextUserFk, + ROW_NUMBER() OVER (ORDER BY userFk, timed) MOD 2 isOdd + FROM tmp.workerTimeControl + WHERE timed BETWEEN vDatedFromYesterday AND vDatedToTomorrow + ORDER BY userFk, timed + ), wtcToinsert AS( + SELECT userFk, + dated, + IF(userFk = nextUserFk + AND nextDay IS NULL + AND isOdd + AND direction <> 'out', TRUE, FALSE) outNextDay, + IF(userFk = nextUserFk + AND nextDay IS NULL + AND NOT isOdd + AND direction <> 'out', TRUE, FALSE) outNextDayWhitBreak + FROM wtc + HAVING outNextDay OR outNextDayWhitBreak + )SELECT userFk, util.dayEnd(dated) timed, 'out' direction + FROM wtcToinsert + WHERE outNextDay + UNION ALL + SELECT userFk, dated + INTERVAL 1 DAY, 'in' + FROM wtcToinsert + WHERE outNextDay + UNION ALL + SELECT userFk, util.dayEnd(dated) - INTERVAL 1 SECOND, 'middle' + FROM wtcToinsert + WHERE outNextDayWhitBreak + UNION ALL + SELECT userFk, util.dayEnd(dated), 'out' + FROM wtcToinsert + WHERE outNextDayWhitBreak + UNION ALL + SELECT userFk, dated + INTERVAL 1 DAY, 'in' + FROM wtcToinsert + WHERE outNextDayWhitBreak + UNION ALL + SELECT userFk, dated + INTERVAL 1 DAY + INTERVAL 1 SECOND, 'middle' + FROM wtcToinsert + WHERE outNextDayWhitBreak; - DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControlAux; - CREATE TEMPORARY TABLE tmp.workerTimeControlAux ( - `id` int(11) , - `userFk` int(10) unsigned , - `timed` datetime, - `direction` enum('in', 'out','middle') - ) ENGINE=MEMORY; + INSERT INTO tmp.workerTimeControl (userFk, timed, dated, direction, isReal) + SELECT userFk, timed, DATE(timed), direction, FALSE + FROM tmp.wtcToinsert; - SET @counter := 0; - SET @vIsOdd := FALSE; - - -- Cambio de dia en medio de un descanso - INSERT INTO tmp.workerTimeControlAux (id, userFk, timed, direction) - SELECT @vCont:= @vCont + 1 id, - userFk, - util.dayEnd(dated) timed, - 'middle' direction - FROM(SELECT wtc.userFk, - DATE(@lastTimed) dated, - (@vIsOdd := NOT @vIsOdd) isOdd, - IF(@vIsOdd AND wtc.direction = 'middle' - AND DATE(timed) <> DATE(@lastTimed), TRUE, FALSE) hasBreak, - @lastTimed := wtc.timed - FROM tmp.workerTimeControl wtc - ORDER BY wtc.userFk, wtc.timed - LIMIT 10000000000000000000 - )sub - WHERE hasBreak; - - SET @counter := 0; - SET @vIsOdd := FALSE; - - INSERT INTO tmp.workerTimeControlAux (id, userFk, timed, direction) - SELECT @vCont:= @vCont + 1, - userFk, - DATE_ADD(sub.dated, INTERVAL 1 DAY), - 'middle' - FROM(SELECT wtc.userFk, - DATE(@lastTimed) dated, - (@vIsOdd := NOT @vIsOdd) isOdd, - IF(@vIsOdd AND wtc.direction = 'middle' - AND DATE(timed) <> DATE(@lastTimed), TRUE, FALSE) hasBreak, - @lastTimed := wtc.timed - FROM tmp.workerTimeControl wtc - ORDER BY wtc.userFk, wtc.timed - LIMIT 10000000000000000000 - )sub - WHERE hasBreak; - - -- Cambio de dia - INSERT INTO tmp.workerTimeControlAux (id, userFk, timed, direction) - SELECT @vCont:= @vCont + 1 id, - sub.userFk, - util.dayEnd(sub.dated) timed, - 'out' direction - FROM (SELECT MAX(wtc.timed) timed, wtc.userFk, date(wtc.timed) dated - FROM workerTimeControl wtc - JOIN tmp.`user` w ON w.userFk = wtc.userFk - LEFT JOIN tmp.timeControlError tce ON tce.id = wtc.id - WHERE wtc.timed BETWEEN vDatedFromYesterday AND vDatedToTomorrow - AND tce.id IS NULL - GROUP BY wtc.userFk, DATE(wtc.timed) - ) sub - JOIN tmp.workerTimeControl wtc ON wtc.timed = sub.timed - AND wtc.userFk = sub.userFk - WHERE wtc.direction <> 'out'; - - INSERT INTO tmp.workerTimeControlAux (id, userFk, timed, direction) - SELECT @vCont:= @vCont + 1, sub.userFk, DATE_ADD(sub.dated, INTERVAL 1 DAY), 'in' - FROM (SELECT MAX(wtc.timed) timed, wtc.userFk, date(wtc.timed) dated - FROM workerTimeControl wtc - JOIN tmp.`user` w ON w.userFk = wtc.userFk - LEFT JOIN tmp.timeControlError tce ON tce.id = wtc.id - WHERE wtc.timed BETWEEN vDatedFromYesterday AND vDatedToTomorrow - AND tce.id IS NULL - GROUP BY wtc.userFk, DATE(wtc.timed) - ) sub - JOIN tmp.workerTimeControl wtc ON wtc.timed = sub.timed - AND wtc.userFk = sub.userFk - WHERE wtc.direction <> 'out'; - - INSERT INTO tmp.workerTimeControl (id, userFk, timed, direction, isReal) - SELECT id, userFk, timed, direction, FALSE FROM tmp.workerTimeControlAux; - - SET vHourToSeconds = 3600; - SET @vIsOdd := TRUE; - SET @vDated := 0; - SET @vLastTimed := 0; - SET @vPreviousTimed := 0; - - DROP TEMPORARY TABLE IF EXISTS tmp.workerBreakDays; - CREATE TEMPORARY TABLE tmp.workerBreakDays - (INDEX (userFk), INDEX (dated)) - ENGINE = MEMORY - SELECT sub.userFk, - sub.dated - FROM (SELECT (@vIsOdd := NOT @vIsOdd), - IF(wtc.direction = 'in', @vIsOdd := TRUE, NULL), - IF(@vIsOdd, @vLastTimed := UNIX_TIMESTAMP(wtc.timed), NULL), - IF(@vIsOdd, 0, UNIX_TIMESTAMP(wtc.timed) - @vLastTimed) timeWork, - IF(direction='in', @vDated := DATE(wtc.timed), @vDated) dated, - wtc.userFk - FROM tmp.workerTimeControl wtc - ORDER BY wtc.userFk, wtc.timed, wtc.id - LIMIT 10000000000000000000 - )sub - GROUP BY sub.userFk, sub.dated - HAVING SUM(sub.timeWork) >= vTimeToBreakTime; - - SET @vIsOdd := TRUE; - SET @vDated := 0; - SET @vLastTimed := 0; - - DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControlAux2; - CREATE TEMPORARY TABLE tmp.workerTimeControlAux2 - SELECT * - FROM tmp.workerTimeControl - WHERE timed BETWEEN vDatedFromYesterday AND vDatedTo - ORDER BY userFk, timed, id; - - DROP TEMPORARY TABLE IF EXISTS tmp.timeControlCalculate; + SET @accumulatedForBreakTime = 0; + SET @oldrealDay = NULL; CREATE OR REPLACE TEMPORARY TABLE tmp.timeControlCalculate - (INDEX (userFk, dated)) - ENGINE = MEMORY - SELECT sub.userFk, - sub.dated, - IF(wb.userFk, vBreakTime, 0) + SUM(sub.timeWork) timeWorkSeconds, - SEC_TO_TIME(IF(wb.userFk, vBreakTime, 0) + SUM(sub.timeWork)) timeWorkSexagesimal, - (IF(wb.userFk, vBreakTime, 0) + SUM(sub.timeWork)) / vHourToSeconds timeWorkDecimal, - CAST(GROUP_CONCAT(DATE_FORMAT(sub.realTimed, "%H:%i") - ORDER BY sub.timed ASC SEPARATOR ' - ') AS CHAR(256)) timed - FROM (SELECT (@vIsOdd := NOT @vIsOdd), - IF(direction='in', @vIsOdd := TRUE, 0), - IF(@vIsOdd, @vLastTimed := UNIX_TIMESTAMP(timed), 0), - IF(@vIsOdd, 0, UNIX_TIMESTAMP(timed) - @vLastTimed) timeWork, - timed, - userFk, - DATE(timed) dated, - IF(isReal, timed, NULL) realTimed - FROM tmp.workerTimeControlAux2 - )sub - LEFT JOIN tmp.workerBreakDays wb ON wb.userFk = sub.userFk AND wb.dated = sub.dated - WHERE sub.timed BETWEEN vDatedFrom AND vDatedTo - GROUP BY sub.userFk, sub.dated; + WITH workerTimed AS ( + SELECT + userFk, + dated, + timed, + (direction ='in' AND isReal) breakPoint, + SUM(CASE WHEN (direction ='in' AND isReal) THEN TRUE ELSE FALSE END) + OVER (ORDER BY userFk, timed) AS realDay, + TIMESTAMPDIFF(SECOND, LAG(timed) + OVER (PARTITION BY userFk, dated ORDER BY timed), timed) gapTime, + ROW_NUMBER() + OVER (PARTITION BY userFk, dated ORDER BY timed) MOD 2 isOdd + FROM tmp.workerTimeControl + WHERE timed BETWEEN vDatedFromYesterday AND vDatedToTomorrow + ), accumulated AS ( + SELECT SUM(IF(isOdd, 0, gapTime)) + OVER (PARTITION BY userFk,dated ORDER BY userFk,timed) accumulatedWorkTime, + SUM(IF(NOT isOdd OR breakPoint, 0, IFNULL(gapTime, 0))) + OVER (PARTITION BY realDay ORDER BY realDay,timed) accumulatedBreakTime, + IF(realDay <> @oldrealDay OR (isOdd AND gapTime >= vMaxTimeToBreak), + @accumulatedForBreakTime := 0, + @accumulatedForBreakTime := @accumulatedForBreakTime + + IF(isOdd, 0, gapTime )) accumulatedForBreakTime, + @oldrealDay := realDay, + userFk, + dated, + realDay + FROM workerTimed + ), totalWorked AS ( + SELECT userFk, + dated, + MAX(accumulatedWorkTime) + + IF(MAX(accumulatedForBreakTime) >= vTimeToBreakTime, + LEAST(vBreakTime, MAX(accumulatedBreakTime)), + 0) timeWorkSeconds + FROM accumulated + GROUP BY userFk, dated + )SELECT tw.userFk, + tw.dated, + timeWorkSeconds, + SEC_TO_TIME(timeWorkSeconds) timeWorkSexagesimal, + timeWorkSeconds / vHourSeconds timeWorkDecimal, + sub.tableTimed + FROM totalWorked tw + JOIN ( + SELECT userFk, + dated, + GROUP_CONCAT(DATE_FORMAT(timed, "%H:%i") ORDER BY timed ASC + SEPARATOR ' - ')tableTimed + FROM tmp.workerTimeControl + WHERE timed BETWEEN vDatedFromYesterday AND vDatedToTomorrow + AND isReal + GROUP BY userFk, dated + )sub ON sub.dated = tw.dated + AND sub.userFk = tw.userFk + WHERE tw.dated BETWEEN vDatedFrom AND vDatedTo; - DROP TEMPORARY TABLE tmp.workerBreakDays; DROP TEMPORARY TABLE tmp.timeControlError; - DROP TEMPORARY TABLE tmp.workerTimeControlAux; - DROP TEMPORARY TABLE tmp.workerTimeControlAux2; + DROP TEMPORARY TABLE tmp.wtcToinsert; DROP TEMPORARY TABLE tmp.workerTimeControl; END ;; DELIMITER ; @@ -73958,19 +75053,17 @@ BEGIN * @param vDatedFrom workerTimeControl * @param vDatedTo workerTimeControl */ + DROP TEMPORARY TABLE IF EXISTS tmp.`user`; - DROP TEMPORARY TABLE IF EXISTS tmp.`user`; - - CREATE TEMPORARY TABLE tmp.`user` + CREATE TEMPORARY TABLE tmp.`user` SELECT u.id userFk FROM account.user u - JOIN vn.worker w ON w.userFk = u.id - WHERE w.id = vWorkerFk; + JOIN vn.worker w ON w.id = u.id + WHERE w.id = vWorkerFk; - CALL vn.timeControl_calculate(vDatedFrom, vDatedTo); - - DROP TEMPORARY TABLE tmp.`user`; + CALL vn.timeControl_calculate(vDatedFrom, vDatedTo); + DROP TEMPORARY TABLE tmp.`user`; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -74121,14 +75214,14 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `travelVolume` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET character_set_client = utf8mb3 */ ; +/*!50003 SET character_set_results = utf8mb3 */ ; +/*!50003 SET collation_connection = utf8mb3_general_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `travelVolume`(vTravelFk INT) BEGIN @@ -74142,9 +75235,9 @@ BEGIN e.id Id_Entrada, e.invoiceNumber Referencia, CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) * - vn.item_getVolume(b.itemFk ,b.packageFk)) / vc.trolleyM3 / 1000000 ,1) AS DECIMAL(10,2)) AS CC, + vn.item_getVolume(b.itemFk ,b.packagingFk)) / vc.trolleyM3 / 1000000 ,1) AS DECIMAL(10,2)) AS CC, CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) * - vn.item_getVolume(b.itemFk ,b.packageFk)) / vc.palletM3 / 1000000,1) AS DECIMAL(10,2)) AS espais + vn.item_getVolume(b.itemFk ,b.packagingFk)) / vc.palletM3 / 1000000,1) AS DECIMAL(10,2)) AS espais FROM vn.buy b JOIN vn.entry e ON e.id = b.entryFk JOIN vn.supplier s ON s.id = e.supplierFk @@ -74164,21 +75257,21 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `travelVolume_get` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET character_set_client = utf8mb3 */ ; +/*!50003 SET character_set_results = utf8mb3 */ ; +/*!50003 SET collation_connection = utf8mb3_general_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `travelVolume_get`(vFromDated DATE, vToDated DATE, vWarehouseFk INT) BEGIN SELECT tr.landed Fecha, a.name Agencia, count(DISTINCT e.id) numEntradas, - FLOOR(sum(item_getVolume(b.itemFk, b.packageFk) * b.stickers / 1000000 )) AS m3 + FLOOR(sum(item_getVolume(b.itemFk, b.packagingFk) * b.stickers / 1000000 )) AS m3 FROM vn.travel tr JOIN vn.agencyMode a ON a.id = tr.agencyModeFk JOIN vn.entry e ON e.travelFk = tr.id @@ -74452,52 +75545,46 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `travel_doRecalc` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb3 */ ; -/*!50003 SET character_set_results = utf8mb3 */ ; -/*!50003 SET collation_connection = utf8mb3_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `travel_doRecalc`() -BEGIN +proc: BEGIN /** - * Recounts the number of entries of changed travels. - */ - DECLARE vDone BOOL; +* Recounts the number of entries of changed travels. +*/ DECLARE vTravelFk INT; - DECLARE vTotalEntries INT; - DECLARE cCur CURSOR FOR + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + DO RELEASE_LOCK('vn.ticket_doRecalc'); + END; + + IF !GET_LOCK('vn.travel_doRecalc', 0) THEN + LEAVE proc; + END IF; + + CREATE OR REPLACE TEMPORARY TABLE tTravel + ENGINE = MEMORY SELECT travelFk FROM travelRecalc; - DECLARE CONTINUE HANDLER FOR NOT FOUND - SET vDone = TRUE; + UPDATE travel t + JOIN tTravel tt ON tt.travelFk = t.id + SET t.totalEntries = ( + SELECT COUNT(e.id) + FROM entry e + WHERE e.travelFk = t.id + ); - OPEN cCur; - - myLoop: LOOP - SET vDone = FALSE; - FETCH cCur INTO vTravelFk; - - IF vDone THEN - LEAVE myLoop; - END IF; - - SELECT COUNT(*) INTO vTotalEntries - FROM entry - WHERE travelFk = vTravelFk; - - UPDATE travel - SET totalEntries = vTotalEntries - WHERE id = vTravelFk; - - DELETE FROM travelRecalc WHERE travelFk = vTravelFk; - END LOOP; - - CLOSE cCur; + DELETE tr FROM travelRecalc tr JOIN tTravel t ON tr.travelFk = t.travelFk; + DROP TEMPORARY TABLE tTravel; + DO RELEASE_LOCK('vn.travel_doRecalc'); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -74505,14 +75592,14 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `travel_getEntriesMissingPackage` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET character_set_client = utf8mb3 */ ; +/*!50003 SET character_set_results = utf8mb3 */ ; +/*!50003 SET collation_connection = utf8mb3_general_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `travel_getEntriesMissingPackage`(vSelf INT) BEGIN @@ -74528,7 +75615,7 @@ BEGIN JOIN entry e ON e.travelFk = t.id JOIN buy b ON b.entryFk = e.id WHERE t.id = vTravelFk - AND (b.packing IS NULL OR b.packageFk IS NULL); + AND (b.packing IS NULL OR b.packagingFk IS NULL); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -75277,38 +76364,6 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `workerCreate` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `workerCreate`( - vFirstname VARCHAR(50), - vLastName VARCHAR(50), - vCode CHAR(3), - vBossFk INT, - vUserFk INT, - vFi VARCHAR(15) , - vBirth DATE -) -BEGIN -/** - * Create new worker - * - */ - INSERT INTO worker(id, code, firstName, lastName, bossFk, fi, birth,userFk) - VALUES (vUserFk, vCode, vFirstname, vLastName, vBossFk, vFi, vBirth,vUserFk); -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 */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `workerCreateExternal` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -76422,41 +77477,44 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `workerTimeControl_clockIn` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET character_set_client = utf8mb3 */ ; +/*!50003 SET character_set_results = utf8mb3 */ ; +/*!50003 SET collation_connection = utf8mb3_general_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControl_clockIn`( - vWorker INT, + vWorkerFk INT, vTimed DATETIME, - vDirection VARCHAR(10)) + vDirection VARCHAR(10) +) BEGIN /** * Verifica si el empleado puede fichar - * @param vWorker Identificador del trabajador + * @param vWorkerFk Identificador del trabajador * @param vTimed valor de la fichada, IF vTimed IS NULL vTimed = NOW * @param vDirection solo se pueden pasa los valores del campo * workerTimeControl.direction ENUM('in', 'out', 'middle') * @return Si todo es correcto, retorna el número de id la tabla workerTimeControl. - * Si hay algún problema, devuelve el mesaje a que se debe mostrar al usuario + * Si hay algún problema, devuelve el mesaje que se debe mostrar al usuario * Solo retorna el primer problema, en caso de no ocurrir ningún error se añadirá * fichada a la tabla vn.workerTimeControl */ + DECLARE vLastIn DATETIME; DECLARE vLastOut DATETIME; DECLARE vNextIn DATETIME; - DECLARE vLastDirection VARCHAR(6); - DECLARE vNextDirection VARCHAR(6); + DECLARE vNextOut DATETIME; + DECLARE vNextDirection ENUM('in', 'out'); + DECLARE vLastDirection ENUM('in', 'out'); + DECLARE vDayMaxTime INTEGER; DECLARE vDayBreak INT; DECLARE vShortWeekBreak INT; DECLARE vLongWeekBreak INT; DECLARE vWeekScope INT; - DECLARE vGap INT; DECLARE vMailTo VARCHAR(50) DEFAULT NULL; DECLARE vUserName VARCHAR(50) DEFAULT NULL; DECLARE vIsError BOOLEAN DEFAULT FALSE; @@ -76464,79 +77522,40 @@ BEGIN DECLARE vErrorCode VARCHAR(50); DECLARE vDated DATE; DECLARE vIsAllowedToWork VARCHAR(50); - DECLARE vDepartmentFk INT; - DECLARE vTimedLoop BIGINT; - DECLARE vTimedLoopPrevious BIGINT; - DECLARE vHasBreakWeek BOOLEAN DEFAULT FALSE; - DECLARE vManual BOOLEAN DEFAULT TRUE; - DECLARE vDone INT DEFAULT FALSE; - - DECLARE vCursor CURSOR FOR - SELECT UNIX_TIMESTAMP(vTimed) timed - UNION - SELECT UNIX_TIMESTAMP(timed) - FROM workerTimeControl - WHERE timed BETWEEN (vTimed - INTERVAL vGap SECOND) AND vTimed - AND userFk = vWorker - AND direction IN ('in', 'out') - ORDER BY timed ASC; - - DECLARE vCursor2 CURSOR FOR - SELECT UNIX_TIMESTAMP(vTimed) timed - UNION - SELECT UNIX_TIMESTAMP(timed) - FROM workerTimeControl - WHERE timed BETWEEN vTimed AND (vTimed + INTERVAL vGap SECOND) - AND userFk = vWorker - AND direction IN ('in', 'out') - ORDER BY timed ASC; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + DECLARE vIsManual BOOLEAN DEFAULT TRUE; + DECLARE vMaxWorkShortCycle INT; + DECLARE vMaxWorkLongCycle INT; DECLARE EXIT HANDLER FOR SQLSTATE '45000' BEGIN - SELECT CONCAT(u.name, '@verdnatura.es'), + SELECT CONCAT(u.name, '@verdnatura.es'), CONCAT(w.firstName, ' ', w.lastName) INTO vMailTo, vUserName FROM account.user u JOIN worker w ON w.bossFk = u.id - WHERE w.id = vWorker; + WHERE w.id = vWorkerFk; - CASE vErrorCode - WHEN 'IS_NOT_ALLOWED_FUTURE' THEN - SELECT 'No se permite fichar a futuro' INTO vErrorMessage; - WHEN 'INACTIVE_BUSINESS' THEN - SELECT 'No hay un contrato en vigor' INTO vErrorMessage; - WHEN 'IS_NOT_ALLOWED_WORK' THEN - SELECT 'No está permitido trabajar' INTO vErrorMessage; - WHEN 'ODD_WORKERTIMECONTROL' THEN - SELECT 'Fichadas impares' INTO vErrorMessage; - WHEN 'BREAK_DAY' THEN - SELECT CONCAT('Descanso diario ', FORMAT(vDayBreak/3600, 0), 'h.') - INTO vErrorMessage; - WHEN 'BREAK_WEEK' THEN - SELECT CONCAT('Descanso semanal ', - FORMAT(vShortWeekBreak / 3600,0) ,'h. / ', - FORMAT(vLongWeekBreak / 3600, 0) ,'h.') INTO vErrorMessage; - WHEN 'WRONG_DIRECTION' THEN - SELECT 'Dirección incorrecta' INTO vErrorMessage; - ELSE - SELECT 'Error sin definir'INTO vErrorMessage; - END CASE; + SELECT `description` INTO vErrorMessage + FROM workerTimeControlError + WHERE `code` = vErrorCode; + + IF vErrorMessage IS NULL THEN + SET vErrorMessage = 'Error sin definir'; + END IF; SELECT vErrorMessage `error`; SELECT CONCAT(vUserName, ' no ha podido fichar por el siguiente problema: ', vErrorMessage) INTO vErrorMessage; - CALL mail_insert( vMailTo, vMailTo, 'Error al fichar', vErrorMessage); + CALL mail_insert( vMailTo, vMailTo, 'Error al fichar', vErrorMessage); END; IF (vTimed IS NULL) THEN SET vTimed = util.VN_NOW(); - SET vManual = FALSE; + SET vIsManual = FALSE; END IF; SET vDated = DATE(vTimed); @@ -76546,70 +77565,38 @@ BEGIN wc.dayBreak), wc.shortWeekBreak, wc.longWeekBreak, - wc.weekScope + wc.weekScope, + wc.dayMaxTime, + wc.maxWorkShortCycle, + wc.maxWorkLongCycle INTO vDayBreak, vShortWeekBreak, vLongWeekBreak, - vWeekScope + vWeekScope, + vDayMaxTime, + vMaxWorkShortCycle, + vMaxWorkLongCycle FROM business b JOIN professionalCategory pc ON pc.id = b.workerBusinessProfessionalCategoryFk - JOIN workerTimeControlConfig wc ON TRUE - WHERE b.workerFk = vWorker + JOIN workerTimeControlConfig wc + WHERE b.workerFk = vWorkerFk AND vDated BETWEEN b.started AND IFNULL(b.ended, vDated); - SELECT timed INTO vLastIn - FROM workerTimeControl - WHERE userFk = vWorker - AND direction = 'in' - AND timed < vTimed - ORDER BY timed DESC - LIMIT 1; - - SELECT timed INTO vLastOut - FROM workerTimeControl - WHERE userFk = vWorker - AND direction = 'out' - AND timed < vTimed - ORDER BY timed DESC - LIMIT 1; - - SELECT timed INTO vNextIn - FROM workerTimeControl - WHERE userFk = vWorker - AND direction = 'in' - AND timed > vTimed - ORDER BY timed ASC - LIMIT 1; - - SELECT direction INTO vNextDirection - FROM workerTimeControl - WHERE userFk = vWorker - AND timed > vTimed - ORDER BY timed ASC - LIMIT 1; - - SELECT direction INTO vLastDirection - FROM workerTimeControl - WHERE userFk = vWorker - AND timed < vTimed - ORDER BY timed DESC - LIMIT 1; - - -- FICHADAS A FUTURO - IF vTimed > DATE_ADD(util.VN_NOW(), INTERVAL 60 SECOND) THEN - SET vErrorCode = 'IS_NOT_ALLOWED_FUTURE'; - CALL util.throw(vErrorCode); - END IF; - -- CONTRATO EN VIGOR IF vDayBreak IS NULL THEN SET vErrorCode = 'INACTIVE_BUSINESS'; CALL util.throw(vErrorCode); END IF; + -- FICHADAS A FUTURO + IF vTimed > util.VN_NOW() + INTERVAL 1 MINUTE THEN + SET vErrorCode = 'IS_NOT_ALLOWED_FUTURE'; + CALL util.throw(vErrorCode); + END IF; + -- VERIFICAR SI ESTÁ PERMITIDO TRABAJAR - CALL timeBusiness_calculateByWorker(vWorker, vDated, vDated); + CALL timeBusiness_calculateByWorker(vWorkerFk, vDated, vDated); SELECT isAllowedToWork INTO vIsAllowedToWork FROM tmp.timeBusinessCalculate; DROP TEMPORARY TABLE tmp.timeBusinessCalculate; @@ -76620,7 +77607,7 @@ BEGIN END IF; -- DIRECCION CORRECTA - CALL workerTimeControl_direction(vWorker, vTimed); + CALL workerTimeControl_direction(vWorkerFk, vTimed); IF (SELECT IF(IF(option1 IN ('inMiddle', 'outMiddle'), 'middle', @@ -76636,17 +77623,25 @@ BEGIN END IF; DROP TEMPORARY TABLE tmp.workerTimeControlDirection; - IF vIsError = TRUE THEN + IF vIsError THEN SET vErrorCode = 'WRONG_DIRECTION'; CALL util.throw(vErrorCode); END IF; -- FICHADAS IMPARES + SELECT timed INTO vLastIn + FROM workerTimeControl + WHERE userFk = vWorkerFk + AND direction = 'in' + AND timed < vTimed + ORDER BY timed DESC + LIMIT 1; + IF (SELECT IF(vDirection = 'in', MOD(COUNT(*), 2) , IF (vDirection = 'out', NOT MOD(COUNT(*), 2), FALSE)) FROM workerTimeControl - WHERE userFk = vWorker + WHERE userFk = vWorkerFk AND timed BETWEEN vLastIn AND vTimed ) THEN SET vErrorCode = 'ODD_WORKERTIMECONTROL'; @@ -76654,6 +77649,22 @@ BEGIN END IF; -- DESCANSO DIARIO + SELECT timed INTO vLastOut + FROM workerTimeControl + WHERE userFk = vWorkerFk + AND direction = 'out' + AND timed < vTimed + ORDER BY timed DESC + LIMIT 1; + + SELECT timed INTO vNextIn + FROM workerTimeControl + WHERE userFk = vWorkerFk + AND direction = 'in' + AND timed > vTimed + ORDER BY timed ASC + LIMIT 1; + CASE vDirection WHEN 'in' THEN IF UNIX_TIMESTAMP(vTimed) - UNIX_TIMESTAMP(vLastOut) <= vDayBreak THEN @@ -76671,94 +77682,93 @@ BEGIN CALL util.throw(vErrorCode); END IF; - -- VERIFICAR DESCANSO SEMANAL + + IF (vDirection IN('in', 'out')) THEN - -- VERIFICA DESCANSO CORTO EN LA ÚLTIMA SEMANA - SET vGap = vWeekScope; - SET vTimedLoopPrevious = UNIX_TIMESTAMP((vTimed - INTERVAL vGap SECOND)); - SET vDone = FALSE; - OPEN vCursor; - l:LOOP - FETCH vCursor INTO vTimedLoop; - IF vDone THEN - LEAVE l; - END IF; - IF vShortWeekBreak - (vTimedLoop - vTimedLoopPrevious) <= 0 THEN - SET vHasBreakWeek = TRUE; - LEAVE l; - END IF; - SET vTimedLoopPrevious = vTimedLoop; - END LOOP l; - CLOSE vCursor; - -- VERIFICA DESCANSO LARGO EN LA ÚLTIMAS 2 SEMANAS - IF NOT vHasBreakWeek THEN - SET vGap = vWeekScope * 2; - SET vTimedLoopPrevious = UNIX_TIMESTAMP(vTimed - INTERVAL vGap SECOND); - SET vDone = FALSE; - OPEN vCursor; - l:LOOP - FETCH vCursor INTO vTimedLoop; - IF vDone THEN - LEAVE l; - END IF; - IF vLongWeekBreak - (vTimedLoop - vTimedLoopPrevious) <= 0 THEN - SET vHasBreakWeek = TRUE; - LEAVE l; - END IF; - SET vTimedLoopPrevious = vTimedLoop; - END LOOP l; - CLOSE vCursor; + -- VERIFICA MAXIMO TIEMPO DESDE ENTRADA HASTA LA SALIDA + + SELECT timed INTO vNextOut + FROM workerTimeControl + WHERE userFk = vWorkerFk + AND direction = 'out' + AND timed > vTimed + ORDER BY timed ASC + LIMIT 1; + + SELECT direction INTO vNextDirection + FROM workerTimeControl + WHERE userFk = vWorkerFk + AND direction IN('in','out') + AND timed > vTimed + ORDER BY timed ASC + LIMIT 1; + + SELECT direction INTO vLastDirection + FROM workerTimeControl + WHERE userFk = vWorkerFk + AND direction IN('in', 'out') + AND timed < vTimed + ORDER BY timed ASC + LIMIT 1; + + IF (vDirection ='in' + AND vNextDirection = 'out' + AND UNIX_TIMESTAMP(vNextOut) - UNIX_TIMESTAMP(vTimed) > vDayMaxTime) OR + (vDirection ='out' + AND vLastDirection = 'in' + AND UNIX_TIMESTAMP(vTimed) -UNIX_TIMESTAMP(vLastIn) > vDayMaxTime) THEN + SET vErrorCode = 'DAY_MAX_TIME'; + CALL util.throw(vErrorCode); END IF; - IF vManual THEN - -- VERIFICA DESCANSO CORTO EN LA PRÓXIMA SEMANA - SET vGap = vWeekScope; - SET vTimedLoopPrevious = vTimed; - SET vDone = FALSE; - OPEN vCursor2; - l:LOOP - FETCH vCursor2 INTO vTimedLoop; - IF vDone THEN - LEAVE l; - END IF; - IF vShortWeekBreak - (vTimedLoop - vTimedLoopPrevious) <= 0 THEN - SET vHasBreakWeek = TRUE; - LEAVE l; - END IF; - SET vTimedLoopPrevious = vTimedLoop; - END LOOP l; - CLOSE vCursor2; - -- VERIFICA DESCANSO LARGO EN LAS PRÓXIMAS 2 SEMANAS - IF NOT vHasBreakWeek THEN - SET vGap = vWeekScope * 2; - SET vTimedLoopPrevious = vTimed; - SET vDone = FALSE; - OPEN vCursor2; - l:LOOP - FETCH vCursor2 INTO vTimedLoop; - IF vDone THEN - LEAVE l; - END IF; - IF vShortWeekBreak - (vTimedLoop - vTimedLoopPrevious) <= 0 THEN - SET vHasBreakWeek = TRUE; - LEAVE l; - END IF; - SET vTimedLoopPrevious = vTimedLoop; - END LOOP l; - CLOSE vCursor2; - END IF; - END IF; - IF NOT vHasBreakWeek THEN + -- VERIFICA DESCANSO SEMANAL + + WITH wtc AS( + (SELECT timed + FROM vn.workerTimeControl + WHERE userFk = vWorkerFk + AND direction IN ('in', 'out') + AND timed BETWEEN vTimed - INTERVAL (vWeekScope * 2) SECOND + AND vTimed + INTERVAL (vWeekScope * 2) SECOND ) + UNION + (SELECT vTimed) + ), wtcGap AS( + SELECT timed, + TIMESTAMPDIFF(SECOND, LAG(timed) OVER (ORDER BY timed), timed) gap + FROM wtc + ORDER BY timed + ), wtcBreak AS( + SELECT timed, + IF(IFNULL(gap, 0) > vShortWeekBreak, TRUE, FALSE) hasShortBreak, + IF(IFNULL(gap, 0) > vLongWeekBreak, TRUE, FALSE) hasLongBreak + FROM wtcGap + ORDER BY timed + ), wtcBreakCounter AS( + SELECT timed, + SUM(hasShortBreak) OVER (ORDER BY timed) breakCounter , + LEAD(hasLongBreak) OVER (ORDER BY timed) nextHasLongBreak + FROM wtcBreak + )SELECT TIMESTAMPDIFF(SECOND, MIN(timed), MAX(timed)) > vMaxWorkLongCycle OR + (TIMESTAMPDIFF(SECOND, MIN(timed), MAX(timed))> vMaxWorkShortCycle + AND NOT SUM(IFNULL(nextHasLongBreak, 1))) + hasError INTO vIsError + FROM wtcBreakCounter + GROUP BY breakCounter + HAVING hasError + LIMIT 1; + + IF vIsError THEN SET vErrorCode = 'BREAK_WEEK'; CALL util.throw(vErrorCode); END IF; END IF; -- SE PERMITE FICHAR - INSERT INTO workerTimeControl(userFk, timed, direction, manual) - VALUES(vWorker, vTimed, vDirection, vManual); + INSERT INTO workerTimeControl(userFk, timed, direction, `manual`) + VALUES(vWorkerFk, vTimed, vDirection, vIsManual); SELECT LAST_INSERT_ID() id; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -77628,15 +78638,28 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `worker_updateBusiness`(vSelf INT) BEGIN /** - * Actualiza en la tabla @worker el contrato actual del trabajador. + * Activates an account and configures its email settings. * - * @param vSelf Id del trabajador + * @param vSelf account id. */ - UPDATE worker w - LEFT JOIN business b ON b.workerFk = w.id - AND util.VN_CURDATE() BETWEEN b.started AND IFNULL(b.ended, util.VN_CURDATE()) - SET w.businessFk = b.id - WHERE w.id = vSelf; + DECLARE vOldBusinessFk INT; + DECLARE vNewBusinessFk INT; + + SELECT businessFk INTO vOldBusinessFk FROM worker WHERE id = vSelf; + + SELECT id INTO vNewBusinessFk + FROM business + WHERE workerFk = vSelf + AND util.VN_CURDATE() BETWEEN started AND IFNULL(ended, util.VN_CURDATE()) + LIMIT 1; + + UPDATE worker + SET businessFk = vNewBusinessFk + WHERE id = vSelf; + + IF vOldBusinessFk IS NULL THEN + CALL account.account_enable(vSelf); + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -78204,6 +79227,74 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `zone_getAddresses` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getAddresses`( + vSelf INT, + vLanded DATE +) +BEGIN +/** + * Devuelve un listado de todos los clientes activos + * con consignatarios a los que se les puede + * vender producto para esa zona y no tiene un ticket + * para ese día. + * + * @param vSelf Id de zona + * @param vDated Fecha de entrega + * @return Un select + */ + CALL zone_getPostalCode(vSelf); + + WITH notHasTicket AS ( + SELECT id + FROM vn.client + WHERE id NOT IN ( + SELECT clientFk + FROM vn.ticket + WHERE landed BETWEEN vLanded AND util.dayEnd(vLanded) + ) + ) + SELECT c.id clientFk, + c.name, + c.phone, + c.mobile, + c.salesPersonFk, + u.name username, + aai.invoiced, + cnb.lastShipped + FROM vn.client c + JOIN notHasTicket ON notHasTicket.id = c.id + LEFT JOIN account.`user` u ON u.id = c.salesPersonFk + JOIN vn.`address` a ON a.clientFk = c.id + JOIN vn.postCode pc ON pc.code = a.postalCode + JOIN vn.town t ON t.id = pc.townFk AND t.provinceFk = a.provinceFk + JOIN vn.zoneGeo zg ON zg.name = a.postalCode + JOIN tmp.zoneNodes zn ON zn.geoFk = pc.geoFk + LEFT JOIN bs.clientNewBorn cnb ON cnb.clientFk = c.id + LEFT JOIN vn.annualAverageInvoiced aai ON aai.clientFk = c.id + JOIN vn.clientType ct ON ct.code = c.typeFk + WHERE a.isActive + AND c.isActive + AND ct.code = 'normal' + AND c.businessTypeFk <> 'worker' + GROUP BY c.id; + + DROP TEMPORARY TABLE tmp.zoneNodes; +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 */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `zone_getAgency` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -78986,8 +80077,7 @@ BEGIN */ DECLARE vGeoFk INT DEFAULT NULL; - DROP TEMPORARY TABLE IF EXISTS tmp.zoneNodes; - CREATE TEMPORARY TABLE tmp.zoneNodes ( + CREATE OR REPLACE TEMPORARY TABLE tmp.zoneNodes ( geoFk INT, name VARCHAR(100), parentFk INT, @@ -79000,14 +80090,14 @@ BEGIN CALL zone_getLeaves(vSelf, NULL , NULL, TRUE); - UPDATE tmp.zoneNodes zn + UPDATE tmp.zoneNodes SET isChecked = 0 WHERE parentFk IS NULL; myLoop: LOOP SET vGeoFk = NULL; SELECT geoFk INTO vGeoFk - FROM tmp.zoneNodes zn + FROM tmp.zoneNodes WHERE NOT isChecked LIMIT 1; @@ -79023,10 +80113,6 @@ BEGIN DELETE FROM tmp.zoneNodes WHERE sons > 0; - - SELECT zn.geoFk, zn.name - FROM tmp.zoneNodes zn - JOIN zone z ON z.id = zn.zoneFk; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -79997,7 +81083,7 @@ USE `pbx`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `sipConf` AS select `s`.`user_id` AS `id`,`s`.`extension` AS `name`,NULL AS `callbackextension`,`s`.`md5Secret` AS `md5secret`,`u`.`nickname` AS `callerid`,`c`.`host` AS `host`,`c`.`deny` AS `deny`,`c`.`permit` AS `permit`,`c`.`type` AS `type`,`c`.`context` AS `context`,`c`.`incomingLimit` AS `incominglimit`,`c`.`pickupGroup` AS `pickupgroup`,`c`.`careInvite` AS `careinvite`,`c`.`insecure` AS `insecure`,`c`.`transport` AS `transport`,`c`.`nat` AS `nat`,`r`.`ipAddr` AS `ipaddr`,`r`.`regSeconds` AS `regseconds`,`r`.`port` AS `port`,`r`.`defaultUser` AS `defaultuser`,`r`.`userAgent` AS `useragent`,`r`.`lastMs` AS `lastms`,`r`.`fullContact` AS `fullcontact`,`r`.`regServer` AS `regserver` from (((`pbx`.`sip` `s` join `account`.`user` `u` on(`u`.`id` = `s`.`user_id`)) left join `pbx`.`sipReg` `r` on(`s`.`user_id` = `r`.`userId`)) join `pbx`.`sipConfig` `c`) */; +/*!50001 VIEW `sipConf` AS select `s`.`user_id` AS `id`,`s`.`extension` AS `name`,`s`.`extension` AS `regexten`,NULL AS `callbackextension`,`s`.`md5Secret` AS `md5secret`,`u`.`nickname` AS `callerid`,`c`.`host` AS `host`,`c`.`deny` AS `deny`,`c`.`permit` AS `permit`,`c`.`type` AS `type`,`c`.`context` AS `context`,`c`.`incomingLimit` AS `incominglimit`,`c`.`pickupGroup` AS `pickupgroup`,`c`.`directMedia` AS `directmedia`,`c`.`insecure` AS `insecure`,`c`.`transport` AS `transport`,`c`.`nat` AS `nat`,`c`.`disallow` AS `disallow`,`c`.`allow` AS `allow`,`r`.`ipAddr` AS `ipaddr`,`r`.`regSeconds` AS `regseconds`,`r`.`port` AS `port`,`r`.`defaultUser` AS `defaultuser`,`r`.`userAgent` AS `useragent`,`r`.`lastMs` AS `lastms`,`r`.`fullContact` AS `fullcontact`,`r`.`regServer` AS `regserver` from (((`pbx`.`sip` `s` join `account`.`user` `u` on(`u`.`id` = `s`.`user_id`)) left join `pbx`.`sipReg` `r` on(`s`.`user_id` = `r`.`userId`)) join `pbx`.`sipConfig` `c`) */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -80238,12 +81324,12 @@ USE `vn`; /*!50001 SET @saved_cs_client = @@character_set_client */; /*!50001 SET @saved_cs_results = @@character_set_results */; /*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8mb4 */; -/*!50001 SET character_set_results = utf8mb4 */; -/*!50001 SET collation_connection = utf8mb4_unicode_ci */; +/*!50001 SET character_set_client = utf8mb3 */; +/*!50001 SET character_set_results = utf8mb3 */; +/*!50001 SET collation_connection = utf8mb3_general_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `awbVolume` AS select `d`.`awbFk` AS `awbFk`,`b`.`stickers` * `i`.`density` * if(`p`.`volume` > 0,`p`.`volume`,`p`.`width` * `p`.`depth` * if(`p`.`height` = 0,`i`.`size` + 10,`p`.`height`)) / (`vc`.`aerealVolumetricDensity` * 1000) AS `volume`,`b`.`id` AS `buyFk` from ((((((((`buy` `b` join `item` `i` on(`b`.`itemFk` = `i`.`id`)) join `itemType` `it` on(`i`.`typeFk` = `it`.`id`)) join `packaging` `p` on(`p`.`id` = `b`.`packageFk`)) join `entry` `e` on(`b`.`entryFk` = `e`.`id`)) join `travel` `t` on(`t`.`id` = `e`.`travelFk`)) join `duaEntry` `de` on(`de`.`entryFk` = `e`.`id`)) join `dua` `d` on(`d`.`id` = `de`.`duaFk`)) join `volumeConfig` `vc`) where `t`.`shipped` > makedate(year(`util`.`VN_CURDATE`()) - 1,1) */; +/*!50001 VIEW `awbVolume` AS select `d`.`awbFk` AS `awbFk`,`b`.`stickers` * `i`.`density` * if(`p`.`volume` > 0,`p`.`volume`,`p`.`width` * `p`.`depth` * if(`p`.`height` = 0,`i`.`size` + 10,`p`.`height`)) / (`vc`.`aerealVolumetricDensity` * 1000) AS `volume`,`b`.`id` AS `buyFk` from ((((((((`buy` `b` join `item` `i` on(`b`.`itemFk` = `i`.`id`)) join `itemType` `it` on(`i`.`typeFk` = `it`.`id`)) join `packaging` `p` on(`p`.`id` = `b`.`packagingFk`)) join `entry` `e` on(`b`.`entryFk` = `e`.`id`)) join `travel` `t` on(`t`.`id` = `e`.`travelFk`)) join `duaEntry` `de` on(`de`.`entryFk` = `e`.`id`)) join `dua` `d` on(`d`.`id` = `de`.`duaFk`)) join `volumeConfig` `vc`) where `t`.`shipped` > makedate(year(`util`.`VN_CURDATE`()) - 1,1) */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -80374,24 +81460,6 @@ USE `vn`; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; --- --- Final view structure for view `cmr_list` --- - -/*!50001 DROP VIEW IF EXISTS `cmr_list`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8mb4 */; -/*!50001 SET character_set_results = utf8mb4 */; -/*!50001 SET collation_connection = utf8mb4_unicode_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `cmr_list` AS select `cmr`.`id` AS `cmrFk`,`cmr`.`ticketFk` AS `ticketFk`,`cmr`.`truckPlate` AS `truckPlate`,`cmr`.`observations` AS `observations`,`cmr`.`senderInstruccions` AS `senderInstruccions`,`cmr`.`paymentInstruccions` AS `paymentInstruccions`,`cmr`.`specialAgreements` AS `specialAgreements`,`cmr`.`created` AS `created`,`cmr`.`packagesList` AS `packagesList`,`aTo`.`nickname` AS `clientName`,`aTo`.`postalCode` AS `clientPostalCode`,`aTo`.`street` AS `clientStreet`,`aTo`.`city` AS `clientCity`,`pTo`.`name` AS `clientProvince`,`cTo`.`country` AS `clientCountry`,`su`.`name` AS `companyName`,`su`.`street` AS `companyStreet`,`su`.`postCode` AS `companyPostCode`,`su`.`city` AS `companyCity`,`cSu`.`country` AS `companyCountry`,concat(`aFrom`.`street`,' ',`aFrom`.`postalCode`,' ',`aFrom`.`city`,' (',`cFrom`.`country`,')') AS `warehouseAddress`,`cmr`.`created` AS `shipped`,`aTo`.`nickname` AS `clientOficialName`,`cmr`.`supplierFk` AS `supplierFk`,`aSu`.`name` AS `carrierName`,`aSu`.`street` AS `carrierStreet`,`aSu`.`postCode` AS `carrierPostCode`,`aSu`.`city` AS `carrierCity`,`cAs`.`country` AS `carrierCountry`,ifnull(`aTo`.`phone`,`client`.`phone`) AS `phone`,ifnull(`aTo`.`mobile`,`client`.`mobile`) AS `mobile`,`aTo`.`id` AS `addressFk`,`c`.`stamp` AS `stamp`,`cmr`.`merchandiseDetail` AS `merchandiseDetail` from ((((((((((((`cmr` left join `address` `aTo` on(`aTo`.`id` = `cmr`.`addressToFk`)) left join `province` `pTo` on(`pTo`.`id` = `aTo`.`provinceFk`)) left join `country` `cTo` on(`cTo`.`id` = `pTo`.`countryFk`)) left join `client` on(`client`.`id` = `aTo`.`clientFk`)) left join `supplier` `su` on(`su`.`id` = `cmr`.`companyFk`)) left join `country` `cSu` on(`cSu`.`id` = `su`.`countryFk`)) left join `address` `aFrom` on(`aFrom`.`id` = `cmr`.`addressFromFk`)) left join `province` `pFrom` on(`pFrom`.`id` = `aFrom`.`provinceFk`)) left join `country` `cFrom` on(`cFrom`.`id` = `pFrom`.`countryFk`)) left join `supplier` `aSu` on(`aSu`.`id` = `cmr`.`supplierFk`)) left join `country` `cAs` on(`cAs`.`id` = `aSu`.`countryFk`)) join `company` `c` on(`c`.`id` = `cmr`.`companyFk`)) */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - -- -- Final view structure for view `companyL10n` -- @@ -81490,24 +82558,6 @@ USE `vn`; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; --- --- Final view structure for view `routesReduced` --- - -/*!50001 DROP VIEW IF EXISTS `routesReduced`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8mb4 */; -/*!50001 SET character_set_results = utf8mb4 */; -/*!50001 SET collation_connection = utf8mb4_unicode_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `routesReduced` AS select `et`.`description` AS `description`,`rm`.`name` AS `name`,`t`.`routeFk` AS `routeFk`,`et`.`eta` AS `eta`,`rm`.`bufferFk` AS `bufferFk`,`rm`.`beachFk` AS `beachFk`,`i`.`itemPackingTypeFk` AS `itempackingTypeFk` from (((((((`expeditionTruck` `et` join `routesMonitor` `rm` on(`rm`.`expeditionTruckFk` = `et`.`id`)) join `ticket` `t` on(`t`.`routeFk` = `rm`.`routeFk`)) join `ticketState` `ts` on(`ts`.`ticketFk` = `t`.`id`)) join `state` `st` on(`st`.`id` = `ts`.`stateFk`)) join `sale` `s` on(`s`.`ticketFk` = `t`.`id`)) join `item` `i` on(`i`.`id` = `s`.`itemFk`)) join `config` `c`) where `et`.`eta` > `util`.`yesterday`() group by `t`.`routeFk` order by `et`.`eta`,`t`.`routeFk` */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - -- -- Final view structure for view `saleCost` -- @@ -82165,4 +83215,4 @@ USE `vn`; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2023-08-30 15:59:19 +-- Dump completed on 2023-11-20 10:10:52 diff --git a/db/export-data.sh b/db/export-data.sh index a516992d3..97092da4f 100755 --- a/db/export-data.sh +++ b/db/export-data.sh @@ -45,12 +45,12 @@ TABLES=( alertLevel bookingPlanner businessType - cplusInvoiceType472 + siiTypeInvoiceIn siiTypeInvoiceOut cplusRectificationType cplusSubjectOp cplusTaxBreak - cplusTrascendency472 + siiTrascendencyInvoiceIn claimResponsible claimReason claimRedelivery @@ -68,6 +68,8 @@ TABLES=( volumeConfig workCenter companyI18n + workerTimeControlError + silexACL ) dump_tables ${TABLES[@]} diff --git a/loopback/locale/en.json b/loopback/locale/en.json index 949136459..ed6aa474f 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -197,5 +197,7 @@ "Booking completed": "Booking complete", "The ticket is in preparation": "The ticket [{{ticketId}}]({{{ticketUrl}}}) of the sales person {{salesPersonId}} is in preparation", "You can only add negative amounts in refund tickets": "You can only add negative amounts in refund tickets", - "Try again": "Try again" -} + "Try again": "Try again", + "keepPrice": "keepPrice", + "Cannot past travels with entries": "Cannot past travels with entries" +} \ No newline at end of file diff --git a/modules/client/back/methods/client/filter.js b/modules/client/back/methods/client/filter.js index eaf4ecf30..47d5f6d2f 100644 --- a/modules/client/back/methods/client/filter.js +++ b/modules/client/back/methods/client/filter.js @@ -82,12 +82,15 @@ module.exports = Self => { if (args.zoneFk) { let stmts = []; stmts.push(new ParameterizedSQL('CALL vn.zone_getPostalCode(?)', [args.zoneFk])); - stmts.push(`SELECT name FROM tmp.zoneNodes`); + stmts.push(` + SELECT zn.geoFk, zn.name + FROM tmp.zoneNodes zn + JOIN zone z ON z.id = zn.zoneFk`); stmts.push(`DROP TEMPORARY TABLE tmp.zoneNodes`); const sql = ParameterizedSQL.join(stmts, ';'); - const [results] = await conn.executeStmt(sql); + const results = await conn.executeStmt(sql); - for (let result of results) + for (let result of results[1]) postalCode.push(result.name); } diff --git a/modules/ticket/back/methods/ticket/specs/getSalespersonMana.spec.js b/modules/ticket/back/methods/ticket/specs/getSalespersonMana.spec.js index 6029ca4a7..12c115ff9 100644 --- a/modules/ticket/back/methods/ticket/specs/getSalespersonMana.spec.js +++ b/modules/ticket/back/methods/ticket/specs/getSalespersonMana.spec.js @@ -9,7 +9,7 @@ describe('ticket getSalesPersonMana()', () => { const mana = await models.Ticket.getSalesPersonMana(1, options); - expect(mana).toEqual(124); + expect(mana).toEqual(73); await tx.rollback(); } catch (e) { From 0a2fd9cf5de1915d897d4a5871f74f74ff988019 Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Mon, 20 Nov 2023 18:39:37 +0100 Subject: [PATCH 383/427] fix: refs #6432, #5848 account sync fixes --- .../test.js | 4 +- ...ount-synchronizer.js => account-linker.js} | 12 +- modules/account/back/models/account-config.js | 158 ++++++++---------- modules/account/back/models/ldap-config.js | 3 +- modules/account/back/models/ldap-config.json | 2 +- modules/account/back/models/role-config.js | 4 +- modules/account/back/models/role-config.json | 2 +- modules/account/back/models/samba-config.js | 3 +- modules/account/back/models/samba-config.json | 2 +- modules/account/back/models/sip-config.js | 2 +- modules/account/back/models/sip-config.json | 3 +- modules/account/front/descriptor/index.html | 3 +- 12 files changed, 96 insertions(+), 102 deletions(-) rename modules/account/back/methods/{account-synchronizer => account-linker}/test.js (59%) rename modules/account/back/mixins/{account-synchronizer.js => account-linker.js} (85%) diff --git a/modules/account/back/methods/account-synchronizer/test.js b/modules/account/back/methods/account-linker/test.js similarity index 59% rename from modules/account/back/methods/account-synchronizer/test.js rename to modules/account/back/methods/account-linker/test.js index a77940168..990af2df8 100644 --- a/modules/account/back/methods/account-synchronizer/test.js +++ b/modules/account/back/methods/account-linker/test.js @@ -1,3 +1,4 @@ +const NotFoundError = require('vn-loopback/util/not-found-error'); module.exports = Self => { Self.remoteMethod('test', { @@ -9,7 +10,8 @@ module.exports = Self => { }); Self.test = async function() { - let connector = await Self.getSynchronizer(); + const connector = await Self.getLinker(); + if (!connector) throw new NotFoundError('Linker not configured'); await connector.test(); }; }; diff --git a/modules/account/back/mixins/account-synchronizer.js b/modules/account/back/mixins/account-linker.js similarity index 85% rename from modules/account/back/mixins/account-synchronizer.js rename to modules/account/back/mixins/account-linker.js index 8ba8bfe9d..c882d0893 100644 --- a/modules/account/back/mixins/account-synchronizer.js +++ b/modules/account/back/mixins/account-linker.js @@ -3,14 +3,14 @@ const app = require('vn-loopback/server/server'); const UserError = require('vn-loopback/util/user-error'); module.exports = function(Self, options) { - require('../methods/account-synchronizer/test')(Self); + require('../methods/account-linker/test')(Self); Self.once('attached', function() { - app.models.AccountConfig.addSynchronizer(Self); + app.models.AccountConfig.addLinker(Self); }); /** - * Mixin for user synchronizers. + * Mixin for account linkers. * * @property {Array} $ * @property {Object} accountConfig @@ -18,12 +18,12 @@ module.exports = function(Self, options) { */ let Mixin = { /** - * Initalizes the synchronizer. + * Initalizes the linker. */ async init() {}, /** - * Deinitalizes the synchronizer. + * Deinitalizes the linker. */ async deinit() {}, @@ -57,7 +57,7 @@ module.exports = function(Self, options) { async syncRoles() {}, /** - * Tests synchronizer configuration. + * Tests linker configuration. */ async test() { try { diff --git a/modules/account/back/models/account-config.js b/modules/account/back/models/account-config.js index 0db699b99..2cc6b240d 100644 --- a/modules/account/back/models/account-config.js +++ b/modules/account/back/models/account-config.js @@ -3,94 +3,85 @@ const models = require('vn-loopback/server/server').models; module.exports = Self => { Object.assign(Self, { - synchronizers: [], + linkers: [], - addSynchronizer(synchronizer) { - this.synchronizers.push(synchronizer); + addLinker(linker) { + this.linkers.push(linker); }, - async getInstance() { - let instance = await Self.findOne({ + async initEngine() { + const accountConfig = await Self.findOne({ fields: ['homedir', 'shell', 'idBase'] }); - await instance.synchronizerInit(); - return instance; + const mailConfig = await models.MailConfig.findOne({ + fields: ['domain'] + }); + + const linkers = []; + + for (const Linker of Self.linkers) { + const linker = await Linker.getLinker(); + if (!linker) continue; + Object.assign(linker, {accountConfig}); + await linker.init(); + linkers.push(linker); + } + + Object.assign(accountConfig, { + linkers, + domain: mailConfig.domain + }); + + return { + accountConfig, + linkers + }; + }, + + async deinitEngine(engine) { + for (const linker of engine.linkers) + await linker.deinit(); + }, + + async syncUser(userName, password) { + const engine = await Self.initEngine(); + try { + await Self.syncUserBase(engine, userName, password, true); + } finally { + await Self.deinitEngine(engine); + } }, async syncUsers() { - let instance = await Self.getInstance(); + const engine = await Self.initEngine(); + + let usersToSync = new Set(); + for (const linker of engine.linkers) + await linker.getUsers(usersToSync); - let usersToSync = await instance.synchronizerGetUsers(); usersToSync = Array.from(usersToSync.values()) .sort((a, b) => a.localeCompare(b)); for (let userName of usersToSync) { try { + // eslint-disable-next-line no-console console.log(`Synchronizing user '${userName}'`); - await instance.synchronizerSyncUser(userName); + + await Self.syncUserBase(engine, userName); + + // eslint-disable-next-line no-console console.log(` -> User '${userName}' sinchronized`); } catch (err) { + // eslint-disable-next-line no-console console.error(` -> User '${userName}' synchronization error:`, err.message); } } - await instance.synchronizerDeinit(); + await Self.deinitEngine(engine); await Self.syncRoles(); }, - async syncUser(userName, password) { - let instance = await Self.getInstance(); - try { - await instance.synchronizerSyncUser(userName, password, true); - } finally { - await instance.synchronizerDeinit(); - } - }, - - async syncRoles() { - let instance = await Self.getInstance(); - try { - await instance.synchronizerSyncRoles(); - } finally { - await instance.synchronizerDeinit(); - } - }, - - async getSynchronizer() { - return await Self.findOne(); - } - }); - - Object.assign(Self.prototype, { - async synchronizerInit() { - let mailConfig = await models.MailConfig.findOne({ - fields: ['domain'] - }); - - let synchronizers = []; - - for (let Synchronizer of Self.synchronizers) { - let synchronizer = await Synchronizer.getSynchronizer(); - if (!synchronizer) continue; - Object.assign(synchronizer, { - accountConfig: this - }); - await synchronizer.init(); - synchronizers.push(synchronizer); - } - - Object.assign(this, { - synchronizers, - domain: mailConfig.domain - }); - }, - - async synchronizerDeinit() { - for (let synchronizer of this.synchronizers) - await synchronizer.deinit(); - }, - - async synchronizerSyncUser(userName, password, syncGroups) { + async syncUserBase(engine, userName, password, syncGroups) { if (!userName) return; userName = userName.toLowerCase(); @@ -98,7 +89,7 @@ module.exports = Self => { if (['administrator', 'root'].indexOf(userName) >= 0) return; - let user = await models.VnUser.findOne({ + const user = await models.VnUser.findOne({ where: {name: userName}, fields: [ 'id', @@ -130,27 +121,28 @@ module.exports = Self => { ] }); - let info = { + const info = { user, hasAccount: false }; if (user) { - let exists = await models.Account.exists(user.id); + const exists = await models.Account.exists(user.id); + const {accountConfig} = engine; Object.assign(info, { hasAccount: user.active && exists, - corporateMail: `${userName}@${this.domain}`, - uidNumber: this.idBase + user.id + corporateMail: `${userName}@${accountConfig.domain}`, + uidNumber: accountConfig.idBase + user.id }); } - let errs = []; + const errs = []; - for (let synchronizer of this.synchronizers) { + for (const linker of engine.linkers) { try { - await synchronizer.syncUser(userName, info, password); + await linker.syncUser(userName, info, password); if (syncGroups) - await synchronizer.syncUserGroups(userName, info); + await linker.syncUserGroups(userName, info); } catch (err) { errs.push(err); } @@ -159,18 +151,16 @@ module.exports = Self => { if (errs.length) throw errs[0]; }, - async synchronizerGetUsers() { - let usersToSync = new Set(); + async syncRoles() { + const engine = await Self.initEngine(); + try { + await Self.rawSql(`CALL account.role_sync`); - for (let synchronizer of this.synchronizers) - await synchronizer.getUsers(usersToSync); - - return usersToSync; - }, - - async synchronizerSyncRoles() { - for (let synchronizer of this.synchronizers) - await synchronizer.syncRoles(); + for (const linker of engine.linkers) + await linker.syncRoles(); + } finally { + await Self.deinitEngine(engine); + } } }); }; diff --git a/modules/account/back/models/ldap-config.js b/modules/account/back/models/ldap-config.js index 9dcc4136d..b557d243c 100644 --- a/modules/account/back/models/ldap-config.js +++ b/modules/account/back/models/ldap-config.js @@ -7,7 +7,7 @@ const nthash = require('smbhash').nthash; module.exports = Self => { const shouldSync = process.env.NODE_ENV !== 'test'; - Self.getSynchronizer = async function() { + Self.getLinker = async function() { return await Self.findOne({ fields: [ 'server', @@ -24,6 +24,7 @@ module.exports = Self => { this.client = ldap.createClient({ url: this.server }); + this.client.on('error', () => {}); await this.client.bind(this.rdn, this.password); }, diff --git a/modules/account/back/models/ldap-config.json b/modules/account/back/models/ldap-config.json index 2fd5aa901..d4d3a094d 100644 --- a/modules/account/back/models/ldap-config.json +++ b/modules/account/back/models/ldap-config.json @@ -7,7 +7,7 @@ } }, "mixins": { - "AccountSynchronizer": {} + "AccountLinker": {} }, "properties": { "id": { diff --git a/modules/account/back/models/role-config.js b/modules/account/back/models/role-config.js index b90ef75fb..d6c57b70b 100644 --- a/modules/account/back/models/role-config.js +++ b/modules/account/back/models/role-config.js @@ -1,6 +1,6 @@ module.exports = Self => { - Self.getSynchronizer = async function() { + Self.getLinker = async function() { let NODE_ENV = process.env.NODE_ENV; if (!NODE_ENV || NODE_ENV == 'development') return null; @@ -45,6 +45,7 @@ module.exports = Self => { } if (!isUpdatable) { + // eslint-disable-next-line no-console console.warn(`RoleConfig.syncUser(): User '${userName}' cannot be updated, not managed by me`); return; } @@ -82,6 +83,7 @@ module.exports = Self => { [mysqlUser, this.userHost]); } catch (err) { if (err.code == 'ER_REVOKE_GRANTS') + // eslint-disable-next-line no-console console.warn(`${err.code}: ${err.sqlMessage}: ${err.sql}`); else throw err; diff --git a/modules/account/back/models/role-config.json b/modules/account/back/models/role-config.json index f4138bea8..3b843eaea 100644 --- a/modules/account/back/models/role-config.json +++ b/modules/account/back/models/role-config.json @@ -7,7 +7,7 @@ } }, "mixins": { - "AccountSynchronizer": {} + "AccountLinker": {} }, "properties": { "id": { diff --git a/modules/account/back/models/samba-config.js b/modules/account/back/models/samba-config.js index 7714fb01c..f5672ca21 100644 --- a/modules/account/back/models/samba-config.js +++ b/modules/account/back/models/samba-config.js @@ -13,7 +13,7 @@ const UserAccountControlFlags = { module.exports = Self => { const shouldSync = process.env.NODE_ENV !== 'test'; - Self.getSynchronizer = async function() { + Self.getLinker = async function() { return await Self.findOne({ fields: [ 'host', @@ -39,6 +39,7 @@ module.exports = Self => { url: `ldaps://${this.adController}:636`, tlsOptions: {rejectUnauthorized: this.verifyCert} }); + adClient.on('error', () => {}); await adClient.bind(bindDn, this.adPassword); Object.assign(this, { adClient, diff --git a/modules/account/back/models/samba-config.json b/modules/account/back/models/samba-config.json index 28cbb2689..4c9e0a794 100644 --- a/modules/account/back/models/samba-config.json +++ b/modules/account/back/models/samba-config.json @@ -7,7 +7,7 @@ } }, "mixins": { - "AccountSynchronizer": {} + "AccountLinker": {} }, "properties": { "id": { diff --git a/modules/account/back/models/sip-config.js b/modules/account/back/models/sip-config.js index 3b5cb2dbb..703783337 100644 --- a/modules/account/back/models/sip-config.js +++ b/modules/account/back/models/sip-config.js @@ -2,7 +2,7 @@ const app = require('vn-loopback/server/server'); module.exports = Self => { - Self.getSynchronizer = async function() { + Self.getLinker = async function() { return await Self.findOne({fields: ['id']}); }; diff --git a/modules/account/back/models/sip-config.json b/modules/account/back/models/sip-config.json index 6c5ba3db3..a25d09c67 100644 --- a/modules/account/back/models/sip-config.json +++ b/modules/account/back/models/sip-config.json @@ -7,7 +7,7 @@ } }, "mixins": { - "AccountSynchronizer": {} + "AccountLinker": {} }, "properties": { "id": { @@ -16,4 +16,3 @@ } } } - \ No newline at end of file diff --git a/modules/account/front/descriptor/index.html b/modules/account/front/descriptor/index.html index b0a70edd1..86e78dfce 100644 --- a/modules/account/front/descriptor/index.html +++ b/modules/account/front/descriptor/index.html @@ -68,7 +68,6 @@ Deactivate user - + Do you want to synchronize user? From fc653746f0d5e6e0769b1ffa335ca447549f96a8 Mon Sep 17 00:00:00 2001 From: pablone Date: Tue, 21 Nov 2023 07:54:25 +0100 Subject: [PATCH 384/427] remove(barcode): refs #5228 remove barcode from report --- .../expedition-pallet-label/assets/css/style.css | 3 --- .../expedition-pallet-label.html | 1 - .../expedition-pallet-label.js | 14 -------------- 3 files changed, 18 deletions(-) diff --git a/print/templates/reports/expedition-pallet-label/assets/css/style.css b/print/templates/reports/expedition-pallet-label/assets/css/style.css index bd7366486..178ce79d2 100644 --- a/print/templates/reports/expedition-pallet-label/assets/css/style.css +++ b/print/templates/reports/expedition-pallet-label/assets/css/style.css @@ -56,9 +56,6 @@ html { margin-left: 35px; float:left; } -#barcode{ - text-align: center; -} #right { float: right; margin-top: 20px; diff --git a/print/templates/reports/expedition-pallet-label/expedition-pallet-label.html b/print/templates/reports/expedition-pallet-label/expedition-pallet-label.html index 0cb25613e..a34755f91 100644 --- a/print/templates/reports/expedition-pallet-label/expedition-pallet-label.html +++ b/print/templates/reports/expedition-pallet-label/expedition-pallet-label.html @@ -9,7 +9,6 @@ -
diff --git a/print/templates/reports/expedition-pallet-label/expedition-pallet-label.js b/print/templates/reports/expedition-pallet-label/expedition-pallet-label.js index bcd90418f..00f1f8ba1 100644 --- a/print/templates/reports/expedition-pallet-label/expedition-pallet-label.js +++ b/print/templates/reports/expedition-pallet-label/expedition-pallet-label.js @@ -39,19 +39,5 @@ module.exports = { const data = String(id); return qrcode.toDataURL(data, {margin: 0}); }, - getBarcode(id) { - const xmlSerializer = new XMLSerializer(); - const document = new DOMImplementation().createDocument('http://www.w3.org/1999/xhtml', 'html', null); - const svgNode = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); - - jsBarcode(svgNode, id, { - xmlDocument: document, - format: 'code128', - displayValue: false, - width: 6, - height: 90, - }); - return xmlSerializer.serializeToString(svgNode); - }, }, }; From dd11cf53273e6f52e0d27c37afe2ed61a23adcb5 Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 21 Nov 2023 09:03:25 +0100 Subject: [PATCH 385/427] ref #5835 fix test --- .../back/methods/invoice-in-due-day/specs/new.spec.js | 6 ------ 1 file changed, 6 deletions(-) diff --git a/modules/invoiceIn/back/methods/invoice-in-due-day/specs/new.spec.js b/modules/invoiceIn/back/methods/invoice-in-due-day/specs/new.spec.js index f2f04b993..c188a511d 100644 --- a/modules/invoiceIn/back/methods/invoice-in-due-day/specs/new.spec.js +++ b/modules/invoiceIn/back/methods/invoice-in-due-day/specs/new.spec.js @@ -5,11 +5,6 @@ describe('invoiceInDueDay new()', () => { beforeAll(async() => { const activeCtx = { accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } }; spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ active: activeCtx @@ -24,7 +19,6 @@ describe('invoiceInDueDay new()', () => { req: { accessToken: {userId: userId}, - headers: {origin: 'http://localhost:5000'}, } }; From bf7c67dbdeb595594beff1977a6374f0d8a5009d Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Tue, 21 Nov 2023 09:26:02 +0100 Subject: [PATCH 386/427] fix: refs #6197 add definer to events --- modules/account/back/models/role-inherit.js | 2 +- modules/zone/back/models/zone-closure.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/account/back/models/role-inherit.js b/modules/account/back/models/role-inherit.js index 7d31e62b1..e994f844e 100644 --- a/modules/account/back/models/role-inherit.js +++ b/modules/account/back/models/role-inherit.js @@ -9,7 +9,7 @@ module.exports = Self => { Self.observe(hook, async() => { try { await Self.rawSql(` - CREATE EVENT account.role_sync + CREATE DEFINER = CURRENT_ROLE EVENT account.role_sync ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 5 SECOND DO CALL role_sync; `); diff --git a/modules/zone/back/models/zone-closure.js b/modules/zone/back/models/zone-closure.js index d25d6f707..61350ef56 100644 --- a/modules/zone/back/models/zone-closure.js +++ b/modules/zone/back/models/zone-closure.js @@ -14,7 +14,7 @@ module.exports = Self => { async function doCalc(ctx) { try { await Self.rawSql(` - CREATE EVENT zoneClosure_doRecalc + CREATE DEFINER = CURRENT_ROLE EVENT zoneClosure_doRecalc ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 15 SECOND DO CALL zoneClosure_recalc; `); From 02e8b909262ba5c94f04a99c150807d8033d90a2 Mon Sep 17 00:00:00 2001 From: alexm Date: Tue, 21 Nov 2023 10:12:07 +0100 Subject: [PATCH 387/427] refs #6454 test: fix e2e by dump --- e2e/helpers/selectors.js | 1 + .../10-travel/02_basic_data_and_log.spec.js | 21 +++++++- e2e/paths/14-account/06_accounts.spec.js | 12 ----- e2e/paths/14-account/08_samba.spec.js | 5 +- loopback/locale/es.json | 3 +- .../back/methods/ticket/specs/addSale.spec.js | 54 ++++++++----------- modules/travel/front/search-panel/index.js | 13 +---- 7 files changed, 50 insertions(+), 59 deletions(-) diff --git a/e2e/helpers/selectors.js b/e2e/helpers/selectors.js index b5dbd42ac..acd13800b 100644 --- a/e2e/helpers/selectors.js +++ b/e2e/helpers/selectors.js @@ -145,6 +145,7 @@ export default { adController: 'vn-account-samba vn-textfield[ng-model="$ctrl.config.adController"]', adUser: 'vn-account-samba vn-textfield[ng-model="$ctrl.config.adUser"]', adPassword: 'vn-account-samba vn-textfield[ng-model="$ctrl.config.adPassword"]', + userDn: 'vn-account-samba vn-textfield[ng-model="$ctrl.config.userDn"]', verifyCert: 'vn-account-samba vn-check[ng-model="$ctrl.config.verifyCert"]', save: 'vn-account-samba vn-submit' }, diff --git a/e2e/paths/10-travel/02_basic_data_and_log.spec.js b/e2e/paths/10-travel/02_basic_data_and_log.spec.js index 5abf8a65e..0079e8023 100644 --- a/e2e/paths/10-travel/02_basic_data_and_log.spec.js +++ b/e2e/paths/10-travel/02_basic_data_and_log.spec.js @@ -22,7 +22,7 @@ describe('Travel basic data path', () => { await page.waitForState('travel.card.basicData'); }); - it('should set a wrong delivery date then receive an error on submit', async() => { + it('should throw error if try move a travel with entries', async() => { const lastMonth = Date.vnNew(); lastMonth.setMonth(lastMonth.getMonth() - 1); @@ -30,6 +30,23 @@ describe('Travel basic data path', () => { await page.waitToClick(selectors.travelBasicData.save); const message = await page.waitForSnackbar(); + expect(message.text).toContain('Cannot past travels with entries'); + }); + + it('should set a wrong delivery date then receive an error on submit', async() => { + await page.loginAndModule('buyer', 'travel'); + await page.write(selectors.travelIndex.generalSearchFilter, '4'); + await page.keyboard.press('Enter'); + await page.accessToSection('travel.card.basicData'); + await page.waitForState('travel.card.basicData'); + + const lastMonth = Date.vnNew(); + lastMonth.setMonth(lastMonth.getMonth() - 2); + + await page.pickDate(selectors.travelBasicData.deliveryDate, lastMonth); + await page.waitToClick(selectors.travelBasicData.save); + const message = await page.waitForSnackbar(); + expect(message.text).toContain('Landing cannot be lesser than shipment'); }); @@ -39,7 +56,7 @@ describe('Travel basic data path', () => { await page.waitToClick(selectors.travelBasicData.undoChanges); const result = await page.waitToGetProperty(selectors.travelBasicData.reference, 'value'); - expect(result).toEqual('third travel'); + expect(result).toEqual('fourth travel'); }); it('should now edit the whole form then save', async() => { diff --git a/e2e/paths/14-account/06_accounts.spec.js b/e2e/paths/14-account/06_accounts.spec.js index 83893e0cf..8bd6ea7d5 100644 --- a/e2e/paths/14-account/06_accounts.spec.js +++ b/e2e/paths/14-account/06_accounts.spec.js @@ -23,18 +23,6 @@ describe('Account Accounts path', () => { expect(message.text).toContain('Roles synchronized!'); }); - it('should sync user', async() => { - await page.waitToClick(selectors.accountAccounts.syncUser); - await page.write(selectors.accountAccounts.syncUserName, 'sysadmin'); - await page.write(selectors.accountAccounts.syncUserPassword, 'nightmare'); - - await page.waitToClick(selectors.accountAccounts.buttonAccept); - - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('User synchronized!'); - }); - it('should relogin', async() => { await page.loginAndModule('sysadmin', 'account'); await page.accessToSection('account.accounts'); diff --git a/e2e/paths/14-account/08_samba.spec.js b/e2e/paths/14-account/08_samba.spec.js index 6e7ef9bbf..a92344acb 100644 --- a/e2e/paths/14-account/08_samba.spec.js +++ b/e2e/paths/14-account/08_samba.spec.js @@ -20,8 +20,9 @@ describe('Account Samba path', () => { await page.waitToClick(selectors.accountSamba.checkEnable); await page.write(selectors.accountSamba.adDomain, '1234'); await page.write(selectors.accountSamba.adController, '1234'); - await page.write(selectors.accountSamba.adUser, 'nightmare'); - await page.write(selectors.accountSamba.adPassword, 'sysadmin'); + await page.write(selectors.accountSamba.adUser, 'sysadmin'); + await page.write(selectors.accountSamba.adPassword, 'nightmare'); + await page.write(selectors.accountSamba.userDn, 'testDn'); await page.waitToClick(selectors.accountSamba.verifyCert); await page.waitToClick(selectors.accountSamba.save); diff --git a/loopback/locale/es.json b/loopback/locale/es.json index a4de6f997..41acc36c3 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -327,5 +327,6 @@ "The notification subscription of this worker cant be modified": "La subscripción a la notificación de este trabajador no puede ser modificada", "User disabled": "Usuario desactivado", "The amount cannot be less than the minimum": "La cantidad no puede ser menor que la cantidad mínima", - "quantityLessThanMin": "La cantidad no puede ser menor que la cantidad mínima" + "quantityLessThanMin": "La cantidad no puede ser menor que la cantidad mínima", + "Cannot past travels with entries": "No se pueden pasar envíos con entradas" } diff --git a/modules/ticket/back/methods/ticket/specs/addSale.spec.js b/modules/ticket/back/methods/ticket/specs/addSale.spec.js index b1ecb133b..8c0e39bec 100644 --- a/modules/ticket/back/methods/ticket/specs/addSale.spec.js +++ b/modules/ticket/back/methods/ticket/specs/addSale.spec.js @@ -3,33 +3,30 @@ const LoopBackContext = require('loopback-context'); describe('ticket addSale()', () => { const ticketId = 13; - beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, + function getActiveCtx(userId) { + return { + accessToken: {userId}, http: { req: { - headers: {origin: 'http://localhost'} + accessToken: {userId}, + headers: {origin: 'http://localhost'}, + __: () => {} } } }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + } it('should create a new sale for the ticket with id 13', async() => { const tx = await models.Ticket.beginTransaction({}); + const activeCtx = getActiveCtx(9); + const ctx = activeCtx.http; + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ + active: activeCtx + }); try { const options = {transaction: tx}; - const ctx = { - req: { - accessToken: {userId: 9}, - headers: {origin: 'localhost:5000'}, - __: () => {} - } - }; const itemId = 4; const quantity = 10; const newSale = await models.Ticket.addSale(ctx, ticketId, itemId, quantity, options); @@ -45,19 +42,16 @@ describe('ticket addSale()', () => { it('should not be able to add a sale if the item quantity is not available', async() => { const tx = await models.Ticket.beginTransaction({}); + const activeCtx = getActiveCtx(18); + const ctx = activeCtx.http; + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ + active: activeCtx + }); let error; - try { const options = {transaction: tx}; - const ctx = { - req: { - accessToken: {userId: 9}, - headers: {origin: 'localhost:5000'}, - __: () => {} - } - }; const itemId = 11; const quantity = 10; @@ -74,18 +68,16 @@ describe('ticket addSale()', () => { it('should not be able to add a sale if the ticket is not editable', async() => { const tx = await models.Ticket.beginTransaction({}); + const activeCtx = getActiveCtx(9); + const ctx = activeCtx.http; + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ + active: activeCtx + }); let error; - try { const options = {transaction: tx}; - const ctx = { - req: { - accessToken: {userId: 9}, - headers: {origin: 'localhost:5000'}, - __: () => {} - } - }; + const notEditableTicketId = 1; const itemId = 4; const quantity = 10; diff --git a/modules/travel/front/search-panel/index.js b/modules/travel/front/search-panel/index.js index f53c15ca8..5969a8c3f 100644 --- a/modules/travel/front/search-panel/index.js +++ b/modules/travel/front/search-panel/index.js @@ -37,17 +37,8 @@ class Controller extends SearchPanel { } applyFilters(param) { - if (typeof this.filter.scopeDays === 'number') { - const today = Date.vnNew(); - const shippedFrom = new Date(today.getTime()); - shippedFrom.setDate(today.getDate() - 30); - shippedFrom.setHours(0, 0, 0, 0); - - const shippedTo = new Date(today.getTime()); - shippedTo.setDate(shippedTo.getDate() + this.filter.scopeDays); - shippedTo.setHours(23, 59, 59, 999); - Object.assign(this.filter, {shippedFrom, shippedTo}); - } + if (this.filter?.search) + delete this.filter.scopeDays; this.model.applyFilter({}, this.filter) .then(() => { From 707173d6184c9f7dbe663d69e3dd2e2fb4042c79 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Wed, 22 Nov 2023 07:04:33 +0100 Subject: [PATCH 388/427] refs #5890 fix: getTickets --- back/methods/collection/getTickets.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/back/methods/collection/getTickets.js b/back/methods/collection/getTickets.js index f04822697..cfd404beb 100644 --- a/back/methods/collection/getTickets.js +++ b/back/methods/collection/getTickets.js @@ -74,8 +74,8 @@ module.exports = Self => { LEFT JOIN parking p ON p.id = sh.parkingFk LEFT JOIN itemColor ic ON ic.itemFk = s.itemFk LEFT JOIN origin o ON o.id = i.originFk - WHERE tc.collectionFk = ? - GROUP BY ish.id, p.code, p2.code + WHERE tc.collectionFk = ? AND iss.quantity IS NOT NULL + GROUP BY s.id, ish.id, p.code, p2.code ORDER BY pickingOrder;`, [id], myOptions); if (print) From a27bb53089eb6913b2ffbd14dc6c296be1ac6dee Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 22 Nov 2023 08:57:45 +0100 Subject: [PATCH 389/427] refs #5835 getTotals fixed --- .../back/methods/invoice-in/getTotals.js | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/modules/invoiceIn/back/methods/invoice-in/getTotals.js b/modules/invoiceIn/back/methods/invoice-in/getTotals.js index f35c10617..4c45284d5 100644 --- a/modules/invoiceIn/back/methods/invoice-in/getTotals.js +++ b/modules/invoiceIn/back/methods/invoice-in/getTotals.js @@ -29,15 +29,18 @@ module.exports = Self => { SELECT iit.*, SUM(iidd.amount) totalDueDay FROM vn.invoiceIn ii - LEFT JOIN (SELECT SUM(iit.taxableBase) totalTaxableBase, - CAST(SUM(iit.taxableBase * (1 + (ti.PorcentajeIva / 100))) AS DECIMAL(10,2)) totalVat + LEFT JOIN ( + SELECT SUM(iit.taxableBase) totalTaxableBase, + CAST( + SUM(COALESCE(iit.taxableBase * (1 + (ti.PorcentajeIva / 100)), iit.taxableBase)) + AS DECIMAL(10, 2) + ) totalVat FROM vn.invoiceInTax iit LEFT JOIN sage.TiposIva ti ON ti.CodigoIva = iit.taxTypeSageFk - WHERE iit.invoiceInFk = ?) iit ON TRUE + WHERE iit.invoiceInFk = ? + ) iit ON TRUE LEFT JOIN vn.invoiceInDueDay iidd ON iidd.invoiceInFk = ii.id - WHERE - ii.id = ?`, [id, id]); - + WHERE ii.id = ?`, [id, id]); return result; }; }; From e856de0cfd8681f05b1639d003074545f38f9f39 Mon Sep 17 00:00:00 2001 From: jgallego Date: Wed, 22 Nov 2023 15:54:38 +0100 Subject: [PATCH 390/427] feat: refs #6028 test --- .../00-getRoutesByWorker.sql | 4 -- .../client/specs/getRoutesByWorker.spec.js | 19 ------ modules/route/back/methods/route/filter.js | 6 +- .../route/back/methods/route/getByWorker.js | 66 +++++++++++++++++++ .../back/methods/route/getRoutesByWorker.js | 48 -------------- .../methods/route/specs/getByWorker.spec.js | 39 +++++++++++ modules/route/back/models/route.js | 2 +- 7 files changed, 110 insertions(+), 74 deletions(-) rename db/changes/{233001 => 234801}/00-getRoutesByWorker.sql (71%) delete mode 100644 modules/client/back/methods/client/specs/getRoutesByWorker.spec.js create mode 100644 modules/route/back/methods/route/getByWorker.js delete mode 100644 modules/route/back/methods/route/getRoutesByWorker.js create mode 100644 modules/route/back/methods/route/specs/getByWorker.spec.js diff --git a/db/changes/233001/00-getRoutesByWorker.sql b/db/changes/234801/00-getRoutesByWorker.sql similarity index 71% rename from db/changes/233001/00-getRoutesByWorker.sql rename to db/changes/234801/00-getRoutesByWorker.sql index aa612d48e..bdc4a246e 100644 --- a/db/changes/233001/00-getRoutesByWorker.sql +++ b/db/changes/234801/00-getRoutesByWorker.sql @@ -18,7 +18,3 @@ INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `pri ('Route', 'insertTicket', 'WRITE', 'ALLOW', 'ROLE', 'employee'), ('Route', 'getDeliveryPoint', 'READ', 'ALLOW', 'ROLE', 'deliveryBoss'), ('Route', 'summary', 'READ', 'ALLOW', 'ROLE', 'employee'); - - -INSERT INTO salix.AccessToken (id, ttl, scopes, created, userId, outdated) VALUES('1z0GILWTs8huKrJGp7Fj0PvHaGA8Gg9DTNhm6nn6AfhkNJygeVUHMZKOGfMPp0xO', 1209600, NULL, '2023-07-17 13:34:10', 56, '2023-07-31 13:34:10'); -INSERT INTO salix.AccessToken (id, ttl, scopes, created, userId, outdated) VALUES('1z0GILWTs8huKrJGp7Fj0PvHaGA8Gg9DTNhm6nn6AfhkNJygeVUHMZKOGfMPp0xP', 1209600, NULL, '2023-07-17 13:34:10', 57, '2023-07-31 13:34:10'); diff --git a/modules/client/back/methods/client/specs/getRoutesByWorker.spec.js b/modules/client/back/methods/client/specs/getRoutesByWorker.spec.js deleted file mode 100644 index b43fe49d2..000000000 --- a/modules/client/back/methods/client/specs/getRoutesByWorker.spec.js +++ /dev/null @@ -1,19 +0,0 @@ -const {models} = require('vn-loopback/server/server'); - -describe('getRoutesByWorker', () => { - fit('should return the routes of the worker can view all routes', async() => { - const deliveryBossId = 57; - const ctx = {req: {accessToken: {userId: deliveryBossId}}}; - const result = await models.Route.getRoutesByWorker(ctx); - - expect(result.length).toEqual(7); - }); - - fit('should return the routes of the worker can not view all routes', async() => { - const deliveryId = 56; - const ctx = {req: {accessToken: {userId: deliveryId}}}; - const result = await models.Route.getRoutesByWorker(ctx); - - expect(result.length).toEqual(5); - }); -}); diff --git a/modules/route/back/methods/route/filter.js b/modules/route/back/methods/route/filter.js index fc35e979f..afefa77d1 100644 --- a/modules/route/back/methods/route/filter.js +++ b/modules/route/back/methods/route/filter.js @@ -105,7 +105,7 @@ module.exports = Self => { } }); - filter = mergeFilters(ctx.args.filter, {where}); + filter = mergeFilters(filter, {where}); let stmts = []; let stmt; @@ -129,9 +129,11 @@ module.exports = Self => { r.description, am.name agencyName, u.name AS workerUserName, - v.numberPlate AS vehiclePlateNumber + v.numberPlate AS vehiclePlateNumber, + Date_format(r.time, '%H:%i') hour FROM route r LEFT JOIN agencyMode am ON am.id = r.agencyModeFk + LEFT JOIN agency a ON a.id = am.agencyFk LEFT JOIN vehicle v ON v.id = r.vehicleFk LEFT JOIN worker w ON w.id = r.workerFk LEFT JOIN account.user u ON u.id = w.id` diff --git a/modules/route/back/methods/route/getByWorker.js b/modules/route/back/methods/route/getByWorker.js new file mode 100644 index 000000000..2f8a286e6 --- /dev/null +++ b/modules/route/back/methods/route/getByWorker.js @@ -0,0 +1,66 @@ +const mergeFilters = require('vn-loopback/util/filter').mergeFilters; + +module.exports = Self => { + Self.remoteMethodCtx('getByWorker', { + description: 'Return the routes by worker', + accessType: 'READ', + returns: { + type: ['object'], + root: true + }, + http: { + path: `/getByWorker`, + verb: 'GET' + } + }); + + Self.getByWorker = async ctx => { + const models = Self.app.models; + const userId = ctx.req.accessToken.userId; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const canViewAll = await models.ACL.checkAccessAcl(ctx, 'Route', 'canViewAllRoute', 'READ'); + let filterGrant = {}; + console.log(userId); + console.log(canViewAll); + if (canViewAll) { + const userConfig = await models.UserConfig.getUserConfig(ctx, myOptions); + filterGrant = { + where: {'a.warehouseFk': userConfig.warehouseFk} + }; + } else { + filterGrant = { + where: {'r.workerFk': userId} + }; + } + + const currentDate = Date.vnNew(); + currentDate.setHours(0, 0, 0, 0); + const nextDay = Date.vnNew(); + nextDay.setDate(currentDate.getDate() + 1); + + const filter = { + where: { + and: [ + { + or: [ + {'r.created': currentDate}, + {'r.created': nextDay} + ] + } + ] + }, + order: [ + 'r.created ASC', + 'r.time ASC', + 'am.name ASC' + ] + }; + + const result = await Self.filter(ctx, mergeFilters(filter, filterGrant)); + return result; + }; +}; diff --git a/modules/route/back/methods/route/getRoutesByWorker.js b/modules/route/back/methods/route/getRoutesByWorker.js deleted file mode 100644 index 0a6f59816..000000000 --- a/modules/route/back/methods/route/getRoutesByWorker.js +++ /dev/null @@ -1,48 +0,0 @@ -module.exports = Self => { - Self.remoteMethodCtx('getRoutesByWorker', { - description: 'Return the routes by worker', - accessType: 'READ', - returns: { - type: 'object', - root: true - }, - http: { - path: `/get-routes-by-worker`, - verb: 'GET' - } - }); - - Self.getRoutesByWorker = async(ctx, options) => { - const userId = ctx.req.accessToken.userId; - const myOptions = {}; - - if (typeof options == 'object') - Object.assign(myOptions, options); - - const canViewAll = await Self.app.models.ACL.checkAccessAcl(ctx, 'Route', 'canViewAllRoute', 'READ'); - const condition = canViewAll ? `ay.warehouseFK = uc.warehouseFk` : `r.workerFk = ${userId}`; - - return Self.rawSql(` - SELECT concat(w.firstName , ' ', w.lastName) driver, - r.id, - Date_format(r.time, '%H:%i') hour, - r.created, - r.m3, - v.numberPlate, - a.name, - r.kmStart, - r.kmEnd, - r.started, - r.finished - FROM vn.route r - JOIN vn.vehicle v ON r.vehicleFk = v.id - JOIN vn.agencyMode a ON r.agencyModeFk = a.id - JOIN vn.agency ay ON a.agencyFk = ay.id - JOIN vn.worker w ON r.workerFk = w.id - LEFT JOIN vn.userConfig uc ON uc.userFk = ? - WHERE (r.created = util.VN_CURDATE() OR r.created = TIMESTAMPADD(day, 1, util.VN_CURDATE())) - AND ${condition} - ORDER BY r.created ASC, r.time ASC, a.name ASC - `, [userId], myOptions); - }; -}; diff --git a/modules/route/back/methods/route/specs/getByWorker.spec.js b/modules/route/back/methods/route/specs/getByWorker.spec.js new file mode 100644 index 000000000..52b8d6d87 --- /dev/null +++ b/modules/route/back/methods/route/specs/getByWorker.spec.js @@ -0,0 +1,39 @@ +const app = require('vn-loopback/server/server'); +const LoopBackContext = require('loopback-context'); + +fdescribe('route getByWorker()', () => { + const userId = 56; + const activeCtx = { + accessToken: {userId: userId}, + http: { + req: { + headers: {origin: 'http://localhost'} + } + } + }; + const ctx = {req: activeCtx}; + + beforeAll(() => { + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ + active: activeCtx + }); + }); + + it('should return routes assigned to the worker', async() => { + const result = await app.models.Route.getByWorker(ctx); + + // Aquí se verifica que el resultado contiene rutas asignadas al usuario + console.log(result); + + expect(result.every(route => route.workerFk === userId)).toBe(true); + }); + + it('should return all routes if user has canViewAllRoute permission', async() => { + // Simular que el usuario tiene permiso para ver todas las rutas + spyOn(app.models.ACL, 'checkAccessAcl').and.returnValue(Promise.resolve(true)); + + const result = await app.models.Route.getByWorker(ctx); + + expect(result.some(route => route.workerFk != userId)).toBe(true); + }); +}); diff --git a/modules/route/back/models/route.js b/modules/route/back/models/route.js index 073c601fe..cbdd75679 100644 --- a/modules/route/back/models/route.js +++ b/modules/route/back/models/route.js @@ -14,10 +14,10 @@ module.exports = Self => { require('../methods/route/driverRouteEmail')(Self); require('../methods/route/sendSms')(Self); require('../methods/route/downloadZip')(Self); - require('../methods/route/getRoutesByWorker')(Self); require('../methods/route/cmr')(Self); require('../methods/route/getExternalCmrs')(Self); require('../methods/route/downloadCmrsZip')(Self); + require('../methods/route/getByWorker')(Self); Self.validate('kmStart', validateDistance, { message: 'Distance must be lesser than 1000' From 6b07ee4eb1913294468af4e4202c9d768c1ff716 Mon Sep 17 00:00:00 2001 From: carlossa Date: Wed, 22 Nov 2023 18:35:14 +0100 Subject: [PATCH 391/427] hotfix workerhours --- modules/worker/front/time-control/index.js | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/modules/worker/front/time-control/index.js b/modules/worker/front/time-control/index.js index a60c71589..f8a94be52 100644 --- a/modules/worker/front/time-control/index.js +++ b/modules/worker/front/time-control/index.js @@ -111,10 +111,8 @@ class Controller extends Section { dayIndex.setDate(dayIndex.getDate() + 1); } - if (this.worker) { - this.fetchHours(); - this.getWeekData(); - } + this.fetchHours(); + this.getWeekData(); } set weekTotalHours(totalHours) { @@ -404,7 +402,7 @@ class Controller extends Section { }); } - changeState(state, reason) { + state(state, reason) { this.state = state; this.reason = reason; this.repaint(); From f4fabb9fff0f95506c289834adbef3e6af58e713 Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 23 Nov 2023 08:26:14 +0100 Subject: [PATCH 392/427] refs #6491 refactor(order_filter): optimized --- CHANGELOG.md | 1 + modules/order/back/methods/order/filter.js | 3 +++ 2 files changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 08a62f044..1f16511b6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - (Ticket -> Adelantar) Permite mover lineas sin generar negativos - (Ticket -> Adelantar) Permite modificar la fecha de los tickets +- (Trabajadores -> Notificaciones) Nueva sección (lilium) ### Changed ### Fixed diff --git a/modules/order/back/methods/order/filter.js b/modules/order/back/methods/order/filter.js index 97fca5c10..592ed11e6 100644 --- a/modules/order/back/methods/order/filter.js +++ b/modules/order/back/methods/order/filter.js @@ -139,6 +139,8 @@ module.exports = Self => { filter = mergeFilters(filter, {where}); const stmts = []; let stmt; + stmts.push(`SET @_optimizer_search_depth = @@optimizer_search_depth`); + stmts.push(`SET SESSION optimizer_search_depth = 0`); stmt = new ParameterizedSQL(` CREATE OR REPLACE TEMPORARY TABLE tmp.filter @@ -195,6 +197,7 @@ module.exports = Self => { stmt.merge(`GROUP BY id`); stmt.merge(conn.makePagination(filter)); stmts.push(stmt); + stmts.push(`SET SESSION optimizer_search_depth = @_optimizer_search_depth`); stmt = new ParameterizedSQL(`SELECT * FROM tmp.filter`); stmt.merge(conn.makeOrderBy(filter.order)); From 217aa1ac770ffb1e3e13cc76188cf800671af8bc Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 23 Nov 2023 08:35:08 +0100 Subject: [PATCH 393/427] refs #6491 deploy(2350) init version --- CHANGELOG.md | 7 +++++++ db/{changes => .archive}/233001/.gitkeep | 0 db/{changes => .archive}/233001/00-aclSaleTracking.sql | 0 db/{changes => .archive}/233001/00-clientSms.sql | 0 db/{changes => .archive}/233001/00-company.sql | 0 db/{changes => .archive}/233001/00-fixACLVehicle.sql | 0 db/{changes => .archive}/233001/00-itemRecycle.sql | 0 .../233001/00-itemShelving_inventory.sql | 0 db/{changes => .archive}/233001/00-noUniqueSocialName.sql | 0 db/{changes => .archive}/233001/00-roadmap.sql | 0 db/{changes => .archive}/233001/00-roadmapACL.sql | 0 db/{changes => .archive}/233001/00-ticketWeight.sql | 0 db/{changes => .archive}/233201/.gitkeep | 0 .../233201/00-acl_viaexpressConfig.sql | 0 db/{changes => .archive}/233201/00-transferClient.sql | 0 db/{changes => .archive}/233201/00-updatePrice.sql | 0 db/{changes => .archive}/233201/00-viaexpress.sql | 0 db/{changes => .archive}/233201/00-workerDocuware.sql | 0 db/{changes => .archive}/233202/00-client_create_upper.sql | 0 db/{changes => .archive}/233202/00-ticketSmsACL.sql | 0 db/{changes => .archive}/233401/00-setDeleted_acl.sql | 0 db/{changes => .archive}/233601/.gitkeep | 0 db/{changes => .archive}/233601/00-aclWorker.sql | 0 db/{changes => .archive}/233601/00-addExpeditionState.sql | 0 db/{changes => .archive}/233601/00-department.sql | 0 db/{changes => .archive}/233601/00-saleGroupDetail.sql | 0 db/{changes => .archive}/233801/.gitkeep | 0 db/{changes => .archive}/233801/00-firstScript.sql | 0 db/{changes => .archive}/233801/01-deviceLog_acl.sql | 0 db/{changes => .archive}/233802/.gitkeep | 0 .../233802/00-collectionGetTicketsACL.sql | 0 db/changes/235001/.gitkeep | 0 package-lock.json | 4 ++-- package.json | 2 +- 34 files changed, 10 insertions(+), 3 deletions(-) rename db/{changes => .archive}/233001/.gitkeep (100%) rename db/{changes => .archive}/233001/00-aclSaleTracking.sql (100%) rename db/{changes => .archive}/233001/00-clientSms.sql (100%) rename db/{changes => .archive}/233001/00-company.sql (100%) rename db/{changes => .archive}/233001/00-fixACLVehicle.sql (100%) rename db/{changes => .archive}/233001/00-itemRecycle.sql (100%) rename db/{changes => .archive}/233001/00-itemShelving_inventory.sql (100%) rename db/{changes => .archive}/233001/00-noUniqueSocialName.sql (100%) rename db/{changes => .archive}/233001/00-roadmap.sql (100%) rename db/{changes => .archive}/233001/00-roadmapACL.sql (100%) rename db/{changes => .archive}/233001/00-ticketWeight.sql (100%) rename db/{changes => .archive}/233201/.gitkeep (100%) rename db/{changes => .archive}/233201/00-acl_viaexpressConfig.sql (100%) rename db/{changes => .archive}/233201/00-transferClient.sql (100%) rename db/{changes => .archive}/233201/00-updatePrice.sql (100%) rename db/{changes => .archive}/233201/00-viaexpress.sql (100%) rename db/{changes => .archive}/233201/00-workerDocuware.sql (100%) rename db/{changes => .archive}/233202/00-client_create_upper.sql (100%) rename db/{changes => .archive}/233202/00-ticketSmsACL.sql (100%) rename db/{changes => .archive}/233401/00-setDeleted_acl.sql (100%) rename db/{changes => .archive}/233601/.gitkeep (100%) rename db/{changes => .archive}/233601/00-aclWorker.sql (100%) rename db/{changes => .archive}/233601/00-addExpeditionState.sql (100%) rename db/{changes => .archive}/233601/00-department.sql (100%) rename db/{changes => .archive}/233601/00-saleGroupDetail.sql (100%) rename db/{changes => .archive}/233801/.gitkeep (100%) rename db/{changes => .archive}/233801/00-firstScript.sql (100%) rename db/{changes => .archive}/233801/01-deviceLog_acl.sql (100%) rename db/{changes => .archive}/233802/.gitkeep (100%) rename db/{changes => .archive}/233802/00-collectionGetTicketsACL.sql (100%) create mode 100644 db/changes/235001/.gitkeep diff --git a/CHANGELOG.md b/CHANGELOG.md index 1f16511b6..d8d040fd6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,13 @@ 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). +## [2350.01] - 2023-12-14 + +### Added +### Changed +### Fixed + + ## [2348.01] - 2023-11-30 ### Added diff --git a/db/changes/233001/.gitkeep b/db/.archive/233001/.gitkeep similarity index 100% rename from db/changes/233001/.gitkeep rename to db/.archive/233001/.gitkeep diff --git a/db/changes/233001/00-aclSaleTracking.sql b/db/.archive/233001/00-aclSaleTracking.sql similarity index 100% rename from db/changes/233001/00-aclSaleTracking.sql rename to db/.archive/233001/00-aclSaleTracking.sql diff --git a/db/changes/233001/00-clientSms.sql b/db/.archive/233001/00-clientSms.sql similarity index 100% rename from db/changes/233001/00-clientSms.sql rename to db/.archive/233001/00-clientSms.sql diff --git a/db/changes/233001/00-company.sql b/db/.archive/233001/00-company.sql similarity index 100% rename from db/changes/233001/00-company.sql rename to db/.archive/233001/00-company.sql diff --git a/db/changes/233001/00-fixACLVehicle.sql b/db/.archive/233001/00-fixACLVehicle.sql similarity index 100% rename from db/changes/233001/00-fixACLVehicle.sql rename to db/.archive/233001/00-fixACLVehicle.sql diff --git a/db/changes/233001/00-itemRecycle.sql b/db/.archive/233001/00-itemRecycle.sql similarity index 100% rename from db/changes/233001/00-itemRecycle.sql rename to db/.archive/233001/00-itemRecycle.sql diff --git a/db/changes/233001/00-itemShelving_inventory.sql b/db/.archive/233001/00-itemShelving_inventory.sql similarity index 100% rename from db/changes/233001/00-itemShelving_inventory.sql rename to db/.archive/233001/00-itemShelving_inventory.sql diff --git a/db/changes/233001/00-noUniqueSocialName.sql b/db/.archive/233001/00-noUniqueSocialName.sql similarity index 100% rename from db/changes/233001/00-noUniqueSocialName.sql rename to db/.archive/233001/00-noUniqueSocialName.sql diff --git a/db/changes/233001/00-roadmap.sql b/db/.archive/233001/00-roadmap.sql similarity index 100% rename from db/changes/233001/00-roadmap.sql rename to db/.archive/233001/00-roadmap.sql diff --git a/db/changes/233001/00-roadmapACL.sql b/db/.archive/233001/00-roadmapACL.sql similarity index 100% rename from db/changes/233001/00-roadmapACL.sql rename to db/.archive/233001/00-roadmapACL.sql diff --git a/db/changes/233001/00-ticketWeight.sql b/db/.archive/233001/00-ticketWeight.sql similarity index 100% rename from db/changes/233001/00-ticketWeight.sql rename to db/.archive/233001/00-ticketWeight.sql diff --git a/db/changes/233201/.gitkeep b/db/.archive/233201/.gitkeep similarity index 100% rename from db/changes/233201/.gitkeep rename to db/.archive/233201/.gitkeep diff --git a/db/changes/233201/00-acl_viaexpressConfig.sql b/db/.archive/233201/00-acl_viaexpressConfig.sql similarity index 100% rename from db/changes/233201/00-acl_viaexpressConfig.sql rename to db/.archive/233201/00-acl_viaexpressConfig.sql diff --git a/db/changes/233201/00-transferClient.sql b/db/.archive/233201/00-transferClient.sql similarity index 100% rename from db/changes/233201/00-transferClient.sql rename to db/.archive/233201/00-transferClient.sql diff --git a/db/changes/233201/00-updatePrice.sql b/db/.archive/233201/00-updatePrice.sql similarity index 100% rename from db/changes/233201/00-updatePrice.sql rename to db/.archive/233201/00-updatePrice.sql diff --git a/db/changes/233201/00-viaexpress.sql b/db/.archive/233201/00-viaexpress.sql similarity index 100% rename from db/changes/233201/00-viaexpress.sql rename to db/.archive/233201/00-viaexpress.sql diff --git a/db/changes/233201/00-workerDocuware.sql b/db/.archive/233201/00-workerDocuware.sql similarity index 100% rename from db/changes/233201/00-workerDocuware.sql rename to db/.archive/233201/00-workerDocuware.sql diff --git a/db/changes/233202/00-client_create_upper.sql b/db/.archive/233202/00-client_create_upper.sql similarity index 100% rename from db/changes/233202/00-client_create_upper.sql rename to db/.archive/233202/00-client_create_upper.sql diff --git a/db/changes/233202/00-ticketSmsACL.sql b/db/.archive/233202/00-ticketSmsACL.sql similarity index 100% rename from db/changes/233202/00-ticketSmsACL.sql rename to db/.archive/233202/00-ticketSmsACL.sql diff --git a/db/changes/233401/00-setDeleted_acl.sql b/db/.archive/233401/00-setDeleted_acl.sql similarity index 100% rename from db/changes/233401/00-setDeleted_acl.sql rename to db/.archive/233401/00-setDeleted_acl.sql diff --git a/db/changes/233601/.gitkeep b/db/.archive/233601/.gitkeep similarity index 100% rename from db/changes/233601/.gitkeep rename to db/.archive/233601/.gitkeep diff --git a/db/changes/233601/00-aclWorker.sql b/db/.archive/233601/00-aclWorker.sql similarity index 100% rename from db/changes/233601/00-aclWorker.sql rename to db/.archive/233601/00-aclWorker.sql diff --git a/db/changes/233601/00-addExpeditionState.sql b/db/.archive/233601/00-addExpeditionState.sql similarity index 100% rename from db/changes/233601/00-addExpeditionState.sql rename to db/.archive/233601/00-addExpeditionState.sql diff --git a/db/changes/233601/00-department.sql b/db/.archive/233601/00-department.sql similarity index 100% rename from db/changes/233601/00-department.sql rename to db/.archive/233601/00-department.sql diff --git a/db/changes/233601/00-saleGroupDetail.sql b/db/.archive/233601/00-saleGroupDetail.sql similarity index 100% rename from db/changes/233601/00-saleGroupDetail.sql rename to db/.archive/233601/00-saleGroupDetail.sql diff --git a/db/changes/233801/.gitkeep b/db/.archive/233801/.gitkeep similarity index 100% rename from db/changes/233801/.gitkeep rename to db/.archive/233801/.gitkeep diff --git a/db/changes/233801/00-firstScript.sql b/db/.archive/233801/00-firstScript.sql similarity index 100% rename from db/changes/233801/00-firstScript.sql rename to db/.archive/233801/00-firstScript.sql diff --git a/db/changes/233801/01-deviceLog_acl.sql b/db/.archive/233801/01-deviceLog_acl.sql similarity index 100% rename from db/changes/233801/01-deviceLog_acl.sql rename to db/.archive/233801/01-deviceLog_acl.sql diff --git a/db/changes/233802/.gitkeep b/db/.archive/233802/.gitkeep similarity index 100% rename from db/changes/233802/.gitkeep rename to db/.archive/233802/.gitkeep diff --git a/db/changes/233802/00-collectionGetTicketsACL.sql b/db/.archive/233802/00-collectionGetTicketsACL.sql similarity index 100% rename from db/changes/233802/00-collectionGetTicketsACL.sql rename to db/.archive/233802/00-collectionGetTicketsACL.sql diff --git a/db/changes/235001/.gitkeep b/db/changes/235001/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/package-lock.json b/package-lock.json index b66279ae3..78ef93987 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "salix-back", - "version": "23.48.01", + "version": "23.50.01", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "salix-back", - "version": "23.48.01", + "version": "23.50.01", "license": "GPL-3.0", "dependencies": { "axios": "^1.2.2", diff --git a/package.json b/package.json index 04fcb008b..586c963dd 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "salix-back", - "version": "23.48.01", + "version": "23.50.01", "author": "Verdnatura Levante SL", "description": "Salix backend", "license": "GPL-3.0", From f44424dbcfe92bc3bb5b5f3e42467ef8acfb6d2c Mon Sep 17 00:00:00 2001 From: jgallego Date: Thu, 23 Nov 2023 09:44:47 +0100 Subject: [PATCH 394/427] test: refs #6028 test --- back/methods/collection/newCollection.js | 133 ------------------ .../collection/spec/newCollection.spec.js | 12 -- back/models/collection.js | 1 - .../00-getRoutesByWorker.sql | 6 + .../route/back/methods/route/getByWorker.js | 3 +- .../methods/route/specs/getByWorker.spec.js | 5 +- 6 files changed, 8 insertions(+), 152 deletions(-) delete mode 100644 back/methods/collection/newCollection.js delete mode 100644 back/methods/collection/spec/newCollection.spec.js rename db/changes/{234801 => 235001}/00-getRoutesByWorker.sql (71%) diff --git a/back/methods/collection/newCollection.js b/back/methods/collection/newCollection.js deleted file mode 100644 index 2be9f8b0e..000000000 --- a/back/methods/collection/newCollection.js +++ /dev/null @@ -1,133 +0,0 @@ -module.exports = Self => { - Self.remoteMethodCtx('newCollection', { - description: 'Make a new collection of tickets', - accessType: 'WRITE', - accepts: [{ - arg: 'collectionFk', - type: 'Number', - required: false, - description: 'The collection id' - }, { - arg: 'sectorFk', - type: 'Number', - required: true, - description: 'The sector of worker' - }, { - arg: 'vWagons', - type: 'Number', - required: true, - description: 'The number of wagons' - }], - returns: { - type: 'Object', - root: true - }, - http: { - path: `/newCollection`, - verb: 'POST' - } - }); - - Self.newCollection = async(ctx, collectionFk, sectorFk, vWagons) => { - let query = ''; - const userId = ctx.req.accessToken.userId; - - if (!collectionFk) { - query = `CALL vn.collectionTrain_newBeta(?,?,?)`; - const [result] = await Self.rawSql(query, [sectorFk, vWagons, userId], {userId}); - if (result.length == 0) - throw new Error(`No collections for today`); - - collectionFk = result[0].vCollectionFk; - } - - query = `CALL vn.collectionTicket_get(?)`; - const [tickets] = await Self.rawSql(query, [collectionFk], {userId}); - - query = `CALL vn.collectionSale_get(?)`; - const [sales] = await Self.rawSql(query, [collectionFk], {userId}); - - query = `CALL vn.collectionPlacement_get(?)`; - const [placements] = await Self.rawSql(query, [collectionFk], {userId}); - - query = `CALL vn.collectionSticker_print(?,?)`; - await Self.rawSql(query, [collectionFk, sectorFk], {userId}); - - return makeCollection(tickets, sales, placements, collectionFk); - }; - - /** - * Returns a collection json - * @param {*} tickets - Request tickets - * @param {*} sales - Request sales - * @param {*} placements - Request placements - * @param {*} collectionFk - Request placements - * @return {Object} Collection JSON - */ - async function makeCollection(tickets, sales, placements, collectionFk) { - let collection = []; - - for (let i = 0; i < tickets.length; i++) { - let ticket = {}; - ticket['ticketFk'] = tickets[i]['ticketFk']; - ticket['level'] = tickets[i]['level']; - ticket['agencyName'] = tickets[i]['agencyName']; - ticket['warehouseFk'] = tickets[i]['warehouseFk']; - ticket['salesPersonFk'] = tickets[i]['salesPersonFk']; - - let ticketSales = []; - - for (let x = 0; x < sales.length; x++) { - if (sales[x]['ticketFk'] == ticket['ticketFk']) { - let sale = {}; - sale['collectionFk'] = collectionFk; - sale['ticketFk'] = sales[x]['ticketFk']; - sale['saleFk'] = sales[x]['saleFk']; - sale['itemFk'] = sales[x]['itemFk']; - sale['quantity'] = sales[x]['quantity']; - if (sales[x]['quantityPicked'] != null) - sale['quantityPicked'] = sales[x]['quantityPicked']; - else - sale['quantityPicked'] = 0; - sale['longName'] = sales[x]['longName']; - sale['size'] = sales[x]['size']; - sale['color'] = sales[x]['color']; - sale['discount'] = sales[x]['discount']; - sale['price'] = sales[x]['price']; - sale['stems'] = sales[x]['stems']; - sale['category'] = sales[x]['category']; - sale['origin'] = sales[x]['origin']; - sale['clientFk'] = sales[x]['clientFk']; - sale['productor'] = sales[x]['productor']; - sale['reserved'] = sales[x]['reserved']; - sale['isPreviousPrepared'] = sales[x]['isPreviousPrepared']; - sale['isPrepared'] = sales[x]['isPrepared']; - sale['isControlled'] = sales[x]['isControlled']; - - let salePlacements = []; - - for (let z = 0; z < placements.length; z++) { - if (placements[z]['saleFk'] == sale['saleFk']) { - let placement = {}; - placement['saleFk'] = placements[z]['saleFk']; - placement['itemFk'] = placements[z]['itemFk']; - placement['placement'] = placements[z]['placement']; - placement['shelving'] = placements[z]['shelving']; - placement['created'] = placements[z]['created']; - placement['visible'] = placements[z]['visible']; - placement['order'] = placements[z]['order']; - placement['grouping'] = placements[z]['grouping']; - salePlacements.push(placement); - } - } - sale['placements'] = salePlacements; - ticketSales.push(sale); - } - } - ticket['sales'] = ticketSales; - collection.push(ticket); - } - - return collection; - } -}; diff --git a/back/methods/collection/spec/newCollection.spec.js b/back/methods/collection/spec/newCollection.spec.js deleted file mode 100644 index e729594d1..000000000 --- a/back/methods/collection/spec/newCollection.spec.js +++ /dev/null @@ -1,12 +0,0 @@ -const {models} = require('vn-loopback/server/server'); - -describe('newCollection()', () => { - it('should return a new collection', async() => { - pending('#3400 analizar que hacer con rutas de back collection'); - let ctx = {req: {accessToken: {userId: 1106}}}; - let response = await models.Collection.newCollection(ctx, 1, 1, 1); - - expect(response.length).toBeGreaterThan(0); - expect(response[0].ticketFk).toEqual(2); - }); -}); diff --git a/back/models/collection.js b/back/models/collection.js index bfa906af6..1c10d49fa 100644 --- a/back/models/collection.js +++ b/back/models/collection.js @@ -1,6 +1,5 @@ module.exports = Self => { require('../methods/collection/getCollection')(Self); - require('../methods/collection/newCollection')(Self); require('../methods/collection/getSectors')(Self); require('../methods/collection/setSaleQuantity')(Self); require('../methods/collection/previousLabel')(Self); diff --git a/db/changes/234801/00-getRoutesByWorker.sql b/db/changes/235001/00-getRoutesByWorker.sql similarity index 71% rename from db/changes/234801/00-getRoutesByWorker.sql rename to db/changes/235001/00-getRoutesByWorker.sql index bdc4a246e..00d6e658a 100644 --- a/db/changes/234801/00-getRoutesByWorker.sql +++ b/db/changes/235001/00-getRoutesByWorker.sql @@ -11,7 +11,13 @@ INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `pri ('Route', 'findOne', 'READ', 'ALLOW', 'ROLE', 'employee'), ('Route', 'getRoutesByWorker', 'READ', 'ALLOW', 'ROLE', 'employee'), ('Route', 'canViewAllRoute', 'READ', 'ALLOW', 'ROLE', 'deliveryBoss'), + ('Route', 'cmr', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('Route', 'downloadCmrsZip', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('Route', 'downloadZip', 'READ', 'ALLOW', 'ROLE', 'employee'), ('Route', 'filter', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('Route', 'getByWorker', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('Route', 'getDeliveryPoint', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('Route', 'getExternalCmrs', 'READ', 'ALLOW', 'ROLE', 'employee'), ('Route', 'getSuggestedTickets', 'READ', 'ALLOW', 'ROLE', 'employee'), ('Route', 'getTickets', 'READ', 'ALLOW', 'ROLE', 'employee'), ('Route', 'guessPriority', 'WRITE', 'ALLOW', 'ROLE', 'employee'), diff --git a/modules/route/back/methods/route/getByWorker.js b/modules/route/back/methods/route/getByWorker.js index 2f8a286e6..7e70cb1f1 100644 --- a/modules/route/back/methods/route/getByWorker.js +++ b/modules/route/back/methods/route/getByWorker.js @@ -24,8 +24,7 @@ module.exports = Self => { const canViewAll = await models.ACL.checkAccessAcl(ctx, 'Route', 'canViewAllRoute', 'READ'); let filterGrant = {}; - console.log(userId); - console.log(canViewAll); + if (canViewAll) { const userConfig = await models.UserConfig.getUserConfig(ctx, myOptions); filterGrant = { diff --git a/modules/route/back/methods/route/specs/getByWorker.spec.js b/modules/route/back/methods/route/specs/getByWorker.spec.js index 52b8d6d87..f3103509a 100644 --- a/modules/route/back/methods/route/specs/getByWorker.spec.js +++ b/modules/route/back/methods/route/specs/getByWorker.spec.js @@ -1,7 +1,7 @@ const app = require('vn-loopback/server/server'); const LoopBackContext = require('loopback-context'); -fdescribe('route getByWorker()', () => { +describe('route getByWorker()', () => { const userId = 56; const activeCtx = { accessToken: {userId: userId}, @@ -22,9 +22,6 @@ fdescribe('route getByWorker()', () => { it('should return routes assigned to the worker', async() => { const result = await app.models.Route.getByWorker(ctx); - // Aquí se verifica que el resultado contiene rutas asignadas al usuario - console.log(result); - expect(result.every(route => route.workerFk === userId)).toBe(true); }); From 900dffbbba344b62662e7fa8ce388d0d9006a20e Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 23 Nov 2023 10:26:28 +0100 Subject: [PATCH 395/427] refs #5811 delete viaexpress expeditions included --- back/models/viaexpress-config.js | 2 + loopback/locale/en.json | 3 +- loopback/locale/es.json | 5 +- .../methods/expedition/deleteExpeditions.js | 66 +++++++++++-------- modules/ticket/back/models/expedition.json | 2 +- 5 files changed, 45 insertions(+), 33 deletions(-) diff --git a/back/models/viaexpress-config.js b/back/models/viaexpress-config.js index d0335b28b..429c0a0d8 100644 --- a/back/models/viaexpress-config.js +++ b/back/models/viaexpress-config.js @@ -1,4 +1,6 @@ module.exports = Self => { require('../methods/viaexpress-config/internationalExpedition')(Self); require('../methods/viaexpress-config/renderer')(Self); + require('../methods/viaexpress-config/deleteShipment')(Self); + require('../methods/viaexpress-config/deleteShipmentRenderer')(Self); }; diff --git a/loopback/locale/en.json b/loopback/locale/en.json index ed6aa474f..7d5b5ed47 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -199,5 +199,6 @@ "You can only add negative amounts in refund tickets": "You can only add negative amounts in refund tickets", "Try again": "Try again", "keepPrice": "keepPrice", - "Cannot past travels with entries": "Cannot past travels with entries" + "Cannot past travels with entries": "Cannot past travels with entries", + "It was not able to remove the next expeditions:": "It was not able to remove the next expeditions: {{expeditions}}" } \ No newline at end of file diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 41acc36c3..01384efb4 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -328,5 +328,6 @@ "User disabled": "Usuario desactivado", "The amount cannot be less than the minimum": "La cantidad no puede ser menor que la cantidad mínima", "quantityLessThanMin": "La cantidad no puede ser menor que la cantidad mínima", - "Cannot past travels with entries": "No se pueden pasar envíos con entradas" -} + "Cannot past travels with entries": "No se pueden pasar envíos con entradas", + "It was not able to remove the next expeditions:": "No se pudo eliminar las siguientes expediciones: {{expeditions}}" +} \ No newline at end of file diff --git a/modules/ticket/back/methods/expedition/deleteExpeditions.js b/modules/ticket/back/methods/expedition/deleteExpeditions.js index 2419d3a5e..72c48fd3a 100644 --- a/modules/ticket/back/methods/expedition/deleteExpeditions.js +++ b/modules/ticket/back/methods/expedition/deleteExpeditions.js @@ -1,6 +1,7 @@ +const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { - Self.remoteMethod('deleteExpeditions', { + Self.remoteMethodCtx('deleteExpeditions', { description: 'Delete the selected expeditions', accessType: 'WRITE', accepts: [{ @@ -9,44 +10,51 @@ module.exports = Self => { required: true, description: 'The expeditions ids to delete' }], - returns: { - type: ['object'], - root: true - }, http: { path: `/deleteExpeditions`, verb: 'POST' } }); - Self.deleteExpeditions = async(expeditionIds, options) => { + Self.deleteExpeditions = async(ctx, expeditionIds) => { const models = Self.app.models; - const myOptions = {}; - let tx; + const $t = ctx.req.__; + const notDeletedExpeditions = []; - if (typeof options == 'object') - Object.assign(myOptions, options); + for (let expeditionId of expeditionIds) { + const filter = { + fields: [], + where: { + id: expeditionId + }, + include: [ + { + relation: 'agencyMode', + scope: { + fields: ['code'], + } + } + ] + }; - if (!myOptions.transaction) { - tx = await Self.beginTransaction({}); - myOptions.transaction = tx; + const expedition = await models.Expedition.findOne(filter); + const {code} = expedition.agencyMode(); + + if (code && code.toLowerCase().substring(0, 10) == 'viaexpress') { + const isDeleted = await models.ViaexpressConfig.deleteShipment(expeditionId); + + if (isDeleted === 'true') + await models.Expedition.destroyById(expeditionId); + + else if (!isDeleted) + notDeletedExpeditions.push(expeditionId); + } else + await models.Expedition.destroyById(expeditionId); } - - try { - const promises = []; - for (let expeditionId of expeditionIds) { - const deletedExpedition = models.Expedition.destroyById(expeditionId, myOptions); - promises.push(deletedExpedition); - } - - const deletedExpeditions = await Promise.all(promises); - - if (tx) await tx.commit(); - - return deletedExpeditions; - } catch (e) { - if (tx) await tx.rollback(); - throw e; + if (notDeletedExpeditions.length) { + throw new UserError( + $t(`It was not able to remove the next expeditions:`, {expeditions: notDeletedExpeditions.join()}) + ); } }; }; diff --git a/modules/ticket/back/models/expedition.json b/modules/ticket/back/models/expedition.json index 1ad083ce3..069c6e281 100644 --- a/modules/ticket/back/models/expedition.json +++ b/modules/ticket/back/models/expedition.json @@ -33,7 +33,7 @@ }, "agencyMode": { "type": "belongsTo", - "model": "agency-mode", + "model": "AgencyMode", "foreignKey": "agencyModeFk" }, "worker": { From 2e67ef4f5d40e86cfc6bfa251b2da278509e2a5f Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 23 Nov 2023 10:32:07 +0100 Subject: [PATCH 396/427] refs #5811 refactor deleteExpeditions --- modules/ticket/back/methods/expedition/deleteExpeditions.js | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/modules/ticket/back/methods/expedition/deleteExpeditions.js b/modules/ticket/back/methods/expedition/deleteExpeditions.js index 72c48fd3a..a53c5d82c 100644 --- a/modules/ticket/back/methods/expedition/deleteExpeditions.js +++ b/modules/ticket/back/methods/expedition/deleteExpeditions.js @@ -43,11 +43,9 @@ module.exports = Self => { if (code && code.toLowerCase().substring(0, 10) == 'viaexpress') { const isDeleted = await models.ViaexpressConfig.deleteShipment(expeditionId); - if (isDeleted === 'true') - await models.Expedition.destroyById(expeditionId); + if (isDeleted === 'true') await models.Expedition.destroyById(expeditionId); - else if (!isDeleted) - notDeletedExpeditions.push(expeditionId); + else notDeletedExpeditions.push(expeditionId); } else await models.Expedition.destroyById(expeditionId); } From db15285858f366732b256725756b57306e7437a5 Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 23 Nov 2023 11:21:56 +0100 Subject: [PATCH 397/427] refs #5811 test updated --- .../methods/expedition/deleteExpeditions.js | 20 ++++++++++++++----- .../specs/deleteExpeditions.spec.js | 13 ++++++------ 2 files changed, 21 insertions(+), 12 deletions(-) diff --git a/modules/ticket/back/methods/expedition/deleteExpeditions.js b/modules/ticket/back/methods/expedition/deleteExpeditions.js index a53c5d82c..3c98c8017 100644 --- a/modules/ticket/back/methods/expedition/deleteExpeditions.js +++ b/modules/ticket/back/methods/expedition/deleteExpeditions.js @@ -13,6 +13,10 @@ module.exports = Self => { http: { path: `/deleteExpeditions`, verb: 'POST' + }, + returns: { + type: ['object'], + root: true } }); @@ -20,6 +24,7 @@ module.exports = Self => { const models = Self.app.models; const $t = ctx.req.__; const notDeletedExpeditions = []; + const deletedExpeditions = []; for (let expeditionId of expeditionIds) { const filter = { @@ -43,16 +48,21 @@ module.exports = Self => { if (code && code.toLowerCase().substring(0, 10) == 'viaexpress') { const isDeleted = await models.ViaexpressConfig.deleteShipment(expeditionId); - if (isDeleted === 'true') await models.Expedition.destroyById(expeditionId); - - else notDeletedExpeditions.push(expeditionId); - } else - await models.Expedition.destroyById(expeditionId); + if (isDeleted === 'true') { + const deletedExpedition = await models.Expedition.destroyById(expeditionId); + deletedExpeditions.push(deletedExpedition); + } else notDeletedExpeditions.push(expeditionId); + } else { + const deletedExpedition = await models.Expedition.destroyById(expeditionId); + deletedExpeditions.push(deletedExpedition); + } } + if (notDeletedExpeditions.length) { throw new UserError( $t(`It was not able to remove the next expeditions:`, {expeditions: notDeletedExpeditions.join()}) ); } + return deletedExpeditions; }; }; diff --git a/modules/ticket/back/methods/expedition/specs/deleteExpeditions.spec.js b/modules/ticket/back/methods/expedition/specs/deleteExpeditions.spec.js index 61937989e..bf8bafe34 100644 --- a/modules/ticket/back/methods/expedition/specs/deleteExpeditions.spec.js +++ b/modules/ticket/back/methods/expedition/specs/deleteExpeditions.spec.js @@ -2,17 +2,16 @@ const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); describe('ticket deleteExpeditions()', () => { + let ctx; beforeAll(async() => { - const activeCtx = { + ctx = { accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } + req: { + headers: {origin: 'http://localhost'} } }; spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx + active: ctx }); }); @@ -23,7 +22,7 @@ describe('ticket deleteExpeditions()', () => { const options = {transaction: tx}; const expeditionIds = [12, 13]; - const result = await models.Expedition.deleteExpeditions(expeditionIds, options); + const result = await models.Expedition.deleteExpeditions(ctx, expeditionIds, options); expect(result.length).toEqual(2); From 5b145a57e6991bf07c54c4f1126834028c592cc9 Mon Sep 17 00:00:00 2001 From: jgallego Date: Thu, 23 Nov 2023 11:29:53 +0100 Subject: [PATCH 398/427] error: refs 6028 test front quitado --- modules/route/front/tickets/index.spec.js | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/modules/route/front/tickets/index.spec.js b/modules/route/front/tickets/index.spec.js index 2c73048bd..fef4b8331 100644 --- a/modules/route/front/tickets/index.spec.js +++ b/modules/route/front/tickets/index.spec.js @@ -209,22 +209,6 @@ describe('Route', () => { }); }); - describe('guessPriority()', () => { - it('should perform a GET query then call both refresh and showSuccess methods', () => { - jest.spyOn(controller.$.model, 'refresh'); - jest.spyOn(controller.vnApp, 'showSuccess'); - controller.$params = {id: 99}; - - const url = `Routes/${controller.$params.id}/guessPriority/`; - $httpBackend.expectGET(url).respond('ok'); - controller.guessPriority(); - $httpBackend.flush(); - - expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Order changed'); - expect(controller.$.model.refresh).toHaveBeenCalledWith(); - }); - }); - describe('onDrop()', () => { it('should call the insert method when dragging a ticket number', () => { jest.spyOn(controller, 'insert'); From 6b2c1e09de32381e265b4838e01e25c09442f77a Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 23 Nov 2023 11:31:00 +0100 Subject: [PATCH 399/427] refs #5835 refactor --- modules/invoiceIn/back/methods/invoice-in/getTotals.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/invoiceIn/back/methods/invoice-in/getTotals.js b/modules/invoiceIn/back/methods/invoice-in/getTotals.js index 4c45284d5..7bef9f7e9 100644 --- a/modules/invoiceIn/back/methods/invoice-in/getTotals.js +++ b/modules/invoiceIn/back/methods/invoice-in/getTotals.js @@ -32,7 +32,7 @@ module.exports = Self => { LEFT JOIN ( SELECT SUM(iit.taxableBase) totalTaxableBase, CAST( - SUM(COALESCE(iit.taxableBase * (1 + (ti.PorcentajeIva / 100)), iit.taxableBase)) + SUM(IFNULL(iit.taxableBase * (1 + (ti.PorcentajeIva / 100)), iit.taxableBase)) AS DECIMAL(10, 2) ) totalVat FROM vn.invoiceInTax iit From 4735307f5d439d25ac3d4a476a01a77399613c80 Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 23 Nov 2023 11:49:00 +0100 Subject: [PATCH 400/427] refs #5890: fix(Collection/getTickets): accepts iss.quantity nulls --- back/methods/collection/getTickets.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/back/methods/collection/getTickets.js b/back/methods/collection/getTickets.js index cfd404beb..50117b954 100644 --- a/back/methods/collection/getTickets.js +++ b/back/methods/collection/getTickets.js @@ -49,7 +49,7 @@ module.exports = Self => { ish.packing, ish.grouping, s.isAdded, - s.originalQuantity, + s.originalQuantity, s.quantity saleQuantity, iss.quantity reservedQuantity, SUM(iss.quantity) OVER (PARTITION BY s.id ORDER BY ish.id) accumulatedQuantity, @@ -74,7 +74,7 @@ module.exports = Self => { LEFT JOIN parking p ON p.id = sh.parkingFk LEFT JOIN itemColor ic ON ic.itemFk = s.itemFk LEFT JOIN origin o ON o.id = i.originFk - WHERE tc.collectionFk = ? AND iss.quantity IS NOT NULL + WHERE tc.collectionFk = ? GROUP BY s.id, ish.id, p.code, p2.code ORDER BY pickingOrder;`, [id], myOptions); @@ -105,7 +105,7 @@ module.exports = Self => { LEFT JOIN vn.buy c ON c.itemFk = s.itemFk LEFT JOIN vn.entry e ON e.id = c.entryFk LEFT JOIN vn.travel tr ON tr.id = e.travelFk - WHERE s.ticketFk = ? + WHERE s.ticketFk = ? AND tr.landed >= util.VN_CURDATE() - INTERVAL 1 YEAR`, [ticketId], myOptions); ticket.sales = []; From eeef279483a5adc30d3ad3e31197d1f0e0141c5f Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 23 Nov 2023 13:34:29 +0100 Subject: [PATCH 401/427] refs #5811 replace decription --- back/methods/viaexpress-config/deleteShipment.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/back/methods/viaexpress-config/deleteShipment.js b/back/methods/viaexpress-config/deleteShipment.js index 40509899b..babd3eeee 100644 --- a/back/methods/viaexpress-config/deleteShipment.js +++ b/back/methods/viaexpress-config/deleteShipment.js @@ -3,7 +3,7 @@ const {DOMParser} = require('xmldom'); module.exports = Self => { Self.remoteMethod('deleteShipment', { - description: 'Create an expedition and return a label', + description: 'Delete a shipment by providing the expedition ID, interacting with Viaexpress API', accessType: 'WRITE', accepts: [{ arg: 'expeditionFk', From ebe467f721c659ab7cfaa12230fc6771e3d2b73c Mon Sep 17 00:00:00 2001 From: carlossa Date: Fri, 24 Nov 2023 07:04:55 +0100 Subject: [PATCH 402/427] refs #6506 hotfix --- modules/worker/front/calendar/index.html | 1 + 1 file changed, 1 insertion(+) diff --git a/modules/worker/front/calendar/index.html b/modules/worker/front/calendar/index.html index d64c22408..75e892575 100644 --- a/modules/worker/front/calendar/index.html +++ b/modules/worker/front/calendar/index.html @@ -70,6 +70,7 @@ fields="['started', 'ended']" ng-model="$ctrl.businessId" search-function="{businessFk: $search}" + show-field="businessFk" value-field="businessFk" order="businessFk DESC" limit="5"> From 8a568f180a3d9de0f745aa33ff894616fb3eec8a Mon Sep 17 00:00:00 2001 From: carlossa Date: Fri, 24 Nov 2023 07:47:57 +0100 Subject: [PATCH 403/427] refs #6506 fix e2e, refactor business --- modules/worker/front/calendar/index.html | 2 +- modules/worker/front/time-control/index.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/worker/front/calendar/index.html b/modules/worker/front/calendar/index.html index 75e892575..0e5433dc5 100644 --- a/modules/worker/front/calendar/index.html +++ b/modules/worker/front/calendar/index.html @@ -71,7 +71,7 @@ ng-model="$ctrl.businessId" search-function="{businessFk: $search}" show-field="businessFk" - value-field="businessFk" + value-field="businessId" order="businessFk DESC" limit="5"> diff --git a/modules/worker/front/time-control/index.js b/modules/worker/front/time-control/index.js index f8a94be52..4d5f55d27 100644 --- a/modules/worker/front/time-control/index.js +++ b/modules/worker/front/time-control/index.js @@ -402,7 +402,7 @@ class Controller extends Section { }); } - state(state, reason) { + changeState(state, reason) { this.state = state; this.reason = reason; this.repaint(); From 5d18c211a0c9159a39e4f4d02c18d899f4d1b689 Mon Sep 17 00:00:00 2001 From: carlossa Date: Fri, 24 Nov 2023 08:40:06 +0100 Subject: [PATCH 404/427] refs #6507 state --- modules/worker/front/time-control/index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/worker/front/time-control/index.js b/modules/worker/front/time-control/index.js index 4d5f55d27..f8a94be52 100644 --- a/modules/worker/front/time-control/index.js +++ b/modules/worker/front/time-control/index.js @@ -402,7 +402,7 @@ class Controller extends Section { }); } - changeState(state, reason) { + state(state, reason) { this.state = state; this.reason = reason; this.repaint(); From 8ac3887d8025840b3b90c4cbaae3af4e3d2171c4 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 24 Nov 2023 10:53:38 +0100 Subject: [PATCH 405/427] refs #5811 rename methods --- .../{deleteShipment.ejs => deleteExpedition.ejs} | 0 .../{deleteShipment.js => deleteExpedition.js} | 8 ++++---- ...eteShipmentRenderer.js => deleteExpeditionRenderer.js} | 8 ++++---- back/models/viaexpress-config.js | 4 ++-- .../ticket/back/methods/expedition/deleteExpeditions.js | 2 +- 5 files changed, 11 insertions(+), 11 deletions(-) rename back/methods/viaexpress-config/{deleteShipment.ejs => deleteExpedition.ejs} (100%) rename back/methods/viaexpress-config/{deleteShipment.js => deleteExpedition.js} (88%) rename back/methods/viaexpress-config/{deleteShipmentRenderer.js => deleteExpeditionRenderer.js} (79%) diff --git a/back/methods/viaexpress-config/deleteShipment.ejs b/back/methods/viaexpress-config/deleteExpedition.ejs similarity index 100% rename from back/methods/viaexpress-config/deleteShipment.ejs rename to back/methods/viaexpress-config/deleteExpedition.ejs diff --git a/back/methods/viaexpress-config/deleteShipment.js b/back/methods/viaexpress-config/deleteExpedition.js similarity index 88% rename from back/methods/viaexpress-config/deleteShipment.js rename to back/methods/viaexpress-config/deleteExpedition.js index babd3eeee..189745554 100644 --- a/back/methods/viaexpress-config/deleteShipment.js +++ b/back/methods/viaexpress-config/deleteExpedition.js @@ -2,7 +2,7 @@ const axios = require('axios'); const {DOMParser} = require('xmldom'); module.exports = Self => { - Self.remoteMethod('deleteShipment', { + Self.remoteMethod('deleteExpedition', { description: 'Delete a shipment by providing the expedition ID, interacting with Viaexpress API', accessType: 'WRITE', accepts: [{ @@ -15,19 +15,19 @@ module.exports = Self => { root: true }, http: { - path: `/deleteShipment`, + path: `/deleteExpedition`, verb: 'POST' } }); - Self.deleteShipment = async expeditionFk => { + Self.deleteExpedition = async expeditionFk => { const models = Self.app.models; const viaexpressConfig = await models.ViaexpressConfig.findOne({ fields: ['url'] }); - const renderedXml = await models.ViaexpressConfig.deleteShipmentRenderer(expeditionFk); + const renderedXml = await models.ViaexpressConfig.deleteExpeditionRenderer(expeditionFk); const response = await axios.post(`${viaexpressConfig.url}ServicioVxClientes.asmx`, renderedXml, { headers: { 'Content-Type': 'application/soap+xml; charset=utf-8' diff --git a/back/methods/viaexpress-config/deleteShipmentRenderer.js b/back/methods/viaexpress-config/deleteExpeditionRenderer.js similarity index 79% rename from back/methods/viaexpress-config/deleteShipmentRenderer.js rename to back/methods/viaexpress-config/deleteExpeditionRenderer.js index d9106a9ec..645eaddd1 100644 --- a/back/methods/viaexpress-config/deleteShipmentRenderer.js +++ b/back/methods/viaexpress-config/deleteExpeditionRenderer.js @@ -2,7 +2,7 @@ const fs = require('fs'); const ejs = require('ejs'); module.exports = Self => { - Self.remoteMethod('deleteShipmentRenderer', { + Self.remoteMethod('deleteExpeditionRenderer', { description: 'Renders the data from an XML', accessType: 'READ', accepts: [{ @@ -15,12 +15,12 @@ module.exports = Self => { root: true }, http: { - path: `/deleteShipmentRenderer`, + path: `/deleteExpeditionRenderer`, verb: 'GET' } }); - Self.deleteShipmentRenderer = async expeditionFk => { + Self.deleteExpeditionRenderer = async expeditionFk => { const models = Self.app.models; const viaexpressConfig = await models.ViaexpressConfig.findOne({ @@ -37,7 +37,7 @@ module.exports = Self => { externalId: expedition.externalId }; - const template = fs.readFileSync(__dirname + '/deleteShipment.ejs', 'utf-8'); + const template = fs.readFileSync(__dirname + '/deleteExpedition.ejs', 'utf-8'); const renderedXml = ejs.render(template, data); return renderedXml; }; diff --git a/back/models/viaexpress-config.js b/back/models/viaexpress-config.js index 429c0a0d8..d00c99e82 100644 --- a/back/models/viaexpress-config.js +++ b/back/models/viaexpress-config.js @@ -1,6 +1,6 @@ module.exports = Self => { require('../methods/viaexpress-config/internationalExpedition')(Self); require('../methods/viaexpress-config/renderer')(Self); - require('../methods/viaexpress-config/deleteShipment')(Self); - require('../methods/viaexpress-config/deleteShipmentRenderer')(Self); + require('../methods/viaexpress-config/deleteExpedition')(Self); + require('../methods/viaexpress-config/deleteExpeditionRenderer')(Self); }; diff --git a/modules/ticket/back/methods/expedition/deleteExpeditions.js b/modules/ticket/back/methods/expedition/deleteExpeditions.js index 3c98c8017..55ca474d7 100644 --- a/modules/ticket/back/methods/expedition/deleteExpeditions.js +++ b/modules/ticket/back/methods/expedition/deleteExpeditions.js @@ -46,7 +46,7 @@ module.exports = Self => { const {code} = expedition.agencyMode(); if (code && code.toLowerCase().substring(0, 10) == 'viaexpress') { - const isDeleted = await models.ViaexpressConfig.deleteShipment(expeditionId); + const isDeleted = await models.ViaexpressConfig.deleteExpedition(expeditionId); if (isDeleted === 'true') { const deletedExpedition = await models.Expedition.destroyById(expeditionId); From 2be1639e9fb841da26c819379dcee66828d55e99 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 24 Nov 2023 12:42:25 +0100 Subject: [PATCH 406/427] refactor: refs #3222 Expence to expense --- db/.archive/225201/00-invoiceOut_new.sql | 14 +- db/.archive/231001/02-invoiceOut_new.sql | 14 +- db/.archive/232001/00-invoiceOut_new.sql | 14 +- db/dump/fixtures.sql | 10 +- db/dump/structure.sql | 158 +++++++++--------- .../invoiceIn/back/locale/invoiceIn/en.yml | 2 +- .../invoiceIn/back/locale/invoiceIn/es.yml | 2 +- .../invoiceIn/back/locale/invoiceInTax/en.yml | 2 +- .../invoiceIn/back/locale/invoiceInTax/es.yml | 2 +- .../back/methods/invoice-in/filter.js | 2 +- .../invoiceIn/back/models/invoice-in-tax.json | 2 +- modules/invoiceIn/back/models/invoice-in.json | 2 +- modules/item/back/models/expense.json | 2 +- modules/item/back/models/item.json | 2 +- modules/item/front/basic-data/index.html | 2 +- .../methods/agency-term/createInvoiceIn.js | 4 +- .../route/back/models/agency-term-config.json | 2 +- .../back/models/ticket-service-type.json | 2 +- 18 files changed, 119 insertions(+), 119 deletions(-) diff --git a/db/.archive/225201/00-invoiceOut_new.sql b/db/.archive/225201/00-invoiceOut_new.sql index 8e23fb43b..c0f6bc697 100644 --- a/db/.archive/225201/00-invoiceOut_new.sql +++ b/db/.archive/225201/00-invoiceOut_new.sql @@ -118,13 +118,13 @@ BEGIN SELECT 'UPDATE', account.myUser_getId(), ti.id, CONCAT('Crea factura ', vNewRef) FROM tmp.ticketToInvoice ti; - CALL invoiceExpenceMake(vNewInvoiceId); + CALL invoiceExpenseMake(vNewInvoiceId); CALL invoiceTaxMake(vNewInvoiceId,vTaxArea); UPDATE invoiceOut io JOIN ( SELECT SUM(amount) AS total - FROM invoiceOutExpence + FROM invoiceOutExpense WHERE invoiceOutFk = vNewInvoiceId ) base JOIN ( @@ -166,18 +166,18 @@ BEGIN SET @vTaxableBaseServices := 0.00; SET @vTaxCodeGeneral := NULL; - INSERT INTO vn.invoiceInTax(invoiceInFk, taxableBase, expenceFk, taxTypeSageFk, transactionTypeSageFk) - SELECT vNewInvoiceInId, @vTaxableBaseServices, sub.expenceFk, sub.taxTypeSageFk , sub.transactionTypeSageFk + INSERT INTO vn.invoiceInTax(invoiceInFk, taxableBase, expenseFk, taxTypeSageFk, transactionTypeSageFk) + SELECT vNewInvoiceInId, @vTaxableBaseServices, sub.expenseFk, sub.taxTypeSageFk , sub.transactionTypeSageFk FROM ( - SELECT @vTaxableBaseServices := SUM(tst.taxableBase) taxableBase, i.expenceFk, i.taxTypeSageFk , i.transactionTypeSageFk, @vTaxCodeGeneral := i.taxClassCodeFk + SELECT @vTaxableBaseServices := SUM(tst.taxableBase) taxableBase, i.expenseFk, i.taxTypeSageFk , i.transactionTypeSageFk, @vTaxCodeGeneral := i.taxClassCodeFk FROM tmp.ticketServiceTax tst JOIN vn.invoiceOutTaxConfig i ON i.taxClassCodeFk = tst.code WHERE i.isService HAVING taxableBase ) sub; - INSERT INTO vn.invoiceInTax(invoiceInFk, taxableBase, expenceFk, taxTypeSageFk, transactionTypeSageFk) - SELECT vNewInvoiceInId, SUM(tt.taxableBase) - IF(tt.code = @vTaxCodeGeneral, @vTaxableBaseServices, 0) taxableBase, i.expenceFk, i.taxTypeSageFk , i.transactionTypeSageFk + INSERT INTO vn.invoiceInTax(invoiceInFk, taxableBase, expenseFk, taxTypeSageFk, transactionTypeSageFk) + SELECT vNewInvoiceInId, SUM(tt.taxableBase) - IF(tt.code = @vTaxCodeGeneral, @vTaxableBaseServices, 0) taxableBase, i.expenseFk, i.taxTypeSageFk , i.transactionTypeSageFk FROM tmp.ticketTax tt JOIN vn.invoiceOutTaxConfig i ON i.taxClassCodeFk = tt.code WHERE !i.isService diff --git a/db/.archive/231001/02-invoiceOut_new.sql b/db/.archive/231001/02-invoiceOut_new.sql index d570dfb72..e87c44cd0 100644 --- a/db/.archive/231001/02-invoiceOut_new.sql +++ b/db/.archive/231001/02-invoiceOut_new.sql @@ -139,13 +139,13 @@ BEGIN SELECT 'UPDATE', account.myUser_getId(), ti.id, CONCAT('Crea factura ', vNewRef) FROM tmp.ticketToInvoice ti; - CALL invoiceExpenceMake(vNewInvoiceId); + CALL invoiceExpenseMake(vNewInvoiceId); CALL invoiceTaxMake(vNewInvoiceId,vTaxArea); UPDATE invoiceOut io JOIN ( SELECT SUM(amount) total - FROM invoiceOutExpence + FROM invoiceOutExpense WHERE invoiceOutFk = vNewInvoiceId ) base JOIN ( @@ -182,15 +182,15 @@ BEGIN SET @vTaxableBaseServices := 0.00; SET @vTaxCodeGeneral := NULL; - INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenceFk, taxTypeSageFk, transactionTypeSageFk) + INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenseFk, taxTypeSageFk, transactionTypeSageFk) SELECT vNewInvoiceInFk, @vTaxableBaseServices, - sub.expenceFk, + sub.expenseFk, sub.taxTypeSageFk, sub.transactionTypeSageFk FROM ( SELECT @vTaxableBaseServices := SUM(tst.taxableBase) taxableBase, - i.expenceFk, + i.expenseFk, i.taxTypeSageFk, i.transactionTypeSageFk, @vTaxCodeGeneral := i.taxClassCodeFk @@ -200,11 +200,11 @@ BEGIN HAVING taxableBase ) sub; - INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenceFk, taxTypeSageFk, transactionTypeSageFk) + INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenseFk, taxTypeSageFk, transactionTypeSageFk) SELECT vNewInvoiceInFk, SUM(tt.taxableBase) - IF(tt.code = @vTaxCodeGeneral, @vTaxableBaseServices, 0) taxableBase, - i.expenceFk, + i.expenseFk, i.taxTypeSageFk , i.transactionTypeSageFk FROM tmp.ticketTax tt diff --git a/db/.archive/232001/00-invoiceOut_new.sql b/db/.archive/232001/00-invoiceOut_new.sql index b497dffda..175c31b74 100644 --- a/db/.archive/232001/00-invoiceOut_new.sql +++ b/db/.archive/232001/00-invoiceOut_new.sql @@ -135,13 +135,13 @@ BEGIN INSERT INTO ticketTracking(stateFk,ticketFk,workerFk) SELECT * FROM tmp.updateInter; - CALL invoiceExpenceMake(vNewInvoiceId); + CALL invoiceExpenseMake(vNewInvoiceId); CALL invoiceTaxMake(vNewInvoiceId,vTaxArea); UPDATE invoiceOut io JOIN ( SELECT SUM(amount) total - FROM invoiceOutExpence + FROM invoiceOutExpense WHERE invoiceOutFk = vNewInvoiceId ) base JOIN ( @@ -178,15 +178,15 @@ BEGIN SET @vTaxableBaseServices := 0.00; SET @vTaxCodeGeneral := NULL; - INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenceFk, taxTypeSageFk, transactionTypeSageFk) + INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenseFk, taxTypeSageFk, transactionTypeSageFk) SELECT vNewInvoiceInFk, @vTaxableBaseServices, - sub.expenceFk, + sub.expenseFk, sub.taxTypeSageFk, sub.transactionTypeSageFk FROM ( SELECT @vTaxableBaseServices := SUM(tst.taxableBase) taxableBase, - i.expenceFk, + i.expenseFk, i.taxTypeSageFk, i.transactionTypeSageFk, @vTaxCodeGeneral := i.taxClassCodeFk @@ -196,11 +196,11 @@ BEGIN HAVING taxableBase ) sub; - INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenceFk, taxTypeSageFk, transactionTypeSageFk) + INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenseFk, taxTypeSageFk, transactionTypeSageFk) SELECT vNewInvoiceInFk, SUM(tt.taxableBase) - IF(tt.code = @vTaxCodeGeneral, @vTaxableBaseServices, 0) taxableBase, - i.expenceFk, + i.expenseFk, i.taxTypeSageFk , i.transactionTypeSageFk FROM tmp.ticketTax tt diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 788487ed0..93b7b796f 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -630,7 +630,7 @@ INSERT INTO `vn`.`invoiceOutTax` (`invoiceOutFk`, `taxableBase`, `vat`, `pgcFk`) (4, 8.07, 0.81, 4770000010), (5, 8.07, 0.81, 4770000010); -INSERT INTO `vn`.`expence`(`id`, `name`, `isWithheld`) +INSERT INTO `vn`.`expense`(`id`, `name`, `isWithheld`) VALUES (2000000000, 'Inmovilizado pendiente', 0), (2000000001, 'Compra de bienes de inmovilizado', 0), @@ -642,7 +642,7 @@ INSERT INTO `vn`.`expence`(`id`, `name`, `isWithheld`) (7050000000, 'Prestacion de servicios', 1); -INSERT INTO `vn`.`invoiceOutExpence`(`id`, `invoiceOutFk`, `amount`, `expenceFk`, `created`) +INSERT INTO `vn`.`invoiceOutExpense`(`id`, `invoiceOutFk`, `amount`, `expenseFk`, `created`) VALUES (1, 1, 813.06, 2000000000, util.VN_CURDATE()), (2, 1, 33.80, 4751000000, util.VN_CURDATE()), @@ -922,7 +922,7 @@ INSERT INTO `vn`.`itemFamily`(`code`, `description`) ('SER', 'Services'), ('VT', 'Sales'); -INSERT INTO `vn`.`item`(`id`, `typeFk`, `stems`, `originFk`, `description`, `producerFk`, `intrastatFk`, `expenceFk`, +INSERT INTO `vn`.`item`(`id`, `typeFk`, `stems`, `originFk`, `description`, `producerFk`, `intrastatFk`, `expenseFk`, `comment`, `relevancy`, `image`, `subName`, `minPrice`, `stars`, `family`, `isFloramondo`, `genericFk`, `itemPackingTypeFk`, `hasMinPrice`, `packingShelve`, `weightByPiece`) VALUES (1, 2, 1, 1, NULL, 1, 06021010, 2000000000, NULL, 0, '1', NULL, 0, 1, 'EMB', 0, NULL, 'V', 0, 15,3), @@ -1939,7 +1939,7 @@ INSERT INTO `vn`.`ticketRequest`(`id`, `description`, `requesterFk`, `attenderFk (4, 'Melee weapon combat first 15cm', 18, 35, 15, NULL, 1.30, NULL, NULL, 11, util.VN_CURDATE()), (5, 'Melee weapon combat first 15cm', 18, 35, 15, 4, 1.30, 0, NULL, 18, util.VN_CURDATE()); -INSERT INTO `vn`.`ticketServiceType`(`id`, `name`, `expenceFk`) +INSERT INTO `vn`.`ticketServiceType`(`id`, `name`, `expenseFk`) VALUES (1, 'Porte Agencia', 7001000000), (2, 'Portes Retorno', 7001000000), @@ -2561,7 +2561,7 @@ INSERT INTO `vn`.`duaInvoiceIn`(`id`, `duaFk`, `invoiceInFk`) (9, 9, 9), (10, 10, 10); -INSERT INTO `vn`.`invoiceInTax` (`invoiceInFk`, `taxableBase`, `expenceFk`, `foreignValue`, `taxTypeSageFk`, `transactionTypeSageFk`) +INSERT INTO `vn`.`invoiceInTax` (`invoiceInFk`, `taxableBase`, `expenseFk`, `foreignValue`, `taxTypeSageFk`, `transactionTypeSageFk`) VALUES (1, 99.99, '2000000000', NULL, NULL, NULL), (2, 999.99, '2000000000', NULL, NULL, NULL), diff --git a/db/dump/structure.sql b/db/dump/structure.sql index d8a717aa3..1db4252f4 100644 --- a/db/dump/structure.sql +++ b/db/dump/structure.sql @@ -9692,7 +9692,7 @@ proc: BEGIN `name`, longName, subName, - expenceFk, + expenseFk, typeFk, intrastatFk, originFk, @@ -10080,7 +10080,7 @@ BEGIN `name`, longName, subName, - expenceFk, + expenseFk, typeFk, intrastatFk, originFk, @@ -17338,7 +17338,7 @@ BEGIN JOIN vn.XDiario x ON x.id = mci.id JOIN vn.supplier s ON s.id = supplierFk JOIN vn.invoiceInTax iit ON iit.invoiceInFk = ii.id - JOIN vn.expence e ON e.id = iit.expenceFk + JOIN vn.expense e ON e.id = iit.expenseFk JOIN TiposRetencion t ON t.CodigoRetencion = ii.withholdingSageFk LEFT JOIN tmp.invoiceDua id ON id.id = mci.id JOIN (SELECT SUM(x2.BASEEURO) taxableBase, SUM(x2.EURODEBE) taxBase @@ -17441,7 +17441,7 @@ BEGIN i.serial COLLATE utf8mb3_unicode_ci serial, i.supplierFk, i.issued, - IF(expenceFkDeductible, FALSE, i.isVatDeductible) isVatDeductible, + IF(expenseFkDeductible, FALSE, i.isVatDeductible) isVatDeductible, IF(c.code = 'EUR', '',c.`code`) currencyFk FROM vn.invoiceIn i JOIN vn.currency c ON c.id = i.currencyFk @@ -17949,7 +17949,7 @@ BEGIN e.id accountFk, UCASE(e.name), '' - FROM vn.expence e + FROM vn.expense e UNION SELECT company_getCode(vCompanyFk), b.account, @@ -22010,7 +22010,7 @@ DROP TABLE IF EXISTS `agencyTermConfig`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `agencyTermConfig` ( - `expenceFk` varchar(10) DEFAULT NULL, + `expenseFk` varchar(10) DEFAULT NULL, `vatAccountSupported` varchar(15) DEFAULT NULL, `vatPercentage` decimal(28,10) DEFAULT NULL, `transaction` varchar(50) DEFAULT NULL @@ -29097,19 +29097,19 @@ SET character_set_client = utf8; SET character_set_client = @saved_cs_client; -- --- Table structure for table `expence` +-- Table structure for table `expense` -- -DROP TABLE IF EXISTS `expence`; +DROP TABLE IF EXISTS `expense`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; -CREATE TABLE `expence` ( +CREATE TABLE `expense` ( `id` varchar(10) NOT NULL, `name` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL, `isWithheld` tinyint(4) NOT NULL DEFAULT 0, `code` varchar(25) DEFAULT NULL, PRIMARY KEY (`id`), - UNIQUE KEY `expence_UN` (`code`) + UNIQUE KEY `expense_UN` (`code`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -29862,7 +29862,7 @@ CREATE TABLE `invoiceIn` ( `bookEntried` date DEFAULT NULL COMMENT 'Fecha Asiento', `isVatDeductible` tinyint(1) NOT NULL DEFAULT 1, `withholdingSageFk` smallint(6) DEFAULT NULL COMMENT 'Tipos de retención SAGE', - `expenceFkDeductible` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL, + `expenseFkDeductible` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL, `editorFk` int(10) unsigned DEFAULT NULL, PRIMARY KEY (`id`), KEY `proveedor_id` (`supplierFk`), @@ -29877,12 +29877,12 @@ CREATE TABLE `invoiceIn` ( KEY `recibida_ibfk_6` (`cplusRectificationTypeFk`), KEY `recibida_ibfk_7` (`siiTrascendencyInvoiceInFk`), KEY `invoiceIn_withholdingFk_idx` (`withholdingSageFk`), - KEY `invoiceIn_expenceFkDeductible_idx` (`expenceFkDeductible`), + KEY `invoiceIn_expenseFkDeductible_idx` (`expenseFkDeductible`), KEY `invoiceIn_fk_editor` (`editorFk`), KEY `invoiceIn_FK` (`currencyFk`), CONSTRAINT `invoiceInCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE, CONSTRAINT `invoiceIn_FK` FOREIGN KEY (`currencyFk`) REFERENCES `currency` (`id`) ON UPDATE CASCADE, - CONSTRAINT `invoiceIn_expenceFkDeductible` FOREIGN KEY (`expenceFkDeductible`) REFERENCES `expence` (`id`) ON UPDATE CASCADE, + CONSTRAINT `invoiceIn_expenseFkDeductible` FOREIGN KEY (`expenseFkDeductible`) REFERENCES `expense` (`id`) ON UPDATE CASCADE, CONSTRAINT `invoiceIn_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`), CONSTRAINT `invoiceIn_ibfk_3` FOREIGN KEY (`cplusSubjectOpFk`) REFERENCES `cplusSubjectOp` (`id`) ON UPDATE CASCADE, CONSTRAINT `invoiceIn_ibfk_4` FOREIGN KEY (`cplusTaxBreakFk`) REFERENCES `cplusTaxBreak` (`id`) ON UPDATE CASCADE, @@ -30283,7 +30283,7 @@ CREATE TABLE `invoiceInSage` ( `taxTypeSageFk` smallint(6) NOT NULL, `transactionTypeSageFk` tinyint(4) NOT NULL, `isService` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Para diferenciar producto de servicio', - `expenceFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, + `expenseFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, `withholdingSageFk` smallint(6) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `invoiceInSafe_unique` (`taxClassFk`,`invoiceInSerialFk`,`isService`,`withholdingSageFk`), @@ -30292,8 +30292,8 @@ CREATE TABLE `invoiceInSage` ( KEY `invoiceInSage_invoiceInSerialFk` (`invoiceInSerialFk`), KEY `invoiceInSage_taxTypeSageFk` (`taxTypeSageFk`), KEY `invoiceInSage_transactionTypeSageFk` (`transactionTypeSageFk`), - KEY `invoiceInSage_idx` (`expenceFk`), - CONSTRAINT `invoiceInSage_expenceFk` FOREIGN KEY (`expenceFk`) REFERENCES `expence` (`id`) ON UPDATE CASCADE, + KEY `invoiceInSage_idx` (`expenseFk`), + CONSTRAINT `invoiceInSage_expenseFk` FOREIGN KEY (`expenseFk`) REFERENCES `expense` (`id`) ON UPDATE CASCADE, CONSTRAINT `invoiceInSage_invoiceInSerialFk` FOREIGN KEY (`invoiceInSerialFk`) REFERENCES `invoiceInSerial` (`code`) ON UPDATE CASCADE, CONSTRAINT `invoiceInSage_taxClassFk` FOREIGN KEY (`taxClassFk`) REFERENCES `taxClass` (`code`) ON UPDATE CASCADE, CONSTRAINT `invoiceInSage_taxTypeSageFk` FOREIGN KEY (`taxTypeSageFk`) REFERENCES `sage`.`TiposIva` (`CodigoIva`) ON UPDATE CASCADE, @@ -30334,7 +30334,7 @@ CREATE TABLE `invoiceInTax` ( `invoiceInFk` mediumint(8) unsigned NOT NULL, `taxCodeFk` int(10) DEFAULT NULL, `taxableBase` decimal(10,2) NOT NULL, - `expenceFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, + `expenseFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, `foreignValue` decimal(10,2) DEFAULT NULL, `taxTypeSageFk` smallint(6) DEFAULT NULL COMMENT 'Tipo de IVA SAGE', `transactionTypeSageFk` tinyint(4) DEFAULT NULL COMMENT 'Tipo de transacción SAGE', @@ -30345,9 +30345,9 @@ CREATE TABLE `invoiceInTax` ( KEY `recibida_iva_ibfk_2` (`taxCodeFk`), KEY `recibida_iva_taxTypeSageFk` (`taxTypeSageFk`), KEY `invoiceInTax_transactionTypeSageFk_idx` (`transactionTypeSageFk`), - KEY `invoiceInTax_idx` (`expenceFk`), + KEY `invoiceInTax_idx` (`expenseFk`), KEY `invoiceInTax_fk_editor` (`editorFk`), - CONSTRAINT `invoiceInTax_expenceFk` FOREIGN KEY (`expenceFk`) REFERENCES `expence` (`id`) ON UPDATE CASCADE, + CONSTRAINT `invoiceInTax_expenseFk` FOREIGN KEY (`expenseFk`) REFERENCES `expense` (`id`) ON UPDATE CASCADE, CONSTRAINT `invoiceInTax_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`), CONSTRAINT `invoiceInTax_ibfk_5` FOREIGN KEY (`invoiceInFk`) REFERENCES `invoiceIn` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `invoiceInTax_transactionTypeSageFk` FOREIGN KEY (`transactionTypeSageFk`) REFERENCES `sage`.`TiposTransacciones` (`CodigoTransaccion`) ON UPDATE CASCADE, @@ -30615,23 +30615,23 @@ CREATE TABLE `invoiceOutConfig` ( /*!40101 SET character_set_client = @saved_cs_client */; -- --- Table structure for table `invoiceOutExpence` +-- Table structure for table `invoiceOutExpense` -- -DROP TABLE IF EXISTS `invoiceOutExpence`; +DROP TABLE IF EXISTS `invoiceOutExpense`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; -CREATE TABLE `invoiceOutExpence` ( +CREATE TABLE `invoiceOutExpense` ( `id` int(11) NOT NULL AUTO_INCREMENT, `invoiceOutFk` int(10) unsigned NOT NULL, `amount` decimal(10,2) NOT NULL DEFAULT 0.00, - `expenceFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, + `expenseFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, `created` timestamp NULL DEFAULT current_timestamp(), PRIMARY KEY (`id`), - KEY `invoiceOutExpence_FK_1_idx` (`invoiceOutFk`), - KEY `invoiceOutExpence_expenceFk_idx` (`expenceFk`), - CONSTRAINT `invoiceOutExpence_FK_1` FOREIGN KEY (`invoiceOutFk`) REFERENCES `invoiceOut` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `invoiceOutExpence_expenceFk` FOREIGN KEY (`expenceFk`) REFERENCES `expence` (`id`) ON UPDATE CASCADE + KEY `invoiceOutExpense_FK_1_idx` (`invoiceOutFk`), + KEY `invoiceOutExpense_expenseFk_idx` (`expenseFk`), + CONSTRAINT `invoiceOutExpense_FK_1` FOREIGN KEY (`invoiceOutFk`) REFERENCES `invoiceOut` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `invoiceOutExpense_expenseFk` FOREIGN KEY (`expenseFk`) REFERENCES `expense` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Desglosa la base imponible de una factura en funcion del tipo de gasto/venta'; /*!40101 SET character_set_client = @saved_cs_client */; @@ -30694,7 +30694,7 @@ CREATE TABLE `invoiceOutTaxConfig` ( `taxTypeSageFk` smallint(6) DEFAULT NULL, `transactionTypeSageFk` tinyint(4) DEFAULT NULL, `isService` tinyint(1) DEFAULT 0, - `expenceFk` varchar(10) DEFAULT NULL, + `expenseFk` varchar(10) DEFAULT NULL, PRIMARY KEY (`id`), KEY `invoiceOutTaxConfig_FK` (`taxClassCodeFk`), KEY `invoiceOutTaxConfig_FK_1` (`taxTypeSageFk`), @@ -30737,7 +30737,7 @@ CREATE TABLE `item` ( `description` varchar(1000) DEFAULT NULL, `density` int(11) NOT NULL DEFAULT 167 COMMENT 'Almacena la densidad en kg/m3 para el calculo de los portes, si no se especifica se pone por defecto la del tipo en un trigger', `relevancy` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'La web ordena de forma descendiente por este campo para mostrar los artículos', - `expenceFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT '7001000000', + `expenseFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT '7001000000', `isActive` tinyint(1) NOT NULL DEFAULT 1, `longName` varchar(50) DEFAULT NULL, `subName` varchar(50) DEFAULT NULL, @@ -30792,11 +30792,11 @@ CREATE TABLE `item` ( KEY `item_size_IDX` (`size`) USING BTREE, KEY `item_size_IDX2` (`longName`) USING BTREE, KEY `item_lastUsed_IDX` (`lastUsed`) USING BTREE, - KEY `item_expenceFk_idx` (`expenceFk`), + KEY `item_expenseFk_idx` (`expenseFk`), KEY `item_fk_editor` (`editorFk`), CONSTRAINT `item_FK` FOREIGN KEY (`genericFk`) REFERENCES `item` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT `item_FK_1` FOREIGN KEY (`typeFk`) REFERENCES `itemType` (`id`), - CONSTRAINT `item_expenceFk` FOREIGN KEY (`expenceFk`) REFERENCES `expence` (`id`) ON UPDATE CASCADE, + CONSTRAINT `item_expenseFk` FOREIGN KEY (`expenseFk`) REFERENCES `expense` (`id`) ON UPDATE CASCADE, CONSTRAINT `item_family` FOREIGN KEY (`family`) REFERENCES `itemFamily` (`code`) ON UPDATE CASCADE, CONSTRAINT `item_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`), CONSTRAINT `item_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `origin` (`id`) ON UPDATE CASCADE, @@ -40606,10 +40606,10 @@ DROP TABLE IF EXISTS `ticketServiceType`; CREATE TABLE `ticketServiceType` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL, - `expenceFk` varchar(10) NOT NULL DEFAULT '7050000000', + `expenseFk` varchar(10) NOT NULL DEFAULT '7050000000', PRIMARY KEY (`id`), - KEY `ticketServiceType_expenceFk_idx` (`expenceFk`), - CONSTRAINT `ticketServiceType_expenceFk` FOREIGN KEY (`expenceFk`) REFERENCES `expence` (`id`) ON UPDATE CASCADE + KEY `ticketServiceType_expenseFk_idx` (`expenseFk`), + CONSTRAINT `ticketServiceType_expenseFk` FOREIGN KEY (`expenseFk`) REFERENCES `expense` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci COMMENT='Lista de los posibles servicios a elegir'; /*!40101 SET character_set_client = @saved_cs_client */; @@ -46533,7 +46533,7 @@ BEGIN WHERE io.ref = vInvoiceRef UNION ALL SELECT ioe.amount - FROM invoiceOutExpence ioe + FROM invoiceOutExpense ioe JOIN invoiceOut io ON io.id = ioe.invoiceOutFk WHERE io.ref = vInvoiceRef ) t1; @@ -57741,7 +57741,7 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `invoiceExpenceMake` */; +/*!50003 DROP PROCEDURE IF EXISTS `invoiceExpenseMake` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -57749,28 +57749,28 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceExpenceMake`(IN vInvoice INT) +CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceExpenseMake`(IN vInvoice INT) BEGIN /* Inserta las partidas de gasto correspondientes a la factura * REQUIERE tabla tmp.ticketToInvoice * @param vInvoice Numero de factura */ - DELETE FROM invoiceOutExpence + DELETE FROM invoiceOutExpense WHERE invoiceOutFk = vInvoice; - INSERT INTO invoiceOutExpence(invoiceOutFk, expenceFk, amount) + INSERT INTO invoiceOutExpense(invoiceOutFk, expenseFk, amount) SELECT vInvoice, - expenceFk, + expenseFk, SUM(ROUND(quantity * price * (100 - discount)/100,2)) amount FROM tmp.ticketToInvoice t JOIN sale s ON s.ticketFk = t.id JOIN item i ON i.id = s.itemFk - GROUP BY i.expenceFk + GROUP BY i.expenseFk HAVING amount != 0; - INSERT INTO invoiceOutExpence(invoiceOutFk, expenceFk, amount) + INSERT INTO invoiceOutExpense(invoiceOutFk, expenseFk, amount) SELECT vInvoice, - tst.expenceFk, + tst.expenseFk, SUM(ROUND(ts.quantity * ts.price ,2)) amount FROM tmp.ticketToInvoice t JOIN ticketService ts ON ts.ticketFk = t.id @@ -58125,7 +58125,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceInTax_getFromEntries`(IN vId BEGIN DECLARE vRate DOUBLE DEFAULT 1; DECLARE vDated DATE; - DECLARE vExpenceFk VARCHAR(10); + DECLARE vExpenseFk VARCHAR(10); SELECT MAX(rr.dated) INTO vDated FROM referenceRate rr @@ -58139,8 +58139,8 @@ BEGIN WHERE dated = vDated; END IF; - SELECT id INTO vExpenceFk - FROM vn.expence + SELECT id INTO vExpenseFk + FROM vn.expense WHERE `name` = 'Adquisición mercancia Extracomunitaria' GROUP BY id LIMIT 1; @@ -58148,10 +58148,10 @@ BEGIN DELETE FROM invoiceInTax WHERE invoiceInFk = vId; - INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenceFk, foreignValue, taxTypeSageFk, transactionTypeSageFk) + INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenseFk, foreignValue, taxTypeSageFk, transactionTypeSageFk) SELECT ii.id, SUM(b.buyingValue * b.quantity) / IFNULL(vRate,1) taxableBase, - vExpenceFk, + vExpenseFk, IF(ii.currencyFk = 1,NULL,SUM(b.buyingValue * b.quantity )) divisa, taxTypeSageFk, transactionTypeSageFk @@ -58188,7 +58188,7 @@ BEGIN SELECT ii.bookEntried, iit.foreignValue, ii.companyFk, - ii.expenceFkDeductible, + ii.expenseFkDeductible, iit.taxableBase, iit.transactionTypeSageFk, ii.serial, @@ -58218,8 +58218,8 @@ BEGIN cit.id invoicesCount, e.code, e.isWithheld, - e.id expenceFk, - e.name expenceName + e.id expenseFk, + e.name expenseName FROM invoiceIn ii JOIN supplier s ON s.id = ii.supplierFk LEFT JOIN province p ON p.id = s.provinceFk @@ -58231,7 +58231,7 @@ BEGIN JOIN siiTypeInvoiceIn cit ON cit.id = ii.siiTypeInvoiceInFk LEFT JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id LEFT JOIN sage.TiposTransacciones ttr ON ttr.CodigoTransaccion = iit.transactionTypeSageFk - LEFT JOIN expence e ON e.id = iit.expenceFk + LEFT JOIN expense e ON e.id = iit.expenseFk LEFT JOIN sage.TiposIva ti ON ti.CodigoIva = iit.taxTypeSageFk LEFT JOIN sage.taxType tt ON tt.id = ti.CodigoIva WHERE ii.id = vSelf; @@ -58286,7 +58286,7 @@ BEGIN empresa_id) SELECT vBookNumber ASIEN, tii.bookEntried FECHA, - IF(tii.isWithheld, LPAD(RIGHT(tii.supplierAccount, 5), 10, tii.expenceFk),tii.expenceFk) SUBCTA, + IF(tii.isWithheld, LPAD(RIGHT(tii.supplierAccount, 5), 10, tii.expenseFk),tii.expenseFk) SUBCTA, tii.supplierAccount CONTRA, IF(tii.isWithheld AND tii.taxableBase < 0, NULL, ROUND(SUM(tii.taxableBase),2)) EURODEBE, IF(tii.isWithheld AND tii.taxableBase < 0, ROUND(SUM(-tii.taxableBase), 2), NULL) EUROHABER, @@ -58301,7 +58301,7 @@ BEGIN tii.companyFk empresa_id FROM tInvoiceIn tii WHERE tii.code IS NULL OR tii.code <> 'suplido' - GROUP BY tii.expenceFk; + GROUP BY tii.expenseFk; -- Líneas de IVA INSERT INTO XDiario( @@ -58335,11 +58335,11 @@ BEGIN empresa_id) SELECT vBookNumber ASIEN, tii.bookEntried FECHA, - IF(tii.expenceFkDeductible>0, tii.expenceFkDeductible, tii.CuentaIvaSoportado) SUBCTA, + IF(tii.expenseFkDeductible>0, tii.expenseFkDeductible, tii.CuentaIvaSoportado) SUBCTA, tii.supplierAccount CONTRA, SUM(ROUND(tii.PorcentajeIva * tii.taxableBase / 100, 2)) EURODEBE, SUM(tii.taxableBase) BASEEURO, - GROUP_CONCAT(DISTINCT tii.expenceName SEPARATOR ', ') CONCEPTO, + GROUP_CONCAT(DISTINCT tii.expenseName SEPARATOR ', ') CONCEPTO, vSelf FACTURA, tii.PorcentajeIva IVA, IF(tii.isUeeMember AND eWithheld.id IS NULL, '', '*') AUXILIAR, @@ -58365,13 +58365,13 @@ BEGIN LEFT JOIN ( SELECT e.id FROM tInvoiceIn tii - JOIN expence e ON e.id = tii.expenceFk + JOIN expense e ON e.id = tii.expenseFk WHERE e.isWithheld LIMIT 1 ) eWithheld ON TRUE WHERE tii.taxTypeSageFk IS NOT NULL AND (tii.taxCode IS NULL OR tii.taxCode NOT IN ('import10', 'import21')) - GROUP BY tii.PorcentajeIva, tii.expenceFk; + GROUP BY tii.PorcentajeIva, tii.expenseFk; -- Línea iva inversor sujeto pasivo INSERT INTO XDiario( @@ -58408,7 +58408,7 @@ BEGIN tii.supplierAccount CONTRA, SUM(ROUND(tii.PorcentajeIva * tii.taxableBase / 100,2)) EUROHABER, ROUND(SUM(tii.taxableBase),2) BASEEURO, - GROUP_CONCAT(DISTINCT tii.expenceName SEPARATOR ', ') CONCEPTO, + GROUP_CONCAT(DISTINCT tii.expenseName SEPARATOR ', ') CONCEPTO, vSelf FACTURA, tii.PorcentajeIva IVA, '*' AUXILIAR, @@ -58436,7 +58436,7 @@ BEGIN AND NOT(tii.isVies AND c.nontaxableTransactionTypeFk = tii.transactionTypeSageFk AND tii.taxCode = 'nonTaxable') - GROUP BY tii.PorcentajeIva, tii.expenceFk; + GROUP BY tii.PorcentajeIva, tii.expenseFk; -- Actualización del registro original UPDATE invoiceIn ii @@ -58509,14 +58509,14 @@ BEGIN FROM ticket WHERE refFk = vInvoiceRef; - CALL invoiceExpenceMake(vInvoiceFk); + CALL invoiceExpenseMake(vInvoiceFk); CALL invoiceTaxMake(vInvoiceFk,vTaxArea); UPDATE invoiceOut io JOIN ( SELECT SUM(amount) AS total - FROM invoiceOutExpence + FROM invoiceOutExpense WHERE invoiceOutFk = vInvoiceFk ) base JOIN ( @@ -58552,7 +58552,7 @@ BEGIN * param vInvoice factura_id */ DECLARE vBookNumber INT; - DECLARE vExpenceConcept VARCHAR(50); + DECLARE vExpenseConcept VARCHAR(50); DECLARE vSpainCountryFk INT; DECLARE vOldBookNumber INT; @@ -58644,7 +58644,7 @@ BEGIN SELECT vBookNumber AS ASIEN, rs.FECHA, - ioe.expenceFk AS SUBCTA, + ioe.expenseFk AS SUBCTA, rs.clientBookingAccount AS CONTRA, ioe.amount AS EUROHABER, rs.Concept AS CONCEPTO, @@ -58652,13 +58652,13 @@ BEGIN rs.FECHA_OP, rs.companyFk AS empresa_id FROM rs - JOIN invoiceOutExpence ioe + JOIN invoiceOutExpense ioe WHERE ioe.invoiceOutFk = vInvoice; SELECT GROUP_CONCAT(`name` SEPARATOR ',') - INTO vExpenceConcept - FROM expence e - JOIN invoiceOutExpence ioe ON ioe.expenceFk = e.id + INTO vExpenseConcept + FROM expense e + JOIN invoiceOutExpense ioe ON ioe.expenseFk = e.id WHERE ioe.invoiceOutFk = vInvoice; -- Lineas de IVA @@ -58701,7 +58701,7 @@ BEGIN rs.clientBookingAccount AS CONTRA, iot.vat AS EUROHABER, iot.taxableBase AS BASEEURO, - CONCAT(vExpenceConcept,' : ',rs.Concept) AS CONCEPTO, + CONCAT(vExpenseConcept,' : ',rs.Concept) AS CONCEPTO, rs.invoiceNum AS FACTURA, IF(pe2.equFk,0,pgc.rate) AS IVA, IF(pe2.equFk,0,pgce.rate) AS RECEQUIV, @@ -58844,7 +58844,7 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutTaxAndExpence` */; +/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutTaxAndExpense` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -58852,7 +58852,7 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOutTaxAndExpence`() +CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOutTaxAndExpense`() BEGIN /* Para tickets ya facturados, vuelve a repetir el proceso de facturación. @@ -58906,7 +58906,7 @@ BEGIN FROM ticket WHERE refFk = vInvoiceRef; - CALL invoiceExpenceMake(vInvoice); + CALL invoiceExpenseMake(vInvoice); CALL invoiceTaxMake(vInvoice,vCountry,vTaxArea); FETCH rs INTO vInvoice ,vInvoiceRef; @@ -59140,13 +59140,13 @@ BEGIN INSERT INTO ticketTracking(stateFk,ticketFk,workerFk) SELECT * FROM tmp.updateInter; - CALL invoiceExpenceMake(vNewInvoiceId); + CALL invoiceExpenseMake(vNewInvoiceId); CALL invoiceTaxMake(vNewInvoiceId,vTaxArea); UPDATE invoiceOut io JOIN ( SELECT SUM(amount) total - FROM invoiceOutExpence + FROM invoiceOutExpense WHERE invoiceOutFk = vNewInvoiceId ) base JOIN ( @@ -59183,15 +59183,15 @@ BEGIN SET @vTaxableBaseServices := 0.00; SET @vTaxCodeGeneral := NULL; - INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenceFk, taxTypeSageFk, transactionTypeSageFk) + INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenseFk, taxTypeSageFk, transactionTypeSageFk) SELECT vNewInvoiceInFk, @vTaxableBaseServices, - sub.expenceFk, + sub.expenseFk, sub.taxTypeSageFk, sub.transactionTypeSageFk FROM ( SELECT @vTaxableBaseServices := SUM(tst.taxableBase) taxableBase, - i.expenceFk, + i.expenseFk, i.taxTypeSageFk, i.transactionTypeSageFk, @vTaxCodeGeneral := i.taxClassCodeFk @@ -59201,11 +59201,11 @@ BEGIN HAVING taxableBase ) sub; - INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenceFk, taxTypeSageFk, transactionTypeSageFk) + INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenseFk, taxTypeSageFk, transactionTypeSageFk) SELECT vNewInvoiceInFk, SUM(tt.taxableBase) - IF(tt.code = @vTaxCodeGeneral, @vTaxableBaseServices, 0) taxableBase, - i.expenceFk, + i.expenseFk, i.taxTypeSageFk , i.transactionTypeSageFk FROM tmp.ticketTax tt diff --git a/modules/invoiceIn/back/locale/invoiceIn/en.yml b/modules/invoiceIn/back/locale/invoiceIn/en.yml index ec9a824b6..9e94eba0d 100644 --- a/modules/invoiceIn/back/locale/invoiceIn/en.yml +++ b/modules/invoiceIn/back/locale/invoiceIn/en.yml @@ -16,5 +16,5 @@ columns: bookEntried: book entried isVatDeductible: is VAT deductible withholdingSageFk: withholding - expenceFkDeductible: expence deductible + expenseFkDeductible: expense deductible editorFk: editor \ No newline at end of file diff --git a/modules/invoiceIn/back/locale/invoiceIn/es.yml b/modules/invoiceIn/back/locale/invoiceIn/es.yml index 64e96b379..bd64c4327 100644 --- a/modules/invoiceIn/back/locale/invoiceIn/es.yml +++ b/modules/invoiceIn/back/locale/invoiceIn/es.yml @@ -16,5 +16,5 @@ columns: bookEntried: fecha asiento isVatDeductible: impuesto deducible withholdingSageFk: código de retención - expenceFkDeductible: gasto deducible + expenseFkDeductible: gasto deducible editorFk: editor \ No newline at end of file diff --git a/modules/invoiceIn/back/locale/invoiceInTax/en.yml b/modules/invoiceIn/back/locale/invoiceInTax/en.yml index c0d12c37d..6af547d3f 100644 --- a/modules/invoiceIn/back/locale/invoiceInTax/en.yml +++ b/modules/invoiceIn/back/locale/invoiceInTax/en.yml @@ -4,7 +4,7 @@ columns: invoiceInFk: invoice in taxCodeFk: tax taxableBase: taxable base - expenceFk: expence + expenseFk: expense foreignValue: foreign amount taxTypeSageFk: tax type transactionTypeSageFk: transaction type diff --git a/modules/invoiceIn/back/locale/invoiceInTax/es.yml b/modules/invoiceIn/back/locale/invoiceInTax/es.yml index 7cb847ed8..92f3855e4 100644 --- a/modules/invoiceIn/back/locale/invoiceInTax/es.yml +++ b/modules/invoiceIn/back/locale/invoiceInTax/es.yml @@ -4,7 +4,7 @@ columns: invoiceInFk: factura recibida taxCodeFk: código IVA taxableBase: base imponible - expenceFk: código gasto + expenseFk: código gasto foreignValue: importe divisa taxTypeSageFk: código impuesto transactionTypeSageFk: código transacción diff --git a/modules/invoiceIn/back/methods/invoice-in/filter.js b/modules/invoiceIn/back/methods/invoice-in/filter.js index f5eab9099..dd193af85 100644 --- a/modules/invoiceIn/back/methods/invoice-in/filter.js +++ b/modules/invoiceIn/back/methods/invoice-in/filter.js @@ -146,7 +146,7 @@ module.exports = Self => { ii.docFk AS dmsFk, dm.file, ii.supplierFk, - ii.expenceFkDeductible deductibleExpenseFk, + ii.expenseFkDeductible deductibleExpenseFk, s.name AS supplierName, s.account, SUM(iid.amount) AS amount, diff --git a/modules/invoiceIn/back/models/invoice-in-tax.json b/modules/invoiceIn/back/models/invoice-in-tax.json index 1f68476c3..bc57a4376 100644 --- a/modules/invoiceIn/back/models/invoice-in-tax.json +++ b/modules/invoiceIn/back/models/invoice-in-tax.json @@ -21,7 +21,7 @@ "expenseFk": { "type": "number", "mysql": { - "columnName": "expenceFk" + "columnName": "expenseFk" } }, "created": { diff --git a/modules/invoiceIn/back/models/invoice-in.json b/modules/invoiceIn/back/models/invoice-in.json index 754899866..5be55c851 100644 --- a/modules/invoiceIn/back/models/invoice-in.json +++ b/modules/invoiceIn/back/models/invoice-in.json @@ -51,7 +51,7 @@ "deductibleExpenseFk": { "type": "number", "mysql": { - "columnName": "expenceFkDeductible" + "columnName": "expenseFkDeductible" } } }, diff --git a/modules/item/back/models/expense.json b/modules/item/back/models/expense.json index 03147c08b..468063602 100644 --- a/modules/item/back/models/expense.json +++ b/modules/item/back/models/expense.json @@ -3,7 +3,7 @@ "base": "VnModel", "options": { "mysql": { - "table": "expence" + "table": "expense" } }, "properties": { diff --git a/modules/item/back/models/item.json b/modules/item/back/models/item.json index 6db1f5efc..3f3547fd1 100644 --- a/modules/item/back/models/item.json +++ b/modules/item/back/models/item.json @@ -119,7 +119,7 @@ "expenseFk": { "type": "number", "mysql": { - "columnName": "expenceFk" + "columnName": "expenseFk" } }, "minPrice": { diff --git a/modules/item/front/basic-data/index.html b/modules/item/front/basic-data/index.html index 426c17800..3e47faa5f 100644 --- a/modules/item/front/basic-data/index.html +++ b/modules/item/front/basic-data/index.html @@ -105,7 +105,7 @@ url="Expenses" label="Expense" ng-model="$ctrl.item.expenseFk" - vn-name="expence" + vn-name="expense" initial-data="$ctrl.item.expense"> diff --git a/modules/route/back/methods/agency-term/createInvoiceIn.js b/modules/route/back/methods/agency-term/createInvoiceIn.js index 5a8430e49..f00ab95c6 100644 --- a/modules/route/back/methods/agency-term/createInvoiceIn.js +++ b/modules/route/back/methods/agency-term/createInvoiceIn.js @@ -54,7 +54,7 @@ module.exports = Self => { dmsFk: firstDms.id, }, myOptions); - const expence = await models.AgencyTermConfig.findOne(null, myOptions); + const expense = await models.AgencyTermConfig.findOne(null, myOptions); const [taxTypeSage] = await Self.rawSql(` SELECT IFNULL(s.taxTypeSageFk, CodigoIva) value @@ -78,7 +78,7 @@ module.exports = Self => { await models.InvoiceInTax.create({ invoiceInFk: newInvoiceIn.id, taxableBase: firstRow.totalPrice, - expenseFk: expence.expenceFk, + expenseFk: expense.expenseFk, taxTypeSageFk: taxTypeSage.value, transactionTypeSageFk: transactionTypeSage.value }, myOptions); diff --git a/modules/route/back/models/agency-term-config.json b/modules/route/back/models/agency-term-config.json index c94fc266b..81a608acf 100644 --- a/modules/route/back/models/agency-term-config.json +++ b/modules/route/back/models/agency-term-config.json @@ -7,7 +7,7 @@ } }, "properties": { - "expenceFk": { + "expenseFk": { "type": "string", "id": true }, diff --git a/modules/ticket/back/models/ticket-service-type.json b/modules/ticket/back/models/ticket-service-type.json index ec2c9232a..9340d6023 100644 --- a/modules/ticket/back/models/ticket-service-type.json +++ b/modules/ticket/back/models/ticket-service-type.json @@ -18,7 +18,7 @@ "expenseFk": { "type": "number", "mysql": { - "columnName": "expenceFk" + "columnName": "expenseFk" } } }, From f9d5cad4123a1c032c05e56e36da9927d7f52b10 Mon Sep 17 00:00:00 2001 From: carlossa Date: Mon, 27 Nov 2023 07:57:18 +0100 Subject: [PATCH 407/427] refs #6506 contract --- modules/worker/front/calendar/index.html | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/modules/worker/front/calendar/index.html b/modules/worker/front/calendar/index.html index d64c22408..0b6732024 100644 --- a/modules/worker/front/calendar/index.html +++ b/modules/worker/front/calendar/index.html @@ -70,17 +70,18 @@ fields="['started', 'ended']" ng-model="$ctrl.businessId" search-function="{businessFk: $search}" + show-field="businessFk" value-field="businessFk" order="businessFk DESC" limit="5"> - -
#{{businessFk}}
-
- {{started | date: 'dd/MM/yyyy'}} - {{ended ? (ended | date: 'dd/MM/yyyy') : 'Indef.'}} -
-
- - + +
#{{businessFk}}
+
+ {{started | date: 'dd/MM/yyyy'}} - {{ended ? (ended | date: 'dd/MM/yyyy') : 'Indef.'}} +
+
+ +
From aefff68c2903d94f1470b11d76781635fcad1b8c Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 27 Nov 2023 09:51:56 +0100 Subject: [PATCH 408/427] refactor: refs #3222 Requested changes --- modules/invoiceIn/back/models/invoice-in-tax.json | 5 +---- modules/item/back/models/item.json | 8 +------- 2 files changed, 2 insertions(+), 11 deletions(-) diff --git a/modules/invoiceIn/back/models/invoice-in-tax.json b/modules/invoiceIn/back/models/invoice-in-tax.json index bc57a4376..5bfbbe2a8 100644 --- a/modules/invoiceIn/back/models/invoice-in-tax.json +++ b/modules/invoiceIn/back/models/invoice-in-tax.json @@ -19,10 +19,7 @@ "type": "number" }, "expenseFk": { - "type": "number", - "mysql": { - "columnName": "expenseFk" - } + "type": "number" }, "created": { "type": "date" diff --git a/modules/item/back/models/item.json b/modules/item/back/models/item.json index 3f3547fd1..097fe7708 100644 --- a/modules/item/back/models/item.json +++ b/modules/item/back/models/item.json @@ -117,10 +117,7 @@ "description": "The item family" }, "expenseFk": { - "type": "number", - "mysql": { - "columnName": "expenseFk" - } + "type": "number" }, "minPrice": { "type": "number" @@ -131,9 +128,6 @@ "nonRecycledPlastic": { "type": "number" }, - "minQuantity": { - "type": "number" - }, "packingOut": { "type": "number" }, From 37555cbb63290c523e2d237d5d058890d59cb751 Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 27 Nov 2023 15:10:00 +0100 Subject: [PATCH 409/427] refs #6335 warmFix(ticketAdvance): correct properties --- modules/ticket/front/advance/index.js | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/modules/ticket/front/advance/index.js b/modules/ticket/front/advance/index.js index fb539311f..1f47d8242 100644 --- a/modules/ticket/front/advance/index.js +++ b/modules/ticket/front/advance/index.js @@ -202,9 +202,9 @@ export default class Controller extends Section { if (!ticket.landed) { const newLanded = await this.getLanded({ shipped: this.$.model.userParams.dateToAdvance, - addressFk: ticket.addressFk, - agencyModeFk: ticket.agencyModeFk, - warehouseFk: ticket.warehouseFk + addressFk: ticket.futureAddressFk, + agencyModeFk: ticket.agencyModeFk ?? ticket.futureAgencyModeFk, + warehouseFk: ticket.futureWarehouseFk }); if (!newLanded) throw new Error(this.$t(`No delivery zone available for this landing date`)); @@ -213,13 +213,13 @@ export default class Controller extends Section { ticket.zoneFk = newLanded.zoneFk; } const params = { - clientFk: ticket.clientFk, + clientFk: ticket.futureClientFk, nickname: ticket.nickname, agencyModeFk: ticket.agencyModeFk ?? ticket.futureAgencyModeFk, - addressFk: ticket.addressFk, + addressFk: ticket.futureAddressFk, zoneFk: ticket.zoneFk ?? ticket.futureZoneFk, - warehouseFk: ticket.warehouseFk, - companyFk: ticket.companyFk, + warehouseFk: ticket.futureWarehouseFk, + companyFk: ticket.futureCompanyFk, shipped: this.$.model.userParams.dateToAdvance, landed: ticket.landed, isDeleted: false, From 2fa56cce4b0a554b63e12bea0112e047700acbc8 Mon Sep 17 00:00:00 2001 From: jgallego Date: Tue, 28 Nov 2023 09:22:00 +0100 Subject: [PATCH 410/427] fix: refs #5652 arreglo fixtures --- db/dump/fixtures.sql | 6 +++--- .../back/methods/sales-monitor/specs/salesFilter.spec.js | 2 +- modules/ticket/back/methods/ticket/specs/filter.spec.js | 2 +- .../back/methods/ticket/specs/getSalespersonMana.spec.js | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 93b7b796f..2d5a4093c 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -362,7 +362,7 @@ INSERT INTO `vn`.`contactChannel`(`id`, `name`) INSERT INTO `vn`.`client`(`id`,`name`,`fi`,`socialName`,`contact`,`street`,`city`,`postcode`,`phone`,`mobile`,`isRelevant`,`email`,`iban`,`dueDay`,`accountingAccount`,`isEqualizated`,`provinceFk`,`hasToInvoice`,`credit`,`countryFk`,`isActive`,`gestdocFk`,`quality`,`payMethodFk`,`created`,`isToBeMailed`,`contactChannelFk`,`hasSepaVnl`,`hasCoreVnl`,`hasCoreVnh`,`riskCalculated`,`clientTypeFk`, `hasToInvoiceByAddress`,`isTaxDataChecked`,`isFreezed`,`creditInsurance`,`isCreatedAsServed`,`hasInvoiceSimplified`,`salesPersonFk`,`isVies`,`eypbc`, `businessTypeFk`,`typeFk`) VALUES - (1101, 'Bruce Wayne', '84612325V', 'BATMAN', 'Alfred', '1007 MOUNTAIN DRIVE, GOTHAM', 'Gotham', 46460, 1111111111, 222222222, 1, 'BruceWayne@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1, 'florist','loses'), + (1101, 'Bruce Wayne', '84612325V', 'BATMAN', 'Alfred', '1007 MOUNTAIN DRIVE, GOTHAM', 'Gotham', 46460, 1111111111, 222222222, 1, 'BruceWayne@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1, 'florist','normal'), (1102, 'Petter Parker', '87945234L', 'SPIDER MAN', 'Aunt May', '20 INGRAM STREET, QUEENS, USA', 'Gotham', 46460, 1111111111, 222222222, 1, 'PetterParker@mydomain.com', NULL, 0, 1234567890, 0, 2, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1, 'florist','normal'), (1103, 'Clark Kent', '06815934E', 'SUPER MAN', 'lois lane', '344 CLINTON STREET, APARTAMENT 3-D', 'Gotham', 46460, 1111111111, 222222222, 1, 'ClarkKent@mydomain.com', NULL, 0, 1234567890, 0, 3, 1, 0, 19, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1, 'florist','normal'), (1104, 'Tony Stark', '06089160W', 'IRON MAN', 'Pepper Potts', '10880 MALIBU POINT, 90265', 'Gotham', 46460, 1111111111, 222222222, 1, 'TonyStark@mydomain.com', NULL, 0, 1234567890, 0, 2, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1, 'florist','normal'), @@ -372,8 +372,8 @@ INSERT INTO `vn`.`client`(`id`,`name`,`fi`,`socialName`,`contact`,`street`,`city (1108, 'Charles Xavier', '22641921P', 'PROFESSOR X', 'Beast', '3800 VICTORY PKWY, CINCINNATI, OH 45207, USA', 'Gotham', 46460, 1111111111, 222222222, 1, 'CharlesXavier@mydomain.com', NULL, 0, 1234567890, 0, 5, 1, 300, 13, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 1, NULL, 0, 0, 19, 0, 1, 'florist','normal'), (1109, 'Bruce Banner', '16104829E', 'HULK', 'Black widow', 'SOMEWHERE IN NEW YORK', 'Gotham', 46460, 1111111111, 222222222, 1, 'BruceBanner@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, 0, NULL, 0, 0, 9, 0, 1, 'florist','normal'), (1110, 'Jessica Jones', '58282869H', 'JESSICA JONES', 'Luke Cage', 'NYCC 2015 POSTER', 'Gotham', 46460, 1111111111, 222222222, 1, 'JessicaJones@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, 0, NULL, 0, 0, NULL, 0, 1, 'florist','normal'), - (1111, 'Missing', NULL, 'MISSING MAN', 'Anton', 'THE SPACE, UNIVERSE FAR AWAY', 'Gotham', 46460, 1111111111, 222222222, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 4, 0, 1, 0, NULL, 1, 0, NULL, 0, 1, 'others','normal'), - (1112, 'Trash', NULL, 'GARBAGE MAN', 'Unknown name', 'NEW YORK CITY, UNDERGROUND', 'Gotham', 46460, 1111111111, 222222222, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 4, 0, 1, 0, NULL, 1, 0, NULL, 0, 1, 'others','normal'); + (1111, 'Missing', NULL, 'MISSING MAN', 'Anton', 'THE SPACE, UNIVERSE FAR AWAY', 'Gotham', 46460, 1111111111, 222222222, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 4, 0, 1, 0, NULL, 1, 0, NULL, 0, 1, 'others','loses'), + (1112, 'Trash', NULL, 'GARBAGE MAN', 'Unknown name', 'NEW YORK CITY, UNDERGROUND', 'Gotham', 46460, 1111111111, 222222222, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 4, 0, 1, 0, NULL, 1, 0, NULL, 0, 1, 'others','loses'); INSERT INTO `vn`.`client`(`id`, `name`, `fi`, `socialName`, `contact`, `street`, `city`, `postcode`, `isRelevant`, `email`, `iban`,`dueDay`,`accountingAccount`, `isEqualizated`, `provinceFk`, `hasToInvoice`, `credit`, `countryFk`, `isActive`, `gestdocFk`, `quality`, `payMethodFk`,`created`, `isTaxDataChecked`) SELECT id, name, CONCAT(RPAD(CONCAT(id,9),8,id),'A'), CONCAT(name, 'Social'), CONCAT(name, 'Contact'), CONCAT(name, 'Street'), 'GOTHAM', 46460, 1, CONCAT(name,'@mydomain.com'), NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1,NULL, 10, 5, util.VN_CURDATE(), 1 diff --git a/modules/monitor/back/methods/sales-monitor/specs/salesFilter.spec.js b/modules/monitor/back/methods/sales-monitor/specs/salesFilter.spec.js index c3da7f08b..bdafd14e2 100644 --- a/modules/monitor/back/methods/sales-monitor/specs/salesFilter.spec.js +++ b/modules/monitor/back/methods/sales-monitor/specs/salesFilter.spec.js @@ -151,7 +151,7 @@ describe('SalesMonitor salesFilter()', () => { const result = await models.SalesMonitor.salesFilter(ctx, filter, options); const firstRow = result[0]; - expect(result.length).toEqual(15); + expect(result.length).toEqual(12); expect(firstRow.alertLevel).not.toEqual(0); await tx.rollback(); diff --git a/modules/ticket/back/methods/ticket/specs/filter.spec.js b/modules/ticket/back/methods/ticket/specs/filter.spec.js index 2e5730980..43f3c3680 100644 --- a/modules/ticket/back/methods/ticket/specs/filter.spec.js +++ b/modules/ticket/back/methods/ticket/specs/filter.spec.js @@ -68,7 +68,7 @@ describe('ticket filter()', () => { const filter = {}; const result = await models.Ticket.filter(ctx, filter, options); - expect(result.length).toEqual(9); + expect(result.length).toEqual(6); await tx.rollback(); } catch (e) { diff --git a/modules/ticket/back/methods/ticket/specs/getSalespersonMana.spec.js b/modules/ticket/back/methods/ticket/specs/getSalespersonMana.spec.js index 12c115ff9..6029ca4a7 100644 --- a/modules/ticket/back/methods/ticket/specs/getSalespersonMana.spec.js +++ b/modules/ticket/back/methods/ticket/specs/getSalespersonMana.spec.js @@ -9,7 +9,7 @@ describe('ticket getSalesPersonMana()', () => { const mana = await models.Ticket.getSalesPersonMana(1, options); - expect(mana).toEqual(73); + expect(mana).toEqual(124); await tx.rollback(); } catch (e) { From f2673c38183ef06dd7c8ed7e04bddd842b53ab52 Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 28 Nov 2023 12:12:42 +0100 Subject: [PATCH 411/427] refs #5835 rate added --- modules/invoiceIn/back/methods/invoice-in/summary.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/invoiceIn/back/methods/invoice-in/summary.js b/modules/invoiceIn/back/methods/invoice-in/summary.js index 0e55eeaac..fe198b2b4 100644 --- a/modules/invoiceIn/back/methods/invoice-in/summary.js +++ b/modules/invoiceIn/back/methods/invoice-in/summary.js @@ -112,7 +112,7 @@ module.exports = Self => { { relation: 'taxTypeSage', scope: { - fields: ['vat'] + fields: ['vat', 'rate'] } }] } From 63533459b0991abf3c3d67492c1739780f7bbd98 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Tue, 28 Nov 2023 13:22:17 +0100 Subject: [PATCH 412/427] refs #6434 feat: improve signIn method --- back/methods/vn-user/sign-in.js | 8 +--- back/methods/vn-user/specs/sign-in.spec.js | 15 +++--- back/models/vn-user.js | 47 ++++++++++++++----- db/changes/234901/00-createSignInLogTable.sql | 15 ++++++ modules/account/back/models/sign_in-log.json | 7 ++- 5 files changed, 66 insertions(+), 26 deletions(-) create mode 100644 db/changes/234901/00-createSignInLogTable.sql diff --git a/back/methods/vn-user/sign-in.js b/back/methods/vn-user/sign-in.js index 9c2d568f4..782046641 100644 --- a/back/methods/vn-user/sign-in.js +++ b/back/methods/vn-user/sign-in.js @@ -49,13 +49,7 @@ module.exports = Self => { if (vnUser.twoFactor) throw new ForbiddenError(null, 'REQUIRES_2FA'); } - const validateLogin = await Self.validateLogin(user, password); - await Self.app.models.SignInLog.create({ - token: validateLogin.token, - userFk: vnUser.id, - ip: ctx.req.ip - }); - return validateLogin; + return Self.validateLogin(user, password, ctx); }; Self.passExpired = async vnUser => { diff --git a/back/methods/vn-user/specs/sign-in.spec.js b/back/methods/vn-user/specs/sign-in.spec.js index ac2dfe2b2..1c4b4af51 100644 --- a/back/methods/vn-user/specs/sign-in.spec.js +++ b/back/methods/vn-user/specs/sign-in.spec.js @@ -2,7 +2,7 @@ const {models} = require('vn-loopback/server/server'); describe('VnUser Sign-in()', () => { const employeeId = 1; - const unauthCtx = { + const unAuthCtx = { req: { headers: {}, connection: { @@ -15,20 +15,21 @@ describe('VnUser Sign-in()', () => { const {VnUser, AccessToken, SignInLog} = models; describe('when credentials are correct', () => { it('should return the token if user uses email', async() => { - let login = await VnUser.signIn(unauthCtx, 'salesAssistant@mydomain.com', 'nightmare'); + let login = await VnUser.signIn(unAuthCtx, 'salesAssistant@mydomain.com', 'nightmare'); let accessToken = await AccessToken.findById(login.token); let ctx = {req: {accessToken: accessToken}}; let signInLog = await SignInLog.find({where: {token: accessToken.id}}); expect(signInLog.length).toEqual(1); expect(signInLog[0].userFk).toEqual(accessToken.userId); + expect(signInLog[0].owner).toEqual(true); expect(login.token).toBeDefined(); await VnUser.logout(ctx.req.accessToken.id); }); it('should return the token', async() => { - let login = await VnUser.signIn(unauthCtx, 'salesAssistant', 'nightmare'); + let login = await VnUser.signIn(unAuthCtx, 'salesAssistant', 'nightmare'); let accessToken = await AccessToken.findById(login.token); let ctx = {req: {accessToken: accessToken}}; @@ -38,7 +39,7 @@ describe('VnUser Sign-in()', () => { }); it('should return the token if the user doesnt exist but the client does', async() => { - let login = await VnUser.signIn(unauthCtx, 'PetterParker', 'nightmare'); + let login = await VnUser.signIn(unAuthCtx, 'PetterParker', 'nightmare'); let accessToken = await AccessToken.findById(login.token); let ctx = {req: {accessToken: accessToken}}; @@ -53,7 +54,7 @@ describe('VnUser Sign-in()', () => { let error; try { - await VnUser.signIn(unauthCtx, 'IDontExist', 'TotallyWrongPassword'); + await VnUser.signIn(unAuthCtx, 'IDontExist', 'TotallyWrongPassword'); } catch (e) { error = e; } @@ -74,7 +75,7 @@ describe('VnUser Sign-in()', () => { const options = {transaction: tx}; await employee.updateAttribute('twoFactor', 'email', options); - await VnUser.signIn(unauthCtx, 'employee', 'nightmare', options); + await VnUser.signIn(unAuthCtx, 'employee', 'nightmare', options); await tx.rollback(); } catch (e) { await tx.rollback(); @@ -99,7 +100,7 @@ describe('VnUser Sign-in()', () => { const options = {transaction: tx}; await employee.updateAttribute('passExpired', yesterday, options); - await VnUser.signIn(unauthCtx, 'employee', 'nightmare', options); + await VnUser.signIn(unAuthCtx, 'employee', 'nightmare', options); await tx.rollback(); } catch (e) { await tx.rollback(); diff --git a/back/models/vn-user.js b/back/models/vn-user.js index 719e96cbf..6b9b9bab5 100644 --- a/back/models/vn-user.js +++ b/back/models/vn-user.js @@ -124,20 +124,43 @@ module.exports = function(Self) { return email.send(); }); - Self.signInValidate = (user, userToken) => { + + /** + * Sign-in validate. * + * @param {Integer} user The user + * @param {Object} userToken Options + * @param {Object} token accessToken + * @param {Object} ctx context + */ + Self.signInValidate = async(user, userToken, token, ctx) => { const [[key, value]] = Object.entries(Self.userUses(user)); - if (userToken[key].toLowerCase().trim() !== value.toLowerCase().trim()) { - console.error('ERROR!!! - Signin with other user', userToken, user); + const isOwner = Self.rawSql(`SELECT ? = ? `, [userToken[key], value]); + await Self.app.models.SignInLog.create({ + token: token.id, + userFk: userToken.id, + ip: ctx.req.ip, + owner: isOwner + }); + if (!isOwner) { + console.error('ERROR!!! - SignIn with other user', userToken, user); throw new UserError('Try again'); } }; - Self.validateLogin = async function(user, password) { + /** + * Validate login params* + * @param {String} user The user + * @param {String} password + * @param {Object} ctx context + */ + Self.validateLogin = async function(user, password, ctx) { const loginInfo = Object.assign({password}, Self.userUses(user)); const token = await Self.login(loginInfo, 'user'); const userToken = await token.user.get(); - Self.signInValidate(user, userToken); + + if (ctx) + await Self.signInValidate(user, userToken, token, ctx); try { await Self.app.models.Account.sync(userToken.name, password); @@ -187,8 +210,8 @@ module.exports = function(Self) { }; Self.sharedClass._methods.find(method => method.name == 'changePassword').ctor.settings.acls = - Self.sharedClass._methods.find(method => method.name == 'changePassword').ctor.settings.acls - .filter(acl => acl.property != 'changePassword'); + Self.sharedClass._methods.find(method => method.name == 'changePassword').ctor.settings.acls + .filter(acl => acl.property != 'changePassword'); Self.userSecurity = async(ctx, userId, options) => { const models = Self.app.models; @@ -226,10 +249,12 @@ module.exports = function(Self) { const env = process.env.NODE_ENV; const liliumUrl = await Self.app.models.Url.findOne({ - where: {and: [ - {appName: 'lilium'}, - {environment: env} - ]} + where: { + and: [ + {appName: 'lilium'}, + {environment: env} + ] + } }); class Mailer { diff --git a/db/changes/234901/00-createSignInLogTable.sql b/db/changes/234901/00-createSignInLogTable.sql new file mode 100644 index 000000000..f77268375 --- /dev/null +++ b/db/changes/234901/00-createSignInLogTable.sql @@ -0,0 +1,15 @@ + +DROP TABLE IF EXISTS `account`.`signInLog`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `account`.`signInLog` ( + id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, + `token` varchar(255) NOT NULL , + `userFk` int(10) unsigned DEFAULT NULL, + `creationDate` timestamp NULL DEFAULT current_timestamp(), + `ip` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, + `owner` tinyint(1) DEFAULT 1, + KEY `userFk` (`userFk`), + CONSTRAINT `signInLog_ibfk_1` FOREIGN KEY (`userFk`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +); + diff --git a/modules/account/back/models/sign_in-log.json b/modules/account/back/models/sign_in-log.json index c5c014e60..0da3dc3dd 100644 --- a/modules/account/back/models/sign_in-log.json +++ b/modules/account/back/models/sign_in-log.json @@ -25,7 +25,12 @@ "type": "number" }, "ip": { - "type": "string" + "type": "string" + }, + "owner": { + "type": "boolean", + "required": true, + "default": true } }, "relations": { From 2e22984e77de749f76d93f36821350160c3ad138 Mon Sep 17 00:00:00 2001 From: alexm Date: Wed, 29 Nov 2023 09:13:54 +0100 Subject: [PATCH 413/427] refs #6197 fix: add salix role in fixtures --- db/dump/fixtures.sql | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 93b7b796f..441026f43 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -1,3 +1,7 @@ +CREATE ROLE 'salix'; +GRANT 'salix' TO 'root'@'%'; +SET DEFAULT ROLE 'salix' FOR 'root'@'%'; + CREATE SCHEMA IF NOT EXISTS `vn2008`; CREATE SCHEMA IF NOT EXISTS `tmp`; From 48b82b02cad3501d599c4ef688942de5f0ecf807 Mon Sep 17 00:00:00 2001 From: JAVIER SEGARRA MARTINEZ Date: Wed, 29 Nov 2023 19:32:10 +0000 Subject: [PATCH 414/427] refs #6434 change param type for signInValidate --- back/models/vn-user.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/back/models/vn-user.js b/back/models/vn-user.js index 6b9b9bab5..e32d83a36 100644 --- a/back/models/vn-user.js +++ b/back/models/vn-user.js @@ -127,7 +127,7 @@ module.exports = function(Self) { /** * Sign-in validate. * - * @param {Integer} user The user + * @param {String} user The user * @param {Object} userToken Options * @param {Object} token accessToken * @param {Object} ctx context From ed6c0924d794e1a99a1f08e9c69ba55303120c24 Mon Sep 17 00:00:00 2001 From: JAVIER SEGARRA MARTINEZ Date: Wed, 29 Nov 2023 19:33:04 +0000 Subject: [PATCH 415/427] refs #6434 perf: remove console.error --- back/models/vn-user.js | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/back/models/vn-user.js b/back/models/vn-user.js index e32d83a36..288bd4d1f 100644 --- a/back/models/vn-user.js +++ b/back/models/vn-user.js @@ -141,10 +141,8 @@ module.exports = function(Self) { ip: ctx.req.ip, owner: isOwner }); - if (!isOwner) { - console.error('ERROR!!! - SignIn with other user', userToken, user); + if (!isOwner) throw new UserError('Try again'); - } }; /** From 9176cdb4cbed343727f470d01bc0cfff9a65ad8b Mon Sep 17 00:00:00 2001 From: JAVIER SEGARRA MARTINEZ Date: Wed, 29 Nov 2023 19:34:00 +0000 Subject: [PATCH 416/427] refs #6434 perf: new field in SignInLog table --- back/models/vn-user.js | 1 + 1 file changed, 1 insertion(+) diff --git a/back/models/vn-user.js b/back/models/vn-user.js index 288bd4d1f..ad0f88d8c 100644 --- a/back/models/vn-user.js +++ b/back/models/vn-user.js @@ -136,6 +136,7 @@ module.exports = function(Self) { const [[key, value]] = Object.entries(Self.userUses(user)); const isOwner = Self.rawSql(`SELECT ? = ? `, [userToken[key], value]); await Self.app.models.SignInLog.create({ + userName: user, token: token.id, userFk: userToken.id, ip: ctx.req.ip, From 46774b2e73b42fefa147803770e54adfd992a06c Mon Sep 17 00:00:00 2001 From: JAVIER SEGARRA MARTINEZ Date: Wed, 29 Nov 2023 19:35:37 +0000 Subject: [PATCH 417/427] refs #6434 perf: new field in SignInLog table --- db/changes/234901/00-createSignInLogTable.sql | 1 + 1 file changed, 1 insertion(+) diff --git a/db/changes/234901/00-createSignInLogTable.sql b/db/changes/234901/00-createSignInLogTable.sql index f77268375..49187c9cb 100644 --- a/db/changes/234901/00-createSignInLogTable.sql +++ b/db/changes/234901/00-createSignInLogTable.sql @@ -7,6 +7,7 @@ CREATE TABLE `account`.`signInLog` ( `token` varchar(255) NOT NULL , `userFk` int(10) unsigned DEFAULT NULL, `creationDate` timestamp NULL DEFAULT current_timestamp(), + `userName` varchar(30) NOT NULL, `ip` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, `owner` tinyint(1) DEFAULT 1, KEY `userFk` (`userFk`), From 1576ab992d2cc6a4b5f1e89efa5c2c6136c52634 Mon Sep 17 00:00:00 2001 From: JAVIER SEGARRA MARTINEZ Date: Wed, 29 Nov 2023 19:36:30 +0000 Subject: [PATCH 418/427] refs #6434 perf: new field in SignInLog table --- modules/account/back/models/sign_in-log.json | 3 +++ 1 file changed, 3 insertions(+) diff --git a/modules/account/back/models/sign_in-log.json b/modules/account/back/models/sign_in-log.json index 0da3dc3dd..8656e92dc 100644 --- a/modules/account/back/models/sign_in-log.json +++ b/modules/account/back/models/sign_in-log.json @@ -27,6 +27,9 @@ "ip": { "type": "string" }, + "userName": { + "type": "string" + }, "owner": { "type": "boolean", "required": true, From 138d11b7b0cb72c3b0d91fa553eaf32cfba5b8de Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Thu, 30 Nov 2023 08:10:32 +0100 Subject: [PATCH 419/427] refs #6434 perf new version folder for sql file --- db/changes/{234604 => 264802}/00-createSignInLogTable.sql | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename db/changes/{234604 => 264802}/00-createSignInLogTable.sql (100%) diff --git a/db/changes/234604/00-createSignInLogTable.sql b/db/changes/264802/00-createSignInLogTable.sql similarity index 100% rename from db/changes/234604/00-createSignInLogTable.sql rename to db/changes/264802/00-createSignInLogTable.sql From 6b354a20adc64aed73826740de80839051aca1c0 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Thu, 30 Nov 2023 08:13:28 +0100 Subject: [PATCH 420/427] refs #6434 perf: add sql table description --- db/changes/234901/00-createSignInLogTable.sql | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/db/changes/234901/00-createSignInLogTable.sql b/db/changes/234901/00-createSignInLogTable.sql index 49187c9cb..942f651c9 100644 --- a/db/changes/234901/00-createSignInLogTable.sql +++ b/db/changes/234901/00-createSignInLogTable.sql @@ -1,4 +1,9 @@ +-- +-- Table structure for table `signInLog` +-- Description: log to debug cross-login error +-- + DROP TABLE IF EXISTS `account`.`signInLog`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; From 58855a7cddb75720369e9eb596f96f0e16f8f692 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Thu, 30 Nov 2023 08:14:56 +0100 Subject: [PATCH 421/427] refs #6434 perf: remove bad characters method description --- back/models/vn-user.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/back/models/vn-user.js b/back/models/vn-user.js index ad0f88d8c..e14cd30ea 100644 --- a/back/models/vn-user.js +++ b/back/models/vn-user.js @@ -126,7 +126,7 @@ module.exports = function(Self) { }); /** - * Sign-in validate. * + * Sign-in validate * @param {String} user The user * @param {Object} userToken Options * @param {Object} token accessToken @@ -147,7 +147,7 @@ module.exports = function(Self) { }; /** - * Validate login params* + * Validate login params * @param {String} user The user * @param {String} password * @param {Object} ctx context From 80f8037f58f72f0e3ecdf34755d81422951eebe8 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Thu, 30 Nov 2023 08:23:14 +0100 Subject: [PATCH 422/427] refs #6434 perf remove version folder for sql file --- db/changes/264802/00-createSignInLogTable.sql | 20 ------------------- 1 file changed, 20 deletions(-) delete mode 100644 db/changes/264802/00-createSignInLogTable.sql diff --git a/db/changes/264802/00-createSignInLogTable.sql b/db/changes/264802/00-createSignInLogTable.sql deleted file mode 100644 index 525348135..000000000 --- a/db/changes/264802/00-createSignInLogTable.sql +++ /dev/null @@ -1,20 +0,0 @@ - - --- --- Table structure for table `signInLog` --- Description: log to debug cross-login error --- - -DROP TABLE IF EXISTS `account`.`signInLog`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `account`.`signInLog` ( - id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, - `token` varchar(255) NOT NULL , - `userFk` int(10) unsigned DEFAULT NULL, - `creationDate` timestamp NULL DEFAULT current_timestamp(), - `ip` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, - KEY `userFk` (`userFk`), - CONSTRAINT `signInLog_ibfk_1` FOREIGN KEY (`userFk`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -); - From 7611acb8f2d156358b8d4699594cfbc2ac3157f6 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Thu, 30 Nov 2023 08:34:10 +0100 Subject: [PATCH 423/427] refs #6434 perf rename version folder for sql file --- db/changes/{234901 => 234802}/00-createSignInLogTable.sql | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename db/changes/{234901 => 234802}/00-createSignInLogTable.sql (100%) diff --git a/db/changes/234901/00-createSignInLogTable.sql b/db/changes/234802/00-createSignInLogTable.sql similarity index 100% rename from db/changes/234901/00-createSignInLogTable.sql rename to db/changes/234802/00-createSignInLogTable.sql From 9cdb7c3ccab620912c1a4bb9c7c7ac955895c00e Mon Sep 17 00:00:00 2001 From: carlossa Date: Thu, 30 Nov 2023 09:18:00 +0100 Subject: [PATCH 424/427] refs #6065 remove workcenter --- modules/worker/front/time-control/index.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/modules/worker/front/time-control/index.js b/modules/worker/front/time-control/index.js index f8a94be52..f6a6ed535 100644 --- a/modules/worker/front/time-control/index.js +++ b/modules/worker/front/time-control/index.js @@ -111,8 +111,10 @@ class Controller extends Section { dayIndex.setDate(dayIndex.getDate() + 1); } - this.fetchHours(); - this.getWeekData(); + if (this.worker) { + this.fetchHours(); + this.getWeekData(); + } } set weekTotalHours(totalHours) { @@ -171,8 +173,6 @@ class Controller extends Section { ]} }; this.$.model.applyFilter(filter, params).then(() => { - if (!this.card.hasWorkCenter) return; - this.getWorkedHours(this.started, this.ended); this.getAbsences(); }); From 3f22f48df728e16624d86985df9e180ad448e510 Mon Sep 17 00:00:00 2001 From: pablone Date: Thu, 30 Nov 2023 12:13:12 +0100 Subject: [PATCH 425/427] fix(getFiltered): refs #3271 fix to event filter --- db/dump/fixtures.sql | 6 +- .../back/methods/route/getExternalCmrs.js | 190 +++++++++--------- .../back/methods/zone/getEventsFiltered.js | 57 +++--- .../zone/specs/getEventsFiltered.spec.js | 10 +- 4 files changed, 133 insertions(+), 130 deletions(-) diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 788487ed0..a0b97b34e 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -2343,9 +2343,11 @@ INSERT INTO `vn`.`zoneEvent`(`zoneFk`, `type`, `weekDays`) (8, 'indefinitely', 'mon,tue,wed,thu,fri,sat,sun'), (10, 'indefinitely', 'mon,tue,wed,thu,fri,sat,sun'); -INSERT INTO `vn`.`zoneEvent`(`zoneFk`, `type`, `started`, `ended`) +INSERT INTO `vn`.`zoneEvent`(`zoneFk`, `type`, `started`, `ended`, `weekDays`) VALUES - (9, 'range', DATE_ADD(util.VN_CURDATE(), INTERVAL -1 YEAR), DATE_ADD(util.VN_CURDATE(), INTERVAL +1 YEAR)); + (9, 'range', DATE_ADD(util.VN_CURDATE(), INTERVAL -1 YEAR), DATE_ADD(util.VN_CURDATE(), INTERVAL +1 YEAR), 'mon'), + (9, 'range', util.VN_CURDATE(), NULL, 'tue'), + (9, 'range', NULL, util.VN_CURDATE(), 'wed'); INSERT INTO `vn`.`workerTimeControl`(`userFk`, `timed`, `manual`, `direction`, `isSendMail`) VALUES diff --git a/modules/route/back/methods/route/getExternalCmrs.js b/modules/route/back/methods/route/getExternalCmrs.js index 4750e53a1..3fc9798b0 100644 --- a/modules/route/back/methods/route/getExternalCmrs.js +++ b/modules/route/back/methods/route/getExternalCmrs.js @@ -3,99 +3,101 @@ const buildFilter = require('vn-loopback/util/filter').buildFilter; const mergeFilters = require('vn-loopback/util/filter').mergeFilters; module.exports = Self => { - Self.remoteMethod('getExternalCmrs', { - description: 'Returns an array of external cmrs', - accessType: 'READ', - accepts: [ - { - arg: 'filter', - type: 'object', - description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string', - }, - { - arg: 'cmrFk', - type: 'integer', - description: 'Searchs the route by id', - }, - { - arg: 'ticketFk', - type: 'integer', - description: 'The worker id', - }, - { - arg: 'routeFk', - type: 'integer', - description: 'The route id', - }, - { - arg: 'country', - type: 'string', - description: 'The agencyMode id', - }, - { - arg: 'clientFk', - type: 'integer', - description: 'The vehicle id', - }, - { - arg: 'hasCmrDms', - type: 'boolean', - description: 'The vehicle id', - }, - { - arg: 'shipped', - type: 'date', - description: 'The to date filter', - }, - ], - returns: { - type: ['object'], - root: true - }, - http: { - path: `/getExternalCmrs`, - verb: 'GET' - } - }); + Self.remoteMethod('getExternalCmrs', { + description: 'Returns an array of external cmrs', + accessType: 'READ', + accepts: [ + { + arg: 'filter', + type: 'object', + description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string', + }, + { + arg: 'cmrFk', + type: 'integer', + description: 'Searchs the route by id', + }, + { + arg: 'ticketFk', + type: 'integer', + description: 'The worker id', + }, + { + arg: 'routeFk', + type: 'integer', + description: 'The route id', + }, + { + arg: 'country', + type: 'string', + description: 'The agencyMode id', + }, + { + arg: 'clientFk', + type: 'integer', + description: 'The vehicle id', + }, + { + arg: 'hasCmrDms', + type: 'boolean', + description: 'The vehicle id', + }, + { + arg: 'shipped', + type: 'date', + description: 'The to date filter', + }, + ], + returns: { + type: ['object'], + root: true + }, + http: { + path: `/getExternalCmrs`, + verb: 'GET' + } + }); - Self.getExternalCmrs = async( - filter, - cmrFk, - ticketFk, - routeFk, - country, - clientFk, - hasCmrDms, - shipped, - options - ) => { - const params = { - cmrFk, - ticketFk, - routeFk, - country, - clientFk, - hasCmrDms, - shipped, - }; - const conn = Self.dataSource.connector; + Self.getExternalCmrs = async( + filter, + cmrFk, + ticketFk, + routeFk, + country, + clientFk, + hasCmrDms, + shipped, + options + ) => { + const params = { + cmrFk, + ticketFk, + routeFk, + country, + clientFk, + hasCmrDms, + shipped, + }; + const conn = Self.dataSource.connector; - let where = buildFilter(params, (param, value) => {return {[param]: value}}); - filter = mergeFilters(filter, {where}); + let where = buildFilter(params, (param, value) => { + return {[param]: value}; + }); + filter = mergeFilters(filter, {where}); - if (!filter.where) { - const yesterday = new Date(); - yesterday.setDate(yesterday.getDate() - 1); - filter.where = {'shipped': yesterday.toISOString().split('T')[0]} - } + if (!filter.where) { + const yesterday = new Date(); + yesterday.setDate(yesterday.getDate() - 1); + filter.where = {'shipped': yesterday.toISOString().split('T')[0]}; + } - const myOptions = {}; + const myOptions = {}; - if (typeof options == 'object') - Object.assign(myOptions, options); + if (typeof options == 'object') + Object.assign(myOptions, options); - let stmts = []; - const stmt = new ParameterizedSQL(` + let stmts = []; + const stmt = new ParameterizedSQL(` SELECT * FROM ( SELECT t.cmrFk, @@ -129,13 +131,13 @@ module.exports = Self => { AND dm.code = 'DELIVERY' AND t.cmrFk ) sub - `); + `); - stmt.merge(conn.makeSuffix(filter)); - const itemsIndex = stmts.push(stmt) - 1; + stmt.merge(conn.makeSuffix(filter)); + const itemsIndex = stmts.push(stmt) - 1; - const sql = ParameterizedSQL.join(stmts, ';'); - const result = await conn.executeStmt(sql); - return itemsIndex === 0 ? result : result[itemsIndex]; - }; + const sql = ParameterizedSQL.join(stmts, ';'); + const result = await conn.executeStmt(sql); + return itemsIndex === 0 ? result : result[itemsIndex]; + }; }; diff --git a/modules/zone/back/methods/zone/getEventsFiltered.js b/modules/zone/back/methods/zone/getEventsFiltered.js index b7875785d..85db76a58 100644 --- a/modules/zone/back/methods/zone/getEventsFiltered.js +++ b/modules/zone/back/methods/zone/getEventsFiltered.js @@ -35,44 +35,39 @@ module.exports = Self => { if (typeof options == 'object') Object.assign(myOptions, options); - query = ` - SELECT * - FROM vn.zoneEvent - WHERE zoneFk = ? - AND ((type = 'indefinitely') - OR (type = 'day' AND dated BETWEEN ? AND ?) - OR (type = 'range' - AND ( - (started BETWEEN ? AND ?) - OR - (ended BETWEEN ? AND ?) - OR - (started <= ? AND ended >= ?) - ) - ) - ) - ORDER BY type='indefinitely' DESC, type='range' DESC, type='day' DESC;`; - const events = await Self.rawSql(query, - [zoneFk, started, ended, started, ended, started, ended, started, ended], myOptions); + ended = simpleDate(ended); + started = simpleDate(started); query = ` - SELECT e.* - FROM vn.zoneExclusion e - LEFT JOIN vn.zoneExclusionGeo eg ON eg.zoneExclusionFk = e.id - WHERE e.zoneFk = ? - AND e.dated BETWEEN ? AND ? - AND eg.zoneExclusionFk IS NULL;`; + SELECT * + FROM vn.zoneEvent + WHERE zoneFk = ? + AND (IFNULL(started, ?) <= ? AND IFNULL(ended,?) >= ?) + ORDER BY type='indefinitely' DESC, type='range' DESC, type='day' DESC;`; + const events = await Self.rawSql(query, + [zoneFk, started, ended, ended, started], myOptions); + + query = ` + SELECT e.* + FROM vn.zoneExclusion e + LEFT JOIN vn.zoneExclusionGeo eg ON eg.zoneExclusionFk = e.id + WHERE e.zoneFk = ? + AND e.dated BETWEEN ? AND ? + AND eg.zoneExclusionFk IS NULL;`; const exclusions = await Self.rawSql(query, [zoneFk, started, ended], myOptions); query = ` - SELECT eg.*, e.zoneFk, e.dated, e.created, e.userFk - FROM vn.zoneExclusion e - LEFT JOIN vn.zoneExclusionGeo eg ON eg.zoneExclusionFk = e.id - WHERE e.zoneFk = ? - AND e.dated BETWEEN ? AND ? - AND eg.zoneExclusionFk IS NOT NULL;`; + SELECT eg.*, e.zoneFk, e.dated, e.created, e.userFk + FROM vn.zoneExclusion e + LEFT JOIN vn.zoneExclusionGeo eg ON eg.zoneExclusionFk = e.id + WHERE e.zoneFk = ? + AND e.dated BETWEEN ? AND ? + AND eg.zoneExclusionFk IS NOT NULL;`; const geoExclusions = await Self.rawSql(query, [zoneFk, started, ended], myOptions); return {events, exclusions, geoExclusions}; }; + function simpleDate(date) { + return date.toISOString().split('T')[0]; + } }; diff --git a/modules/zone/back/methods/zone/specs/getEventsFiltered.spec.js b/modules/zone/back/methods/zone/specs/getEventsFiltered.spec.js index 6fd6bb994..d1c7f1fc4 100644 --- a/modules/zone/back/methods/zone/specs/getEventsFiltered.spec.js +++ b/modules/zone/back/methods/zone/specs/getEventsFiltered.spec.js @@ -30,7 +30,7 @@ describe('zone getEventsFiltered()', () => { const result = await models.Zone.getEventsFiltered(9, today, today, options); - expect(result.events.length).toEqual(1); + expect(result.events.length).toEqual(3); expect(result.exclusions.length).toEqual(0); await tx.rollback(); @@ -47,11 +47,15 @@ describe('zone getEventsFiltered()', () => { const options = {transaction: tx}; const date = Date.vnNew(); date.setFullYear(date.getFullYear() - 2); - const dateTomorrow = new Date(date.setDate(date.getDate() + 1)); + const dateTomorrow = new Date(date); + dateTomorrow.setDate(dateTomorrow.getDate() + 1); const result = await models.Zone.getEventsFiltered(9, date, dateTomorrow, options); + console.log('dateTomorrow: ', dateTomorrow); + console.log('date: ', date); + console.log('result: ', result); - expect(result.events.length).toEqual(0); + expect(result.events.length).toEqual(1); expect(result.exclusions.length).toEqual(0); await tx.rollback(); From ab69dcd4fe5c182f71713de516ff12c40a29a792 Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 30 Nov 2023 12:32:41 +0100 Subject: [PATCH 426/427] refs #6524 fix: fixtures and feat: new changelog format --- CHANGELOG.md | 13 ++++++------- db/dump/fixtures.sql | 4 ++++ 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1f16511b6..70174ede3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,14 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [2348.01] - 2023-11-30 -### Added -- (Ticket -> Adelantar) Permite mover lineas sin generar negativos -- (Ticket -> Adelantar) Permite modificar la fecha de los tickets -- (Trabajadores -> Notificaciones) Nueva sección (lilium) +### Características Añadidas 🆕 +- **Tickets → Adelantar:** Permite mover lineas sin generar negativos +- **Tickets → Adelantar:** Permite modificar la fecha de los tickets +- **Trabajadores → Notificaciones:** Nueva sección (lilium) -### Changed -### Fixed -- (Ticket -> RocketChat) Arreglada detección de cambios +### Correcciones 🛠️ +- **Tickets → RocketChat:** Arreglada detección de cambios ## [2346.01] - 2023-11-16 diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 788487ed0..d9eed401e 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -1,6 +1,10 @@ CREATE SCHEMA IF NOT EXISTS `vn2008`; CREATE SCHEMA IF NOT EXISTS `tmp`; +CREATE ROLE 'salix'; +GRANT 'salix' TO 'root'@'%'; +SET DEFAULT ROLE 'salix' FOR 'root'@'%'; + UPDATE `util`.`config` SET `environment`= 'development'; From 72283005b80ee3fab6dbb25daa1e1258846a28a5 Mon Sep 17 00:00:00 2001 From: pablone Date: Thu, 30 Nov 2023 14:43:14 +0100 Subject: [PATCH 427/427] remove(console.log): refs #3271 remove console.log --- modules/zone/back/methods/zone/specs/getEventsFiltered.spec.js | 3 --- 1 file changed, 3 deletions(-) diff --git a/modules/zone/back/methods/zone/specs/getEventsFiltered.spec.js b/modules/zone/back/methods/zone/specs/getEventsFiltered.spec.js index d1c7f1fc4..7167b83de 100644 --- a/modules/zone/back/methods/zone/specs/getEventsFiltered.spec.js +++ b/modules/zone/back/methods/zone/specs/getEventsFiltered.spec.js @@ -51,9 +51,6 @@ describe('zone getEventsFiltered()', () => { dateTomorrow.setDate(dateTomorrow.getDate() + 1); const result = await models.Zone.getEventsFiltered(9, date, dateTomorrow, options); - console.log('dateTomorrow: ', dateTomorrow); - console.log('date: ', date); - console.log('result: ', result); expect(result.events.length).toEqual(1); expect(result.exclusions.length).toEqual(0);