From efa32a3dc725f936a33599daeb2b440632ac84b7 Mon Sep 17 00:00:00 2001 From: alexm Date: Fri, 4 Mar 2022 13:04:28 +0100 Subject: [PATCH] export structure --- back/methods/account/login.js | 1 + db/dump/dumpedFixtures.sql | 16 +- db/dump/structure.sql | 16540 ++++++++-------- db/export-structure.sh | 1 - .../account/back/methods/user-account/sync.js | 2 +- 5 files changed, 8689 insertions(+), 7871 deletions(-) diff --git a/back/methods/account/login.js b/back/methods/account/login.js index 7393e8374..efcf463ee 100644 --- a/back/methods/account/login.js +++ b/back/methods/account/login.js @@ -57,6 +57,7 @@ module.exports = Self => { throw new UserError('User disabled'); try { + console.log('FALLA?'); await $.UserAccount.sync(instance.username, password); } catch (err) { console.warn(err); diff --git a/db/dump/dumpedFixtures.sql b/db/dump/dumpedFixtures.sql index 8bd3099a5..f449ae0ae 100644 --- a/db/dump/dumpedFixtures.sql +++ b/db/dump/dumpedFixtures.sql @@ -34,7 +34,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2022-02-25 8:13:15 +-- Dump completed on 2022-03-04 12:54:27 USE `account`; -- MariaDB dump 10.19 Distrib 10.5.12-MariaDB, for debian-linux-gnu (x86_64) -- @@ -120,7 +120,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2022-02-25 8:13:16 +-- Dump completed on 2022-03-04 12:54:28 USE `salix`; -- MariaDB dump 10.19 Distrib 10.5.12-MariaDB, for debian-linux-gnu (x86_64) -- @@ -186,7 +186,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2022-02-25 8:13:17 +-- Dump completed on 2022-03-04 12:54:29 USE `vn`; -- MariaDB dump 10.19 Distrib 10.5.12-MariaDB, for debian-linux-gnu (x86_64) -- @@ -452,7 +452,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2022-02-25 8:13:22 +-- Dump completed on 2022-03-04 12:54:34 USE `cache`; -- MariaDB dump 10.19 Distrib 10.5.12-MariaDB, for debian-linux-gnu (x86_64) -- @@ -488,7 +488,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2022-02-25 8:13:23 +-- Dump completed on 2022-03-04 12:54:35 USE `hedera`; -- MariaDB dump 10.19 Distrib 10.5.12-MariaDB, for debian-linux-gnu (x86_64) -- @@ -554,7 +554,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2022-02-25 8:13:24 +-- Dump completed on 2022-03-04 12:54:36 USE `postgresql`; -- MariaDB dump 10.19 Distrib 10.5.12-MariaDB, for debian-linux-gnu (x86_64) -- @@ -640,7 +640,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2022-02-25 8:13:25 +-- Dump completed on 2022-03-04 12:54:37 USE `sage`; -- MariaDB dump 10.19 Distrib 10.5.12-MariaDB, for debian-linux-gnu (x86_64) -- @@ -696,4 +696,4 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2022-02-25 8:13:26 +-- Dump completed on 2022-03-04 12:54:38 diff --git a/db/dump/structure.sql b/db/dump/structure.sql index 2c9b97348..5a818abe6 100644 --- a/db/dump/structure.sql +++ b/db/dump/structure.sql @@ -169,6 +169,7 @@ CREATE TABLE `mailClientAccess` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `client` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, `action` set('OK','REJECT') CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT 'REJECT', + `description` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `mailFrom` (`client`) ) ENGINE=InnoDBDEFAULT CHARSET=utf8; @@ -214,6 +215,7 @@ CREATE TABLE `mailSenderAccess` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `sender` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, `action` set('OK','REJECT') NOT NULL DEFAULT 'REJECT', + `description` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `mailFrom` (`sender`) ) ENGINE=InnoDBDEFAULT CHARSET=utf8; @@ -697,52 +699,52 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `passwordGenerate`() RETURNS text CHARSET utf8 COLLATE utf8_unicode_ci READS SQL DATA -BEGIN -/** - * Generates a random password that meets the minimum requirements. - * - * @return Generated password - */ - DECLARE vMinLength TINYINT; - DECLARE vMinAlpha TINYINT; - DECLARE vMinUpper TINYINT; - DECLARE vMinDigits TINYINT; - DECLARE vMinPunct TINYINT; - DECLARE vAlpha TINYINT DEFAULT 0; - DECLARE vUpper TINYINT DEFAULT 0; - DECLARE vDigits TINYINT DEFAULT 0; - DECLARE vPunct TINYINT DEFAULT 0; - DECLARE vRandIndex INT; - DECLARE vPwd TEXT DEFAULT ''; - - DECLARE vAlphaChars TEXT DEFAULT 'abcdefghijklmnopqrstuvwxyz'; - DECLARE vUpperChars TEXT DEFAULT 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; - DECLARE vDigitChars TEXT DEFAULT '1234567890'; - DECLARE vPunctChars TEXT DEFAULT '!$%&()=.'; - - SELECT length, nAlpha, nUpper, nDigits, nPunct - INTO vMinLength, vMinAlpha, vMinUpper, vMinDigits, vMinPunct FROM userPassword; - - WHILE LENGTH(vPwd) < vMinLength OR vAlpha < vMinAlpha - OR vUpper < vMinUpper OR vDigits < vMinDigits OR vPunct < vMinPunct DO - SET vRandIndex = FLOOR((RAND() * 4) + 1); - - CASE - WHEN vRandIndex = 1 THEN - SET vPwd = CONCAT(vPwd, SUBSTRING(vAlphaChars, FLOOR((RAND() * 26) + 1), 1)); - SET vAlpha = vAlpha + 1; - WHEN vRandIndex = 2 THEN - SET vPwd = CONCAT(vPwd, SUBSTRING(vUpperChars, FLOOR((RAND() * 26) + 1), 1)); - SET vUpper = vUpper + 1; - WHEN vRandIndex = 3 THEN - SET vPwd = CONCAT(vPwd, SUBSTRING(vDigitChars, FLOOR((RAND() * 10) + 1), 1)); - SET vDigits = vDigits + 1; - WHEN vRandIndex = 4 THEN - SET vPwd = CONCAT(vPwd, SUBSTRING(vPunctChars, FLOOR((RAND() * LENGTH(vPunctChars)) + 1), 1)); - SET vPunct = vPunct + 1; - END CASE; - END WHILE; - RETURN vPwd; +BEGIN +/** + * Generates a random password that meets the minimum requirements. + * + * @return Generated password + */ + DECLARE vMinLength TINYINT; + DECLARE vMinAlpha TINYINT; + DECLARE vMinUpper TINYINT; + DECLARE vMinDigits TINYINT; + DECLARE vMinPunct TINYINT; + DECLARE vAlpha TINYINT DEFAULT 0; + DECLARE vUpper TINYINT DEFAULT 0; + DECLARE vDigits TINYINT DEFAULT 0; + DECLARE vPunct TINYINT DEFAULT 0; + DECLARE vRandIndex INT; + DECLARE vPwd TEXT DEFAULT ''; + + DECLARE vAlphaChars TEXT DEFAULT 'abcdefghijklmnopqrstuvwxyz'; + DECLARE vUpperChars TEXT DEFAULT 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; + DECLARE vDigitChars TEXT DEFAULT '1234567890'; + DECLARE vPunctChars TEXT DEFAULT '!$%&()=.'; + + SELECT length, nAlpha, nUpper, nDigits, nPunct + INTO vMinLength, vMinAlpha, vMinUpper, vMinDigits, vMinPunct FROM userPassword; + + WHILE LENGTH(vPwd) < vMinLength OR vAlpha < vMinAlpha + OR vUpper < vMinUpper OR vDigits < vMinDigits OR vPunct < vMinPunct DO + SET vRandIndex = FLOOR((RAND() * 4) + 1); + + CASE + WHEN vRandIndex = 1 THEN + SET vPwd = CONCAT(vPwd, SUBSTRING(vAlphaChars, FLOOR((RAND() * 26) + 1), 1)); + SET vAlpha = vAlpha + 1; + WHEN vRandIndex = 2 THEN + SET vPwd = CONCAT(vPwd, SUBSTRING(vUpperChars, FLOOR((RAND() * 26) + 1), 1)); + SET vUpper = vUpper + 1; + WHEN vRandIndex = 3 THEN + SET vPwd = CONCAT(vPwd, SUBSTRING(vDigitChars, FLOOR((RAND() * 10) + 1), 1)); + SET vDigits = vDigits + 1; + WHEN vRandIndex = 4 THEN + SET vPwd = CONCAT(vPwd, SUBSTRING(vPunctChars, FLOOR((RAND() * LENGTH(vPunctChars)) + 1), 1)); + SET vPunct = vPunct + 1; + END CASE; + END WHILE; + RETURN vPwd; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -881,23 +883,23 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `user_getMysqlRole`(vUserName VARCHAR(255)) RETURNS varchar(255) CHARSET utf8 COLLATE utf8_unicode_ci DETERMINISTIC -BEGIN -/** - * From a username, it returns the associated MySQL wich should be used when - * using external authentication systems. - * - * @param vUserName The user name - * @return The associated MySQL role - */ - DECLARE vRole VARCHAR(255); - - SELECT CONCAT(IF(r.hasLogin, c.rolePrefix, ''), r.name) INTO vRole - FROM role r - JOIN user u ON u.role = r.id - JOIN roleConfig c - WHERE u.name = vUserName; - - RETURN vRole; +BEGIN +/** + * From a username, it returns the associated MySQL wich should be used when + * using external authentication systems. + * + * @param vUserName The user name + * @return The associated MySQL role + */ + DECLARE vRole VARCHAR(255); + + SELECT CONCAT(IF(r.hasLogin, c.rolePrefix, ''), r.name) INTO vRole + FROM role r + JOIN user u ON u.role = r.id + JOIN roleConfig c + WHERE u.name = vUserName; + + RETURN vRole; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -916,20 +918,20 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `user_getNameFromId`(vSelf INT) RETURNS varchar(30) CHARSET utf8 COLLATE utf8_unicode_ci DETERMINISTIC -BEGIN -/** - * Gets user name from it's id. - * - * @param vSelf The user id - * @return The user name - */ - DECLARE vName VARCHAR(30); - - SELECT `name` INTO vName - FROM user - WHERE id = vSelf; - - RETURN vName; +BEGIN +/** + * Gets user name from it's id. + * + * @param vSelf The user id + * @return The user name + */ + DECLARE vName VARCHAR(30); + + SELECT `name` INTO vName + FROM user + WHERE id = vSelf; + + RETURN vName; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -3869,21 +3871,21 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `carteras_add2`() -BEGIN -/** - * Inserta en "bs.carteras". - */ - DELETE FROM bs.carteras - WHERE Año >= YEAR(CURDATE()) - 1; - - INSERT INTO bs.carteras(Año,Mes,CodigoTrabajador,Peso) - SELECT t.year AS Año, t.month AS Mes, w.code AS CodigoTrabajador, SUM(v.importe) AS Peso - FROM vn.time t - JOIN bs.ventas v on t.dated = v.fecha - JOIN vn.client c on c.id = v.Id_Cliente - JOIN vn.worker w ON w.id = c.salesPersonFk - WHERE t.year >= YEAR(CURDATE()) - 1 - GROUP BY w.code, t.year , t.month; +BEGIN +/** + * Inserta en "bs.carteras". + */ + DELETE FROM bs.carteras + WHERE Año >= YEAR(CURDATE()) - 1; + + INSERT INTO bs.carteras(Año,Mes,CodigoTrabajador,Peso) + SELECT t.year AS Año, t.month AS Mes, w.code AS CodigoTrabajador, SUM(v.importe) AS Peso + FROM vn.time t + JOIN bs.ventas v on t.dated = v.fecha + JOIN vn.client c on c.id = v.Id_Cliente + JOIN vn.worker w ON w.id = c.salesPersonFk + WHERE t.year >= YEAR(CURDATE()) - 1 + GROUP BY w.code, t.year , t.month; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -6326,22 +6328,25 @@ BEGIN */ DECLARE vStarted DATE DEFAULT DATE_FORMAT(DATE_ADD(CURDATE(), INTERVAL -17 MONTH), '%Y-%m-01'); - DELETE v - FROM vendedores v - JOIN vn.`time` t ON t.`year` = v.año AND t.`month` = v.mes - WHERE t.dated BETWEEN vStarted AND CURDATE(); - - INSERT INTO vendedores(Id_Trabajador, año, mes, portfolioWeight) - SELECT c.lastSalesPersonFk - , t.`year` - , t.`month` - , SUM(v.importe) - FROM vn.`time` t - STRAIGHT_JOIN bs.ventas v ON t.dated = v.fecha - JOIN vn.`client` c ON c.id = v.Id_Cliente - WHERE c.lastSalesPersonFk IS NOT NULL - AND v.fecha BETWEEN vStarted AND CURDATE() - GROUP BY c.lastSalesPersonFk, t.`month`, t.`year`; + UPDATE vendedores v + JOIN vn.`time` t ON t.`year` = v.año AND t.`month` = v.mes + SET v.portfolioWeight = NULL + WHERE t.dated BETWEEN vStarted AND CURDATE(); + + UPDATE vendedores v + JOIN ( + SELECT c.lastSalesPersonFk + , t.`year` + , t.`month` + , SUM(v.importe) importe + FROM vn.`time` t + STRAIGHT_JOIN bs.ventas v ON t.dated = v.fecha + JOIN vn.`client` c ON c.id = v.Id_Cliente + WHERE c.lastSalesPersonFk IS NOT NULL + AND v.fecha BETWEEN vStarted AND CURDATE() + GROUP BY c.lastSalesPersonFk, t.`year`, t.`month` + ) sub ON sub.lastSalesPersonFk = v.Id_Trabajador AND sub.`year` = v.año AND sub.`month`= v.mes + SET v.portfolioWeight = sub.importe; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -6478,104 +6483,104 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ventas_contables_add`(IN vYear INT, IN vMonth INT) -BEGIN - - /** - * Reemplaza las ventas contables del último año. - * Es el origen de datos para el balance de Entradas - * - * @param vYear Año a reemplazar - * @param vMonth Mes a reemplazar - * - **/ - - DECLARE TIPO_PATRIMONIAL INT DEFAULT 188; - - DELETE FROM bs.ventas_contables - WHERE year = vYear - AND month = vMonth; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; - CREATE TEMPORARY TABLE tmp.ticket_list - (PRIMARY KEY (Id_Ticket)) - ENGINE = MEMORY - SELECT Id_Ticket - FROM vn2008.Tickets t - JOIN vn2008.Facturas f ON f.Id_Factura = t.Factura - WHERE year(f.Fecha) = vYear - AND month(f.Fecha) = vMonth; - - INSERT INTO bs.ventas_contables(year - , month - , venta - , grupo - , reino_id - , tipo_id - , empresa_id - , gasto) - - SELECT vYear - , vMonth - , round(sum(Cantidad * Preu * (100 - m.Descuento)/100)) - , IF( - e.empresa_grupo = e2.empresa_grupo - ,1 - ,IF(e2.empresa_grupo,2,0) - ) as grupo - , tp.reino_id - , a.tipo_id - , t.empresa_id - , 7000000000 - + IF(e.empresa_grupo = e2.empresa_grupo - ,1 - ,IF(e2.empresa_grupo,2,0) - ) * 1000000 - + tp.reino_id * 10000 as Gasto - FROM vn2008.Movimientos m - JOIN vn2008.Tickets t on t.Id_Ticket = m.Id_Ticket - JOIN vn2008.Consignatarios cs on cs.Id_Consigna = t.Id_Consigna - JOIN vn2008.Clientes c on c.Id_Cliente = cs.Id_Cliente - JOIN tmp.ticket_list tt on tt.Id_Ticket = t.Id_Ticket - JOIN vn2008.Articles a on m.Id_Article = a.Id_Article - JOIN vn2008.empresa e on e.id = t.empresa_id - LEFT JOIN vn2008.empresa e2 on e2.Id_Cliente = c.Id_Cliente - JOIN vn2008.Tipos tp on tp.tipo_id = a.tipo_id - WHERE Cantidad <> 0 - AND Preu <> 0 - AND m.Descuento <> 100 - AND a.tipo_id != TIPO_PATRIMONIAL - GROUP BY grupo, reino_id, tipo_id, empresa_id, Gasto; - - INSERT INTO bs.ventas_contables(year - , month - , venta - , grupo - , reino_id - , tipo_id - , empresa_id - , gasto) - SELECT vYear - , vMonth - , sum(ts.quantity * ts.price) - , IF( - c.companyGroupFk = c2.companyGroupFk - ,1 - ,IF(c2.companyGroupFk, 2, 0) - ) as grupo - , NULL - , NULL - , t.companyFk - , 7050000000 - FROM vn.ticketService ts - JOIN vn.ticket t ON ts.ticketFk = t.id - JOIN vn.address a on a.id = t.addressFk - JOIN vn.client cl on cl.id = a.clientFk - JOIN tmp.ticket_list tt on tt.Id_Ticket = t.id - JOIN vn.company c on c.id = t.companyFk - LEFT JOIN vn.company c2 on c2.clientFk = cl.id - GROUP BY grupo, t.companyFk ; - - DROP TEMPORARY TABLE tmp.ticket_list; +BEGIN + + /** + * Reemplaza las ventas contables del último año. + * Es el origen de datos para el balance de Entradas + * + * @param vYear Año a reemplazar + * @param vMonth Mes a reemplazar + * + **/ + + DECLARE TIPO_PATRIMONIAL INT DEFAULT 188; + + DELETE FROM bs.ventas_contables + WHERE year = vYear + AND month = vMonth; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; + CREATE TEMPORARY TABLE tmp.ticket_list + (PRIMARY KEY (Id_Ticket)) + ENGINE = MEMORY + SELECT Id_Ticket + FROM vn2008.Tickets t + JOIN vn2008.Facturas f ON f.Id_Factura = t.Factura + WHERE year(f.Fecha) = vYear + AND month(f.Fecha) = vMonth; + + INSERT INTO bs.ventas_contables(year + , month + , venta + , grupo + , reino_id + , tipo_id + , empresa_id + , gasto) + + SELECT vYear + , vMonth + , round(sum(Cantidad * Preu * (100 - m.Descuento)/100)) + , IF( + e.empresa_grupo = e2.empresa_grupo + ,1 + ,IF(e2.empresa_grupo,2,0) + ) as grupo + , tp.reino_id + , a.tipo_id + , t.empresa_id + , 7000000000 + + IF(e.empresa_grupo = e2.empresa_grupo + ,1 + ,IF(e2.empresa_grupo,2,0) + ) * 1000000 + + tp.reino_id * 10000 as Gasto + FROM vn2008.Movimientos m + JOIN vn2008.Tickets t on t.Id_Ticket = m.Id_Ticket + JOIN vn2008.Consignatarios cs on cs.Id_Consigna = t.Id_Consigna + JOIN vn2008.Clientes c on c.Id_Cliente = cs.Id_Cliente + JOIN tmp.ticket_list tt on tt.Id_Ticket = t.Id_Ticket + JOIN vn2008.Articles a on m.Id_Article = a.Id_Article + JOIN vn2008.empresa e on e.id = t.empresa_id + LEFT JOIN vn2008.empresa e2 on e2.Id_Cliente = c.Id_Cliente + JOIN vn2008.Tipos tp on tp.tipo_id = a.tipo_id + WHERE Cantidad <> 0 + AND Preu <> 0 + AND m.Descuento <> 100 + AND a.tipo_id != TIPO_PATRIMONIAL + GROUP BY grupo, reino_id, tipo_id, empresa_id, Gasto; + + INSERT INTO bs.ventas_contables(year + , month + , venta + , grupo + , reino_id + , tipo_id + , empresa_id + , gasto) + SELECT vYear + , vMonth + , sum(ts.quantity * ts.price) + , IF( + c.companyGroupFk = c2.companyGroupFk + ,1 + ,IF(c2.companyGroupFk, 2, 0) + ) as grupo + , NULL + , NULL + , t.companyFk + , 7050000000 + FROM vn.ticketService ts + JOIN vn.ticket t ON ts.ticketFk = t.id + JOIN vn.address a on a.id = t.addressFk + JOIN vn.client cl on cl.id = a.clientFk + JOIN tmp.ticket_list tt on tt.Id_Ticket = t.id + JOIN vn.company c on c.id = t.companyFk + LEFT JOIN vn.company c2 on c2.clientFk = cl.id + GROUP BY grupo, t.companyFk ; + + DROP TEMPORARY TABLE tmp.ticket_list; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -6886,33 +6891,33 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `waste_addSales_lastWeek__`() -BEGIN - DECLARE vWeek INT; - DECLARE vYear INT; - - SELECT week, year - INTO vWeek, vYear - FROM vn.time - WHERE dated = TIMESTAMPADD(WEEK, -1, CURDATE()); - - REPLACE bs.waste - SELECT *, 100 * mermas / total as porcentaje - FROM ( - SELECT buyer, - year, - week, - family, - itemFk, - itemTypeFk, - floor(sum(value)) as total, - floor(sum(IF(clientTypeFk = 'loses', value, 0))) as mermas - FROM vn.saleValue - where year = vYear and week = vWeek - - GROUP BY family, itemFk - - ) sub - ORDER BY mermas DESC; +BEGIN + DECLARE vWeek INT; + DECLARE vYear INT; + + SELECT week, year + INTO vWeek, vYear + FROM vn.time + WHERE dated = TIMESTAMPADD(WEEK, -1, CURDATE()); + + REPLACE bs.waste + SELECT *, 100 * mermas / total as porcentaje + FROM ( + SELECT buyer, + year, + week, + family, + itemFk, + itemTypeFk, + floor(sum(value)) as total, + floor(sum(IF(clientTypeFk = 'loses', value, 0))) as mermas + FROM vn.saleValue + where year = vYear and week = vWeek + + GROUP BY family, itemFk + + ) sub + ORDER BY mermas DESC; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -7639,146 +7644,146 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `availableNoRaids_refresh`(OUT `vCalc` INT, IN `vRefresh` INT, IN `vWarehouse` INT, IN `vDate` DATE) -proc: BEGIN - DECLARE vStartDate DATE; - DECLARE vEndDate DATETIME; - DECLARE vReserveDate DATETIME; - DECLARE vParams CHAR(100); - DECLARE vInventoryDate DATE; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - CALL cache_calc_unlock (vCalc); - RESIGNAL; - END; - - IF vDate < CURDATE() THEN - LEAVE proc; - END IF; - - CALL vn.itemStock (vWarehouse, vDate, NULL); - - SET vParams = CONCAT_WS('/', vWarehouse, vDate); - CALL cache_calc_start (vCalc, vRefresh, 'availableNoRaids', vParams); - - IF !vRefresh THEN - LEAVE proc; - END IF; - - -- Calcula algunos parámetros necesarios - - SET vStartDate = TIMESTAMP(vDate, '00:00:00'); - SET vEndDate = TIMESTAMP(TIMESTAMPADD(DAY, 4, vDate), '23:59:59'); - - SELECT inventoried INTO vInventoryDate FROM vn.config; - - SELECT SUBTIME(NOW(), reserveTime) INTO vReserveDate - FROM hedera.orderConfig; - - -- Calcula el ultimo dia de vida para cada producto - - DROP TEMPORARY TABLE IF EXISTS item_range; - CREATE TEMPORARY TABLE item_range - (PRIMARY KEY (item_id)) - ENGINE = MEMORY - SELECT c.item_id, IF(it.life IS NULL, NULL, - TIMESTAMP(TIMESTAMPADD(DAY, it.life, c.landing), '23:59:59')) AS date_end - FROM ( - SELECT b.itemFk item_id, MAX(t.landed) landing - FROM vn.buy b - JOIN vn.entry e ON b.entryFk = e.id - JOIN vn.travel t ON t.id = e.travelFk - JOIN vn.warehouse w ON w.id = t.warehouseInFk - WHERE t.landed BETWEEN vInventoryDate AND vStartDate - AND t.warehouseInFk = vWarehouse - AND NOT e.isInventory - AND NOT e.isRaid - GROUP BY b.itemFk - ) c - JOIN vn.item i ON i.id = c.item_id - JOIN vn.itemType it ON it.id = i.typeFk - HAVING date_end >= vStartDate OR date_end IS NULL; - - -- Replica la tabla item_range para poder usarla varias veces en la misma consulta - - DROP TEMPORARY TABLE IF EXISTS item_range_copy1; - CREATE TEMPORARY TABLE item_range_copy1 LIKE item_range; - INSERT INTO item_range_copy1 - SELECT * FROM item_range; - - DROP TEMPORARY TABLE IF EXISTS item_range_copy2; - CREATE TEMPORARY TABLE item_range_copy2 LIKE item_range; - INSERT INTO item_range_copy2 - SELECT * FROM item_range; - - DROP TEMPORARY TABLE IF EXISTS item_range_copy3; - CREATE TEMPORARY TABLE item_range_copy3 LIKE item_range; - INSERT INTO item_range_copy3 - SELECT * FROM item_range; - - DROP TEMPORARY TABLE IF EXISTS item_range_copy4; - CREATE TEMPORARY TABLE item_range_copy4 LIKE item_range; - INSERT INTO item_range_copy4 - SELECT * FROM item_range; - - -- Calcula el ATP - - DELETE FROM availableNoRaids WHERE calc_id = vCalc; - - INSERT INTO availableNoRaids (calc_id, item_id, available) - SELECT vCalc, t.item_id, SUM(stock) amount FROM ( - SELECT il.itemFk AS item_id, stock - FROM tmp.itemList il - JOIN item_range ir ON ir.item_id = il.itemFk - UNION ALL - SELECT t.item_id, minacum(dt, amount, vDate) AS available FROM ( - SELECT itemFk AS item_id, DATE(dat) dt, SUM(quantity) amount FROM ( - SELECT i.itemFk, i.shipped AS dat, i.quantity - FROM vn.itemTicketOut i - JOIN item_range_copy1 ir ON ir.item_id = i.itemFk - WHERE i.shipped >= vStartDate - AND (ir.date_end IS NULL OR i.shipped <= ir.date_end) - AND i.warehouseFk = vWarehouse - UNION ALL - SELECT i.itemFk, i.landed AS dat, i.quantity - FROM vn.itemEntryIn i - JOIN item_range_copy2 ir ON ir.item_id = i.itemFk - WHERE i.landed >= vStartDate - AND (ir.date_end IS NULL OR i.landed <= ir.date_end) - AND i.warehouseInFk = vWarehouse - AND i.isVirtualStock = FALSE - UNION ALL - SELECT i.itemFk, i.shipped AS dat, i.quantity - FROM vn.itemEntryOut i - JOIN item_range_copy3 ir ON ir.item_id = i.itemFk - WHERE i.shipped >= vStartDate - AND (ir.date_end IS NULL OR i.shipped <= ir.date_end) - AND i.warehouseOutFk = vWarehouse - UNION ALL - SELECT r.item_id, r.shipment, -r.amount - FROM hedera.order_row r - JOIN hedera.`order` o ON o.id = r.order_id - JOIN item_range_copy4 ir ON ir.item_id = r.item_id - WHERE r.shipment >= vStartDate - AND (ir.date_end IS NULL OR r.shipment <= ir.date_end) - AND r.warehouse_id = vWarehouse - AND r.created >= vReserveDate - AND NOT o.confirmed - ) t - GROUP BY item_id, dt - ) t - GROUP BY t.item_id - ) t GROUP BY t.item_id; - - DROP TEMPORARY TABLE IF EXISTS - tmp.itemList - ,item_range - ,item_range_copy1 - ,item_range_copy2 - ,item_range_copy3 - ,item_range_copy4; - - CALL cache_calc_end (vCalc); +proc: BEGIN + DECLARE vStartDate DATE; + DECLARE vEndDate DATETIME; + DECLARE vReserveDate DATETIME; + DECLARE vParams CHAR(100); + DECLARE vInventoryDate DATE; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + CALL cache_calc_unlock (vCalc); + RESIGNAL; + END; + + IF vDate < CURDATE() THEN + LEAVE proc; + END IF; + + CALL vn.itemStock (vWarehouse, vDate, NULL); + + SET vParams = CONCAT_WS('/', vWarehouse, vDate); + CALL cache_calc_start (vCalc, vRefresh, 'availableNoRaids', vParams); + + IF !vRefresh THEN + LEAVE proc; + END IF; + + -- Calcula algunos parámetros necesarios + + SET vStartDate = TIMESTAMP(vDate, '00:00:00'); + SET vEndDate = TIMESTAMP(TIMESTAMPADD(DAY, 4, vDate), '23:59:59'); + + SELECT inventoried INTO vInventoryDate FROM vn.config; + + SELECT SUBTIME(NOW(), reserveTime) INTO vReserveDate + FROM hedera.orderConfig; + + -- Calcula el ultimo dia de vida para cada producto + + DROP TEMPORARY TABLE IF EXISTS item_range; + CREATE TEMPORARY TABLE item_range + (PRIMARY KEY (item_id)) + ENGINE = MEMORY + SELECT c.item_id, IF(it.life IS NULL, NULL, + TIMESTAMP(TIMESTAMPADD(DAY, it.life, c.landing), '23:59:59')) AS date_end + FROM ( + SELECT b.itemFk item_id, MAX(t.landed) landing + FROM vn.buy b + JOIN vn.entry e ON b.entryFk = e.id + JOIN vn.travel t ON t.id = e.travelFk + JOIN vn.warehouse w ON w.id = t.warehouseInFk + WHERE t.landed BETWEEN vInventoryDate AND vStartDate + AND t.warehouseInFk = vWarehouse + AND NOT e.isInventory + AND NOT e.isRaid + GROUP BY b.itemFk + ) c + JOIN vn.item i ON i.id = c.item_id + JOIN vn.itemType it ON it.id = i.typeFk + HAVING date_end >= vStartDate OR date_end IS NULL; + + -- Replica la tabla item_range para poder usarla varias veces en la misma consulta + + DROP TEMPORARY TABLE IF EXISTS item_range_copy1; + CREATE TEMPORARY TABLE item_range_copy1 LIKE item_range; + INSERT INTO item_range_copy1 + SELECT * FROM item_range; + + DROP TEMPORARY TABLE IF EXISTS item_range_copy2; + CREATE TEMPORARY TABLE item_range_copy2 LIKE item_range; + INSERT INTO item_range_copy2 + SELECT * FROM item_range; + + DROP TEMPORARY TABLE IF EXISTS item_range_copy3; + CREATE TEMPORARY TABLE item_range_copy3 LIKE item_range; + INSERT INTO item_range_copy3 + SELECT * FROM item_range; + + DROP TEMPORARY TABLE IF EXISTS item_range_copy4; + CREATE TEMPORARY TABLE item_range_copy4 LIKE item_range; + INSERT INTO item_range_copy4 + SELECT * FROM item_range; + + -- Calcula el ATP + + DELETE FROM availableNoRaids WHERE calc_id = vCalc; + + INSERT INTO availableNoRaids (calc_id, item_id, available) + SELECT vCalc, t.item_id, SUM(stock) amount FROM ( + SELECT il.itemFk AS item_id, stock + FROM tmp.itemList il + JOIN item_range ir ON ir.item_id = il.itemFk + UNION ALL + SELECT t.item_id, minacum(dt, amount, vDate) AS available FROM ( + SELECT itemFk AS item_id, DATE(dat) dt, SUM(quantity) amount FROM ( + SELECT i.itemFk, i.shipped AS dat, i.quantity + FROM vn.itemTicketOut i + JOIN item_range_copy1 ir ON ir.item_id = i.itemFk + WHERE i.shipped >= vStartDate + AND (ir.date_end IS NULL OR i.shipped <= ir.date_end) + AND i.warehouseFk = vWarehouse + UNION ALL + SELECT i.itemFk, i.landed AS dat, i.quantity + FROM vn.itemEntryIn i + JOIN item_range_copy2 ir ON ir.item_id = i.itemFk + WHERE i.landed >= vStartDate + AND (ir.date_end IS NULL OR i.landed <= ir.date_end) + AND i.warehouseInFk = vWarehouse + AND i.isVirtualStock = FALSE + UNION ALL + SELECT i.itemFk, i.shipped AS dat, i.quantity + FROM vn.itemEntryOut i + JOIN item_range_copy3 ir ON ir.item_id = i.itemFk + WHERE i.shipped >= vStartDate + AND (ir.date_end IS NULL OR i.shipped <= ir.date_end) + AND i.warehouseOutFk = vWarehouse + UNION ALL + SELECT r.item_id, r.shipment, -r.amount + FROM hedera.order_row r + JOIN hedera.`order` o ON o.id = r.order_id + JOIN item_range_copy4 ir ON ir.item_id = r.item_id + WHERE r.shipment >= vStartDate + AND (ir.date_end IS NULL OR r.shipment <= ir.date_end) + AND r.warehouse_id = vWarehouse + AND r.created >= vReserveDate + AND NOT o.confirmed + ) t + GROUP BY item_id, dt + ) t + GROUP BY t.item_id + ) t GROUP BY t.item_id; + + DROP TEMPORARY TABLE IF EXISTS + tmp.itemList + ,item_range + ,item_range_copy1 + ,item_range_copy2 + ,item_range_copy3 + ,item_range_copy4; + + CALL cache_calc_end (vCalc); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -8022,27 +8027,27 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `cache_calc_end`(IN `v_calc` INT) -BEGIN - DECLARE v_cache_name VARCHAR(255); - DECLARE v_params VARCHAR(255); - - -- Libera el bloqueo y actualiza la fecha de ultimo refresco. - - UPDATE cache_calc cc JOIN cache c ON c.id = cc.cache_id - SET - cc.last_refresh = NOW(), - cc.expires = LEAST(ADDTIME(NOW(), c.lifetime), util.midNight()), - cc.connection_id = NULL - WHERE cc.id = v_calc; - - SELECT c.name, ca.params INTO v_cache_name, v_params - FROM cache c - JOIN cache_calc ca ON c.id = ca.cache_id - WHERE ca.id = v_calc; - - IF v_cache_name IS NOT NULL THEN - DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, ''))); - END IF; +BEGIN + DECLARE v_cache_name VARCHAR(255); + DECLARE v_params VARCHAR(255); + + -- Libera el bloqueo y actualiza la fecha de ultimo refresco. + + UPDATE cache_calc cc JOIN cache c ON c.id = cc.cache_id + SET + cc.last_refresh = NOW(), + cc.expires = LEAST(ADDTIME(NOW(), c.lifetime), util.midNight()), + cc.connection_id = NULL + WHERE cc.id = v_calc; + + SELECT c.name, ca.params INTO v_cache_name, v_params + FROM cache c + JOIN cache_calc ca ON c.id = ca.cache_id + WHERE ca.id = v_calc; + + IF v_cache_name IS NOT NULL THEN + DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, ''))); + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -8060,88 +8065,88 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `cache_calc_start`(OUT `v_calc` INT, INOUT `v_refresh` INT, IN `v_cache_name` VARCHAR(50), IN `v_params` VARCHAR(100)) -proc: BEGIN - DECLARE v_valid BOOL; - DECLARE v_lock_id VARCHAR(100); - DECLARE v_cache_id INT; - DECLARE v_expires DATETIME; - DECLARE v_clean_time DATETIME; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - IF v_lock_id IS NOT NULL THEN - DO RELEASE_LOCK(v_lock_id); - END IF; - - RESIGNAL; - END; - - SET v_params = IFNULL(v_params, ''); - - -- Si el servidor se ha reiniciado invalida todos los calculos. - - SELECT COUNT(*) > 0 INTO v_valid FROM cache_valid; - - IF !v_valid - THEN - DELETE FROM cache_calc; - INSERT INTO cache_valid (valid) VALUES (TRUE); - END IF; - - -- Obtiene un bloqueo exclusivo para que no haya problemas de concurrencia. - - SET v_lock_id = CONCAT_WS('/', v_cache_name, v_params); - - IF !GET_LOCK(v_lock_id, 30) - THEN - SET v_calc = NULL; - SET v_refresh = FALSE; - LEAVE proc; - END IF; - - -- Comprueba si el calculo solicitado existe y esta actualizado. - - SELECT c.id, ca.id, ca.expires - INTO v_cache_id, v_calc, v_expires - FROM cache c - LEFT JOIN cache_calc ca - ON ca.cache_id = c.id AND ca.params = v_params COLLATE 'utf8_general_ci' - WHERE c.name = v_cache_name COLLATE 'utf8_general_ci'; - - -- Si existe una calculo valido libera el bloqueo y devuelve su identificador. - - IF !v_refresh AND NOW() < v_expires - THEN - DO RELEASE_LOCK(v_lock_id); - SET v_refresh = FALSE; - LEAVE proc; - END IF; - - -- Si el calculo no existe le crea una entrada en la tabla de calculos. - - IF v_calc IS NULL - THEN - INSERT INTO cache_calc SET - cache_id = v_cache_id, - cacheName = v_cache_name, - params = v_params, - last_refresh = NULL, - expires = NULL, - connection_id = CONNECTION_ID(); - - SET v_calc = LAST_INSERT_ID(); - ELSE - UPDATE cache_calc - SET - last_refresh = NULL, - expires = NULL, - connection_id = CONNECTION_ID() - WHERE id = v_calc; - END IF; - - -- Si se debe recalcular mantiene el bloqueo y devuelve su identificador. - - SET v_refresh = TRUE; +proc: BEGIN + DECLARE v_valid BOOL; + DECLARE v_lock_id VARCHAR(100); + DECLARE v_cache_id INT; + DECLARE v_expires DATETIME; + DECLARE v_clean_time DATETIME; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + IF v_lock_id IS NOT NULL THEN + DO RELEASE_LOCK(v_lock_id); + END IF; + + RESIGNAL; + END; + + SET v_params = IFNULL(v_params, ''); + + -- Si el servidor se ha reiniciado invalida todos los calculos. + + SELECT COUNT(*) > 0 INTO v_valid FROM cache_valid; + + IF !v_valid + THEN + DELETE FROM cache_calc; + INSERT INTO cache_valid (valid) VALUES (TRUE); + END IF; + + -- Obtiene un bloqueo exclusivo para que no haya problemas de concurrencia. + + SET v_lock_id = CONCAT_WS('/', v_cache_name, v_params); + + IF !GET_LOCK(v_lock_id, 30) + THEN + SET v_calc = NULL; + SET v_refresh = FALSE; + LEAVE proc; + END IF; + + -- Comprueba si el calculo solicitado existe y esta actualizado. + + SELECT c.id, ca.id, ca.expires + INTO v_cache_id, v_calc, v_expires + FROM cache c + LEFT JOIN cache_calc ca + ON ca.cache_id = c.id AND ca.params = v_params COLLATE 'utf8_general_ci' + WHERE c.name = v_cache_name COLLATE 'utf8_general_ci'; + + -- Si existe una calculo valido libera el bloqueo y devuelve su identificador. + + IF !v_refresh AND NOW() < v_expires + THEN + DO RELEASE_LOCK(v_lock_id); + SET v_refresh = FALSE; + LEAVE proc; + END IF; + + -- Si el calculo no existe le crea una entrada en la tabla de calculos. + + IF v_calc IS NULL + THEN + INSERT INTO cache_calc SET + cache_id = v_cache_id, + cacheName = v_cache_name, + params = v_params, + last_refresh = NULL, + expires = NULL, + connection_id = CONNECTION_ID(); + + SET v_calc = LAST_INSERT_ID(); + ELSE + UPDATE cache_calc + SET + last_refresh = NULL, + expires = NULL, + connection_id = CONNECTION_ID() + WHERE id = v_calc; + END IF; + + -- Si se debe recalcular mantiene el bloqueo y devuelve su identificador. + + SET v_refresh = TRUE; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -8159,24 +8164,24 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `cache_calc_unlock`(IN `v_calc` INT) -proc: BEGIN - DECLARE v_cache_name VARCHAR(50); - DECLARE v_params VARCHAR(100); - - IF v_calc IS NULL THEN - LEAVE proc; - END IF; - - SELECT c.name, ca.params INTO v_cache_name, v_params - FROM cache c - JOIN cache_calc ca ON c.id = ca.cache_id - WHERE ca.id = v_calc; - - DELETE FROM cache_calc WHERE id = v_calc; - - IF v_cache_name IS NOT NULL THEN - DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, ''))); - END IF; +proc: BEGIN + DECLARE v_cache_name VARCHAR(50); + DECLARE v_params VARCHAR(100); + + IF v_calc IS NULL THEN + LEAVE proc; + END IF; + + SELECT c.name, ca.params INTO v_cache_name, v_params + FROM cache c + JOIN cache_calc ca ON c.id = ca.cache_id + WHERE ca.id = v_calc; + + DELETE FROM cache_calc WHERE id = v_calc; + + IF v_cache_name IS NOT NULL THEN + DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, ''))); + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -8215,13 +8220,13 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `clean`() -BEGIN - - DECLARE vDateShort DATETIME; - - SET vDateShort = TIMESTAMPADD(MONTH, -1, CURDATE()); - - DELETE FROM cache.departure_limit WHERE Fecha < vDateShort; +BEGIN + + DECLARE vDateShort DATETIME; + + SET vDateShort = TIMESTAMPADD(MONTH, -1, CURDATE()); + + DELETE FROM cache.departure_limit WHERE Fecha < vDateShort; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -9754,6 +9759,61 @@ CREATE TABLE `supplier` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='/tmp/floricode/FEC010104/CC090916.txt'; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Temporary table structure for view `supplyOffer` +-- + +DROP TABLE IF EXISTS `supplyOffer`; +/*!50001 DROP VIEW IF EXISTS `supplyOffer`*/; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +/*!50001 CREATE TABLE `supplyOffer` ( + `vmpID` tinyint NOT NULL, + `diId` tinyint NOT NULL, + `srId` tinyint NOT NULL, + `Item_ArticleCode` tinyint NOT NULL, + `product_name` tinyint NOT NULL, + `company_name` tinyint NOT NULL, + `Price` tinyint NOT NULL, + `Quality` tinyint NOT NULL, + `s1` tinyint NOT NULL, + `s2` tinyint NOT NULL, + `s3` tinyint NOT NULL, + `s4` tinyint NOT NULL, + `s5` tinyint NOT NULL, + `s6` tinyint NOT NULL, + `NumberOfUnits` tinyint NOT NULL, + `EmbalageCode` tinyint NOT NULL, + `LatestDeliveryDateTime` tinyint NOT NULL, + `EarliestDespatchDateTime` tinyint NOT NULL, + `FirstOrderDateTime` tinyint NOT NULL, + `LatestOrderDateTime` tinyint NOT NULL, + `NumberOfItemsPerCask` tinyint NOT NULL, + `NumberOfLayersPerTrolley` tinyint NOT NULL, + `MinimumNumberToOrder` tinyint NOT NULL, + `MaximumNumberToOrder` tinyint NOT NULL, + `IncrementalOrderableQuantity` tinyint NOT NULL, + `PackingPrice` tinyint NOT NULL, + `MarketPlaceID` tinyint NOT NULL, + `PictureReference` tinyint NOT NULL, + `supplyResponseUpdated` tinyint NOT NULL, + `group_id` tinyint NOT NULL, + `marketPlace` tinyint NOT NULL, + `DeliveryPrice` tinyint NOT NULL, + `ChargeAmount` tinyint NOT NULL, + `MinimumQuantity` tinyint NOT NULL, + `MaximumQuantity` tinyint NOT NULL, + `OrderUnit` tinyint NOT NULL, + `IncrementalOrderUnit` tinyint NOT NULL, + `isEarlyBird` tinyint NOT NULL, + `isVNHSupplier` tinyint NOT NULL, + `expenseFk` tinyint NOT NULL, + `intrastatFk` tinyint NOT NULL, + `originFk` tinyint NOT NULL, + `itemTypeFk` tinyint NOT NULL +) ENGINE=MyISAM */; +SET character_set_client = @saved_cs_client; + -- -- Table structure for table `supplyResponse` -- @@ -9980,22 +10040,22 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `imageName`(vPictureReference VARCHAR(255)) RETURNS varchar(255) CHARSET utf8 COLLATE utf8_unicode_ci DETERMINISTIC -BEGIN - - SET vPictureReference = REPLACE(vPictureReference,'.',''); - - SET vPictureReference = REPLACE(vPictureReference,'/',''); - - SET vPictureReference = REPLACE(vPictureReference,'%',''); - - SET vPictureReference = REPLACE(vPictureReference,':',''); - - SET vPictureReference = REPLACE(vPictureReference,'?',''); - - SET vPictureReference = REPLACE(vPictureReference,'=',''); - - RETURN vPictureReference; - +BEGIN + + SET vPictureReference = REPLACE(vPictureReference,'.',''); + + SET vPictureReference = REPLACE(vPictureReference,'/',''); + + SET vPictureReference = REPLACE(vPictureReference,'%',''); + + SET vPictureReference = REPLACE(vPictureReference,':',''); + + SET vPictureReference = REPLACE(vPictureReference,'?',''); + + SET vPictureReference = REPLACE(vPictureReference,'=',''); + + RETURN vPictureReference; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -10045,28 +10105,28 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `deliveryInformation_Delete`() -BEGIN - - DECLARE vID INT; - DECLARE vGap INT DEFAULT 100; - DECLARE vTope INT; - - SELECT MIN(ID), MAX(ID) - INTO vID, vTope - FROM edi.deliveryInformation; - - WHILE vID <= vTope DO - - SET vID = vID + vGap; - - DELETE - FROM edi.deliveryInformation - WHERE ID < vID - AND EarliestDespatchDateTime IS NULL; - - END WHILE; - - +BEGIN + + DECLARE vID INT; + DECLARE vGap INT DEFAULT 100; + DECLARE vTope INT; + + SELECT MIN(ID), MAX(ID) + INTO vID, vTope + FROM edi.deliveryInformation; + + WHILE vID <= vTope DO + + SET vID = vID + vGap; + + DELETE + FROM edi.deliveryInformation + WHERE ID < vID + AND EarliestDespatchDateTime IS NULL; + + END WHILE; + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -10451,38 +10511,38 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ekt_loadNotBuy`() -BEGIN - - /** - * Ejecuta ekt_load para aquellos ekt de hoy que no tienen vn.buy - */ - - DECLARE vEktFk INTEGER; - DECLARE done BOOL; - - - DECLARE cursor1 CURSOR FOR SELECT e.id - FROM edi.ekt e - LEFT JOIN vn.buy b ON b.ektFk = e.id - WHERE e.fec >= CURDATE() - AND ISNULL(b.ektFk); - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; - - OPEN cursor1; - bucle: LOOP - - FETCH cursor1 INTO vEktFk; - - IF done THEN - LEAVE bucle; - END IF; - - CALL edi.ekt_load(vEktFk); - - END LOOP bucle; - CLOSE cursor1; - +BEGIN + + /** + * Ejecuta ekt_load para aquellos ekt de hoy que no tienen vn.buy + */ + + DECLARE vEktFk INTEGER; + DECLARE done BOOL; + + + DECLARE cursor1 CURSOR FOR SELECT e.id + FROM edi.ekt e + LEFT JOIN vn.buy b ON b.ektFk = e.id + WHERE e.fec >= CURDATE() + AND ISNULL(b.ektFk); + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; + + OPEN cursor1; + bucle: LOOP + + FETCH cursor1 INTO vEktFk; + + IF done THEN + LEAVE bucle; + END IF; + + CALL edi.ekt_load(vEktFk); + + END LOOP bucle; + CLOSE cursor1; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -10709,11 +10769,11 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET character_set_client = 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 = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `floramondo_offerRefresh`() proc: BEGIN @@ -11028,16 +11088,14 @@ proc: BEGIN UPDATE vn.item i JOIN itemToInsert ii ON i.supplyResponseFk = ii.`srId` - JOIN vn.packaging p ON p.id LIKE ii.EmbalageCode AND hasCompressionVariations - JOIN vn.itemTag diameter ON diameter.itemFk = i.id - JOIN vn.tag tDiameter ON tDiameter.overwrite = 'diameter' AND tDiameter.id = diameter.tagFk - JOIN vn.itemTag size ON size.itemFk = i.id - JOIN vn.tag tSize ON tSize.overwrite = 'size' AND tSize.id = size.tagFk - SET i.`compression` = - (PI() * POW(diameter.`value`/ 2, 2) * size.`value`) - / - ((p.width * p.depth * p.height) / ii.NumberOfItemsPerCask); - + JOIN vn.packaging p ON p.id LIKE ii.EmbalageCode -- AND hasCompressionVariations + JOIN vn.itemTag it ON it.itemFk = i.id + JOIN vn.tag tSize ON tSize.overwrite = 'size' AND tSize.id = it.tagFk + JOIN vn.volumeConfig vc + SET i.packingOut = vc.standardFlowerBox * 1000 + * ii.NumberOfItemsPerCask + / (p.width * p.depth * IFNULL(p.height, it.value )); + DROP TABLE IF EXISTS tmp.item; CREATE TABLE tmp.item (PRIMARY KEY (id)) @@ -12148,56 +12206,56 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `item_freeAdd`() -BEGIN - - /** - * Rellena la tabla item_free con los id ausentes en vn.item - * - */ - - DECLARE vCounter INT DEFAULT 400000; - - DECLARE vCounterNewItems INT DEFAULT 0; - - DECLARE vMaxItem INT; - - DECLARE vExists BOOLEAN DEFAULT FALSE; - - SELECT MAX(id) - INTO vMaxItem - FROM vn.item; - - DROP TEMPORARY TABLE IF EXISTS tmp.itemBusy; - CREATE TEMPORARY TABLE tmp.itemBusy - (id INT PRIMARY KEY) - SELECT i.id - FROM vn.item i - WHERE id >= 400000 - UNION ALL - SELECT ifr.id - FROM edi.item_free ifr; - - WHILE vCounter < vMaxItem DO - - SET vCounter = vCounter + 1; - - SELECT count(*) INTO vExists - FROM tmp.itemBusy - WHERE id = vCounter; - - IF NOT vExists THEN - - SET vCounterNewItems = vCounterNewItems + 1; - - INSERT INTO edi.item_free(id) - VALUES (vCounter); - - END IF; - - END WHILE; - - DROP TEMPORARY TABLE tmp.itemBusy; - +BEGIN + + /** + * Rellena la tabla item_free con los id ausentes en vn.item + * + */ + + DECLARE vCounter INT DEFAULT 400000; + + DECLARE vCounterNewItems INT DEFAULT 0; + + DECLARE vMaxItem INT; + + DECLARE vExists BOOLEAN DEFAULT FALSE; + + SELECT MAX(id) + INTO vMaxItem + FROM vn.item; + + DROP TEMPORARY TABLE IF EXISTS tmp.itemBusy; + CREATE TEMPORARY TABLE tmp.itemBusy + (id INT PRIMARY KEY) + SELECT i.id + FROM vn.item i + WHERE id >= 400000 + UNION ALL + SELECT ifr.id + FROM edi.item_free ifr; + + WHILE vCounter < vMaxItem DO + + SET vCounter = vCounter + 1; + + SELECT count(*) INTO vExists + FROM tmp.itemBusy + WHERE id = vCounter; + + IF NOT vExists THEN + + SET vCounterNewItems = vCounterNewItems + 1; + + INSERT INTO edi.item_free(id) + VALUES (vCounter); + + END IF; + + END WHILE; + + DROP TEMPORARY TABLE tmp.itemBusy; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -12460,49 +12518,49 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `orderLog__`(vItemFk INT) -BEGIN - - DECLARE vSupplyResponseFk INT; - DECLARE vDescription VARCHAR(100); - - SELECT supplyResponseFk, CONCAT(id, ' ',longName) INTO vSupplyResponseFk, vDescription - FROM vn.item - WHERE id = vItemFk; - - SELECT * FROM - ( - SELECT 'Cliente confirma' accion, or2.created hora, amount Cantidad - FROM hedera.order_row or2 - JOIN vn.item i ON i.id = or2.item_id - WHERE i.supplyResponseFk = vSupplyResponseFk - - UNION ALL - - SELECT vDescription, NULL, NULL - - UNION ALL - - SELECT 'Cliente se conecta' , o.date_make , NULL - FROM hedera.`order` o - JOIN hedera.order_row or2 ON or2.order_id = o.id - JOIN vn.item i ON i.id = or2.item_id - WHERE i.supplyResponseFk = vSupplyResponseFk - - UNION ALL - - SELECT DISTINCT 'Subasta cambia cantidad', srl.created, srl.NumberOfUnitsNew * sr.NumberOfItemsPerCask - FROM edi.supplyResponseLog srl - JOIN edi.supplyResponse sr ON sr.ID = srl.supplyResponseFk - WHERE srl.supplyResponseFk = vSupplyResponseFk - - UNION ALL - - SELECT 'Linea de venta definitiva', s.created, s.quantity - FROM vn.sale s - JOIN vn.item i ON i.id = s.itemFk - WHERE i.supplyResponseFk = vSupplyResponseFk) sub - ORDER BY hora; - +BEGIN + + DECLARE vSupplyResponseFk INT; + DECLARE vDescription VARCHAR(100); + + SELECT supplyResponseFk, CONCAT(id, ' ',longName) INTO vSupplyResponseFk, vDescription + FROM vn.item + WHERE id = vItemFk; + + SELECT * FROM + ( + SELECT 'Cliente confirma' accion, or2.created hora, amount Cantidad + FROM hedera.order_row or2 + JOIN vn.item i ON i.id = or2.item_id + WHERE i.supplyResponseFk = vSupplyResponseFk + + UNION ALL + + SELECT vDescription, NULL, NULL + + UNION ALL + + SELECT 'Cliente se conecta' , o.date_make , NULL + FROM hedera.`order` o + JOIN hedera.order_row or2 ON or2.order_id = o.id + JOIN vn.item i ON i.id = or2.item_id + WHERE i.supplyResponseFk = vSupplyResponseFk + + UNION ALL + + SELECT DISTINCT 'Subasta cambia cantidad', srl.created, srl.NumberOfUnitsNew * sr.NumberOfItemsPerCask + FROM edi.supplyResponseLog srl + JOIN edi.supplyResponse sr ON sr.ID = srl.supplyResponseFk + WHERE srl.supplyResponseFk = vSupplyResponseFk + + UNION ALL + + SELECT 'Linea de venta definitiva', s.created, s.quantity + FROM vn.sale s + JOIN vn.item i ON i.id = s.itemFk + WHERE i.supplyResponseFk = vSupplyResponseFk) sub + ORDER BY hora; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -12520,55 +12578,55 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_calcCompByFloramondo`(vSelf INT) -BEGIN - - /** - * Recalcula "a pelo" los componentes para un ticket de Floramondo - * - * Pendiente de concretar la solución cuando Logiflora conteste. - * - * @param vSelf Identificador de vn.ticket - */ - - CALL cache.last_buy_refresh(TRUE); - - DELETE sc.* - FROM vn.saleComponent sc - JOIN vn.sale s ON s.id = sc.saleFk - WHERE s.ticketFk = vSelf; - - UPDATE vn.sale s - JOIN vn.item i ON i.id = s.itemFk - JOIN edi.floraHollandConfig fhc - LEFT JOIN cache.last_buy lb ON lb.item_id = i.id - LEFT JOIN vn.buy b ON b.id = lb.buy_id - LEFT JOIN vn.warehouse w ON w.id = lb.warehouse_id AND w.name = 'Floramondo' - SET s.price = b.buyingValue * (1 + fhc.floramondoMargin) - WHERE s.ticketFk = vSelf; - - INSERT INTO vn.saleComponent(saleFk, componentFk, value) - SELECT s.id, c.id, MAX(b.buyingValue) - FROM vn.sale s - JOIN vn.item i ON i.id = s.itemFk - LEFT JOIN cache.last_buy lb ON lb.item_id = i.id - LEFT JOIN vn.buy b ON b.id = lb.buy_id - LEFT JOIN vn.warehouse w ON w.id = lb.warehouse_id AND w.name = 'Floramondo' - JOIN vn.component c ON c.code = 'purchaseValue' - WHERE s.ticketFk = vSelf - GROUP BY s.id; - - INSERT INTO vn.saleComponent(saleFk, componentFk, value) - SELECT s.id, c.id, MAX(b.buyingValue) * fhc.floramondoMargin - FROM vn.sale s - JOIN vn.item i ON i.id = s.itemFk - JOIN edi.floraHollandConfig fhc - LEFT JOIN cache.last_buy lb ON lb.item_id = i.id - LEFT JOIN vn.buy b ON b.id = lb.buy_id - LEFT JOIN vn.warehouse w ON w.id = lb.warehouse_id AND w.name = 'Floramondo' - JOIN vn.component c ON c.code = 'margin' - WHERE s.ticketFk = vSelf - GROUP BY s.id; - +BEGIN + + /** + * Recalcula "a pelo" los componentes para un ticket de Floramondo + * + * Pendiente de concretar la solución cuando Logiflora conteste. + * + * @param vSelf Identificador de vn.ticket + */ + + CALL cache.last_buy_refresh(TRUE); + + DELETE sc.* + FROM vn.saleComponent sc + JOIN vn.sale s ON s.id = sc.saleFk + WHERE s.ticketFk = vSelf; + + UPDATE vn.sale s + JOIN vn.item i ON i.id = s.itemFk + JOIN edi.floraHollandConfig fhc + LEFT JOIN cache.last_buy lb ON lb.item_id = i.id + LEFT JOIN vn.buy b ON b.id = lb.buy_id + LEFT JOIN vn.warehouse w ON w.id = lb.warehouse_id AND w.name = 'Floramondo' + SET s.price = b.buyingValue * (1 + fhc.floramondoMargin) + WHERE s.ticketFk = vSelf; + + INSERT INTO vn.saleComponent(saleFk, componentFk, value) + SELECT s.id, c.id, MAX(b.buyingValue) + FROM vn.sale s + JOIN vn.item i ON i.id = s.itemFk + LEFT JOIN cache.last_buy lb ON lb.item_id = i.id + LEFT JOIN vn.buy b ON b.id = lb.buy_id + LEFT JOIN vn.warehouse w ON w.id = lb.warehouse_id AND w.name = 'Floramondo' + JOIN vn.component c ON c.code = 'purchaseValue' + WHERE s.ticketFk = vSelf + GROUP BY s.id; + + INSERT INTO vn.saleComponent(saleFk, componentFk, value) + SELECT s.id, c.id, MAX(b.buyingValue) * fhc.floramondoMargin + FROM vn.sale s + JOIN vn.item i ON i.id = s.itemFk + JOIN edi.floraHollandConfig fhc + LEFT JOIN cache.last_buy lb ON lb.item_id = i.id + LEFT JOIN vn.buy b ON b.id = lb.buy_id + LEFT JOIN vn.warehouse w ON w.id = lb.warehouse_id AND w.name = 'Floramondo' + JOIN vn.component c ON c.code = 'margin' + WHERE s.ticketFk = vSelf + GROUP BY s.id; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -13451,24 +13509,24 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `hedera`.`order_afterUpdate` AFTER UPDATE ON `order` FOR EACH ROW -BEGIN - CALL stock.log_add('order', NEW.id, OLD.id); - - IF !(OLD.address_id <=> NEW.address_id) - OR !(OLD.company_id <=> NEW.company_id) - OR !(OLD.customer_id <=> NEW.customer_id) THEN - CALL order_requestRecalc(NEW.id); - END IF; - - IF !(OLD.address_id <=> NEW.address_id) AND NEW.address_id = 2850 THEN - -- Fallo que se actualiza no se sabe como tickets en este cliente - CALL vn.mail_insert( - 'jgallego@verdnatura.es', - 'noreply@verdnatura.es', - 'Actualizada order al address 2850', - CONCAT(account.myUserGetName(), ' ha creado la order ',NEW.id) - ); - END IF; +BEGIN + CALL stock.log_add('order', NEW.id, OLD.id); + + IF !(OLD.address_id <=> NEW.address_id) + OR !(OLD.company_id <=> NEW.company_id) + OR !(OLD.customer_id <=> NEW.customer_id) THEN + CALL order_requestRecalc(NEW.id); + END IF; + + IF !(OLD.address_id <=> NEW.address_id) AND NEW.address_id = 2850 THEN + -- Fallo que se actualiza no se sabe como tickets en este cliente + CALL vn.mail_insert( + 'jgallego@verdnatura.es', + 'noreply@verdnatura.es', + 'Actualizada order al address 2850', + CONCAT(account.myUserGetName(), ' ha creado la order ',NEW.id) + ); + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -14862,30 +14920,30 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `item_listAllocation`(IN `vWh` TINYINT, IN `vDate` DATE, IN `vType` INT, IN `vPrefix` VARCHAR(255), IN `vUseIds` BOOLEAN) -BEGIN -/** - * Lists visible items and it's box sizes of the specified - * type at specified date. - * - * @param vWh The warehouse id - * @param vDate The visible date - * @param vType The type id - * @param vPrefix The article prefix to filter or %NULL for all - * @param vUseIds Whether to order the result by item id - * @select List of visible items with it's box sizes - */ - CALL item_getVisible(vWh, vDate, vType, vPrefix); - - IF vUseIds - THEN - SELECT * FROM tmp.itemVisible - ORDER BY Id_Article; - ELSE - SELECT * FROM tmp.itemVisible - ORDER BY Article, packing; - END IF; - - DROP TEMPORARY TABLE tmp.itemVisible; +BEGIN +/** + * Lists visible items and it's box sizes of the specified + * type at specified date. + * + * @param vWh The warehouse id + * @param vDate The visible date + * @param vType The type id + * @param vPrefix The article prefix to filter or %NULL for all + * @param vUseIds Whether to order the result by item id + * @select List of visible items with it's box sizes + */ + CALL item_getVisible(vWh, vDate, vType, vPrefix); + + IF vUseIds + THEN + SELECT * FROM tmp.itemVisible + ORDER BY Id_Article; + ELSE + SELECT * FROM tmp.itemVisible + ORDER BY Article, packing; + END IF; + + DROP TEMPORARY TABLE tmp.itemVisible; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -15032,82 +15090,82 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `myBasket_configure`( - vDelivery DATE, - vDeliveryMethod VARCHAR(45), - vAgency INT, +CREATE DEFINER=`root`@`localhost` PROCEDURE `myBasket_configure`( + vDelivery DATE, + vDeliveryMethod VARCHAR(45), + vAgency INT, vAddress INT) -BEGIN -/** - * Configura la cesta de la compra utilizando los parámetros - * pasados. Si los parámetros no son válidos devuelve un error. - * - * @param vDelivery Fecha de recogida - * @param vAgency Id de la agencia - * @param vAddress Id de dirección de envío, @NULL si es recogida - */ - DECLARE vSelf INT; - DECLARE vCompany INT; - DECLARE vDeliveryMethodId INT; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vSelf = NULL; - DECLARE EXIT HANDLER FOR SQLSTATE '45000' - BEGIN - ROLLBACK; - RESIGNAL; - END; - - START TRANSACTION; - - SELECT id INTO vDeliveryMethodId - FROM vn.deliveryMethod - WHERE code = vDeliveryMethod; - - IF vDeliveryMethod = 'PICKUP' AND vAddress IS NULL - THEN - SELECT defaultAddressFk INTO vAddress - FROM myClient; - END IF; - - SET vSelf = myBasket_getId(); - - IF vSelf IS NULL - THEN - - SELECT defaultCompanyFk INTO vCompany - FROM orderConfig; - - INSERT INTO `order` - SET - customer_id = account.userGetId(), - date_send = vDelivery, - delivery_method_id = vDeliveryMethodId, - agency_id = vAgency, - address_id = vAddress, - source_app = 'WEB', - company_id = vCompany; - - SET vSelf = LAST_INSERT_ID(); - - INSERT INTO basketOrder SET - clientFk = account.userGetId(), - orderFk = vSelf; - ELSE - UPDATE `order` - SET - date_send = vDelivery, - delivery_method_id = vDeliveryMethodId, - agency_id = vAgency, - address_id = vAddress - WHERE - id = vSelf; - - CALL order_update(vSelf); - END IF; - - CALL order_checkConfig(vSelf); - - COMMIT; +BEGIN +/** + * Configura la cesta de la compra utilizando los parámetros + * pasados. Si los parámetros no son válidos devuelve un error. + * + * @param vDelivery Fecha de recogida + * @param vAgency Id de la agencia + * @param vAddress Id de dirección de envío, @NULL si es recogida + */ + DECLARE vSelf INT; + DECLARE vCompany INT; + DECLARE vDeliveryMethodId INT; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vSelf = NULL; + DECLARE EXIT HANDLER FOR SQLSTATE '45000' + BEGIN + ROLLBACK; + RESIGNAL; + END; + + START TRANSACTION; + + SELECT id INTO vDeliveryMethodId + FROM vn.deliveryMethod + WHERE code = vDeliveryMethod; + + IF vDeliveryMethod = 'PICKUP' AND vAddress IS NULL + THEN + SELECT defaultAddressFk INTO vAddress + FROM myClient; + END IF; + + SET vSelf = myBasket_getId(); + + IF vSelf IS NULL + THEN + + SELECT defaultCompanyFk INTO vCompany + FROM orderConfig; + + INSERT INTO `order` + SET + customer_id = account.userGetId(), + date_send = vDelivery, + delivery_method_id = vDeliveryMethodId, + agency_id = vAgency, + address_id = vAddress, + source_app = 'WEB', + company_id = vCompany; + + SET vSelf = LAST_INSERT_ID(); + + INSERT INTO basketOrder SET + clientFk = account.userGetId(), + orderFk = vSelf; + ELSE + UPDATE `order` + SET + date_send = vDelivery, + delivery_method_id = vDeliveryMethodId, + agency_id = vAgency, + address_id = vAddress + WHERE + id = vSelf; + + CALL order_update(vSelf); + END IF; + + CALL order_checkConfig(vSelf); + + COMMIT; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -15332,62 +15390,62 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `myOrder_newWithAddress`( - OUT vSelf INT, - vLandingDate DATE, +CREATE DEFINER=`root`@`localhost` PROCEDURE `myOrder_newWithAddress`( + OUT vSelf INT, + vLandingDate DATE, vAddressFk INT) -BEGIN -/** - * Crea una nueva orden para el usuario actual especificando - * una fecha de entrega. - * - * @param vSelf Id de la nueva orden - * @param vLandingDate Fecha de entrega - */ - DECLARE vCompany INT; - DECLARE vDeliveryMethodId INT; - DECLARE vAgencyMode INT; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vSelf = NULL; - DECLARE EXIT HANDLER FOR SQLSTATE '45000' - BEGIN - ROLLBACK; - SET vSelf = NULL; - RESIGNAL; - END; - - START TRANSACTION; - - SELECT a.agencyModeFk, a.id - INTO vAgencyMode, vAddressFk - FROM vn.address a - WHERE a.id = vAddressFk; - - SELECT deliveryMethodFk INTO vDeliveryMethodId - FROM vn.agencyMode am - WHERE am.id = vAgencyMode; - - IF vCompany IS NULL - THEN - SELECT defaultCompanyFk INTO vCompany - FROM orderConfig; - END IF; - - INSERT INTO `order` - SET - customer_id = account.userGetId(), - date_send = vLandingDate, - delivery_method_id = vDeliveryMethodId, - agency_id = vAgencyMode, - address_id = vAddressFk, - source_app = 'WEB', - company_id = vCompany; - - SET vSelf = LAST_INSERT_ID(); - - CALL order_checkConfig(vSelf); - - COMMIT; +BEGIN +/** + * Crea una nueva orden para el usuario actual especificando + * una fecha de entrega. + * + * @param vSelf Id de la nueva orden + * @param vLandingDate Fecha de entrega + */ + DECLARE vCompany INT; + DECLARE vDeliveryMethodId INT; + DECLARE vAgencyMode INT; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vSelf = NULL; + DECLARE EXIT HANDLER FOR SQLSTATE '45000' + BEGIN + ROLLBACK; + SET vSelf = NULL; + RESIGNAL; + END; + + START TRANSACTION; + + SELECT a.agencyModeFk, a.id + INTO vAgencyMode, vAddressFk + FROM vn.address a + WHERE a.id = vAddressFk; + + SELECT deliveryMethodFk INTO vDeliveryMethodId + FROM vn.agencyMode am + WHERE am.id = vAgencyMode; + + IF vCompany IS NULL + THEN + SELECT defaultCompanyFk INTO vCompany + FROM orderConfig; + END IF; + + INSERT INTO `order` + SET + customer_id = account.userGetId(), + date_send = vLandingDate, + delivery_method_id = vDeliveryMethodId, + agency_id = vAgencyMode, + address_id = vAddressFk, + source_app = 'WEB', + company_id = vCompany; + + SET vSelf = LAST_INSERT_ID(); + + CALL order_checkConfig(vSelf); + + COMMIT; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -15404,62 +15462,62 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `myOrder_newWithDate`( - OUT vSelf INT, +CREATE DEFINER=`root`@`localhost` PROCEDURE `myOrder_newWithDate`( + OUT vSelf INT, vLandingDate DATE) -BEGIN -/** - * Crea una nueva orden para el usuario actual especificando - * una fecha de entrega. - * - * @param vSelf Id de la nueva orden - * @param vLandingDate Fecha de entrega - */ - DECLARE vCompany INT; - DECLARE vDeliveryMethodId INT; - DECLARE vAgencyMode INT; - DECLARE vAddress INT; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vSelf = NULL; - DECLARE EXIT HANDLER FOR SQLSTATE '45000' - BEGIN - ROLLBACK; - SET vSelf = NULL; - RESIGNAL; - END; - - START TRANSACTION; - - SELECT a.agencyModeFk, a.id - INTO vAgencyMode, vAddress - FROM myClient c - JOIN vn.address a ON a.id = c.defaultAddressFk; - - SELECT deliveryMethodFk INTO vDeliveryMethodId - FROM vn.agencyMode am - WHERE am.id = vAgencyMode; - - IF vCompany IS NULL - THEN - SELECT defaultCompanyFk INTO vCompany - FROM orderConfig; - END IF; - - INSERT INTO `order` - SET - customer_id = account.userGetId(), - date_send = vLandingDate, - delivery_method_id = vDeliveryMethodId, - agency_id = vAgencyMode, - address_id = vAddress, - source_app = 'WEB', - company_id = vCompany; - - SET vSelf = LAST_INSERT_ID(); - - CALL order_checkConfig(vSelf); - - COMMIT; +BEGIN +/** + * Crea una nueva orden para el usuario actual especificando + * una fecha de entrega. + * + * @param vSelf Id de la nueva orden + * @param vLandingDate Fecha de entrega + */ + DECLARE vCompany INT; + DECLARE vDeliveryMethodId INT; + DECLARE vAgencyMode INT; + DECLARE vAddress INT; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vSelf = NULL; + DECLARE EXIT HANDLER FOR SQLSTATE '45000' + BEGIN + ROLLBACK; + SET vSelf = NULL; + RESIGNAL; + END; + + START TRANSACTION; + + SELECT a.agencyModeFk, a.id + INTO vAgencyMode, vAddress + FROM myClient c + JOIN vn.address a ON a.id = c.defaultAddressFk; + + SELECT deliveryMethodFk INTO vDeliveryMethodId + FROM vn.agencyMode am + WHERE am.id = vAgencyMode; + + IF vCompany IS NULL + THEN + SELECT defaultCompanyFk INTO vCompany + FROM orderConfig; + END IF; + + INSERT INTO `order` + SET + customer_id = account.userGetId(), + date_send = vLandingDate, + delivery_method_id = vDeliveryMethodId, + agency_id = vAgencyMode, + address_id = vAddress, + source_app = 'WEB', + company_id = vCompany; + + SET vSelf = LAST_INSERT_ID(); + + CALL order_checkConfig(vSelf); + + COMMIT; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -18299,19 +18357,19 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sip_getExtension`(vUserId INT(10)) -BEGIN - - /* - * Devuelve la extensión pbx del usuario - * - * @param vUserId Id del usuario - * - */ - - SELECT extension - FROM sip s - WHERE s.user_id = vUserId; - +BEGIN + + /* + * Devuelve la extensión pbx del usuario + * + * @param vUserId Id del usuario + * + */ + + SELECT extension + FROM sip s + WHERE s.user_id = vUserId; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -18520,32 +18578,32 @@ CREATE TABLE `business` ( /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `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; - +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!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 */ ; @@ -18755,16 +18813,16 @@ DROP TABLE IF EXISTS `income_employee`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `income_employee` ( `id` int(11) NOT NULL AUTO_INCREMENT, - `debe` decimal(10,2) DEFAULT NULL, - `haber` decimal(10,2) DEFAULT '0.00', + `debe` decimal(10,2) NOT NULL DEFAULT '0.00', + `haber` decimal(10,2) NOT NULL DEFAULT '0.00', `id_incomeType` int(11) DEFAULT NULL, `odbc_date` date DEFAULT NULL, `person_id` int(11) DEFAULT NULL, `concepto` longtext, PRIMARY KEY (`id`), - KEY `fincometype_id` (`id_incomeType`), KEY `fperson_id` (`person_id`), - CONSTRAINT `fincometype_id` FOREIGN KEY (`id_incomeType`) REFERENCES `incometype_employee` (`id_incometype`) ON DELETE NO ACTION ON UPDATE NO ACTION, + KEY `income_employeeId_incomeType_idx` (`id_incomeType`), + CONSTRAINT `income_employeeId_incomeType` FOREIGN KEY (`id_incomeType`) REFERENCES `vn2008`.`payroll_conceptos` (`conceptoid`) ON UPDATE CASCADE, CONSTRAINT `income_employee_FK` FOREIGN KEY (`person_id`) REFERENCES `vn`.`person` (`id`) ) ENGINE=InnoDBDEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; @@ -19653,9 +19711,9 @@ SET character_set_client = @saved_cs_client; /*!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 collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `accountingMovements_add`(vYear INT, vCompanyFk INT) BEGIN @@ -25087,20 +25145,20 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `slowLog_prune`() -BEGIN -/** - * Prunes MySQL slow query log table deleting all records older than one week. - */ - DECLARE vSlowQueryLog INT DEFAULT @@slow_query_log; - - SET GLOBAL slow_query_log = 'OFF'; - RENAME TABLE `mysql`.`slow_log` TO `mysql`.`slow_log_temp`; - - DELETE FROM `mysql`.`slow_log_temp` - WHERE start_time < TIMESTAMPADD(WEEK, -1, NOW()); - - RENAME TABLE `mysql`.`slow_log_temp` TO `mysql`.`slow_log`; - SET GLOBAL slow_query_log = vSlowQueryLog; +BEGIN +/** + * Prunes MySQL slow query log table deleting all records older than one week. + */ + DECLARE vSlowQueryLog INT DEFAULT @@slow_query_log; + + SET GLOBAL slow_query_log = 'OFF'; + RENAME TABLE `mysql`.`slow_log` TO `mysql`.`slow_log_temp`; + + DELETE FROM `mysql`.`slow_log_temp` + WHERE start_time < TIMESTAMPADD(WEEK, -1, NOW()); + + RENAME TABLE `mysql`.`slow_log_temp` TO `mysql`.`slow_log`; + SET GLOBAL slow_query_log = vSlowQueryLog; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -25681,7 +25739,7 @@ CREATE TABLE `agency` ( `labelZone` tinyint(4) NOT NULL DEFAULT '0', `workCenterFk` int(11) DEFAULT NULL, `supplierFk` int(11) DEFAULT NULL, - `isAnyVolumeAllowed` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Permite vender productos cualquier volumen', + `isAnyVolumeAllowed` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Permite vender productos que tengan vn.itemType.IsUnconventionalSize = TRUE', PRIMARY KEY (`id`), KEY `warehouse_id` (`warehouseFk`), KEY `Id_Banco` (`bankFk`), @@ -25802,7 +25860,7 @@ CREATE TABLE `agencyTerm` ( `routePrice` decimal(10,2) DEFAULT NULL COMMENT 'precio fijo por ruta', `minimumKm` int(11) NOT NULL DEFAULT '0', `minimumM3` decimal(10,2) NOT NULL DEFAULT '0.00', - `m3Price` decimal(10,0) NOT NULL DEFAULT '0', + `m3Price` decimal(10,2) NOT NULL DEFAULT '0.00', PRIMARY KEY (`agencyFk`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -26554,59 +26612,59 @@ CREATE TABLE `buy` ( /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`buy_beforeInsert` - BEFORE INSERT ON `buy` - FOR EACH ROW -trig: BEGIN - DECLARE vWarehouse INT; - DECLARE vLanding DATE; - DECLARE vGrouping INT; - DECLARE vGroupingMode TINYINT; - DECLARE vGenericFk INT; - - IF @isModeInventory THEN - LEAVE trig; - END IF; - - CALL buy_checkGrouping(NEW.`grouping`); - - SELECT t.warehouseInFk, t.landed INTO vWarehouse, vLanding - FROM entry e - JOIN travel t ON t.id = e.travelFk - WHERE e.id = NEW.entryFk; - - SELECT b.`grouping`, b.groupingMode INTO vGrouping, vGroupingMode - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - WHERE t.landed <= vLanding - AND b.itemFk = NEW.itemFk - AND !b.isIgnored - ORDER BY t.warehouseInFk = vWarehouse DESC, t.landed DESC, b.id DESC - LIMIT 1; - - IF NEW.`grouping` IS NULL THEN - SET NEW.`grouping` = vGrouping; - END IF; - - IF NEW.groupingMode IS NULL THEN - SET NEW.groupingMode = vGroupingMode; - END IF; - - -- Generics - - SELECT i.genericFk INTO vGenericFk - FROM vn.item i - WHERE i.id = NEW.itemFk; - - IF vGenericFk THEN - - SET NEW.itemOriginalFk = NEW.itemFk; - - SET NEW.itemFk = vGenericFk; - - END IF; - +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`buy_beforeInsert` + BEFORE INSERT ON `buy` + FOR EACH ROW +trig: BEGIN + DECLARE vWarehouse INT; + DECLARE vLanding DATE; + DECLARE vGrouping INT; + DECLARE vGroupingMode TINYINT; + DECLARE vGenericFk INT; + + IF @isModeInventory THEN + LEAVE trig; + END IF; + + CALL buy_checkGrouping(NEW.`grouping`); + + SELECT t.warehouseInFk, t.landed INTO vWarehouse, vLanding + FROM entry e + JOIN travel t ON t.id = e.travelFk + WHERE e.id = NEW.entryFk; + + SELECT b.`grouping`, b.groupingMode INTO vGrouping, vGroupingMode + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + WHERE t.landed <= vLanding + AND b.itemFk = NEW.itemFk + AND !b.isIgnored + ORDER BY t.warehouseInFk = vWarehouse DESC, t.landed DESC, b.id DESC + LIMIT 1; + + IF NEW.`grouping` IS NULL THEN + SET NEW.`grouping` = vGrouping; + END IF; + + IF NEW.groupingMode IS NULL THEN + SET NEW.groupingMode = vGroupingMode; + END IF; + + -- Generics + + SELECT i.genericFk INTO vGenericFk + FROM vn.item i + WHERE i.id = NEW.itemFk; + + IF vGenericFk THEN + + SET NEW.itemOriginalFk = NEW.itemFk; + + SET NEW.itemFk = vGenericFk; + + END IF; + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -26648,37 +26706,37 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`buy_beforeUpdate` - BEFORE UPDATE ON `buy` - FOR EACH ROW -trig:BEGIN - - DECLARE vGenericFk INT; - - IF @isTriggerDisabled THEN - - LEAVE trig; - - END IF; - - IF !(NEW.`grouping` <=> OLD.`grouping`) THEN - CALL buy_checkGrouping(NEW.`grouping`); - END IF; - - -- Generics - - SELECT i.genericFk INTO vGenericFk - FROM vn.item i - WHERE i.id = NEW.itemFk; - - IF vGenericFk THEN - - SET NEW.itemOriginalFk = NEW.itemFk; - - SET NEW.itemFk = vGenericFk; - - END IF; - +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`buy_beforeUpdate` + BEFORE UPDATE ON `buy` + FOR EACH ROW +trig:BEGIN + + DECLARE vGenericFk INT; + + IF @isTriggerDisabled THEN + + LEAVE trig; + + END IF; + + IF !(NEW.`grouping` <=> OLD.`grouping`) THEN + CALL buy_checkGrouping(NEW.`grouping`); + END IF; + + -- Generics + + SELECT i.genericFk INTO vGenericFk + FROM vn.item i + WHERE i.id = NEW.itemFk; + + IF vGenericFk THEN + + SET NEW.itemOriginalFk = NEW.itemFk; + + SET NEW.itemFk = vGenericFk; + + END IF; + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -28164,39 +28222,39 @@ CREATE TABLE `collection` ( /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`collection_BEFORE_UPDATE` - BEFORE UPDATE ON `collection` - FOR EACH ROW -BEGIN - - DECLARE vStateFk INT; - DECLARE vTotalLines INT; - DECLARE vPickedLines INT; - - IF NEW.saleTotalCount <= NEW.salePickedCount - AND (NEW.saleTotalCount != OLD.saleTotalCount - OR NEW.salePickedCount != OLD.salePickedCount) - THEN - - SELECT id INTO vStateFk - FROM vn.state - WHERE code = 'PREPARED'; - - SET NEW.stateFk = vStateFk; - - END IF; - - IF NEW.saleTotalCount > NEW.salePickedCount - AND (NEW.saleTotalCount != OLD.saleTotalCount OR NEW.salePickedCount != OLD.salePickedCount) THEN - - SELECT id INTO vStateFk - FROM vn.state - WHERE code = 'ON_PREPARATION'; - - SET NEW.stateFk = vStateFk; - - END IF; - +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`collection_BEFORE_UPDATE` + BEFORE UPDATE ON `collection` + FOR EACH ROW +BEGIN + + DECLARE vStateFk INT; + DECLARE vTotalLines INT; + DECLARE vPickedLines INT; + + IF NEW.saleTotalCount <= NEW.salePickedCount + AND (NEW.saleTotalCount != OLD.saleTotalCount + OR NEW.salePickedCount != OLD.salePickedCount) + THEN + + SELECT id INTO vStateFk + FROM vn.state + WHERE code = 'PREPARED'; + + SET NEW.stateFk = vStateFk; + + END IF; + + IF NEW.saleTotalCount > NEW.salePickedCount + AND (NEW.saleTotalCount != OLD.saleTotalCount OR NEW.salePickedCount != OLD.salePickedCount) THEN + + SELECT id INTO vStateFk + FROM vn.state + WHERE code = 'ON_PREPARATION'; + + SET NEW.stateFk = vStateFk; + + END IF; + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -29642,35 +29700,37 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET character_set_client = 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 = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`dms_beforeUpdate` - BEFORE UPDATE ON `dms` - FOR EACH ROW -BEGIN - DECLARE vHardCopyNumber INT; - - IF (NEW.hasFile <> 0) AND (OLD.hasFile = 0) AND (NEW.hardCopyNumber IS NULL) THEN - - IF (SELECT NOT hasDms FROM warehouse WHERE id = NEW.warehouseFk) THEN - SET NEW.warehouseFk = (SELECT id FROM warehouse WHERE name = 'Algemesi'); - END IF; - - SELECT 1 + MAX(hardCopyNumber) INTO vHardCopyNumber - FROM dms - WHERE warehouseFk = NEW.warehouseFk; - - SET NEW.hardCopyNumber = IFNULL(vHardCopyNumber,1); - END IF; - - IF ((NEW.hardCopyNumber = 0) OR NEW.hardCopyNumber IS NULL) AND (OLD.hardCopyNumber <> 0) THEN - - SET NEW.hasFile = 0; - END IF; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`dms_beforeUpdate` + BEFORE UPDATE ON `dms` + FOR EACH ROW +BEGIN + DECLARE vHardCopyNumber INT; + + IF (NEW.hasFile <> 0) AND (OLD.hasFile = 0) AND (NEW.hardCopyNumber IS NULL) + OR + (NEW.hardCopyNumber = OLD.hardCopyNumber AND OLD.warehouseFk <> NEW.warehouseFk) THEN + + IF (SELECT NOT hasDms FROM warehouse WHERE id = NEW.warehouseFk) THEN + SET NEW.warehouseFk = (SELECT id FROM warehouse WHERE name = 'Algemesi'); + END IF; + + SELECT 1 + MAX(hardCopyNumber) INTO vHardCopyNumber + FROM dms + WHERE warehouseFk = NEW.warehouseFk; + + SET NEW.hardCopyNumber = IFNULL(vHardCopyNumber,1); + END IF; + + IF ((NEW.hardCopyNumber = 0) OR NEW.hardCopyNumber IS NULL) AND (OLD.hardCopyNumber <> 0) THEN + + SET NEW.hasFile = 0; + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -30329,7 +30389,7 @@ CREATE TABLE `entryObservation` ( KEY `observationType_id_observationTypeFk` (`observationTypeFk`), CONSTRAINT `entry_id_entryFk` FOREIGN KEY (`entryFk`) REFERENCES `entry` (`id`), CONSTRAINT `observationType_id_observationTypeFk` FOREIGN KEY (`observationTypeFk`) REFERENCES `observationType` (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; -- @@ -30487,6 +30547,7 @@ CREATE TABLE `errorProduction` ( `lastname` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, `rol` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, `ticketNumber` int(11) DEFAULT NULL, + `lineNumber` int(11) DEFAULT NULL, `error` int(11) DEFAULT NULL, `volume` double DEFAULT NULL, `hourStart` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, @@ -31449,13 +31510,13 @@ CREATE TABLE `glsConfig` ( /*!40101 SET character_set_client = @saved_cs_client */; -- --- Table structure for table `glsExpedition` +-- Table structure for table `glsExpedition__` -- -DROP TABLE IF EXISTS `glsExpedition`; +DROP TABLE IF EXISTS `glsExpedition__`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; -CREATE TABLE `glsExpedition` ( +CREATE TABLE `glsExpedition__` ( `expeditionFk` int(11) NOT NULL, `barcode` bigint(20) unsigned DEFAULT NULL, `uid` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, @@ -32634,6 +32695,30 @@ CREATE TABLE `invoiceOutTax` ( ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `invoiceOutTaxConfig` +-- + +DROP TABLE IF EXISTS `invoiceOutTaxConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `invoiceOutTaxConfig` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `taxClassCodeFk` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL, + `taxTypeSageFk` smallint(6) DEFAULT NULL, + `transactionTypeSageFk` tinyint(4) DEFAULT NULL, + `isService` tinyint(1) DEFAULT '0', + `expenceFk` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `invoiceOutTaxConfig_FK` (`taxClassCodeFk`), + KEY `invoiceOutTaxConfig_FK_1` (`taxTypeSageFk`), + KEY `invoiceOutTaxConfig_FK_2` (`transactionTypeSageFk`), + CONSTRAINT `invoiceOutTaxConfig_FK` FOREIGN KEY (`taxClassCodeFk`) REFERENCES `taxClass` (`code`), + CONSTRAINT `invoiceOutTaxConfig_FK_1` FOREIGN KEY (`taxTypeSageFk`) REFERENCES `sage`.`TiposIva` (`CodigoIva`), + CONSTRAINT `invoiceOutTaxConfig_FK_2` FOREIGN KEY (`transactionTypeSageFk`) REFERENCES `sage`.`TiposTransacciones` (`CodigoTransaccion`) +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `item` -- @@ -32788,26 +32873,26 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`item_afterInsert` - AFTER INSERT ON `item` - FOR EACH ROW -BEGIN - - CALL hedera.image_ref('catalog', NEW.image); - - INSERT INTO vn.itemTaxCountry(itemFk, countryFk) - SELECT NEW.id, 1; - - INSERT INTO vn.itemTaxCountry(itemFk, countryFk) - SELECT NEW.id, 5; - - INSERT INTO vn.itemTaxCountry(itemFk, countryFk) - SELECT NEW.id, 30; - - DELETE ifr.* - FROM edi.item_free ifr - WHERE ifr.id = NEW.id; - +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`item_afterInsert` + AFTER INSERT ON `item` + FOR EACH ROW +BEGIN + + CALL hedera.image_ref('catalog', NEW.image); + + INSERT INTO vn.itemTaxCountry(itemFk, countryFk) + SELECT NEW.id, 1; + + INSERT INTO vn.itemTaxCountry(itemFk, countryFk) + SELECT NEW.id, 5; + + INSERT INTO vn.itemTaxCountry(itemFk, countryFk) + SELECT NEW.id, 30; + + DELETE ifr.* + FROM edi.item_free ifr + WHERE ifr.id = NEW.id; + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -36536,13 +36621,13 @@ CREATE TABLE `projectNotes` ( /*!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' */ ; +/*!50003 SET sql_mode = 'STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`$manager`@`%`*/ /*!50003 TRIGGER projectNotes_BeforeInsert +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER projectNotes_BeforeInsert BEFORE INSERT ON projectNotes FOR EACH ROW BEGIN @@ -36560,6 +36645,99 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +-- +-- Table structure for table `property` +-- + +DROP TABLE IF EXISTS `property`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `property` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(250) COLLATE utf8_unicode_ci NOT NULL, + `cadaster` varchar(200) COLLATE utf8_unicode_ci DEFAULT NULL, + `smallholding` int(11) DEFAULT NULL, + `area` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, + `townFk` int(11) NOT NULL, + `registry` varchar(200) COLLATE utf8_unicode_ci DEFAULT NULL, + `volume` int(11) DEFAULT NULL, + `book` int(11) DEFAULT NULL, + `page` int(11) DEFAULT NULL, + `farm` int(11) DEFAULT NULL, + `registration` int(11) DEFAULT NULL, + `value` int(11) DEFAULT NULL, + `propertyGroupFk` int(11) NOT NULL, + `companyFk` smallint(5) unsigned NOT NULL, + `photo` blob, + `allocation` varchar(200) COLLATE utf8_unicode_ci DEFAULT NULL, + `m2` decimal(10,2) DEFAULT NULL, + `tome` int(11) DEFAULT NULL, + `url` varchar(250) COLLATE utf8_unicode_ci DEFAULT NULL, + `protocol` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'numero de protocolo notarial de la escritura de compra venta', + PRIMARY KEY (`id`), + KEY `property_FK` (`propertyGroupFk`), + KEY `property_FK_1` (`townFk`), + KEY `property_company` (`companyFk`), + CONSTRAINT `property_FK` FOREIGN KEY (`propertyGroupFk`) REFERENCES `propertyGroup` (`id`) ON UPDATE CASCADE, + CONSTRAINT `property_FK_1` FOREIGN KEY (`townFk`) REFERENCES `town` (`id`) ON UPDATE CASCADE, + CONSTRAINT `property_company` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `propertyDms` +-- + +DROP TABLE IF EXISTS `propertyDms`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `propertyDms` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `dmsFk` int(11) NOT NULL, + `propertyFk` int(11) NOT NULL, + PRIMARY KEY (`id`), + KEY `propertyDms_FK` (`dmsFk`), + KEY `propertyDms_FK_1` (`propertyFk`), + CONSTRAINT `propertyDms_FK` FOREIGN KEY (`dmsFk`) REFERENCES `dms` (`id`) ON UPDATE CASCADE, + CONSTRAINT `propertyDms_FK_1` FOREIGN KEY (`propertyFk`) REFERENCES `property` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `propertyGroup` +-- + +DROP TABLE IF EXISTS `propertyGroup`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `propertyGroup` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `description` varchar(100) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `propertyNotes` +-- + +DROP TABLE IF EXISTS `propertyNotes`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `propertyNotes` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `propertyFk` int(10) unsigned NOT NULL, + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `note` text COLLATE utf8_unicode_ci NOT NULL, + `userFk` int(10) unsigned DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `propertyNotes_FK_1` (`userFk`), + KEY `propertyNotes_FK` (`propertyFk`), + CONSTRAINT `propertyNotes_FK` FOREIGN KEY (`propertyFk`) REFERENCES `account`.`user` (`id`), + CONSTRAINT `propertyNotes_FK_1` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `province` -- @@ -36646,19 +36824,19 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`province_afterUpdate` - AFTER UPDATE ON `province` - FOR EACH ROW -BEGIN - IF !(OLD.autonomyFk <=> NEW.autonomyFk) THEN - CALL zoneGeo_setParent(NEW.geoFk, - (SELECT geoFk FROM autonomy WHERE id = NEW.autonomyFk)); - END IF; - - IF !(OLD.`name` <=> NEW.`name`) THEN - UPDATE zoneGeo SET `name` = NEW.`name` - WHERE id = NEW.geoFk; - END IF; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`province_afterUpdate` + AFTER UPDATE ON `province` + FOR EACH ROW +BEGIN + IF !(OLD.autonomyFk <=> NEW.autonomyFk) THEN + CALL zoneGeo_setParent(NEW.geoFk, + (SELECT geoFk FROM autonomy WHERE id = NEW.autonomyFk)); + END IF; + + IF !(OLD.`name` <=> NEW.`name`) THEN + UPDATE zoneGeo SET `name` = NEW.`name` + WHERE id = NEW.geoFk; + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -36858,20 +37036,20 @@ CREATE TABLE `receipt` ( /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`receipt_beforeInsert` - BEFORE INSERT ON `receipt` - FOR EACH ROW -BEGIN - DECLARE vIsAutoConciliated BOOLEAN; - - IF NEW.isConciliate = FALSE THEN - SELECT isAutoConciliated INTO vIsAutoConciliated - FROM accounting a - JOIN accountingType at2 ON at2.id = a.accountingTypeFk - WHERE a.id = NEW.bankFk; - - SET NEW.isConciliate = vIsAutoConciliated; - END IF; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`receipt_beforeInsert` + BEFORE INSERT ON `receipt` + FOR EACH ROW +BEGIN + DECLARE vIsAutoConciliated BOOLEAN; + + IF NEW.isConciliate = FALSE THEN + SELECT isAutoConciliated INTO vIsAutoConciliated + FROM accounting a + JOIN accountingType at2 ON at2.id = a.accountingTypeFk + WHERE a.id = NEW.bankFk; + + SET NEW.isConciliate = vIsAutoConciliated; + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -36927,18 +37105,18 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`receipt_afterUpdate` - AFTER UPDATE ON `receipt` - FOR EACH ROW -BEGIN - IF NEW.isConciliate = FALSE AND NEW.payed > OLD.payed THEN - CALL mail_insert( - 'finanzas@verdnatura.es', - NULL, - CONCAT('Cambios de recibos del cliente: ', NEW.clientFk), - CONCAT('Se ha cambiado el recibo: ', NEW.Id, ' de ', OLD.payed, ' a ', NEW.payed) - ); - END IF; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`receipt_afterUpdate` + AFTER UPDATE ON `receipt` + FOR EACH ROW +BEGIN + IF NEW.isConciliate = FALSE AND NEW.payed > OLD.payed THEN + CALL mail_insert( + 'finanzas@verdnatura.es', + NULL, + CONCAT('Cambios de recibos del cliente: ', NEW.clientFk), + CONCAT('Se ha cambiado el recibo: ', NEW.Id, ' de ', OLD.payed, ' a ', NEW.payed) + ); + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -38688,6 +38866,7 @@ CREATE TABLE `shelving` ( `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', + `isRecyclable` tinyint(1) NOT NULL DEFAULT '1' COMMENT 'las matrículas marcadas como reciclables se liberan cada noche desde vn.shelving_clean para poder volver a utilizarlas', PRIMARY KEY (`code`), KEY `shelving_fk1_idx` (`parkingFk`), KEY `shelving_fk2_idx` (`userFk`), @@ -40060,31 +40239,31 @@ CREATE TABLE `ticketCollection` ( /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER ticketCollection_afterDelete -AFTER DELETE -ON ticketCollection FOR EACH ROW -BEGIN - - DECLARE vSalesRemaining INT; - - SELECT count(*) INTO vSalesRemaining - FROM vn.ticketCollection tc - JOIN sale s ON s.ticketFk = tc.ticketFk - WHERE collectionFk = OLD.collectionFk - AND tc.id != OLD.id; - - IF NOT vSalesRemaining THEN - - DELETE FROM vn.collection WHERE id = OLD.collectionFk; - - ELSE - - UPDATE vn.collection - SET saleTotalCount = vSalesRemaining - WHERE id = OLD.collectionFk; - - END IF; - +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER ticketCollection_afterDelete +AFTER DELETE +ON ticketCollection FOR EACH ROW +BEGIN + + DECLARE vSalesRemaining INT; + + SELECT count(*) INTO vSalesRemaining + FROM vn.ticketCollection tc + JOIN sale s ON s.ticketFk = tc.ticketFk + WHERE collectionFk = OLD.collectionFk + AND tc.id != OLD.id; + + IF NOT vSalesRemaining THEN + + DELETE FROM vn.collection WHERE id = OLD.collectionFk; + + ELSE + + UPDATE vn.collection + SET saleTotalCount = vSalesRemaining + WHERE id = OLD.collectionFk; + + END IF; + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -43633,16 +43812,16 @@ DELIMITER ;; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;; /*!50003 SET @saved_time_zone = @@time_zone */ ;; /*!50003 SET time_zone = 'SYSTEM' */ ;; -/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `workerTimeControl_sendMail` ON SCHEDULE EVERY 1 WEEK STARTS '2020-11-25 08: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_sendMail(vWeek, vYear, NULL); +/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `workerTimeControl_sendMail` ON SCHEDULE EVERY 1 WEEK STARTS '2020-11-25 08: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_sendMail(vWeek, vYear, NULL); END */ ;; /*!50003 SET time_zone = @saved_time_zone */ ;; /*!50003 SET sql_mode = @saved_sql_mode */ ;; @@ -44195,57 +44374,57 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `clientGetDebt`(`vClient` INT, `vDate` DATE) RETURNS decimal(10,2) READS SQL DATA -BEGIN -/** - * Devuelve el saldo de un cliente. - * - * @param vClient Identificador del cliente - * @param vDate Fecha hasta la que tener en cuenta - * @return Saldo del cliente - */ - DECLARE vDateEnd DATETIME; - DECLARE vDateIni DATETIME; - DECLARE vDebt DECIMAL(10,2); - DECLARE vHasDebt BOOLEAN; - - SELECT COUNT(*) INTO vHasDebt - FROM `client` c - WHERE c.id = vClient AND c.typeFk = 'normal'; - - IF NOT vHasDebt THEN - RETURN 0; - END IF; - - SET vDate = IFNULL(vDate, CURDATE()); - - SET vDateIni = TIMESTAMPADD(MONTH, -2, CURDATE()); - SET vDateEnd = TIMESTAMP(vDate, '23:59:59'); - - SELECT IFNULL(SUM(t.amount), 0) INTO vDebt - FROM ( - SELECT SUM(IFNULL(totalWithVat,0)) amount - FROM ticket - WHERE clientFk = vClient - AND refFk IS NULL - AND shipped BETWEEN vDateIni AND vDateEnd - UNION ALL - SELECT SUM(amountPaid) amount - FROM receipt - WHERE clientFk = vClient - AND payed > vDateEnd - UNION ALL - SELECT SUM(amount) - FROM clientRisk - WHERE clientFk = vClient - UNION ALL - SELECT CAST(-SUM(amount) / 100 AS DECIMAL(10,2)) - FROM hedera.tpvTransaction - WHERE clientFk = vClient - AND receiptFk IS NULL - AND `status` = 'ok' - ) t; - - RETURN vDebt; +BEGIN +/** + * Devuelve el saldo de un cliente. + * + * @param vClient Identificador del cliente + * @param vDate Fecha hasta la que tener en cuenta + * @return Saldo del cliente + */ + DECLARE vDateEnd DATETIME; + DECLARE vDateIni DATETIME; + DECLARE vDebt DECIMAL(10,2); + DECLARE vHasDebt BOOLEAN; + + SELECT COUNT(*) INTO vHasDebt + FROM `client` c + WHERE c.id = vClient AND c.typeFk = 'normal'; + + IF NOT vHasDebt THEN + RETURN 0; + END IF; + + SET vDate = IFNULL(vDate, CURDATE()); + + SET vDateIni = TIMESTAMPADD(MONTH, -2, CURDATE()); + SET vDateEnd = TIMESTAMP(vDate, '23:59:59'); + + SELECT IFNULL(SUM(t.amount), 0) INTO vDebt + FROM ( + SELECT SUM(IFNULL(totalWithVat,0)) amount + FROM ticket + WHERE clientFk = vClient + AND refFk IS NULL + AND shipped BETWEEN vDateIni AND vDateEnd + UNION ALL + SELECT SUM(amountPaid) amount + FROM receipt + WHERE clientFk = vClient + AND payed > vDateEnd + UNION ALL + SELECT SUM(amount) + FROM clientRisk + WHERE clientFk = vClient + UNION ALL + SELECT CAST(-SUM(amount) / 100 AS DECIMAL(10,2)) + FROM hedera.tpvTransaction + WHERE clientFk = vClient + AND receiptFk IS NULL + AND `status` = 'ok' + ) t; + + RETURN vDebt; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -44670,29 +44849,29 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `collectionExpeditionLacks`(vCollectionFk INT) RETURNS varchar(100) CHARSET utf8 COLLATE utf8_unicode_ci DETERMINISTIC -BEGIN - - DECLARE vExpeditionLacks BOOL; - DECLARE vAnswer VARCHAR(100) DEFAULT ''; - - SELECT (COUNT(*) > 0) INTO vExpeditionLacks - FROM vn.ticketCollection tc - LEFT JOIN vn.expedition e ON e.ticketFk = tc.ticketFk - WHERE tc.collectionFk = vCollectionFk - AND ISNULL(e.id); - - IF vExpeditionLacks THEN - - SELECT CONCAT('Colección: ',tc.collectionFk,' Tickets: ' , GROUP_CONCAT(tc.ticketFk) ) INTO vAnswer - FROM vn.ticketCollection tc - LEFT JOIN vn.expedition e ON e.ticketFk = tc.ticketFk - WHERE tc.collectionFk = vCollectionFk - AND ISNULL(e.id); - - END IF; - - RETURN vAnswer; - +BEGIN + + DECLARE vExpeditionLacks BOOL; + DECLARE vAnswer VARCHAR(100) DEFAULT ''; + + SELECT (COUNT(*) > 0) INTO vExpeditionLacks + FROM vn.ticketCollection tc + LEFT JOIN vn.expedition e ON e.ticketFk = tc.ticketFk + WHERE tc.collectionFk = vCollectionFk + AND ISNULL(e.id); + + IF vExpeditionLacks THEN + + SELECT CONCAT('Colección: ',tc.collectionFk,' Tickets: ' , GROUP_CONCAT(tc.ticketFk) ) INTO vAnswer + FROM vn.ticketCollection tc + LEFT JOIN vn.expedition e ON e.ticketFk = tc.ticketFk + WHERE tc.collectionFk = vCollectionFk + AND ISNULL(e.id); + + END IF; + + RETURN vAnswer; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -44819,79 +44998,79 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `ekt_getEntry`(vEktFk INT) RETURNS int(11) READS SQL DATA -BEGIN - - /** - * Devuelve el numero de entrada para el ekt - * - * @param vEktFk Identificador de edi.ekt - */ - - DECLARE vTravelFk INT; - DECLARE vEntryFk INT DEFAULT 0; - DECLARE vEntryAssignFk INT; - - SET vTravelFk = vn.ekt_getTravel(vEktFk); - - IF vTravelFk THEN - - SELECT ea.id INTO vEntryAssignFk - FROM edi.ekt e - JOIN vn.travel tr ON tr.id = vTravelFk - JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk - AND ea.warehouseInFk = tr.warehouseInFk - AND ea.agencyModeFk = tr.agencyFk - AND IFNULL(ea.sub, e.sub) <=> e.sub - AND IFNULL(ea.kop, e.kop) <=> e.kop - AND IFNULL(ea.pro, e.pro) <=> e.pro - WHERE e.id = vEktFk - ORDER BY ea.sub <=> e.sub AND ea.kop <=> e.kop AND ea.pro <=> e.pro DESC, - ea.sub <=> e.sub AND ea.kop <=> e.kop AND ISNULL(ea.pro) DESC, - ea.sub <=> e.sub AND ISNULL(ea.kop) AND ea.pro <=> e.pro DESC, - ea.sub <=> e.sub AND ISNULL(ea.kop) AND ISNULL(ea.pro) DESC, - ISNULL(ea.sub) AND ea.kop <=> e.kop AND ea.pro <=> e.pro DESC, - ISNULL(ea.sub) AND ea.kop <=> e.kop AND ISNULL(ea.pro) DESC, - ISNULL(ea.sub) AND ISNULL(ea.kop) AND ea.pro <=> e.pro DESC - LIMIT 1; - - SELECT MAX(e.id) INTO vEntryFk - FROM vn.entry e - JOIN vn.ektEntryAssign ea ON ea.id = vEntryAssignFk - WHERE e.travelFk = vTravelFk - AND e.sub <=> ea.sub - AND e.kop <=> ea.kop - AND e.pro <=> ea.pro; - - - IF IFNULL(vEntryFk,0) = 0 THEN - - INSERT INTO vn.entry(travelFk, supplierFk, companyFk, currencyFk, kop, sub, ref, pro) - SELECT vTravelFk, ea.supplierFk, c.id, cu.id, ea.kop, ea.sub, ea.ref, ea.pro - FROM vn.ektEntryAssign ea - JOIN vn.company c ON c.code = 'VNL' - JOIN vn.currency cu ON cu.code = 'EUR' - WHERE ea.id = vEntryAssignFk; - - SELECT MAX(id) INTO vEntryFk - FROM vn.entry - WHERE travelFk = vTravelFk; - - END IF; - - UPDATE vn.ektEntryAssign - SET entryFk = vEntryFk - WHERE id = vEntryAssignFk; - - ELSE - - SELECT ec.defaultEntry INTO vEntryFk - FROM vn.entryConfig ec; - - INSERT IGNORE INTO vn.entry(id) VALUES(vEntryFk); - - END IF; - - RETURN vEntryFk; +BEGIN + + /** + * Devuelve el numero de entrada para el ekt + * + * @param vEktFk Identificador de edi.ekt + */ + + DECLARE vTravelFk INT; + DECLARE vEntryFk INT DEFAULT 0; + DECLARE vEntryAssignFk INT; + + SET vTravelFk = vn.ekt_getTravel(vEktFk); + + IF vTravelFk THEN + + SELECT ea.id INTO vEntryAssignFk + FROM edi.ekt e + JOIN vn.travel tr ON tr.id = vTravelFk + JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk + AND ea.warehouseInFk = tr.warehouseInFk + AND ea.agencyModeFk = tr.agencyFk + AND IFNULL(ea.sub, e.sub) <=> e.sub + AND IFNULL(ea.kop, e.kop) <=> e.kop + AND IFNULL(ea.pro, e.pro) <=> e.pro + WHERE e.id = vEktFk + ORDER BY ea.sub <=> e.sub AND ea.kop <=> e.kop AND ea.pro <=> e.pro DESC, + ea.sub <=> e.sub AND ea.kop <=> e.kop AND ISNULL(ea.pro) DESC, + ea.sub <=> e.sub AND ISNULL(ea.kop) AND ea.pro <=> e.pro DESC, + ea.sub <=> e.sub AND ISNULL(ea.kop) AND ISNULL(ea.pro) DESC, + ISNULL(ea.sub) AND ea.kop <=> e.kop AND ea.pro <=> e.pro DESC, + ISNULL(ea.sub) AND ea.kop <=> e.kop AND ISNULL(ea.pro) DESC, + ISNULL(ea.sub) AND ISNULL(ea.kop) AND ea.pro <=> e.pro DESC + LIMIT 1; + + SELECT MAX(e.id) INTO vEntryFk + FROM vn.entry e + JOIN vn.ektEntryAssign ea ON ea.id = vEntryAssignFk + WHERE e.travelFk = vTravelFk + AND e.sub <=> ea.sub + AND e.kop <=> ea.kop + AND e.pro <=> ea.pro; + + + IF IFNULL(vEntryFk,0) = 0 THEN + + INSERT INTO vn.entry(travelFk, supplierFk, companyFk, currencyFk, kop, sub, ref, pro) + SELECT vTravelFk, ea.supplierFk, c.id, cu.id, ea.kop, ea.sub, ea.ref, ea.pro + FROM vn.ektEntryAssign ea + JOIN vn.company c ON c.code = 'VNL' + JOIN vn.currency cu ON cu.code = 'EUR' + WHERE ea.id = vEntryAssignFk; + + SELECT MAX(id) INTO vEntryFk + FROM vn.entry + WHERE travelFk = vTravelFk; + + END IF; + + UPDATE vn.ektEntryAssign + SET entryFk = vEntryFk + WHERE id = vEntryAssignFk; + + ELSE + + SELECT ec.defaultEntry INTO vEntryFk + FROM vn.entryConfig ec; + + INSERT IGNORE INTO vn.entry(id) VALUES(vEntryFk); + + END IF; + + RETURN vEntryFk; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -45270,32 +45449,32 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `expedition_checkRoute`(vPalletFk INT,vExpeditionFk INT) RETURNS tinyint(1) DETERMINISTIC -BEGIN -/** -* Comprueba si las expediciones del pallet son todas -* de la misma ruta. -* -* @param vExpeditionFk numero de expedition a comprobar -* @param vPalletFk numero de pallet -* @return vHasDistinctRoutes -*/ - DECLARE vRouteFk INT; - DECLARE vHasDistinctRoutes BOOL; - - SELECT t.routeFk INTO vRouteFk - FROM vn.expedition e - JOIN vn.ticket t ON e.ticketFk = t.id - WHERE e.id = vExpeditionFk; - - SELECT COUNT(*) > 0 INTO vHasDistinctRoutes - FROM vn.expeditionScan es - JOIN vn.expedition e ON es.expeditionFk = e.id - JOIN vn.ticket t ON e.ticketFk = t.id - WHERE es.palletFk = vPalletFk - AND t.routeFk <> vRouteFk; - - RETURN vHasDistinctRoutes; - +BEGIN +/** +* Comprueba si las expediciones del pallet son todas +* de la misma ruta. +* +* @param vExpeditionFk numero de expedition a comprobar +* @param vPalletFk numero de pallet +* @return vHasDistinctRoutes +*/ + DECLARE vRouteFk INT; + DECLARE vHasDistinctRoutes BOOL; + + SELECT t.routeFk INTO vRouteFk + FROM vn.expedition e + JOIN vn.ticket t ON e.ticketFk = t.id + WHERE e.id = vExpeditionFk; + + SELECT COUNT(*) > 0 INTO vHasDistinctRoutes + FROM vn.expeditionScan es + JOIN vn.expedition e ON es.expeditionFk = e.id + JOIN vn.ticket t ON e.ticketFk = t.id + WHERE es.palletFk = vPalletFk + AND t.routeFk <> vRouteFk; + + RETURN vHasDistinctRoutes; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -46290,19 +46469,19 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `isLogifloraDay`(vShipped DATE, vWarehouse INT) RETURNS tinyint(1) DETERMINISTIC -BEGIN - - DECLARE vIsLogifloraDay BOOLEAN; - - SELECT COUNT(*) INTO vIsLogifloraDay - FROM edi.warehouseFloramondo wf - JOIN vn.floramondoConfig fc - WHERE wf.warehouseFk = vWarehouse - AND vShipped BETWEEN DATE(TIMESTAMPADD(DAY, wf.travellingDays , fc.nextLanded)) - AND DATE(TIMESTAMPADD(DAY, wf.travellingDays + wf.dayRange , fc.nextLanded)); - - RETURN vIsLogifloraDay; - +BEGIN + + DECLARE vIsLogifloraDay BOOLEAN; + + SELECT COUNT(*) INTO vIsLogifloraDay + FROM edi.warehouseFloramondo wf + JOIN vn.floramondoConfig fc + WHERE wf.warehouseFk = vWarehouse + AND vShipped BETWEEN DATE(TIMESTAMPADD(DAY, wf.travellingDays , fc.nextLanded)) + AND DATE(TIMESTAMPADD(DAY, wf.travellingDays + wf.dayRange , fc.nextLanded)); + + RETURN vIsLogifloraDay; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -46540,17 +46719,17 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `item_getFhImage`(itemFk INT) RETURNS varchar(255) CHARSET utf8 COLLATE utf8_unicode_ci DETERMINISTIC -BEGIN - DECLARE vImageUrl VARCHAR(255); - SELECT sr.PictureReference INTO vImageUrl - FROM vn.buy b - JOIN edi.ekt e ON b.ektFk = e.id - JOIN edi.supplyResponse sr ON sr.Item_ArticleCode =e.`ref` - JOIN vn.item i ON i.id = b.itemFk - WHERE b.itemFk = itemFk - ORDER BY (sr.EmbalageCode = e.package) DESC - LIMIT 1; - RETURN vImageUrl; +BEGIN + DECLARE vImageUrl VARCHAR(255); + SELECT sr.PictureReference INTO vImageUrl + FROM vn.buy b + JOIN edi.ekt e ON b.ektFk = e.id + JOIN edi.supplyResponse sr ON sr.Item_ArticleCode =e.`ref` + JOIN vn.item i ON i.id = b.itemFk + WHERE b.itemFk = itemFk + ORDER BY (sr.EmbalageCode = e.package) DESC + LIMIT 1; + RETURN vImageUrl; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -46569,30 +46748,30 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `item_getPackage`(vItemFk INT) RETURNS varchar(50) CHARSET utf8 COLLATE utf8_unicode_ci DETERMINISTIC -BEGIN - - DECLARE vDiameter INT; - DECLARE vPackageFk VARCHAR(50); - DECLARE vCoeficient DOUBLE DEFAULT 1.08; - - SELECT MAX(LEFT(value,3)) INTO vDiameter - FROM vn.itemTag it - JOIN vn.tag t ON t.id = it.tagFk - WHERE it.itemFk = vItemFk - AND t.overwrite = 'diameter'; - - SELECT 8000 + FLOOR(vc.ccLength * vc.ccWidth / (vCoeficient * PI() * (vDiameter / 2) * (vDiameter / 2))) - INTO vPackageFk - FROM vn.volumeConfig vc; - - INSERT IGNORE INTO vn.packaging(id, width, `depth`) - SELECT vPackageFk, - FLOOR(vc.ccWidth / FLOOR(vc.ccWidth / vDiameter)), - FLOOR(vc.ccLength / FLOOR(vc.ccLength / vDiameter)) - FROM vn.volumeConfig vc; - - RETURN vPackageFk; - +BEGIN + + DECLARE vDiameter INT; + DECLARE vPackageFk VARCHAR(50); + DECLARE vCoeficient DOUBLE DEFAULT 1.08; + + SELECT MAX(LEFT(value,3)) INTO vDiameter + FROM vn.itemTag it + JOIN vn.tag t ON t.id = it.tagFk + WHERE it.itemFk = vItemFk + AND t.overwrite = 'diameter'; + + SELECT 8000 + FLOOR(vc.ccLength * vc.ccWidth / (vCoeficient * PI() * (vDiameter / 2) * (vDiameter / 2))) + INTO vPackageFk + FROM vn.volumeConfig vc; + + INSERT IGNORE INTO vn.packaging(id, width, `depth`) + SELECT vPackageFk, + FLOOR(vc.ccWidth / FLOOR(vc.ccWidth / vDiameter)), + FLOOR(vc.ccLength / FLOOR(vc.ccLength / vDiameter)) + FROM vn.volumeConfig vc; + + RETURN vPackageFk; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -46650,23 +46829,23 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `machineWorker_Worker`(vWorkerFk VARCHAR(10)) RETURNS varchar(20) CHARSET utf8 COLLATE utf8_unicode_ci READS SQL DATA -BEGIN -/** - * Comprueba si existen registros en las últimas 12 horas del trabajador vWorkerFk y si tiene a nulo la hora outTimed (indica la hora que deja el vehículo) - * - * @param vWorkerFk id del trabajador - * @return Devuelve REGISTERED/UNREGISTERED en caso de que haya registros - */ - - IF (SELECT COUNT(*) - FROM machineWorker m - WHERE m.workerFk = vWorkerFk - AND m.inTimed >= TIMESTAMPADD(HOUR , -12,NOW()) AND ISNULL(m.outTimed)) - THEN - RETURN "REGISTERED"; - ELSE - RETURN "UNREGISTERED"; - END IF; +BEGIN +/** + * Comprueba si existen registros en las últimas 12 horas del trabajador vWorkerFk y si tiene a nulo la hora outTimed (indica la hora que deja el vehículo) + * + * @param vWorkerFk id del trabajador + * @return Devuelve REGISTERED/UNREGISTERED en caso de que haya registros + */ + + IF (SELECT COUNT(*) + FROM machineWorker m + WHERE m.workerFk = vWorkerFk + AND m.inTimed >= TIMESTAMPADD(HOUR , -12,NOW()) AND ISNULL(m.outTimed)) + THEN + RETURN "REGISTERED"; + ELSE + RETURN "UNREGISTERED"; + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -46685,23 +46864,23 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `machine_checkPlate`(vPlate VARCHAR(10)) RETURNS tinyint(1) READS SQL DATA -BEGIN -/** - * Comprueba si existe matrícula - * - * @param vPlate matrícula del vehículo - * @return Devuelve TRUE en caso de que exista - * - */ - - IF (SELECT COUNT(*) - FROM machine m - WHERE m.plate = vPlate - ) THEN - RETURN TRUE; - ELSE - RETURN FALSE; - END IF; +BEGIN +/** + * Comprueba si existe matrícula + * + * @param vPlate matrícula del vehículo + * @return Devuelve TRUE en caso de que exista + * + */ + + IF (SELECT COUNT(*) + FROM machine m + WHERE m.plate = vPlate + ) THEN + RETURN TRUE; + ELSE + RETURN FALSE; + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -47184,27 +47363,27 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `specie_IsForbidden`(vItemFk INT, vAddressFk INT) RETURNS tinyint(1) READS SQL DATA -BEGIN - - DECLARE vIsForbbiden BOOL; - DECLARE vLeft INT; - - SELECT zg.lft INTO vLeft - FROM vn.address a - JOIN vn.zoneGeo zg ON zg.name = a.postalCode - WHERE a.id = vAddressFk; - - SELECT sgi.isForbidden INTO vIsForbbiden - FROM vn.specieGeoInvasive sgi - JOIN vn.zoneGeo zg ON zg.id = sgi.zoneGeofk - JOIN vn.itemBotanical ib ON ib.genusFk = sgi.genusFk AND sgi.specieFk IN ('sp.',ib.specieFk) - WHERE vLeft BETWEEN zg.lft AND zg.rgt - AND ib.itemFk = vItemFk - ORDER BY zg.`depth` DESC - LIMIT 1; - - RETURN IFNULL(vIsForbbiden, FALSE); - +BEGIN + + DECLARE vIsForbbiden BOOL; + DECLARE vLeft INT; + + SELECT zg.lft INTO vLeft + FROM vn.address a + JOIN vn.zoneGeo zg ON zg.name = a.postalCode + WHERE a.id = vAddressFk; + + SELECT sgi.isForbidden INTO vIsForbbiden + FROM vn.specieGeoInvasive sgi + JOIN vn.zoneGeo zg ON zg.id = sgi.zoneGeofk + JOIN vn.itemBotanical ib ON ib.genusFk = sgi.genusFk AND sgi.specieFk IN ('sp.',ib.specieFk) + WHERE vLeft BETWEEN zg.lft AND zg.rgt + AND ib.itemFk = vItemFk + ORDER BY zg.`depth` DESC + LIMIT 1; + + RETURN IFNULL(vIsForbbiden, FALSE); + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -47308,55 +47487,55 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `testNIE`(vNIE VARCHAR(9)) RETURNS tinyint(1) DETERMINISTIC -BEGIN - - DECLARE vIndice INT; - DECLARE vNumero VARCHAR(7); - DECLARE vOperador VARCHAR(9); - DECLARE vParteNumerica DECIMAL(8,0); - DECLARE vLetraInicial VARCHAR(1); - DECLARE vLetraFinal VARCHAR(1); - DECLARE vLetrasFinalesPosibles VARCHAR(24) DEFAULT "TRWAGMYFPDXBNJZSQVHLCKE"; - DECLARE vLetraInicialEsIncorrecta BOOL DEFAULT FALSE; - - SET vLetraInicial = SUBSTR(vNIE, 1, 1); - SET vLetraFinal = SUBSTR(vNIE, 9, 1); - SET vNumero = SUBSTR(vNIE, 2, 7); - - CASE vLetraInicial - - WHEN 'X' THEN - - SET vOperador = "0"; - - WHEN 'Y' THEN - - SET vOperador = "1"; - - WHEN 'Z' THEN - - SET vOperador = "2"; - - ELSE - - SET vLetraInicialEsIncorrecta = TRUE; - - END CASE; - - SET vOperador = CONCAT(vOperador, vNumero); - SET vParteNumerica = CAST(vOperador AS DECIMAL(8,0)); - SET vIndice = Round(vParteNumerica Mod 23, 0) + 1; - - IF SUBSTR(vLetrasFinalesPosibles, vIndice, 1) = vLetraFinal AND vLetraInicialEsIncorrecta = FALSE THEN - - RETURN TRUE; - - ELSE - - RETURN FALSE; - - END IF; - +BEGIN + + DECLARE vIndice INT; + DECLARE vNumero VARCHAR(7); + DECLARE vOperador VARCHAR(9); + DECLARE vParteNumerica DECIMAL(8,0); + DECLARE vLetraInicial VARCHAR(1); + DECLARE vLetraFinal VARCHAR(1); + DECLARE vLetrasFinalesPosibles VARCHAR(24) DEFAULT "TRWAGMYFPDXBNJZSQVHLCKE"; + DECLARE vLetraInicialEsIncorrecta BOOL DEFAULT FALSE; + + SET vLetraInicial = SUBSTR(vNIE, 1, 1); + SET vLetraFinal = SUBSTR(vNIE, 9, 1); + SET vNumero = SUBSTR(vNIE, 2, 7); + + CASE vLetraInicial + + WHEN 'X' THEN + + SET vOperador = "0"; + + WHEN 'Y' THEN + + SET vOperador = "1"; + + WHEN 'Z' THEN + + SET vOperador = "2"; + + ELSE + + SET vLetraInicialEsIncorrecta = TRUE; + + END CASE; + + SET vOperador = CONCAT(vOperador, vNumero); + SET vParteNumerica = CAST(vOperador AS DECIMAL(8,0)); + SET vIndice = Round(vParteNumerica Mod 23, 0) + 1; + + IF SUBSTR(vLetrasFinalesPosibles, vIndice, 1) = vLetraFinal AND vLetraInicialEsIncorrecta = FALSE THEN + + RETURN TRUE; + + ELSE + + RETURN FALSE; + + END IF; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -47375,29 +47554,29 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `testNIF`(vNIF VARCHAR(9)) RETURNS tinyint(1) DETERMINISTIC -BEGIN - - DECLARE vIndice INT; - DECLARE vParteNumerica DECIMAL(8,0); - DECLARE vLetra VARCHAR(1); - DECLARE vLetrasPosibles VARCHAR(24) DEFAULT "TRWAGMYFPDXBNJZSQVHLCKE"; - - SET vLetra = SUBSTRING(vNIF, 9, 1); - - SET vParteNumerica = CAST(SUBSTRING(vNIF, 1, 8) AS DECIMAL(8,0)); - - SET vIndice = Round(vParteNumerica MOD 23, 0) + 1; - - If SUBSTRING(vLetrasPosibles, vIndice, 1) = vLetra Then - - RETURN TRUE; - - ELSE - - RETURN FALSE; - - END IF; - +BEGIN + + DECLARE vIndice INT; + DECLARE vParteNumerica DECIMAL(8,0); + DECLARE vLetra VARCHAR(1); + DECLARE vLetrasPosibles VARCHAR(24) DEFAULT "TRWAGMYFPDXBNJZSQVHLCKE"; + + SET vLetra = SUBSTRING(vNIF, 9, 1); + + SET vParteNumerica = CAST(SUBSTRING(vNIF, 1, 8) AS DECIMAL(8,0)); + + SET vIndice = Round(vParteNumerica MOD 23, 0) + 1; + + If SUBSTRING(vLetrasPosibles, vIndice, 1) = vLetra Then + + RETURN TRUE; + + ELSE + + RETURN FALSE; + + END IF; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -47459,79 +47638,79 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `ticketPositionInPath`(vTicketId INT) RETURNS varchar(10) CHARSET utf8 DETERMINISTIC -BEGIN - - DECLARE vRestTicketsMaxOrder INT; - DECLARE vRestTicketsMinOrder INT; - DECLARE vRestTicketsPacking INT; - DECLARE vMyProductionOrder INT; - DECLARE vPosition VARCHAR(10) DEFAULT 'MID'; - DECLARE vMyPath INT; - DECLARE vMyWarehouse INT; - DECLARE PACKING_ORDER INT; - DECLARE vExpeditionsCount INT; - DECLARE vIsValenciaPath BOOLEAN DEFAULT FALSE; - -SELECT `order` - INTO PACKING_ORDER - FROM state - WHERE code = 'PACKING'; - -SELECT t.routeFk, t.warehouseFk, IFNULL(ts.productionOrder,0) - INTO vMyPath, vMyWarehouse, vMyProductionOrder - FROM ticket t - LEFT JOIN ticketState ts on ts.ticket = t.id - WHERE t.id = vTicketId; - -SELECT (ag.`name` = 'VN_VALENCIA') - INTO vIsValenciaPath - FROM vn2008.Rutas r - JOIN vn2008.Agencias a on a.Id_Agencia = r.Id_Agencia - JOIN vn2008.agency ag on ag.agency_id = a.agency_id - WHERE r.Id_Ruta = vMyPath; - -IF vIsValenciaPath THEN -- Rutas Valencia - - SELECT COUNT(*) - INTO vExpeditionsCount - FROM expedition e - JOIN ticket t ON t.id = e.ticketFk - WHERE t.routeFk = vMyPath; - - SELECT MAX(ts.productionOrder), MIN(ts.productionOrder) - INTO vRestTicketsMaxOrder, vRestTicketsMinOrder - FROM ticket t - LEFT JOIN ticketState ts on t.id = ts.ticket - WHERE t.routeFk = vMyPath - AND t.warehouseFk = vMyWarehouse - AND t.id != vTicketid; - - SELECT COUNT(*) - INTO vRestTicketsPacking - FROM ticket t - LEFT JOIN ticketState ts on t.id = ts.ticket - WHERE ts.productionOrder = PACKING_ORDER - AND t.routeFk = vMyPath - AND t.warehouseFk = vMyWarehouse - AND t.id != vTicketid; - - IF vExpeditionsCount = 1 THEN - SET vPosition = 'FIRST'; - ELSEIF vRestTicketsMinOrder > PACKING_ORDER THEN - SET vPosition = 'LAST'; - ELSEIF vRestTicketsPacking THEN - SET vPosition = 'SHARED'; - ELSE - SET vPosition = 'MID'; - END IF; - -ELSE - SET vPosition = 'MID'; - -END IF; - -RETURN vPosition; - +BEGIN + + DECLARE vRestTicketsMaxOrder INT; + DECLARE vRestTicketsMinOrder INT; + DECLARE vRestTicketsPacking INT; + DECLARE vMyProductionOrder INT; + DECLARE vPosition VARCHAR(10) DEFAULT 'MID'; + DECLARE vMyPath INT; + DECLARE vMyWarehouse INT; + DECLARE PACKING_ORDER INT; + DECLARE vExpeditionsCount INT; + DECLARE vIsValenciaPath BOOLEAN DEFAULT FALSE; + +SELECT `order` + INTO PACKING_ORDER + FROM state + WHERE code = 'PACKING'; + +SELECT t.routeFk, t.warehouseFk, IFNULL(ts.productionOrder,0) + INTO vMyPath, vMyWarehouse, vMyProductionOrder + FROM ticket t + LEFT JOIN ticketState ts on ts.ticket = t.id + WHERE t.id = vTicketId; + +SELECT (ag.`name` = 'VN_VALENCIA') + INTO vIsValenciaPath + FROM vn2008.Rutas r + JOIN vn2008.Agencias a on a.Id_Agencia = r.Id_Agencia + JOIN vn2008.agency ag on ag.agency_id = a.agency_id + WHERE r.Id_Ruta = vMyPath; + +IF vIsValenciaPath THEN -- Rutas Valencia + + SELECT COUNT(*) + INTO vExpeditionsCount + FROM expedition e + JOIN ticket t ON t.id = e.ticketFk + WHERE t.routeFk = vMyPath; + + SELECT MAX(ts.productionOrder), MIN(ts.productionOrder) + INTO vRestTicketsMaxOrder, vRestTicketsMinOrder + FROM ticket t + LEFT JOIN ticketState ts on t.id = ts.ticket + WHERE t.routeFk = vMyPath + AND t.warehouseFk = vMyWarehouse + AND t.id != vTicketid; + + SELECT COUNT(*) + INTO vRestTicketsPacking + FROM ticket t + LEFT JOIN ticketState ts on t.id = ts.ticket + WHERE ts.productionOrder = PACKING_ORDER + AND t.routeFk = vMyPath + AND t.warehouseFk = vMyWarehouse + AND t.id != vTicketid; + + IF vExpeditionsCount = 1 THEN + SET vPosition = 'FIRST'; + ELSEIF vRestTicketsMinOrder > PACKING_ORDER THEN + SET vPosition = 'LAST'; + ELSEIF vRestTicketsPacking THEN + SET vPosition = 'SHARED'; + ELSE + SET vPosition = 'MID'; + END IF; + +ELSE + SET vPosition = 'MID'; + +END IF; + +RETURN vPosition; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -47673,21 +47852,21 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `ticket_CC_volume`(vTicketFk INT) RETURNS decimal(10,1) READS SQL DATA -BEGIN - - DECLARE vCC DECIMAL(10,1); - - SELECT sum(sv.volume * IF(i.itemPackingTypeFk = 'H', vc.dutchCompressionRate, 1)) / (p.volume / 1000000) - INTO vCC - FROM vn.saleVolume sv - JOIN vn.sale s ON s.id = sv.saleFk - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.packaging p ON p.id = 'CC' - JOIN vn.volumeConfig vc - WHERE sv.ticketFk = vTicketFk; - - RETURN vCC; - +BEGIN + + DECLARE vCC DECIMAL(10,1); + + SELECT sum(sv.volume * IF(i.itemPackingTypeFk = 'H', vc.dutchCompressionRate, 1)) / (p.volume / 1000000) + INTO vCC + FROM vn.saleVolume sv + JOIN vn.sale s ON s.id = sv.saleFk + JOIN vn.item i ON i.id = s.itemFk + JOIN vn.packaging p ON p.id = 'CC' + JOIN vn.volumeConfig vc + WHERE sv.ticketFk = vTicketFk; + + RETURN vCC; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -47821,21 +48000,21 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `ticket_getWeight`(vTicketFk INT) RETURNS decimal(10,3) READS SQL DATA -BEGIN -/** - * Devuelve el peso total del ticket - * - * @return Total peso - */ - - DECLARE vWeight DECIMAL(10,3); - - SELECT sum(weight) INTO vWeight - FROM saleVolume - WHERE ticketFk = vTicketFk; - - RETURN vWeight; - +BEGIN +/** + * Devuelve el peso total del ticket + * + * @return Total peso + */ + + DECLARE vWeight DECIMAL(10,3); + + SELECT sum(weight) INTO vWeight + FROM saleVolume + WHERE ticketFk = vTicketFk; + + RETURN vWeight; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -47912,18 +48091,18 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `ticket_HasUbication`(vTicketFk INT) RETURNS tinyint(1) READS SQL DATA -BEGIN - - DECLARE hasUbication BOOL; - - SELECT COUNT(*) INTO hasUbication - FROM vn.ticket t - JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk - WHERE rm.beachFk - AND t.id = vTicketFk; - - RETURN hasUbication; - +BEGIN + + DECLARE hasUbication BOOL; + + SELECT COUNT(*) INTO hasUbication + FROM vn.ticket t + JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk + WHERE rm.beachFk + AND t.id = vTicketFk; + + RETURN hasUbication; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -48339,24 +48518,24 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `workerMachinery_isRegistered`(vWorkerFk VARCHAR(10)) RETURNS tinyint(1) READS SQL DATA -BEGIN -/** - * Comprueba si existen registros en las últimas horas (maxHours de machineWorkerConfig) del trabajador vWorkerFk y si tiene a nulo la hora outTimed (indica la hora que deja el vehículo) - * - * @param vWorkerFk id del trabajador - * @return Devuelve TRUE/FALSE en caso de que haya o no registros - */ - - IF (SELECT COUNT(*) - FROM machineWorker m - WHERE m.workerFk = vWorkerFk - AND m.inTimed >= TIMESTAMPADD(HOUR , -(SELECT maxHours from machineWorkerConfig), NOW()) AND ISNULL(m.outTimed)) - THEN - RETURN TRUE; - ELSE - RETURN FALSE; - END IF; - +BEGIN +/** + * Comprueba si existen registros en las últimas horas (maxHours de machineWorkerConfig) del trabajador vWorkerFk y si tiene a nulo la hora outTimed (indica la hora que deja el vehículo) + * + * @param vWorkerFk id del trabajador + * @return Devuelve TRUE/FALSE en caso de que haya o no registros + */ + + IF (SELECT COUNT(*) + FROM machineWorker m + WHERE m.workerFk = vWorkerFk + AND m.inTimed >= TIMESTAMPADD(HOUR , -(SELECT maxHours from machineWorkerConfig), NOW()) AND ISNULL(m.outTimed)) + THEN + RETURN TRUE; + ELSE + RETURN FALSE; + END IF; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -48975,23 +49154,23 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `agencyVolume__`(vDated DATE, vAgency INT) -BEGIN - - SELECT ELT(it.temperature + 1,'Calientes','Frios','Secos') AS Temp, - CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) * - vn.item_getVolume(b.itemFk ,b.packageFk)) / vc.carro / 1000000 ,1) AS DECIMAL(10,2)) AS carros , - CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) * - vn.item_getVolume(b.itemFk ,b.packageFk)) / vc.espai / 1000000,1) AS DECIMAL(10,2)) AS espais - FROM vn.buy b - INNER JOIN vn.entry e ON e.id = b.entryFk - INNER JOIN vn.travel tr ON tr.id = e.travelFk - INNER JOIN vn.volumeConfig vc - INNER JOIN vn.item i ON i.id = b.itemFk - INNER JOIN vn.itemType it ON it.id = i.typeFk - WHERE tr.landed = vDated - AND tr.agencyFk IN (0, vAgency) - GROUP BY Temp; - +BEGIN + + SELECT ELT(it.temperature + 1,'Calientes','Frios','Secos') AS Temp, + CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) * + vn.item_getVolume(b.itemFk ,b.packageFk)) / vc.carro / 1000000 ,1) AS DECIMAL(10,2)) AS carros , + CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) * + vn.item_getVolume(b.itemFk ,b.packageFk)) / vc.espai / 1000000,1) AS DECIMAL(10,2)) AS espais + FROM vn.buy b + INNER JOIN vn.entry e ON e.id = b.entryFk + INNER JOIN vn.travel tr ON tr.id = e.travelFk + INNER JOIN vn.volumeConfig vc + INNER JOIN vn.item i ON i.id = b.itemFk + INNER JOIN vn.itemType it ON it.id = i.typeFk + WHERE tr.landed = vDated + AND tr.agencyFk IN (0, vAgency) + GROUP BY Temp; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -49184,40 +49363,40 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `buyUltimate`(vWarehouseFk SMALLINT, vDated DATE) -BEGIN -/** - * Calcula las últimas compras realizadas hasta una fecha - * - * @param vWarehouseFk Id del almacén - * @param vDated Compras hasta fecha - * @return tmp.buyUltimate - */ - CALL cache.last_buy_refresh (FALSE); - - DROP TEMPORARY TABLE IF EXISTS tmp.buyUltimate; - CREATE TEMPORARY TABLE tmp.buyUltimate - (PRIMARY KEY (itemFk, warehouseFk), - INDEX(itemFk)) - ENGINE = MEMORY - SELECT item_id itemFk, buy_id buyFk, warehouse_id warehouseFk, landing - FROM cache.last_buy - WHERE warehouse_id = vWarehouseFk OR vWarehouseFk IS NULL; - - CALL buyUltimateFromInterval(vWarehouseFk, CURDATE(), vDated); - - REPLACE INTO tmp.buyUltimate - SELECT itemFk, buyFk, warehouseFk, landed landing - FROM tmp.buyUltimateFromInterval - WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL) - AND landed <= vDated; - - INSERT IGNORE INTO tmp.buyUltimate - SELECT itemFk, buyFk, warehouseFk, landed landing - FROM tmp.buyUltimateFromInterval - WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL) - AND landed > vDated; - - DROP TEMPORARY TABLE tmp.buyUltimateFromInterval; +BEGIN +/** + * Calcula las últimas compras realizadas hasta una fecha + * + * @param vWarehouseFk Id del almacén + * @param vDated Compras hasta fecha + * @return tmp.buyUltimate + */ + CALL cache.last_buy_refresh (FALSE); + + DROP TEMPORARY TABLE IF EXISTS tmp.buyUltimate; + CREATE TEMPORARY TABLE tmp.buyUltimate + (PRIMARY KEY (itemFk, warehouseFk), + INDEX(itemFk)) + ENGINE = MEMORY + SELECT item_id itemFk, buy_id buyFk, warehouse_id warehouseFk, landing + FROM cache.last_buy + WHERE warehouse_id = vWarehouseFk OR vWarehouseFk IS NULL; + + CALL buyUltimateFromInterval(vWarehouseFk, CURDATE(), vDated); + + REPLACE INTO tmp.buyUltimate + SELECT itemFk, buyFk, warehouseFk, landed landing + FROM tmp.buyUltimateFromInterval + WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL) + AND landed <= vDated; + + INSERT IGNORE INTO tmp.buyUltimate + SELECT itemFk, buyFk, warehouseFk, landed landing + FROM tmp.buyUltimateFromInterval + WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL) + AND landed > vDated; + + DROP TEMPORARY TABLE tmp.buyUltimateFromInterval; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -49235,126 +49414,126 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `buyUltimateFromInterval`(vWarehouseFk SMALLINT, vStarted DATE, vEnded DATE) -BEGIN -/** - * Calcula las últimas compras realizadas - * desde un rango de fechas. - * - * @param vWarehouseFk Id del almacén si es NULL se actualizan todos - * @param vStarted Fecha inicial - * @param vEnded Fecha fin - * @return tmp.buyUltimateFromInterval - */ - IF vEnded IS NULL THEN - SET vEnded = vStarted; - END IF; - - IF vEnded < vStarted THEN - SET vStarted = TIMESTAMPADD(MONTH, -1, vEnded); - END IF; - - -- Item - - DROP TEMPORARY TABLE IF EXISTS tmp.buyUltimateFromInterval; - CREATE TEMPORARY TABLE tmp.buyUltimateFromInterval - (PRIMARY KEY (itemFk, warehouseFk), INDEX(buyFk), INDEX(landed), INDEX(warehouseFk), INDEX(itemFk)) - ENGINE = MEMORY - SELECT - b.itemFk, - t.warehouseInFk warehouseFk, - MULTIMAX(t.landed, b.id) buyFk, - MAX(t.landed) landed - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - WHERE t.landed BETWEEN vStarted AND vEnded - AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) - AND b.price2 > 0 - AND NOT b.isIgnored - AND b.quantity > 0 - GROUP BY itemFk, warehouseInFk; - - INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed) - SELECT - b.itemFk, - t.warehouseInFk warehouseFk, - b.id buyFk, - t.landed - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - WHERE t.landed > vEnded - AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) - AND b.price2 > 0 - AND NOT b.isIgnored - GROUP BY itemFk, warehouseInFk; - - INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed) - SELECT - b.itemFk, - t.warehouseInFk warehouseFk, - b.id buyFk, - t.landed - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - WHERE t.landed BETWEEN vStarted AND vEnded - AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) - AND b.quantity = 0 - GROUP BY itemFk, warehouseInFk; - - - - -- ItemOriginal - - INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed) - SELECT - b.itemFk, - t.warehouseInFk warehouseFk, - MULTIMAX(t.landed, b.id) buyFk, - MAX(t.landed) landed - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - WHERE t.landed BETWEEN vStarted AND vEnded - AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) - AND b.price2 > 0 - AND NOT b.isIgnored - AND b.quantity > 0 - AND itemOriginalFk - GROUP BY itemOriginalFk, warehouseInFk; - - INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed) - SELECT - b.itemFk, - t.warehouseInFk warehouseFk, - b.id buyFk, - t.landed - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - WHERE t.landed > vEnded - AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) - AND b.price2 > 0 - AND NOT b.isIgnored - AND itemOriginalFk - GROUP BY itemOriginalFk, warehouseInFk; - - INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed) - SELECT - b.itemFk, - t.warehouseInFk warehouseFk, - b.id buyFk, - t.landed - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - WHERE t.landed BETWEEN vStarted AND vEnded - AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) - AND b.quantity = 0 - AND itemOriginalFk - GROUP BY itemOriginalFk, warehouseInFk; - +BEGIN +/** + * Calcula las últimas compras realizadas + * desde un rango de fechas. + * + * @param vWarehouseFk Id del almacén si es NULL se actualizan todos + * @param vStarted Fecha inicial + * @param vEnded Fecha fin + * @return tmp.buyUltimateFromInterval + */ + IF vEnded IS NULL THEN + SET vEnded = vStarted; + END IF; + + IF vEnded < vStarted THEN + SET vStarted = TIMESTAMPADD(MONTH, -1, vEnded); + END IF; + + -- Item + + DROP TEMPORARY TABLE IF EXISTS tmp.buyUltimateFromInterval; + CREATE TEMPORARY TABLE tmp.buyUltimateFromInterval + (PRIMARY KEY (itemFk, warehouseFk), INDEX(buyFk), INDEX(landed), INDEX(warehouseFk), INDEX(itemFk)) + ENGINE = MEMORY + SELECT + b.itemFk, + t.warehouseInFk warehouseFk, + MULTIMAX(t.landed, b.id) buyFk, + MAX(t.landed) landed + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + WHERE t.landed BETWEEN vStarted AND vEnded + AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) + AND b.price2 > 0 + AND NOT b.isIgnored + AND b.quantity > 0 + GROUP BY itemFk, warehouseInFk; + + INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed) + SELECT + b.itemFk, + t.warehouseInFk warehouseFk, + b.id buyFk, + t.landed + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + WHERE t.landed > vEnded + AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) + AND b.price2 > 0 + AND NOT b.isIgnored + GROUP BY itemFk, warehouseInFk; + + INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed) + SELECT + b.itemFk, + t.warehouseInFk warehouseFk, + b.id buyFk, + t.landed + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + WHERE t.landed BETWEEN vStarted AND vEnded + AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) + AND b.quantity = 0 + GROUP BY itemFk, warehouseInFk; + + + + -- ItemOriginal + + INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed) + SELECT + b.itemFk, + t.warehouseInFk warehouseFk, + MULTIMAX(t.landed, b.id) buyFk, + MAX(t.landed) landed + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + WHERE t.landed BETWEEN vStarted AND vEnded + AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) + AND b.price2 > 0 + AND NOT b.isIgnored + AND b.quantity > 0 + AND itemOriginalFk + GROUP BY itemOriginalFk, warehouseInFk; + + INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed) + SELECT + b.itemFk, + t.warehouseInFk warehouseFk, + b.id buyFk, + t.landed + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + WHERE t.landed > vEnded + AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) + AND b.price2 > 0 + AND NOT b.isIgnored + AND itemOriginalFk + GROUP BY itemOriginalFk, warehouseInFk; + + INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed) + SELECT + b.itemFk, + t.warehouseInFk warehouseFk, + b.id buyFk, + t.landed + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + WHERE t.landed BETWEEN vStarted AND vEnded + AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) + AND b.quantity = 0 + AND itemOriginalFk + GROUP BY itemOriginalFk, warehouseInFk; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -49423,67 +49602,67 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_afterUpsert`(vSelf INT) -BEGIN -/** - * Triggered actions when a buy is updated or inserted. - * - * @param vSelf The buy reference - */ - DECLARE vEntryFk INT; - DECLARE vItemFk INT; - DECLARE vPackingOut DECIMAL(10,2); - DECLARE vWarehouse INT; - DECLARE vStandardFlowerBox INT; - DECLARE vWarehouseOut INT; - DECLARE vIsMerchandise BOOL; - DECLARE vIsFeedStock BOOL; - - 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 - INTO vWarehouse, vWarehouseOut - FROM entry e - JOIN travel t ON t.id = e.travelFk - WHERE e.id = vEntryFk; - - IF vIsMerchandise THEN - - REPLACE itemCost SET - itemFk = vItemFk, - warehouseFk = vWarehouse, - cm3 = buy_getUnitVolume(vSelf), - cm3Delivery = IFNULL((vStandardFlowerBox * 1000) / vPackingOut, buy_getUnitVolume(vSelf)); - - UPDATE vn.itemCost ic - JOIN cache.last_buy lb ON lb.item_id = ic.itemFk AND lb.warehouse_id = ic.warehouseFk - JOIN vn.buy b ON b.id = lb.buy_id - SET ic.grams = b.weight * 1000 / b.packing - WHERE ic.itemFk = vItemFk AND - ic.warehouseFk = vWarehouse; - - END IF; - - SELECT isFeedStock INTO vIsFeedStock - FROM warehouse WHERE id = vWarehouseOut AND id <> 13; - - IF vIsFeedStock THEN - INSERT IGNORE INTO producer(`name`) - SELECT es.company_name - FROM buy b - JOIN edi.ekt be ON be.id = b.ektFk - JOIN edi.supplier es ON es.supplier_id = be.pro - WHERE b.id = vSelf; - - END IF; - +BEGIN +/** + * Triggered actions when a buy is updated or inserted. + * + * @param vSelf The buy reference + */ + DECLARE vEntryFk INT; + DECLARE vItemFk INT; + DECLARE vPackingOut DECIMAL(10,2); + DECLARE vWarehouse INT; + DECLARE vStandardFlowerBox INT; + DECLARE vWarehouseOut INT; + DECLARE vIsMerchandise BOOL; + DECLARE vIsFeedStock BOOL; + + 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 + INTO vWarehouse, vWarehouseOut + FROM entry e + JOIN travel t ON t.id = e.travelFk + WHERE e.id = vEntryFk; + + IF vIsMerchandise THEN + + REPLACE itemCost SET + itemFk = vItemFk, + warehouseFk = vWarehouse, + cm3 = buy_getUnitVolume(vSelf), + cm3Delivery = IFNULL((vStandardFlowerBox * 1000) / vPackingOut, buy_getUnitVolume(vSelf)); + + UPDATE vn.itemCost ic + JOIN cache.last_buy lb ON lb.item_id = ic.itemFk AND lb.warehouse_id = ic.warehouseFk + JOIN vn.buy b ON b.id = lb.buy_id + SET ic.grams = b.weight * 1000 / b.packing + WHERE ic.itemFk = vItemFk AND + ic.warehouseFk = vWarehouse; + + END IF; + + SELECT isFeedStock INTO vIsFeedStock + FROM warehouse WHERE id = vWarehouseOut AND id <> 13; + + IF vIsFeedStock THEN + INSERT IGNORE INTO producer(`name`) + SELECT es.company_name + FROM buy b + JOIN edi.ekt be ON be.id = b.ektFk + JOIN edi.supplier es ON es.supplier_id = be.pro + WHERE b.id = vSelf; + + END IF; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -49749,24 +49928,24 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` 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()); - - 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; +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()); + + 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 */ ; @@ -50126,13 +50305,361 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET character_set_client = 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 = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `catalog_calculate`( +CREATE DEFINER=`root`@`localhost` PROCEDURE `catalog_calculate`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT) +BEGIN + + /** + * Calcula los articulos disponibles y sus precios + * + * @table tmp.item(itemFk) Listado de artículos a calcular + * @param vLanded Fecha de recepcion de mercancia + * @param vAddressFk Id del consignatario + * @param vAgencyModeFk Id de la agencia + * @return tmp.ticketCalculateItem(itemFk, available, producer, + * item, size, stems, category, inkFk, image, origin, price) + * @return tmp.ticketLot(warehouseFk, itemFk, available, buyFk) + * @return tmp.ticketComponent + * @return tmp.ticketComponentPrice + */ + + DECLARE vAvailableCalc INT; + DECLARE vAvailableNoRaidsCalc INT; + DECLARE vShipped DATE; + DECLARE vWarehouseFk SMALLINT; + DECLARE vZoneFk INT; + DECLARE vDone BOOL; + DECLARE cTravelTree CURSOR FOR + SELECT zoneFk, warehouseFk, shipped FROM tmp.zoneGetShipped; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + CALL vn.zone_getShipped (vLanded, vAddressFk, vAgencyModeFk, FALSE); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; + CREATE TEMPORARY TABLE tmp.ticketLot( + `warehouseFk` smallint(5) unsigned NOT NULL, + `itemFk` int(11) NOT NULL, + `available` double DEFAULT NULL, + `buyFk` int(11) DEFAULT NULL, + `fix` tinyint(3) unsigned DEFAULT '0', -- este campo parece obsoleto + `zoneFk` int(11) NOT NULL, + KEY `itemFk` (`itemFk`), + KEY `item_warehouse` (`itemFk`,`warehouseFk`) USING HASH + ) ENGINE=MEMORY DEFAULT CHARSET=utf8; + + CALL catalog_componentPrepare(); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketCalculateItem; + CREATE TEMPORARY TABLE tmp.ticketCalculateItem( + itemFk INT(11) NOT NULL, + available INT(11), + producer VARCHAR(50), + item VARCHAR(50), + size INT(10) UNSIGNED, + stems INT(11), + category VARCHAR(3), + inkFk VARCHAR(3), + image VARCHAR(50), + origin VARCHAR(3), + price DECIMAL(10,2), + priceKg DECIMAL(10,2), + PRIMARY KEY `itemFk` (`itemFk`) + ) ENGINE = MEMORY DEFAULT CHARSET=utf8; + + OPEN cTravelTree; + + l: LOOP + SET vDone = FALSE; + FETCH cTravelTree INTO vZoneFk, vWarehouseFk, vShipped; + + IF vDone THEN + LEAVE l; + END IF; + + CALL `cache`.available_refresh (vAvailableCalc, FALSE, vWarehouseFk, vShipped); + CALL `cache`.availableNoRaids_refresh (vAvailableNoRaidsCalc, FALSE, vWarehouseFk, vShipped); + CALL vn.buyUltimate(vWarehouseFk, vShipped); + + INSERT INTO tmp.ticketLot (warehouseFk, itemFk, available, buyFk, zoneFk) + SELECT vWarehouseFk, + a.item_id, + IFNULL(a.available, 0), + bu.buyFk, + vZoneFk + FROM `cache`.available a + LEFT JOIN cache.availableNoRaids anr ON anr.item_id = a.item_id + AND anr.calc_id = vAvailableNoRaidsCalc + JOIN tmp.item i ON i.itemFk = a.item_id + JOIN vn.item it ON it.id = i.itemFk + LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = a.item_id + LEFT JOIN edi.supplyOffer so ON so.srId = it.supplyResponseFk + LEFT JOIN (SELECT isVNHSupplier, isEarlyBird, TRUE AS itemAllowed + FROM vn.addressFilter af + JOIN (SELECT ad.provinceFk, p.countryFk, ad.isLogifloraAllowed + FROM vn.address ad + JOIN vn.province p ON p.id = ad.provinceFk + WHERE ad.id = vAddressFk + ) sub2 ON sub2.provinceFk <=> IFNULL(af.provinceFk, sub2.provinceFk) + AND sub2.countryFk <=> IFNULL(af.countryFk, sub2.countryFk) + AND sub2.isLogifloraAllowed <=> IFNULL(af.isLogifloraAllowed, sub2.isLogifloraAllowed) + WHERE vWarehouseFk = af.warehouseFk + ) sub ON sub.isVNHSupplier = so.isVNHSupplier + AND IFNULL(sub.isEarlyBird, so.isEarlyBird) = so.isEarlyBird + JOIN vn.agencyMode am ON am.id = vAgencyModeFk + JOIN vn.agency ag ON ag.id = am.agencyFk + JOIN vn.itemType itt ON itt.id = it.typeFk + WHERE a.calc_id = vAvailableCalc + AND a.available > 0 + AND (sub.itemAllowed OR NOT it.isFloramondo OR anr.available > 0) + AND (ag.isAnyVolumeAllowed OR NOT itt.isUnconventionalSize); + + DROP TEMPORARY TABLE tmp.buyUltimate; + + CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk); + + INSERT INTO tmp.ticketCalculateItem ( + itemFk, + available, + producer, + item, + size, + stems, + category, + inkFk, + image, + origin, + price, + priceKg) + SELECT + tl.itemFk, + SUM(tl.available) available, + p.name producer, + i.name item, + i.size size, + i.stems, + i.category, + i.inkFk, + i.image, + o.code origin, + bl.price, + bl.priceKg + FROM tmp.ticketLot tl + JOIN item i ON tl.itemFk = i.id + LEFT JOIN producer p ON p.id = i.producerFk AND p.isVisible + JOIN origin o ON o.id = i.originFk + JOIN ( + SELECT * + FROM (SELECT price, itemFk, priceKg + FROM tmp.ticketComponentPrice + WHERE warehouseFk = vWarehouseFk + ORDER BY (rate = 2) DESC) sub + GROUP BY itemFk + ) bl ON bl.itemFk = tl.itemFk + WHERE tl.zoneFk = vZoneFk AND tl.warehouseFk = vWarehouseFk + GROUP BY tl.itemFk + ON DUPLICATE KEY UPDATE available = available + VALUES(available); + + END LOOP; + + CLOSE cTravelTree; + +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 `catalog_calculate_beta` */; +/*!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`@`localhost` PROCEDURE `catalog_calculate_beta`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT) +BEGIN + + /** + * Calcula los articulos disponibles y sus precios + * + * @table tmp.item(itemFk) Listado de artículos a calcular + * @param vLanded Fecha de recepcion de mercancia + * @param vAddressFk Id del consignatario + * @param vAgencyModeFk Id de la agencia + * @return tmp.ticketCalculateItem(itemFk, available, producer, + * item, size, stems, category, inkFk, image, origin, price) + * @return tmp.ticketLot(warehouseFk, itemFk, available, buyFk) + * @return tmp.ticketComponent + * @return tmp.ticketComponentPrice + */ + + DECLARE vAvailableCalc INT; + DECLARE vAvailableNoRaidsCalc INT; + DECLARE vShipped DATE; + DECLARE vWarehouseFk SMALLINT; + DECLARE vZoneFk INT; + DECLARE vDone BOOL; + DECLARE cTravelTree CURSOR FOR + SELECT zoneFk, warehouseFk, shipped FROM tmp.zoneGetShipped; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + CALL vn.zone_getShipped (vLanded, vAddressFk, vAgencyModeFk, FALSE); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; + CREATE TEMPORARY TABLE tmp.ticketLot( + `warehouseFk` smallint(5) unsigned NOT NULL, + `itemFk` int(11) NOT NULL, + `available` double DEFAULT NULL, + `buyFk` int(11) DEFAULT NULL, + `fix` tinyint(3) unsigned DEFAULT '0', -- este campo parece obsoleto + `zoneFk` int(11) NOT NULL, + KEY `itemFk` (`itemFk`), + KEY `item_warehouse` (`itemFk`,`warehouseFk`) USING HASH + ) ENGINE=MEMORY DEFAULT CHARSET=utf8; + + CALL catalog_componentPrepare(); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketCalculateItem; + CREATE TEMPORARY TABLE tmp.ticketCalculateItem( + itemFk INT(11) NOT NULL, + available INT(11), + producer VARCHAR(50), + item VARCHAR(50), + size INT(10) UNSIGNED, + stems INT(11), + category VARCHAR(3), + inkFk VARCHAR(3), + image VARCHAR(50), + origin VARCHAR(3), + price DECIMAL(10,2), + priceKg DECIMAL(10,2), + PRIMARY KEY `itemFk` (`itemFk`) + ) ENGINE = MEMORY DEFAULT CHARSET=utf8; + + OPEN cTravelTree; + + l: LOOP + SET vDone = FALSE; + FETCH cTravelTree INTO vZoneFk, vWarehouseFk, vShipped; + + IF vDone THEN + LEAVE l; + END IF; + + CALL `cache`.available_refresh (vAvailableCalc, FALSE, vWarehouseFk, vShipped); + CALL `cache`.availableNoRaids_refresh (vAvailableNoRaidsCalc, FALSE, vWarehouseFk, vShipped); + CALL vn.buyUltimate(vWarehouseFk, vShipped); + + INSERT INTO tmp.ticketLot (warehouseFk, itemFk, available, buyFk, zoneFk) + SELECT vWarehouseFk, + a.item_id, + IFNULL(a.available, 0), + bu.buyFk, + vZoneFk + FROM `cache`.available a + LEFT JOIN cache.availableNoRaids anr ON anr.item_id = a.item_id + AND anr.calc_id = vAvailableNoRaidsCalc + JOIN tmp.item i ON i.itemFk = a.item_id + JOIN vn.item it ON it.id = i.itemFk + LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = a.item_id + LEFT JOIN edi.supplyOffer so ON so.srId = it.supplyResponseFk + LEFT JOIN (SELECT isVNHSupplier, isEarlyBird, TRUE AS itemAllowed + FROM vn.addressFilter af + JOIN (SELECT ad.provinceFk, p.countryFk, ad.isLogifloraAllowed + FROM vn.address ad + JOIN vn.province p ON p.id = ad.provinceFk + WHERE ad.id = vAddressFk + ) sub2 ON sub2.provinceFk <=> IFNULL(af.provinceFk, sub2.provinceFk) + AND sub2.countryFk <=> IFNULL(af.countryFk, sub2.countryFk) + AND sub2.isLogifloraAllowed <=> IFNULL(af.isLogifloraAllowed, sub2.isLogifloraAllowed) + WHERE vWarehouseFk = af.warehouseFk + ) sub ON sub.isVNHSupplier = so.isVNHSupplier + AND IFNULL(sub.isEarlyBird, so.isEarlyBird) = so.isEarlyBird + JOIN vn.agencyMode am ON am.id = vAgencyModeFk + JOIN vn.agency ag ON ag.id = am.agencyFk + JOIN vn.itemType itt ON itt.id = it.typeFk + WHERE a.calc_id = vAvailableCalc + AND a.available > 0 + AND (sub.itemAllowed OR NOT it.isFloramondo OR anr.available > 0) + AND (ag.isAnyVolumeAllowed OR NOT itt.isUnconventionalSize); + + DROP TEMPORARY TABLE tmp.buyUltimate; + + CALL vn.catalog_componentCalculate_beta(vZoneFk, vAddressFk, vShipped, vWarehouseFk); + + INSERT INTO tmp.ticketCalculateItem ( + itemFk, + available, + producer, + item, + size, + stems, + category, + inkFk, + image, + origin, + price, + priceKg) + SELECT + tl.itemFk, + SUM(tl.available) available, + p.name producer, + i.name item, + i.size size, + i.stems, + i.category, + i.inkFk, + i.image, + o.code origin, + bl.price, + bl.priceKg + FROM tmp.ticketLot tl + JOIN item i ON tl.itemFk = i.id + LEFT JOIN producer p ON p.id = i.producerFk AND p.isVisible + JOIN origin o ON o.id = i.originFk + JOIN ( + SELECT * + FROM (SELECT price, itemFk, priceKg + FROM tmp.ticketComponentPrice + WHERE warehouseFk = vWarehouseFk + ORDER BY (rate = 2) DESC) sub + GROUP BY itemFk + ) bl ON bl.itemFk = tl.itemFk + WHERE tl.zoneFk = vZoneFk AND tl.warehouseFk = vWarehouseFk + GROUP BY tl.itemFk + ON DUPLICATE KEY UPDATE available = available + VALUES(available); + + END LOOP; + + CLOSE cTravelTree; + +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 `catalog_calculate__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = 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`@`localhost` PROCEDURE `catalog_calculate__`( vLanded DATE, vAddressFk INT, vAgencyModeFk INT) @@ -50281,193 +50808,707 @@ 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 `catalog_calculate_beta` */; +/*!50003 DROP PROCEDURE IF EXISTS `catalog_componentCalculate` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET character_set_client = 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 = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `catalog_calculate_beta`( - vLanded DATE, - vAddressFk INT, - vAgencyModeFk INT) -proc: BEGIN -/** - * Calcula los articulos disponibles y sus precios - * - * @table tmp.item(itemFk) Listado de artículos a calcular - * @param vLanded Fecha de recepcion de mercancia - * @param vAddressFk Id del consignatario - * @param vAgencyModeFk Id de la agencia - * @return tmp.ticketCalculateItem(itemFk, available, producer, - * item, size, stems, category, inkFk, image, origin, price) - * @return tmp.ticketLot(warehouseFk, itemFk, available, buyFk) - * @return tmp.ticketComponent - * @return tmp.ticketComponentPrice - */ - - DECLARE vAvailableCalc INT; - DECLARE vAvailableNoRaidsCalc INT; - DECLARE vShipped DATE; - DECLARE vWarehouseFk SMALLINT; - DECLARE vZoneFk INT; - DECLARE vDone BOOL; - DECLARE cTravelTree CURSOR FOR - SELECT zoneFk, warehouseFk, shipped FROM tmp.zoneGetShipped; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - -- Establece los almacenes y las fechas que van a entrar al disponible - CALL vn.zone_getShipped (vLanded, vAddressFk, vAgencyModeFk, FALSE); - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; - CREATE TEMPORARY TABLE tmp.ticketLot( - `warehouseFk` smallint(5) unsigned NOT NULL, - `itemFk` int(11) NOT NULL, - `available` double DEFAULT NULL, - `buyFk` int(11) DEFAULT NULL, - `fix` tinyint(3) unsigned DEFAULT '0', -- este campo parece obsoleto - `zoneFk` int(11) NOT NULL, - KEY `itemFk` (`itemFk`), - KEY `item_warehouse` (`itemFk`,`warehouseFk`) USING HASH - ) ENGINE=MEMORY DEFAULT CHARSET=utf8; - - CALL catalog_componentPrepare(); - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketCalculateItem; - CREATE TEMPORARY TABLE tmp.ticketCalculateItem( - itemFk INT(11) NOT NULL, - available INT(11), - producer VARCHAR(50), - item VARCHAR(50), - size INT(10) UNSIGNED, - stems INT(11), - category VARCHAR(3), - inkFk VARCHAR(3), - image VARCHAR(50), - origin VARCHAR(3), - price DECIMAL(10,2), - priceKg DECIMAL(10,2), - PRIMARY KEY `itemFk` (`itemFk`) - ) ENGINE = MEMORY DEFAULT CHARSET=utf8; - - OPEN cTravelTree; - - l: LOOP - SET vDone = FALSE; - FETCH cTravelTree INTO vZoneFk, vWarehouseFk, vShipped; - - IF vDone THEN - LEAVE l; - END IF; - - CALL `cache`.available_refresh (vAvailableCalc, FALSE, vWarehouseFk, vShipped); - CALL `cache`.availableNoRaids_refresh (vAvailableNoRaidsCalc, FALSE, vWarehouseFk, vShipped); - CALL vn.buyUltimate (vWarehouseFk, vShipped); - - INSERT INTO tmp.ticketLot (warehouseFk, itemFk, available, buyFk, zoneFk) - SELECT vWarehouseFk, - a.item_id, - IFNULL(a.available, 0), - bu.buyFk, - vZoneFk - FROM `cache`.available a - LEFT JOIN cache.availableNoRaids anr ON anr.item_id = a.item_id - AND anr.calc_id = vAvailableNoRaidsCalc - JOIN tmp.item i ON i.itemFk = a.item_id - JOIN vn.item it ON it.id = i.itemFk - LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = a.item_id - LEFT JOIN edi.supplyOffer so ON so.srId = it.supplyResponseFk - LEFT JOIN (SELECT isVNHSupplier, isEarlyBird, TRUE AS itemAllowed - FROM vn.addressFilter af - JOIN (SELECT ad.provinceFk, p.countryFk, ad.isLogifloraAllowed - FROM vn.address ad - JOIN vn.province p ON p.id = ad.provinceFk - WHERE ad.id = vAddressFk - ) sub2 ON sub2.provinceFk <=> IFNULL(af.provinceFk, sub2.provinceFk) - AND sub2.countryFk <=> IFNULL(af.countryFk, sub2.countryFk) - AND sub2.isLogifloraAllowed <=> IFNULL(af.isLogifloraAllowed, sub2.isLogifloraAllowed) - WHERE vWarehouseFk = af.warehouseFk - ) sub ON sub.isVNHSupplier = so.isVNHSupplier - AND IFNULL(sub.isEarlyBird, so.isEarlyBird) = so.isEarlyBird - WHERE a.calc_id = vAvailableCalc - AND a.available > 0 - AND (sub.itemAllowed OR NOT it.isFloramondo OR anr.available > 0) - ; - - CALL util.debugAdd('ticketLot_beta: ', (SELECT COUNT(*) FROM tmp.ticketLot)); +CREATE DEFINER=`root`@`localhost` PROCEDURE `catalog_componentCalculate`( vZoneFk INT, + vAddressFk INT, + vShipped DATE, + vWarehouseFk INT) +BEGIN + /** + * Calcula los componentes de los articulos de tmp.ticketLot + * + * @param vZoneFk para calcular el transporte + * @param vAddressFk Consignatario + * @param vShipped dia de salida del pedido + * @param vWarehouseFk warehouse de salida del pedido + * @table tmp.ticketLot (warehouseFk, available, itemFk, buyFk, zoneFk) + * @table tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost) + * + * @return tmp.ticketComponentPrice (warehouseFk, itemFk, rate, `grouping`, price, priceKg) + */ - DROP TEMPORARY TABLE tmp.buyUltimate; + DECLARE vClientFk INT; + DECLARE vIsFrenchVNHBuyer BOOLEAN DEFAULT FALSE; + DECLARE vVNHWarehouseFk INT DEFAULT 7; + DECLARE vFrenchDiscount DECIMAL(3,2) DEFAULT 0.12; - CALL vn.catalog_componentCalculate_beta(vZoneFk, vAddressFk, vShipped, vWarehouseFk); + SELECT clientFk INTO vClientFK + FROM address + WHERE id = vAddressFk; - INSERT INTO tmp.ticketCalculateItem ( - itemFk, - available, - producer, - item, - size, - stems, - category, - inkFk, - image, - origin, - price, - priceKg) + SELECT (c.country = 'FRANCIA' AND vWarehouseFk = vVNHWarehouseFk) + INTO vIsFrenchVNHBuyer + FROM vn.country c + JOIN vn.province p ON p.countryFk = c.id + JOIN vn.address a ON a.provinceFk = p.id + WHERE a.id = vAddressFk; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCalculate; + + CREATE TEMPORARY TABLE tmp.ticketComponentCalculate + (PRIMARY KEY (itemFk, warehouseFk)) + ENGINE = MEMORY + SELECT + tl.itemFk, + tl.warehouseFk, + tl.available, + -- IF((@rate2 := IFNULL(pf.rate2, b.price2)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate2) rate2, + IF(i.hasMinPrice, GREATEST(i.minPrice,IFNULL(pf.rate2, b.price2)),IFNULL(pf.rate2, b.price2)) rate2, + IF(i.hasMinPrice, GREATEST(i.minPrice,IFNULL(pf.rate3, b.price3)),IFNULL(pf.rate3, b.price3)) rate3, + -- @minPrice := IF((@rate3 := IFNULL(pf.rate3, b.price3)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate3) rate3, + -- TRUE AS minPrice, + IFNULL(pf.packing, GREATEST(b.grouping, b.packing)) packing, + IFNULL(pf.`grouping`, b.`grouping`) `grouping`, + ABS(IFNULL(pf.box, b.groupingMode)) groupingMode, + tl.buyFk, + i.typeFk, + IF(i.hasKgPrice, b.weight / b.packing, NULL) weightGrouping + FROM tmp.ticketLot tl + JOIN buy b ON b.id = tl.buyFk + JOIN item i ON i.id = tl.itemFk + JOIN itemType it ON it.id = i.typeFk + JOIN itemCategory ic ON ic.id = it.categoryFk + LEFT JOIN specialPrice sp ON sp.itemFk = i.id + AND sp.clientFk = vClientFk + LEFT JOIN ( + SELECT * FROM ( + SELECT pf.itemFk, + pf.`grouping`, + pf.packing, + pf.box, + pf.rate2, + pf.rate3, + zw.warehouseFk + FROM priceFixed pf + JOIN zoneWarehouse zw ON zw.zoneFk = vZoneFk + AND zw.warehouseFk IN (pf.warehouseFk,0) + WHERE vShipped BETWEEN pf.started AND pf.ended + ORDER BY pf.itemFk, pf.warehouseFk DESC + ) tpf + GROUP BY tpf.itemFk, tpf.warehouseFk + ) pf ON pf.itemFk = tl.itemFk + AND pf.warehouseFk = tl.warehouseFk + WHERE b.buyingValue + b.freightValue + b.packageValue + b.comissionValue > 0.01 + AND ic.merchandise + AND tl.zoneFk = vZoneFk + AND tl.warehouseFk = vWarehouseFk; + + -- Coste + INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) + SELECT + tcc.warehouseFk, + tcc.itemFk, + c2.id, + b.buyingValue + b.freightValue + b.packageValue + b.comissionValue + FROM tmp.ticketComponentCalculate tcc + JOIN vn.component c2 ON c2.code = 'purchaseValue' + JOIN buy b ON b.id = tcc.buyFk; + + -- Margen + INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) + SELECT + tcc.warehouseFk, + tcc.itemFk, + c2.id, + tcc.rate3 - b.buyingValue - b.freightValue - b.packageValue - b.comissionValue + FROM tmp.ticketComponentCalculate tcc + JOIN vn.component c2 ON c2.code = 'margin' + JOIN buy b ON b.id = tcc.buyFk; + + -- Promo Francia + IF vIsFrenchVNHBuyer THEN + + INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) + SELECT + tcc.warehouseFk, + tcc.itemFk, + c2.id, + - vFrenchDiscount * (b.buyingValue + b.freightValue + b.packageValue + b.comissionValue) / ( 1 - vFrenchDiscount) + FROM tmp.ticketComponentCalculate tcc + JOIN vn.component c2 ON c2.code = 'frenchOffer' + JOIN buy b ON b.id = tcc.buyFk; + + END IF; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentBase; + CREATE TEMPORARY TABLE tmp.ticketComponentBase ENGINE = MEMORY + SELECT tc.itemFk, ROUND(SUM(tc.cost), 4) AS base, tc.warehouseFk + FROM tmp.ticketComponent tc + JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tc.itemFk AND tcc.warehouseFk = tc.warehouseFk + GROUP BY tc.itemFk, warehouseFk; + + -- RECOBRO + INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost) + SELECT tcb.warehouseFk, tcb.itemFk, c2.id, + ROUND(tcb.base * + LEAST( + MAX(GREATEST(IFNULL(cr.priceIncreasing,0), + IFNULL(cr1.priceIncreasing,0), + IFNULL(cr2.priceIncreasing,0)) + ), + 0.25), + 3) + FROM tmp.ticketComponentBase tcb + JOIN vn.component c2 ON c2.code = 'debtCollection' + JOIN claimRatio cr ON cr.clientFk = vClientFk + LEFT JOIN clientYoke cy1 ON cy1.leftOx = cr.clientFk + LEFT JOIN claimRatio cr1 ON cr1.clientFk = cy1.rightOx + LEFT JOIN clientYoke cy2 ON cy2.rightOx = cr.clientFk + LEFT JOIN claimRatio cr2 ON cr2.clientFk = cy2.leftOx + WHERE GREATEST(IFNULL(cr.priceIncreasing,0), IFNULL(cr1.priceIncreasing,0), IFNULL(cr2.priceIncreasing,0)) > 0.009 + GROUP BY tcb.itemFk; + + -- Mana auto + INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost) + SELECT tcb.warehouseFk, tcb.itemFk, c2.id, ROUND(base * (0.01 + wm.pricesModifierRate), 3) as manaAuto + FROM tmp.ticketComponentBase tcb + JOIN `client` c on c.id = vClientFk + JOIN workerMana wm ON c.salesPersonFk = wm.workerFk + JOIN vn.component c2 ON c2.code = 'autoMana' + WHERE wm.isPricesModifierActivated + HAVING manaAuto <> 0; + + -- Precios especiales + INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost) + SELECT tcb.warehouseFk, + tcb.itemFk, + c2.id, + GREATEST( + IFNULL(ROUND(tcb.base * c2.tax, 4), 0), + IF(i.hasMinPrice, i.minPrice,0) - tcc.rate3 + ) cost + FROM tmp.ticketComponentBase tcb + JOIN vn.component c2 ON c2.code = 'lastUnitsDiscount' + JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tcb.itemFk AND tcc.warehouseFk = tcb.warehouseFk + LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk + JOIN vn.item i ON i.id = tcb.itemFk + WHERE sp.value IS NULL + AND i.supplyResponseFk IS NULL; + + -- Venta por paquetes + INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost) + SELECT tcc.warehouseFk, tcc.itemFk, c2.id, tcc.rate2 - tcc.rate3 + FROM tmp.ticketComponentCalculate tcc + JOIN vn.component c2 ON c2.code = 'salePerPackage' + JOIN buy b ON b.id = tcc.buyFk + LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk + WHERE sp.value IS NULL; + + DROP TEMPORARY TABLE IF EXISTS tmp.zone; + CREATE TEMPORARY TABLE IF NOT EXISTS tmp.zone (INDEX (id)) + ENGINE = MEMORY + SELECT vZoneFk id; + + CALL zone_getOptionsForShipment(vShipped, TRUE); + + -- Reparto + INSERT INTO tmp.ticketComponent + SELECT tcc.warehouseFK, + tcc.itemFk, + c2.id, + z.inflation * ROUND(ic.cm3delivery * (IFNULL(zo.price,5000) - IFNULL(zo.bonus,0)) / (1000 * vc.standardFlowerBox) , 4) cost + FROM tmp.ticketComponentCalculate tcc + JOIN item i ON i.id = tcc.itemFk + JOIN tmp.zoneOption zo ON zo.zoneFk = vZoneFk + JOIN zone z ON z.id = vZoneFk + JOIN agencyMode am ON am.id = z.agencyModeFk + JOIN vn.volumeConfig vc + JOIN vn.component c2 ON c2.code = 'delivery' + LEFT JOIN itemCost ic ON ic.warehouseFk = tcc.warehouseFk + AND ic.itemFk = tcc.itemFk + HAVING cost <> 0; + + DROP TEMPORARY TABLE tmp.zoneOption; + /* + -- Extra reparto + INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost) + SELECT tcc.warehouseFk, tcc.itemFk, c2.id, ap.packagingValue cost + FROM tmp.ticketComponentCalculate tcc + JOIN vn.addressForPackaging ap + JOIN vn.component c2 ON c2.code = 'bagged' + WHERE ap.addressFk = vAddressFk; + */ + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCopy; + CREATE TEMPORARY TABLE tmp.ticketComponentCopy ENGINE = MEMORY + SELECT * FROM tmp.ticketComponent; + + -- Precio especial + INSERT INTO tmp.ticketComponent + SELECT tcc.warehouseFk, + tcc.itemFk, + c2.id, + sp.value - SUM(tcc.cost) sumCost + FROM tmp.ticketComponentCopy tcc + JOIN component c ON c.id = tcc.componentFk + JOIN specialPrice sp ON sp.clientFk = vClientFK AND sp.itemFk = tcc.itemFk + JOIN vn.component c2 ON c2.code = 'specialPrices' + WHERE c.classRate IS NULL + AND tcc.warehouseFk = vWarehouseFk + GROUP BY tcc.itemFk, tcc.warehouseFk + HAVING ABS(sumCost) > 0.001; + + -- Rappel + INSERT INTO tmp.ticketComponent + SELECT tcc.warehouseFk, + tcc.itemFk, + IFNULL(c.componentFk ,c2.id), + SUM(tcc.cost) * ((1/(1-c.rappel/100)) -1) sumCost + FROM tmp.ticketComponentCopy tcc + JOIN vn.clientChain cc ON cc.clientFk = vClientFk + JOIN vn.`chain` c ON c.id = cc.chainFk + JOIN vn.component c2 ON c2.code = 'rappel' + WHERE tcc.warehouseFk = vWarehouseFk + GROUP BY tcc.itemFk, tcc.warehouseFk; + + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentSum; + CREATE TEMPORARY TABLE tmp.ticketComponentSum + (INDEX (itemFk, warehouseFk)) + ENGINE = MEMORY + SELECT SUM(cost) sumCost, tc.itemFk, tc.warehouseFk, c.classRate + FROM tmp.ticketComponent tc + JOIN component c ON c.id = tc.componentFk + GROUP BY tc.itemFk, tc.warehouseFk, c.classRate; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentRate; + CREATE TEMPORARY TABLE tmp.ticketComponentRate ENGINE = MEMORY + SELECT tcc.warehouseFk, + tcc.itemFk, + 1 rate, + IF(tcc.groupingMode = 1, tcc.`grouping`, 1) `grouping`, + CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) price, + CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) / weightGrouping priceKg + FROM tmp.ticketComponentCalculate tcc + JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk + AND tcs.warehouseFk = tcc.warehouseFk + WHERE IFNULL(tcs.classRate, 1) = 1 + AND tcc.groupingMode < 2 AND (tcc.packing > tcc.`grouping` or tcc.groupingMode = 0) + GROUP BY tcs.warehouseFk, tcs.itemFk; + + INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg) SELECT - tl.itemFk, - SUM(tl.available) available, - p.name producer, - i.name item, - i.size size, - i.stems, - i.category, - i.inkFk, - i.image, - o.code origin, - bl.price, - bl.priceKg - FROM tmp.ticketLot tl - JOIN item i ON tl.itemFk = i.id - LEFT JOIN producer p ON p.id = i.producerFk AND p.isVisible - JOIN origin o ON o.id = i.originFk - JOIN ( - SELECT * - FROM (SELECT price, itemFk, priceKg - FROM tmp.ticketComponentPrice - WHERE warehouseFk = vWarehouseFk - ORDER BY (rate = 2) DESC) sub - GROUP BY itemFk - ) bl ON bl.itemFk = tl.itemFk - WHERE tl.zoneFk = vZoneFk AND tl.warehouseFk = vWarehouseFk - GROUP BY tl.itemFk - ON DUPLICATE KEY UPDATE available = available + VALUES(available); + tcc.warehouseFk, + tcc.itemFk, + 2 rate, + tcc.packing `grouping`, + SUM(tcs.sumCost) price, + SUM(tcs.sumCost) / weightGrouping priceKg + FROM tmp.ticketComponentCalculate tcc + JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk + AND tcs.warehouseFk = tcc.warehouseFk + WHERE tcc.available IS NULL OR (IFNULL(tcs.classRate, 2) = 2 + AND tcc.packing > 0 AND tcc.available >= tcc.packing) + GROUP BY tcs.warehouseFk, tcs.itemFk; - END LOOP; - - CLOSE cTravelTree; + INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg) + SELECT + tcc.warehouseFk, + tcc.itemFk, + 3 rate, + tcc.available `grouping`, + SUM(tcs.sumCost) price, + SUM(tcs.sumCost) / weightGrouping priceKg + FROM tmp.ticketComponentCalculate tcc + JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk + AND tcs.warehouseFk = tcc.warehouseFk + WHERE IFNULL(tcs.classRate, 3) = 3 + GROUP BY tcs.warehouseFk, tcs.itemFk; + INSERT INTO tmp.ticketComponentPrice (warehouseFk, itemFk, rate, `grouping`, price, priceKg) + SELECT * FROM ( + SELECT * FROM tmp.ticketComponentRate ORDER BY price + ) t + GROUP BY itemFk, warehouseFk, `grouping`; + + DROP TEMPORARY TABLE + tmp.ticketComponentCalculate, + tmp.ticketComponentSum, + tmp.ticketComponentBase, + tmp.ticketComponentRate, + tmp.ticketComponentCopy; + 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 `catalog_componentCalculate` */; +/*!50003 DROP PROCEDURE IF EXISTS `catalog_componentCalculate_beta` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET character_set_client = 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 = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `catalog_componentCalculate`( +CREATE DEFINER=`root`@`localhost` PROCEDURE `catalog_componentCalculate_beta`( vZoneFk INT, + vAddressFk INT, + vShipped DATE, + vWarehouseFk INT) +BEGIN + /** + * Calcula los componentes de los articulos de tmp.ticketLot + * + * @param vZoneFk para calcular el transporte + * @param vAddressFk Consignatario + * @param vShipped dia de salida del pedido + * @param vWarehouseFk warehouse de salida del pedido + * @table tmp.ticketLot (warehouseFk, available, itemFk, buyFk, zoneFk) + * @table tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost) + * + * @return tmp.ticketComponentPrice (warehouseFk, itemFk, rate, `grouping`, price, priceKg) + */ + + DECLARE vClientFk INT; + DECLARE vIsFrenchVNHBuyer BOOLEAN DEFAULT FALSE; + DECLARE vVNHWarehouseFk INT DEFAULT 7; + DECLARE vFrenchDiscount DECIMAL(3,2) DEFAULT 0.12; + DECLARE visAnyVolumeAllowed BOOL; + + SELECT clientFk INTO vClientFK + FROM address + WHERE id = vAddressFk; + + SELECT (c.country = 'FRANCIA' AND vWarehouseFk = vVNHWarehouseFk) + INTO vIsFrenchVNHBuyer + FROM vn.country c + JOIN vn.province p ON p.countryFk = c.id + JOIN vn.address a ON a.provinceFk = p.id + WHERE a.id = vAddressFk; + + + -- Se eliminan los productos de tamaños no convencionales, salvo agencias que lo permitan + SELECT a.isAnyVolumeAllowed INTO visAnyVolumeAllowed + FROM vn.agency a + JOIN vn.agencyMode am ON am.agencyFk = a.id + JOIN vn.`zone`z ON z.agencyModeFk = am.id + WHERE z.id = vZoneFk; + + IF NOT vIsAnyVolumeAllowed THEN + + DELETE tl.* + FROM tmp.ticketLot tl + JOIN vn.item i ON i.id = tl.itemFk + JOIN vn.itemType it ON it.id = i.typeFk + WHERE it.isUnconventionalSize; + + END IF; + + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCalculate; + + CREATE TEMPORARY TABLE tmp.ticketComponentCalculate + (PRIMARY KEY (itemFk, warehouseFk)) + ENGINE = MEMORY + SELECT + tl.itemFk, + tl.warehouseFk, + tl.available, + -- IF((@rate2 := IFNULL(pf.rate2, b.price2)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate2) rate2, + IF(i.hasMinPrice, GREATEST(i.minPrice,IFNULL(pf.rate2, b.price2)),IFNULL(pf.rate2, b.price2)) rate2, + IF(i.hasMinPrice, GREATEST(i.minPrice,IFNULL(pf.rate3, b.price3)),IFNULL(pf.rate3, b.price3)) rate3, + -- @minPrice := IF((@rate3 := IFNULL(pf.rate3, b.price3)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate3) rate3, + -- TRUE AS minPrice, + IFNULL(pf.packing, GREATEST(b.grouping, b.packing)) packing, + IFNULL(pf.`grouping`, b.`grouping`) `grouping`, + ABS(IFNULL(pf.box, b.groupingMode)) groupingMode, + tl.buyFk, + i.typeFk, + IF(i.hasKgPrice, b.weight / b.packing, NULL) weightGrouping + FROM tmp.ticketLot tl + JOIN buy b ON b.id = tl.buyFk + JOIN item i ON i.id = tl.itemFk + JOIN itemType it ON it.id = i.typeFk + JOIN itemCategory ic ON ic.id = it.categoryFk + LEFT JOIN specialPrice sp ON sp.itemFk = i.id + AND sp.clientFk = vClientFk + LEFT JOIN ( + SELECT * FROM ( + SELECT pf.itemFk, + pf.`grouping`, + pf.packing, + pf.box, + pf.rate2, + pf.rate3, + zw.warehouseFk + FROM priceFixed pf + JOIN zoneWarehouse zw ON zw.zoneFk = vZoneFk + AND zw.warehouseFk IN (pf.warehouseFk,0) + WHERE vShipped BETWEEN pf.started AND pf.ended + ORDER BY pf.itemFk, pf.warehouseFk DESC + ) tpf + GROUP BY tpf.itemFk, tpf.warehouseFk + ) pf ON pf.itemFk = tl.itemFk + AND pf.warehouseFk = tl.warehouseFk + WHERE b.buyingValue + b.freightValue + b.packageValue + b.comissionValue > 0.01 + AND ic.merchandise + AND tl.zoneFk = vZoneFk + AND tl.warehouseFk = vWarehouseFk; + + -- Coste + INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) + SELECT + tcc.warehouseFk, + tcc.itemFk, + c2.id, + b.buyingValue + b.freightValue + b.packageValue + b.comissionValue + FROM tmp.ticketComponentCalculate tcc + JOIN vn.component c2 ON c2.code = 'purchaseValue' + JOIN buy b ON b.id = tcc.buyFk; + + -- Margen + INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) + SELECT + tcc.warehouseFk, + tcc.itemFk, + c2.id, + tcc.rate3 - b.buyingValue - b.freightValue - b.packageValue - b.comissionValue + FROM tmp.ticketComponentCalculate tcc + JOIN vn.component c2 ON c2.code = 'margin' + JOIN buy b ON b.id = tcc.buyFk; + + -- Promo Francia + IF vIsFrenchVNHBuyer THEN + + INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) + SELECT + tcc.warehouseFk, + tcc.itemFk, + c2.id, + - vFrenchDiscount * (b.buyingValue + b.freightValue + b.packageValue + b.comissionValue) / ( 1 - vFrenchDiscount) + FROM tmp.ticketComponentCalculate tcc + JOIN vn.component c2 ON c2.code = 'frenchOffer' + JOIN buy b ON b.id = tcc.buyFk; + + END IF; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentBase; + CREATE TEMPORARY TABLE tmp.ticketComponentBase ENGINE = MEMORY + SELECT tc.itemFk, ROUND(SUM(tc.cost), 4) AS base, tc.warehouseFk + FROM tmp.ticketComponent tc + JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tc.itemFk AND tcc.warehouseFk = tc.warehouseFk + GROUP BY tc.itemFk, warehouseFk; + + -- RECOBRO + INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost) + SELECT tcb.warehouseFk, tcb.itemFk, c2.id, + ROUND(tcb.base * + LEAST( + MAX(GREATEST(IFNULL(cr.priceIncreasing,0), + IFNULL(cr1.priceIncreasing,0), + IFNULL(cr2.priceIncreasing,0)) + ), + 0.25), + 3) + FROM tmp.ticketComponentBase tcb + JOIN vn.component c2 ON c2.code = 'debtCollection' + JOIN claimRatio cr ON cr.clientFk = vClientFk + LEFT JOIN clientYoke cy1 ON cy1.leftOx = cr.clientFk + LEFT JOIN claimRatio cr1 ON cr1.clientFk = cy1.rightOx + LEFT JOIN clientYoke cy2 ON cy2.rightOx = cr.clientFk + LEFT JOIN claimRatio cr2 ON cr2.clientFk = cy2.leftOx + WHERE GREATEST(IFNULL(cr.priceIncreasing,0), IFNULL(cr1.priceIncreasing,0), IFNULL(cr2.priceIncreasing,0)) > 0.009 + GROUP BY tcb.itemFk; + + -- Mana auto + INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost) + SELECT tcb.warehouseFk, tcb.itemFk, c2.id, ROUND(base * (0.01 + wm.pricesModifierRate), 3) as manaAuto + FROM tmp.ticketComponentBase tcb + JOIN `client` c on c.id = vClientFk + JOIN workerMana wm ON c.salesPersonFk = wm.workerFk + JOIN vn.component c2 ON c2.code = 'autoMana' + WHERE wm.isPricesModifierActivated + HAVING manaAuto <> 0; + + -- Precios especiales + INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost) + SELECT tcb.warehouseFk, + tcb.itemFk, + c2.id, + GREATEST( + IFNULL(ROUND(tcb.base * c2.tax, 4), 0), + IF(i.hasMinPrice, i.minPrice,0) - tcc.rate3 + ) cost + FROM tmp.ticketComponentBase tcb + JOIN vn.component c2 ON c2.code = 'lastUnitsDiscount' + JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tcb.itemFk AND tcc.warehouseFk = tcb.warehouseFk + LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk + JOIN vn.item i ON i.id = tcb.itemFk + WHERE sp.value IS NULL + AND i.supplyResponseFk IS NULL; + + -- Venta por paquetes + INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost) + SELECT tcc.warehouseFk, tcc.itemFk, c2.id, tcc.rate2 - tcc.rate3 + FROM tmp.ticketComponentCalculate tcc + JOIN vn.component c2 ON c2.code = 'salePerPackage' + JOIN buy b ON b.id = tcc.buyFk + LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk + WHERE sp.value IS NULL; + + DROP TEMPORARY TABLE IF EXISTS tmp.zone; + CREATE TEMPORARY TABLE IF NOT EXISTS tmp.zone (INDEX (id)) + ENGINE = MEMORY + SELECT vZoneFk id; + + CALL zone_getOptionsForShipment(vShipped, TRUE); + + -- Reparto + INSERT INTO tmp.ticketComponent + SELECT tcc.warehouseFK, + tcc.itemFk, + c2.id, + z.inflation * ROUND(ic.cm3delivery * (IFNULL(zo.price,5000) - IFNULL(zo.bonus,0)) / (1000 * vc.standardFlowerBox) , 4) cost + FROM tmp.ticketComponentCalculate tcc + JOIN item i ON i.id = tcc.itemFk + JOIN tmp.zoneOption zo ON zo.zoneFk = vZoneFk + JOIN zone z ON z.id = vZoneFk + JOIN agencyMode am ON am.id = z.agencyModeFk + JOIN vn.volumeConfig vc + JOIN vn.component c2 ON c2.code = 'delivery' + LEFT JOIN itemCost ic ON ic.warehouseFk = tcc.warehouseFk + AND ic.itemFk = tcc.itemFk + HAVING cost <> 0; + + DROP TEMPORARY TABLE tmp.zoneOption; + /* + -- Extra reparto + INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost) + SELECT tcc.warehouseFk, tcc.itemFk, c2.id, ap.packagingValue cost + FROM tmp.ticketComponentCalculate tcc + JOIN vn.addressForPackaging ap + JOIN vn.component c2 ON c2.code = 'bagged' + WHERE ap.addressFk = vAddressFk; + */ + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCopy; + CREATE TEMPORARY TABLE tmp.ticketComponentCopy ENGINE = MEMORY + SELECT * FROM tmp.ticketComponent; + + -- Precio especial + INSERT INTO tmp.ticketComponent + SELECT tcc.warehouseFk, + tcc.itemFk, + c2.id, + sp.value - SUM(tcc.cost) sumCost + FROM tmp.ticketComponentCopy tcc + JOIN component c ON c.id = tcc.componentFk + JOIN specialPrice sp ON sp.clientFk = vClientFK AND sp.itemFk = tcc.itemFk + JOIN vn.component c2 ON c2.code = 'specialPrices' + WHERE c.classRate IS NULL + AND tcc.warehouseFk = vWarehouseFk + GROUP BY tcc.itemFk, tcc.warehouseFk + HAVING ABS(sumCost) > 0.001; + + -- Rappel + INSERT INTO tmp.ticketComponent + SELECT tcc.warehouseFk, + tcc.itemFk, + IFNULL(c.componentFk ,c2.id), + SUM(tcc.cost) * ((1/(1-c.rappel/100)) -1) sumCost + FROM tmp.ticketComponentCopy tcc + JOIN vn.clientChain cc ON cc.clientFk = vClientFk + JOIN vn.`chain` c ON c.id = cc.chainFk + JOIN vn.component c2 ON c2.code = 'rappel' + WHERE tcc.warehouseFk = vWarehouseFk + GROUP BY tcc.itemFk, tcc.warehouseFk; + + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentSum; + CREATE TEMPORARY TABLE tmp.ticketComponentSum + (INDEX (itemFk, warehouseFk)) + ENGINE = MEMORY + SELECT SUM(cost) sumCost, tc.itemFk, tc.warehouseFk, c.classRate + FROM tmp.ticketComponent tc + JOIN component c ON c.id = tc.componentFk + GROUP BY tc.itemFk, tc.warehouseFk, c.classRate; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentRate; + CREATE TEMPORARY TABLE tmp.ticketComponentRate ENGINE = MEMORY + SELECT tcc.warehouseFk, + tcc.itemFk, + 1 rate, + IF(tcc.groupingMode = 1, tcc.`grouping`, 1) `grouping`, + CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) price, + CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) / weightGrouping priceKg + FROM tmp.ticketComponentCalculate tcc + JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk + AND tcs.warehouseFk = tcc.warehouseFk + WHERE IFNULL(tcs.classRate, 1) = 1 + AND tcc.groupingMode < 2 AND (tcc.packing > tcc.`grouping` or tcc.groupingMode = 0) + GROUP BY tcs.warehouseFk, tcs.itemFk; + + INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg) + SELECT + tcc.warehouseFk, + tcc.itemFk, + 2 rate, + tcc.packing `grouping`, + SUM(tcs.sumCost) price, + SUM(tcs.sumCost) / weightGrouping priceKg + FROM tmp.ticketComponentCalculate tcc + JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk + AND tcs.warehouseFk = tcc.warehouseFk + WHERE tcc.available IS NULL OR (IFNULL(tcs.classRate, 2) = 2 + AND tcc.packing > 0 AND tcc.available >= tcc.packing) + GROUP BY tcs.warehouseFk, tcs.itemFk; + + INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg) + SELECT + tcc.warehouseFk, + tcc.itemFk, + 3 rate, + tcc.available `grouping`, + SUM(tcs.sumCost) price, + SUM(tcs.sumCost) / weightGrouping priceKg + FROM tmp.ticketComponentCalculate tcc + JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk + AND tcs.warehouseFk = tcc.warehouseFk + WHERE IFNULL(tcs.classRate, 3) = 3 + GROUP BY tcs.warehouseFk, tcs.itemFk; + + INSERT INTO tmp.ticketComponentPrice (warehouseFk, itemFk, rate, `grouping`, price, priceKg) + SELECT * FROM ( + SELECT * FROM tmp.ticketComponentRate ORDER BY price + ) t + GROUP BY itemFk, warehouseFk, `grouping`; + + DROP TEMPORARY TABLE + tmp.ticketComponentCalculate, + tmp.ticketComponentSum, + tmp.ticketComponentBase, + tmp.ticketComponentRate, + tmp.ticketComponentCopy; + +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 `catalog_componentCalculate__` */; +/*!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`@`localhost` PROCEDURE `catalog_componentCalculate__`( vZoneFk INT, vAddressFk INT, vShipped DATE, @@ -50907,465 +51948,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 `catalog_componentCalculate_beta` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `catalog_componentCalculate_beta`( - vZoneFk INT, - vAddressFk INT, - vShipped DATE, - vWarehouseFk INT) -proc: BEGIN -/** - * Calcula los componentes de los articulos de tmp.ticketLot - * - * @param vZoneFk para calcular el transporte - * @param vAddressFk Consignatario - * @param vShipped dia de salida del pedido - * @param vWarehouseFk warehouse de salida del pedido - * @table tmp.ticketLot (warehouseFk, available, itemFk, buyFk, zoneFk) - * @table tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost) - * - * @return tmp.ticketComponentPrice (warehouseFk, itemFk, rate, `grouping`, price, priceKg) - */ - DECLARE vClientFk INT; - DECLARE vIsFrenchVNHBuyer BOOLEAN DEFAULT FALSE; - DECLARE vVNHWarehouseFk INT DEFAULT 7; - DECLARE vIsLogifloraAllowed BOOLEAN DEFAULT 0; - DECLARE vVisibleCache INT; - DECLARE vIsZonePremium BOOL; - DECLARE vFrenchDiscount DECIMAL(3,2) DEFAULT 0.12; - DECLARE visAnyVolumeAllowed BOOL; - - SELECT * FROM tmp.ticketLot; - - SELECT (COUNT(*) > 0) INTO vIsZonePremium - FROM vn.zoneFilter zf - WHERE zf.zoneFk = vZoneFk; -/* - SELECT vc.standardFlowerBox * 1000 INTO vBoxVolume - FROM vn.volumeConfig vc; - */ - SELECT clientFk, isLogifloraAllowed INTO vClientFK, vIsLogifloraAllowed - FROM address - WHERE id = vAddressFk; - - SELECT (c.country = 'FRANCIA' AND vWarehouseFk = vVNHWarehouseFk) - INTO vIsFrenchVNHBuyer - FROM vn.country c - JOIN vn.province p ON p.countryFk = c.id - JOIN vn.address a ON a.provinceFk = p.id - WHERE a.id = vAddressFk; - - /* - -- Se eliminan los productos de tamaños no convencionales, salvo agencias que lo permitan - SELECT a.isAnyVolumeAllowed INTO visAnyVolumeAllowed - FROM vn.agency a - JOIN vn.agencyMode am ON am.agencyFk = a.id - JOIN vn.`zone`z ON z.agencyModeFk = am.id - WHERE z.id = vZoneFk; - - IF NOT vIsAnyVolumeAllowed THEN - - DELETE tl.* - FROM tmp.ticketLot tl - JOIN vn.item i ON i.id = tl.itemFk - JOIN vn.itemType it ON it.id = i.typeFk - WHERE it.isUnconventionalSize; - - END IF; - - -- Esto sirve para que los franceses compren sólo por las cuentas de VNH - DELETE tl.* - FROM tmp.ticketLot tl - JOIN vn.item i ON i.id = tl.itemFk - JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk - JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID - WHERE v.isVNHSupplier != vIsFrenchVNHBuyer; - - IF (NOT vIsLogifloraAllowed AND vVNHWarehouseFk != vWarehouseFk) - OR NOT vn.isLogifloraDay(vShipped, vWarehouseFk) - - THEN - - CALL cache.visible_refresh(vVisibleCache, FALSE, vWarehouseFk); - - DELETE tl FROM tmp.ticketLot tl - JOIN item i ON i.id = tl.itemFk - LEFT JOIN vn.buy b ON b.id = tl.buyFk - LEFT JOIN vn.entry e ON e.id = b.entryFk - LEFT JOIN vn.supplier s ON s.id = e.supplierFk - LEFT JOIN cache.visible v ON v.calc_id = vVisibleCache AND v.item_id = i.id - LEFT JOIN (SELECT DISTINCT s.itemFk - FROM vn.sale s - JOIN vn.ticket t ON t.id = s.ticketFk - WHERE t.warehouseFk = vWarehouseFk - AND t.addressFk = vAddressFk - AND t.shipped = vShipped - AND t.zoneFk = vZoneFk) sub ON sub.itemFk = i.id - WHERE (i.supplyResponseFk - AND (IFNULL(e.isRaid,TRUE) OR s.nickname = 'INVENTARIO') - AND ISNULL(sub.itemFk) - AND IFNULL(v.visible,0) = 0 - AND vWarehouseFk = tl.warehouseFk); - - END IF; - - -- Eliminem productes de la oferta que no deuen vore els francesos - IF vIsFrenchVNHBuyer THEN - - CALL cache.visible_refresh(vVisibleCache, FALSE, vWarehouseFk); - - DELETE tl FROM tmp.ticketLot tl - JOIN item i ON i.id = tl.itemFk - JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk - JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID - LEFT JOIN cache.visible v ON v.calc_id = vVisibleCache AND v.item_id = i.id - LEFT JOIN (SELECT DISTINCT s.itemFk - FROM vn.sale s - JOIN vn.ticket t ON t.id = s.ticketFk - WHERE t.warehouseFk = vWarehouseFk - AND t.addressFk = vAddressFk - AND t.shipped = vShipped - AND t.zoneFk = vZoneFk) sub ON sub.itemFk = i.id - WHERE (mp.isEarlyBird = FALSE - AND IFNULL(sub.itemFk,0) = 0 - AND IFNULL(v.visible ,0) = 0); - - END IF; - - -- Eliminem productes de la oferta que no deuen vore les zones PREMIUM - IF vIsZonePremium THEN - - DELETE tl.* - FROM tmp.ticketLot tl - JOIN item i ON i.id = tl.itemFk - LEFT JOIN vn.zoneFilter zf ON zf.itemTypeFk = i.typeFk - AND zf.zoneFk = vZoneFk - AND i.`size` <= zf.sizeMax - WHERE zf.id IS NULL ; - - END IF; - - -- Eliminem productes de la oferta que la zona no pot transportar - DELETE tl.* - FROM tmp.ticketLot tl - JOIN item i ON i.id = tl.itemFk - JOIN vn.zone z ON z.id = vZoneFk - WHERE i.size > z.itemMaxSize; - */ - -- SET @rate2 := 0; - -- SET @rate3 := 0; - -- SET @minPrice := 0; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCalculate; - - CREATE TEMPORARY TABLE tmp.ticketComponentCalculate - (PRIMARY KEY (itemFk, warehouseFk)) - ENGINE = MEMORY - SELECT - tl.itemFk, - tl.warehouseFk, - tl.available, - -- IF((@rate2 := IFNULL(pf.rate2, b.price2)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate2) rate2, - IF(i.hasMinPrice, GREATEST(i.minPrice,IFNULL(pf.rate2, b.price2)),IFNULL(pf.rate2, b.price2)) rate2, - IF(i.hasMinPrice, GREATEST(i.minPrice,IFNULL(pf.rate3, b.price3)),IFNULL(pf.rate3, b.price3)) rate3, - -- @minPrice := IF((@rate3 := IFNULL(pf.rate3, b.price3)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate3) rate3, - -- TRUE AS minPrice, - IFNULL(pf.packing, GREATEST(b.grouping, b.packing)) packing, - IFNULL(pf.`grouping`, b.`grouping`) `grouping`, - ABS(IFNULL(pf.box, b.groupingMode)) groupingMode, - tl.buyFk, - i.typeFk, - IF(i.hasKgPrice, b.weight / b.packing, NULL) weightGrouping - FROM tmp.ticketLot tl - JOIN buy b ON b.id = tl.buyFk - JOIN item i ON i.id = tl.itemFk - JOIN itemType it ON it.id = i.typeFk - JOIN itemCategory ic ON ic.id = it.categoryFk - LEFT JOIN specialPrice sp ON sp.itemFk = i.id - AND sp.clientFk = vClientFk - LEFT JOIN ( - SELECT * FROM ( - SELECT pf.itemFk, - pf.`grouping`, - pf.packing, - pf.box, - pf.rate2, - pf.rate3, - zw.warehouseFk - FROM priceFixed pf - JOIN zoneWarehouse zw ON zw.zoneFk = vZoneFk - AND zw.warehouseFk IN (pf.warehouseFk,0) - WHERE vShipped BETWEEN pf.started AND pf.ended - ORDER BY pf.itemFk, pf.warehouseFk DESC - ) tpf - GROUP BY tpf.itemFk, tpf.warehouseFk - ) pf ON pf.itemFk = tl.itemFk - AND pf.warehouseFk = tl.warehouseFk - WHERE b.buyingValue + b.freightValue + b.packageValue + b.comissionValue > 0.01 - AND ic.merchandise - AND tl.zoneFk = vZoneFk - AND tl.warehouseFk = vWarehouseFk; - - -- Coste - INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) - SELECT - tcc.warehouseFk, - tcc.itemFk, - c2.id, - b.buyingValue + b.freightValue + b.packageValue + b.comissionValue - FROM tmp.ticketComponentCalculate tcc - JOIN vn.component c2 ON c2.code = 'purchaseValue' - JOIN buy b ON b.id = tcc.buyFk; - - -- Margen - INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) - SELECT - tcc.warehouseFk, - tcc.itemFk, - c2.id, - tcc.rate3 - b.buyingValue - b.freightValue - b.packageValue - b.comissionValue - FROM tmp.ticketComponentCalculate tcc - JOIN vn.component c2 ON c2.code = 'margin' - JOIN buy b ON b.id = tcc.buyFk; - - -- Promo Francia - IF vIsFrenchVNHBuyer THEN - - INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) - SELECT - tcc.warehouseFk, - tcc.itemFk, - c2.id, - - vFrenchDiscount * (b.buyingValue + b.freightValue + b.packageValue + b.comissionValue) / ( 1 - vFrenchDiscount) - FROM tmp.ticketComponentCalculate tcc - JOIN vn.component c2 ON c2.code = 'frenchOffer' - JOIN buy b ON b.id = tcc.buyFk; - - END IF; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentBase; - CREATE TEMPORARY TABLE tmp.ticketComponentBase ENGINE = MEMORY - SELECT tc.itemFk, ROUND(SUM(tc.cost), 4) AS base, tc.warehouseFk - FROM tmp.ticketComponent tc - JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tc.itemFk AND tcc.warehouseFk = tc.warehouseFk - GROUP BY tc.itemFk, warehouseFk; - - -- RECOBRO - INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost) - SELECT tcb.warehouseFk, tcb.itemFk, c2.id, - ROUND(tcb.base * - LEAST( - MAX(GREATEST(IFNULL(cr.priceIncreasing,0), - IFNULL(cr1.priceIncreasing,0), - IFNULL(cr2.priceIncreasing,0)) - ), - 0.25), - 3) - FROM tmp.ticketComponentBase tcb - JOIN vn.component c2 ON c2.code = 'debtCollection' - JOIN claimRatio cr ON cr.clientFk = vClientFk - LEFT JOIN clientYoke cy1 ON cy1.leftOx = cr.clientFk - LEFT JOIN claimRatio cr1 ON cr1.clientFk = cy1.rightOx - LEFT JOIN clientYoke cy2 ON cy2.rightOx = cr.clientFk - LEFT JOIN claimRatio cr2 ON cr2.clientFk = cy2.leftOx - WHERE GREATEST(IFNULL(cr.priceIncreasing,0), IFNULL(cr1.priceIncreasing,0), IFNULL(cr2.priceIncreasing,0)) > 0.009 - GROUP BY tcb.itemFk; - - -- Mana auto - INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost) - SELECT tcb.warehouseFk, tcb.itemFk, c2.id, ROUND(base * (0.01 + wm.pricesModifierRate), 3) as manaAuto - FROM tmp.ticketComponentBase tcb - JOIN `client` c on c.id = vClientFk - JOIN workerMana wm ON c.salesPersonFk = wm.workerFk - JOIN vn.component c2 ON c2.code = 'autoMana' - WHERE wm.isPricesModifierActivated - HAVING manaAuto <> 0; - - -- Precios especiales - INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost) - SELECT tcb.warehouseFk, - tcb.itemFk, - c2.id, - GREATEST( - IFNULL(ROUND(tcb.base * c2.tax, 4), 0), - IF(i.hasMinPrice, i.minPrice,0) - tcc.rate3 - ) cost - FROM tmp.ticketComponentBase tcb - JOIN vn.component c2 ON c2.code = 'lastUnitsDiscount' - JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tcb.itemFk AND tcc.warehouseFk = tcb.warehouseFk - LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk - JOIN vn.item i ON i.id = tcb.itemFk - WHERE sp.value IS NULL - AND i.supplyResponseFk IS NULL; - - -- Venta por paquetes - INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost) - SELECT tcc.warehouseFk, tcc.itemFk, c2.id, tcc.rate2 - tcc.rate3 - FROM tmp.ticketComponentCalculate tcc - JOIN vn.component c2 ON c2.code = 'salePerPackage' - JOIN buy b ON b.id = tcc.buyFk - LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk - WHERE sp.value IS NULL; - - DROP TEMPORARY TABLE IF EXISTS tmp.zone; - CREATE TEMPORARY TABLE IF NOT EXISTS tmp.zone (INDEX (id)) - ENGINE = MEMORY - SELECT vZoneFk id; - - CALL zone_getOptionsForShipment(vShipped, TRUE); - - -- Reparto - INSERT INTO tmp.ticketComponent - SELECT tcc.warehouseFK, - tcc.itemFk, - c2.id, - z.inflation * ROUND(ic.cm3delivery * (IFNULL(zo.price,5000) - IFNULL(zo.bonus,0)) / (1000 * vc.standardFlowerBox) , 4) cost - FROM tmp.ticketComponentCalculate tcc - JOIN item i ON i.id = tcc.itemFk - JOIN tmp.zoneOption zo ON zo.zoneFk = vZoneFk - JOIN zone z ON z.id = vZoneFk - JOIN agencyMode am ON am.id = z.agencyModeFk - JOIN vn.volumeConfig vc - JOIN vn.component c2 ON c2.code = 'delivery' - LEFT JOIN itemCost ic ON ic.warehouseFk = tcc.warehouseFk - AND ic.itemFk = tcc.itemFk - HAVING cost <> 0; - - DROP TEMPORARY TABLE tmp.zoneOption; - /* - -- Extra reparto - INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost) - SELECT tcc.warehouseFk, tcc.itemFk, c2.id, ap.packagingValue cost - FROM tmp.ticketComponentCalculate tcc - JOIN vn.addressForPackaging ap - JOIN vn.component c2 ON c2.code = 'bagged' - WHERE ap.addressFk = vAddressFk; - */ - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCopy; - CREATE TEMPORARY TABLE tmp.ticketComponentCopy ENGINE = MEMORY - SELECT * FROM tmp.ticketComponent; - - -- Precio especial - INSERT INTO tmp.ticketComponent - SELECT tcc.warehouseFk, - tcc.itemFk, - c2.id, - sp.value - SUM(tcc.cost) sumCost - FROM tmp.ticketComponentCopy tcc - JOIN component c ON c.id = tcc.componentFk - JOIN specialPrice sp ON sp.clientFk = vClientFK AND sp.itemFk = tcc.itemFk - JOIN vn.component c2 ON c2.code = 'specialPrices' - WHERE c.classRate IS NULL - AND tcc.warehouseFk = vWarehouseFk - GROUP BY tcc.itemFk, tcc.warehouseFk - HAVING ABS(sumCost) > 0.001; - - -- Rappel - INSERT INTO tmp.ticketComponent - SELECT tcc.warehouseFk, - tcc.itemFk, - IFNULL(c.componentFk ,c2.id), - SUM(tcc.cost) * ((1/(1-c.rappel/100)) -1) sumCost - FROM tmp.ticketComponentCopy tcc - JOIN vn.clientChain cc ON cc.clientFk = vClientFk - JOIN vn.`chain` c ON c.id = cc.chainFk - JOIN vn.component c2 ON c2.code = 'rappel' - WHERE tcc.warehouseFk = vWarehouseFk - GROUP BY tcc.itemFk, tcc.warehouseFk; - - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentSum; - CREATE TEMPORARY TABLE tmp.ticketComponentSum - (INDEX (itemFk, warehouseFk)) - ENGINE = MEMORY - SELECT SUM(cost) sumCost, tc.itemFk, tc.warehouseFk, c.classRate - FROM tmp.ticketComponent tc - JOIN component c ON c.id = tc.componentFk - GROUP BY tc.itemFk, tc.warehouseFk, c.classRate; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentRate; - CREATE TEMPORARY TABLE tmp.ticketComponentRate ENGINE = MEMORY - SELECT tcc.warehouseFk, - tcc.itemFk, - 1 rate, - IF(tcc.groupingMode = 1, tcc.`grouping`, 1) `grouping`, - CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) price, - CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) / weightGrouping priceKg - FROM tmp.ticketComponentCalculate tcc - JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk - AND tcs.warehouseFk = tcc.warehouseFk - WHERE IFNULL(tcs.classRate, 1) = 1 - AND tcc.groupingMode < 2 AND (tcc.packing > tcc.`grouping` or tcc.groupingMode = 0) - GROUP BY tcs.warehouseFk, tcs.itemFk; - - INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg) - SELECT - tcc.warehouseFk, - tcc.itemFk, - 2 rate, - tcc.packing `grouping`, - SUM(tcs.sumCost) price, - SUM(tcs.sumCost) / weightGrouping priceKg - FROM tmp.ticketComponentCalculate tcc - JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk - AND tcs.warehouseFk = tcc.warehouseFk - WHERE tcc.available IS NULL OR (IFNULL(tcs.classRate, 2) = 2 - AND tcc.packing > 0 AND tcc.available >= tcc.packing) - GROUP BY tcs.warehouseFk, tcs.itemFk; - - IF vIsZonePremium THEN - - DELETE - FROM tmp.ticketComponentRate - WHERE rate = 1; - - END IF; - - INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg) - SELECT - tcc.warehouseFk, - tcc.itemFk, - 3 rate, - tcc.available `grouping`, - SUM(tcs.sumCost) price, - SUM(tcs.sumCost) / weightGrouping priceKg - FROM tmp.ticketComponentCalculate tcc - JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk - AND tcs.warehouseFk = tcc.warehouseFk - WHERE IFNULL(tcs.classRate, 3) = 3 - GROUP BY tcs.warehouseFk, tcs.itemFk; - - INSERT INTO tmp.ticketComponentPrice (warehouseFk, itemFk, rate, `grouping`, price, priceKg) - SELECT * FROM ( - SELECT * FROM tmp.ticketComponentRate ORDER BY price - ) t - GROUP BY itemFk, warehouseFk, `grouping`; - - SELECT * FROM tmp.ticketComponentPrice; - - DROP TEMPORARY TABLE - tmp.ticketComponentCalculate, - tmp.ticketComponentSum, - tmp.ticketComponentBase, - tmp.ticketComponentRate, - tmp.ticketComponentCopy; - -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 `catalog_componentPrepare` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -51595,11 +52177,11 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET character_set_client = 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 = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `clean`() BEGIN @@ -51628,9 +52210,6 @@ BEGIN DELETE FROM itemShelving WHERE created < CURDATE() AND visible = 0; DELETE FROM ticketDown WHERE created < TIMESTAMPADD(DAY,-1,CURDATE()); DELETE FROM entryLog WHERE creationDate < vDateShort; - DELETE g FROM glsExpedition g - JOIN expedition e ON e.id = g.expeditionFk - WHERE e.created < v26Month; DELETE IGNORE FROM expedition WHERE created < v26Month; DELETE FROM sms WHERE created < v18Month; DELETE FROM saleTracking WHERE created < vDateShort; @@ -51765,9 +52344,7 @@ BEGIN DELETE FROM travelLog WHERE creationDate < v3Month; - CALL shelving_clean; - CALL ticketPackagingRecovery; - + CALL shelving_clean; END ;; DELIMITER ; @@ -51786,87 +52363,87 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `clean_logiflora`() -BEGIN - /* partir en 2 procedimientos, uno que borre compras y otro articulos - * item_clean, buy_clean - * */ - - DECLARE vMaxDated DATE DEFAULT TIMESTAMPADD(DAY, - 7, CURDATE()); - DECLARE vDone INT DEFAULT FALSE; - DECLARE vBuyFk INT; - DECLARE cur1 CURSOR FOR SELECT id FROM tmp.buy; - DECLARE cur2 CURSOR FOR SELECT id FROM tmp.item; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - DROP TEMPORARY TABLE IF EXISTS tmp.buy; - - CREATE TEMPORARY TABLE tmp.buy - ENGINE = MEMORY - SELECT b.id - FROM vn.buy b - JOIN vn.entry e ON e.id = b.entryFk - JOIN vn.travel tr ON tr.id = e.travelFk - JOIN vn.agencyMode am ON am.id = tr.agencyFk - WHERE b.quantity = 0 - AND am.name = 'LOGIFLORA' - AND e.isRaid; - - OPEN cur1; - - read_loop: LOOP - - SET vDone = FALSE; - - FETCH cur1 INTO vBuyFk; - - IF vDone THEN - LEAVE read_loop; - END IF; - - DELETE FROM vn.buy WHERE id = vBuyFk; - - END LOOP; - - CLOSE cur1; - - DROP TEMPORARY TABLE tmp.buy; - - DROP TEMPORARY TABLE IF EXISTS tmp.item; - - CREATE TEMPORARY TABLE tmp.item - ENGINE = MEMORY - SELECT DISTINCT i.id - FROM vn.item i - LEFT JOIN hedera.orderRow o ON o.itemFk = i.id - LEFT JOIN vn.sale s ON s.itemFk = i.id - LEFT JOIN vn.buy b ON b.itemFk = i.id - WHERE i.supplyResponseFk - AND o.id IS NULL - AND b.id IS NULL - AND s.id IS NULL - AND i.created < vMaxDated; - - OPEN cur2; - - read_loop: LOOP - - SET vDone = FALSE; - - FETCH cur2 INTO vBuyFk; - - IF vDone THEN - LEAVE read_loop; - END IF; - - DELETE FROM vn.item WHERE id = vBuyFk; - - END LOOP; - - CLOSE cur2; - - DROP TEMPORARY TABLE tmp.item; - +BEGIN + /* partir en 2 procedimientos, uno que borre compras y otro articulos + * item_clean, buy_clean + * */ + + DECLARE vMaxDated DATE DEFAULT TIMESTAMPADD(DAY, - 7, CURDATE()); + DECLARE vDone INT DEFAULT FALSE; + DECLARE vBuyFk INT; + DECLARE cur1 CURSOR FOR SELECT id FROM tmp.buy; + DECLARE cur2 CURSOR FOR SELECT id FROM tmp.item; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + DROP TEMPORARY TABLE IF EXISTS tmp.buy; + + CREATE TEMPORARY TABLE tmp.buy + ENGINE = MEMORY + SELECT b.id + FROM vn.buy b + JOIN vn.entry e ON e.id = b.entryFk + JOIN vn.travel tr ON tr.id = e.travelFk + JOIN vn.agencyMode am ON am.id = tr.agencyFk + WHERE b.quantity = 0 + AND am.name = 'LOGIFLORA' + AND e.isRaid; + + OPEN cur1; + + read_loop: LOOP + + SET vDone = FALSE; + + FETCH cur1 INTO vBuyFk; + + IF vDone THEN + LEAVE read_loop; + END IF; + + DELETE FROM vn.buy WHERE id = vBuyFk; + + END LOOP; + + CLOSE cur1; + + DROP TEMPORARY TABLE tmp.buy; + + DROP TEMPORARY TABLE IF EXISTS tmp.item; + + CREATE TEMPORARY TABLE tmp.item + ENGINE = MEMORY + SELECT DISTINCT i.id + FROM vn.item i + LEFT JOIN hedera.orderRow o ON o.itemFk = i.id + LEFT JOIN vn.sale s ON s.itemFk = i.id + LEFT JOIN vn.buy b ON b.itemFk = i.id + WHERE i.supplyResponseFk + AND o.id IS NULL + AND b.id IS NULL + AND s.id IS NULL + AND i.created < vMaxDated; + + OPEN cur2; + + read_loop: LOOP + + SET vDone = FALSE; + + FETCH cur2 INTO vBuyFk; + + IF vDone THEN + LEAVE read_loop; + END IF; + + DELETE FROM vn.item WHERE id = vBuyFk; + + END LOOP; + + CLOSE cur2; + + DROP TEMPORARY TABLE tmp.item; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -51906,76 +52483,76 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `clientCreate`( - vFirstname VARCHAR(50), - vSurnames VARCHAR(50), - vFi VARCHAR(9), - vAddress TEXT, - vPostcode CHAR(5), - vCity VARCHAR(25), - vProvinceFk SMALLINT(5), - vCompanyFk SMALLINT(5), - vPhone VARCHAR(11), - vEmail VARCHAR(255), +CREATE DEFINER=`root`@`localhost` PROCEDURE `clientCreate`( + vFirstname VARCHAR(50), + vSurnames VARCHAR(50), + vFi VARCHAR(9), + vAddress TEXT, + vPostcode CHAR(5), + vCity VARCHAR(25), + vProvinceFk SMALLINT(5), + vCompanyFk SMALLINT(5), + vPhone VARCHAR(11), + vEmail VARCHAR(255), vUserFk INT) -BEGIN -/** - * Create new client - * - */ - DECLARE vPayMethodFk INT DEFAULT 4; - DECLARE vDueDay INT DEFAULT 5; - DECLARE vDefaultCredit DECIMAL(10, 2) DEFAULT 300.00; - DECLARE vIsTaxDataChecked TINYINT(1) DEFAULT 1; - DECLARE vHasCoreVnl BOOLEAN DEFAULT TRUE; - DECLARE vMandateTypeFk INT DEFAULT 2; - - INSERT INTO `client` ( - id, - name, - street, - fi, - phone, - email, - provinceFk, - city, - postcode, - socialName, - payMethodFk, - dueDay, - credit, - isTaxDataChecked, - hasCoreVnl, - isEqualizated) - VALUES ( - vUserFk, - CONCAT('TR ', vFirstname, ' ', vSurnames), - vAddress, - TRIM(vFi), - vPhone, - vEmail, - vProvinceFk, - vCity, - vPostcode, - CONCAT(vSurnames, ' ', vFirstname), - vPayMethodFk, - vDueDay, - vDefaultCredit, - vIsTaxDataChecked, - vHasCoreVnl, - FALSE - ) ON duplicate key update - payMethodFk = vPayMethodFk, - dueDay = vDueDay, - credit = vDefaultCredit, - isTaxDataChecked = vIsTaxDataChecked, - hasCoreVnl = vHasCoreVnl, - isActive = TRUE; - - IF (SELECT COUNT(*) FROM mandate WHERE clientFk = vUserFk AND companyFk = vCompanyFk AND mandateTypeFk = vMandateTypeFk) = 0 THEN - INSERT INTO mandate (clientFk, companyFk, mandateTypeFk) - VALUES (vUserFk, vCompanyFk, vMandateTypeFk); - END IF; +BEGIN +/** + * Create new client + * + */ + DECLARE vPayMethodFk INT DEFAULT 4; + DECLARE vDueDay INT DEFAULT 5; + DECLARE vDefaultCredit DECIMAL(10, 2) DEFAULT 300.00; + DECLARE vIsTaxDataChecked TINYINT(1) DEFAULT 1; + DECLARE vHasCoreVnl BOOLEAN DEFAULT TRUE; + DECLARE vMandateTypeFk INT DEFAULT 2; + + INSERT INTO `client` ( + id, + name, + street, + fi, + phone, + email, + provinceFk, + city, + postcode, + socialName, + payMethodFk, + dueDay, + credit, + isTaxDataChecked, + hasCoreVnl, + isEqualizated) + VALUES ( + vUserFk, + CONCAT('TR ', vFirstname, ' ', vSurnames), + vAddress, + TRIM(vFi), + vPhone, + vEmail, + vProvinceFk, + vCity, + vPostcode, + CONCAT(vSurnames, ' ', vFirstname), + vPayMethodFk, + vDueDay, + vDefaultCredit, + vIsTaxDataChecked, + vHasCoreVnl, + FALSE + ) ON duplicate key update + payMethodFk = vPayMethodFk, + dueDay = vDueDay, + credit = vDefaultCredit, + isTaxDataChecked = vIsTaxDataChecked, + hasCoreVnl = vHasCoreVnl, + isActive = TRUE; + + IF (SELECT COUNT(*) FROM mandate WHERE clientFk = vUserFk AND companyFk = vCompanyFk AND mandateTypeFk = vMandateTypeFk) = 0 THEN + INSERT INTO mandate (clientFk, companyFk, mandateTypeFk) + VALUES (vUserFk, vCompanyFk, vMandateTypeFk); + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -52035,50 +52612,50 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `clientFreeze`() -BEGIN -/** - * Congela diariamente aquellos clientes que son morosos sin recobro, - * pero que no sean trabajadores, - * y que el riesgo no sea menor que cero - * hasta que no se gire la remesa no se congelan a los clientes de giro - */ - - DECLARE vIsRemittanced BOOLEAN; - - SELECT id into vIsRemittanced - FROM receipt - WHERE invoiceFk LIKE 'REMESA%' - AND payed > util.firstDayOfMonth(CURDATE()) - limit 1; - - DROP TEMPORARY TABLE IF EXISTS tmp.clientGetDebt; - CREATE TEMPORARY TABLE tmp.clientGetDebt - SELECT clientFk - FROM bs.defaulter - WHERE created = CURDATE() - AND amount; - - CALL clientGetDebt(CURDATE()); - - UPDATE client c - JOIN bi.defaulters d ON d.client = c.id AND d.date = CURDATE() - JOIN config ON TRUE - LEFT JOIN account.`user` u ON u.id = c.id AND u.active - LEFT JOIN worker w ON w.id = u.id - LEFT JOIN recovery r ON r.clientFk = c.id AND r.finished IS NULL - LEFT JOIN payMethod pm ON pm.id = c.payMethodFk - LEFT JOIN tmp.risk rk ON rk.clientFk = c.id - SET c.isFreezed = TRUE, - d.frozened = CURDATE(), - u.active = FALSE - WHERE (d.amount > config.defaultersMaxAmount - AND rk.risk > 0) - AND c.typeFk = 'normal' - AND r.id IS NULL - AND w.id IS NULL - AND (vIsRemittanced OR pm.code <> 'bankDraft'); - - DROP TEMPORARY TABLE tmp.clientGetDebt; +BEGIN +/** + * Congela diariamente aquellos clientes que son morosos sin recobro, + * pero que no sean trabajadores, + * y que el riesgo no sea menor que cero + * hasta que no se gire la remesa no se congelan a los clientes de giro + */ + + DECLARE vIsRemittanced BOOLEAN; + + SELECT id into vIsRemittanced + FROM receipt + WHERE invoiceFk LIKE 'REMESA%' + AND payed > util.firstDayOfMonth(CURDATE()) + limit 1; + + DROP TEMPORARY TABLE IF EXISTS tmp.clientGetDebt; + CREATE TEMPORARY TABLE tmp.clientGetDebt + SELECT clientFk + FROM bs.defaulter + WHERE created = CURDATE() + AND amount; + + CALL clientGetDebt(CURDATE()); + + UPDATE client c + JOIN bi.defaulters d ON d.client = c.id AND d.date = CURDATE() + JOIN config ON TRUE + LEFT JOIN account.`user` u ON u.id = c.id AND u.active + LEFT JOIN worker w ON w.id = u.id + LEFT JOIN recovery r ON r.clientFk = c.id AND r.finished IS NULL + LEFT JOIN payMethod pm ON pm.id = c.payMethodFk + LEFT JOIN tmp.risk rk ON rk.clientFk = c.id + SET c.isFreezed = TRUE, + d.frozened = CURDATE(), + u.active = FALSE + WHERE (d.amount > config.defaultersMaxAmount + AND rk.risk > 0) + AND c.typeFk = 'normal' + AND r.id IS NULL + AND w.id IS NULL + AND (vIsRemittanced OR pm.code <> 'bankDraft'); + + DROP TEMPORARY TABLE tmp.clientGetDebt; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -52096,59 +52673,59 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `clientGetDebt`(vDate DATE) -BEGIN -/** - * Calcula el riesgo para los clientes activos - * - * @table tmp.clientGetDebt(clientFk) - * @param vDate Fecha maxima de los registros - * @return tmp.risk - */ - DECLARE vStarted DATETIME DEFAULT TIMESTAMPADD(DAY, -35, CURDATE()); - DECLARE vEnded DATETIME; - - SET vEnded = TIMESTAMP(IFNULL(vDate, CURDATE()), '23:59:59'); - - DROP TEMPORARY TABLE IF EXISTS tClientRisk; - CREATE TEMPORARY TABLE tClientRisk - ENGINE = MEMORY - SELECT cr.clientFk, SUM(cr.amount) amount - FROM clientRisk cr - JOIN tmp.clientGetDebt c ON c.clientFk = cr.clientFk - GROUP BY cr.clientFk; - - INSERT INTO tClientRisk - SELECT c.clientFk, SUM(r.amountPaid) - FROM receipt r - JOIN tmp.clientGetDebt c ON c.clientFk = r.clientFk - WHERE r.payed > vEnded - GROUP BY c.clientFk; - - INSERT INTO tClientRisk - SELECT t.clientFk, CAST(-SUM(t.amount) / 100 AS DECIMAL(10,2)) - FROM hedera.tpvTransaction t - JOIN tmp.clientGetDebt c ON c.clientFk = t.clientFk - WHERE t.receiptFk IS NULL - AND t.status = 'ok' - GROUP BY t.clientFk; - - INSERT INTO tClientRisk - SELECT t.clientFk, totalWithVat - FROM ticket t - JOIN tmp.clientGetDebt c ON c.clientFk = t.clientFk - WHERE refFk IS NULL - AND shipped BETWEEN vStarted AND vEnded; - - DROP TEMPORARY TABLE IF EXISTS tmp.risk; - CREATE TEMPORARY TABLE tmp.risk - (PRIMARY KEY (clientFk)) - ENGINE = MEMORY - SELECT clientFk, SUM(amount) risk - FROM client c - JOIN tClientRisk cr ON cr.clientFk = c.id - GROUP BY c.id; - - DROP TEMPORARY TABLE tClientRisk; +BEGIN +/** + * Calcula el riesgo para los clientes activos + * + * @table tmp.clientGetDebt(clientFk) + * @param vDate Fecha maxima de los registros + * @return tmp.risk + */ + DECLARE vStarted DATETIME DEFAULT TIMESTAMPADD(DAY, -35, CURDATE()); + DECLARE vEnded DATETIME; + + SET vEnded = TIMESTAMP(IFNULL(vDate, CURDATE()), '23:59:59'); + + DROP TEMPORARY TABLE IF EXISTS tClientRisk; + CREATE TEMPORARY TABLE tClientRisk + ENGINE = MEMORY + SELECT cr.clientFk, SUM(cr.amount) amount + FROM clientRisk cr + JOIN tmp.clientGetDebt c ON c.clientFk = cr.clientFk + GROUP BY cr.clientFk; + + INSERT INTO tClientRisk + SELECT c.clientFk, SUM(r.amountPaid) + FROM receipt r + JOIN tmp.clientGetDebt c ON c.clientFk = r.clientFk + WHERE r.payed > vEnded + GROUP BY c.clientFk; + + INSERT INTO tClientRisk + SELECT t.clientFk, CAST(-SUM(t.amount) / 100 AS DECIMAL(10,2)) + FROM hedera.tpvTransaction t + JOIN tmp.clientGetDebt c ON c.clientFk = t.clientFk + WHERE t.receiptFk IS NULL + AND t.status = 'ok' + GROUP BY t.clientFk; + + INSERT INTO tClientRisk + SELECT t.clientFk, totalWithVat + FROM ticket t + JOIN tmp.clientGetDebt c ON c.clientFk = t.clientFk + WHERE refFk IS NULL + AND shipped BETWEEN vStarted AND vEnded; + + DROP TEMPORARY TABLE IF EXISTS tmp.risk; + CREATE TEMPORARY TABLE tmp.risk + (PRIMARY KEY (clientFk)) + ENGINE = MEMORY + SELECT clientFk, SUM(amount) risk + FROM client c + JOIN tClientRisk cr ON cr.clientFk = c.id + GROUP BY c.id; + + DROP TEMPORARY TABLE tClientRisk; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -53110,38 +53687,38 @@ DELIMITER ; /*!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 collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `collectionOrTicket_printSticker`(vParam INT, vSectorFk INT) -BEGIN - - /*Imprime una etiqueta amarilla a partir de una colección o ticket - * - * @param vParam colección o ticket a imprimir - * @param vSectorFk id del sector - */ - - DECLARE vLabelReport INT; - - SELECT labelReportFk INTO vLabelReport - FROM sector - WHERE id = vSectorFk; - - IF vLabelReport THEN - - INSERT INTO ticketTrolley(ticket, labelCount) - SELECT ticketFk, 1 - FROM ticketCollection - WHERE collectionFk = vParam OR ticketFK = vParam - ON DUPLICATE KEY UPDATE labelCount = labelCount + 1; - - INSERT INTO printServerQueue(labelReportFk, param1, workerFk) - SELECT vLabelReport, vParam, getUser(); - - END IF; - +BEGIN + + /*Imprime una etiqueta amarilla a partir de una colección o ticket + * + * @param vParam colección o ticket a imprimir + * @param vSectorFk id del sector + */ + + DECLARE vLabelReport INT; + + SELECT labelReportFk INTO vLabelReport + FROM sector + WHERE id = vSectorFk; + + IF vLabelReport THEN + + INSERT INTO ticketTrolley(ticket, labelCount) + SELECT ticketFk, 1 + FROM ticketCollection + WHERE collectionFk = vParam OR ticketFK = vParam + ON DUPLICATE KEY UPDATE labelCount = labelCount + 1; + + INSERT INTO printServerQueue(labelReportFk, param1, workerFk) + SELECT vLabelReport, vParam, getUser(); + + END IF; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -53582,20 +54159,20 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_get_`(vWorkerFk INT) -BEGIN - - /* Obtiene colección del sacador si tiene líneas pendientes - * - * @param vWorkerFk id del worker - */ - - SELECT c.id AS collectionFk, date(c.created) AS created - FROM vn.collection c - LEFT JOIN vn.state s ON c.stateFk = s.id - WHERE c.workerFk = vWorkerFk AND s.code = 'ON_PREPARATION' - AND created >= TIMESTAMPADD(HOUR , -6,NOW()); - - +BEGIN + + /* Obtiene colección del sacador si tiene líneas pendientes + * + * @param vWorkerFk id del worker + */ + + SELECT c.id AS collectionFk, date(c.created) AS created + FROM vn.collection c + LEFT JOIN vn.state s ON c.stateFk = s.id + WHERE c.workerFk = vWorkerFk AND s.code = 'ON_PREPARATION' + AND created >= TIMESTAMPADD(HOUR , -6,NOW()); + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -53613,21 +54190,21 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_kill`(vSelf INT) -BEGIN - - /* Elimina una coleccion y coloca sus tickets en OK - * - */ - - INSERT INTO vncontrol.inter(state_id, Id_Ticket) - SELECT s.id, ticketFk - FROM vn.ticketCollection tc - JOIN vn.state s ON s.code = 'OK' - WHERE tc.collectionFk = vSelf; - - DELETE FROM vn.collection - WHERE id = vSelf; - +BEGIN + + /* Elimina una coleccion y coloca sus tickets en OK + * + */ + + INSERT INTO vncontrol.inter(state_id, Id_Ticket) + SELECT s.id, ticketFk + FROM vn.ticketCollection tc + JOIN vn.state s ON s.code = 'OK' + WHERE tc.collectionFk = vSelf; + + DELETE FROM vn.collection + WHERE id = vSelf; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -54318,7 +54895,7 @@ proc:BEGIN CALL vn.productionControl(vWarehouseFk, 0); -- Esto hay que corregirlo añadiendo un nuevo parámetro al proc. PAK 23/12/21 - IF vSectorFk = 65 THEN + IF vSectorFk = 65 THEN -- Pedidos pequeños SET vTrainFk = 2; @@ -54344,13 +54921,18 @@ proc:BEGIN JOIN vn.state s ON s.id = pb.state WHERE pb.agency = 'REC_ALGEMESI' AND s.code != 'PICKER_DESIGNED'; - + + -- 2/3/2022 PAK Se acuerda con Pepe que los pedidos con riesgo no se sacan aunque se asignen. + DELETE pb.* + FROM tmp.productionBuffer pb + WHERE pb.problem LIKE '%RIESGO%'; + -- 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' + WHERE s.code = 'PICKER_DESIGNED' AND pb.workerCode = vWorkerCode; IF hasAssignedTickets THEN @@ -54364,7 +54946,7 @@ proc:BEGIN SELECT pb.ticketFk FROM tmp.productionBuffer pb JOIN vn.state s ON s.id = pb.state - WHERE s.code = 'PICKER_DESIGNED' + WHERE s.code = 'PICKER_DESIGNED' AND pb.workerCode = vWorkerCode ORDER BY HH, mm, @@ -54880,27 +55462,27 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `company_getFiscaldata`(workerFk INT) -BEGIN - -DECLARE vCompanyFk INT; - - SELECT IFNULL(uc.companyFk, rc.defaultCompanyFk) - INTO vCompanyFk - FROM vn.routeConfig rc - LEFT JOIN userConfig uc ON uc.userFk = workerFk; - - - SELECT - s.name AS name , - s.NIF AS nif , - s.street AS street , - s.city AS city , - s.postCode AS postCode - - FROM vn.company c - JOIN vn.worker w ON w.id = c.workerManagerFk - JOIN vn.supplier s ON s.id = c.id - WHERE c.id = vCompanyFk; +BEGIN + +DECLARE vCompanyFk INT; + + SELECT IFNULL(uc.companyFk, rc.defaultCompanyFk) + INTO vCompanyFk + FROM vn.routeConfig rc + LEFT JOIN userConfig uc ON uc.userFk = workerFk; + + + SELECT + s.name AS name , + s.NIF AS nif , + s.street AS street , + s.city AS city , + s.postCode AS postCode + + FROM vn.company c + JOIN vn.worker w ON w.id = c.workerManagerFk + JOIN vn.supplier s ON s.id = c.id + WHERE c.id = vCompanyFk; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -55553,18 +56135,18 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `department_getHasMistake`() -BEGIN - -/** - * Obtiene los sectores a los cuales les ponemos errores - * - */ - - SELECT id, name - FROM department - WHERE hasToMistake <> FALSE; - - +BEGIN + +/** + * Obtiene los sectores a los cuales les ponemos errores + * + */ + + SELECT id, name + FROM department + WHERE hasToMistake <> FALSE; + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -55673,18 +56255,18 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `deviceLog_add`(vWorkerFk INT, vAppName VARCHAR(45), vAppVersion VARCHAR(45), vAndroid_id VARCHAR(100)) -BEGIN -/* - * Inserta registro en tabla devicelog el log del usuario conectado - * @param vAppName es el nombre de la app - * @param vAppVersion es la versión de la app - * @param vAndroid_id es el android_id del dispositivo que se ha logueado - */ - - INSERT INTO deviceLog (userFK, nameApp, versionApp, android_id) - VALUES(vWorkerFk, vAppName, vAppVersion, vAndroid_id); - - +BEGIN +/* + * Inserta registro en tabla devicelog el log del usuario conectado + * @param vAppName es el nombre de la app + * @param vAppVersion es la versión de la app + * @param vAndroid_id es el android_id del dispositivo que se ha logueado + */ + + INSERT INTO deviceLog (userFK, nameApp, versionApp, android_id) + VALUES(vWorkerFk, vAppName, vAppVersion, vAndroid_id); + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -55726,19 +56308,19 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `deviceProductionUser_getWorker`(vAndroid_id VARCHAR(50)) -BEGIN -/** - * Selecciona si hay registrado un device con un android_id - * - * @param vAndroid_id el número android_id del dispositivo - * - */ - 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;*/ - +BEGIN +/** + * Selecciona si hay registrado un device con un android_id + * + * @param vAndroid_id el número android_id del dispositivo + * + */ + 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;*/ + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -55756,18 +56338,18 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `deviceProduction_getnameDevice`(vAndroid_id VARCHAR(50)) -BEGIN -/** - * Selecciona el id del dispositivo que corresponde al vAndroid_id - * - * @param vAndroid_id el número android_id del dispositivo - * - */ - - SELECT dp.id - FROM deviceProduction dp - WHERE dp.android_id = vAndroid_id; - +BEGIN +/** + * Selecciona el id del dispositivo que corresponde al vAndroid_id + * + * @param vAndroid_id el número android_id del dispositivo + * + */ + + SELECT dp.id + FROM deviceProduction dp + WHERE dp.android_id = vAndroid_id; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -56589,15 +57171,15 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ediTables_Update`() -BEGIN - - INSERT IGNORE INTO vn.genus(name) - SELECT latin_genus_name - FROM edi.genus ; - - INSERT IGNORE INTO vn.specie(name) - SELECT LCASE(latin_species_name) - FROM edi.specie ; +BEGIN + + INSERT IGNORE INTO vn.genus(name) + SELECT latin_genus_name + FROM edi.genus ; + + INSERT IGNORE INTO vn.specie(name) + SELECT LCASE(latin_species_name) + FROM edi.specie ; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -56740,65 +57322,65 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ekt_add__`(vPutOrderFk INT) -BEGIN - -/** - * Añade ekt para las ordenes de compra de proveedores que no envian el ekt por email - * - * @param vPutOrderFk PutOrderId de donde coger los datos - **/ - - INSERT INTO edi.ekt(entryYear, - deliveryNumber, - fec, - hor, - item, - pac, - qty, - ori, - cat, - pro, - pri, - package, - s1, - s2, - s3, - s4, - s5, - s6, - putOrderFk, - `ref`, - kop) - SELECT year(curdate()) entryYear, - p.id deliveryNumber , - CURDATE() fec, - CURTIME() hor, - i.longName item, - sr.NumberOfItemsPerCask pac, - p.quantity qty, - o.code ori, - i.category cat, - mp.supplierFk pro, - sr.Price pri, - sr.EmbalageCode package, - i.value5 s1, - i.value6 s2, - i.value7 s3, - i.value8 s4, - i.value9 s5, - i.value10 s6, - p.id putOrderFk, - sr.Item_ArticleCode, - sr.vmpID - FROM edi.putOrder p - JOIN edi.supplyResponse sr ON sr.ID = p.supplyResponseID - JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID - JOIN vn.item i ON i.supplyResponseFk = sr.ID - JOIN vn.origin o ON o.id = i.originFk - WHERE p.id = vPutOrderFk; - - CALL edi.ekt_load(LAST_INSERT_ID()); - +BEGIN + +/** + * Añade ekt para las ordenes de compra de proveedores que no envian el ekt por email + * + * @param vPutOrderFk PutOrderId de donde coger los datos + **/ + + INSERT INTO edi.ekt(entryYear, + deliveryNumber, + fec, + hor, + item, + pac, + qty, + ori, + cat, + pro, + pri, + package, + s1, + s2, + s3, + s4, + s5, + s6, + putOrderFk, + `ref`, + kop) + SELECT year(curdate()) entryYear, + p.id deliveryNumber , + CURDATE() fec, + CURTIME() hor, + i.longName item, + sr.NumberOfItemsPerCask pac, + p.quantity qty, + o.code ori, + i.category cat, + mp.supplierFk pro, + sr.Price pri, + sr.EmbalageCode package, + i.value5 s1, + i.value6 s2, + i.value7 s3, + i.value8 s4, + i.value9 s5, + i.value10 s6, + p.id putOrderFk, + sr.Item_ArticleCode, + sr.vmpID + FROM edi.putOrder p + JOIN edi.supplyResponse sr ON sr.ID = p.supplyResponseID + JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID + JOIN vn.item i ON i.supplyResponseFk = sr.ID + JOIN vn.origin o ON o.id = i.originFk + WHERE p.id = vPutOrderFk; + + CALL edi.ekt_load(LAST_INSERT_ID()); + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -56849,216 +57431,216 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `entryConverter__`(IN `vEntry` INT) -BEGIN - - DECLARE vWarehouseIn INT; - DECLARE vWarehouseOut INT; - DECLARE vTravel INT; - - DECLARE done BOOL DEFAULT FALSE; - - DECLARE vId_Entrada INT; - DECLARE vId_Article INT; - DECLARE vEtiquetas INT; - DECLARE vId_Cubo VARCHAR(10); - DECLARE vPacking INT; - DECLARE vGrouping INT; - DECLARE vCantidad INT; - DECLARE vCostefijo DECIMAL(10,3); - DECLARE vPortefijo DECIMAL(10,3); - DECLARE vEmbalajefijo DECIMAL(10); - DECLARE vComisionfija DECIMAL(10,3); - DECLARE vCaja INT; - DECLARE vNicho VARCHAR(5); - DECLARE vTarifa1 DECIMAL(10,2); - DECLARE vTarifa2 DECIMAL(10,2); - DECLARE vTarifa3 DECIMAL(10,2); - DECLARE vPVP DECIMAL(10,2); - DECLARE vCompra INT; - - DECLARE rs CURSOR FOR - SELECT - b.Id_Entrada, - b.Id_Article, - b.Etiquetas, - b.Id_Cubo, - b.Packing, - b.`grouping`, - b.Cantidad, - b.Costefijo, - b.Portefijo, - b.Embalajefijo, - b.Comisionfija, - b.caja, - b.Nicho, - b.Tarifa1, - b.Tarifa2, - b.Tarifa3, - b.PVP - FROM vn2008.Compres b - JOIN vn.itemConversor ic ON ic.espItemFk = b.Id_Article - WHERE Id_Entrada = vEntry; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - - SELECT warehouseInFk, warehouseOutFk, tr.id - INTO vWarehouseIn, vWarehouseOut, vTravel - FROM travel tr - JOIN entry e ON e.travelFk = tr.id - WHERE e.id = vEntry; - - UPDATE travel - SET warehouseInFk = vWarehouseOut, - warehouseOutFk = vWarehouseIn - WHERE id = vTravel; - - UPDATE vn2008.Compres c - LEFT JOIN vn.itemConversor ic ON ic.espItemFk = c.Id_Article - SET Etiquetas = 0, Cantidad = 0 - WHERE c.Id_Entrada = vEntry - AND ic.espItemFk IS NULL; - - OPEN rs; - - DELETE FROM vn2008.Compres WHERE Id_Entrada = vEntry; - - FETCH rs INTO - vId_Entrada, - vId_Article, - vEtiquetas, - vId_Cubo, - vPacking, - vGrouping, - vCantidad, - vCostefijo, - vPortefijo, - vEmbalajefijo, - vComisionfija, - vCaja, - vNicho, - vTarifa1, - vTarifa2, - vTarifa3, - vPVP; - - WHILE NOT done DO - - -- Primero la linea original con las cantidades invertidas - INSERT INTO vn2008.Compres - ( - Id_Entrada, - Id_Article, - Etiquetas, - Id_Cubo, - Packing, - `grouping`, - Cantidad, - Costefijo, - Portefijo, - Embalajefijo, - Comisionfija, - caja, - Nicho, - Tarifa1, - Tarifa2, - Tarifa3, - PVP - ) - VALUES - ( - vId_Entrada, - vId_Article, - - vEtiquetas, - vId_Cubo, - vPacking, - vGrouping, - - vCantidad, - vCostefijo, - vPortefijo, - vEmbalajefijo, - vComisionfija, - vCaja, - vNicho, - vTarifa1, - vTarifa2, - vTarifa3, - vPVP); - - -- Ahora la linea nueva, con el item genérico - INSERT INTO vn2008.Compres - ( - Id_Entrada, - Id_Article, - Etiquetas, - Id_Cubo, - Packing, - `grouping`, - Cantidad, - Costefijo, - Portefijo, - Embalajefijo, - Comisionfija, - caja, - Nicho, - Tarifa1, - Tarifa2, - Tarifa3, - PVP - ) - SELECT - vId_Entrada, - genItemFk as Id_Article, - vEtiquetas, - vId_Cubo, - vPacking, - vGrouping, - vCantidad, - vCostefijo, - vPortefijo, - vEmbalajefijo, - vComisionfija, - vCaja, - vNicho, - vTarifa1, - vTarifa2, - vTarifa3, - vPVP - FROM itemConversor - WHERE espItemFk = vId_Article; - - SELECT LAST_INSERT_ID() - INTO vCompra; - - REPLACE vn2008.Compres_mark(Id_Compra,`comment`) - SELECT vCompra, vId_Article; - - - FETCH rs INTO - vId_Entrada, - vId_Article, - vEtiquetas, - vId_Cubo, - vPacking, - vGrouping, - vCantidad, - vCostefijo, - vPortefijo, - vEmbalajefijo, - vComisionfija, - vCaja, - vNicho, - vTarifa1, - vTarifa2, - vTarifa3, - vPVP; - - END WHILE; - - - CLOSE rs; - - - +BEGIN + + DECLARE vWarehouseIn INT; + DECLARE vWarehouseOut INT; + DECLARE vTravel INT; + + DECLARE done BOOL DEFAULT FALSE; + + DECLARE vId_Entrada INT; + DECLARE vId_Article INT; + DECLARE vEtiquetas INT; + DECLARE vId_Cubo VARCHAR(10); + DECLARE vPacking INT; + DECLARE vGrouping INT; + DECLARE vCantidad INT; + DECLARE vCostefijo DECIMAL(10,3); + DECLARE vPortefijo DECIMAL(10,3); + DECLARE vEmbalajefijo DECIMAL(10); + DECLARE vComisionfija DECIMAL(10,3); + DECLARE vCaja INT; + DECLARE vNicho VARCHAR(5); + DECLARE vTarifa1 DECIMAL(10,2); + DECLARE vTarifa2 DECIMAL(10,2); + DECLARE vTarifa3 DECIMAL(10,2); + DECLARE vPVP DECIMAL(10,2); + DECLARE vCompra INT; + + DECLARE rs CURSOR FOR + SELECT + b.Id_Entrada, + b.Id_Article, + b.Etiquetas, + b.Id_Cubo, + b.Packing, + b.`grouping`, + b.Cantidad, + b.Costefijo, + b.Portefijo, + b.Embalajefijo, + b.Comisionfija, + b.caja, + b.Nicho, + b.Tarifa1, + b.Tarifa2, + b.Tarifa3, + b.PVP + FROM vn2008.Compres b + JOIN vn.itemConversor ic ON ic.espItemFk = b.Id_Article + WHERE Id_Entrada = vEntry; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; + + SELECT warehouseInFk, warehouseOutFk, tr.id + INTO vWarehouseIn, vWarehouseOut, vTravel + FROM travel tr + JOIN entry e ON e.travelFk = tr.id + WHERE e.id = vEntry; + + UPDATE travel + SET warehouseInFk = vWarehouseOut, + warehouseOutFk = vWarehouseIn + WHERE id = vTravel; + + UPDATE vn2008.Compres c + LEFT JOIN vn.itemConversor ic ON ic.espItemFk = c.Id_Article + SET Etiquetas = 0, Cantidad = 0 + WHERE c.Id_Entrada = vEntry + AND ic.espItemFk IS NULL; + + OPEN rs; + + DELETE FROM vn2008.Compres WHERE Id_Entrada = vEntry; + + FETCH rs INTO + vId_Entrada, + vId_Article, + vEtiquetas, + vId_Cubo, + vPacking, + vGrouping, + vCantidad, + vCostefijo, + vPortefijo, + vEmbalajefijo, + vComisionfija, + vCaja, + vNicho, + vTarifa1, + vTarifa2, + vTarifa3, + vPVP; + + WHILE NOT done DO + + -- Primero la linea original con las cantidades invertidas + INSERT INTO vn2008.Compres + ( + Id_Entrada, + Id_Article, + Etiquetas, + Id_Cubo, + Packing, + `grouping`, + Cantidad, + Costefijo, + Portefijo, + Embalajefijo, + Comisionfija, + caja, + Nicho, + Tarifa1, + Tarifa2, + Tarifa3, + PVP + ) + VALUES + ( + vId_Entrada, + vId_Article, + - vEtiquetas, + vId_Cubo, + vPacking, + vGrouping, + - vCantidad, + vCostefijo, + vPortefijo, + vEmbalajefijo, + vComisionfija, + vCaja, + vNicho, + vTarifa1, + vTarifa2, + vTarifa3, + vPVP); + + -- Ahora la linea nueva, con el item genérico + INSERT INTO vn2008.Compres + ( + Id_Entrada, + Id_Article, + Etiquetas, + Id_Cubo, + Packing, + `grouping`, + Cantidad, + Costefijo, + Portefijo, + Embalajefijo, + Comisionfija, + caja, + Nicho, + Tarifa1, + Tarifa2, + Tarifa3, + PVP + ) + SELECT + vId_Entrada, + genItemFk as Id_Article, + vEtiquetas, + vId_Cubo, + vPacking, + vGrouping, + vCantidad, + vCostefijo, + vPortefijo, + vEmbalajefijo, + vComisionfija, + vCaja, + vNicho, + vTarifa1, + vTarifa2, + vTarifa3, + vPVP + FROM itemConversor + WHERE espItemFk = vId_Article; + + SELECT LAST_INSERT_ID() + INTO vCompra; + + REPLACE vn2008.Compres_mark(Id_Compra,`comment`) + SELECT vCompra, vId_Article; + + + FETCH rs INTO + vId_Entrada, + vId_Article, + vEtiquetas, + vId_Cubo, + vPacking, + vGrouping, + vCantidad, + vCostefijo, + vPortefijo, + vEmbalajefijo, + vComisionfija, + vCaja, + vNicho, + vTarifa1, + vTarifa2, + vTarifa3, + vPVP; + + END WHILE; + + + CLOSE rs; + + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -57120,62 +57702,62 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `entryPrepare__`(IN `idE` BIGINT) -BEGIN - SELECT - b.quantity / b.packing AS Paquetes, - b.packing AS `Grouping`, - barcode, - 'ASEGURADO' AS asegurado, - ic.name, - ic.order, - s.name AS Consignatario, - e.supplierFk AS Id_Cliente, - e.isOrdered, - e.isConfirmed, - 10 AS Calidad, - LPAD(IFNULL(cpd.id, ip.code), - 5, - '0') AS path, - b.entryFk AS Id_Ticket, - t.landed AS Fecha, - b.itemFk, - b.quantity, - i.name AS Concepte, - i.size, - i.inkFk, - i.category, - o.code AS Origen, - 0 AS Bultos, - wIn.`name` AS Tipo, - 0 AS OK, - 0 AS Reservado, - i.stems, - b.id AS Id_Movimiento, - ip.code, - 'PEDIDO ASEGURADO' AS MSG, - 0 AS Seguro, - i.image, - pr.name AS producer - FROM vn.buy b - JOIN vn.entry e ON b.entryFk = e.id - JOIN vn.travel t ON t.id = e.travelFk - JOIN vn.warehouse wIn ON wIn.id = t.warehouseInFk - JOIN vn.warehouse wOut ON wOut.id = t.warehouseOutFk - JOIN vn.item i ON i.id = b.itemFk - JOIN vn.itemType it ON it.id =i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk - JOIN vn.packaging pkg ON pkg.id = b.packageFk - LEFT JOIN vn.itemPlacement ip ON i.id = ip.itemFk AND ip.warehouseFk = wIn.id AND ip.warehouseFk = t.warehouseOutFk - LEFT JOIN (SELECT itemFk, code AS barcode FROM vn.itemBarcode GROUP BY itemFk) ib ON ib.itemFk = b.itemFk - LEFT JOIN vn.origin o ON o.id = i.originFk - LEFT JOIN vn.supplier s ON s.id = e.supplierFk - LEFT JOIN vn.producer pr on pr.id = i.producerFk - LEFT JOIN vn.coolerPathDetail cpd ON LEFT(ip.code, 3) = cpd.hallway - WHERE - NOT wIn.isFeedStock AND NOT e.isInventory AND NOT e.isRaid - AND e.id = 158772 - AND i.typeFk IS NOT NULL - AND ic.display IS NOT FALSE; +BEGIN + SELECT + b.quantity / b.packing AS Paquetes, + b.packing AS `Grouping`, + barcode, + 'ASEGURADO' AS asegurado, + ic.name, + ic.order, + s.name AS Consignatario, + e.supplierFk AS Id_Cliente, + e.isOrdered, + e.isConfirmed, + 10 AS Calidad, + LPAD(IFNULL(cpd.id, ip.code), + 5, + '0') AS path, + b.entryFk AS Id_Ticket, + t.landed AS Fecha, + b.itemFk, + b.quantity, + i.name AS Concepte, + i.size, + i.inkFk, + i.category, + o.code AS Origen, + 0 AS Bultos, + wIn.`name` AS Tipo, + 0 AS OK, + 0 AS Reservado, + i.stems, + b.id AS Id_Movimiento, + ip.code, + 'PEDIDO ASEGURADO' AS MSG, + 0 AS Seguro, + i.image, + pr.name AS producer + FROM vn.buy b + JOIN vn.entry e ON b.entryFk = e.id + JOIN vn.travel t ON t.id = e.travelFk + JOIN vn.warehouse wIn ON wIn.id = t.warehouseInFk + JOIN vn.warehouse wOut ON wOut.id = t.warehouseOutFk + JOIN vn.item i ON i.id = b.itemFk + JOIN vn.itemType it ON it.id =i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk + JOIN vn.packaging pkg ON pkg.id = b.packageFk + LEFT JOIN vn.itemPlacement ip ON i.id = ip.itemFk AND ip.warehouseFk = wIn.id AND ip.warehouseFk = t.warehouseOutFk + LEFT JOIN (SELECT itemFk, code AS barcode FROM vn.itemBarcode GROUP BY itemFk) ib ON ib.itemFk = b.itemFk + LEFT JOIN vn.origin o ON o.id = i.originFk + LEFT JOIN vn.supplier s ON s.id = e.supplierFk + LEFT JOIN vn.producer pr on pr.id = i.producerFk + LEFT JOIN vn.coolerPathDetail cpd ON LEFT(ip.code, 3) = cpd.hallway + WHERE + NOT wIn.isFeedStock AND NOT e.isInventory AND NOT e.isRaid + AND e.id = 158772 + AND i.typeFk IS NOT NULL + AND ic.display IS NOT FALSE; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -57266,22 +57848,22 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `entryVolume__`(vEntryFk INT) -BEGIN - - SELECT ELT(it.temperature + 1,'Calientes','Frios','Secos') AS Temp, - CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) * - vn.item_getVolume(b.itemFk ,b.packageFk)) / vc.carro / 1000000 ,1) AS DECIMAL(10,2)) AS carros , - CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) * - vn.item_getVolume(b.itemFk ,b.packageFk)) / vc.espai / 1000000,1) AS DECIMAL(10,2)) AS espais - FROM vn.buy b - INNER JOIN vn.entry e ON e.id = b.entryFk - INNER JOIN vn.travel tr ON tr.id = e.travelFk - INNER JOIN vn.volumeConfig vc - INNER JOIN vn.item i ON i.id = b.itemFk - INNER JOIN vn.itemType it ON it.id = i.typeFk - WHERE e.id = vEntryFk - GROUP BY Temp; - +BEGIN + + SELECT ELT(it.temperature + 1,'Calientes','Frios','Secos') AS Temp, + CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) * + vn.item_getVolume(b.itemFk ,b.packageFk)) / vc.carro / 1000000 ,1) AS DECIMAL(10,2)) AS carros , + CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) * + vn.item_getVolume(b.itemFk ,b.packageFk)) / vc.espai / 1000000,1) AS DECIMAL(10,2)) AS espais + FROM vn.buy b + INNER JOIN vn.entry e ON e.id = b.entryFk + INNER JOIN vn.travel tr ON tr.id = e.travelFk + INNER JOIN vn.volumeConfig vc + INNER JOIN vn.item i ON i.id = b.itemFk + INNER JOIN vn.itemType it ON it.id = i.typeFk + WHERE e.id = vEntryFk + GROUP BY Temp; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -57435,67 +58017,67 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_clone`(vSelf INT) -BEGIN - -/* - * Clona una entrada - * - * @param vSelf Identificador de vn.entry - */ - - DECLARE vNewEntryFk INT; - - CALL vn.entry_cloneWithoutBuy(vSelf, vNewEntryFk); - - INSERT INTO vn.buy( entryFk, - itemFk, - quantity, - buyingValue, - freightValue, - isIgnored, - stickers, - packing, - `grouping`, - groupingMode, - containerFk, - comissionValue, - packageValue, - packageFk, - price1, - price2, - price3, - minPrice, - producer, - workerFk, - weight, - itemOriginalFk) - SELECT vNewEntryFk, - itemFk, - quantity, - buyingValue, - freightValue, - isIgnored, - stickers, - packing, - `grouping`, - groupingMode, - containerFk, - comissionValue, - packageValue, - packageFk, - price1, - price2, - price3, - minPrice, - producer, - workerFk, - weight, - itemOriginalFk - FROM vn.buy b - WHERE b.entryFk = vSelf; - - SELECT vNewEntryFk; - +BEGIN + +/* + * Clona una entrada + * + * @param vSelf Identificador de vn.entry + */ + + DECLARE vNewEntryFk INT; + + CALL vn.entry_cloneWithoutBuy(vSelf, vNewEntryFk); + + INSERT INTO vn.buy( entryFk, + itemFk, + quantity, + buyingValue, + freightValue, + isIgnored, + stickers, + packing, + `grouping`, + groupingMode, + containerFk, + comissionValue, + packageValue, + packageFk, + price1, + price2, + price3, + minPrice, + producer, + workerFk, + weight, + itemOriginalFk) + SELECT vNewEntryFk, + itemFk, + quantity, + buyingValue, + freightValue, + isIgnored, + stickers, + packing, + `grouping`, + groupingMode, + containerFk, + comissionValue, + packageValue, + packageFk, + price1, + price2, + price3, + minPrice, + producer, + workerFk, + weight, + itemOriginalFk + FROM vn.buy b + WHERE b.entryFk = vSelf; + + SELECT vNewEntryFk; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -57513,45 +58095,45 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_cloneWithoutBuy`(vSelf INT, OUT vNewEntryFk INT) -BEGIN - -/** - * Clona una entrada sin compras - * - * @param vSelf Identificador de vn.entry - * - * @return vNewEntryFk Identificador de la nueva entrada - */ - - START TRANSACTION; - - INSERT INTO vn.entry(supplierFk, - dated, - isInventory, - notes, - isRaid, - commission, - travelFk, - currencyFk, - companyFk, - loadPriority) - SELECT supplierFk, - dated, - isInventory, - notes, - isRaid, - commission, - travelFk, - currencyFk, - companyFk, - loadPriority - FROM vn.entry e - WHERE e.id = vSelf; - - SET vNewEntryFk = LAST_INSERT_ID(); - - COMMIT; - +BEGIN + +/** + * Clona una entrada sin compras + * + * @param vSelf Identificador de vn.entry + * + * @return vNewEntryFk Identificador de la nueva entrada + */ + + START TRANSACTION; + + INSERT INTO vn.entry(supplierFk, + dated, + isInventory, + notes, + isRaid, + commission, + travelFk, + currencyFk, + companyFk, + loadPriority) + SELECT supplierFk, + dated, + isInventory, + notes, + isRaid, + commission, + travelFk, + currencyFk, + companyFk, + loadPriority + FROM vn.entry e + WHERE e.id = vSelf; + + SET vNewEntryFk = LAST_INSERT_ID(); + + COMMIT; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -57569,64 +58151,64 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` 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; - - +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 */ ; @@ -57846,36 +58428,36 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_splitMisfit`(vSelf INT) -BEGIN - - /* Divide una entrada, pasando los registros que ha insertado vn.entry_fixMisfit de la entrada original - * a la nueva - */ - - DECLARE vNewEntryFk INT; - DECLARE vBuyFk INT; - - SELECT MAX(b.id) INTO vBuyFk - FROM vn.buy b - JOIN vn.item i ON i.id = b.itemFk - WHERE b.entryFk = vSelf - AND i.description = 'MISFIT'; - - INSERT INTO vn.entry(supplierFk, dated, notes, travelFk, currencyFk, companyFk) - SELECT supplierFk, dated, CONCAT('E:',vSelf), travelFk, currencyFk, companyFk - FROM vn.entry e - WHERE e.id = vSelf; - - SET vNewEntryFk = LAST_INSERT_ID(); - - UPDATE vn.buy b - SET b.entryFk = vNewEntryFk - WHERE b.entryFk = vSelf - AND b.id > vBuyFk; - - SELECT vNewEntryFk; - - +BEGIN + + /* Divide una entrada, pasando los registros que ha insertado vn.entry_fixMisfit de la entrada original + * a la nueva + */ + + DECLARE vNewEntryFk INT; + DECLARE vBuyFk INT; + + SELECT MAX(b.id) INTO vBuyFk + FROM vn.buy b + JOIN vn.item i ON i.id = b.itemFk + WHERE b.entryFk = vSelf + AND i.description = 'MISFIT'; + + INSERT INTO vn.entry(supplierFk, dated, notes, travelFk, currencyFk, companyFk) + SELECT supplierFk, dated, CONCAT('E:',vSelf), travelFk, currencyFk, companyFk + FROM vn.entry e + WHERE e.id = vSelf; + + SET vNewEntryFk = LAST_INSERT_ID(); + + UPDATE vn.buy b + SET b.entryFk = vNewEntryFk + WHERE b.entryFk = vSelf + AND b.id > vBuyFk; + + SELECT vNewEntryFk; + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -57888,14 +58470,15 @@ DELIMITER ; /*!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 collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `errorProduction_add`(vAction VARCHAR(25), vDatedFrom DATETIME, vDatedTo DATETIME) BEGIN + /** - * Fill in the errorProduction table. + * Fill in the errorProduction table */ DECLARE vDepartment VARCHAR(255); @@ -57907,28 +58490,32 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.volume; DROP TEMPORARY TABLE IF EXISTS tmp.errorsByChecker; - CASE - WHEN vAction = 'SACAR' THEN + CASE + WHEN vAction = 'SACAR' THEN SET vDepartment = 'Sacadores'; - WHEN vAction = 'ENCAJAR' THEN + WHEN vAction = 'ENCAJAR' THEN SET vDepartment = 'Encajadores'; - WHEN vAction = 'CONTROLAR' THEN + WHEN vAction = 'CONTROLAR' THEN SET vDepartment = 'Revisadores'; END CASE; - IF (vDepartment = 'Encajadores') - THEN + IF (vDepartment = 'Encajadores') THEN CREATE TEMPORARY TABLE tmp.total ENGINE = MEMORY - SELECT e.workerFk, COUNT(DISTINCT t.id) ticketCount - FROM expedition e + SELECT e.workerFk, + COUNT(DISTINCT t.id) ticketCount, + COUNT(s.id) lineCount + FROM expedition e JOIN ticket t ON e.ticketFk = t.id + JOIN sale s ON s.ticketFk = t.id WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo GROUP BY e.workerFk; - ELSE + ELSE CREATE TEMPORARY TABLE tmp.total ENGINE = MEMORY - SELECT st.workerFk, COUNT(DISTINCT t.id) ticketCount + SELECT st.workerFk, + COUNT(DISTINCT t.id) ticketCount, + COUNT(s.id) lineCount FROM saleTracking st JOIN vncontrol.accion a ON a.accion_id = st.actionFk JOIN sale s ON s.id = st.saleFk @@ -57940,19 +58527,22 @@ BEGIN CALL timeControl_calculateAll(vDatedFrom, vDatedTo); - CREATE TEMPORARY TABLE tmp.errorsByClaim + CREATE TEMPORARY TABLE tmp.errorsByClaim ENGINE = MEMORY - SELECT COUNT(c.ticketFk) errors, cd.workerFk + SELECT COUNT(c.ticketFk) errors, + cd.workerFk FROM claimDevelopment cd JOIN claim c ON cd.claimFk = c.id JOIN ticket t ON c.ticketFk = t.id JOIN claimResponsible cr ON cd.claimResponsibleFk = cr.id - WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo AND cr.description = vDepartment + WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo + AND cr.description = vDepartment GROUP BY cd.workerFk; CREATE TEMPORARY TABLE tmp.volume ENGINE = MEMORY - SELECT SUM(w.volume) volume, w.workerFk + SELECT SUM(w.volume) volume, + w.workerFk FROM bs.workerProductivity w WHERE w.dated BETWEEN vDatedFrom AND vDatedTo GROUP BY w.workerFk; @@ -57961,52 +58551,58 @@ BEGIN ENGINE = MEMORY SELECT sub1.workerFk, COUNT(id) errors FROM ( - SELECT st.workerFk, t.id + SELECT st.workerFk, + t.id FROM saleMistake sm JOIN saleTracking st ON sm.saleFk = st.saleFk JOIN vncontrol.accion a ON a.accion_id = st.actionFk JOIN sale s ON s.id = sm.saleFk JOIN ticket t on t.id = s.ticketFk - WHERE (t.shipped BETWEEN vDatedFrom AND vDatedTo) AND a.accion = vAction + WHERE (t.shipped BETWEEN vDatedFrom AND vDatedTo) + AND a.accion = vAction GROUP BY s.ticketFk ) sub1 GROUP BY sub1.workerFk; - INSERT INTO errorProduction(userFk, firstname, lastname, rol, ticketNumber, error, volume, hourStart, hourEnd, hourWorked, dated) - SELECT w.id, - w.firstName, - w.lastName, + INSERT INTO errorProduction(userFk, firstname, lastname, rol, ticketNumber, lineNumber, error, volume, hourStart, hourEnd, hourWorked, dated) + SELECT w.id, + w.firstName, + w.lastName, vDepartment, - t.ticketCount totalTickets, + t.ticketCount totalTickets, + t.lineCount, IFNULL(ec.errors,0) + IFNULL(ec2.errors,0) errors, IF(vDepartment = 'Revisadores', NULL, v.volume) volume, - SUBSTRING(tc.timed, 1, 5) hourStart, - SUBSTRING(tc.timed, LENGTH(tc.timed)-4, 5) hourEnd, + SUBSTRING(tc.timed, 1, 5) hourStart, + SUBSTRING(tc.timed, LENGTH(tc.timed)-4, 5) hourEnd, IFNULL(CAST(tc.timeWorkDecimal AS DECIMAL (10,2)) , 0) hourWorked, vDatedFrom dated FROM tmp.total t LEFT JOIN worker w ON w.id = t.workerFk - LEFT JOIN tmp.timeControlCalculate tc ON tc.userFk = t.workerFk - LEFT JOIN tmp.errorsByClaim ec ON ec.workerFk = t.workerFk + LEFT JOIN tmp.timeControlCalculate tc ON tc.userFk = t.workerFk + LEFT JOIN tmp.errorsByClaim ec ON ec.workerFk = t.workerFk LEFT JOIN tmp.volume v ON v.workerFk = t.workerFk - LEFT JOIN tmp.errorsByChecker ec2 ON ec2.workerFk = t.workerFk - GROUP BY w.id; + LEFT JOIN tmp.errorsByChecker ec2 ON ec2.workerFk = t.workerFk + GROUP BY w.id; IF (vDepartment = 'Sacadores') THEN CREATE TEMPORARY TABLE tmp.itemPickerErrors -- Errores de los sacadores, derivadores de los revisadores ENGINE = MEMORY - SELECT COUNT(c.ticketFk) errors, tt.workerFk + SELECT COUNT(c.ticketFk) errors, + tt.workerFk FROM claimDevelopment cd JOIN claim c ON cd.claimFk = c.id JOIN ticket t ON c.ticketFk = t.id JOIN claimResponsible cr ON cd.claimResponsibleFk = cr.id - JOIN ticketTracking tt ON tt.ticketFk = t.id - JOIN state s ON s.id = tt.stateFk - WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo AND cr.description = 'Revisadores' AND s.code = 'ON_PREPARATION' + JOIN ticketTracking tt ON tt.ticketFk = t.id + JOIN state s ON s.id = tt.stateFk + WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo + AND cr.description = 'Revisadores' + AND s.code = 'ON_PREPARATION' GROUP BY workerFk; UPDATE errorProduction ep - JOIN tmp.itemPickerErrors ipe ON ipe.workerFk = ep.userFk + JOIN tmp.itemPickerErrors ipe ON ipe.workerFk = ep.userFk SET ep.error = ep.error + ipe.errors WHERE vDatedFrom = ep.dated AND ep.rol = 'Sacadores'; @@ -58307,29 +58903,15 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET character_set_client = 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 = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionPallet_View`(vPalletFk INT) BEGIN - /* - DECLARE vIsPrint TINYINT; - SELECT isPrint INTO vIsPrint - FROM vn.expeditionPallet - WHERE id = vPalletFk; - - -- IF vIsPrint = 2 THEN -- Valor por defecto cuando se crea un pallet. Tras imprimir, pasa a estado 1 - - UPDATE vn.expeditionPallet - SET isPrint = FALSE - WHERE id = vPalletFk; - - -- END IF; - */ SELECT ep.id Pallet, t.routeFk Rutas, count(*) Cajas @@ -58473,33 +59055,131 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionState_add`(vParam INT, vStateCode VARCHAR(100)) -BEGIN - - /** - * Inserta nuevos registros en la tabla vn.expeditionState, segun el parámetro - * - * @param vParam Identificador de vn.expedition o de vn.route - * @param vStateCode Corresponde a vn.expeditionStateType.code - */ - - IF (SELECT COUNT(*) FROM vn.route r WHERE r.id = vParam) THEN - - INSERT INTO vn.expeditionState(expeditionFk, typeFk) - SELECT e.id, est.id - FROM vn.expedition e - JOIN vn.ticket t ON t.id = e.ticketFk - JOIN vn.expeditionStateType est ON est.code = vStateCode - WHERE t.routeFk = vParam; - - ELSE - - INSERT INTO vn.expeditionState(expeditionFk, typeFk) - SELECT vParam, est.id - FROM vn.expeditionStateType est - WHERE est.code = vStateCode; - - END IF; - +BEGIN + + /** + * Inserta nuevos registros en la tabla vn.expeditionState, segun el parámetro + * + * @param vParam Identificador de vn.expedition o de vn.route + * @param vStateCode Corresponde a vn.expeditionStateType.code + */ + + IF (SELECT COUNT(*) FROM vn.route r WHERE r.id = vParam) THEN + + INSERT INTO vn.expeditionState(expeditionFk, typeFk) + SELECT e.id, est.id + FROM vn.expedition e + JOIN vn.ticket t ON t.id = e.ticketFk + JOIN vn.expeditionStateType est ON est.code = vStateCode + WHERE t.routeFk = vParam; + + ELSE + + INSERT INTO vn.expeditionState(expeditionFk, typeFk) + SELECT vParam, est.id + FROM vn.expeditionStateType est + WHERE est.code = vStateCode; + + END IF; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!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 `expeditionState_addByAdress` */; +/*!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`@`localhost` PROCEDURE `expeditionState_addByAdress`(vAdressFk INT, vRouteFk INT, vStateCode VARCHAR(100)) +BEGIN + + /** + * Inserta nuevos registros en la tabla vn.expeditionState + * + * @param vAdressFk Identificador de vn.ticket + * @param vRouteFk Identificador de vn.route + * @param vStateCode Corresponde a vn.expeditionStateType.code + */ + + INSERT INTO vn.expeditionState(expeditionFk, typeFk) + SELECT e.id, est.id + FROM vn.expedition e + JOIN vn.expeditionStateType est ON est.code = vStateCode + JOIN vn.ticket t ON t.id = e.ticketFk + WHERE t.addressFk = vAdressFk AND t.routeFk = vRouteFk; + +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 `expeditionState_addByExpedition` */; +/*!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`@`localhost` PROCEDURE `expeditionState_addByExpedition`(vExpeditionFk INT, vStateCode VARCHAR(100)) +BEGIN + + /** + * Inserta nuevos registros en la tabla vn.expeditionState + * + * @param vExpeditionFk Identificador de vn.expedition + * @param vStateCode Corresponde a vn.expeditionStateType.code + */ + + INSERT INTO vn.expeditionState(expeditionFk, typeFk) + SELECT vExpeditionFk, est.id + FROM vn.expeditionStateType est + WHERE est.code = vStateCode; + +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 `expeditionState_addByRoute` */; +/*!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`@`localhost` PROCEDURE `expeditionState_addByRoute`(vRouteFk INT, vStateCode VARCHAR(100)) +BEGIN + + /** + * Inserta nuevos registros en la tabla vn.expeditionState, por rutas + * + * @param vRouteFk Identificador de vn.route + * @param vStateCode Corresponde a vn.expeditionStateType.code + */ + + INSERT INTO vn.expeditionState(expeditionFk, typeFk) + SELECT e.id, est.id + FROM vn.expedition e + JOIN vn.ticket t ON t.id = e.ticketFk + JOIN vn.expeditionStateType est ON est.code = vStateCode + WHERE t.routeFk = vRouteFk; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -58574,6 +59254,47 @@ BEGIN SET exp.checked = vChecked WHERE exp.id = vExpeditionFk; +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 `expedition_getFromRoute` */; +/*!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`@`localhost` PROCEDURE `expedition_getFromRoute`(vRouteFk INT) +BEGIN +/** + * Obtiene las expediciones a partir de una ruta + * @param vRouteFk Id de la ruta + */ + + SELECT e.id, + e.ticketFk, + e.checked, + t.routeFk, + ts.alertLevel, + a.street, + a.city, + a.postalCode, + t.addressFk, + a.nickname + FROM expedition e + JOIN ticket t ON t.id = e.ticketFk + JOIN ticketState ts ON ts.ticketFk = e.ticketFk + JOIN address a ON t.addressFk = a.id + LEFT JOIN warehouse w ON t.warehouseFk = w.id + WHERE t.routeFk = vRouteFk AND e.isBox <> FALSE; + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -58833,15 +59554,15 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `freelance_getInfo`(workerFk INT) -BEGIN - SELECT s.name, s.street, s.city, s.nif, s.postCode - FROM route r - JOIN agencyMode am ON r.agencyModeFk = am.id - JOIN agency a ON am.agencyFk = a.id - JOIN supplier s ON a.supplierFk = s.id - WHERE r.workerFk = workerFk - ORDER BY r.id DESC - LIMIT 1; +BEGIN + SELECT s.name, s.street, s.city, s.nif, s.postCode + FROM route r + JOIN agencyMode am ON r.agencyModeFk = am.id + JOIN agency a ON am.agencyFk = a.id + JOIN supplier s ON a.supplierFk = s.id + WHERE r.workerFk = workerFk + ORDER BY r.id DESC + LIMIT 1; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -58859,81 +59580,81 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `fustControl`(vFromDated DATE, vToDated DATE) -BEGIN - - DECLARE vSijsnerClientFk INT DEFAULT 19752; - - DECLARE vDateStart DATETIME; - DECLARE vDateEnd DATETIME; - - SET vDateStart = vFromDated; - SET vDateEnd = util.Dayend(vToDated); - - SELECT p.id FustCode, - CAST(sent.stucks AS DECIMAL(10,0)) FH, - CAST(tp.stucks AS DECIMAL(10,0)) Tickets, - CAST(-sj.stucks AS DECIMAL(10,0)) Sijsner, - CAST(IFNULL(sent.stucks,0) - IFNULL(tp.stucks,0) + IFNULL(sj.stucks,0) AS DECIMAL(10,0)) saldo - FROM vn.packaging p - LEFT JOIN ( - SELECT FustCode, sum(fustQuantity) stucks - FROM ( - SELECT IFNULL(pe.equivalentFk ,b.packageFk) FustCode, s.quantity / b.packing AS fustQuantity - FROM vn.sale s - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN vn.warehouse w ON w.id = t.warehouseFk - JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk - JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND lb.warehouse_id = t.warehouseFk - JOIN vn.buy b ON b.id = lb.buy_id - JOIN vn.packaging p ON p.id = b.packageFk - LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id - JOIN vn.address a ON a.id = t.addressFk - JOIN vn.province p2 ON p2.id = a.provinceFk - JOIN vn.country c ON c.id = p2.countryFk - WHERE t.shipped BETWEEN vDateStart AND vDateEnd - AND wa.name = 'VNH' - AND p.isPackageReturnable - AND c.country = 'FRANCIA') sub - GROUP BY FustCode) sent ON sent.FustCode = p.id - LEFT JOIN ( - SELECT FustCode, sum(quantity) stucks - FROM ( - SELECT IFNULL(pe.equivalentFk ,tp.packagingFk) FustCode, tp.quantity - FROM vn.ticketPackaging tp - JOIN vn.ticket t ON t.id = tp.ticketFk - JOIN vn.warehouse w ON w.id = t.warehouseFk - JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk - JOIN vn.packaging p ON p.id = tp.packagingFk - LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id - JOIN vn.address a ON a.id = t.addressFk - JOIN vn.province p2 ON p2.id = a.provinceFk - JOIN vn.country c ON c.id = p2.countryFk - WHERE t.shipped BETWEEN vDateStart AND vDateEnd - AND wa.name = 'VNH' - AND p.isPackageReturnable - AND c.country = 'FRANCIA' - AND t.clientFk != vSijsnerClientFk - AND tp.quantity > 0) sub - GROUP BY FustCode) tp ON tp.FustCode = p.id - LEFT JOIN ( - SELECT FustCode, sum(quantity) stucks - FROM ( - SELECT IFNULL(pe.equivalentFk ,tp.packagingFk) FustCode, tp.quantity - FROM vn.ticketPackaging tp - JOIN vn.ticket t ON t.id = tp.ticketFk - JOIN vn.warehouse w ON w.id = t.warehouseFk - JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk - JOIN vn.packaging p ON p.id = tp.packagingFk - LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id - WHERE t.shipped BETWEEN TIMESTAMPADD(DAY, 1, vDateStart ) AND TIMESTAMPADD(DAY, 1, vDateEnd ) - AND wa.name = 'VNH' - AND p.isPackageReturnable - AND t.clientFk = vSijsnerClientFk) sub - GROUP BY FustCode) sj ON sj.FustCode = p.id - WHERE sent.stucks - OR tp.stucks - OR sj.stucks; - +BEGIN + + DECLARE vSijsnerClientFk INT DEFAULT 19752; + + DECLARE vDateStart DATETIME; + DECLARE vDateEnd DATETIME; + + SET vDateStart = vFromDated; + SET vDateEnd = util.Dayend(vToDated); + + SELECT p.id FustCode, + CAST(sent.stucks AS DECIMAL(10,0)) FH, + CAST(tp.stucks AS DECIMAL(10,0)) Tickets, + CAST(-sj.stucks AS DECIMAL(10,0)) Sijsner, + CAST(IFNULL(sent.stucks,0) - IFNULL(tp.stucks,0) + IFNULL(sj.stucks,0) AS DECIMAL(10,0)) saldo + FROM vn.packaging p + LEFT JOIN ( + SELECT FustCode, sum(fustQuantity) stucks + FROM ( + SELECT IFNULL(pe.equivalentFk ,b.packageFk) FustCode, s.quantity / b.packing AS fustQuantity + FROM vn.sale s + JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.warehouse w ON w.id = t.warehouseFk + JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk + JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND lb.warehouse_id = t.warehouseFk + JOIN vn.buy b ON b.id = lb.buy_id + JOIN vn.packaging p ON p.id = b.packageFk + LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id + JOIN vn.address a ON a.id = t.addressFk + JOIN vn.province p2 ON p2.id = a.provinceFk + JOIN vn.country c ON c.id = p2.countryFk + WHERE t.shipped BETWEEN vDateStart AND vDateEnd + AND wa.name = 'VNH' + AND p.isPackageReturnable + AND c.country = 'FRANCIA') sub + GROUP BY FustCode) sent ON sent.FustCode = p.id + LEFT JOIN ( + SELECT FustCode, sum(quantity) stucks + FROM ( + SELECT IFNULL(pe.equivalentFk ,tp.packagingFk) FustCode, tp.quantity + FROM vn.ticketPackaging tp + JOIN vn.ticket t ON t.id = tp.ticketFk + JOIN vn.warehouse w ON w.id = t.warehouseFk + JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk + JOIN vn.packaging p ON p.id = tp.packagingFk + LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id + JOIN vn.address a ON a.id = t.addressFk + JOIN vn.province p2 ON p2.id = a.provinceFk + JOIN vn.country c ON c.id = p2.countryFk + WHERE t.shipped BETWEEN vDateStart AND vDateEnd + AND wa.name = 'VNH' + AND p.isPackageReturnable + AND c.country = 'FRANCIA' + AND t.clientFk != vSijsnerClientFk + AND tp.quantity > 0) sub + GROUP BY FustCode) tp ON tp.FustCode = p.id + LEFT JOIN ( + SELECT FustCode, sum(quantity) stucks + FROM ( + SELECT IFNULL(pe.equivalentFk ,tp.packagingFk) FustCode, tp.quantity + FROM vn.ticketPackaging tp + JOIN vn.ticket t ON t.id = tp.ticketFk + JOIN vn.warehouse w ON w.id = t.warehouseFk + JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk + JOIN vn.packaging p ON p.id = tp.packagingFk + LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id + WHERE t.shipped BETWEEN TIMESTAMPADD(DAY, 1, vDateStart ) AND TIMESTAMPADD(DAY, 1, vDateEnd ) + AND wa.name = 'VNH' + AND p.isPackageReturnable + AND t.clientFk = vSijsnerClientFk) sub + GROUP BY FustCode) sj ON sj.FustCode = p.id + WHERE sent.stucks + OR tp.stucks + OR sj.stucks; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -58951,38 +59672,38 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `fustControlDetail`(vFromDated DATE, vToDated DATE) -BEGIN - - DECLARE vSijsnerClientFk INT DEFAULT 19752; - - DECLARE vDateStart DATETIME; - DECLARE vDateEnd DATETIME; - - SET vDateStart = vFromDated; - SET vDateEnd = util.Dayend(vToDated); - - SELECT a.nickname shopName, - a.city , - IFNULL(pe.equivalentFk ,tp.packagingFk) FustCode, - tp.quantity, - tp.ticketFk, - CONCAT('From ', vFromDated,' to ', vToDated) AS dateRange - FROM vn.ticketPackaging tp - JOIN vn.ticket t ON t.id = tp.ticketFk - JOIN vn.warehouse w ON w.id = t.warehouseFk - JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk - JOIN vn.packaging p ON p.id = tp.packagingFk - LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id - JOIN vn.address a ON a.id = t.addressFk - JOIN vn.province p2 ON p2.id = a.provinceFk - JOIN vn.country c ON c.id = p2.countryFk - WHERE t.shipped BETWEEN vFromDated AND util.dayend(vToDated) - AND wa.name = 'VNH' - AND p.isPackageReturnable - AND c.country = 'FRANCIA' - AND t.clientFk != vSijsnerClientFk - AND tp.quantity > 0; - +BEGIN + + DECLARE vSijsnerClientFk INT DEFAULT 19752; + + DECLARE vDateStart DATETIME; + DECLARE vDateEnd DATETIME; + + SET vDateStart = vFromDated; + SET vDateEnd = util.Dayend(vToDated); + + SELECT a.nickname shopName, + a.city , + IFNULL(pe.equivalentFk ,tp.packagingFk) FustCode, + tp.quantity, + tp.ticketFk, + CONCAT('From ', vFromDated,' to ', vToDated) AS dateRange + FROM vn.ticketPackaging tp + JOIN vn.ticket t ON t.id = tp.ticketFk + JOIN vn.warehouse w ON w.id = t.warehouseFk + JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk + JOIN vn.packaging p ON p.id = tp.packagingFk + LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id + JOIN vn.address a ON a.id = t.addressFk + JOIN vn.province p2 ON p2.id = a.provinceFk + JOIN vn.country c ON c.id = p2.countryFk + WHERE t.shipped BETWEEN vFromDated AND util.dayend(vToDated) + AND wa.name = 'VNH' + AND p.isPackageReturnable + AND c.country = 'FRANCIA' + AND t.clientFk != vSijsnerClientFk + AND tp.quantity > 0; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -59273,25 +59994,25 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` 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(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; - - +BEGIN + + 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 ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -62011,225 +62732,225 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOut_new`( - vSerial VARCHAR(255), - vInvoiceDate DATETIME, - vTaxArea VARCHAR(25), +CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOut_new`( + vSerial VARCHAR(255), + vInvoiceDate DATETIME, + vTaxArea VARCHAR(25), OUT vNewInvoiceId INT) -BEGIN - -/* Creación de facturas emitidas. -* requiere previamente tabla ticketToInvoice(id). -* -* @param vSerial serie a la cual se hace la factura -* @param vInvoiceDate fecha de la factura -* @param vTaxArea tipo de iva en relacion a la empresa y al cliente -* @param vNewInvoiceId id de la factura que se acaba de generar -* -* @return vNewInvoiceId -*/ - - DECLARE vSpainCountryCode INT DEFAULT 1; - DECLARE vIsAnySaleToInvoice BOOL; - DECLARE vIsAnyServiceToInvoice BOOL; - DECLARE vNewRef VARCHAR(255); - DECLARE vWorker INT DEFAULT account.myUser_getId(); - DECLARE vCompany INT; - DECLARE vSupplier INT; - DECLARE vClient INT; - DECLARE vCplusStandardInvoiceTypeFk INT DEFAULT 1; - DECLARE vCplusCorrectingInvoiceTypeFk INT DEFAULT 6; - DECLARE vCplusSimplifiedInvoiceTypeFk INT DEFAULT 2; - DECLARE vCorrectingSerial VARCHAR(1) DEFAULT 'R'; - DECLARE vSimplifiedSerial VARCHAR(1) DEFAULT 'S'; - DECLARE vNewInvoiceInId INT; - DECLARE vIsInterCompany BOOL; - - SET vInvoiceDate = IFNULL(vInvoiceDate,CURDATE()); - - SELECT t.clientFk, t.companyFk - INTO vClient, vCompany - FROM ticketToInvoice tt - JOIN ticket t ON t.id = tt.id - LIMIT 1; - - -- Eliminem de ticketToInvoice els tickets que no han de ser facturats - DELETE ti.* - FROM ticketToInvoice ti - JOIN ticket t ON t.id = ti.id - JOIN client c ON c.id = t.clientFk - WHERE YEAR(t.shipped) < 2001 - OR c.isTaxDataChecked = FALSE - OR t.isDeleted - OR c.hasToInvoice = FALSE; - - SELECT SUM(s.quantity * s.price * (100 - s.discount)/100), ts.id - INTO vIsAnySaleToInvoice, vIsAnyServiceToInvoice - FROM ticketToInvoice t - LEFT JOIN sale s ON s.ticketFk = t.id - LEFT JOIN ticketService ts ON ts.ticketFk = t.id; - - IF (vIsAnySaleToInvoice OR vIsAnyServiceToInvoice) - AND (vCorrectingSerial = vSerial OR NOT hasAnyNegativeBase()) - THEN - - -- el trigger añade el siguiente Id_Factura correspondiente a la vSerial - INSERT INTO invoiceOut - ( - ref, - serial, - issued, - clientFk, - dued, - companyFk, - cplusInvoiceType477Fk - ) - SELECT - 1, - vSerial, - vInvoiceDate, - vClient, - getDueDate(vInvoiceDate, dueDay), - vCompany, - IF(vSerial = vCorrectingSerial, - vCplusCorrectingInvoiceTypeFk, - IF(vSerial = vSimplifiedSerial, - vCplusSimplifiedInvoiceTypeFk, - vCplusStandardInvoiceTypeFk)) - FROM client - WHERE id = vClient; - - - SET vNewInvoiceId = LAST_INSERT_ID(); - - SELECT `ref` - INTO vNewRef - FROM invoiceOut - WHERE id = vNewInvoiceId; - - UPDATE ticket t - JOIN ticketToInvoice ti ON ti.id = t.id - SET t.refFk = vNewRef; - - DROP TEMPORARY TABLE IF EXISTS tmp.updateInter; - CREATE TEMPORARY TABLE tmp.updateInter ENGINE = MEMORY - SELECT s.id,ti.id ticket_id,vWorker Id_Trabajador - FROM ticketToInvoice ti - LEFT JOIN vn.ticketState ts ON ti.id = ts.ticket - JOIN state s - WHERE IFNULL(ts.alertLevel,0) < 3 and s.`code` = vn.getAlert3State(ti.id); - - INSERT INTO vncontrol.inter(state_id,Id_Ticket,Id_Trabajador) - SELECT * FROM tmp.updateInter; - - - INSERT INTO ticketLog (action, userFk,originFk, description) - SELECT 'UPDATE',account.userGetId(),ti.id, CONCAT('Crea factura ',vNewRef) - FROM ticketToInvoice ti; - - CALL invoiceExpenceMake(vNewInvoiceId); - CALL invoiceTaxMake(vNewInvoiceId,vTaxArea); - - UPDATE invoiceOut io - JOIN ( - SELECT SUM(amount) AS total - FROM invoiceOutExpence - WHERE invoiceOutFk = vNewInvoiceId - ) base - JOIN ( - SELECT SUM(vat) AS total - FROM invoiceOutTax - WHERE invoiceOutFk = vNewInvoiceId - ) vat - SET io.amount = base.total + vat.total - WHERE io.id = vNewInvoiceId; - - DROP TEMPORARY TABLE tmp.updateInter; - - SELECT ios.isCEE INTO vIsInterCompany - FROM vn.ticket t - JOIN vn.company c ON c.clientFk = t.clientFk - JOIN vn.invoiceOut io ON io.`ref` = t.refFk - JOIN vn.invoiceOutSerial ios ON ios.code = io.serial - WHERE t.refFk = vNewRef; - - IF (vIsInterCompany) THEN - - SELECT vCompany INTO vSupplier; - SELECT id INTO vCompany FROM company WHERE clientFk = vClient; - - INSERT INTO invoiceIn(supplierFk, supplierRef, issued, companyFk) - SELECT vSupplier, vNewRef, vInvoiceDate, vCompany; - - SET vNewInvoiceInId = LAST_INSERT_ID(); - - DROP TEMPORARY TABLE IF EXISTS tmp.ticket; - CREATE TEMPORARY TABLE tmp.ticket - (KEY (ticketFk)) - ENGINE = MEMORY - SELECT id ticketFk - FROM ticketToInvoice; - - CALL `ticket_getTax`('NATIONAL'); - - SET @vTaxableBaseServices := 0.00; - SET @vTaxCodeGeneral := NULL; - - INSERT INTO vn.invoiceInTax(invoiceInFk, taxableBase, expenceFk, taxTypeSageFk, transactionTypeSageFk) - SELECT vNewInvoiceInId, @vTaxableBaseServices, sub.expenceFk, sub.taxTypeSageFk , sub.transactionTypeSageFk - FROM ( - SELECT @vTaxableBaseServices := SUM(tst.taxableBase) taxableBase, i.expenceFk, i.taxTypeSageFk , i.transactionTypeSageFk, @vTaxCodeGeneral := i.taxClassCodeFk - FROM tmp.ticketServiceTax tst - JOIN vn.invoiceOutTaxConfig i ON i.taxClassCodeFk = tst.code - WHERE i.isService - HAVING taxableBase - ) sub; - - INSERT INTO vn.invoiceInTax(invoiceInFk, taxableBase, expenceFk, taxTypeSageFk, transactionTypeSageFk) - SELECT vNewInvoiceInId, SUM(tt.taxableBase) - IF(tt.code = @vTaxCodeGeneral, @vTaxableBaseServices, 0) taxableBase, i.expenceFk, i.taxTypeSageFk , i.transactionTypeSageFk - FROM tmp.ticketTax tt - JOIN vn.invoiceOutTaxConfig i ON i.taxClassCodeFk = tt.code - WHERE !i.isService - GROUP BY tt.pgcFk - HAVING taxableBase - ORDER BY tt.priority; - - CALL `vn`.`invoiceInDueDay_calculate`(vNewInvoiceInId); - - INSERT INTO vn2008.intrastat_data (recibida_id, intrastat_id, importe, unidades, Paises_Id, neto) - SELECT - vNewInvoiceInId, - i.intrastatFk, - CAST(SUM((s.quantity * s.price * (100 - s.discount) / 100)) AS DECIMAL(10,2)) importe, - CAST(SUM(IFNULL(i.stems, 1) * s.quantity) AS DECIMAL (10 , 2 )) stems, - s2.countryFk, - CAST(SUM(IF(sv.physicalWeight, sv.physicalWeight, i.density * sub.cm3delivery/1000000)) AS DECIMAL(10,2)) neto - FROM vn.sale s - LEFT JOIN (SELECT ic.itemFk, ic.cm3delivery - FROM vn.itemCost ic - WHERE ic.cm3 - GROUP BY ic.itemFk) sub ON s.itemFk = sub.itemFk - LEFT JOIN vn.saleVolume sv ON sv.saleFk = s.id - LEFT JOIN vn.ticket t ON s.ticketFk = t.id - LEFT JOIN vn.supplier s2 ON s2.id = t.companyFk - LEFT JOIN vn.item i ON i.id = s.itemFk - LEFT JOIN vn.intrastat it ON it.id = i.intrastatFk - JOIN vn.invoiceOut iOut ON iOut.ref = t.refFk - WHERE iOut.`ref` = vNewRef - GROUP BY i.intrastatFk - ORDER BY i.intrastatFk; - - - DROP TEMPORARY TABLE tmp.ticket; - DROP TEMPORARY TABLE tmp.ticketAmount; - DROP TEMPORARY TABLE tmp.ticketTax; - DROP TEMPORARY TABLE tmp.ticketServiceTax; - - END IF; - - END IF; - - DROP TEMPORARY TABLE `ticketToInvoice`; +BEGIN + +/* Creación de facturas emitidas. +* requiere previamente tabla ticketToInvoice(id). +* +* @param vSerial serie a la cual se hace la factura +* @param vInvoiceDate fecha de la factura +* @param vTaxArea tipo de iva en relacion a la empresa y al cliente +* @param vNewInvoiceId id de la factura que se acaba de generar +* +* @return vNewInvoiceId +*/ + + DECLARE vSpainCountryCode INT DEFAULT 1; + DECLARE vIsAnySaleToInvoice BOOL; + DECLARE vIsAnyServiceToInvoice BOOL; + DECLARE vNewRef VARCHAR(255); + DECLARE vWorker INT DEFAULT account.myUser_getId(); + DECLARE vCompany INT; + DECLARE vSupplier INT; + DECLARE vClient INT; + DECLARE vCplusStandardInvoiceTypeFk INT DEFAULT 1; + DECLARE vCplusCorrectingInvoiceTypeFk INT DEFAULT 6; + DECLARE vCplusSimplifiedInvoiceTypeFk INT DEFAULT 2; + DECLARE vCorrectingSerial VARCHAR(1) DEFAULT 'R'; + DECLARE vSimplifiedSerial VARCHAR(1) DEFAULT 'S'; + DECLARE vNewInvoiceInId INT; + DECLARE vIsInterCompany BOOL; + + SET vInvoiceDate = IFNULL(vInvoiceDate,CURDATE()); + + SELECT t.clientFk, t.companyFk + INTO vClient, vCompany + FROM ticketToInvoice tt + JOIN ticket t ON t.id = tt.id + LIMIT 1; + + -- Eliminem de ticketToInvoice els tickets que no han de ser facturats + DELETE ti.* + FROM ticketToInvoice ti + JOIN ticket t ON t.id = ti.id + JOIN client c ON c.id = t.clientFk + WHERE YEAR(t.shipped) < 2001 + OR c.isTaxDataChecked = FALSE + OR t.isDeleted + OR c.hasToInvoice = FALSE; + + SELECT SUM(s.quantity * s.price * (100 - s.discount)/100), ts.id + INTO vIsAnySaleToInvoice, vIsAnyServiceToInvoice + FROM ticketToInvoice t + LEFT JOIN sale s ON s.ticketFk = t.id + LEFT JOIN ticketService ts ON ts.ticketFk = t.id; + + IF (vIsAnySaleToInvoice OR vIsAnyServiceToInvoice) + AND (vCorrectingSerial = vSerial OR NOT hasAnyNegativeBase()) + THEN + + -- el trigger añade el siguiente Id_Factura correspondiente a la vSerial + INSERT INTO invoiceOut + ( + ref, + serial, + issued, + clientFk, + dued, + companyFk, + cplusInvoiceType477Fk + ) + SELECT + 1, + vSerial, + vInvoiceDate, + vClient, + getDueDate(vInvoiceDate, dueDay), + vCompany, + IF(vSerial = vCorrectingSerial, + vCplusCorrectingInvoiceTypeFk, + IF(vSerial = vSimplifiedSerial, + vCplusSimplifiedInvoiceTypeFk, + vCplusStandardInvoiceTypeFk)) + FROM client + WHERE id = vClient; + + + SET vNewInvoiceId = LAST_INSERT_ID(); + + SELECT `ref` + INTO vNewRef + FROM invoiceOut + WHERE id = vNewInvoiceId; + + UPDATE ticket t + JOIN ticketToInvoice ti ON ti.id = t.id + SET t.refFk = vNewRef; + + DROP TEMPORARY TABLE IF EXISTS tmp.updateInter; + CREATE TEMPORARY TABLE tmp.updateInter ENGINE = MEMORY + SELECT s.id,ti.id ticket_id,vWorker Id_Trabajador + FROM ticketToInvoice ti + LEFT JOIN vn.ticketState ts ON ti.id = ts.ticket + JOIN state s + WHERE IFNULL(ts.alertLevel,0) < 3 and s.`code` = vn.getAlert3State(ti.id); + + INSERT INTO vncontrol.inter(state_id,Id_Ticket,Id_Trabajador) + SELECT * FROM tmp.updateInter; + + + INSERT INTO ticketLog (action, userFk,originFk, description) + SELECT 'UPDATE',account.userGetId(),ti.id, CONCAT('Crea factura ',vNewRef) + FROM ticketToInvoice ti; + + CALL invoiceExpenceMake(vNewInvoiceId); + CALL invoiceTaxMake(vNewInvoiceId,vTaxArea); + + UPDATE invoiceOut io + JOIN ( + SELECT SUM(amount) AS total + FROM invoiceOutExpence + WHERE invoiceOutFk = vNewInvoiceId + ) base + JOIN ( + SELECT SUM(vat) AS total + FROM invoiceOutTax + WHERE invoiceOutFk = vNewInvoiceId + ) vat + SET io.amount = base.total + vat.total + WHERE io.id = vNewInvoiceId; + + DROP TEMPORARY TABLE tmp.updateInter; + + SELECT ios.isCEE INTO vIsInterCompany + FROM vn.ticket t + JOIN vn.company c ON c.clientFk = t.clientFk + JOIN vn.invoiceOut io ON io.`ref` = t.refFk + JOIN vn.invoiceOutSerial ios ON ios.code = io.serial + WHERE t.refFk = vNewRef; + + IF (vIsInterCompany) THEN + + SELECT vCompany INTO vSupplier; + SELECT id INTO vCompany FROM company WHERE clientFk = vClient; + + INSERT INTO invoiceIn(supplierFk, supplierRef, issued, companyFk) + SELECT vSupplier, vNewRef, vInvoiceDate, vCompany; + + SET vNewInvoiceInId = LAST_INSERT_ID(); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticket; + CREATE TEMPORARY TABLE tmp.ticket + (KEY (ticketFk)) + ENGINE = MEMORY + SELECT id ticketFk + FROM ticketToInvoice; + + CALL `ticket_getTax`('NATIONAL'); + + SET @vTaxableBaseServices := 0.00; + SET @vTaxCodeGeneral := NULL; + + INSERT INTO vn.invoiceInTax(invoiceInFk, taxableBase, expenceFk, taxTypeSageFk, transactionTypeSageFk) + SELECT vNewInvoiceInId, @vTaxableBaseServices, sub.expenceFk, sub.taxTypeSageFk , sub.transactionTypeSageFk + FROM ( + SELECT @vTaxableBaseServices := SUM(tst.taxableBase) taxableBase, i.expenceFk, i.taxTypeSageFk , i.transactionTypeSageFk, @vTaxCodeGeneral := i.taxClassCodeFk + FROM tmp.ticketServiceTax tst + JOIN vn.invoiceOutTaxConfig i ON i.taxClassCodeFk = tst.code + WHERE i.isService + HAVING taxableBase + ) sub; + + INSERT INTO vn.invoiceInTax(invoiceInFk, taxableBase, expenceFk, taxTypeSageFk, transactionTypeSageFk) + SELECT vNewInvoiceInId, SUM(tt.taxableBase) - IF(tt.code = @vTaxCodeGeneral, @vTaxableBaseServices, 0) taxableBase, i.expenceFk, i.taxTypeSageFk , i.transactionTypeSageFk + FROM tmp.ticketTax tt + JOIN vn.invoiceOutTaxConfig i ON i.taxClassCodeFk = tt.code + WHERE !i.isService + GROUP BY tt.pgcFk + HAVING taxableBase + ORDER BY tt.priority; + + CALL `vn`.`invoiceInDueDay_calculate`(vNewInvoiceInId); + + INSERT INTO vn2008.intrastat_data (recibida_id, intrastat_id, importe, unidades, Paises_Id, neto) + SELECT + vNewInvoiceInId, + i.intrastatFk, + CAST(SUM((s.quantity * s.price * (100 - s.discount) / 100)) AS DECIMAL(10,2)) importe, + CAST(SUM(IFNULL(i.stems, 1) * s.quantity) AS DECIMAL (10 , 2 )) stems, + s2.countryFk, + CAST(SUM(IF(sv.physicalWeight, sv.physicalWeight, i.density * sub.cm3delivery/1000000)) AS DECIMAL(10,2)) neto + FROM vn.sale s + LEFT JOIN (SELECT ic.itemFk, ic.cm3delivery + FROM vn.itemCost ic + WHERE ic.cm3 + GROUP BY ic.itemFk) sub ON s.itemFk = sub.itemFk + LEFT JOIN vn.saleVolume sv ON sv.saleFk = s.id + LEFT JOIN vn.ticket t ON s.ticketFk = t.id + LEFT JOIN vn.supplier s2 ON s2.id = t.companyFk + LEFT JOIN vn.item i ON i.id = s.itemFk + LEFT JOIN vn.intrastat it ON it.id = i.intrastatFk + JOIN vn.invoiceOut iOut ON iOut.ref = t.refFk + WHERE iOut.`ref` = vNewRef + GROUP BY i.intrastatFk + ORDER BY i.intrastatFk; + + + DROP TEMPORARY TABLE tmp.ticket; + DROP TEMPORARY TABLE tmp.ticketAmount; + DROP TEMPORARY TABLE tmp.ticketTax; + DROP TEMPORARY TABLE tmp.ticketServiceTax; + + END IF; + + END IF; + + DROP TEMPORARY TABLE `ticketToInvoice`; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -62637,84 +63358,84 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemCard`(IN `vBarcode` VARCHAR(22), IN `vWarehouseFk` INT, IN isBarcode BOOL) -BEGIN - - /* - * @deprecated: Utilizar item_getInfo - */ - - 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, - i.comment as referencia - 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; - +BEGIN + + /* + * @deprecated: Utilizar item_getInfo + */ + + 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, + i.comment as referencia + 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 */ ; @@ -62822,119 +63543,119 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemDiary__`(IN vItemId INT, IN vWarehouse INT) -BEGIN - DECLARE vDateInventory DATETIME; - DECLARE vCurdate DATE DEFAULT CURDATE(); - DECLARE vDayEnd DATETIME DEFAULT util.dayEnd(vCurdate); - - SELECT vn.barcodeToItem(vItemId) INTO vItemId; - - -- traduccion: date, alertLevel, origin, reference, name, In, Out, Balance - SELECT inventoried INTO vDateInventory FROM config; - SET @a = 0; - SELECT DATE(date) AS date, - alertLevel, - stateName, - origin, - reference, - clientFk, - name, - `in`, - `out`, - @a := @a + IFNULL(`in`,0) - IFNULL(`out`,0) as balance, - isPicked, - isTicket, - `in` as invalue - FROM - ( SELECT tr.landed as date, - b.quantity as `in`, - NULL as `out`, - IF(tr.isReceived != FALSE,3, IF(tr.isDelivered,1,0)) as alertLevel, - st.name AS stateName, - s.name as name, - e.ref as reference, - e.id as origin, - s.id as clientFk, - TRUE isPicked, - FALSE AS isTicket - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel tr ON tr.id = e.travelFk - JOIN supplier s ON s.id = e.supplierFk - JOIN alertLevel al ON al.id = - CASE - WHEN tr.isReceived != FALSE THEN 3 - WHEN tr.isDelivered THEN 1 - ELSE 0 - END - JOIN state st ON st.code = al.code - WHERE tr.landed >= vDateInventory - AND vWarehouse = tr.warehouseInFk - AND b.itemFk = vItemId - AND e.isInventory = 0 - AND e.isRaid = 0 - UNION ALL - - SELECT tr.shipped as date, - NULL as `in`, - b.quantity as `out`, - IF(tr.isReceived != FALSE,3, IF(tr.isDelivered,1,0)) as alertLevel, - st.name AS stateName, - s.name as name, - e.ref as reference, - e.id as origin, - s.id as clientFk, - TRUE isPicked, - FALSE AS isTicket - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel tr ON tr.id = e.travelFk - JOIN warehouse w ON w.id = tr.warehouseOutFk - JOIN supplier s ON s.id = e.supplierFk - JOIN alertLevel al ON al.id = - CASE - WHEN tr.isReceived != FALSE THEN 3 - WHEN tr.isDelivered THEN 1 - ELSE 0 - END - JOIN state st ON st.code = al.code - WHERE tr.shipped >= vDateInventory - AND vWarehouse =tr.warehouseOutFk - AND s.id <> 4 - AND b.itemFk = vItemId - AND e.isInventory = 0 - AND w.isFeedStock = 0 - AND e.isRaid = 0 - UNION ALL - - SELECT t.shipped as date, - NULL as `in`, - s.quantity as `out`, - al.id as alertLevel, - st.name AS stateName, - t.nickname as name, - t.refFk as reference, - t.id as origin, - t.clientFk, - stk.id as isPicked, -- TRUE as isPicked - TRUE as isTicket - FROM sale s - JOIN ticket t ON t.id = s.ticketFk - LEFT JOIN ticketState ts ON ts.ticket = t.id - LEFT JOIN state st ON st.code = ts.code - JOIN client c ON c.id = t.clientFk - JOIN alertLevel al ON al.id = - CASE - WHEN t.shipped < vCurdate THEN 3 - WHEN t.shipped > vDayEnd THEN 0 - ELSE IFNULL(ts.alertLevel, 0) - END - LEFT JOIN saleTracking stk ON stk.saleFk = s.id AND stk.stateFk = 14 -- comentar - WHERE t.shipped >= vDateInventory - AND s.itemFk = vItemId - AND vWarehouse =t.warehouseFk - ) AS itemDiary - ORDER BY date, isTicket, alertLevel DESC, isPicked DESC, `in` DESC, `out` DESC; +BEGIN + DECLARE vDateInventory DATETIME; + DECLARE vCurdate DATE DEFAULT CURDATE(); + DECLARE vDayEnd DATETIME DEFAULT util.dayEnd(vCurdate); + + SELECT vn.barcodeToItem(vItemId) INTO vItemId; + + -- traduccion: date, alertLevel, origin, reference, name, In, Out, Balance + SELECT inventoried INTO vDateInventory FROM config; + SET @a = 0; + SELECT DATE(date) AS date, + alertLevel, + stateName, + origin, + reference, + clientFk, + name, + `in`, + `out`, + @a := @a + IFNULL(`in`,0) - IFNULL(`out`,0) as balance, + isPicked, + isTicket, + `in` as invalue + FROM + ( SELECT tr.landed as date, + b.quantity as `in`, + NULL as `out`, + IF(tr.isReceived != FALSE,3, IF(tr.isDelivered,1,0)) as alertLevel, + st.name AS stateName, + s.name as name, + e.ref as reference, + e.id as origin, + s.id as clientFk, + TRUE isPicked, + FALSE AS isTicket + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel tr ON tr.id = e.travelFk + JOIN supplier s ON s.id = e.supplierFk + JOIN alertLevel al ON al.id = + CASE + WHEN tr.isReceived != FALSE THEN 3 + WHEN tr.isDelivered THEN 1 + ELSE 0 + END + JOIN state st ON st.code = al.code + WHERE tr.landed >= vDateInventory + AND vWarehouse = tr.warehouseInFk + AND b.itemFk = vItemId + AND e.isInventory = 0 + AND e.isRaid = 0 + UNION ALL + + SELECT tr.shipped as date, + NULL as `in`, + b.quantity as `out`, + IF(tr.isReceived != FALSE,3, IF(tr.isDelivered,1,0)) as alertLevel, + st.name AS stateName, + s.name as name, + e.ref as reference, + e.id as origin, + s.id as clientFk, + TRUE isPicked, + FALSE AS isTicket + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel tr ON tr.id = e.travelFk + JOIN warehouse w ON w.id = tr.warehouseOutFk + JOIN supplier s ON s.id = e.supplierFk + JOIN alertLevel al ON al.id = + CASE + WHEN tr.isReceived != FALSE THEN 3 + WHEN tr.isDelivered THEN 1 + ELSE 0 + END + JOIN state st ON st.code = al.code + WHERE tr.shipped >= vDateInventory + AND vWarehouse =tr.warehouseOutFk + AND s.id <> 4 + AND b.itemFk = vItemId + AND e.isInventory = 0 + AND w.isFeedStock = 0 + AND e.isRaid = 0 + UNION ALL + + SELECT t.shipped as date, + NULL as `in`, + s.quantity as `out`, + al.id as alertLevel, + st.name AS stateName, + t.nickname as name, + t.refFk as reference, + t.id as origin, + t.clientFk, + stk.id as isPicked, -- TRUE as isPicked + TRUE as isTicket + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + LEFT JOIN ticketState ts ON ts.ticket = t.id + LEFT JOIN state st ON st.code = ts.code + JOIN client c ON c.id = t.clientFk + JOIN alertLevel al ON al.id = + CASE + WHEN t.shipped < vCurdate THEN 3 + WHEN t.shipped > vDayEnd THEN 0 + ELSE IFNULL(ts.alertLevel, 0) + END + LEFT JOIN saleTracking stk ON stk.saleFk = s.id AND stk.stateFk = 14 -- comentar + WHERE t.shipped >= vDateInventory + AND s.itemFk = vItemId + AND vWarehouse =t.warehouseFk + ) AS itemDiary + ORDER BY date, isTicket, alertLevel DESC, isPicked DESC, `in` DESC, `out` DESC; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -65172,36 +65893,36 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSaleSupplyAdd`(vItemShelvingFk INT, saleFk INT, vQuantity INT) -BEGIN - -/* - * Añade línea a itemShelvingSale y regulariza el carro - * - * @param vItemShelvingFk Id itemShelving - * @param saleFk Id de sale - * @param vQuantity cantidad a regularizar - * - */ - - INSERT INTO itemShelvingSale( itemShelvingFk, - saleFk, - quantity, - userFk) - VALUES ( vItemShelvingFk, - saleFk, - vQuantity, - getUser()); - - UPDATE itemShelving - SET quantity = quantity - vQuantity, - visible = visible - vQuantity, - available = available - vQuantity +BEGIN + +/* + * Añade línea a itemShelvingSale y regulariza el carro + * + * @param vItemShelvingFk Id itemShelving + * @param saleFk Id de sale + * @param vQuantity cantidad a regularizar + * + */ + + INSERT INTO itemShelvingSale( itemShelvingFk, + saleFk, + quantity, + userFk) + VALUES ( vItemShelvingFk, + saleFk, + vQuantity, + getUser()); + + UPDATE itemShelving + SET quantity = quantity - vQuantity, + visible = visible - vQuantity, + available = available - vQuantity WHERE id = vItemShelvingFk; - + UPDATE vn2008.Movimientos_mark SET valor = 1 - WHERE Id_Movimiento = saleFk; - + WHERE Id_Movimiento = saleFk; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -65368,11 +66089,11 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET character_set_client = 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 = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` 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 @@ -65396,7 +66117,7 @@ BEGIN 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); @@ -65406,7 +66127,7 @@ BEGIN WHERE `code` = vShelvingFk COLLATE utf8_unicode_ci; END IF; - + IF (SELECT COUNT(*) FROM itemShelving WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk AND itemFk = vItemFk @@ -65808,46 +66529,46 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_inventory`(vParkingFromFk INT, vParkingToFk INT) -BEGIN - - /** - * Devuelve un listado de ubicaciones a revisar - * - * @param vParkingFromFk Parking de partida, identificador de vn.parking - * @param vParkingToFk Parking de llegada, identificador de vn.parking - */ - - DECLARE vSectorFk INT; - DECLARE vPickingOrderFrom INT; - DECLARE vPickingOrderTo INT; - - SELECT p.sectorFk, p.pickingOrder INTO vSectorFk, vPickingOrderFrom - FROM vn.parking p - WHERE p.id = vParkingFromFk; - - SELECT p.pickingOrder INTO vPickingOrderTo - FROM vn.parking p - WHERE p.id = vParkingToFk; - - CALL vn.visible_getMisfit(vSectorFk); - - SELECT p.code parking , - ish.shelvingFk , - ish.itemFk, - i.longName, - ish.visible , - ish.visible / ish.packing packs, - ish.packing, - sm.visible - sm.parked faltan - FROM vn.itemShelving ish - JOIN vn.item i ON i.id = ish.itemFk - JOIN tmp.stockMisfit sm ON sm.itemFk = ish.itemFk - JOIN vn.shelving sh ON sh.code = ish.shelvingFk - JOIN vn.parking p ON p.id = sh.parkingFk - WHERE p.pickingOrder BETWEEN vPickingOrderFrom AND vPickingOrderTo - AND p.sectorFk = vSectorFk - ORDER BY p.pickingOrder ; - +BEGIN + + /** + * Devuelve un listado de ubicaciones a revisar + * + * @param vParkingFromFk Parking de partida, identificador de vn.parking + * @param vParkingToFk Parking de llegada, identificador de vn.parking + */ + + DECLARE vSectorFk INT; + DECLARE vPickingOrderFrom INT; + DECLARE vPickingOrderTo INT; + + SELECT p.sectorFk, p.pickingOrder INTO vSectorFk, vPickingOrderFrom + FROM vn.parking p + WHERE p.id = vParkingFromFk; + + SELECT p.pickingOrder INTO vPickingOrderTo + FROM vn.parking p + WHERE p.id = vParkingToFk; + + CALL vn.visible_getMisfit(vSectorFk); + + SELECT p.code parking , + ish.shelvingFk , + ish.itemFk, + i.longName, + ish.visible , + ish.visible / ish.packing packs, + ish.packing, + sm.visible - sm.parked faltan + FROM vn.itemShelving ish + JOIN vn.item i ON i.id = ish.itemFk + JOIN tmp.stockMisfit sm ON sm.itemFk = ish.itemFk + JOIN vn.shelving sh ON sh.code = ish.shelvingFk + JOIN vn.parking p ON p.id = sh.parkingFk + WHERE p.pickingOrder BETWEEN vPickingOrderFrom AND vPickingOrderTo + AND p.sectorFk = vSectorFk + ORDER BY p.pickingOrder ; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -65989,74 +66710,74 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `itemStockUpdate`( - vItemFk INT, - vWarehouseFk INT, - vNewVisible INT, +CREATE DEFINER=`root`@`localhost` PROCEDURE `itemStockUpdate`( + vItemFk INT, + vWarehouseFk INT, + vNewVisible INT, vIsTrash BOOLEAN) -BEGIN - - DECLARE vTicketFk INT; - DECLARE vClientFk INT; - DECLARE vCompanyVnlFk INT DEFAULT 442; - DECLARE vVisible INT DEFAULT 0; - DECLARE vCalc INT; - DECLARE vParkedStuff INT; - - SELECT barcodeToItem(vItemFk) INTO vItemFk; - - CALL cache.visible_refresh(vCalc, TRUE, vWarehouseFk); - - SELECT IFNULL(visible,0) INTO vVisible - FROM cache.visible - WHERE calc_id = vCalc - AND item_id = vItemFk; - - SELECT sum(visible) INTO vParkedStuff - FROM itemShelvingStock - WHERE warehouseFk = vWarehouseFk - AND itemFk = vItemFk; - - SET vNewVisible = vNewVisible + IFNULL(vParkedStuff,0); - - SELECT IF(vIsTrash, 200, 400) INTO vClientFk; - - SELECT t.id INTO vTicketFk - FROM ticket t - JOIN address a ON a.id=t.addressFk - WHERE t.warehouseFk = vWarehouseFk - AND t.clientFk = vClientFk - AND DATE(t.shipped) = CURDATE() - AND a.isDefaultAddress - LIMIT 1; - - IF vTicketFk IS NULL THEN - - CALL ticket_add( - vClientFk, - CURDATE(), - vWarehouseFk, - vCompanyVnlFk, - NULL, - NULL, - NULL, - CURDATE(), - account.userGetId(), - FALSE, - vTicketFk); - - END IF; - - INSERT INTO sale(ticketFk, itemFk, concept, quantity, price, discount) - SELECT vTicketFk, vItemFk, CONCAT(longName,' ', getWorkerCode(), ' ',LEFT(CAST(NOW() AS TIME),5)), vVisible - vNewVisible, 0, 0 - FROM item - WHERE id = vItemFk; - - UPDATE cache.visible - SET visible = vNewVisible - WHERE calc_id = vCalc - AND item_id = vItemFk; - +BEGIN + + DECLARE vTicketFk INT; + DECLARE vClientFk INT; + DECLARE vCompanyVnlFk INT DEFAULT 442; + DECLARE vVisible INT DEFAULT 0; + DECLARE vCalc INT; + DECLARE vParkedStuff INT; + + SELECT barcodeToItem(vItemFk) INTO vItemFk; + + CALL cache.visible_refresh(vCalc, TRUE, vWarehouseFk); + + SELECT IFNULL(visible,0) INTO vVisible + FROM cache.visible + WHERE calc_id = vCalc + AND item_id = vItemFk; + + SELECT sum(visible) INTO vParkedStuff + FROM itemShelvingStock + WHERE warehouseFk = vWarehouseFk + AND itemFk = vItemFk; + + SET vNewVisible = vNewVisible + IFNULL(vParkedStuff,0); + + SELECT IF(vIsTrash, 200, 400) INTO vClientFk; + + SELECT t.id INTO vTicketFk + FROM ticket t + JOIN address a ON a.id=t.addressFk + WHERE t.warehouseFk = vWarehouseFk + AND t.clientFk = vClientFk + AND DATE(t.shipped) = CURDATE() + AND a.isDefaultAddress + LIMIT 1; + + IF vTicketFk IS NULL THEN + + CALL ticket_add( + vClientFk, + CURDATE(), + vWarehouseFk, + vCompanyVnlFk, + NULL, + NULL, + NULL, + CURDATE(), + account.userGetId(), + FALSE, + vTicketFk); + + END IF; + + INSERT INTO sale(ticketFk, itemFk, concept, quantity, price, discount) + SELECT vTicketFk, vItemFk, CONCAT(longName,' ', getWorkerCode(), ' ',LEFT(CAST(NOW() AS TIME),5)), vVisible - vNewVisible, 0, 0 + FROM item + WHERE id = vItemFk; + + UPDATE cache.visible + SET visible = vNewVisible + WHERE calc_id = vCalc + AND item_id = vItemFk; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -66168,11 +66889,11 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET character_set_client = 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 = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemTagReorder`(itemTypeFk INT) BEGIN @@ -66197,7 +66918,7 @@ BEGIN SET @isTriggerDisabled = FALSE; - DROP TABLE tmp.item; + -- DROP TABLE tmp.item; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -66391,37 +67112,37 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemTag_replace`(vItemFromFk INT, vItemToFk INT, vPicture VARCHAR(100)) -BEGIN - - /* Reemplaza los tags de un artículo por los de otro, así como su imagen - * - * @param vItemFromFk id de vn.item con el artículo del que se toman los tags - * @param vItemToFk id de vn.item con el artículo del que se toman los tags - * @param vPicture imagen del artículo. Opcional. Si no se especifica, hereada la del vItemFromFk - */ - - DELETE FROM vn.itemTag - WHERE itemFk = vItemToFk; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT vItemToFk, tagFk, value, priority - FROM vn.itemTag - WHERE itemFk = vItemFromFk; - - IF ISNULL(vPicture) THEN - - SELECT image INTO vPicture - FROM vn.item - WHERE id = vItemFromFk; - - END IF; - - UPDATE vn.item i - SET i.image = vPicture - WHERE i.id = vItemToFk; - - CALL vn.itemRefreshTags(vItemToFk); - +BEGIN + + /* Reemplaza los tags de un artículo por los de otro, así como su imagen + * + * @param vItemFromFk id de vn.item con el artículo del que se toman los tags + * @param vItemToFk id de vn.item con el artículo del que se toman los tags + * @param vPicture imagen del artículo. Opcional. Si no se especifica, hereada la del vItemFromFk + */ + + DELETE FROM vn.itemTag + WHERE itemFk = vItemToFk; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT vItemToFk, tagFk, value, priority + FROM vn.itemTag + WHERE itemFk = vItemFromFk; + + IF ISNULL(vPicture) THEN + + SELECT image INTO vPicture + FROM vn.item + WHERE id = vItemFromFk; + + END IF; + + UPDATE vn.item i + SET i.image = vPicture + WHERE i.id = vItemToFk; + + CALL vn.itemRefreshTags(vItemToFk); + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -66514,62 +67235,62 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `itemTrash`( - vItemFk INT, - vWarehouseFk INT, - vQuantity INT, +CREATE DEFINER=`root`@`localhost` PROCEDURE `itemTrash`( + vItemFk INT, + vWarehouseFk INT, + vQuantity INT, vIsTrash BOOLEAN) -BEGIN - - DECLARE vTicketFk INT; - DECLARE vClientFk INT; - DECLARE vCompanyVnlFk INT DEFAULT 442; - DECLARE vCalc INT; - - SELECT barcodeToItem(vItemFk) INTO vItemFk; - - SELECT IF(vIsTrash, 200, 400) INTO vClientFk; - - SELECT t.id INTO vTicketFk - FROM ticket t - JOIN address a ON a.id=t.addressFk - WHERE t.warehouseFk = vWarehouseFk - AND t.clientFk = vClientFk - AND DATE(t.shipped) = CURDATE() - AND a.isDefaultAddress - LIMIT 1; - - CALL cache.visible_refresh(vCalc, TRUE, vWarehouseFk); - - IF vTicketFk IS NULL THEN - - CALL ticket_add( - vClientFk, - CURDATE(), - vWarehouseFk, - vCompanyVnlFk, - NULL, - NULL, - NULL, - CURDATE(), - account.userGetId(), - FALSE, - vTicketFk); - END IF; - - INSERT INTO sale(ticketFk, itemFk, concept, quantity) - SELECT vTicketFk, - vItemFk, - CONCAT(longName,' ',getWorkerCode(), ' ', LEFT(CAST(NOW() AS TIME),5)), - vQuantity - FROM item - WHERE id = vItemFk; - - UPDATE cache.visible - SET visible = visible - vQuantity - WHERE calc_id = vCalc - AND item_id = vItemFk; - +BEGIN + + DECLARE vTicketFk INT; + DECLARE vClientFk INT; + DECLARE vCompanyVnlFk INT DEFAULT 442; + DECLARE vCalc INT; + + SELECT barcodeToItem(vItemFk) INTO vItemFk; + + SELECT IF(vIsTrash, 200, 400) INTO vClientFk; + + SELECT t.id INTO vTicketFk + FROM ticket t + JOIN address a ON a.id=t.addressFk + WHERE t.warehouseFk = vWarehouseFk + AND t.clientFk = vClientFk + AND DATE(t.shipped) = CURDATE() + AND a.isDefaultAddress + LIMIT 1; + + CALL cache.visible_refresh(vCalc, TRUE, vWarehouseFk); + + IF vTicketFk IS NULL THEN + + CALL ticket_add( + vClientFk, + CURDATE(), + vWarehouseFk, + vCompanyVnlFk, + NULL, + NULL, + NULL, + CURDATE(), + account.userGetId(), + FALSE, + vTicketFk); + END IF; + + INSERT INTO sale(ticketFk, itemFk, concept, quantity) + SELECT vTicketFk, + vItemFk, + CONCAT(longName,' ',getWorkerCode(), ' ', LEFT(CAST(NOW() AS TIME),5)), + vQuantity + FROM item + WHERE id = vItemFk; + + UPDATE cache.visible + SET visible = visible - vQuantity + WHERE calc_id = vCalc + AND item_id = vItemFk; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -66641,126 +67362,126 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `item_clean`(vItemFrom INT, vItemTo INT) -BEGIN - -/* - * Elimina todos los items repetidos y los sustituye por el que tiene menor id - */ - - START TRANSACTION; - - SET @isModeInventory:= TRUE; - - -- Deletes - - UPDATE IGNORE vn.itemCost ic - JOIN tmp.itemsToReplace itr ON ic.itemFk = itr.idOld - SET ic.itemFk = itr.idNew; - - DELETE ic.* - FROM vn.itemCost ic - JOIN tmp.itemsToReplace itr ON ic.itemFk = itr.idOld; - - DELETE rt.* - FROM vn2008.rec_translator rt - JOIN tmp.itemsToReplace itr ON rt.Id_Article = itr.idOld; - - DELETE w.* - FROM bs.waste w - JOIN tmp.itemsToReplace itr ON w.itemFk = itr.idOld; - - DELETE pf.* - FROM vn.priceFixed pf - JOIN tmp.itemsToReplace itr ON pf.itemFk = itr.idOld; - - DELETE imp.* - FROM vn.itemMatchProperties imp - JOIN tmp.itemsToReplace itr ON imp.itemFk = itr.idOld; - - DELETE ib.* - FROM vn.itemBotanical ib - JOIN tmp.itemsToReplace itr ON ib.itemFk = itr.idOld; - - DELETE ip.* - FROM vn.itemProposal ip - JOIN tmp.itemsToReplace itr ON ip.itemFk = itr.idOld; - - DELETE it.* - FROM vn.itemTag it - JOIN tmp.itemsToReplace itr ON it.itemFk = itr.idOld; - - DELETE ib.* - FROM vn.itemBarcode ib - JOIN tmp.itemsToReplace itr ON ib.itemFk = itr.idOld; - - DELETE itc.* - FROM vn.itemTaxCountry itc - JOIN tmp.itemsToReplace itr ON itc.itemFk = itr.idOld; - - DELETE ip.* - FROM vn.itemPlacement ip - JOIN tmp.itemsToReplace itr ON ip.itemFk = itr.idOld; - - -- Updates - - UPDATE vn.buy b - JOIN tmp.itemsToReplace itr ON b.itemFk = itr.idOld - SET b.itemFk = itr.idNew; - - UPDATE vn.sale s - JOIN tmp.itemsToReplace itr ON s.itemFk = itr.idOld - SET s.itemFk = itr.idNew; - - UPDATE vn.specialPrice sp - JOIN tmp.itemsToReplace itr ON sp.itemFk = itr.idOld - SET sp.itemFk = itr.idNew; - - UPDATE vn.packaging p - JOIN tmp.itemsToReplace itr ON p.itemFk = itr.idOld - SET p.itemFk = itr.idNew; - - UPDATE vn.packaging p - JOIN tmp.itemsToReplace itr ON p.freightItemFk = itr.idOld - SET p.freightItemFk = itr.idNew; - - UPDATE hedera.orderRow o - JOIN tmp.itemsToReplace itr ON o.itemFk = itr.idOld - SET o.itemFk = itr.idNew; - - UPDATE vn.itemLog il - JOIN tmp.itemsToReplace itr ON il.originFk = itr.idOld - SET il.originFk = itr.idNew; - - UPDATE vn.itemShelving ish - JOIN tmp.itemsToReplace itr ON ish.itemFk = itr.idOld - SET ish.itemFk = itr.idNew; - - UPDATE vn.ticketPackagingStartingStock tpss - JOIN tmp.itemsToReplace itr ON tpss.itemFk = itr.idOld - SET tpss.itemFk = itr.idNew; - - UPDATE vn.inventoryFailure ifa - JOIN tmp.itemsToReplace itr ON ifa.itemFk = itr.idOld - SET ifa.itemFk = itr.idNew; - - UPDATE vn.genericAllocation ga - JOIN tmp.itemsToReplace itr ON ga.itemFk = itr.idOld - SET ga.itemFk = itr.idNew; - - UPDATE vn.itemPlacementSupply ips - JOIN tmp.itemsToReplace itr ON ips.itemFk = itr.idOld - SET ips.itemFk = itr.idNew; - - -- Eliminamos los items repetidos - - DELETE i.* - FROM vn.item i - JOIN tmp.itemsToReplace itr ON i.id = itr.idOld; - - SET @isModeInventory:= FALSE; - - COMMIT; - +BEGIN + +/* + * Elimina todos los items repetidos y los sustituye por el que tiene menor id + */ + + START TRANSACTION; + + SET @isModeInventory:= TRUE; + + -- Deletes + + UPDATE IGNORE vn.itemCost ic + JOIN tmp.itemsToReplace itr ON ic.itemFk = itr.idOld + SET ic.itemFk = itr.idNew; + + DELETE ic.* + FROM vn.itemCost ic + JOIN tmp.itemsToReplace itr ON ic.itemFk = itr.idOld; + + DELETE rt.* + FROM vn2008.rec_translator rt + JOIN tmp.itemsToReplace itr ON rt.Id_Article = itr.idOld; + + DELETE w.* + FROM bs.waste w + JOIN tmp.itemsToReplace itr ON w.itemFk = itr.idOld; + + DELETE pf.* + FROM vn.priceFixed pf + JOIN tmp.itemsToReplace itr ON pf.itemFk = itr.idOld; + + DELETE imp.* + FROM vn.itemMatchProperties imp + JOIN tmp.itemsToReplace itr ON imp.itemFk = itr.idOld; + + DELETE ib.* + FROM vn.itemBotanical ib + JOIN tmp.itemsToReplace itr ON ib.itemFk = itr.idOld; + + DELETE ip.* + FROM vn.itemProposal ip + JOIN tmp.itemsToReplace itr ON ip.itemFk = itr.idOld; + + DELETE it.* + FROM vn.itemTag it + JOIN tmp.itemsToReplace itr ON it.itemFk = itr.idOld; + + DELETE ib.* + FROM vn.itemBarcode ib + JOIN tmp.itemsToReplace itr ON ib.itemFk = itr.idOld; + + DELETE itc.* + FROM vn.itemTaxCountry itc + JOIN tmp.itemsToReplace itr ON itc.itemFk = itr.idOld; + + DELETE ip.* + FROM vn.itemPlacement ip + JOIN tmp.itemsToReplace itr ON ip.itemFk = itr.idOld; + + -- Updates + + UPDATE vn.buy b + JOIN tmp.itemsToReplace itr ON b.itemFk = itr.idOld + SET b.itemFk = itr.idNew; + + UPDATE vn.sale s + JOIN tmp.itemsToReplace itr ON s.itemFk = itr.idOld + SET s.itemFk = itr.idNew; + + UPDATE vn.specialPrice sp + JOIN tmp.itemsToReplace itr ON sp.itemFk = itr.idOld + SET sp.itemFk = itr.idNew; + + UPDATE vn.packaging p + JOIN tmp.itemsToReplace itr ON p.itemFk = itr.idOld + SET p.itemFk = itr.idNew; + + UPDATE vn.packaging p + JOIN tmp.itemsToReplace itr ON p.freightItemFk = itr.idOld + SET p.freightItemFk = itr.idNew; + + UPDATE hedera.orderRow o + JOIN tmp.itemsToReplace itr ON o.itemFk = itr.idOld + SET o.itemFk = itr.idNew; + + UPDATE vn.itemLog il + JOIN tmp.itemsToReplace itr ON il.originFk = itr.idOld + SET il.originFk = itr.idNew; + + UPDATE vn.itemShelving ish + JOIN tmp.itemsToReplace itr ON ish.itemFk = itr.idOld + SET ish.itemFk = itr.idNew; + + UPDATE vn.ticketPackagingStartingStock tpss + JOIN tmp.itemsToReplace itr ON tpss.itemFk = itr.idOld + SET tpss.itemFk = itr.idNew; + + UPDATE vn.inventoryFailure ifa + JOIN tmp.itemsToReplace itr ON ifa.itemFk = itr.idOld + SET ifa.itemFk = itr.idNew; + + UPDATE vn.genericAllocation ga + JOIN tmp.itemsToReplace itr ON ga.itemFk = itr.idOld + SET ga.itemFk = itr.idNew; + + UPDATE vn.itemPlacementSupply ips + JOIN tmp.itemsToReplace itr ON ips.itemFk = itr.idOld + SET ips.itemFk = itr.idNew; + + -- Eliminamos los items repetidos + + DELETE i.* + FROM vn.item i + JOIN tmp.itemsToReplace itr ON i.id = itr.idOld; + + SET @isModeInventory:= FALSE; + + COMMIT; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -66781,7 +67502,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `item_cleanLauncher`() BEGIN DECLARE vItemTo INT DEFAULT 0; - DECLARE vStep INT DEFAULT 20; + DECLARE vStep INT DEFAULT 500; DECLARE vCounter INT DEFAULT 0; DECLARE vItemFrom INT; DECLARE vItemEnd INT; @@ -66791,7 +67512,7 @@ BEGIN ORDER BY created DESC LIMIT 1; - SET vItemEnd = vItemFrom + 500; + SET vItemEnd = vItemFrom + 100000; DROP TEMPORARY TABLE IF EXISTS tmp.itemsToReplaceSource; CREATE TEMPORARY TABLE tmp.itemsToReplaceSource @@ -67044,71 +67765,71 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getInfo`(IN `vBarcode` VARCHAR(22), IN `vWarehouseFk` INT) -BEGIN - - /* - * Devuelve información relativa al item correspondiente del vBarcode pasado - * - * @param vBarcode código relativo al ítem - * @param vWarehouseFk código del almacén - */ - - DECLARE vCacheVisibleFk INT; - DECLARE vCacheAvailableFk INT; - DECLARE vVisibleItemShelving INT; - DECLARE vItemFk INT; - - SELECT vn.barcodeToItem(vBarcode) INTO vItemFk; - - CALL cache.visible_refresh(vCacheVisibleFk, FALSE,vWarehouseFk); - CALL cache.available_refresh(vCacheAvailableFk, FALSE,vWarehouseFk, CURDATE()); - - SELECT SUM(visible) INTO vVisibleItemShelving - 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, - p.name as producer, - o.code as origin, - v.visible - IFNULL(vVisibleItemShelving,0) as unlocated, - a.available, - vVisibleItemShelving, - v.visible, - c.`grouping`, - c.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, - i.comment as reference - 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 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; - +BEGIN + + /* + * Devuelve información relativa al item correspondiente del vBarcode pasado + * + * @param vBarcode código relativo al ítem + * @param vWarehouseFk código del almacén + */ + + DECLARE vCacheVisibleFk INT; + DECLARE vCacheAvailableFk INT; + DECLARE vVisibleItemShelving INT; + DECLARE vItemFk INT; + + SELECT vn.barcodeToItem(vBarcode) INTO vItemFk; + + CALL cache.visible_refresh(vCacheVisibleFk, FALSE,vWarehouseFk); + CALL cache.available_refresh(vCacheAvailableFk, FALSE,vWarehouseFk, CURDATE()); + + SELECT SUM(visible) INTO vVisibleItemShelving + 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, + p.name as producer, + o.code as origin, + v.visible - IFNULL(vVisibleItemShelving,0) as unlocated, + a.available, + vVisibleItemShelving, + v.visible, + c.`grouping`, + c.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, + i.comment as reference + 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 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 */ ; @@ -67973,21 +68694,21 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `item_saveReference`(vBarcode VARCHAR(22), vReference VARCHAR(150)) -BEGIN - -/** - * Actualiza la referencia del item - * - * @param vBarcode del item - * @param vReference referencia a actualizar - */ - - DECLARE vItemFk INT; - - SELECT barcodeToItem(vBarcode) INTO vItemFk; - - UPDATE item SET comment = vReference WHERE id = vItemFk; - +BEGIN + +/** + * Actualiza la referencia del item + * + * @param vBarcode del item + * @param vReference referencia a actualizar + */ + + DECLARE vItemFk INT; + + SELECT barcodeToItem(vBarcode) INTO vItemFk; + + UPDATE item SET comment = vReference WHERE id = vItemFk; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -68069,33 +68790,33 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `item_setGeneric`(vSelf INT) -BEGIN - - /* Asigna el código genérico a un item - * - * @param vSelf identificador de vn.item - */ - - DECLARE vGenericFk INT; - - SELECT ga.itemFk INTO vGenericFk - FROM vn.genericAllocation ga - JOIN vn.item i ON (i.typeFk = ga.typeFk OR ISNULL(ga.typeFk)) - JOIN vn.itemTag it1 ON it1.itemFk = i.id AND (it1.value = ga.origin OR ISNULL(ga.origin)) - JOIN vn.itemTag it2 ON it2.itemFk = i.id AND (it2.value = ga.color OR ISNULL(ga.color)) - JOIN vn.itemTag it3 ON it3.itemFk = i.id AND (it3.value = ga.quality OR ISNULL(ga.quality)) - JOIN vn.itemTag it4 ON it4.itemFk = i.id AND (it4.value = ga.numFlores OR ISNULL(ga.numFlores)) - JOIN vn.itemTag it5 ON it5.itemFk = i.id AND (it5.value = ga.category OR ISNULL(ga.category)) - JOIN vn.itemTag it6 ON it6.itemFk = i.id AND (it6.value = ga.productor OR ISNULL(ga.productor)) - WHERE i.id = vSelf - AND ga.itemFk != vSelf - AND NOT i.isFloramondo - LIMIT 1; - - UPDATE vn.item - SET genericFk = vGenericFk - WHERE id = vSelf; - +BEGIN + + /* Asigna el código genérico a un item + * + * @param vSelf identificador de vn.item + */ + + DECLARE vGenericFk INT; + + SELECT ga.itemFk INTO vGenericFk + FROM vn.genericAllocation ga + JOIN vn.item i ON (i.typeFk = ga.typeFk OR ISNULL(ga.typeFk)) + JOIN vn.itemTag it1 ON it1.itemFk = i.id AND (it1.value = ga.origin OR ISNULL(ga.origin)) + JOIN vn.itemTag it2 ON it2.itemFk = i.id AND (it2.value = ga.color OR ISNULL(ga.color)) + JOIN vn.itemTag it3 ON it3.itemFk = i.id AND (it3.value = ga.quality OR ISNULL(ga.quality)) + JOIN vn.itemTag it4 ON it4.itemFk = i.id AND (it4.value = ga.numFlores OR ISNULL(ga.numFlores)) + JOIN vn.itemTag it5 ON it5.itemFk = i.id AND (it5.value = ga.category OR ISNULL(ga.category)) + JOIN vn.itemTag it6 ON it6.itemFk = i.id AND (it6.value = ga.productor OR ISNULL(ga.productor)) + WHERE i.id = vSelf + AND ga.itemFk != vSelf + AND NOT i.isFloramondo + LIMIT 1; + + UPDATE vn.item + SET genericFk = vGenericFk + WHERE id = vSelf; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -68113,19 +68834,19 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `item_updatePackingShelve`(vSelf INT, vPacking INT) -BEGIN - +BEGIN + /** - * Actualiza el valor de item.packingShelve - * - * @param vSelf Identificador de vn.item - * @param vPacking Cantidad de unidades de venta que caben en una bandeja - */ - - UPDATE vn.item i - SET i.packingShelve = vPacking - WHERE i.id = vSelf; - + * Actualiza el valor de item.packingShelve + * + * @param vSelf Identificador de vn.item + * @param vPacking Cantidad de unidades de venta que caben en una bandeja + */ + + UPDATE vn.item i + SET i.packingShelve = vPacking + WHERE i.id = vSelf; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -68143,15 +68864,15 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `item_updatePackingType`(vItem INT, vItemPackingTypeFk VARCHAR(1)) -BEGIN -/** - * Update the packing type of an item - * - * @param vItem id del item a actualizar - * @param vItemPackingTypeFk packing type - */ - UPDATE item SET itemPackingTypeFk = vItemPackingTypeFk WHERE id = vItem; - +BEGIN +/** + * Update the packing type of an item + * + * @param vItem id del item a actualizar + * @param vItemPackingTypeFk packing type + */ + UPDATE item SET itemPackingTypeFk = vItemPackingTypeFk WHERE id = vItem; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -68968,22 +69689,22 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `machine_getWorkerPlate`(vWorkerFk INT) -BEGIN -/** - * Selecciona la matrícula del vehículo del workerfk - * - * @param vWorkerFk el id del trabajador - * - * - **/ - - SELECT m.plate - FROM machine m - JOIN machineWorker mw ON mw.machineFk = m.id - WHERE mw.inTimed >= TIMESTAMPADD(HOUR , -12,NOW()) - AND ISNULL(mw.outTimed) - AND mw.workerFk = vWorkerFk; - +BEGIN +/** + * Selecciona la matrícula del vehículo del workerfk + * + * @param vWorkerFk el id del trabajador + * + * + **/ + + SELECT m.plate + FROM machine m + JOIN machineWorker mw ON mw.machineFk = m.id + WHERE mw.inTimed >= TIMESTAMPADD(HOUR , -12,NOW()) + AND ISNULL(mw.outTimed) + AND mw.workerFk = vWorkerFk; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -68996,9 +69717,9 @@ DELIMITER ; /*!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 collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `mail_insert`( vReceiver VARCHAR(255), @@ -69022,7 +69743,8 @@ BEGIN WHERE creationDate >= CURDATE() AND `receiver` = vReceiver AND `replyTo` = vReplyTo - AND `subject` = vSubject; + AND `subject` = vSubject + AND !sent; IF NOT vIsRepeated THEN @@ -70303,29 +71025,29 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `parking_setOrder`(vWarehouseFk INT) -BEGIN - - /* - * Ordena el orden de preparacion de los parking de acuerdo con la tabla vn.corridor - */ - - UPDATE vn.parking p - JOIN ( - SELECT code, - @orden := @orden + 10 AS po - FROM ( - SELECT c.prepOrder, - p.code, - @orden := 0, - IF(c.isAscendent, 1,-1) * CAST(SUBSTRING(p.code,3,2) AS DECIMAL(2,0)) subCorridor , - CAST(IF(LENGTH(p.code) > 5, SUBSTRING(p.code,6,2), 0) AS DECIMAL(2,0)) ubication - FROM vn.parking p - JOIN vn.sector s ON s.id = p.sectorFk - JOIN vn.corridor c ON c.code = LEFT(p.code,1) COLLATE utf8_general_ci - WHERE s.warehouseFk = vWarehouseFk) sub - ORDER BY sub.prepOrder, subCorridor, ubication) sub2 ON sub2.code = p.code - SET p.pickingOrder = sub2.po; - +BEGIN + + /* + * Ordena el orden de preparacion de los parking de acuerdo con la tabla vn.corridor + */ + + UPDATE vn.parking p + JOIN ( + SELECT code, + @orden := @orden + 10 AS po + FROM ( + SELECT c.prepOrder, + p.code, + @orden := 0, + IF(c.isAscendent, 1,-1) * CAST(SUBSTRING(p.code,3,2) AS DECIMAL(2,0)) subCorridor , + CAST(IF(LENGTH(p.code) > 5, SUBSTRING(p.code,6,2), 0) AS DECIMAL(2,0)) ubication + FROM vn.parking p + JOIN vn.sector s ON s.id = p.sectorFk + JOIN vn.corridor c ON c.code = LEFT(p.code,1) COLLATE utf8_general_ci + WHERE s.warehouseFk = vWarehouseFk) sub + ORDER BY sub.prepOrder, subCorridor, ubication) sub2 ON sub2.code = p.code + SET p.pickingOrder = sub2.po; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -70418,180 +71140,180 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `placement_test`(vParamFk INT(11)) -BEGIN - - DECLARE vCalcFk INT; - DECLARE vWarehouseFk INT; - DECLARE vWarehouseAliasFk INT; - DECLARE vCurrentYear INT DEFAULT YEAR(NOW()); - - DROP TEMPORARY TABLE IF EXISTS tmp.sale; - CREATE TEMPORARY TABLE tmp.sale - ENGINE = MEMORY - SELECT 0000000 as ticketFk, - 0000000 as saleFk, - 0000000 as itemFk, - FALSE as isStowaway, - 0 as quantity; - - INSERT INTO tmp.sale(ticketFk, saleFk, itemFk, isStowaway) - SELECT s.ticketFk, s.id, s.itemFk, FALSE - FROM vn.ticketCollection tc - JOIN vn.collection c ON c.id = tc.collectionFk - JOIN vn.sale s ON s.ticketFk = tc.ticketFk - JOIN vn.item i ON i.id = s.itemFk - WHERE tc.collectionFk = vParamFk - AND (i.itemPackingTypeFk = c.itemPackingTypeFk OR ISNULL(c.itemPackingTypeFk)) - UNION ALL - SELECT s.ticketFk, s.id, s.itemFk, FALSE - 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 - JOIN tmp.sale ts ON ts.ticketFk = t.id - JOIN vn.warehouse w ON w.id = t.warehouseFk - LIMIT 1; - - CALL cache.visible_refresh(vCalcFk,FALSE,vWarehouseFk); - - UPDATE tmp.sale ts - JOIN ( SELECT itemFk, sum(visible) as visible - FROM vn.itemShelvingStock iss - JOIN vn.warehouse w ON w.id = iss.warehouseFk - WHERE w.aliasFk = vWarehouseAliasFk - GROUP BY iss.itemFk ) iss ON iss.itemFk = ts.itemFk - SET ts.quantity = iss.visible; - - DROP TEMPORARY TABLE IF EXISTS tmp.sale2; - CREATE TEMPORARY TABLE tmp.sale2 - ENGINE = MEMORY - SELECT * FROM tmp.sale; - - - DROP TEMPORARY TABLE IF EXISTS tmp.`grouping`; - CREATE TEMPORARY TABLE tmp.`grouping` - (PRIMARY KEY (itemFk)) - ENGINE = MEMORY - SELECT b.itemFk, - CASE b.groupingMode - WHEN 0 THEN 1 - WHEN 2 THEN b.packing - ELSE b.`grouping` - END AS `grouping` - FROM buy b - JOIN cache.last_buy lb ON lb.buy_id = b.id - WHERE lb.warehouse_id = vWarehouseFk - ; - - DROP TEMPORARY TABLE IF EXISTS tmp.grouping2; - CREATE TEMPORARY TABLE tmp.grouping2 - ENGINE = MEMORY - SELECT * FROM tmp.`grouping`; - - DROP TEMPORARY TABLE IF EXISTS tmp.salePlacementList; - CREATE TEMPORARY TABLE tmp.salePlacementList - ENGINE = MEMORY - - SELECT ts.saleFk, - ts.itemFk, - CONCAT( - IF( iss.id, - CONCAT('< ', IFNULL(wk.`code`, '---'),' > '), - ''), - p.`code`) COLLATE utf8_general_ci as placement , - 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, - sc.isPreviousPrepared, - iss.id as itemShelvingSaleFk, - ts.ticketFk - ,iss.id - , st.saleFk as salePreviousPrepared - , iss.userFk - FROM tmp.sale ts - LEFT JOIN (SELECT DISTINCT saleFk - FROM vn.saleTracking st - JOIN vn.state s ON s.id = st.stateFk - WHERE st.isChecked - AND s.semaphore = 1) st ON st.saleFk = ts.saleFk - JOIN vn.itemShelving ish ON ish.itemFk = ts.itemFk - JOIN vn.shelving sh ON sh.code = ish.shelvingFk - JOIN vn.parking p ON p.id = sh.parkingFk - JOIN vn.sector sc ON sc.id = p.sectorFk - JOIN vn.warehouse w ON w.id = sc.warehouseFk - LEFT JOIN tmp.`grouping` g ON g.itemFk = ts.itemFk - 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 - ; - - DROP TEMPORARY TABLE IF EXISTS tmp.salePlacementList_2; - CREATE TEMPORARY TABLE tmp.salePlacementList_2 - ENGINE MEMORY - 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 - ) sub - GROUP BY saleFk; - - DROP TEMPORARY TABLE IF EXISTS tmp.salePlacementList_3; - CREATE TEMPORARY TABLE tmp.salePlacementList_3 - ENGINE MEMORY - SELECT s1.saleFk, `order`as saleOrder - FROM tmp.salePlacementList s1 - JOIN tmp.salePlacementList_2 s2 ON s2.saleFk = s1.saleFk AND s2.olderPriority = s1.priority; - - UPDATE tmp.salePlacementList s1 - 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 */ - UPDATE tmp.salePlacementList - SET saleOrder = `order`; - - SELECT * - FROM tmp.salePlacementList - ORDER BY visible <> 0 DESC,saleOrder, IF(isPreviousPrepared,2,1), IF(itemShelvingSaleFk,1,2),priority; - - DROP TEMPORARY TABLE - tmp.sale, - tmp.sale2, - tmp.`grouping`, - tmp.grouping2, - tmp.salePlacementList_2, - tmp.salePlacementList_3; - +BEGIN + + DECLARE vCalcFk INT; + DECLARE vWarehouseFk INT; + DECLARE vWarehouseAliasFk INT; + DECLARE vCurrentYear INT DEFAULT YEAR(NOW()); + + DROP TEMPORARY TABLE IF EXISTS tmp.sale; + CREATE TEMPORARY TABLE tmp.sale + ENGINE = MEMORY + SELECT 0000000 as ticketFk, + 0000000 as saleFk, + 0000000 as itemFk, + FALSE as isStowaway, + 0 as quantity; + + INSERT INTO tmp.sale(ticketFk, saleFk, itemFk, isStowaway) + SELECT s.ticketFk, s.id, s.itemFk, FALSE + FROM vn.ticketCollection tc + JOIN vn.collection c ON c.id = tc.collectionFk + JOIN vn.sale s ON s.ticketFk = tc.ticketFk + JOIN vn.item i ON i.id = s.itemFk + WHERE tc.collectionFk = vParamFk + AND (i.itemPackingTypeFk = c.itemPackingTypeFk OR ISNULL(c.itemPackingTypeFk)) + UNION ALL + SELECT s.ticketFk, s.id, s.itemFk, FALSE + 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 + JOIN tmp.sale ts ON ts.ticketFk = t.id + JOIN vn.warehouse w ON w.id = t.warehouseFk + LIMIT 1; + + CALL cache.visible_refresh(vCalcFk,FALSE,vWarehouseFk); + + UPDATE tmp.sale ts + JOIN ( SELECT itemFk, sum(visible) as visible + FROM vn.itemShelvingStock iss + JOIN vn.warehouse w ON w.id = iss.warehouseFk + WHERE w.aliasFk = vWarehouseAliasFk + GROUP BY iss.itemFk ) iss ON iss.itemFk = ts.itemFk + SET ts.quantity = iss.visible; + + DROP TEMPORARY TABLE IF EXISTS tmp.sale2; + CREATE TEMPORARY TABLE tmp.sale2 + ENGINE = MEMORY + SELECT * FROM tmp.sale; + + + DROP TEMPORARY TABLE IF EXISTS tmp.`grouping`; + CREATE TEMPORARY TABLE tmp.`grouping` + (PRIMARY KEY (itemFk)) + ENGINE = MEMORY + SELECT b.itemFk, + CASE b.groupingMode + WHEN 0 THEN 1 + WHEN 2 THEN b.packing + ELSE b.`grouping` + END AS `grouping` + FROM buy b + JOIN cache.last_buy lb ON lb.buy_id = b.id + WHERE lb.warehouse_id = vWarehouseFk + ; + + DROP TEMPORARY TABLE IF EXISTS tmp.grouping2; + CREATE TEMPORARY TABLE tmp.grouping2 + ENGINE = MEMORY + SELECT * FROM tmp.`grouping`; + + DROP TEMPORARY TABLE IF EXISTS tmp.salePlacementList; + CREATE TEMPORARY TABLE tmp.salePlacementList + ENGINE = MEMORY + + SELECT ts.saleFk, + ts.itemFk, + CONCAT( + IF( iss.id, + CONCAT('< ', IFNULL(wk.`code`, '---'),' > '), + ''), + p.`code`) COLLATE utf8_general_ci as placement , + 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, + sc.isPreviousPrepared, + iss.id as itemShelvingSaleFk, + ts.ticketFk + ,iss.id + , st.saleFk as salePreviousPrepared + , iss.userFk + FROM tmp.sale ts + LEFT JOIN (SELECT DISTINCT saleFk + FROM vn.saleTracking st + JOIN vn.state s ON s.id = st.stateFk + WHERE st.isChecked + AND s.semaphore = 1) st ON st.saleFk = ts.saleFk + JOIN vn.itemShelving ish ON ish.itemFk = ts.itemFk + JOIN vn.shelving sh ON sh.code = ish.shelvingFk + JOIN vn.parking p ON p.id = sh.parkingFk + JOIN vn.sector sc ON sc.id = p.sectorFk + JOIN vn.warehouse w ON w.id = sc.warehouseFk + LEFT JOIN tmp.`grouping` g ON g.itemFk = ts.itemFk + 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 + ; + + DROP TEMPORARY TABLE IF EXISTS tmp.salePlacementList_2; + CREATE TEMPORARY TABLE tmp.salePlacementList_2 + ENGINE MEMORY + 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 + ) sub + GROUP BY saleFk; + + DROP TEMPORARY TABLE IF EXISTS tmp.salePlacementList_3; + CREATE TEMPORARY TABLE tmp.salePlacementList_3 + ENGINE MEMORY + SELECT s1.saleFk, `order`as saleOrder + FROM tmp.salePlacementList s1 + JOIN tmp.salePlacementList_2 s2 ON s2.saleFk = s1.saleFk AND s2.olderPriority = s1.priority; + + UPDATE tmp.salePlacementList s1 + 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 */ + UPDATE tmp.salePlacementList + SET saleOrder = `order`; + + SELECT * + FROM tmp.salePlacementList + ORDER BY visible <> 0 DESC,saleOrder, IF(isPreviousPrepared,2,1), IF(itemShelvingSaleFk,1,2),priority; + + DROP TEMPORARY TABLE + tmp.sale, + tmp.sale2, + tmp.`grouping`, + tmp.grouping2, + tmp.salePlacementList_2, + tmp.salePlacementList_3; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -70609,18 +71331,18 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `prepareClientList`() -BEGIN - - /* - * Require la tabla tmp.ticket(id,clientFk) - */ - - DROP TEMPORARY TABLE IF EXISTS tmp.client; - CREATE TEMPORARY TABLE tmp.client - (PRIMARY KEY (id)) - ENGINE = MEMORY - SELECT DISTINCT clientFk id - FROM tmp.ticket; +BEGIN + + /* + * Require la tabla tmp.ticket(id,clientFk) + */ + + DROP TEMPORARY TABLE IF EXISTS tmp.client; + CREATE TEMPORARY TABLE tmp.client + (PRIMARY KEY (id)) + ENGINE = MEMORY + SELECT DISTINCT clientFk id + FROM tmp.ticket; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -70638,25 +71360,25 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `prepareTicketList`(vStartingDate DATETIME, vEndingDate DATETIME) -BEGIN - - DROP TEMPORARY TABLE IF EXISTS tmp.productionTicket; - CREATE TEMPORARY TABLE tmp.productionTicket - (PRIMARY KEY (ticketFk)) - ENGINE = MEMORY - SELECT t.id ticketFk, t.clientFk - FROM vn.ticket t - LEFT JOIN vn.ticketState ts ON ts.ticket = t.id - JOIN vn.client c ON c.id = t.clientFk - WHERE c.typeFk IN ('normal','handMaking','internalUse') - AND ( - t.shipped BETWEEN CURDATE() AND vEndingDate - OR ( - ts.alertLevel < 3 - AND t.shipped >= vStartingDate - AND t.shipped < CURDATE() - ) - ); +BEGIN + + DROP TEMPORARY TABLE IF EXISTS tmp.productionTicket; + CREATE TEMPORARY TABLE tmp.productionTicket + (PRIMARY KEY (ticketFk)) + ENGINE = MEMORY + SELECT t.id ticketFk, t.clientFk + FROM vn.ticket t + LEFT JOIN vn.ticketState ts ON ts.ticket = t.id + JOIN vn.client c ON c.id = t.clientFk + WHERE c.typeFk IN ('normal','handMaking','internalUse') + AND ( + t.shipped BETWEEN CURDATE() AND vEndingDate + OR ( + ts.alertLevel < 3 + AND t.shipped >= vStartingDate + AND t.shipped < CURDATE() + ) + ); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -70804,225 +71526,225 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `prod`(vWarehouseFk INT, vScopeDays INT) -proc: BEGIN - - DECLARE vEndingDate DATETIME DEFAULT TIMESTAMPADD(DAY,vScopeDays,util.dayEnd(CURDATE())); - - DECLARE vIsTodayRelative BOOLEAN; - - SELECT isTodayRelative INTO vIsTodayRelative - FROM vn.worker - WHERE userFk = vn.getUser(); - - CALL vn.prepareTicketList(TIMESTAMPADD(DAY,-1,CURDATE()), vEndingDate); - - DROP TEMPORARY TABLE IF EXISTS tmp.ticket; - CREATE TEMPORARY TABLE tmp.ticket - SELECT * FROM tmp.productionTicket; - - CALL vn.prepareClientList(); - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketGetProblems; - CREATE TEMPORARY TABLE tmp.ticketGetProblems - (INDEX (ticketFk)) ENGINE = MEMORY - SELECT tt.ticketFk, tt.clientFk, t.warehouseFk, t.shipped - FROM tmp.productionTicket tt - JOIN vn.ticket t ON t.id = tt.ticketFk; - - CALL vn.ticketGetProblems(vIsTodayRelative); - - DROP TEMPORARY TABLE IF EXISTS tmp.productionBuffer; - CREATE TEMPORARY TABLE tmp.productionBuffer - (PRIMARY KEY(ticketFk)) - ENGINE = MEMORY - SELECT tt.ticketFk - , tt.clientFk - , t.warehouseFk - , t.nickname - , t.packages - , IF(HOUR(t.shipped), HOUR(t.shipped), IFNULL(HOUR(zc.hour),HOUR(z.hour))) as HH - , IFNULL(HOUR(zc.hour),HOUR(z.hour)) as Departure - , IF(MINUTE(t.shipped), MINUTE(t.shipped), IFNULL(MINUTE(zc.hour), MINUTE(z.hour))) as mm - , t.routeFk - , IF(am.deliveryMethodFk = 2,z.`id`,0) as zona - , t.nickname addressNickname - , a.postalCode - , a.city - , p.name province - , CONCAT(z.`name`,' ',IFNULL(RIGHT(t.routeFk,3),'')) agency - , am.id agencyModeFk - , 0 AS `lines` - , CAST( 0 AS DECIMAL(5,2)) AS m3 - , CAST( 0 AS DECIMAL(5,2)) AS preparationRate - , "" as problem - , IFNULL(tls.state,2) AS state - , w.code workerCode - , DATE(t.shipped) shipped - , wk.code AS salesPersonCode - , p.id provinceFk - , tls.productionOrder - , ifnull(tls.alertLevel,0) alertLevel - , t.isBoxed as palletized - , rg.deviceId ubicacion - , tlu.lastUpdated - -- , tls.updated lastUpdated - , ifnull(st.graphCategory,0) graphCategory - , pk.code as parking - , 0 AS H - , 0 AS V - , 0 AS F - , 0 AS P - , st.isOk - , ag.isOwn - FROM tmp.productionTicket tt - JOIN vn.ticket t on tt.ticketFk = t.id - LEFT JOIN vn.ticketStateToday tst ON tst.ticket = t.id - LEFT JOIN vn.state st ON st.id = tst.state - LEFT JOIN vn.client c ON c.id = t.clientFk - LEFT JOIN vn.worker wk ON wk.id = c.salesPersonFk - JOIN vn.address a on a.id = t.addressFk - LEFT JOIN vn.province p on p.id = a.provinceFk - JOIN vn.agencyMode am ON am.id = t.agencyModeFk - JOIN vn.agency ag ON ag.id = am.agencyFk - LEFT JOIN vn.ticketState tls on tls.ticket = tt.ticketFk - LEFT JOIN vn.ticketLastUpdated tlu ON tlu.ticketFk = tt.ticketFk - LEFT JOIN vn.worker w on w.id = tls.worker - LEFT JOIN vn.routeGate rg ON rg.routeFk = t.routeFk - LEFT JOIN vn.zone z ON z.id = t.zoneFk - LEFT JOIN vn.zoneClosure zc ON zc.zoneFk = t.zoneFk AND date(t.shipped) = zc.dated - LEFT JOIN vn.ticketParking tp ON tp.ticketFk = t.id - LEFT JOIN vn.parking pk ON pk.id = tp.parkingFk - WHERE t.warehouseFk = vWarehouseFk - AND am.deliveryMethodFk IN (1,2,3); - - ALTER TABLE tmp.productionBuffer - CHANGE COLUMN `problem` `problem` VARCHAR(255), - ADD COLUMN `collectionH` INT, - ADD COLUMN `collectionV` INT, - ADD COLUMN `collectionF` INT, - ADD COLUMN `collectionP` INT; - - -- Líneas y volumen por ticket - UPDATE tmp.productionBuffer pb - JOIN ( - SELECT tt.ticketFk, - COUNT(*) as `lines`, - sum(sv.volume) as m3, - IFNULL(sum(IF(sv.isPicked,sv.volume,0)) / sum(sv.volume),0) as rate - FROM tmp.productionTicket tt - JOIN vn.saleVolume sv on sv.ticketFk = tt.ticketFk - GROUP BY tt.ticketFk - ) m on m.ticketFk = pb.ticketFk - SET pb.`lines` = m.`lines`, - pb.m3 = m.m3, - pb.preparationRate = m.rate; - - DELETE FROM tmp.productionBuffer - WHERE `lines`= 0; - - -- Lineas por linea de encajado - UPDATE tmp.productionBuffer pb - JOIN ( SELECT ticketFk, - sum(sub.H) H, - sum(sub.V) V, - sum(sub.F) F, - sum(sub.P) P - FROM ( - SELECT t.ticketFk, - sum(i.itemPackingTypeFk = 'H') H, - sum(i.itemPackingTypeFk = 'V') V, - sum(i.itemPackingTypeFk = 'F') F, - sum(i.itemPackingTypeFk = 'P') P - FROM tmp.productionTicket t - JOIN vn.sale s ON s.ticketFk = t.ticketFk - JOIN vn.item i ON i.id = s.itemFk - GROUP BY t.ticketFk, i.itemPackingTypeFk) sub - GROUP BY ticketFk - ) sub2 ON sub2.ticketFk = pb.ticketFk - SET pb.H = sub2.H, - pb.V = sub2.V, - pb.F = sub2.F, - pb.P = sub2.P; - - -- Colecciones segun tipo de encajado - UPDATE tmp.productionBuffer pb - JOIN vn.ticketCollection tc ON pb.ticketFk = tc.ticketFk - JOIN vn.collection c ON c.id = tc.collectionFk - SET pb.collectionH = c.id - WHERE c.itemPackingTypeFk = 'H' OR ISNULL(c.itemPackingTypeFk); - - UPDATE tmp.productionBuffer pb - JOIN vn.ticketCollection tc ON pb.ticketFk = tc.ticketFk - JOIN vn.collection c ON c.id = tc.collectionFk - SET pb.collectionV = c.id - WHERE c.itemPackingTypeFk = 'V' OR ISNULL(c.itemPackingTypeFk); - - UPDATE tmp.productionBuffer pb - JOIN vn.ticketCollection tc ON pb.ticketFk = tc.ticketFk - JOIN vn.collection c ON c.id = tc.collectionFk - SET pb.collectionF = c.id - WHERE c.itemPackingTypeFk = 'F' OR ISNULL(c.itemPackingTypeFk); - - UPDATE tmp.productionBuffer pb - JOIN vn.ticketCollection tc ON pb.ticketFk = tc.ticketFk - JOIN vn.collection c ON c.id = tc.collectionFk - SET pb.collectionP = c.id - WHERE c.itemPackingTypeFk = 'P' OR ISNULL(c.itemPackingTypeFk); - - -- Cajas - ALTER TABLE tmp.productionBuffer - ADD Cajas DOUBLE DEFAULT NULL; - /* - -- Problemas por ticket - UPDATE tmp.productionBuffer pb - JOIN tmp.ticketProblems tp ON tp.ticketFk = pb.ticketFk - SET pb.problem = CAST(CONCAT( IFNULL(tp.itemShortage,''), - IFNULL(tp.itemDelay,''), - IF(tp.isFreezed,' CONGELADO',''), - IF(tp.risk,' RIESGO',''), - IF(tp.hasTicketRequest, ' COD 100',''), - IF(tp.isTaxDataChecked, '',' FICHA INCOMPLETA'), - IF(tp.componentLack,' COMPONENTES', '') - ) as char(255)); - */ - -- Refresca la caché para el cierre dinámico de agencias - -- CALL cache.departure_timing(vWarehouseFk); -/* - -- Tickets de recogida - REPLACE tmp.productionBuffer( - shipped - , ticketFk - , agency - , clientFk - , addressNickname - , state - , workerCode - , alertLevel - , warehouseFk - ) - SELECT DATE(t.shipped) - , t.id - , am.name - , t.clientFk - , a.nickname - , s.id as state - , w.code - , ifnull(tls.alertLevel,0) alert_level - , vWarehouseFk - FROM vn.ticket t - JOIN vn.address a on a.id = t.addressFk - JOIN vn.agencyMode am ON am.id = t.agencyModeFk - LEFT JOIN vn2008.warehouse_pickup wp ON wp.agency_id = am.id - LEFT JOIN vn.ticketState tls on tls.ticket = t.id - LEFT JOIN vn.state s ON s.id = tls.state - LEFT JOIN vn.worker w on w.id = tls.worker - WHERE t.shipped between TIMESTAMPADD(WEEK,-1,CURDATE()) AND util.dayend(TIMESTAMPADD(DAY,-1,CURDATE())) - AND wp.warehouse_id = vWarehouseFk; -*/ - DROP TEMPORARY TABLE tmp.productionTicket; - DROP TEMPORARY TABLE tmp.ticket; - DROP TEMPORARY TABLE IF EXISTS tmp.risk; - +proc: BEGIN + + DECLARE vEndingDate DATETIME DEFAULT TIMESTAMPADD(DAY,vScopeDays,util.dayEnd(CURDATE())); + + DECLARE vIsTodayRelative BOOLEAN; + + SELECT isTodayRelative INTO vIsTodayRelative + FROM vn.worker + WHERE userFk = vn.getUser(); + + CALL vn.prepareTicketList(TIMESTAMPADD(DAY,-1,CURDATE()), vEndingDate); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticket; + CREATE TEMPORARY TABLE tmp.ticket + SELECT * FROM tmp.productionTicket; + + CALL vn.prepareClientList(); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketGetProblems; + CREATE TEMPORARY TABLE tmp.ticketGetProblems + (INDEX (ticketFk)) ENGINE = MEMORY + SELECT tt.ticketFk, tt.clientFk, t.warehouseFk, t.shipped + FROM tmp.productionTicket tt + JOIN vn.ticket t ON t.id = tt.ticketFk; + + CALL vn.ticketGetProblems(vIsTodayRelative); + + DROP TEMPORARY TABLE IF EXISTS tmp.productionBuffer; + CREATE TEMPORARY TABLE tmp.productionBuffer + (PRIMARY KEY(ticketFk)) + ENGINE = MEMORY + SELECT tt.ticketFk + , tt.clientFk + , t.warehouseFk + , t.nickname + , t.packages + , IF(HOUR(t.shipped), HOUR(t.shipped), IFNULL(HOUR(zc.hour),HOUR(z.hour))) as HH + , IFNULL(HOUR(zc.hour),HOUR(z.hour)) as Departure + , IF(MINUTE(t.shipped), MINUTE(t.shipped), IFNULL(MINUTE(zc.hour), MINUTE(z.hour))) as mm + , t.routeFk + , IF(am.deliveryMethodFk = 2,z.`id`,0) as zona + , t.nickname addressNickname + , a.postalCode + , a.city + , p.name province + , CONCAT(z.`name`,' ',IFNULL(RIGHT(t.routeFk,3),'')) agency + , am.id agencyModeFk + , 0 AS `lines` + , CAST( 0 AS DECIMAL(5,2)) AS m3 + , CAST( 0 AS DECIMAL(5,2)) AS preparationRate + , "" as problem + , IFNULL(tls.state,2) AS state + , w.code workerCode + , DATE(t.shipped) shipped + , wk.code AS salesPersonCode + , p.id provinceFk + , tls.productionOrder + , ifnull(tls.alertLevel,0) alertLevel + , t.isBoxed as palletized + , rg.deviceId ubicacion + , tlu.lastUpdated + -- , tls.updated lastUpdated + , ifnull(st.graphCategory,0) graphCategory + , pk.code as parking + , 0 AS H + , 0 AS V + , 0 AS F + , 0 AS P + , st.isOk + , ag.isOwn + FROM tmp.productionTicket tt + JOIN vn.ticket t on tt.ticketFk = t.id + LEFT JOIN vn.ticketStateToday tst ON tst.ticket = t.id + LEFT JOIN vn.state st ON st.id = tst.state + LEFT JOIN vn.client c ON c.id = t.clientFk + LEFT JOIN vn.worker wk ON wk.id = c.salesPersonFk + JOIN vn.address a on a.id = t.addressFk + LEFT JOIN vn.province p on p.id = a.provinceFk + JOIN vn.agencyMode am ON am.id = t.agencyModeFk + JOIN vn.agency ag ON ag.id = am.agencyFk + LEFT JOIN vn.ticketState tls on tls.ticket = tt.ticketFk + LEFT JOIN vn.ticketLastUpdated tlu ON tlu.ticketFk = tt.ticketFk + LEFT JOIN vn.worker w on w.id = tls.worker + LEFT JOIN vn.routeGate rg ON rg.routeFk = t.routeFk + LEFT JOIN vn.zone z ON z.id = t.zoneFk + LEFT JOIN vn.zoneClosure zc ON zc.zoneFk = t.zoneFk AND date(t.shipped) = zc.dated + LEFT JOIN vn.ticketParking tp ON tp.ticketFk = t.id + LEFT JOIN vn.parking pk ON pk.id = tp.parkingFk + WHERE t.warehouseFk = vWarehouseFk + AND am.deliveryMethodFk IN (1,2,3); + + ALTER TABLE tmp.productionBuffer + CHANGE COLUMN `problem` `problem` VARCHAR(255), + ADD COLUMN `collectionH` INT, + ADD COLUMN `collectionV` INT, + ADD COLUMN `collectionF` INT, + ADD COLUMN `collectionP` INT; + + -- Líneas y volumen por ticket + UPDATE tmp.productionBuffer pb + JOIN ( + SELECT tt.ticketFk, + COUNT(*) as `lines`, + sum(sv.volume) as m3, + IFNULL(sum(IF(sv.isPicked,sv.volume,0)) / sum(sv.volume),0) as rate + FROM tmp.productionTicket tt + JOIN vn.saleVolume sv on sv.ticketFk = tt.ticketFk + GROUP BY tt.ticketFk + ) m on m.ticketFk = pb.ticketFk + SET pb.`lines` = m.`lines`, + pb.m3 = m.m3, + pb.preparationRate = m.rate; + + DELETE FROM tmp.productionBuffer + WHERE `lines`= 0; + + -- Lineas por linea de encajado + UPDATE tmp.productionBuffer pb + JOIN ( SELECT ticketFk, + sum(sub.H) H, + sum(sub.V) V, + sum(sub.F) F, + sum(sub.P) P + FROM ( + SELECT t.ticketFk, + sum(i.itemPackingTypeFk = 'H') H, + sum(i.itemPackingTypeFk = 'V') V, + sum(i.itemPackingTypeFk = 'F') F, + sum(i.itemPackingTypeFk = 'P') P + FROM tmp.productionTicket t + JOIN vn.sale s ON s.ticketFk = t.ticketFk + JOIN vn.item i ON i.id = s.itemFk + GROUP BY t.ticketFk, i.itemPackingTypeFk) sub + GROUP BY ticketFk + ) sub2 ON sub2.ticketFk = pb.ticketFk + SET pb.H = sub2.H, + pb.V = sub2.V, + pb.F = sub2.F, + pb.P = sub2.P; + + -- Colecciones segun tipo de encajado + UPDATE tmp.productionBuffer pb + JOIN vn.ticketCollection tc ON pb.ticketFk = tc.ticketFk + JOIN vn.collection c ON c.id = tc.collectionFk + SET pb.collectionH = c.id + WHERE c.itemPackingTypeFk = 'H' OR ISNULL(c.itemPackingTypeFk); + + UPDATE tmp.productionBuffer pb + JOIN vn.ticketCollection tc ON pb.ticketFk = tc.ticketFk + JOIN vn.collection c ON c.id = tc.collectionFk + SET pb.collectionV = c.id + WHERE c.itemPackingTypeFk = 'V' OR ISNULL(c.itemPackingTypeFk); + + UPDATE tmp.productionBuffer pb + JOIN vn.ticketCollection tc ON pb.ticketFk = tc.ticketFk + JOIN vn.collection c ON c.id = tc.collectionFk + SET pb.collectionF = c.id + WHERE c.itemPackingTypeFk = 'F' OR ISNULL(c.itemPackingTypeFk); + + UPDATE tmp.productionBuffer pb + JOIN vn.ticketCollection tc ON pb.ticketFk = tc.ticketFk + JOIN vn.collection c ON c.id = tc.collectionFk + SET pb.collectionP = c.id + WHERE c.itemPackingTypeFk = 'P' OR ISNULL(c.itemPackingTypeFk); + + -- Cajas + ALTER TABLE tmp.productionBuffer + ADD Cajas DOUBLE DEFAULT NULL; + /* + -- Problemas por ticket + UPDATE tmp.productionBuffer pb + JOIN tmp.ticketProblems tp ON tp.ticketFk = pb.ticketFk + SET pb.problem = CAST(CONCAT( IFNULL(tp.itemShortage,''), + IFNULL(tp.itemDelay,''), + IF(tp.isFreezed,' CONGELADO',''), + IF(tp.risk,' RIESGO',''), + IF(tp.hasTicketRequest, ' COD 100',''), + IF(tp.isTaxDataChecked, '',' FICHA INCOMPLETA'), + IF(tp.componentLack,' COMPONENTES', '') + ) as char(255)); + */ + -- Refresca la caché para el cierre dinámico de agencias + -- CALL cache.departure_timing(vWarehouseFk); +/* + -- Tickets de recogida + REPLACE tmp.productionBuffer( + shipped + , ticketFk + , agency + , clientFk + , addressNickname + , state + , workerCode + , alertLevel + , warehouseFk + ) + SELECT DATE(t.shipped) + , t.id + , am.name + , t.clientFk + , a.nickname + , s.id as state + , w.code + , ifnull(tls.alertLevel,0) alert_level + , vWarehouseFk + FROM vn.ticket t + JOIN vn.address a on a.id = t.addressFk + JOIN vn.agencyMode am ON am.id = t.agencyModeFk + LEFT JOIN vn2008.warehouse_pickup wp ON wp.agency_id = am.id + LEFT JOIN vn.ticketState tls on tls.ticket = t.id + LEFT JOIN vn.state s ON s.id = tls.state + LEFT JOIN vn.worker w on w.id = tls.worker + WHERE t.shipped between TIMESTAMPADD(WEEK,-1,CURDATE()) AND util.dayend(TIMESTAMPADD(DAY,-1,CURDATE())) + AND wp.warehouse_id = vWarehouseFk; +*/ + DROP TEMPORARY TABLE tmp.productionTicket; + DROP TEMPORARY TABLE tmp.ticket; + DROP TEMPORARY TABLE IF EXISTS tmp.risk; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -72296,99 +73018,99 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `reportLabelCollection_get`(vSelf INT) -BEGIN - -/** - * Obtiene los datos necesarios de un ticket o colección - * - * @param vSelf Ticket/Colección del que sacar los datos - **/ - - DECLARE vItemPackingTypeFk VARCHAR(1); - DECLARE vIsTicket BOOL; - - -- Averiguamos si es un ticket o una colección - SELECT IF(id, TRUE, FALSE) INTO vIsTicket - FROM vn.ticket - WHERE created > (CURRENT_DATE() - INTERVAL 1 MONTH) - AND id = vSelf; - - -- Si los sacadores NO son de V, pinta los colores - SELECT itemPackingTypeFk INTO vItemPackingTypeFk - FROM vn.collection - WHERE id = vSelf; - - IF !(vItemPackingTypeFk <=> 'V') THEN - - SELECT CONCAT(tc.collectionFk, ' ', LEFT(cc.code,4)) `level`, - tc.ticketFk, - LEFT(IF(t.routeFk IS NULL, am.name, zo.name ), 12) agencyDescription, - am.name, - t.clientFk, - COUNT(*) notes, - w.code workerCode, - tt.labelCount, - IF(HOUR(t.shipped), TIME(t.shipped), TIME(zo.`hour`)) horaagencia, - t.shipped, - COUNT(*) lineas, - t.nickName, - CONCAT(CAST(SUM(sv.volume) AS DECIMAL(5,2)) , "m³") m3 - FROM vn.ticket t - JOIN vn.ticketCollection tc ON tc.ticketFk = t.id - JOIN vn.collection c ON c.id = tc.collectionFk - JOIN vn.collectionColors cc ON cc.shelve = tc.`level` - AND cc.wagon = tc.wagon - AND cc.trainFk = c.trainFk - JOIN vn.sale s ON s.ticketFk = t.id - LEFT JOIN vn.saleVolume sv ON sv.saleFk = s.id - JOIN vn.worker w ON w.id = c.workerFk - JOIN vn.agencyMode am ON am.id = t.agencyModeFk - LEFT JOIN vn.ticketTrolley tt ON tt.ticket = t.id - LEFT JOIN vn.address a ON a.id = t.addressFk - LEFT JOIN vn.route r ON r.id = t.routeFk - LEFT JOIN vn.zoneEstimatedDelivery ze ON ze.zoneFk = t.zoneFk - LEFT JOIN vn.agencyMode agm ON r.agencyModeFk =agm.id - LEFT JOIN vn.zone zo ON t.zoneFk = zo.id - WHERE IF(vIsTicket, tc.ticketFk = vSelf, tc.collectionFk = vSelf) - GROUP BY t.id - ORDER BY cc.code; - - ELSE - - SELECT CONCAT(tc.collectionFk,' ', SUBSTRING('ABCDEFGH',tc.wagon, 1), '-', tc.`level`) `level`, - tc.ticketFk, - LEFT(IF(t.routeFk IS NULL, am.name, zo.name ), 12) agencyDescription, - am.name, - t.clientFk, - CAST(IF(ic.code = 'plant', CONCAT(MAX(i.`size`),' cm'), COUNT(*)) AS CHAR) notes, - w.code workerCode, - tt.labelCount, - IF(HOUR(t.shipped), TIME(t.shipped), TIME(zo.`hour`)) horaagencia, - t.shipped, - COUNT(*) lineas, - t.nickName, - CONCAT(CAST(SUM(sv.volume) AS DECIMAL(5,2)), "m³") m3 - FROM vn.ticket t - JOIN vn.ticketCollection tc ON tc.ticketFk = t.id - JOIN vn.collection c ON c.id = tc.collectionFk - JOIN vn.sale s ON s.ticketFk = t.id - LEFT JOIN vn.saleVolume sv ON sv.saleFk = s.id - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.itemType it ON it.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk - JOIN vn.worker w ON w.id = c.workerFk - JOIN vn.agencyMode am ON am.id = t.agencyModeFk - LEFT JOIN vn.ticketTrolley tt ON tt.ticket = t.id - LEFT JOIN vn.address a ON a.id = t.addressFk - LEFT JOIN vn.route r ON r.id = t.routeFk - LEFT JOIN vn.zoneEstimatedDelivery ze ON ze.zoneFk = t.zoneFk - LEFT JOIN vn.agencyMode agm ON r.agencyModeFk =agm.id - LEFT JOIN vn.`zone` zo ON t.zoneFk = zo.id - WHERE IF(vIsTicket, tc.ticketFk = vSelf, tc.collectionFk = vSelf) - GROUP BY t.id; - - END IF; - +BEGIN + +/** + * Obtiene los datos necesarios de un ticket o colección + * + * @param vSelf Ticket/Colección del que sacar los datos + **/ + + DECLARE vItemPackingTypeFk VARCHAR(1); + DECLARE vIsTicket BOOL; + + -- Averiguamos si es un ticket o una colección + SELECT IF(id, TRUE, FALSE) INTO vIsTicket + FROM vn.ticket + WHERE created > (CURRENT_DATE() - INTERVAL 1 MONTH) + AND id = vSelf; + + -- Si los sacadores NO son de V, pinta los colores + SELECT itemPackingTypeFk INTO vItemPackingTypeFk + FROM vn.collection + WHERE id = vSelf; + + IF !(vItemPackingTypeFk <=> 'V') THEN + + SELECT CONCAT(tc.collectionFk, ' ', LEFT(cc.code,4)) `level`, + tc.ticketFk, + LEFT(IF(t.routeFk IS NULL, am.name, zo.name ), 12) agencyDescription, + am.name, + t.clientFk, + COUNT(*) notes, + w.code workerCode, + tt.labelCount, + IF(HOUR(t.shipped), TIME(t.shipped), TIME(zo.`hour`)) horaagencia, + t.shipped, + COUNT(*) lineas, + t.nickName, + CONCAT(CAST(SUM(sv.volume) AS DECIMAL(5,2)) , "m³") m3 + FROM vn.ticket t + JOIN vn.ticketCollection tc ON tc.ticketFk = t.id + JOIN vn.collection c ON c.id = tc.collectionFk + JOIN vn.collectionColors cc ON cc.shelve = tc.`level` + AND cc.wagon = tc.wagon + AND cc.trainFk = c.trainFk + JOIN vn.sale s ON s.ticketFk = t.id + LEFT JOIN vn.saleVolume sv ON sv.saleFk = s.id + JOIN vn.worker w ON w.id = c.workerFk + JOIN vn.agencyMode am ON am.id = t.agencyModeFk + LEFT JOIN vn.ticketTrolley tt ON tt.ticket = t.id + LEFT JOIN vn.address a ON a.id = t.addressFk + LEFT JOIN vn.route r ON r.id = t.routeFk + LEFT JOIN vn.zoneEstimatedDelivery ze ON ze.zoneFk = t.zoneFk + LEFT JOIN vn.agencyMode agm ON r.agencyModeFk =agm.id + LEFT JOIN vn.zone zo ON t.zoneFk = zo.id + WHERE IF(vIsTicket, tc.ticketFk = vSelf, tc.collectionFk = vSelf) + GROUP BY t.id + ORDER BY cc.code; + + ELSE + + SELECT CONCAT(tc.collectionFk,' ', SUBSTRING('ABCDEFGH',tc.wagon, 1), '-', tc.`level`) `level`, + tc.ticketFk, + LEFT(IF(t.routeFk IS NULL, am.name, zo.name ), 12) agencyDescription, + am.name, + t.clientFk, + CAST(IF(ic.code = 'plant', CONCAT(MAX(i.`size`),' cm'), COUNT(*)) AS CHAR) notes, + w.code workerCode, + tt.labelCount, + IF(HOUR(t.shipped), TIME(t.shipped), TIME(zo.`hour`)) horaagencia, + t.shipped, + COUNT(*) lineas, + t.nickName, + CONCAT(CAST(SUM(sv.volume) AS DECIMAL(5,2)), "m³") m3 + FROM vn.ticket t + JOIN vn.ticketCollection tc ON tc.ticketFk = t.id + JOIN vn.collection c ON c.id = tc.collectionFk + JOIN vn.sale s ON s.ticketFk = t.id + LEFT JOIN vn.saleVolume sv ON sv.saleFk = s.id + JOIN vn.item i ON i.id = s.itemFk + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk + JOIN vn.worker w ON w.id = c.workerFk + JOIN vn.agencyMode am ON am.id = t.agencyModeFk + LEFT JOIN vn.ticketTrolley tt ON tt.ticket = t.id + LEFT JOIN vn.address a ON a.id = t.addressFk + LEFT JOIN vn.route r ON r.id = t.routeFk + LEFT JOIN vn.zoneEstimatedDelivery ze ON ze.zoneFk = t.zoneFk + LEFT JOIN vn.agencyMode agm ON r.agencyModeFk =agm.id + LEFT JOIN vn.`zone` zo ON t.zoneFk = zo.id + WHERE IF(vIsTicket, tc.ticketFk = vSelf, tc.collectionFk = vSelf) + GROUP BY t.id; + + END IF; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -72540,25 +73262,25 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `routeGate_assignDevice`(vDevice VARCHAR(30), vRouteFk INT) -BEGIN -/** - * Asigna el dispositivo la ruta - * - * @param vDevice Dispositivo a remplazar - * @param vRouteFk Ruta a la cual asignarlo - */ - IF ISNULL(vDevice) THEN - - DELETE FROM routeGate - WHERE routeFk = vRouteFk; - - ELSE - - REPLACE routeGate(routeFk, deviceId) - VALUES(vRouteFk, vDevice); - - END IF; - +BEGIN +/** + * Asigna el dispositivo la ruta + * + * @param vDevice Dispositivo a remplazar + * @param vRouteFk Ruta a la cual asignarlo + */ + IF ISNULL(vDevice) THEN + + DELETE FROM routeGate + WHERE routeFk = vRouteFk; + + ELSE + + REPLACE routeGate(routeFk, deviceId) + VALUES(vRouteFk, vDevice); + + END IF; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -72875,64 +73597,64 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `route_getTickets`(vRouteFk INT) -BEGIN -/** - * Pasado un RouteFk devuelve la información - * de sus tickets. - * - * @param vRouteFk - * - * @select Información de los tickets - */ - - SELECT - t.id AS Id, - t.clientFk AS Client, - a.id AS Address, - a.nickname AS ClientName, - t.packages AS Packages, - a.street AS AddressName, - a.postalCode AS PostalCode, - a.city AS City, - sub2.itemPackingTypeFk AS PackingType, - c.phone AS ClientPhone, - c.mobile AS ClientMobile, - a.phone AS AddressPhone, - a.mobile AS AddressMobile, - tl.longitude AS Longitude, - tl.latitude AS Latitude, - wm.mediaValue AS SalePersonPhone, - tob.Note AS Note, - t.isSigned AS Signed, - st.id AS Polizon - FROM ticket t - JOIN client c ON t.clientFk = c.id - JOIN address a ON t.addressFk = a.id - LEFT JOIN ticketLocation tl ON tl.ticketFk = t.id - LEFT JOIN workerMedia wm ON wm.workerFk = c.salesPersonFk - LEFT JOIN - (SELECT tob.description AS Note, t.id - FROM ticketObservation tob - JOIN ticket t ON tob.ticketFk = t.id - JOIN observationType ot ON ot.id = tob.observationTypeFk - WHERE t.routeFk = vRouteFk - AND ot.code = 'delivery' - )tob ON tob.id = t.id - LEFT JOIN stowaway st ON st.shipFk = t.id - LEFT JOIN - (SELECT sub.ticketFk, - CONCAT('(', GROUP_CONCAT(DISTINCT sub.itemPackingTypeFk ORDER BY sub.items DESC SEPARATOR ','), ') ') itemPackingTypeFk - FROM (SELECT s.ticketFk , i.itemPackingTypeFk, COUNT(*) items - FROM ticket t - JOIN sale s ON s.ticketFk = t.id - JOIN item i ON i.id = s.itemFk - WHERE t.routeFk = vRouteFk - GROUP BY t.id,i.itemPackingTypeFk)sub - GROUP BY sub.ticketFk - ) sub2 ON sub2.ticketFk = t.id - WHERE t.routeFk = vRouteFk - GROUP BY t.id - ORDER BY t.priority; +BEGIN +/** + * Pasado un RouteFk devuelve la información + * de sus tickets. + * + * @param vRouteFk + * + * @select Información de los tickets + */ + + SELECT + t.id AS Id, + t.clientFk AS Client, + a.id AS Address, + a.nickname AS ClientName, + t.packages AS Packages, + a.street AS AddressName, + a.postalCode AS PostalCode, + a.city AS City, + sub2.itemPackingTypeFk AS PackingType, + c.phone AS ClientPhone, + c.mobile AS ClientMobile, + a.phone AS AddressPhone, + a.mobile AS AddressMobile, + tl.longitude AS Longitude, + tl.latitude AS Latitude, + wm.mediaValue AS SalePersonPhone, + tob.Note AS Note, + t.isSigned AS Signed, + st.id AS Polizon + FROM ticket t + JOIN client c ON t.clientFk = c.id + JOIN address a ON t.addressFk = a.id + LEFT JOIN ticketLocation tl ON tl.ticketFk = t.id + LEFT JOIN workerMedia wm ON wm.workerFk = c.salesPersonFk + LEFT JOIN + (SELECT tob.description AS Note, t.id + FROM ticketObservation tob + JOIN ticket t ON tob.ticketFk = t.id + JOIN observationType ot ON ot.id = tob.observationTypeFk + WHERE t.routeFk = vRouteFk + AND ot.code = 'delivery' + )tob ON tob.id = t.id + LEFT JOIN stowaway st ON st.shipFk = t.id + LEFT JOIN + (SELECT sub.ticketFk, + CONCAT('(', GROUP_CONCAT(DISTINCT sub.itemPackingTypeFk ORDER BY sub.items DESC SEPARATOR ','), ') ') itemPackingTypeFk + FROM (SELECT s.ticketFk , i.itemPackingTypeFk, COUNT(*) items + FROM ticket t + JOIN sale s ON s.ticketFk = t.id + JOIN item i ON i.id = s.itemFk + WHERE t.routeFk = vRouteFk + GROUP BY t.id,i.itemPackingTypeFk)sub + GROUP BY sub.ticketFk + ) sub2 ON sub2.ticketFk = t.id + WHERE t.routeFk = vRouteFk + GROUP BY t.id + ORDER BY t.priority; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -73155,28 +73877,28 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `saleBuy_Add`(vSaleFk INT, vBuyFk INT) -BEGIN - - /* Añade un registro a la tabla saleBuy en el caso de que sea posible mantener la trazabilidad - * - * @param vSaleFk clave primaria de vn.sale - * @param vBuyFk clave primaria de vn.buy - */ - /*IF (SELECT COUNT(*) - FROM vn.sale s - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.itemType it ON it.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk - WHERE s.id = vSaleFk - AND ic.code = 'fruit') THEN */ - - IF (SELECT COUNT(*) FROM vn.buy WHERE id = vBuyFk AND itemOriginalFk) THEN - - INSERT INTO vn.saleBuy (saleFk, buyFk) - VALUES(vSaleFk, vBuyFk); - - END IF; - +BEGIN + + /* Añade un registro a la tabla saleBuy en el caso de que sea posible mantener la trazabilidad + * + * @param vSaleFk clave primaria de vn.sale + * @param vBuyFk clave primaria de vn.buy + */ + /*IF (SELECT COUNT(*) + FROM vn.sale s + JOIN vn.item i ON i.id = s.itemFk + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk + WHERE s.id = vSaleFk + AND ic.code = 'fruit') THEN */ + + IF (SELECT COUNT(*) FROM vn.buy WHERE id = vBuyFk AND itemOriginalFk) THEN + + INSERT INTO vn.saleBuy (saleFk, buyFk) + VALUES(vSaleFk, vBuyFk); + + END IF; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -73194,17 +73916,17 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `saleGroup_add`() -BEGIN - - /* - * Añade un nuevo registro a la tabla y devuelve su id - */ - - INSERT INTO vn.saleGroup(userFk) - VALUES (account.myUser_getId()); - - SELECT LAST_INSERT_ID(); - +BEGIN + + /* + * Añade un nuevo registro a la tabla y devuelve su id + */ + + INSERT INTO vn.saleGroup(userFk) + VALUES (account.myUser_getId()); + + SELECT LAST_INSERT_ID(); + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -73286,77 +74008,77 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `saleItemShelvingMake__`(IN `vTicketFk` INT, IN `vSectorFk` INT) -BEGIN - - SET @rest:= CAST(0 AS DECIMAL(10,0)); - SET @saleFk := CAST(0 AS DECIMAL(10,0)); - SET @reserved := CAST(0 AS DECIMAL(10,0)); - - UPDATE vn.itemShelving ish - JOIN vn.saleItemShelving sis ON sis.itemShelvingFk = ish.id - JOIN sale s ON s.id = sis.saleFk - SET ish.visible = sis.quantity + ish.visible, - ish.available = sis.quantity + ish.visible - WHERE s.ticketFk = vTicketFk; - - DELETE sis.* - FROM saleItemShelving sis - JOIN sale s ON s.id = sis.saleFk - WHERE s.ticketFk = vTicketFk; - - INSERT INTO saleItemShelving( saleFk, - itemShelvingFk, - quantity, - ubication) - SELECT saleFk, - itemShelvingFk, - CAST(Reserved as DECIMAL(10,0)) as Reserved, - ubication - FROM - (SELECT saleFk, - itemShelvingFk, - ubication, - @rest := IF(@saleFk = saleFk, @rest, quantity) as Falta, - @reserved := IF(available < @rest, available, IF(@rest < packing,0,@rest)) as Reserved, - @rest := @rest - @reserved, - @saleFk := saleFk - FROM - ( SELECT s.id as saleFk, - ish.created, - ish.id as itemShelvingFk, - ish.available, - s.quantity, - ish.packing, - CONCAT(p.`column`, '-',p.`row`,': ', sh.code ) as ubication - FROM vn.sale s - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN vn.sector sc ON sc.warehouseFk = t.warehouseFk - JOIN vn.parking p ON p.sectorFk = sc.id - JOIN vn.shelving sh ON sh.parkingFk = p.id - JOIN vn.itemShelving ish ON ish.shelvingFk = sh.code AND ish.itemFk = s.itemFk - WHERE t.id = vTicketFk - AND sc.id = vSectorFk - AND s.quantity MOD ish.packing = 0 - AND s.quantity >= ish.packing - ORDER BY s.id, - sh.priority DESC, - ish.packing DESC, - ish.created - ) sub - ) sub2 - WHERE Reserved > 0; - - UPDATE vn.itemShelving ish - JOIN vn.saleItemShelving sis ON sis.itemShelvingFk = ish.id - JOIN vn.sale s ON s.id = sis.saleFk - SET ish.available = ish.visible - sis.quantity, - ish.visible = ish.visible - sis.quantity - WHERE s.ticketFk = vTicketFk - AND s.isPicked = FALSE; - - CALL vn.saleItemShelvingIsPicked(vTicketFk, TRUE); - - +BEGIN + + SET @rest:= CAST(0 AS DECIMAL(10,0)); + SET @saleFk := CAST(0 AS DECIMAL(10,0)); + SET @reserved := CAST(0 AS DECIMAL(10,0)); + + UPDATE vn.itemShelving ish + JOIN vn.saleItemShelving sis ON sis.itemShelvingFk = ish.id + JOIN sale s ON s.id = sis.saleFk + SET ish.visible = sis.quantity + ish.visible, + ish.available = sis.quantity + ish.visible + WHERE s.ticketFk = vTicketFk; + + DELETE sis.* + FROM saleItemShelving sis + JOIN sale s ON s.id = sis.saleFk + WHERE s.ticketFk = vTicketFk; + + INSERT INTO saleItemShelving( saleFk, + itemShelvingFk, + quantity, + ubication) + SELECT saleFk, + itemShelvingFk, + CAST(Reserved as DECIMAL(10,0)) as Reserved, + ubication + FROM + (SELECT saleFk, + itemShelvingFk, + ubication, + @rest := IF(@saleFk = saleFk, @rest, quantity) as Falta, + @reserved := IF(available < @rest, available, IF(@rest < packing,0,@rest)) as Reserved, + @rest := @rest - @reserved, + @saleFk := saleFk + FROM + ( SELECT s.id as saleFk, + ish.created, + ish.id as itemShelvingFk, + ish.available, + s.quantity, + ish.packing, + CONCAT(p.`column`, '-',p.`row`,': ', sh.code ) as ubication + FROM vn.sale s + JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.sector sc ON sc.warehouseFk = t.warehouseFk + JOIN vn.parking p ON p.sectorFk = sc.id + JOIN vn.shelving sh ON sh.parkingFk = p.id + JOIN vn.itemShelving ish ON ish.shelvingFk = sh.code AND ish.itemFk = s.itemFk + WHERE t.id = vTicketFk + AND sc.id = vSectorFk + AND s.quantity MOD ish.packing = 0 + AND s.quantity >= ish.packing + ORDER BY s.id, + sh.priority DESC, + ish.packing DESC, + ish.created + ) sub + ) sub2 + WHERE Reserved > 0; + + UPDATE vn.itemShelving ish + JOIN vn.saleItemShelving sis ON sis.itemShelvingFk = ish.id + JOIN vn.sale s ON s.id = sis.saleFk + SET ish.available = ish.visible - sis.quantity, + ish.visible = ish.visible - sis.quantity + WHERE s.ticketFk = vTicketFk + AND s.isPicked = FALSE; + + CALL vn.saleItemShelvingIsPicked(vTicketFk, TRUE); + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -73487,20 +74209,20 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `saleParking_add__`(vSaleFk INT, vParkingCode VARCHAR(10)) -BEGIN - - /* - * Inserta registro en saleParking - * - * vSaleFk Identificador de vn.sale - * vParkingCode Code de vn.parking - */ - - INSERT INTO vn.saleParking(saleFk, parkingFk, userFk) - SELECT vSaleFk, p.id, account.myUser_getId() - FROM vn.parking p - WHERE p.code = vParkingCode COLLATE utf8_unicode_ci; - +BEGIN + + /* + * Inserta registro en saleParking + * + * vSaleFk Identificador de vn.sale + * vParkingCode Code de vn.parking + */ + + INSERT INTO vn.saleParking(saleFk, parkingFk, userFk) + SELECT vSaleFk, p.id, account.myUser_getId() + FROM vn.parking p + WHERE p.code = vParkingCode COLLATE utf8_unicode_ci; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -73724,28 +74446,28 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `saleTracking_add`(vSaleGroupFk INT) -BEGIN - - /* Inserta en vn.saleTracking las lineas de una previa - * - * @param vSaleGroupFk Identificador de vn.saleGroup - */ - - REPLACE vn.saleTracking(saleFk, - isChecked, - workerFk, - actionFk, - stateFk) - SELECT sgd.saleFk , - TRUE, - account.myUser_getId(), - a.accion_id, - s.id - FROM vn.saleGroupDetail sgd - JOIN vncontrol.accion a ON a.accion = 'SACAR' - JOIN vn.state s ON s.code = 'ON_PREPARATION' - WHERE sgd.saleGroupFk = vSaleGroupFk; - +BEGIN + + /* Inserta en vn.saleTracking las lineas de una previa + * + * @param vSaleGroupFk Identificador de vn.saleGroup + */ + + REPLACE vn.saleTracking(saleFk, + isChecked, + workerFk, + actionFk, + stateFk) + SELECT sgd.saleFk , + TRUE, + account.myUser_getId(), + a.accion_id, + s.id + FROM vn.saleGroupDetail sgd + JOIN vncontrol.accion a ON a.accion = 'SACAR' + JOIN vn.state s ON s.code = 'ON_PREPARATION' + WHERE sgd.saleGroupFk = vSaleGroupFk; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -73763,21 +74485,21 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `saleTracking_addPreparedSaleGroup`(vSaleGroupFk INT) -BEGIN - - /** - * Inserta lineas de vn.saleTracking para un saleGroup (previa) que escanea un sacador - * - * @param vSaleGroupFk Identificador de vn.saleGroup - */ - - REPLACE vn.saleTracking(saleFk, isChecked, workerFk, actionFk, stateFk) - SELECT sgd.saleFk, TRUE, account.myUser_getId(), a.accion_id id, s.id - FROM vn.saleGroupDetail sgd - JOIN vncontrol.accion a ON a.accion = 'SACAR' - JOIN vn.state s ON s.code = 'PREPARED' - WHERE sgd.saleGroupFk = vSaleGroupFk; - +BEGIN + + /** + * Inserta lineas de vn.saleTracking para un saleGroup (previa) que escanea un sacador + * + * @param vSaleGroupFk Identificador de vn.saleGroup + */ + + REPLACE vn.saleTracking(saleFk, isChecked, workerFk, actionFk, stateFk) + SELECT sgd.saleFk, TRUE, account.myUser_getId(), a.accion_id id, s.id + FROM vn.saleGroupDetail sgd + JOIN vncontrol.accion a ON a.accion = 'SACAR' + JOIN vn.state s ON s.code = 'PREPARED' + WHERE sgd.saleGroupFk = vSaleGroupFk; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -73795,31 +74517,31 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `saleTracking_addPrevOK`(vSectorCollectionFk INT) -BEGIN - - /** - * Inserta los registros de la colección de sector con el estado PREVIA OK - * - * @param vSectorCollectionFk Identificador de vn.sectorCollection - */ - - REPLACE vn.saleTracking(saleFk, - isChecked, - workerFk, - actionFk, - stateFk) - SELECT sgd.saleFk, - TRUE, - sc.userFk, - a.accion_id, - s.id - FROM vn.sectorCollection sc - JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id - JOIN vn.saleGroupDetail sgd ON sgd.saleGroupFk = scsg.saleGroupFk - JOIN vn.state s ON s.code = 'OK PREVIOUS' - JOIN vncontrol.accion a ON a.accion = 'PRESACAR' - WHERE sc.id = vSectorCollectionFk; - +BEGIN + + /** + * Inserta los registros de la colección de sector con el estado PREVIA OK + * + * @param vSectorCollectionFk Identificador de vn.sectorCollection + */ + + REPLACE vn.saleTracking(saleFk, + isChecked, + workerFk, + actionFk, + stateFk) + SELECT sgd.saleFk, + TRUE, + sc.userFk, + a.accion_id, + s.id + FROM vn.sectorCollection sc + JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id + JOIN vn.saleGroupDetail sgd ON sgd.saleGroupFk = scsg.saleGroupFk + JOIN vn.state s ON s.code = 'OK PREVIOUS' + JOIN vncontrol.accion a ON a.accion = 'PRESACAR' + WHERE sc.id = vSectorCollectionFk; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -74345,42 +75067,42 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_getForSijsner__`(vDated DATE) -BEGIN - - /** - * Devuelve el listado de ventas que tiene que etiquetar Sijsner para la fecha dada - * - * @param vDated Fecha de preparación de los tickets - */ - - SELECT b.printedStickers OR s.isPicked isPrinted, - t.shipped , - t.nickname , - s.ticketFk , - s.itemFk , - FLOOR(s.quantity / e.pac) stickers, - CONCAT(FLOOR(s.quantity / e.pac) , ' x ', e.pac ) amount, - s.concept, - e.kop, - e.sub, - sp.company_name supplier, - b.id buyFk - FROM vn.sale s - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN vn.warehouse w ON w.id = t.warehouseFk - 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.item i ON i.id = s.itemFk - JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND lb.warehouse_id = t.warehouseFk - JOIN vn.buy b ON b.id = lb.buy_id - LEFT JOIN edi.ekt e ON e.id = b.ektFk - LEFT JOIN edi.supplier sp ON sp.supplier_id = e.pro - WHERE t.shipped BETWEEN vDated AND TIMESTAMPADD(HOUR,23,vDated) - AND c.code != 'ES' - AND w.code IN ('FLM','VNH') - AND s.quantity ; - +BEGIN + + /** + * Devuelve el listado de ventas que tiene que etiquetar Sijsner para la fecha dada + * + * @param vDated Fecha de preparación de los tickets + */ + + SELECT b.printedStickers OR s.isPicked isPrinted, + t.shipped , + t.nickname , + s.ticketFk , + s.itemFk , + FLOOR(s.quantity / e.pac) stickers, + CONCAT(FLOOR(s.quantity / e.pac) , ' x ', e.pac ) amount, + s.concept, + e.kop, + e.sub, + sp.company_name supplier, + b.id buyFk + FROM vn.sale s + JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.warehouse w ON w.id = t.warehouseFk + 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.item i ON i.id = s.itemFk + JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND lb.warehouse_id = t.warehouseFk + JOIN vn.buy b ON b.id = lb.buy_id + LEFT JOIN edi.ekt e ON e.id = b.ektFk + LEFT JOIN edi.supplier sp ON sp.supplier_id = e.pro + WHERE t.shipped BETWEEN vDated AND TIMESTAMPADD(HOUR,23,vDated) + AND c.code != 'ES' + AND w.code IN ('FLM','VNH') + AND s.quantity ; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -74398,118 +75120,118 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_getFromTicketOrCollection`(vParam INT) -BEGIN -/* - * Visualizar lineas de la tabla sale a través del parámetro vParam que puede ser ticket o collection - * - * @param vParam Identificador de ticket o collection - */ - - DECLARE vItemPackingTypeFk VARCHAR(1); - DECLARE vIsCollection BOOL; - - SELECT COUNT(*) INTO vIsCollection - FROM collection c - WHERE c.id = vParam; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticket; - DROP TEMPORARY TABLE IF EXISTS tmp.ticket2; - - IF vIsCollection THEN - - CREATE TEMPORARY TABLE tmp.ticket - (INDEX (id)) - ENGINE = MEMORY - SELECT tc.ticketFk id - FROM ticketCollection tc - JOIN ticket t ON t.id = tc.ticketFk - WHERE tc.collectionFk = vParam; - - CREATE TEMPORARY TABLE tmp.ticket2 - (INDEX (id)) - ENGINE = MEMORY - SELECT tc.ticketFk id - FROM ticketCollection tc - JOIN ticket t ON t.id = tc.ticketFk - WHERE tc.collectionFk = vParam; - ELSE - CREATE TEMPORARY TABLE tmp.ticket - (INDEX (id)) - ENGINE = MEMORY - SELECT vParam id; - - CREATE TEMPORARY TABLE tmp.ticket2 - (INDEX (id)) - ENGINE = MEMORY - SELECT vParam id; - END IF; - - - - SELECT s.ticketFk, - sgd.saleGroupFk, - s.id as saleFk, - s.itemFk, - s.quantity, - i.longName, - i.size, - s.reserved, - MAX(IF(st.semaphore <=> 1, TRUE, FALSE)) as isPreviousPrepared, - MAX(IF(st.semaphore <=> 2, TRUE, FALSE)) as isPrepared, - MAX(IF(st.semaphore <=> 3, TRUE, FALSE)) as isControlled, - MAX(IF(st.semaphore <=> 4, TRUE, FALSE)) as isPreControlled, - ic.color, - ip.productor, - s.discount, - s.price, - i.stems, - i.category, - o.code origin, - tt.clientFk, - s.originalQuantity, - TRIM(CONCAT(LPAD(s.concept,30,' '), ' ', - RPAD(IFNULL(i.size,''),5,' '))) line1, - '' cel1, - TRIM(CONCAT(LPAD(IFNULL(ip.productor,''),30,' '), ' ',LPAD(IFNULL(o.code,''),4,' '))) line2, - IF(s.quantity MOD IFNULL(b.packing,s.quantity + 1), - CONCAT(CAST(s.quantity/IFNULL(b.`grouping`,1) AS DECIMAL(10,0)),' x ',IFNULL(b.`grouping`,1)), - CONCAT(CAST(s.quantity / IFNULL(b.packing,1) AS DECIMAL(10,0)),' pack de ',IFNULL(b.packing,1))) cel2, - TRIM(CONCAT(ic.color)) line3, - p.code cel3, - s.isAdded, - sub2.originalQuantity as startQuantity, -- eliminar cuando tengamos la nueva apk - IFNULL(c.workerFk,getUser()) as workerFk, - IFNULL(SUM(iss.quantity),0) as pickedQuantity, - i.packingShelve - FROM tmp.ticket t - JOIN sale s ON s.ticketFk = t.id - JOIN ticket tt ON tt.id = t.id - LEFT JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND lb.warehouse_id = tt.warehouseFk - LEFT JOIN buy b ON b.id = lb.buy_id - JOIN item i ON i.id = s.itemFk - LEFT JOIN ticketCollection tc ON tc.ticketFk = t.id - LEFT JOIN collection c ON c.id = tc.collectionFk - LEFT JOIN (SELECT sub.saleFk, sub.isChecked, sub.stateFk, sub.originalQuantity - FROM (SELECT DISTINCT st.id, st.saleFk, st.isChecked, st.stateFk, st.originalQuantity - FROM tmp.ticket2 t - JOIN sale s ON s.ticketFk = t.id - JOIN saleTracking st ON st.saleFk = s.id - ORDER BY st.id DESC) sub - GROUP BY sub.saleFk, sub.stateFK) sub2 ON sub2.saleFk = s.id AND sub2.isChecked = 1 - LEFT JOIN itemShelvingSale iss ON iss.saleFk = s.id - LEFT JOIN state st ON st.id = sub2.stateFk - LEFT JOIN itemColor ic ON ic.itemFk = s.itemFk - LEFT JOIN itemProductor ip ON ip.itemFk = s.itemFk - LEFT JOIN origin o ON o.id = i.originFk - LEFT JOIN saleGroupDetail sgd ON sgd.saleFk = s.id - LEFT JOIN saleGroup sg ON sg.id = sgd.saleGroupFk - LEFT JOIN parking p ON p.id = sg.parkingFk - GROUP BY s.id; - - - DROP TEMPORARY TABLE tmp.ticket; - DROP TEMPORARY TABLE tmp.ticket2; - +BEGIN +/* + * Visualizar lineas de la tabla sale a través del parámetro vParam que puede ser ticket o collection + * + * @param vParam Identificador de ticket o collection + */ + + DECLARE vItemPackingTypeFk VARCHAR(1); + DECLARE vIsCollection BOOL; + + SELECT COUNT(*) INTO vIsCollection + FROM collection c + WHERE c.id = vParam; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticket; + DROP TEMPORARY TABLE IF EXISTS tmp.ticket2; + + IF vIsCollection THEN + + CREATE TEMPORARY TABLE tmp.ticket + (INDEX (id)) + ENGINE = MEMORY + SELECT tc.ticketFk id + FROM ticketCollection tc + JOIN ticket t ON t.id = tc.ticketFk + WHERE tc.collectionFk = vParam; + + CREATE TEMPORARY TABLE tmp.ticket2 + (INDEX (id)) + ENGINE = MEMORY + SELECT tc.ticketFk id + FROM ticketCollection tc + JOIN ticket t ON t.id = tc.ticketFk + WHERE tc.collectionFk = vParam; + ELSE + CREATE TEMPORARY TABLE tmp.ticket + (INDEX (id)) + ENGINE = MEMORY + SELECT vParam id; + + CREATE TEMPORARY TABLE tmp.ticket2 + (INDEX (id)) + ENGINE = MEMORY + SELECT vParam id; + END IF; + + + + SELECT s.ticketFk, + sgd.saleGroupFk, + s.id as saleFk, + s.itemFk, + s.quantity, + i.longName, + i.size, + s.reserved, + MAX(IF(st.semaphore <=> 1, TRUE, FALSE)) as isPreviousPrepared, + MAX(IF(st.semaphore <=> 2, TRUE, FALSE)) as isPrepared, + MAX(IF(st.semaphore <=> 3, TRUE, FALSE)) as isControlled, + MAX(IF(st.semaphore <=> 4, TRUE, FALSE)) as isPreControlled, + ic.color, + ip.productor, + s.discount, + s.price, + i.stems, + i.category, + o.code origin, + tt.clientFk, + s.originalQuantity, + TRIM(CONCAT(LPAD(s.concept,30,' '), ' ', + RPAD(IFNULL(i.size,''),5,' '))) line1, + '' cel1, + TRIM(CONCAT(LPAD(IFNULL(ip.productor,''),30,' '), ' ',LPAD(IFNULL(o.code,''),4,' '))) line2, + IF(s.quantity MOD IFNULL(b.packing,s.quantity + 1), + CONCAT(CAST(s.quantity/IFNULL(b.`grouping`,1) AS DECIMAL(10,0)),' x ',IFNULL(b.`grouping`,1)), + CONCAT(CAST(s.quantity / IFNULL(b.packing,1) AS DECIMAL(10,0)),' pack de ',IFNULL(b.packing,1))) cel2, + TRIM(CONCAT(ic.color)) line3, + p.code cel3, + s.isAdded, + sub2.originalQuantity as startQuantity, -- eliminar cuando tengamos la nueva apk + IFNULL(c.workerFk,getUser()) as workerFk, + IFNULL(SUM(iss.quantity),0) as pickedQuantity, + i.packingShelve + FROM tmp.ticket t + JOIN sale s ON s.ticketFk = t.id + JOIN ticket tt ON tt.id = t.id + LEFT JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND lb.warehouse_id = tt.warehouseFk + LEFT JOIN buy b ON b.id = lb.buy_id + JOIN item i ON i.id = s.itemFk + LEFT JOIN ticketCollection tc ON tc.ticketFk = t.id + LEFT JOIN collection c ON c.id = tc.collectionFk + LEFT JOIN (SELECT sub.saleFk, sub.isChecked, sub.stateFk, sub.originalQuantity + FROM (SELECT DISTINCT st.id, st.saleFk, st.isChecked, st.stateFk, st.originalQuantity + FROM tmp.ticket2 t + JOIN sale s ON s.ticketFk = t.id + JOIN saleTracking st ON st.saleFk = s.id + ORDER BY st.id DESC) sub + GROUP BY sub.saleFk, sub.stateFK) sub2 ON sub2.saleFk = s.id AND sub2.isChecked = 1 + LEFT JOIN itemShelvingSale iss ON iss.saleFk = s.id + LEFT JOIN state st ON st.id = sub2.stateFk + LEFT JOIN itemColor ic ON ic.itemFk = s.itemFk + LEFT JOIN itemProductor ip ON ip.itemFk = s.itemFk + LEFT JOIN origin o ON o.id = i.originFk + LEFT JOIN saleGroupDetail sgd ON sgd.saleFk = s.id + LEFT JOIN saleGroup sg ON sg.id = sgd.saleGroupFk + LEFT JOIN parking p ON p.id = sg.parkingFk + GROUP BY s.id; + + + DROP TEMPORARY TABLE tmp.ticket; + DROP TEMPORARY TABLE tmp.ticket2; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -74527,211 +75249,211 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_getProblems`(IN vIsTodayRelative tinyint(1)) -BEGIN -/** - * Calcula los problemas de cada venta - * para un conjunto de tickets. - * - * @table tmp.sale_getProblems(ticketFk, clientFk, warehouseFk, shipped) Identificadores de los tickets a calcular - * @return tmp.sale_problems - */ - DECLARE vWarehouse INT; - DECLARE vDate DATE; - DECLARE vAvailableCache INT; - DECLARE vDone INT DEFAULT 0; - DECLARE vComponentCount INT; - - DECLARE vCursor CURSOR FOR - SELECT DISTINCT tt.warehouseFk, IF(vIsTodayRelative, CURDATE(), date(tt.shipped)) - FROM tmp.sale_getProblems tt - WHERE DATE(tt.shipped) BETWEEN CURDATE() - AND TIMESTAMPADD(DAY, IF(vIsTodayRelative, 9.9, 1.9), CURDATE()); - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = 1; - - DROP TEMPORARY TABLE IF EXISTS tmp.sale_problems; - CREATE TEMPORARY TABLE tmp.sale_problems ( - ticketFk INT(11), - saleFk INT(11), - isFreezed INTEGER(1) DEFAULT 0, - risk DECIMAL(10,2) DEFAULT 0, - hasHighRisk TINYINT(1) DEFAULT 0, - hasTicketRequest INTEGER(1) DEFAULT 0, - isAvailable INTEGER(1) DEFAULT 1, - itemShortage VARCHAR(250), - isTaxDataChecked INTEGER(1) DEFAULT 1, - itemDelay VARCHAR(250), - hasComponentLack INTEGER(1), - isTooLittle BOOL DEFAULT FALSE, - PRIMARY KEY (ticketFk, saleFk) - ) ENGINE = MEMORY; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; - CREATE TEMPORARY TABLE tmp.ticket_list - (PRIMARY KEY (ticketFk)) - ENGINE = MEMORY - SELECT tp.ticketFk, c.id clientFk - FROM tmp.sale_getProblems tp - JOIN vn.client c ON c.id = tp.clientFk; - - SELECT COUNT(*) INTO vComponentCount - FROM vn.component c - WHERE c.isRequired; - - INSERT INTO tmp.sale_problems(ticketFk, isTooLittle) - SELECT sub.ticketFk, TRUE - FROM (SELECT tl.ticketFk, SUM(sv.litros) litros, t.totalWithoutVat - FROM tmp.ticket_list tl - JOIN vn.saleVolume sv ON sv.ticketFk = tl.ticketFk - JOIN vn.ticket t ON t.id = tl.ticketFk - JOIN vn.zoneClosure zc ON zc.zoneFk = t.zoneFk AND zc.dated = CURDATE() - WHERE NOW() < TIMESTAMPADD(MINUTE,MINUTE(zc.`hour`) ,TIMESTAMPADD(HOUR,HOUR(zc.`hour`),CURDATE())) - GROUP BY tl.ticketFk) sub - JOIN vn.volumeConfig vc - WHERE sub.litros < vc.minTicketVolume - AND sub.totalWithoutVat < vc.minTicketValue; - - INSERT INTO tmp.sale_problems(ticketFk, hasComponentLack, saleFk) - SELECT tl.ticketFk, (COUNT(DISTINCT s.id) * vComponentCount > COUNT(c.id)), s.id - FROM tmp.ticket_list tl - JOIN vn.sale s ON s.ticketFk = tl.ticketFk - LEFT JOIN vn.saleComponent sc ON sc.saleFk = s.id - LEFT JOIN vn.component c ON c.id = sc.componentFk AND c.isRequired - JOIN vn.ticket t ON t.id = tl.ticketFk - JOIN vn.agencyMode am ON am.id = t.agencyModeFk - JOIN vn.deliveryMethod dm ON dm.id = am.deliveryMethodFk - WHERE dm.code IN('AGENCY','DELIVERY','PICKUP') - GROUP BY tl.ticketFk, s.id; - - INSERT INTO tmp.sale_problems(ticketFk, isFreezed) - SELECT DISTINCT tl.ticketFk, TRUE - FROM tmp.ticket_list tl - JOIN vn.client c ON c.id = tl.clientFk - WHERE c.isFreezed - ON DUPLICATE KEY UPDATE - isFreezed = c.isFreezed; - - DROP TEMPORARY TABLE IF EXISTS tmp.clientGetDebt; - CREATE TEMPORARY TABLE tmp.clientGetDebt - (PRIMARY KEY (clientFk)) - ENGINE = MEMORY - SELECT DISTINCT clientFk - FROM tmp.ticket_list; - - CALL clientGetDebt(CURDATE()); - - INSERT INTO tmp.sale_problems(ticketFk, risk, hasHighRisk) - SELECT DISTINCT tl.ticketFk, r.risk, ((r.risk - cc.riskTolerance) > c.credit + 10) - FROM tmp.ticket_list tl - JOIN vn.ticket t ON t.id = tl.ticketFk - JOIN vn.agencyMode a ON t.agencyModeFk = a.id - JOIN tmp.risk r ON r.clientFk = t.clientFk - JOIN vn.client c ON c.id = t.clientFk - JOIN vn.clientConfig cc - WHERE r.risk > c.credit + 10 - AND a.isRiskFree = FALSE - ON DUPLICATE KEY UPDATE - risk = r.risk, hasHighRisk = ((r.risk - cc.riskTolerance) > c.credit + 10); - - INSERT INTO tmp.sale_problems(ticketFk, hasTicketRequest) - SELECT DISTINCT tl.ticketFk, TRUE - FROM tmp.ticket_list tl - JOIN vn.ticketRequest tr ON tr.ticketFk = tl.ticketFk - WHERE tr.isOK IS NULL - ON DUPLICATE KEY UPDATE - hasTicketRequest = TRUE; - - OPEN vCursor; - - WHILE NOT vDone - DO - FETCH vCursor INTO vWarehouse, vDate; - - CALL cache.available_refresh(vAvailableCache, FALSE, vWarehouse, vDate); - - INSERT INTO tmp.sale_problems(ticketFk, isAvailable, saleFk) - SELECT tl.ticketFk, FALSE, s.id - FROM tmp.ticket_list tl - JOIN vn.ticket t ON t.id = tl.ticketFk - JOIN vn.sale s ON s.ticketFk = t.id - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.itemType it on it.id = i.typeFk - LEFT JOIN cache.available av ON av.item_id = i.id - AND av.calc_id = vAvailableCache - WHERE date(t.shipped) = vDate - AND it.categoryFk != 6 - AND IFNULL(av.available, 0) < 0 - AND s.isPicked = FALSE - AND NOT i.generic - AND vWarehouse = t.warehouseFk - GROUP BY tl.ticketFk - ON DUPLICATE KEY UPDATE - isAvailable = FALSE, saleFk = VALUES(saleFk); - - INSERT INTO tmp.sale_problems(ticketFk, itemShortage, saleFk) - SELECT ticketFk, problem, saleFk - FROM ( - SELECT tl.ticketFk, CONCAT('F: ',GROUP_CONCAT(i.id, ' ', i.longName, ' ')) problem, s.id AS saleFk - FROM tmp.ticket_list tl - JOIN vn.ticket t ON t.id = tl.ticketFk - JOIN vn.sale s ON s.ticketFk = t.id - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.itemType it on it.id = i.typeFk - LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk - LEFT JOIN cache.available av ON av.item_id = i.id AND av.calc_id = vAvailableCache - WHERE IFNULL(av.available, 0) <= 0 - AND s.quantity > IFNULL(issw.visible, 0) - AND s.quantity > 0 - AND s.isPicked = FALSE - AND s.reserved = FALSE - AND it.categoryFk != 6 - AND IF(vIsTodayRelative, TRUE, date(t.shipped) = vDate) - AND NOT i.generic - AND CURDATE() = vDate - AND t.warehouseFk = vWarehouse - GROUP BY tl.ticketFk) sub - ON DUPLICATE KEY UPDATE - itemShortage = sub.problem, saleFk = sub.saleFk; - - INSERT INTO tmp.sale_problems(ticketFk, itemDelay, saleFk) - SELECT ticketFk, problem, saleFk - FROM ( - SELECT tl.ticketFk, GROUP_CONCAT('I: ',i.id, ' ', i.longName, ' ') problem, s.id AS saleFk - FROM tmp.ticket_list tl - JOIN vn.ticket t ON t.id = tl.ticketFk - JOIN vn.sale s ON s.ticketFk = t.id - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.itemType it on it.id = i.typeFk - LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk - LEFT JOIN cache.available av ON av.item_id = i.id AND av.calc_id = vAvailableCache - WHERE IFNULL(av.available, 0) >= s.quantity - AND s.quantity > IFNULL(issw.visible, 0) - AND s.quantity > 0 - AND s.isPicked = FALSE - AND s.reserved = FALSE - AND it.categoryFk != 6 - AND IF(vIsTodayRelative, TRUE, date(t.shipped) = vDate) - AND NOT i.generic - AND CURDATE() = vDate - AND t.warehouseFk = vWarehouse - GROUP BY tl.ticketFk) sub - ON DUPLICATE KEY UPDATE - itemDelay = sub.problem, saleFk = sub.saleFk; - END WHILE; - - CLOSE vCursor; - - INSERT INTO tmp.sale_problems(ticketFk, isTaxDataChecked) - SELECT DISTINCT tl.ticketFk, FALSE - FROM tmp.ticket_list tl - JOIN vn.client c ON c.id = tl.clientFk - WHERE c.isTaxDataChecked = FALSE - ON DUPLICATE KEY UPDATE - isTaxDataChecked = FALSE; - - DROP TEMPORARY TABLE - tmp.clientGetDebt, - tmp.ticket_list; +BEGIN +/** + * Calcula los problemas de cada venta + * para un conjunto de tickets. + * + * @table tmp.sale_getProblems(ticketFk, clientFk, warehouseFk, shipped) Identificadores de los tickets a calcular + * @return tmp.sale_problems + */ + DECLARE vWarehouse INT; + DECLARE vDate DATE; + DECLARE vAvailableCache INT; + DECLARE vDone INT DEFAULT 0; + DECLARE vComponentCount INT; + + DECLARE vCursor CURSOR FOR + SELECT DISTINCT tt.warehouseFk, IF(vIsTodayRelative, CURDATE(), date(tt.shipped)) + FROM tmp.sale_getProblems tt + WHERE DATE(tt.shipped) BETWEEN CURDATE() + AND TIMESTAMPADD(DAY, IF(vIsTodayRelative, 9.9, 1.9), CURDATE()); + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = 1; + + DROP TEMPORARY TABLE IF EXISTS tmp.sale_problems; + CREATE TEMPORARY TABLE tmp.sale_problems ( + ticketFk INT(11), + saleFk INT(11), + isFreezed INTEGER(1) DEFAULT 0, + risk DECIMAL(10,2) DEFAULT 0, + hasHighRisk TINYINT(1) DEFAULT 0, + hasTicketRequest INTEGER(1) DEFAULT 0, + isAvailable INTEGER(1) DEFAULT 1, + itemShortage VARCHAR(250), + isTaxDataChecked INTEGER(1) DEFAULT 1, + itemDelay VARCHAR(250), + hasComponentLack INTEGER(1), + isTooLittle BOOL DEFAULT FALSE, + PRIMARY KEY (ticketFk, saleFk) + ) ENGINE = MEMORY; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; + CREATE TEMPORARY TABLE tmp.ticket_list + (PRIMARY KEY (ticketFk)) + ENGINE = MEMORY + SELECT tp.ticketFk, c.id clientFk + FROM tmp.sale_getProblems tp + JOIN vn.client c ON c.id = tp.clientFk; + + SELECT COUNT(*) INTO vComponentCount + FROM vn.component c + WHERE c.isRequired; + + INSERT INTO tmp.sale_problems(ticketFk, isTooLittle) + SELECT sub.ticketFk, TRUE + FROM (SELECT tl.ticketFk, SUM(sv.litros) litros, t.totalWithoutVat + FROM tmp.ticket_list tl + JOIN vn.saleVolume sv ON sv.ticketFk = tl.ticketFk + JOIN vn.ticket t ON t.id = tl.ticketFk + JOIN vn.zoneClosure zc ON zc.zoneFk = t.zoneFk AND zc.dated = CURDATE() + WHERE NOW() < TIMESTAMPADD(MINUTE,MINUTE(zc.`hour`) ,TIMESTAMPADD(HOUR,HOUR(zc.`hour`),CURDATE())) + GROUP BY tl.ticketFk) sub + JOIN vn.volumeConfig vc + WHERE sub.litros < vc.minTicketVolume + AND sub.totalWithoutVat < vc.minTicketValue; + + INSERT INTO tmp.sale_problems(ticketFk, hasComponentLack, saleFk) + SELECT tl.ticketFk, (COUNT(DISTINCT s.id) * vComponentCount > COUNT(c.id)), s.id + FROM tmp.ticket_list tl + JOIN vn.sale s ON s.ticketFk = tl.ticketFk + LEFT JOIN vn.saleComponent sc ON sc.saleFk = s.id + LEFT JOIN vn.component c ON c.id = sc.componentFk AND c.isRequired + JOIN vn.ticket t ON t.id = tl.ticketFk + JOIN vn.agencyMode am ON am.id = t.agencyModeFk + JOIN vn.deliveryMethod dm ON dm.id = am.deliveryMethodFk + WHERE dm.code IN('AGENCY','DELIVERY','PICKUP') + GROUP BY tl.ticketFk, s.id; + + INSERT INTO tmp.sale_problems(ticketFk, isFreezed) + SELECT DISTINCT tl.ticketFk, TRUE + FROM tmp.ticket_list tl + JOIN vn.client c ON c.id = tl.clientFk + WHERE c.isFreezed + ON DUPLICATE KEY UPDATE + isFreezed = c.isFreezed; + + DROP TEMPORARY TABLE IF EXISTS tmp.clientGetDebt; + CREATE TEMPORARY TABLE tmp.clientGetDebt + (PRIMARY KEY (clientFk)) + ENGINE = MEMORY + SELECT DISTINCT clientFk + FROM tmp.ticket_list; + + CALL clientGetDebt(CURDATE()); + + INSERT INTO tmp.sale_problems(ticketFk, risk, hasHighRisk) + SELECT DISTINCT tl.ticketFk, r.risk, ((r.risk - cc.riskTolerance) > c.credit + 10) + FROM tmp.ticket_list tl + JOIN vn.ticket t ON t.id = tl.ticketFk + JOIN vn.agencyMode a ON t.agencyModeFk = a.id + JOIN tmp.risk r ON r.clientFk = t.clientFk + JOIN vn.client c ON c.id = t.clientFk + JOIN vn.clientConfig cc + WHERE r.risk > c.credit + 10 + AND a.isRiskFree = FALSE + ON DUPLICATE KEY UPDATE + risk = r.risk, hasHighRisk = ((r.risk - cc.riskTolerance) > c.credit + 10); + + INSERT INTO tmp.sale_problems(ticketFk, hasTicketRequest) + SELECT DISTINCT tl.ticketFk, TRUE + FROM tmp.ticket_list tl + JOIN vn.ticketRequest tr ON tr.ticketFk = tl.ticketFk + WHERE tr.isOK IS NULL + ON DUPLICATE KEY UPDATE + hasTicketRequest = TRUE; + + OPEN vCursor; + + WHILE NOT vDone + DO + FETCH vCursor INTO vWarehouse, vDate; + + CALL cache.available_refresh(vAvailableCache, FALSE, vWarehouse, vDate); + + INSERT INTO tmp.sale_problems(ticketFk, isAvailable, saleFk) + SELECT tl.ticketFk, FALSE, s.id + FROM tmp.ticket_list tl + JOIN vn.ticket t ON t.id = tl.ticketFk + JOIN vn.sale s ON s.ticketFk = t.id + JOIN vn.item i ON i.id = s.itemFk + JOIN vn.itemType it on it.id = i.typeFk + LEFT JOIN cache.available av ON av.item_id = i.id + AND av.calc_id = vAvailableCache + WHERE date(t.shipped) = vDate + AND it.categoryFk != 6 + AND IFNULL(av.available, 0) < 0 + AND s.isPicked = FALSE + AND NOT i.generic + AND vWarehouse = t.warehouseFk + GROUP BY tl.ticketFk + ON DUPLICATE KEY UPDATE + isAvailable = FALSE, saleFk = VALUES(saleFk); + + INSERT INTO tmp.sale_problems(ticketFk, itemShortage, saleFk) + SELECT ticketFk, problem, saleFk + FROM ( + SELECT tl.ticketFk, CONCAT('F: ',GROUP_CONCAT(i.id, ' ', i.longName, ' ')) problem, s.id AS saleFk + FROM tmp.ticket_list tl + JOIN vn.ticket t ON t.id = tl.ticketFk + JOIN vn.sale s ON s.ticketFk = t.id + JOIN vn.item i ON i.id = s.itemFk + JOIN vn.itemType it on it.id = i.typeFk + LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk + LEFT JOIN cache.available av ON av.item_id = i.id AND av.calc_id = vAvailableCache + WHERE IFNULL(av.available, 0) <= 0 + AND s.quantity > IFNULL(issw.visible, 0) + AND s.quantity > 0 + AND s.isPicked = FALSE + AND s.reserved = FALSE + AND it.categoryFk != 6 + AND IF(vIsTodayRelative, TRUE, date(t.shipped) = vDate) + AND NOT i.generic + AND CURDATE() = vDate + AND t.warehouseFk = vWarehouse + GROUP BY tl.ticketFk) sub + ON DUPLICATE KEY UPDATE + itemShortage = sub.problem, saleFk = sub.saleFk; + + INSERT INTO tmp.sale_problems(ticketFk, itemDelay, saleFk) + SELECT ticketFk, problem, saleFk + FROM ( + SELECT tl.ticketFk, GROUP_CONCAT('I: ',i.id, ' ', i.longName, ' ') problem, s.id AS saleFk + FROM tmp.ticket_list tl + JOIN vn.ticket t ON t.id = tl.ticketFk + JOIN vn.sale s ON s.ticketFk = t.id + JOIN vn.item i ON i.id = s.itemFk + JOIN vn.itemType it on it.id = i.typeFk + LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk + LEFT JOIN cache.available av ON av.item_id = i.id AND av.calc_id = vAvailableCache + WHERE IFNULL(av.available, 0) >= s.quantity + AND s.quantity > IFNULL(issw.visible, 0) + AND s.quantity > 0 + AND s.isPicked = FALSE + AND s.reserved = FALSE + AND it.categoryFk != 6 + AND IF(vIsTodayRelative, TRUE, date(t.shipped) = vDate) + AND NOT i.generic + AND CURDATE() = vDate + AND t.warehouseFk = vWarehouse + GROUP BY tl.ticketFk) sub + ON DUPLICATE KEY UPDATE + itemDelay = sub.problem, saleFk = sub.saleFk; + END WHILE; + + CLOSE vCursor; + + INSERT INTO tmp.sale_problems(ticketFk, isTaxDataChecked) + SELECT DISTINCT tl.ticketFk, FALSE + FROM tmp.ticket_list tl + JOIN vn.client c ON c.id = tl.clientFk + WHERE c.isTaxDataChecked = FALSE + ON DUPLICATE KEY UPDATE + isTaxDataChecked = FALSE; + + DROP TEMPORARY TABLE + tmp.clientGetDebt, + tmp.ticket_list; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -75007,24 +75729,24 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_PriceFix`(vTicketFk INT) -BEGIN - - DELETE sc.* - FROM vn.saleComponent sc - JOIN vn.sale s ON s.id = sc.saleFk - JOIN vn.component c ON c.id = sc.componentFk - JOIN vn.componentType ct ON ct.id = c.typeFk - WHERE s.ticketFk = vTicketFk - AND ct.`type` = 'otros'; - - UPDATE vn.sale s - JOIN ( - SELECT sc.saleFk, sum(sc.value ) price - FROM vn.saleComponent sc - JOIN vn.sale s ON s.id = sc.saleFk - WHERE s.ticketFk = vTicketFk - GROUP BY sc.saleFk) sub ON sub.saleFk = s.id - SET s.price = sub.price; +BEGIN + + DELETE sc.* + FROM vn.saleComponent sc + JOIN vn.sale s ON s.id = sc.saleFk + JOIN vn.component c ON c.id = sc.componentFk + JOIN vn.componentType ct ON ct.id = c.typeFk + WHERE s.ticketFk = vTicketFk + AND ct.`type` = 'otros'; + + UPDATE vn.sale s + JOIN ( + SELECT sc.saleFk, sum(sc.value ) price + FROM vn.saleComponent sc + JOIN vn.sale s ON s.id = sc.saleFk + WHERE s.ticketFk = vTicketFk + GROUP BY sc.saleFk) sub ON sub.saleFk = s.id + SET s.price = sub.price; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -75171,31 +75893,31 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_setQuantity`(vSaleFk INT, vQuantity INT) -BEGIN -/* - * Actualiza la cantidad de la línea de venta - * - * @vSaleFk id de la línea de venta - * @vQuantity cantidad a modificar - * - */ - - DECLARE vDescription VARCHAR(100); - DECLARE vOrigin INT; - - SELECT CONCAT("Cambio cantidad ",concept," de ", quantity," a ", vQuantity) INTO vDescription - FROM sale - WHERE id = vSaleFk; - - SELECT ticketFk INTO vOrigin FROM sale WHERE id = vSaleFk; - - CALL logAdd(vOrigin, 'update', 'ticket', vDescription); - - UPDATE sale - SET originalQuantity = quantity, - quantity = vQuantity - WHERE id = vSaleFk; - +BEGIN +/* + * Actualiza la cantidad de la línea de venta + * + * @vSaleFk id de la línea de venta + * @vQuantity cantidad a modificar + * + */ + + DECLARE vDescription VARCHAR(100); + DECLARE vOrigin INT; + + SELECT CONCAT("Cambio cantidad ",concept," de ", quantity," a ", vQuantity) INTO vDescription + FROM sale + WHERE id = vSaleFk; + + SELECT ticketFk INTO vOrigin FROM sale WHERE id = vSaleFk; + + CALL logAdd(vOrigin, 'update', 'ticket', vDescription); + + UPDATE sale + SET originalQuantity = quantity, + quantity = vQuantity + WHERE id = vSaleFk; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -75260,33 +75982,33 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `scanTreeCreate__`() -BEGIN - CALL nestTree( - 'vn2008', - 'scan', - 'vn2008', - 'scanTree' - ); - - UPDATE vn2008.scanTree st - JOIN ( - SELECT sl.scan_id, - MAX(sl.odbc_date) lastScanned, - COUNT(DISTINCT t.routeFk) routeCount, - MIN(t.routeFk) mod 1000 as minRoute, - MAX(t.routeFk) mod 1000 as maxRoute, - COUNT(sl.scan_line_id) as scanned - FROM vn2008.scan_line sl - JOIN expedition e ON e.id = sl.`code` - JOIN ticket t ON t.id = e.ticketFk - WHERE t.routeFk - GROUP BY sl.scan_id - ) rs ON rs.scan_id = st.id - SET st.lastScanned = rs.lastScanned, - st.routeCount = rs.routeCount, - st.minRoute = rs.minRoute, - st.maxRoute = IF(rs.minRoute != rs.maxRoute, rs.maxRoute,NULL), - st.scanned = rs.scanned; +BEGIN + CALL nestTree( + 'vn2008', + 'scan', + 'vn2008', + 'scanTree' + ); + + UPDATE vn2008.scanTree st + JOIN ( + SELECT sl.scan_id, + MAX(sl.odbc_date) lastScanned, + COUNT(DISTINCT t.routeFk) routeCount, + MIN(t.routeFk) mod 1000 as minRoute, + MAX(t.routeFk) mod 1000 as maxRoute, + COUNT(sl.scan_line_id) as scanned + FROM vn2008.scan_line sl + JOIN expedition e ON e.id = sl.`code` + JOIN ticket t ON t.id = e.ticketFk + WHERE t.routeFk + GROUP BY sl.scan_id + ) rs ON rs.scan_id = st.id + SET st.lastScanned = rs.lastScanned, + st.routeCount = rs.routeCount, + st.minRoute = rs.minRoute, + st.maxRoute = IF(rs.minRoute != rs.maxRoute, rs.maxRoute,NULL), + st.scanned = rs.scanned; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -75356,31 +76078,33 @@ 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`@`localhost` PROCEDURE `sectorCollection_get`(vSectorFk INT) -BEGIN - - /** - * Devuelve las colecciones del sector que corresponden al usuario conectado, y que estan incompletas - * - * @param vSectorFk Identificador de vn.sector - */ - - SELECT DISTINCT sc.id collectionFk, sc.created - FROM vn.sectorCollection sc - JOIN vn.state s ON s.code = 'PREVIOUS_PREPARATION' - LEFT JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id - LEFT JOIN vn.saleGroupDetail sgd ON sgd.saleGroupFk = scsg.saleGroupFk - LEFT JOIN vn.saleTracking st ON st.saleFk = sgd.saleFk AND st.stateFk = s.id AND st.workerFk = sc.userFk - WHERE sc.userFk = account.myUser_getId() - AND (ISNULL(scsg.sectorCollectionFk) - OR NOT st.isChecked); - +BEGIN + + /** + * Devuelve las colecciones del sector que corresponden al usuario conectado, y que estan incompletas + * + * @param vSectorFk Identificador de vn.sector + */ + + SELECT DISTINCT sc.id collectionFk, sc.created + FROM vn.sectorCollection sc + JOIN vn.state s ON s.code = 'PREVIOUS_PREPARATION' + LEFT JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id + LEFT JOIN vn.saleGroupDetail sgd ON sgd.saleGroupFk = scsg.saleGroupFk + LEFT JOIN vn.saleTracking st ON st.saleFk = sgd.saleFk AND st.stateFk = s.id AND st.workerFk = sc.userFk + LEFT JOIN vn.sale sl ON sl.id = st.saleFk + WHERE sc.userFk = account.myUser_getId() + AND (ISNULL(scsg.sectorCollectionFk) + OR + (NOT st.isChecked AND sl.quantity > 0)); + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -75398,36 +76122,36 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sectorCollection_getSale`(vSelf INT) -BEGIN - - /** - * Devuelve las lineas de venta correspondientes a esa coleccion de sector - * - * @param vSelf Identificador de vn.sectorCollection - */ - - SELECT s.ticketFk, - s.itemFk, - i.longName, - IFNULL(i.itemPackingTypeFk,' ') itemPackingTypeFk, - IFNULL(i.subName ,' ') subName, - s.quantity, - w.code workerCode, - sgd.saleFk, - IFNULL(iss.quantity,0) pickedQuantity, - c.salesPersonFk - FROM vn.sale s - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.saleGroupDetail sgd ON sgd.saleFk = s.id - JOIN vn.sectorCollectionSaleGroup scsg ON scsg.saleGroupFk = sgd.saleGroupFk - JOIN vn.saleTracking st ON st.saleFk = s.id - JOIN vn.state stt ON stt.id = st.stateFk AND stt.code = 'PREVIOUS_PREPARATION' - JOIN vn.worker w ON w.id = st.workerFk - JOIN vn.ticket t ON t.id= s.ticketFk - JOIN vn.client c ON c.id=t.clientFk - LEFT JOIN vn.itemShelvingSaleSum iss ON iss.saleFk = s.id - WHERE scsg.sectorCollectionFk = vSelf; - +BEGIN + + /** + * Devuelve las lineas de venta correspondientes a esa coleccion de sector + * + * @param vSelf Identificador de vn.sectorCollection + */ + + SELECT s.ticketFk, + s.itemFk, + i.longName, + IFNULL(i.itemPackingTypeFk,' ') itemPackingTypeFk, + IFNULL(i.subName ,' ') subName, + s.quantity, + w.code workerCode, + sgd.saleFk, + IFNULL(iss.quantity,0) pickedQuantity, + c.salesPersonFk + FROM vn.sale s + JOIN vn.item i ON i.id = s.itemFk + JOIN vn.saleGroupDetail sgd ON sgd.saleFk = s.id + JOIN vn.sectorCollectionSaleGroup scsg ON scsg.saleGroupFk = sgd.saleGroupFk + JOIN vn.saleTracking st ON st.saleFk = s.id + JOIN vn.state stt ON stt.id = st.stateFk AND stt.code = 'PREVIOUS_PREPARATION' + JOIN vn.worker w ON w.id = st.workerFk + JOIN vn.ticket t ON t.id= s.ticketFk + JOIN vn.client c ON c.id=t.clientFk + LEFT JOIN vn.itemShelvingSaleSum iss ON iss.saleFk = s.id + WHERE scsg.sectorCollectionFk = vSelf; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -75445,33 +76169,33 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sectorCollection_new`(vSectorFk INT) -BEGIN - - /** - * Inserta una nueva colección, si el usuario no tiene ninguna vacia. - * Esto se hace para evitar que por error se generen colecciones sin sentido. - * - * @param vSectorFk Identificador de vn.sector - */ - - DECLARE hasEmptyCollections BOOLEAN; - DECLARE vUserFk INT; - - SET vUserFk = account.myUser_getId(); - - SELECT (COUNT(sc.id) > 0) INTO hasEmptyCollections - FROM vn.sectorCollection sc - LEFT JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id - WHERE ISNULL(scsg.id) - AND sc.userFk = vUserFk - AND sc.sectorFk = vSectorFk; - - IF NOT hasEmptyCollections THEN - - INSERT INTO vn.sectorCollection(userFk, sectorFk) - VALUES(vUserFk, vSectorFk); - END IF; - +BEGIN + + /** + * Inserta una nueva colección, si el usuario no tiene ninguna vacia. + * Esto se hace para evitar que por error se generen colecciones sin sentido. + * + * @param vSectorFk Identificador de vn.sector + */ + + DECLARE hasEmptyCollections BOOLEAN; + DECLARE vUserFk INT; + + SET vUserFk = account.myUser_getId(); + + SELECT (COUNT(sc.id) > 0) INTO hasEmptyCollections + FROM vn.sectorCollection sc + LEFT JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id + WHERE ISNULL(scsg.id) + AND sc.userFk = vUserFk + AND sc.sectorFk = vSectorFk; + + IF NOT hasEmptyCollections THEN + + INSERT INTO vn.sectorCollection(userFk, sectorFk) + VALUES(vUserFk, vSectorFk); + END IF; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -76207,11 +76931,11 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET character_set_client = 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 = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `shelving_clean`() BEGIN @@ -76220,24 +76944,25 @@ BEGIN WHERE length(code) > 3 AND parked < TIMESTAMPADD(WEEK,-1,CURDATE()); - DELETE FROM vn.itemShelving + DELETE FROM vn.itemShelving WHERE visible <= 0 - AND created < TIMESTAMPADD(MONTH,-1,CURDATE()); - - DELETE ish.* + AND created < TIMESTAMPADD(MONTH,-1,CURDATE()); + + DELETE ish.* FROM vn.itemShelving ish JOIN vn.shelving sh ON sh.code = ish.shelvingFk - WHERE sh.parkingFk IS NULL - AND ish.created < TIMESTAMPADD(WEEK,-1,CURDATE()); + WHERE sh.parkingFk IS NULL + AND ish.created < TIMESTAMPADD(WEEK,-1,CURDATE()); UPDATE vn.shelving sh LEFT JOIN vn.itemShelving its ON its.shelvingFk = sh.`code` SET isPrinted = 0, parkingFk = NULL - WHERE its.id IS NULL - AND ( sh.parked IS NULL + WHERE its.id IS NULL + AND sh.isRecyclable + AND ( sh.parked IS NULL OR - sh.parked < TIMESTAMPADD(MONTH,-1,CURDATE()) + sh.parked < TIMESTAMPADD(MONTH,-1,CURDATE()) ); END ;; @@ -76257,88 +76982,88 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` 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; - +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 */ ; @@ -78255,19 +78980,19 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketCollection_setUsedShelves`(vTicketFk INT, vUsedShelves INT) -BEGIN - - /* - * Inserta número de baldas que ocupa un ticket - * - * @param vTicketFk Identificador de ticket - * @param vUsedShelves Número de baldas - */ - - UPDATE ticketCollection tc - SET tc.usedShelves = vUsedShelves - WHERE tc.ticketFk = vTicketFk; - +BEGIN + + /* + * Inserta número de baldas que ocupa un ticket + * + * @param vTicketFk Identificador de ticket + * @param vUsedShelves Número de baldas + */ + + UPDATE ticketCollection tc + SET tc.usedShelves = vUsedShelves + WHERE tc.ticketFk = vTicketFk; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -79419,25 +80144,25 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketManaToPromo`(vTicketFk INT) -BEGIN - - DECLARE vManaComponent INT; - - DECLARE vPromoComponent INT; - - SELECT id INTO vManaComponent - FROM vn.component c - WHERE c.code = 'mana'; - - SELECT id INTO vPromoComponent - FROM vn.component c - WHERE c.code = 'floramondoPromo'; - - UPDATE vn.saleComponent sc - JOIN vn.sale s ON s.id = sc.saleFk - SET componentFk = vPromoComponent - WHERE componentFk = vManaComponent - AND s.ticketFk = vTicketFk; +BEGIN + + DECLARE vManaComponent INT; + + DECLARE vPromoComponent INT; + + SELECT id INTO vManaComponent + FROM vn.component c + WHERE c.code = 'mana'; + + SELECT id INTO vPromoComponent + FROM vn.component c + WHERE c.code = 'floramondoPromo'; + + UPDATE vn.saleComponent sc + JOIN vn.sale s ON s.id = sc.saleFk + SET componentFk = vPromoComponent + WHERE componentFk = vManaComponent + AND s.ticketFk = vTicketFk; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -79560,39 +80285,39 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketObservation_addNewBorn`(vTicketFk INT) -BEGIN - - /** - * Inserta observaciones para los tickets con clientes nuevos o recuperados - * - * @param vTicketFk Identificador de vn.ticket - */ - - DECLARE vDescription VARCHAR(20) DEFAULT '¡Cliente NUEVO! '; - +BEGIN + + /** + * Inserta observaciones para los tickets con clientes nuevos o recuperados + * + * @param vTicketFk Identificador de vn.ticket + */ + + DECLARE vDescription VARCHAR(20) DEFAULT '¡Cliente NUEVO! '; + INSERT INTO vn.ticketObservation(ticketFk, observationTypeFk, description) SELECT vTicketFk, ot.id, vDescription FROM vn.observationType ot WHERE ot.hasNewBornMessage ON DUPLICATE KEY UPDATE description = CONCAT(vDescription, ticketObservation.description); - + 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 `ticketPackagingRecovery` */; +/*!50003 DROP PROCEDURE IF EXISTS `ticketPackagingRecovery__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET character_set_client = 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 = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketPackagingRecovery`() +CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketPackagingRecovery__`() BEGIN /* Recupera los embalajes que han caido en el cliente 31 */ @@ -79653,66 +80378,66 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketParking_findSkipped`(vTicketFk INT, vItemPackingTypeFk VARCHAR(1)) -BEGIN - -/** - * Averigua los tickets que se han saltado por un error en el proceso encajado - * @param vTicketFk Ticket - * @param vItemPackingTypeFk Modo de encajado - * @return un select con los tickets afectados - */ - - DECLARE vParkingFk INT; - DECLARE vParked DATETIME; - DECLARE vLevel INT; - DECLARE vWagon INT; - DECLARE vCollectionFk INT; - - SELECT IFNULL(`level`,0), IFNULL(`wagon`,0),IFNULL(collectionFk,0) - INTO vLevel, vWagon, vCollectionFk - FROM vn.ticketCollection tc - JOIN vn.collection c ON c.id = tc.collectionFk AND c.itemPackingTypeFk = vItemPackingTypeFk - WHERE ticketFk = vTicketFk - ORDER BY c.id DESC - LIMIT 1; - - SELECT created, parkingFk - INTO vParked, vParkingFk - FROM vn.ticketParking tp - JOIN vn.parking p ON p.id = tp.parkingFk - JOIN vn.sector s ON s.id = p.sectorFk - WHERE ticketFk = vTicketFk - AND s.itemPackingTypeFk = vItemPackingTypeFk - AND s.isPackagingArea ; - - SELECT tp.ticketFk, CONCAT(tc.collectionFk, ' ', tc.wagon, ' - ', tc.level) coleccion, tp.created, p.code, am.name as Agencia - FROM vn.ticketParking tp - JOIN vn.parking p ON p.id = tp.parkingFk - JOIN vn.sector sc ON sc.id = p.sectorFk - LEFT JOIN vn.ticketCollection tc ON tc.ticketFk = tp.ticketFk - JOIN vn.ticketStateToday tst ON tst.ticket = tp.ticketFk - JOIN vn.ticket t ON t.id = tp.ticketFk - JOIN vn.zone z ON z.id = t.zoneFk - JOIN vn.agencyMode am ON am.id = z.agencyModeFk - JOIN vn.state s ON s.id = tst.state - WHERE (s.alertLevel < 2 - AND tp.parkingFk = vParkingFk - AND sc.isPackagingArea - AND ( - ( IFNULL(tc.collectionFk,-1) != IFNULL(@vCollectionFk,0) AND tp.created < vParked ) - OR - ( tc.collectionFk = vCollectionFk - AND (LEFT(tc.wagon,1) < LEFT(vWagon,1) - OR (LEFT(tc.wagon,1) = LEFT(vWagon,1) AND LEFT(tc.level,1) < LEFT(vLevel,1))) - ) - ) - ) -- Etiquetas que no se han escaneado y ya estamos con una posterior - OR - (s.alertLevel > 1 - AND tp.parkingFk = vParkingFk - AND sc.isPackagingArea - AND tp.created < vParked - AND t.packages <=> 0); +BEGIN + +/** + * Averigua los tickets que se han saltado por un error en el proceso encajado + * @param vTicketFk Ticket + * @param vItemPackingTypeFk Modo de encajado + * @return un select con los tickets afectados + */ + + DECLARE vParkingFk INT; + DECLARE vParked DATETIME; + DECLARE vLevel INT; + DECLARE vWagon INT; + DECLARE vCollectionFk INT; + + SELECT IFNULL(`level`,0), IFNULL(`wagon`,0),IFNULL(collectionFk,0) + INTO vLevel, vWagon, vCollectionFk + FROM vn.ticketCollection tc + JOIN vn.collection c ON c.id = tc.collectionFk AND c.itemPackingTypeFk = vItemPackingTypeFk + WHERE ticketFk = vTicketFk + ORDER BY c.id DESC + LIMIT 1; + + SELECT created, parkingFk + INTO vParked, vParkingFk + FROM vn.ticketParking tp + JOIN vn.parking p ON p.id = tp.parkingFk + JOIN vn.sector s ON s.id = p.sectorFk + WHERE ticketFk = vTicketFk + AND s.itemPackingTypeFk = vItemPackingTypeFk + AND s.isPackagingArea ; + + SELECT tp.ticketFk, CONCAT(tc.collectionFk, ' ', tc.wagon, ' - ', tc.level) coleccion, tp.created, p.code, am.name as Agencia + FROM vn.ticketParking tp + JOIN vn.parking p ON p.id = tp.parkingFk + JOIN vn.sector sc ON sc.id = p.sectorFk + LEFT JOIN vn.ticketCollection tc ON tc.ticketFk = tp.ticketFk + JOIN vn.ticketStateToday tst ON tst.ticket = tp.ticketFk + JOIN vn.ticket t ON t.id = tp.ticketFk + JOIN vn.zone z ON z.id = t.zoneFk + JOIN vn.agencyMode am ON am.id = z.agencyModeFk + JOIN vn.state s ON s.id = tst.state + WHERE (s.alertLevel < 2 + AND tp.parkingFk = vParkingFk + AND sc.isPackagingArea + AND ( + ( IFNULL(tc.collectionFk,-1) != IFNULL(@vCollectionFk,0) AND tp.created < vParked ) + OR + ( tc.collectionFk = vCollectionFk + AND (LEFT(tc.wagon,1) < LEFT(vWagon,1) + OR (LEFT(tc.wagon,1) = LEFT(vWagon,1) AND LEFT(tc.level,1) < LEFT(vLevel,1))) + ) + ) + ) -- Etiquetas que no se han escaneado y ya estamos con una posterior + OR + (s.alertLevel > 1 + AND tp.parkingFk = vParkingFk + AND sc.isPackagingArea + AND tp.created < vParked + AND t.packages <=> 0); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -79857,25 +80582,25 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketStateToday_setOnchecking__`(vParamFk INT) -BEGIN - /* - * @deprecated:utilizar ticketStateToday_setState - */ - - DECLARE vAlertLevel INT; - - SELECT s.alertLevel INTO vAlertLevel - FROM vn.state s - JOIN vn.ticketStateToday tst ON tst.state = s.id - WHERE tst.ticket = vParamFk - LIMIT 1; - - IF vAlertLevel < 2 THEN - - CALL vn.ticketStateUpdate(vParamFk, 'ON_CHECKING'); - - END IF; - +BEGIN + /* + * @deprecated:utilizar ticketStateToday_setState + */ + + DECLARE vAlertLevel INT; + + SELECT s.alertLevel INTO vAlertLevel + FROM vn.state s + JOIN vn.ticketStateToday tst ON tst.state = s.id + WHERE tst.ticket = vParamFk + LIMIT 1; + + IF vAlertLevel < 2 THEN + + CALL vn.ticketStateUpdate(vParamFk, 'ON_CHECKING'); + + END IF; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -79893,33 +80618,33 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketStateToday_setOnPreviousChecking__`(vParamFk INT) -BEGIN - - /* - * @deprecated:utilizar ticketStateToday_setState - */ - - - /* - * Cambia el estado del ticket al estado de "control previa" - * - * @param vParamFk ticket a cambiar el estado - * - */ - DECLARE vAlertLevel INT; - - SELECT s.alertLevel INTO vAlertLevel - FROM state s - JOIN ticketStateToday tst ON tst.state = s.id - WHERE tst.ticket = vParamFk - LIMIT 1; - - IF vAlertLevel < 2 THEN - - CALL ticketStateUpdate(vParamFk, 'PREVIOUS_CONTROL'); - - END IF; - +BEGIN + + /* + * @deprecated:utilizar ticketStateToday_setState + */ + + + /* + * Cambia el estado del ticket al estado de "control previa" + * + * @param vParamFk ticket a cambiar el estado + * + */ + DECLARE vAlertLevel INT; + + SELECT s.alertLevel INTO vAlertLevel + FROM state s + JOIN ticketStateToday tst ON tst.state = s.id + WHERE tst.ticket = vParamFk + LIMIT 1; + + IF vAlertLevel < 2 THEN + + CALL ticketStateUpdate(vParamFk, 'PREVIOUS_CONTROL'); + + END IF; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -79937,29 +80662,29 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketStateToday_setState`(vTicketFk INT, vStateCode VARCHAR(45)) -BEGIN - - /* Modifica el estado de un ticket de hoy - * - * @param vTicketFk el id del ticket - * @param vStateCode estado a modificar del ticket - * - */ - - DECLARE vAlertLevel INT; - - SELECT s.alertLevel INTO vAlertLevel - FROM state s - JOIN ticketStateToday tst ON tst.state = s.id - WHERE tst.ticket = vTicketFk - LIMIT 1; - - IF vAlertLevel < 2 THEN - - CALL vn.ticket_setState(vTicketFk, vStateCode); - - END IF; - +BEGIN + + /* Modifica el estado de un ticket de hoy + * + * @param vTicketFk el id del ticket + * @param vStateCode estado a modificar del ticket + * + */ + + DECLARE vAlertLevel INT; + + SELECT s.alertLevel INTO vAlertLevel + FROM state s + JOIN ticketStateToday tst ON tst.state = s.id + WHERE tst.ticket = vTicketFk + LIMIT 1; + + IF vAlertLevel < 2 THEN + + CALL vn.ticket_setState(vTicketFk, vStateCode); + + END IF; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -80148,63 +80873,63 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketToPrePrepare`(IN vSaleGroupFk INT, IN vSectorFk INT) -BEGIN - -/* Devuelve las lineas de vn.sale para preparación previa según el saleGroup - * - * - * @param vSaleGroupFk Identificador de vn.saleGroup -*/ - DECLARE vIsResetCode BOOLEAN; - - SELECT (vSaleGroupFk = 2000000) INTO vIsResetCode; - - IF vIsResetCode THEN - - UPDATE vn.saleTracking st - JOIN vn.state s ON s.code = 'OK PREVIOUS' - JOIN vn.state s2 ON s2.id = st.stateFk - SET st.stateFk = s.id - WHERE workerFk = vn.getUser() - AND s2.code = 'PREVIOUS_PREPARATION'; - - ELSE - - UPDATE vn.saleTracking st - JOIN vn.saleGroupDetail sgd ON sgd.saleFk = st.saleFk - SET workerFk = vn.getUser() - WHERE sgd.saleGroupFk = vSaleGroupFk; - - UPDATE vn.saleGroup sg - SET sg.userFk = vn.getUser() - WHERE sg.id = vSaleGroupFk; - - SELECT s.ticketFk, - s.itemFk, - i.longName, - IFNULL(i.itemPackingTypeFk,' ') itemPackingTypeFk, - IFNULL(i.subName ,' ') subName, - s.quantity originalQuantity , - s.quantity, - w.code workerCode, - sgd.saleFk, - IFNULL(iss.quantity,0) pickedQuantity, - vSectorFk, - c.salesPersonFk - FROM vn.sale s - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.saleGroupDetail sgd ON sgd.saleFk = s.id - JOIN vn.saleTracking st ON st.saleFk = s.id - JOIN vn.state stt ON stt.id = st.stateFk - JOIN vn.worker w ON w.id = st.workerFk - LEFT JOIN vn.itemShelvingSaleSum iss ON iss.saleFk = s.id - JOIN vn.ticket t ON t.id= s.ticketFk - JOIN vn.client c ON c.id=t.clientFk - WHERE st.workerFk = account.myUser_getId() - AND stt.code = 'PREVIOUS_PREPARATION'; - - END IF; - +BEGIN + +/* Devuelve las lineas de vn.sale para preparación previa según el saleGroup + * + * + * @param vSaleGroupFk Identificador de vn.saleGroup +*/ + DECLARE vIsResetCode BOOLEAN; + + SELECT (vSaleGroupFk = 2000000) INTO vIsResetCode; + + IF vIsResetCode THEN + + UPDATE vn.saleTracking st + JOIN vn.state s ON s.code = 'OK PREVIOUS' + JOIN vn.state s2 ON s2.id = st.stateFk + SET st.stateFk = s.id + WHERE workerFk = vn.getUser() + AND s2.code = 'PREVIOUS_PREPARATION'; + + ELSE + + UPDATE vn.saleTracking st + JOIN vn.saleGroupDetail sgd ON sgd.saleFk = st.saleFk + SET workerFk = vn.getUser() + WHERE sgd.saleGroupFk = vSaleGroupFk; + + UPDATE vn.saleGroup sg + SET sg.userFk = vn.getUser() + WHERE sg.id = vSaleGroupFk; + + SELECT s.ticketFk, + s.itemFk, + i.longName, + IFNULL(i.itemPackingTypeFk,' ') itemPackingTypeFk, + IFNULL(i.subName ,' ') subName, + s.quantity originalQuantity , + s.quantity, + w.code workerCode, + sgd.saleFk, + IFNULL(iss.quantity,0) pickedQuantity, + vSectorFk, + c.salesPersonFk + FROM vn.sale s + JOIN vn.item i ON i.id = s.itemFk + JOIN vn.saleGroupDetail sgd ON sgd.saleFk = s.id + JOIN vn.saleTracking st ON st.saleFk = s.id + JOIN vn.state stt ON stt.id = st.stateFk + JOIN vn.worker w ON w.id = st.workerFk + LEFT JOIN vn.itemShelvingSaleSum iss ON iss.saleFk = s.id + JOIN vn.ticket t ON t.id= s.ticketFk + JOIN vn.client c ON c.id=t.clientFk + WHERE st.workerFk = account.myUser_getId() + AND stt.code = 'PREVIOUS_PREPARATION'; + + END IF; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -80451,102 +81176,102 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_add`( - vClientId INT - ,vShipped DATE - ,vWarehouseFk INT - ,vCompanyFk INT - ,vAddressFk INT - ,vAgencyModeFk INT - ,vRouteFk INT - ,vlanded DATE - ,vUserId INT - ,vIsRequiredZone INT +CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_add`( + vClientId INT + ,vShipped DATE + ,vWarehouseFk INT + ,vCompanyFk INT + ,vAddressFk INT + ,vAgencyModeFk INT + ,vRouteFk INT + ,vlanded DATE + ,vUserId INT + ,vIsRequiredZone INT ,OUT vNewTicket INT) -BEGIN - - DECLARE vZoneFk INT; - DECLARE vPrice DECIMAL(10,2); - DECLARE vBonus DECIMAL(10,2); - - IF vClientId IS NULL THEN - CALL util.throw ('CLIENT_NOT_ESPECIFIED'); - END IF; - - IF NOT vAddressFk OR vAddressFk IS NULL THEN - SELECT id INTO vAddressFk - FROM address - WHERE clientFk = vClientId AND isDefaultAddress; - END IF; - - IF vAgencyModeFk IS NOT NULL THEN - - CALL vn.zone_getShipped (vlanded, vAddressFk, vAgencyModeFk, TRUE); - - SELECT zoneFk, price, bonus INTO vZoneFk, vPrice, vBonus - FROM tmp.zoneGetShipped - WHERE shipped = vShipped AND warehouseFk = vWarehouseFk LIMIT 1; - - IF (vZoneFk IS NULL OR vZoneFk = 0) AND vIsRequiredZone THEN - CALL util.throw ('NOT_ZONE_WITH_THIS_PARAMETERS'); - END IF; - END IF; - INSERT INTO ticket ( - clientFk, - shipped, - addressFk, - agencyModeFk, - nickname, - warehouseFk, - routeFk, - companyFk, - landed, - zoneFk, - zonePrice, - zoneBonus - ) - SELECT - vClientId, - vShipped, - a.id, - vAgencyModeFk, - a.nickname, - vWarehouseFk, - IF(vRouteFk,vRouteFk,NULL), - vCompanyFk, - vlanded, - vZoneFk, - vPrice, - vBonus - FROM address a - JOIN agencyMode am ON am.id = a.agencyModeFk - WHERE a.id = vAddressFk; - - SET vNewTicket = LAST_INSERT_ID(); - - INSERT INTO ticketObservation(ticketFk, observationTypeFk, description) - SELECT vNewTicket, ao.observationTypeFk, ao.description - FROM addressObservation ao - JOIN address a ON a.id = ao.addressFk - WHERE a.id = vAddressFk; - - IF (SELECT COUNT(*) FROM bs.clientNewBorn cnb - WHERE cnb.clientFk = vClientId - AND NOT cnb.isRookie) = 0 THEN - - CALL vn.ticketObservation_addNewBorn(vNewTicket); - - END IF; - - INSERT INTO vn.ticketLog - SET originFk = vNewTicket, userFk = vUserId, `action` = 'insert', description = CONCAT('Ha creado el ticket:', ' ', vNewTicket); - - IF (SELECT ct.isCreatedAsServed FROM vn.clientType ct JOIN vn.client c ON c.typeFk = ct.code WHERE c.id = vClientId ) <> FALSE THEN - INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) - SELECT id, vNewTicket, account.myUser_getId() - FROM state - WHERE `code` = 'DELIVERED'; - END IF; +BEGIN + + DECLARE vZoneFk INT; + DECLARE vPrice DECIMAL(10,2); + DECLARE vBonus DECIMAL(10,2); + + IF vClientId IS NULL THEN + CALL util.throw ('CLIENT_NOT_ESPECIFIED'); + END IF; + + IF NOT vAddressFk OR vAddressFk IS NULL THEN + SELECT id INTO vAddressFk + FROM address + WHERE clientFk = vClientId AND isDefaultAddress; + END IF; + + IF vAgencyModeFk IS NOT NULL THEN + + CALL vn.zone_getShipped (vlanded, vAddressFk, vAgencyModeFk, TRUE); + + SELECT zoneFk, price, bonus INTO vZoneFk, vPrice, vBonus + FROM tmp.zoneGetShipped + WHERE shipped = vShipped AND warehouseFk = vWarehouseFk LIMIT 1; + + IF (vZoneFk IS NULL OR vZoneFk = 0) AND vIsRequiredZone THEN + CALL util.throw ('NOT_ZONE_WITH_THIS_PARAMETERS'); + END IF; + END IF; + INSERT INTO ticket ( + clientFk, + shipped, + addressFk, + agencyModeFk, + nickname, + warehouseFk, + routeFk, + companyFk, + landed, + zoneFk, + zonePrice, + zoneBonus + ) + SELECT + vClientId, + vShipped, + a.id, + vAgencyModeFk, + a.nickname, + vWarehouseFk, + IF(vRouteFk,vRouteFk,NULL), + vCompanyFk, + vlanded, + vZoneFk, + vPrice, + vBonus + FROM address a + JOIN agencyMode am ON am.id = a.agencyModeFk + WHERE a.id = vAddressFk; + + SET vNewTicket = LAST_INSERT_ID(); + + INSERT INTO ticketObservation(ticketFk, observationTypeFk, description) + SELECT vNewTicket, ao.observationTypeFk, ao.description + FROM addressObservation ao + JOIN address a ON a.id = ao.addressFk + WHERE a.id = vAddressFk; + + IF (SELECT COUNT(*) FROM bs.clientNewBorn cnb + WHERE cnb.clientFk = vClientId + AND NOT cnb.isRookie) = 0 THEN + + CALL vn.ticketObservation_addNewBorn(vNewTicket); + + END IF; + + INSERT INTO vn.ticketLog + SET originFk = vNewTicket, userFk = vUserId, `action` = 'insert', description = CONCAT('Ha creado el ticket:', ' ', vNewTicket); + + IF (SELECT ct.isCreatedAsServed FROM vn.clientType ct JOIN vn.client c ON c.typeFk = ct.code WHERE c.id = vClientId ) <> FALSE THEN + INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) + SELECT id, vNewTicket, account.myUser_getId() + FROM state + WHERE `code` = 'DELIVERED'; + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -80564,21 +81289,21 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_administrativeCopy`(vOriginalTicket INT, OUT vNewTicket INT) -BEGIN - - INSERT INTO vn.ticket(clientFk, addressFk, shipped, warehouseFk, companyFk, landed) - SELECT t.clientFk , t.addressFk , t.shipped ,w.id, t.companyFk , t.landed - FROM vn.ticket t - JOIN vn.warehouse w ON w.name = 'INVENTARIO' - WHERE t.id = vOriginalTicket; - - SELECT LAST_INSERT_ID() INTO vNewTicket; - - INSERT INTO vn.sale(ticketFk, itemFk, concept, quantity, price, discount) - SELECT vNewTicket, s.itemFk , s.concept , s.quantity , s.price , s.discount - FROM vn.sale s - WHERE s.ticketFk = vOriginalTicket; - +BEGIN + + INSERT INTO vn.ticket(clientFk, addressFk, shipped, warehouseFk, companyFk, landed) + SELECT t.clientFk , t.addressFk , t.shipped ,w.id, t.companyFk , t.landed + FROM vn.ticket t + JOIN vn.warehouse w ON w.name = 'INVENTARIO' + WHERE t.id = vOriginalTicket; + + SELECT LAST_INSERT_ID() INTO vNewTicket; + + INSERT INTO vn.sale(ticketFk, itemFk, concept, quantity, price, discount) + SELECT vNewTicket, s.itemFk , s.concept , s.quantity , s.price , s.discount + FROM vn.sale s + WHERE s.ticketFk = vOriginalTicket; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -80596,46 +81321,46 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` 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 ( - 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 - GROUP BY sv.ticketFk - HAVING liters <= vLitersMax AND `lines` <= vLinesMax AND ticketFuture; +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 ( + 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 + GROUP BY sv.ticketFk + HAVING liters <= vLitersMax AND `lines` <= vLinesMax AND ticketFuture; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -80653,49 +81378,49 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` 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; - +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 ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -80713,36 +81438,36 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_changeClient`(vNewClient INT, vUserFk INT) -BEGIN - -/** - * Dado un conjunto de tickets - * cambia el cliente al nuevo cliente dado - * - * params @vNewClient nuevo cliente - * params @vUserFk usuario que realiza el cambio - * - * table @tmp.ticket(ticketFk) conjunto de tickets - */ - - INSERT INTO ticketLog (originFk, userFk, `action`, changedModel, oldInstance, newInstance) - SELECT t.id, vUserFk, 'update', 'Ticket', CONCAT('{"clientFk":',t.clientFk,'}'), CONCAT('{"clientFk":',vNewClient,'}') - FROM ticket t - JOIN tmp.ticket tt - ON t.id = tt.ticketFk; - - UPDATE ticket t - JOIN tmp.ticket tt - ON t.id = tt.ticketFk - SET t.clientFk = vNewClient; - - UPDATE ticket t - JOIN tmp.ticket tt - ON t.id = tt.ticketFk - JOIN stowaway s - ON s.shipFk = tt.ticketFk - SET t.clientFk = vNewClient; - +BEGIN + +/** + * Dado un conjunto de tickets + * cambia el cliente al nuevo cliente dado + * + * params @vNewClient nuevo cliente + * params @vUserFk usuario que realiza el cambio + * + * table @tmp.ticket(ticketFk) conjunto de tickets + */ + + INSERT INTO ticketLog (originFk, userFk, `action`, changedModel, oldInstance, newInstance) + SELECT t.id, vUserFk, 'update', 'Ticket', CONCAT('{"clientFk":',t.clientFk,'}'), CONCAT('{"clientFk":',vNewClient,'}') + FROM ticket t + JOIN tmp.ticket tt + ON t.id = tt.ticketFk; + + UPDATE ticket t + JOIN tmp.ticket tt + ON t.id = tt.ticketFk + SET t.clientFk = vNewClient; + + UPDATE ticket t + JOIN tmp.ticket tt + ON t.id = tt.ticketFk + JOIN stowaway s + ON s.shipFk = tt.ticketFk + SET t.clientFk = vNewClient; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -81829,41 +82554,41 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_DelayTruck`(vWarehouserFk INT, vHour INT, vMinute INT) -BEGIN - - DECLARE done INT DEFAULT FALSE; - DECLARE vTicketFk INT; - DECLARE cur1 CURSOR FOR SELECT ticketFk FROM tmp.ticket; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - - CALL vn.productionControl(vWarehouserFk,0) ; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticket; - CREATE TEMPORARY TABLE tmp.ticket - SELECT ticketFk - FROM tmp.productionBuffer - WHERE shipped = curdate() - AND problem LIKE '%I:%' - AND (HH <= vHour OR HH = vHour AND mm < vMinute) - AND alertLevel = 0; - - OPEN cur1; - - read_loop: LOOP - - FETCH cur1 INTO vTicketFk; - - IF done THEN - LEAVE read_loop; - END IF; - - CALL vn.ticket_DelayTruckSplit(vTicketFk); - - END LOOP; - - CLOSE cur1; - +BEGIN + + DECLARE done INT DEFAULT FALSE; + DECLARE vTicketFk INT; + DECLARE cur1 CURSOR FOR SELECT ticketFk FROM tmp.ticket; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; + + CALL vn.productionControl(vWarehouserFk,0) ; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticket; + CREATE TEMPORARY TABLE tmp.ticket + SELECT ticketFk + FROM tmp.productionBuffer + WHERE shipped = curdate() + AND problem LIKE '%I:%' + AND (HH <= vHour OR HH = vHour AND mm < vMinute) + AND alertLevel = 0; + + OPEN cur1; + + read_loop: LOOP + + FETCH cur1 INTO vTicketFk; + + IF done THEN + LEAVE read_loop; + END IF; + + CALL vn.ticket_DelayTruckSplit(vTicketFk); + + END LOOP; + + CLOSE cur1; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -81947,23 +82672,23 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_doRecalc`() -proc: BEGIN -/** - * Recalculates modified ticket. - */ - - DECLARE vDone BOOL; - DECLARE vTicketFk INT; - - DECLARE cCur CURSOR FOR - SELECT ticketFk FROM ticketRecalc; - - DECLARE CONTINUE HANDLER FOR NOT FOUND - SET vDone = TRUE; - - DECLARE CONTINUE HANDLER FOR SQLEXCEPTION - BEGIN - DO RELEASE_LOCK('vn.ticket_doRecalc'); +proc: BEGIN +/** + * Recalculates modified ticket. + */ + + DECLARE vDone BOOL; + DECLARE vTicketFk INT; + + DECLARE cCur CURSOR FOR + SELECT ticketFk FROM ticketRecalc; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + DECLARE CONTINUE HANDLER FOR SQLEXCEPTION + BEGIN + DO RELEASE_LOCK('vn.ticket_doRecalc'); ROLLBACK; GET DIAGNOSTICS CONDITION 2 @errno = MYSQL_ERRNO, @text = MESSAGE_TEXT; CALL `vn`.`mail_insert`('robert@verdnatura.es', @@ -81972,33 +82697,33 @@ proc: BEGIN CONCAT('Se ha detectato un problema en ticket_doRecalc al calcular el total del ticket : ', vTicketFk,' el error es el: ', CONCAT('ERROR ', IFNULL(@errno, 0), ': ', ifnull(@text, ''))) - ); - RESIGNAL; - END; - - IF !GET_LOCK('vn.ticket_doRecalc', 0) THEN - LEAVE proc; - END IF; - - OPEN cCur; - - myLoop: LOOP - SET vDone = FALSE; - FETCH cCur INTO vTicketFk; - - IF vDone THEN - LEAVE myLoop; - END IF; - - START TRANSACTION; + ); + RESIGNAL; + END; + + IF !GET_LOCK('vn.ticket_doRecalc', 0) THEN + LEAVE proc; + END IF; + + OPEN cCur; + + myLoop: LOOP + SET vDone = FALSE; + FETCH cCur INTO vTicketFk; + + IF vDone THEN + LEAVE myLoop; + END IF; + + START TRANSACTION; CALL ticket_recalc(vTicketFk); - + DELETE FROM ticketRecalc WHERE ticketFk = vTicketFk; - COMMIT; - END LOOP; - - CLOSE cCur; - DO RELEASE_LOCK('vn.ticket_doRecalc'); + COMMIT; + END LOOP; + + CLOSE cCur; + DO RELEASE_LOCK('vn.ticket_doRecalc'); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -82115,100 +82840,100 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_getFromFloramondo`(vDated DATE) -BEGIN - - /** - * Genera una tabla con la lista de tickets de Floramondo para una fecha determinada - * - * @param vDated Fecha de preparación de los pedidos - * - * @return tmp.ticketFloramondo(ticketFk, clientName, agencyName, freight, expeditionCount, margin, trolleys, pallets) - */ - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketFloramondo; - CREATE TEMPORARY TABLE tmp.ticketFloramondo - (ticketFk INT PRIMARY KEY, - clientName VARCHAR(50), - agencyName VARCHAR(50), - freight DECIMAL(10,2), - expeditionCount INT, - margin DECIMAL(10,3), - trolleys INT, - pallets INT) - ENGINE = MEMORY; - - INSERT INTO tmp.ticketFloramondo(ticketFk, clientName, agencyName) - SELECT t.id ticketFk, t.nickname , am.name - FROM vn.ticket t - JOIN vn.agencyMode am ON am.id = t.agencyModeFk - JOIN vn.warehouse w ON w.id = t.warehouseFk AND w.code IN ('VNH','FLM') - AND t.shipped BETWEEN vDated AND TIMESTAMPADD(HOUR, 23, vDated); - - - DROP TEMPORARY TABLE IF EXISTS tmp.ticket; - CREATE TEMPORARY TABLE tmp.ticket - (ticketFk INT PRIMARY KEY) - SELECT ticketFk - FROM tmp.ticketFloramondo; - - -- Freight - UPDATE tmp.ticketFloramondo tf - JOIN (SELECT sum(sc.value) freight, t.ticketFk - FROM vn.saleComponent sc - JOIN vn.component c ON c.id = sc.componentFk - JOIN vn.componentType ct ON ct.id = c.typeFk - JOIN vn.sale s ON s.id = sc.saleFk - JOIN tmp.ticket t ON t.ticketFk = s.ticketFk - WHERE ct.code = 'FREIGHT' - GROUP BY t.ticketFk) sb ON sb.ticketFk = tf.ticketFk - SET tf.freight = sb.freight; - - -- Expedition Count - UPDATE tmp.ticketFloramondo tf - JOIN (SELECT count(*) expeditionCount, t.ticketFk - FROM vn.expedition e - JOIN tmp.ticket t ON t.ticketFk = e.ticketFk - GROUP BY t.ticketFk) sb ON sb.ticketFk = tf.ticketFk - SET tf.expeditionCount = sb.expeditionCount; - - -- Margin - UPDATE tmp.ticketFloramondo tf - JOIN (SELECT sum(IF(ct.code = 'COST',sc.value,0)) cost, - sum(IF (ct.isMargin, sc.value,0)) margin, - t.ticketFk - FROM vn.saleComponent sc - JOIN vn.component c ON c.id = sc.componentFk - JOIN vn.componentType ct ON ct.id = c.typeFk - JOIN vn.sale s ON s.id = sc.saleFk - JOIN tmp.ticket t ON t.ticketFk = s.ticketFk - GROUP BY t.ticketFk) sb ON sb.ticketFk = tf.ticketFk - SET tf.margin = sb.margin / sb.cost; - - -- Trolleys - UPDATE tmp.ticketFloramondo tf - JOIN (SELECT sum(tp.quantity) trolleys, t.ticketFk - FROM vn.ticketPackaging tp - JOIN tmp.ticket t ON t.ticketFk = tp.ticketFk - JOIN vn.packaging p ON p.id = tp.packagingFk - WHERE p.isTrolley - GROUP BY t.ticketFk) sb ON sb.ticketFk = tf.ticketFk - SET tf.trolleys = sb.trolleys; - - -- Pallets - UPDATE tmp.ticketFloramondo tf - JOIN (SELECT sum(tp.quantity) pallets, t.ticketFk - FROM vn.ticketPackaging tp - JOIN tmp.ticket t ON t.ticketFk = tp.ticketFk - JOIN vn.packaging p ON p.id = tp.packagingFk - WHERE p.isPallet - GROUP BY t.ticketFk) sb ON sb.ticketFk = tf.ticketFk - SET tf.pallets = sb.pallets; - - SELECT * FROM tmp.ticketFloramondo; - - DROP TEMPORARY TABLE tmp.ticket; - DROP TEMPORARY TABLE tmp.ticketFloramondo; - +BEGIN + + /** + * Genera una tabla con la lista de tickets de Floramondo para una fecha determinada + * + * @param vDated Fecha de preparación de los pedidos + * + * @return tmp.ticketFloramondo(ticketFk, clientName, agencyName, freight, expeditionCount, margin, trolleys, pallets) + */ + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketFloramondo; + CREATE TEMPORARY TABLE tmp.ticketFloramondo + (ticketFk INT PRIMARY KEY, + clientName VARCHAR(50), + agencyName VARCHAR(50), + freight DECIMAL(10,2), + expeditionCount INT, + margin DECIMAL(10,3), + trolleys INT, + pallets INT) + ENGINE = MEMORY; + + INSERT INTO tmp.ticketFloramondo(ticketFk, clientName, agencyName) + SELECT t.id ticketFk, t.nickname , am.name + FROM vn.ticket t + JOIN vn.agencyMode am ON am.id = t.agencyModeFk + JOIN vn.warehouse w ON w.id = t.warehouseFk AND w.code IN ('VNH','FLM') + AND t.shipped BETWEEN vDated AND TIMESTAMPADD(HOUR, 23, vDated); + + + DROP TEMPORARY TABLE IF EXISTS tmp.ticket; + CREATE TEMPORARY TABLE tmp.ticket + (ticketFk INT PRIMARY KEY) + SELECT ticketFk + FROM tmp.ticketFloramondo; + + -- Freight + UPDATE tmp.ticketFloramondo tf + JOIN (SELECT sum(sc.value) freight, t.ticketFk + FROM vn.saleComponent sc + JOIN vn.component c ON c.id = sc.componentFk + JOIN vn.componentType ct ON ct.id = c.typeFk + JOIN vn.sale s ON s.id = sc.saleFk + JOIN tmp.ticket t ON t.ticketFk = s.ticketFk + WHERE ct.code = 'FREIGHT' + GROUP BY t.ticketFk) sb ON sb.ticketFk = tf.ticketFk + SET tf.freight = sb.freight; + + -- Expedition Count + UPDATE tmp.ticketFloramondo tf + JOIN (SELECT count(*) expeditionCount, t.ticketFk + FROM vn.expedition e + JOIN tmp.ticket t ON t.ticketFk = e.ticketFk + GROUP BY t.ticketFk) sb ON sb.ticketFk = tf.ticketFk + SET tf.expeditionCount = sb.expeditionCount; + + -- Margin + UPDATE tmp.ticketFloramondo tf + JOIN (SELECT sum(IF(ct.code = 'COST',sc.value,0)) cost, + sum(IF (ct.isMargin, sc.value,0)) margin, + t.ticketFk + FROM vn.saleComponent sc + JOIN vn.component c ON c.id = sc.componentFk + JOIN vn.componentType ct ON ct.id = c.typeFk + JOIN vn.sale s ON s.id = sc.saleFk + JOIN tmp.ticket t ON t.ticketFk = s.ticketFk + GROUP BY t.ticketFk) sb ON sb.ticketFk = tf.ticketFk + SET tf.margin = sb.margin / sb.cost; + + -- Trolleys + UPDATE tmp.ticketFloramondo tf + JOIN (SELECT sum(tp.quantity) trolleys, t.ticketFk + FROM vn.ticketPackaging tp + JOIN tmp.ticket t ON t.ticketFk = tp.ticketFk + JOIN vn.packaging p ON p.id = tp.packagingFk + WHERE p.isTrolley + GROUP BY t.ticketFk) sb ON sb.ticketFk = tf.ticketFk + SET tf.trolleys = sb.trolleys; + + -- Pallets + UPDATE tmp.ticketFloramondo tf + JOIN (SELECT sum(tp.quantity) pallets, t.ticketFk + FROM vn.ticketPackaging tp + JOIN tmp.ticket t ON t.ticketFk = tp.ticketFk + JOIN vn.packaging p ON p.id = tp.packagingFk + WHERE p.isPallet + GROUP BY t.ticketFk) sb ON sb.ticketFk = tf.ticketFk + SET tf.pallets = sb.pallets; + + SELECT * FROM tmp.ticketFloramondo; + + DROP TEMPORARY TABLE tmp.ticket; + DROP TEMPORARY TABLE tmp.ticketFloramondo; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -82693,24 +83418,24 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_merge`(vSelf INT, vTicketTargetFk INT) -BEGIN - - /** - * Fusiona el primer ticket al segundo - * - * @param vSelf Número de ticket a fusionar - * @param vTicketTargetFk Ticket destino - * - */ - - UPDATE vn.sale s - SET s.ticketFk = vTicketTargetFk - WHERE s.ticketFk = vSelf; - - UPDATE vn.ticket t - SET t.shipped = TIMESTAMPADD(YEAR, - YEAR(NOW()) MOD 2000, t.shipped ) - WHERE t.id = vSelf; - +BEGIN + + /** + * Fusiona el primer ticket al segundo + * + * @param vSelf Número de ticket a fusionar + * @param vTicketTargetFk Ticket destino + * + */ + + UPDATE vn.sale s + SET s.ticketFk = vTicketTargetFk + WHERE s.ticketFk = vSelf; + + UPDATE vn.ticket t + SET t.shipped = TIMESTAMPADD(YEAR, - YEAR(NOW()) MOD 2000, t.shipped ) + WHERE t.id = vSelf; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -82785,28 +83510,28 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_recalc`(vTicketId INT) -BEGIN -/** - * Calcula y guarda el total con/sin IVA en un ticket. - * - * @param vTicketId Identificador del ticket - */ - - DROP TEMPORARY TABLE IF EXISTS tmp.ticket; - CREATE TEMPORARY TABLE tmp.ticket - ENGINE = MEMORY - SELECT vTicketId ticketFk; - - CALL ticketGetTotal; - - UPDATE ticket t - JOIN tmp.ticketTotal tt ON tt.ticketFk = t.id - SET t.totalWithVat = tt.total, - t.totalWithoutVat = tt.totalWithoutVat; - - DROP TEMPORARY TABLE - tmp.ticket, - tmp.ticketTotal; +BEGIN +/** + * Calcula y guarda el total con/sin IVA en un ticket. + * + * @param vTicketId Identificador del ticket + */ + + DROP TEMPORARY TABLE IF EXISTS tmp.ticket; + CREATE TEMPORARY TABLE tmp.ticket + ENGINE = MEMORY + SELECT vTicketId ticketFk; + + CALL ticketGetTotal; + + UPDATE ticket t + JOIN tmp.ticketTotal tt ON tt.ticketFk = t.id + SET t.totalWithVat = tt.total, + t.totalWithoutVat = tt.totalWithoutVat; + + DROP TEMPORARY TABLE + tmp.ticket, + tmp.ticketTotal; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -82824,91 +83549,91 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_recalcComponents`(IN vTicketFk BIGINT, vIsTicketEditable BOOLEAN) -proc: BEGIN - -/** - * Este procedimiento recalcula los componentes de un ticket, - * eliminando los componentes existentes e insertandolos de nuevo - * - * @param vTicketFk Id del ticket - * @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 vZoneFk INTEGER; - - 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 t.id = vTicketFk; - - 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; - - IF vLanded IS NULL OR vZoneFk IS NULL THEN - - 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; - - END IF; - - DROP TEMPORARY TABLE tmp.zoneGetLanded; - - -- 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, vZoneFk zoneFk - FROM sale s - LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk - WHERE s.ticketFk = vTicketFk - GROUP BY s.itemFk; - - 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; - - -- si el ticket esta facturado, respeta los precios - CALL ticketComponentUpdateSale(IF(vIsTicketEditable, 1, 6)); - - CALL catalog_componentPurge(); - DROP TEMPORARY TABLE - tmp.buyUltimate, - tmp.sale; +proc: BEGIN + +/** + * Este procedimiento recalcula los componentes de un ticket, + * eliminando los componentes existentes e insertandolos de nuevo + * + * @param vTicketFk Id del ticket + * @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 vZoneFk INTEGER; + + 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 t.id = vTicketFk; + + 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; + + IF vLanded IS NULL OR vZoneFk IS NULL THEN + + 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; + + END IF; + + DROP TEMPORARY TABLE tmp.zoneGetLanded; + + -- 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, vZoneFk zoneFk + FROM sale s + LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk + WHERE s.ticketFk = vTicketFk + GROUP BY s.itemFk; + + 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; + + -- si el ticket esta facturado, respeta los precios + CALL ticketComponentUpdateSale(IF(vIsTicketEditable, 1, 6)); + + CALL catalog_componentPurge(); + DROP TEMPORARY TABLE + tmp.buyUltimate, + tmp.sale; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -83121,17 +83846,17 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_requestRecalc`(vSelf INT) -proc: BEGIN -/** - * Adds a request to recalculate the ticket total. - * - * @param vSelf The ticket identifier - */ - IF vSelf IS NULL THEN - LEAVE proc; - END IF; - - INSERT IGNORE INTO ticketRecalc SET ticketFk = vSelf; +proc: BEGIN +/** + * Adds a request to recalculate the ticket total. + * + * @param vSelf The ticket identifier + */ + IF vSelf IS NULL THEN + LEAVE proc; + END IF; + + INSERT IGNORE INTO ticketRecalc SET ticketFk = vSelf; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -83149,27 +83874,27 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_setNextState`(vSelf INT) -BEGIN -/** - * Cambia el estado del ticket al siguiente estado según la tabla state - * - * @param vSelf id dle ticket - */ - DECLARE vStateFk INT; - DECLARE vNewStateFk INT; - - SELECT stateFk INTO vStateFk - FROM ticketState - WHERE ticketFk = vSelf; - - SELECT nextStateFk INTO vNewStateFk - FROM state - WHERE id = vStateFk; - - INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) - VALUES (vNewStateFk, vSelf, account.myUser_getId()); - - SELECT TRUE AS IsUpdated; +BEGIN +/** + * Cambia el estado del ticket al siguiente estado según la tabla state + * + * @param vSelf id dle ticket + */ + DECLARE vStateFk INT; + DECLARE vNewStateFk INT; + + SELECT stateFk INTO vStateFk + FROM ticketState + WHERE ticketFk = vSelf; + + SELECT nextStateFk INTO vNewStateFk + FROM state + WHERE id = vStateFk; + + INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) + VALUES (vNewStateFk, vSelf, account.myUser_getId()); + + SELECT TRUE AS IsUpdated; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -83187,40 +83912,40 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_setPreviousState`(vTicketFk INT) -BEGIN - - DECLARE vControlFk INT; - - SELECT MAX(inter_id) INTO vControlFk - FROM vncontrol.inter - WHERE Id_Ticket = vTicketFk; - - IF (SELECT s.code - FROM vn.state s - JOIN vncontrol.inter i ON i.state_id = s.id - WHERE i.inter_id = vControlFk) - = 'PREVIOUS_PREPARATION' THEN - - SELECT inter_id - INTO vControlFk - FROM vncontrol.inter i - JOIN vn.state s ON i.state_id = s.id - WHERE Id_Ticket = vTicketFk - AND inter_id < vControlFk - AND s.code != 'PREVIOUS_PREPARATION' - ORDER BY inter_id DESC - LIMIT 1; - - INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) - SELECT s.nextStateFk, i.Id_Ticket, account.myUser_getId() - FROM vncontrol.inter i - JOIN vn.state s ON i.state_id = s.id - WHERE inter_id = vControlFk; - - END IF; - - SELECT TRUE AS IsUpdated; - +BEGIN + + DECLARE vControlFk INT; + + SELECT MAX(inter_id) INTO vControlFk + FROM vncontrol.inter + WHERE Id_Ticket = vTicketFk; + + IF (SELECT s.code + FROM vn.state s + JOIN vncontrol.inter i ON i.state_id = s.id + WHERE i.inter_id = vControlFk) + = 'PREVIOUS_PREPARATION' THEN + + SELECT inter_id + INTO vControlFk + FROM vncontrol.inter i + JOIN vn.state s ON i.state_id = s.id + WHERE Id_Ticket = vTicketFk + AND inter_id < vControlFk + AND s.code != 'PREVIOUS_PREPARATION' + ORDER BY inter_id DESC + LIMIT 1; + + INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) + SELECT s.nextStateFk, i.Id_Ticket, account.myUser_getId() + FROM vncontrol.inter i + JOIN vn.state s ON i.state_id = s.id + WHERE inter_id = vControlFk; + + END IF; + + SELECT TRUE AS IsUpdated; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -83238,30 +83963,30 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_setState`(vTicketFk INT, vStateCode VARCHAR(45)) -BEGIN - - /* Modifica el estado de un ticket - * - * @param vTicketFk el id del ticket - * @param vStateCode estado a modificar del ticket - * - */ - - DECLARE vAlertLevel INT; - - SELECT s.alertLevel INTO vAlertLevel - FROM vn.state s - JOIN vn.ticketState ts ON ts.stateFk = s.id - WHERE ts.ticketFk = vTicketFk; - - IF !(vStateCode = 'ON_CHECKING' AND vAlertLevel > 1) THEN - - INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) - SELECT id, vTicketFk, account.myUser_getId() - FROM vn.state - WHERE `code` = vStateCode collate utf8_unicode_ci; - - END IF; +BEGIN + + /* Modifica el estado de un ticket + * + * @param vTicketFk el id del ticket + * @param vStateCode estado a modificar del ticket + * + */ + + DECLARE vAlertLevel INT; + + SELECT s.alertLevel INTO vAlertLevel + FROM vn.state s + JOIN vn.ticketState ts ON ts.stateFk = s.id + WHERE ts.ticketFk = vTicketFk; + + IF !(vStateCode = 'ON_CHECKING' AND vAlertLevel > 1) THEN + + INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) + SELECT id, vTicketFk, account.myUser_getId() + FROM vn.state + WHERE `code` = vStateCode collate utf8_unicode_ci; + + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -84123,27 +84848,27 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `tpvTransaction_checkStatus`() -BEGIN -/** - * - * Envia mail con los cobros web no - * trasladados a la ficha del cliente. - * - */ - INSERT INTO mail (receiver,replyTo,subject,body) - SELECT 'administracion@verdnatura.es', - 'noreply@verdnatura.es', - CONCAT('Cobro web no trasladado a la ficha del cliente ', t.clientFk), - CONCAT('Hay un importe de ', t.amount/100, '€ del cliente ', t.clientFk, ' con fecha ', t.created, - ', que no se ha trasladado a recibos. Si nos ha llegado el importe al banco confirme el pago en - - https://salix.verdnatura.es/#!/client/',t.clientFk,'/web-payment') - FROM hedera.tpvTransaction t - WHERE t.receiptFk IS NULL - AND t.status = 'ok' - AND t.created < DATE_ADD(NOW(),INTERVAL - 2 DAY) - GROUP BY t.clientFk; - +BEGIN +/** + * + * Envia mail con los cobros web no + * trasladados a la ficha del cliente. + * + */ + INSERT INTO mail (receiver,replyTo,subject,body) + SELECT 'administracion@verdnatura.es', + 'noreply@verdnatura.es', + CONCAT('Cobro web no trasladado a la ficha del cliente ', t.clientFk), + CONCAT('Hay un importe de ', t.amount/100, '€ del cliente ', t.clientFk, ' con fecha ', t.created, + ', que no se ha trasladado a recibos. Si nos ha llegado el importe al banco confirme el pago en + + https://salix.verdnatura.es/#!/client/',t.clientFk,'/web-payment') + FROM hedera.tpvTransaction t + WHERE t.receiptFk IS NULL + AND t.status = 'ok' + AND t.created < DATE_ADD(NOW(),INTERVAL - 2 DAY) + GROUP BY t.clientFk; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -84204,21 +84929,21 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `travelVolume_get`(vFromDated DATE, vToDated DATE, vWarehouseFk INT) -BEGIN - - SELECT tr.landed Fecha, - a.name Agencia, - count(DISTINCT e.id) numEntradas, - FLOOR(sum(item_getVolume(b.itemFk, b.packageFk) * b.stickers / 1000000 )) AS m3 - FROM vn.travel tr - JOIN vn.agencyMode a ON a.id = tr.agencyFk - JOIN vn.entry e ON e.travelFk = tr.id - JOIN vn.buy b ON b.entryFk = e.id - WHERE tr.landed BETWEEN vFromDated AND vToDated - AND e.isRaid = FALSE - AND tr.warehouseInFk = vWarehouseFk - GROUP BY tr.landed , a.name ; - +BEGIN + + SELECT tr.landed Fecha, + a.name Agencia, + count(DISTINCT e.id) numEntradas, + FLOOR(sum(item_getVolume(b.itemFk, b.packageFk) * b.stickers / 1000000 )) AS m3 + FROM vn.travel tr + JOIN vn.agencyMode a ON a.id = tr.agencyFk + JOIN vn.entry e ON e.travelFk = tr.id + JOIN vn.buy b ON b.entryFk = e.id + WHERE tr.landed BETWEEN vFromDated AND vToDated + AND e.isRaid = FALSE + AND tr.warehouseInFk = vWarehouseFk + GROUP BY tr.landed , a.name ; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -84266,54 +84991,54 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `travel_clone`(vSelf INT, vDays INT, OUT vNewTravelFk INT) -BEGIN - - /** - * Clona un travel el número de dias indicado y devuelve su Id - * - * @param vSelf Identificador de vn.travel - * @param vDays Número de dias a futuro - * - * @return vNewTravelFk Nuevo número de travel - */ - - SELECT tr.id INTO vNewTravelFk - FROM vn.travel tr - JOIN vn.travel tr2 USING(shipped, warehouseInFk, warehouseOutFk, agencyFk, `ref`) - WHERE tr2.id = vSelf - AND tr.landed = TIMESTAMPADD(DAY, vDays, tr2.landed); - - IF ISNULL(vNewTravelFk) THEN - - START TRANSACTION; - - INSERT INTO vn.travel( shipped, - shipmentHour, - landed, - landingHour, - warehouseInFk, - warehouseOutFk, - agencyFk, - `ref`, - cargoSupplierFk) - SELECT shipped, - shipmentHour, - TIMESTAMPADD(DAY, vDays, landed), - landingHour, - warehouseInFk, - warehouseOutFk, - agencyFk, - `ref`, - cargoSupplierFk - FROM vn.travel - WHERE id = vSelf; - - SELECT LAST_INSERT_ID() INTO vNewTravelFk; - - COMMIT; - - END IF; - +BEGIN + + /** + * Clona un travel el número de dias indicado y devuelve su Id + * + * @param vSelf Identificador de vn.travel + * @param vDays Número de dias a futuro + * + * @return vNewTravelFk Nuevo número de travel + */ + + SELECT tr.id INTO vNewTravelFk + FROM vn.travel tr + JOIN vn.travel tr2 USING(shipped, warehouseInFk, warehouseOutFk, agencyFk, `ref`) + WHERE tr2.id = vSelf + AND tr.landed = TIMESTAMPADD(DAY, vDays, tr2.landed); + + IF ISNULL(vNewTravelFk) THEN + + START TRANSACTION; + + INSERT INTO vn.travel( shipped, + shipmentHour, + landed, + landingHour, + warehouseInFk, + warehouseOutFk, + agencyFk, + `ref`, + cargoSupplierFk) + SELECT shipped, + shipmentHour, + TIMESTAMPADD(DAY, vDays, landed), + landingHour, + warehouseInFk, + warehouseOutFk, + agencyFk, + `ref`, + cargoSupplierFk + FROM vn.travel + WHERE id = vSelf; + + SELECT LAST_INSERT_ID() INTO vNewTravelFk; + + COMMIT; + + END IF; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -84330,146 +85055,146 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `travel_cloneWithEntries`( - IN vTravelFk INT, - IN vDateStart DATE, - IN vDateEnd DATE, - IN vWarehouseOutFk INT, - IN vWarehouseInFk INT, - IN vRef VARCHAR(255), - IN vAgencyModeFk INT, +CREATE DEFINER=`root`@`localhost` PROCEDURE `travel_cloneWithEntries`( + IN vTravelFk INT, + IN vDateStart DATE, + IN vDateEnd DATE, + IN vWarehouseOutFk INT, + IN vWarehouseInFk INT, + IN vRef VARCHAR(255), + IN vAgencyModeFk INT, OUT vNewTravelFk INT) -BEGIN -/** - * Clona un travel junto con sus entradas y compras - * - * @param vTravelFk travel plantilla a clonar - * @param vDateStart fecha del shipment del nuevo travel - * @param vDateEnd fecha del landing del nuevo travel - * @param vWarehouseOutFk fecha del salida del nuevo travel - * @param vWarehouseInFk warehouse de landing del nuevo travel - * @param vRef referencia del nuevo travel - * @param vAgencyModeFk del nuevo travel - * @param vNewTravelFk id del nuevo travel - */ - DECLARE vEntryNew INT; - DECLARE vDone BOOLEAN DEFAULT FALSE; - DECLARE vAuxEntryFk INT; - DECLARE vRsEntry CURSOR FOR - SELECT e.id - FROM entry e - JOIN travel t - ON t.id = e.travelFk - WHERE e.travelFk = vTravelFk; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION/*, 1062 Duplicate key*/ - BEGIN - ROLLBACK; - - END; - - START TRANSACTION; - INSERT INTO travel (shipped, landed, warehouseInFk, warehouseOutFk, agencyFk, `ref`, isDelivered, isReceived, m3, kg) - SELECT vDateStart, vDateEnd, vWarehouseInFk, vWarehouseOutFk, vAgencyModeFk, vRef, isDelivered, isReceived, m3, kg - FROM travel - WHERE id = vTravelFk; - - SET vNewTravelFk = LAST_INSERT_ID(); - CALL logAdd(vNewTravelFk, 'insert', 'travel', CONCAT('clona travel ',vTravelFk)); - SET vDone = FALSE; - SET @isModeInventory = TRUE; - OPEN vRsEntry ; - FETCH vRsEntry INTO vAuxEntryFk; - - WHILE NOT vDone DO - INSERT INTO entry ( - supplierFk, - ref, - isInventory, - isConfirmed, - isOrdered, - isRaid, - commission, - created, - evaNotes, - travelFk, - currencyFk, - companyFk, - gestDocFk, - invoiceInFk) - SELECT supplierFk, - ref, - isInventory, - isConfirmed, - isOrdered, - isRaid, - commission, - created, - evaNotes, - vNewTravelFk, - currencyFk, - companyFk, - gestDocFk, - invoiceInFk - FROM entry - WHERE id = vAuxEntryFk; - - SET vEntryNew = LAST_INSERT_ID(); - - CALL logAdd(vEntryNew, 'insert', 'entry', CONCAT('clona entrada ',vAuxEntryFk)); - INSERT INTO buy ( - entryFk, - itemFk, - quantity, - buyingValue, - packageFk, - stickers, - freightValue, - packageValue, - comissionValue, - packing, - `grouping`, - groupingMode, - location, - price1, - price2, - price3, - minPrice, - producer, - printedStickers, - isChecked, - weight) - SELECT vEntryNew, - itemFk, - quantity, - buyingValue, - packageFk, - stickers, - freightValue, - packageValue, - comissionValue, - packing, - `grouping`, - groupingMode, - location, - price1, - price2, - price3, - minPrice, - producer, - printedStickers, - isChecked, - weight - FROM buy - WHERE entryFk = vAuxEntryFk; - - FETCH vRsEntry INTO vAuxEntryFk; - END WHILE; - SET @isModeInventory = FALSE; - CLOSE vRsEntry; - COMMIT; +BEGIN +/** + * Clona un travel junto con sus entradas y compras + * + * @param vTravelFk travel plantilla a clonar + * @param vDateStart fecha del shipment del nuevo travel + * @param vDateEnd fecha del landing del nuevo travel + * @param vWarehouseOutFk fecha del salida del nuevo travel + * @param vWarehouseInFk warehouse de landing del nuevo travel + * @param vRef referencia del nuevo travel + * @param vAgencyModeFk del nuevo travel + * @param vNewTravelFk id del nuevo travel + */ + DECLARE vEntryNew INT; + DECLARE vDone BOOLEAN DEFAULT FALSE; + DECLARE vAuxEntryFk INT; + DECLARE vRsEntry CURSOR FOR + SELECT e.id + FROM entry e + JOIN travel t + ON t.id = e.travelFk + WHERE e.travelFk = vTravelFk; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION/*, 1062 Duplicate key*/ + BEGIN + ROLLBACK; + + END; + + START TRANSACTION; + INSERT INTO travel (shipped, landed, warehouseInFk, warehouseOutFk, agencyFk, `ref`, isDelivered, isReceived, m3, kg) + SELECT vDateStart, vDateEnd, vWarehouseInFk, vWarehouseOutFk, vAgencyModeFk, vRef, isDelivered, isReceived, m3, kg + FROM travel + WHERE id = vTravelFk; + + SET vNewTravelFk = LAST_INSERT_ID(); + CALL logAdd(vNewTravelFk, 'insert', 'travel', CONCAT('clona travel ',vTravelFk)); + SET vDone = FALSE; + SET @isModeInventory = TRUE; + OPEN vRsEntry ; + FETCH vRsEntry INTO vAuxEntryFk; + + WHILE NOT vDone DO + INSERT INTO entry ( + supplierFk, + ref, + isInventory, + isConfirmed, + isOrdered, + isRaid, + commission, + created, + evaNotes, + travelFk, + currencyFk, + companyFk, + gestDocFk, + invoiceInFk) + SELECT supplierFk, + ref, + isInventory, + isConfirmed, + isOrdered, + isRaid, + commission, + created, + evaNotes, + vNewTravelFk, + currencyFk, + companyFk, + gestDocFk, + invoiceInFk + FROM entry + WHERE id = vAuxEntryFk; + + SET vEntryNew = LAST_INSERT_ID(); + + CALL logAdd(vEntryNew, 'insert', 'entry', CONCAT('clona entrada ',vAuxEntryFk)); + INSERT INTO buy ( + entryFk, + itemFk, + quantity, + buyingValue, + packageFk, + stickers, + freightValue, + packageValue, + comissionValue, + packing, + `grouping`, + groupingMode, + location, + price1, + price2, + price3, + minPrice, + producer, + printedStickers, + isChecked, + weight) + SELECT vEntryNew, + itemFk, + quantity, + buyingValue, + packageFk, + stickers, + freightValue, + packageValue, + comissionValue, + packing, + `grouping`, + groupingMode, + location, + price1, + price2, + price3, + minPrice, + producer, + printedStickers, + isChecked, + weight + FROM buy + WHERE entryFk = vAuxEntryFk; + + FETCH vRsEntry INTO vAuxEntryFk; + END WHILE; + SET @isModeInventory = FALSE; + CLOSE vRsEntry; + COMMIT; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -84912,60 +85637,60 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `typeTagMake`(vTypeFk INT) -BEGIN -/* - * Plantilla para modificar reemplazar todos los tags - * por los valores que tienen los articulos - * - * @param vTypeFk tipo a modificar - * - */ - DELETE it.* - FROM itemTag it - JOIN item i ON i.id = it.itemFk - WHERE i.typeFk = vTypeFk; - - INSERT INTO itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id, CONCAT(i.size,' cm'), 1 - FROM item i - JOIN tag t ON t.name = 'Longitud' COLLATE utf8_general_ci - WHERE i.typeFk = vTypeFk; - - INSERT INTO itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id, i.category, 5 - FROM item i - JOIN tag t ON t.name = 'Categoria' COLLATE utf8_general_ci - WHERE i.typeFk = vTypeFk; - - INSERT INTO itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id, ink.name, 2 - FROM item i - JOIN tag t ON t.name = 'Color' COLLATE utf8_general_ci - JOIN ink ON ink.id = i.inkFk - WHERE i.typeFk = vTypeFk; - - INSERT INTO itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id, p.name, 3 - FROM item i - JOIN tag t ON t.name = 'Productor' COLLATE utf8_general_ci - JOIN producer p ON p.id = i.producerFk - WHERE i.typeFk = vTypeFk; - - INSERT INTO itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id, o.name, 4 - FROM item i - JOIN tag t ON t.name = 'Origen' COLLATE utf8_general_ci - JOIN origin o ON o.id = i.originFk - WHERE i.typeFk = vTypeFk; - /* - INSERT INTO itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id, i.stems, 6 - FROM item i - JOIN tag t ON t.name = 'Tallos' COLLATE utf8_general_ci - WHERE i.typeFk = vTypeFk; - */ --- CALL itemTagArrangedUpdate(NULL); - +BEGIN +/* + * Plantilla para modificar reemplazar todos los tags + * por los valores que tienen los articulos + * + * @param vTypeFk tipo a modificar + * + */ + DELETE it.* + FROM itemTag it + JOIN item i ON i.id = it.itemFk + WHERE i.typeFk = vTypeFk; + + INSERT INTO itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id, CONCAT(i.size,' cm'), 1 + FROM item i + JOIN tag t ON t.name = 'Longitud' COLLATE utf8_general_ci + WHERE i.typeFk = vTypeFk; + + INSERT INTO itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id, i.category, 5 + FROM item i + JOIN tag t ON t.name = 'Categoria' COLLATE utf8_general_ci + WHERE i.typeFk = vTypeFk; + + INSERT INTO itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id, ink.name, 2 + FROM item i + JOIN tag t ON t.name = 'Color' COLLATE utf8_general_ci + JOIN ink ON ink.id = i.inkFk + WHERE i.typeFk = vTypeFk; + + INSERT INTO itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id, p.name, 3 + FROM item i + JOIN tag t ON t.name = 'Productor' COLLATE utf8_general_ci + JOIN producer p ON p.id = i.producerFk + WHERE i.typeFk = vTypeFk; + + INSERT INTO itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id, o.name, 4 + FROM item i + JOIN tag t ON t.name = 'Origen' COLLATE utf8_general_ci + JOIN origin o ON o.id = i.originFk + WHERE i.typeFk = vTypeFk; + /* + INSERT INTO itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id, i.stems, 6 + FROM item i + JOIN tag t ON t.name = 'Tallos' COLLATE utf8_general_ci + WHERE i.typeFk = vTypeFk; + */ +-- CALL itemTagArrangedUpdate(NULL); + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -86436,16 +87161,16 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerMistakeType_get`() -BEGIN - -/** - * Obtiene los tipos de error para los trabajadores - */ - - SELECT code, description - FROM workerMistakeType - ORDER BY description; - +BEGIN + +/** + * Obtiene los tipos de error para los trabajadores + */ + + SELECT code, description + FROM workerMistakeType + ORDER BY description; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -86463,27 +87188,27 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerMistake_add`(vWorkerFk INT, vWorkerMistakeTypeFk VARCHAR(10), vUserFk INT ) -BEGIN - -/** - * Añade error al trabajador - * - * @param vWorkerFk id del trabajador al cual se le va a añadir error - * @param vWorkerMistakeTypeFk code del tipo de error - * @param vUserFk id del usuario que pone el error - * - */ - DECLARE vWorkerName VARCHAR(255) DEFAULT account.user_getNameFromId(vUserFk); - - IF(account.user_hasRole(vWorkerName,'coolerBoss')) - THEN - INSERT INTO vn.workerMistake(userFk, workerMistakeTypeFk) - VALUES(vWorkerFk, vWorkerMistakeTypeFk); - ELSE - CALL util.throw('No tienes permisos para realizar la acción'); - - END IF; - +BEGIN + +/** + * Añade error al trabajador + * + * @param vWorkerFk id del trabajador al cual se le va a añadir error + * @param vWorkerMistakeTypeFk code del tipo de error + * @param vUserFk id del usuario que pone el error + * + */ + DECLARE vWorkerName VARCHAR(255) DEFAULT account.user_getNameFromId(vUserFk); + + IF(account.user_hasRole(vWorkerName,'coolerBoss')) + THEN + INSERT INTO vn.workerMistake(userFk, workerMistakeTypeFk) + VALUES(vWorkerFk, vWorkerMistakeTypeFk); + ELSE + CALL util.throw('No tienes permisos para realizar la acción'); + + END IF; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -86501,28 +87226,28 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerShelving_Add`(vWorkerFk INT, vBarcode VARCHAR(12)) -BEGIN -/* - * Inserta en workerShelving asociando los carros al trabajador - * @Param vWorkerFk es id del trabajador - * @Param vBarcode se puede pasar tanto el smarttag como el shelving - */ - DECLARE vIsShelvingFk BOOL; - - SELECT COUNT(*) > 0 INTO vIsShelvingFk - FROM vn.shelving s - WHERE s.code = vBarcode COLLATE utf8_general_ci; - - IF NOT vIsShelvingFk THEN - - SELECT st.shelvingFk INTO vBarcode - FROM vn.smartTag st - WHERE st.code = vBarcode COLLATE utf8_general_ci; - - END IF; - - INSERT INTO vn.workerShelving (workerFk, shelvingFk) - VALUES(vWorkerFk, vBarcode); +BEGIN +/* + * Inserta en workerShelving asociando los carros al trabajador + * @Param vWorkerFk es id del trabajador + * @Param vBarcode se puede pasar tanto el smarttag como el shelving + */ + DECLARE vIsShelvingFk BOOL; + + SELECT COUNT(*) > 0 INTO vIsShelvingFk + FROM vn.shelving s + WHERE s.code = vBarcode COLLATE utf8_general_ci; + + IF NOT vIsShelvingFk THEN + + SELECT st.shelvingFk INTO vBarcode + FROM vn.smartTag st + WHERE st.code = vBarcode COLLATE utf8_general_ci; + + END IF; + + INSERT INTO vn.workerShelving (workerFk, shelvingFk) + VALUES(vWorkerFk, vBarcode); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -86540,32 +87265,32 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerShelving_delete`(vWorkerFk INT, vBarcode VARCHAR(12)) -BEGIN -/* - * Borra de workerShelving el carro o etiqueta insertado por el trabajador - * @param vWorkerFk es id del trabajador - * @param vBarcode se puede pasar tanto el smarttag como el shelving - */ - DECLARE vIsShelvingFk BOOL; - - - SELECT COUNT(*) > 0 INTO vIsShelvingFk - FROM vn.shelving s - WHERE s.code = vBarcode COLLATE utf8_general_ci; - - - IF NOT vIsShelvingFk THEN - - SELECT st.shelvingFk INTO vBarcode - FROM vn.smartTag st - WHERE st.code = vBarcode COLLATE utf8_general_ci; - - END IF; - - DELETE FROM vn.workerShelving - WHERE shelvingFk = vBarcode COLLATE utf8_general_ci - AND workerFk = vWorkerFk ; - +BEGIN +/* + * Borra de workerShelving el carro o etiqueta insertado por el trabajador + * @param vWorkerFk es id del trabajador + * @param vBarcode se puede pasar tanto el smarttag como el shelving + */ + DECLARE vIsShelvingFk BOOL; + + + SELECT COUNT(*) > 0 INTO vIsShelvingFk + FROM vn.shelving s + WHERE s.code = vBarcode COLLATE utf8_general_ci; + + + IF NOT vIsShelvingFk THEN + + SELECT st.shelvingFk INTO vBarcode + FROM vn.smartTag st + WHERE st.code = vBarcode COLLATE utf8_general_ci; + + END IF; + + DELETE FROM vn.workerShelving + WHERE shelvingFk = vBarcode COLLATE utf8_general_ci + AND workerFk = vWorkerFk ; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -86843,32 +87568,32 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControl_calculateOddDays`() -BEGIN -/* - * Calculo de las fichadas impares por empleado y dia - * @return tmp.workerTimeControlOddDays (userFk, dated) - */ - SET @cont := FALSE; - SET @lastUserFk:= NULL; - DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControlOddDays; - CREATE TEMPORARY TABLE tmp.workerTimeControlOddDays - SELECT sub2.userFk workerFk, sub2.dated - FROM (SELECT userFk, - dated, - COUNT(*) cont2 - FROM (SELECT DATE(wtc.timed) dated, - userFk, - IFNULL(@cont, @cont := TRUE ), - IF(direction = 'in' OR userFk <> @lastUserFk, @cont := @cont+1, TRUE), - @cont cont, - @lastUserFk := userFk - FROM workerTimeControl wtc - WHERE wtc.timed BETWEEN TIMESTAMPADD(YEAR,-1,CURDATE()) AND util.dayEnd(CURDATE()) - ORDER BY userFk, timed)sub - GROUP BY cont - HAVING cont2 MOD 2 = 1)sub2 - JOIN worker w ON w.userFk = sub2.userFk; - +BEGIN +/* + * Calculo de las fichadas impares por empleado y dia + * @return tmp.workerTimeControlOddDays (userFk, dated) + */ + SET @cont := FALSE; + SET @lastUserFk:= NULL; + DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControlOddDays; + CREATE TEMPORARY TABLE tmp.workerTimeControlOddDays + SELECT sub2.userFk workerFk, sub2.dated + FROM (SELECT userFk, + dated, + COUNT(*) cont2 + FROM (SELECT DATE(wtc.timed) dated, + userFk, + IFNULL(@cont, @cont := TRUE ), + IF(direction = 'in' OR userFk <> @lastUserFk, @cont := @cont+1, TRUE), + @cont cont, + @lastUserFk := userFk + FROM workerTimeControl wtc + WHERE wtc.timed BETWEEN TIMESTAMPADD(YEAR,-1,CURDATE()) AND util.dayEnd(CURDATE()) + ORDER BY userFk, timed)sub + GROUP BY cont + HAVING cont2 MOD 2 = 1)sub2 + JOIN worker w ON w.userFk = sub2.userFk; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -87454,314 +88179,314 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControl_clockIn`(vWorker INT, vTimed DATETIME, vDirection VARCHAR(10)) -BEGIN -/** - * Verifica si el empleado puede fichar - * @param vWorker Identificador del trabajador - * @param vTimed valor de la fichada, IF vTimed IS NULL vTimed = NOW() - * @param vDirection solo se pueden pasa los valores del campo workerTimeControl.direction ENUM('in', 'out', 'middle') - * @return Si todo es correcto, retorna el número de id la tabla workerTimeControl. Si hay algún problema, devuelve el mesaje a que se debe mostrar al usuario - * Solo retorna el primer problema, en caso de no ocurrir ningún error se añadirá fichada a la tabla vn.workerTimeControl - */ - DECLARE vLastIn DATETIME; - DECLARE vLastOut DATETIME; - DECLARE vNextIn DATETIME; - DECLARE vLastDirection VARCHAR(6); - DECLARE vNextDirection VARCHAR(6); - DECLARE vDayBreak INT; - DECLARE vShortWeekBreak INT; - DECLARE vLongWeekBreak INT; - DECLARE vWeekScope INT; - DECLARE vGap INT; - DECLARE vMailTo VARCHAR(50) DEFAULT NULL; - DECLARE vUserName VARCHAR(50) DEFAULT NULL; - DECLARE vIsError BOOLEAN DEFAULT FALSE; - DECLARE vErrorMessage VARCHAR(255) DEFAULT NULL; - DECLARE vErrorCode VARCHAR(50); - DECLARE vDated DATE; - DECLARE vIsAllowedToWork VARCHAR(50); - DECLARE vDepartmentFk INT; - DECLARE vTimedLoop INT; - DECLARE vTimedLoopPrevious INT; - DECLARE vHasBreakWeek BOOLEAN DEFAULT FALSE; - DECLARE vManual BOOLEAN DEFAULT TRUE; - DECLARE vDone INT DEFAULT FALSE; - - DECLARE vCursor CURSOR FOR - SELECT UNIX_TIMESTAMP(NOW() - INTERVAL vGap SECOND) - UNION - SELECT UNIX_TIMESTAMP(NOW()) - UNION - (SELECT UNIX_TIMESTAMP(timed) - FROM workerTimeControl - WHERE timed BETWEEN (vTimed - INTERVAL vGap SECOND) AND vTimed AND - userFk = vWorker AND - direction IN ('in', 'out') - ORDER BY timed ASC); - - DECLARE vCursor2 CURSOR FOR - SELECT UNIX_TIMESTAMP(NOW() - INTERVAL vGap SECOND) - UNION - SELECT UNIX_TIMESTAMP(NOW()) - UNION - SELECT UNIX_TIMESTAMP(timed) - FROM workerTimeControl - WHERE timed BETWEEN vTimed AND (vTimed - INTERVAL vGap SECOND) AND - userFk = vWorker AND - direction IN ('in', 'out') - ORDER BY timed ASC; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - DECLARE EXIT HANDLER FOR SQLSTATE '45000' - BEGIN - - SELECT CONCAT(u.name, '@verdnatura.es'), CONCAT(w.firstName, ' ', w.lastName) - INTO vMailTo, vUserName - FROM account.user u - JOIN worker w ON w.bossFk = u.id - WHERE w.id = vWorker; - - CASE vErrorCode - WHEN 'IS_NOT_ALLOWED_FUTURE' THEN - SELECT 'No se permite fichar a futuro' INTO vErrorMessage; - WHEN 'INACTIVE_BUSINESS' THEN - SELECT 'No hay un contrato en vigor' INTO vErrorMessage; - WHEN 'IS_NOT_ALLOWED_WORK' THEN - SELECT 'No está permitido trabajar' INTO vErrorMessage; - WHEN 'ODD_WORKERTIMECONTROL' THEN - SELECT 'Fichadas impares' INTO vErrorMessage; - WHEN 'BREAK_DAY' THEN - SELECT CONCAT('Descanso diario ', FORMAT(vDayBreak/3600, 0) , 'h.') INTO vErrorMessage; - WHEN 'BREAK_WEEK' THEN - SELECT CONCAT('Descanso semanal ', - FORMAT(vShortWeekBreak / 3600,0) ,'h. / ', - FORMAT(vLongWeekBreak / 3600, 0) ,'h.') INTO vErrorMessage; - WHEN 'WRONG_DIRECTION' THEN - SELECT 'Dirección incorrecta' INTO vErrorMessage; - ELSE - SELECT 'Error sin definir'INTO vErrorMessage; - END CASE; - - SELECT vErrorMessage `error`; - SELECT CONCAT(vUserName, ' no ha podido fichar por el siguiente problema: ', vErrorMessage) INTO vErrorMessage; - CALL mail_insert( vMailTo, vMailTo, 'Error al fichar', vErrorMessage); - - END; - - IF (vTimed IS NULL) THEN - SET vTimed = NOW(); - SET vManual = FALSE; - END IF; - - SET vDated = DATE(vTimed); - - SELECT IF(pc.category_name = 'Conductor +3500kg', wc.dayBreakDriver, wc.dayBreak), - wc.shortWeekBreak, - wc.longWeekBreak, - wc.weekScope - INTO vDayBreak, - vShortWeekBreak, - vLongWeekBreak, - vWeekScope - FROM workerLabour w - JOIN postgresql.business_labour bl ON bl.business_id = w.businessFk - JOIN postgresql.professional_category pc ON pc.professional_category_id = bl.professional_category_id - JOIN workerTimeControlConfig wc ON TRUE - WHERE w.workerFk = vWorker - AND vDated BETWEEN w.started AND IFNULL(w.ended, vDated); - - SELECT timed INTO vLastIn - FROM workerTimeControl - WHERE userFk = vWorker - AND direction = 'in' - AND timed < vTimed - ORDER BY timed DESC - LIMIT 1; - - SELECT timed INTO vLastOut - FROM workerTimeControl - WHERE userFk = vWorker - AND direction = 'out' - AND timed < vTimed - ORDER BY timed DESC - LIMIT 1; - - SELECT timed INTO vNextIn - FROM workerTimeControl - WHERE userFk = vWorker - AND direction = 'in' - AND timed > vTimed - ORDER BY timed ASC - LIMIT 1; - - SELECT direction INTO vNextDirection - FROM workerTimeControl - WHERE userFk = vWorker - AND timed > vTimed - ORDER BY timed ASC - LIMIT 1; - - SELECT direction INTO vLastDirection - FROM workerTimeControl - WHERE userFk = vWorker - AND timed < vTimed - ORDER BY timed DESC - LIMIT 1; - - -- FICHADAS A FUTURO - IF vTimed > DATE_ADD(NOW(), INTERVAL 60 SECOND) THEN - SET vErrorCode = 'IS_NOT_ALLOWED_FUTURE'; - CALL util.throw(vErrorCode); - END IF; - - -- CONTRATO EN VIGOR - IF vDayBreak IS NULL THEN - SET vErrorCode = 'INACTIVE_BUSINESS'; - CALL util.throw(vErrorCode); - END IF; - - -- VERIFICAR SI ESTÁ PERMITIDO TRABAJAR - CALL timeBusiness_calculateByWorker(vWorker, vDated, vDated); - SELECT isAllowedToWork INTO vIsAllowedToWork - FROM tmp.timeBusinessCalculate; - DROP TEMPORARY TABLE tmp.timeBusinessCalculate; - - IF NOT vIsAllowedToWork THEN - SET vErrorCode = 'IS_NOT_ALLOWED_WORK'; - CALL util.throw(vErrorCode); - END IF; - - -- DIRECCION CORRECTA - CALL vn.workerTimeControl_direction(vWorker, vTimed); - IF (SELECT IF(IF(option1 IN ('inMiddle', 'outMiddle'), 'middle', option1) <> vDirection - AND IF(option2 IN ('inMiddle', 'outMiddle'), 'middle', IFNULL(option2, '')) <> vDirection, TRUE , FALSE) - FROM tmp.workerTimeControlDirection) THEN - SET vIsError = TRUE; - END IF; - - DROP TEMPORARY TABLE tmp.workerTimeControlDirection; - IF vIsError = TRUE THEN - SET vErrorCode = 'WRONG_DIRECTION'; - CALL util.throw(vErrorCode); - END IF; - - -- FICHADAS IMPARES - IF (SELECT IF(vDirection = 'in', MOD(COUNT(*), 2) , IF (vDirection = 'out', NOT MOD(COUNT(*), 2), FALSE)) - FROM workerTimeControl - WHERE userFk = vWorker - AND timed BETWEEN vLastIn AND vTimed - ) THEN - SET vErrorCode = 'ODD_WORKERTIMECONTROL'; - CALL util.throw(vErrorCode); - END IF; - - -- DESCANSO DIARIO - CASE vDirection - WHEN 'in' THEN - IF UNIX_TIMESTAMP(vTimed) - UNIX_TIMESTAMP(vLastOut) <= vDayBreak THEN - SET vIsError = TRUE; - END IF; - WHEN 'out' THEN - IF UNIX_TIMESTAMP(vNextIn) - UNIX_TIMESTAMP(vTimed) <= vDayBreak THEN - SET vIsError = TRUE; - END IF; - ELSE BEGIN END; - END CASE; - - IF vIsError THEN - SET vErrorCode = 'BREAK_DAY'; - CALL util.throw(vErrorCode); - END IF; - - -- VERIFICAR DESCANSO SEMANAL - IF (vDirection IN('in', 'out')) THEN - -- VERIFICA DESCANSO CORTO EN LA ÚLTIMA SEMANA - SET vGap = vWeekScope; - SET vTimedLoopPrevious = UNIX_TIMESTAMP((vTimed - INTERVAL vGap SECOND)); - SET vDone = FALSE; - OPEN vCursor; - l:LOOP - FETCH vCursor INTO vTimedLoop; - IF vDone THEN - LEAVE l; - END IF; - IF vShortWeekBreak - (vTimedLoop - vTimedLoopPrevious) < 0 THEN - SET vHasBreakWeek = TRUE; - LEAVE l; - END IF; - SET vTimedLoopPrevious = vTimedLoop; - END LOOP l; - CLOSE vCursor; - -- VERIFICA DESCANSO LARGO EN LA ÚLTIMAS 2 SEMANAS - IF NOT vHasBreakWeek THEN - SET vGap = vWeekScope * 2; - SET vTimedLoopPrevious = UNIX_TIMESTAMP((vTimed - INTERVAL vGap SECOND)); - SET vDone = FALSE; - OPEN vCursor; - l:LOOP - FETCH vCursor INTO vTimedLoop; - IF vDone THEN - LEAVE l; - END IF; - IF vLongWeekBreak - (vTimedLoop - vTimedLoopPrevious) < 0 THEN - SET vHasBreakWeek = TRUE; - LEAVE l; - END IF; - SET vTimedLoopPrevious = vTimedLoop; - END LOOP l; - CLOSE vCursor; - END IF; - - IF vManual THEN - -- VERIFICA DESCANSO CORTO EN LA PRÓXIMA SEMANA - SET vGap = vWeekScope; - SET vTimedLoopPrevious = vTimed; - SET vDone = FALSE; - OPEN vCursor; - l:LOOP - FETCH vCursor INTO vTimedLoop; - IF vDone THEN - LEAVE l; - END IF; - IF vShortWeekBreak - (vTimedLoop - vTimedLoopPrevious) < 0 THEN - SET vHasBreakWeek = TRUE; - LEAVE l; - END IF; - SET vTimedLoopPrevious = vTimedLoop; - END LOOP l; - CLOSE vCursor; - -- VERIFICA DESCANSO LARGO EN LAS PRÓXIMAS 2 SEMANAS - IF NOT vHasBreakWeek THEN - SET vGap = vWeekScope * 2; - SET vTimedLoopPrevious = vTimed; - SET vDone = FALSE; - OPEN vCursor; - l:LOOP - FETCH vCursor INTO vTimedLoop; - IF vDone THEN - LEAVE l; - END IF; - IF vShortWeekBreak - (vTimedLoop - vTimedLoopPrevious) < 0 THEN - SET vHasBreakWeek = TRUE; - LEAVE l; - END IF; - SET vTimedLoopPrevious = vTimedLoop; - END LOOP l; - CLOSE vCursor; - END IF; - END IF; - IF NOT vHasBreakWeek THEN - SET vErrorCode = 'BREAK_WEEK'; - CALL util.throw(vErrorCode); - END IF; - END IF; - - -- SE PERMITE FICHAR - INSERT INTO workerTimeControl(userFk, timed, direction, manual) - VALUES(vWorker, vTimed, vDirection, vManual); - - SELECT LAST_INSERT_ID() id; +BEGIN +/** + * Verifica si el empleado puede fichar + * @param vWorker Identificador del trabajador + * @param vTimed valor de la fichada, IF vTimed IS NULL vTimed = NOW() + * @param vDirection solo se pueden pasa los valores del campo workerTimeControl.direction ENUM('in', 'out', 'middle') + * @return Si todo es correcto, retorna el número de id la tabla workerTimeControl. Si hay algún problema, devuelve el mesaje a que se debe mostrar al usuario + * Solo retorna el primer problema, en caso de no ocurrir ningún error se añadirá fichada a la tabla vn.workerTimeControl + */ + DECLARE vLastIn DATETIME; + DECLARE vLastOut DATETIME; + DECLARE vNextIn DATETIME; + DECLARE vLastDirection VARCHAR(6); + DECLARE vNextDirection VARCHAR(6); + DECLARE vDayBreak INT; + DECLARE vShortWeekBreak INT; + DECLARE vLongWeekBreak INT; + DECLARE vWeekScope INT; + DECLARE vGap INT; + DECLARE vMailTo VARCHAR(50) DEFAULT NULL; + DECLARE vUserName VARCHAR(50) DEFAULT NULL; + DECLARE vIsError BOOLEAN DEFAULT FALSE; + DECLARE vErrorMessage VARCHAR(255) DEFAULT NULL; + DECLARE vErrorCode VARCHAR(50); + DECLARE vDated DATE; + DECLARE vIsAllowedToWork VARCHAR(50); + DECLARE vDepartmentFk INT; + DECLARE vTimedLoop INT; + DECLARE vTimedLoopPrevious INT; + DECLARE vHasBreakWeek BOOLEAN DEFAULT FALSE; + DECLARE vManual BOOLEAN DEFAULT TRUE; + DECLARE vDone INT DEFAULT FALSE; + + DECLARE vCursor CURSOR FOR + SELECT UNIX_TIMESTAMP(NOW() - INTERVAL vGap SECOND) + UNION + SELECT UNIX_TIMESTAMP(NOW()) + UNION + (SELECT UNIX_TIMESTAMP(timed) + FROM workerTimeControl + WHERE timed BETWEEN (vTimed - INTERVAL vGap SECOND) AND vTimed AND + userFk = vWorker AND + direction IN ('in', 'out') + ORDER BY timed ASC); + + DECLARE vCursor2 CURSOR FOR + SELECT UNIX_TIMESTAMP(NOW() - INTERVAL vGap SECOND) + UNION + SELECT UNIX_TIMESTAMP(NOW()) + UNION + SELECT UNIX_TIMESTAMP(timed) + FROM workerTimeControl + WHERE timed BETWEEN vTimed AND (vTimed - INTERVAL vGap SECOND) AND + userFk = vWorker AND + direction IN ('in', 'out') + ORDER BY timed ASC; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + DECLARE EXIT HANDLER FOR SQLSTATE '45000' + BEGIN + + SELECT CONCAT(u.name, '@verdnatura.es'), CONCAT(w.firstName, ' ', w.lastName) + INTO vMailTo, vUserName + FROM account.user u + JOIN worker w ON w.bossFk = u.id + WHERE w.id = vWorker; + + CASE vErrorCode + WHEN 'IS_NOT_ALLOWED_FUTURE' THEN + SELECT 'No se permite fichar a futuro' INTO vErrorMessage; + WHEN 'INACTIVE_BUSINESS' THEN + SELECT 'No hay un contrato en vigor' INTO vErrorMessage; + WHEN 'IS_NOT_ALLOWED_WORK' THEN + SELECT 'No está permitido trabajar' INTO vErrorMessage; + WHEN 'ODD_WORKERTIMECONTROL' THEN + SELECT 'Fichadas impares' INTO vErrorMessage; + WHEN 'BREAK_DAY' THEN + SELECT CONCAT('Descanso diario ', FORMAT(vDayBreak/3600, 0) , 'h.') INTO vErrorMessage; + WHEN 'BREAK_WEEK' THEN + SELECT CONCAT('Descanso semanal ', + FORMAT(vShortWeekBreak / 3600,0) ,'h. / ', + FORMAT(vLongWeekBreak / 3600, 0) ,'h.') INTO vErrorMessage; + WHEN 'WRONG_DIRECTION' THEN + SELECT 'Dirección incorrecta' INTO vErrorMessage; + ELSE + SELECT 'Error sin definir'INTO vErrorMessage; + END CASE; + + SELECT vErrorMessage `error`; + SELECT CONCAT(vUserName, ' no ha podido fichar por el siguiente problema: ', vErrorMessage) INTO vErrorMessage; + CALL mail_insert( vMailTo, vMailTo, 'Error al fichar', vErrorMessage); + + END; + + IF (vTimed IS NULL) THEN + SET vTimed = NOW(); + SET vManual = FALSE; + END IF; + + SET vDated = DATE(vTimed); + + SELECT IF(pc.category_name = 'Conductor +3500kg', wc.dayBreakDriver, wc.dayBreak), + wc.shortWeekBreak, + wc.longWeekBreak, + wc.weekScope + INTO vDayBreak, + vShortWeekBreak, + vLongWeekBreak, + vWeekScope + FROM workerLabour w + JOIN postgresql.business_labour bl ON bl.business_id = w.businessFk + JOIN postgresql.professional_category pc ON pc.professional_category_id = bl.professional_category_id + JOIN workerTimeControlConfig wc ON TRUE + WHERE w.workerFk = vWorker + AND vDated BETWEEN w.started AND IFNULL(w.ended, vDated); + + SELECT timed INTO vLastIn + FROM workerTimeControl + WHERE userFk = vWorker + AND direction = 'in' + AND timed < vTimed + ORDER BY timed DESC + LIMIT 1; + + SELECT timed INTO vLastOut + FROM workerTimeControl + WHERE userFk = vWorker + AND direction = 'out' + AND timed < vTimed + ORDER BY timed DESC + LIMIT 1; + + SELECT timed INTO vNextIn + FROM workerTimeControl + WHERE userFk = vWorker + AND direction = 'in' + AND timed > vTimed + ORDER BY timed ASC + LIMIT 1; + + SELECT direction INTO vNextDirection + FROM workerTimeControl + WHERE userFk = vWorker + AND timed > vTimed + ORDER BY timed ASC + LIMIT 1; + + SELECT direction INTO vLastDirection + FROM workerTimeControl + WHERE userFk = vWorker + AND timed < vTimed + ORDER BY timed DESC + LIMIT 1; + + -- FICHADAS A FUTURO + IF vTimed > DATE_ADD(NOW(), INTERVAL 60 SECOND) THEN + SET vErrorCode = 'IS_NOT_ALLOWED_FUTURE'; + CALL util.throw(vErrorCode); + END IF; + + -- CONTRATO EN VIGOR + IF vDayBreak IS NULL THEN + SET vErrorCode = 'INACTIVE_BUSINESS'; + CALL util.throw(vErrorCode); + END IF; + + -- VERIFICAR SI ESTÁ PERMITIDO TRABAJAR + CALL timeBusiness_calculateByWorker(vWorker, vDated, vDated); + SELECT isAllowedToWork INTO vIsAllowedToWork + FROM tmp.timeBusinessCalculate; + DROP TEMPORARY TABLE tmp.timeBusinessCalculate; + + IF NOT vIsAllowedToWork THEN + SET vErrorCode = 'IS_NOT_ALLOWED_WORK'; + CALL util.throw(vErrorCode); + END IF; + + -- DIRECCION CORRECTA + CALL vn.workerTimeControl_direction(vWorker, vTimed); + IF (SELECT IF(IF(option1 IN ('inMiddle', 'outMiddle'), 'middle', option1) <> vDirection + AND IF(option2 IN ('inMiddle', 'outMiddle'), 'middle', IFNULL(option2, '')) <> vDirection, TRUE , FALSE) + FROM tmp.workerTimeControlDirection) THEN + SET vIsError = TRUE; + END IF; + + DROP TEMPORARY TABLE tmp.workerTimeControlDirection; + IF vIsError = TRUE THEN + SET vErrorCode = 'WRONG_DIRECTION'; + CALL util.throw(vErrorCode); + END IF; + + -- FICHADAS IMPARES + IF (SELECT IF(vDirection = 'in', MOD(COUNT(*), 2) , IF (vDirection = 'out', NOT MOD(COUNT(*), 2), FALSE)) + FROM workerTimeControl + WHERE userFk = vWorker + AND timed BETWEEN vLastIn AND vTimed + ) THEN + SET vErrorCode = 'ODD_WORKERTIMECONTROL'; + CALL util.throw(vErrorCode); + END IF; + + -- DESCANSO DIARIO + CASE vDirection + WHEN 'in' THEN + IF UNIX_TIMESTAMP(vTimed) - UNIX_TIMESTAMP(vLastOut) <= vDayBreak THEN + SET vIsError = TRUE; + END IF; + WHEN 'out' THEN + IF UNIX_TIMESTAMP(vNextIn) - UNIX_TIMESTAMP(vTimed) <= vDayBreak THEN + SET vIsError = TRUE; + END IF; + ELSE BEGIN END; + END CASE; + + IF vIsError THEN + SET vErrorCode = 'BREAK_DAY'; + CALL util.throw(vErrorCode); + END IF; + + -- VERIFICAR DESCANSO SEMANAL + IF (vDirection IN('in', 'out')) THEN + -- VERIFICA DESCANSO CORTO EN LA ÚLTIMA SEMANA + SET vGap = vWeekScope; + SET vTimedLoopPrevious = UNIX_TIMESTAMP((vTimed - INTERVAL vGap SECOND)); + SET vDone = FALSE; + OPEN vCursor; + l:LOOP + FETCH vCursor INTO vTimedLoop; + IF vDone THEN + LEAVE l; + END IF; + IF vShortWeekBreak - (vTimedLoop - vTimedLoopPrevious) < 0 THEN + SET vHasBreakWeek = TRUE; + LEAVE l; + END IF; + SET vTimedLoopPrevious = vTimedLoop; + END LOOP l; + CLOSE vCursor; + -- VERIFICA DESCANSO LARGO EN LA ÚLTIMAS 2 SEMANAS + IF NOT vHasBreakWeek THEN + SET vGap = vWeekScope * 2; + SET vTimedLoopPrevious = UNIX_TIMESTAMP((vTimed - INTERVAL vGap SECOND)); + SET vDone = FALSE; + OPEN vCursor; + l:LOOP + FETCH vCursor INTO vTimedLoop; + IF vDone THEN + LEAVE l; + END IF; + IF vLongWeekBreak - (vTimedLoop - vTimedLoopPrevious) < 0 THEN + SET vHasBreakWeek = TRUE; + LEAVE l; + END IF; + SET vTimedLoopPrevious = vTimedLoop; + END LOOP l; + CLOSE vCursor; + END IF; + + IF vManual THEN + -- VERIFICA DESCANSO CORTO EN LA PRÓXIMA SEMANA + SET vGap = vWeekScope; + SET vTimedLoopPrevious = vTimed; + SET vDone = FALSE; + OPEN vCursor; + l:LOOP + FETCH vCursor INTO vTimedLoop; + IF vDone THEN + LEAVE l; + END IF; + IF vShortWeekBreak - (vTimedLoop - vTimedLoopPrevious) < 0 THEN + SET vHasBreakWeek = TRUE; + LEAVE l; + END IF; + SET vTimedLoopPrevious = vTimedLoop; + END LOOP l; + CLOSE vCursor; + -- VERIFICA DESCANSO LARGO EN LAS PRÓXIMAS 2 SEMANAS + IF NOT vHasBreakWeek THEN + SET vGap = vWeekScope * 2; + SET vTimedLoopPrevious = vTimed; + SET vDone = FALSE; + OPEN vCursor; + l:LOOP + FETCH vCursor INTO vTimedLoop; + IF vDone THEN + LEAVE l; + END IF; + IF vShortWeekBreak - (vTimedLoop - vTimedLoopPrevious) < 0 THEN + SET vHasBreakWeek = TRUE; + LEAVE l; + END IF; + SET vTimedLoopPrevious = vTimedLoop; + END LOOP l; + CLOSE vCursor; + END IF; + END IF; + IF NOT vHasBreakWeek THEN + SET vErrorCode = 'BREAK_WEEK'; + CALL util.throw(vErrorCode); + END IF; + END IF; + + -- SE PERMITE FICHAR + INSERT INTO workerTimeControl(userFk, timed, direction, manual) + VALUES(vWorker, vTimed, vDirection, vManual); + + SELECT LAST_INSERT_ID() id; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -87774,9 +88499,9 @@ DELIMITER ; /*!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 collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControl_direction`(vWorkerFk VARCHAR(10), vTimed DATETIME) BEGIN @@ -87793,6 +88518,80 @@ BEGIN SET vTimed = NOW(); END IF; + SELECT timed INTO vLastIn + FROM workerTimeControl + WHERE userFk = vWorkerFk + AND direction = 'in' + AND timed < vTimed + ORDER BY timed DESC + LIMIT 1; + + SELECT (COUNT(*)mod 2 = 1) INTO vIsMiddleOdd + FROM workerTimeControl + WHERE userFk = vWorkerFk + AND direction = 'middle' + AND timed BETWEEN vLastIn AND NOW(); + + DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControlDirection; + CREATE TEMPORARY TABLE tmp.workerTimeControlDirection + SELECT IF(isCorrect, option1, NULL) option1, + IF(isCorrect, option2, NULL) option2 + FROM( SELECT IF(w.direction <> 'out' AND (UNIX_TIMESTAMP(vTimed) - UNIX_TIMESTAMP(w.timed) > wc.dayBreak), FALSE, TRUE) isCorrect, + CASE WHEN w.direction ='in' THEN 'inMiddle' + WHEN w.direction = 'out' THEN 'in' + WHEN w.direction = 'middle' AND vIsMiddleOdd THEN 'outMiddle' + WHEN w.direction IS NULL THEN 'in' + ELSE 'inMiddle' + END option1, + CASE WHEN w.direction ='in' THEN 'out' + WHEN w.direction = 'out' THEN NULL + WHEN w.direction = 'middle' AND vIsMiddleOdd THEN NULL + WHEN w.direction IS NULL THEN NULL + ELSE 'out' + END option2 + FROM workerTimeControl w + JOIN workerTimeControlConfig wc ON TRUE + WHERE w.timed <= vTimed + AND w.userFk = vWorkerFk + ORDER BY w.timed DESC + LIMIT 1)sub; + + IF (SELECT IF(COUNT(*)=0, TRUE, FALSE) FROM tmp.workerTimeControlDirection ) THEN + INSERT INTO tmp.workerTimeControlDirection (option1, option2) + VALUES('in', NULL); + 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 `workerTimeControl_direction__` */; +/*!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`@`localhost` PROCEDURE `workerTimeControl_direction__`(vWorkerFk VARCHAR(10), vTimed DATETIME) +BEGIN +/** + * Devuelve que direcciones de fichadas son lógicas a partir de la anterior fichada + * @param vWorkerFk Identificador del trabajador + * @return (option1, option2) + * Los valores posibles de retorno son ('in', 'inMiddle', 'outMiddle', 'out') + */ + DECLARE vLastIn DATETIME ; + DECLARE vIsMiddleOdd BOOLEAN ; + + IF (vTimed IS NULL) THEN + SET vTimed = NOW(); + END IF; + SELECT timed INTO vLastIn FROM workerTimeControl WHERE userFk = vWorkerFk @@ -88387,7 +89186,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControl_sendMailByDepartm BEGIN /** - * Inserta el registro de horario semanalmente de PRODUCCION, CAMARA, TALLER NATURAL y TALLER ARTIFICIAL en vn.mail. + * Inserta el registro de horario semanalmente de PRODUCCION, CAMARA, REPARTO, TALLER NATURAL y TALLER ARTIFICIAL en vn.mail. * * @param vWeek * @param vYear @@ -88470,8 +89269,8 @@ BEGIN @@ -89661,21 +90460,21 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `worker_getFromHasMistake`(vDepartmentFk INT) -BEGIN - -/** - * Obtiene los trabajadores de los departamentos que se les puede poner error - * @param vDepartmentFk id del departamento - * - */ - - SELECT w.id,w.firstName, w.lastName,d.name - FROM worker w - JOIN workerDepartment wd ON wd.workerFk = w.id - JOIN department d ON d.id = wd.departmentFk - WHERE d.id = vDepartmentFk - ORDER BY firstName; - +BEGIN + +/** + * Obtiene los trabajadores de los departamentos que se les puede poner error + * @param vDepartmentFk id del departamento + * + */ + + SELECT w.id,w.firstName, w.lastName,d.name + FROM worker w + JOIN workerDepartment wd ON wd.workerFk = w.id + JOIN department d ON d.id = wd.departmentFk + WHERE d.id = vDepartmentFk + ORDER BY firstName; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -89887,17 +90686,17 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `worker_getSector`() -BEGIN - -/** - * Obtiene el sector del usuario conectado -*/ - - SELECT s.id,s.description,s.warehouseFk - FROM sector s - JOIN worker w ON w.sectorFk = s.id - WHERE w.id = account.userGetId(); - +BEGIN + +/** + * Obtiene el sector del usuario conectado +*/ + + SELECT s.id,s.description,s.warehouseFk + FROM sector s + JOIN worker w ON w.sectorFk = s.id + WHERE w.id = account.userGetId(); + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -89915,18 +90714,18 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `worker_updateSector`(vSectorFk INT) -BEGIN - -/** - * ACtualiza el sector del usuario conectado - * - * @param vSectorFk id del sector -*/ - UPDATE worker - SET sectorFk = vSectorFk - WHERE id = account.userGetId(); - - +BEGIN + +/** + * ACtualiza el sector del usuario conectado + * + * @param vSectorFk id del sector +*/ + UPDATE worker + SET sectorFk = vSectorFk + WHERE id = account.userGetId(); + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -90580,23 +91379,23 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_ETD_byTime`() -BEGIN - - SET @m := 0; - - DROP TEMPORARY TABLE IF EXISTS tmpZone; - CREATE TEMPORARY TABLE tmpZone - SELECT remainingVolume, - hourTheoretical, - @m := @m + minutesLess totalMinutes - FROM zoneEstimatedDelivery ze - WHERE ze.remainingVolume - ORDER BY ze.hourTheoretical DESC; - - SELECT * FROM tmpZone; - - DROP TABLE tmpZone; - +BEGIN + + SET @m := 0; + + DROP TEMPORARY TABLE IF EXISTS tmpZone; + CREATE TEMPORARY TABLE tmpZone + SELECT remainingVolume, + hourTheoretical, + @m := @m + minutesLess totalMinutes + FROM zoneEstimatedDelivery ze + WHERE ze.remainingVolume + ORDER BY ze.hourTheoretical DESC; + + SELECT * FROM tmpZone; + + DROP TABLE tmpZone; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -91123,106 +91922,106 @@ DELIMITER ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getLeaves2`(vSelf INT, vParentFk INT, vSearch VARCHAR(255)) -BEGIN -/** - * 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 - * @param vSearch cadena a buscar - * - * @return tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) - * - */ - DECLARE vIsNumber BOOL; - DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch != ''; - - DROP TEMPORARY TABLE IF EXISTS tNodes; - CREATE TEMPORARY TABLE tNodes - (UNIQUE (id)) - ENGINE = MEMORY - SELECT id - FROM zoneGeo - LIMIT 0; - - IF vIsSearch THEN - SET vIsNumber = vSearch REGEXP '^[0-9]+$'; - - INSERT INTO tNodes - SELECT id - FROM zoneGeo - WHERE (vIsNumber AND `name` = vSearch) - OR (!vIsNumber AND `name` LIKE CONCAT('%', vSearch, '%')) - LIMIT 1000; - - ELSEIF vParentFk IS NULL THEN - INSERT INTO tNodes - SELECT geoFk - FROM zoneIncluded - WHERE zoneFk = vSelf; - END IF; - - IF vParentFk IS NULL THEN - DROP TEMPORARY TABLE IF EXISTS tChilds; - CREATE TEMPORARY TABLE tChilds - (INDEX(id)) - ENGINE = MEMORY - SELECT id - FROM tNodes; - - DROP TEMPORARY TABLE IF EXISTS tParents; - CREATE TEMPORARY TABLE tParents - (INDEX(id)) - ENGINE = MEMORY - SELECT id - FROM zoneGeo - LIMIT 0; - - myLoop: LOOP - DELETE FROM tParents; - INSERT INTO tParents - SELECT parentFk id - FROM zoneGeo g - JOIN tChilds c ON c.id = g.id - WHERE g.parentFk IS NOT NULL; - - INSERT IGNORE INTO tNodes - SELECT id - FROM tParents; - - IF ROW_COUNT() = 0 THEN - LEAVE myLoop; - END IF; - - DELETE FROM tChilds; - INSERT INTO tChilds - SELECT id - FROM tParents; - END LOOP; - - DROP TEMPORARY TABLE tChilds, tParents; - END IF; - - IF !vIsSearch THEN - INSERT IGNORE INTO tNodes - SELECT id - FROM zoneGeo - WHERE parentFk <=> vParentFk; - END IF; - - INSERT IGNORE INTO tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) - SELECT g.id, - g.`name`, - g.parentFk, - g.sons, - NOT g.sons OR type = 'country', - 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); - - DROP TEMPORARY TABLE tNodes; +BEGIN +/** + * 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 + * @param vSearch cadena a buscar + * + * @return tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) + * + */ + DECLARE vIsNumber BOOL; + DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch != ''; + + DROP TEMPORARY TABLE IF EXISTS tNodes; + CREATE TEMPORARY TABLE tNodes + (UNIQUE (id)) + ENGINE = MEMORY + SELECT id + FROM zoneGeo + LIMIT 0; + + IF vIsSearch THEN + SET vIsNumber = vSearch REGEXP '^[0-9]+$'; + + INSERT INTO tNodes + SELECT id + FROM zoneGeo + WHERE (vIsNumber AND `name` = vSearch) + OR (!vIsNumber AND `name` LIKE CONCAT('%', vSearch, '%')) + LIMIT 1000; + + ELSEIF vParentFk IS NULL THEN + INSERT INTO tNodes + SELECT geoFk + FROM zoneIncluded + WHERE zoneFk = vSelf; + END IF; + + IF vParentFk IS NULL THEN + DROP TEMPORARY TABLE IF EXISTS tChilds; + CREATE TEMPORARY TABLE tChilds + (INDEX(id)) + ENGINE = MEMORY + SELECT id + FROM tNodes; + + DROP TEMPORARY TABLE IF EXISTS tParents; + CREATE TEMPORARY TABLE tParents + (INDEX(id)) + ENGINE = MEMORY + SELECT id + FROM zoneGeo + LIMIT 0; + + myLoop: LOOP + DELETE FROM tParents; + INSERT INTO tParents + SELECT parentFk id + FROM zoneGeo g + JOIN tChilds c ON c.id = g.id + WHERE g.parentFk IS NOT NULL; + + INSERT IGNORE INTO tNodes + SELECT id + FROM tParents; + + IF ROW_COUNT() = 0 THEN + LEAVE myLoop; + END IF; + + DELETE FROM tChilds; + INSERT INTO tChilds + SELECT id + FROM tParents; + END LOOP; + + DROP TEMPORARY TABLE tChilds, tParents; + END IF; + + IF !vIsSearch THEN + INSERT IGNORE INTO tNodes + SELECT id + FROM zoneGeo + WHERE parentFk <=> vParentFk; + END IF; + + INSERT IGNORE INTO tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) + SELECT g.id, + g.`name`, + g.parentFk, + g.sons, + NOT g.sons OR type = 'country', + 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); + + DROP TEMPORARY TABLE tNodes; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -91239,94 +92038,94 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getLeaves___`( - vSelf INT, - vParentFk INT, - vSearch VARCHAR(255) +CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getLeaves___`( + vSelf INT, + vParentFk INT, + vSearch VARCHAR(255) ) -BEGIN - DECLARE vIsNumber BOOL; - DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch != ''; - - DROP TEMPORARY TABLE IF EXISTS tNodes; - CREATE TEMPORARY TABLE tNodes - (UNIQUE (id)) - ENGINE = MEMORY - SELECT id FROM zoneGeo LIMIT 0; - - IF vIsSearch THEN - SET vIsNumber = vSearch REGEXP '^[0-9]+$'; - - INSERT INTO tNodes - SELECT id FROM zoneGeo - WHERE (vIsNumber AND `name` = vSearch) - OR (!vIsNumber AND `name` LIKE CONCAT('%', vSearch, '%')) - LIMIT 1000; - ELSEIF vParentFk IS NULL THEN - INSERT INTO tNodes - SELECT geoFk FROM zoneIncluded - WHERE zoneFk = vSelf; - END IF; - - IF vParentFk IS NULL THEN - DROP TEMPORARY TABLE IF EXISTS tChilds; - CREATE TEMPORARY TABLE tChilds - ENGINE = MEMORY - SELECT id FROM tNodes; - - DROP TEMPORARY TABLE IF EXISTS tParents; - CREATE TEMPORARY TABLE tParents - ENGINE = MEMORY - SELECT id FROM zoneGeo LIMIT 0; - - myLoop: LOOP - DELETE FROM tParents; - INSERT INTO tParents - SELECT parentFk id - FROM zoneGeo g - JOIN tChilds c ON c.id = g.id - WHERE g.parentFk IS NOT NULL; - - INSERT IGNORE INTO tNodes - SELECT id FROM tParents; - - IF ROW_COUNT() = 0 THEN - LEAVE myLoop; - END IF; - - DELETE FROM tChilds; - INSERT INTO tChilds - SELECT id FROM tParents; - END LOOP; - - DROP TEMPORARY TABLE - tChilds, - tParents; - END IF; - - IF !vIsSearch THEN - INSERT IGNORE INTO tNodes - SELECT id FROM zoneGeo - WHERE parentFk <=> vParentFk; - END IF; - - - INSERT IGNORE INTO zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) - SELECT g.id, - g.`name`, - g.parentFk, - g.sons, - NOT g.sons OR type = 'country', - 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)) - ; - - DROP TEMPORARY TABLE tNodes; +BEGIN + DECLARE vIsNumber BOOL; + DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch != ''; + + DROP TEMPORARY TABLE IF EXISTS tNodes; + CREATE TEMPORARY TABLE tNodes + (UNIQUE (id)) + ENGINE = MEMORY + SELECT id FROM zoneGeo LIMIT 0; + + IF vIsSearch THEN + SET vIsNumber = vSearch REGEXP '^[0-9]+$'; + + INSERT INTO tNodes + SELECT id FROM zoneGeo + WHERE (vIsNumber AND `name` = vSearch) + OR (!vIsNumber AND `name` LIKE CONCAT('%', vSearch, '%')) + LIMIT 1000; + ELSEIF vParentFk IS NULL THEN + INSERT INTO tNodes + SELECT geoFk FROM zoneIncluded + WHERE zoneFk = vSelf; + END IF; + + IF vParentFk IS NULL THEN + DROP TEMPORARY TABLE IF EXISTS tChilds; + CREATE TEMPORARY TABLE tChilds + ENGINE = MEMORY + SELECT id FROM tNodes; + + DROP TEMPORARY TABLE IF EXISTS tParents; + CREATE TEMPORARY TABLE tParents + ENGINE = MEMORY + SELECT id FROM zoneGeo LIMIT 0; + + myLoop: LOOP + DELETE FROM tParents; + INSERT INTO tParents + SELECT parentFk id + FROM zoneGeo g + JOIN tChilds c ON c.id = g.id + WHERE g.parentFk IS NOT NULL; + + INSERT IGNORE INTO tNodes + SELECT id FROM tParents; + + IF ROW_COUNT() = 0 THEN + LEAVE myLoop; + END IF; + + DELETE FROM tChilds; + INSERT INTO tChilds + SELECT id FROM tParents; + END LOOP; + + DROP TEMPORARY TABLE + tChilds, + tParents; + END IF; + + IF !vIsSearch THEN + INSERT IGNORE INTO tNodes + SELECT id FROM zoneGeo + WHERE parentFk <=> vParentFk; + END IF; + + + INSERT IGNORE INTO zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) + SELECT g.id, + g.`name`, + g.parentFk, + g.sons, + NOT g.sons OR type = 'country', + 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)) + ; + + DROP TEMPORARY TABLE tNodes; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -91909,19 +92708,19 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vncontrol`.`ticketTracking_afterInsert` - AFTER INSERT ON `inter` - FOR EACH ROW -BEGIN - - DECLARE vNumTicketsPrepared INT; - - REPLACE vn.ticketLastState(ticketFk, ticketTrackingFk, name) - SELECT NEW.Id_Ticket, NEW.inter_id, `name` - FROM vn.state - WHERE id = NEW.state_id; - - +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vncontrol`.`ticketTracking_afterInsert` + AFTER INSERT ON `inter` + FOR EACH ROW +BEGIN + + DECLARE vNumTicketsPrepared INT; + + REPLACE vn.ticketLastState(ticketFk, ticketTrackingFk, name) + SELECT NEW.Id_Ticket, NEW.inter_id, `name` + FROM vn.state + WHERE id = NEW.state_id; + + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -92391,6 +93190,25 @@ USE `edi`; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; +-- +-- Final view structure for view `supplyOffer` +-- + +/*!50001 DROP TABLE IF EXISTS `supplyOffer`*/; +/*!50001 DROP VIEW IF EXISTS `supplyOffer`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8mb4 */; +/*!50001 SET character_set_results = utf8mb4 */; +/*!50001 SET collation_connection = utf8mb4_unicode_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ +/*!50001 VIEW `supplyOffer` AS select `sr`.`vmpID` AS `vmpID`,`di`.`ID` AS `diId`,`sr`.`ID` AS `srId`,`sr`.`Item_ArticleCode` AS `Item_ArticleCode`,`sr`.`VBNOmschrijving` AS `product_name`,`s`.`company_name` AS `company_name`,cast(`sr`.`Price` as decimal(10,3)) AS `Price`,`sr`.`Quality` AS `Quality`,`sr`.`s1` AS `s1`,`sr`.`s2` AS `s2`,`sr`.`s3` AS `s3`,`sr`.`s4` AS `s4`,`sr`.`s5` AS `s5`,`sr`.`s6` AS `s6`,`sr`.`NumberOfUnits` AS `NumberOfUnits`,least(if((`sr`.`EmbalageCode` = 800),((`sr`.`EmbalageCode` * 10) + `sr`.`NumberOfItemsPerCask`),`sr`.`EmbalageCode`),ifnull(`idt`.`bucket_id`,'999')) AS `EmbalageCode`,`di`.`LatestDeliveryDateTime` AS `LatestDeliveryDateTime`,`di`.`EarliestDespatchDateTime` AS `EarliestDespatchDateTime`,`di`.`FirstOrderDateTime` AS `FirstOrderDateTime`,`di`.`LatestOrderDateTime` AS `LatestOrderDateTime`,`sr`.`NumberOfItemsPerCask` AS `NumberOfItemsPerCask`,`sr`.`NumberOfLayersPerTrolley` AS `NumberOfLayersPerTrolley`,`sr`.`MinimumNumberToOrder` AS `MinimumNumberToOrder`,`sr`.`MaximumNumberToOrder` AS `MaximumNumberToOrder`,`sr`.`IncrementalOrderableQuantity` AS `IncrementalOrderableQuantity`,`sr`.`PackingPrice` AS `PackingPrice`,`sr`.`MarketPlaceID` AS `MarketPlaceID`,`sr`.`PictureReference` AS `PictureReference`,`sr`.`updated` AS `supplyResponseUpdated`,`i`.`group_id` AS `group_id`,`mp`.`name` AS `marketPlace`,`di`.`DeliveryPrice` AS `DeliveryPrice`,`di`.`ChargeAmount` AS `ChargeAmount`,`di`.`MinimumQuantity` AS `MinimumQuantity`,`di`.`MaximumQuantity Integer` AS `MaximumQuantity`,cast((`sr`.`MinimumNumberToOrder` * (case `sr`.`MinimumOrderUnitType` when 1 then 1 when 2 then (`sr`.`NumberOfItemsPerCask` / `sr`.`NumberBunchesPerCask`) when 3 then `sr`.`NumberOfItemsPerCask` when 4 then (floor(((128 * 56) / (`b`.`x_size` * `b`.`y_size`))) * `sr`.`NumberOfItemsPerCask`) when 5 then ((floor(((128 * 56) / (`b`.`x_size` * `b`.`y_size`))) * `sr`.`NumberOfItemsPerCask`) * `sr`.`NumberOfLayersPerTrolley`) end)) as decimal(10,0)) AS `OrderUnit`,cast((`sr`.`IncrementalOrderableQuantity` * (case `sr`.`IncrementalOrderableQuantityType` when 1 then 1 when 2 then (`sr`.`NumberOfItemsPerCask` / `sr`.`NumberBunchesPerCask`) when 3 then `sr`.`NumberOfItemsPerCask` when 4 then (floor(((128 * 56) / (`b`.`x_size` * `b`.`y_size`))) * `sr`.`NumberOfItemsPerCask`) when 5 then ((floor(((128 * 56) / (`b`.`x_size` * `b`.`y_size`))) * `sr`.`NumberOfItemsPerCask`) * `sr`.`NumberOfLayersPerTrolley`) end)) as decimal(10,0)) AS `IncrementalOrderUnit`,`mp`.`isEarlyBird` AS `isEarlyBird`,`v`.`isVNHSupplier` AS `isVNHSupplier`,`igo`.`expenseFk` AS `expenseFk`,`igo`.`intrastatFk` AS `intrastatFk`,`igo`.`originFk` AS `originFk`,ifnull(`idt`.`itemTypeFk`,`igo`.`itemTypeFk`) AS `itemTypeFk` from (((((((((`edi`.`deliveryInformation` `di` join `edi`.`supplyResponse` `sr` on((`sr`.`ID` = `di`.`supplyResponseID`))) left join `edi`.`supplier` `s` on((`s`.`glnAddressCode` = `sr`.`SupplierGLN`))) join `edi`.`bucket` `b` on((`b`.`bucket_id` = `sr`.`EmbalageCode`))) join `edi`.`item` `i` on((`i`.`id` = `sr`.`Item_ArticleCode`))) join `edi`.`marketPlace` `mp` on((`mp`.`id` = `sr`.`MarketPlaceID`))) join `vn`.`floramondoConfig` `fm`) left join `edi`.`item_defaultType` `idt` on((`idt`.`item_id` = `i`.`id`))) join `edi`.`VMPSettings` `v` on((`v`.`VMPID` = `sr`.`vmpID`))) join `edi`.`item_groupToOffer` `igo` on((`igo`.`group_code` = `i`.`group_id`))) where ((`v`.`isBlocked` = 0) and (`s`.`isBanned` = 0) and (`sr`.`NumberOfUnits` > 0) and (now() between `di`.`FirstOrderDateTime` and `di`.`LatestOrderDateTime`) and (`mp`.`isOffered` = 1) and (`di`.`LatestDeliveryDateTime` between cast(`fm`.`nextLanded` as date) and concat(cast(`fm`.`nextLanded` as date),' ',`fm`.`MaxLatestDeliveryHour`))) group by `sr`.`ID` having (`EmbalageCode` <> 999) */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + -- -- Current Database: `hedera` -- @@ -95963,4 +96781,4 @@ USE `vncontrol`; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2022-02-25 8:12:26 +-- Dump completed on 2022-03-04 12:54:19 diff --git a/db/export-structure.sh b/db/export-structure.sh index c5c65ef34..d9729879d 100755 --- a/db/export-structure.sh +++ b/db/export-structure.sh @@ -25,7 +25,6 @@ IGNORETABLES=( --ignore-table=bs.productionIndicators --ignore-table=bs.VentasPorCliente --ignore-table=bs.v_ventas - --ignore-table=edi.supplyOffer --ignore-table=postgresql.currentWorkersStats --ignore-table=vn.accounting__ --ignore-table=vn.agencyModeZone diff --git a/modules/account/back/methods/user-account/sync.js b/modules/account/back/methods/user-account/sync.js index 7c50dc236..013ca2dcb 100644 --- a/modules/account/back/methods/user-account/sync.js +++ b/modules/account/back/methods/user-account/sync.js @@ -26,7 +26,7 @@ module.exports = Self => { Self.sync = async function(userName, password, force) { let $ = Self.app.models; - + console.log(userName, password, force); let user = await $.Account.findOne({ fields: ['id'], where: {name: userName}
- Según la información recogida en el sistema, adjuntamos tabla con los registros. Cualquier incidencia rogamos la comunique a laboral@verdnatura.es. -

+ Según la información recogida en el sistema, adjuntamos la tabla con los registros. Cualquier incidencia rogamos la comunique a laboral@verdnatura.es. +
De no recibir incidencia por su parte, se entenderá que el registro es correcto.