diff --git a/back/models/accounting-type.json b/back/models/accounting-type.json index c2bf977b2..be08ac533 100644 --- a/back/models/accounting-type.json +++ b/back/models/accounting-type.json @@ -25,6 +25,9 @@ }, "isAutoConciliated": { "type": "boolean" + }, + "maxAmount": { + "type": "number" } }, "acls": [{ diff --git a/db/changes/10370-pickles/00-accountingType.sql b/db/changes/10370-pickles/00-accountingType.sql new file mode 100644 index 000000000..1313e8223 --- /dev/null +++ b/db/changes/10370-pickles/00-accountingType.sql @@ -0,0 +1,3 @@ +ALTER TABLE vn.accountingType ADD maxAmount INT DEFAULT NULL NULL; + +UPDATE vn.accountingType SET maxAmount = 1000 WHERE code = 'cash'; 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/fixtures.sql b/db/dump/fixtures.sql index fe2da1f38..49ff08db9 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -7,7 +7,7 @@ ALTER TABLE `vn`.`zoneGeo` AUTO_INCREMENT = 1; ALTER TABLE `vn`.`ticket` AUTO_INCREMENT = 1; INSERT INTO `salix`.`AccessToken` (`id`, `ttl`, `created`, `userId`) - VALUES + VALUES ('TOTALLY_SECURE_TOKEN', '1209600', CURDATE(), 66); @@ -154,16 +154,16 @@ INSERT INTO `vn`.`shelving` (`code`, `parkingFk`, `isPrinted`, `priority`, `park ('GVC', '1', '0', '1', '0', '1106'), ('HEJ', '2', '0', '1', '0', '1106'); -INSERT INTO `vn`.`accountingType`(`id`, `description`, `receiptDescription`,`code`) +INSERT INTO `vn`.`accountingType`(`id`, `description`, `receiptDescription`,`code`, `maxAmount`) VALUES - (1, 'CC y Polizas de crédito', NULL, NULL), - (2, 'Cash', 'Cash', 'cash'), - (3, 'Credit card', 'Credit Card', 'creditCard'), - (4, 'Finalcial lines', NULL, NULL), - (5, 'Other products', NULL, NULL), - (6, 'Loans', NULL, NULL), - (7, 'Leasing', NULL, NULL), - (8, 'Compensations', 'Compensations', 'compensation'); + (1, 'CC y Polizas de crédito', NULL, NULL, NULL), + (2, 'Cash', 'Cash', 'cash', 1000), + (3, 'Credit card', 'Credit Card', 'creditCard', NULL), + (4, 'Finalcial lines', NULL, NULL, NULL), + (5, 'Other products', NULL, NULL, NULL), + (6, 'Loans', NULL, NULL, NULL), + (7, 'Leasing', NULL, NULL, NULL), + (8, 'Compensations', 'Compensations', 'compensation', NULL); INSERT INTO `vn`.`bank`(`id`, `bank`, `account`, `cash`, `entityFk`, `isActive`, `currencyFk`) VALUES @@ -1285,11 +1285,11 @@ INSERT INTO `vn`.`supplierAddress`(`id`, `supplierFk`, `nickname`, `street`, `pr (5, 442, 'GCR building', 'Bristol district', 1, '46000', 'Gotham', '111111111', '222222222'), (6, 442, 'The Gotham Tonight building', 'Bristol district', 1, '46000', 'Gotham', '111111111', '222222222'); -INSERT INTO `vn`.`supplier`(`id`, `name`, `nickname`,`account`,`countryFk`,`nif`,`isFarmer`,`commission`, `created`, `isActive`, `street`, `city`, `provinceFk`, `postCode`, `payMethodFk`, `payDemFk`, `payDay`, `taxTypeSageFk`, `withholdingSageFk`, `transactionTypeSageFk`, `workerFk`, `supplierActivityFk`) +INSERT INTO `vn`.`supplier`(`id`, `name`, `nickname`,`account`,`countryFk`,`nif`,`isFarmer`,`commission`, `created`, `isActive`, `street`, `city`, `provinceFk`, `postCode`, `payMethodFk`, `payDemFk`, `payDay`, `taxTypeSageFk`, `withholdingSageFk`, `transactionTypeSageFk`, `workerFk`, `supplierActivityFk`, `isPayMethodChecked`) VALUES - (1, 'Plants SL', 'Plants nick', 4100000001, 1, '06089160W', 0, 0, CURDATE(), 1, 'supplier address 1', 'PONTEVEDRA', 1, 15214, 1, 1, 15, 4, 1, 1, 18, 'flowerPlants'), - (2, 'Farmer King', 'The farmer', 4000020002, 1, '87945234L', 1, 0, CURDATE(), 1, 'supplier address 2', 'SILLA', 2, 43022, 1, 2, 10, 93, 2, 8, 18, 'animals'), - (442, 'Verdnatura Levante SL', 'Verdnatura', 5115000442, 1, '06815934E', 0, 0, CURDATE(), 1, 'supplier address 3', 'SILLA', 1, 43022, 1, 2, 15, 6, 9, 3, 18, 'flowerPlants'); + (1, 'Plants SL', 'Plants nick', 4100000001, 1, '06089160W', 0, 0, CURDATE(), 1, 'supplier address 1', 'PONTEVEDRA', 1, 15214, 1, 1, 15, 4, 1, 1, 18, 'flowerPlants', 1), + (2, 'Farmer King', 'The farmer', 4000020002, 1, '87945234L', 1, 0, CURDATE(), 1, 'supplier address 2', 'SILLA', 2, 43022, 1, 2, 10, 93, 2, 8, 18, 'animals', 1), + (442, 'Verdnatura Levante SL', 'Verdnatura', 5115000442, 1, '06815934E', 0, 0, CURDATE(), 1, 'supplier address 3', 'SILLA', 1, 43022, 1, 2, 15, 6, 9, 3, 18, 'flowerPlants', 1); INSERT INTO `vn`.`supplierContact`(`id`, `supplierFk`, `phone`, `mobile`, `email`, `observation`, `name`) VALUES diff --git a/db/dump/structure.sql b/db/dump/structure.sql index 5a2f9055f..68f320ec6 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 ; @@ -36833,6 +36437,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`), @@ -37035,6 +36641,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`), @@ -37106,14 +36713,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`) @@ -38161,7 +37768,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'; @@ -38170,6 +37777,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 @@ -40218,6 +39828,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` -- @@ -40295,7 +39919,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`) @@ -40344,13 +39968,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', @@ -40666,6 +40290,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 */; @@ -40860,14 +40487,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 @@ -41545,6 +41172,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 */ ;; @@ -41715,7 +41360,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 */ ;; @@ -41767,34 +41412,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 */ ;; @@ -42158,17 +41775,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; @@ -42873,7 +42490,7 @@ BEGIN * * */ - DECLARE vIsGranted BOOLEAN; + /*DECLARE vIsGranted BOOLEAN; DECLARE vDeviceProductionFk INT(11) DEFAULT NULL; SELECT dp.id INTO vDeviceProductionFk @@ -42888,7 +42505,7 @@ BEGIN AND dpu.deviceProductionFk = vDeviceProductionFk; RETURN vIsGranted; - END IF; + END IF;*/ RETURN TRUE; END ;; DELIMITER ; @@ -42906,7 +42523,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; @@ -46213,7 +45830,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; @@ -47160,7 +46777,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 @@ -47330,10 +46947,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; @@ -47341,11 +46954,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 @@ -47354,14 +46970,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 @@ -47389,10 +46997,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 ;; @@ -47526,17 +47131,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, @@ -47653,26 +47258,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 */ ; @@ -47709,17 +47319,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; @@ -48428,7 +48038,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); @@ -50661,14 +50271,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; @@ -50678,9 +50293,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; @@ -50697,29 +50312,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 @@ -50773,13 +50365,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 @@ -50801,7 +50394,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; @@ -50810,7 +50404,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; @@ -50825,13 +50422,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, @@ -51405,7 +51007,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`, @@ -52098,9 +51700,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 ;; @@ -52139,6 +51741,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(); @@ -54128,19 +54267,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 ; @@ -54152,9 +54291,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 ;; @@ -54166,11 +54305,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 ; @@ -54220,6 +54359,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 * @@ -55795,6 +55990,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 */ ; @@ -57208,23 +57478,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 ;; @@ -60514,7 +60785,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; @@ -60791,18 +61152,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 @@ -60810,6 +61175,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 @@ -60817,7 +61191,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 @@ -60825,15 +61199,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 ;; @@ -62904,6 +63280,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 */ ; @@ -63062,6 +63526,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 */ ; @@ -63135,6 +63744,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 */ ; @@ -64119,24 +64761,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); @@ -64146,16 +64788,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 @@ -64168,19 +64810,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 ;; @@ -65219,70 +65862,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 */ ; @@ -65726,31 +66305,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 */ ; @@ -66062,6 +66649,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 */ ; @@ -66308,9 +66979,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 ;; @@ -66338,6 +67009,7 @@ BEGIN PREPARE stmt FROM @qryLog; EXECUTE stmt; + DEALLOCATE PREPARE stmt; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -66966,7 +67638,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 */ ; @@ -66976,7 +67648,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; @@ -67041,81 +67713,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 */ ; @@ -70845,14 +71442,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 @@ -71369,7 +71975,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 */ ; @@ -71379,7 +71985,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; @@ -71715,6 +72321,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 */ ; @@ -72597,7 +73301,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 ;; @@ -73542,13 +74246,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 @@ -76005,9 +76732,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 ;; @@ -76024,26 +76751,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 ; @@ -78056,7 +78850,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. @@ -78089,9 +78883,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 ;; @@ -78111,7 +78905,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 @@ -78280,74 +79074,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 */ ; @@ -80588,17 +81409,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. @@ -80877,185 +81725,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 */ ; @@ -81183,17 +82058,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 */ ; @@ -82900,24 +83785,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; @@ -82928,7 +83815,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); @@ -82936,7 +83823,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, @@ -82954,11 +83841,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 @@ -82973,12 +83860,12 @@ BEGIN CONCAT(' - + @@ -83014,12 +83901,12 @@ BEGIN Horas a trabajar: Horas trabajadas: Balance: - ', - GROUP_CONCAT(DISTINCT ' ', DATE_FORMAT( rh.dated, '%d-%m-%y'), - ' ', CONCAT(UCASE(LEFT(DAYNAME(rh.dated), 1)), SUBSTRING(DAYNAME(rh.dated), 2)), + ', + GROUP_CONCAT(DISTINCT ' ', DATE_FORMAT( rh.dated, '%d-%m-%y'), + ' ', CONCAT(UCASE(LEFT(DAYNAME(rh.dated), 1)), SUBSTRING(DAYNAME(rh.dated), 2)), ' ', IFNULL(rh.timeWorkDay,' '),' ', IFNULL(rh.type,' '), - ' ', IF(rh.tm = 0,' ',rh.tm), - ' ', IF(rh.tc = 0,' ',rh.tc), + ' ', IF(rh.tm = 0,' ',rh.tm), + ' ', IF(rh.tc = 0,' ',rh.tc), ' ', IF(rh.balance = 0,' ',rh.balance), '' ORDER BY rh.dated SEPARATOR ''), ' @@ -83031,12 +83918,13 @@ BEGIN ') FROM tmp.reportHours rh - JOIN account.emailUser eu ON rh.id = eu.userFk + JOIN account.emailUser eu ON rh.id = eu.userFk GROUP BY rh.id; DROP TEMPORARY TABLE tmp.timeControlCalculate; DROP TEMPORARY TABLE tmp.timeBusinessCalculate; DROP TEMPORARY TABLE tmp.reportHours; + */ END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -83051,10 +83939,11 @@ 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_sendMailByDepartmentLauncher`() BEGIN + /* No se ejecutará hasta nuevo aviso de Sandra. DECLARE vWeek,vYear INT; IF (DAYNAME(CURDATE()) = 'miércoles') THEN @@ -83066,6 +83955,7 @@ BEGIN CALL vn.workerTimeControl_sendMailByDepartment(vWeek, vYear, NULL); END IF; + */ END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -85498,18 +86388,20 @@ 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 `zone_getLeaves`( - vSelf INT, - vParentFk INT, - vSearch VARCHAR(255) -) +CREATE DEFINER=`root`@`%` PROCEDURE `zone_getLeaves`(vSelf INT, vParentFk INT, vSearch VARCHAR(255)) BEGIN +/** + * Devuelve las ubicaciones incluidas en la ruta y que sean hijos de parentFk. + * @param vSelf Id de la zona + * @param vParentFk Id del geo a calcular + * @param vSearch cadena a buscar + */ DECLARE vIsNumber BOOL; DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch != ''; @@ -85517,19 +86409,24 @@ BEGIN CREATE TEMPORARY TABLE tNodes (UNIQUE (id)) ENGINE = MEMORY - SELECT id FROM zoneGeo LIMIT 0; + SELECT id + FROM zoneGeo + LIMIT 0; IF vIsSearch THEN SET vIsNumber = vSearch REGEXP '^[0-9]+$'; - + INSERT INTO tNodes - SELECT id FROM zoneGeo + SELECT id + FROM zoneGeo WHERE (vIsNumber AND `name` = vSearch) OR (!vIsNumber AND `name` LIKE CONCAT('%', vSearch, '%')) LIMIT 1000; + ELSEIF vParentFk IS NULL THEN INSERT INTO tNodes - SELECT geoFk FROM zoneIncluded + SELECT geoFk + FROM zoneIncluded WHERE zoneFk = vSelf; END IF; @@ -85537,12 +86434,15 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS tChilds; CREATE TEMPORARY TABLE tChilds ENGINE = MEMORY - SELECT id FROM tNodes; + SELECT id + FROM tNodes; DROP TEMPORARY TABLE IF EXISTS tParents; CREATE TEMPORARY TABLE tParents ENGINE = MEMORY - SELECT id FROM zoneGeo LIMIT 0; + SELECT id + FROM zoneGeo + LIMIT 0; myLoop: LOOP DELETE FROM tParents; @@ -85553,7 +86453,8 @@ BEGIN WHERE g.parentFk IS NOT NULL; INSERT IGNORE INTO tNodes - SELECT id FROM tParents; + SELECT id + FROM tParents; IF ROW_COUNT() = 0 THEN LEAVE myLoop; @@ -85561,30 +86462,29 @@ BEGIN DELETE FROM tChilds; INSERT INTO tChilds - SELECT id FROM tParents; + SELECT id + FROM tParents; END LOOP; - DROP TEMPORARY TABLE - tChilds, - tParents; + DROP TEMPORARY TABLE tChilds, tParents; END IF; IF !vIsSearch THEN INSERT IGNORE INTO tNodes - SELECT id FROM zoneGeo + SELECT id + FROM zoneGeo WHERE parentFk <=> vParentFk; END IF; - SELECT g.id, - g.`name`, + SELECT g.id, + g.name, g.parentFk, g.sons, isIncluded selected FROM zoneGeo g JOIN tNodes n ON n.id = g.id - LEFT JOIN zoneIncluded i - ON i.geoFk = g.id AND i.zoneFk = vSelf - ORDER BY depth, selected DESC, `name`; + LEFT JOIN zoneIncluded i ON i.geoFk = g.id AND i.zoneFk = vSelf + ORDER BY `depth`, selected DESC, name; DROP TEMPORARY TABLE tNodes; END ;; @@ -85603,15 +86503,9 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `zone_getLeaves2`( - vSelf INT, - vParentFk INT, - vSearch VARCHAR(255) -) +CREATE DEFINER=`root`@`%` PROCEDURE `zone_getLeaves2`(vSelf INT, vParentFk INT, vSearch VARCHAR(255)) BEGIN /** - * HAY QUE REFACTORIZAR ESTE Y zone_getLeaves - * https://redmine.verdnatura.es/issues/3073 * Devuelve los geoFk incluidos en la ruta y que sean hijos de parentFk * @param vSelf Id de la zona * @param vParentFk Id del geo a calcular @@ -85627,19 +86521,24 @@ BEGIN CREATE TEMPORARY TABLE tNodes (UNIQUE (id)) ENGINE = MEMORY - SELECT id FROM zoneGeo LIMIT 0; + SELECT id + FROM zoneGeo + LIMIT 0; IF vIsSearch THEN SET vIsNumber = vSearch REGEXP '^[0-9]+$'; INSERT INTO tNodes - SELECT id FROM zoneGeo + SELECT id + FROM zoneGeo WHERE (vIsNumber AND `name` = vSearch) OR (!vIsNumber AND `name` LIKE CONCAT('%', vSearch, '%')) LIMIT 1000; + ELSEIF vParentFk IS NULL THEN INSERT INTO tNodes - SELECT geoFk FROM zoneIncluded + SELECT geoFk + FROM zoneIncluded WHERE zoneFk = vSelf; END IF; @@ -85648,13 +86547,16 @@ BEGIN CREATE TEMPORARY TABLE tChilds (INDEX(id)) ENGINE = MEMORY - SELECT id FROM tNodes; + SELECT id + FROM tNodes; DROP TEMPORARY TABLE IF EXISTS tParents; CREATE TEMPORARY TABLE tParents (INDEX(id)) ENGINE = MEMORY - SELECT id FROM zoneGeo LIMIT 0; + SELECT id + FROM zoneGeo + LIMIT 0; myLoop: LOOP DELETE FROM tParents; @@ -85665,7 +86567,8 @@ BEGIN WHERE g.parentFk IS NOT NULL; INSERT IGNORE INTO tNodes - SELECT id FROM tParents; + SELECT id + FROM tParents; IF ROW_COUNT() = 0 THEN LEAVE myLoop; @@ -85673,22 +86576,22 @@ BEGIN DELETE FROM tChilds; INSERT INTO tChilds - SELECT id FROM tParents; + SELECT id + FROM tParents; END LOOP; - DROP TEMPORARY TABLE - tChilds, - tParents; + DROP TEMPORARY TABLE tChilds, tParents; END IF; IF !vIsSearch THEN INSERT IGNORE INTO tNodes - SELECT id FROM zoneGeo + SELECT id + FROM zoneGeo WHERE parentFk <=> vParentFk; END IF; INSERT IGNORE INTO tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) - SELECT g.id, + SELECT g.id, g.`name`, g.parentFk, g.sons, @@ -85696,10 +86599,10 @@ BEGIN vSelf FROM zoneGeo g JOIN tNodes n ON n.id = g.id - LEFT JOIN zoneIncluded i - ON i.geoFk = g.id AND i.zoneFk = vSelf - WHERE (i.isIncluded = TRUE - OR (i.isIncluded IS NULL AND vParentFk IS NOT NULL)); + LEFT JOIN zoneIncluded i ON i.geoFk = g.id AND i.zoneFk = vSelf + WHERE i.isIncluded = TRUE + OR (i.isIncluded IS NULL AND vParentFk IS NOT NULL); + DROP TEMPORARY TABLE tNodes; END ;; DELIMITER ; @@ -87614,7 +88517,7 @@ USE `vn`; /*!50001 SET collation_connection = utf8mb4_general_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `absenceType` AS select `cs`.`calendar_state_id` AS `id`,`cs`.`type` AS `name`,`cs`.`rgb` AS `rgb`,`cs`.`code` AS `code`,`cs`.`holidayEntitlementRate` AS `holidayEntitlementRate`,`cs`.`discountRate` AS `discountRate` from `postgresql`.`calendar_state` `cs` */; +/*!50001 VIEW `absenceType` AS select `cs`.`calendar_state_id` AS `id`,`cs`.`type` AS `name`,`cs`.`rgb` AS `rgb`,`cs`.`code` AS `code`,`cs`.`permissionRate` AS `permissionRate`,`cs`.`holidayEntitlementRate` AS `holidayEntitlementRate`,`cs`.`discountRate` AS `discountRate` from `postgresql`.`calendar_state` `cs` */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -88108,7 +89011,7 @@ USE `vn`; /*!50001 SET collation_connection = utf8_general_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `entryList` AS select `e`.`id` AS `entryFk`,if(`tr`.`isReceived`,' x','') AS `isHere`,`tr`.`landed` AS `landed`,ifnull(`s`.`nickname`,`s`.`name`) AS `supplier`,`e`.`ref` AS `entryRef`,`a`.`name` AS `agency`,`tr`.`ref` AS `travelRef`,`tr`.`appointment` AS `appointment`,`e`.`supplierFk` AS `supplierFk`,`tr`.`warehouseInFk` AS `warehouseInFk` from (((`entry` `e` join `travel` `tr` on((`tr`.`id` = `e`.`travelFk`))) join `supplier` `s` on((`s`.`id` = `e`.`supplierFk`))) left join `agency` `a` on((`tr`.`agencyFk` = `a`.`id`))) where (`tr`.`landed` between (curdate() + interval -(1) week) and (curdate() + interval 3 month)) order by (`tr`.`landed` < (curdate() + interval 3 day)),`tr`.`landed` desc,`s`.`name`,`e`.`id` desc */; +/*!50001 VIEW `entryList` AS select `e`.`id` AS `entryFk`,if(`tr`.`isReceived`,' x','') AS `isHere`,`tr`.`landed` AS `landed`,ifnull(`s`.`nickname`,`s`.`name`) AS `supplier`,`e`.`ref` AS `entryRef`,`a`.`name` AS `agency`,`tr`.`ref` AS `travelRef`,`tr`.`appointment` AS `appointment`,`e`.`supplierFk` AS `supplierFk`,`tr`.`warehouseInFk` AS `warehouseInFk` from (((`entry` `e` join `travel` `tr` on((`tr`.`id` = `e`.`travelFk`))) join `supplier` `s` on((`s`.`id` = `e`.`supplierFk`))) left join `agency` `a` on((`tr`.`agencyFk` = `a`.`id`))) where (`tr`.`landed` between (curdate() + interval -(1) week) and (curdate() + interval 3 month)) order by (`tr`.`landed` < (curdate() + interval 2 day)) desc,`tr`.`landed` desc,ifnull(`s`.`nickname`,`s`.`name`),`e`.`id` desc */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -88564,7 +89467,7 @@ USE `vn`; /*!50001 SET collation_connection = utf8_general_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `invoiceCorrectionDataSource` AS select `s`.`itemFk` AS `itemFk`,`s`.`quantity` AS `quantity`,`s`.`concept` AS `concept`,`s`.`price` AS `price`,`s`.`discount` AS `discount`,`t`.`refFk` AS `refFk`,`s`.`id` AS `saleFk`,`t`.`shipped` AS `shipped` from (`sale` `s` join `ticket` `t` on((`t`.`id` = `s`.`ticketFk`))) */; +/*!50001 VIEW `invoiceCorrectionDataSource` AS select `s`.`itemFk` AS `itemFk`,`s`.`quantity` AS `quantity`,`s`.`concept` AS `concept`,`s`.`price` AS `price`,`s`.`discount` AS `discount`,`t`.`refFk` AS `refFk`,`s`.`id` AS `saleFk`,`t`.`shipped` AS `shipped` from (`sale` `s` join `ticket` `t` on((`t`.`id` = `s`.`ticketFk`))) where (`t`.`shipped` > (curdate() + interval -(1) year)) */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -90013,6 +90916,25 @@ USE `vn`; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; +-- +-- Final view structure for view `workerDepartmentTest` +-- + +/*!50001 DROP TABLE IF EXISTS `workerDepartmentTest`*/; +/*!50001 DROP VIEW IF EXISTS `workerDepartmentTest`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8mb4 */; +/*!50001 SET character_set_results = utf8mb4 */; +/*!50001 SET collation_connection = utf8mb4_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `workerDepartmentTest` AS select `p`.`workerFk` AS `workerFk`,`d`.`id` AS `departmentFk` from ((((`vn`.`person` `p` join `postgresql`.`profile` `pr` on((`pr`.`person_id` = `p`.`id`))) join `postgresql`.`business` `b` on((`b`.`client_id` = `pr`.`profile_id`))) join `postgresql`.`business_labour` `bl` on((`b`.`business_id` = `bl`.`business_id`))) join `vn`.`department` `d` on((`d`.`id` = `bl`.`department_id`))) where (curdate() between `b`.`date_start` and ifnull(`b`.`date_end`,curdate())) */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + -- -- Final view structure for view `workerLabour` -- @@ -90204,20 +91126,20 @@ USE `vn`; /*!50001 SET collation_connection = @saved_col_connection */; -- --- Final view structure for view `workerWithoutDevice` +-- Final view structure for view `workerWithoutDevice__` -- -/*!50001 DROP TABLE IF EXISTS `workerWithoutDevice`*/; -/*!50001 DROP VIEW IF EXISTS `workerWithoutDevice`*/; +/*!50001 DROP TABLE IF EXISTS `workerWithoutDevice__`*/; +/*!50001 DROP VIEW IF EXISTS `workerWithoutDevice__`*/; /*!50001 SET @saved_cs_client = @@character_set_client */; /*!50001 SET @saved_cs_results = @@character_set_results */; /*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 SET character_set_client = utf8mb4 */; +/*!50001 SET character_set_results = utf8mb4 */; +/*!50001 SET collation_connection = utf8mb4_general_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `workerWithoutDevice` AS select `c`.`workerFk` AS `workerFk`,`cl`.`name` AS `Trabajador`,count(distinct `c`.`id`) AS `Colecciones` from ((`collection` `c` join `client` `cl` on((`cl`.`id` = `c`.`workerFk`))) left join `deviceProductionUser` `dpu` on((`dpu`.`userFk` = `c`.`workerFk`))) where ((`c`.`created` > curdate()) and isnull(`dpu`.`userFk`)) group by `c`.`workerFk` */; +/*!50001 VIEW `workerWithoutDevice__` AS select `c`.`workerFk` AS `workerFk`,`cl`.`name` AS `Trabajador`,count(distinct `c`.`id`) AS `Colecciones` from ((`collection` `c` join `client` `cl` on((`cl`.`id` = `c`.`workerFk`))) left join `deviceProductionUser` `dpu` on((`dpu`.`userFk` = `c`.`workerFk`))) where ((`c`.`created` > curdate()) and isnull(`dpu`.`userFk`)) group by `c`.`workerFk` */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -90294,4 +91216,4 @@ USE `vncontrol`; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2021-10-20 8:37:55 +-- Dump completed on 2021-11-08 8:19:44 diff --git a/e2e/helpers/selectors.js b/e2e/helpers/selectors.js index 08a21f838..d4d5d33aa 100644 --- a/e2e/helpers/selectors.js +++ b/e2e/helpers/selectors.js @@ -1147,6 +1147,7 @@ export default { alias: 'vn-supplier-basic-data vn-textfield[ng-model="$ctrl.supplier.nickname"]', isSerious: 'vn-supplier-basic-data vn-check[ng-model="$ctrl.supplier.isSerious"]', isActive: 'vn-supplier-basic-data vn-check[ng-model="$ctrl.supplier.isActive"]', + isPayMethodChecked: 'vn-supplier-basic-data vn-check[ng-model="$ctrl.supplier.isPayMethodChecked"]', notes: 'vn-supplier-basic-data vn-textarea[ng-model="$ctrl.supplier.note"]', saveButton: 'vn-supplier-basic-data button[type="submit"]', }, diff --git a/e2e/paths/02-client/14_balance.spec.js b/e2e/paths/02-client/14_balance.spec.js index d408215ff..d3de842e3 100644 --- a/e2e/paths/02-client/14_balance.spec.js +++ b/e2e/paths/02-client/14_balance.spec.js @@ -105,7 +105,23 @@ describe('Client balance path', () => { expect(result).toContain('-€100.00'); }); + it('should create a new payment and check the cash exceeded the maximum', async() => { + const amountPaid = '1001'; + + await page.closePopup(); + await page.waitToClick(selectors.clientBalance.newPaymentButton); + await page.autocompleteSearch(selectors.clientBalance.newPaymentBank, 'Cash'); + await page.write(selectors.clientBalance.newPaymentAmount, amountPaid); + await page.clearInput(selectors.clientBalance.newDescription); + await page.write(selectors.clientBalance.newDescription, 'Payment'); + await page.waitToClick(selectors.clientBalance.saveButton); + const message = await page.waitForSnackbar(); + + expect(message.text).toContain('Amount exceeded'); + }); + it('should create a new payment that sets the balance back to the original negative value', async() => { + await page.closePopup(); await page.waitToClick(selectors.clientBalance.newPaymentButton); await page.autocompleteSearch(selectors.clientBalance.newPaymentBank, 'Pay on receipt'); await page.overwrite(selectors.clientBalance.newPaymentAmount, '-150'); diff --git a/e2e/paths/13-supplier/02_basic_data.spec.js b/e2e/paths/13-supplier/02_basic_data.spec.js index 2bc94402b..f98fa779e 100644 --- a/e2e/paths/13-supplier/02_basic_data.spec.js +++ b/e2e/paths/13-supplier/02_basic_data.spec.js @@ -22,6 +22,7 @@ describe('Supplier basic data path', () => { await page.write(selectors.supplierBasicData.alias, 'Plants Nick SL'); await page.waitToClick(selectors.supplierBasicData.isSerious); await page.waitToClick(selectors.supplierBasicData.isActive); + await page.waitToClick(selectors.supplierBasicData.isPayMethodChecked); await page.write(selectors.supplierBasicData.notes, 'Some notes'); await page.waitToClick(selectors.supplierBasicData.saveButton); @@ -52,6 +53,12 @@ describe('Supplier basic data path', () => { expect(result).toBe('unchecked'); }); + it('should check the isPayMethodChecked checkbox is now unchecked', async() => { + const result = await page.checkboxState(selectors.supplierBasicData.isPayMethodChecked); + + expect(result).toBe('unchecked'); + }); + it('should check the notes were edited', async() => { const result = await page.waitToGetProperty(selectors.supplierBasicData.notes, 'value'); diff --git a/modules/client/front/balance/create/index.html b/modules/client/front/balance/create/index.html index f9bf89b04..56e505463 100644 --- a/modules/client/front/balance/create/index.html +++ b/modules/client/front/balance/create/index.html @@ -44,7 +44,8 @@ label="Amount" ng-model="$ctrl.amountPaid" step="0.01" - required="true"> + required="true" + max="$ctrl.maxAmount"> diff --git a/modules/client/front/balance/create/index.js b/modules/client/front/balance/create/index.js index 5b5866732..d306c6f84 100644 --- a/modules/client/front/balance/create/index.js +++ b/modules/client/front/balance/create/index.js @@ -61,8 +61,14 @@ class Controller extends Dialog { if (value) { const accountingType = value.accountingType; - this.receipt.description = + if (this.originalDescription) { + this.receipt.description = `${accountingType && accountingType.receiptDescription}, ${this.originalDescription}`; + } else { + this.receipt.description = + `${accountingType && accountingType.receiptDescription}`; + } + this.maxAmount = accountingType && accountingType.maxAmount; } } @@ -123,6 +129,11 @@ class Controller extends Dialog { if (response !== 'accept') return super.responseHandler(response); + const exceededAmount = this.receipt.amountPaid > this.maxAmount; + + if (this.bankSelection.accountingType.code == 'cash' && exceededAmount) + return this.vnApp.showError(this.$t('Amount exceeded', {maxAmount: this.maxAmount})); + let receiptId; return this.$http.post(`Clients/${this.clientFk}/createReceipt`, this.receipt) .then(res => { diff --git a/modules/client/front/balance/create/index.spec.js b/modules/client/front/balance/create/index.spec.js index a2e3e2015..77fe32e0f 100644 --- a/modules/client/front/balance/create/index.spec.js +++ b/modules/client/front/balance/create/index.spec.js @@ -23,6 +23,7 @@ describe('Client', () => { clientFk: 1101, companyFk: 442 }; + controller.bankSelection = {accountingType: {code: 'myCode'}}; })); describe('bankSelection() setter', () => { diff --git a/modules/client/front/balance/create/locale/es.yml b/modules/client/front/balance/create/locale/es.yml index 266e4365c..056590966 100644 --- a/modules/client/front/balance/create/locale/es.yml +++ b/modules/client/front/balance/create/locale/es.yml @@ -1 +1,2 @@ -View receipt: Ver recibo \ No newline at end of file +View receipt: Ver recibo +Amount exceeded: Según ley contra el fraude no se puede recibir cobros por importe igual o superior a {{maxAmount}} \ No newline at end of file diff --git a/modules/item/front/last-entries/index.js b/modules/item/front/last-entries/index.js index a92ec4858..014761da9 100644 --- a/modules/item/front/last-entries/index.js +++ b/modules/item/front/last-entries/index.js @@ -6,7 +6,7 @@ class Controller extends Section { super($element, $); const from = new Date(); - from.setDate(from.getDate()); + from.setDate(from.getDate() - 75); from.setHours(0, 0, 0, 0); const to = new Date(); diff --git a/modules/order/back/methods/order/filter.js b/modules/order/back/methods/order/filter.js index bd987dd5b..ddbaba5bd 100644 --- a/modules/order/back/methods/order/filter.js +++ b/modules/order/back/methods/order/filter.js @@ -172,11 +172,11 @@ module.exports = Self => { LEFT JOIN zoneEstimatedDelivery zed ON zed.zoneFk = t.zoneFk`); stmt.merge(conn.makeWhere(filter.where)); + stmt.merge(`GROUP BY id`); stmt.merge(conn.makePagination(filter)); stmts.push(stmt); stmt = new ParameterizedSQL(`SELECT * FROM tmp.filter`); - stmt.merge(`GROUP BY id`); stmt.merge(conn.makeOrderBy(filter.order)); const ordersIndex = stmts.push(stmt) - 1; diff --git a/modules/supplier/back/models/supplier.json b/modules/supplier/back/models/supplier.json index 30ed721a5..4a22144ba 100644 --- a/modules/supplier/back/models/supplier.json +++ b/modules/supplier/back/models/supplier.json @@ -101,7 +101,10 @@ "mysql": { "columnName": "withholdingSageFk" } - } + }, + "isPayMethodChecked": { + "type": "boolean" + } }, "relations": { "payMethod": { @@ -160,13 +163,5 @@ "model": "SupplierAddress", "foreignKey": "supplierFk" } - }, - "acls": [ - { - "accessType": "READ", - "principalType": "ROLE", - "principalId": "$everyone", - "permission": "ALLOW" - } - ] + } } \ No newline at end of file diff --git a/modules/supplier/front/basic-data/index.html b/modules/supplier/front/basic-data/index.html index a30eee719..0ec80641d 100644 --- a/modules/supplier/front/basic-data/index.html +++ b/modules/supplier/front/basic-data/index.html @@ -36,6 +36,10 @@ label="Active" ng-model="$ctrl.supplier.isActive"> + + { const stmts = []; - const startedMinusOne = new Date(started); - startedMinusOne.setDate(started.getDate() - 1); - - const endedPlusOne = new Date(ended); - endedPlusOne.setDate(ended.getDate() + 1); - stmts.push(` DROP TEMPORARY TABLE IF EXISTS tmp.timeControlCalculate, tmp.timeBusinessCalculate `); - stmts.push(new ParameterizedSQL('CALL vn.timeControl_calculateByUser(?, ?, ?)', [userId, startedMinusOne, endedPlusOne])); + stmts.push(new ParameterizedSQL('CALL vn.timeControl_calculateByUser(?, ?, ?)', [userId, started, ended])); - stmts.push(new ParameterizedSQL('CALL vn.timeBusiness_calculateByUser(?, ?, ?)', [userId, startedMinusOne, endedPlusOne])); + stmts.push(new ParameterizedSQL('CALL vn.timeBusiness_calculateByUser(?, ?, ?)', [userId, started, ended])); const resultIndex = stmts.push(new ParameterizedSQL(` - SELECT tbc.dated, tbc.timeWorkSeconds expectedHours, tcc.timeWorkSeconds workedHours - FROM tmp.timeBusinessCalculate tbc - LEFT JOIN tmp.timeControlCalculate tcc ON tcc.dated = tbc.dated - WHERE tbc.dated BETWEEN ? AND ? + SELECT tcc.dated, tbc.timeWorkSeconds expectedHours, tcc.timeWorkSeconds workedHours + FROM tmp.timeControlCalculate tcc + LEFT JOIN tmp.timeBusinessCalculate tbc ON tcc.dated = tbc.dated + WHERE tcc.dated BETWEEN DATE(?) AND DATE(?) `, [started, ended])) - 1; stmts.push(` diff --git a/modules/worker/back/methods/worker/specs/getWorkedHours.spec.js b/modules/worker/back/methods/worker/specs/getWorkedHours.spec.js index c06ff8502..3132a9003 100644 --- a/modules/worker/back/methods/worker/specs/getWorkedHours.spec.js +++ b/modules/worker/back/methods/worker/specs/getWorkedHours.spec.js @@ -1,17 +1,17 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('Worker getWorkedHours()', () => { it(`should return the expected hours and the worked hours of a given date`, async() => { const workerID = 1106; - let started = new Date(); + const started = new Date(); started.setHours(0, 0, 0, 0); - let ended = new Date(); - ended.setHours(0, 0, 0, 0); + const ended = new Date(); + ended.setHours(23, 59, 59, 999); - const [result] = await app.models.Worker.getWorkedHours(workerID, started, ended); + const [result] = await models.Worker.getWorkedHours(workerID, started, ended); - expect(result.expectedHours).toEqual(28800); // 8:00 hours seconds + expect(result.expectedHours).toEqual(28800); // 8:00 hours in seconds expect(result.workedHours).toEqual(29400); // 8:10 hours in seconds }); }); diff --git a/modules/worker/front/time-control/index.js b/modules/worker/front/time-control/index.js index 0fb5f9dbe..96913c505 100644 --- a/modules/worker/front/time-control/index.js +++ b/modules/worker/front/time-control/index.js @@ -171,7 +171,6 @@ class Controller extends Section { from: from, to: to }; - const query = `Workers/${this.$params.id}/getWorkedHours`; return this.$http.get(query, {params}).then(res => { const workDays = res.data; @@ -212,7 +211,8 @@ class Controller extends Section { let todayInWeek = this.weekDays.find(day => day.dated.getTime() === today.getTime()); if (todayInWeek && todayInWeek.hours && todayInWeek.hours.length) { - const remainingTime = todayInWeek.workedHours ? ((todayInWeek.expectedHours - todayInWeek.workedHours) * 1000) : null; + const remainingTime = todayInWeek.workedHours ? + ((todayInWeek.expectedHours - todayInWeek.workedHours) * 1000) : null; const lastKnownEntry = todayInWeek.hours[todayInWeek.hours.length - 1]; const lastKnownTime = new Date(lastKnownEntry.timed).getTime(); const finishTimeStamp = lastKnownTime && remainingTime ? lastKnownTime + remainingTime : null; diff --git a/modules/zone/back/methods/zone/getEventsFiltered.js b/modules/zone/back/methods/zone/getEventsFiltered.js new file mode 100644 index 000000000..2788f45d0 --- /dev/null +++ b/modules/zone/back/methods/zone/getEventsFiltered.js @@ -0,0 +1,63 @@ +module.exports = Self => { + Self.remoteMethod('getEventsFiltered', { + description: 'Get events filtered for zone and date', + accepts: [ + { + arg: 'zoneFk', + type: 'number', + description: 'The zone id', + required: true + }, + { + arg: 'started', + type: 'date', + description: 'The date calendar start', + }, + { + arg: 'ended', + type: 'date', + description: 'The date calendar end', + } + ], + returns: { + type: 'object', + root: true + }, + http: { + path: `/getEventsFiltered`, + verb: 'GET' + } + }); + + Self.getEventsFiltered = async(zoneFk, started, ended, options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + query = ` + SELECT * + FROM vn.zoneEvent + WHERE zoneFk = ? + AND ((type = 'indefinitely') + OR (type = 'day' AND dated BETWEEN ? AND ?) + OR (type = 'range' + AND ( + (started BETWEEN ? AND ?) + OR (ended BETWEEN ? AND ?) + ) + ) + ) + ORDER BY type='indefinitely' DESC, type='range' DESC, type='day' DESC;`; + const events = await Self.rawSql(query, [zoneFk, started, ended, started, ended, started, ended], myOptions); + + query = ` + SELECT * + FROM vn.zoneExclusion + WHERE zoneFk = ? + AND dated BETWEEN ? AND ?;`; + const exclusions = await Self.rawSql(query, [zoneFk, started, ended], myOptions); + + return {events, exclusions}; + }; +}; diff --git a/modules/zone/back/methods/zone/specs/clone.spec.js b/modules/zone/back/methods/zone/specs/clone.spec.js index 1ede5feb7..92392d789 100644 --- a/modules/zone/back/methods/zone/specs/clone.spec.js +++ b/modules/zone/back/methods/zone/specs/clone.spec.js @@ -1,12 +1,12 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('agency clone()', () => { it('should clone a zone', async() => { - const tx = await app.models.Zone.beginTransaction({}); + const tx = await models.Zone.beginTransaction({}); try { const options = {transaction: tx}; - const newZone = await app.models.Zone.clone(1, options); + const newZone = await models.Zone.clone(1, options); expect(newZone.name).toEqual('Zone pickup A'); diff --git a/modules/zone/back/methods/zone/specs/deleteZone.spec.js b/modules/zone/back/methods/zone/specs/deleteZone.spec.js index d8abe1da8..968685fec 100644 --- a/modules/zone/back/methods/zone/specs/deleteZone.spec.js +++ b/modules/zone/back/methods/zone/specs/deleteZone.spec.js @@ -1,4 +1,4 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); describe('zone deletezone()', () => { @@ -16,13 +16,13 @@ describe('zone deletezone()', () => { active: activeCtx }); try { - const originalTickets = await app.models.Ticket.find({ + const originalTickets = await models.Ticket.find({ where: { zoneFk: zoneId } }); ticketIDs = originalTickets.map(ticket => ticket.id); - originalTicketStates = await app.models.TicketState.find({where: { + originalTicketStates = await models.TicketState.find({where: { ticketFk: {inq: ticketIDs}, code: 'FIXING'}}); } catch (error) { @@ -31,16 +31,16 @@ describe('zone deletezone()', () => { }); it('should delete a zone and update their tickets', async() => { - const tx = await app.models.Zone.beginTransaction({}); + const tx = await models.Zone.beginTransaction({}); try { const options = {transaction: tx}; - await app.models.Zone.deleteZone(ctx, zoneId, options); + await models.Zone.deleteZone(ctx, zoneId, options); - const updatedZone = await app.models.Zone.findById(zoneId, null, options); - const anUpdatedTicket = await app.models.Ticket.findById(ticketIDs[0], null, options); + const updatedZone = await models.Zone.findById(zoneId, null, options); + const anUpdatedTicket = await models.Ticket.findById(ticketIDs[0], null, options); - const updatedTicketStates = await app.models.TicketState.find({ + const updatedTicketStates = await models.TicketState.find({ where: { ticketFk: {inq: ticketIDs}, code: 'FIXING' diff --git a/modules/zone/back/methods/zone/specs/getEvents.spec.js b/modules/zone/back/methods/zone/specs/getEvents.spec.js index 4227908bb..d1c51baff 100644 --- a/modules/zone/back/methods/zone/specs/getEvents.spec.js +++ b/modules/zone/back/methods/zone/specs/getEvents.spec.js @@ -1,13 +1,13 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('zone getEvents()', () => { it('should return all events for the specified geo and agency mode', async() => { - const tx = await app.models.Zone.beginTransaction({}); + const tx = await models.Zone.beginTransaction({}); try { const options = {transaction: tx}; - let result = await app.models.Zone.getEvents(20, 1, options); + let result = await models.Zone.getEvents(20, 1, options); expect(result.events.length).toEqual(10); diff --git a/modules/zone/back/methods/zone/specs/getEventsFiltered.spec.js b/modules/zone/back/methods/zone/specs/getEventsFiltered.spec.js new file mode 100644 index 000000000..ffa416282 --- /dev/null +++ b/modules/zone/back/methods/zone/specs/getEventsFiltered.spec.js @@ -0,0 +1,21 @@ +const models = require('vn-loopback/server/server').models; + +describe('zone getEventsFiltered()', () => { + it('should return events and exclusions for the specified zoneFk in a range of dates', async() => { + const tx = await models.Zone.beginTransaction({}); + + try { + const options = {transaction: tx}; + + let result = await models.Zone.getEventsFiltered(10, '2021-10-01', '2021-10-02', options); + + expect(result.events.length).toEqual(1); + expect(result.exclusions.length).toEqual(0); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); +}); diff --git a/modules/zone/back/methods/zone/specs/getLeaves.spec.js b/modules/zone/back/methods/zone/specs/getLeaves.spec.js index 853962cc4..db7359671 100644 --- a/modules/zone/back/methods/zone/specs/getLeaves.spec.js +++ b/modules/zone/back/methods/zone/specs/getLeaves.spec.js @@ -1,13 +1,13 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('zone getLeaves()', () => { it('should return the country and the childs containing the search value', async() => { - const tx = await app.models.Zone.beginTransaction({}); + const tx = await models.Zone.beginTransaction({}); try { const options = {transaction: tx}; - let result = await app.models.Zone.getLeaves(1, null, '46000', options); + let result = await models.Zone.getLeaves(1, null, '46000', options); expect(result.length).toEqual(1); diff --git a/modules/zone/back/methods/zone/specs/includingExpired.spec.js b/modules/zone/back/methods/zone/specs/includingExpired.spec.js index ea28727f4..98fdc272d 100644 --- a/modules/zone/back/methods/zone/specs/includingExpired.spec.js +++ b/modules/zone/back/methods/zone/specs/includingExpired.spec.js @@ -1,4 +1,4 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('zone includingExpired()', () => { const inhousePickupId = 1; @@ -6,14 +6,14 @@ describe('zone includingExpired()', () => { const warehouseId = 1; it('should return an array containing all zones', async() => { - const tx = await app.models.Zone.beginTransaction({}); + const tx = await models.Zone.beginTransaction({}); const ctx = {req: {accessToken: {userId: 1}}}; const where = {}; try { const options = {transaction: tx}; - const result = await app.models.Zone.includingExpired(ctx, {where}, options); + const result = await models.Zone.includingExpired(ctx, {where}, options); expect(result.length).toBeGreaterThan(2); @@ -28,12 +28,12 @@ describe('zone includingExpired()', () => { const ctx = {req: {accessToken: {userId: 1}}}; const where = {agencyModeFk: inhousePickupId}; - const tx = await app.models.Zone.beginTransaction({}); + const tx = await models.Zone.beginTransaction({}); try { const options = {transaction: tx}; - const result = await app.models.Zone.includingExpired(ctx, {where}, options); + const result = await models.Zone.includingExpired(ctx, {where}, options); const validAgency = result.every(zone => zone.agencyModeFk = inhousePickupId); @@ -56,12 +56,12 @@ describe('zone includingExpired()', () => { warehouseFk: warehouseId }; - const tx = await app.models.Zone.beginTransaction({}); + const tx = await models.Zone.beginTransaction({}); try { const options = {transaction: tx}; - const result = await app.models.Zone.includingExpired(ctx, {where}, options); + const result = await models.Zone.includingExpired(ctx, {where}, options); const firstZone = result[0]; expect(firstZone.name).toEqual('Zone pickup A'); diff --git a/modules/zone/back/methods/zone/specs/toggleIsIncluded.spec.js b/modules/zone/back/methods/zone/specs/toggleIsIncluded.spec.js index 5fe948747..562e62f5f 100644 --- a/modules/zone/back/methods/zone/specs/toggleIsIncluded.spec.js +++ b/modules/zone/back/methods/zone/specs/toggleIsIncluded.spec.js @@ -1,13 +1,13 @@ -const app = require('vn-loopback/server/server'); +const models = require('vn-loopback/server/server').models; describe('zone toggleIsIncluded()', () => { it('should return the created location with isIncluded true', async() => { - const tx = await app.models.Zone.beginTransaction({}); + const tx = await models.Zone.beginTransaction({}); try { const options = {transaction: tx}; - let result = await app.models.Zone.toggleIsIncluded(1, 20, true, options); + let result = await models.Zone.toggleIsIncluded(1, 20, true, options); expect(result.isIncluded).toBeTrue(); @@ -19,12 +19,12 @@ describe('zone toggleIsIncluded()', () => { }); it('should return the created location with isIncluded false', async() => { - const tx = await app.models.Zone.beginTransaction({}); + const tx = await models.Zone.beginTransaction({}); try { const options = {transaction: tx}; - let result = await app.models.Zone.toggleIsIncluded(1, 20, false, options); + let result = await models.Zone.toggleIsIncluded(1, 20, false, options); expect(result.isIncluded).toBeFalse(); @@ -36,14 +36,14 @@ describe('zone toggleIsIncluded()', () => { }); it('should return the amount of deleted locations', async() => { - const tx = await app.models.Zone.beginTransaction({}); + const tx = await models.Zone.beginTransaction({}); try { const options = {transaction: tx}; - await app.models.Zone.toggleIsIncluded(1, 20, false, options); + await models.Zone.toggleIsIncluded(1, 20, false, options); - let result = await app.models.Zone.toggleIsIncluded(1, 20, undefined, options); + let result = await models.Zone.toggleIsIncluded(1, 20, undefined, options); expect(result).toEqual({count: 1}); diff --git a/modules/zone/back/models/zone.js b/modules/zone/back/models/zone.js index 0b1b9d106..9771c958b 100644 --- a/modules/zone/back/models/zone.js +++ b/modules/zone/back/models/zone.js @@ -2,6 +2,7 @@ module.exports = Self => { require('../methods/zone/clone')(Self); require('../methods/zone/getLeaves')(Self); require('../methods/zone/getEvents')(Self); + require('../methods/zone/getEventsFiltered')(Self); require('../methods/zone/toggleIsIncluded')(Self); require('../methods/zone/getUpcomingDeliveries')(Self); require('../methods/zone/deleteZone')(Self); diff --git a/modules/zone/front/events/index.html b/modules/zone/front/events/index.html index d48b5f0d8..25ec2827f 100644 --- a/modules/zone/front/events/index.html +++ b/modules/zone/front/events/index.html @@ -1,5 +1,6 @@ diff --git a/modules/zone/front/events/index.js b/modules/zone/front/events/index.js index 29b534c0c..0df16a42a 100644 --- a/modules/zone/front/events/index.js +++ b/modules/zone/front/events/index.js @@ -21,14 +21,18 @@ class Controller extends Section { } refresh() { - let data = {}; - this.$q.all([ - this.$http.get(this.path) - .then(res => data.events = res.data), - this.$http.get(this.exclusionsPath) - .then(res => data.exclusions = res.data) - ]).finally(() => { - this.$.data = data; + this.$.data = null; + this.$.$applyAsync(() => { + const params = { + zoneFk: this.$params.id, + started: this.$.calendar.firstDay, + ended: this.$.calendar.lastDay + }; + + this.$http.get(`Zones/getEventsFiltered`, {params}).then(res => { + const data = res.data; + this.$.data = data; + }); }); } diff --git a/modules/zone/front/events/index.spec.js b/modules/zone/front/events/index.spec.js index c1b0d78b3..ed2c91c31 100644 --- a/modules/zone/front/events/index.spec.js +++ b/modules/zone/front/events/index.spec.js @@ -17,8 +17,26 @@ describe('component vnZoneEvents', () => { describe('refresh()', () => { it('should set the zone and then call both getSummary() and getWarehouses()', () => { - $httpBackend.expectGET(`Zones/1/events`).respond({id: 1}); - $httpBackend.expectGET(`Zones/1/exclusions`).respond({id: 1}); + const date = '2021-10-01'; + + controller.$params.id = 999; + controller.$.calendar = { + firstDay: date, + lastDay: date + }; + + const params = { + zoneFk: controller.$params.id, + started: date, + ended: date + }; + + const query = `Zones/getEventsFiltered?ended=${date}&started=${date}&zoneFk=${params.zoneFk}`; + const response = { + events: 'myEvents', + exclusions: 'myExclusions' + }; + $httpBackend.whenGET(query).respond(response); controller.refresh(); $httpBackend.flush(); diff --git a/print/templates/reports/invoice/invoice.html b/print/templates/reports/invoice/invoice.html index 671bb8c7f..8b13f2a15 100644 --- a/print/templates/reports/invoice/invoice.html +++ b/print/templates/reports/invoice/invoice.html @@ -96,7 +96,7 @@
-

Shipped

+

{{$t('shipped')}}

diff --git a/print/templates/reports/invoice/sql/tickets.sql b/print/templates/reports/invoice/sql/tickets.sql index feca81ead..7d135bd03 100644 --- a/print/templates/reports/invoice/sql/tickets.sql +++ b/print/templates/reports/invoice/sql/tickets.sql @@ -4,4 +4,5 @@ SELECT t.nickname FROM invoiceOut io JOIN ticket t ON t.refFk = io.ref -WHERE io.id = ? \ No newline at end of file +WHERE io.id = ? +ORDER BY t.shipped \ No newline at end of file