From 6e4d7e8b01682e3327c82213d4b44a0cb12b30ec Mon Sep 17 00:00:00 2001 From: alexandre Date: Tue, 6 Jun 2023 10:31:08 +0200 Subject: [PATCH 001/212] 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 002/212] 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 003/212] 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 004/212] 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 005/212] 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 006/212] 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 007/212] 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 008/212] 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 009/212] 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 010/212] 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 011/212] 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 012/212] 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 8267daef3a80304060afe759f91276ac05c20ae3 Mon Sep 17 00:00:00 2001 From: vicent Date: Fri, 21 Jul 2023 12:58:44 +0200 Subject: [PATCH 013/212] 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 014/212] 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 015/212] 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 6eb88f8ab7f7923af915791f9adb4934bd708ee6 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Fri, 11 Aug 2023 11:58:30 +0200 Subject: [PATCH 016/212] 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 017/212] 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 018/212] 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 019/212] 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 020/212] 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 021/212] 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 022/212] =?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 4ae06d4b6b22a846bf5ad422898c0fb29d0a6bc4 Mon Sep 17 00:00:00 2001 From: pablone Date: Fri, 25 Aug 2023 07:36:52 +0200 Subject: [PATCH 023/212] 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 024/212] 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 025/212] 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 026/212] 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 0b9199688e786f3da556966fe6ec97dd6a82ad51 Mon Sep 17 00:00:00 2001 From: carlossa Date: Wed, 30 Aug 2023 12:48:57 +0200 Subject: [PATCH 027/212] 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 028/212] 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 c2a54b8c6590458094ec6cdc512bc00d556dccf4 Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 31 Aug 2023 13:02:56 +0200 Subject: [PATCH 029/212] 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 52d698b0ebdd622b24337c370e75ed932d5266e8 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 1 Sep 2023 12:38:35 +0200 Subject: [PATCH 030/212] 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:16:35 +0200 Subject: [PATCH 031/212] 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 032/212] 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 04d04e6598a37c424400c9855ad55c252e5cf9de Mon Sep 17 00:00:00 2001 From: pablone Date: Wed, 6 Sep 2023 13:59:28 +0200 Subject: [PATCH 033/212] 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 034/212] 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 035/212] 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 036/212] 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 e20a8d215ddbb365621db07b3e7028723a2e3e31 Mon Sep 17 00:00:00 2001 From: guillermo Date: Thu, 7 Sep 2023 11:47:33 +0200 Subject: [PATCH 037/212] 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 038/212] 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 039/212] 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 040/212] 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 041/212] 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 042/212] 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 043/212] 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 044/212] 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 705505b931a3398b5406bb993d00c2610ffdb366 Mon Sep 17 00:00:00 2001 From: jgallego Date: Mon, 11 Sep 2023 16:24:47 +0200 Subject: [PATCH 045/212] 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 046/212] 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 0ddcb57209845852889d1e16874bb1ff873b71a7 Mon Sep 17 00:00:00 2001 From: carlossa Date: Tue, 12 Sep 2023 10:40:10 +0200 Subject: [PATCH 047/212] 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 048/212] 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 049/212] 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 050/212] 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 a44e5206a7f2701f9195fd9af64ae3a538c342c1 Mon Sep 17 00:00:00 2001 From: pablone Date: Thu, 14 Sep 2023 14:18:00 +0200 Subject: [PATCH 051/212] 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 0912bd40f3d51572cbd7c5923c056a0163ea31b4 Mon Sep 17 00:00:00 2001 From: carlossa Date: Fri, 15 Sep 2023 09:15:48 +0200 Subject: [PATCH 052/212] 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 55b53c86c436ca42f76a34c045dc9f961303106a Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 18 Sep 2023 07:38:30 +0200 Subject: [PATCH 053/212] 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 054/212] 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 cdf0951a1b9106015ffcf187d4c3da96e2e889d6 Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 18 Sep 2023 10:12:32 +0200 Subject: [PATCH 055/212] 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 056/212] 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 057/212] 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 361c2b4cad3cfccaddb2d012055ecd72ed10a77d Mon Sep 17 00:00:00 2001 From: pablone Date: Tue, 19 Sep 2023 07:33:27 +0200 Subject: [PATCH 058/212] 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 059/212] 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 060/212] 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 f60b6b84fedb6e0ca9b0b75bf7c2fe48f2825a8a Mon Sep 17 00:00:00 2001 From: carlossa Date: Wed, 20 Sep 2023 11:58:36 +0200 Subject: [PATCH 061/212] 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 062/212] 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 063/212] 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 064/212] 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 065/212] 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 4761b0f7840c78d0ce8fbef765feec97fc834d9a Mon Sep 17 00:00:00 2001 From: jgallego Date: Thu, 21 Sep 2023 10:41:20 +0200 Subject: [PATCH 066/212] =?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 067/212] 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 068/212] 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 069/212] 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 070/212] 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 c7e26f9155e3be023a7f7bdbc745fae1e5b6c23a Mon Sep 17 00:00:00 2001 From: carlossa Date: Fri, 22 Sep 2023 06:08:07 +0200 Subject: [PATCH 071/212] 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 072/212] 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 073/212] 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 074/212] 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 075/212] 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 076/212] 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 077/212] 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 078/212] 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 079/212] 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 9b10a2904c39fd5d6931dd796bb43759a574983c Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 25 Sep 2023 08:23:23 +0200 Subject: [PATCH 080/212] 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 081/212] 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 082/212] 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 13:06:28 +0200 Subject: [PATCH 083/212] 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 084/212] 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 db8dc8487b7ba76a507259a024c13a0f802b7b1f Mon Sep 17 00:00:00 2001 From: jorgep Date: Mon, 25 Sep 2023 15:28:08 +0200 Subject: [PATCH 085/212] 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 086/212] 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 087/212] 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 2ea2943ecadc3f660b8c389cb7ac47e4db73983d Mon Sep 17 00:00:00 2001 From: sergiodt Date: Tue, 26 Sep 2023 13:12:18 +0200 Subject: [PATCH 088/212] 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 089/212] 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 090/212] 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 091/212] 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 092/212] 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 093/212] 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 094/212] 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 095/212] 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 d4e5815d417122c905e7583ef314311d21793fcf Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 28 Sep 2023 08:30:50 +0200 Subject: [PATCH 096/212] 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 097/212] 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 098/212] 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 099/212] 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 100/212] 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 101/212] 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 102/212] 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 103/212] 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 104/212] 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 105/212] =?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 106/212] 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 107/212] 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 b33700abc93d568d554e5715d05a192b62f226e5 Mon Sep 17 00:00:00 2001 From: alexm Date: Fri, 29 Sep 2023 11:57:25 +0200 Subject: [PATCH 108/212] 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 109/212] 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 110/212] 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 111/212] 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 112/212] 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 113/212] 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 114/212] 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 115/212] 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 116/212] 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 117/212] 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 118/212] 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 119/212] 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 120/212] 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 121/212] 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 122/212] 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 123/212] 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 124/212] 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 125/212] 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 126/212] 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 127/212] 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 128/212] 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 129/212] 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 130/212] 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 131/212] 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 132/212] 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 133/212] 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 134/212] 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 135/212] 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 136/212] 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 137/212] 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 138/212] 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 139/212] 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 140/212] 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 141/212] 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 142/212] 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 143/212] 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 144/212] 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 145/212] 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 146/212] 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 147/212] 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 148/212] 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 149/212] =?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 150/212] 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 151/212] 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 152/212] 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 153/212] 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 154/212] 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 155/212] 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 156/212] 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 157/212] 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 158/212] 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 159/212] 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 160/212] 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 161/212] 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 162/212] 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 163/212] 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 164/212] 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 165/212] 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 166/212] 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 167/212] =?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 168/212] 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 169/212] 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 170/212] 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 171/212] 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 172/212] 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 173/212] 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 174/212] =?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 175/212] 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 176/212] 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 177/212] 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 178/212] 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 179/212] 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 180/212] 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 181/212] 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 182/212] 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 183/212] 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 184/212] 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 185/212] 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 488181e1b63593ba03de4a1adb15dcbf9a0ce9e1 Mon Sep 17 00:00:00 2001 From: pablone Date: Thu, 19 Oct 2023 08:37:28 +0200 Subject: [PATCH 186/212] =?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 187/212] 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 188/212] 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 189/212] 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 190/212] 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 191/212] 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 192/212] 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 193/212] 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 194/212] 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 195/212] 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 196/212] 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 197/212] 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 198/212] 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 199/212] 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 200/212] 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 201/212] 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 202/212] 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 203/212] 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 204/212] 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 205/212] 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 22b7c5981294dcf5573c4f23b92a7f3010f5e98c Mon Sep 17 00:00:00 2001 From: alexm Date: Tue, 24 Oct 2023 09:23:03 +0200 Subject: [PATCH 206/212] 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 589d7cbbb82dce802cf30096ed1e47e85dd157e0 Mon Sep 17 00:00:00 2001 From: alexm Date: Tue, 24 Oct 2023 12:02:21 +0200 Subject: [PATCH 207/212] 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 208/212] 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 209/212] 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 013b010c220702957705347d672edcf173484317 Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 26 Oct 2023 07:56:57 +0200 Subject: [PATCH 210/212] 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 211/212] 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 cecdf8633cea829928b37608f14ea7e97e29184f Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 26 Oct 2023 09:27:32 +0200 Subject: [PATCH 212/212] 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",