diff --git a/db/dump/dumpedFixtures.sql b/db/dump/dumpedFixtures.sql index 8151ce601..3b2d3f431 100644 --- a/db/dump/dumpedFixtures.sql +++ b/db/dump/dumpedFixtures.sql @@ -19,7 +19,7 @@ USE `util`; -- -- Dumping data for table `config` -- - + LOCK TABLES `config` WRITE; /*!40000 ALTER TABLE `config` DISABLE KEYS */; INSERT INTO `config` VALUES (1,'10360',0,'production',NULL); @@ -34,7 +34,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2021-10-20 8:38:20 +-- Dump completed on 2021-11-08 8:19:54 USE `account`; -- MariaDB dump 10.19 Distrib 10.6.4-MariaDB, for Linux (x86_64) -- @@ -72,7 +72,7 @@ INSERT INTO `roleInherit` VALUES (1,1,2),(2,1,3),(3,1,70),(4,2,11),(5,3,11),(6,5 /*!40000 ALTER TABLE `roleInherit` ENABLE KEYS */; UNLOCK TABLES; --- +-- -- Dumping data for table `roleRole` -- @@ -120,7 +120,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2021-10-20 8:38:22 +-- Dump completed on 2021-11-08 8:19:55 USE `salix`; -- MariaDB dump 10.19 Distrib 10.6.4-MariaDB, for Linux (x86_64) -- @@ -176,7 +176,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2021-10-20 8:38:23 +-- Dump completed on 2021-11-08 8:19:56 USE `vn`; -- MariaDB dump 10.19 Distrib 10.6.4-MariaDB, for Linux (x86_64) -- @@ -432,7 +432,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2021-10-20 8:38:27 +-- Dump completed on 2021-11-08 8:20:01 USE `cache`; -- MariaDB dump 10.19 Distrib 10.6.4-MariaDB, for Linux (x86_64) -- @@ -468,7 +468,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2021-10-20 8:38:28 +-- Dump completed on 2021-11-08 8:20:02 USE `hedera`; -- MariaDB dump 10.19 Distrib 10.6.4-MariaDB, for Linux (x86_64) -- @@ -534,7 +534,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2021-10-20 8:38:29 +-- Dump completed on 2021-11-08 8:20:03 USE `postgresql`; -- MariaDB dump 10.19 Distrib 10.6.4-MariaDB, for Linux (x86_64) -- @@ -608,7 +608,7 @@ UNLOCK TABLES; LOCK TABLES `workcenter` WRITE; /*!40000 ALTER TABLE `workcenter` DISABLE KEYS */; -INSERT INTO `workcenter` VALUES (1,'Silla',20,NULL,1,'Av espioca 100',552703),(2,'Mercaflor',19,NULL,NULL,NULL,NULL),(3,'Marjales',26,20008,NULL,NULL,NULL),(4,'VNH',NULL,NULL,3,NULL,NULL),(5,'Madrid',28,2867,5,'Av constitución 3',554145),(6,'Vilassar',88,88038,2,'Cami del Crist, 33',556412),(7,'Tenerife',NULL,NULL,10,NULL,NULL),(8,NULL,NULL,NULL,NULL,NULL,NULL),(9,'Algemesi',20,1348,60,'Fenollars, 2',523549),(10,NULL,NULL,NULL,NULL,NULL,NULL); +INSERT INTO `workcenter` VALUES (1,'Silla',20,NULL,1,'Av espioca 100',552703),(2,'Mercaflor',19,NULL,NULL,NULL,NULL),(3,'Marjales',26,20008,NULL,NULL,NULL),(4,'VNH',NULL,NULL,3,NULL,NULL),(5,'Madrid',28,2868,5,'Av constitución 3',554145),(6,'Vilassar',88,88038,2,'Cami del Crist, 33',556412),(7,'Tenerife',NULL,NULL,10,NULL,NULL),(8,NULL,NULL,NULL,NULL,NULL,NULL),(9,'Algemesi',20,1351,60,'Fenollars, 2',523549),(10,NULL,NULL,NULL,NULL,NULL,NULL); /*!40000 ALTER TABLE `workcenter` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; @@ -620,7 +620,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2021-10-20 8:38:30 +-- Dump completed on 2021-11-08 8:20:05 USE `sage`; -- MariaDB dump 10.19 Distrib 10.6.4-MariaDB, for Linux (x86_64) -- @@ -676,4 +676,4 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2021-10-20 8:38:31 +-- Dump completed on 2021-11-08 8:20:06 diff --git a/db/dump/structure.sql b/db/dump/structure.sql index 734a926d1..3ab1d5608 100644 --- a/db/dump/structure.sql +++ b/db/dump/structure.sql @@ -1675,7 +1675,7 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `role_syncPrivileges`() +CREATE DEFINER=`root`@`localhost` PROCEDURE `role_syncPrivileges`() BEGIN /** * Synchronizes permissions of MySQL role users based on role hierarchy. @@ -1692,9 +1692,9 @@ BEGIN DECLARE vIsMysql BOOL DEFAULT VERSION() NOT LIKE '%MariaDB%'; DECLARE vVersion INT DEFAULT SUBSTRING_INDEX(VERSION(), '.', 1); DECLARE vTplUser VARCHAR(255) DEFAULT 'any'; - DECLARE vTplHost VARCHAR(255) DEFAULT '%'; - DECLARE vRoleHost VARCHAR(255) DEFAULT 'localhost'; - DECLARE vAllHost VARCHAR(255) DEFAULT '%'; + DECLARE vTplHost VARCHAR(255); + DECLARE vUserHost VARCHAR(255) DEFAULT '%'; + DECLARE vRoleHost VARCHAR(255); DECLARE vPrefix VARCHAR(2) DEFAULT 'z-'; DECLARE vPrefixedLike VARCHAR(255); DECLARE vPassword VARCHAR(255) DEFAULT ''; @@ -1702,13 +1702,23 @@ BEGIN -- Deletes computed role users SET vPrefixedLike = CONCAT(vPrefix, '%'); + SET vRoleHost = vUserHost; IF vIsMysql THEN + SET vTplHost = 'localhost'; + DELETE FROM mysql.user WHERE `User` LIKE vPrefixedLike; ELSE + SET vTplHost = ''; + DELETE FROM mysql.global_priv - WHERE `User` LIKE vPrefixedLike; + WHERE `User` LIKE vPrefixedLike + OR JSON_EXTRACT(`Priv`, '$.plugin') = 'pam'; + + DELETE FROM mysql.roles_mapping + WHERE `User` LIKE vPrefixedLike + OR `Role` LIKE vPrefixedLike; END IF; DELETE FROM mysql.db @@ -1734,21 +1744,10 @@ BEGIN ENGINE = MEMORY SELECT id, - `name` role, + `name` `role`, CONCAT(vPrefix, `name`) prefixedRole - FROM role - WHERE hasLogin; - - DROP TEMPORARY TABLE IF EXISTS tRoleInherit; - CREATE TEMPORARY TABLE tRoleInherit - (INDEX (inheritsFrom)) - ENGINE = MEMORY - SELECT - r.prefixedRole, - ri.`name` inheritsFrom - FROM tRole r - JOIN roleRole rr ON rr.role = r.id - JOIN role ri ON ri.id = rr.inheritsFrom; + FROM `role` + WHERE hasLogin; -- Recreate role users @@ -1757,7 +1756,7 @@ BEGIN CREATE TEMPORARY TABLE tUser SELECT r.prefixedRole `User`, - vTplHost `Host`, + vRoleHost `Host`, IFNULL(t.`authentication_string`, '') `authentication_string`, IFNULL(t.`plugin`, @@ -1789,16 +1788,16 @@ BEGIN FROM tRole r LEFT JOIN mysql.user t ON t.`User` = vTplUser - AND t.`Host` = vRoleHost + AND t.`Host` = vTplHost LEFT JOIN mysql.user u ON u.`User` = r.role - AND u.`Host` = vRoleHost; + AND u.`Host` = vTplHost; IF vVersion <= 5 THEN SELECT `Password` INTO vPassword FROM mysql.user WHERE `User` = vTplUser - AND `Host` = vRoleHost; + AND `Host` = vTplHost; INSERT INTO mysql.user ( `User`, @@ -1861,55 +1860,41 @@ BEGIN FROM tUser; END IF; - DROP TEMPORARY TABLE IF EXISTS tUser; - ELSE - INSERT INTO mysql.global_priv ( - `User`, - `Host`, - `Priv` - ) - SELECT + DROP TEMPORARY TABLE tUser; + + -- Get role inheritance + + DROP TEMPORARY TABLE IF EXISTS tRoleInherit; + CREATE TEMPORARY TABLE tRoleInherit + (INDEX (inheritsFrom)) + ENGINE = MEMORY + SELECT r.prefixedRole, - vTplHost, - JSON_MERGE_PATCH( - IFNULL(t.`Priv`, '{}'), - IFNULL(u.`Priv`, '{}'), - JSON_OBJECT( - 'mysql_old_password', JSON_VALUE(t.`Priv`, '$.mysql_old_password'), - 'mysql_native_password', JSON_VALUE(t.`Priv`, '$.mysql_native_password'), - 'authentication_string', JSON_VALUE(t.`Priv`, '$.authentication_string'), - 'ssl_type', JSON_VALUE(t.`Priv`, '$.ssl_type') - ) - ) + ri.`name` inheritsFrom FROM tRole r - LEFT JOIN mysql.global_priv t - ON t.`User` = vTplUser - AND t.`Host` = vRoleHost - LEFT JOIN mysql.global_priv u - ON u.`User` = r.role - AND u.`Host` = vRoleHost; - END IF; + JOIN `roleRole` rr ON rr.role = r.id + JOIN `role` ri ON ri.id = rr.inheritsFrom; - INSERT INTO mysql.proxies_priv ( - `User`, - `Host`, - `Proxied_user`, - `Proxied_host`, - `Grantor` - ) - SELECT - '', - vAllHost, - prefixedRole, - vTplHost, - CONCAT(prefixedRole, '@', vTplHost) - FROM tRole; + -- Proxy privileges - -- Copies global privileges + INSERT INTO mysql.proxies_priv ( + `User`, + `Host`, + `Proxied_user`, + `Proxied_host`, + `Grantor` + ) + SELECT + '', + vUserHost, + prefixedRole, + vRoleHost, + CONCAT(prefixedRole, '@', vRoleHost) + FROM tRole; - DROP TEMPORARY TABLE IF EXISTS tUserPriv; + -- Global privileges - IF vIsMysql THEN + DROP TEMPORARY TABLE IF EXISTS tUserPriv; CREATE TEMPORARY TABLE tUserPriv (INDEX (prefixedRole)) ENGINE = MEMORY @@ -1947,13 +1932,13 @@ BEGIN FROM tRoleInherit r JOIN mysql.user u ON u.`User` = r.inheritsFrom - AND u.`Host`= vRoleHost + AND u.`Host`= vTplHost GROUP BY r.prefixedRole; UPDATE mysql.user u JOIN tUserPriv t ON u.`User` = t.prefixedRole - AND u.`Host` = vTplHost + AND u.`Host` = vRoleHost SET u.`Select_priv` = t.`Select_priv`, @@ -2013,167 +1998,226 @@ BEGIN = t.`Trigger_priv`, u.`Create_tablespace_priv` = t.`Create_tablespace_priv`; - ELSE - CREATE TEMPORARY TABLE tUserPriv - (INDEX (prefixedRole)) + + DROP TEMPORARY TABLE tUserPriv; + + -- Schema level privileges + + INSERT INTO mysql.db ( + `User`, + `Host`, + `Db`, + `Select_priv`, + `Insert_priv`, + `Update_priv`, + `Delete_priv`, + `Create_priv`, + `Drop_priv`, + `Grant_priv`, + `References_priv`, + `Index_priv`, + `Alter_priv`, + `Create_tmp_table_priv`, + `Lock_tables_priv`, + `Create_view_priv`, + `Show_view_priv`, + `Create_routine_priv`, + `Alter_routine_priv`, + `Execute_priv`, + `Event_priv`, + `Trigger_priv` + ) SELECT r.prefixedRole, - BIT_OR(JSON_VALUE(p.`Priv`, '$.access')) access + vRoleHost, + t.`Db`, + MAX(t.`Select_priv`), + MAX(t.`Insert_priv`), + MAX(t.`Update_priv`), + MAX(t.`Delete_priv`), + MAX(t.`Create_priv`), + MAX(t.`Drop_priv`), + MAX(t.`Grant_priv`), + MAX(t.`References_priv`), + MAX(t.`Index_priv`), + MAX(t.`Alter_priv`), + MAX(t.`Create_tmp_table_priv`), + MAX(t.`Lock_tables_priv`), + MAX(t.`Create_view_priv`), + MAX(t.`Show_view_priv`), + MAX(t.`Create_routine_priv`), + MAX(t.`Alter_routine_priv`), + MAX(t.`Execute_priv`), + MAX(t.`Event_priv`), + MAX(t.`Trigger_priv`) FROM tRoleInherit r + JOIN mysql.db t + ON t.`User` = r.inheritsFrom + AND t.`Host`= vTplHost + GROUP BY r.prefixedRole, t.`Db`; + + -- Table level privileges + + INSERT INTO mysql.tables_priv ( + `User`, + `Host`, + `Db`, + `Table_name`, + `Grantor`, + `Timestamp`, + `Table_priv`, + `Column_priv` + ) + SELECT + r.prefixedRole, + vRoleHost, + t.`Db`, + t.`Table_name`, + t.`Grantor`, + MAX(t.`Timestamp`), + IFNULL(GROUP_CONCAT(NULLIF(t.`Table_priv`, '')), ''), + IFNULL(GROUP_CONCAT(NULLIF(t.`Column_priv`, '')), '') + FROM tRoleInherit r + JOIN mysql.tables_priv t + ON t.`User` = r.inheritsFrom + AND t.`Host`= vTplHost + GROUP BY r.prefixedRole, t.`Db`, t.`Table_name`; + + -- Column level privileges + + INSERT INTO mysql.columns_priv ( + `User`, + `Host`, + `Db`, + `Table_name`, + `Column_name`, + `Timestamp`, + `Column_priv` + ) + SELECT + r.prefixedRole, + vRoleHost, + t.`Db`, + t.`Table_name`, + t.`Column_name`, + MAX(t.`Timestamp`), + IFNULL(GROUP_CONCAT(NULLIF(t.`Column_priv`, '')), '') + FROM tRoleInherit r + JOIN mysql.columns_priv t + ON t.`User` = r.inheritsFrom + AND t.`Host`= vTplHost + GROUP BY r.prefixedRole, t.`Db`, t.`Table_name`, t.`Column_name`; + + -- Routine privileges + + INSERT IGNORE INTO mysql.procs_priv ( + `User`, + `Host`, + `Db`, + `Routine_name`, + `Routine_type`, + `Grantor`, + `Timestamp`, + `Proc_priv` + ) + SELECT + r.prefixedRole, + vRoleHost, + t.`Db`, + t.`Routine_name`, + t.`Routine_type`, + t.`Grantor`, + t.`Timestamp`, + t.`Proc_priv` + FROM tRoleInherit r + JOIN mysql.procs_priv t + ON t.`User` = r.inheritsFrom + AND t.`Host`= vTplHost; + + -- Cleanup + + DROP TEMPORARY TABLE tRoleInherit; + ELSE + -- Roles + + INSERT INTO mysql.global_priv (`Host`, `User`, `Priv`) + SELECT vTplHost, prefixedRole, + JSON_OBJECT( + 'access', 0, + 'is_role', true + ) + FROM tRole r; + + INSERT INTO mysql.roles_mapping (`Host`, `User`, `Role`, `Admin_option`) + SELECT vTplHost, r.prefixedRole, i.`name`, 'N' + FROM tRole r + JOIN roleRole ri + ON ri.`role` = r.id + JOIN `role` i + ON ri.`inheritsFrom` = i.id JOIN mysql.global_priv p - ON p.`User` = r.inheritsFrom - AND p.`Host`= vRoleHost - GROUP BY r.prefixedRole; - - UPDATE mysql.global_priv p - JOIN tUserPriv t - ON p.`User` = t.prefixedRole - AND p.`Host` = vTplHost - SET - p.`Priv` = JSON_SET(p.`Priv`, '$.access', t.access); + ON p.`User` = i.`name` AND p.`Host` = vTplHost; + + -- Backward compatibility + + INSERT INTO mysql.global_priv ( + `User`, + `Host`, + `Priv` + ) + SELECT + r.prefixedRole, + vRoleHost, + JSON_MERGE_PATCH( + IFNULL(t.`Priv`, '{}'), + IFNULL(u.`Priv`, '{}'), + JSON_OBJECT( + 'mysql_old_password', JSON_VALUE(t.`Priv`, '$.mysql_old_password'), + 'mysql_native_password', JSON_VALUE(t.`Priv`, '$.mysql_native_password'), + 'authentication_string', JSON_VALUE(t.`Priv`, '$.authentication_string'), + 'ssl_type', JSON_VALUE(t.`Priv`, '$.ssl_type'), + 'default_role', r.prefixedRole, + 'is_role', FALSE + ) + ) + FROM tRole r + LEFT JOIN mysql.global_priv t + ON t.`User` = vTplUser + AND t.Host = vTplHost + LEFT JOIN mysql.global_priv u + ON u.`User` = r.role + AND u.Host = vTplHost; + + INSERT INTO mysql.roles_mapping (`Host`, `User`, `Role`, `Admin_option`) + SELECT vRoleHost, prefixedRole, prefixedRole, 'N' + FROM tRole; + + -- Accounts + + INSERT INTO mysql.global_priv (`Host`, `User`, `Priv`) + SELECT vUserHost, u.`name`, + JSON_OBJECT( + 'access', 0, + 'plugin', 'pam', + 'authentication_string', '', + 'default_role', r.`prefixedRole` + ) + FROM `user` u + JOIN account a ON a.`id` = u.`id` + JOIN tRole r ON r.`id` = u.`role` + WHERE u.`active`; + + INSERT INTO mysql.roles_mapping (`Host`, `User`, `Role`, `Admin_option`) + SELECT vUserHost, u.`name`, r.prefixedRole, 'N' + FROM `user` u + JOIN account a ON a.`id` = u.`id` + JOIN tRole r ON r.`id` = u.`role` + WHERE u.`active`; END IF; - DROP TEMPORARY TABLE tUserPriv; - - -- Copy schema level privileges - - INSERT INTO mysql.db ( - `User`, - `Host`, - `Db`, - `Select_priv`, - `Insert_priv`, - `Update_priv`, - `Delete_priv`, - `Create_priv`, - `Drop_priv`, - `Grant_priv`, - `References_priv`, - `Index_priv`, - `Alter_priv`, - `Create_tmp_table_priv`, - `Lock_tables_priv`, - `Create_view_priv`, - `Show_view_priv`, - `Create_routine_priv`, - `Alter_routine_priv`, - `Execute_priv`, - `Event_priv`, - `Trigger_priv` - ) - SELECT - r.prefixedRole, - vTplHost, - t.`Db`, - MAX(t.`Select_priv`), - MAX(t.`Insert_priv`), - MAX(t.`Update_priv`), - MAX(t.`Delete_priv`), - MAX(t.`Create_priv`), - MAX(t.`Drop_priv`), - MAX(t.`Grant_priv`), - MAX(t.`References_priv`), - MAX(t.`Index_priv`), - MAX(t.`Alter_priv`), - MAX(t.`Create_tmp_table_priv`), - MAX(t.`Lock_tables_priv`), - MAX(t.`Create_view_priv`), - MAX(t.`Show_view_priv`), - MAX(t.`Create_routine_priv`), - MAX(t.`Alter_routine_priv`), - MAX(t.`Execute_priv`), - MAX(t.`Event_priv`), - MAX(t.`Trigger_priv`) - FROM tRoleInherit r - JOIN mysql.db t - ON t.`User` = r.inheritsFrom - AND t.`Host`= vRoleHost - GROUP BY r.prefixedRole, t.`Db`; - - -- Copy table level privileges - - INSERT INTO mysql.tables_priv ( - `User`, - `Host`, - `Db`, - `Table_name`, - `Grantor`, - `Timestamp`, - `Table_priv`, - `Column_priv` - ) - SELECT - r.prefixedRole, - vTplHost, - t.`Db`, - t.`Table_name`, - t.`Grantor`, - MAX(t.`Timestamp`), - IFNULL(GROUP_CONCAT(NULLIF(t.`Table_priv`, '')), ''), - IFNULL(GROUP_CONCAT(NULLIF(t.`Column_priv`, '')), '') - FROM tRoleInherit r - JOIN mysql.tables_priv t - ON t.`User` = r.inheritsFrom - AND t.`Host`= vRoleHost - GROUP BY r.prefixedRole, t.`Db`, t.`Table_name`; - - -- Copy column level privileges - - INSERT INTO mysql.columns_priv ( - `User`, - `Host`, - `Db`, - `Table_name`, - `Column_name`, - `Timestamp`, - `Column_priv` - ) - SELECT - r.prefixedRole, - vTplHost, - t.`Db`, - t.`Table_name`, - t.`Column_name`, - MAX(t.`Timestamp`), - IFNULL(GROUP_CONCAT(NULLIF(t.`Column_priv`, '')), '') - FROM tRoleInherit r - JOIN mysql.columns_priv t - ON t.`User` = r.inheritsFrom - AND t.`Host`= vRoleHost - GROUP BY r.prefixedRole, t.`Db`, t.`Table_name`, t.`Column_name`; - - -- Copy routine privileges - - INSERT IGNORE INTO mysql.procs_priv ( - `User`, - `Host`, - `Db`, - `Routine_name`, - `Routine_type`, - `Grantor`, - `Timestamp`, - `Proc_priv` - ) - SELECT - r.prefixedRole, - vTplHost, - t.`Db`, - t.`Routine_name`, - t.`Routine_type`, - t.`Grantor`, - t.`Timestamp`, - t.`Proc_priv` - FROM tRoleInherit r - JOIN mysql.procs_priv t - ON t.`User` = r.inheritsFrom - AND t.`Host`= vRoleHost; - - -- Free memory - - DROP TEMPORARY TABLE - tRole, - tRoleInherit; + -- Cleanup + DROP TEMPORARY TABLE tRole; FLUSH PRIVILEGES; END ;; DELIMITER ; @@ -3589,7 +3633,7 @@ DELIMITER ;; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; /*!50003 SET @saved_time_zone = @@time_zone */ ;; /*!50003 SET time_zone = 'SYSTEM' */ ;; -/*!50106 CREATE*/ /*!50117 DEFINER=`z-sysadmin`@`%`*/ /*!50106 EVENT `nightTask_launchAll` ON SCHEDULE EVERY 1 DAY STARTS '2020-08-05 03:00:00' ON COMPLETION PRESERVE ENABLE DO CALL bs.nightTask_launchAll */ ;; +/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `nightTask_launchAll` ON SCHEDULE EVERY 1 DAY STARTS '2020-08-05 03:00:00' ON COMPLETION PRESERVE ENABLE DO CALL bs.nightTask_launchAll */ ;; /*!50003 SET time_zone = @saved_time_zone */ ;; /*!50003 SET sql_mode = @saved_sql_mode */ ;; /*!50003 SET character_set_client = @saved_cs_client */ ;; @@ -5470,13 +5514,15 @@ BEGIN FROM nightTaskConfig LIMIT 1; IF vNErrors > 0 AND vLogMail IS NOT NULL THEN - INSERT INTO vn.mail SET - `sender` = vLogMail, - `subject` = 'Nightly task failed', - `body` = CONCAT( + CALL vn.mail_insert( + vLogMail, + NULL, + 'Nightly task failed', + CONCAT( vNErrors, ' procedures of nightly tasks have failed. ', 'Please, see `', SCHEMA() ,'`.`nightTask` table for more info.' - ); + ) + ); END IF; END ;; DELIMITER ; @@ -7398,7 +7444,7 @@ DELIMITER ;; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; /*!50003 SET @saved_time_zone = @@time_zone */ ;; /*!50003 SET time_zone = 'SYSTEM' */ ;; -/*!50106 CREATE*/ /*!50117 DEFINER=`z-sysadmin`@`%`*/ /*!50106 EVENT `cacheCalc_clean` ON SCHEDULE EVERY 30 MINUTE STARTS '2017-01-23 13:15:58' ON COMPLETION NOT PRESERVE ENABLE DO CALL cacheCalc_clean */ ;; +/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `cacheCalc_clean` ON SCHEDULE EVERY 30 MINUTE STARTS '2017-01-23 13:15:58' ON COMPLETION NOT PRESERVE ENABLE DO CALL cacheCalc_clean */ ;; /*!50003 SET time_zone = @saved_time_zone */ ;; /*!50003 SET sql_mode = @saved_sql_mode */ ;; /*!50003 SET character_set_client = @saved_cs_client */ ;; @@ -7416,7 +7462,7 @@ DELIMITER ;; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; /*!50003 SET @saved_time_zone = @@time_zone */ ;; /*!50003 SET time_zone = 'SYSTEM' */ ;; -/*!50106 CREATE*/ /*!50117 DEFINER=`z-sysadmin`@`%`*/ /*!50106 EVENT `cache_clean` ON SCHEDULE EVERY 5 MINUTE STARTS '2019-04-29 13:06:16' ON COMPLETION NOT PRESERVE ENABLE DO CALL cache_clean */ ;; +/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `cache_clean` ON SCHEDULE EVERY 5 MINUTE STARTS '2019-04-29 13:06:16' ON COMPLETION NOT PRESERVE ENABLE DO CALL cache_clean */ ;; /*!50003 SET time_zone = @saved_time_zone */ ;; /*!50003 SET sql_mode = @saved_sql_mode */ ;; /*!50003 SET character_set_client = @saved_cs_client */ ;; @@ -8840,7 +8886,7 @@ CREATE TABLE `ekt` ( `s6` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, `ok` tinyint(4) NOT NULL DEFAULT '0', `trolleyFk` int(11) DEFAULT NULL, - `putOrderFk` int(10) unsigned DEFAULT NULL, + `putOrderFk` bigint(20) unsigned DEFAULT NULL, `scanned` tinyint(1) NOT NULL DEFAULT '0', PRIMARY KEY (`id`) USING BTREE, UNIQUE KEY `barcode_year` (`barcode`,`entryYear`), @@ -9823,9 +9869,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -9841,6 +9887,10 @@ BEGIN FROM supplyResponse sr LEFT JOIN edi.deliveryInformation di ON sr.ID = di.supplyResponseID WHERE di.LatestOrderDateTime < vOneWeekAgo OR di.ID IS NULL; + + DELETE FROM putOrder + WHERE created < TIMESTAMPADD(MONTH,-1,CURDATE()); + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -9967,11 +10017,11 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `ekt_load`(IN `vSelf` INT) BEGIN @@ -9988,7 +10038,7 @@ BEGIN -- Carga los datos necesarios del EKT - SELECT ref, qty, package, putOrderFk, i2.id + SELECT ref, qty, package, putOrderFk MOD 1000000, i2.id INTO vRef, vQty, vPackage, vPutOrderFk, vItem FROM ekt e LEFT JOIN item i ON e.ref = i.id @@ -10344,7 +10394,7 @@ CREATE DEFINER=`root`@`%` PROCEDURE `exchange_new`( IN `vP2` TINYINT, IN `vAuction` SMALLINT, IN `vPackage` INT, - IN `vPutOrderFk` INT) + IN `vPutOrderFk` BIGINT) BEGIN /** * Adds a new exchange, generates it's barcode and @@ -10354,6 +10404,7 @@ BEGIN */ DECLARE vEkt INT; DECLARE vRewriteKop INT DEFAULT NULL; + DECLARE vTruncatePutOrder INT DEFAULT NULL; DECLARE vBarcode CHAR(15) DEFAULT NULL; DECLARE vIsDuplicated BOOL; DECLARE vUpdateExistent BOOL DEFAULT FALSE; @@ -10410,6 +10461,8 @@ BEGIN call util.debugAdd('vBarcode',vBarcode); call util.debugAdd('vDeliveryNumber',vDeliveryNumber); SET vIsDuplicated = FALSE; + SET vTruncatePutOrder = vPutOrderFk MOD 1000000; + INSERT INTO ekt SET barcode = IFNULL(vBarcode, barcode) ,deliveryNumber = vDeliveryNumber @@ -10442,7 +10495,7 @@ BEGIN ,k4 = vP2 ,auction = vAuction ,package = vPackage - ,putOrderFk = vPutOrderFk; + ,putOrderFk = vTruncatePutOrder; -- If it exists duplicado updates it @@ -10499,7 +10552,7 @@ BEGIN ,k4 = vP2 ,auction = vAuction ,package = vPackage - ,putOrderFk = IFNULL(vPutOrderFk, putOrderFk) + ,putOrderFk = IFNULL(vTruncatePutOrder, putOrderFk) WHERE id = vEkt; END IF; @@ -11947,9 +12000,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -11964,6 +12017,16 @@ BEGIN 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.myUserGetName(), ' ha creado la order ',NEW.id) + ); + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -17455,6 +17518,46 @@ CREATE TABLE `business` ( CONSTRAINT `bussiness_provider` FOREIGN KEY (`provider_id`) REFERENCES `profile` (`profile_id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `postgresql`.`business_beforeUpdate` + BEFORE UPDATE ON `business` FOR EACH ROW +BEGIN + DECLARE isOverlapping BOOL; + + IF !(OLD.date_start <=> NEW.date_start AND OLD.date_end <=> NEW.date_end) THEN + + SELECT COUNT(*) > 0 INTO isOverlapping + FROM business b + WHERE (util.hasDateOverlapped( + NEW.date_start, + IFNULL(NEW.date_end,b.date_start), + b.date_start, + IFNULL(b.date_end,NEW.date_start)) + OR (NEW.date_end <=> NULL AND b.date_end <=> NULL)) + AND b.business_id <> OLD.business_id + AND client_id = OLD.client_id + ; + + IF isOverlapping THEN + CALL util.throw ('IS_OVERLAPPING'); + END IF; + + END IF; + +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; -- -- Table structure for table `business_labour` @@ -18876,14 +18979,14 @@ BEGIN JOIN vn.XDiario x ON x.ASIEN = m.Asiento SET m.BaseIva1 = x.BASEEURO , m.PorIva1 = x.IVA, - m.CuotaIva1 = (x.IVA/100) * x.BASEEURO , + m.CuotaIva1 = CAST((x.IVA/100) * x.BASEEURO AS DECIMAL(10,2)) , m.CodigoTransaccion1 = 56 , m.CodigoIva1 = 22, m.IvaDeducible1 = TRUE, m.FechaFacturaOriginal = x.FECHA_EX, m.SuFacturaNo = x.FACTURAEX, m.FechaOperacion = x.FECHA_OP, - m.ImporteFactura = m.ImporteFactura + x.BASEEURO + (x.IVA/100) * x.BASEEURO + m.ImporteFactura = m.ImporteFactura + x.BASEEURO + CAST((x.IVA/100) * x.BASEEURO AS DECIMAL(10,2)) WHERE m.CodigoCuenta = 4700000999 AND m.enlazadoSage = FALSE AND x.SERIE='D' @@ -18893,11 +18996,11 @@ BEGIN JOIN vn.XDiario x ON x.ASIEN = m.Asiento SET m.BaseIva2 = x.BASEEURO , m.PorIva2 = x.IVA, - m.CuotaIva2 = (x.IVA/100) * x.BASEEURO , + m.CuotaIva2 = CAST((x.IVA/100) * x.BASEEURO AS DECIMAL(10,2)), m.CodigoTransaccion2 = 56 , m.CodigoIva2 = 90, m.IvaDeducible2 = TRUE, - m.ImporteFactura = m.ImporteFactura + x.BASEEURO + (x.IVA/100) * x.BASEEURO + m.ImporteFactura = m.ImporteFactura + x.BASEEURO + CAST((x.IVA/100) * x.BASEEURO AS DECIMAL(10,2)) WHERE m.CodigoCuenta = 4700000999 AND m.enlazadoSage = FALSE AND x.SERIE='D' @@ -19166,545 +19269,6 @@ DELIMITER ; /*!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 PROCEDURE IF EXISTS `movContaAdd__` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `movContaAdd__`() -BEGIN - /* Copia en movConta los asientos de XDiario para que luego los importe el proceso automático que hay en SQL Server - */ - DECLARE vDated DATE; - SELECT CONCAT(YEAR(CURDATE()), "-01-01") INTO vDated; - TRUNCATE XDiario_movConta_IVA; - DELETE FROM movConta WHERE enlazadoSage = FALSE AND Asiento <> 1 ; - CALL clientesProveedoresAdd; - CALL planCuentasPgcAdd; - CALL XDiario_movConta_IVA_InvoiceOutAdd_Manager; - CALL XDiario_movConta_IVA_InvoiceInAdd_Manager; - INSERT INTO movConta( - TipoEntrada, -- VARCHAR(2) - Ejercicio, -- Año - CodigoEmpresa, -- ENT(2) - Asiento, -- LONG(4), nº ASIENTO - CargoAbono, -- VARCHAR(1) "D" debe ó "H" haber - CodigoCuenta, -- VARCHAR(15) partida contable - Contrapartida, -- VARCHAR(15) partida contable - FechaAsiento, -- FECHA(8) - Comentario, -- VARCHAR(40) - ImporteAsiento, -- DOBLE(19) - NumeroPeriodo, -- ENT(2) "-1" Al informar este valor se calcula automát. A partir de la fecha de asiento - FechaGrabacion, -- FECHA(8) - CodigoDivisa, -- VARCHAR(3) - ImporteCambio, -- DOBLE(19) - ImporteDivisa, -- DOBLE(19) - FactorCambio, -- DOBLE(19) - IdProcesoIME, -- GUID(16) - TipoCarteraIME, -- ENT(2) "0" para que no genere cartera - TipoAnaliticaIME, -- ENT(2) - StatusTraspasadoIME, -- BYTE "0" para dejar como no importado aún - TipoImportacionIME, -- BYTE "0" Alta "1" Baja - Metalico347, -- ENT(2) - /* ESTOS CAMPOS SOLO SE INFORMAN EN EL CASO DE SER FACTURA */ - BaseIva1, -- DOBLE(19) - PorBaseCorrectora1, -- DOBLE(19) - PorIva1, -- DOBLE(19) - CuotaIva1, -- DOBLE(19) - PorRecargoEquivalencia1,-- DOBLE(19) - RecargoEquivalencia1, -- DOBLE(19) - CodigoTransaccion1, -- BYTE "0" Nacional "1" Intracomunitario "2" Extracomunitario - BaseIva2, - PorBaseCorrectora2, - PorIva2, - CuotaIva2, - PorRecargoEquivalencia2, - RecargoEquivalencia2, - CodigoTransaccion2, - BaseIva3, - PorBaseCorrectora3, - PorIva3, - CuotaIva3, - PorRecargoEquivalencia3, - RecargoEquivalencia3, - CodigoTransaccion3, - BaseIva4, - PorBaseCorrectora4, - PorIva4, - CuotaIva4, - PorRecargoEquivalencia4, - RecargoEquivalencia4, - CodigoTransaccion4, - Año, -- ENT(2) - Serie, -- VARCHAR(10) - Factura, -- LONG(4) - SuFacturaNo, -- VARCHAR(40) - FechaFactura, -- FECHA(8) - ImporteFactura, -- DOBLE(19) - TipoFactura, -- VARCHAR(1) "E" / "R" / "I" - CodigoCuentaFactura, -- VARCHAR(15) cuenta del cliente/proveedor - CifDni, -- VARCHAR(13) - Nombre, -- VARCHAR(35) - CodigoRetencion, -- ENT(2) - BaseRetencion, -- DOBLE(19) - PorRetencion, -- DOBLE(19) - ImporteRetencion, -- DOBLE(19) - SiglaNacion, -- VARCHAR(2) "ES" por defecto - EjercicioFactura, -- ENT(2) - FechaOperacion, -- FECHA(8) - Exclusion347, -- ENT(2) - MantenerAsiento, -- BYTE "-1" mantener "0" Sage asigna nuevo - ClaveOperacionFactura_, -- VARCHAR(1) P(4721000011,4721000021)-I(4721000015-4720000005-4720000006)-D (Rectificativas) - TipoRectificativa, -- ENT(2) - FechaFacturaOriginal, -- FECHA(8) - BaseImponibleOriginal, -- DOBLE(19) - CuotaIvaOriginal, -- DOBLE(19) - ClaseAbonoRectificativas,-- ENT(2) - RecargoEquivalenciaOriginal, -- DOBLE(19) */ - LibreA1, - CodigoIva1, -- ENT(6) - CodigoIva2, -- ENT(6) - CodigoIva3, -- ENT(6) - CodigoIva4, -- ENT(6) - IvaDeducible1, -- Entero 2 ((-1)) - IvaDeducible2, -- Entero 2 ((-1)) - IvaDeducible3, -- Entero 2 ((-1)) - IvaDeducible4, -- Entero 2 ((-1))-- ENT(6) - Intracomunitaria -- INT(2) - ) - SELECT 'EN' as TipoEntrada, - YEAR(x.FECHA) AS Ejercicio, - IF (@@hostname = 'db', c.companyCode, companyCodeTest) AS CodigoEmpresa, -- ENT(2) c.companyCode AS CodigoEmpresa, - x.ASIEN AS Asiento, -- LONG(4), nº ASIENTO - IF(EURODEBE<>0 OR (EURODEBE=0 AND EUROHABER IS NULL),'D','H')AS CargoAbono, -- IF(EURODEBE IS NULL,"H","D") AS CargoAbono, VARCHAR(1) "D" debe ó "H" haber - x.SUBCTA AS CodigoCuenta, -- VARCHAR(15) partida contable - x.CONTRA AS Contrapartida, -- VARCHAR(15) partida contable - x.FECHA AS FechaAsiento, -- FECHA(8) - SUBSTRING(x.CONCEPTO, 1, 40) AS Comentario, -- VARCHAR(40) - IF(x.EURODEBE,x.EURODEBE,x.EUROHABER) AS ImporteAsiento, -- DOBLE(19) - MONTH(x.FECHA) AS NumeroPeriodo, -- ENT(2) "-1" Al informar este valor se calcula automát. A partir de la fecha de asiento - IF( sub2.FECREGCON IS NULL, sub2.FECHA_EX, sub2.FECREGCON) FechaGrabacion, -- FECHA(8) - IF(x.CAMBIO,IFNULL(xmi.CodigoDivisa, sub3.code),'') CodigoDivisa, -- VARCHAR(3) - x.CAMBIO AS ImporteCambio, -- DOBLE(19) - IFNULL(x.DEBEME,x.HABERME) AS ImporteDivisa, -- DOBLE(19) - IF(x.CAMBIO,1,0) AS FactorCambio, -- DOBLE(19) - NULL AS IdProcesoIME, -- GUID(16) - 0 AS TipoCarteraIME, -- ENT(2) "0" para que no genere cartera - 0 AS TipoAnaliticaIME, -- ENT(2) - 0 AS StatusTraspasadoIME, -- BYTE "0" para dejar como no importado aún - 0 AS TipoImportacionIME, -- BYTE "0" Alta "1" Baja - x.METAL as Metalico347, - /* ESTOS CAMPOS SOLO SE INFORMAN EN EL CASO DE SER FACTURA */ - xmi.BaseIva1, -- DOBLE(19) - xmi.PorBaseCorrectora1, -- DOBLE(19) - xmi.PorIva1, -- DOBLE(19) - xmi.CuotaIva1, -- DOBLE(19) - xmi.PorRecargoEquivalencia1,-- DOBLE(19) - xmi.RecargoEquivalencia1, -- DOBLE(19) - xmi.CodigoTransaccion1, -- BYTE "0" Nacional "1" Intracomunitario "2" Extracomunitario - xmi.BaseIva2, - xmi.PorBaseCorrectora2, - xmi.PorIva2, - xmi.CuotaIva2, - xmi.PorRecargoEquivalencia2, - xmi.RecargoEquivalencia2, - xmi.CodigoTransaccion2, - xmi.BaseIva3, - xmi.PorBaseCorrectora3, - xmi.PorIva3, - xmi.CuotaIva3, - xmi.PorRecargoEquivalencia3, - xmi.RecargoEquivalencia3, - xmi.CodigoTransaccion3, - xmi.BaseIva4, - xmi.PorBaseCorrectora4, - xmi.PorIva4, - xmi.CuotaIva4, - xmi.PorRecargoEquivalencia4, - xmi.RecargoEquivalencia4, - xmi.CodigoTransaccion4, - xmi.Año, -- ENT(2) - xmi.Serie, -- VARCHAR(10) - xmi.Factura, -- LONG(4) - xmi.SuFacturaNo, -- VARCHAR(40) - xmi.FechaFactura, -- FECHA(8) - xmi.ImporteFactura, -- DOBLE(19) - xmi.TipoFactura, -- VARCHAR(1) "E" / "R" - xmi.CodigoCuentaFactura, -- VARCHAR(15) cuenta del cliente/proveedor - xmi.CifDni, -- VARCHAR(13) - xmi.Nombre, -- VARCHAR(35) - xmi.CodigoRetencion, -- ENT(2) - xmi.BaseRetencion, -- DOBLE(19) - xmi.PorRetencion, -- DOBLE(19) - xmi.ImporteRetencion, -- DOBLE(19) - xmi.SiglaNacion, -- VARCHAR(2) "ES" por defecto - xmi.EjercicioFactura, -- ENT(2) - xmi.FechaOperacion, -- FECHA(8) - xmi.Exclusion347, -- ENT(2) - 1, -- xmi.MantenerAsiento BYTE "-1" mantener "0" Sage asigna nuevo - xmi.ClaveOperacionFactura, -- VARCHAR(1) - xmi.TipoRectificativa, -- ENT(2) - xmi.FechaFacturaOriginal, -- FECHA(8) - xmi.BaseImponibleOriginal, -- DOBLE(19) - xmi.CuotaIvaOriginal, -- DOBLE(19) - xmi.ClaseAbonoRectificativas,-- ENT(2) - xmi.RecargoEquivalenciaOriginal,-- DOBLE(19) */ - xmi.LibreA1, - xmi.CodigoIva1, -- ENT(6) - xmi.CodigoIva2, -- ENT(6) - xmi.CodigoIva3, -- ENT(6) - xmi.CodigoIva4, -- ENT(6) - xmi.IvaDeducible1, -- Entero 2 ((-1)) - xmi.IvaDeducible2, -- Entero 2 ((-1)) - xmi.IvaDeducible3, -- Entero 2 ((-1)) - xmi.IvaDeducible4, -- Entero 2 ((-1))-- ENT(6) - xmi.Intracomunitaria -- TINYINT(1) - FROM vn2008.XDiario x - JOIN vn.company c ON c.id = x.empresa_id - LEFT JOIN XDiario_movConta_IVA xmi ON xmi.id = x.id AND xmi.moveData > 0 - LEFT JOIN (SELECT ASIEN, FECREGCON, FECHA_EX - FROM (SELECT ASIEN, FECREGCON, FECHA_EX - FROM vn2008.XDiario - ORDER BY ASIEN, FECREGCON DESC, FECHA_EX DESC - ) sub GROUP BY ASIEN - )sub2 ON sub2.ASIEN = x.ASIEN - LEFT JOIN ( SELECT DISTINCT(account),cu.code - FROM vn.bank b - JOIN vn.currency cu ON cu.id = b.currencyFk - WHERE cu.code <> "EUR" -- no se informa cuando la divisa en EUR - )sub3 ON sub3.account = x.SUBCTA - WHERE x.enlazadoSage = 0 AND - c.companyCode AND - x.FECHA >= vDated; - --- Prepara Metálicos - UPDATE sage.movConta m - JOIN (SELECT Asiento, SUBSTR(c.socialName,1,35) Nombre, c.fi, n.SiglaNacion - FROM sage.movConta m - JOIN vn.client c ON c.id = IF(m.CargoAbono = "H", m.CodigoCuenta-4300000000, m.Contrapartida-4300000000 ) - LEFT JOIN Naciones n ON n.countryFk = c.countryFk - WHERE m.Metalico347 = TRUE AND - m.enlazadoSage = FALSE - ) AS sub ON m.Asiento = sub.Asiento - SET m.Metalico347 = TRUE, - m.TipoFactura = "I", - m.CifDni = sub.fi , - m.Nombre = sub.Nombre, - m.SiglaNacion = sub.SiglaNacion - WHERE m.enlazadoSage = FALSE; - - UPDATE sage.movConta m - SET Metalico347 = FALSE, - m.TipoFactura = "", - m.Metalico347 = FALSE - WHERE CargoAbono = "D" AND - m.enlazadoSage = FALSE; - --- Elimina cuentas de cliente/proveedor que no se utilizarán en la importación - DELETE cp - FROM clientesProveedores cp - JOIN (SELECT cp.codigoCuenta - FROM clientesProveedores cp - LEFT JOIN movConta mc ON mc.codigoCuenta = cp.codigoCuenta AND mc.enlazadoSage = FALSE - WHERE mc.codigoCuenta IS NULL - GROUP BY cp.codigoCuenta - ) sub ON sub.codigoCuenta = cp.codigoCuenta ; - --- Elimina cuentas contables que no se utilizarán en la importación - DELETE pc - FROM planCuentasPGC pc - JOIN ( SELECT pc.codigoCuenta - FROM planCuentasPGC pc - LEFT JOIN movConta mc ON mc.codigoCuenta = pc.codigoCuenta AND mc.enlazadoSage = FALSE - WHERE mc.codigoCuenta IS NULL - GROUP BY pc.codigoCuenta - ) sub ON sub.codigoCuenta = pc.codigoCuenta ; - --- DUAS - UPDATE movConta m - JOIN vn.XDiario x ON x.ASIEN = m.Asiento AND x.SUBCTA =m.CodigoCuenta - JOIN (SELECT ASIEN - FROM vn.invoiceIn ii - JOIN vn.XDiario x ON x.CLAVE = ii.id - WHERE enlazadoSage = 0 AND - SUBCTA = '4700000999' - )sub ON sub.ASIEN = x.Asien - SET m.BaseIva1 = x.BASEEURO , - m.PorIva1 = x.IVA, - m.CuotaIva1 = (x.IVA/100) * x.BASEEURO , - m.CodigoTransaccion1 = 56 , - m.CodigoIva1 = IF(x.IVA = 10, 22, 90), - m.IvaDeducible1 = TRUE, - m.Serie = x.SERIE, - m.Factura = x.FACTURA, - m.TipoFactura = "R", - m.FechaFacturaOriginal = x.FECHA_EX, - m.SuFacturaNo = x.FACTURAEX, - m.FechaOperacion = x.FECHA_OP - WHERE x.SERIE = 'D' AND - m.enlazadoSage = FALSE; - --- Rectificativas -UPDATE movConta m - JOIN (SELECT x.ASIEN, x.FECHA_RT, x.SERIE_RT, x.FACTU_RT - FROM movConta m - JOIN vn.XDiario x ON x.ASIEN = m.Asiento - WHERE m.TipoRectificativa>0 AND - m.enlazadoSage = FALSE AND - x.FACTU_RT IS NOT NULL - GROUP BY x.ASIEN - ) sub ON sub.ASIEN = m.Asiento - SET m.EjercicioFacturaOriginal = YEAR(sub.FECHA_RT), - m.SerieFacturaOriginal = sub.SERIE_RT, - m.NumeroFacturaOriginal = sub.FACTU_RT - WHERE m.TipoRectificativa > 0 AND - m.enlazadoSage = FALSE ; - --- Exportaciones Andorras y Canarias cambia TT (la cuenta de taxCode es compartida, id:125) -UPDATE sage.movConta m - SET CodigoTransaccion1 = 15, - CodigoTransaccion2 = IF(CodigoTransaccion2 = 0, 0, 15), - CodigoTransaccion3 = IF(CodigoTransaccion3 = 0, 0, 15), - CodigoTransaccion4 = IF(CodigoTransaccion4 = 0, 0, 15) - WHERE enlazadoSage = FALSE AND - (CodigoTransaccion1 = 14 OR CodigoTransaccion2 = 14 OR CodigoTransaccion3 = 14 OR CodigoTransaccion4 = 14) AND - SiglaNAcion IN ('XC','XB'); - - - --- Divisas - UPDATE sage.movConta - SET CodigoDivisa = IF(ImporteCambio<>0, "USD", "") - WHERE enlazadoSage = FALSE AND - ImporteCambio<>0 AND - ImporteDivisa<>0; - - -/*-- Actualiza las facturas DUA para excluirlas del 347 y marcarlas como intracomunitarias -/*UPDATE sage.movConta mc - SET - mc.Intracomunitaria = 1, - mc.Exclusion347 = 1 -WHERE - mc.CodigoCuenta = '4700000999'; */ - - --- MARCAR EN CASO DE SER INTRACOMUNITARIA -/* -UPDATE sage.movConta mc - SET - mc.Intracomunitaria = 1 -WHERE - mc.CodigoTransaccion1 IN (20,29); -*/ - - - -- LAS FACTURAS RTECTIFICATIVAS QUE TIENEN CUENTA DE IVA 477.2 SALE CON T.T. 1, TODAS ESTAS FACTURAS DEBEN DE TENER T.T. 15 - - /*UPDATE sage.movConta mc - JOIN - (SELECT - Asiento - FROM - sage.movConta - WHERE - CodigoCuenta = 4770000002) sub ON sub.Asiento = mc.Asiento -SET - CodigoTransaccion1 = CASE - WHEN CodigoTransaccion1 = 1 THEN 15 - ELSE CodigoTransaccion1 - END, - CodigoTransaccion2 = CASE - WHEN CodigoTransaccion2 = 1 THEN 15 - ELSE CodigoTransaccion2 - END, - CodigoTransaccion3 = CASE - WHEN CodigoTransaccion3 = 1 THEN 15 - ELSE CodigoTransaccion3 - END, - CodigoTransaccion4 = CASE - WHEN CodigoTransaccion4 = 1 THEN 15 - ELSE CodigoTransaccion4 - END -WHERE - serie = 'R'; - -*/ - -/* -Nombre Tipo Longitud Descripción campo / Valor por defecto -MovPosicion Guid contador 16 Automático, no informar -Ejercicio Entero 2 -1 -- Al informar este valor se calcula automát. A partir de la fecha de asiento -CodigoEmpresa Entero 2 Empresa de Sage 200c donde va destinado el asiento -Asiento Entero Largo 4 Número de asiento -CargoAbono Texto 1 "D" - Debe / "H" - Haber -CodigoCuenta Texto 15 Cuenta contable del movimiento -Contrapartida Texto 15 Es informativo, no es necesario informarlo -FechaAsiento Fecha 8 Fecha del asiento -TipoDocumento Texto 6 -DocumentoConta Texto 9 -Comentario Texto 40 Comentario del asiento -ImporteAsiento Doble 19 Importe del movimiento -CodigoDiario Entero 2 -CodigoCanal Texto 10 Centro coste analítico (no necesario informar) -CodigoActividad Texto 1 -FechaVencimiento Fecha 8 Si se tienen que generar efectos, será la fecha de vto. Del efecto. No informar -NumeroPeriodo Entero 2 -1 -- Al informar este valor se calcula automát. A partir de la fecha de asiento -CodigoUsuario Entero 2 -FechaGrabacion Fecha 8 -TipoEntrada Texto 2 -CodigoDepartamento Texto 10 Centro coste analítico (no necesario informar) -CodigoSeccion Texto 10 Centro coste analítico (no necesario informar) -CodigoDivisa Texto 3 -ImporteCambio Doble 19 -ImporteDivisa Doble 19 -FactorCambio Doble 19 -CodigoProyecto Texto 10 Centro coste analítico (no necesario informar) -LibreN1 Entero Largo 4 Campo libre numérico -LibreN2 Entero Largo 4 Campo libre numérico -LibreA1 Texto 15 Campo libre alfanumérico -LibreA2 Texto 15 Campo libre alfanumérico -IdDelegacion Texto 10 Centro coste analítico (no necesario informar) -OrdenMovimientos Contador 4 Número de orden de cada movimiento dentro de un mismo asiento, autonumerar para cada asiento -MovCartera Guid 16 -IdProcesoIME Guid 16 guid igual para todos los registros que correspondan a una misma importación. -TipoCarteraIME Entero 2 0 - Para que no genere cartera -TipoAnaliticaIME Entero 2 -StatusTraspasadoIME Byte 1 0 - Para que quede marcado el movimiento como no importado todavía. -TipoImportacionIME Byte 1 0 - Alta -BaseIva1 Doble 19 Base para el IVA 1 (idéntico para cada posible IVA hasta el 4) (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -PorBaseCorrectora1 Doble 19 Base correctora (en caso de que la haya) para el IVA 1 (idéntico para cada posible IVA hasta el 4) (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -PorIva1 Doble 19 Porcentaje IVA 1 (idéntico para cada posible IVA hasta el 4) (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -CuotaIva1 Doble 19 Cuota IVA 1 (idéntico para cada posible IVA hasta el 4) (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -PorRecargoEquivalencia1 Doble 19 Si hay recargo - Porcentaje de recargo para el IVA 1 (idéntico para cada posible IVA hasta el 4) (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -RecargoEquivalencia1 Doble 19 Si hay recargo - Importe de Recargo para el IVA 1 (idéntico para cada posible IVA hasta el 4) (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -CodigoTransaccion1 Byte 1 Ver con dpto. de contabilidad - Depende de la naturaleza del asiento (Nacional, Intracoumunitario, etc…) (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -BaseIva2 Doble 19 0 -PorBaseCorrectora2 Doble 19 0 -PorIva2 Doble 19 0 -CuotaIva2 Doble 19 0 -PorRecargoEquivalencia2 Doble 19 0 -RecargoEquivalencia2 Doble 19 0 -CodigoTransaccion2 Byte 1 0 -BaseIva3 Doble 19 0 -PorBaseCorrectora3 Doble 19 0 -PorIva3 Doble 19 0 -CuotaIva3 Doble 19 0 -PorRecargoEquivalencia3 Doble 19 0 -RecargoEquivalencia3 Doble 19 0 -CodigoTransaccion3 Byte 1 0 -BaseIva4 Doble 19 0 -PorBaseCorrectora4 Doble 19 0 -PorIva4 Doble 19 0 -CuotaIva4 Doble 19 0 -PorRecargoEquivalencia4 Doble 19 0 -RecargoEquivalencia4 Doble 19 0 -CodigoTransaccion4 Byte 1 0 -Año Entero 2 Ejercicio de la factura en el caso de que sea un asiento de facturas. (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -Serie Texto 10 Serie de la factura en el caso de que sea un asiento de facturas. (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -Factura Entero Largo 4 Número de la factura en el caso de que sea un asiento de facturas. (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -SuFacturaNo Texto 40 Número de la factura del proveedor para factura recibidas, en el caso de que el asiento sea de una factura. (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -FechaFactura Fecha 8 Fecha de la factura en el caso de que sea un asiento de facturas. (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -ImporteFactura Doble 19 Importe de la factura en el caso de que sea un asiento de facturas. (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -TipoFactura Texto 1 "E" - Factura emitida / "R" - Factura Recibida - en el caso de que sea un asiento de facturas. (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -CodigoCuentaFactura Texto 15 Cuenta contable del cliente / proveedor en el caso de que sea un asiento de facturas. (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -CifDni Texto 13 CIF del cliente / proveedor en el caso de que sea un asiento de facturas. (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -Nombre Texto 35 Nombre del cliente / proveedor en el caso de que sea un asiento de facturas. (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -CodigoRetencion Entero 2 Código de retención de la factura en el caso de que sea un asiento de facturas. (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -BaseRetencion Doble 19 Base de retención de la factura en el caso de que sea un asiento de facturas. (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -PorRetencion Doble 19 Porcentaje de retención de la factura en el caso de que sea un asiento de facturas. (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -ImporteRetencion Doble 19 Importe de retención de la factura en el caso de que sea un asiento de facturas. (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -AbonoIva Entero 2 0 -CodigoActividadF Texto 1 ('') -Intracomunitaria Entero 2 0 -CodigoTerritorio Entero 2 0 -SiglaNacion Texto 2 Sigla de la nación de la factura en el caso de que sea un asiento de facturas. (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -RetencionInformativa Entero 2 0 -EjercicioFacturaOriginal Entero 2 0 -SerieFacturaOriginal Texto 10 ('') -NumeroFacturaOriginal Entero Largo 4 0 -EjercicioFactura Entero 2 Ejercicio de la factura en el caso de que sea un asiento de facturas. (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -CobroPagoRetencion Texto 1 ('') -FechaOperacion Fecha 8 Normalmente Fecha Factura en el caso de que sea un asiento de facturas. (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -Exclusion347 Entero 2 0 -MovIdentificadorIME Guid contador 16 (newid()) -Previsiones Texto 1 ('') -MantenerAsiento Byte 1 -1 si se quiere mantener el número de asiento que se informa en la importación o "0" si se quiere que se asigne automáticamente el asiento en Sage 200c -OrdenMovIME Entero 2 0 -Metalico347 Entero 2 0 -ClaveOperacionFactura_ Texto 1 Ver con dpto. de contabilidad - Depende de la naturaleza del asiento (Nacional, Intracoumunitario, etc…) (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -SerieAgrupacion_ Texto 10 ('') -NumeroFacturaInicial_ Entero Largo 4 0 -NumeroFacturaFinal_ Entero Largo 4 0 -IdAsientoExterno Texto 50 ('') -IdDiarioExterno Texto 10 ('') -IdFacturaExterno Texto 50 ('') -IdMovimiento Texto 40 ('') -IdCuadre Entero 2 ((0)) -FechaCuadre Fecha 8 (getdate()) -TipoCuadre Texto 4 ('') -AgrupacionCuadre Entero Largo 4 ((0)) -StatusSaldo Entero 2 ((0)) -StatusConciliacion Entero 2 ((0)) -CodigoConciliacion Entero Largo 4 ((0)) -FechaConciliacion Fecha 8 -TipoConciliacion Entero 2 ((0)) -IndicadorContaBanco Texto 1 ('') -Descripcion3 Texto 40 ('') -Descripcion4 Texto 40 ('') -Descripcion5 Texto 40 ('') -Descripcion6 Texto 40 ('') -Descripcion7 Texto 40 ('') -Descripcion8 Texto 50 ('') -Descripcion9 Texto 50 ('') -Descripcion2 Texto 250 ('') -Descripcion1 Texto 250 ('') -Punteo1 Entero 2 ((0)) -Punteo9 Entero 2 ((0)) -Punteo8 Entero 2 ((0)) -Punteo7 Entero 2 ((0)) -Punteo6 Entero 2 ((0)) -Punteo5 Entero 2 ((0)) -Punteo4 Entero 2 ((0)) -Punteo3 Entero 2 ((0)) -Punteo2 Entero 2 ((0)) -CodigoIva1 Entero 2 ((0)) -CodigoIva2 Entero 2 ((0)) -CodigoIva3 Entero 2 ((0)) -CodigoIva4 Entero 2 ((0)) -CriterioIva Byte 1 ((0)) -FechaMaxVencimiento Fecha 8 -TipoCriterioCaja Byte 1 ((0)) -MovFacturaOrigenIME Texto 50 ('') -IdFacturaExternoFinal Texto 50 ('') -IdFacturaExternoInicial Texto 50 ('') -IdFacturaExternoOriginal Texto 50 ('') -NumFacturasExternoAgrupacion Entero Largo 4 ((0)) -CodigoMedioCobro Texto 1 ('') -MedioCobro Texto 31 ('') -IvaDeducible1 Entero 2 ((-1)) -IvaDeducible2 Entero 2 ((-1)) -IvaDeducible3 Entero 2 ((-1)) -IvaDeducible4 Entero 2 ((-1)) -TipoRectificativa Entero 2 ((0)) -FechaFacturaOriginal Fecha 8 -BaseImponibleOriginal Doble 19 ((0)) -CuotaIvaOriginal Doble 19 ((0)) -ClaseAbonoRectificativas Entero 2 ((0)) -RecargoEquivalenciaOriginal Doble 19 ((0)) -ObjetoFactura Texto 500 ('') -*/ -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 PROCEDURE IF EXISTS `movContaAdd___` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -22518,7 +22082,7 @@ DELIMITER ;; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; /*!50003 SET @saved_time_zone = @@time_zone */ ;; /*!50003 SET time_zone = 'SYSTEM' */ ;; -/*!50106 CREATE*/ /*!50117 DEFINER=`z-sysadmin`@`%`*/ /*!50106 EVENT `log_clean` ON SCHEDULE EVERY 1 DAY STARTS '2019-06-17 02:45:00' ON COMPLETION PRESERVE ENABLE DO CALL log_clean */ ;; +/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `log_clean` ON SCHEDULE EVERY 1 DAY STARTS '2019-06-17 02:45:00' ON COMPLETION PRESERVE ENABLE DO CALL log_clean */ ;; /*!50003 SET time_zone = @saved_time_zone */ ;; /*!50003 SET sql_mode = @saved_sql_mode */ ;; /*!50003 SET character_set_client = @saved_cs_client */ ;; @@ -23628,9 +23192,10 @@ DROP TABLE IF EXISTS `version`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `version` ( `code` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - `number` char(11) COLLATE utf8_unicode_ci NOT NULL, - `gitCommit` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - `updated` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `number` char(11) COLLATE utf8_unicode_ci DEFAULT NULL, + `gitCommit` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `updated` datetime DEFAULT NULL, + `lastNumber` char(11) COLLATE utf8_unicode_ci DEFAULT NULL, PRIMARY KEY (`code`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -23645,9 +23210,9 @@ DROP TABLE IF EXISTS `versionUser`; CREATE TABLE `versionUser` ( `code` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `user` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - `number` char(11) COLLATE utf8_unicode_ci NOT NULL, - `gitCommit` varchar(255) COLLATE utf8_unicode_ci NOT NULL, - `updated` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `number` char(11) COLLATE utf8_unicode_ci DEFAULT NULL, + `gitCommit` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `updated` datetime NOT NULL, PRIMARY KEY (`code`,`user`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -23887,6 +23452,28 @@ DELIMITER ; /*!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 `hasDateOverlapped` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `hasDateOverlapped`(vSarted1 DATE, vEnded1 DATE, vSarted2 DATE, vEnded2 DATE) RETURNS tinyint(1) + DETERMINISTIC +BEGIN + + RETURN GREATEST(vSarted1, vSarted2) <= LEAST(vEnded1,vEnded2); + +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 `hmacSha2` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -24885,6 +24472,7 @@ SET character_set_client = utf8; `name` tinyint NOT NULL, `rgb` tinyint NOT NULL, `code` tinyint NOT NULL, + `permissionRate` tinyint NOT NULL, `holidayEntitlementRate` tinyint NOT NULL, `discountRate` tinyint NOT NULL ) ENGINE=MyISAM */; @@ -25577,11 +25165,11 @@ DELIMITER ; DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`awb_au` AFTER UPDATE ON `awb` FOR EACH ROW BEGIN -/* -IF NEW.amount <> OLD.amount THEN - CALL vn2008.buy_tarifas_awb(NEW.code); -END IF; -*/ + + IF NEW.amount <> OLD.amount THEN + CALL vn2008.buy_tarifas_awb(NEW.code); + END IF; + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -27264,6 +26852,7 @@ CREATE TABLE `cmr` ( `packagesList` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `merchandiseDetail` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `state` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, + `landed` datetime DEFAULT NULL COMMENT 'Hora de llegada a destino', PRIMARY KEY (`id`), KEY `cmr_fk1_idx` (`ticketFk`), KEY `cmr_fk2_idx` (`companyFk`), @@ -27835,8 +27424,6 @@ CREATE TABLE `config` ( `fakeEmail` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `defaultersMaxAmount` int(10) DEFAULT '200' COMMENT 'maxima deuda permitida a partir de la cual se bloquea a un usuario', `ASIEN` bigint(20) DEFAULT NULL, - `deviceHuntingMode` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Habilita el modo cazador para usuarios sin device registrado', - `tractorHuntingMode` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Habilita el modo cazador para usuarios que no se han logeado un tractor para sacar', `dayStartingHour` int(11) NOT NULL DEFAULT '3' COMMENT 'Hora a la que empieza una nueva jornada de producción', PRIMARY KEY (`id`), KEY `fechainv_idx` (`inventoried`) @@ -28745,6 +28332,21 @@ CREATE TABLE `deviceProduction` ( ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `deviceProductionConfig` +-- + +DROP TABLE IF EXISTS `deviceProductionConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `deviceProductionConfig` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `isAllUsersallowed` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Permite que cualquier usuario pueda loguearse', + `isTractorHuntingMode` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Habilita el modo cazador para usuarios que no se han logeado un tractor para sacar', + PRIMARY KEY (`id`) +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `deviceProductionModels` -- @@ -31503,14 +31105,26 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`invoiceOut_afterInsert` AFTER INSERT ON `vn`.`invoiceOut` FOR EACH ROW BEGIN CALL clientRisk_update(NEW.clientFk, NEW.companyFk, NEW.amount); + IF (SELECT COUNT(*) + FROM client + WHERE id = NEW.clientFk + AND businessTypeFk = 'officialOrganism' + ) THEN + CALL mail_insert('administracion@verdnatura.es', + NULL, + CONCAT('Se ha emitido una factura al organismo: ', NEW.clientFk), + CONCAT('Presentar factura en FACE https://salix.verdnatura.es/#!/invoice-out/', + NEW.id, + '/summary')); + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -31769,10 +31383,10 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`item_afterInsert` - AFTER INSERT ON `item` FOR EACH ROW +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`item_afterInsert` + AFTER INSERT ON `item` + FOR EACH ROW BEGIN - DECLARE vStandardFlowerBox INT; CALL hedera.image_ref('catalog', NEW.image); @@ -31784,16 +31398,6 @@ BEGIN INSERT INTO vn.itemTaxCountry(itemFk, countryFk) SELECT NEW.id, 30; - - IF NEW.packingOut THEN - SELECT standardFlowerBox * 1000 INTO vStandardFlowerBox - FROM volumeConfig; - - UPDATE itemCost ic - JOIN warehouse w ON w.id = ic.warehouseFk - SET cm3Delivery = vStandardFlowerBox / NEW.packingOut - WHERE ic.itemFk = NEW.id AND w.hasProduction; - END IF; END */;; DELIMITER ; @@ -36832,6 +36436,8 @@ CREATE TABLE `sector` ( `workerFk` int(11) DEFAULT NULL, `labelReport__` tinyint(3) DEFAULT NULL, `printerFk` tinyint(3) unsigned DEFAULT NULL, + `isHideForPickers` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'sector a ocultar a los sacadores', + `isReserve` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Sectores de reserva, como Albenfruit o Fuentes', PRIMARY KEY (`id`,`warehouseFk`), UNIQUE KEY `code_UNIQUE` (`code`), KEY `sector_fk1_idx` (`warehouseFk`), @@ -37034,6 +36640,7 @@ CREATE TABLE `shelving` ( `priority` int(11) DEFAULT NULL, `parked` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `userFk` int(10) unsigned DEFAULT NULL, + `isSpam` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'señala las matrículas con producto que se puede llevar a la reserva', PRIMARY KEY (`code`), KEY `shelving_fk1_idx` (`parkingFk`), KEY `shelving_fk2_idx` (`userFk`), @@ -37105,14 +36712,14 @@ DELIMITER ; -- -- Table structure for table `silexACL` -- - -DROP TABLE IF EXISTS `silexACL`; + +DROP TABLE IF EXISTS `silexACL`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `silexACL` ( `id` int(11) NOT NULL AUTO_INCREMENT, - `module` varchar(50) NOT NULL, - `method` varchar(50) NOT NULL, + `module` varchar(255) NOT NULL, + `method` varchar(255) NOT NULL, `role` varchar(20) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `module_UNIQUE` (`module`,`method`,`role`) @@ -38160,7 +37767,7 @@ BEGIN call util.debugAdd(NEW.id,CONCAT(OLD.routeFk,' ',NEW.routeFk)); END IF; - IF !(NEW.shipped <=> OLD.shipped) THEN + IF !(DATE(NEW.shipped) <=> DATE(OLD.shipped)) THEN IF YEAR(NEW.shipped) < 2000 THEN SIGNAL SQLSTATE '46000' SET MESSAGE_TEXT = 'Year cannot be lesser than 2000'; @@ -38169,6 +37776,9 @@ BEGIN IF YEAR(NEW.shipped) = 2000 THEN SET NEW.isDeleted = TRUE; END IF; + + SET NEW.nickname = CONCAT('<',DAY(OLD.shipped),'> ', NEW.nickname ); + END IF; IF !(NEW.isDeleted <=> OLD.isDeleted) AND NEW.isDeleted THEN @@ -40217,6 +39827,20 @@ SET character_set_client = utf8; ) ENGINE=MyISAM */; SET character_set_client = @saved_cs_client; +-- +-- Temporary table structure for view `workerDepartmentTest` +-- + +DROP TABLE IF EXISTS `workerDepartmentTest`; +/*!50001 DROP VIEW IF EXISTS `workerDepartmentTest`*/; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +/*!50001 CREATE TABLE `workerDepartmentTest` ( + `workerFk` tinyint NOT NULL, + `departmentFk` tinyint NOT NULL +) ENGINE=MyISAM */; +SET character_set_client = @saved_cs_client; + -- -- Table structure for table `workerDisableExcluded` -- @@ -40294,7 +39918,7 @@ DROP TABLE IF EXISTS `workerHourPrice`; CREATE TABLE `workerHourPrice` ( `id` int(11) NOT NULL AUTO_INCREMENT, `dated` date NOT NULL, - `hollidayInc` decimal(4,2) DEFAULT NULL, + `holidayInc` decimal(4,2) DEFAULT NULL, `nightInc` decimal(4,2) DEFAULT NULL, `extraInc` decimal(4,2) DEFAULT NULL, PRIMARY KEY (`id`) @@ -40343,13 +39967,13 @@ CREATE TABLE `workerJourney` ( `priceOrdinaryHour` decimal(5,2) NOT NULL DEFAULT '0.00', `nocturn` decimal(5,2) NOT NULL DEFAULT '0.00', `priceNocturnHour` decimal(5,2) NOT NULL DEFAULT '0.00', - `hollyday` decimal(5,2) NOT NULL DEFAULT '0.00', - `priceHollydayHour` decimal(5,2) NOT NULL DEFAULT '0.00', + `holiday` decimal(5,2) NOT NULL DEFAULT '0.00', + `priceHolidayHour` decimal(5,2) NOT NULL DEFAULT '0.00', `lunch` decimal(5,2) NOT NULL DEFAULT '0.00', `priceExtraHour` decimal(5,2) NOT NULL DEFAULT '0.00', `extra` decimal(5,2) NOT NULL DEFAULT '0.00', `contractJourney` decimal(5,2) NOT NULL DEFAULT '0.00', - `priceExtraHollyday` decimal(5,2) NOT NULL DEFAULT '0.00', + `priceExtraHoliday` decimal(5,2) NOT NULL DEFAULT '0.00', `businessFk` int(11) DEFAULT NULL, `isPaid` tinyint(1) NOT NULL DEFAULT '0', `isUpdated` tinyint(1) NOT NULL DEFAULT '0', @@ -40665,6 +40289,9 @@ CREATE TABLE `workerTimeControlConfig` ( `mailSuccessFolder` varchar(45) COLLATE utf8_bin NOT NULL, `mailErrorFolder` varchar(45) COLLATE utf8_bin NOT NULL, `mailUser` varchar(45) COLLATE utf8_bin NOT NULL, + `minHoursToBreak` decimal(5,2) unsigned NOT NULL COMMENT 'Horas mínimas que se deben trabajar para añadir descanso remunerado', + `breakHours` decimal(5,2) unsigned NOT NULL COMMENT 'Descanso remunerado', + `hoursCompleteWeek` int(10) unsigned NOT NULL COMMENT 'Horas a realizar por semana para que se considere jornada completa', PRIMARY KEY (`id`) ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='All values in seconds'; /*!40101 SET character_set_client = @saved_cs_client */; @@ -40859,14 +40486,14 @@ SET character_set_client = utf8; SET character_set_client = @saved_cs_client; -- --- Temporary table structure for view `workerWithoutDevice` +-- Temporary table structure for view `workerWithoutDevice__` -- -DROP TABLE IF EXISTS `workerWithoutDevice`; -/*!50001 DROP VIEW IF EXISTS `workerWithoutDevice`*/; +DROP TABLE IF EXISTS `workerWithoutDevice__`; +/*!50001 DROP VIEW IF EXISTS `workerWithoutDevice__`*/; SET @saved_cs_client = @@character_set_client; SET character_set_client = utf8; -/*!50001 CREATE TABLE `workerWithoutDevice` ( +/*!50001 CREATE TABLE `workerWithoutDevice__` ( `workerFk` tinyint NOT NULL, `Trabajador` tinyint NOT NULL, `Colecciones` tinyint NOT NULL @@ -41544,6 +41171,24 @@ END */ ;; /*!50003 SET character_set_client = @saved_cs_client */ ;; /*!50003 SET character_set_results = @saved_cs_results */ ;; /*!50003 SET collation_connection = @saved_col_connection */ ;; +/*!50106 DROP EVENT IF EXISTS `mysqlConnectionsSorter_kill` */;; +DELIMITER ;; +/*!50003 SET @saved_cs_client = @@character_set_client */ ;; +/*!50003 SET @saved_cs_results = @@character_set_results */ ;; +/*!50003 SET @saved_col_connection = @@collation_connection */ ;; +/*!50003 SET character_set_client = utf8mb4 */ ;; +/*!50003 SET character_set_results = utf8mb4 */ ;; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; +/*!50003 SET @saved_time_zone = @@time_zone */ ;; +/*!50003 SET time_zone = 'SYSTEM' */ ;; +/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `mysqlConnectionsSorter_kill` ON SCHEDULE EVERY 1 MINUTE STARTS '2021-10-28 09:56:27' ON COMPLETION NOT PRESERVE ENABLE DO CALL mysqlConnectionsSorter_kill() */ ;; +/*!50003 SET time_zone = @saved_time_zone */ ;; +/*!50003 SET sql_mode = @saved_sql_mode */ ;; +/*!50003 SET character_set_client = @saved_cs_client */ ;; +/*!50003 SET character_set_results = @saved_cs_results */ ;; +/*!50003 SET collation_connection = @saved_col_connection */ ;; /*!50106 DROP EVENT IF EXISTS `printQueue_check` */;; DELIMITER ;; /*!50003 SET @saved_cs_client = @@character_set_client */ ;; @@ -41714,7 +41359,7 @@ DELIMITER ;; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; /*!50003 SET @saved_time_zone = @@time_zone */ ;; /*!50003 SET time_zone = 'SYSTEM' */ ;; -/*!50106 CREATE*/ /*!50117 DEFINER=`z-sysadmin`@`%`*/ /*!50106 EVENT `ticket_doRecalc` ON SCHEDULE EVERY 10 SECOND STARTS '2021-02-26 07:32:23' ON COMPLETION PRESERVE ENABLE DO CALL ticket_doRecalc */ ;; +/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `ticket_doRecalc` ON SCHEDULE EVERY 10 SECOND STARTS '2021-02-26 07:32:23' ON COMPLETION PRESERVE ENABLE DO CALL ticket_doRecalc */ ;; /*!50003 SET time_zone = @saved_time_zone */ ;; /*!50003 SET sql_mode = @saved_sql_mode */ ;; /*!50003 SET character_set_client = @saved_cs_client */ ;; @@ -41766,34 +41411,6 @@ END */ ;; /*!50003 SET character_set_client = @saved_cs_client */ ;; /*!50003 SET character_set_results = @saved_cs_results */ ;; /*!50003 SET collation_connection = @saved_col_connection */ ;; -/*!50106 DROP EVENT IF EXISTS `workerTimeControl_sendMailByDepartment` */;; -DELIMITER ;; -/*!50003 SET @saved_cs_client = @@character_set_client */ ;; -/*!50003 SET @saved_cs_results = @@character_set_results */ ;; -/*!50003 SET @saved_col_connection = @@collation_connection */ ;; -/*!50003 SET character_set_client = utf8mb4 */ ;; -/*!50003 SET character_set_results = utf8mb4 */ ;; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ;; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; -/*!50003 SET @saved_time_zone = @@time_zone */ ;; -/*!50003 SET time_zone = 'SYSTEM' */ ;; -/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `workerTimeControl_sendMailByDepartment` ON SCHEDULE EVERY 1 WEEK STARTS '2021-09-29 12:00:00' ON COMPLETION NOT PRESERVE ENABLE DO BEGIN - DECLARE vWeek,vYear INT; - - SELECT week,year INTO vWeek,vYear - FROM vn.time - WHERE dated IN (DATE_ADD(CURDATE(), INTERVAL -10 DAY), DATE_ADD(CURDATE(), INTERVAL -4 DAY)) - GROUP BY year,week - LIMIT 1; - - CALL vn.workerTimeControl_sendMailByDepartment(vWeek, vYear, NULL); -END */ ;; -/*!50003 SET time_zone = @saved_time_zone */ ;; -/*!50003 SET sql_mode = @saved_sql_mode */ ;; -/*!50003 SET character_set_client = @saved_cs_client */ ;; -/*!50003 SET character_set_results = @saved_cs_results */ ;; -/*!50003 SET collation_connection = @saved_col_connection */ ;; /*!50106 DROP EVENT IF EXISTS `zoneGeo_doCalc` */;; DELIMITER ;; /*!50003 SET @saved_cs_client = @@character_set_client */ ;; @@ -42157,17 +41774,17 @@ DELIMITER ; /*!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 `buy_hasNotifyPassport` */; +/*!50003 DROP FUNCTION IF EXISTS `buy_hasNotifyPassport__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `buy_hasNotifyPassport`(vBuyFk INT, vItemFk INT) RETURNS tinyint(1) +CREATE DEFINER=`root`@`%` FUNCTION `buy_hasNotifyPassport__`(vBuyFk INT, vItemFk INT) RETURNS tinyint(1) READS SQL DATA BEGIN DECLARE vHasPassport BOOL; @@ -42872,7 +42489,7 @@ BEGIN * * */ - DECLARE vIsGranted BOOLEAN; + /*DECLARE vIsGranted BOOLEAN; DECLARE vDeviceProductionFk INT(11) DEFAULT NULL; SELECT dp.id INTO vDeviceProductionFk @@ -42887,7 +42504,7 @@ BEGIN AND dpu.deviceProductionFk = vDeviceProductionFk; RETURN vIsGranted; - END IF; + END IF;*/ RETURN TRUE; END ;; DELIMITER ; @@ -42905,7 +42522,7 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`z-sysadmin`@`%` FUNCTION `duaTax_getRate`(vDua INT, vTaxClass INT) RETURNS decimal(5,2) +CREATE DEFINER=`root`@`%` FUNCTION `duaTax_getRate`(vDua INT, vTaxClass INT) RETURNS decimal(5,2) DETERMINISTIC BEGIN DECLARE vCountryFk INTEGER; @@ -46212,7 +45829,7 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`z-sysadmin`@`%` FUNCTION `time_getSalesYear`(vMonth INT, vYear INT) RETURNS int(11) +CREATE DEFINER=`root`@`%` FUNCTION `time_getSalesYear`(vMonth INT, vYear INT) RETURNS int(11) DETERMINISTIC BEGIN DECLARE vSalesYear INT; @@ -47159,7 +46776,7 @@ BEGIN * */ INSERT INTO mail (receiver,replyTo,subject,body) - SELECT 'administracion@verdnatura.es' sender, + 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 @@ -47329,10 +46946,6 @@ BEGIN */ DECLARE vEntryFk INT; DECLARE vItemFk INT; - DECLARE vSize INT; - DECLARE vPackageFk VARCHAR(10); - DECLARE vStickers INT; - DECLARE vPacking INT; DECLARE vPackingOut DECIMAL(10,2); DECLARE vWarehouse INT; DECLARE vStandardFlowerBox INT; @@ -47340,11 +46953,14 @@ BEGIN DECLARE vIsMerchandise BOOL; DECLARE vIsFeedStock BOOL; - SELECT b.entryFk, b.itemFk, b.stickers, b.packing, i.packingOut - INTO vEntryFk, vItemFk, vStickers, vPacking, vPackingOut + SELECT b.entryFk, b.itemFk, i.packingOut, ic.merchandise, vc.standardFlowerBox + INTO vEntryFk, vItemFk, vPackingOut, vIsMerchandise, vStandardFlowerBox 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.packageFk AND NOT p.isBox + JOIN volumeConfig vc ON TRUE WHERE b.id = vSelf; SELECT t.warehouseInFk, t.warehouseOutFk @@ -47353,14 +46969,6 @@ BEGIN JOIN travel t ON t.id = e.travelFk WHERE e.id = vEntryFk; - SELECT k.merchandise m, vc.standardFlowerBox - INTO vIsMerchandise, vStandardFlowerBox - FROM itemCategory k - JOIN itemType it ON it.categoryFk = k.id - JOIN item i ON i.typeFk = it.id - JOIN volumeConfig vc ON TRUE - WHERE i.id = vItemFk; - IF vIsMerchandise THEN REPLACE itemCost SET @@ -47388,10 +46996,7 @@ BEGIN JOIN edi.ekt be ON be.id = b.ektFk JOIN edi.supplier es ON es.supplier_id = be.pro WHERE b.id = vSelf; - - IF buy_hasNotifyPassport(vSelf, vItemFk) THEN - CALL vn.buy_notifyPassport(vSelf, vItemFk, vStickers, vPacking); - END IF; + END IF; END ;; @@ -47525,17 +47130,17 @@ DELIMITER ; /*!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 PROCEDURE IF EXISTS `buy_notifyPassport` */; +/*!50003 DROP PROCEDURE IF EXISTS `buy_notifyPassport__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `buy_notifyPassport`( +CREATE DEFINER=`root`@`%` PROCEDURE `buy_notifyPassport__`( IN vBuyFk INT, IN vItemFk INT, IN vStickers SMALLINT, @@ -47652,26 +47257,31 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `buy_updateGrouping`(vWarehouseFk INT,vItemFk INT,vGrouping INT) +CREATE DEFINER=`root`@`%` PROCEDURE `buy_updateGrouping`(vWarehouseFk INT, vItemFk INT, vGrouping INT) BEGIN +/** + * Actualiza el grouping de las últimas compras de un artículo + * + * @param vWarehouseFk Id del almacén + * @param vItemFk Id del Artículo + * @param vGrouping Cantidad de grouping + */ + + CALL vn.buyUltimate(vWarehouseFk, CURDATE()); -DECLARE lastId INT; - -CALL vn2008.item_last_buy_(vWarehouseFk,vItemFk); - -SELECT b.buy_id INTO lastId -FROM vn2008.t_item_last_buy b -INNER JOIN vn2008.Compres c ON c.Id_Compra = b.buy_id -where b.warehouse_id = vWarehouseFk AND b.item_id =vItemFk; - -UPDATE vn.buy SET `grouping` = vGrouping WHERE id = lastId; + UPDATE vn.buy b + JOIN tmp.buyUltimate bu ON b.id = bu.buyFk + SET b.`grouping` = vGrouping + WHERE bu.warehouseFk = vWarehouseFk + AND bu.itemFk = vItemFk; + DROP TEMPORARY TABLE tmp.buyUltimate; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -47708,17 +47318,17 @@ DELIMITER ; /*!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 PROCEDURE IF EXISTS `camaraFutureVolume` */; +/*!50003 DROP PROCEDURE IF EXISTS `camaraFutureVolume__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `camaraFutureVolume`(vWarehouseFk INT, vDateStart DATE, vDateEnd DATE) +CREATE DEFINER=`root`@`%` PROCEDURE `camaraFutureVolume__`(vWarehouseFk INT, vDateStart DATE, vDateEnd DATE) BEGIN DECLARE vDated DATE; @@ -48427,7 +48037,7 @@ proc: BEGIN IF (NOT vIsLogifloraAllowed AND vVNHWarehouseFk != vWarehouseFk) OR NOT vn.isLogifloraDay(vShipped, vWarehouseFk) - OR NOT(vIsCatalonianBuyer OR vIsFrenchVNHBuyer) + -- OR NOT(vIsCatalonianBuyer OR vIsFrenchVNHBuyer) THEN CALL cache.visible_refresh(vVisibleCache, FALSE, vWarehouseFk); @@ -50660,14 +50270,19 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `collectionPlacement_get`(vParamFk INT(11)) BEGIN + + /* Devuelve el listado de ubicaciones a las que hay que ir para preparar una colección o ticket + * + * @param vParamFk Identificador de vn.collection o Identificador de vn.ticket + */ DECLARE vCalcFk INT; DECLARE vWarehouseFk INT; @@ -50677,9 +50292,9 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.sale; CREATE TEMPORARY TABLE tmp.sale ENGINE = MEMORY - SELECT 0000000 as ticketFk, - 0000000 as saleFk, - 0000000 as itemFk, + SELECT 00000000 as ticketFk, + 00000000 as saleFk, + 00000000 as itemFk, FALSE as isStowaway, 0 as quantity; @@ -50696,29 +50311,6 @@ BEGIN FROM vn.sale s WHERE s.ticketFk = vParamFk; - - /* UNION ALL - SELECT sw.shipFk, s.id, s.itemFk, TRUE - FROM vn.sale s - JOIN vn.stowaway sw ON sw.id = s.ticketFk - JOIN vn.ticketCollection tc ON tc.ticketFk = sw.shipFk - WHERE tc.collectionFk = vParamFk; - - INSERT INTO tmp.sale(ticketFk, saleFk, itemFk, isStowaway) - SELECT s.ticketFk, s.id, s.itemFk, FALSE - FROM vn.sale s - JOIN vn.ticket t ON t.id = s.ticketFk - WHERE s.ticketFk = vParamFk - AND t.shipped > '2020-01-01' - UNION ALL - SELECT sw.shipFk, s.id, s.itemFk, TRUE - FROM vn.sale s - JOIN vn.stowaway sw ON sw.id = s.ticketFk - WHERE sw.shipFk = vParamFk; - - DELETE FROM tmp.sale - WHERE saleFk = 0; - */ SELECT t.warehouseFk, w.aliasFk INTO vWarehouseFk, vWarehouseAliasFk FROM vn.ticket t @@ -50772,13 +50364,14 @@ BEGIN CONCAT('< ', IFNULL(wk.`code`, '---'),' > '), ''), p.`code`) COLLATE utf8_general_ci as placement , + sh.priority shelvingPriority, -- PAK 05/11/2021 sh.code COLLATE utf8_general_ci as shelving, ish.created, ish.visible, IF(ts.isStowaway, - 100000, IF(ish.visible > 0 OR iss.id, 1, 100000)) * p.pickingOrder as `order`, IFNULL(IF(sc.isPreviousPreparedByPacking, ish.packing, g.`grouping`),1) as `grouping`, IF(iss.id, TO_SECONDS(TIMESTAMPADD(YEAR,-vCurrentYear,iss.created)), TO_SECONDS(TIMESTAMPADD(YEAR,- year(ish.created),ish.created)) + TO_SECONDS(TIMESTAMPADD(YEAR,-vCurrentYear,NOW()))) as priority, - 0 as saleOrder, + CAST(0 AS DECIMAL(10,0)) as saleOrder, sc.isPreviousPrepared, iss.id as itemShelvingSaleFk, ts.ticketFk @@ -50800,7 +50393,8 @@ BEGIN LEFT JOIN vn.itemShelvingSale iss ON iss.saleFk = ts.saleFk AND iss.itemShelvingFk = ish.id LEFT JOIN vn.worker wk ON wk.id = iss.userFk WHERE w.aliasFk = vWarehouseAliasFk - HAVING (iss.id AND st.saleFk) OR salePreviousPrepared IS NULL + AND NOT sc.isHideForPickers + HAVING (iss.id AND st.saleFk) OR salePreviousPrepared IS NULL ; DROP TEMPORARY TABLE IF EXISTS tmp.salePlacementList_2; @@ -50809,7 +50403,10 @@ BEGIN SELECT saleFk, priority as olderPriority FROM (SELECT saleFk, priority FROM tmp.salePlacementList - ORDER BY IF(isPreviousPrepared,2,1), IF(visible > 0 OR itemShelvingSaleFk,1,2), priority + ORDER BY IF(isPreviousPrepared,2,1), + IF(visible > 0 OR itemShelvingSaleFk,1,2), + IFNULL(shelvingPriority,0) DESC, -- PAK 05/11/21 + priority ) sub GROUP BY saleFk; @@ -50824,13 +50421,18 @@ BEGIN JOIN tmp.salePlacementList_3 s3 ON s3.saleFk = s1.saleFk SET s1.saleOrder = s3.saleOrder; /* - -- Anula el orden de antigüedad y ordena por ubicación */ + -- Anula el orden de antigüedad y ordena por ubicación UPDATE tmp.salePlacementList - SET saleOrder = `order`; + SET saleOrder = `order`;*/ SELECT * FROM tmp.salePlacementList - ORDER BY visible <> 0 DESC,saleOrder, IF(isPreviousPrepared,2,1), IF(itemShelvingSaleFk,1,2),priority; + ORDER BY visible <> 0 DESC, + saleOrder, + IF(isPreviousPrepared,2,1), + IF(itemShelvingSaleFk,1,2), + shelvingPriority DESC, -- PAK 05/11/2021 + priority; DROP TEMPORARY TABLE tmp.sale, @@ -51404,7 +51006,7 @@ BEGIN LEFT JOIN vn.ticketObservation tob ON tob.ticketFk = t.id AND tob.observationTypeFk = 1 WHERE t.id = vParamFk - AND t.shipped >= CURDATE() + AND t.shipped >= util.yesterday() UNION ALL SELECT t.id ticketFk, IF(!(vItemPackingTypeFk <=> 'V'), cc.code, CONCAT(SUBSTRING('ABCDEFGH', tc.wagon, 1), '-', tc.`level`)) `level`, @@ -52097,9 +51699,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -52138,6 +51740,543 @@ proc:BEGIN CALL util.debugAdd('vn.collection_newWithWagon',CONCAT('sector: ',vSectorFk,' wagons:',vWagons)); + SELECT w.code INTO vWorkerCode + FROM vn.worker w + WHERE w.id = vn.getUser(); + + -- Establecemos el almacén y si es un sector de preparación previa, así como el estado para los tickets que se vayan preparando + SELECT isPreviousPrepared, warehouseFk, itemPackingTypeFk, code + INTO vIsPreviousPrepared, vWarehouseFk, vItemPackingTypeFk, vSectorCode + FROM vn.sector + WHERE id = vSectorFk; + +-- Si está habilitado el modo cazador para las motos, y el usuario no está registrado, se sale. + + IF (SELECT isTractorHuntingMode FROM vn.deviceProductionConfig dpc) AND vItemPackingTypeFk = 'H' THEN + IF (SELECT COUNT(*) FROM vn.workerWithoutTractor wwt WHERE wwt.workerFk = account.userGetId()) THEN + INSERT INTO tmp.kk(userFk) VALUES(vn.getUser()); + LEAVE proc; + END IF; + END IF; + +-- Si hay colecciones sin terminar, sale del proceso + SELECT count(*) INTO vNotReadyCollections + FROM vn.collection c + WHERE c.workerFk = vn.getUser() + AND c.saleTotalCount > c.salePickedCount + 1 + AND c.created > TIMESTAMPADD(HOUR , -5,NOW()); + + IF vMaxNotReadyCollections < vNotReadyCollections THEN + + LEAVE proc; + + END IF; + +/* + IF LENGTH(vSectorCode) = 2 THEN + + SELECT CAST(SUBSTRING(vSectorCode,2,1) AS UNSIGNED) INTO vWagons; + + END IF; +*/ + SET vMaxTicketPrinted = 8 * vWagons; + SET vMaxTickets = 4 * vWagons; + + + IF vIsPreviousPrepared THEN + + LEAVE proc; -- Hasta que tengamos el altillo, vamos a cancelar esta opcion + + SELECT id INTO vStateFk + FROM vn.state + WHERE `code` = 'PREVIOUS_PREPARATION'; + ELSE + + SELECT id INTO vStateFk + FROM vn.state + WHERE `code` = 'ON_PREPARATION'; + + END IF; + + -- Averiguamos si es comercial el usuario + SELECT FALSE -- (r.name = 'salesPerson') + INTO myUserIsSalesPersonRole + FROM account.user u + JOIN account.role r ON r.id = u.role + WHERE u.id = vn.getUser(); + + -- Se obtiene nº de colección y el buffer con los pedidos preparables + INSERT INTO vn.collection + SET workerFk = account.myUser_getId(), + itemPackingTypeFk = vItemPackingTypeFk; + + SELECT LAST_INSERT_ID() INTO vCollectionFk; + + CALL vn.productionControl(vWarehouseFk, 0); + + -- 05/08/2021 PAK Jose Frau pide que los tickets de recogida en Algemesí sólo se saquen si están asignados. + DELETE pb.* + FROM tmp.productionBuffer pb + JOIN vn.state s ON s.id = pb.state + WHERE pb.agency = 'REC_ALGEMESI' + AND s.code != 'PICKER_DESIGNED'; + + -- Comprobamos si hay tickets asignados. En ese caso, nos centramos exclusivamente en esos tickets + -- y los sacamos independientemente de problemas o tamaños + SELECT COUNT(*) INTO hasAssignedTickets + FROM tmp.productionBuffer pb + JOIN vn.state s ON s.id = pb.state + WHERE s.code = 'PICKER_DESIGNED' + AND pb.workerCode = vWorkerCode + AND LENGTH(pb.problem) = 0; + + IF hasAssignedTickets THEN + + UPDATE vn.collection + SET itemPackingTypeFk = NULL + WHERE id = vCollectionFk; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketToSplit; + CREATE TEMPORARY TABLE tmp.ticketToSplit + SELECT pb.ticketFk + FROM tmp.productionBuffer pb + JOIN vn.state s ON s.id = pb.state + WHERE s.code = 'PICKER_DESIGNED' + AND pb.workerCode = vWorkerCode + AND LENGTH(pb.problem) = 0 + ORDER BY HH, + mm, + s.`order` DESC, + pb.m3 DESC; + + WHILE (SELECT COUNT(*) FROM tmp.ticketToSplit) DO + + SELECT MIN(ticketFk) INTO vTicketToSplit + FROM tmp.ticketToSplit; + + CALL vn.ticket_splitItemPackingType(vTicketToSplit); + + INSERT INTO vn.ticketCollection(ticketFk, collectionFk) + SELECT ticketFk, vCollectionFk + FROM tmp.ticketIPT; + + DELETE FROM tmp.ticketToSplit + WHERE ticketFk = vTicketToSplit; + + DROP TEMPORARY TABLE tmp.ticketIPT; + + END WHILE; + + CALL vn.productionControl(vWarehouseFk, 0); + + ELSE + + SELECT COUNT(*) INTO vPrintedTickets + FROM tmp.productionBuffer pb + JOIN vn.state s ON s.id = pb.state + JOIN vn.agencyMode am ON am.id = pb.agencyModeFk + JOIN vn.agency a ON a.id = am.agencyFk + WHERE pb.shipped = CURDATE() + AND (pb.ubicacion IS NOT NULL OR a.isOwn = FALSE ) + AND s.isPreparable + AND (pb.H > 0 AND vItemPackingTypeFk = 'H' AND ISNULL(pb.collectionH) + OR pb.V > 0 AND vItemPackingTypeFk = 'V' AND ISNULL(pb.collectionV) + OR pb.F > 0 AND vItemPackingTypeFk = 'F' AND ISNULL(pb.collectionF) + OR pb.P > 0 AND vItemPackingTypeFk = 'P' AND ISNULL(pb.collectionP)); + + SET vMaxTicketPrinted = vMaxTicketPrinted - vPrintedTickets; + -- AutoPRINT + + IF vMaxTicketPrinted > 0 THEN + + INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) + SELECT s2.id, pb.ticketFk, vn.getUser() + FROM tmp.productionBuffer pb + JOIN vn.agencyMode am ON am.id = pb.agencyModeFk + JOIN vn.agency a ON a.id = am.agencyFk + JOIN vn.state s ON s.id = pb.state + JOIN vn.state s2 ON s2.code = 'PRINTED_AUTO' + JOIN vn.ticket t ON t.id = pb.ticketFk + WHERE pb.shipped = CURDATE() + AND LENGTH(pb.problem) = 0 + AND (pb.ubicacion IS NOT NULL OR a.isOwn = FALSE ) + AND s.isPrintable + AND (pb.m3 > 0.05 OR s.isOK) + AND (pb.H > 0 AND vItemPackingTypeFk = 'H' AND ISNULL(pb.collectionH) + OR pb.V > 0 AND vItemPackingTypeFk = 'V' AND ISNULL(pb.collectionV) + OR pb.F > 0 AND vItemPackingTypeFk = 'F' AND ISNULL(pb.collectionF) + OR pb.P > 0 AND vItemPackingTypeFk = 'P' AND ISNULL(pb.collectionP)) + AND t.created < TIMESTAMPADD(MINUTE, -10, NOW()) + ORDER BY HH, + mm, + s.`order` DESC, + pb.m3 DESC + LIMIT vMaxTicketPrinted; + + END IF; + + -- Se seleccionan los primeros tickets, asignando colección para dejarlos bloqueados a otros sacadores. + -- Se splitan los tickets preparables, para que solo tengan un tipo de empaquetado + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketToSplit; + CREATE TEMPORARY TABLE tmp.ticketToSplit + SELECT pb.ticketFk + FROM tmp.productionBuffer pb + JOIN vn.agencyMode am ON am.id = pb.agencyModeFk + JOIN vn.agency a ON a.id = am.agencyFk + JOIN vn.ticketStateToday tst ON tst.ticket = pb.ticketFk + JOIN vn.state s ON s.id = tst.state + WHERE ( pb.H > 0 AND vItemPackingTypeFk = 'H' AND ISNULL(pb.collectionH) + OR pb.V > 0 AND vItemPackingTypeFk = 'V' AND ISNULL(pb.collectionV) + OR pb.F > 0 AND vItemPackingTypeFk = 'F' AND ISNULL(pb.collectionF) + OR pb.P > 0 AND vItemPackingTypeFk = 'P' AND ISNULL(pb.collectionP)) + AND (pb.ubicacion IS NOT NULL OR a.isOwn = FALSE ) + AND LENGTH(pb.problem) = 0 + AND s.isPreparable + AND NOT myUserIsSalesPersonRole + ORDER BY pb.HH, pb.mm, s.`order` DESC + LIMIT vMaxTickets; + + WHILE (SELECT COUNT(*) FROM tmp.ticketToSplit) DO + + SELECT MIN(ticketFk) INTO vTicketToSplit + FROM tmp.ticketToSplit; + + CALL vn.ticket_splitItemPackingType(vTicketToSplit); + + INSERT INTO vn.ticketCollection(ticketFk, collectionFk) + SELECT ticketFk, vCollectionFk + FROM tmp.ticketIPT + WHERE itemPackingTypeFk = vItemPackingTypeFk; + + DELETE FROM tmp.ticketToSplit + WHERE ticketFk = vTicketToSplit; + + DROP TEMPORARY TABLE tmp.ticketIPT; + + END WHILE; + + END IF; + + -- Creamos una tabla temporal con los datos que necesitamos para depurar la colección + DROP TEMPORARY TABLE IF EXISTS tmp.ticket; + CREATE TEMPORARY TABLE tmp.ticket + SELECT pb.ticketFk, + pb.`lines`, + pb.m3 * 1000 liters, + 0 as height, + 0 as shelve, + 0 as wagon, + pb.productionOrder, + pb.HH, + pb.mm + FROM tmp.productionBuffer pb + JOIN vn.ticketCollection tc ON tc.ticketFk = pb.ticketFk + WHERE tc.collectionFk = vCollectionFk + LIMIT vMaxTickets; + + -- Es importante que el primer ticket se coja en todos los casos + SET vFirstTicketFk = 0; + + SELECT ticketFk, HH, mm + INTO vFirstTicketFk, vHour, vMinute + FROM tmp.ticket + ORDER BY productionOrder DESC, HH, mm + LIMIT 1; + + -- Hay que excluir aquellos que no tengan la misma hora de preparación + DELETE + FROM tmp.ticket + WHERE HH != vHour + OR mm != vMinute; + + -- En el caso de pedidos de más volumen de un carro, la colección será monoticket. Pero si el primer pedido + -- no es monoticket, excluimos a los de más de un carro + IF (SELECT (t.liters > vc.trolleyM3 * 1000) + FROM tmp.ticket t + JOIN vn.volumeConfig vc + WHERE t.ticketFk = vFirstTicketFk) THEN + + DELETE + FROM tmp.ticket + WHERE ticketFk != vFirstTicketFk; + + ELSE + + DELETE t.* + FROM tmp.ticket t + JOIN vn.volumeConfig vc + WHERE t.liters > vc.trolleyM3 * 1000; + + END IF; + + -- Elimina los tickets bloqueados que no se van a preparar + DELETE tc.* + FROM vn.ticketCollection tc + LEFT JOIN tmp.ticket t ON t.ticketFk = tc.ticketFk + WHERE tc.collectionFk = vCollectionFk + AND t.ticketFk IS NULL; + + /* + * + * Construccion del tren + * + */ + + -- Establece altura máxima por pedido, porque las plantas no se pueden recostar. + UPDATE tmp.ticket t + JOIN + ( SELECT MAX(i.size) maxHeigth, + tc.ticketFk + FROM vn.ticketCollection tc + JOIN vn.sale s ON s.ticketFk = tc.ticketFk + JOIN vn.item i ON i.id = s.itemFk + WHERE i.itemPackingTypeFk = 'V' + AND tc.collectionFk = vCollectionFk + GROUP BY tc.ticketFk) sub ON sub.ticketFk = t.ticketFk + SET t.height = IFNULL(sub.maxHeigth,0); + + -- Vamos a generar una tabla con todas las posibilidades de asignacion de pedido + DROP TEMPORARY TABLE IF EXISTS tmp.wagonsVolumetry; + CREATE TEMPORARY TABLE tmp.wagonsVolumetry + SELECT cv.`level` as shelve, + 1 as wagon, + cv.`lines`, + cv.liters, + cv.height + FROM vn.collectionVolumetry cv; + + SET vWagonCounter = 1; + + WHILE vWagonCounter < vWagons DO + + SET vWagonCounter = vWagonCounter + 1; + + INSERT INTO tmp.wagonsVolumetry(shelve, wagon, `lines`, liters, height) + SELECT cv.`level` as shelve, + vWagonCounter as wagon, + cv.`lines`, + cv.liters, + cv.height + FROM vn.collectionVolumetry cv + WHERE cv.itemPackingTypeFk = IFNULL(vItemPackingTypeFk, 'H'); + + END WHILE; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketShelve; + CREATE TEMPORARY TABLE tmp.ticketShelve + SELECT ticketFk, shelve, wagon, linesDif, LitersDif, heightDif + FROM ( + SELECT t.ticketFk, + wv.shelve, + wv.wagon, + t.productionOrder, + CAST(wv.`lines` AS SIGNED) - t.`lines` as linesDif, + CAST(wv.liters AS SIGNED) - t.liters as litersDif, + CAST(wv.height AS SIGNED) - t.height as heightDif + FROM tmp.wagonsVolumetry wv + JOIN tmp.ticket t + ) sub + WHERE linesDif >= 0 + AND litersDif >= 0 + AND heightDif >= 0 + ORDER BY productionOrder DESC, linesDif, LitersDif, heightDif ; + + -- Insertamos una opcion virtual para carro completo. Todo ticket tiene que poder entrar en un carro completo.... + INSERT INTO tmp.ticketShelve(ticketFk, shelve, wagon, linesDif, LitersDif, heightDif) + SELECT t.ticketFk, 0, wv.wagon, 999, 999,999 + FROM tmp.ticket t + JOIN tmp.wagonsVolumetry wv + GROUP BY t.ticketFk, wv.wagon; + + SET vWagonCounter = 0; + + WHILE vWagonCounter < vWagons DO + + SET vWagonCounter = vWagonCounter + 1; + + -- Asignamos la primera balda util al primer pedido + IF vWagonCounter = 1 THEN + + SELECT shelve INTO vShelve + FROM tmp.ticketShelve + WHERE ticketFk = vFirstTicketFk + AND wagon = vWagonCounter + ORDER BY heightDif, litersDif, linesDif + LIMIT 1; + + ELSE + + SELECT shelve, ticketFk INTO vShelve, vFirstTicketFk + FROM tmp.ticketShelve + WHERE wagon = vWagonCounter + ORDER BY heightDif, litersDif, linesDif + LIMIT 1; + + END IF; + + IF vShelve > 0 THEN + + UPDATE tmp.ticket + SET shelve = vShelve, + wagon = vWagonCounter + WHERE ticketFk = vFirstTicketFk; + + DELETE FROM tmp.ticketShelve + WHERE ticketFk = vFirstTicketFk + OR (shelve = vShelve AND wagon = vWagonCounter); + + WHILE (SELECT COUNT(*) FROM tmp.ticketShelve WHERE wagon = vWagonCounter) DO + + SELECT ticketFk, shelve + INTO vTicket, vShelve + FROM tmp.ticketShelve + WHERE wagon = vWagonCounter + LIMIT 1; + + UPDATE tmp.ticket + SET shelve = vShelve, + wagon = vWagonCounter + WHERE ticketFk = vTicket; + + DELETE FROM tmp.ticketShelve + WHERE ticketFk = vTicket + OR (shelve = vShelve AND wagon = vWagonCounter); + + END WHILE; + + ELSE + + UPDATE tmp.ticket + SET shelve = 1, wagon = vWagonCounter + WHERE ticketFk = vFirstTicketFk; + + DELETE FROM tmp.ticketShelve + WHERE ticketFk = vFirstTicketFk + AND wagon != vWagonCounter; + + END IF; + + END WHILE; + + -- Eliminamos los que se han quedado sin balda + DELETE FROM tmp.ticket WHERE shelve = 0; + + -- Elimina los tickets bloqueados que no se van a preparar + DELETE tc.* + FROM vn.ticketCollection tc + LEFT JOIN tmp.ticket t ON t.ticketFk = tc.ticketFk + WHERE tc.collectionFk = vCollectionFk + AND t.ticketFk IS NULL; + + -- Elimina los tickets que ya estan en otra coleccion + DELETE tc.* + FROM vn.ticketCollection tc + JOIN vn.ticketCollection tc2 ON tc2.ticketFk = tc.ticketFk + WHERE tc.collectionFk = vCollectionFk + AND tc2.collectionFk != vCollectionFk; + + -- Actualiza el estado de la colección + UPDATE vn.collection c + JOIN vn.state st ON st.code = 'ON_PREPARATION' + SET c.stateFk = st.id + WHERE c.id = vCollectionFk; + + -- Asigna las bandejas + UPDATE vn.ticketCollection tc + JOIN tmp.ticket t ON t.ticketFk = tc.ticketFk + SET tc.level = t.shelve, tc.wagon = t.wagon; + + -- Actualiza el estado de los tickets + INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) + SELECT vStateFk, ticketFk, account.myUser_getId() + FROM vn.ticketCollection tc + WHERE tc.collectionFk = vCollectionFk; + + -- Aviso para la preparacion previa + INSERT INTO vn.ticketDown(ticketFk, collectionFk) + SELECT tc.ticketFk, tc.collectionFk + FROM vn.ticketCollection tc + WHERE tc.collectionFk = vCollectionFk; + + IF (SELECT count(*) FROM vn.ticketCollection WHERE collectionFk = vCollectionFk) THEN + + CALL vn.salesMerge_byCollection(vCollectionFk); + + UPDATE vn.collection c + JOIN (SELECT count(*) saleTotalCount , + sum(s.isPicked != 0) salePickedCount + FROM vn.ticketCollection tc + JOIN vn.sale s ON s.ticketFk = tc.ticketFk + WHERE tc.collectionFk = vCollectionFk + AND s.quantity > 0 + ) sub + SET c.saleTotalCount = sub.saleTotalCount, + c.salePickedCount = sub.salePickedCount + WHERE c.id = vCollectionFk; + + SELECT vCollectionFk; + + ELSE + + DELETE FROM vn.collection WHERE id = vCollectionFk; + -- SELECT NULL; + + END IF; + + DROP TEMPORARY TABLE tmp.ticketToSplit; + +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 PROCEDURE IF EXISTS `collection_newWithWagon__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `collection_newWithWagon__`(vSectorFk INT, vWagons INT) +proc:BEGIN + + DECLARE vIsPreviousPrepared BOOLEAN; + DECLARE vCollectionFk INT; + DECLARE vWarehouseFk INT; + DECLARE vMaxTickets INT; + DECLARE vStateFk INT; + DECLARE vFirstTicketFk INT; + DECLARE vHour INT; + DECLARE vMinute INT; + DECLARE vWorkerCode VARCHAR(3); + DECLARE vWagon INT; + DECLARE vWagonCounter INT; + DECLARE vShelve INT; + DECLARE vTicket INT; + DECLARE vTicketToSplit INT; + DECLARE myUserIsSalesPersonRole BOOLEAN; + DECLARE vPrintedTickets INT; + DECLARE vMaxTicketPrinted INT; + DECLARE vItemPackingTypeFk VARCHAR(1); + DECLARE hasAssignedTickets BOOLEAN; + DECLARE vMaxNotReadyCollections INT DEFAULT 0; + DECLARE vNotReadyCollections INT; + DECLARE vSectorCode VARCHAR(20); + + /*IF NOT vn.deviceProductionUser_Exists(vn.getUser()) THEN + + LEAVE proc; + + END IF;*/ + + CALL util.debugAdd('vn.collection_newWithWagon',CONCAT('sector: ',vSectorFk,' wagons:',vWagons)); + + SELECT w.code INTO vWorkerCode FROM vn.worker w WHERE w.id = vn.getUser(); @@ -54127,19 +54266,19 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `deviceProductionUser_exists`(vUserFk INT) BEGIN - SELECT COUNT(*) AS UserExists +/* SELECT COUNT(*) AS UserExists FROM vn.deviceProductionUser dpu - WHERE dpu.userFk = vUserFk; - + WHERE dpu.userFk = vUserFk;*/ + SELECT TRUE; END ;; DELIMITER ; @@ -54151,9 +54290,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -54165,11 +54304,11 @@ BEGIN * @param vAndroid_id el número android_id del dispositivo * */ - - SELECT account.user_getNameFromId(dpu.userFk) + SELECT 103; +/* SELECT account.user_getNameFromId(dpu.userFk) FROM deviceProductionUser dpu JOIN deviceProduction dp ON dpu.deviceProductionFk = dp.id - WHERE dp.android_id = vAndroid_id; + WHERE dp.android_id = vAndroid_id;*/ END ;; DELIMITER ; @@ -54219,6 +54358,62 @@ DELIMITER ;; CREATE DEFINER=`root`@`%` 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 + */ + DECLARE vIsAuthorized BOOL DEFAULT TRUE; + DECLARE vIsDepartment BOOL; + DECLARE vIsAllUsersAllowed BOOL; + DECLARE vMessage VARCHAR(200); + + SELECT dpc.isAllUsersallowed INTO vIsAllUsersAllowed + FROM vn.deviceProductionConfig dpc; + + IF NOT vIsAllUsersAllowed THEN + + SELECT COUNT(*) INTO vIsDepartment + FROM vn.workerDepartment dp + JOIN department d ON d.id = dp.departmentFk + WHERE dp.workerFk = vUserFk AND d.name = "PRODUCCION"; + + IF vIsDepartment THEN + SELECT COUNT(*) INTO vIsAuthorized + 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; + END IF; + + END IF; + + SELECT vIsAuthorized,vMessage; + +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 PROCEDURE IF EXISTS `device_checkLogin__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `device_checkLogin__`(vUserFk INT, vAndroidID VARCHAR(50)) +BEGIN + /* * Comprueba si está registrado el dispositivo mediante su androidId * @@ -55794,6 +55989,81 @@ BEGIN s.price FROM sale s WHERE s.id = vSale; +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 PROCEDURE IF EXISTS `entry_fixMisfit` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `entry_fixMisfit`(vSelf INT) +BEGIN + + /* Arregla el descuadre de una entrada, agregando registros en vn.buy para compensar la diferencia + * entre las etiquetas impresas y las etiquetas esperadas + * + */ + + INSERT INTO vn.buy(entryFk, itemFk) + SELECT vSelf, i.id + FROM vn.item i + WHERE i.description = 'MISFIT' + LIMIT 1; + + INSERT INTO vn.buy(entryFk, + itemFk, + quantity, + buyingValue, + freightValue, + isIgnored, + stickers, + packing, + `grouping`, + groupingMode, + containerFk, + comissionValue, + packageValue, + location, + packageFk, + price1, + price2, + price3, + minPrice, + producer) + SELECT vSelf, + itemFk, + (printedStickers - stickers) * packing AS quantity, + buyingValue, + freightValue, + TRUE isIgnored, + printedStickers - stickers, + packing, + `grouping`, + groupingMode, + containerFk, + comissionValue, + packageValue, + location, + packageFk, + price1, + price2, + price3, + minPrice, + producer + FROM vn.buy b + WHERE b.entryFk = vSelf + AND b.printedStickers != b.stickers; + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -57207,23 +57477,24 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `intrastat_data_neto_Update`(IN vinvoiceInFk INT) +CREATE DEFINER=`root`@`%` PROCEDURE `intrastat_data_neto_Update`(IN vInvoiceInFk INT) BEGIN -UPDATE vn2008.intrastat_data id - JOIN ( - SELECT i.intrastatFk, - LEAST(sum(b.quantity) * IFNULL(it.gramsMax,100000) / 1000 ,sum(r.cm3 * b.quantity) * IF(i.density, i.density, it.density) / 1000000) as neto - FROM vn.entry e - JOIN vn.travel tr ON tr.id = e.travelFk - JOIN vn.buy b ON b.entryFk = e.id - JOIN vn.item i ON i.id = b.itemFk - join vn.itemType it ON it.id = i.typeFk - JOIN bi.rotacion r ON r.Id_Article = i.id AND tr.warehouseInFk = r.warehouse_id - WHERE e.invoiceInFk = vinvoiceInFk - GROUP BY i.intrastatFk) sub ON sub.intrastatFk = id.intrastat_id - SET id.neto = ROUND(sub.neto,1) - WHERE id.recibida_id = vInvoiceInFk; + UPDATE vn2008.intrastat_data id + JOIN ( + SELECT i.intrastatFk, + LEAST(SUM(b.quantity) * IFNULL(it.gramsMax,100000) / 1000, + SUM(ic.cm3 * b.quantity) * IF(i.density, i.density, it.density) / 1000000) as neto + FROM entry e + JOIN travel tr ON tr.id = e.travelFk + JOIN buy b ON b.entryFk = e.id + JOIN item i ON i.id = b.itemFk + join itemType it ON it.id = i.typeFk + JOIN itemCost ic ON ic.itemFk = i.id AND tr.warehouseInFk = ic.warehouseFk + WHERE e.invoiceInFk = vinvoiceInFk + GROUP BY i.intrastatFk) sub ON sub.intrastatFk = id.intrastat_id + SET id.neto = ROUND(sub.neto, 1) + WHERE id.recibida_id = vInvoiceInFk; END ;; @@ -60513,7 +60784,97 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `itemCard`(IN `vBarcode` VARCHAR(22), IN `vWarehouseFk` INT, isBarcode BOOL) +CREATE DEFINER=`root`@`%` PROCEDURE `itemCard`(IN `vBarcode` VARCHAR(22), IN `vWarehouseFk` INT, IN isBarcode BOOL) +BEGIN + + DECLARE vCacheVisibleFk INT; + DECLARE vCacheAvailableFk INT; + DECLARE vVisibleAltillo INT; + DECLARE vItemFk INT; + + IF isBarcode THEN + SELECT vn.barcodeToItem(vBarcode) INTO vItemFk; + ELSE + SELECT i.id INTO vItemFk + FROM vn.item i + WHERE i.name LIKE CONCAT('%',vBarcode,'%') + ORDER BY i.id ASC + LIMIT 1; + END IF; + + IF vItemFk IS NULL THEN + SELECT vn.barcodeToItem(vBarcode) INTO vItemFk; + END IF; + + CALL cache.visible_refresh(vCacheVisibleFk, FALSE,vWarehouseFk); + CALL cache.available_refresh(vCacheAvailableFk, FALSE,vWarehouseFk, CURDATE()); + + SELECT SUM(visible) INTO vVisibleAltillo + FROM vn.itemShelvingStock + WHERE itemFk = vItemFk AND warehouseFk = vWarehouseFk; + + CALL vn.buyUltimate(vWarehouseFk, CURDATE()); + + SELECT i.id, + i.longName, + i.tag5, + i.value5, + i.tag6, + i.value6, + i.tag7, + i.value7, + i.image, + i.size, + i.stems, + i.category, + i.minimum as min, + i.upToDown as repo, + p.name as producer, + o.code as origin, + ip.code as nicho, + ip.reserve as reserva, + v.visible - IFNULL(vVisibleAltillo,0) as enNicho, + a.available, + vVisibleAltillo as enAltillo, + v.visible as total, + c.`grouping` as `grouping`, + c.Packing as packing, + CONCAT('https://verdnatura.es/vn-image-data/catalog/200x200/', i.image) as urlImage200, + CONCAT('https://verdnatura.es/vn-image-data/catalog/1600x900/', i.image) as urlImage, + i.itemPackingTypeFk + FROM vn.item i + LEFT JOIN vn.producer p ON p.id = i.producerFk + LEFT JOIN vn.origin o ON o.id = i.originFk + LEFT JOIN vn.itemPlacement ip ON ip.itemFk = i.id + LEFT JOIN cache.visible v ON v.calc_id = vCacheVisibleFk AND v.item_id = i.id + LEFT JOIN cache.available a ON a.calc_id = vCacheAvailableFk AND a.item_id = i.id + LEFT JOIN ( + SELECT b.itemFk, b2.`grouping`, b2.packing + FROM tmp.buyUltimate b + JOIN vn.buy b2 ON b2.id = b.buyFk + WHERE b.warehouseFk = vWarehouseFk + ) c ON i.id = c.itemFk + WHERE i.id = vItemFk; + + DROP TEMPORARY TABLE tmp.buyUltimate; + +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 PROCEDURE IF EXISTS `itemCard__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemCard__`(IN `vBarcode` VARCHAR(22), IN `vWarehouseFk` INT, isBarcode BOOL) BEGIN DECLARE vCacheVisibleFk INT; @@ -60790,18 +61151,22 @@ BEGIN CALL cache.stock_refresh(FALSE); - SELECT fue.itemFk, + SELECT i.id itemFk, i.longName, i.size, i.subName, - v.amount as visible, - fue.reserva, + 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) as saldo + 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 ( - SELECT ish.itemFk, CAST(SUM(ish.visible) AS DECIMAL(10,0)) AS reserva + 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 JOIN vn.shelving sh ON sh.code = ish.shelvingFk JOIN vn.parking p ON p.id = sh.parkingFk @@ -60809,6 +61174,15 @@ BEGIN WHERE s.code = 'FUENTES_PICASSE' 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 + FROM vn.itemShelving ish + JOIN vn.shelving sh ON sh.code = ish.shelvingFk + 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 + ) alb ON alb.itemFk = i.id LEFT JOIN cache.stock v ON i.id = v.item_id AND v.warehouse_id = vWarehouseFk LEFT JOIN ( SELECT item_id, CAST(sum(amount)AS DECIMAL(10,0)) as venta @@ -60816,7 +61190,7 @@ BEGIN WHERE dat BETWEEN CURDATE() AND TIMESTAMPADD(DAY,vDaysInFuture , util.dayend(curdate())) AND warehouse_id = vWarehouseFk GROUP BY item_id - ) sale ON sale.item_id = fue.itemFk + ) sale ON sale.item_id = i.id LEFT JOIN ( SELECT item_id, CAST(sum(amount)AS DECIMAL(10,0)) as compra FROM vn2008.item_entry_in @@ -60824,15 +61198,17 @@ BEGIN AND warehouse_id = vWarehouseFk AND isVirtualStock = FALSE GROUP BY item_id - ) buy ON buy.item_id = fue.itemFk + ) buy ON buy.item_id = i.id LEFT JOIN ( SELECT item_id, CAST(sum(amount)AS DECIMAL(10,0)) as traslado FROM vn2008.item_entry_out WHERE dat BETWEEN CURDATE() AND TIMESTAMPADD(DAY,vDaysInFuture , util.dayend(curdate())) AND warehouse_id = vWarehouseFk GROUP BY item_id - ) mov ON mov.item_id = fue.itemFk - + ) mov ON mov.item_id = i.id + WHERE (v.amount OR fue.Fuentes OR alb.Albenfruit) + AND i.itemPackingTypeFk = 'H' + AND ic.shortLife ; END ;; @@ -62903,6 +63279,94 @@ DELIMITER ; /*!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 PROCEDURE IF EXISTS `itemShelving_add` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemShelving_add`(IN vShelvingFk VARCHAR(8), IN vBarcode VARCHAR(22), IN vShelve VARCHAR(2), IN vDeep INT, IN vQuantity INT, IN vPackagingFk VARCHAR(10), IN vGrouping INT, IN vPacking INT, IN vWarehouseFk INT, IN vLevel INT) +BEGIN + +/** + * Añade registro o lo actualiza si ya existe. + * + * @param vShelvingFk matrícula del carro + * @param vBarcode el id del registro + * @param vShelve de itemshleving + * @param vDeep indica profundidad + * @param vQuantity indica la cantidad del producto + * @param vPackagingFk el packaging del producto en itemShelving + * @param vGrouping el grouping del producto en itemShelving + * @param vPacking el packing del producto + * @param vWarehouseFk indica el sector + * @param vLevel indica el level + * + **/ + + 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 quantity = quantity+vQuantity,visible = visible+vQuantity,available = available+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, + shelve, + deep, + quantity, + visible, + available, + grouping, + packing, + packagingFk, + level) + + SELECT + vItemFk, + vShelvingFk, + vShelve, + vDeep, + vQuantity, + vQuantity, + vQuantity, + IF(vGrouping = 0, IFNULL(b.packing, vPacking), vGrouping) as `grouping`, + IF(vPacking = 0, b.packing, vPacking) as packing, + IF(vPackagingFk = '', b.packageFk, vPackagingFk) as packaging, + vLevel + 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 ; +/*!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 PROCEDURE IF EXISTS `itemShelving_BuyerGet` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -63061,6 +63525,151 @@ DELIMITER ; /*!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 PROCEDURE IF EXISTS `itemShelving_get` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemShelving_get`(IN vShelvingFk VARCHAR(8)) +BEGIN +/** + * Lista artículos de itemshelving + * + * @param vShelvingFk matrícula del carro + * + **/ + + SELECT ish.itemFk as item, + IFNULL(i.longName, CONCAT(i.name, ' ', i.size)) as description, + ish.visible as visible, + ceil(ish.visible/ish.packing) as stickers, + ish.packing as packing, + ish.grouping, + IF (p.column IS NULL, "", p.column) as col, + IF (p.row IS NULL, "", p.row) as row, + IF (p.code IS NULL, "", p.code) as code, + ish.id, + s.priority + FROM itemShelving ish + JOIN item i ON i.id = ish.itemFk + INNER JOIN shelving s ON vShelvingFk = s.code COLLATE utf8_unicode_ci + LEFT JOIN parking p ON s.parkingFk = p.id + WHERE ish.shelvingFk COLLATE utf8_unicode_ci = vShelvingFk; + +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 PROCEDURE IF EXISTS `itemShelving_getSaleDate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` 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 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 + WHERE shelvingFk = vShelvingFk COLLATE utf8_unicode_ci + GROUP BY itemFk; + + DROP TEMPORARY TABLE IF EXISTS tmp.item; + CREATE TEMPORARY TABLE tmp.item + (PRIMARY KEY (itemFk)) + ENGINE = MEMORY + SELECT * FROM tmp.itemShelvingDistinct; + + DROP TEMPORARY TABLE IF EXISTS tmp.stockByDay; + CREATE TEMPORARY TABLE tmp.stockByDay + (index (itemFk, dated)) + ENGINE = MEMORY + SELECT t3.amount, dated, + @stock := IF(@itemFk = t3.itemFk, @stock + t3.amount, t3.amount) stock, + @itemFk := t3.itemFk itemFk + FROM ( + SELECT * FROM ( + SELECT t2.* FROM ( + SELECT item_id itemFk, amount, CURDATE() dated + FROM cache.stock + WHERE warehouse_id = vWarehouseFk + UNION ALL + SELECT ish.itemFk, - sum(visible), CURDATE() + 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 + GROUP BY ish.itemFk + UNION ALL + SELECT item_id, sum(iei.amount), dat + FROM vn2008.item_entry_in iei + WHERE dat >= CURDATE() + AND warehouse_id = vWarehouseFk + AND isVirtualStock = FALSE + GROUP BY item_id, dat + UNION ALL + SELECT item_id, sum(ieo.amount), dat + FROM vn2008.item_entry_out ieo + WHERE dat >= CURDATE() + AND warehouse_id = vWarehouseFk + GROUP BY item_id, dat + UNION ALL + SELECT i.itemFk, sum(io.amount), dat + FROM vn2008.item_out io + JOIN tmp.item i ON i.itemFk = io.item_id + WHERE io.dat >= CURDATE() + AND io.warehouse_id = vWarehouseFk + GROUP BY io.item_id, io.dat + ) t2 + JOIN tmp.itemShelvingDistinct ish ON ish.itemFk = t2.itemFk) t + order by t.itemFk, DATE(t.dated), t.amount DESC) t3; + + SELECT sbd.itemFk, i.longName, DATE(dated) dated, ish.visible amount, sbd.stock + FROM tmp.stockByDay sbd + JOIN vn.item i ON i.id = sbd.itemFk + JOIN tmp.itemShelvingDistinct ish ON ish.itemFk = sbd.itemFk + WHERE ish.visible >= sbd.stock + GROUP BY itemFk + ORDER BY dated; + + DROP TEMPORARY TABLE tmp.stockByDay, + tmp.itemShelvingDistinct, + tmp.item; +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 PROCEDURE IF EXISTS `itemShelving_inventory` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -63134,6 +63743,39 @@ BEGIN SET stars = vStars WHERE id = vId; +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 PROCEDURE IF EXISTS `itemShelving_update` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `itemShelving_update`(vVisible INT, vPacking INT, vShelf INT ,vGrouping INT ) +BEGIN +/** + * Actualiza itemShelving. + * + * @param vVisible la cantidad visible del registro a actualizar + * @param vShelf el id del registro a actualizar + * @param vPacking el packing del del producto en itemShelving + * @param vGrouping el grouping del producto en itemShelving + */ + UPDATE itemShelving SET + available = vVisible, + visible = vVisible, + packing = vPacking, + grouping = vGrouping + WHERE id = vShelf; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -64118,24 +64760,24 @@ BEGIN DECLARE vCalcFk INT; DECLARE vTypeFk INT; - DECLARE vTag1 VARCHAR(25); - DECLARE vTag5 VARCHAR(25); - DECLARE vTag6 VARCHAR(25); - DECLARE vTag7 VARCHAR(25); - DECLARE vTag8 VARCHAR(25); + DECLARE vTag1 VARCHAR(25) 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); - DECLARE vValue5 VARCHAR(50); - DECLARE vValue6 VARCHAR(50); - DECLARE vValue7 VARCHAR(50); - DECLARE vValue8 VARCHAR(50); + 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 + LEFT JOIN vn.tag t1 ON t1.id = it1.tagFk WHERE i.id = vItemFk; CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, vDate); @@ -64145,16 +64787,16 @@ BEGIN i.subName, i.tag5, i.value5, - (i.value5 <=> vValue5 COLLATE utf8_general_ci) match5, + (i.value5 <=> vValue5) match5, i.tag6, i.value6, - (i.value6 <=> vValue6 COLLATE utf8_general_ci) match6, + (i.value6 <=> vValue6) match6, i.tag7, i.value7, - (i.value7 <=> vValue7 COLLATE utf8_general_ci) match7, + (i.value7 <=> vValue7) match7, i.tag8, i.value8, - (i.value8 <=> vValue8 COLLATE utf8_general_ci) match8, + (i.value8 <=> vValue8) match8, a.available, IFNULL(ip.counter,0) counter, IF(b.groupingMode = 1, b.grouping, b.packing) as minQuantity @@ -64167,19 +64809,20 @@ BEGIN LEFT JOIN vn.buy b ON b.id = lb.buy_id WHERE a.calc_id = vCalcFk AND available > 0 - AND IF(vIsShowedByType,i.typeFk = vTypeFk,true) + AND IF(vIsShowedByType, i.typeFk = vTypeFk, TRUE) AND i.id != vItemFk ORDER BY counter DESC, - (t1.name = vTag1 COLLATE utf8_general_ci) DESC, - (it1.value = vValue1 COLLATE utf8_general_ci) DESC, - (i.tag6 = vTag6 COLLATE utf8_general_ci) DESC, - (i.value6 = vValue6 COLLATE utf8_general_ci) DESC, - (i.tag5 = vTag5 COLLATE utf8_general_ci) DESC, - (i.value5 = vValue5 COLLATE utf8_general_ci) DESC, - (i.tag7 = vTag7 COLLATE utf8_general_ci) DESC, - (i.value7 = vValue7 COLLATE utf8_general_ci) DESC, - (i.tag8 = vTag8 COLLATE utf8_general_ci) DESC, - (i.value8 = vValue8 COLLATE utf8_general_ci) DESC; + (t1.name = vTag1) DESC, + (it1.value = vValue1) DESC, + (i.tag6 = vTag6) DESC, + (i.value6 = vValue6) DESC, + (i.tag5 = vTag5) DESC, + (i.value5 = vValue5) DESC, + (i.tag7 = vTag7) DESC, + (i.value7 = vValue7) DESC, + (i.tag8 = vTag8) DESC, + (i.value8 = vValue8) DESC + LIMIT 30; END ;; @@ -65218,70 +65861,6 @@ DELIMITER ; /*!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 PROCEDURE IF EXISTS `kk` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `kk`(vCIF VARCHAR(9)) -BEGIN - - DECLARE vLetraInicial VARCHAR(1); - DECLARE vLetraFinal VARCHAR(1); - DECLARE vParteNumerica VARCHAR(7); - DECLARE vSuma INT DEFAULT 0; - DECLARE vNumero INT DEFAULT 0; - DECLARE i INT DEFAULT 0; - DECLARE vResult BOOL DEFAULT FALSE; - - SET vLetraInicial = SUBSTR(vCIF, 1, 1); - SET vLetraFinal = SUBSTR(vCIF, 9, 1); - SET vParteNumerica = SUBSTR(vCIF, 2, 7); - - 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 numérico - IF CAST(vLetraFinal AS DECIMAL(1,0)) = vSuma THEN - - SET vResult = TRUE; - - END IF; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `ledger_doCompensation` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -65725,31 +66304,39 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `mail_insert`( - vReceiver VARCHAR(50), - vReplyTo VARCHAR(50), - vSubject VARCHAR(50), - vBody VARCHAR(255)) + vReceiver VARCHAR(255), + vReplyTo VARCHAR(50), + vSubject VARCHAR(100), + vBody TEXT) BEGIN - - DECLARE vIsRepeated BOOLEAN; - - SELECT COUNT(*) INTO vIsRepeated +/** + * Inserta en la tabla vn.mail + * + * @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 FROM vn.mail WHERE creationDate >= CURDATE() AND `receiver` = vReceiver AND `replyTo` = vReplyTo AND `subject` = vSubject; - + IF NOT vIsRepeated THEN - - INSERT INTO vn.mail SET + + INSERT INTO vn.mail SET `receiver` = vReceiver, `replyTo` = vReplyTo, `subject` = vSubject, `body` = vBody; - + END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -66061,6 +66648,90 @@ BEGIN DROP TEMPORARY TABLE vn2008.Tickets_to_fusion; END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `mysqlConnectionsSorter_kill` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `mysqlConnectionsSorter_kill`() +BEGIN + +/** + * 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 + FROM information_schema.processlist p + WHERE USER = 'sorter' + AND TIME >= 30; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + OPEN vCursor; + + l: LOOP + + FETCH vCursor INTO vProcesId; + + IF vDone THEN + LEAVE l; + END IF; + + KILL vProcesId; + + END LOOP; + + CLOSE vCursor; + +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 PROCEDURE IF EXISTS `mysqlPreparedCount_check` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `mysqlPreparedCount_check`() +BEGIN + DECLARE vPreparedCount INTEGER; + + SELECT VARIABLE_VALUE INTO vPreparedCount + FROM INFORMATION_SCHEMA.GLOBAL_STATUS + WHERE VARIABLE_NAME LIKE '%prepared_stmt_count%'; + + IF(vPreparedCount >= 40000) THEN + 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: ', + vPreparedCount, + ', está próximo a exceder su límite. \r\n Hay que reiniciar el servicio LF.VMP.Service del servidor a3.') + ); + END IF; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -66307,9 +66978,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -66337,6 +67008,7 @@ BEGIN PREPARE stmt FROM @qryLog; EXECUTE stmt; + DEALLOCATE PREPARE stmt; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -66965,7 +67637,7 @@ DELIMITER ; /*!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 PROCEDURE IF EXISTS `payRoll` */; +/*!50003 DROP PROCEDURE IF EXISTS `payRoll__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -66975,7 +67647,7 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `payRoll`(IN vFromDated DATE, IN vToDated DATE, IN vFromPaid DATE, IN vToPaid DATE, IN vPartTime BOOL) +CREATE DEFINER=`root`@`%` PROCEDURE `payRoll__`(IN vFromDated DATE, IN vToDated DATE, IN vFromPaid DATE, IN vToPaid DATE, IN vPartTime BOOL) BEGIN SET @userFk := 0; @@ -67040,81 +67712,6 @@ DELIMITER ; /*!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 PROCEDURE IF EXISTS `payRoll__` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `payRoll__`(IN vFromDated DATE, IN vToDated DATE, IN vFromPaid DATE, IN vToPaid DATE, IN vPartTime BOOL) -BEGIN - - SET @userFk := 0; - - SELECT CONCAT(w.lastName,', ',w.firstname) AS Trabajador, - CAST(Sum((wj.total + wj.permission + wj.lunch)* wj.priceOrdinaryHour + wj.hollyday * wj.priceHollydayHour - + wj.nocturn * wj.priceNocturnHour - + wj.extra * wj.priceExtraHour) AS DECIMAL(10,2)) AS salario, - CAST(Sum(wj.permission) AS DECIMAL(10,2)) AS permission, - CAST(Sum(wj.total) AS DECIMAL(10,2)) AS total, - CAST(Sum(wj.nocturn) AS DECIMAL(10,2)) AS nocturn, - CAST(Sum(wj.hollyday) AS DECIMAL(10,2)) AS hollyday, - CAST(Sum(wj.lunch) AS DECIMAL(10,2)) AS lunch, - CAST(Sum(wj.extra) AS DECIMAL(10,2)) AS extra, - CAST(Sum(wj.contractJourney) AS DECIMAL(10,2)) AS contractJourney, - d.name AS departamento, - CAST(Sum((wj.contractJourney + wj.permission) * wj.priceOrdinaryHour) AS DECIMAL(10,2)) AS teorico, - CAST(Sum((wj.lunch + wj.permission + wj.total) * wj.priceordinaryhour) AS DECIMAL(10,2)) AS practico, - CAST(Sum(wj.nocturn * wj.pricenocturnhour) AS DECIMAL(10,2)) AS nocturno, - CAST(Sum(wj.hollyday * wj.priceHollydayHour) AS DECIMAL(10,2)) AS festivos, - CAST(Sum(wj.extra * wj.priceextrahour) AS DECIMAL(10,2)) AS extras, - MAX(wj.businessFk) as businessFk, - Min(b.date_start) AS fromDated, - Max(b.date_end) AS toDated, - blp.importepactado, - bl.porhoras, - IF(wj.userFk != @userFk, CAST(IFNULL(a.Anticipos,0) AS DECIMAL(10,2)), 0) AS Anticipos, - IF(wj.userFk != @userFk, CAST(IFNULL(se.SaldoEuros,0) AS DECIMAL(10,2)), 0) AS SaldoEuros, - @userFk := wj.userFk as userFk - - FROM vn.worker w - JOIN vn.workerJourney wj ON w.userFk = wj.userFk - JOIN postgresql.business_labour bl ON bl.business_id = wj.businessFk - JOIN postgresql.calendar_labour_type cl ON cl.calendar_labour_type_id = bl.calendar_labour_type_id - JOIN vn.department d ON bl.department_id = d.id - JOIN postgresql.business_labour_payroll blp ON bl.business_id = blp.business_id - JOIN postgresql.business b ON b.business_id = wj.businessFk - LEFT JOIN - (SELECT userFk, sum(debe) as Anticipos - FROM postgresql.income_employee ie - JOIN postgresql.person pe ON ie.person_id = pe.person_id - JOIN vn.worker w ON w.id = pe.id_trabajador - WHERE odbc_date BETWEEN vFromPaid AND vToPaid - AND id_incomeType = 14 -- Salario - GROUP BY userFk - ) a ON a.userFk = wj.userFk - LEFT JOIN - (SELECT userFk, sum(debe) - sum(haber) as SaldoEuros - FROM postgresql.income_employee ie - JOIN postgresql.person pe ON ie.person_id = pe.person_id - JOIN vn.worker w ON w.id = pe.id_trabajador - GROUP BY userFk - ) se ON se.userFk = wj.userFk - WHERE wj.dated BETWEEN vFromDated AND vToDated - AND IF(vPartTime,cl.hours_week <= 40,cl.hours_week = 40) - GROUP BY wj.userFk - ORDER BY w.lastName, w.firstname; - -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 PROCEDURE IF EXISTS `placement_test` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -70844,14 +71441,23 @@ BEGIN RPAD(IFNULL(i.size,''),5,' ') ) ) as line1, + '' cel1, + IF(s.quantity MOD b.packing, + CONCAT(CAST(s.quantity/b.`grouping` AS decimal(10,0)),' x ',b.`grouping`), + CONCAT(CAST(s.quantity / b.packing AS DECIMAL(10,0)),' pack de ',b.packing)) cel2, + TRIM(CONCAT(ic.color, IF(MAX(IF(st.semaphore <=> 1, TRUE, FALSE)) AND t.id != t.showTicketFk, CONCAT(' [ TICKET ',t.id,' ] '),''), IFNULL(LPAD(st.parkingCode,40,' '),''))) as line3, + '' cel3, TRIM(CONCAT(LPAD(IFNULL(ip.productor,''),30,' '), ' ',LPAD(IFNULL(o.code,''),4,' '))) as line2, TRIM(CONCAT(ic.color, IF(MAX(IF(st.semaphore <=> 1, TRUE, FALSE)) AND t.id != t.showTicketFk, CONCAT(' [ TICKET ',t.id,' ] '),''), IFNULL(LPAD(st.parkingCode,40,' '),''))) as line3, s.isAdded, str.originalQuantity as startQuantity, -- eliminar cuando tengamos la nueva apk - IFNULL(c.workerFk,getUser()), + IFNULL(c.workerFk,getUser()) as workerFk, IFNULL(SUM(iss.quantity),0) as pickedQuantity FROM vn.sale s JOIN tmp.ticket t ON t.id = s.ticketFk + JOIN vn.ticket tt ON tt.id = t.id + JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND lb.warehouse_id = tt.warehouseFk + JOIN vn.buy b ON b.id = lb.buy_id JOIN vn.item i ON i.id = s.itemFk LEFT JOIN vn.ticketCollection tc ON tc.ticketFk = t.id LEFT JOIN vn.collection c ON c.id = tc.collectionFk @@ -71368,7 +71974,7 @@ DELIMITER ; /*!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 PROCEDURE IF EXISTS `shelvingFuture` */; +/*!50003 DROP PROCEDURE IF EXISTS `shelvingFuture__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -71378,7 +71984,7 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `shelvingFuture`(vSectorFk INT) +CREATE DEFINER=`root`@`%` PROCEDURE `shelvingFuture__`(vSectorFk INT) BEGIN DECLARE vDone BOOL DEFAULT FALSE; @@ -71714,6 +72320,104 @@ BEGIN sh.parked < TIMESTAMPADD(MONTH,-1,CURDATE()) ); +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 PROCEDURE IF EXISTS `shelving_getSpam` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `shelving_getSpam`(vDated DATE, vWarehouseFk INT) +BEGIN + + /* Devuelve las matrículas con productos que no son necesarios para la venta hasta la fecha señalada + * + * @param vDated Fecha hasta la que se puede pasar sin esos productos. + * @param vWarehouse Identificador único de vn.warehouse + */ + + DROP TEMPORARY TABLE IF EXISTS tmp.stock; + + CALL cache.stock_refresh(FALSE); + + CREATE TEMPORARY TABLE tmp.stock + SELECT i.id itemFk, + v.amount - IFNULL(fue.reserva,0) as visible, + fue.reserva, + 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.reserva,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 + LEFT JOIN ( + SELECT ish.itemFk, CAST(SUM(ish.visible) AS DECIMAL(10,0)) AS reserva + FROM vn.itemShelving ish + JOIN vn.shelving sh ON sh.code = ish.shelvingFk + JOIN vn.parking p ON p.id = sh.parkingFk + JOIN vn.sector s ON s.id = p.sectorFk + WHERE s.code = 'FUENTES_PICASSE' + OR sh.isSpam + GROUP BY ish.itemFk + ) fue ON fue.itemFk = i.id + LEFT JOIN cache.stock v ON i.id = v.item_id AND v.warehouse_id = vWarehouseFk + LEFT JOIN ( + SELECT item_id, CAST(sum(amount)AS DECIMAL(10,0)) as venta + FROM vn2008.item_out + WHERE dat BETWEEN CURDATE() AND util.dayend(vDated) + AND warehouse_id = vWarehouseFk + GROUP BY item_id + ) sale ON sale.item_id = i.id + LEFT JOIN ( + SELECT item_id, CAST(sum(amount)AS DECIMAL(10,0)) as compra + FROM vn2008.item_entry_in + WHERE dat BETWEEN CURDATE() AND util.dayend(vDated) + AND warehouse_id = vWarehouseFk + AND isVirtualStock = FALSE + GROUP BY item_id + ) buy ON buy.item_id = i.id + LEFT JOIN ( + SELECT item_id, CAST(sum(amount)AS DECIMAL(10,0)) as traslado + FROM vn2008.item_entry_out + WHERE dat BETWEEN CURDATE() AND util.dayend(vDated) + AND warehouse_id = vWarehouseFk + GROUP BY item_id + ) mov ON mov.item_id = i.id + WHERE v.amount; + + SELECT ish.shelvingFk matricula, + i.longName articulo, + ish.visible, + count(*) lineas, + sum(ish.visible <= s.saldo) spam, + p.code parking, + s.description sector , + w.name AS almacen, + sh.isSpam + FROM vn.itemShelving ish + JOIN vn.item i ON i.id = ish.itemFk + JOIN vn.shelving sh ON sh.code = ish.shelvingFk + JOIN vn.parking p ON p.id = sh.parkingFk + JOIN vn.sector s ON s.id = p.sectorFk + JOIN vn.warehouse w ON w.id = s.warehouseFk + LEFT JOIN tmp.stock s ON s.itemFk = ish.itemFk + WHERE (w.name = 'Algemesi' + OR (w.name = 'NuncaJamas' AND ish.created < curdate())) + AND ish.visible + GROUP BY ish.shelvingFk + HAVING lineas = spam OR isSpam; + + DROP TEMPORARY TABLE tmp.stock; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -72596,7 +73300,7 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`z-sysadmin`@`%` PROCEDURE `test`() +CREATE DEFINER=`root`@`%` PROCEDURE `test`() BEGIN select 'procedimiento ejecutado con éxito'; END ;; @@ -73541,13 +74245,36 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `ticketCollection_get`(vTicketFk INT) +BEGIN + + SELECT tc.collectionFk + FROM vn.ticketCollection tc + WHERE ticketFk = vTicketFk; + +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 PROCEDURE IF EXISTS `ticketCollection_get__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticketCollection_get__`(vTicketFk INT) BEGIN SELECT tc.collectionFk @@ -76004,9 +76731,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -76023,26 +76750,93 @@ BEGIN */ SELECT sv.ticketFk , - sum(litros) liters, - count(*) `lines`, + CAST(sum(litros) AS DECIMAL(10,0)) liters, + CAST(count(*) AS DECIMAL(10,0)) `lines`, sub2.id ticketFuture, sub2.shipped FROM vn.saleVolume sv JOIN vn.ticket t ON t.id = sv.ticketFk + JOIN vn.address a ON a.id = t.addressFk + JOIN vn.province p ON p.id = a.provinceFk + JOIN vn.country c ON c.id = p.countryFk + JOIN vn.ticketState ts ON ts.ticketFk = t.id + JOIN vn.alertLevel al ON al.id = ts.alertLevel + LEFT JOIN vn.ticketParking tp ON tp.ticketFk = t.id LEFT JOIN ( SELECT * FROM ( SELECT t.addressFk , t.id, t.shipped FROM vn.ticket t - WHERE t.shipped BETWEEN vDated + WHERE t.shipped BETWEEN TIMESTAMPADD(DAY, vScopeDays,vDated) AND util.dayend(TIMESTAMPADD(DAY, vScopeDays,vDated)) AND t.warehouseFk = vWarehouseFk - ORDER BY t.shipped) sub + ) sub GROUP BY sub.addressFk ) sub2 ON sub2.addressFk = t.addressFk AND t.id != sub2.id WHERE t.shipped BETWEEN vDated AND util.dayend(vDated) AND t.warehouseFk = vWarehouseFk + AND al.code = 'FREE' + AND tp.ticketFk IS NULL GROUP BY sv.ticketFk - HAVING liters < vLitersMax AND `lines` < vLinesMax AND ticketFuture; + HAVING liters <= vLitersMax AND `lines` <= vLinesMax AND ticketFuture; +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 PROCEDURE IF EXISTS `ticket_canMerge__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ticket_canMerge__`(vDated DATE, vScopeDays INT, vLitersMax INT, vLinesMax INT, vWarehouseFk INT) +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 + * @param vLinesMax Número máximo de lineas de los tickets a catapultar + * @param vWarehouseFk Identificador de vn.warehouse + */ + + SELECT sv.ticketFk , + CAST(sum(litros) AS DECIMAL(10,0)) liters, + CAST(count(*) AS DECIMAL(10,0)) `lines`, + sub2.id ticketFuture, + sub2.shipped + FROM vn.saleVolume sv + JOIN vn.ticket t ON t.id = sv.ticketFk + JOIN vn.address a ON a.id = t.addressFk + JOIN vn.province p ON p.id = a.provinceFk + JOIN vn.country c ON c.id = p.countryFk + JOIN vn.ticketState ts ON ts.ticketFk = t.id + JOIN vn.alertLevel al ON al.id = ts.alertLevel + LEFT JOIN vn.ticketParking tp ON tp.ticketFk = t.id + LEFT JOIN tmp.routeDayMove ra ON ra.routeFk = t.routeFk + LEFT JOIN ( + SELECT * FROM ( + SELECT t.addressFk , t.id, t.shipped + FROM vn.ticket t + WHERE t.shipped BETWEEN TIMESTAMPADD(DAY, vScopeDays,vDated) + AND util.dayend(TIMESTAMPADD(DAY, vScopeDays,vDated)) + AND t.warehouseFk = vWarehouseFk + ) sub + GROUP BY sub.addressFk + ) sub2 ON sub2.addressFk = t.addressFk AND t.id != sub2.id + WHERE t.shipped BETWEEN vDated AND util.dayend(vDated) + AND t.warehouseFk = vWarehouseFk + AND al.code = 'FREE' + AND tp.ticketFk IS NULL + AND ra.routeFk IS NULL + GROUP BY sv.ticketFk + HAVING liters <= vLitersMax AND `lines` <= vLinesMax AND ticketFuture; END ;; DELIMITER ; @@ -78055,7 +78849,7 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`z-sysadmin`@`%` PROCEDURE `ticket_recalc`(vTicketId INT) +CREATE DEFINER=`root`@`%` PROCEDURE `ticket_recalc`(vTicketId INT) BEGIN /** * Calcula y guarda el total con/sin IVA en un ticket. @@ -78088,9 +78882,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -78110,7 +78904,7 @@ proc: BEGIN DECLARE vAddressFk INT; DECLARE vLanded DATE; DECLARE vZoneFk INTEGER; - + IF vIsTicketEditable IS NULL THEN SELECT IFNULL(ts.alertLevel,0) = 0 AND IFNULL(t.refFk,'') = '' INTO vIsTicketEditable @@ -78279,74 +79073,101 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticket_recalcComponents__`(IN vTicketFk BIGINT ) +CREATE DEFINER=`root`@`%` PROCEDURE `ticket_recalcComponents__`(IN vTicketFk BIGINT, vIsTicketEditable BOOLEAN) proc: BEGIN /** - * Este procedimiento trata de "rebionizar" un ticket, + * Este procedimiento recalcula los componentes de un ticket, * eliminando los componentes existentes e insertandolos de nuevo * * @param vTicketFk Id del ticket - * @return tmp.buyUltimate + * @param vIsTicketEditable si no se quiere forzar llamar con NULL */ DECLARE vShipped DATE; DECLARE vWarehouseFk SMALLINT; DECLARE vAgencyModeFk INT; DECLARE vAddressFk INT; DECLARE vLanded DATE; - DECLARE vIsTicketEditable BOOLEAN; DECLARE vZoneFk INTEGER; - - SELECT (IFNULL(ts.alertLevel,0) >0 or IFNULL(t.refFk,"") != "") = FALSE, t.zoneFk - INTO vIsTicketEditable, vZoneFk + + -- Santos 2021, borrar a partir del dia 31 PAK + IF (SELECT COUNT(*) + FROM tmp.routeDayMove ra + JOIN vn.ticket t ON t.routeFk = ra.routeFk + WHERE t.id = vTicketFk) THEN + + LEAVE proc; + + END IF; + + IF vIsTicketEditable IS NULL THEN + SELECT IFNULL(ts.alertLevel,0) = 0 AND IFNULL(t.refFk,'') = '' + INTO vIsTicketEditable + FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket + WHERE id = vTicketFk; + END IF; + + SELECT t.warehouseFk, + t.shipped, + t.addressFk, + t.agencyModeFk, + t.landed, + t.zoneFk + INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded, vZoneFk FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket - WHERE id = vTicketFk; - - SELECT warehouseFk, date(shipped), addressFk, agencyModeFk, landed - INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded - FROM ticket - WHERE id = vTicketFk; + WHERE t.id = vTicketFk; + + IF vLanded IS NULL OR vZoneFk IS NULL THEN + + CALL zone_getLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk, TRUE); + + IF (SELECT COUNT(*) FROM tmp.zoneGetLanded LIMIT 1) = 0 THEN + CALL util.throw('There is no zone for these parameters'); + END IF; + + UPDATE ticket t + 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; + DROP TEMPORARY TABLE tmp.zoneGetLanded; - CALL vn.zone_getShipped (vlanded, vAddressFk, vAgencyModeFk, TRUE); - - CALL vn.buyUltimate (vWarehouseFk, vShipped); -- rellena la tabla buyUltimate con la ultima compra + END IF; + + -- rellena la tabla buyUltimate con la ultima compra + CALL buyUltimate (vWarehouseFk, vShipped); DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; CREATE TEMPORARY TABLE tmp.ticketLot SELECT vWarehouseFk warehouseFk, NULL available, - s.itemFk, bu.buyFk + s.itemFk, bu.buyFk, vZoneFk zoneFk FROM sale s LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk WHERE s.ticketFk = vTicketFk GROUP BY s.itemFk; - - CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped); - + + CALL catalog_componentPrepare(); + CALL catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk); + DROP TEMPORARY TABLE IF EXISTS tmp.sale; CREATE TEMPORARY TABLE tmp.sale (PRIMARY KEY (saleFk)) ENGINE = MEMORY - SELECT id saleFk, vWarehouseFk warehouseFk - FROM sale s - WHERE s.ticketFk = vTicketFk; - - CALL vn.ticketComponentUpdateSale(IF(vIsTicketEditable,1,6)); -- si el ticket esta facturado, respeta los precios + SELECT id saleFk, vWarehouseFk warehouseFk + FROM sale s + WHERE s.ticketFk = vTicketFk; + + -- si el ticket esta facturado, respeta los precios + CALL ticketComponentUpdateSale(IF(vIsTicketEditable, 1, 6)); - IF vLanded IS NULL THEN - - CALL zone_getLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk); - - UPDATE vn2008.Tickets t - SET t.landing = (SELECT landed FROM tmp.zoneGetLanded) - WHERE Id_Ticket = vTicketFk; - - DROP TEMPORARY TABLE tmp.zoneGetLanded; - - END IF; - - DROP TEMPORARY TABLE tmp.buyUltimate; - DROP TEMPORARY TABLE tmp.ticketComponentPrice; - DROP TEMPORARY TABLE tmp.ticketComponent; - DROP TEMPORARY TABLE tmp.sale; + CALL catalog_componentPurge(); + DROP TEMPORARY TABLE + tmp.buyUltimate, + tmp.sale; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -80587,17 +81408,44 @@ DELIMITER ; /*!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 PROCEDURE IF EXISTS `workerJourneyReplace` */; +/*!50003 DROP PROCEDURE IF EXISTS `workerJourneyReplaceLauncher__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `workerJourneyReplace`(vFromDate DATE, vToDate DATE, vUserFk INT) +CREATE DEFINER=`root`@`%` PROCEDURE `workerJourneyReplaceLauncher__`() +BEGIN + + DECLARE vDateStart DATE; + DECLARE vDateEnd DATE; + + SET vDateStart = TIMESTAMPADD(MONTH,-1,CURDATE()); + SET vDateEnd = util.yesterday(); + + CALL vn.workerJourneyReplace(vDateStart,vDateEnd,0); + +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 PROCEDURE IF EXISTS `workerJourneyReplace__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `workerJourneyReplace__`(vFromDate DATE, vToDate DATE, vUserFk INT) BEGIN /* Actualiza la tabla workerJourney para que actue como caché permanente revisable de las jornadas laborales. @@ -80876,185 +81724,212 @@ DELIMITER ; /*!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 PROCEDURE IF EXISTS `workerJourneyReplaceLauncher` */; +/*!50003 DROP PROCEDURE IF EXISTS `workerJourney_replace` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `workerJourneyReplaceLauncher`() +CREATE DEFINER=`root`@`%` PROCEDURE `workerJourney_replace`(vDatedFrom DATE, vDatedTo DATE, vWorkerFk INT) BEGIN +/** + * 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 vMinHoursToBreak DECIMAL(10,2); + DECLARE vBreakHours DECIMAL(10,2); + DECLARE vMonthByYear INT; + DECLARE vWeeksByYear INT DEFAULT 52; + DECLARE vMonthsByYear INT DEFAULT 12; + DECLARE vDaysByWeek INT DEFAULT 5; - DECLARE vDateStart DATE; - DECLARE vDateEnd DATE; - - SET vDateStart = TIMESTAMPADD(MONTH,-1,CURDATE()); - SET vDateEnd = util.yesterday(); - - CALL vn.workerJourneyReplace(vDateStart,vDateEnd,0); - -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 PROCEDURE IF EXISTS `workerJourney_Replace` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `workerJourney_Replace`(vFromDate DATE, vToDate DATE, vUserFk INT) -BEGIN - /* Actualiza la tabla workerJourney para que actue como caché permanente revisable de las jornadas laborales. - * vUserFk es opcional. El valor 0 indica que se tenga en cuenta a todos los usuarios.8 - */ + SET vDatedTimeTo = util.dayEnd(vDatedTo); + SELECT minHoursToBreak, breakHours + INTO vMinHoursToBreak, vBreakHours + FROM workerTimeControlConfig; + DELETE FROM workerJourney - WHERE dated BETWEEN vFromDate AND vToDate - AND IFNULL(vUserFk, userFk) = userFk; - - IF vUserFk IS NULL THEN - CALL vn.timeControl_calculateAll( vFromDate , CONCAT(REPLACE(vToDate, '00:00:00', ''), ' 23:59:59')); - CALL vn.timeBusiness_calculateAll( vFromDate , CONCAT(REPLACE(vToDate, '00:00:00', ''), ' 23:59:59')); + WHERE dated BETWEEN vDatedFrom AND vDatedTo + AND NOT isPaid + AND NOT isUpdated + AND (vWorkerFk IS NULL OR userFK = vWorkerFk); + + -- 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 w.workerFk, t.dated, w.businessFk + FROM workerLabour w + JOIN time t ON t.dated BETWEEN w.started AND IFNULL(w.ended,CURDATE()) + WHERE t.dated BETWEEN vDatedFrom AND vDatedTo + AND (vWorkerFk IS NULL OR w.workerFk = vWorkerFk) + ORDER BY w.workerFk, t.dated, w.businessFk; + + IF vWorkerFk THEN + CALL timeControl_calculateByUser(vWorkerFk, vDatedFrom , vDatedTimeTo); ELSE - CALL vn.timeControl_calculateByUser( vUserFk, vFromDate , CONCAT(REPLACE(vToDate, '00:00:00', ''), ' 23:59:59')); - CALL vn.timeBusiness_calculateByUser( vUserFk, vFromDate , CONCAT(REPLACE(vToDate, '00:00:00', ''), ' 23:59:59')); + CALL timeControl_calculateAll(vDatedFrom, vDatedTimeTo); END IF; - -- Se inicia la tabla con todas las fechas posibles para cada uno de los trabajadores que han fichado en el rango de fechas. - INSERT IGNORE INTO workerJourney(userFk, dated, businessFk) - SELECT tbc.userFk, tbc.dated, tbc.businessFk - FROM tmp.timeBusinessCalculate tbc; - - -- Se actualiza la cantidad total de horas prácticas, así como el tiempo de almuerzo remunerado, si corresponde UPDATE workerJourney wj JOIN tmp.timeControlCalculate t ON wj.dated = t.dated AND wj.userFk = t.userFk - SET wj.total = CAST(IF(t.timeWorkDecimal >= 5.33,t.timeWorkDecimal-0.33,t.timeWorkDecimal) AS DECIMAL (10,2)), - wj.lunch = IF(t.timeWorkDecimal >= 5.33,0.33,0) - WHERE wj.dated BETWEEN vFromDate AND vToDate - AND wj.isPaid = FALSE - AND wj.isUpdated = FALSE - AND IFNULL(vUserFk, wj.userFk) = wj.userFk; - - DROP TEMPORARY TABLE tmp.timeControlCalculate; - - /********** NOCTURNIDAD ************/ - DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControl; - + 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 + DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControl; CREATE TEMPORARY TABLE tmp.workerTimeControl - SELECT w.*, 0 as Non - FROM vn.workerTimeControl w - WHERE timed BETWEEN vFromDate AND vToDate - AND IFNULL(vUserFk, userFk) = userFk - ORDER BY userFk, timed; - - -- Regalamos un segundo para evitar que hayan fichadas en las horas claves de inicio y fin de la nocturnidad. - UPDATE tmp.workerTimeControl - SET timed = TIMESTAMPADD(SECOND,-1,timed) - WHERE TIME(timed) IN ('06:00:00','22:00:00'); - - -- Fichada virtual a las 6:00 h, hora en que empieza la jornada diurna - INSERT INTO tmp.workerTimeControl(userFk, timed) - SELECT userFk, TIMESTAMPADD(HOUR, 6, DATE(timed)) - FROM vn.workerTimeControl - WHERE IFNULL(vUserFk, userFk) = userFk - GROUP BY userFk, DATE(timed); - - -- Fichada virtual a las 22:00 h, momento en que empieza la jornada nocturna. - INSERT INTO tmp.workerTimeControl(userFk, timed) - SELECT userFk, TIMESTAMPADD(HOUR, 22, DATE(timed)) - FROM vn.workerTimeControl - WHERE IFNULL(vUserFk, userFk) = userFk - GROUP BY userFk, DATE(timed); - + SELECT sub.userFk, sub.timed, sub.order, 0 Non, FALSE manual + FROM (SELECT w.userFk, + IF(TIME(w.timed) IN ('06:00:00','22:00:00'), TIMESTAMPADD(SECOND, -1, w.timed), w.timed) timed, -- Regalamos un segundo para evitar que hayan fichadas en las horas claves de inicio y fin de la nocturnidad. + w.`order` + FROM workerTimeControl w + WHERE w.timed BETWEEN vDatedFrom AND vDatedTo + AND w.userFk = IFNULL(vWorkerFk, w.userFk) + UNION ALL + SELECT w.userFk, + TIMESTAMPADD(HOUR, 6, DATE(w.timed)), + w.`order` + FROM workerTimeControl w + WHERE w.timed BETWEEN vDatedFrom AND vDatedTo + AND w.userFk = IFNULL(vWorkerFk, w.userFk) + GROUP BY w.userFk, DATE(w.timed) + UNION ALL + SELECT w.userFk, + TIMESTAMPADD(HOUR, 22, DATE(w.timed)), + w.order + FROM workerTimeControl w + WHERE w.timed BETWEEN vDatedFrom AND vDatedTo + AND w.userFk = IFNULL(vWorkerFk, w.userFk) + GROUP BY w.userFk, DATE(w.timed) + ) sub + ORDER BY sub.userFk, sub.timed; + -- Establece el orden en que se han de leer las fichadas - CALL vn.workerTimeControlSetOrder; + CALL workerTimeControlSetOrder(); -- Marca los impares para facilitar la consulta siguiente UPDATE tmp.workerTimeControl SET Non = 1 WHERE `order` mod 2; - + -- Actualizamos la nocturnidad UPDATE workerJourney wj - JOIN - (SELECT userFk, Dia, sum(Nocturnidad) as Nocturnidad FROM - (SELECT userFk, - date(timed) as Dia, - ((IF( TIME(timed) < '06:00:00' OR (TIME(timed) = '06:00:00' AND Non = FALSE ) , IF(Non,-1,1),0) - +IF(TIME(timed) > '22:00:00' OR (TIME(timed) = '22:00:00' AND Non = TRUE), If(Non,-1,1),0) - )* (HOUR(`timed`) + MINUTE(`timed`) / 60) - ) as Nocturnidad - FROM tmp.workerTimeControl - ) sub - GROUP BY Dia, userFk - HAVING Nocturnidad - ) night ON night.userFk = wj.userFk AND night.Dia = wj.dated + JOIN(SELECT userFk, Dia, sum(Nocturnidad) Nocturnidad FROM + (SELECT userFk, + date(timed) Dia, + ((IF( TIME(timed) < '06:00:00' OR (TIME(timed) = '06:00:00' AND Non = FALSE ) , IF(Non,-1,1),0) + + + IF(TIME(timed) > '22:00:00' OR (TIME(timed) = '22:00:00' AND Non = TRUE), If(Non,-1,1),0)) + * (HOUR(`timed`) + MINUTE(`timed`) / 60) + ) Nocturnidad + FROM tmp.workerTimeControl + ) sub + GROUP BY Dia, userFk + HAVING Nocturnidad + ) night ON night.userFk = wj.userFk AND night.Dia = wj.dated SET wj.nocturn = night.Nocturnidad - WHERE wj.isPaid = FALSE AND isUpdated = FALSE; + WHERE NOT wj.isPaid + AND NOT isUpdated; + + + -- Horas téoricas y precio de la hora ordinaria + UPDATE workerJourney wj + JOIN postgresql.business_labour_payroll blp ON blp.business_id = wj.businessFk + JOIN postgresql.business_labour bl ON bl.business_id = wj.businessFk + JOIN postgresql.calendar_labour_type cl ON cl.calendar_labour_type_id = bl.calendar_labour_type_id + SET wj.priceOrdinaryHour = (vMonthsByYear * blp.importepactado) / (vWeeksByYear * cl.hours_week), + wj.contractJourney = cl.hours_week / vDaysByWeek + WHERE wj.dated BETWEEN vDatedFrom AND vDatedTo + AND (vWorkerFk IS NULL OR wj.userFk = vWorkerFk) + AND NOT wj.isPaid + AND NOT isUpdated; + -- Precio Extras, Vacaciones y Nocturnas + UPDATE workerJourney wj + JOIN(SELECT MAX(w.dated), t.dated, w.holidayInc, w.nightInc, w.extraInc + FROM time t + JOIN workerHourPrice w ON w.dated <= t.dated + WHERE t.dated BETWEEN vDatedFrom AND vDatedTo + GROUP BY t.dated + ) sub ON sub.dated = wj.dated + SET wj.priceHolidayHour = wj.priceOrdinaryHour * sub.holidayInc, + wj.priceNocturnHour = wj.priceOrdinaryHour * sub.nightInc, + wj.priceExtraHour = wj.priceOrdinaryHour * sub.extraInc + WHERE wj.dated BETWEEN vDatedFrom AND vDatedTo + AND (vWorkerFk IS NULL OR wj.userFk = vWorkerFk) + AND NOT wj.isPaid + AND NOT wj.isUpdated; - -- Precios de hora ordinaria, Extras, Vacaciones y Nocturnas - -- Falta importe pactado en el procedimiento ¿? - UPDATE vn.workerJourney wj - JOIN postgresql.business_labour_payroll blp ON blp.business_id = wj.businessFk - JOIN postgresql.business_labour bl ON bl.business_id = wj.businessFk - JOIN postgresql.calendar_labour_type pclt ON pclt.calendar_labour_type_id = bl.calendar_labour_type_id - JOIN (SELECT dated, hollidayInc, nightInc, extraInc - FROM ( SELECT tm.dated , hollidayInc, nightInc, extraInc - FROM vn.time tm - JOIN vn.workerHourPrice whp ON tm.dated >= whp.dated - ORDER BY tm.dated, whp.dated DESC - ) sub - GROUP BY dated - ) conv ON conv.dated = wj.dated - SET - wj.priceOrdinaryHour = @priceOrdinaryHour := FORMAT((12 * blp.importepactado) / (52 * pclt.hours_week),2), - wj.priceHollydayHour = @priceOrdinaryHour * conv.hollidayInc, - wj.priceNocturnHour = @priceOrdinaryHour * conv.nightInc, - wj.priceExtraHour = @priceOrdinaryHour * conv.extraInc - WHERE wj.dated BETWEEN vFromDate AND vToDate - AND IFNULL(vUserFk, userFk) = userFk - AND wj.isPaid = FALSE - AND isUpdated = FALSE; + -- Elimina el precio de las horas extras para los contratos parciales. + UPDATE workerJourney wj + JOIN postgresql.business_labour bl ON bl.business_id = wj.businessFk + JOIN postgresql.calendar_labour_type cl ON cl.calendar_labour_type_id = bl.calendar_labour_type_id + SET wj.priceExtraHour = 0 + WHERE cl.isPartial + AND wj.dated BETWEEN vDatedFrom AND vDatedTo + AND (vWorkerFk IS NULL OR wj.userFk = vWorkerFk) + AND NOT wj.isPaid + AND NOT wj.isUpdated; - -- Horas téoricas bajas, vacaciones y festivos personales - UPDATE vn.workerJourney wj - JOIN tmp.timeBusinessCalculate b ON b.dated = wj.dated AND b.userFk = wj.userFk - SET wj.permission = b.timeBusinessDecimal * b.permissionRate, - wj.contractJourney = b.timeWorkDecimal - WHERE wj.dated BETWEEN vFromDate AND vToDate - AND IFNULL(vUserFk, wj.userFk) = wj.userFk - AND wj.isPaid = FALSE - AND wj.isUpdated = FALSE; + -- Bajas, vacaciones y festivos personales + UPDATE workerJourney wj + JOIN businessCalendar bc ON bc.businessFk = wj.businessFk AND bc.dated = wj.dated + JOIN absenceType ab ON ab.id = bc.absenceTypeFk + JOIN postgresql.business_labour bl ON bl.business_id = wj.businessFk + SET wj.permission = ab.permissionRate * wj.contractJourney, + wj.contractJourney = IF(ab.permissionRate = 1, 0, ab.permissionRate) * wj.contractJourney, + wj.holiday = wj.total - IF(ab.permissionRate = 1, 0, ab.permissionRate) * wj.contractJourney + WHERE ab.permissionRate > 0 + AND wj.dated BETWEEN vDatedFrom AND vDatedTo + AND (vWorkerFk IS NULL OR wj.userFk = vWorkerFk) + AND NOT wj.isPaid + AND NOT wj.isUpdated; + + -- Festivos por centro de trabajo + UPDATE workerJourney wj + JOIN calendarHolidays ch ON ch.dated = wj.dated + JOIN postgresql.business_labour bl ON bl.business_id = wj.businessFk + AND bl.workcenter_id = ch.workcenterFk + SET wj.holiday = wj.total, + wj.permission = wj.contractJourney, + wj.contractJourney = 0 + WHERE wj.dated BETWEEN vDatedFrom AND vDatedTo + AND (vWorkerFk IS NULL OR wj.userFk = vWorkerFk) + AND NOT wj.isPaid + AND NOT wj.isUpdated; + + -- Sábados / Domingos + UPDATE workerJourney + SET holiday = total, + contractJourney = 0 + WHERE DAYNAME(dated) IN ('sábado', 'domingo') + AND dated BETWEEN vDatedFrom AND vDatedTo + AND (vWorkerFk IS NULL OR userFk = vWorkerFk) + AND NOT isPaid + AND NOT isUpdated; - UPDATE vn.workerJourney wj - JOIN tmp.timeBusinessCalculate b ON b.dated = wj.dated AND b.userFk = wj.userFk - SET wj.hollyday = wj.total - b.timeWorkDecimal - WHERE wj.dated BETWEEN vFromDate AND vToDate - AND IFNULL(vUserFk, wj.userFk) = wj.userFk - AND wj.isPaid = FALSE - AND wj.isUpdated = FALSE - AND b.permissionRate > 0 ; - -- Horas extras - UPDATE workerJourney - SET extra = lunch + total - contractJourney - WHERE dated BETWEEN vFromDate AND vToDate - AND IFNULL(vUserFk, userFk) = userFk - AND isPaid = FALSE - AND isUpdated = FALSE; - + UPDATE workerJourney + SET extra = lunch + total - contractJourney + WHERE dated BETWEEN vDatedFrom AND vDatedTo + AND (vWorkerFk IS NULL OR userFk = vWorkerFk) + AND NOT isPaid + AND NOT isUpdated; + + DROP TEMPORARY TABLE tmp.timeControlCalculate; + DROP TEMPORARY TABLE tmp.workerTimeControl; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -81182,17 +82057,27 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `workerTimeControlNonDays`() BEGIN - - SELECT wtc.userFk, date(wtc.timed) as Fecha , COUNT(wtc.`order`) as maxOrder, c.name as worker, wb.code as Boss, CONCAT (au.name, "@verdnatura.es") AS bossMail - FROM workerTimeControl wtc - JOIN worker w ON w.userFk = wtc.userFk - LEFT JOIN worker wb ON wb.id = w.bossFk - JOIN client c ON c.id = wtc.userFk - LEFT JOIN account.user au ON au.id = wb.userFK - WHERE timed BETWEEN TIMESTAMPADD(YEAR,-5,CURDATE()) AND CURDATE() - GROUP BY userFk, date(timed) - HAVING maxOrder mod 2 = 1 - ORDER BY Boss; + SET @cont := 0; + SELECT sub2.userFk, sub2.dated as Fecha ,CONCAT (w.firstName," ", w.lastName) AS worker,au.name as Boss,d.name + FROM (SELECT userFk, + dated, + COUNT(*) cont2 + FROM (SELECT DATE(wtc.timed) dated, + userFk, + IFNULL(@cont, @cont := 0 ), + IF(direction = 'in', @cont:=@cont+1, true), + @cont cont + FROM vn.workerTimeControl wtc + WHERE wtc.timed BETWEEN TIMESTAMPADD(YEAR,-1,CURDATE()) AND CURDATE() + ORDER BY userFk, timed)sub + GROUP BY cont + HAVING cont2 mod 2 = 1)sub2 + JOIN worker w ON w.userFk = sub2.userFk + LEFT JOIN worker wb ON wb.id = w.bossFk + LEFT JOIN account.user au ON au.id = wb.userFK + LEFT JOIN vn.workerDepartment wd on wd.workerFk = w.id + LEFT JOIN vn.department d ON d.id = wd.departmentFk + ORDER BY Boss asc; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -82899,24 +83784,26 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `workerTimeControl_sendMailByDepartment`(vWeek INT, vYear INT, vWorkerFk INT) +CREATE DEFINER=`root`@`%` PROCEDURE `workerTimeControl_sendMailByDepartment`(IN vWeek int, IN vYear int, IN vWorkerFk int) BEGIN + /** * Inserta el registro de horario semanalmente de PRODUCCION, CAMARA, TALLER NATURAL y TALLER ARTIFICIAL en vn.mail. - * - * @param vWeek + * + * @param vWeek * @param vYear * @param vWorkerFk -> En el caso de querer generarlo para todos los empleados deberá de informarse como NULL */ - + + /* DECLARE vDateStart DATETIME; DECLARE vDateEnd DATETIME; - + SELECT CONCAT (MIN(dated), ' 00:00:00'), CONCAT (MAX(dated), ' 23:59:59') INTO vDateStart, vDateEnd - FROM time - WHERE year = vYear AND + FROM time + WHERE year = vYear AND week = vWeek; SET session group_concat_max_len = 15000; @@ -82927,7 +83814,7 @@ BEGIN IF vWorkerFk IS NULL THEN CALL timeControl_calculateAll(vDateStart,vDateEnd); - CALL timeBusiness_calculateAll(vDateStart,vDateEnd); + CALL timeBusiness_calculateAll(vDateStart,vDateEnd); ELSE CALL timeControl_calculateByUser(vWorkerFk,vDateStart,vDateEnd); CALL timeBusiness_calculateByUser(vWorkerFk,vDateStart,vDateEnd); @@ -82935,7 +83822,7 @@ BEGIN CREATE TEMPORARY TABLE tmp.reportHours SELECT t.dated, - IF (tm.hoursWeek IS NULL,'', GROUP_CONCAT(DATE_FORMAT(wtc.timed,'%H:%i') ORDER BY wtc.timed ASC SEPARATOR ' ') ) timeWorkDay, + IF (tm.hoursWeek IS NULL,'', GROUP_CONCAT(DATE_FORMAT(wtc.timed,'%H:%i') ORDER BY wtc.timed ASC SEPARATOR ' ') ) timeWorkDay, IFNULL(tm.timeWorkDecimal,0) tm, IFNULL(CAST(tc.timeWorkDecimal AS DECIMAL (10,2)) , 0) tc, IFNULL(CAST(IFNULL(tc.timeWorkDecimal, 0) - IFNULL(tm.timeWorkDecimal, 0) AS DECIMAL (10,2)), 0) balance, @@ -82953,11 +83840,11 @@ BEGIN d.name, tm.businessFk FROM time t - LEFT JOIN tmp.timeBusinessCalculate tm ON tm.dated = t.dated + LEFT JOIN tmp.timeBusinessCalculate tm ON tm.dated = t.dated LEFT JOIN tmp.timeControlCalculate tc ON tc.dated = tm.dated AND tc.userFk = tm.userFk LEFT JOIN vn.workerTimeControl wtc ON wtc.userFk = tm.userFk AND DATE(wtc.timed) = t.dated LEFT JOIN workerLabour wl ON wl.workerFk = tm.userFk AND wl.businessFk = tm.businessFk - LEFT JOIN workCenter wc ON wc.id = wl.workCenterFk + LEFT JOIN workCenter wc ON wc.id = wl.workCenterFk LEFT JOIN department d ON d.id = wl.departmentFk LEFT JOIN worker w ON w.id = tm.userFk LEFT JOIN client c ON c.id = w.id @@ -82972,12 +83859,12 @@ BEGIN CONCAT(' - +
@@ -83013,12 +83900,12 @@ BEGIN