From bb86c27202878d487e86e7f07a7511cadf516fcc Mon Sep 17 00:00:00 2001 From: robert Date: Wed, 20 Mar 2024 11:07:55 +0100 Subject: [PATCH 001/170] feat: refs #7116 create table agencyIncoming --- db/routines/bs/procedures/salesByItemTypeDay_add.sql | 2 +- db/versions/10960-silverRoebelini/00-firstScript.sql | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) create mode 100644 db/versions/10960-silverRoebelini/00-firstScript.sql diff --git a/db/routines/bs/procedures/salesByItemTypeDay_add.sql b/db/routines/bs/procedures/salesByItemTypeDay_add.sql index 5c12081a0..0f5c5c543 100644 --- a/db/routines/bs/procedures/salesByItemTypeDay_add.sql +++ b/db/routines/bs/procedures/salesByItemTypeDay_add.sql @@ -27,7 +27,7 @@ BEGIN JOIN vn.ticket t ON t.id = s.ticketFk WHERE ic.merchandise AND t.shipped BETWEEN vDateStart AND util.dayEnd(vDateEnd) - GROUP BY it.id, bs.dated; + GROUP BY i.id, bs.dated; INSERT INTO salesByItemTypeDay (itemTypeFk, dated, trash, faults) SELECT it.id itemTypeFk, diff --git a/db/versions/10960-silverRoebelini/00-firstScript.sql b/db/versions/10960-silverRoebelini/00-firstScript.sql new file mode 100644 index 000000000..c72ce10a7 --- /dev/null +++ b/db/versions/10960-silverRoebelini/00-firstScript.sql @@ -0,0 +1,11 @@ +-- Place your SQL code here +CREATE TABLE IF NOT EXISTS `vn`.`agencyIncoming` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `code` varchar(50) DEFAULT NULL, + `description` varchar(50) DEFAULT NULL, + `isOrigin` tinyint(1) DEFAULT NULL, + PRIMARY KEY (`id`) +) +ENGINE=InnoDB +DEFAULT CHARSET=utf8mb3 +COLLATE=utf8mb3_unicode_ci; \ No newline at end of file From 634bde1c9cf8efd49c2896d0f8c017482c20fcba Mon Sep 17 00:00:00 2001 From: robert Date: Wed, 20 Mar 2024 11:10:06 +0100 Subject: [PATCH 002/170] refs #7116 --- db/routines/bs/procedures/salesByItemTypeDay_add.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/routines/bs/procedures/salesByItemTypeDay_add.sql b/db/routines/bs/procedures/salesByItemTypeDay_add.sql index 0f5c5c543..5c12081a0 100644 --- a/db/routines/bs/procedures/salesByItemTypeDay_add.sql +++ b/db/routines/bs/procedures/salesByItemTypeDay_add.sql @@ -27,7 +27,7 @@ BEGIN JOIN vn.ticket t ON t.id = s.ticketFk WHERE ic.merchandise AND t.shipped BETWEEN vDateStart AND util.dayEnd(vDateEnd) - GROUP BY i.id, bs.dated; + GROUP BY it.id, bs.dated; INSERT INTO salesByItemTypeDay (itemTypeFk, dated, trash, faults) SELECT it.id itemTypeFk, From 1c6e881273bb3997c572ea1f8f92fe88d033334e Mon Sep 17 00:00:00 2001 From: robert Date: Thu, 6 Jun 2024 11:45:09 +0200 Subject: [PATCH 003/170] feat: refs #7544 crear evento claim_changeState --- db/routines/vn/events/claim_changeState.sql | 22 +++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 db/routines/vn/events/claim_changeState.sql diff --git a/db/routines/vn/events/claim_changeState.sql b/db/routines/vn/events/claim_changeState.sql new file mode 100644 index 000000000..c9e4c3cc5 --- /dev/null +++ b/db/routines/vn/events/claim_changeState.sql @@ -0,0 +1,22 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` EVENT `vn`.`claim_changeState` + ON SCHEDULE EVERY 1 DAY + STARTS '2024-06-06 07:52:46.000' + ON COMPLETION PRESERVE + ENABLE +DO BEGIN + + DECLARE vClaimStete INT; + + SELECT id INTO vClaimStete + FROM claimState cs + WHERE cs.code = 'canceled' + + UPDATE claim c + JOIN claimState cs ON cs.id = c.claimStateFk + SET c.claimStateFk = vClaimStete + WHERE c.created < util.VN_CURDATE() - INTERVAL 2 MONTH + AND cs.code IN('incomplete','coming','waiting','out') + +END$$ +DELIMITER ; From ef50d493f18602f9c37fddf05ee2e357404f8182 Mon Sep 17 00:00:00 2001 From: robert Date: Thu, 6 Jun 2024 11:54:39 +0200 Subject: [PATCH 004/170] feat: refs #7544 --- db/routines/vn/events/claim_changeState.sql | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/db/routines/vn/events/claim_changeState.sql b/db/routines/vn/events/claim_changeState.sql index c9e4c3cc5..790ef0c34 100644 --- a/db/routines/vn/events/claim_changeState.sql +++ b/db/routines/vn/events/claim_changeState.sql @@ -10,13 +10,13 @@ DO BEGIN SELECT id INTO vClaimStete FROM claimState cs - WHERE cs.code = 'canceled' + WHERE cs.code = 'canceled'; UPDATE claim c JOIN claimState cs ON cs.id = c.claimStateFk SET c.claimStateFk = vClaimStete WHERE c.created < util.VN_CURDATE() - INTERVAL 2 MONTH - AND cs.code IN('incomplete','coming','waiting','out') + AND cs.code IN('incomplete','coming','waiting','out'); END$$ DELIMITER ; From 9f9063567a957f9442ab64c23b2e0f6be39f032b Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 11 Jun 2024 12:40:07 +0200 Subject: [PATCH 005/170] refactor: refs #7505 item_getVisible refactor --- .../cache/procedures/visible_refresh.sql | 5 +- db/routines/vn/procedures/item_GetVisible.sql | 43 ------------- db/routines/vn/procedures/item_getVisible.sql | 49 ++++++++++++++ .../vn/procedures/multipleInventory.sql | 64 ++++++------------- 4 files changed, 70 insertions(+), 91 deletions(-) delete mode 100644 db/routines/vn/procedures/item_GetVisible.sql create mode 100644 db/routines/vn/procedures/item_getVisible.sql diff --git a/db/routines/cache/procedures/visible_refresh.sql b/db/routines/cache/procedures/visible_refresh.sql index 63b42dfd9..954b8ff23 100644 --- a/db/routines/cache/procedures/visible_refresh.sql +++ b/db/routines/cache/procedures/visible_refresh.sql @@ -20,11 +20,12 @@ proc: BEGIN CREATE OR REPLACE TEMPORARY TABLE tmp.itemVisible (PRIMARY KEY (item_id)) ENGINE = MEMORY - SELECT item_id, amount stock, amount visible FROM `cache`.stock + SELECT item_id, amount stock, amount visible + FROM `cache`.stock WHERE warehouse_id = v_warehouse; -- Calculamos los movimientos confirmados de hoy - CALL vn.item_GetVisible(v_warehouse, NULL); + CALL vn.item_getVisible(v_warehouse, util.VN_CURDATE(), NULL); DELETE FROM visible WHERE calc_id = v_calc; INSERT INTO visible (calc_id, item_id,visible) diff --git a/db/routines/vn/procedures/item_GetVisible.sql b/db/routines/vn/procedures/item_GetVisible.sql deleted file mode 100644 index ca5e43107..000000000 --- a/db/routines/vn/procedures/item_GetVisible.sql +++ /dev/null @@ -1,43 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_GetVisible`(vWarehouse SMALLINT, vItem INT) -BEGIN - DECLARE vTomorrow DATETIME DEFAULT TIMESTAMPADD(DAY, 1, util.VN_CURDATE()); - - INSERT INTO tmp.itemVisible (item_id, visible) - SELECT item_id, SUM(amount) amount - FROM ( - SELECT i.itemFk AS item_id, quantity AS amount - FROM itemTicketOut i - LEFT JOIN ticketState ts ON ts.ticketFk = i.ticketFk - JOIN state s ON s.id = ts.stateFk - LEFT JOIN (SELECT DISTINCT saleFk - FROM saleTracking st - JOIN state s ON s.id = st.stateFk - WHERE st.created > util.VN_CURDATE() - AND (s.isPicked OR st.isChecked) - ) stPrevious ON `stPrevious`.`saleFk` = i.saleFk - WHERE i.warehouseFk = vWarehouse - AND (vItem IS NULL OR i.itemFk = vItem) - AND (s.isPicked OR i.reserved OR stPrevious.saleFk ) - AND i.shipped >= util.VN_CURDATE() AND i.shipped < vTomorrow - UNION ALL - SELECT iei.itemFk, quantity - FROM itemEntryIn iei - WHERE (iei.isReceived != FALSE /*OR ip.modificationDate > util.VN_CURDATE()*/) - AND iei.landed >= util.VN_CURDATE() AND iei.landed < vTomorrow - AND iei.warehouseInFk = vWarehouse - AND (vItem IS NULL OR iei.itemFk = vItem) - AND iei.isVirtualStock is FALSE - UNION ALL - SELECT itemFk, quantity - FROM itemEntryOut - WHERE isDelivered != FALSE - AND shipped >= util.VN_CURDATE() AND shipped < vTomorrow - AND warehouseOutFk = vWarehouse - AND (vItem IS NULL OR itemFk = vItem) - ) t - GROUP BY item_id - ON DUPLICATE KEY UPDATE - visible = IFNULL(stock,0) + VALUES(visible); -END$$ -DELIMITER ; diff --git a/db/routines/vn/procedures/item_getVisible.sql b/db/routines/vn/procedures/item_getVisible.sql new file mode 100644 index 000000000..0516b9d06 --- /dev/null +++ b/db/routines/vn/procedures/item_getVisible.sql @@ -0,0 +1,49 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_getVisible`( + vWarehouseFk INT, + vDated INT, + vItemFk INT +) +BEGIN + DECLARE vTomorrow DATETIME DEFAULT vDated + INTERVAL 1 DAY; + + INSERT INTO tmp.itemVisible (item_id, visible) + SELECT itemFk, SUM(quantity) + FROM ( + SELECT i.itemFk, i.quantity + FROM itemTicketOut i + LEFT JOIN ticketState ts ON ts.ticketFk = i.ticketFk + JOIN `state` s ON s.id = ts.stateFk + LEFT JOIN ( + SELECT DISTINCT st.saleFk + FROM saleTracking st + JOIN state s ON s.id = st.stateFk + WHERE st.created > vDated + AND (s.isPicked OR st.isChecked) + ) stPrevious ON `stPrevious`.`saleFk` = i.saleFk + WHERE i.warehouseFk = vWarehouseFk + AND (vItemFk IS NULL OR i.itemFk = vItemFk) + AND (s.isPicked OR i.reserved OR stPrevious.saleFk) + AND i.shipped >= vDated AND i.shipped < vTomorrow + UNION ALL + SELECT itemFk, quantity + FROM itemEntryIn + WHERE isReceived + AND landed >= vDated AND landed < vTomorrow + AND warehouseInFk = vWarehouseFk + AND (vItemFk IS NULL OR itemFk = vItemFk) + AND NOT isVirtualStock + UNION ALL + SELECT itemFk, quantity + FROM itemEntryOut + WHERE isDelivered + AND shipped >= vDated + AND shipped < vTomorrow + AND warehouseOutFk = vWarehouseFk + AND (vItemFk IS NULL OR itemFk = vItemFk) + ) t + GROUP BY itemFk + ON DUPLICATE KEY UPDATE + visible = IFNULL(stock, 0) + VALUES(visible); +END$$ +DELIMITER ; diff --git a/db/routines/vn/procedures/multipleInventory.sql b/db/routines/vn/procedures/multipleInventory.sql index 2a28aa9a0..4d5c5d366 100644 --- a/db/routines/vn/procedures/multipleInventory.sql +++ b/db/routines/vn/procedures/multipleInventory.sql @@ -1,9 +1,9 @@ -DELIMITER $$ +DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`multipleInventory`( vDate DATE, vWarehouseFk TINYINT, vMaxDays TINYINT -) +) proc: BEGIN DECLARE vDateTomorrow DATE DEFAULT vDate + INTERVAL 1 DAY; DECLARE vDateFrom DATE DEFAULT vDate; @@ -78,47 +78,18 @@ proc: BEGIN ai.sd = sub.Subtotal; -- Cálculo del visible - UPDATE tmp.itemInventory ai - JOIN ( - SELECT itemFk Id_Article, SUM(quantity) Subtotal - FROM ( - SELECT s.itemFk, s.quantity - FROM sale s - JOIN ticket t ON t.id = s.ticketFk - JOIN warehouse w ON w.id = t.warehouseFk - WHERE t.shipped >= vDate - AND t.shipped < vDateTomorrow - AND (NOT isPicked AND NOT t.isLabeled AND t.refFk IS NULL) - AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk - AND w.isComparative - UNION ALL - SELECT b.itemFk, - b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseInFk - WHERE t.landed = vDate - AND NOT t.isReceived - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk - AND w.isComparative - UNION ALL - SELECT b.itemFk, b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseOutFk - WHERE t.shipped = vDate - AND NOT t.isReceived - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk - AND w.isComparative - ) sub2 - GROUP BY itemFk - ) sub ON ai.id = sub.Id_Article - SET ai.visible = ai.visible + sub.Subtotal; + CALL `cache`.stock_refresh(false); + + CREATE OR REPLACE TEMPORARY TABLE tmp.itemVisible + (PRIMARY KEY (item_id)) + ENGINE = MEMORY + SELECT item_id, amount stock, amount visible FROM `cache`.stock + WHERE warehouse_id = vWarehouseFk; + + CALL vn.item_getVisible(vWarehouseFk, util.VN_CURDATE(), NULL); + UPDATE tmp.itemInventory it + JOIN tmp.itemVisible iv ON iv.item_id = it.id + SET it.visible = iv.visible; -- Calculo del disponible CREATE OR REPLACE TEMPORARY TABLE tmp.itemCalc @@ -189,6 +160,7 @@ proc: BEGIN DROP TEMPORARY TABLE tmp.itemTravel, tmp.itemCalc, - tmp.itemAtp; -END$$ -DELIMITER ; + tmp.itemAtp, + tmp.itemVisible; +END$$ +DELIMITER ; From a9aad7406aec4e0065069c2db4598a65d930bf3c Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 11 Jun 2024 12:51:36 +0200 Subject: [PATCH 006/170] refactor: refs #7505 Minor change --- db/routines/vn/procedures/multipleInventory.sql | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/db/routines/vn/procedures/multipleInventory.sql b/db/routines/vn/procedures/multipleInventory.sql index 4d5c5d366..05f25268c 100644 --- a/db/routines/vn/procedures/multipleInventory.sql +++ b/db/routines/vn/procedures/multipleInventory.sql @@ -87,9 +87,9 @@ proc: BEGIN WHERE warehouse_id = vWarehouseFk; CALL vn.item_getVisible(vWarehouseFk, util.VN_CURDATE(), NULL); - UPDATE tmp.itemInventory it - JOIN tmp.itemVisible iv ON iv.item_id = it.id - SET it.visible = iv.visible; + UPDATE tmp.itemInventory it + JOIN tmp.itemVisible iv ON iv.item_id = it.id + SET it.visible = iv.visible; -- Calculo del disponible CREATE OR REPLACE TEMPORARY TABLE tmp.itemCalc From 4f10a93584f309711d455d9081dfee2df9e80ae1 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 11 Jun 2024 13:36:46 +0200 Subject: [PATCH 007/170] refactor: refs #7505 Minor change --- db/routines/vn/procedures/multipleInventory.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/routines/vn/procedures/multipleInventory.sql b/db/routines/vn/procedures/multipleInventory.sql index 05f25268c..630301b94 100644 --- a/db/routines/vn/procedures/multipleInventory.sql +++ b/db/routines/vn/procedures/multipleInventory.sql @@ -86,7 +86,7 @@ proc: BEGIN SELECT item_id, amount stock, amount visible FROM `cache`.stock WHERE warehouse_id = vWarehouseFk; - CALL vn.item_getVisible(vWarehouseFk, util.VN_CURDATE(), NULL); + CALL item_getVisible(vWarehouseFk, util.VN_CURDATE(), NULL); UPDATE tmp.itemInventory it JOIN tmp.itemVisible iv ON iv.item_id = it.id SET it.visible = iv.visible; From 3bd596e5fd91d63a5c10f62fc45bd8805063d9ca Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 11 Jun 2024 13:53:41 +0200 Subject: [PATCH 008/170] refactor: refs #7505 Added description --- db/routines/vn/procedures/item_getVisible.sql | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/db/routines/vn/procedures/item_getVisible.sql b/db/routines/vn/procedures/item_getVisible.sql index 0516b9d06..2294d8903 100644 --- a/db/routines/vn/procedures/item_getVisible.sql +++ b/db/routines/vn/procedures/item_getVisible.sql @@ -5,6 +5,14 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_getVisible`( vItemFk INT ) BEGIN +/** + * Calcula el visible de un artículo o de todos. + * + * @param vWarehouse Warehouse id + * @param vDated Max date to filter + * @param vItemFk Item id + * @param tmp.itemVisible(item_id, stock, visible) + */ DECLARE vTomorrow DATETIME DEFAULT vDated + INTERVAL 1 DAY; INSERT INTO tmp.itemVisible (item_id, visible) From aa0e06cfec4be89f54eb2828f115fc8ae800d54e Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 11 Jun 2024 14:00:59 +0200 Subject: [PATCH 009/170] refactor: refs #7505 Changed name --- db/routines/cache/procedures/visible_refresh.sql | 2 +- .../vn/procedures/{item_getVisible.sql => item_calcVisible.sql} | 2 +- db/routines/vn/procedures/multipleInventory.sql | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) rename db/routines/vn/procedures/{item_getVisible.sql => item_calcVisible.sql} (99%) diff --git a/db/routines/cache/procedures/visible_refresh.sql b/db/routines/cache/procedures/visible_refresh.sql index 954b8ff23..b200e86f2 100644 --- a/db/routines/cache/procedures/visible_refresh.sql +++ b/db/routines/cache/procedures/visible_refresh.sql @@ -25,7 +25,7 @@ proc: BEGIN WHERE warehouse_id = v_warehouse; -- Calculamos los movimientos confirmados de hoy - CALL vn.item_getVisible(v_warehouse, util.VN_CURDATE(), NULL); + CALL vn.item_calcVisible(v_warehouse, util.VN_CURDATE(), NULL); DELETE FROM visible WHERE calc_id = v_calc; INSERT INTO visible (calc_id, item_id,visible) diff --git a/db/routines/vn/procedures/item_getVisible.sql b/db/routines/vn/procedures/item_calcVisible.sql similarity index 99% rename from db/routines/vn/procedures/item_getVisible.sql rename to db/routines/vn/procedures/item_calcVisible.sql index 2294d8903..f7eee661b 100644 --- a/db/routines/vn/procedures/item_getVisible.sql +++ b/db/routines/vn/procedures/item_calcVisible.sql @@ -1,5 +1,5 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_getVisible`( +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_calcVisible`( vWarehouseFk INT, vDated INT, vItemFk INT diff --git a/db/routines/vn/procedures/multipleInventory.sql b/db/routines/vn/procedures/multipleInventory.sql index 630301b94..b201bcaae 100644 --- a/db/routines/vn/procedures/multipleInventory.sql +++ b/db/routines/vn/procedures/multipleInventory.sql @@ -86,7 +86,7 @@ proc: BEGIN SELECT item_id, amount stock, amount visible FROM `cache`.stock WHERE warehouse_id = vWarehouseFk; - CALL item_getVisible(vWarehouseFk, util.VN_CURDATE(), NULL); + CALL item_calcVisible(vWarehouseFk, util.VN_CURDATE(), NULL); UPDATE tmp.itemInventory it JOIN tmp.itemVisible iv ON iv.item_id = it.id SET it.visible = iv.visible; From cbd46330b31d8efcbab8ce2b116dd8f048cd8eec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Thu, 27 Jun 2024 13:01:42 +0200 Subject: [PATCH 010/170] feat: Turn issues into calculated columns refs#7213 --- .../functions/ticket_isProblemCalcNeeded.sql | 27 +++ db/routines/vn/procedures/buyUltimate.sql | 34 +-- .../vn/procedures/buyUltimateFromInterval.sql | 195 ++++++++++-------- db/routines/vn/procedures/sale_setProblem.sql | 9 +- .../sale_setProblemComponentLack.sql | 8 +- ...ale_setProblemComponentLackByComponent.sql | 8 +- .../vn/procedures/sale_setProblemRounding.sql | 9 +- .../vn/procedures/ticket_setProblem.sql | 12 +- .../vn/procedures/ticket_setProblemFreeze.sql | 8 +- .../procedures/ticket_setProblemRequest.sql | 6 +- .../vn/procedures/ticket_setProblemRisk.sql | 17 +- .../procedures/ticket_setProblemRounding.sql | 7 +- .../ticket_setProblemTaxDataChecked.sql | 6 +- .../procedures/ticket_setProblemTooLittle.sql | 8 +- .../ticket_setProblemTooLittleItemCost.sql | 6 +- 15 files changed, 234 insertions(+), 126 deletions(-) create mode 100644 db/routines/vn/functions/ticket_isProblemCalcNeeded.sql diff --git a/db/routines/vn/functions/ticket_isProblemCalcNeeded.sql b/db/routines/vn/functions/ticket_isProblemCalcNeeded.sql new file mode 100644 index 000000000..4974a8c76 --- /dev/null +++ b/db/routines/vn/functions/ticket_isProblemCalcNeeded.sql @@ -0,0 +1,27 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`ticket_isProblemCalcNeeded`( + vSelf INT +) + RETURNS BOOL + DETERMINISTIC +BEGIN +/** + * Check if the ticket requires to update column vn.ticket.problem + * + * @param vSelf Id ticket + * @return BOOL + */ + DECLARE vIsProblemCalcNeeded BOOL; + + SELECT COUNT(*) INTO vIsProblemCalcNeeded + FROM ticket t + JOIN client c ON c.id = t.clientFk + JOIN agencyMode am ON am.id = t.agencyModeFk + JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk + WHERE t.id = vSelf + AND dm.code IN ('AGENCY','DELIVERY','PICKUP') + AND c.typeFk = 'normal'; + + RETURN vIsProblemCalcNeeded; +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/buyUltimate.sql b/db/routines/vn/procedures/buyUltimate.sql index 4346ef640..98b16cbc0 100644 --- a/db/routines/vn/procedures/buyUltimate.sql +++ b/db/routines/vn/procedures/buyUltimate.sql @@ -1,5 +1,8 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buyUltimate`(vWarehouseFk SMALLINT, vDated DATE) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buyUltimate`( + vWarehouseFk SMALLINT, + vDated DATE +) BEGIN /** * Calcula las últimas compras realizadas hasta una fecha @@ -19,21 +22,22 @@ BEGIN FROM cache.last_buy WHERE warehouse_id = vWarehouseFk OR vWarehouseFk IS NULL; - CALL buyUltimateFromInterval(vWarehouseFk, util.VN_CURDATE(), vDated); + IF vDated >= util.VN_CURDATE() THEN + CALL buyUltimateFromInterval(vWarehouseFk, util.VN_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 - AND NOT isIgnored; - - INSERT IGNORE INTO tmp.buyUltimate - SELECT itemFk, buyFk, warehouseFk, landed landing - FROM tmp.buyUltimateFromInterval - WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL) - AND landed > vDated - ORDER BY isIgnored = FALSE DESC; + REPLACE INTO tmp.buyUltimate + SELECT itemFk, buyFk, warehouseFk, landed landing + FROM tmp.buyUltimateFromInterval + WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL) + AND landed <= vDated + AND NOT isIgnored; + INSERT IGNORE INTO tmp.buyUltimate + SELECT itemFk, buyFk, warehouseFk, landed landing + FROM tmp.buyUltimateFromInterval + WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL) + AND landed > vDated + ORDER BY isIgnored = FALSE DESC; + END IF; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/buyUltimateFromInterval.sql b/db/routines/vn/procedures/buyUltimateFromInterval.sql index e264b500d..5879b58e1 100644 --- a/db/routines/vn/procedures/buyUltimateFromInterval.sql +++ b/db/routines/vn/procedures/buyUltimateFromInterval.sql @@ -1,5 +1,9 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buyUltimateFromInterval`(vWarehouseFk SMALLINT, vStarted DATE, vEnded DATE) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buyUltimateFromInterval`( + vWarehouseFk SMALLINT, + vStarted DATE, + vEnded DATE +) BEGIN /** * Calcula las últimas compras realizadas @@ -21,12 +25,13 @@ BEGIN -- 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)) + (PRIMARY KEY (itemFk, warehouseFk), + INDEX(buyFk), INDEX(landed), INDEX(warehouseFk), INDEX(itemFk)) ENGINE = MEMORY SELECT itemFk, warehouseFk, buyFk, - MAX(landed) landed, + landed, isIgnored FROM (SELECT b.itemFk, t.warehouseInFk warehouseFk, @@ -45,93 +50,117 @@ BEGIN INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored) - SELECT - b.itemFk, - t.warehouseInFk warehouseFk, - b.id buyFk, - t.landed, - b.isIgnored - 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; + SELECT itemFk, + warehouseFk, + buyFk, + landed, + isIgnored + FROM (SELECT b.itemFk, + t.warehouseInFk warehouseFk, + b.id buyFk, + t.landed, + b.isIgnored + 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 + ORDER BY NOT b.isIgnored DESC, t.landed DESC, b.id DESC + LIMIT 10000000000000000000) sub + GROUP BY itemFk, warehouseFk; INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored) - SELECT - b.itemFk, - t.warehouseInFk warehouseFk, - b.id buyFk, - t.landed, - b.isIgnored - 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; + SELECT itemFk, + warehouseFk, + buyFk, + landed, + isIgnored + FROM (SELECT b.itemFk, + t.warehouseInFk warehouseFk, + b.id buyFk, + t.landed, + b.isIgnored + 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 + ORDER BY NOT b.isIgnored DESC, t.landed DESC, b.id DESC + LIMIT 10000000000000000000) sub + GROUP BY itemFk, warehouseFk; -- ItemOriginal INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored) SELECT itemFk, - warehouseFk, - buyFk, - MAX(landed) landed, - isIgnored - FROM (SELECT b.itemFk, - t.warehouseInFk warehouseFk, - b.id buyFk, - t.landed, - itemOriginalFk, - b.isIgnored - 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 - ORDER BY t.landed DESC, b.id DESC - LIMIT 10000000000000000000) sub - GROUP BY itemOriginalFk, warehouseFk; + warehouseFk, + buyFk, + landed, + isIgnored + FROM (SELECT b.itemFk, + t.warehouseInFk warehouseFk, + b.id buyFk, + t.landed, + itemOriginalFk, + b.isIgnored + 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 + ORDER BY t.landed DESC, b.id DESC + LIMIT 10000000000000000000) sub + GROUP BY itemFk, warehouseFk; + INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored) + SELECT itemFk, + warehouseFk, + buyFk, + landed, + isIgnored + FROM (SELECT b.itemFk, + t.warehouseInFk warehouseFk, + b.id buyFk, + t.landed, + b.isIgnored + 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 + ORDER BY t.landed DESC, b.id DESC + LIMIT 10000000000000000000) sub + GROUP BY itemFk, warehouseFk; INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored) - SELECT - b.itemFk, - t.warehouseInFk warehouseFk, - b.id buyFk, - t.landed, - b.isIgnored - 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, isIgnored) - SELECT - b.itemFk, - t.warehouseInFk warehouseFk, - b.id buyFk, - t.landed, - b.isIgnored - 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; + SELECT itemFk, + warehouseFk, + buyFk, + landed, + isIgnored + FROM + (SELECT b.itemFk, + t.warehouseInFk warehouseFk, + b.id buyFk, + t.landed, + b.isIgnored + 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 + ORDER BY t.landed DESC, b.id DESC + LIMIT 10000000000000000000) sub + GROUP BY itemFk, warehouseFk; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/sale_setProblem.sql b/db/routines/vn/procedures/sale_setProblem.sql index 20319cc3f..1ba7a1353 100644 --- a/db/routines/vn/procedures/sale_setProblem.sql +++ b/db/routines/vn/procedures/sale_setProblem.sql @@ -6,8 +6,15 @@ BEGIN /** * Update column sale.problem with a problem code * @param vProblemCode Code to set or unset - * @table tmp.sale(saleFk, hasProblem) + * @table tmp.sale(saleFk, hasProblem, isProblemCalcNeeded) */ + UPDATE tmp.sale ts + JOIN sale s ON s.id = ts.saleFk + SET s.problem = NULL + WHERE NOT ts.isProblemCalcNeeded; + + DELETE FROM tmp.sale WHERE NOT isProblemCalcNeeded; + UPDATE sale s JOIN tmp.sale ts ON ts.saleFk = s.id SET s.problem = CONCAT( diff --git a/db/routines/vn/procedures/sale_setProblemComponentLack.sql b/db/routines/vn/procedures/sale_setProblemComponentLack.sql index 363663a00..aa5f5f1be 100644 --- a/db/routines/vn/procedures/sale_setProblemComponentLack.sql +++ b/db/routines/vn/procedures/sale_setProblemComponentLack.sql @@ -10,9 +10,13 @@ BEGIN * @param vSelf Id del sale */ CREATE OR REPLACE TEMPORARY TABLE tmp.sale - (INDEX(saleFk)) + (INDEX(saleFk, isProblemCalcNeeded)) ENGINE = MEMORY - SELECT vSelf saleFk, sale_hasComponentLack(vSelf) hasProblem; + SELECT vSelf saleFk, + sale_hasComponentLack(vSelf) hasProblem, + ticket_isProblemCalcNeeded(ticketFk) isProblemCalcNeeded + FROM sale + WHERE id = vSelf; CALL sale_setProblem('hasComponentLack'); diff --git a/db/routines/vn/procedures/sale_setProblemComponentLackByComponent.sql b/db/routines/vn/procedures/sale_setProblemComponentLackByComponent.sql index b911327dd..2ee49b656 100644 --- a/db/routines/vn/procedures/sale_setProblemComponentLackByComponent.sql +++ b/db/routines/vn/procedures/sale_setProblemComponentLackByComponent.sql @@ -10,11 +10,13 @@ BEGIN * @param vComponentFk Id component */ CREATE OR REPLACE TEMPORARY TABLE tmp.sale - (INDEX(saleFk)) + (INDEX(saleFk, isProblemCalcNeeded)) ENGINE = MEMORY - SELECT saleFk, sale_hasComponentLack(saleFk)hasProblem + SELECT saleFk, + sale_hasComponentLack(saleFk) hasProblem, + ticket_isProblemCalcNeeded(ticketFk) isProblemCalcNeeded FROM ( - SELECT s.id saleFk + SELECT s.id saleFk, s.ticketFk FROM ticket t JOIN sale s ON s.ticketFk = t.id LEFT JOIN saleComponent sc ON sc.saleFk = s.id diff --git a/db/routines/vn/procedures/sale_setProblemRounding.sql b/db/routines/vn/procedures/sale_setProblemRounding.sql index f14cd408f..f58d00799 100644 --- a/db/routines/vn/procedures/sale_setProblemRounding.sql +++ b/db/routines/vn/procedures/sale_setProblemRounding.sql @@ -11,9 +11,10 @@ BEGIN DECLARE vWarehouseFk INT; DECLARE vShipped DATE; DECLARE vQuantity INT; + DECLARE vIsProblemCalcNeeded BOOL; - SELECT s.itemFk, t.warehouseFk, t.shipped, s.quantity - INTO vItemFk, vWarehouseFk, vShipped, vQuantity + SELECT s.itemFk, t.warehouseFk, t.shipped, s.quantity, ticket_isProblemCalcNeeded(t.id) + INTO vItemFk, vWarehouseFk, vShipped, vQuantity, vIsProblemCalcNeeded FROM sale s JOIN ticket t ON t.id = s.ticketFk WHERE s.id = vSelf; @@ -21,7 +22,9 @@ BEGIN CALL buyUltimate(vWarehouseFk, vShipped); CREATE OR REPLACE TEMPORARY TABLE tmp.sale - SELECT vSelf saleFk, MOD(vQuantity, b.`grouping`) hasProblem + SELECT vSelf saleFk, + MOD(vQuantity, b.`grouping`) hasProblem, + vIsProblemCalcNeeded isProblemCalcNeeded FROM tmp.buyUltimate bu JOIN buy b ON b.id = bu.buyFk WHERE bu.itemFk = vItemFk; diff --git a/db/routines/vn/procedures/ticket_setProblem.sql b/db/routines/vn/procedures/ticket_setProblem.sql index bab8f1f52..a75cb91ed 100644 --- a/db/routines/vn/procedures/ticket_setProblem.sql +++ b/db/routines/vn/procedures/ticket_setProblem.sql @@ -4,11 +4,19 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_setProblem`( ) BEGIN /** - * Update column ticket.problem with a problem code + * Update column ticket.problem with a problem code and SET NULL when + * the problem is not requiered * * @param vProblemCode Code to set or unset - * @table tmp.ticket(ticketFk, hasProblem) + * @table tmp.ticket(ticketFk, hasProblem, isProblemCalcNeeded) */ + UPDATE ticket t + JOIN tmp.ticket tt ON tt.ticketFk = t.id + SET t.problem = NULL + WHERE NOT tt.isProblemCalcNeeded; + + DELETE FROM tmp.ticket WHERE NOT isProblemCalcNeeded; + UPDATE ticket t JOIN tmp.ticket tt ON tt.ticketFk = t.id SET t.problem = CONCAT( diff --git a/db/routines/vn/procedures/ticket_setProblemFreeze.sql b/db/routines/vn/procedures/ticket_setProblemFreeze.sql index 560bce612..1de939ba7 100644 --- a/db/routines/vn/procedures/ticket_setProblemFreeze.sql +++ b/db/routines/vn/procedures/ticket_setProblemFreeze.sql @@ -9,9 +9,11 @@ BEGIN * @param vClientFk Id Cliente, if NULL all clients */ CREATE OR REPLACE TEMPORARY TABLE tmp.ticket - (INDEX(ticketFk)) + (INDEX(ticketFk, isProblemCalcNeeded)) ENGINE = MEMORY - SELECT t.id ticketFk, FALSE hasProblem + SELECT t.id ticketFk, + FALSE hasProblem, + ticket_isProblemCalcNeeded(t.id) isProblemCalcNeeded FROM ticket t WHERE t.shipped >= util.VN_CURDATE() AND (vClientFk IS NULL OR t.clientFk = vClientFk); @@ -21,7 +23,7 @@ BEGIN JOIN client c ON c.id = ti.clientFk SET t.hasProblem = TRUE WHERE c.isFreezed; - + CALL ticket_setProblem('isFreezed'); DROP TEMPORARY TABLE tmp.ticket; diff --git a/db/routines/vn/procedures/ticket_setProblemRequest.sql b/db/routines/vn/procedures/ticket_setProblemRequest.sql index 19bba5b76..687facfc7 100644 --- a/db/routines/vn/procedures/ticket_setProblemRequest.sql +++ b/db/routines/vn/procedures/ticket_setProblemRequest.sql @@ -9,9 +9,11 @@ BEGIN * @param vSelf Id ticket, if NULL ALL tickets */ CREATE OR REPLACE TEMPORARY TABLE tmp.ticket - (INDEX(ticketFk)) + (INDEX(ticketFk, isProblemCalcNeeded)) ENGINE = MEMORY - SELECT t.id ticketFk, FALSE hasProblem + SELECT t.id ticketFk, + FALSE hasProblem, + ticket_isProblemCalcNeeded(t.id) isProblemCalcNeeded FROM ticket t WHERE t.shipped >= util.VN_CURDATE() AND (vSelf IS NULL OR t.id = vSelf); diff --git a/db/routines/vn/procedures/ticket_setProblemRisk.sql b/db/routines/vn/procedures/ticket_setProblemRisk.sql index 5f73ee838..efa5b10e2 100644 --- a/db/routines/vn/procedures/ticket_setProblemRisk.sql +++ b/db/routines/vn/procedures/ticket_setProblemRisk.sql @@ -10,21 +10,30 @@ BEGIN */ DECLARE vHasRisk BOOL; DECLARE vHasHighRisk BOOL; + DECLARE vIsProblemCalcNeeded BOOL; - SELECT t.risk > (c.credit + 10), ((t.risk - cc.riskTolerance) > (c.credit + 10)) - INTO vHasRisk, vHasHighRisk + SELECT t.risk > (c.credit + 10), + (t.risk - cc.riskTolerance) > (c.credit + 10), + ticket_isProblemCalcNeeded(t.id) + INTO vHasRisk, vHasHighRisk, vIsProblemCalcNeeded FROM client c JOIN ticket t ON t.clientFk = c.id JOIN clientConfig cc WHERE t.id = vSelf; CREATE OR REPLACE TEMPORARY TABLE tmp.ticket - SELECT vSelf ticketFk, vHasRisk hasProblem; + ENGINE = MEMORY + SELECT vSelf ticketFk, + vHasRisk hasProblem, + vIsProblemCalcNeeded isProblemCalcNeeded; CALL ticket_setProblem('hasRisk'); CREATE OR REPLACE TEMPORARY TABLE tmp.ticket - SELECT vSelf ticketFk, vHasHighRisk hasProblem; + ENGINE = MEMORY + SELECT vSelf ticketFk, + vHasHighRisk hasProblem, + vIsProblemCalcNeeded isProblemCalcNeeded; CALL ticket_setProblem('hasHighRisk'); diff --git a/db/routines/vn/procedures/ticket_setProblemRounding.sql b/db/routines/vn/procedures/ticket_setProblemRounding.sql index 81294325c..fb580eacf 100644 --- a/db/routines/vn/procedures/ticket_setProblemRounding.sql +++ b/db/routines/vn/procedures/ticket_setProblemRounding.sql @@ -18,8 +18,11 @@ BEGIN CALL buyUltimate(vWarehouseFk, vDated); - CREATE OR REPLACE TEMPORARY TABLE tmp.sale - SELECT s.id saleFk , MOD(s.quantity, b.`grouping`) hasProblem + CREATE OR REPLACE TEMPORARY TABLE tmp.sale + (INDEX(saleFk, isProblemCalcNeeded)) + SELECT s.id saleFk , + MOD(s.quantity, b.`grouping`) hasProblem, + ticket_isProblemCalcNeeded(t.id) isProblemCalcNeeded FROM ticket t JOIN sale s ON s.ticketFk = t.id JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk diff --git a/db/routines/vn/procedures/ticket_setProblemTaxDataChecked.sql b/db/routines/vn/procedures/ticket_setProblemTaxDataChecked.sql index 00918426b..9877b5acc 100644 --- a/db/routines/vn/procedures/ticket_setProblemTaxDataChecked.sql +++ b/db/routines/vn/procedures/ticket_setProblemTaxDataChecked.sql @@ -9,9 +9,11 @@ BEGIN * @param vClientFk Id cliente, if NULL all clients */ CREATE OR REPLACE TEMPORARY TABLE tmp.ticket - (INDEX(ticketFk)) + (INDEX(ticketFk, isProblemCalcNeeded)) ENGINE = MEMORY - SELECT t.id ticketFk, IF(c.isTaxDataChecked, FALSE, TRUE) hasProblem + SELECT t.id ticketFk, + IF(c.isTaxDataChecked, FALSE, TRUE) hasProblem, + ticket_isProblemCalcNeeded(t.id) isProblemCalcNeeded FROM ticket t JOIN client c ON c.id = t.clientFk WHERE t.shipped >= util.VN_CURDATE() diff --git a/db/routines/vn/procedures/ticket_setProblemTooLittle.sql b/db/routines/vn/procedures/ticket_setProblemTooLittle.sql index 98a0787af..48cc47809 100644 --- a/db/routines/vn/procedures/ticket_setProblemTooLittle.sql +++ b/db/routines/vn/procedures/ticket_setProblemTooLittle.sql @@ -8,13 +8,17 @@ BEGIN * * @param vSelf Id del ticket */ + CREATE OR REPLACE TEMPORARY TABLE tmp.ticket - (INDEX(ticketFk)) + (INDEX(ticketFk, isProblemCalcNeeded)) ENGINE = MEMORY - SELECT vSelf ticketFk, ticket_isTooLittle(vSelf) hasProblem; + SELECT vSelf ticketFk, + ticket_isTooLittle(vSelf) hasProblem, + ticket_isProblemCalcNeeded(vSelf) isProblemCalcNeeded; CALL ticket_setProblem('isTooLittle'); DROP TEMPORARY TABLE tmp.ticket; + END$$ DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/ticket_setProblemTooLittleItemCost.sql b/db/routines/vn/procedures/ticket_setProblemTooLittleItemCost.sql index cd1f42783..1f41c0716 100644 --- a/db/routines/vn/procedures/ticket_setProblemTooLittleItemCost.sql +++ b/db/routines/vn/procedures/ticket_setProblemTooLittleItemCost.sql @@ -10,7 +10,7 @@ BEGIN * @param vItemFk Id del item, NULL ALL items */ CREATE OR REPLACE TEMPORARY TABLE tmp.ticket - (INDEX(ticketFk)) + (INDEX(ticketFk, isProblemCalcNeeded)) ENGINE = MEMORY WITH tickets AS( SELECT t.id ticketFk @@ -19,7 +19,9 @@ BEGIN WHERE t.shipped >= util.VN_CURDATE() AND (s.itemFk = vItemFk OR vItemFk IS NULL) GROUP BY t.id - )SELECT ticketFk, ticket_isTooLittle(ticketFk) hasProblem + )SELECT ticketFk, + ticket_isTooLittle(ticketFk) hasProblem, + ticket_isProblemCalcNeeded(t.id) isProblemCalcNeeded FROM tickets; CALL ticket_setProblem('isTooLittle'); From 8b617df13d6846670a9c5db69ee96b3f0a5a2ba6 Mon Sep 17 00:00:00 2001 From: robert Date: Fri, 28 Jun 2024 09:59:55 +0200 Subject: [PATCH 011/170] feat: refs #7116 create table --- db/versions/10960-silverRoebelini/00-firstScript.sql | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/db/versions/10960-silverRoebelini/00-firstScript.sql b/db/versions/10960-silverRoebelini/00-firstScript.sql index c72ce10a7..264e30791 100644 --- a/db/versions/10960-silverRoebelini/00-firstScript.sql +++ b/db/versions/10960-silverRoebelini/00-firstScript.sql @@ -1,10 +1,7 @@ -- Place your SQL code here CREATE TABLE IF NOT EXISTS `vn`.`agencyIncoming` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `code` varchar(50) DEFAULT NULL, - `description` varchar(50) DEFAULT NULL, - `isOrigin` tinyint(1) DEFAULT NULL, - PRIMARY KEY (`id`) + `agencyModeFk` int(11) NOT NULL AUTO_INCREMENT, + PRIMARY KEY (`agencyModeFk`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 From 00f3755de74a06fee0e4e38af775e16b59c60413 Mon Sep 17 00:00:00 2001 From: robert Date: Mon, 1 Jul 2024 07:46:49 +0200 Subject: [PATCH 012/170] feat: refs #7116 agencyIncoming --- db/versions/10960-silverRoebelini/00-firstScript.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/versions/10960-silverRoebelini/00-firstScript.sql b/db/versions/10960-silverRoebelini/00-firstScript.sql index 264e30791..75fc5277f 100644 --- a/db/versions/10960-silverRoebelini/00-firstScript.sql +++ b/db/versions/10960-silverRoebelini/00-firstScript.sql @@ -1,6 +1,6 @@ -- Place your SQL code here CREATE TABLE IF NOT EXISTS `vn`.`agencyIncoming` ( - `agencyModeFk` int(11) NOT NULL AUTO_INCREMENT, + `agencyModeFk` int(11) NOT NULL, PRIMARY KEY (`agencyModeFk`) ) ENGINE=InnoDB From 19c378d6bd675b7e2079a6785477fd4b78ab66b0 Mon Sep 17 00:00:00 2001 From: robert Date: Wed, 3 Jul 2024 08:48:24 +0200 Subject: [PATCH 013/170] =?UTF-8?q?feat:=20refs=20#7116=20a=C3=B1adir=20co?= =?UTF-8?q?mentario?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- db/versions/10960-silverRoebelini/00-firstScript.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/versions/10960-silverRoebelini/00-firstScript.sql b/db/versions/10960-silverRoebelini/00-firstScript.sql index 75fc5277f..228e0b014 100644 --- a/db/versions/10960-silverRoebelini/00-firstScript.sql +++ b/db/versions/10960-silverRoebelini/00-firstScript.sql @@ -5,4 +5,4 @@ CREATE TABLE IF NOT EXISTS `vn`.`agencyIncoming` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 -COLLATE=utf8mb3_unicode_ci; \ No newline at end of file +COLLATE=utf8mb3_unicode_ci COMMENT='Agencias de entrada de mercancias';; \ No newline at end of file From d1ef1c80f8271026905e45fd2790160984ae5de1 Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 3 Jul 2024 09:36:20 +0200 Subject: [PATCH 014/170] feat: refs #7382 Added unique key --- db/versions/11127-silverMoss/00-firstScript.sql | 1 + 1 file changed, 1 insertion(+) create mode 100644 db/versions/11127-silverMoss/00-firstScript.sql diff --git a/db/versions/11127-silverMoss/00-firstScript.sql b/db/versions/11127-silverMoss/00-firstScript.sql new file mode 100644 index 000000000..aae2e857e --- /dev/null +++ b/db/versions/11127-silverMoss/00-firstScript.sql @@ -0,0 +1 @@ +ALTER TABLE vn.invoiceInTax ADD CONSTRAINT invoiceInTax_unique UNIQUE KEY (invoiceInFk,expenseFk); From a8d663bee46d62da682a56f5fed24bce5714c029 Mon Sep 17 00:00:00 2001 From: jgallego Date: Wed, 3 Jul 2024 10:49:51 +0200 Subject: [PATCH 015/170] feat: refs #7348 hasDailyInvoice field --- db/routines/vn/procedures/client_create.sql | 24 ++++++++++++------- .../11126-blueCamellia/00-firstScript.sql | 2 ++ 2 files changed, 17 insertions(+), 9 deletions(-) create mode 100644 db/versions/11126-blueCamellia/00-firstScript.sql diff --git a/db/routines/vn/procedures/client_create.sql b/db/routines/vn/procedures/client_create.sql index d5d7258a1..f2321e129 100644 --- a/db/routines/vn/procedures/client_create.sql +++ b/db/routines/vn/procedures/client_create.sql @@ -34,20 +34,25 @@ BEGIN DECLARE vIsTaxDataChecked TINYINT(1); DECLARE vHasCoreVnl BOOLEAN; DECLARE vMandateTypeFk INT; + DECLARE vHasDailyInvoice BOOLEAN; - SELECT defaultPayMethodFk, - defaultDueDay, - defaultCredit, - defaultIsTaxDataChecked, - defaultHasCoreVnl, - defaultMandateTypeFk + SELECT cc.defaultPayMethodFk, + cc.defaultDueDay, + cc.defaultCredit, + cc.defaultIsTaxDataChecked, + cc.defaultHasCoreVnl, + cc.defaultMandateTypeFk, + c.hasDailyInvoice INTO vPayMethodFk, vDueDay, vDefaultCredit, vIsTaxDataChecked, vHasCoreVnl, - vMandateTypeFk - FROM clientConfig; + vMandateTypeFk, + vHasDailyInvoice + FROM clientConfig cc + LEFT JOIN province p ON p.id = vProvinceFk + LEFT JOIN country c ON c.id = p.countryFk; INSERT INTO `client` SET id = vUserFk, @@ -65,7 +70,8 @@ BEGIN credit = vDefaultCredit, isTaxDataChecked = vIsTaxDataChecked, hasCoreVnl = vHasCoreVnl, - isEqualizated = FALSE + isEqualizated = FALSE, + hasDailyInvoice = vHasDailyInvoice ON duplicate KEY UPDATE payMethodFk = vPayMethodFk, dueDay = vDueDay, diff --git a/db/versions/11126-blueCamellia/00-firstScript.sql b/db/versions/11126-blueCamellia/00-firstScript.sql new file mode 100644 index 000000000..45c2ed2dc --- /dev/null +++ b/db/versions/11126-blueCamellia/00-firstScript.sql @@ -0,0 +1,2 @@ +ALTER TABLE `client` +ADD COLUMN `hasDailyInvoice` TINYINT(1) NOT NULL DEFAULT 0 COMMENT 'Indica si el cliente requiere facturación diaria por defecto se copiará lo que tenga country.hasDailyInvoice'; From cf63d6e71c2d86bdb44f40f227da3ae49e02ce3e Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 3 Jul 2024 11:17:33 +0200 Subject: [PATCH 016/170] feat: refs #7378 Added productionConfigLog --- .../triggers/productionConfig_afterDelete.sql | 12 ++++++++++ .../productionConfig_beforeInsert.sql | 8 +++++++ .../productionConfig_beforeUpdate.sql | 8 +++++++ .../11130-crimsonIvy/00-firstScript.sql | 23 +++++++++++++++++++ 4 files changed, 51 insertions(+) create mode 100644 db/routines/vn/triggers/productionConfig_afterDelete.sql create mode 100644 db/routines/vn/triggers/productionConfig_beforeInsert.sql create mode 100644 db/routines/vn/triggers/productionConfig_beforeUpdate.sql create mode 100644 db/versions/11130-crimsonIvy/00-firstScript.sql diff --git a/db/routines/vn/triggers/productionConfig_afterDelete.sql b/db/routines/vn/triggers/productionConfig_afterDelete.sql new file mode 100644 index 000000000..384bf681e --- /dev/null +++ b/db/routines/vn/triggers/productionConfig_afterDelete.sql @@ -0,0 +1,12 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`productionConfig_afterDelete` + AFTER DELETE ON `productionConfig` + FOR EACH ROW +BEGIN + INSERT INTO productionConfig + SET `action` = 'delete', + `changedModel` = 'ProductionConfig', + `changedModelId` = OLD.id, + `userFk` = account.myUser_getId(); +END$$ +DELIMITER ; diff --git a/db/routines/vn/triggers/productionConfig_beforeInsert.sql b/db/routines/vn/triggers/productionConfig_beforeInsert.sql new file mode 100644 index 000000000..99b217be4 --- /dev/null +++ b/db/routines/vn/triggers/productionConfig_beforeInsert.sql @@ -0,0 +1,8 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`productionConfig_beforeInsert` + BEFORE INSERT ON `productionConfig` + FOR EACH ROW +BEGIN + SET NEW.editorFk = account.myUser_getId(); +END$$ +DELIMITER ; diff --git a/db/routines/vn/triggers/productionConfig_beforeUpdate.sql b/db/routines/vn/triggers/productionConfig_beforeUpdate.sql new file mode 100644 index 000000000..f1ceaa471 --- /dev/null +++ b/db/routines/vn/triggers/productionConfig_beforeUpdate.sql @@ -0,0 +1,8 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`productionConfig_beforeUpdate` + BEFORE UPDATE ON `productionConfig` + FOR EACH ROW +BEGIN + SET NEW.editorFk = account.myUser_getId(); +END$$ +DELIMITER ; diff --git a/db/versions/11130-crimsonIvy/00-firstScript.sql b/db/versions/11130-crimsonIvy/00-firstScript.sql new file mode 100644 index 000000000..3bde55f55 --- /dev/null +++ b/db/versions/11130-crimsonIvy/00-firstScript.sql @@ -0,0 +1,23 @@ +ALTER TABLE vn.productionConfig + ADD editorFk int(10) unsigned DEFAULT NULL NULL; +ALTER TABLE vn.productionConfig + ADD CONSTRAINT productionConfig_user_FK FOREIGN KEY (editorFk) REFERENCES account.`user`(id); + +CREATE OR REPLACE TABLE `vn`.`productionConfigLog` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `originFk` int(11) DEFAULT NULL, + `userFk` int(10) unsigned DEFAULT NULL, + `action` set('insert','update','delete','select') NOT NULL, + `creationDate` timestamp NULL DEFAULT current_timestamp(), + `description` text CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL, + `changedModel` enum('ProductionConfig') NOT NULL DEFAULT 'ProductionConfig', + `oldInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`oldInstance`)), + `newInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`newInstance`)), + `changedModelId` int(11) NOT NULL, + `changedModelValue` varchar(45) DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `logRateuserFk` (`userFk`), + KEY `productionConfigLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`), + KEY `productionConfigLog_originFk` (`originFk`,`creationDate`), + CONSTRAINT `productionConfigUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; From 4f9552379ed043f5d334e588fc9678085e7a9929 Mon Sep 17 00:00:00 2001 From: robert Date: Wed, 3 Jul 2024 13:46:19 +0200 Subject: [PATCH 017/170] feat: refs #7654 entry_splitByShelving --- .../vn/procedures/entry_splitByShelving.sql | 170 ++++++++---------- .../11131-brownPhormium/00-firstScript.sql | 1 + 2 files changed, 80 insertions(+), 91 deletions(-) create mode 100644 db/versions/11131-brownPhormium/00-firstScript.sql diff --git a/db/routines/vn/procedures/entry_splitByShelving.sql b/db/routines/vn/procedures/entry_splitByShelving.sql index 2898141ea..839bf02d1 100644 --- a/db/routines/vn/procedures/entry_splitByShelving.sql +++ b/db/routines/vn/procedures/entry_splitByShelving.sql @@ -9,70 +9,81 @@ BEGIN * @param vToEntryFk Entrada destino */ DECLARE vBuyFk INT; - DECLARE vIshStickers INT; - DECLARE vBuyStickers INT; - DECLARE vDone BOOLEAN DEFAULT FALSE; - - DECLARE cur CURSOR FOR - SELECT bb.id buyFk, - FLOOR(ish.visible / ish.packing) ishStickers, - bb.stickers buyStickers - FROM vn.itemShelving ish - JOIN (SELECT b.id, b.itemFk, b.stickers - FROM vn.buy b - WHERE b.entryFk = vFromEntryFk - ORDER BY b.stickers DESC - LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk - AND bb.stickers >= FLOOR(ish.visible / ish.packing) - WHERE shelvingFk = vShelvingFk COLLATE utf8_general_ci - GROUP BY ish.id; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + DECLARE vIshStickers INT; + DECLARE vBuyStickers INT; + DECLARE vDone BOOLEAN DEFAULT FALSE; - -- Cantidades de la matrícula que exceden la de las entradas - SELECT ish.itemFk, - i.longName, - FLOOR(ish.visible / ish.packing) AS etiEnMatricula, - bb.stickers etiEnEntrada - FROM vn.itemShelving ish - JOIN vn.item i ON i.id = ish.itemFk - LEFT JOIN (SELECT b.id, b.itemFk, b.stickers - FROM vn.buy b - WHERE b.entryFk = vFromEntryFk - ORDER BY b.stickers DESC - LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk - WHERE shelvingFk = vShelvingFk COLLATE utf8_general_ci - AND IFNULL(bb.stickers,0) < FLOOR(ish.visible / ish.packing) - GROUP BY ish.id; - - OPEN cur; - - read_loop: LOOP - SET vDone = FALSE; + DECLARE cur CURSOR FOR + SELECT bb.id buyFk, + FLOOR(ish.visible / ish.packing) ishStickers, + bb.stickers buyStickers + FROM itemShelving ish + JOIN (SELECT b.id, b.itemFk, b.stickers + FROM buy b + WHERE b.entryFk = vFromEntryFk + ORDER BY b.stickers DESC + LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk + AND bb.stickers >= FLOOR(ish.visible / ish.packing) + WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_general_ci + AND NOT ish.isSplit + GROUP BY ish.id; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - FETCH cur INTO vBuyFk, vIshStickers, vBuyStickers; + OPEN cur; - IF vDone THEN - LEAVE read_loop; - END IF; + read_loop: LOOP + SET vDone = FALSE; - IF vIshStickers = vBuyStickers THEN - UPDATE vn.buy - SET entryFk = vToEntryFk - WHERE id = vBuyFk; - ELSE - UPDATE vn.buy - SET stickers = stickers - vIshStickers, - quantity = stickers * packing - WHERE id = vBuyFk; - - INSERT INTO vn.buy(entryFk, + FETCH cur INTO vBuyFk, vIshStickers, vBuyStickers; + + IF vDone THEN + LEAVE read_loop; + END IF; + + IF vIshStickers = vBuyStickers THEN + UPDATE buy + SET entryFk = vToEntryFk + WHERE id = vBuyFk; + ELSE + UPDATE buy + SET stickers = stickers - vIshStickers, + quantity = stickers * packing + WHERE id = vBuyFk; + + INSERT INTO buy(entryFk, + itemFk, + quantity, + buyingValue, + freightValue, + isIgnored, + stickers, + packing, + `grouping`, + groupingMode, + comissionValue, + packageValue, + location, + packagingFk, + price1, + price2, + price3, + minPrice, + workerFk, + isChecked, + isPickedOff, + ektFk, + weight, + deliveryFk, + itemOriginalFk) + SELECT + vToEntryFk, itemFk, - quantity, + vIshStickers * packing, buyingValue, freightValue, isIgnored, - stickers, + vIshStickers, packing, `grouping`, groupingMode, @@ -90,40 +101,17 @@ BEGIN ektFk, weight, deliveryFk, - itemOriginalFk) - SELECT - vToEntryFk, - itemFk, - vIshStickers * packing, - buyingValue, - freightValue, - isIgnored, - vIshStickers, - packing, - `grouping`, - groupingMode, - comissionValue, - packageValue, - location, - packagingFk, - price1, - price2, - price3, - minPrice, - workerFk, - isChecked, - isPickedOff, - ektFk, - weight, - deliveryFk, - itemOriginalFk - FROM vn.buy - WHERE id = vBuyFk; - - UPDATE buy SET printedStickers = vIshStickers WHERE id = LAST_INSERT_ID(); - END IF; - END LOOP; - - CLOSE cur; + itemOriginalFk + FROM buy + WHERE id = vBuyFk; + + UPDATE buy SET printedStickers = vIshStickers WHERE id = LAST_INSERT_ID(); + END IF; + + UPDATE itemShelving + SET isSplit = TRUE + WHERE shelvingFk = vShelvingFk; + END LOOP; + CLOSE cur; END$$ DELIMITER ; diff --git a/db/versions/11131-brownPhormium/00-firstScript.sql b/db/versions/11131-brownPhormium/00-firstScript.sql new file mode 100644 index 000000000..341c9f1a3 --- /dev/null +++ b/db/versions/11131-brownPhormium/00-firstScript.sql @@ -0,0 +1 @@ +ALTER TABLE vn.itemShelving ADD isSplit tinyint(1) NULL COMMENT 'Este valor cambia al splitar un carro que se ha quedado en holanda'; \ No newline at end of file From 2278b9a05aa25835ded18b6f2ff784ba5d88ff3f Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 3 Jul 2024 14:20:43 +0200 Subject: [PATCH 018/170] feat: refs #7382 Changes --- .../vn/procedures/invoiceIn_booking.sql | 25 +++++++++++++------ .../11127-silverMoss/00-firstScript.sql | 1 - 2 files changed, 18 insertions(+), 8 deletions(-) delete mode 100644 db/versions/11127-silverMoss/00-firstScript.sql diff --git a/db/routines/vn/procedures/invoiceIn_booking.sql b/db/routines/vn/procedures/invoiceIn_booking.sql index cd838861a..decbb7b1a 100644 --- a/db/routines/vn/procedures/invoiceIn_booking.sql +++ b/db/routines/vn/procedures/invoiceIn_booking.sql @@ -13,20 +13,31 @@ BEGIN * @param vBookEntry Id de asiento, si es NULL se genera uno nuevo */ DECLARE vFiscalYear INT; - DECLARE vHasDistinctTransactions INT; + DECLARE vDistinctTransactions INT; + DECLARE vHasRepeatedTransactions BOOL; - SELECT COUNT(DISTINCT transactionTypeSageFk) INTO vHasDistinctTransactions - FROM invoiceIn ii - JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id + SELECT COUNT(DISTINCT iit.transactionTypeSageFk) INTO vDistinctTransactions + FROM invoiceInTax iit JOIN invoiceInSerial iis ON iis.code = ii.serial - WHERE ii.id = vSelf + WHERE iit.invoiceInFk = vSelf AND iis.taxAreaFk = 'CEE' - AND transactionTypeSageFk; + AND iit.transactionTypeSageFk; - IF vHasDistinctTransactions > 1 THEN + IF vDistinctTransactions > 1 THEN CALL util.throw ('This invoice does not allow different types of transactions'); END IF; + SELECT TRUE INTO vHasRepeatedTransactions + FROM invoiceInTax + WHERE invoiceInFk = vSelf + GROUP BY transactionTypeSageFk + HAVING COUNT(transactionTypeSageFk) > 1 + LIMIT 1; + + IF vHasRepeatedTransactions THEN + CALL util.throw ('This invoice contains repeated types of transactions'); + END IF; + CREATE OR REPLACE TEMPORARY TABLE tInvoiceIn ENGINE = MEMORY SELECT ii.bookEntried, diff --git a/db/versions/11127-silverMoss/00-firstScript.sql b/db/versions/11127-silverMoss/00-firstScript.sql deleted file mode 100644 index aae2e857e..000000000 --- a/db/versions/11127-silverMoss/00-firstScript.sql +++ /dev/null @@ -1 +0,0 @@ -ALTER TABLE vn.invoiceInTax ADD CONSTRAINT invoiceInTax_unique UNIQUE KEY (invoiceInFk,expenseFk); From 246b34571d786f8fbf635038304135629ab16077 Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 3 Jul 2024 14:24:26 +0200 Subject: [PATCH 019/170] feat: refs #7382 Fix --- db/routines/vn/procedures/invoiceIn_booking.sql | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/db/routines/vn/procedures/invoiceIn_booking.sql b/db/routines/vn/procedures/invoiceIn_booking.sql index decbb7b1a..c194a774d 100644 --- a/db/routines/vn/procedures/invoiceIn_booking.sql +++ b/db/routines/vn/procedures/invoiceIn_booking.sql @@ -17,7 +17,8 @@ BEGIN DECLARE vHasRepeatedTransactions BOOL; SELECT COUNT(DISTINCT iit.transactionTypeSageFk) INTO vDistinctTransactions - FROM invoiceInTax iit + FROM invoiceIn ii + JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id JOIN invoiceInSerial iis ON iis.code = ii.serial WHERE iit.invoiceInFk = vSelf AND iis.taxAreaFk = 'CEE' From 1ec7cd9540dc3e1d003cbb8d31e3b291383af0fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Wed, 3 Jul 2024 16:59:01 +0200 Subject: [PATCH 020/170] Hotfix sale_getProblems --- db/routines/vn/procedures/sale_getProblems.sql | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/db/routines/vn/procedures/sale_getProblems.sql b/db/routines/vn/procedures/sale_getProblems.sql index 9944ab0c2..f198be54b 100644 --- a/db/routines/vn/procedures/sale_getProblems.sql +++ b/db/routines/vn/procedures/sale_getProblems.sql @@ -278,12 +278,11 @@ BEGIN -- Redondeo: Cantidad pedida incorrecta en al grouping de la última compra CALL buyUltimate(vWarehouseFk, vDate); INSERT INTO tmp.sale_problems(ticketFk, hasRounding, saleFk) - SELECT ticketFk, problem, saleFk + SELECT ticketFk,problem , saleFk FROM ( SELECT tl.ticketFk, - s.id saleFk , - LEFT(GROUP_CONCAT('RE: ',i.id, ' ', IFNULL(i.longName,''), ' '), 250) problem, - MOD(s.quantity, b.`grouping`) hasRounding + s.id saleFk, + LEFT(GROUP_CONCAT('RE: ',i.id, ' ', IFNULL(i.longName,''), ' '), 250) problem FROM tmp.ticket_list tl JOIN ticket t ON t.id = tl.ticketFk AND t.warehouseFk = vWarehouseFk @@ -291,9 +290,9 @@ BEGIN JOIN item i ON i.id = s.itemFk JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk JOIN buy b ON b.id = bu.buyFk + WHERE MOD(s.quantity, b.`grouping`) GROUP BY tl.ticketFk - HAVING hasRounding - ) sub + )sub ON DUPLICATE KEY UPDATE hasRounding = sub.problem, saleFk = sub.saleFk; END LOOP; CLOSE vCursor; From 097350adb66a233515018f2e8a17b86065fdef54 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Wed, 3 Jul 2024 17:07:25 +0200 Subject: [PATCH 021/170] Hotfix sale_getProblems --- db/routines/vn/procedures/sale_getProblems.sql | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/db/routines/vn/procedures/sale_getProblems.sql b/db/routines/vn/procedures/sale_getProblems.sql index f198be54b..ba4ff5857 100644 --- a/db/routines/vn/procedures/sale_getProblems.sql +++ b/db/routines/vn/procedures/sale_getProblems.sql @@ -278,11 +278,11 @@ BEGIN -- Redondeo: Cantidad pedida incorrecta en al grouping de la última compra CALL buyUltimate(vWarehouseFk, vDate); INSERT INTO tmp.sale_problems(ticketFk, hasRounding, saleFk) - SELECT ticketFk,problem , saleFk + SELECT ticketFk, problem ,saleFk FROM ( SELECT tl.ticketFk, s.id saleFk, - LEFT(GROUP_CONCAT('RE: ',i.id, ' ', IFNULL(i.longName,''), ' '), 250) problem + LEFT(GROUP_CONCAT('RE: ',i.id, ' ', IFNULL(i.longName,'') SEPARATOR ', '), 250) problem FROM tmp.ticket_list tl JOIN ticket t ON t.id = tl.ticketFk AND t.warehouseFk = vWarehouseFk From d65af6aaaac6c5cb85856d2f44f97bf327b26a43 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Wed, 3 Jul 2024 18:00:28 +0200 Subject: [PATCH 022/170] feat: Avisar cuando no hay posibilidad de fichar refs #7669 --- .../vn/procedures/workerTimeControl_direction.sql | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/db/routines/vn/procedures/workerTimeControl_direction.sql b/db/routines/vn/procedures/workerTimeControl_direction.sql index f7a68e1e4..807dc46c6 100644 --- a/db/routines/vn/procedures/workerTimeControl_direction.sql +++ b/db/routines/vn/procedures/workerTimeControl_direction.sql @@ -9,6 +9,8 @@ BEGIN */ DECLARE vLastIn DATETIME ; DECLARE vIsMiddleOdd BOOLEAN ; + DECLARE vMailTo VARCHAR(50) DEFAULT NULL; + DECLARE vUserName VARCHAR(50) DEFAULT NULL; IF (vTimed IS NULL) THEN SET vTimed = util.VN_NOW(); @@ -57,5 +59,18 @@ BEGIN VALUES('in', NULL); END IF; + IF (SELECT option1 IS NULL AND option2 IS NULL FROM tmp.workerTimeControlDirection) THEN + SELECT CONCAT(u.name, '@verdnatura.es'), CONCAT(w.firstName, ' ', w.lastName) + INTO vMailTo, vUserName + FROM account.user u + JOIN worker w ON w.bossFk = u.id + WHERE w.id = vWorkerFk; + + CALL mail_insert( + vMailTo, + vMailTo, + 'Error al fichar', + CONCAT(vUserName, ' tiene problemas para fichar'); + END IF; END$$ DELIMITER ; From 989fa5ac5a3f2b101a38b85413f1552be9c3111f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Wed, 3 Jul 2024 18:10:02 +0200 Subject: [PATCH 023/170] feat: Avisar cuando no hay posibilidad de fichar refs #7669 --- db/routines/vn/procedures/workerTimeControl_direction.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/routines/vn/procedures/workerTimeControl_direction.sql b/db/routines/vn/procedures/workerTimeControl_direction.sql index 807dc46c6..8e807084c 100644 --- a/db/routines/vn/procedures/workerTimeControl_direction.sql +++ b/db/routines/vn/procedures/workerTimeControl_direction.sql @@ -70,7 +70,7 @@ BEGIN vMailTo, vMailTo, 'Error al fichar', - CONCAT(vUserName, ' tiene problemas para fichar'); + CONCAT(vUserName, ' tiene problemas para fichar')); END IF; END$$ DELIMITER ; From d59cab13d8556a12135a8a0540ea4de5d3fdfa34 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Wed, 3 Jul 2024 23:02:28 +0200 Subject: [PATCH 024/170] feat(salix): refs #7380 #7380 client.substitutionAllowed new field --- db/versions/11132-aquaDracena/00-firstScript.sql | 1 + modules/client/back/models/client.json | 3 +++ 2 files changed, 4 insertions(+) create mode 100644 db/versions/11132-aquaDracena/00-firstScript.sql diff --git a/db/versions/11132-aquaDracena/00-firstScript.sql b/db/versions/11132-aquaDracena/00-firstScript.sql new file mode 100644 index 000000000..d309098c5 --- /dev/null +++ b/db/versions/11132-aquaDracena/00-firstScript.sql @@ -0,0 +1 @@ +ALTER TABLE vn.client ADD substitutionAllowed BOOL DEFAULT false NULL; diff --git a/modules/client/back/models/client.json b/modules/client/back/models/client.json index f3eb9919b..97c2a3624 100644 --- a/modules/client/back/models/client.json +++ b/modules/client/back/models/client.json @@ -53,6 +53,9 @@ "isActive": { "type": "boolean" }, + "substitutionAllowed": { + "type": "boolean" + }, "credit": { "type": "number" }, From 17e7dc8c7ee35b0ae9f9a1914b7c9ad2b3f114b0 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Wed, 3 Jul 2024 23:02:47 +0200 Subject: [PATCH 025/170] feat(salix): refs #7380 #7380 new typeObservation --- db/versions/11132-aquaDracena/00-firstScript.sql | 3 +++ 1 file changed, 3 insertions(+) diff --git a/db/versions/11132-aquaDracena/00-firstScript.sql b/db/versions/11132-aquaDracena/00-firstScript.sql index d309098c5..1b304c1d0 100644 --- a/db/versions/11132-aquaDracena/00-firstScript.sql +++ b/db/versions/11132-aquaDracena/00-firstScript.sql @@ -1 +1,4 @@ +INSERT IGNORE INTO vn.observationType (`description`,code,hasNewBornMessage) + VALUES ('Sustitución','substitution',0); + ALTER TABLE vn.client ADD substitutionAllowed BOOL DEFAULT false NULL; From a7b653c42a5f886d8eba1507fff24bcbc8dbdb4d Mon Sep 17 00:00:00 2001 From: guillermo Date: Thu, 4 Jul 2024 07:34:41 +0200 Subject: [PATCH 026/170] refs #7486 Fix collection_new --- .../vn/procedures/collection_assign.sql | 4 +- db/routines/vn/procedures/collection_get.sql | 45 ++++++++++--------- .../vn/procedures/productionControl.sql | 8 +++- db/routines/vn/procedures/ticket_Clone.sql | 5 +++ 4 files changed, 39 insertions(+), 23 deletions(-) diff --git a/db/routines/vn/procedures/collection_assign.sql b/db/routines/vn/procedures/collection_assign.sql index 84067e7d8..bf130b2c6 100644 --- a/db/routines/vn/procedures/collection_assign.sql +++ b/db/routines/vn/procedures/collection_assign.sql @@ -47,9 +47,9 @@ BEGIN INTO vHasTooMuchCollections, vLockName FROM productionConfig pc - LEFT JOIN tCollection ON TRUE; + LEFT JOIN tmp.collection ON TRUE; - DROP TEMPORARY TABLE tCollection; + DROP TEMPORARY TABLE tmp.collection; IF vHasTooMuchCollections THEN CALL util.throw('Hay colecciones pendientes'); diff --git a/db/routines/vn/procedures/collection_get.sql b/db/routines/vn/procedures/collection_get.sql index 372d963c0..d29f14ca9 100644 --- a/db/routines/vn/procedures/collection_get.sql +++ b/db/routines/vn/procedures/collection_get.sql @@ -7,27 +7,32 @@ BEGIN * @param vWorkerFk id del worker. * @table Devuelve tabla temporal con las colecciones pendientes */ - DROP TEMPORARY TABLE IF EXISTS tCollection; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + RESIGNAL; + END; - CREATE TEMPORARY TABLE tCollection - SELECT c.id collectionFk, - date(c.created) created, - COUNT(DISTINCT tc.ticketFk) ticketTotalCount - FROM collection c - JOIN ticketCollection tc ON tc.collectionFk = c.id - JOIN sale s ON s.ticketFk = tc.ticketFk - JOIN ticketState ts ON ts.ticketFk = tc.ticketFk - JOIN state s2 ON s2.id = ts.stateFk - JOIN productionConfig pc - JOIN vn.state ss on ss.code = 'PREPARED' - LEFT JOIN vn.saleTracking st on st.saleFk = s.id AND st.stateFk = ss.id - WHERE c.workerFk = vWorkerFk - AND TIMESTAMPDIFF(HOUR, c.created , util.VN_NOW()) < pc.pendingCollectionsAge - AND s.quantity != 0 - AND s2.order < pc.pendingCollectionsOrder - GROUP BY c.id - HAVING COUNT(*) > COUNT(DISTINCT st.id); + CREATE OR REPLACE TEMPORARY TABLE tmp.collection + ENGINE = MEMORY + SELECT c.id collectionFk, + DATE(c.created) created, + COUNT(DISTINCT tc.ticketFk) ticketTotalCount + FROM collection c + JOIN ticketCollection tc ON tc.collectionFk = c.id + JOIN sale s ON s.ticketFk = tc.ticketFk + JOIN ticketState ts ON ts.ticketFk = tc.ticketFk + JOIN state s2 ON s2.id = ts.stateFk + JOIN productionConfig pc + JOIN vn.state ss ON ss.code = 'PREPARED' + LEFT JOIN vn.saleTracking st ON st.saleFk = s.id + AND st.stateFk = ss.id + WHERE c.workerFk = vWorkerFk + AND TIMESTAMPDIFF(HOUR, c.created , util.VN_NOW()) < pc.pendingCollectionsAge + AND s.quantity + AND s2.order < pc.pendingCollectionsOrder + GROUP BY c.id + HAVING COUNT(*) > COUNT(DISTINCT st.id); - SELECT * FROM tCollection; + SELECT * FROM tmp.collection; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/productionControl.sql b/db/routines/vn/procedures/productionControl.sql index 09c01d1ef..dad46393d 100644 --- a/db/routines/vn/procedures/productionControl.sql +++ b/db/routines/vn/procedures/productionControl.sql @@ -15,6 +15,11 @@ proc: BEGIN DECLARE vEndingDate DATETIME; DECLARE vIsTodayRelative BOOLEAN; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + RESIGNAL; + END; + SELECT util.dayEnd(util.VN_CURDATE()) + INTERVAL LEAST(vScopeDays, maxProductionScopeDays) DAY INTO vEndingDate FROM productionConfig; @@ -31,7 +36,8 @@ proc: BEGIN CALL prepareClientList(); CREATE OR REPLACE TEMPORARY TABLE tmp.sale_getProblems - (INDEX (ticketFk)) ENGINE = MEMORY + (INDEX (ticketFk)) + ENGINE = MEMORY SELECT tt.ticketFk, tt.clientFk, t.warehouseFk, t.shipped FROM tmp.productionTicket tt JOIN ticket t ON t.id = tt.ticketFk; diff --git a/db/routines/vn/procedures/ticket_Clone.sql b/db/routines/vn/procedures/ticket_Clone.sql index 7670e832e..d22d3c7ff 100644 --- a/db/routines/vn/procedures/ticket_Clone.sql +++ b/db/routines/vn/procedures/ticket_Clone.sql @@ -9,6 +9,11 @@ BEGIN */ DECLARE vStateFk INT; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + RESIGNAL; + END; + INSERT INTO ticket ( clientFk, shipped, From 897da1e48a70570d6fc172f301b7ac347bc84622 Mon Sep 17 00:00:00 2001 From: robert Date: Thu, 4 Jul 2024 08:59:22 +0200 Subject: [PATCH 027/170] feat: refs #7654 --- .../vn/procedures/entry_splitByShelving.sql | 164 +++++++++--------- 1 file changed, 82 insertions(+), 82 deletions(-) diff --git a/db/routines/vn/procedures/entry_splitByShelving.sql b/db/routines/vn/procedures/entry_splitByShelving.sql index 839bf02d1..eb07c12b7 100644 --- a/db/routines/vn/procedures/entry_splitByShelving.sql +++ b/db/routines/vn/procedures/entry_splitByShelving.sql @@ -9,81 +9,55 @@ BEGIN * @param vToEntryFk Entrada destino */ DECLARE vBuyFk INT; - DECLARE vIshStickers INT; - DECLARE vBuyStickers INT; - DECLARE vDone BOOLEAN DEFAULT FALSE; + DECLARE vIshStickers INT; + DECLARE vBuyStickers INT; + DECLARE vDone BOOLEAN DEFAULT FALSE; + + DECLARE cur CURSOR FOR + SELECT bb.id buyFk, + FLOOR(ish.visible / ish.packing) ishStickers, + bb.stickers buyStickers + FROM itemShelving ish + JOIN (SELECT b.id, b.itemFk, b.stickers + FROM buy b + WHERE b.entryFk = vFromEntryFk + ORDER BY b.stickers DESC + LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk + AND bb.stickers >= FLOOR(ish.visible / ish.packing) + WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_general_ci + AND NOT ish.isSplit + GROUP BY ish.id; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + OPEN cur; + + read_loop: LOOP + SET vDone = FALSE; - DECLARE cur CURSOR FOR - SELECT bb.id buyFk, - FLOOR(ish.visible / ish.packing) ishStickers, - bb.stickers buyStickers - FROM itemShelving ish - JOIN (SELECT b.id, b.itemFk, b.stickers - FROM buy b - WHERE b.entryFk = vFromEntryFk - ORDER BY b.stickers DESC - LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk - AND bb.stickers >= FLOOR(ish.visible / ish.packing) - WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_general_ci - AND NOT ish.isSplit - GROUP BY ish.id; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - OPEN cur; - - read_loop: LOOP - SET vDone = FALSE; - - FETCH cur INTO vBuyFk, vIshStickers, vBuyStickers; - - IF vDone THEN - LEAVE read_loop; - END IF; - - IF vIshStickers = vBuyStickers THEN - UPDATE buy - SET entryFk = vToEntryFk - WHERE id = vBuyFk; - ELSE - UPDATE buy - SET stickers = stickers - vIshStickers, - quantity = stickers * packing - WHERE id = vBuyFk; - - INSERT INTO buy(entryFk, - itemFk, - quantity, - buyingValue, - freightValue, - isIgnored, - stickers, - packing, - `grouping`, - groupingMode, - comissionValue, - packageValue, - location, - packagingFk, - price1, - price2, - price3, - minPrice, - workerFk, - isChecked, - isPickedOff, - ektFk, - weight, - deliveryFk, - itemOriginalFk) - SELECT - vToEntryFk, + FETCH cur INTO vBuyFk, vIshStickers, vBuyStickers; + + IF vDone THEN + LEAVE read_loop; + END IF; + + IF vIshStickers = vBuyStickers THEN + UPDATE buy + SET entryFk = vToEntryFk + WHERE id = vBuyFk; + ELSE + UPDATE buy + SET stickers = stickers - vIshStickers, + quantity = stickers * packing + WHERE id = vBuyFk; + + INSERT INTO buy(entryFk, itemFk, - vIshStickers * packing, + quantity, buyingValue, freightValue, isIgnored, - vIshStickers, + stickers, packing, `grouping`, groupingMode, @@ -101,17 +75,43 @@ BEGIN ektFk, weight, deliveryFk, - itemOriginalFk - FROM buy - WHERE id = vBuyFk; - - UPDATE buy SET printedStickers = vIshStickers WHERE id = LAST_INSERT_ID(); - END IF; - - UPDATE itemShelving - SET isSplit = TRUE - WHERE shelvingFk = vShelvingFk; - END LOOP; - CLOSE cur; + itemOriginalFk) + SELECT + vToEntryFk, + itemFk, + vIshStickers * packing, + buyingValue, + freightValue, + isIgnored, + vIshStickers, + packing, + `grouping`, + groupingMode, + comissionValue, + packageValue, + location, + packagingFk, + price1, + price2, + price3, + minPrice, + workerFk, + isChecked, + isPickedOff, + ektFk, + weight, + deliveryFk, + itemOriginalFk + FROM buy + WHERE id = vBuyFk; + + UPDATE buy SET printedStickers = vIshStickers WHERE id = LAST_INSERT_ID(); + END IF; + + UPDATE itemShelving + SET isSplit = TRUE + WHERE shelvingFk = vShelvingFk; + END LOOP; + CLOSE cur; END$$ DELIMITER ; From a7895ab0a45c56ce7a04e86258dd3ab2add482f6 Mon Sep 17 00:00:00 2001 From: guillermo Date: Thu, 4 Jul 2024 09:17:22 +0200 Subject: [PATCH 028/170] refs #6769 First commit --- db/routines/vn/procedures/item_getBalance.sql | 224 +++++++++++------- 1 file changed, 144 insertions(+), 80 deletions(-) diff --git a/db/routines/vn/procedures/item_getBalance.sql b/db/routines/vn/procedures/item_getBalance.sql index a4942af6f..561957452 100644 --- a/db/routines/vn/procedures/item_getBalance.sql +++ b/db/routines/vn/procedures/item_getBalance.sql @@ -2,25 +2,65 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_getBalance`( vItemFk INT, vWarehouseFk INT, - vDate DATETIME + vDated DATETIME ) BEGIN /** - * @vItemFk item a buscar - * @vWarehouseFk almacen donde buscar - * @vDate Si la fecha es null, muestra el histórico desde el inventario. - * Si la fecha no es null, muestra histórico desde la fecha de vDate. + * Calcula el disponible. + * + * @vItemFk Id de artículo + * @vWarehouseFk Id de almacén + * @vDated Fecha + * Si la fecha es NULL, muestra el histórico desde el inventario. + * Si la fecha no es NULL, muestra histórico desde la fecha de vDated. */ DECLARE vDateInventory DATETIME; + DECLARE vLifeScope DATE; + DECLARE vWarehouseInventoryFk INT; + DECLARE vSupplierInventoryFk INT; - IF vDate IS NULL THEN - SELECT inventoried INTO vDateInventory - FROM config; - ELSE - SELECT mockUtcTime INTO vDateInventory - FROM util.config; + SELECT IF(vDated, uc.mockUtcTime, c.inventoried) INTO vDateInventory + FROM config c + JOIN util.config uc; + + SELECT COALESCE(vDated, vDateInventory) - INTERVAL MAX(life) DAY + INTO vLifeScope + FROM itemType; + + SELECT warehouseOutFk, supplierFk + INTO vWarehouseInventoryFk, vSupplierInventoryFk + FROM inventoryConfig; + + IF NOT vWarehouseInventoryFk OR NOT vSupplierInventoryFk THEN + CALL util.throw('Config variables are not set'); END IF; + -- Calcula el ultimo dia de vida para cada producto + CREATE OR REPLACE TEMPORARY TABLE tItemRange + (PRIMARY KEY (itemFk)) + ENGINE = MEMORY + SELECT i.id itemFk, + util.dayEnd(c.maxLanded + INTERVAL it.life DAY) ended, + it.life + FROM item i + LEFT JOIN ( + SELECT b.itemFk, MAX(t.landed) maxLanded + FROM buy b + JOIN entry e ON b.entryFk = e.id + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseInFk + JOIN item i ON i.id = b.itemFk + JOIN itemType it ON it.id = i.typeFk + WHERE t.landed BETWEEN vLifeScope AND COALESCE(vDated, vDateInventory) + AND t.warehouseInFk = vWarehouseFk + AND t.warehouseOutFk <> vWarehouseInventoryFk + AND it.life + AND NOT e.isExcludedFromAvailable + GROUP BY b.itemFk + ) c ON i.id = c.itemFk + JOIN itemType it ON it.id = i.typeFk + HAVING ended >= COALESCE(vDated, vDateInventory) OR life IS NULL; + CREATE OR REPLACE TEMPORARY TABLE tItemDiary( shipped DATE, `in` INT(11), @@ -37,8 +77,9 @@ BEGIN `order` TINYINT(3) UNSIGNED, clientType VARCHAR(20), claimFk INT(10) UNSIGNED, - inventorySupplierFk INT(10) - ); + inventorySupplierFk INT(10), + orderFk INT(10) UNSIGNED + ) ENGINE = MEMORY; INSERT INTO tItemDiary WITH entriesIn AS ( @@ -57,7 +98,8 @@ BEGIN NULL `order`, NULL clientType, NULL claimFk, - ec.inventorySupplierFk + vSupplierInventoryFk inventorySupplierFk, + NULL orderFk FROM vn.buy b JOIN vn.entry e ON e.id = b.entryFk JOIN vn.travel tr ON tr.id = e.travelFk @@ -66,20 +108,20 @@ BEGIN OR (util.VN_CURDATE() AND tr.isReceived), 'DELIVERED', 'FREE') - JOIN vn.entryConfig ec WHERE tr.landed >= vDateInventory - AND vWarehouseFk = tr.warehouseInFk - AND (s.id <> ec.inventorySupplierFk OR vDate IS NULL) + AND tr.warehouseInFk = vWarehouseFk + AND (s.id <> vSupplierInventoryFk OR vDated IS NULL) AND b.itemFk = vItemFk AND NOT e.isExcludedFromAvailable AND NOT e.isRaid - ), entriesOut AS ( + ), + entriesOut AS ( SELECT tr.shipped, NULL, b.quantity, st.alertLevel, st.name stateName, - s.name , + s.name, e.invoiceNumber, e.id entryFk, s.id supplierFk, @@ -89,7 +131,8 @@ BEGIN NULL `order`, NULL clientType, NULL claimFk, - ec.inventorySupplierFk + vSupplierInventoryFk, + NULL orderFk FROM vn.buy b JOIN vn.entry e ON e.id = b.entryFk JOIN vn.travel tr ON tr.id = e.travelFk @@ -102,39 +145,41 @@ BEGIN JOIN vn.entryConfig ec WHERE tr.shipped >= vDateInventory AND vWarehouseFk = tr.warehouseOutFk - AND (s.id <> ec.inventorySupplierFk OR vDate IS NULL) + AND (s.id <> vSupplierInventoryFk OR vDated IS NULL) AND b.itemFk = vItemFk AND NOT e.isExcludedFromAvailable AND NOT w.isFeedStock AND NOT e.isRaid - ), sales AS ( - SELECT DATE(t.shipped) shipped, - s.quantity, - st2.alertLevel, - st2.name, - t.nickname, - t.refFk, - t.id ticketFk, - t.clientFk, - s.id saleFk, - st.`order`, - c.typeFk, - cb.claimFk - FROM vn.sale s - JOIN vn.ticket t ON t.id = s.ticketFk - LEFT JOIN vn.ticketState ts ON ts.ticketFk = t.id - LEFT JOIN vn.state st ON st.`code` = ts.`code` - JOIN vn.client c ON c.id = t.clientFk - JOIN vn.state st2 ON st2.`code` = IF(t.shipped < util.VN_CURDATE(), - 'DELIVERED', - IF (t.shipped > util.dayEnd(util.VN_CURDATE()), - 'FREE', - IFNULL(ts.code, 'FREE'))) - LEFT JOIN vn.claimBeginning cb ON s.id = cb.saleFk - WHERE t.shipped >= vDateInventory - AND s.itemFk = vItemFk - AND vWarehouseFk = t.warehouseFk - ),sale AS ( + ), + sales AS ( + WITH itemSales AS ( + SELECT DATE(t.shipped) shipped, + s.quantity, + st2.alertLevel, + st2.name, + t.nickname, + t.refFk, + t.id ticketFk, + t.clientFk, + s.id saleFk, + st.`order`, + c.typeFk, + cb.claimFk + FROM vn.sale s + JOIN vn.ticket t ON t.id = s.ticketFk + LEFT JOIN vn.ticketState ts ON ts.ticketFk = t.id + LEFT JOIN vn.state st ON st.`code` = ts.`code` + JOIN vn.client c ON c.id = t.clientFk + JOIN vn.state st2 ON st2.`code` = IF(t.shipped < util.VN_CURDATE(), + 'DELIVERED', + IF (t.shipped > util.dayEnd(util.VN_CURDATE()), + 'FREE', + IFNULL(ts.code, 'FREE'))) + LEFT JOIN vn.claimBeginning cb ON s.id = cb.saleFk + WHERE t.shipped >= vDateInventory + AND s.itemFk = vItemFk + AND vWarehouseFk = t.warehouseFk + ) SELECT s.shipped, NULL `in`, s.quantity, @@ -144,39 +189,55 @@ BEGIN s.refFk, s.ticketFk, s.clientFk, - IF(stk.saleFk, TRUE, NULL), + IF(stk.saleFk, TRUE, FALSE), TRUE, s.saleFk, s.`order`, s.typeFk, s.claimFk, - NULL - FROM sales s + NULL, + NULL orderFk + FROM itemSales s LEFT JOIN vn.state stPrep ON stPrep.`code` = 'PREPARED' LEFT JOIN vn.saleTracking stk ON stk.saleFk = s.saleFk AND stk.stateFk = stPrep.id GROUP BY s.saleFk - ) SELECT shipped, - `in`, - `out`, - alertLevel, - stateName, - `name`, - reference, - origin, - clientFk, - isPicked, - isTicket, - lineFk, - `order`, - clientType, - claimFk, - inventorySupplierFk - FROM entriesIn + ), + orders AS ( + SELECT r.shipment, + NULL 'in', + r.amount, + NULL alertLevel, + NULL stateName, + NULL, + NULL invoiceNumber, + NULL entryFk, + NULL supplierFk, + FALSE, + FALSE isTicket, + NULL buyFk, + NULL 'order', + c.typeFk, + NULL claimFk, + NULL inventorySupplierFk, + o.id + FROM hedera.orderRow r + JOIN hedera.`order` o ON o.id = r.orderFk + JOIN tItemRange ir ON ir.itemFk = r.itemFk + JOIN vn.client c ON c.id = o.customer_id + WHERE r.shipment >= vDateInventory + AND (ir.ended IS NULL OR r.shipment <= ir.ended) + AND r.warehouseFk = vWarehouseFk + AND NOT o.confirmed + AND r.itemFk = vItemFk + ) + SELECT * FROM entriesIn UNION ALL SELECT * FROM entriesOut UNION ALL - SELECT * FROM sale + SELECT * FROM sales + UNION ALL + SELECT * FROM orders ORDER BY shipped, (inventorySupplierFk = clientFk) DESC, alertLevel DESC, @@ -186,8 +247,7 @@ BEGIN `in` DESC, `out` DESC; - IF vDate IS NULL THEN - + IF vDated IS NULL THEN SET @a := 0; SET @currentLineFk := 0; SET @shipped := ''; @@ -211,16 +271,16 @@ BEGIN t.isPicked, t.clientType, t.claimFk, - t.`order` + t.`order`, + t.orderFk FROM tItemDiary t LEFT JOIN alertLevel a ON a.id = t.alertLevel; - ELSE SELECT IFNULL(SUM(IFNULL(`in`, 0)) - SUM(IFNULL(`out`, 0)), 0) INTO @a FROM tItemDiary - WHERE shipped < vDate; + WHERE shipped < vDated; - SELECT vDate shipped, + SELECT vDated shipped, 0 alertLevel, 0 stateName, 0 origin, @@ -236,7 +296,8 @@ BEGIN 0 isPicked, 0 clientType, 0 claimFk, - NULL `order` + NULL `order`, + 0 orderFk UNION ALL SELECT shipped, alertlevel, @@ -253,11 +314,14 @@ BEGIN isPicked, clientType, claimFk, - `order` + `order`, + orderFk FROM tItemDiary - WHERE shipped >= vDate; + WHERE shipped >= vDated; END IF; - DROP TEMPORARY TABLE tItemDiary; + DROP TEMPORARY TABLE + tItemDiary, + tItemRange; END$$ DELIMITER ; From 009dcd8fc7d3aabf91166752c09dd67749ce8caa Mon Sep 17 00:00:00 2001 From: guillermo Date: Thu, 4 Jul 2024 09:23:57 +0200 Subject: [PATCH 029/170] refs #7486 Fix tests --- db/dump/.dump/structure.sql | 3404 +++++++++++++++++------------------ 1 file changed, 1702 insertions(+), 1702 deletions(-) diff --git a/db/dump/.dump/structure.sql b/db/dump/.dump/structure.sql index cd5b6aa3b..6797c01a5 100644 --- a/db/dump/.dump/structure.sql +++ b/db/dump/.dump/structure.sql @@ -3109,55 +3109,55 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `analisis_ventas_update`() -BEGIN - DECLARE vLastMonth DATE; - - SET vLastMonth = util.firstDayOfMonth(TIMESTAMPADD(MONTH, -1, util.VN_CURDATE())); - - DELETE FROM analisis_ventas - WHERE Año > YEAR(vLastMonth) - OR (Año = YEAR(vLastMonth) AND Mes >= MONTH(vLastMonth)); - - INSERT INTO analisis_ventas ( - Familia, - Reino, - Comercial, - Comprador, - Provincia, - almacen, - Año, - Mes, - Semana, - Vista, - Importe - ) - SELECT - it.name, - ic.name, - w.code, - w2.code, - p.name, - wa.name, - tm.year, - tm.month, - tm.week, - dm.description, - bt.importe - FROM bs.ventas bt - LEFT JOIN vn.itemType it ON it.id = bt.tipo_id - LEFT JOIN vn.itemCategory ic ON ic.id = it.categoryFk - LEFT JOIN vn.client c on c.id = bt.Id_Cliente - LEFT JOIN vn.worker w ON w.id = c.salesPersonFk - LEFT JOIN vn.worker w2 ON w2.id = it.workerFk - JOIN vn.time tm ON tm.dated = bt.fecha - JOIN vn.sale s ON s.id = bt.Id_Movimiento - LEFT JOIN vn.ticket t ON t.id = s.ticketFk - JOIN vn.agencyMode am ON am.id = t.agencyModeFk - LEFT JOIN vn.deliveryMethod dm ON dm.id = am.deliveryMethodFk - LEFT JOIN vn.address a ON a.id = t.addressFk - LEFT JOIN vn.province p ON p.id = a.provinceFk - LEFT JOIN vn.warehouse wa ON wa.id = t.warehouseFk - WHERE bt.fecha >= vLastMonth AND ic.merchandise; +BEGIN + DECLARE vLastMonth DATE; + + SET vLastMonth = util.firstDayOfMonth(TIMESTAMPADD(MONTH, -1, util.VN_CURDATE())); + + DELETE FROM analisis_ventas + WHERE Año > YEAR(vLastMonth) + OR (Año = YEAR(vLastMonth) AND Mes >= MONTH(vLastMonth)); + + INSERT INTO analisis_ventas ( + Familia, + Reino, + Comercial, + Comprador, + Provincia, + almacen, + Año, + Mes, + Semana, + Vista, + Importe + ) + SELECT + it.name, + ic.name, + w.code, + w2.code, + p.name, + wa.name, + tm.year, + tm.month, + tm.week, + dm.description, + bt.importe + FROM bs.ventas bt + LEFT JOIN vn.itemType it ON it.id = bt.tipo_id + LEFT JOIN vn.itemCategory ic ON ic.id = it.categoryFk + LEFT JOIN vn.client c on c.id = bt.Id_Cliente + LEFT JOIN vn.worker w ON w.id = c.salesPersonFk + LEFT JOIN vn.worker w2 ON w2.id = it.workerFk + JOIN vn.time tm ON tm.dated = bt.fecha + JOIN vn.sale s ON s.id = bt.Id_Movimiento + LEFT JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.agencyMode am ON am.id = t.agencyModeFk + LEFT JOIN vn.deliveryMethod dm ON dm.id = am.deliveryMethodFk + LEFT JOIN vn.address a ON a.id = t.addressFk + LEFT JOIN vn.province p ON p.id = a.provinceFk + LEFT JOIN vn.warehouse wa ON wa.id = t.warehouseFk + WHERE bt.fecha >= vLastMonth AND ic.merchandise; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -3355,21 +3355,21 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `clean`() -BEGIN - DECLARE vDateShort DATETIME; - DECLARE vDateLong DATETIME; - DECLARE vOneYearAgo DATETIME; - - SET vDateShort = TIMESTAMPADD(MONTH, -2, util.VN_CURDATE()); - SET vDateLong = TIMESTAMPADD(MONTH, -18,util.VN_CURDATE()); - SET vOneYearAgo = TIMESTAMPADD(YEAR, -1,util.VN_CURDATE()); - - DELETE FROM bi.Greuge_Evolution - WHERE (Fecha < vDateShort AND weekday(Fecha) != 1) - OR Fecha < vOneYearAgo; - - DELETE FROM bi.defaulters WHERE `date` < vDateLong; - DELETE FROM bi.defaulting WHERE `date` < vDateLong; +BEGIN + DECLARE vDateShort DATETIME; + DECLARE vDateLong DATETIME; + DECLARE vOneYearAgo DATETIME; + + SET vDateShort = TIMESTAMPADD(MONTH, -2, util.VN_CURDATE()); + SET vDateLong = TIMESTAMPADD(MONTH, -18,util.VN_CURDATE()); + SET vOneYearAgo = TIMESTAMPADD(YEAR, -1,util.VN_CURDATE()); + + DELETE FROM bi.Greuge_Evolution + WHERE (Fecha < vDateShort AND weekday(Fecha) != 1) + OR Fecha < vOneYearAgo; + + DELETE FROM bi.defaulters WHERE `date` < vDateLong; + DELETE FROM bi.defaulting WHERE `date` < vDateLong; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -3558,18 +3558,18 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `facturacion_media_anual_update`() -BEGIN - TRUNCATE TABLE bs.clientAnnualConsumption; - - REPLACE bi.facturacion_media_anual(Id_Cliente, Consumo) - SELECT clientFk, avg(Facturacion) - FROM ( - SELECT clientFk, YEAR(issued) year, MONTH(issued) month, sum(amount) as Facturacion - FROM vn.invoiceOut - WHERE issued BETWEEN TIMESTAMPADD(YEAR,-1,util.VN_CURDATE()) AND TIMESTAMPADD(DAY, - DAY(util.VN_CURDATE()),util.VN_CURDATE()) - GROUP BY clientFk, year, month - ) vol - GROUP BY clientFk; +BEGIN + TRUNCATE TABLE bs.clientAnnualConsumption; + + REPLACE bi.facturacion_media_anual(Id_Cliente, Consumo) + SELECT clientFk, avg(Facturacion) + FROM ( + SELECT clientFk, YEAR(issued) year, MONTH(issued) month, sum(amount) as Facturacion + FROM vn.invoiceOut + WHERE issued BETWEEN TIMESTAMPADD(YEAR,-1,util.VN_CURDATE()) AND TIMESTAMPADD(DAY, - DAY(util.VN_CURDATE()),util.VN_CURDATE()) + GROUP BY clientFk, year, month + ) vol + GROUP BY clientFk; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -4934,29 +4934,29 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `carteras_add`() -BEGIN -/** - * Inserta en la tabla @bs.carteras las ventas desde el año pasado - * agrupadas por trabajador, año y mes - */ - DECLARE vYear INT DEFAULT YEAR(util.VN_CURDATE()) - 1; - - DELETE FROM bs.carteras WHERE Año >= vYear; - - CALL util.time_generate( - MAKEDATE(vYear, 1), - (SELECT MAX(fecha) FROM ventas) - ); - - INSERT INTO carteras(Año, Mes , CodigoTrabajador, Peso) - SELECT t.`year`, t.`month`, w.code, SUM(v.importe) - FROM tmp.time t - JOIN 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 - GROUP BY w.code, t.`year`, t.`month`; - - DROP TEMPORARY TABLE tmp.time; +BEGIN +/** + * Inserta en la tabla @bs.carteras las ventas desde el año pasado + * agrupadas por trabajador, año y mes + */ + DECLARE vYear INT DEFAULT YEAR(util.VN_CURDATE()) - 1; + + DELETE FROM bs.carteras WHERE Año >= vYear; + + CALL util.time_generate( + MAKEDATE(vYear, 1), + (SELECT MAX(fecha) FROM ventas) + ); + + INSERT INTO carteras(Año, Mes , CodigoTrabajador, Peso) + SELECT t.`year`, t.`month`, w.code, SUM(v.importe) + FROM tmp.time t + JOIN 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 + GROUP BY w.code, t.`year`, t.`month`; + + DROP TEMPORARY TABLE tmp.time; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -5881,82 +5881,82 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `nightTask_launchAll`() -BEGIN -/** - * Runs all nightly tasks. - */ - DECLARE vDone BOOL; - DECLARE vError VARCHAR(255); - DECLARE vErrorCode VARCHAR(255); - DECLARE vSchema VARCHAR(255); - DECLARE vProcedure VARCHAR(255); - DECLARE vLogMail VARCHAR(255); - DECLARE vNightTaskFk INT; - - DECLARE vQueue CURSOR FOR - SELECT id, `schema`, `procedure` - FROM nightTask - WHERE finished <= util.VN_CURDATE() - OR finished IS NULL - ORDER BY `order`; - - DECLARE CONTINUE HANDLER FOR NOT FOUND - SET vDone = TRUE; - - SET max_sp_recursion_depth = 3; - - SELECT logMail INTO vLogMail - FROM nightTaskConfig LIMIT 1; - - OPEN vQueue; - l: LOOP - SET vDone = FALSE; - FETCH vQueue INTO vNightTaskFk, vSchema, vProcedure; - - IF vDone THEN - LEAVE l; - END IF; - - UPDATE nightTask - SET `started` = util.VN_NOW(), - `finished` = NULL, - `error` = NULL, - `errorCode` = NULL - WHERE id = vNightTaskFk; - - SET vError = NULL; - CALL nightTask_launchTask( - vSchema, - vProcedure, - vError, - vErrorCode - ); - - IF vError IS NOT NULL THEN - IF vLogMail IS NOT NULL THEN - CALL vn.mail_insert( - vLogMail, - NULL, - CONCAT('Nightly task failed (', vSchema, '.', vProcedure, ')'), - CONCAT( - '[', vErrorCode, '] ', vError, CHAR(13, 10), -- Line break - 'See ', SCHEMA(), '.nightTask table for more info.' - ) - ); - END IF; - - UPDATE nightTask - SET `error` = vError, - `errorCode` = vErrorCode - WHERE id = vNightTaskFk; - ELSE - UPDATE nightTask - SET finished = util.VN_NOW(), - lastFinished = util.VN_NOW() - WHERE id = vNightTaskFk; - END IF; - END LOOP; - CLOSE vQueue; +BEGIN +/** + * Runs all nightly tasks. + */ + DECLARE vDone BOOL; + DECLARE vError VARCHAR(255); + DECLARE vErrorCode VARCHAR(255); + DECLARE vSchema VARCHAR(255); + DECLARE vProcedure VARCHAR(255); + DECLARE vLogMail VARCHAR(255); + DECLARE vNightTaskFk INT; + + DECLARE vQueue CURSOR FOR + SELECT id, `schema`, `procedure` + FROM nightTask + WHERE finished <= util.VN_CURDATE() + OR finished IS NULL + ORDER BY `order`; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + SET max_sp_recursion_depth = 3; + + SELECT logMail INTO vLogMail + FROM nightTaskConfig LIMIT 1; + + OPEN vQueue; + l: LOOP + SET vDone = FALSE; + FETCH vQueue INTO vNightTaskFk, vSchema, vProcedure; + + IF vDone THEN + LEAVE l; + END IF; + + UPDATE nightTask + SET `started` = util.VN_NOW(), + `finished` = NULL, + `error` = NULL, + `errorCode` = NULL + WHERE id = vNightTaskFk; + + SET vError = NULL; + CALL nightTask_launchTask( + vSchema, + vProcedure, + vError, + vErrorCode + ); + + IF vError IS NOT NULL THEN + IF vLogMail IS NOT NULL THEN + CALL vn.mail_insert( + vLogMail, + NULL, + CONCAT('Nightly task failed (', vSchema, '.', vProcedure, ')'), + CONCAT( + '[', vErrorCode, '] ', vError, CHAR(13, 10), -- Line break + 'See ', SCHEMA(), '.nightTask table for more info.' + ) + ); + END IF; + + UPDATE nightTask + SET `error` = vError, + `errorCode` = vErrorCode + WHERE id = vNightTaskFk; + ELSE + UPDATE nightTask + SET finished = util.VN_NOW(), + lastFinished = util.VN_NOW() + WHERE id = vNightTaskFk; + END IF; + END LOOP; + CLOSE vQueue; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -6336,8 +6336,8 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `salesByItemTypeDay_addLauncher`() -BEGIN - CALL bs.salesByItemTypeDay_add(util.VN_CURDATE() - INTERVAL 30 DAY, util.VN_CURDATE()); +BEGIN + CALL bs.salesByItemTypeDay_add(util.VN_CURDATE() - INTERVAL 30 DAY, util.VN_CURDATE()); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -7589,27 +7589,27 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `cache_calc_end`(IN `v_calc` INT) -BEGIN - DECLARE v_cache_name VARCHAR(255); - DECLARE v_params VARCHAR(255); - - -- Libera el bloqueo y actualiza la fecha de ultimo refresco. - - UPDATE cache_calc cc JOIN cache c ON c.id = cc.cache_id - SET - cc.last_refresh = NOW(), - cc.expires = ADDTIME(NOW(), c.lifetime), - cc.connection_id = NULL - WHERE cc.id = v_calc; - - SELECT c.name, ca.params INTO v_cache_name, v_params - FROM cache c - JOIN cache_calc ca ON c.id = ca.cache_id - WHERE ca.id = v_calc; - - IF v_cache_name IS NOT NULL THEN - DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, ''))); - END IF; +BEGIN + DECLARE v_cache_name VARCHAR(255); + DECLARE v_params VARCHAR(255); + + -- Libera el bloqueo y actualiza la fecha de ultimo refresco. + + UPDATE cache_calc cc JOIN cache c ON c.id = cc.cache_id + SET + cc.last_refresh = NOW(), + cc.expires = ADDTIME(NOW(), c.lifetime), + cc.connection_id = NULL + WHERE cc.id = v_calc; + + SELECT c.name, ca.params INTO v_cache_name, v_params + FROM cache c + JOIN cache_calc ca ON c.id = ca.cache_id + WHERE ca.id = v_calc; + + IF v_cache_name IS NOT NULL THEN + DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, ''))); + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -7627,89 +7627,89 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `cache_calc_start`(OUT `v_calc` INT, INOUT `v_refresh` INT, IN `v_cache_name` VARCHAR(50), IN `v_params` VARCHAR(100)) -proc: BEGIN - DECLARE v_valid BOOL; - DECLARE v_lock_id VARCHAR(100); - DECLARE v_cache_id INT; - DECLARE v_expires DATETIME; - DECLARE v_clean_time DATETIME; - DECLARE vLastRefresh DATETIME; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - IF v_lock_id IS NOT NULL THEN - DO RELEASE_LOCK(v_lock_id); - END IF; - - RESIGNAL; - END; - - SET v_params = IFNULL(v_params, ''); - - -- Si el servidor se ha reiniciado invalida todos los calculos. - - SELECT COUNT(*) > 0 INTO v_valid FROM cache_valid; - - IF !v_valid - THEN - DELETE FROM cache_calc; - INSERT INTO cache_valid (valid) VALUES (TRUE); - END IF; - - -- Obtiene un bloqueo exclusivo para que no haya problemas de concurrencia. - - SET v_lock_id = CONCAT_WS('/', v_cache_name, v_params); - - IF !GET_LOCK(v_lock_id, 30) - THEN - SET v_calc = NULL; - SET v_refresh = FALSE; - LEAVE proc; - END IF; - - -- Comprueba si el calculo solicitado existe y esta actualizado. - - SELECT c.id, ca.id, ca.expires, ca.last_refresh - INTO v_cache_id, v_calc, v_expires, vLastRefresh - FROM cache c - LEFT JOIN cache_calc ca - ON ca.cache_id = c.id AND ca.params = v_params COLLATE 'utf8_general_ci' - WHERE c.name = v_cache_name COLLATE 'utf8_general_ci'; - - -- Si existe una calculo valido libera el bloqueo y devuelve su identificador. - - IF !v_refresh AND NOW() < v_expires AND vLastRefresh >= CURDATE() - THEN - DO RELEASE_LOCK(v_lock_id); - SET v_refresh = FALSE; - LEAVE proc; - END IF; - - -- Si el calculo no existe le crea una entrada en la tabla de calculos. - - IF v_calc IS NULL - THEN - INSERT INTO cache_calc SET - cache_id = v_cache_id, - cacheName = v_cache_name, - params = v_params, - last_refresh = NULL, - expires = NULL, - connection_id = CONNECTION_ID(); - - SET v_calc = LAST_INSERT_ID(); - ELSE - UPDATE cache_calc - SET - last_refresh = NULL, - expires = NULL, - connection_id = CONNECTION_ID() - WHERE id = v_calc; - END IF; - - -- Si se debe recalcular mantiene el bloqueo y devuelve su identificador. - - SET v_refresh = TRUE; +proc: BEGIN + DECLARE v_valid BOOL; + DECLARE v_lock_id VARCHAR(100); + DECLARE v_cache_id INT; + DECLARE v_expires DATETIME; + DECLARE v_clean_time DATETIME; + DECLARE vLastRefresh DATETIME; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + IF v_lock_id IS NOT NULL THEN + DO RELEASE_LOCK(v_lock_id); + END IF; + + RESIGNAL; + END; + + SET v_params = IFNULL(v_params, ''); + + -- Si el servidor se ha reiniciado invalida todos los calculos. + + SELECT COUNT(*) > 0 INTO v_valid FROM cache_valid; + + IF !v_valid + THEN + DELETE FROM cache_calc; + INSERT INTO cache_valid (valid) VALUES (TRUE); + END IF; + + -- Obtiene un bloqueo exclusivo para que no haya problemas de concurrencia. + + SET v_lock_id = CONCAT_WS('/', v_cache_name, v_params); + + IF !GET_LOCK(v_lock_id, 30) + THEN + SET v_calc = NULL; + SET v_refresh = FALSE; + LEAVE proc; + END IF; + + -- Comprueba si el calculo solicitado existe y esta actualizado. + + SELECT c.id, ca.id, ca.expires, ca.last_refresh + INTO v_cache_id, v_calc, v_expires, vLastRefresh + FROM cache c + LEFT JOIN cache_calc ca + ON ca.cache_id = c.id AND ca.params = v_params COLLATE 'utf8_general_ci' + WHERE c.name = v_cache_name COLLATE 'utf8_general_ci'; + + -- Si existe una calculo valido libera el bloqueo y devuelve su identificador. + + IF !v_refresh AND NOW() < v_expires AND vLastRefresh >= CURDATE() + THEN + DO RELEASE_LOCK(v_lock_id); + SET v_refresh = FALSE; + LEAVE proc; + END IF; + + -- Si el calculo no existe le crea una entrada en la tabla de calculos. + + IF v_calc IS NULL + THEN + INSERT INTO cache_calc SET + cache_id = v_cache_id, + cacheName = v_cache_name, + params = v_params, + last_refresh = NULL, + expires = NULL, + connection_id = CONNECTION_ID(); + + SET v_calc = LAST_INSERT_ID(); + ELSE + UPDATE cache_calc + SET + last_refresh = NULL, + expires = NULL, + connection_id = CONNECTION_ID() + WHERE id = v_calc; + END IF; + + -- Si se debe recalcular mantiene el bloqueo y devuelve su identificador. + + SET v_refresh = TRUE; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -10228,524 +10228,524 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `floramondo_offerRefresh`() -proc: BEGIN - DECLARE vLanded DATETIME; - DECLARE vDone INT DEFAULT FALSE; - DECLARE vFreeId INT; - DECLARE vSupplyResponseFk INT; - DECLARE vLastInserted DATETIME; - DECLARE vIsAuctionDay BOOLEAN; - DECLARE vMaxNewItems INT DEFAULT 10000; - DECLARE vStartingTime DATETIME; - DECLARE vAalsmeerMarketPlaceID VARCHAR(13) DEFAULT '8713783439043'; - DECLARE vDayRange INT; - - DECLARE cur1 CURSOR FOR - SELECT id - FROM edi.item_free; - - DECLARE cur2 CURSOR FOR - SELECT srId - FROM itemToInsert; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - DECLARE EXIT HANDLER FOR SQLSTATE '45000' - BEGIN - ROLLBACK; - RESIGNAL; - END; - - DECLARE CONTINUE HANDLER FOR SQLEXCEPTION - BEGIN - DO RELEASE_LOCK('edi.floramondo_offerRefresh'); - SET @isTriggerDisabled = FALSE; - RESIGNAL; - END; - - IF 'test' = (SELECT environment FROM util.config) THEN - LEAVE proc; - END IF; - - IF !GET_LOCK('edi.floramondo_offerRefresh', 0) THEN - LEAVE proc; - END IF; - - SELECT dayRange INTO vDayRange - FROM offerRefreshConfig; - - IF vDayRange IS NULL THEN - CALL util.throw("Variable vDayRange not declared"); - END IF; - - SET vStartingTime = util.VN_NOW(); - - TRUNCATE edi.offerList; - - INSERT INTO edi.offerList(supplier, total) - SELECT v.name, COUNT(DISTINCT sr.ID) total - FROM edi.supplyResponse sr - JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID - WHERE sr.NumberOfUnits > 0 - AND sr.EmbalageCode != 999 - GROUP BY sr.vmpID; - - UPDATE edi.offerList o - JOIN (SELECT v.name, COUNT(*) total - FROM edi.supplyOffer sr - JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID - GROUP BY sr.vmpID) sub ON o.supplier = sub.name - SET o.`filter` = sub.total; - - -- Elimina de la lista de items libres aquellos que ya existen - DELETE itf.* - FROM edi.item_free itf - JOIN vn.item i ON i.id = itf.id; - - CREATE OR REPLACE TEMPORARY TABLE tmp - (INDEX (`Item_ArticleCode`)) - ENGINE = MEMORY - SELECT t.* - FROM ( - SELECT * - FROM edi.supplyOffer - ORDER BY (MarketPlaceID = vAalsmeerMarketPlaceID) DESC, - NumberOfUnits DESC LIMIT 10000000000000000000) t - GROUP BY t.srId; - - CREATE OR REPLACE TEMPORARY TABLE edi.offer (INDEX (`srID`), INDEX (`EmbalageCode`), - INDEX (`ef1`), INDEX (`ef2`), INDEX (`ef3`), INDEX (`ef4`),INDEX (`ef5`), INDEX (`ef6`), - INDEX (`s1Value`), INDEX (`s2Value`), INDEX (`s3Value`), INDEX (`s4Value`),INDEX (`s5Value`), INDEX (`s6Value`)) - ENGINE = MEMORY - SELECT so.*, - ev1.type_description s1Value, - ev2.type_description s2Value, - ev3.type_description s3Value, - ev4.type_description s4Value, - ev5.type_description s5Value, - ev6.type_description s6Value, - eif1.feature ef1, - eif2.feature ef2, - eif3.feature ef3, - eif4.feature ef4, - eif5.feature ef5, - eif6.feature ef6 - FROM tmp so - LEFT JOIN edi.item_feature eif1 ON eif1.item_id = so.Item_ArticleCode - AND eif1.presentation_order = 1 - AND eif1.expiry_date IS NULL - LEFT JOIN edi.item_feature eif2 ON eif2.item_id = so.Item_ArticleCode - AND eif2.presentation_order = 2 - AND eif2.expiry_date IS NULL - LEFT JOIN edi.item_feature eif3 ON eif3.item_id = so.Item_ArticleCode - AND eif3.presentation_order = 3 - AND eif3.expiry_date IS NULL - LEFT JOIN edi.item_feature eif4 ON eif4.item_id = so.Item_ArticleCode - AND eif4.presentation_order = 4 - AND eif4.expiry_date IS NULL - LEFT JOIN edi.item_feature eif5 ON eif5.item_id = so.Item_ArticleCode - AND eif5.presentation_order = 5 - AND eif5.expiry_date IS NULL - LEFT JOIN edi.item_feature eif6 ON eif6.item_id = so.Item_ArticleCode - AND eif6.presentation_order = 6 - AND eif6.expiry_date IS NULL - LEFT JOIN edi.`value` ev1 ON ev1.type_id = eif1.feature - AND so.s1 = ev1.type_value - LEFT JOIN edi.`value` ev2 ON ev2.type_id = eif2.feature - AND so.s2 = ev2.type_value - LEFT JOIN edi.`value` ev3 ON ev3.type_id = eif3.feature - AND so.s3 = ev3.type_value - LEFT JOIN edi.`value` ev4 ON ev4.type_id = eif4.feature - AND so.s4 = ev4.type_value - LEFT JOIN edi.`value` ev5 ON ev5.type_id = eif5.feature - AND so.s5 = ev5.type_value - LEFT JOIN edi.`value` ev6 ON ev6.type_id = eif6.feature - AND so.s6 = ev6.type_value - ORDER BY Price; - - DROP TEMPORARY TABLE tmp; - - DELETE o - FROM edi.offer o - LEFT JOIN vn.tag t1 ON t1.ediTypeFk = o.ef1 AND t1.overwrite = 'size' - LEFT JOIN vn.tag t2 ON t2.ediTypeFk = o.ef2 AND t2.overwrite = 'size' - LEFT JOIN vn.tag t3 ON t3.ediTypeFk = o.ef3 AND t3.overwrite = 'size' - LEFT JOIN vn.tag t4 ON t4.ediTypeFk = o.ef4 AND t4.overwrite = 'size' - LEFT JOIN vn.tag t5 ON t5.ediTypeFk = o.ef5 AND t5.overwrite = 'size' - LEFT JOIN vn.tag t6 ON t6.ediTypeFk = o.ef6 AND t6.overwrite = 'size' - JOIN vn.floramondoConfig fc ON TRUE - WHERE (t1.id IS NOT NULL AND CONVERT(s1Value, UNSIGNED) > fc.itemMaxSize) - OR (t2.id IS NOT NULL AND CONVERT(s2Value, UNSIGNED) > fc.itemMaxSize) - OR (t3.id IS NOT NULL AND CONVERT(s3Value, UNSIGNED) > fc.itemMaxSize) - OR (t4.id IS NOT NULL AND CONVERT(s4Value, UNSIGNED) > fc.itemMaxSize) - OR (t5.id IS NOT NULL AND CONVERT(s5Value, UNSIGNED) > fc.itemMaxSize) - OR (t6.id IS NOT NULL AND CONVERT(s6Value, UNSIGNED) > fc.itemMaxSize); - - START TRANSACTION; - - -- Actualizamos el campo supplyResponseFk para aquellos articulos que ya estan creados y reutilizamos - UPDATE IGNORE edi.offer o - JOIN vn.item i - ON i.name = o.product_name - AND i.subname <=> o.company_name - AND i.value5 <=> o.s1Value - AND i.value6 <=> o.s2Value - AND i.value7 <=> o.s3Value - AND i.value8 <=> o.s4Value - AND i.value9 <=> o.s5Value - AND i.value10 <=> o.s6Value - AND i.NumberOfItemsPerCask <=> o.NumberOfItemsPerCask - AND i.EmbalageCode <=> o.EmbalageCode - AND i.quality <=> o.Quality - JOIN vn.itemType it ON it.id = i.typeFk - LEFT JOIN vn.sale s ON s.itemFk = i.id - LEFT JOIN vn.ticket t ON t.id = s.ticketFk - AND t.shipped > (util.VN_CURDATE() - INTERVAL 1 WEEK) - LEFT JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk - LEFT JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID - LEFT JOIN edi.putOrder po ON po.supplyResponseID = i.supplyResponseFk - AND po.OrderTradeLineDateTime > (util.VN_CURDATE() - INTERVAL 1 WEEK) - SET i.supplyResponseFk = o.srID - WHERE (sr.ID IS NULL - OR sr.NumberOfUnits = 0 - OR di.LatestOrderDateTime < util.VN_NOW() - OR di.ID IS NULL) - AND it.isInventory - AND t.id IS NULL - AND po.id IS NULL; - - CREATE OR REPLACE TEMPORARY TABLE itemToInsert - ENGINE = MEMORY - SELECT o.*, CAST(NULL AS DECIMAL(6,0)) itemFk - FROM edi.offer o - LEFT JOIN vn.item i ON i.supplyResponseFk = o.srId - WHERE i.id IS NULL - LIMIT vMaxNewItems; - - -- Reciclado de nº de item - OPEN cur1; - OPEN cur2; - - read_loop: LOOP - - FETCH cur2 INTO vSupplyResponseFk; - FETCH cur1 INTO vFreeId; - - IF vDone THEN - LEAVE read_loop; - END IF; - - UPDATE itemToInsert - SET itemFk = vFreeId - WHERE srId = vSupplyResponseFk; - - END LOOP; - - CLOSE cur1; - CLOSE cur2; - - -- Insertamos todos los items en Articles de la oferta - INSERT INTO vn.item(id, - `name`, - longName, - subName, - expenseFk, - typeFk, - intrastatFk, - originFk, - supplyResponseFk, - numberOfItemsPerCask, - embalageCode, - quality, - isFloramondo) - SELECT iti.itemFk, - iti.product_name, - iti.product_name, - iti.company_name, - iti.expenseFk, - iti.itemTypeFk, - iti.intrastatFk, - iti.originFk, - iti.`srId`, - iti.NumberOfItemsPerCask, - iti.EmbalageCode, - iti.Quality, - TRUE - FROM itemToInsert iti; - - -- Inserta la foto de los articulos nuevos (prioridad alta) - INSERT IGNORE INTO vn.itemImageQueue(itemFk, url) - SELECT i.id, PictureReference - FROM itemToInsert ii - JOIN vn.item i ON i.supplyResponseFk = ii.srId - WHERE PictureReference IS NOT NULL - AND i.image IS NULL; - - INSERT INTO edi.`log`(tableName, fieldName,fieldValue) - SELECT 'itemImageQueue','NumImagenesPtes', COUNT(*) - FROM vn.itemImageQueue - WHERE attempts = 0; - - -- Inserta si se añadiesen tags nuevos - INSERT IGNORE INTO vn.tag (name, ediTypeFk) - SELECT description, type_id FROM edi.type; - - -- Desabilita el trigger para recalcular los tags al final - SET @isTriggerDisabled = TRUE; - - -- Inserta los tags sólo en los articulos nuevos - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , ii.product_name, 1 - FROM itemToInsert ii - JOIN vn.tag t ON t.`name` = 'Producto' - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT ii.product_name IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , ii.Quality, 3 - FROM itemToInsert ii - JOIN vn.tag t ON t.`name` = 'Calidad' - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT ii.Quality IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , ii.company_name, 4 - FROM itemToInsert ii - JOIN vn.tag t ON t.`name` = 'Productor' - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT ii.company_name IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s1Value, 5 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef1 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s1Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s2Value, 6 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef2 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s2Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s3Value, 7 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef3 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s3Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s4Value, 8 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef4 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s4Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s5Value, 9 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef5 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s5Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s6Value, 10 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef6 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s6Value IS NULL; - - INSERT IGNORE INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id, IFNULL(ink.name, ik.color), 11 - FROM itemToInsert ii - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - JOIN vn.tag t ON t.`name` = 'Color' - LEFT JOIN edi.feature f ON f.item_id = ii.Item_ArticleCode - LEFT JOIN edi.`type` tp ON tp.type_id = f.feature_type_id - AND tp.`description` = 'Hoofdkleur 1' - LEFT JOIN vn.ink ON ink.dutchCode = f.feature_value - LEFT JOIN vn.itemInk ik ON ik.longName = i.longName - WHERE ink.name IS NOT NULL - OR ik.color IS NOT NULL; - - CREATE OR REPLACE TABLE tmp.item - (PRIMARY KEY (id)) - SELECT i.id FROM vn.item i - JOIN itemToInsert ii ON i.supplyResponseFk = ii.`srId`; - - CALL vn.item_refreshTags(); - - DROP TABLE tmp.item; - - SELECT MIN(LatestDeliveryDateTime) INTO vLanded - FROM edi.supplyResponse sr - JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID - JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID - JOIN vn.floramondoConfig fc - WHERE mp.isLatestOrderDateTimeRelevant - AND di.LatestOrderDateTime > IF( - fc.MaxLatestOrderHour > HOUR(util.VN_NOW()), - util.VN_CURDATE(), - util.VN_CURDATE() + INTERVAL 1 DAY); - - UPDATE vn.floramondoConfig - SET nextLanded = vLanded - WHERE vLanded IS NOT NULL; - - -- Elimina la oferta obsoleta - UPDATE vn.buy b - JOIN vn.entry e ON e.id = b.entryFk - JOIN vn.travel tr ON tr.id = e.travelFk - JOIN vn.agencyMode am ON am.id = tr.agencyModeFk - JOIN vn.item i ON i.id = b.itemFk - LEFT JOIN edi.supplyResponse sr ON i.supplyResponseFk = sr.ID - LEFT JOIN edi.deliveryInformation di ON di.ID = b.deliveryFk - SET b.quantity = 0 - WHERE (IFNULL(di.LatestOrderDateTime,util.VN_NOW()) <= util.VN_NOW() - OR i.supplyResponseFk IS NULL - OR sr.NumberOfUnits = 0) - AND am.name = 'LOGIFLORA' - AND e.isRaid; - - -- Localiza las entradas de cada almacen - UPDATE edi.warehouseFloramondo - SET entryFk = vn.entry_getForLogiflora(vLanded + INTERVAL travellingDays DAY, warehouseFk); - - IF vLanded IS NOT NULL THEN - -- Actualiza la oferta existente - UPDATE vn.buy b - JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk - JOIN vn.item i ON i.id = b.itemFk - JOIN edi.offer o ON i.supplyResponseFk = o.`srId` - SET b.quantity = o.NumberOfUnits * o.NumberOfItemsPerCask, - b.buyingValue = o.price - WHERE (b.quantity <> o.NumberOfUnits * o.NumberOfItemsPerCask - OR b.buyingValue <> o.price); - - -- Inserta el resto - SET vLastInserted := util.VN_NOW(); - - -- Inserta la oferta - INSERT INTO vn.buy ( - entryFk, - itemFk, - quantity, - buyingValue, - stickers, - packing, - `grouping`, - groupingMode, - packagingFk, - deliveryFk) - SELECT wf.entryFk, - i.id, - o.NumberOfUnits * o.NumberOfItemsPerCask quantity, - o.Price, - o.NumberOfUnits etiquetas, - o.NumberOfItemsPerCask packing, - GREATEST(1, IFNULL(o.MinimumQuantity,0)) * o.NumberOfItemsPerCask `grouping`, - 'packing', - o.embalageCode, - o.diId - FROM edi.offer o - JOIN vn.item i ON i.supplyResponseFk = o.srId - JOIN edi.warehouseFloramondo wf - JOIN vn.packaging p ON p.id - LIKE o.embalageCode - LEFT JOIN vn.buy b ON b.itemFk = i.id - AND b.entryFk = wf.entryFk - WHERE b.id IS NULL; -- Quitar esta linea y mirar de crear los packages a tiempo REAL - - INSERT INTO vn.itemCost( - itemFk, - warehouseFk, - cm3, - cm3delivery) - SELECT b.itemFk, - wf.warehouseFk, - @cm3 := vn.buy_getUnitVolume(b.id), - IFNULL((vc.standardFlowerBox * 1000) / i.packingOut, @cm3) - FROM warehouseFloramondo wf - JOIN vn.volumeConfig vc - JOIN vn.buy b ON b.entryFk = wf.entryFk - JOIN vn.item i ON i.id = b.itemFk - LEFT JOIN vn.itemCost ic ON ic.itemFk = b.itemFk - AND ic.warehouseFk = wf.warehouseFk - WHERE (ic.cm3 IS NULL OR ic.cm3 = 0) - ON DUPLICATE KEY UPDATE cm3 = @cm3, cm3delivery = IFNULL((vc.standardFlowerBox * 1000) / i.packingOut, @cm3); - - CREATE OR REPLACE TEMPORARY TABLE tmp.buyRecalc - SELECT b.id - FROM vn.buy b - JOIN warehouseFloramondo wf ON wf.entryFk = b.entryFk - WHERE b.created >= vLastInserted; - - CALL vn.buy_recalcPrices(); - - UPDATE edi.offerList o - JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total - FROM vn.buy b - JOIN vn.item i ON i.id = b.itemFk - JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk - JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID - JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk - JOIN vn.warehouse w ON w.id = wf.warehouseFk - WHERE w.name = 'VNH' - AND b.quantity > 0 - GROUP BY sr.vmpID) sub ON o.supplier = sub.name - SET o.vnh = sub.total; - - UPDATE edi.offerList o - JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total - FROM vn.buy b - JOIN vn.item i ON i.id = b.itemFk - JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk - JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID - JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk - JOIN vn.warehouse w ON w.id = wf.warehouseFk - WHERE w.name = 'ALGEMESI' - AND b.quantity > 0 - GROUP BY sr.vmpID) sub ON o.supplier = sub.name - SET o.algemesi = sub.total; - END IF; - - DROP TEMPORARY TABLE - edi.offer, - itemToInsert; - - SET @isTriggerDisabled = FALSE; - - COMMIT; - - -- Esto habria que pasarlo a procesos programados o trabajar con tags y dejar las familias - UPDATE vn.item i - SET typeFk = 121 - WHERE i.longName LIKE 'Rosa Garden %' - AND typeFk = 17; - - UPDATE vn.item i - SET typeFk = 156 - WHERE i.longName LIKE 'Rosa ec %' - AND typeFk = 17; - - -- Refresca las fotos de los items existentes que mostramos (prioridad baja) - INSERT IGNORE INTO vn.itemImageQueue(itemFk, url, priority) - SELECT i.id, sr.PictureReference, 100 - FROM edi.supplyResponse sr - JOIN vn.item i ON i.supplyResponseFk = sr.ID - JOIN edi.supplyOffer so ON so.srId = sr.ID - JOIN hedera.image i2 ON i2.name = i.image - AND i2.collectionFk = 'catalog' - WHERE i2.updated <= (UNIX_TIMESTAMP(util.VN_NOW()) - vDayRange) - AND sr.NumberOfUnits; - - INSERT INTO edi.`log` - SET tableName = 'floramondo_offerRefresh', - fieldName = 'Tiempo de proceso', - fieldValue = TIMEDIFF(util.VN_NOW(), vStartingTime); - - DO RELEASE_LOCK('edi.floramondo_offerRefresh'); +proc: BEGIN + DECLARE vLanded DATETIME; + DECLARE vDone INT DEFAULT FALSE; + DECLARE vFreeId INT; + DECLARE vSupplyResponseFk INT; + DECLARE vLastInserted DATETIME; + DECLARE vIsAuctionDay BOOLEAN; + DECLARE vMaxNewItems INT DEFAULT 10000; + DECLARE vStartingTime DATETIME; + DECLARE vAalsmeerMarketPlaceID VARCHAR(13) DEFAULT '8713783439043'; + DECLARE vDayRange INT; + + DECLARE cur1 CURSOR FOR + SELECT id + FROM edi.item_free; + + DECLARE cur2 CURSOR FOR + SELECT srId + FROM itemToInsert; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + DECLARE EXIT HANDLER FOR SQLSTATE '45000' + BEGIN + ROLLBACK; + RESIGNAL; + END; + + DECLARE CONTINUE HANDLER FOR SQLEXCEPTION + BEGIN + DO RELEASE_LOCK('edi.floramondo_offerRefresh'); + SET @isTriggerDisabled = FALSE; + RESIGNAL; + END; + + IF 'test' = (SELECT environment FROM util.config) THEN + LEAVE proc; + END IF; + + IF !GET_LOCK('edi.floramondo_offerRefresh', 0) THEN + LEAVE proc; + END IF; + + SELECT dayRange INTO vDayRange + FROM offerRefreshConfig; + + IF vDayRange IS NULL THEN + CALL util.throw("Variable vDayRange not declared"); + END IF; + + SET vStartingTime = util.VN_NOW(); + + TRUNCATE edi.offerList; + + INSERT INTO edi.offerList(supplier, total) + SELECT v.name, COUNT(DISTINCT sr.ID) total + FROM edi.supplyResponse sr + JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID + WHERE sr.NumberOfUnits > 0 + AND sr.EmbalageCode != 999 + GROUP BY sr.vmpID; + + UPDATE edi.offerList o + JOIN (SELECT v.name, COUNT(*) total + FROM edi.supplyOffer sr + JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID + GROUP BY sr.vmpID) sub ON o.supplier = sub.name + SET o.`filter` = sub.total; + + -- Elimina de la lista de items libres aquellos que ya existen + DELETE itf.* + FROM edi.item_free itf + JOIN vn.item i ON i.id = itf.id; + + CREATE OR REPLACE TEMPORARY TABLE tmp + (INDEX (`Item_ArticleCode`)) + ENGINE = MEMORY + SELECT t.* + FROM ( + SELECT * + FROM edi.supplyOffer + ORDER BY (MarketPlaceID = vAalsmeerMarketPlaceID) DESC, + NumberOfUnits DESC LIMIT 10000000000000000000) t + GROUP BY t.srId; + + CREATE OR REPLACE TEMPORARY TABLE edi.offer (INDEX (`srID`), INDEX (`EmbalageCode`), + INDEX (`ef1`), INDEX (`ef2`), INDEX (`ef3`), INDEX (`ef4`),INDEX (`ef5`), INDEX (`ef6`), + INDEX (`s1Value`), INDEX (`s2Value`), INDEX (`s3Value`), INDEX (`s4Value`),INDEX (`s5Value`), INDEX (`s6Value`)) + ENGINE = MEMORY + SELECT so.*, + ev1.type_description s1Value, + ev2.type_description s2Value, + ev3.type_description s3Value, + ev4.type_description s4Value, + ev5.type_description s5Value, + ev6.type_description s6Value, + eif1.feature ef1, + eif2.feature ef2, + eif3.feature ef3, + eif4.feature ef4, + eif5.feature ef5, + eif6.feature ef6 + FROM tmp so + LEFT JOIN edi.item_feature eif1 ON eif1.item_id = so.Item_ArticleCode + AND eif1.presentation_order = 1 + AND eif1.expiry_date IS NULL + LEFT JOIN edi.item_feature eif2 ON eif2.item_id = so.Item_ArticleCode + AND eif2.presentation_order = 2 + AND eif2.expiry_date IS NULL + LEFT JOIN edi.item_feature eif3 ON eif3.item_id = so.Item_ArticleCode + AND eif3.presentation_order = 3 + AND eif3.expiry_date IS NULL + LEFT JOIN edi.item_feature eif4 ON eif4.item_id = so.Item_ArticleCode + AND eif4.presentation_order = 4 + AND eif4.expiry_date IS NULL + LEFT JOIN edi.item_feature eif5 ON eif5.item_id = so.Item_ArticleCode + AND eif5.presentation_order = 5 + AND eif5.expiry_date IS NULL + LEFT JOIN edi.item_feature eif6 ON eif6.item_id = so.Item_ArticleCode + AND eif6.presentation_order = 6 + AND eif6.expiry_date IS NULL + LEFT JOIN edi.`value` ev1 ON ev1.type_id = eif1.feature + AND so.s1 = ev1.type_value + LEFT JOIN edi.`value` ev2 ON ev2.type_id = eif2.feature + AND so.s2 = ev2.type_value + LEFT JOIN edi.`value` ev3 ON ev3.type_id = eif3.feature + AND so.s3 = ev3.type_value + LEFT JOIN edi.`value` ev4 ON ev4.type_id = eif4.feature + AND so.s4 = ev4.type_value + LEFT JOIN edi.`value` ev5 ON ev5.type_id = eif5.feature + AND so.s5 = ev5.type_value + LEFT JOIN edi.`value` ev6 ON ev6.type_id = eif6.feature + AND so.s6 = ev6.type_value + ORDER BY Price; + + DROP TEMPORARY TABLE tmp; + + DELETE o + FROM edi.offer o + LEFT JOIN vn.tag t1 ON t1.ediTypeFk = o.ef1 AND t1.overwrite = 'size' + LEFT JOIN vn.tag t2 ON t2.ediTypeFk = o.ef2 AND t2.overwrite = 'size' + LEFT JOIN vn.tag t3 ON t3.ediTypeFk = o.ef3 AND t3.overwrite = 'size' + LEFT JOIN vn.tag t4 ON t4.ediTypeFk = o.ef4 AND t4.overwrite = 'size' + LEFT JOIN vn.tag t5 ON t5.ediTypeFk = o.ef5 AND t5.overwrite = 'size' + LEFT JOIN vn.tag t6 ON t6.ediTypeFk = o.ef6 AND t6.overwrite = 'size' + JOIN vn.floramondoConfig fc ON TRUE + WHERE (t1.id IS NOT NULL AND CONVERT(s1Value, UNSIGNED) > fc.itemMaxSize) + OR (t2.id IS NOT NULL AND CONVERT(s2Value, UNSIGNED) > fc.itemMaxSize) + OR (t3.id IS NOT NULL AND CONVERT(s3Value, UNSIGNED) > fc.itemMaxSize) + OR (t4.id IS NOT NULL AND CONVERT(s4Value, UNSIGNED) > fc.itemMaxSize) + OR (t5.id IS NOT NULL AND CONVERT(s5Value, UNSIGNED) > fc.itemMaxSize) + OR (t6.id IS NOT NULL AND CONVERT(s6Value, UNSIGNED) > fc.itemMaxSize); + + START TRANSACTION; + + -- Actualizamos el campo supplyResponseFk para aquellos articulos que ya estan creados y reutilizamos + UPDATE IGNORE edi.offer o + JOIN vn.item i + ON i.name = o.product_name + AND i.subname <=> o.company_name + AND i.value5 <=> o.s1Value + AND i.value6 <=> o.s2Value + AND i.value7 <=> o.s3Value + AND i.value8 <=> o.s4Value + AND i.value9 <=> o.s5Value + AND i.value10 <=> o.s6Value + AND i.NumberOfItemsPerCask <=> o.NumberOfItemsPerCask + AND i.EmbalageCode <=> o.EmbalageCode + AND i.quality <=> o.Quality + JOIN vn.itemType it ON it.id = i.typeFk + LEFT JOIN vn.sale s ON s.itemFk = i.id + LEFT JOIN vn.ticket t ON t.id = s.ticketFk + AND t.shipped > (util.VN_CURDATE() - INTERVAL 1 WEEK) + LEFT JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk + LEFT JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID + LEFT JOIN edi.putOrder po ON po.supplyResponseID = i.supplyResponseFk + AND po.OrderTradeLineDateTime > (util.VN_CURDATE() - INTERVAL 1 WEEK) + SET i.supplyResponseFk = o.srID + WHERE (sr.ID IS NULL + OR sr.NumberOfUnits = 0 + OR di.LatestOrderDateTime < util.VN_NOW() + OR di.ID IS NULL) + AND it.isInventory + AND t.id IS NULL + AND po.id IS NULL; + + CREATE OR REPLACE TEMPORARY TABLE itemToInsert + ENGINE = MEMORY + SELECT o.*, CAST(NULL AS DECIMAL(6,0)) itemFk + FROM edi.offer o + LEFT JOIN vn.item i ON i.supplyResponseFk = o.srId + WHERE i.id IS NULL + LIMIT vMaxNewItems; + + -- Reciclado de nº de item + OPEN cur1; + OPEN cur2; + + read_loop: LOOP + + FETCH cur2 INTO vSupplyResponseFk; + FETCH cur1 INTO vFreeId; + + IF vDone THEN + LEAVE read_loop; + END IF; + + UPDATE itemToInsert + SET itemFk = vFreeId + WHERE srId = vSupplyResponseFk; + + END LOOP; + + CLOSE cur1; + CLOSE cur2; + + -- Insertamos todos los items en Articles de la oferta + INSERT INTO vn.item(id, + `name`, + longName, + subName, + expenseFk, + typeFk, + intrastatFk, + originFk, + supplyResponseFk, + numberOfItemsPerCask, + embalageCode, + quality, + isFloramondo) + SELECT iti.itemFk, + iti.product_name, + iti.product_name, + iti.company_name, + iti.expenseFk, + iti.itemTypeFk, + iti.intrastatFk, + iti.originFk, + iti.`srId`, + iti.NumberOfItemsPerCask, + iti.EmbalageCode, + iti.Quality, + TRUE + FROM itemToInsert iti; + + -- Inserta la foto de los articulos nuevos (prioridad alta) + INSERT IGNORE INTO vn.itemImageQueue(itemFk, url) + SELECT i.id, PictureReference + FROM itemToInsert ii + JOIN vn.item i ON i.supplyResponseFk = ii.srId + WHERE PictureReference IS NOT NULL + AND i.image IS NULL; + + INSERT INTO edi.`log`(tableName, fieldName,fieldValue) + SELECT 'itemImageQueue','NumImagenesPtes', COUNT(*) + FROM vn.itemImageQueue + WHERE attempts = 0; + + -- Inserta si se añadiesen tags nuevos + INSERT IGNORE INTO vn.tag (name, ediTypeFk) + SELECT description, type_id FROM edi.type; + + -- Desabilita el trigger para recalcular los tags al final + SET @isTriggerDisabled = TRUE; + + -- Inserta los tags sólo en los articulos nuevos + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , ii.product_name, 1 + FROM itemToInsert ii + JOIN vn.tag t ON t.`name` = 'Producto' + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT ii.product_name IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , ii.Quality, 3 + FROM itemToInsert ii + JOIN vn.tag t ON t.`name` = 'Calidad' + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT ii.Quality IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , ii.company_name, 4 + FROM itemToInsert ii + JOIN vn.tag t ON t.`name` = 'Productor' + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT ii.company_name IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s1Value, 5 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef1 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s1Value IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s2Value, 6 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef2 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s2Value IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s3Value, 7 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef3 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s3Value IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s4Value, 8 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef4 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s4Value IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s5Value, 9 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef5 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s5Value IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s6Value, 10 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef6 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s6Value IS NULL; + + INSERT IGNORE INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id, IFNULL(ink.name, ik.color), 11 + FROM itemToInsert ii + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + JOIN vn.tag t ON t.`name` = 'Color' + LEFT JOIN edi.feature f ON f.item_id = ii.Item_ArticleCode + LEFT JOIN edi.`type` tp ON tp.type_id = f.feature_type_id + AND tp.`description` = 'Hoofdkleur 1' + LEFT JOIN vn.ink ON ink.dutchCode = f.feature_value + LEFT JOIN vn.itemInk ik ON ik.longName = i.longName + WHERE ink.name IS NOT NULL + OR ik.color IS NOT NULL; + + CREATE OR REPLACE TABLE tmp.item + (PRIMARY KEY (id)) + SELECT i.id FROM vn.item i + JOIN itemToInsert ii ON i.supplyResponseFk = ii.`srId`; + + CALL vn.item_refreshTags(); + + DROP TABLE tmp.item; + + SELECT MIN(LatestDeliveryDateTime) INTO vLanded + FROM edi.supplyResponse sr + JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID + JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID + JOIN vn.floramondoConfig fc + WHERE mp.isLatestOrderDateTimeRelevant + AND di.LatestOrderDateTime > IF( + fc.MaxLatestOrderHour > HOUR(util.VN_NOW()), + util.VN_CURDATE(), + util.VN_CURDATE() + INTERVAL 1 DAY); + + UPDATE vn.floramondoConfig + SET nextLanded = vLanded + WHERE vLanded IS NOT NULL; + + -- Elimina la oferta obsoleta + UPDATE vn.buy b + JOIN vn.entry e ON e.id = b.entryFk + JOIN vn.travel tr ON tr.id = e.travelFk + JOIN vn.agencyMode am ON am.id = tr.agencyModeFk + JOIN vn.item i ON i.id = b.itemFk + LEFT JOIN edi.supplyResponse sr ON i.supplyResponseFk = sr.ID + LEFT JOIN edi.deliveryInformation di ON di.ID = b.deliveryFk + SET b.quantity = 0 + WHERE (IFNULL(di.LatestOrderDateTime,util.VN_NOW()) <= util.VN_NOW() + OR i.supplyResponseFk IS NULL + OR sr.NumberOfUnits = 0) + AND am.name = 'LOGIFLORA' + AND e.isRaid; + + -- Localiza las entradas de cada almacen + UPDATE edi.warehouseFloramondo + SET entryFk = vn.entry_getForLogiflora(vLanded + INTERVAL travellingDays DAY, warehouseFk); + + IF vLanded IS NOT NULL THEN + -- Actualiza la oferta existente + UPDATE vn.buy b + JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk + JOIN vn.item i ON i.id = b.itemFk + JOIN edi.offer o ON i.supplyResponseFk = o.`srId` + SET b.quantity = o.NumberOfUnits * o.NumberOfItemsPerCask, + b.buyingValue = o.price + WHERE (b.quantity <> o.NumberOfUnits * o.NumberOfItemsPerCask + OR b.buyingValue <> o.price); + + -- Inserta el resto + SET vLastInserted := util.VN_NOW(); + + -- Inserta la oferta + INSERT INTO vn.buy ( + entryFk, + itemFk, + quantity, + buyingValue, + stickers, + packing, + `grouping`, + groupingMode, + packagingFk, + deliveryFk) + SELECT wf.entryFk, + i.id, + o.NumberOfUnits * o.NumberOfItemsPerCask quantity, + o.Price, + o.NumberOfUnits etiquetas, + o.NumberOfItemsPerCask packing, + GREATEST(1, IFNULL(o.MinimumQuantity,0)) * o.NumberOfItemsPerCask `grouping`, + 'packing', + o.embalageCode, + o.diId + FROM edi.offer o + JOIN vn.item i ON i.supplyResponseFk = o.srId + JOIN edi.warehouseFloramondo wf + JOIN vn.packaging p ON p.id + LIKE o.embalageCode + LEFT JOIN vn.buy b ON b.itemFk = i.id + AND b.entryFk = wf.entryFk + WHERE b.id IS NULL; -- Quitar esta linea y mirar de crear los packages a tiempo REAL + + INSERT INTO vn.itemCost( + itemFk, + warehouseFk, + cm3, + cm3delivery) + SELECT b.itemFk, + wf.warehouseFk, + @cm3 := vn.buy_getUnitVolume(b.id), + IFNULL((vc.standardFlowerBox * 1000) / i.packingOut, @cm3) + FROM warehouseFloramondo wf + JOIN vn.volumeConfig vc + JOIN vn.buy b ON b.entryFk = wf.entryFk + JOIN vn.item i ON i.id = b.itemFk + LEFT JOIN vn.itemCost ic ON ic.itemFk = b.itemFk + AND ic.warehouseFk = wf.warehouseFk + WHERE (ic.cm3 IS NULL OR ic.cm3 = 0) + ON DUPLICATE KEY UPDATE cm3 = @cm3, cm3delivery = IFNULL((vc.standardFlowerBox * 1000) / i.packingOut, @cm3); + + CREATE OR REPLACE TEMPORARY TABLE tmp.buyRecalc + SELECT b.id + FROM vn.buy b + JOIN warehouseFloramondo wf ON wf.entryFk = b.entryFk + WHERE b.created >= vLastInserted; + + CALL vn.buy_recalcPrices(); + + UPDATE edi.offerList o + JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total + FROM vn.buy b + JOIN vn.item i ON i.id = b.itemFk + JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk + JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID + JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk + JOIN vn.warehouse w ON w.id = wf.warehouseFk + WHERE w.name = 'VNH' + AND b.quantity > 0 + GROUP BY sr.vmpID) sub ON o.supplier = sub.name + SET o.vnh = sub.total; + + UPDATE edi.offerList o + JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total + FROM vn.buy b + JOIN vn.item i ON i.id = b.itemFk + JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk + JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID + JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk + JOIN vn.warehouse w ON w.id = wf.warehouseFk + WHERE w.name = 'ALGEMESI' + AND b.quantity > 0 + GROUP BY sr.vmpID) sub ON o.supplier = sub.name + SET o.algemesi = sub.total; + END IF; + + DROP TEMPORARY TABLE + edi.offer, + itemToInsert; + + SET @isTriggerDisabled = FALSE; + + COMMIT; + + -- Esto habria que pasarlo a procesos programados o trabajar con tags y dejar las familias + UPDATE vn.item i + SET typeFk = 121 + WHERE i.longName LIKE 'Rosa Garden %' + AND typeFk = 17; + + UPDATE vn.item i + SET typeFk = 156 + WHERE i.longName LIKE 'Rosa ec %' + AND typeFk = 17; + + -- Refresca las fotos de los items existentes que mostramos (prioridad baja) + INSERT IGNORE INTO vn.itemImageQueue(itemFk, url, priority) + SELECT i.id, sr.PictureReference, 100 + FROM edi.supplyResponse sr + JOIN vn.item i ON i.supplyResponseFk = sr.ID + JOIN edi.supplyOffer so ON so.srId = sr.ID + JOIN hedera.image i2 ON i2.name = i.image + AND i2.collectionFk = 'catalog' + WHERE i2.updated <= (UNIX_TIMESTAMP(util.VN_NOW()) - vDayRange) + AND sr.NumberOfUnits; + + INSERT INTO edi.`log` + SET tableName = 'floramondo_offerRefresh', + fieldName = 'Tiempo de proceso', + fieldValue = TIMEDIFF(util.VN_NOW(), vStartingTime); + + DO RELEASE_LOCK('edi.floramondo_offerRefresh'); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -11324,28 +11324,28 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `contact_request`( - vName VARCHAR(100), - vPhone VARCHAR(15), - vEmail VARCHAR(100), +CREATE DEFINER=`root`@`localhost` PROCEDURE `contact_request`( + vName VARCHAR(100), + vPhone VARCHAR(15), + vEmail VARCHAR(100), vMessage TEXT) READS SQL DATA -BEGIN -/** - * Set actions for contact request - * - * @param vName Name - * @param vPhone Phone number - * @param vEmail e-mail - * @param vMessage text of the message - */ - - CALL vn.mail_insert( - 'floranet@verdnatura.es', - vEmail, - 'Contact request', - CONCAT('Phone: ',vPhone, ' Message: ', vMessage) - ); +BEGIN +/** + * Set actions for contact request + * + * @param vName Name + * @param vPhone Phone number + * @param vEmail e-mail + * @param vMessage text of the message + */ + + CALL vn.mail_insert( + 'floranet@verdnatura.es', + vEmail, + 'Contact request', + CONCAT('Phone: ',vPhone, ' Message: ', vMessage) + ); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -11364,27 +11364,27 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `deliveryDate_get`(vPostalCode VARCHAR(15)) READS SQL DATA -BEGIN -/** - * Returns available dates for this postalCode, in the next seven days. - * - * @param vPostalCode Delivery address postal code - */ - DECLARE vCurrentDayOfWeek INT; - - SET vCurrentDayOfWeek = DAYOFWEEK(NOW()); - - SELECT DISTINCT nextDay - FROM ( - SELECT CURDATE() + INTERVAL IF( - apc.dayOfWeek >= vCurrentDayOfWeek, - apc.dayOfWeek - vCurrentDayOfWeek, - 7 - apc.dayOfWeek - ) DAY nextDay, - NOW() + INTERVAL apc.hoursInAdvance HOUR minDeliveryTime - FROM addressPostCode apc - WHERE apc.postCode = vPostalCode - HAVING nextDay > minDeliveryTime) sub; +BEGIN +/** + * Returns available dates for this postalCode, in the next seven days. + * + * @param vPostalCode Delivery address postal code + */ + DECLARE vCurrentDayOfWeek INT; + + SET vCurrentDayOfWeek = DAYOFWEEK(NOW()); + + SELECT DISTINCT nextDay + FROM ( + SELECT CURDATE() + INTERVAL IF( + apc.dayOfWeek >= vCurrentDayOfWeek, + apc.dayOfWeek - vCurrentDayOfWeek, + 7 - apc.dayOfWeek + ) DAY nextDay, + NOW() + INTERVAL apc.hoursInAdvance HOUR minDeliveryTime + FROM addressPostCode apc + WHERE apc.postCode = vPostalCode + HAVING nextDay > minDeliveryTime) sub; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -41995,9 +41995,9 @@ 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 `itemImageQueue_check` ON SCHEDULE EVERY 1 HOUR STARTS '2023-07-28 00:00:00' ON COMPLETION PRESERVE ENABLE DO BEGIN - DELETE FROM itemImageQueue - WHERE attempts >= (SELECT downloadMaxAttempts FROM itemConfig); +/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `itemImageQueue_check` ON SCHEDULE EVERY 1 HOUR STARTS '2023-07-28 00:00:00' ON COMPLETION PRESERVE ENABLE DO BEGIN + DELETE FROM itemImageQueue + WHERE attempts >= (SELECT downloadMaxAttempts FROM itemConfig); END */ ;; /*!50003 SET time_zone = @saved_time_zone */ ;; /*!50003 SET sql_mode = @saved_sql_mode */ ;; @@ -42689,37 +42689,37 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `client_getDebt`(`vClient` INT, `vDate` DATE) RETURNS decimal(10,2) READS SQL DATA -BEGIN -/** - * Returns the risk of a customer. - * - * @param vClient client id - * @param vDate date to check the risk - * @return Client risk - */ - 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; - - CREATE OR REPLACE TEMPORARY TABLE tmp.clientGetDebt (clientFk INT); - INSERT INTO tmp.clientGetDebt SET clientFk = vClient; - - CALL vn.client_getDebt(vDate); - - SELECT risk INTO vDebt FROM tmp.risk; - - DROP TEMPORARY TABLE - tmp.clientGetDebt, - tmp.risk; - - RETURN vDebt; +BEGIN +/** + * Returns the risk of a customer. + * + * @param vClient client id + * @param vDate date to check the risk + * @return Client risk + */ + 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; + + CREATE OR REPLACE TEMPORARY TABLE tmp.clientGetDebt (clientFk INT); + INSERT INTO tmp.clientGetDebt SET clientFk = vClient; + + CALL vn.client_getDebt(vDate); + + SELECT risk INTO vDebt FROM tmp.risk; + + DROP TEMPORARY TABLE + tmp.clientGetDebt, + tmp.risk; + + RETURN vDebt; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -43744,8 +43744,8 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `getInventoryDate`() RETURNS date DETERMINISTIC -BEGIN - RETURN (SELECT inventoried FROM config LIMIT 1); +BEGIN + RETURN (SELECT inventoried FROM config LIMIT 1); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -51378,82 +51378,82 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_assign`( - vUserFk INT, - OUT vCollectionFk INT +CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_assign`( + vUserFk INT, + OUT vCollectionFk INT ) -BEGIN -/** - * Comprueba si existen colecciones libres que se ajustan - * al perfil del usuario y le asigna la más antigua. - * Añade un registro al semillero de colecciones. - * - * @param vUserFk Id de usuario - * @param vCollectionFk Id de colección - */ - DECLARE vHasTooMuchCollections BOOL; - - -- Si hay colecciones sin terminar, sale del proceso - CALL collection_get(vUserFk); - - SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0 - INTO vHasTooMuchCollections - FROM productionConfig pc - LEFT JOIN tCollection ON TRUE; - - DROP TEMPORARY TABLE tCollection; - - IF vHasTooMuchCollections THEN - CALL util.throw('Hay colecciones pendientes'); - END IF; - - -- Se eliminan las colecciones sin asignar que estan obsoletas - INSERT INTO ticketTracking(stateFk, ticketFk) - SELECT s.id, tc.ticketFk - FROM `collection` c - JOIN ticketCollection tc ON tc.collectionFk = c.id - JOIN `state` s ON s.code = 'PRINTED_AUTO' - JOIN productionConfig pc - WHERE c.workerFk IS NULL - AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; - - DELETE c.* - FROM `collection` c - JOIN productionConfig pc - WHERE c.workerFk IS NULL - AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; - - -- Se añade registro al semillero - INSERT INTO collectionHotbed(userFk) - VALUES(vUserFk); - - -- Comprueba si hay colecciones disponibles que se ajustan a su configuracion - SELECT MIN(c.id) INTO vCollectionFk - FROM `collection` c - JOIN operator o - ON (o.itemPackingTypeFk = c.itemPackingTypeFk OR c.itemPackingTypeFk IS NULL) - AND o.numberOfWagons = c.wagons - AND o.trainFk = c.trainFk - AND o.warehouseFk = c.warehouseFk - AND c.workerFk IS NULL - AND (c.saleTotalCount <= o.linesLimit OR o.linesLimit IS NULL) - JOIN ( - SELECT tc.collectionFk, SUM(sv.volume) volume - FROM ticketCollection tc - JOIN saleVolume sv ON sv.ticketFk = tc.ticketFk - WHERE sv.shipped >= util.VN_CURDATE() - GROUP BY tc.collectionFk - ) sub ON sub.collectionFk = c.id - AND (volume <= o.volumeLimit OR o.volumeLimit IS NULL) - WHERE o.workerFk = vUserFk; - - IF vCollectionFk IS NULL THEN - CALL collection_new(vUserFk, vCollectionFk); - END IF; - - UPDATE `collection` - SET workerFk = vUserFk - WHERE id = vCollectionFk; +BEGIN +/** + * Comprueba si existen colecciones libres que se ajustan + * al perfil del usuario y le asigna la más antigua. + * Añade un registro al semillero de colecciones. + * + * @param vUserFk Id de usuario + * @param vCollectionFk Id de colección + */ + DECLARE vHasTooMuchCollections BOOL; + + -- Si hay colecciones sin terminar, sale del proceso + CALL collection_get(vUserFk); + + SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0 + INTO vHasTooMuchCollections + FROM productionConfig pc + LEFT JOIN tmp.collection ON TRUE; + + DROP TEMPORARY TABLE tmp.collection; + + IF vHasTooMuchCollections THEN + CALL util.throw('Hay colecciones pendientes'); + END IF; + + -- Se eliminan las colecciones sin asignar que estan obsoletas + INSERT INTO ticketTracking(stateFk, ticketFk) + SELECT s.id, tc.ticketFk + FROM `collection` c + JOIN ticketCollection tc ON tc.collectionFk = c.id + JOIN `state` s ON s.code = 'PRINTED_AUTO' + JOIN productionConfig pc + WHERE c.workerFk IS NULL + AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; + + DELETE c.* + FROM `collection` c + JOIN productionConfig pc + WHERE c.workerFk IS NULL + AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; + + -- Se añade registro al semillero + INSERT INTO collectionHotbed(userFk) + VALUES(vUserFk); + + -- Comprueba si hay colecciones disponibles que se ajustan a su configuracion + SELECT MIN(c.id) INTO vCollectionFk + FROM `collection` c + JOIN operator o + ON (o.itemPackingTypeFk = c.itemPackingTypeFk OR c.itemPackingTypeFk IS NULL) + AND o.numberOfWagons = c.wagons + AND o.trainFk = c.trainFk + AND o.warehouseFk = c.warehouseFk + AND c.workerFk IS NULL + AND (c.saleTotalCount <= o.linesLimit OR o.linesLimit IS NULL) + JOIN ( + SELECT tc.collectionFk, SUM(sv.volume) volume + FROM ticketCollection tc + JOIN saleVolume sv ON sv.ticketFk = tc.ticketFk + WHERE sv.shipped >= util.VN_CURDATE() + GROUP BY tc.collectionFk + ) sub ON sub.collectionFk = c.id + AND (volume <= o.volumeLimit OR o.volumeLimit IS NULL) + WHERE o.workerFk = vUserFk; + + IF vCollectionFk IS NULL THEN + CALL collection_new(vUserFk, vCollectionFk); + END IF; + + UPDATE `collection` + SET workerFk = vUserFk + WHERE id = vCollectionFk; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -51478,9 +51478,9 @@ BEGIN * @param vWorkerFk id del worker. * @table Devuelve tabla temporal con las colecciones pendientes */ - DROP TEMPORARY TABLE IF EXISTS tCollection; + DROP TEMPORARY TABLE IF EXISTS tmp.collection; - CREATE TEMPORARY TABLE tCollection + CREATE TEMPORARY TABLE tmp.collection SELECT c.id collectionFk, date(c.created) created, COUNT(DISTINCT tc.ticketFk) ticketTotalCount @@ -51499,7 +51499,7 @@ BEGIN GROUP BY c.id HAVING COUNT(*) > COUNT(DISTINCT st.id); - SELECT * FROM tCollection; + SELECT * FROM tmp.collection; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60631,167 +60631,167 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_getSaleDate`(vShelvingFk VARCHAR(3)) -BEGIN - - /* Devuelve la mínima fecha en que se necesita cada producto en esa matrícula. - * - * @param vShelvingFk Matrícula del carro o pallet - */ - - DECLARE vWarehouseFk INT; - DECLARE vStockScopeDays INT; - - SELECT s.warehouseFk, stockScopeDays - INTO vWarehouseFk, vStockScopeDays - FROM sector s - JOIN operator o ON s.id = o.sectorFk - JOIN productionConfig pc - WHERE o.workerFk = account.myUser_getId(); - - IF vWarehouseFk IS NULL - THEN CALL util.throw('WarehouseFk not setted'); - END IF; - - IF vStockScopeDays IS NULL - THEN CALL util.throw('StockScopeDays not setted'); - END IF; - - CREATE OR REPLACE TEMPORARY TABLE tmp.tItems - (PRIMARY KEY (itemFk)) - ENGINE = MEMORY - SELECT itemFk, SUM(visible) visible - FROM itemShelving - WHERE shelvingFk = vShelvingFk COLLATE utf8_unicode_ci - GROUP BY itemFk; - - CREATE OR REPLACE TEMPORARY TABLE tmp.tStockByDay - (INDEX (itemFk, dated)) - ENGINE = MEMORY - SELECT dated, - SUM(t3.amount) OVER (PARTITION BY t3.itemFk ORDER BY dated) stock, - t3.itemFk - FROM ( - SELECT t.itemFk, dated, SUM(amount) amount - FROM ( - SELECT t2.itemFk, t2.amount, t2.dated - FROM ( - SELECT item_id itemFk, amount, util.VN_CURDATE() dated - FROM cache.stock s - JOIN tmp.tItems i ON i.itemFk = s.item_id - WHERE s.warehouse_id = vWarehouseFk - UNION ALL - SELECT ish.itemFk, - SUM(ish.visible), util.VN_CURDATE() - FROM itemShelving ish - JOIN tmp.tItems i ON i.itemFk = ish.itemFk - JOIN shelving sh ON sh.code = ish.shelvingFk - JOIN parking p ON sh.parkingFk = p.id - JOIN sector s ON s.id = p.sectorFk - WHERE s.isReserve - GROUP BY ish.itemFk - UNION ALL - SELECT iei.itemFk, SUM(quantity), landed - FROM itemEntryIn iei - JOIN tmp.tItems i ON i.itemFk = iei.itemFk - WHERE iei.landed BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY - AND iei.warehouseInFk = vWarehouseFk - AND NOT isVirtualStock - GROUP BY iei.itemFk, iei.landed - UNION ALL - SELECT ieo.itemFk, SUM(quantity), shipped - FROM itemEntryOut ieo - JOIN tmp.tItems i ON i.itemFk = ieo.itemFk - WHERE ieo.shipped BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY - AND ieo.warehouseOutFk = vWarehouseFk - GROUP BY ieo.itemFk, ieo.shipped - UNION ALL - SELECT i.itemFk, SUM(ito.quantity), DATE(ito.shipped) - FROM itemTicketOut ito - JOIN tmp.tItems i ON i.itemFk = ito.itemFk - WHERE ito.shipped BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY - AND ito.warehouseFk = vWarehouseFk - GROUP BY ito.itemFk, ito.shipped - ) t2 - JOIN tmp.tItems i ON i.itemFk = t2.itemFk)t - GROUP BY t.itemFk, dated - ) t3; - - -- Se restan las entradas de hoy - UPDATE tmp.tStockByDay sbd - JOIN (SELECT iei.itemFk, SUM(quantity) todayEntry - FROM itemEntryIn iei - JOIN tmp.tItems i ON i.itemFk = iei.itemFk - WHERE iei.landed = util.VN_CURDATE() - AND iei.warehouseInFk = vWarehouseFk - AND NOT iei.isVirtualStock) sub ON sub.itemFk = sbd.itemFk - SET sbd.stock = sbd.stock - sub.todayEntry - WHERE sbd.dated = util.VN_CURDATE(); - - -- Se añaden las lineas de venta servidas - UPDATE tmp.tStockByDay sbd - JOIN (SELECT s.itemFK, SUM(quantity) amount - FROM sale s - JOIN ticket t ON t.id = s.ticketFk - WHERE t.warehouseFk = vWarehouseFk - AND t.shipped BETWEEN util.VN_CURDATE() AND util.midnight() - AND s.isPicked - GROUP BY s.itemFk) sub ON sub.itemFk = sbd.itemFk - SET sbd.stock = sbd.stock + sub.amount; - - -- Se añaden los items ubicados hoy - UPDATE tmp.tStockByDay sbd - JOIN (SELECT ish.itemFK, SUM(ish.visible) amount - FROM itemShelving ish - JOIN shelving sh ON sh.code = ish.shelvingFk - JOIN parking p ON p.id = sh.parkingFk - JOIN sector s ON s.id = p.sectorFk - WHERE s.warehouseFk = vWarehouseFk - AND NOT s.isReserve - AND ish.created BETWEEN util.VN_CURDATE() AND util.midnight() - GROUP BY ish.itemFk) sub ON sub.itemFk = sbd.itemFk - SET sbd.stock = sbd.stock + sub.amount; - - SELECT ts.itemFk, - i.longName, - IF(ts.stock<=0, ts.dated, NULL) dated, - ts.stock, - sub4.visible, - sub4.shelvingFk - FROM( - SELECT IFNULL(sub2.minDated, sub.minDated) dated, - IFNULL(sub2.itemFk, sub.itemFk) itemFk - FROM(SELECT sbd.itemFk, - MIN(dated) minDated, - sbd.stock - FROM tmp.tItems ti - LEFT JOIN tmp.tStockByDay sbd ON sbd.itemFk = ti.itemFk - GROUP BY itemFk)sub - LEFT JOIN ( - SELECT sbd.itemFk, - MIN(dated) minDated, - sbd.stock - FROM tmp.tItems ti - LEFT JOIN tmp.tStockByDay sbd ON sbd.itemFk = ti.itemFk - WHERE sbd.stock <= 0 - GROUP BY itemFk)sub2 ON sub2.itemFk =sub.itemFk - WHERE sub2.itemFk IS NOT NULL - OR (sub2.itemFk IS NULL AND sub.itemFk IS NOT NULL)) sub3 - LEFT JOIN tmp.tStockByDay ts ON ts.itemFk = sub3.itemFk AND ts.dated = sub3.dated - JOIN (SELECT ish.itemFk, - ish.visible, - p.sectorFk, - ish.shelvingFk - FROM itemShelving ish - JOIN vn.shelving sh ON sh.code = ish.shelvingFk - LEFT JOIN parking p ON p.id = parkingFk - LEFT JOIN vn.sector s ON s.id = p.sectorFk - WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci - ) sub4 ON sub4.itemFk = ts.itemFk - LEFT JOIN sector s ON s.id = sub4.sectorFk - LEFT JOIN item i ON i.id = ts.itemFk - WHERE NOT s.isReserve; - - DROP TEMPORARY TABLE tmp.tStockByDay, tmp.tItems; - +BEGIN + + /* Devuelve la mínima fecha en que se necesita cada producto en esa matrícula. + * + * @param vShelvingFk Matrícula del carro o pallet + */ + + DECLARE vWarehouseFk INT; + DECLARE vStockScopeDays INT; + + SELECT s.warehouseFk, stockScopeDays + INTO vWarehouseFk, vStockScopeDays + FROM sector s + JOIN operator o ON s.id = o.sectorFk + JOIN productionConfig pc + WHERE o.workerFk = account.myUser_getId(); + + IF vWarehouseFk IS NULL + THEN CALL util.throw('WarehouseFk not setted'); + END IF; + + IF vStockScopeDays IS NULL + THEN CALL util.throw('StockScopeDays not setted'); + END IF; + + CREATE OR REPLACE TEMPORARY TABLE tmp.tItems + (PRIMARY KEY (itemFk)) + ENGINE = MEMORY + SELECT itemFk, SUM(visible) visible + FROM itemShelving + WHERE shelvingFk = vShelvingFk COLLATE utf8_unicode_ci + GROUP BY itemFk; + + CREATE OR REPLACE TEMPORARY TABLE tmp.tStockByDay + (INDEX (itemFk, dated)) + ENGINE = MEMORY + SELECT dated, + SUM(t3.amount) OVER (PARTITION BY t3.itemFk ORDER BY dated) stock, + t3.itemFk + FROM ( + SELECT t.itemFk, dated, SUM(amount) amount + FROM ( + SELECT t2.itemFk, t2.amount, t2.dated + FROM ( + SELECT item_id itemFk, amount, util.VN_CURDATE() dated + FROM cache.stock s + JOIN tmp.tItems i ON i.itemFk = s.item_id + WHERE s.warehouse_id = vWarehouseFk + UNION ALL + SELECT ish.itemFk, - SUM(ish.visible), util.VN_CURDATE() + FROM itemShelving ish + JOIN tmp.tItems i ON i.itemFk = ish.itemFk + JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN parking p ON sh.parkingFk = p.id + JOIN sector s ON s.id = p.sectorFk + WHERE s.isReserve + GROUP BY ish.itemFk + UNION ALL + SELECT iei.itemFk, SUM(quantity), landed + FROM itemEntryIn iei + JOIN tmp.tItems i ON i.itemFk = iei.itemFk + WHERE iei.landed BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY + AND iei.warehouseInFk = vWarehouseFk + AND NOT isVirtualStock + GROUP BY iei.itemFk, iei.landed + UNION ALL + SELECT ieo.itemFk, SUM(quantity), shipped + FROM itemEntryOut ieo + JOIN tmp.tItems i ON i.itemFk = ieo.itemFk + WHERE ieo.shipped BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY + AND ieo.warehouseOutFk = vWarehouseFk + GROUP BY ieo.itemFk, ieo.shipped + UNION ALL + SELECT i.itemFk, SUM(ito.quantity), DATE(ito.shipped) + FROM itemTicketOut ito + JOIN tmp.tItems i ON i.itemFk = ito.itemFk + WHERE ito.shipped BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY + AND ito.warehouseFk = vWarehouseFk + GROUP BY ito.itemFk, ito.shipped + ) t2 + JOIN tmp.tItems i ON i.itemFk = t2.itemFk)t + GROUP BY t.itemFk, dated + ) t3; + + -- Se restan las entradas de hoy + UPDATE tmp.tStockByDay sbd + JOIN (SELECT iei.itemFk, SUM(quantity) todayEntry + FROM itemEntryIn iei + JOIN tmp.tItems i ON i.itemFk = iei.itemFk + WHERE iei.landed = util.VN_CURDATE() + AND iei.warehouseInFk = vWarehouseFk + AND NOT iei.isVirtualStock) sub ON sub.itemFk = sbd.itemFk + SET sbd.stock = sbd.stock - sub.todayEntry + WHERE sbd.dated = util.VN_CURDATE(); + + -- Se añaden las lineas de venta servidas + UPDATE tmp.tStockByDay sbd + JOIN (SELECT s.itemFK, SUM(quantity) amount + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + WHERE t.warehouseFk = vWarehouseFk + AND t.shipped BETWEEN util.VN_CURDATE() AND util.midnight() + AND s.isPicked + GROUP BY s.itemFk) sub ON sub.itemFk = sbd.itemFk + SET sbd.stock = sbd.stock + sub.amount; + + -- Se añaden los items ubicados hoy + UPDATE tmp.tStockByDay sbd + JOIN (SELECT ish.itemFK, SUM(ish.visible) amount + FROM itemShelving ish + JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN parking p ON p.id = sh.parkingFk + JOIN sector s ON s.id = p.sectorFk + WHERE s.warehouseFk = vWarehouseFk + AND NOT s.isReserve + AND ish.created BETWEEN util.VN_CURDATE() AND util.midnight() + GROUP BY ish.itemFk) sub ON sub.itemFk = sbd.itemFk + SET sbd.stock = sbd.stock + sub.amount; + + SELECT ts.itemFk, + i.longName, + IF(ts.stock<=0, ts.dated, NULL) dated, + ts.stock, + sub4.visible, + sub4.shelvingFk + FROM( + SELECT IFNULL(sub2.minDated, sub.minDated) dated, + IFNULL(sub2.itemFk, sub.itemFk) itemFk + FROM(SELECT sbd.itemFk, + MIN(dated) minDated, + sbd.stock + FROM tmp.tItems ti + LEFT JOIN tmp.tStockByDay sbd ON sbd.itemFk = ti.itemFk + GROUP BY itemFk)sub + LEFT JOIN ( + SELECT sbd.itemFk, + MIN(dated) minDated, + sbd.stock + FROM tmp.tItems ti + LEFT JOIN tmp.tStockByDay sbd ON sbd.itemFk = ti.itemFk + WHERE sbd.stock <= 0 + GROUP BY itemFk)sub2 ON sub2.itemFk =sub.itemFk + WHERE sub2.itemFk IS NOT NULL + OR (sub2.itemFk IS NULL AND sub.itemFk IS NOT NULL)) sub3 + LEFT JOIN tmp.tStockByDay ts ON ts.itemFk = sub3.itemFk AND ts.dated = sub3.dated + JOIN (SELECT ish.itemFk, + ish.visible, + p.sectorFk, + ish.shelvingFk + FROM itemShelving ish + JOIN vn.shelving sh ON sh.code = ish.shelvingFk + LEFT JOIN parking p ON p.id = parkingFk + LEFT JOIN vn.sector s ON s.id = p.sectorFk + WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci + ) sub4 ON sub4.itemFk = ts.itemFk + LEFT JOIN sector s ON s.id = sub4.sectorFk + LEFT JOIN item i ON i.id = ts.itemFk + WHERE NOT s.isReserve; + + DROP TEMPORARY TABLE tmp.tStockByDay, tmp.tItems; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -62333,50 +62333,50 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getAtp`(vDated DATE) -BEGIN -/** - * Calcula el valor mínimo acumulado para cada artículo ordenado por fecha y - * almacén. - * - * @param vDated Si no hay movimientos en la fecha indicada, debe devolver 0 - * @table tmp.itemCalc(itemFk, wareHouseFk, dated, quantity) - * @return tmp.itemAtp(itemFk, warehouseFk, quantity) - */ - CREATE OR REPLACE TEMPORARY TABLE tItemOrdered - (UNIQUE(itemFk, warehouseFk, dated)) - ENGINE = MEMORY - SELECT itemFk, warehouseFk, dated, SUM(quantity) quantity - FROM ( - SELECT itemFk, warehouseFk, dated, quantity - FROM tmp.itemCalc - UNION ALL - SELECT itemFk, warehouseFk, vDated, 0 - FROM (SELECT DISTINCT itemFk, warehouseFk FROM tmp.itemCalc) t2 - ) t1 - GROUP BY itemFk, warehouseFk, dated - ORDER BY itemFk, warehouseFk, dated; - - SET @lastItemFk := 0; - SET @lastWareHouseFk := 0; - SET @lastQuantity := 0; - - CREATE OR REPLACE TEMPORARY TABLE tmp.itemAtp - (INDEX (itemFk, wareHouseFk)) - SELECT itemFk, wareHouseFk, MIN(quantityAccumulated) quantity - FROM ( - SELECT - itemFk, - IF(itemFk <> @lastItemFk OR wareHouseFk <> @lastWareHouseFk, - @lastQuantity := quantity, - @lastQuantity := @lastQuantity + quantity) quantityAccumulated, - wareHouseFk, - @lastItemFk := itemFk, - @lastWareHouseFk := wareHouseFk - FROM tItemOrdered - )sub - GROUP BY itemFk, wareHouseFk; - - DROP TEMPORARY TABLE tItemOrdered; +BEGIN +/** + * Calcula el valor mínimo acumulado para cada artículo ordenado por fecha y + * almacén. + * + * @param vDated Si no hay movimientos en la fecha indicada, debe devolver 0 + * @table tmp.itemCalc(itemFk, wareHouseFk, dated, quantity) + * @return tmp.itemAtp(itemFk, warehouseFk, quantity) + */ + CREATE OR REPLACE TEMPORARY TABLE tItemOrdered + (UNIQUE(itemFk, warehouseFk, dated)) + ENGINE = MEMORY + SELECT itemFk, warehouseFk, dated, SUM(quantity) quantity + FROM ( + SELECT itemFk, warehouseFk, dated, quantity + FROM tmp.itemCalc + UNION ALL + SELECT itemFk, warehouseFk, vDated, 0 + FROM (SELECT DISTINCT itemFk, warehouseFk FROM tmp.itemCalc) t2 + ) t1 + GROUP BY itemFk, warehouseFk, dated + ORDER BY itemFk, warehouseFk, dated; + + SET @lastItemFk := 0; + SET @lastWareHouseFk := 0; + SET @lastQuantity := 0; + + CREATE OR REPLACE TEMPORARY TABLE tmp.itemAtp + (INDEX (itemFk, wareHouseFk)) + SELECT itemFk, wareHouseFk, MIN(quantityAccumulated) quantity + FROM ( + SELECT + itemFk, + IF(itemFk <> @lastItemFk OR wareHouseFk <> @lastWareHouseFk, + @lastQuantity := quantity, + @lastQuantity := @lastQuantity + quantity) quantityAccumulated, + wareHouseFk, + @lastItemFk := itemFk, + @lastWareHouseFk := wareHouseFk + FROM tItemOrdered + )sub + GROUP BY itemFk, wareHouseFk; + + DROP TEMPORARY TABLE tItemOrdered; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -64541,197 +64541,197 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `multipleInventory`( - vDate DATE, - vWarehouseFk TINYINT, - vMaxDays TINYINT +CREATE DEFINER=`root`@`localhost` PROCEDURE `multipleInventory`( + vDate DATE, + vWarehouseFk TINYINT, + vMaxDays TINYINT ) -proc: BEGIN - DECLARE vDateTomorrow DATE DEFAULT vDate + INTERVAL 1 DAY; - DECLARE vDateFrom DATE DEFAULT vDate; - DECLARE vDateTo DATETIME; - DECLARE vDateToTomorrow DATETIME; - DECLARE vDefaultDayRange INT; - - IF vDate < util.VN_CURDATE() THEN - LEAVE proc; - END IF; - - IF vDate = util.VN_CURDATE() THEN - SELECT inventoried INTO vDateFrom - FROM config; - END IF; - - SELECT defaultDayRange INTO vDefaultDayRange - FROM comparativeConfig; - - SET vDateTo = vDate + INTERVAL IFNULL(vMaxDays, vDefaultDayRange) DAY; - SET vDateToTomorrow = vDateTo + INTERVAL 1 DAY; - - ALTER TABLE tmp.itemInventory - ADD `avalaible` INT NOT NULL, - ADD `sd` INT NOT NULL, - ADD `rest` INT NOT NULL, - ADD `expected` INT NOT NULL, - ADD `inventory` INT NOT NULL, - ADD `visible` INT NOT NULL, - ADD `life` TINYINT NOT NULL DEFAULT '0'; - - -- Calculo del inventario - UPDATE tmp.itemInventory ai - JOIN ( - SELECT itemFk Id_Article, SUM(quantity) Subtotal - FROM ( - SELECT s.itemFk, - s.quantity quantity - FROM sale s - JOIN ticket t ON t.id = s.ticketFk - JOIN warehouse w ON w.id = t.warehouseFk - WHERE t.shipped BETWEEN vDateFrom AND util.dayEnd(vDate) - AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk - AND w.isComparative - UNION ALL - SELECT b.itemFk, b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseInFk - WHERE t.landed BETWEEN vDateFrom AND util.dayEnd(vDate) - AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk - AND w.isComparative - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - UNION ALL - SELECT b.itemFk, - b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseOutFk - WHERE t.shipped BETWEEN vDateFrom AND util.dayEnd(vDate) - AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk - AND w.isComparative - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - ) sub2 - GROUP BY itemFk - ) sub ON ai.id = sub.Id_Article - SET ai.inventory = sub.Subtotal, - ai.visible = sub.Subtotal, - ai.avalaible = sub.Subtotal, - ai.sd = sub.Subtotal; - - -- Cálculo del visible - UPDATE tmp.itemInventory ai - JOIN ( - SELECT itemFk Id_Article, SUM(quantity) Subtotal - FROM ( - SELECT s.itemFk, s.quantity - FROM sale s - JOIN ticket t ON t.id = s.ticketFk - JOIN warehouse w ON w.id = t.warehouseFk - WHERE t.shipped >= vDate - AND t.shipped < vDateTomorrow - AND (NOT isPicked AND NOT t.isLabeled AND t.refFk IS NULL) - AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk - AND w.isComparative - UNION ALL - SELECT b.itemFk, - b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseInFk - WHERE t.landed = vDate - AND NOT t.isReceived - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk - AND w.isComparative - UNION ALL - SELECT b.itemFk, b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseOutFk - WHERE t.shipped = vDate - AND NOT t.isReceived - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk - AND w.isComparative - ) sub2 - GROUP BY itemFk - ) sub ON ai.id = sub.Id_Article - SET ai.visible = ai.visible + sub.Subtotal; - - -- Calculo del disponible - CREATE OR REPLACE TEMPORARY TABLE tmp.itemCalc - (INDEX (itemFk, warehouseFk)) - ENGINE = MEMORY - SELECT sub.itemFk, - vWarehouseFk warehouseFk, - sub.dated, - SUM(sub.quantity) quantity - FROM ( - SELECT s.itemFk, - DATE(t.shipped) dated, - - s.quantity quantity - FROM sale s - JOIN ticket t ON t.id = s.ticketFk - JOIN warehouse w ON w.id = t.warehouseFk - WHERE t.shipped BETWEEN vDateTomorrow AND vDateTo - AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk - AND w.isComparative - UNION ALL - SELECT b.itemFk, t.landed, b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseInFk - WHERE t.landed BETWEEN vDateTomorrow AND vDateTo - AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk - AND w.isComparative - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - UNION ALL - SELECT b.itemFk, t.shipped, - b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseOutFk - WHERE t.shipped BETWEEN vDateTomorrow AND vDateTo - AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk - AND w.isComparative - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - ) sub - GROUP BY sub.itemFk, sub.dated; - - CALL item_getAtp(vDate); - CALL travel_upcomingArrivals(vWarehouseFk, vDate); - - UPDATE tmp.itemInventory ai - JOIN ( - SELECT it.itemFk, - SUM(it.quantity) quantity, - im.quantity minQuantity - FROM tmp.itemCalc it - JOIN tmp.itemAtp im ON im.itemFk = it.itemFk - JOIN item i ON i.id = it.itemFk - LEFT JOIN origin o ON o.id = i.originFk - LEFT JOIN tmp.itemTravel t ON t.wh = o.warehouseFk - WHERE it.dated < IF(vMaxDays < 0 AND t.landing IS NOT NULL, - t.landing, - vDateToTomorrow) - GROUP BY it.itemFk - ) sub ON sub.itemFk = ai.id - SET ai.avalaible = IF(sub.minQuantity > 0, - ai.avalaible, - ai.avalaible + sub.minQuantity), - ai.sd = ai.inventory + sub.quantity; - - DROP TEMPORARY TABLE - tmp.itemTravel, - tmp.itemCalc, - tmp.itemAtp; +proc: BEGIN + DECLARE vDateTomorrow DATE DEFAULT vDate + INTERVAL 1 DAY; + DECLARE vDateFrom DATE DEFAULT vDate; + DECLARE vDateTo DATETIME; + DECLARE vDateToTomorrow DATETIME; + DECLARE vDefaultDayRange INT; + + IF vDate < util.VN_CURDATE() THEN + LEAVE proc; + END IF; + + IF vDate = util.VN_CURDATE() THEN + SELECT inventoried INTO vDateFrom + FROM config; + END IF; + + SELECT defaultDayRange INTO vDefaultDayRange + FROM comparativeConfig; + + SET vDateTo = vDate + INTERVAL IFNULL(vMaxDays, vDefaultDayRange) DAY; + SET vDateToTomorrow = vDateTo + INTERVAL 1 DAY; + + ALTER TABLE tmp.itemInventory + ADD `avalaible` INT NOT NULL, + ADD `sd` INT NOT NULL, + ADD `rest` INT NOT NULL, + ADD `expected` INT NOT NULL, + ADD `inventory` INT NOT NULL, + ADD `visible` INT NOT NULL, + ADD `life` TINYINT NOT NULL DEFAULT '0'; + + -- Calculo del inventario + UPDATE tmp.itemInventory ai + JOIN ( + SELECT itemFk Id_Article, SUM(quantity) Subtotal + FROM ( + SELECT s.itemFk, - s.quantity quantity + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + JOIN warehouse w ON w.id = t.warehouseFk + WHERE t.shipped BETWEEN vDateFrom AND util.dayEnd(vDate) + AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk + AND w.isComparative + UNION ALL + SELECT b.itemFk, b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseInFk + WHERE t.landed BETWEEN vDateFrom AND util.dayEnd(vDate) + AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk + AND w.isComparative + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + UNION ALL + SELECT b.itemFk, - b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseOutFk + WHERE t.shipped BETWEEN vDateFrom AND util.dayEnd(vDate) + AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk + AND w.isComparative + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + ) sub2 + GROUP BY itemFk + ) sub ON ai.id = sub.Id_Article + SET ai.inventory = sub.Subtotal, + ai.visible = sub.Subtotal, + ai.avalaible = sub.Subtotal, + ai.sd = sub.Subtotal; + + -- Cálculo del visible + UPDATE tmp.itemInventory ai + JOIN ( + SELECT itemFk Id_Article, SUM(quantity) Subtotal + FROM ( + SELECT s.itemFk, s.quantity + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + JOIN warehouse w ON w.id = t.warehouseFk + WHERE t.shipped >= vDate + AND t.shipped < vDateTomorrow + AND (NOT isPicked AND NOT t.isLabeled AND t.refFk IS NULL) + AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk + AND w.isComparative + UNION ALL + SELECT b.itemFk, - b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseInFk + WHERE t.landed = vDate + AND NOT t.isReceived + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk + AND w.isComparative + UNION ALL + SELECT b.itemFk, b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseOutFk + WHERE t.shipped = vDate + AND NOT t.isReceived + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk + AND w.isComparative + ) sub2 + GROUP BY itemFk + ) sub ON ai.id = sub.Id_Article + SET ai.visible = ai.visible + sub.Subtotal; + + -- Calculo del disponible + CREATE OR REPLACE TEMPORARY TABLE tmp.itemCalc + (INDEX (itemFk, warehouseFk)) + ENGINE = MEMORY + SELECT sub.itemFk, + vWarehouseFk warehouseFk, + sub.dated, + SUM(sub.quantity) quantity + FROM ( + SELECT s.itemFk, + DATE(t.shipped) dated, + - s.quantity quantity + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + JOIN warehouse w ON w.id = t.warehouseFk + WHERE t.shipped BETWEEN vDateTomorrow AND vDateTo + AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk + AND w.isComparative + UNION ALL + SELECT b.itemFk, t.landed, b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseInFk + WHERE t.landed BETWEEN vDateTomorrow AND vDateTo + AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk + AND w.isComparative + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + UNION ALL + SELECT b.itemFk, t.shipped, - b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseOutFk + WHERE t.shipped BETWEEN vDateTomorrow AND vDateTo + AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk + AND w.isComparative + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + ) sub + GROUP BY sub.itemFk, sub.dated; + + CALL item_getAtp(vDate); + CALL travel_upcomingArrivals(vWarehouseFk, vDate); + + UPDATE tmp.itemInventory ai + JOIN ( + SELECT it.itemFk, + SUM(it.quantity) quantity, + im.quantity minQuantity + FROM tmp.itemCalc it + JOIN tmp.itemAtp im ON im.itemFk = it.itemFk + JOIN item i ON i.id = it.itemFk + LEFT JOIN origin o ON o.id = i.originFk + LEFT JOIN tmp.itemTravel t ON t.wh = o.warehouseFk + WHERE it.dated < IF(vMaxDays < 0 AND t.landing IS NOT NULL, + t.landing, + vDateToTomorrow) + GROUP BY it.itemFk + ) sub ON sub.itemFk = ai.id + SET ai.avalaible = IF(sub.minQuantity > 0, + ai.avalaible, + ai.avalaible + sub.minQuantity), + ai.sd = ai.inventory + sub.quantity; + + DROP TEMPORARY TABLE + tmp.itemTravel, + tmp.itemCalc, + tmp.itemAtp; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -67555,43 +67555,43 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sales_merge`(vTicketFk INT) -BEGIN - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - CREATE OR REPLACE TEMPORARY TABLE tSalesToPreserve - (PRIMARY KEY (id)) - ENGINE = MEMORY - SELECT s.id, s.itemFk, SUM(s.quantity) newQuantity - FROM sale s - JOIN item i ON i.id = s.itemFk - JOIN itemType it ON it.id = i.typeFk - WHERE s.ticketFk = vTicketFk - AND it.isMergeable - GROUP BY s.itemFk, s.price, s.discount; - - START TRANSACTION; - - UPDATE sale s - JOIN tSalesToPreserve stp ON stp.id = s.id - SET s.quantity = newQuantity - WHERE s.ticketFk = vTicketFk; - - DELETE s.* - FROM sale s - LEFT JOIN tSalesToPreserve stp ON stp.id = s.id - JOIN item i ON i.id = s.itemFk - JOIN itemType it ON it.id = i.typeFk - WHERE s.ticketFk = vTicketFk - AND stp.id IS NULL - AND it.isMergeable; - - COMMIT; - - DROP TEMPORARY TABLE tSalesToPreserve; +BEGIN + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + CREATE OR REPLACE TEMPORARY TABLE tSalesToPreserve + (PRIMARY KEY (id)) + ENGINE = MEMORY + SELECT s.id, s.itemFk, SUM(s.quantity) newQuantity + FROM sale s + JOIN item i ON i.id = s.itemFk + JOIN itemType it ON it.id = i.typeFk + WHERE s.ticketFk = vTicketFk + AND it.isMergeable + GROUP BY s.itemFk, s.price, s.discount; + + START TRANSACTION; + + UPDATE sale s + JOIN tSalesToPreserve stp ON stp.id = s.id + SET s.quantity = newQuantity + WHERE s.ticketFk = vTicketFk; + + DELETE s.* + FROM sale s + LEFT JOIN tSalesToPreserve stp ON stp.id = s.id + JOIN item i ON i.id = s.itemFk + JOIN itemType it ON it.id = i.typeFk + WHERE s.ticketFk = vTicketFk + AND stp.id IS NULL + AND it.isMergeable; + + COMMIT; + + DROP TEMPORARY TABLE tSalesToPreserve; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -69404,30 +69404,30 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sectorCollection_new`(vSectorFk INT) -BEGIN -/** - * Inserta una nueva colección, si el usuario no tiene ninguna vacia. - * Esto se hace para evitar que por error se generen colecciones sin sentido. - * - * @param vSectorFk Identificador de #vn.sector - */ - DECLARE hasEmptyCollections BOOL; - DECLARE vUserFk INT; - - SET vUserFk = account.myUser_getId(); - - SELECT (COUNT(sc.id) > 0) INTO hasEmptyCollections - FROM vn.sectorCollection sc - LEFT JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id - WHERE ISNULL(scsg.id) - AND sc.userFk = vUserFk - AND sc.sectorFk = vSectorFk - AND sc.created >= util.VN_CURDATE(); - - IF NOT hasEmptyCollections THEN - INSERT INTO vn.sectorCollection(userFk, sectorFk) - VALUES(vUserFk, vSectorFk); - END IF; +BEGIN +/** + * Inserta una nueva colección, si el usuario no tiene ninguna vacia. + * Esto se hace para evitar que por error se generen colecciones sin sentido. + * + * @param vSectorFk Identificador de #vn.sector + */ + DECLARE hasEmptyCollections BOOL; + DECLARE vUserFk INT; + + SET vUserFk = account.myUser_getId(); + + SELECT (COUNT(sc.id) > 0) INTO hasEmptyCollections + FROM vn.sectorCollection sc + LEFT JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id + WHERE ISNULL(scsg.id) + AND sc.userFk = vUserFk + AND sc.sectorFk = vSectorFk + AND sc.created >= util.VN_CURDATE(); + + IF NOT hasEmptyCollections THEN + INSERT INTO vn.sectorCollection(userFk, sectorFk) + VALUES(vUserFk, vSectorFk); + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -73367,59 +73367,59 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_DelayTruckSplit`(vTicketFk INT) -BEGIN -/** - * Splita las lineas de ticket que no estan ubicadas - * - * @param vTicketFk Id ticket - */ - DECLARE vNewTicketFk INT; - DECLARE vTotalLines INT; - DECLARE vLinesToSplit INT; - - DROP TEMPORARY TABLE IF EXISTS tmp.SalesToSplit; - - SELECT COUNT(*) INTO vTotalLines - FROM sale - WHERE ticketFk = vTicketFk; - - CREATE TEMPORARY TABLE tmp.SalesToSplit - SELECT s.id saleFk - FROM ticket t - JOIN sale s ON t.id = s.ticketFk - LEFT JOIN ( - SELECT ish.itemFk itemFk, - SUM(ish.visible) visible, - s.warehouseFk warehouseFk - FROM itemShelving ish - JOIN shelving sh ON sh.code = ish.shelvingFk - JOIN parking p ON p.id = sh.parkingFk - JOIN sector s ON s.id = p.sectorFk - GROUP BY ish.itemFk, - s.warehouseFk - ) issw ON issw.itemFk = s.itemFk - AND issw.warehouseFk = t.warehouseFk - WHERE s.quantity > IFNULL(issw.visible, 0) - AND s.quantity > 0 - AND NOT s.isPicked - AND NOT s.reserved - AND t.id = vTicketFk; - - SELECT COUNT(*) INTO vLinesToSplit - FROM tmp.SalesToSplit; - - IF vLinesToSplit = vTotalLines AND vLinesToSplit > 0 THEN - SET vNewTicketFk = vTicketFk; - ELSE - CALL ticket_Clone(vTicketFk, vNewTicketFk); - UPDATE sale s - JOIN tmp.SalesToSplit sts ON sts.saleFk = s.id - SET s.ticketFk = vNewTicketFk; - END IF; - - CALL ticketStateUpdate(vNewTicketFk, 'FIXING'); - - DROP TEMPORARY TABLE tmp.SalesToSplit; +BEGIN +/** + * Splita las lineas de ticket que no estan ubicadas + * + * @param vTicketFk Id ticket + */ + DECLARE vNewTicketFk INT; + DECLARE vTotalLines INT; + DECLARE vLinesToSplit INT; + + DROP TEMPORARY TABLE IF EXISTS tmp.SalesToSplit; + + SELECT COUNT(*) INTO vTotalLines + FROM sale + WHERE ticketFk = vTicketFk; + + CREATE TEMPORARY TABLE tmp.SalesToSplit + SELECT s.id saleFk + FROM ticket t + JOIN sale s ON t.id = s.ticketFk + LEFT JOIN ( + SELECT ish.itemFk itemFk, + SUM(ish.visible) visible, + s.warehouseFk warehouseFk + FROM itemShelving ish + JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN parking p ON p.id = sh.parkingFk + JOIN sector s ON s.id = p.sectorFk + GROUP BY ish.itemFk, + s.warehouseFk + ) issw ON issw.itemFk = s.itemFk + AND issw.warehouseFk = t.warehouseFk + WHERE s.quantity > IFNULL(issw.visible, 0) + AND s.quantity > 0 + AND NOT s.isPicked + AND NOT s.reserved + AND t.id = vTicketFk; + + SELECT COUNT(*) INTO vLinesToSplit + FROM tmp.SalesToSplit; + + IF vLinesToSplit = vTotalLines AND vLinesToSplit > 0 THEN + SET vNewTicketFk = vTicketFk; + ELSE + CALL ticket_Clone(vTicketFk, vNewTicketFk); + UPDATE sale s + JOIN tmp.SalesToSplit sts ON sts.saleFk = s.id + SET s.ticketFk = vNewTicketFk; + END IF; + + CALL ticketStateUpdate(vNewTicketFk, 'FIXING'); + + DROP TEMPORARY TABLE tmp.SalesToSplit; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -73437,84 +73437,84 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_doCmr`(vSelf INT) -BEGIN -/** -* Crea u actualiza la información del CMR asociado con -* un ticket específico en caso de que sea necesario. -* -* @param vSelf El id del ticket -*/ - DECLARE vCmrFk INT; - SELECT cmrFk INTO vCmrFk - FROM ticket - WHERE id = vSelf; - - CREATE OR REPLACE TEMPORARY TABLE tTicket - SELECT wo.firstName, - v.numberPlate, - com.id companyFk, - a.id addressFk, - c2.defaultAddressFk, - IFNULL(sat.supplierFk, su.id) supplierFk, - t.landed - FROM ticket t - JOIN ticketState ts ON ts.ticketFk = t.id - JOIN `state` s ON s.id = ts.stateFk - JOIN alertLevel al ON al.id = s.alertLevel - JOIN client c ON c.id = t.clientFk - JOIN `address` a ON a.id = t.addressFk - JOIN province p ON p.id = a.provinceFk - JOIN country co ON co.id = p.countryFk - JOIN warehouse w ON w.id = t.warehouseFk - JOIN company com ON com.id = t.companyFk - JOIN client c2 ON c2.id = com.clientFk - JOIN supplierAccount sa ON sa.id = com.supplierAccountFk - JOIN supplier su ON su.id = sa.supplierFk - LEFT JOIN route r ON r.id = t.routeFk - LEFT JOIN worker wo ON wo.id = r.workerFk - LEFT JOIN vehicle v ON v.id = r.vehicleFk - LEFT JOIN agencyMode am ON am.id = r.agencyModeFk - LEFT JOIN agency ag ON ag.id = am.agencyFk - LEFT JOIN supplierAgencyTerm sat ON sat.agencyFk = ag.id - AND wo.isFreelance - WHERE al.code IN ('PACKED', 'DELIVERED') - AND co.code <> 'ES' - AND am.name <> 'ABONO' - AND w.code = 'ALG' - AND t.id = vSelf - GROUP BY t.id; - - IF vCmrFk THEN - UPDATE cmr c - JOIN tTicket t - SET c.senderInstruccions = t.firstName, - c.truckPlate = t.numberPlate, - c.companyFk = t.companyFk, - c.addressToFk = t.addressFk, - c.addressFromFk = t.defaultAddressFk, - c.supplierFk = t.supplierFk, - c.ead = t.landed - WHERE id = vCmrFk; - ELSE - INSERT INTO cmr ( - senderInstruccions, - truckPlate, - companyFk, - addressToFk, - addressFromFk, - supplierFk, - ead - ) - SELECT * FROM tTicket; - - IF (SELECT EXISTS(SELECT * FROM tTicket)) THEN - UPDATE ticket - SET cmrFk = LAST_INSERT_ID() - WHERE id = vSelf; - END IF; - END IF; - - DROP TEMPORARY TABLE tTicket; +BEGIN +/** +* Crea u actualiza la información del CMR asociado con +* un ticket específico en caso de que sea necesario. +* +* @param vSelf El id del ticket +*/ + DECLARE vCmrFk INT; + SELECT cmrFk INTO vCmrFk + FROM ticket + WHERE id = vSelf; + + CREATE OR REPLACE TEMPORARY TABLE tTicket + SELECT wo.firstName, + v.numberPlate, + com.id companyFk, + a.id addressFk, + c2.defaultAddressFk, + IFNULL(sat.supplierFk, su.id) supplierFk, + t.landed + FROM ticket t + JOIN ticketState ts ON ts.ticketFk = t.id + JOIN `state` s ON s.id = ts.stateFk + JOIN alertLevel al ON al.id = s.alertLevel + JOIN client c ON c.id = t.clientFk + JOIN `address` a ON a.id = t.addressFk + JOIN province p ON p.id = a.provinceFk + JOIN country co ON co.id = p.countryFk + JOIN warehouse w ON w.id = t.warehouseFk + JOIN company com ON com.id = t.companyFk + JOIN client c2 ON c2.id = com.clientFk + JOIN supplierAccount sa ON sa.id = com.supplierAccountFk + JOIN supplier su ON su.id = sa.supplierFk + LEFT JOIN route r ON r.id = t.routeFk + LEFT JOIN worker wo ON wo.id = r.workerFk + LEFT JOIN vehicle v ON v.id = r.vehicleFk + LEFT JOIN agencyMode am ON am.id = r.agencyModeFk + LEFT JOIN agency ag ON ag.id = am.agencyFk + LEFT JOIN supplierAgencyTerm sat ON sat.agencyFk = ag.id + AND wo.isFreelance + WHERE al.code IN ('PACKED', 'DELIVERED') + AND co.code <> 'ES' + AND am.name <> 'ABONO' + AND w.code = 'ALG' + AND t.id = vSelf + GROUP BY t.id; + + IF vCmrFk THEN + UPDATE cmr c + JOIN tTicket t + SET c.senderInstruccions = t.firstName, + c.truckPlate = t.numberPlate, + c.companyFk = t.companyFk, + c.addressToFk = t.addressFk, + c.addressFromFk = t.defaultAddressFk, + c.supplierFk = t.supplierFk, + c.ead = t.landed + WHERE id = vCmrFk; + ELSE + INSERT INTO cmr ( + senderInstruccions, + truckPlate, + companyFk, + addressToFk, + addressFromFk, + supplierFk, + ead + ) + SELECT * FROM tTicket; + + IF (SELECT EXISTS(SELECT * FROM tTicket)) THEN + UPDATE ticket + SET cmrFk = LAST_INSERT_ID() + WHERE id = vSelf; + END IF; + END IF; + + DROP TEMPORARY TABLE tTicket; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -80930,126 +80930,126 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getLeaves`( - vSelf INT, - vParentFk INT, - vSearch VARCHAR(255), - vHasInsert BOOL +CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getLeaves`( + vSelf INT, + vParentFk INT, + vSearch VARCHAR(255), + vHasInsert BOOL ) -BEGIN -/** - * Devuelve las ubicaciones incluidas en la ruta y que sean hijos de parentFk. - * @param vSelf Id de la zona - * @param vParentFk Id del geo a calcular - * @param vSearch Cadena a buscar - * @param vHasInsert Indica si inserta en tmp.zoneNodes - * Optional @table tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) - */ - DECLARE vIsNumber BOOL; - DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch <> ''; - - CREATE OR REPLACE TEMPORARY TABLE tNodes - (UNIQUE (id)) - ENGINE = MEMORY - SELECT id - FROM zoneGeo - LIMIT 0; - - IF vIsSearch THEN - SET vIsNumber = vSearch REGEXP '^[0-9]+$'; - - INSERT INTO tNodes - SELECT id - FROM zoneGeo - WHERE (vIsNumber AND `name` = vSearch) - OR (!vIsNumber AND `name` LIKE CONCAT('%', vSearch, '%')) - LIMIT 1000; - - ELSEIF vParentFk IS NULL THEN - INSERT INTO tNodes - SELECT geoFk - FROM zoneIncluded - WHERE zoneFk = vSelf; - END IF; - - IF vParentFk IS NULL THEN - CREATE OR REPLACE TEMPORARY TABLE tChilds - (INDEX(id)) - ENGINE = MEMORY - SELECT id FROM tNodes; - - CREATE OR REPLACE TEMPORARY TABLE tParents - (INDEX(id)) - ENGINE = MEMORY - SELECT id FROM zoneGeo LIMIT 0; - - myLoop: LOOP - DELETE FROM tParents; - INSERT INTO tParents - SELECT parentFk id - FROM zoneGeo g - JOIN tChilds c ON c.id = g.id - WHERE g.parentFk IS NOT NULL; - - INSERT IGNORE INTO tNodes - SELECT id FROM tParents; - - IF NOT ROW_COUNT() THEN - LEAVE myLoop; - END IF; - - DELETE FROM tChilds; - INSERT INTO tChilds - SELECT id FROM tParents; - END LOOP; - - DROP TEMPORARY TABLE tChilds, tParents; - END IF; - - IF NOT vIsSearch THEN - INSERT IGNORE INTO tNodes - SELECT id - FROM zoneGeo - WHERE parentFk <=> vParentFk; - END IF; - - CREATE OR REPLACE TEMPORARY TABLE tZones - SELECT g.id, - g.name, - g.parentFk, - g.sons, - NOT g.sons OR `type` = 'country' isChecked, - i.isIncluded selected, - g.`depth`, - vSelf - FROM zoneGeo g - JOIN tNodes n ON n.id = g.id - LEFT JOIN zoneIncluded i ON i.geoFk = g.id - AND i.zoneFk = vSelf - ORDER BY g.`depth`, selected DESC, g.name; - - IF vHasInsert THEN - INSERT IGNORE INTO tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) - SELECT id, - name, - parentFk, - sons, - isChecked, - vSelf - FROM tZones - WHERE selected - OR (selected IS NULL AND vParentFk IS NOT NULL); - ELSE - SELECT id, - name, - parentFk, - sons, - selected - FROM tZones - ORDER BY `depth`, selected DESC, name; - END IF; - - DROP TEMPORARY TABLE tNodes, tZones; +BEGIN +/** + * Devuelve las ubicaciones incluidas en la ruta y que sean hijos de parentFk. + * @param vSelf Id de la zona + * @param vParentFk Id del geo a calcular + * @param vSearch Cadena a buscar + * @param vHasInsert Indica si inserta en tmp.zoneNodes + * Optional @table tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) + */ + DECLARE vIsNumber BOOL; + DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch <> ''; + + CREATE OR REPLACE TEMPORARY TABLE tNodes + (UNIQUE (id)) + ENGINE = MEMORY + SELECT id + FROM zoneGeo + LIMIT 0; + + IF vIsSearch THEN + SET vIsNumber = vSearch REGEXP '^[0-9]+$'; + + INSERT INTO tNodes + SELECT id + FROM zoneGeo + WHERE (vIsNumber AND `name` = vSearch) + OR (!vIsNumber AND `name` LIKE CONCAT('%', vSearch, '%')) + LIMIT 1000; + + ELSEIF vParentFk IS NULL THEN + INSERT INTO tNodes + SELECT geoFk + FROM zoneIncluded + WHERE zoneFk = vSelf; + END IF; + + IF vParentFk IS NULL THEN + CREATE OR REPLACE TEMPORARY TABLE tChilds + (INDEX(id)) + ENGINE = MEMORY + SELECT id FROM tNodes; + + CREATE OR REPLACE TEMPORARY TABLE tParents + (INDEX(id)) + ENGINE = MEMORY + SELECT id FROM zoneGeo LIMIT 0; + + myLoop: LOOP + DELETE FROM tParents; + INSERT INTO tParents + SELECT parentFk id + FROM zoneGeo g + JOIN tChilds c ON c.id = g.id + WHERE g.parentFk IS NOT NULL; + + INSERT IGNORE INTO tNodes + SELECT id FROM tParents; + + IF NOT ROW_COUNT() THEN + LEAVE myLoop; + END IF; + + DELETE FROM tChilds; + INSERT INTO tChilds + SELECT id FROM tParents; + END LOOP; + + DROP TEMPORARY TABLE tChilds, tParents; + END IF; + + IF NOT vIsSearch THEN + INSERT IGNORE INTO tNodes + SELECT id + FROM zoneGeo + WHERE parentFk <=> vParentFk; + END IF; + + CREATE OR REPLACE TEMPORARY TABLE tZones + SELECT g.id, + g.name, + g.parentFk, + g.sons, + NOT g.sons OR `type` = 'country' isChecked, + i.isIncluded selected, + g.`depth`, + vSelf + FROM zoneGeo g + JOIN tNodes n ON n.id = g.id + LEFT JOIN zoneIncluded i ON i.geoFk = g.id + AND i.zoneFk = vSelf + ORDER BY g.`depth`, selected DESC, g.name; + + IF vHasInsert THEN + INSERT IGNORE INTO tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) + SELECT id, + name, + parentFk, + sons, + isChecked, + vSelf + FROM tZones + WHERE selected + OR (selected IS NULL AND vParentFk IS NOT NULL); + ELSE + SELECT id, + name, + parentFk, + sons, + selected + FROM tZones + ORDER BY `depth`, selected DESC, name; + END IF; + + DROP TEMPORARY TABLE tNodes, tZones; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -81232,48 +81232,48 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getPostalCode`(vSelf INT) -BEGIN -/** - * Devuelve los códigos postales incluidos en una zona - */ - DECLARE vGeoFk INT DEFAULT NULL; - - CREATE OR REPLACE TEMPORARY TABLE tmp.zoneNodes ( - geoFk INT, - name VARCHAR(100), - parentFk INT, - sons INT, - isChecked BOOL DEFAULT 0, - zoneFk INT, - PRIMARY KEY zoneNodesPk (zoneFk, geoFk), - INDEX(geoFk)) - ENGINE = MEMORY; - - CALL zone_getLeaves(vSelf, NULL , NULL, TRUE); - - UPDATE tmp.zoneNodes - SET isChecked = 0 - WHERE parentFk IS NULL; - - myLoop: LOOP - SET vGeoFk = NULL; - SELECT geoFk INTO vGeoFk - FROM tmp.zoneNodes - WHERE NOT isChecked - LIMIT 1; - - CALL zone_getLeaves(vSelf, vGeoFk, NULL, TRUE); - UPDATE tmp.zoneNodes - SET isChecked = TRUE - WHERE geoFk = vGeoFk; - - IF vGeoFk IS NULL THEN - LEAVE myLoop; - END IF; - END LOOP; - - DELETE FROM tmp.zoneNodes - WHERE sons > 0; +BEGIN +/** + * Devuelve los códigos postales incluidos en una zona + */ + DECLARE vGeoFk INT DEFAULT NULL; + + CREATE OR REPLACE TEMPORARY TABLE tmp.zoneNodes ( + geoFk INT, + name VARCHAR(100), + parentFk INT, + sons INT, + isChecked BOOL DEFAULT 0, + zoneFk INT, + PRIMARY KEY zoneNodesPk (zoneFk, geoFk), + INDEX(geoFk)) + ENGINE = MEMORY; + + CALL zone_getLeaves(vSelf, NULL , NULL, TRUE); + + UPDATE tmp.zoneNodes + SET isChecked = 0 + WHERE parentFk IS NULL; + + myLoop: LOOP + SET vGeoFk = NULL; + SELECT geoFk INTO vGeoFk + FROM tmp.zoneNodes + WHERE NOT isChecked + LIMIT 1; + + CALL zone_getLeaves(vSelf, vGeoFk, NULL, TRUE); + UPDATE tmp.zoneNodes + SET isChecked = TRUE + WHERE geoFk = vGeoFk; + + IF vGeoFk IS NULL THEN + LEAVE myLoop; + END IF; + END LOOP; + + DELETE FROM tmp.zoneNodes + WHERE sons > 0; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; From 108a62f73870e319ce1aab5132a317101fe4f817 Mon Sep 17 00:00:00 2001 From: guillermo Date: Thu, 4 Jul 2024 09:32:56 +0200 Subject: [PATCH 030/170] refs #7486 Fix tests --- db/routines/vn/procedures/collection_getAssigned.sql | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/db/routines/vn/procedures/collection_getAssigned.sql b/db/routines/vn/procedures/collection_getAssigned.sql index bfaa3096b..947b53229 100644 --- a/db/routines/vn/procedures/collection_getAssigned.sql +++ b/db/routines/vn/procedures/collection_getAssigned.sql @@ -34,10 +34,10 @@ BEGIN pc.collection_assign_lockname INTO vHasTooMuchCollections, vLockName - FROM tCollection tc + FROM tmp.collection c JOIN productionConfig pc; - DROP TEMPORARY TABLE tCollection; + DROP TEMPORARY TABLE tmp.collection; IF vHasTooMuchCollections THEN CALL util.throw('There are pending collections'); From fcec3bc0ae24f5972281e3ce417a650671407b57 Mon Sep 17 00:00:00 2001 From: carlossa Date: Thu, 4 Jul 2024 09:54:09 +0200 Subject: [PATCH 031/170] refs #5525 fix sql accountDetail --- print/templates/reports/sepa-core/sepa-core.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/print/templates/reports/sepa-core/sepa-core.js b/print/templates/reports/sepa-core/sepa-core.js index 96c512a9d..f32fd92e7 100755 --- a/print/templates/reports/sepa-core/sepa-core.js +++ b/print/templates/reports/sepa-core/sepa-core.js @@ -27,7 +27,8 @@ module.exports = { FROM supplierAccount sa JOIN company co ON co.supplierAccountFk = sa.id JOIN supplier s ON sa.supplierFk = s.id - WHERE co.id = ?`) [this.companyId]; + WHERE co.id = ? + AND ad.accountDetailTypeFk = 3`) [this.companyId]; } } From cf7de14de6e5c9babc89d70c20224aa96c665c3f Mon Sep 17 00:00:00 2001 From: guillermo Date: Thu, 4 Jul 2024 11:34:55 +0200 Subject: [PATCH 032/170] refs #6769 Changes, with error no database selected --- db/routines/vn/procedures/item_getBalance.sql | 95 ++++++++----------- 1 file changed, 38 insertions(+), 57 deletions(-) diff --git a/db/routines/vn/procedures/item_getBalance.sql b/db/routines/vn/procedures/item_getBalance.sql index 561957452..dc4e16789 100644 --- a/db/routines/vn/procedures/item_getBalance.sql +++ b/db/routines/vn/procedures/item_getBalance.sql @@ -61,29 +61,11 @@ BEGIN JOIN itemType it ON it.id = i.typeFk HAVING ended >= COALESCE(vDated, vDateInventory) OR life IS NULL; - CREATE OR REPLACE TEMPORARY TABLE tItemDiary( - shipped DATE, - `in` INT(11), - `out` INT(11), - alertLevel INT(11), - stateName VARCHAR(20), - `name` VARCHAR(50), - reference VARCHAR(50), - origin INT(11), - clientFk INT(11), - isPicked INT(11), - isTicket TINYINT(1), - lineFk INT(11), - `order` TINYINT(3) UNSIGNED, - clientType VARCHAR(20), - claimFk INT(10) UNSIGNED, - inventorySupplierFk INT(10), - orderFk INT(10) UNSIGNED - ) ENGINE = MEMORY; - - INSERT INTO tItemDiary + CREATE OR REPLACE TEMPORARY TABLE tItemDiary + ENGINE = MEMORY WITH entriesIn AS ( - SELECT tr.landed shipped, + SELECT 'entry' `type`, + tr.landed shipped, b.quantity `in`, NULL `out`, st.alertLevel , @@ -98,13 +80,12 @@ BEGIN NULL `order`, NULL clientType, NULL claimFk, - vSupplierInventoryFk inventorySupplierFk, - NULL orderFk + vSupplierInventoryFk inventorySupplierFk FROM vn.buy b JOIN vn.entry e ON e.id = b.entryFk JOIN vn.travel tr ON tr.id = e.travelFk JOIN vn.supplier s ON s.id = e.supplierFk - JOIN vn.state st ON st.`code` = IF( tr.landed < util.VN_CURDATE() + JOIN vn.state st ON st.`code` = IF(tr.landed < util.VN_CURDATE() OR (util.VN_CURDATE() AND tr.isReceived), 'DELIVERED', 'FREE') @@ -116,7 +97,8 @@ BEGIN AND NOT e.isRaid ), entriesOut AS ( - SELECT tr.shipped, + SELECT 'entry', + tr.shipped, NULL, b.quantity, st.alertLevel, @@ -131,8 +113,7 @@ BEGIN NULL `order`, NULL clientType, NULL claimFk, - vSupplierInventoryFk, - NULL orderFk + vSupplierInventoryFk FROM vn.buy b JOIN vn.entry e ON e.id = b.entryFk JOIN vn.travel tr ON tr.id = e.travelFk @@ -180,7 +161,8 @@ BEGIN AND s.itemFk = vItemFk AND vWarehouseFk = t.warehouseFk ) - SELECT s.shipped, + SELECT 'ticket', + s.shipped, NULL `in`, s.quantity, s.alertLevel, @@ -195,8 +177,7 @@ BEGIN s.`order`, s.typeFk, s.claimFk, - NULL, - NULL orderFk + NULL FROM itemSales s LEFT JOIN vn.state stPrep ON stPrep.`code` = 'PREPARED' LEFT JOIN vn.saleTracking stk ON stk.saleFk = s.saleFk @@ -204,23 +185,23 @@ BEGIN GROUP BY s.saleFk ), orders AS ( - SELECT r.shipment, + SELECT 'order' `type`, + r.shipment, NULL 'in', r.amount, NULL alertLevel, NULL stateName, - NULL, + c.name, NULL invoiceNumber, - NULL entryFk, - NULL supplierFk, + o.id origin, + c.id, FALSE, FALSE isTicket, NULL buyFk, NULL 'order', c.typeFk, NULL claimFk, - NULL inventorySupplierFk, - o.id + NULL FROM hedera.orderRow r JOIN hedera.`order` o ON o.id = r.orderFk JOIN tItemRange ir ON ir.itemFk = r.itemFk @@ -252,7 +233,8 @@ BEGIN SET @currentLineFk := 0; SET @shipped := ''; - SELECT DATE(@shipped:= t.shipped) shipped, + SELECT t.type, + DATE(@shipped:= t.shipped) shipped, t.alertLevel, t.stateName, t.origin, @@ -271,8 +253,7 @@ BEGIN t.isPicked, t.clientType, t.claimFk, - t.`order`, - t.orderFk + t.`order` FROM tItemDiary t LEFT JOIN alertLevel a ON a.id = t.alertLevel; ELSE @@ -280,26 +261,27 @@ BEGIN FROM tItemDiary WHERE shipped < vDated; - SELECT vDated shipped, - 0 alertLevel, - 0 stateName, - 0 origin, - '' reference, - 0 clientFk, + SELECT NULL `type`, + vDated shipped, + NULL alertLevel, + NULL stateName, + NULL origin, + NULL reference, + NULL clientFk, 'Inventario calculado', @a invalue, NULL `out`, @a balance, - 0 lastPreparedLineFk, - 0 isTicket, - 0 lineFk, - 0 isPicked, - 0 clientType, - 0 claimFk, - NULL `order`, - 0 orderFk + NULL lastPreparedLineFk, + NULL isTicket, + NULL lineFk, + NULL isPicked, + NULL clientType, + NULL claimFk, + NULL `order` UNION ALL - SELECT shipped, + SELECT `type`, + shipped, alertlevel, stateName, origin, @@ -314,8 +296,7 @@ BEGIN isPicked, clientType, claimFk, - `order`, - orderFk + `order` FROM tItemDiary WHERE shipped >= vDated; END IF; From 1fff3aa681acf5789975d1fad1a4ec051c9baa47 Mon Sep 17 00:00:00 2001 From: robert Date: Thu, 4 Jul 2024 12:34:56 +0200 Subject: [PATCH 033/170] feat: refs #7670 addSale --- modules/ticket/back/methods/ticket/addSale.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/ticket/back/methods/ticket/addSale.js b/modules/ticket/back/methods/ticket/addSale.js index 8dc7a633c..ad393fc65 100644 --- a/modules/ticket/back/methods/ticket/addSale.js +++ b/modules/ticket/back/methods/ticket/addSale.js @@ -70,7 +70,7 @@ module.exports = Self => { quantity: quantity }, myOptions); - await Self.rawSql('CALL vn.sale_calculateComponent(?, NULL)', [newSale.id], myOptions); + await Self.rawSql('CALL vn.sale_calculateComponent(?, ?)', [newSale.id, 'renewPrices'], myOptions); await Self.rawSql('CALL vn.ticket_recalc(?, NULL)', [id], myOptions); const sale = await models.Sale.findById(newSale.id, { From 776fd0564869de1019dd70df6972585fc894ee66 Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 4 Jul 2024 12:45:52 +0200 Subject: [PATCH 034/170] fix: send rocket after commit cau 199307 --- modules/ticket/back/methods/sale/deleteSales.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/modules/ticket/back/methods/sale/deleteSales.js b/modules/ticket/back/methods/sale/deleteSales.js index 0207815a9..0290b2b9d 100644 --- a/modules/ticket/back/methods/sale/deleteSales.js +++ b/modules/ticket/back/methods/sale/deleteSales.js @@ -66,6 +66,10 @@ module.exports = Self => { promises.push(deletedSale); } + const deletedSales = await Promise.all(promises); + + if (tx) await tx.commit(); + const salesPerson = ticket.client().salesPersonUser(); if (salesPerson) { const url = await Self.app.models.Url.getUrl(); @@ -75,13 +79,9 @@ module.exports = Self => { ticketUrl: `${url}ticket/${ticketId}/sale`, deletions: deletions }); - await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message, myOptions); + await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message); } - const deletedSales = await Promise.all(promises); - - if (tx) await tx.commit(); - return deletedSales; } catch (e) { if (tx) await tx.rollback(); From cf621071d07c849b072173ce1baf718eaa0c1c0c Mon Sep 17 00:00:00 2001 From: carlossa Date: Thu, 4 Jul 2024 16:50:54 +0200 Subject: [PATCH 035/170] refs #5525 fixear sql, fixtures, js --- db/dump/fixtures.before.sql | 15 +++++++++++++++ print/templates/reports/sepa-core/sepa-core.html | 3 +-- print/templates/reports/sepa-core/sepa-core.js | 15 +++++++++------ .../templates/reports/sepa-core/sql/supplier.sql | 14 ++++++++------ 4 files changed, 33 insertions(+), 14 deletions(-) diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index b6275d03c..05c1bbaa7 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -3884,3 +3884,18 @@ INSERT INTO `vn`.`calendarHolidays` (calendarHolidaysTypeFk, dated, calendarHoli (1, '2001-05-17', 1, 5), (1, '2001-05-18', 1, 5); +INSERT INTO vn.accountDetail +(id, value, accountDetailTypeFk, supplierAccountFk) +VALUES + (21, 'ES12345B12345678', 3, 241), + (35, 'ES12346B12345679', 3, 241); + +INSERT INTO vn.accountDetailType +(id, description) +VALUES + (1, 'IBAN'), + (2, 'SWIFT'), + (3, 'Referencia Remesas'), + (4, 'Referencia Transferencias'), + (5, 'Referencia Nominas'), + (6, 'ABA'); diff --git a/print/templates/reports/sepa-core/sepa-core.html b/print/templates/reports/sepa-core/sepa-core.html index 363ebdfe5..e5d14d06c 100644 --- a/print/templates/reports/sepa-core/sepa-core.html +++ b/print/templates/reports/sepa-core/sepa-core.html @@ -27,8 +27,7 @@ {{$t('supplier.identifier')}} -
{{supplier.iban}}
-
{{supplier.nif}}
+
{{supplier.accountDetailValue.join(', ')}}
diff --git a/print/templates/reports/sepa-core/sepa-core.js b/print/templates/reports/sepa-core/sepa-core.js index f32fd92e7..6b941556e 100755 --- a/print/templates/reports/sepa-core/sepa-core.js +++ b/print/templates/reports/sepa-core/sepa-core.js @@ -7,7 +7,11 @@ module.exports = { async serverPrefetch() { this.client = await this.findOneFromDef('client', [this.companyId, this.companyId, this.id]); this.checkMainEntity(this.client); - this.supplier = await this.findOneFromDef('supplier', [this.companyId, this.companyId, this.id]); + const suppliers = await this.rawSqlFromDef('supplier', [this.companyId, this.companyId, this.id]); + this.supplier = { + ...suppliers[0], + accountDetailValue: suppliers.map(val => val?.accountDetailValue) + }; }, props: { id: { @@ -23,12 +27,11 @@ module.exports = { methods: { getSupplierCif() { return db.findOne(` - SELECT sa.iban, s.nif + SELECT DISTINCT ad.value FROM supplierAccount sa - JOIN company co ON co.supplierAccountFk = sa.id - JOIN supplier s ON sa.supplierFk = s.id - WHERE co.id = ? - AND ad.accountDetailTypeFk = 3`) [this.companyId]; + JOIN accountDetail ad ON ad.supplierAccountFk = sa.id + JOIN accountDetailType adt ON adt.id = ad.accountDetailTypeFk AND adt.id = 3 + WHERE sa.supplierFk = ?`) [this.companyId]; } } diff --git a/print/templates/reports/sepa-core/sql/supplier.sql b/print/templates/reports/sepa-core/sql/supplier.sql index 156fc71c0..a49896244 100644 --- a/print/templates/reports/sepa-core/sql/supplier.sql +++ b/print/templates/reports/sepa-core/sql/supplier.sql @@ -1,15 +1,16 @@ SELECT - m.code mandateCode, + m.code AS mandateCode, s.name, s.street, - sc.name country, + sc.name AS country, s.postCode, s.city, - sp.name province, + sp.name AS province, s.nif, sa.iban, sa.supplierFk, - be.name bankName + be.name AS bankName, + ad.value AS accountDetailValue FROM client c LEFT JOIN mandate m ON m.clientFk = c.id AND m.companyFk = ? AND m.finished IS NULL @@ -19,9 +20,10 @@ FROM LEFT JOIN province p ON p.id = c.provinceFk LEFT JOIN supplierAccount sa ON sa.supplierFk = s.id LEFT JOIN bankEntity be ON sa.bankEntityFk = be.id + LEFT JOIN accountDetail ad ON ad.supplierAccountFk = sa.id + LEFT JOIN accountDetailType adt ON adt.id = ad.accountDetailTypeFk AND adt.id = 3 WHERE (m.companyFk = ? OR m.companyFk IS NULL) AND (c.id = ? OR (c.id IS NULL AND c.countryFk = sa.countryFk)) ORDER BY - m.created DESC -LIMIT 1; + m.created DESC; From 64f5ad0e1960155c66c334a3b893a4a2d55c40fe Mon Sep 17 00:00:00 2001 From: carlossa Date: Thu, 4 Jul 2024 16:54:57 +0200 Subject: [PATCH 036/170] refs #5525 remove AS --- print/templates/reports/sepa-core/sql/supplier.sql | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/print/templates/reports/sepa-core/sql/supplier.sql b/print/templates/reports/sepa-core/sql/supplier.sql index a49896244..a32d311de 100644 --- a/print/templates/reports/sepa-core/sql/supplier.sql +++ b/print/templates/reports/sepa-core/sql/supplier.sql @@ -1,16 +1,16 @@ SELECT - m.code AS mandateCode, + m.code mandateCode, s.name, s.street, - sc.name AS country, + sc.name country, s.postCode, s.city, - sp.name AS province, + sp.name province, s.nif, sa.iban, sa.supplierFk, - be.name AS bankName, - ad.value AS accountDetailValue + be.name bankName, + ad.value accountDetailValue FROM client c LEFT JOIN mandate m ON m.clientFk = c.id AND m.companyFk = ? AND m.finished IS NULL From 6f0196d656fb8ffcdcfb20bc4979f9a23bc8a963 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 5 Jul 2024 07:06:40 +0200 Subject: [PATCH 037/170] refs #6769 Changes --- db/routines/vn/procedures/item_getBalance.sql | 57 ++++++++++--------- 1 file changed, 31 insertions(+), 26 deletions(-) diff --git a/db/routines/vn/procedures/item_getBalance.sql b/db/routines/vn/procedures/item_getBalance.sql index dc4e16789..c2e0bc0c1 100644 --- a/db/routines/vn/procedures/item_getBalance.sql +++ b/db/routines/vn/procedures/item_getBalance.sql @@ -6,13 +6,11 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_getBalance`( ) BEGIN /** - * Calcula el disponible. + * Calcula el balance de un artículo. * * @vItemFk Id de artículo * @vWarehouseFk Id de almacén - * @vDated Fecha - * Si la fecha es NULL, muestra el histórico desde el inventario. - * Si la fecha no es NULL, muestra histórico desde la fecha de vDated. + * @vDated Fecha a calcular, si es NULL muestra el histórico desde el inventario */ DECLARE vDateInventory DATETIME; DECLARE vLifeScope DATE; @@ -64,7 +62,8 @@ BEGIN CREATE OR REPLACE TEMPORARY TABLE tItemDiary ENGINE = MEMORY WITH entriesIn AS ( - SELECT 'entry' `type`, + SELECT 'entry' originType, + e.id origin, tr.landed shipped, b.quantity `in`, NULL `out`, @@ -72,8 +71,8 @@ BEGIN st.name stateName, s.name `name`, e.invoiceNumber reference, - e.id origin, - s.id clientFk, + 'supplier' entityType, + s.id entity, IF(st.`code` = 'DELIVERED', TRUE, FALSE) isPicked, FALSE isTicket, b.id lineFk, @@ -98,6 +97,7 @@ BEGIN ), entriesOut AS ( SELECT 'entry', + e.id originType, tr.shipped, NULL, b.quantity, @@ -105,8 +105,8 @@ BEGIN st.name stateName, s.name, e.invoiceNumber, - e.id entryFk, - s.id supplierFk, + 'supplier' entityType, + s.id entity, IF(st.`code` = 'DELIVERED' , TRUE, FALSE), FALSE isTicket, b.id, @@ -123,7 +123,6 @@ BEGIN OR (tr.shipped = util.VN_CURDATE() AND tr.isReceived), 'DELIVERED', 'FREE') - JOIN vn.entryConfig ec WHERE tr.shipped >= vDateInventory AND vWarehouseFk = tr.warehouseOutFk AND (s.id <> vSupplierInventoryFk OR vDated IS NULL) @@ -141,7 +140,8 @@ BEGIN t.nickname, t.refFk, t.id ticketFk, - t.clientFk, + 'client' entityType, + t.clientFk entity, s.id saleFk, st.`order`, c.typeFk, @@ -162,6 +162,7 @@ BEGIN AND vWarehouseFk = t.warehouseFk ) SELECT 'ticket', + s.ticketFk, s.shipped, NULL `in`, s.quantity, @@ -169,8 +170,8 @@ BEGIN s.name, s.nickname, s.refFk, - s.ticketFk, - s.clientFk, + s.entityType, + s.entity, IF(stk.saleFk, TRUE, FALSE), TRUE, s.saleFk, @@ -185,7 +186,8 @@ BEGIN GROUP BY s.saleFk ), orders AS ( - SELECT 'order' `type`, + SELECT 'order' originType, + o.id origin, r.shipment, NULL 'in', r.amount, @@ -193,7 +195,7 @@ BEGIN NULL stateName, c.name, NULL invoiceNumber, - o.id origin, + 'client' entityType, c.id, FALSE, FALSE isTicket, @@ -220,7 +222,7 @@ BEGIN UNION ALL SELECT * FROM orders ORDER BY shipped, - (inventorySupplierFk = clientFk) DESC, + (inventorySupplierFk = entity) DESC, alertLevel DESC, isTicket, `order` DESC, @@ -233,13 +235,14 @@ BEGIN SET @currentLineFk := 0; SET @shipped := ''; - SELECT t.type, + SELECT t.originType, + t.origin, DATE(@shipped:= t.shipped) shipped, t.alertLevel, t.stateName, - t.origin, t.reference, - t.clientFk, + t.entityType, + t.entity, t.name, t.`in` invalue, t.`out`, @@ -261,13 +264,14 @@ BEGIN FROM tItemDiary WHERE shipped < vDated; - SELECT NULL `type`, + SELECT NULL originType, + NULL origin, vDated shipped, NULL alertLevel, NULL stateName, - NULL origin, NULL reference, - NULL clientFk, + NULL entityType, + NULL entity, 'Inventario calculado', @a invalue, NULL `out`, @@ -280,13 +284,14 @@ BEGIN NULL claimFk, NULL `order` UNION ALL - SELECT `type`, + SELECT originType, + origin, shipped, alertlevel, stateName, - origin, - reference, - clientFk, + reference, + entityType, + entity, name, `in`, `out`, @a := @a + IFNULL(`in`, 0) - IFNULL(`out`, 0), From 50c9ded103a66f7b667f6ec0f4da4ccfe71e5a86 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 5 Jul 2024 08:38:40 +0200 Subject: [PATCH 038/170] refs #6769 Fix --- db/routines/vn/procedures/item_getBalance.sql | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/db/routines/vn/procedures/item_getBalance.sql b/db/routines/vn/procedures/item_getBalance.sql index c2e0bc0c1..a12397aa6 100644 --- a/db/routines/vn/procedures/item_getBalance.sql +++ b/db/routines/vn/procedures/item_getBalance.sql @@ -34,7 +34,8 @@ BEGIN END IF; -- Calcula el ultimo dia de vida para cada producto - CREATE OR REPLACE TEMPORARY TABLE tItemRange + -- Tiene tmp a propósito, porque si no falla al utilizarlo en el WITH + CREATE OR REPLACE TEMPORARY TABLE tmp.itemRange (PRIMARY KEY (itemFk)) ENGINE = MEMORY SELECT i.id itemFk, @@ -206,7 +207,7 @@ BEGIN NULL FROM hedera.orderRow r JOIN hedera.`order` o ON o.id = r.orderFk - JOIN tItemRange ir ON ir.itemFk = r.itemFk + JOIN tmp.itemRange ir ON ir.itemFk = r.itemFk JOIN vn.client c ON c.id = o.customer_id WHERE r.shipment >= vDateInventory AND (ir.ended IS NULL OR r.shipment <= ir.ended) @@ -308,6 +309,6 @@ BEGIN DROP TEMPORARY TABLE tItemDiary, - tItemRange; + tmp.itemRange; END$$ DELIMITER ; From 859f610f43a1760631bd24bc16fe013b3ea8a526 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Fri, 5 Jul 2024 08:43:45 +0200 Subject: [PATCH 039/170] hotFix itemNewer refs #6964 --- .../methods/item-shelving/getListItemNewer.js | 2 +- .../specs/getListItemNewer.spec.js | 25 +++++-------------- 2 files changed, 7 insertions(+), 20 deletions(-) diff --git a/modules/item/back/methods/item-shelving/getListItemNewer.js b/modules/item/back/methods/item-shelving/getListItemNewer.js index 1702bb05b..dafefe712 100644 --- a/modules/item/back/methods/item-shelving/getListItemNewer.js +++ b/modules/item/back/methods/item-shelving/getListItemNewer.js @@ -63,7 +63,7 @@ module.exports = Self => { FROM tItemShelving ti JOIN tItemInSector tis ON tis.itemFk = ti.itemFk JOIN vn.productionConfig pc - WHERE ti.created > tis.created + INTERVAL pc.itemOlderReviewHours HOUR;`, + WHERE ti.created + INTERVAL pc.itemOlderReviewHours HOUR < tis.created ;`, [shelvingFk, shelvingFk], myOptions); return result; }; diff --git a/modules/item/back/methods/item-shelving/specs/getListItemNewer.spec.js b/modules/item/back/methods/item-shelving/specs/getListItemNewer.spec.js index 15c480992..9287a179d 100644 --- a/modules/item/back/methods/item-shelving/specs/getListItemNewer.spec.js +++ b/modules/item/back/methods/item-shelving/specs/getListItemNewer.spec.js @@ -2,30 +2,17 @@ const {models} = require('vn-loopback/server/server'); describe('itemShelving getListItemNewer()', () => { - it('should return true because there is an older item', async() => { - const shelving = 'NCC'; - const parking = 'A-47-1'; + fit('should return true because there is an older item', async() => { + const shelving = 'NBB'; + const parking = '700-01'; - const sectorCamHighCode = 'CAMARA SECTOR D'; - const sectorCamCode = 'NAVE ALGEMESI'; - - const sectorCamCodeHighId = 1; - const sectorCamCodeId = 9991; + const sectorCamHighCode = 'FIRST'; + const sectorCamCode = 'NS'; const tx = await models.Sector.beginTransaction({}); const myOptions = {transaction: tx}; try { - const sectorHighCam = await models.Sector.findById(sectorCamCodeHighId, null, myOptions); - await sectorHighCam.updateAttributes({ - code: sectorCamHighCode - }); - - const sectorCam = await models.Sector.findById(sectorCamCodeId, null, myOptions); - await sectorCam.updateAttributes({ - code: sectorCamCode - }); - const config = await models.ProductionConfig.findOne(); await config.updateAttributes({ @@ -35,7 +22,7 @@ describe('itemShelving getListItemNewer()', () => { const result = await models.ItemShelving.getListItemNewer(shelving, parking, myOptions); - expect(result.length).toEqual(2); + expect(result.length).toEqual(3); await tx.rollback(); } catch (e) { await tx.rollback(); From 159f2f5f1c4b73a48fc994c1a17d97a48038e1b6 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Fri, 5 Jul 2024 08:44:09 +0200 Subject: [PATCH 040/170] hotFix itemNewer refs #6964 --- .../back/methods/item-shelving/specs/getListItemNewer.spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/item/back/methods/item-shelving/specs/getListItemNewer.spec.js b/modules/item/back/methods/item-shelving/specs/getListItemNewer.spec.js index 9287a179d..962863095 100644 --- a/modules/item/back/methods/item-shelving/specs/getListItemNewer.spec.js +++ b/modules/item/back/methods/item-shelving/specs/getListItemNewer.spec.js @@ -2,7 +2,7 @@ const {models} = require('vn-loopback/server/server'); describe('itemShelving getListItemNewer()', () => { - fit('should return true because there is an older item', async() => { + it('should return true because there is an older item', async() => { const shelving = 'NBB'; const parking = '700-01'; From e3db143b443c7ecdc1412b7627c120a05d534207 Mon Sep 17 00:00:00 2001 From: jgallego Date: Fri, 5 Jul 2024 08:55:24 +0200 Subject: [PATCH 041/170] feat: refs #7348 campo en json --- modules/client/back/models/client.json | 3 +++ 1 file changed, 3 insertions(+) diff --git a/modules/client/back/models/client.json b/modules/client/back/models/client.json index f3eb9919b..f24f69ae7 100644 --- a/modules/client/back/models/client.json +++ b/modules/client/back/models/client.json @@ -144,6 +144,9 @@ }, "recommendedCredit": { "type": "number" + }, + "hasDailyInvoice": { + "type": "boolean" } }, From 923efadf6a760bbeb207e096acf20861cc83bc50 Mon Sep 17 00:00:00 2001 From: robert Date: Fri, 5 Jul 2024 09:00:40 +0200 Subject: [PATCH 042/170] fix: refs #6371 restore table Series --- db/dump/.dump/structure.sql | 44 +++++++++---------- .../11134-silverRaphis/00-firstScript.sql | 42 ++++++++++++++++++ 2 files changed, 64 insertions(+), 22 deletions(-) create mode 100644 db/versions/11134-silverRaphis/00-firstScript.sql diff --git a/db/dump/.dump/structure.sql b/db/dump/.dump/structure.sql index 6797c01a5..5755ce085 100644 --- a/db/dump/.dump/structure.sql +++ b/db/dump/.dump/structure.sql @@ -19,7 +19,7 @@ -- Current Database: `account` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `account` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci */; +CREATE DATABASE /*!32312 */ `account` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci */; USE `account`; @@ -2230,7 +2230,7 @@ DELIMITER ; -- Current Database: `bi` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `bi` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `bi` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `bi`; @@ -4000,7 +4000,7 @@ DELIMITER ; -- Current Database: `bs` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `bs` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `bs` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `bs`; @@ -6967,7 +6967,7 @@ DELIMITER ; -- Current Database: `cache` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `cache` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `cache` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `cache`; @@ -8087,7 +8087,7 @@ DELIMITER ; -- Current Database: `dipole` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `dipole` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `dipole` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `dipole`; @@ -8316,7 +8316,7 @@ DELIMITER ; -- Current Database: `edi` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `edi` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `edi` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `edi`; @@ -11054,7 +11054,7 @@ DELIMITER ; -- Current Database: `floranet` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `floranet` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `floranet` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `floranet`; @@ -11638,7 +11638,7 @@ DELIMITER ; -- Current Database: `hedera` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `hedera` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `hedera` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `hedera`; @@ -15833,7 +15833,7 @@ DELIMITER ; -- Current Database: `pbx` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `pbx` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `pbx` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `pbx`; @@ -16499,7 +16499,7 @@ DELIMITER ; -- Current Database: `psico` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `psico` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `psico` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `psico`; @@ -16834,7 +16834,7 @@ DELIMITER ; -- Current Database: `sage` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `sage` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci */; +CREATE DATABASE /*!32312 */ `sage` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci */; USE `sage`; @@ -19146,7 +19146,7 @@ DELIMITER ; -- Current Database: `salix` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `salix` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `salix` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `salix`; @@ -19440,7 +19440,7 @@ DELIMITER ; -- Current Database: `srt` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `srt` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `srt` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `srt`; @@ -22991,7 +22991,7 @@ DELIMITER ; -- Current Database: `stock` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `stock` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci */; +CREATE DATABASE /*!32312 */ `stock` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci */; USE `stock`; @@ -24069,7 +24069,7 @@ DELIMITER ; -- Current Database: `tmp` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `tmp` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `tmp` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `tmp`; @@ -24147,7 +24147,7 @@ DELIMITER ; -- Current Database: `util` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `util` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `util` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `util`; @@ -26252,7 +26252,7 @@ DELIMITER ; -- Current Database: `vn` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `vn` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `vn` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `vn`; @@ -63220,7 +63220,7 @@ BEGIN * @param vDate -> Date of the purchase operation. * @param vWarehouseFk -> Identifier of the warehouse (warehouseId). */ - ALTER TABLE tmp.itemInventory ADD IF NOT EXISTS buy_id INT; + ALTER TABLE tmp.itemInventory ADD buy_id INT; CALL buyUltimate(vWarehouseFk, vDate); @@ -68883,7 +68883,7 @@ proc: BEGIN CALL zone_getLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk, TRUE); - IF NOT EXISTS (SELECT TRUE FROM tmp.zoneGetLanded LIMIT 1) THEN + (SELECT TRUE FROM tmp.zoneGetLanded LIMIT 1) THEN CALL util.throw(CONCAT('There is no zone for these parameters ', vTicketFk)); END IF; @@ -77852,11 +77852,11 @@ BEGIN IF vWorkerFk THEN CALL timeControl_calculateByUser(vWorkerFk, vDatedFrom , vDatedTimeTo); - CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` + CREATE TEMPORARY TABLE tmp.`user` SELECT vWorkerFk userFk; ELSE CALL timeControl_calculateAll(vDatedFrom, vDatedTimeTo); - CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` + CREATE TEMPORARY TABLE tmp.`user` SELECT id userFk FROM worker w; END IF; @@ -81544,7 +81544,7 @@ DELIMITER ; -- Current Database: `vn2008` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `vn2008` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `vn2008` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `vn2008`; diff --git a/db/versions/11134-silverRaphis/00-firstScript.sql b/db/versions/11134-silverRaphis/00-firstScript.sql new file mode 100644 index 000000000..0836abe4e --- /dev/null +++ b/db/versions/11134-silverRaphis/00-firstScript.sql @@ -0,0 +1,42 @@ +USE `vn`; + +CREATE TABLE IF NOT EXISTS vn.`tillSerial` ( + `code` varchar(2) COLLATE utf8mb3_unicode_ci NOT NULL, + `description` varchar(30) COLLATE utf8mb3_unicode_ci DEFAULT NULL, + `account` varchar(10) COLLATE utf8mb3_unicode_ci DEFAULT NULL, + PRIMARY KEY (`code`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; + +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES(' S', 'Saldos final / inicial', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('A', 'Factura cliente', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('B', 'Factura cliente', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('C', 'Facturas Contado', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('CC', 'Cuadre caja', '6780000000'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('CD', 'Cuenta Director Comercial', '5510000002'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('CH', 'Cheques', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('CM', 'Cambio', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('CR', 'Ingreso/Reintegro Caja Rural', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('CT', 'Correos y telégrafos', '6290000005'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('DC', 'Dietas conductores', '6290000010'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('DH', 'Deudas Holland', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('DT', 'Dietas', '6290000011'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('E', 'Entrada mercancia', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('EN', 'Enric Martinez', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('GC', 'Cuenta con dto. Comercial', '5510000003'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('GP', 'Gastos de personal', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('GR', 'Gastos RRPP dpto comercial', '6290001002'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('GS', 'Gasoil', '6280000002'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('GV', 'Gastos viaje', '6290001000'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('JV', 'Juanvi', '6290000553'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('MB', 'Movimiento bancario', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('MP', 'Materias Primas', '6000000000'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('OG', 'Otros gastos', '6290000000'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('PM', 'Pequeño material', '6290000007'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('R', 'Factura proveedor', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('RC', 'Ingreso/Reintegro Ruralcaja', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('RN', 'Reparación nave', '6220000004'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('SS', 'Gastos Silla', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('T', 'Ticket', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('TA', 'Factura rapida', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('TC', 'Ticket contado', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('TR', 'Traspaso', NULL); \ No newline at end of file From d4b4c0fafe9397d8389586dbecebbae8d8d73ec2 Mon Sep 17 00:00:00 2001 From: jgallego Date: Fri, 5 Jul 2024 09:04:38 +0200 Subject: [PATCH 043/170] feat: refs #7348 campos a modificar --- modules/client/back/methods/client/updateFiscalData.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/modules/client/back/methods/client/updateFiscalData.js b/modules/client/back/methods/client/updateFiscalData.js index 851648658..8ed55b856 100644 --- a/modules/client/back/methods/client/updateFiscalData.js +++ b/modules/client/back/methods/client/updateFiscalData.js @@ -99,6 +99,10 @@ module.exports = Self => { { arg: 'hasElectronicInvoice', type: 'boolean' + }, + { + arg: 'hasDailyInvoice', + type: 'boolean' } ], returns: { @@ -117,8 +121,6 @@ module.exports = Self => { const myOptions = {}; const models = Self.app.models; const args = ctx.args; - const userId = ctx.req.accessToken.userId; - const $t = ctx.req.__; if (typeof options == 'object') Object.assign(myOptions, options); From 27a4b747b5595a50087b34ae0fa866612bd09d0b Mon Sep 17 00:00:00 2001 From: robert Date: Fri, 5 Jul 2024 09:05:39 +0200 Subject: [PATCH 044/170] fix: refs #6371 restore table Series --- .../11134-silverRaphis/00-firstScript.sql | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 db/versions/11134-silverRaphis/00-firstScript.sql diff --git a/db/versions/11134-silverRaphis/00-firstScript.sql b/db/versions/11134-silverRaphis/00-firstScript.sql new file mode 100644 index 000000000..0836abe4e --- /dev/null +++ b/db/versions/11134-silverRaphis/00-firstScript.sql @@ -0,0 +1,42 @@ +USE `vn`; + +CREATE TABLE IF NOT EXISTS vn.`tillSerial` ( + `code` varchar(2) COLLATE utf8mb3_unicode_ci NOT NULL, + `description` varchar(30) COLLATE utf8mb3_unicode_ci DEFAULT NULL, + `account` varchar(10) COLLATE utf8mb3_unicode_ci DEFAULT NULL, + PRIMARY KEY (`code`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; + +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES(' S', 'Saldos final / inicial', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('A', 'Factura cliente', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('B', 'Factura cliente', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('C', 'Facturas Contado', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('CC', 'Cuadre caja', '6780000000'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('CD', 'Cuenta Director Comercial', '5510000002'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('CH', 'Cheques', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('CM', 'Cambio', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('CR', 'Ingreso/Reintegro Caja Rural', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('CT', 'Correos y telégrafos', '6290000005'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('DC', 'Dietas conductores', '6290000010'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('DH', 'Deudas Holland', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('DT', 'Dietas', '6290000011'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('E', 'Entrada mercancia', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('EN', 'Enric Martinez', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('GC', 'Cuenta con dto. Comercial', '5510000003'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('GP', 'Gastos de personal', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('GR', 'Gastos RRPP dpto comercial', '6290001002'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('GS', 'Gasoil', '6280000002'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('GV', 'Gastos viaje', '6290001000'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('JV', 'Juanvi', '6290000553'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('MB', 'Movimiento bancario', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('MP', 'Materias Primas', '6000000000'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('OG', 'Otros gastos', '6290000000'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('PM', 'Pequeño material', '6290000007'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('R', 'Factura proveedor', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('RC', 'Ingreso/Reintegro Ruralcaja', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('RN', 'Reparación nave', '6220000004'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('SS', 'Gastos Silla', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('T', 'Ticket', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('TA', 'Factura rapida', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('TC', 'Ticket contado', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('TR', 'Traspaso', NULL); \ No newline at end of file From aa46d7a53659188933d6cc4a1307f6961f74f168 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 5 Jul 2024 09:46:09 +0200 Subject: [PATCH 045/170] refs #6769 item_getBalance optimization --- db/routines/vn/procedures/item_getBalance.sql | 68 +++++++++++-------- .../11135-whiteErica/00-firstScript.sql | 1 + 2 files changed, 39 insertions(+), 30 deletions(-) create mode 100644 db/versions/11135-whiteErica/00-firstScript.sql diff --git a/db/routines/vn/procedures/item_getBalance.sql b/db/routines/vn/procedures/item_getBalance.sql index a12397aa6..15be8c926 100644 --- a/db/routines/vn/procedures/item_getBalance.sql +++ b/db/routines/vn/procedures/item_getBalance.sql @@ -21,14 +21,14 @@ BEGIN FROM config c JOIN util.config uc; - SELECT COALESCE(vDated, vDateInventory) - INTERVAL MAX(life) DAY + SELECT vDateInventory - INTERVAL MAX(life) DAY INTO vLifeScope FROM itemType; SELECT warehouseOutFk, supplierFk INTO vWarehouseInventoryFk, vSupplierInventoryFk FROM inventoryConfig; - + IF NOT vWarehouseInventoryFk OR NOT vSupplierInventoryFk THEN CALL util.throw('Config variables are not set'); END IF; @@ -50,30 +50,32 @@ BEGIN JOIN warehouse w ON w.id = t.warehouseInFk JOIN item i ON i.id = b.itemFk JOIN itemType it ON it.id = i.typeFk - WHERE t.landed BETWEEN vLifeScope AND COALESCE(vDated, vDateInventory) + WHERE t.landed BETWEEN vLifeScope AND vDateInventory AND t.warehouseInFk = vWarehouseFk AND t.warehouseOutFk <> vWarehouseInventoryFk AND it.life + AND i.id = vItemFk AND NOT e.isExcludedFromAvailable GROUP BY b.itemFk ) c ON i.id = c.itemFk JOIN itemType it ON it.id = i.typeFk - HAVING ended >= COALESCE(vDated, vDateInventory) OR life IS NULL; + WHERE i.id = vItemFk + HAVING ended >= vDateInventory OR life IS NULL; CREATE OR REPLACE TEMPORARY TABLE tItemDiary ENGINE = MEMORY WITH entriesIn AS ( SELECT 'entry' originType, - e.id origin, + e.id originId, tr.landed shipped, b.quantity `in`, NULL `out`, st.alertLevel , st.name stateName, - s.name `name`, e.invoiceNumber reference, 'supplier' entityType, - s.id entity, + s.id entityId, + s.name entityName, IF(st.`code` = 'DELIVERED', TRUE, FALSE) isPicked, FALSE isTicket, b.id lineFk, @@ -104,10 +106,10 @@ BEGIN b.quantity, st.alertLevel, st.name stateName, - s.name, e.invoiceNumber, 'supplier' entityType, - s.id entity, + s.id entityId, + s.name, IF(st.`code` = 'DELIVERED' , TRUE, FALSE), FALSE isTicket, b.id, @@ -125,7 +127,7 @@ BEGIN 'DELIVERED', 'FREE') WHERE tr.shipped >= vDateInventory - AND vWarehouseFk = tr.warehouseOutFk + AND tr.warehouseOutFk = vWarehouseFk AND (s.id <> vSupplierInventoryFk OR vDated IS NULL) AND b.itemFk = vItemFk AND NOT e.isExcludedFromAvailable @@ -138,29 +140,30 @@ BEGIN s.quantity, st2.alertLevel, st2.name, - t.nickname, t.refFk, t.id ticketFk, 'client' entityType, - t.clientFk entity, + t.clientFk entityId, + t.nickname, s.id saleFk, st.`order`, c.typeFk, cb.claimFk FROM vn.sale s JOIN vn.ticket t ON t.id = s.ticketFk - LEFT JOIN vn.ticketState ts ON ts.ticketFk = t.id - LEFT JOIN vn.state st ON st.`code` = ts.`code` + LEFT JOIN vn.ticketLastState tls ON tls.ticketFk = t.id + LEFT JOIN vn.ticketTracking tt ON tt.id = tls.ticketTrackingFk + LEFT JOIN vn.state st ON st.id = tt.stateFk JOIN vn.client c ON c.id = t.clientFk JOIN vn.state st2 ON st2.`code` = IF(t.shipped < util.VN_CURDATE(), 'DELIVERED', IF (t.shipped > util.dayEnd(util.VN_CURDATE()), 'FREE', - IFNULL(ts.code, 'FREE'))) - LEFT JOIN vn.claimBeginning cb ON s.id = cb.saleFk + IFNULL(st.code, 'FREE'))) + LEFT JOIN vn.claimBeginning cb ON cb.saleFk = s.id WHERE t.shipped >= vDateInventory AND s.itemFk = vItemFk - AND vWarehouseFk = t.warehouseFk + AND t.warehouseFk = vWarehouseFk ) SELECT 'ticket', s.ticketFk, @@ -169,10 +172,10 @@ BEGIN s.quantity, s.alertLevel, s.name, - s.nickname, s.refFk, s.entityType, - s.entity, + s.entityId, + s.nickname, IF(stk.saleFk, TRUE, FALSE), TRUE, s.saleFk, @@ -188,16 +191,16 @@ BEGIN ), orders AS ( SELECT 'order' originType, - o.id origin, + o.id originId, r.shipment, NULL 'in', r.amount, NULL alertLevel, NULL stateName, - c.name, NULL invoiceNumber, 'client' entityType, c.id, + c.name, FALSE, FALSE isTicket, NULL buyFk, @@ -212,6 +215,10 @@ BEGIN WHERE r.shipment >= vDateInventory AND (ir.ended IS NULL OR r.shipment <= ir.ended) AND r.warehouseFk = vWarehouseFk + AND r.created >= ( + SELECT SUBTIME(util.VN_NOW(), reserveTime) + FROM hedera.orderConfig + ) AND NOT o.confirmed AND r.itemFk = vItemFk ) @@ -223,7 +230,7 @@ BEGIN UNION ALL SELECT * FROM orders ORDER BY shipped, - (inventorySupplierFk = entity) DESC, + (inventorySupplierFk = entityId) DESC, alertLevel DESC, isTicket, `order` DESC, @@ -237,14 +244,14 @@ BEGIN SET @shipped := ''; SELECT t.originType, - t.origin, + t.originId, DATE(@shipped:= t.shipped) shipped, t.alertLevel, t.stateName, t.reference, t.entityType, - t.entity, - t.name, + t.entityId, + t.entityName, t.`in` invalue, t.`out`, @a := @a + IFNULL(t.`in`, 0) - IFNULL(t.`out`, 0) balance, @@ -266,13 +273,13 @@ BEGIN WHERE shipped < vDated; SELECT NULL originType, - NULL origin, + NULL originId, vDated shipped, NULL alertLevel, NULL stateName, NULL reference, NULL entityType, - NULL entity, + NULL entityId, 'Inventario calculado', @a invalue, NULL `out`, @@ -286,14 +293,15 @@ BEGIN NULL `order` UNION ALL SELECT originType, - origin, + originId, shipped, alertlevel, stateName, reference, entityType, - entity, - name, `in`, + entityId, + entityName, + `in`, `out`, @a := @a + IFNULL(`in`, 0) - IFNULL(`out`, 0), 0, diff --git a/db/versions/11135-whiteErica/00-firstScript.sql b/db/versions/11135-whiteErica/00-firstScript.sql new file mode 100644 index 000000000..902608a3e --- /dev/null +++ b/db/versions/11135-whiteErica/00-firstScript.sql @@ -0,0 +1 @@ +CREATE INDEX travel_landed_IDX USING BTREE ON vn.travel (landed DESC,warehouseInFk,warehouseOutFk); From 182273d3b387c35cd40d296eceee468381d4ca4a Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 5 Jul 2024 09:59:15 +0200 Subject: [PATCH 046/170] refs #7450 Modified msg throw --- db/routines/vn/procedures/entry_isEditable.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/routines/vn/procedures/entry_isEditable.sql b/db/routines/vn/procedures/entry_isEditable.sql index a05a1fd92..c279fac65 100644 --- a/db/routines/vn/procedures/entry_isEditable.sql +++ b/db/routines/vn/procedures/entry_isEditable.sql @@ -18,7 +18,7 @@ BEGIN AND e.id = vSelf; IF vIsEditable AND NOT IFNULL(@isModeInventory, FALSE) THEN - CALL util.throw('Entry is not editable'); + CALL util.throw(CONCAT('Entry ', vSelf, ' is not editable')); END IF; END$$ DELIMITER ; From 3051e4ed251a7dc25a96efdee607769b79c4f2d7 Mon Sep 17 00:00:00 2001 From: robert Date: Fri, 5 Jul 2024 10:35:32 +0200 Subject: [PATCH 047/170] Merge branch '6371-restoreSeries' of https://gitea.verdnatura.es/verdnatura/salix into 6371-restoreSeries --- db/dump/.dump/structure.sql | 44 ++++++++++++++++++------------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/db/dump/.dump/structure.sql b/db/dump/.dump/structure.sql index 5755ce085..6797c01a5 100644 --- a/db/dump/.dump/structure.sql +++ b/db/dump/.dump/structure.sql @@ -19,7 +19,7 @@ -- Current Database: `account` -- -CREATE DATABASE /*!32312 */ `account` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `account` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci */; USE `account`; @@ -2230,7 +2230,7 @@ DELIMITER ; -- Current Database: `bi` -- -CREATE DATABASE /*!32312 */ `bi` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `bi` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `bi`; @@ -4000,7 +4000,7 @@ DELIMITER ; -- Current Database: `bs` -- -CREATE DATABASE /*!32312 */ `bs` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `bs` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `bs`; @@ -6967,7 +6967,7 @@ DELIMITER ; -- Current Database: `cache` -- -CREATE DATABASE /*!32312 */ `cache` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `cache` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `cache`; @@ -8087,7 +8087,7 @@ DELIMITER ; -- Current Database: `dipole` -- -CREATE DATABASE /*!32312 */ `dipole` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `dipole` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `dipole`; @@ -8316,7 +8316,7 @@ DELIMITER ; -- Current Database: `edi` -- -CREATE DATABASE /*!32312 */ `edi` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `edi` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `edi`; @@ -11054,7 +11054,7 @@ DELIMITER ; -- Current Database: `floranet` -- -CREATE DATABASE /*!32312 */ `floranet` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `floranet` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `floranet`; @@ -11638,7 +11638,7 @@ DELIMITER ; -- Current Database: `hedera` -- -CREATE DATABASE /*!32312 */ `hedera` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `hedera` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `hedera`; @@ -15833,7 +15833,7 @@ DELIMITER ; -- Current Database: `pbx` -- -CREATE DATABASE /*!32312 */ `pbx` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `pbx` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `pbx`; @@ -16499,7 +16499,7 @@ DELIMITER ; -- Current Database: `psico` -- -CREATE DATABASE /*!32312 */ `psico` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `psico` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `psico`; @@ -16834,7 +16834,7 @@ DELIMITER ; -- Current Database: `sage` -- -CREATE DATABASE /*!32312 */ `sage` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `sage` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci */; USE `sage`; @@ -19146,7 +19146,7 @@ DELIMITER ; -- Current Database: `salix` -- -CREATE DATABASE /*!32312 */ `salix` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `salix` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `salix`; @@ -19440,7 +19440,7 @@ DELIMITER ; -- Current Database: `srt` -- -CREATE DATABASE /*!32312 */ `srt` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `srt` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `srt`; @@ -22991,7 +22991,7 @@ DELIMITER ; -- Current Database: `stock` -- -CREATE DATABASE /*!32312 */ `stock` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `stock` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci */; USE `stock`; @@ -24069,7 +24069,7 @@ DELIMITER ; -- Current Database: `tmp` -- -CREATE DATABASE /*!32312 */ `tmp` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `tmp` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `tmp`; @@ -24147,7 +24147,7 @@ DELIMITER ; -- Current Database: `util` -- -CREATE DATABASE /*!32312 */ `util` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `util` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `util`; @@ -26252,7 +26252,7 @@ DELIMITER ; -- Current Database: `vn` -- -CREATE DATABASE /*!32312 */ `vn` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `vn` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `vn`; @@ -63220,7 +63220,7 @@ BEGIN * @param vDate -> Date of the purchase operation. * @param vWarehouseFk -> Identifier of the warehouse (warehouseId). */ - ALTER TABLE tmp.itemInventory ADD buy_id INT; + ALTER TABLE tmp.itemInventory ADD IF NOT EXISTS buy_id INT; CALL buyUltimate(vWarehouseFk, vDate); @@ -68883,7 +68883,7 @@ proc: BEGIN CALL zone_getLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk, TRUE); - (SELECT TRUE FROM tmp.zoneGetLanded LIMIT 1) THEN + IF NOT EXISTS (SELECT TRUE FROM tmp.zoneGetLanded LIMIT 1) THEN CALL util.throw(CONCAT('There is no zone for these parameters ', vTicketFk)); END IF; @@ -77852,11 +77852,11 @@ BEGIN IF vWorkerFk THEN CALL timeControl_calculateByUser(vWorkerFk, vDatedFrom , vDatedTimeTo); - CREATE TEMPORARY TABLE tmp.`user` + CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` SELECT vWorkerFk userFk; ELSE CALL timeControl_calculateAll(vDatedFrom, vDatedTimeTo); - CREATE TEMPORARY TABLE tmp.`user` + CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` SELECT id userFk FROM worker w; END IF; @@ -81544,7 +81544,7 @@ DELIMITER ; -- Current Database: `vn2008` -- -CREATE DATABASE /*!32312 */ `vn2008` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `vn2008` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `vn2008`; From f3f450463b628ac57cb811985e3659519bf0fe70 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Fri, 5 Jul 2024 10:47:26 +0200 Subject: [PATCH 048/170] warmFix getSales refs #6861 --- back/methods/collection/getSales.js | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/back/methods/collection/getSales.js b/back/methods/collection/getSales.js index 8f5bfaeef..a9e5f2e60 100644 --- a/back/methods/collection/getSales.js +++ b/back/methods/collection/getSales.js @@ -60,15 +60,17 @@ module.exports = Self => { if (print) await Self.rawSql('CALL vn.collection_printSticker(?,NULL)', [id], myOptions); for (let ticket of tickets) { - let observations = ticket.observaciones.split(' '); + if (ticket.observaciones) { + let observations = ticket.observaciones.split(' '); - for (let observation of observations) { - const salesPerson = ticket.salesPersonFk; - if (observation.startsWith('#') || observation.startsWith('@')) { - await models.Chat.send(ctx, - observation, - $t('ticketCommercial', {ticket: ticket.ticketFk, salesPerson}) - ); + for (let observation of observations) { + const salesPerson = ticket.salesPersonFk; + if (observation.startsWith('#') || observation.startsWith('@')) { + await models.Chat.send(ctx, + observation, + $t('ticketCommercial', {ticket: ticket.ticketFk, salesPerson}) + ); + } } } } From 1799b52f8b8fc0ac5188c38876aacb3aeb2f5a8d Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 5 Jul 2024 12:37:59 +0200 Subject: [PATCH 049/170] feat: refs #7622 Added type column addressWaste --- db/routines/vn/procedures/item_setVisibleDiscard.sql | 3 ++- db/versions/11136-maroonMedeola/00-firstScript.sql | 6 ++++++ .../models/{addressShortage.json => address-waste.json} | 8 ++++++-- 3 files changed, 14 insertions(+), 3 deletions(-) create mode 100644 db/versions/11136-maroonMedeola/00-firstScript.sql rename modules/client/back/models/{addressShortage.json => address-waste.json} (70%) diff --git a/db/routines/vn/procedures/item_setVisibleDiscard.sql b/db/routines/vn/procedures/item_setVisibleDiscard.sql index 0a6c54971..a44d87333 100644 --- a/db/routines/vn/procedures/item_setVisibleDiscard.sql +++ b/db/routines/vn/procedures/item_setVisibleDiscard.sql @@ -6,7 +6,8 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_setVisibleDisc vAddressFk INT) BEGIN /** - * Procedimiento para dar dar de baja/alta un item, si vAddressFk es NULL se entiende que se da de alta y se toma el addressFk de la configuración + * Procedimiento para dar dar de baja/alta un item, si vAdressFk es NULL + * se entiende que se da de alta y se toma el addressFk de la configuración * * @param vItemFk Identificador del ítem * @param vWarehouseFk id del warehouse diff --git a/db/versions/11136-maroonMedeola/00-firstScript.sql b/db/versions/11136-maroonMedeola/00-firstScript.sql new file mode 100644 index 000000000..09abfe391 --- /dev/null +++ b/db/versions/11136-maroonMedeola/00-firstScript.sql @@ -0,0 +1,6 @@ +RENAME TABLE vn.addressShortage TO vn.addressWaste; +ALTER TABLE vn.addressWaste ADD `type` ENUM('internal', 'external') NOT NULL; +INSERT INTO IGNORE vn.addressWaste (addressFk,`type`) VALUES + (2230,'external'), + (5986,'external'), + (7475,'external'); diff --git a/modules/client/back/models/addressShortage.json b/modules/client/back/models/address-waste.json similarity index 70% rename from modules/client/back/models/addressShortage.json rename to modules/client/back/models/address-waste.json index 1ae8d986c..2d7126eae 100644 --- a/modules/client/back/models/addressShortage.json +++ b/modules/client/back/models/address-waste.json @@ -1,15 +1,19 @@ { - "name": "AddressShortage", + "name": "AddressWaste", "base": "VnModel", "options": { "mysql": { - "table": "addressShortage" + "table": "addressWaste" } }, "properties": { "addressFk": { "type": "number", "id": true + }, + "type": { + "type": "string", + "id": true } }, "relations": { From b9e986c9627c26921e880245e4b7c8c264e55a64 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 5 Jul 2024 12:39:54 +0200 Subject: [PATCH 050/170] feat: refs #7622 Fix --- db/versions/11136-maroonMedeola/00-firstScript.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/versions/11136-maroonMedeola/00-firstScript.sql b/db/versions/11136-maroonMedeola/00-firstScript.sql index 09abfe391..b0b92c7e9 100644 --- a/db/versions/11136-maroonMedeola/00-firstScript.sql +++ b/db/versions/11136-maroonMedeola/00-firstScript.sql @@ -1,6 +1,6 @@ RENAME TABLE vn.addressShortage TO vn.addressWaste; ALTER TABLE vn.addressWaste ADD `type` ENUM('internal', 'external') NOT NULL; -INSERT INTO IGNORE vn.addressWaste (addressFk,`type`) VALUES +INSERT IGNORE INTO vn.addressWaste (addressFk,`type`) VALUES (2230,'external'), (5986,'external'), (7475,'external'); From 8ac26c7281ca26fa9110389783c7128ee90d0967 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 5 Jul 2024 12:50:31 +0200 Subject: [PATCH 051/170] refactor: refs #7640 Refactor multipleInventory --- .../vn/procedures/multipleInventory.sql | 85 ++++++++++--------- 1 file changed, 43 insertions(+), 42 deletions(-) diff --git a/db/routines/vn/procedures/multipleInventory.sql b/db/routines/vn/procedures/multipleInventory.sql index ece57727d..704a93152 100644 --- a/db/routines/vn/procedures/multipleInventory.sql +++ b/db/routines/vn/procedures/multipleInventory.sql @@ -76,52 +76,52 @@ proc: BEGIN GROUP BY itemFk; -- Cálculo del visible - UPDATE tItemInventoryCalc iic - JOIN ( - SELECT itemFk, SUM(quantity) visible - FROM ( - SELECT s.itemFk, s.quantity - FROM sale s - JOIN ticket t ON t.id = s.ticketFk - JOIN warehouse w ON w.id = t.warehouseFk - WHERE t.shipped >= vDate - AND t.shipped < vDateTomorrow - AND (NOT isPicked AND NOT t.isLabeled AND t.refFk IS NULL) - AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk - AND w.isComparative - UNION ALL - SELECT b.itemFk, - b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseInFk - WHERE t.landed = vDate - AND NOT t.isReceived - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk - AND w.isComparative - UNION ALL - SELECT b.itemFk, b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseOutFk - WHERE t.shipped = vDate - AND NOT t.isReceived - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk - AND w.isComparative - ) sub2 - GROUP BY itemFk - ) sub ON sub.itemFk = iic.itemFk - SET iic.visible = iic.visible + sub.visible; + CREATE OR REPLACE TEMPORARY TABLE tItemVisibleCalc + (PRIMARY KEY (itemFk)) + ENGINE = MEMORY + SELECT itemFk, SUM(quantity) visible + FROM ( + SELECT s.itemFk, s.quantity + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + JOIN warehouse w ON w.id = t.warehouseFk + WHERE t.shipped >= vDate + AND t.shipped < vDateTomorrow + AND (NOT isPicked AND NOT t.isLabeled AND t.refFk IS NULL) + AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk + AND w.isComparative + UNION ALL + SELECT b.itemFk, - b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseInFk + WHERE t.landed = vDate + AND NOT t.isReceived + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk + AND w.isComparative + UNION ALL + SELECT b.itemFk, b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseOutFk + WHERE t.shipped = vDate + AND NOT t.isReceived + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk + AND w.isComparative + ) sub2 + GROUP BY itemFk; UPDATE tmp.itemInventory ai JOIN tItemInventoryCalc iic ON iic.itemFk = ai.id + JOIN tItemVisibleCalc ivc ON ivc.itemFk = ai.id SET ai.inventory = iic.quantity, - ai.visible = iic.visible, + ai.visible = iic.quantity + ivc.visible, ai.avalaible = iic.quantity, ai.sd = iic.quantity; @@ -195,6 +195,7 @@ proc: BEGIN tmp.itemTravel, tmp.itemCalc, tItemInventoryCalc, + tItemVisibleCalc, tmp.itemAtp; END$$ DELIMITER ; From 1d59883d19f96020ec7d377cc965c975821b60e0 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 5 Jul 2024 13:14:16 +0200 Subject: [PATCH 052/170] feat: refs #7644 Minor change --- print/templates/reports/buy-label/buy-label.html | 2 +- print/templates/reports/buy-label/sql/buys.sql | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/print/templates/reports/buy-label/buy-label.html b/print/templates/reports/buy-label/buy-label.html index 494cdcbc5..b14e54759 100644 --- a/print/templates/reports/buy-label/buy-label.html +++ b/print/templates/reports/buy-label/buy-label.html @@ -59,7 +59,7 @@
- {{buy.id}} + {{buy.itemFk}} diff --git a/print/templates/reports/buy-label/sql/buys.sql b/print/templates/reports/buy-label/sql/buys.sql index 50b34bd03..41fd3556b 100644 --- a/print/templates/reports/buy-label/sql/buys.sql +++ b/print/templates/reports/buy-label/sql/buys.sql @@ -8,6 +8,7 @@ SELECT ROW_NUMBER() OVER(ORDER BY b.id) labelNum, b.`grouping`, i.stems, b.id, + b.itemFk, p.name producer FROM buy b JOIN item i ON i.id = b.itemFk From 3ddf49da0afdbd00b7f4c8466668149b439cacc1 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 5 Jul 2024 13:21:07 +0200 Subject: [PATCH 053/170] feat: refs #7640 Fix --- db/routines/vn/procedures/multipleInventory.sql | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/db/routines/vn/procedures/multipleInventory.sql b/db/routines/vn/procedures/multipleInventory.sql index 704a93152..8eb4dae71 100644 --- a/db/routines/vn/procedures/multipleInventory.sql +++ b/db/routines/vn/procedures/multipleInventory.sql @@ -119,9 +119,9 @@ proc: BEGIN UPDATE tmp.itemInventory ai JOIN tItemInventoryCalc iic ON iic.itemFk = ai.id - JOIN tItemVisibleCalc ivc ON ivc.itemFk = ai.id + LEFT JOIN tItemVisibleCalc ivc ON ivc.itemFk = iic.itemFk SET ai.inventory = iic.quantity, - ai.visible = iic.quantity + ivc.visible, + ai.visible = iic.visible + IFNULL(ivc.visible, 0), ai.avalaible = iic.quantity, ai.sd = iic.quantity; From 55f0e907711b4090fa7c97caf4f54817414d882f Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 5 Jul 2024 13:36:38 +0200 Subject: [PATCH 054/170] feat: refs #7640 Minor change --- db/routines/vn/procedures/multipleInventory.sql | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/db/routines/vn/procedures/multipleInventory.sql b/db/routines/vn/procedures/multipleInventory.sql index 8eb4dae71..662aa2d63 100644 --- a/db/routines/vn/procedures/multipleInventory.sql +++ b/db/routines/vn/procedures/multipleInventory.sql @@ -75,6 +75,13 @@ proc: BEGIN ) sub GROUP BY itemFk; + UPDATE tmp.itemInventory ai + JOIN tItemInventoryCalc iic ON iic.itemFk = ai.id + SET ai.inventory = iic.quantity, + ai.visible = iic.visible, + ai.avalaible = iic.quantity, + ai.sd = iic.quantity; + -- Cálculo del visible CREATE OR REPLACE TEMPORARY TABLE tItemVisibleCalc (PRIMARY KEY (itemFk)) @@ -118,12 +125,8 @@ proc: BEGIN GROUP BY itemFk; UPDATE tmp.itemInventory ai - JOIN tItemInventoryCalc iic ON iic.itemFk = ai.id - LEFT JOIN tItemVisibleCalc ivc ON ivc.itemFk = iic.itemFk - SET ai.inventory = iic.quantity, - ai.visible = iic.visible + IFNULL(ivc.visible, 0), - ai.avalaible = iic.quantity, - ai.sd = iic.quantity; + JOIN tItemVisibleCalc ivc ON ivc.itemFk = ai.id + SET ai.visible = ai.visible + ivc.visible; -- Calculo del disponible CREATE OR REPLACE TEMPORARY TABLE tmp.itemCalc From 592738c7a0c3d39da8c75c6f7fc365023c5402f7 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 5 Jul 2024 13:48:03 +0200 Subject: [PATCH 055/170] refs #7024 & ticket 198125 Hotfix --- db/routines/vn/triggers/entry_beforeUpdate.sql | 2 -- 1 file changed, 2 deletions(-) diff --git a/db/routines/vn/triggers/entry_beforeUpdate.sql b/db/routines/vn/triggers/entry_beforeUpdate.sql index 31c6f9bd6..0a161853b 100644 --- a/db/routines/vn/triggers/entry_beforeUpdate.sql +++ b/db/routines/vn/triggers/entry_beforeUpdate.sql @@ -11,11 +11,9 @@ BEGIN IF NEW.isBooked = OLD.isBooked AND ( NOT (NEW.supplierFk <=> OLD.supplierFk) OR NOT (NEW.dated <=> OLD.dated) OR - NOT (NEW.invoiceNumber <=> OLD.invoiceNumber) OR NOT (NEW.travelFk <=> OLD.travelFk) OR NOT (NEW.companyFk <=> OLD.companyFk) OR NOT (NEW.invoiceInFk <=> OLD.invoiceInFk) OR - NOT (NEW.invoiceAmount <=> OLD.invoiceAmount) OR NOT (NEW.typeFk <=> OLD.typeFk) ) THEN From 3508cf3a9eea30366065b002e4135fce13590a17 Mon Sep 17 00:00:00 2001 From: ivanm Date: Fri, 5 Jul 2024 14:01:09 +0200 Subject: [PATCH 056/170] refs #7561 add fk en userFk --- db/versions/11137-salmonRoebelini/00-firstScript.sql | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 db/versions/11137-salmonRoebelini/00-firstScript.sql diff --git a/db/versions/11137-salmonRoebelini/00-firstScript.sql b/db/versions/11137-salmonRoebelini/00-firstScript.sql new file mode 100644 index 000000000..69d20ac6d --- /dev/null +++ b/db/versions/11137-salmonRoebelini/00-firstScript.sql @@ -0,0 +1,4 @@ +ALTER TABLE vn.expeditionState + MODIFY COLUMN userFk INT(10) UNSIGNED, + ADD CONSTRAINT expeditionState_userFk FOREIGN KEY (userFk) + REFERENCES account.`user`(id); \ No newline at end of file From 5192bfd8ead52327c2b474465f231b8e596466c8 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Fri, 5 Jul 2024 14:58:34 +0200 Subject: [PATCH 057/170] fix(salix): refs #7648 #7648 entryFilter and getBuys by fi --- modules/entry/back/methods/entry/filter.js | 7 ++++--- modules/entry/back/methods/entry/getBuys.js | 7 ++++--- modules/entry/back/methods/entry/specs/filter.spec.js | 4 ++-- modules/entry/back/methods/entry/specs/getBuys.spec.js | 2 +- 4 files changed, 11 insertions(+), 9 deletions(-) diff --git a/modules/entry/back/methods/entry/filter.js b/modules/entry/back/methods/entry/filter.js index 5989494a4..f21d9dbc4 100644 --- a/modules/entry/back/methods/entry/filter.js +++ b/modules/entry/back/methods/entry/filter.js @@ -146,10 +146,11 @@ module.exports = Self => { }); filter = mergeFilters(ctx.args.filter, {where}); const userId = ctx.req.accessToken.userId; - const isSupplier = await Self.app.models.Supplier.findById(userId, myOptions); - if (isSupplier) { + const client = await Self.app.models.Client.findById(userId, myOptions); + const supplier = await Self.app.models.Supplier.findOne({where: {nif: client.fi}}, myOptions); + if (supplier) { if (!filter.where) filter.where = {}; - filter.where[`e.supplierFk`] = ctx.req.accessToken.userId; + filter.where[`e.supplierFk`] = supplier.id; } const stmts = []; let stmt; diff --git a/modules/entry/back/methods/entry/getBuys.js b/modules/entry/back/methods/entry/getBuys.js index 444e6cb14..0cb71653e 100644 --- a/modules/entry/back/methods/entry/getBuys.js +++ b/modules/entry/back/methods/entry/getBuys.js @@ -36,9 +36,10 @@ module.exports = Self => { if (typeof options == 'object') Object.assign(myOptions, options); - const isSupplier = await Self.app.models.Supplier.findById(userId, myOptions); - if (isSupplier) { - const isEntryOwner = (await Self.findById(id)).supplierFk === userId; + const client = await Self.app.models.Client.findById(userId, myOptions); + const supplier = await Self.app.models.Supplier.findOne({where: {nif: client.fi}}, myOptions); + if (supplier) { + const isEntryOwner = (await Self.findById(id)).supplierFk === supplier.id; if (!isEntryOwner) throw new UserError('Access Denied'); } diff --git a/modules/entry/back/methods/entry/specs/filter.spec.js b/modules/entry/back/methods/entry/specs/filter.spec.js index 9d954cdc4..c8a5bd94f 100644 --- a/modules/entry/back/methods/entry/specs/filter.spec.js +++ b/modules/entry/back/methods/entry/specs/filter.spec.js @@ -56,7 +56,7 @@ describe('Entry filter()', () => { try { const ctx = { args: {}, - req: {accessToken: {userId: 2}} + req: {accessToken: {userId: 1102}} }; const result = await models.Entry.filter(ctx, options); @@ -79,7 +79,7 @@ describe('Entry filter()', () => { args: { supplierFk: 1 }, - req: {accessToken: {userId: 2}} + req: {accessToken: {userId: 1102}} }; const result = await models.Entry.filter(ctx, options); diff --git a/modules/entry/back/methods/entry/specs/getBuys.spec.js b/modules/entry/back/methods/entry/specs/getBuys.spec.js index cb7f7cb80..2d3531249 100644 --- a/modules/entry/back/methods/entry/specs/getBuys.spec.js +++ b/modules/entry/back/methods/entry/specs/getBuys.spec.js @@ -40,7 +40,7 @@ describe('entry getBuys()', () => { args: { search: 1 }, - req: {accessToken: {userId: 2}} + req: {accessToken: {userId: 1102}} }; const result = await models.Entry.getBuys(ctx, entryId, options); From 2f10066290c1c064c49a68167dd775698b0fe908 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Sun, 7 Jul 2024 23:23:30 +0200 Subject: [PATCH 058/170] feat(salix): refs #7380 #7380 remove new field --- db/versions/11132-aquaDracena/00-firstScript.sql | 2 -- modules/client/back/models/client.json | 3 --- 2 files changed, 5 deletions(-) diff --git a/db/versions/11132-aquaDracena/00-firstScript.sql b/db/versions/11132-aquaDracena/00-firstScript.sql index 1b304c1d0..a8baa8051 100644 --- a/db/versions/11132-aquaDracena/00-firstScript.sql +++ b/db/versions/11132-aquaDracena/00-firstScript.sql @@ -1,4 +1,2 @@ INSERT IGNORE INTO vn.observationType (`description`,code,hasNewBornMessage) VALUES ('Sustitución','substitution',0); - -ALTER TABLE vn.client ADD substitutionAllowed BOOL DEFAULT false NULL; diff --git a/modules/client/back/models/client.json b/modules/client/back/models/client.json index 97c2a3624..f3eb9919b 100644 --- a/modules/client/back/models/client.json +++ b/modules/client/back/models/client.json @@ -53,9 +53,6 @@ "isActive": { "type": "boolean" }, - "substitutionAllowed": { - "type": "boolean" - }, "credit": { "type": "number" }, From 3c2a44eb53334a31de7646f93a7f68c4a2fa1cc6 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Sun, 7 Jul 2024 23:47:00 +0200 Subject: [PATCH 059/170] feat(salix): refs #7380 #7380 add value to fixtures --- db/dump/fixtures.before.sql | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index 783feaca0..ebf0c3401 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -528,7 +528,8 @@ INSERT INTO `vn`.`observationType`(`id`,`description`, `code`) (5, 'Administrative', 'administrative'), (6, 'Weight', 'weight'), (7, 'InvoiceOut', 'invoiceOut'), - (8, 'DropOff', 'dropOff'); + (8, 'DropOff', 'dropOff'), + (9, 'Sustitución', 'substitution',0); INSERT INTO `vn`.`addressObservation`(`id`,`addressFk`,`observationTypeFk`,`description`) VALUES From 3a2acfb7f8e5e012704c9e3496375521416d06c8 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 8 Jul 2024 07:21:53 +0200 Subject: [PATCH 060/170] feat: refs #7640 Optimization --- db/routines/vn/procedures/multipleInventory.sql | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/db/routines/vn/procedures/multipleInventory.sql b/db/routines/vn/procedures/multipleInventory.sql index 662aa2d63..941ac6c3d 100644 --- a/db/routines/vn/procedures/multipleInventory.sql +++ b/db/routines/vn/procedures/multipleInventory.sql @@ -40,8 +40,7 @@ proc: BEGIN (PRIMARY KEY (itemFk)) ENGINE = MEMORY SELECT itemFk, - SUM(quantity) quantity, - SUM(quantity) visible + SUM(quantity) quantity FROM ( SELECT s.itemFk, - s.quantity quantity FROM sale s @@ -78,7 +77,7 @@ proc: BEGIN UPDATE tmp.itemInventory ai JOIN tItemInventoryCalc iic ON iic.itemFk = ai.id SET ai.inventory = iic.quantity, - ai.visible = iic.visible, + ai.visible = iic.quantity, ai.avalaible = iic.quantity, ai.sd = iic.quantity; From 816b111f79206e35486d1b7491a5aecd86353881 Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 8 Jul 2024 09:20:39 +0200 Subject: [PATCH 061/170] feat: refs #6403 add dynamic clientType --- back/methods/mrw-config/createShipment.ejs | 2 +- back/methods/mrw-config/createShipment.js | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/back/methods/mrw-config/createShipment.ejs b/back/methods/mrw-config/createShipment.ejs index 7468218f2..8e123ddd9 100644 --- a/back/methods/mrw-config/createShipment.ejs +++ b/back/methods/mrw-config/createShipment.ejs @@ -3,7 +3,7 @@ <%= mrw.franchiseCode %> - <%= mrw.subscriberCode %> + <%= expeditionData.clientType %> <%= mrw.user %> <%= mrw.password %> diff --git a/back/methods/mrw-config/createShipment.js b/back/methods/mrw-config/createShipment.js index a2fccb95b..13d3a591f 100644 --- a/back/methods/mrw-config/createShipment.js +++ b/back/methods/mrw-config/createShipment.js @@ -52,7 +52,8 @@ module.exports = Self => { CONCAT( e.ticketFk, LPAD(e.counter, mc.counterWidth, '0')) reference, LPAD(IF(mw.serviceType IS NULL, ms.serviceType, mw.serviceType), mc.serviceTypeWidth,'0') serviceType, IF(mw.weekdays, 'S', 'N') weekDays, - oa.description deliveryObservation + oa.description deliveryObservation, + ms.clientType FROM expedition e JOIN ticket t ON e.ticketFk = t.id JOIN agencyMode am ON am.id = t.agencyModeFk From e9d2ff14764bfc5eddcc1e0121de93d183c71546 Mon Sep 17 00:00:00 2001 From: robert Date: Mon, 8 Jul 2024 09:43:59 +0200 Subject: [PATCH 062/170] feat: refs #7582 claimDestination addColumn code --- db/versions/11138-aquaGalax/00-firstScript.sql | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 db/versions/11138-aquaGalax/00-firstScript.sql diff --git a/db/versions/11138-aquaGalax/00-firstScript.sql b/db/versions/11138-aquaGalax/00-firstScript.sql new file mode 100644 index 000000000..44fdd468f --- /dev/null +++ b/db/versions/11138-aquaGalax/00-firstScript.sql @@ -0,0 +1,9 @@ +USE `vn`; +ALTER TABLE `vn`.`claimDestination` +ADD COLUMN `code` varchar(45) DEFAULT NULL; + +UPDATE vn.claimDestination SET code='Good' WHERE description= 'Bueno'; +UPDATE vn.claimDestination SET code='Garbage/Loss' WHERE description = 'Basura/Perd.'; +UPDATE vn.claimDestination SET code='Manufacturing'WHERE description = 'Confeccion'; +UPDATE vn.claimDestination SET code='Claim' WHERE description = 'Reclam.PRAG'; +UPDATE vn.claimDestination SET code='Corrected' WHERE description = 'Corregido'; \ No newline at end of file From 9f57e50f8964f7617dd0e4999050d0dd901dcf1a Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 8 Jul 2024 09:54:40 +0200 Subject: [PATCH 063/170] feat(salix): refs #7380 #7380 add value to fixtures --- db/dump/fixtures.before.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index ebf0c3401..8bc70fbba 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -529,7 +529,7 @@ INSERT INTO `vn`.`observationType`(`id`,`description`, `code`) (6, 'Weight', 'weight'), (7, 'InvoiceOut', 'invoiceOut'), (8, 'DropOff', 'dropOff'), - (9, 'Sustitución', 'substitution',0); + (9, 'Sustitución', 'substitution'); INSERT INTO `vn`.`addressObservation`(`id`,`addressFk`,`observationTypeFk`,`description`) VALUES From 9f4680325bfb580147fdb1d9ead048a62689851a Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 8 Jul 2024 09:54:52 +0200 Subject: [PATCH 064/170] feat(salix): refs #7380 #7380 rename extension file --- db/versions/11132-aquaDracena/00-firstScript.sql | 2 -- db/versions/11132-aquaDracena/00-firstScript.vn.sql | 2 ++ 2 files changed, 2 insertions(+), 2 deletions(-) delete mode 100644 db/versions/11132-aquaDracena/00-firstScript.sql create mode 100644 db/versions/11132-aquaDracena/00-firstScript.vn.sql diff --git a/db/versions/11132-aquaDracena/00-firstScript.sql b/db/versions/11132-aquaDracena/00-firstScript.sql deleted file mode 100644 index a8baa8051..000000000 --- a/db/versions/11132-aquaDracena/00-firstScript.sql +++ /dev/null @@ -1,2 +0,0 @@ -INSERT IGNORE INTO vn.observationType (`description`,code,hasNewBornMessage) - VALUES ('Sustitución','substitution',0); diff --git a/db/versions/11132-aquaDracena/00-firstScript.vn.sql b/db/versions/11132-aquaDracena/00-firstScript.vn.sql new file mode 100644 index 000000000..64f8442b4 --- /dev/null +++ b/db/versions/11132-aquaDracena/00-firstScript.vn.sql @@ -0,0 +1,2 @@ +INSERT IGNORE INTO vn.observationType (`description`,code) + VALUES ('Sustitución','substitution'); From 62045756e6717d759408b2e883ce0bde25a6baa3 Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 8 Jul 2024 10:50:15 +0200 Subject: [PATCH 065/170] fix: refs #6403 extend length to 6 digits for mrw clientType --- back/methods/mrw-config/createShipment.js | 4 ++-- db/versions/11139-bronzeCataractarum/00-firstScript.sql | 6 ++++++ 2 files changed, 8 insertions(+), 2 deletions(-) create mode 100644 db/versions/11139-bronzeCataractarum/00-firstScript.sql diff --git a/back/methods/mrw-config/createShipment.js b/back/methods/mrw-config/createShipment.js index 13d3a591f..9b23cc370 100644 --- a/back/methods/mrw-config/createShipment.js +++ b/back/methods/mrw-config/createShipment.js @@ -50,10 +50,10 @@ module.exports = Self => { DATE_FORMAT(t.shipped, '%d/%m/%Y') created, t.shipped, CONCAT( e.ticketFk, LPAD(e.counter, mc.counterWidth, '0')) reference, - LPAD(IF(mw.serviceType IS NULL, ms.serviceType, mw.serviceType), mc.serviceTypeWidth,'0') serviceType, + LPAD(IF(mw.serviceType IS NULL, ms.serviceType, mw.serviceType), mc.serviceTypeWidth, '0') serviceType, IF(mw.weekdays, 'S', 'N') weekDays, oa.description deliveryObservation, - ms.clientType + LPAD(ms.clientType, mc.clientTypeWidth, '0') clientType FROM expedition e JOIN ticket t ON e.ticketFk = t.id JOIN agencyMode am ON am.id = t.agencyModeFk diff --git a/db/versions/11139-bronzeCataractarum/00-firstScript.sql b/db/versions/11139-bronzeCataractarum/00-firstScript.sql new file mode 100644 index 000000000..2816fab86 --- /dev/null +++ b/db/versions/11139-bronzeCataractarum/00-firstScript.sql @@ -0,0 +1,6 @@ +-- Place your SQL code here +ALTER TABLE vn.mrwConfig ADD IF NOT EXISTS clientTypeWidth int(10) unsigned NULL + COMMENT 'If it does not reach the required value, it will be padded with zeros on the left to meet the specified length.'; + +UPDATE vn.mrwConfig + SET clientTypeWidth = 6; \ No newline at end of file From 4b0a08d9653f1383666e53eb1eb1b268baf33c0b Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 8 Jul 2024 10:57:46 +0200 Subject: [PATCH 066/170] refactor: refs #7684 vehicle warehouseFk fix --- db/versions/11140-azurePhormium/00-firstScript.sql | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 db/versions/11140-azurePhormium/00-firstScript.sql diff --git a/db/versions/11140-azurePhormium/00-firstScript.sql b/db/versions/11140-azurePhormium/00-firstScript.sql new file mode 100644 index 000000000..7c89110bb --- /dev/null +++ b/db/versions/11140-azurePhormium/00-firstScript.sql @@ -0,0 +1,3 @@ +ALTER TABLE vn.vehicle DROP FOREIGN KEY provinceFk; +ALTER TABLE vn.vehicle + ADD CONSTRAINT vehicle_warehouse_FK FOREIGN KEY (warehouseFk) REFERENCES vn.warehouse(id) ON DELETE RESTRICT ON UPDATE CASCADE; From 3fa0823d931bc8a817772f0ed855172151e537c5 Mon Sep 17 00:00:00 2001 From: robert Date: Mon, 8 Jul 2024 11:01:35 +0200 Subject: [PATCH 067/170] feat: refs #7582 quitar vn --- db/versions/11138-aquaGalax/00-firstScript.sql | 1 - 1 file changed, 1 deletion(-) diff --git a/db/versions/11138-aquaGalax/00-firstScript.sql b/db/versions/11138-aquaGalax/00-firstScript.sql index 44fdd468f..1e759db61 100644 --- a/db/versions/11138-aquaGalax/00-firstScript.sql +++ b/db/versions/11138-aquaGalax/00-firstScript.sql @@ -1,4 +1,3 @@ -USE `vn`; ALTER TABLE `vn`.`claimDestination` ADD COLUMN `code` varchar(45) DEFAULT NULL; From a796787cb5eb3da34a893f25c79c7d52ff939aa0 Mon Sep 17 00:00:00 2001 From: robert Date: Mon, 8 Jul 2024 11:04:35 +0200 Subject: [PATCH 068/170] feat: refs #7582 --- db/versions/11138-aquaGalax/00-firstScript.sql | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/db/versions/11138-aquaGalax/00-firstScript.sql b/db/versions/11138-aquaGalax/00-firstScript.sql index 1e759db61..0c6547260 100644 --- a/db/versions/11138-aquaGalax/00-firstScript.sql +++ b/db/versions/11138-aquaGalax/00-firstScript.sql @@ -1,8 +1,8 @@ ALTER TABLE `vn`.`claimDestination` ADD COLUMN `code` varchar(45) DEFAULT NULL; -UPDATE vn.claimDestination SET code='Good' WHERE description= 'Bueno'; -UPDATE vn.claimDestination SET code='Garbage/Loss' WHERE description = 'Basura/Perd.'; -UPDATE vn.claimDestination SET code='Manufacturing'WHERE description = 'Confeccion'; -UPDATE vn.claimDestination SET code='Claim' WHERE description = 'Reclam.PRAG'; -UPDATE vn.claimDestination SET code='Corrected' WHERE description = 'Corregido'; \ No newline at end of file +UPDATE IGNORE vn.claimDestination SET code='Good' WHERE description= 'Bueno'; +UPDATE IGNORE vn.claimDestination SET code='Garbage/Loss' WHERE description = 'Basura/Perd.'; +UPDATE IGNORE vn.claimDestination SET code='Manufacturing'WHERE description = 'Confeccion'; +UPDATE IGNORE vn.claimDestination SET code='Claim' WHERE description = 'Reclam.PRAG'; +UPDATE IGNORE vn.claimDestination SET code='Corrected' WHERE description = 'Corregido'; \ No newline at end of file From d0e4decf1e5dcf28011adb313d96fb674fd3db6e Mon Sep 17 00:00:00 2001 From: carlossa Date: Mon, 8 Jul 2024 11:05:11 +0200 Subject: [PATCH 069/170] refs #6952 add producer sql trad --- print/templates/reports/invoice/invoice.html | 2 +- print/templates/reports/invoice/locale/en.yml | 2 +- print/templates/reports/invoice/locale/es.yml | 3 ++- print/templates/reports/invoice/sql/sales.sql | 4 +++- 4 files changed, 7 insertions(+), 4 deletions(-) diff --git a/print/templates/reports/invoice/invoice.html b/print/templates/reports/invoice/invoice.html index af1aaa423..c4e0b818a 100644 --- a/print/templates/reports/invoice/invoice.html +++ b/print/templates/reports/invoice/invoice.html @@ -104,7 +104,7 @@ {{sale.itemFk}} {{sale.quantity}} - {{sale.concept}} + {{sale.concept}} {{sale.subName}} {{sale.price | currency('EUR', $i18n.locale)}} {{(sale.discount / 100) | percentage}} {{sale.vatType}} diff --git a/print/templates/reports/invoice/locale/en.yml b/print/templates/reports/invoice/locale/en.yml index 336592f0c..336384457 100644 --- a/print/templates/reports/invoice/locale/en.yml +++ b/print/templates/reports/invoice/locale/en.yml @@ -34,4 +34,4 @@ plantPassport: Plant passport observations: Observations wireTransfer: "Pay method: Transferencia" accountNumber: "Account number: {0}" -services: Services \ No newline at end of file +services: Services diff --git a/print/templates/reports/invoice/locale/es.yml b/print/templates/reports/invoice/locale/es.yml index 32f6fc708..879977e39 100644 --- a/print/templates/reports/invoice/locale/es.yml +++ b/print/templates/reports/invoice/locale/es.yml @@ -34,4 +34,5 @@ plantPassport: Pasaporte fitosanitario observations: Observaciones wireTransfer: "Forma de pago: Transferencia" accountNumber: "Número de cuenta: {0}" -services: Servicios \ No newline at end of file +services: Servicios + diff --git a/print/templates/reports/invoice/sql/sales.sql b/print/templates/reports/invoice/sql/sales.sql index 8e5ad1102..2d29cc520 100644 --- a/print/templates/reports/invoice/sql/sales.sql +++ b/print/templates/reports/invoice/sql/sales.sql @@ -8,7 +8,8 @@ SELECT s.itemFk, s.concept, tc.code vatType, - it.isPackaging + it.isPackaging, + i.subName FROM vn.invoiceOut io JOIN vn.ticket t ON t.refFk = io.ref JOIN vn.supplier su ON su.id = io.companyFk @@ -38,6 +39,7 @@ SELECT NULL, ts.description, tc.code, + NULL, NULL FROM vn.invoiceOut io JOIN vn.ticket t ON t.refFk = io.ref From 0722a97c6000bd9ebc36b9349589bd660ee5e31a Mon Sep 17 00:00:00 2001 From: robert Date: Mon, 8 Jul 2024 11:28:33 +0200 Subject: [PATCH 070/170] feat: refs #7582 --- db/versions/11138-aquaGalax/00-firstScript.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/versions/11138-aquaGalax/00-firstScript.sql b/db/versions/11138-aquaGalax/00-firstScript.sql index 0c6547260..d492e6470 100644 --- a/db/versions/11138-aquaGalax/00-firstScript.sql +++ b/db/versions/11138-aquaGalax/00-firstScript.sql @@ -3,6 +3,6 @@ ADD COLUMN `code` varchar(45) DEFAULT NULL; UPDATE IGNORE vn.claimDestination SET code='Good' WHERE description= 'Bueno'; UPDATE IGNORE vn.claimDestination SET code='Garbage/Loss' WHERE description = 'Basura/Perd.'; -UPDATE IGNORE vn.claimDestination SET code='Manufacturing'WHERE description = 'Confeccion'; +UPDATE IGNORE vn.claimDestination SET code='Manufacturing' WHERE description = 'Confeccion'; UPDATE IGNORE vn.claimDestination SET code='Claim' WHERE description = 'Reclam.PRAG'; UPDATE IGNORE vn.claimDestination SET code='Corrected' WHERE description = 'Corregido'; \ No newline at end of file From f57ab7248233b260fac97baaad5c18005ce5e340 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 8 Jul 2024 13:17:29 +0200 Subject: [PATCH 071/170] refactor: refs #7580 Fix and improvement --- .../vn/procedures/collection_setParking.sql | 17 +++-- .../vn/procedures/saleGroup_setParking.sql | 20 ++++-- db/routines/vn/procedures/setParking.sql | 65 ++++++++----------- .../vn/procedures/ticket_setNextState.sql | 17 ++++- .../vn/procedures/ticket_setParking.sql | 22 +++++-- 5 files changed, 79 insertions(+), 62 deletions(-) diff --git a/db/routines/vn/procedures/collection_setParking.sql b/db/routines/vn/procedures/collection_setParking.sql index 73aa87bfb..5f6ca75da 100644 --- a/db/routines/vn/procedures/collection_setParking.sql +++ b/db/routines/vn/procedures/collection_setParking.sql @@ -1,15 +1,18 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`collection_setParking`(IN `vCollectionFk` VARCHAR(8), IN `vParkingFk` INT) -proc: BEGIN +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`collection_setParking`( + vSelf INT, + vParkingFk INT +) +BEGIN /** * Aparca una colección en un parking. * - * @param vCollectionFk Id de la colección - * @param vParkingFk Id del parking + * @param vSelf Id colección + * @param vParkingFk Id parking */ - REPLACE vn.ticketParking(ticketFk, parkingFk) + REPLACE ticketParking(ticketFk, parkingFk) SELECT tc.ticketFk, vParkingFk - FROM vn.ticketCollection tc - WHERE tc.collectionFk = vCollectionFk; + FROM ticketCollection tc + WHERE tc.collectionFk = vSelf; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/saleGroup_setParking.sql b/db/routines/vn/procedures/saleGroup_setParking.sql index 4872f74c6..551ca6386 100644 --- a/db/routines/vn/procedures/saleGroup_setParking.sql +++ b/db/routines/vn/procedures/saleGroup_setParking.sql @@ -1,17 +1,25 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`saleGroup_setParking`(IN `vSaleGroupFk` VARCHAR(8), IN `vParkingFk` INT) -proc: BEGIN +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`saleGroup_setParking`( + vSaleGroupFk VARCHAR(8), + vParkingFk INT +) +BEGIN /** - * Aparca una preparación previa en un parking + * Aparca una preparación previa en un parking. * * @param vSaleGroupFk id de la preparación previa * @param vParkingFk id del parking */ - UPDATE vn.saleGroup sg + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + RESIGNAL; + END; + + UPDATE saleGroup sg SET sg.parkingFk = vParkingFk WHERE sg.id = vSaleGroupFk - AND sg.created >= TIMESTAMPADD(WEEK,-1,util.VN_CURDATE()); + AND sg.created >= util.VN_CURDATE() - INTERVAL 1 WEEK; - CALL vn.ticket_setNextState(vn.ticket_get(vSaleGroupFk)); + CALL ticket_setNextState(ticket_get(vSaleGroupFk)); END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/setParking.sql b/db/routines/vn/procedures/setParking.sql index d6def07de..c4e1fd19f 100644 --- a/db/routines/vn/procedures/setParking.sql +++ b/db/routines/vn/procedures/setParking.sql @@ -1,6 +1,9 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`setParking`(IN `vParam` VARCHAR(8), IN `vParkingCode` VARCHAR(8)) -proc: BEGIN +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`setParking`( + vParam VARCHAR(8), + vParkingCode VARCHAR(8) +) +BEGIN /** * Aparca una colección, un ticket, un saleGroup o un shelving en un parking * @@ -8,56 +11,40 @@ proc: BEGIN * @param vParkingCode código del parking */ DECLARE vParkingFk INT; - DECLARE vIsSaleGroup BOOL; - DECLARE vIsTicket BOOL; - DECLARE vIsCollection BOOL; + DECLARE vLastWeek DATE; - SET vParkingCode = replace(vParkingCode,' ',''); + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + SET vParkingCode = REPLACE(vParkingCode, ' ', ''); SELECT id INTO vParkingFk - FROM vn.parking + FROM parking WHERE code = vParkingCode COLLATE utf8_unicode_ci; IF vParkingFk IS NULL THEN CALL util.throw('parkingNotExist'); - LEAVE proc; END IF; - IF vParam REGEXP '^[0-9]+$' THEN - -- Se comprueba si es una preparación previa - SELECT COUNT(*) INTO vIsSaleGroup - FROM vn.saleGroup sg - WHERE sg.id = vParam; + IF vParam REGEXP '^[0-9]+$' THEN + SET vLastWeek = util.VN_CURDATE() - INTERVAL 1 WEEK; - IF vIsSaleGroup THEN - CALL vn.saleGroup_setParking(vParam, vParkingFk); - LEAVE proc; - END IF; - - -- Se comprueba si es un ticket - SELECT COUNT(*) INTO vIsTicket - FROM vn.ticket t - WHERE t.id = vParam - AND t.shipped >= TIMESTAMPADD(WEEK,-1,util.VN_CURDATE()); - - IF vIsTicket THEN - CALL vn.ticket_setParking(vParam, vParkingFk); - LEAVE proc; - END IF; - - -- Se comprueba si es una coleccion de tickets - SELECT COUNT(*) INTO vIsCollection - FROM vn.collection c - WHERE c.id = vParam - AND c.created >= TIMESTAMPADD(WEEK,-1,util.VN_CURDATE()); - - IF vIsCollection THEN - CALL vn.collection_setParking(vParam, vParkingFk); - LEAVE proc; + -- Comprobamos si es una prep. previa, ticket o colección + IF (SELECT TRUE FROM saleGroup sg WHERE sg.id = vParam) THEN + CALL saleGroup_setParking(vParam, vParkingFk); + ELSEIF (SELECT TRUE FROM ticket WHERE id = vParam shipped >= vLastWeek) THEN + CALL ticket_setParking(vParam, vParkingFk); + ELSEIF (SELECT TRUE FROM `collection` WHERE id = vParam AND created >= vLastWeek) THEN + CALL collection_setParking(vParam, vParkingFk); END IF; ELSE -- Por descarte, se considera una matrícula - CALL vn.shelving_setParking(vParam, vParkingFk); + CALL shelving_setParking(vParam, vParkingFk); END IF; + + COMMIT; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/ticket_setNextState.sql b/db/routines/vn/procedures/ticket_setNextState.sql index d13cd53f0..b09309a47 100644 --- a/db/routines/vn/procedures/ticket_setNextState.sql +++ b/db/routines/vn/procedures/ticket_setNextState.sql @@ -1,14 +1,21 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_setNextState`(vSelf INT) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_setNextState`( + vSelf INT +) BEGIN /** - * Cambia el estado del ticket al siguiente estado según la tabla state + * Cambia el estado del ticket al siguiente estado según la tabla state. * - * @param vSelf id dle ticket + * @param vSelf Id ticket */ DECLARE vStateFk INT; DECLARE vNewStateFk INT; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + RESIGNAL; + END; + SELECT stateFk INTO vStateFk FROM ticketState WHERE ticketFk = vSelf; @@ -17,6 +24,10 @@ BEGIN FROM state WHERE id = vStateFk; + IF vNewStateFk IS NULL THEN + CALL util.throw('The ticket not have next state'); + END IF; + INSERT INTO ticketTracking(stateFk, ticketFk, userFk) VALUES (vNewStateFk, vSelf, account.myUser_getId()); END$$ diff --git a/db/routines/vn/procedures/ticket_setParking.sql b/db/routines/vn/procedures/ticket_setParking.sql index 54c64daea..7935e0d60 100644 --- a/db/routines/vn/procedures/ticket_setParking.sql +++ b/db/routines/vn/procedures/ticket_setParking.sql @@ -1,11 +1,14 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_setParking`(IN `vTicketFk` VARCHAR(8), IN `vParkingFk` INT) -proc: BEGIN +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_setParking`( + vSelf INT, + vParkingFk INT +) +BEGIN /** - * Aparca un ticket en un parking + * Aparca un ticket en un parking. * - * @param vTicketFk id del ticket - * @param vParkingFk id del parking + * @param vSelf Id ticket + * @param vParkingFk Id parking */ DECLARE vDone INT DEFAULT FALSE; DECLARE vCollectionTicketFk INT; @@ -14,16 +17,21 @@ proc: BEGIN FROM ticket t LEFT JOIN ticketCollection tc1 ON tc1.ticketFk = t.id LEFT JOIN ticketCollection tc2 ON tc2.collectionFk = tc1.collectionFk - WHERE t.id = vTicketFk; + WHERE t.id = vSelf; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + RESIGNAL; + END; + INSERT INTO vn.ticketParking(ticketFk, parkingFk) SELECT IFNULL(tc2.ticketFk, t.id), vParkingFk FROM ticket t LEFT JOIN ticketCollection tc1 ON tc1.ticketFk = t.id LEFT JOIN ticketCollection tc2 ON tc2.collectionFk = tc1.collectionFk - WHERE t.id = vTicketFk + WHERE t.id = vSelf ON DUPLICATE KEY UPDATE parkingFk = vParkingFk; OPEN vCursor; From 73b43aa254f4896261c1cc692fb6fd2dc5f8629e Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 8 Jul 2024 13:22:10 +0200 Subject: [PATCH 072/170] refactor: refs #7580 Fixes --- db/routines/vn/procedures/setParking.sql | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/db/routines/vn/procedures/setParking.sql b/db/routines/vn/procedures/setParking.sql index c4e1fd19f..107ef66f4 100644 --- a/db/routines/vn/procedures/setParking.sql +++ b/db/routines/vn/procedures/setParking.sql @@ -33,9 +33,9 @@ BEGIN SET vLastWeek = util.VN_CURDATE() - INTERVAL 1 WEEK; -- Comprobamos si es una prep. previa, ticket o colección - IF (SELECT TRUE FROM saleGroup sg WHERE sg.id = vParam) THEN + IF (SELECT TRUE FROM saleGroup WHERE id = vParam) THEN CALL saleGroup_setParking(vParam, vParkingFk); - ELSEIF (SELECT TRUE FROM ticket WHERE id = vParam shipped >= vLastWeek) THEN + ELSEIF (SELECT TRUE FROM ticket WHERE id = vParam AND shipped >= vLastWeek) THEN CALL ticket_setParking(vParam, vParkingFk); ELSEIF (SELECT TRUE FROM `collection` WHERE id = vParam AND created >= vLastWeek) THEN CALL collection_setParking(vParam, vParkingFk); From 03b95eb9f6d7e1a9993b6d4e25bb7a4cb6bccfdd Mon Sep 17 00:00:00 2001 From: carlossa Date: Mon, 8 Jul 2024 13:43:08 +0200 Subject: [PATCH 073/170] refs #5525 fix accountDetailValue --- print/templates/reports/sepa-core/sql/supplier.sql | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/print/templates/reports/sepa-core/sql/supplier.sql b/print/templates/reports/sepa-core/sql/supplier.sql index a32d311de..e0ad69257 100644 --- a/print/templates/reports/sepa-core/sql/supplier.sql +++ b/print/templates/reports/sepa-core/sql/supplier.sql @@ -7,7 +7,6 @@ SELECT s.city, sp.name province, s.nif, - sa.iban, sa.supplierFk, be.name bankName, ad.value accountDetailValue @@ -21,9 +20,11 @@ FROM LEFT JOIN supplierAccount sa ON sa.supplierFk = s.id LEFT JOIN bankEntity be ON sa.bankEntityFk = be.id LEFT JOIN accountDetail ad ON ad.supplierAccountFk = sa.id - LEFT JOIN accountDetailType adt ON adt.id = ad.accountDetailTypeFk AND adt.id = 3 + JOIN accountDetailType adt ON adt.id = ad.accountDetailTypeFk WHERE (m.companyFk = ? OR m.companyFk IS NULL) AND (c.id = ? OR (c.id IS NULL AND c.countryFk = sa.countryFk)) + AND adt.id = 3 +GROUP BY ad.value ORDER BY - m.created DESC; +m.created DESC; From 06ae86d78faf3dae812f18045091a41fbe717319 Mon Sep 17 00:00:00 2001 From: carlossa Date: Mon, 8 Jul 2024 13:45:16 +0200 Subject: [PATCH 074/170] refs #5525 fix adt --- print/templates/reports/sepa-core/sql/supplier.sql | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/print/templates/reports/sepa-core/sql/supplier.sql b/print/templates/reports/sepa-core/sql/supplier.sql index e0ad69257..1276f2437 100644 --- a/print/templates/reports/sepa-core/sql/supplier.sql +++ b/print/templates/reports/sepa-core/sql/supplier.sql @@ -20,11 +20,10 @@ FROM LEFT JOIN supplierAccount sa ON sa.supplierFk = s.id LEFT JOIN bankEntity be ON sa.bankEntityFk = be.id LEFT JOIN accountDetail ad ON ad.supplierAccountFk = sa.id - JOIN accountDetailType adt ON adt.id = ad.accountDetailTypeFk + JOIN accountDetailType adt ON adt.id = ad.accountDetailTypeFk AND adt.id = 3 WHERE (m.companyFk = ? OR m.companyFk IS NULL) AND (c.id = ? OR (c.id IS NULL AND c.countryFk = sa.countryFk)) - AND adt.id = 3 GROUP BY ad.value ORDER BY m.created DESC; From 86859c98e37d50bac8fb40f22d0fbba2a7861388 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 8 Jul 2024 13:57:17 +0200 Subject: [PATCH 075/170] refactor: refs #7662 Added transaction --- .../ticket_splitItemPackingType.sql | 97 +++++++++++-------- 1 file changed, 57 insertions(+), 40 deletions(-) diff --git a/db/routines/vn/procedures/ticket_splitItemPackingType.sql b/db/routines/vn/procedures/ticket_splitItemPackingType.sql index d6e8e8a53..bc4c94d46 100644 --- a/db/routines/vn/procedures/ticket_splitItemPackingType.sql +++ b/db/routines/vn/procedures/ticket_splitItemPackingType.sql @@ -1,59 +1,67 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_splitItemPackingType`( - vTicketFk INT, - vOriginalItemPackingTypeFk VARCHAR(1) + vSelf INT, + vItemPackingTypeFk VARCHAR(1) ) BEGIN /** * Clona y reparte las ventas de un ticket en funcion del tipo de empaquetado. * Respeta el id inicial para el tipo propuesto. * - * @param vTicketFk Identificador de vn.ticket - * @param vOriginalItemPackingTypeFk Tipo para el que se reserva el número de ticket original + * @param vSelf Id ticket + * @param vItemPackingTypeFk Tipo para el que se reserva el número de ticket original * @return table tmp.ticketIPT(ticketFk, itemPackingTypeFk) */ DECLARE vItemPackingTypeFk VARCHAR(1) DEFAULT 'H'; DECLARE vNewTicketFk INT; DECLARE vPackingTypesToSplit INT; DECLARE vDone INT DEFAULT FALSE; - - DECLARE cur1 CURSOR FOR + DECLARE vSaleGroup CURSOR FOR SELECT itemPackingTypeFk - FROM tmp.saleGroup + FROM tSaleGroup WHERE itemPackingTypeFk IS NOT NULL - ORDER BY (itemPackingTypeFk = vOriginalItemPackingTypeFk) DESC; + ORDER BY (itemPackingTypeFk = vItemPackingTypeFk) DESC; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN + ROLLBACK; RESIGNAL; END; - DELETE FROM vn.sale - WHERE quantity = 0 - AND ticketFk = vTicketFk; + START TRANSACTION; - CREATE OR REPLACE TEMPORARY TABLE tmp.sale + SELECT id + FROM sale + WHERE ticketFk = vSelf + AND NOT quantity + FOR UPDATE; + + DELETE FROM sale + WHERE NOT quantity + AND ticketFk = vSelf; + + CREATE OR REPLACE TEMPORARY TABLE tSale (PRIMARY KEY (id)) ENGINE = MEMORY - SELECT s.id, i.itemPackingTypeFk , IFNULL(sv.litros, 0) litros - FROM vn.sale s - JOIN vn.item i ON i.id = s.itemFk - LEFT JOIN vn.saleVolume sv ON sv.saleFk = s.id - WHERE s.ticketFk = vTicketFk; + SELECT s.id, i.itemPackingTypeFk, IFNULL(sv.litros, 0) litros + FROM sale s + JOIN item i ON i.id = s.itemFk + LEFT JOIN saleVolume sv ON sv.saleFk = s.id + WHERE s.ticketFk = vSelf; - CREATE OR REPLACE TEMPORARY TABLE tmp.saleGroup + CREATE OR REPLACE TEMPORARY TABLE tSaleGroup ENGINE = MEMORY SELECT itemPackingTypeFk, SUM(litros) totalLitros - FROM tmp.sale + FROM tSale GROUP BY itemPackingTypeFk; SELECT COUNT(*) INTO vPackingTypesToSplit - FROM tmp.saleGroup + FROM tSaleGroup WHERE itemPackingTypeFk IS NOT NULL; - CREATE OR REPLACE TEMPORARY TABLE tmp.ticketIPT ( + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketIPT( ticketFk INT, itemPackingTypeFk VARCHAR(1) ) ENGINE = MEMORY; @@ -61,55 +69,64 @@ BEGIN CASE vPackingTypesToSplit WHEN 0 THEN INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) - VALUES(vTicketFk, vItemPackingTypeFk); + VALUES(vSelf, vItemPackingTypeFk); WHEN 1 THEN INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) - SELECT vTicketFk, itemPackingTypeFk - FROM tmp.saleGroup + SELECT vSelf, itemPackingTypeFk + FROM tSaleGroup WHERE itemPackingTypeFk IS NOT NULL; ELSE - OPEN cur1; - - FETCH cur1 INTO vItemPackingTypeFk; + OPEN vSaleGroup; + FETCH vSaleGroup INTO vItemPackingTypeFk; INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) - VALUES(vTicketFk, vItemPackingTypeFk); + VALUES(vSelf, vItemPackingTypeFk); - read_loop: LOOP - FETCH cur1 INTO vItemPackingTypeFk; + l: LOOP + SET vDone = FALSE; + FETCH vSaleGroup INTO vItemPackingTypeFk; IF vDone THEN - LEAVE read_loop; + LEAVE l; END IF; - CALL vn.ticket_Clone(vTicketFk, vNewTicketFk); + CALL ticket_Clone(vSelf, vNewTicketFk); INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) VALUES(vNewTicketFk, vItemPackingTypeFk); END LOOP; - CLOSE cur1; + CLOSE vSaleGroup; - UPDATE vn.sale s - JOIN tmp.sale ts ON ts.id = s.id + SELECT s.id + FROM sale s + JOIN tSale ts ON ts.id = s.id + JOIN tmp.ticketIPT t ON t.itemPackingTypeFk = ts.itemPackingTypeFk + WHERE s.ticketFk = vSelf + FOR UPDATE; + + UPDATE sale s + JOIN tSale ts ON ts.id = s.id JOIN tmp.ticketIPT t ON t.itemPackingTypeFk = ts.itemPackingTypeFk SET s.ticketFk = t.ticketFk; SELECT itemPackingTypeFk INTO vItemPackingTypeFk - FROM tmp.saleGroup sg + FROM tSaleGroup sg WHERE sg.itemPackingTypeFk IS NOT NULL ORDER BY sg.itemPackingTypeFk LIMIT 1; - UPDATE vn.sale s - JOIN tmp.sale ts ON ts.id = s.id + UPDATE sale s + JOIN tSale ts ON ts.id = s.id JOIN tmp.ticketIPT t ON t.itemPackingTypeFk = vItemPackingTypeFk SET s.ticketFk = t.ticketFk WHERE ts.itemPackingTypeFk IS NULL; END CASE; + COMMIT; + DROP TEMPORARY TABLE - tmp.sale, - tmp.saleGroup; + tSale, + tSaleGroup; END$$ DELIMITER ; From 32793990ec6d86b0ab24181db3416f305c5a3d90 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 8 Jul 2024 14:01:18 +0200 Subject: [PATCH 076/170] refactor: refs #7662 Minor change --- db/routines/vn/procedures/collection_new.sql | 1 - .../ticket_splitItemPackingType.sql | 20 +++++++++---------- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/db/routines/vn/procedures/collection_new.sql b/db/routines/vn/procedures/collection_new.sql index 029427306..cd4b1b47f 100644 --- a/db/routines/vn/procedures/collection_new.sql +++ b/db/routines/vn/procedures/collection_new.sql @@ -229,7 +229,6 @@ BEGIN AND ((vTicketVolume + @volume) <= vVolumeLimit OR vVolumeLimit IS NULL) THEN CALL ticket_splitItemPackingType(vTicketFk, vItemPackingTypeFk); - DROP TEMPORARY TABLE tmp.ticketIPT; UPDATE tmp.productionBuffer pb JOIN ( diff --git a/db/routines/vn/procedures/ticket_splitItemPackingType.sql b/db/routines/vn/procedures/ticket_splitItemPackingType.sql index bc4c94d46..2a84948c9 100644 --- a/db/routines/vn/procedures/ticket_splitItemPackingType.sql +++ b/db/routines/vn/procedures/ticket_splitItemPackingType.sql @@ -10,7 +10,6 @@ BEGIN * * @param vSelf Id ticket * @param vItemPackingTypeFk Tipo para el que se reserva el número de ticket original - * @return table tmp.ticketIPT(ticketFk, itemPackingTypeFk) */ DECLARE vItemPackingTypeFk VARCHAR(1) DEFAULT 'H'; DECLARE vNewTicketFk INT; @@ -61,17 +60,17 @@ BEGIN FROM tSaleGroup WHERE itemPackingTypeFk IS NOT NULL; - CREATE OR REPLACE TEMPORARY TABLE tmp.ticketIPT( + CREATE OR REPLACE TEMPORARY TABLE tTicketIPT( ticketFk INT, itemPackingTypeFk VARCHAR(1) ) ENGINE = MEMORY; CASE vPackingTypesToSplit WHEN 0 THEN - INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) + INSERT INTO tTicketIPT(ticketFk, itemPackingTypeFk) VALUES(vSelf, vItemPackingTypeFk); WHEN 1 THEN - INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) + INSERT INTO tTicketIPT(ticketFk, itemPackingTypeFk) SELECT vSelf, itemPackingTypeFk FROM tSaleGroup WHERE itemPackingTypeFk IS NOT NULL; @@ -79,7 +78,7 @@ BEGIN OPEN vSaleGroup; FETCH vSaleGroup INTO vItemPackingTypeFk; - INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) + INSERT INTO tTicketIPT(ticketFk, itemPackingTypeFk) VALUES(vSelf, vItemPackingTypeFk); l: LOOP @@ -92,7 +91,7 @@ BEGIN CALL ticket_Clone(vSelf, vNewTicketFk); - INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) + INSERT INTO tTicketIPT(ticketFk, itemPackingTypeFk) VALUES(vNewTicketFk, vItemPackingTypeFk); END LOOP; @@ -101,13 +100,13 @@ BEGIN SELECT s.id FROM sale s JOIN tSale ts ON ts.id = s.id - JOIN tmp.ticketIPT t ON t.itemPackingTypeFk = ts.itemPackingTypeFk + JOIN tTicketIPT t ON t.itemPackingTypeFk = ts.itemPackingTypeFk WHERE s.ticketFk = vSelf FOR UPDATE; UPDATE sale s JOIN tSale ts ON ts.id = s.id - JOIN tmp.ticketIPT t ON t.itemPackingTypeFk = ts.itemPackingTypeFk + JOIN tTicketIPT t ON t.itemPackingTypeFk = ts.itemPackingTypeFk SET s.ticketFk = t.ticketFk; SELECT itemPackingTypeFk INTO vItemPackingTypeFk @@ -118,7 +117,7 @@ BEGIN UPDATE sale s JOIN tSale ts ON ts.id = s.id - JOIN tmp.ticketIPT t ON t.itemPackingTypeFk = vItemPackingTypeFk + JOIN tTicketIPT t ON t.itemPackingTypeFk = vItemPackingTypeFk SET s.ticketFk = t.ticketFk WHERE ts.itemPackingTypeFk IS NULL; END CASE; @@ -127,6 +126,7 @@ BEGIN DROP TEMPORARY TABLE tSale, - tSaleGroup; + tSaleGroup, + tTicketIPT; END$$ DELIMITER ; From eaca3427772d8c02d6ccc5ad600b2fb075d67dd4 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 8 Jul 2024 14:11:55 +0200 Subject: [PATCH 077/170] refactor: refs #7662 Minor change --- db/routines/vn/procedures/collection_new.sql | 1 + .../ticket_splitItemPackingType.sql | 19 +++++++++---------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/db/routines/vn/procedures/collection_new.sql b/db/routines/vn/procedures/collection_new.sql index cd4b1b47f..029427306 100644 --- a/db/routines/vn/procedures/collection_new.sql +++ b/db/routines/vn/procedures/collection_new.sql @@ -229,6 +229,7 @@ BEGIN AND ((vTicketVolume + @volume) <= vVolumeLimit OR vVolumeLimit IS NULL) THEN CALL ticket_splitItemPackingType(vTicketFk, vItemPackingTypeFk); + DROP TEMPORARY TABLE tmp.ticketIPT; UPDATE tmp.productionBuffer pb JOIN ( diff --git a/db/routines/vn/procedures/ticket_splitItemPackingType.sql b/db/routines/vn/procedures/ticket_splitItemPackingType.sql index 2a84948c9..87fbafe13 100644 --- a/db/routines/vn/procedures/ticket_splitItemPackingType.sql +++ b/db/routines/vn/procedures/ticket_splitItemPackingType.sql @@ -60,17 +60,17 @@ BEGIN FROM tSaleGroup WHERE itemPackingTypeFk IS NOT NULL; - CREATE OR REPLACE TEMPORARY TABLE tTicketIPT( + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketIPT( ticketFk INT, itemPackingTypeFk VARCHAR(1) ) ENGINE = MEMORY; CASE vPackingTypesToSplit WHEN 0 THEN - INSERT INTO tTicketIPT(ticketFk, itemPackingTypeFk) + INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) VALUES(vSelf, vItemPackingTypeFk); WHEN 1 THEN - INSERT INTO tTicketIPT(ticketFk, itemPackingTypeFk) + INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) SELECT vSelf, itemPackingTypeFk FROM tSaleGroup WHERE itemPackingTypeFk IS NOT NULL; @@ -78,7 +78,7 @@ BEGIN OPEN vSaleGroup; FETCH vSaleGroup INTO vItemPackingTypeFk; - INSERT INTO tTicketIPT(ticketFk, itemPackingTypeFk) + INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) VALUES(vSelf, vItemPackingTypeFk); l: LOOP @@ -91,7 +91,7 @@ BEGIN CALL ticket_Clone(vSelf, vNewTicketFk); - INSERT INTO tTicketIPT(ticketFk, itemPackingTypeFk) + INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) VALUES(vNewTicketFk, vItemPackingTypeFk); END LOOP; @@ -100,13 +100,13 @@ BEGIN SELECT s.id FROM sale s JOIN tSale ts ON ts.id = s.id - JOIN tTicketIPT t ON t.itemPackingTypeFk = ts.itemPackingTypeFk + JOIN tmp.ticketIPT t ON t.itemPackingTypeFk = ts.itemPackingTypeFk WHERE s.ticketFk = vSelf FOR UPDATE; UPDATE sale s JOIN tSale ts ON ts.id = s.id - JOIN tTicketIPT t ON t.itemPackingTypeFk = ts.itemPackingTypeFk + JOIN tmp.ticketIPT t ON t.itemPackingTypeFk = ts.itemPackingTypeFk SET s.ticketFk = t.ticketFk; SELECT itemPackingTypeFk INTO vItemPackingTypeFk @@ -117,7 +117,7 @@ BEGIN UPDATE sale s JOIN tSale ts ON ts.id = s.id - JOIN tTicketIPT t ON t.itemPackingTypeFk = vItemPackingTypeFk + JOIN tmp.ticketIPT t ON t.itemPackingTypeFk = vItemPackingTypeFk SET s.ticketFk = t.ticketFk WHERE ts.itemPackingTypeFk IS NULL; END CASE; @@ -126,7 +126,6 @@ BEGIN DROP TEMPORARY TABLE tSale, - tSaleGroup, - tTicketIPT; + tSaleGroup; END$$ DELIMITER ; From f1276d6f560bf59baaaf01a7721957352bf0ef20 Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 8 Jul 2024 14:51:50 +0200 Subject: [PATCH 078/170] changelog --- CHANGELOG.md | 80 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b322f9f25..4572b137a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,83 @@ +# Version 24.28 - 2024-07-09 + +### Added 🆕 + +- feat boxPicking refs #7357 by:sergiodt +- feat boxPicking refs #7357 (origin/7357_dipole_review) by:sergiodt +- feat:concurrency issue refs #6861 by:Carlos Andrés +- feat expeditionPalletPrint refs #5210 by:sergiodt +- feat front-reservas refs #6861 (origin/6861-Reservas-front) by:sergiodt +- feat itemShelving_filterBuyer refs #7023 by:sergiodt +- feat itemShelvingLog refs #7168 by:sergiodt +- feat itemShelvingSale refs #6861 by:sergiodt +- feat: previas con reserva refs #6861 by:Carlos Andrés +- feat: previas con sitema de reservas refs #6861 by:Carlos Andrés +- feat: previas con sitema de reservas refs #6861 (origin/6861-Pasar-modo-trabajo-de-previa-a-reservas) by:Carlos Andrés +- feat refactor setParking REGEXP refs #7575 (origin/7575_setParking_regExp) by:sergiodt +- feat: refs #6238 add travelKgPercentage table and model (origin/6238-addPercentage) by:jorgep +- feat: refs #6286 check if is teamBoss (origin/6286-setRightWorkerTimeControlAcls) by:jorgep +- feat: refs #6701 Fix error by:guillermo +- feat: refs #6861 trigger by:sergiodt +- feat: refs #7027 mailError managed by:jgallego +- feat: refs #7168 Added vRecords param in proc by:guillermo +- feat: refs #7168 Minor change by:guillermo +- feat: refs #7216 logUnpaid (origin/7216-clientUnpaid) by:jgallego +- feat: refs #7216 triggers by:jgallego +- feat: refs #7296 by:robert +- feat: refs #7296 drop column expeditionTruckFk by:robert +- feat: refs #7490 Changes (origin/7490-duaInvoiceInBooking) by:guillermo +- feat: refs #7545 Deleted hasIncoterms client column (origin/7545-hasIncoterms) by:guillermo +- feat: refs #7555 remove account.password__ by:alexm +- feat: return sql check error by:alexm +- feat roadmap refs #7195 by:sergiodt +- #refs 5890 feat:add assignCollection by:sergiodt +- refs#5890 feat: delete trigger and modify getTickets by:sergiodt +- refs #5890 feat:itemShelving_add by:sergiodt +- refs #5890 feat:reserves by:sergiodt +- refs #5890 feat:trigger by:sergiodt +- refs #5890 feat: triggers by:sergiodt +- refs #6861 feat: getLock by:sergiodt +- refs #6861 feat: obsrevation by:sergiodt +- refs #6861 feat: previas a reservas by:sergiodt +- refs #6861 feat:reserve previos by:sergiodt +- refs #6861 feat: reservePrevious by:sergiodt +- refs #6861 feat:reserveWithReservation by:sergiodt +- refs #6861 feat:sectoCollection reserve by:sergiodt +- refs #6861 feat: skipTest by:sergiodt +- refs #6861 feat: trigger by:sergiodt + +### Changed 📦 + +- feat refactor setParking REGEXP refs #7575 (origin/7575_setParking_regExp) by:sergiodt +- refactor: refs #5447 changed models by:Jon +- refactor: refs #6238 drop useless round by:jorgep +- refactor: refs #6286 replace name by:jorgep +- refactor: refs #6701 Refactor claim_ratio_routine by:guillermo +- refactor: refs #7490 Added final update by:guillermo +- refactor: refs #7490 Deleted update duaInvoiceInBooking by:guillermo +- refactor: refs #7490 Minor changes by:guillermo +- refactor: refs #7519 Minor change by:guillermo + +### Fixed 🛠️ + +- acls, fixtures, models by:carlossa +- fix: refs #6238 delete unused SQL script by:jorgep +- fix: refs #6238 insert ignore by:jorgep +- fix: refs #6238 use scheme by:jorgep +- fix: refs #6286 replace id for reason by:jorgep +- fix: refs #6286 update WorkerTimeControl permissions by:jorgep +- fix(WorkerIncome): refs #7409 fix models by:alexm +- refs #5890 fix: dev by:sergiodt +- refs #6897 fix entry Salix by:carlossa +- refs #6897 fix es.yml by:carlossa +- refs #6897 fix redirection by:carlossa +- refs #6897 fix remove by:carlossa +- refs #7406 fix back by:carlossa +- refs #7406 fix pr by:carlossa +- refs #7409 fix acls by:carlossa +- refs #7409 fix back (origin/7409-workerIncome) by:carlossa +- refs #7409 fix pr by:carlossa + # Version 24.24 - 2024-06-11 ### Added 🆕 From 213524edb598e989e665f21c54982aed3a972079 Mon Sep 17 00:00:00 2001 From: alexm Date: Tue, 9 Jul 2024 07:52:18 +0200 Subject: [PATCH 079/170] deploy: dump db --- db/dump/.dump/data.sql | 53 +- db/dump/.dump/privileges.sql | 54 +- db/dump/.dump/structure.sql | 5799 +++++++++++++++++++--------------- db/dump/.dump/triggers.sql | 105 +- 4 files changed, 3415 insertions(+), 2596 deletions(-) diff --git a/db/dump/.dump/data.sql b/db/dump/.dump/data.sql index c979ea1a2..43f686022 100644 --- a/db/dump/.dump/data.sql +++ b/db/dump/.dump/data.sql @@ -3,7 +3,7 @@ USE `util`; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -INSERT INTO `version` VALUES ('vn-database','11114','cf0f80142fed798c3307565a69158d7dba9276c4','2024-06-25 09:25:54','11115'); +INSERT INTO `version` VALUES ('vn-database','11117','5558e69e648c3819d4a1edf86f8df4b94d36e71a','2024-07-09 07:39:39','11141'); INSERT INTO `versionLog` VALUES ('vn-database','10107','00-firstScript.sql','jenkins@10.0.2.69','2022-04-23 10:53:53',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10112','00-firstScript.sql','jenkins@10.0.2.69','2022-05-09 09:14:53',NULL,NULL); @@ -644,6 +644,7 @@ INSERT INTO `versionLog` VALUES ('vn-database','10849','15-invoiceInLog.sql','je INSERT INTO `versionLog` VALUES ('vn-database','10849','16-travelLog.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:45:55',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10849','17-packingSiteDeviceLog.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:45:55',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10851','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-01-30 13:31:15',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','10852','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:37',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10853','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:46:05',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10853','00-secondScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:46:06',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10854','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-01-30 16:20:34',NULL,NULL); @@ -776,6 +777,7 @@ INSERT INTO `versionLog` VALUES ('vn-database','10975','01-expeditionFk.sql','je INSERT INTO `versionLog` VALUES ('vn-database','10976','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-04-18 07:40:57',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10977','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-04-18 07:40:57',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10978','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:33',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','10983','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:37',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10984','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-07 07:31:59',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10988','00-pbx_prefix.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-04-11 17:00:16',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10990','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-07 07:31:59',NULL,NULL); @@ -844,24 +846,39 @@ INSERT INTO `versionLog` VALUES ('vn-database','11068','00-firstScript.sql','jen INSERT INTO `versionLog` VALUES ('vn-database','11069','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:34',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11070','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:38:13',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11071','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:48',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11073','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:38',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11074','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:35',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11075','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-05-28 12:54:13',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11078','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:35',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11079','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-31 08:22:10',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11080','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-31 12:01:58',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11081','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:38',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11082','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:38:13',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11083','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-03 10:46:36',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11084','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:38:13',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11086','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-27 10:02:02',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11087','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:38:13',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11089','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:39:16',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11090','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:35',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11092','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-07 08:21:23',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11093','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:39:16',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11096','00-addBuyerAcl.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 12:48:51',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11099','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:38',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11100','00-modifyTimeControlAcls.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:38',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11101','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:38',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11102','00-createTravelKgPercentage.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:38',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11103','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:38',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11104','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:38',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11105','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-20 15:36:07',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11106','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:39:49',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11109','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-18 19:09:56',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11110','00-clientUnpaid.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:38',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11111','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:38',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11114','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:39:49',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11116','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:38',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11117','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:38',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11134','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-07-05 11:02:07',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11139','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-07-08 10:58:01',NULL,NULL); /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; @@ -958,6 +975,7 @@ INSERT INTO `role` VALUES (126,'greenhouseBoss','Jefe de invernadero',1,'2023-11 INSERT INTO `role` VALUES (127,'timeControl','Tablet para fichar',1,'2024-01-09 16:36:56','2024-01-09 16:36:56',NULL); INSERT INTO `role` VALUES (129,'buyerAssistant','Comprador que tienes mas permisos para ayudar al buyerBoss en algunas tareas',1,'2024-02-06 06:59:12','2024-02-06 06:59:12',783); INSERT INTO `role` VALUES (130,'reviewer','Revisor de producción',1,'2024-06-11 00:00:00','2024-06-11 00:00:00',10578); +INSERT INTO `role` VALUES (131,'supplier','Privilegios básicos de un proveedor',1,'2024-07-05 10:18:58','2024-07-05 10:18:58',19295); INSERT INTO `roleInherit` VALUES (1,1,2,NULL); INSERT INTO `roleInherit` VALUES (2,1,3,NULL); @@ -1228,6 +1246,8 @@ INSERT INTO `roleInherit` VALUES (368,130,49,10578); INSERT INTO `roleInherit` VALUES (369,50,130,10578); INSERT INTO `roleInherit` VALUES (370,72,130,10578); INSERT INTO `roleInherit` VALUES (371,36,35,NULL); +INSERT INTO `roleInherit` VALUES (372,126,13,19295); +INSERT INTO `roleInherit` VALUES (373,131,2,19295); INSERT INTO `userPassword` VALUES (1,7,1,0,2,1); @@ -1886,12 +1906,12 @@ INSERT INTO `ACL` VALUES (772,'Route','getExpeditionSummary','READ','ALLOW','ROL INSERT INTO `ACL` VALUES (773,'WorkerTimeControl','login','READ','ALLOW','ROLE','timeControl'); INSERT INTO `ACL` VALUES (774,'WorkerTimeControl','getClockIn','READ','ALLOW','ROLE','timeControl'); INSERT INTO `ACL` VALUES (775,'WorkerTimeControl','clockIn','WRITE','ALLOW','ROLE','timeControl'); -INSERT INTO `ACL` VALUES (776,'WorkerTimeControl','addTimeEntry','WRITE','ALLOW','ROLE','employee'); -INSERT INTO `ACL` VALUES (777,'WorkerTimeControl','deleteTimeEntry','WRITE','ALLOW','ROLE','employee'); -INSERT INTO `ACL` VALUES (778,'WorkerTimeControl','updateTimeEntry','WRITE','ALLOW','ROLE','employee'); -INSERT INTO `ACL` VALUES (779,'WorkerTimeControl','sendMail','WRITE','ALLOW','ROLE','employee'); -INSERT INTO `ACL` VALUES (780,'WorkerTimeControl','updateWorkerTimeControlMail','WRITE','ALLOW','ROLE','employee'); -INSERT INTO `ACL` VALUES (781,'WorkerTimeControl','weeklyHourRecordEmail','WRITE','ALLOW','ROLE','employee'); +INSERT INTO `ACL` VALUES (776,'WorkerTimeControl','addTimeEntry','WRITE','ALLOW','ROLE','teamBoss'); +INSERT INTO `ACL` VALUES (777,'WorkerTimeControl','deleteTimeEntry','WRITE','ALLOW','ROLE','teamBoss'); +INSERT INTO `ACL` VALUES (778,'WorkerTimeControl','updateTimeEntry','WRITE','ALLOW','ROLE','teamBoss'); +INSERT INTO `ACL` VALUES (779,'WorkerTimeControl','sendMail','WRITE','ALLOW','ROLE','developer'); +INSERT INTO `ACL` VALUES (780,'WorkerTimeControl','updateMailState','WRITE','ALLOW','ROLE','employee'); +INSERT INTO `ACL` VALUES (781,'WorkerTimeControl','weeklyHourRecordEmail','WRITE','ALLOW','ROLE','teamBoss'); INSERT INTO `ACL` VALUES (782,'WorkerTimeControl','getMailStates','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (783,'WorkerTimeControl','resendWeeklyHourEmail','WRITE','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (784,'VnRole','*','READ','ALLOW','ROLE','employee'); @@ -1941,7 +1961,6 @@ INSERT INTO `ACL` VALUES (830,'InvoiceIn','*','READ','ALLOW','ROLE','deliveryBos INSERT INTO `ACL` VALUES (831,'InvoiceIn','exchangeRateUpdate','*','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (832,'AgencyLog','*','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (833,'AgencyWorkCenter','*','READ','ALLOW','ROLE','employee'); -INSERT INTO `ACL` VALUES (834,'AgencyMode','*','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (835,'Agency','*','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (836,'Agency','*','WRITE','ALLOW','ROLE','deliveryAssistant'); INSERT INTO `ACL` VALUES (837,'AgencyWorkCenter','*','WRITE','ALLOW','ROLE','deliveryAssistant'); @@ -1983,6 +2002,24 @@ INSERT INTO `ACL` VALUES (874,'Roadmap','*','READ','ALLOW','ROLE','production'); INSERT INTO `ACL` VALUES (875,'RoadmapStop','*','WRITE','ALLOW','ROLE','palletizerBoss'); INSERT INTO `ACL` VALUES (876,'RoadmapStop','*','READ','ALLOW','ROLE','production'); INSERT INTO `ACL` VALUES (877,'TravelKgPercentage','*','READ','ALLOW','ROLE','employee'); +INSERT INTO `ACL` VALUES (878,'MrwConfig','getLabel','READ','ALLOW','ROLE','employee'); +INSERT INTO `ACL` VALUES (879,'AgencyMode','*','*','ALLOW','ROLE','deliveryAssistant'); +INSERT INTO `ACL` VALUES (880,'Collection','assignCollection','WRITE','ALLOW','ROLE','production'); +INSERT INTO `ACL` VALUES (881,'TrainingCourse','*','*','ALLOW','ROLE','hr'); +INSERT INTO `ACL` VALUES (882,'TrainingCourseType','*','*','ALLOW','ROLE','hr'); +INSERT INTO `ACL` VALUES (883,'TrainingCenter','*','*','ALLOW','ROLE','hr'); +INSERT INTO `ACL` VALUES (884,'Worker','__get__trainingCourse','*','ALLOW','ROLE','hr'); +INSERT INTO `ACL` VALUES (885,'WorkerTimeControl','addTimeEntry','WRITE','ALLOW','ROLE','hr'); +INSERT INTO `ACL` VALUES (886,'WorkerTimeControl','deleteTimeEntry','WRITE','ALLOW','ROLE','hr'); +INSERT INTO `ACL` VALUES (887,'WorkerTimeControl','updateTimeEntry','WRITE','ALLOW','ROLE','hr'); +INSERT INTO `ACL` VALUES (888,'WorkerTimeControl','weeklyHourRecordEmail','WRITE','ALLOW','ROLE','hr'); +INSERT INTO `ACL` VALUES (889,'WorkerTimeControl','sendMail','WRITE','ALLOW','ROLE','hr'); +INSERT INTO `ACL` VALUES (890,'WorkerTimeControl','updateMailState','WRITE','ALLOW','ROLE','hr'); +INSERT INTO `ACL` VALUES (891,'TravelKgPercentage','*','READ','ALLOW','ROLE','employee'); +INSERT INTO `ACL` VALUES (892,'WorkerIncome','*','*','ALLOW','ROLE','hr'); +INSERT INTO `ACL` VALUES (893,'PayrollComponent','*','*','ALLOW','ROLE','hr'); +INSERT INTO `ACL` VALUES (894,'Worker','__get__incomes','*','ALLOW','ROLE','hr'); +INSERT INTO `ACL` VALUES (895,'ItemShelvingLog','*','READ','ALLOW','ROLE','production'); INSERT INTO `fieldAcl` VALUES (1,'Client','name','update','employee'); INSERT INTO `fieldAcl` VALUES (2,'Client','contact','update','employee'); diff --git a/db/dump/.dump/privileges.sql b/db/dump/.dump/privileges.sql index b99a60395..c063df7ae 100644 --- a/db/dump/.dump/privileges.sql +++ b/db/dump/.dump/privileges.sql @@ -259,7 +259,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','albaran' INSERT IGNORE INTO `tables_priv` VALUES ('','vncontrol','salesPerson','inter','alexm@%','0000-00-00 00:00:00','Insert',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','albaran_gestdoc','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','albaran_state','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Articles','alexm@%','0000-00-00 00:00:00','Select,Insert,Update',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Articles','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','awb','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','awb','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','awb_component','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); @@ -281,8 +281,6 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vncontrol','employee','inter','ale INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','awb_gestdoc','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','awb','alexm@%','0000-00-00 00:00:00','Insert,Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','agency','alexm@%','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','buySource','alexm@%','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','buy_edi','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','buy_edi_k04','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','buy_edi_k03','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','buy_edi_k04','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); @@ -313,7 +311,6 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','Cajas',' INSERT IGNORE INTO `tables_priv` VALUES ('','vn','production','cmrConfig','guillermo@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','hrBoss','awb_recibida','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','hrBoss','awb','juan@%','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Compres','alexm@%','0000-00-00 00:00:00','Select,Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','buy_edi','alexm@%','0000-00-00 00:00:00','Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','salix','developer','ACL','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','Vehiculos_consumo','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); @@ -348,7 +345,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','empresa','alex INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','sectorType','guillermo@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','Tintas','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','claimManager','Movimientos','juan@%','0000-00-00 00:00:00','Insert,Delete',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Entradas','guillermo@10.5.1.3','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','Compres','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','salesPerson','ticket_observation','juan@%','0000-00-00 00:00:00','Insert,Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Entradas_dits','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','sale','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); @@ -364,7 +361,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','tickets_ INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','hrBoss','tickets_gestdoc','alexm@%','0000-00-00 00:00:00','Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','tickets_gestdoc','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Tickets','alexm@%','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','Entradas','alexm@%','0000-00-00 00:00:00','Update',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','Entradas','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyerBoss','Tintas','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','filtros','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','Entradas_kop','alexm@%','0000-00-00 00:00:00','Select',''); @@ -372,9 +369,9 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','flight','jenki INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','warehouse_pickup','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','zones','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','claimManager','warehouse_pickup','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','businessReasonEnd','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','businessCalendar','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','business','alexm@%','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','Entradas','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','buy','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','buySource','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','adminOfficer','budgetNotes','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','packager','specialLabels','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','budgetDms','alexm@%','0000-00-00 00:00:00','Select,Insert',''); @@ -383,7 +380,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','edi','grafana','offerList','juan@d INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','bookingPlanner','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','budgetInvoiceIn','juan@10.5.1.2','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','beach','alexm@%','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','business','alexm@%','0000-00-00 00:00:00','Insert,Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','business','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','Movimientos_revisar','alexm@%','0000-00-00 00:00:00','Select,Insert',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Movimientos_mark','alexm@%','0000-00-00 00:00:00','Select,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','Movimientos_componentes','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); @@ -414,7 +411,6 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','salesPerson','Movimientos INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','handmadeBoss','Reservas','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyerBoss','bankEntity','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','Ordenes','alexm@%','0000-00-00 00:00:00','Select,Update',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','awb','juan@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Origen','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','pago','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','awb','alexm@%','0000-00-00 00:00:00','Update',''); @@ -485,7 +481,6 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','absenceType','alexm@%',' INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','artificialBoss','Entradas_Auto','alexm@%','0000-00-00 00:00:00','Select,Insert',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','productionAssi','Vehiculos_consumo','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','tblContadores','alexm@%','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','buyMark','juan@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','calendar','juan@10.5.1.2','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','calendarHolidays','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','claimManager','claim','alexm@%','0000-00-00 00:00:00','Select',''); @@ -638,7 +633,6 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','ppeGroup','a INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','floramondoNotOfferDay__','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','fuelType','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','ppeDMS','alexm@%','0000-00-00 00:00:00','Select,Insert,Delete',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','manager','genericAllocation','alexm@%','0000-00-00 00:00:00','Select,Insert,Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','ppeComponent','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','ppe','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','glsExpedition__','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); @@ -744,7 +738,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','mrw','guille INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','mrwService','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','ppePlan','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hrBoss','accountingConfig','alexm@%','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','buy','alexm@%','0000-00-00 00:00:00','Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','buy','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','buy','alexm@%','0000-00-00 00:00:00','Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','saleGoal','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','packager','packingSiteLog','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Insert',''); @@ -759,9 +753,8 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenance','moving','guill INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hrBoss','machineDetail','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hrBoss','machineDms','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','claimManager','vehicle','alexm@%','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','awb','alexm@%','0000-00-00 00:00:00','Insert,Update',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','awb','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hrBoss','machine','alexm@%','0000-00-00 00:00:00','Select,Insert,Update',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','buy','juan@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select,Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','Entradas_dits','alexm@%','0000-00-00 00:00:00','Insert,Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','workerTimeControlMail','alexm@%','0000-00-00 00:00:00','Select,Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','bi','coolerBoss','rotacion','alexm@%','0000-00-00 00:00:00','Select',''); @@ -909,7 +902,6 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','adminBoss','ticketService','a INSERT IGNORE INTO `tables_priv` VALUES ('','vn','adminBoss','ticketServiceType','alexm@%','0000-00-00 00:00:00','Select,Insert',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','ticketState','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','ticketStateToday','alexm@%','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','bi','employee','claims_ratio','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','greugeType','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','time','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','ticketWeekly','alexm@%','0000-00-00 00:00:00','Select',''); @@ -1404,6 +1396,12 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','roadmapStop','guill INSERT IGNORE INTO `tables_priv` VALUES ('','vn','production','roadmapStop','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','agencyWorkCenter','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','roadmapStop','guillermo@10.5.1.3','0000-00-00 00:00:00','Insert,Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','greenhouseBoss','business','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','teamBoss','business','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','ticketServiceType','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','business','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','','Select'); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','supplierAgencyTerm','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','clientRate','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','entryEditor','Entradas','guillermo@10.5.1.3','0000-00-00 00:00:00','Insert','Update'); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','clientInforma','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','solunionCAP','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); @@ -1422,6 +1420,17 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBoss','expedition INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBoss','failureLog','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBoss','movingLog','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBoss','sorterLog','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','genericAllocation','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','businessReasonEnd','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','buy_edi','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','buySource','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','bi','salesPerson','claims_ratio','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','deliveryBoss','albaran','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','deliveryBoss','albaran_gestdoc','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','deliveryBoss','albaran_state','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryBoss','deliveryNote','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryBoss','deliveryNoteDms','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryBoss','deliveryNoteState','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); /*!40000 ALTER TABLE `tables_priv` ENABLE KEYS */; /*!40000 ALTER TABLE `columns_priv` DISABLE KEYS */; @@ -1481,6 +1490,10 @@ INSERT IGNORE INTO `columns_priv` VALUES ('','pbx','grafana','sip','user_id','0 INSERT IGNORE INTO `columns_priv` VALUES ('','pbx','grafana','sip','extension','0000-00-00 00:00:00','Select'); INSERT IGNORE INTO `columns_priv` VALUES ('','account','grafana','user','name','0000-00-00 00:00:00','Select'); INSERT IGNORE INTO `columns_priv` VALUES ('','account','grafana','user','active','0000-00-00 00:00:00','Select'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','business','workerFk','0000-00-00 00:00:00','Select'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','business','id','0000-00-00 00:00:00','Select'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','business','departmentFk','0000-00-00 00:00:00','Select'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','business','companyCodeFk','0000-00-00 00:00:00','Select'); INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','routesMonitor','routeFk','0000-00-00 00:00:00','Update'); INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','routesMonitor','name','0000-00-00 00:00:00','Update'); INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','routesMonitor','beachFk','0000-00-00 00:00:00','Update'); @@ -2018,7 +2031,6 @@ INSERT IGNORE INTO `procs_priv` VALUES ('','account','developer','user_hasrouti INSERT IGNORE INTO `procs_priv` VALUES ('','account','grafana','user_hasRole','FUNCTION','jgallego@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','util','guest','time_generate','PROCEDURE','jenkins@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','itemshelving_addbyclaim','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); -INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','itemshelvingtransfer','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','itemshelving_addlist','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','itemshelving_selfconsumption','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','item_getsimilar','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); @@ -2070,7 +2082,6 @@ INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemshelving_add',' INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemshelving_getsaledate','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemshelving_filterbuyer','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemshelving_addbyclaim','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); -INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemshelvingtransfer','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemshelving_addlist','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemshelving_selfconsumption','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','item_getsimilar','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); @@ -2185,7 +2196,7 @@ INSERT IGNORE INTO `global_priv` VALUES ('','financial','{\"access\": 0, \"vers INSERT IGNORE INTO `global_priv` VALUES ('','financialBoss','{\"access\": 0, \"version_id\": 101106, \"is_role\": true}'); INSERT IGNORE INTO `global_priv` VALUES ('','floranet','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','grafana','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); -INSERT IGNORE INTO `global_priv` VALUES ('','greenhouseBoss','{\"access\":0,\"version_id\":100707,\"is_role\":true}'); +INSERT IGNORE INTO `global_priv` VALUES ('','greenhouseBoss','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','guest','{\"access\": 0, \"max_questions\": 40000, \"max_updates\": 1000, \"max_connections\": 150000, \"max_user_connections\": 200, \"max_statement_time\": 0.000000, \"is_role\": true, \"version_id\": 101106}'); INSERT IGNORE INTO `global_priv` VALUES ('','handmadeBoss','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','hedera-web','{\"access\":0,\"version_id\":100707,\"is_role\":true}'); @@ -2201,7 +2212,7 @@ INSERT IGNORE INTO `global_priv` VALUES ('','logisticBoss','{\"access\":0,\"ver INSERT IGNORE INTO `global_priv` VALUES ('','maintenance','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','maintenanceBos','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','maintenanceBoss','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); -INSERT IGNORE INTO `global_priv` VALUES ('','manager','{\"access\":0,\"version_id\":100707,\"is_role\":true}'); +INSERT IGNORE INTO `global_priv` VALUES ('','manager','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','marketing','{\"access\": 0, \"is_role\": true,\"version_id\":101106}'); INSERT IGNORE INTO `global_priv` VALUES ('','marketingBoss','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','officeBoss','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); @@ -2220,6 +2231,7 @@ INSERT IGNORE INTO `global_priv` VALUES ('','salesPerson','{\"access\": 0, \"is INSERT IGNORE INTO `global_priv` VALUES ('','salesTeamBoss','{\"access\":0,\"version_id\":100707,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','salix','{\"access\":33555456,\"version_id\":100707,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','sysadmin','{\"access\": 201326592, \"is_role\": true, \"version_id\": 100707}'); +INSERT IGNORE INTO `global_priv` VALUES ('','teamBoss','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); /*!40000 ALTER TABLE `global_priv` ENABLE KEYS */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; diff --git a/db/dump/.dump/structure.sql b/db/dump/.dump/structure.sql index 6797c01a5..9b5e9e4a7 100644 --- a/db/dump/.dump/structure.sql +++ b/db/dump/.dump/structure.sql @@ -449,7 +449,6 @@ CREATE TABLE `user` ( `created` timestamp NOT NULL DEFAULT current_timestamp(), `updated` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(), `image` varchar(255) DEFAULT NULL, - `password__` char(64) NOT NULL COMMENT 'Deprecated', `recoverPass` tinyint(3) unsigned NOT NULL DEFAULT 1 COMMENT 'Deprecated', `sync` tinyint(4) NOT NULL DEFAULT 0 COMMENT 'Deprecated', `hasGrant` tinyint(1) NOT NULL, @@ -3109,235 +3108,55 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `analisis_ventas_update`() -BEGIN - DECLARE vLastMonth DATE; - - SET vLastMonth = util.firstDayOfMonth(TIMESTAMPADD(MONTH, -1, util.VN_CURDATE())); - - DELETE FROM analisis_ventas - WHERE Año > YEAR(vLastMonth) - OR (Año = YEAR(vLastMonth) AND Mes >= MONTH(vLastMonth)); - - INSERT INTO analisis_ventas ( - Familia, - Reino, - Comercial, - Comprador, - Provincia, - almacen, - Año, - Mes, - Semana, - Vista, - Importe - ) - SELECT - it.name, - ic.name, - w.code, - w2.code, - p.name, - wa.name, - tm.year, - tm.month, - tm.week, - dm.description, - bt.importe - FROM bs.ventas bt - LEFT JOIN vn.itemType it ON it.id = bt.tipo_id - LEFT JOIN vn.itemCategory ic ON ic.id = it.categoryFk - LEFT JOIN vn.client c on c.id = bt.Id_Cliente - LEFT JOIN vn.worker w ON w.id = c.salesPersonFk - LEFT JOIN vn.worker w2 ON w2.id = it.workerFk - JOIN vn.time tm ON tm.dated = bt.fecha - JOIN vn.sale s ON s.id = bt.Id_Movimiento - LEFT JOIN vn.ticket t ON t.id = s.ticketFk - JOIN vn.agencyMode am ON am.id = t.agencyModeFk - LEFT JOIN vn.deliveryMethod dm ON dm.id = am.deliveryMethodFk - LEFT JOIN vn.address a ON a.id = t.addressFk - LEFT JOIN vn.province p ON p.id = a.provinceFk - LEFT JOIN vn.warehouse wa ON wa.id = t.warehouseFk - WHERE bt.fecha >= vLastMonth AND ic.merchandise; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `claim_ratio_routine` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `claim_ratio_routine`() -BEGIN - DECLARE vMonthToRefund INT DEFAULT 4; - - /* - * PAK 2015-11-20 - * Se trata de añadir a la tabla Greuges todos los - * cargos que luego vamos a utilizar para calcular el recobro - */ - - -- Reclamaciones demasiado sensibles - - INSERT INTO vn.greuge(shipped, clientFk, description, - amount, greugeTypeFk, ticketFk) - SELECT c.ticketCreated - , c.clientFk - , concat('Claim ', c.id,' : ', s.concept) - ,round( -1 * ((c.responsibility -1)/4) * s.quantity * - s.price * (100 - s.discount) / 100, 2) - , 4 - , s.ticketFk - FROM vn.sale s - JOIN vn.claimEnd ce ON ce.saleFk = s.id - JOIN vn.claim c ON c.id = ce.claimFk - WHERE ce.claimDestinationFk NOT IN (1,5) - AND NOT ce.isGreuge - AND c.claimStateFk = 3; - - -- Reclamaciones que pasan a Maná - - INSERT INTO vn.greuge(shipped, clientFk, description, - amount, greugeTypeFk, ticketFk) - SELECT c.ticketCreated - , c.clientFk - , concat('Claim_mana ',c.id,' : ', s.concept) - ,round( ((c.responsibility -1)/4) * s.quantity * s.price * (100 - s.discount) / 100, 2) - ,3 - ,s.ticketFk - FROM vn.sale s - JOIN vn.claimEnd ce ON ce.saleFk = s.id - JOIN vn.claim c ON c.id = ce.claimFk - WHERE ce.claimDestinationFk NOT IN (1,5) - AND NOT ce.isGreuge - AND c.claimStateFk = 3 - AND c.isChargedToMana; - - -- Marcamos para no repetir - UPDATE vn.claimEnd ce - JOIN vn.claim c ON c.id = ce.claimFk - SET ce.isGreuge = TRUE - WHERE ce.claimDestinationFk NOT IN (1,5) - AND NOT ce.isGreuge - AND c.claimStateFk = 3; - - -- Recobros - - DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; - CREATE TEMPORARY TABLE tmp.ticket_list - (PRIMARY KEY (Id_Ticket)) - SELECT DISTINCT t.id Id_Ticket - FROM vn.saleComponent sc - JOIN vn.sale s ON sc.saleFk = s.id - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN vn.ticketLastState ts ON ts.ticketFk = t.id - JOIN vn.ticketTracking tt ON tt.id = ts.ticketTrackingFk - JOIN vn.state st ON st.id = tt.stateFk - JOIN vn.alertLevel al ON al.code = 'DELIVERED' - WHERE sc.componentFk = 17 - AND sc.isGreuge = 0 - AND t.shipped >= '2016-10-01' - AND t.shipped < util.VN_CURDATE() - AND st.alertLevel >= al.id; - - DELETE g.* - FROM vn.greuge g - JOIN tmp.ticket_list t ON g.ticketFk = t.Id_Ticket - WHERE g.greugeTypeFk = 2; - - INSERT INTO vn.greuge(clientFk, description, amount,shipped, - greugeTypeFk, ticketFk) - SELECT t.clientFk - ,concat('recobro ', s.ticketFk), - round(SUM(sc.value*s.quantity),2) - AS dif, - date(t.shipped) - , 2 - ,tt.Id_Ticket - FROM vn.sale s - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN tmp.ticket_list tt ON tt.Id_Ticket = t.id - JOIN vn.saleComponent sc - ON sc.saleFk = s.id AND sc.componentFk = 17 - GROUP BY t.id - HAVING ABS(dif) > 1; - - UPDATE vn.saleComponent sc - JOIN vn.sale s ON s.id = sc.saleFk - JOIN tmp.ticket_list tt ON tt.Id_Ticket = s.ticketFk - SET sc.isGreuge = 1 - WHERE sc.componentFk = 17; - - /* - * Recalculamos la ratio de las reclamaciones, que luego - * se va a utilizar en el recobro - */ - - REPLACE bi.claims_ratio(Id_Cliente, Consumo, Reclamaciones, Ratio, recobro) - SELECT id, 0,0,0,0 - FROM vn.client; - - REPLACE bi.claims_ratio(Id_Cliente, Consumo, Reclamaciones, Ratio, recobro) - SELECT fm.Id_Cliente, 12 * fm.Consumo, Reclamaciones, - round(Reclamaciones / (12*fm.Consumo),4), 0 - FROM bi.facturacion_media_anual fm - LEFT JOIN( - SELECT c.clientFk, round(sum(-1 * ((c.responsibility -1)/4) * - s.quantity * s.price * (100 - s.discount) / 100)) - AS Reclamaciones - FROM vn.sale s - JOIN vn.claimEnd ce ON ce.saleFk = s.id - JOIN vn.claim c ON c.id = ce.claimFk - WHERE ce.claimDestinationFk NOT IN (1,5) - AND c.claimStateFk = 3 - AND c.ticketCreated >= TIMESTAMPADD(YEAR, -1, util.VN_CURDATE()) - GROUP BY c.clientFk - ) claims ON claims.clientFk = fm.Id_Cliente; - - - -- Calculamos el porcentaje del recobro para añadirlo al precio de venta - UPDATE bi.claims_ratio cr - JOIN ( - SELECT clientFk Id_Cliente, IFNULL(SUM(amount), 0) AS Greuge - FROM vn.greuge - WHERE shipped <= util.VN_CURDATE() - GROUP BY clientFk - ) g ON g.Id_Cliente = cr.Id_Cliente - SET recobro = GREATEST(0,round(IFNULL(Greuge, 0) / - (IFNULL(Consumo, 0) * vMonthToRefund / 12 ) ,3)); - - -- Protección neonatos - UPDATE bi.claims_ratio cr - JOIN vn.firstTicketShipped fts ON fts.clientFk = cr.Id_Cliente - SET recobro = 0, Ratio = 0 - WHERE fts.shipped > TIMESTAMPADD(MONTH,-1,util.VN_CURDATE()); - - -- CLIENTE 7983, JULIAN SUAU - UPDATE bi.claims_ratio SET recobro = LEAST(0.05, recobro) WHERE Id_Cliente = 7983; - - -- CLIENTE 4358 - UPDATE bi.claims_ratio SET recobro = GREATEST(0.05, recobro) WHERE Id_Cliente = 4358; - - -- CLIENTE 5523, VERDECORA - UPDATE bi.claims_ratio SET recobro = GREATEST(0.12, recobro) WHERE Id_Cliente = 5523; - - -- CLIENTE 15979, SERVEIS VETERINARIS - UPDATE bi.claims_ratio SET recobro = GREATEST(0.05, recobro) WHERE Id_Cliente = 15979; - - -- CLIENTE 5189 i 8942, son de CSR i son el mateix client - UPDATE bi.claims_ratio cr - JOIN (SELECT sum(Consumo * recobro)/sum(Consumo) as recobro - FROM bi.claims_ratio - WHERE Id_Cliente IN ( 5189,8942) - ) sub - SET cr.recobro = sub.recobro - WHERE Id_Cliente IN ( 5189,8942); +BEGIN + DECLARE vLastMonth DATE; + + SET vLastMonth = util.firstDayOfMonth(TIMESTAMPADD(MONTH, -1, util.VN_CURDATE())); + + DELETE FROM analisis_ventas + WHERE Año > YEAR(vLastMonth) + OR (Año = YEAR(vLastMonth) AND Mes >= MONTH(vLastMonth)); + + INSERT INTO analisis_ventas ( + Familia, + Reino, + Comercial, + Comprador, + Provincia, + almacen, + Año, + Mes, + Semana, + Vista, + Importe + ) + SELECT + it.name, + ic.name, + w.code, + w2.code, + p.name, + wa.name, + tm.year, + tm.month, + tm.week, + dm.description, + bt.importe + FROM bs.ventas bt + LEFT JOIN vn.itemType it ON it.id = bt.tipo_id + LEFT JOIN vn.itemCategory ic ON ic.id = it.categoryFk + LEFT JOIN vn.client c on c.id = bt.Id_Cliente + LEFT JOIN vn.worker w ON w.id = c.salesPersonFk + LEFT JOIN vn.worker w2 ON w2.id = it.workerFk + JOIN vn.time tm ON tm.dated = bt.fecha + JOIN vn.sale s ON s.id = bt.Id_Movimiento + LEFT JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.agencyMode am ON am.id = t.agencyModeFk + LEFT JOIN vn.deliveryMethod dm ON dm.id = am.deliveryMethodFk + LEFT JOIN vn.address a ON a.id = t.addressFk + LEFT JOIN vn.province p ON p.id = a.provinceFk + LEFT JOIN vn.warehouse wa ON wa.id = t.warehouseFk + WHERE bt.fecha >= vLastMonth AND ic.merchandise; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -3355,21 +3174,21 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `clean`() -BEGIN - DECLARE vDateShort DATETIME; - DECLARE vDateLong DATETIME; - DECLARE vOneYearAgo DATETIME; - - SET vDateShort = TIMESTAMPADD(MONTH, -2, util.VN_CURDATE()); - SET vDateLong = TIMESTAMPADD(MONTH, -18,util.VN_CURDATE()); - SET vOneYearAgo = TIMESTAMPADD(YEAR, -1,util.VN_CURDATE()); - - DELETE FROM bi.Greuge_Evolution - WHERE (Fecha < vDateShort AND weekday(Fecha) != 1) - OR Fecha < vOneYearAgo; - - DELETE FROM bi.defaulters WHERE `date` < vDateLong; - DELETE FROM bi.defaulting WHERE `date` < vDateLong; +BEGIN + DECLARE vDateShort DATETIME; + DECLARE vDateLong DATETIME; + DECLARE vOneYearAgo DATETIME; + + SET vDateShort = TIMESTAMPADD(MONTH, -2, util.VN_CURDATE()); + SET vDateLong = TIMESTAMPADD(MONTH, -18,util.VN_CURDATE()); + SET vOneYearAgo = TIMESTAMPADD(YEAR, -1,util.VN_CURDATE()); + + DELETE FROM bi.Greuge_Evolution + WHERE (Fecha < vDateShort AND weekday(Fecha) != 1) + OR Fecha < vOneYearAgo; + + DELETE FROM bi.defaulters WHERE `date` < vDateLong; + DELETE FROM bi.defaulting WHERE `date` < vDateLong; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -3558,18 +3377,18 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `facturacion_media_anual_update`() -BEGIN - TRUNCATE TABLE bs.clientAnnualConsumption; - - REPLACE bi.facturacion_media_anual(Id_Cliente, Consumo) - SELECT clientFk, avg(Facturacion) - FROM ( - SELECT clientFk, YEAR(issued) year, MONTH(issued) month, sum(amount) as Facturacion - FROM vn.invoiceOut - WHERE issued BETWEEN TIMESTAMPADD(YEAR,-1,util.VN_CURDATE()) AND TIMESTAMPADD(DAY, - DAY(util.VN_CURDATE()),util.VN_CURDATE()) - GROUP BY clientFk, year, month - ) vol - GROUP BY clientFk; +BEGIN + TRUNCATE TABLE bs.clientAnnualConsumption; + + REPLACE bi.facturacion_media_anual(Id_Cliente, Consumo) + SELECT clientFk, avg(Facturacion) + FROM ( + SELECT clientFk, YEAR(issued) year, MONTH(issued) month, sum(amount) as Facturacion + FROM vn.invoiceOut + WHERE issued BETWEEN TIMESTAMPADD(YEAR,-1,util.VN_CURDATE()) AND TIMESTAMPADD(DAY, - DAY(util.VN_CURDATE()),util.VN_CURDATE()) + GROUP BY clientFk, year, month + ) vol + GROUP BY clientFk; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -4934,29 +4753,29 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `carteras_add`() -BEGIN -/** - * Inserta en la tabla @bs.carteras las ventas desde el año pasado - * agrupadas por trabajador, año y mes - */ - DECLARE vYear INT DEFAULT YEAR(util.VN_CURDATE()) - 1; - - DELETE FROM bs.carteras WHERE Año >= vYear; - - CALL util.time_generate( - MAKEDATE(vYear, 1), - (SELECT MAX(fecha) FROM ventas) - ); - - INSERT INTO carteras(Año, Mes , CodigoTrabajador, Peso) - SELECT t.`year`, t.`month`, w.code, SUM(v.importe) - FROM tmp.time t - JOIN 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 - GROUP BY w.code, t.`year`, t.`month`; - - DROP TEMPORARY TABLE tmp.time; +BEGIN +/** + * Inserta en la tabla @bs.carteras las ventas desde el año pasado + * agrupadas por trabajador, año y mes + */ + DECLARE vYear INT DEFAULT YEAR(util.VN_CURDATE()) - 1; + + DELETE FROM bs.carteras WHERE Año >= vYear; + + CALL util.time_generate( + MAKEDATE(vYear, 1), + (SELECT MAX(fecha) FROM ventas) + ); + + INSERT INTO carteras(Año, Mes , CodigoTrabajador, Peso) + SELECT t.`year`, t.`month`, w.code, SUM(v.importe) + FROM tmp.time t + JOIN 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 + GROUP BY w.code, t.`year`, t.`month`; + + DROP TEMPORARY TABLE tmp.time; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -5881,82 +5700,82 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `nightTask_launchAll`() -BEGIN -/** - * Runs all nightly tasks. - */ - DECLARE vDone BOOL; - DECLARE vError VARCHAR(255); - DECLARE vErrorCode VARCHAR(255); - DECLARE vSchema VARCHAR(255); - DECLARE vProcedure VARCHAR(255); - DECLARE vLogMail VARCHAR(255); - DECLARE vNightTaskFk INT; - - DECLARE vQueue CURSOR FOR - SELECT id, `schema`, `procedure` - FROM nightTask - WHERE finished <= util.VN_CURDATE() - OR finished IS NULL - ORDER BY `order`; - - DECLARE CONTINUE HANDLER FOR NOT FOUND - SET vDone = TRUE; - - SET max_sp_recursion_depth = 3; - - SELECT logMail INTO vLogMail - FROM nightTaskConfig LIMIT 1; - - OPEN vQueue; - l: LOOP - SET vDone = FALSE; - FETCH vQueue INTO vNightTaskFk, vSchema, vProcedure; - - IF vDone THEN - LEAVE l; - END IF; - - UPDATE nightTask - SET `started` = util.VN_NOW(), - `finished` = NULL, - `error` = NULL, - `errorCode` = NULL - WHERE id = vNightTaskFk; - - SET vError = NULL; - CALL nightTask_launchTask( - vSchema, - vProcedure, - vError, - vErrorCode - ); - - IF vError IS NOT NULL THEN - IF vLogMail IS NOT NULL THEN - CALL vn.mail_insert( - vLogMail, - NULL, - CONCAT('Nightly task failed (', vSchema, '.', vProcedure, ')'), - CONCAT( - '[', vErrorCode, '] ', vError, CHAR(13, 10), -- Line break - 'See ', SCHEMA(), '.nightTask table for more info.' - ) - ); - END IF; - - UPDATE nightTask - SET `error` = vError, - `errorCode` = vErrorCode - WHERE id = vNightTaskFk; - ELSE - UPDATE nightTask - SET finished = util.VN_NOW(), - lastFinished = util.VN_NOW() - WHERE id = vNightTaskFk; - END IF; - END LOOP; - CLOSE vQueue; +BEGIN +/** + * Runs all nightly tasks. + */ + DECLARE vDone BOOL; + DECLARE vError VARCHAR(255); + DECLARE vErrorCode VARCHAR(255); + DECLARE vSchema VARCHAR(255); + DECLARE vProcedure VARCHAR(255); + DECLARE vLogMail VARCHAR(255); + DECLARE vNightTaskFk INT; + + DECLARE vQueue CURSOR FOR + SELECT id, `schema`, `procedure` + FROM nightTask + WHERE finished <= util.VN_CURDATE() + OR finished IS NULL + ORDER BY `order`; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + SET max_sp_recursion_depth = 3; + + SELECT logMail INTO vLogMail + FROM nightTaskConfig LIMIT 1; + + OPEN vQueue; + l: LOOP + SET vDone = FALSE; + FETCH vQueue INTO vNightTaskFk, vSchema, vProcedure; + + IF vDone THEN + LEAVE l; + END IF; + + UPDATE nightTask + SET `started` = util.VN_NOW(), + `finished` = NULL, + `error` = NULL, + `errorCode` = NULL + WHERE id = vNightTaskFk; + + SET vError = NULL; + CALL nightTask_launchTask( + vSchema, + vProcedure, + vError, + vErrorCode + ); + + IF vError IS NOT NULL THEN + IF vLogMail IS NOT NULL THEN + CALL vn.mail_insert( + vLogMail, + NULL, + CONCAT('Nightly task failed (', vSchema, '.', vProcedure, ')'), + CONCAT( + '[', vErrorCode, '] ', vError, CHAR(13, 10), -- Line break + 'See ', SCHEMA(), '.nightTask table for more info.' + ) + ); + END IF; + + UPDATE nightTask + SET `error` = vError, + `errorCode` = vErrorCode + WHERE id = vNightTaskFk; + ELSE + UPDATE nightTask + SET finished = util.VN_NOW(), + lastFinished = util.VN_NOW() + WHERE id = vNightTaskFk; + END IF; + END LOOP; + CLOSE vQueue; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -6336,8 +6155,8 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `salesByItemTypeDay_addLauncher`() -BEGIN - CALL bs.salesByItemTypeDay_add(util.VN_CURDATE() - INTERVAL 30 DAY, util.VN_CURDATE()); +BEGIN + CALL bs.salesByItemTypeDay_add(util.VN_CURDATE() - INTERVAL 30 DAY, util.VN_CURDATE()); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -7589,27 +7408,27 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `cache_calc_end`(IN `v_calc` INT) -BEGIN - DECLARE v_cache_name VARCHAR(255); - DECLARE v_params VARCHAR(255); - - -- Libera el bloqueo y actualiza la fecha de ultimo refresco. - - UPDATE cache_calc cc JOIN cache c ON c.id = cc.cache_id - SET - cc.last_refresh = NOW(), - cc.expires = ADDTIME(NOW(), c.lifetime), - cc.connection_id = NULL - WHERE cc.id = v_calc; - - SELECT c.name, ca.params INTO v_cache_name, v_params - FROM cache c - JOIN cache_calc ca ON c.id = ca.cache_id - WHERE ca.id = v_calc; - - IF v_cache_name IS NOT NULL THEN - DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, ''))); - END IF; +BEGIN + DECLARE v_cache_name VARCHAR(255); + DECLARE v_params VARCHAR(255); + + -- Libera el bloqueo y actualiza la fecha de ultimo refresco. + + UPDATE cache_calc cc JOIN cache c ON c.id = cc.cache_id + SET + cc.last_refresh = NOW(), + cc.expires = ADDTIME(NOW(), c.lifetime), + cc.connection_id = NULL + WHERE cc.id = v_calc; + + SELECT c.name, ca.params INTO v_cache_name, v_params + FROM cache c + JOIN cache_calc ca ON c.id = ca.cache_id + WHERE ca.id = v_calc; + + IF v_cache_name IS NOT NULL THEN + DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, ''))); + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -7627,89 +7446,89 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `cache_calc_start`(OUT `v_calc` INT, INOUT `v_refresh` INT, IN `v_cache_name` VARCHAR(50), IN `v_params` VARCHAR(100)) -proc: BEGIN - DECLARE v_valid BOOL; - DECLARE v_lock_id VARCHAR(100); - DECLARE v_cache_id INT; - DECLARE v_expires DATETIME; - DECLARE v_clean_time DATETIME; - DECLARE vLastRefresh DATETIME; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - IF v_lock_id IS NOT NULL THEN - DO RELEASE_LOCK(v_lock_id); - END IF; - - RESIGNAL; - END; - - SET v_params = IFNULL(v_params, ''); - - -- Si el servidor se ha reiniciado invalida todos los calculos. - - SELECT COUNT(*) > 0 INTO v_valid FROM cache_valid; - - IF !v_valid - THEN - DELETE FROM cache_calc; - INSERT INTO cache_valid (valid) VALUES (TRUE); - END IF; - - -- Obtiene un bloqueo exclusivo para que no haya problemas de concurrencia. - - SET v_lock_id = CONCAT_WS('/', v_cache_name, v_params); - - IF !GET_LOCK(v_lock_id, 30) - THEN - SET v_calc = NULL; - SET v_refresh = FALSE; - LEAVE proc; - END IF; - - -- Comprueba si el calculo solicitado existe y esta actualizado. - - SELECT c.id, ca.id, ca.expires, ca.last_refresh - INTO v_cache_id, v_calc, v_expires, vLastRefresh - FROM cache c - LEFT JOIN cache_calc ca - ON ca.cache_id = c.id AND ca.params = v_params COLLATE 'utf8_general_ci' - WHERE c.name = v_cache_name COLLATE 'utf8_general_ci'; - - -- Si existe una calculo valido libera el bloqueo y devuelve su identificador. - - IF !v_refresh AND NOW() < v_expires AND vLastRefresh >= CURDATE() - THEN - DO RELEASE_LOCK(v_lock_id); - SET v_refresh = FALSE; - LEAVE proc; - END IF; - - -- Si el calculo no existe le crea una entrada en la tabla de calculos. - - IF v_calc IS NULL - THEN - INSERT INTO cache_calc SET - cache_id = v_cache_id, - cacheName = v_cache_name, - params = v_params, - last_refresh = NULL, - expires = NULL, - connection_id = CONNECTION_ID(); - - SET v_calc = LAST_INSERT_ID(); - ELSE - UPDATE cache_calc - SET - last_refresh = NULL, - expires = NULL, - connection_id = CONNECTION_ID() - WHERE id = v_calc; - END IF; - - -- Si se debe recalcular mantiene el bloqueo y devuelve su identificador. - - SET v_refresh = TRUE; +proc: BEGIN + DECLARE v_valid BOOL; + DECLARE v_lock_id VARCHAR(100); + DECLARE v_cache_id INT; + DECLARE v_expires DATETIME; + DECLARE v_clean_time DATETIME; + DECLARE vLastRefresh DATETIME; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + IF v_lock_id IS NOT NULL THEN + DO RELEASE_LOCK(v_lock_id); + END IF; + + RESIGNAL; + END; + + SET v_params = IFNULL(v_params, ''); + + -- Si el servidor se ha reiniciado invalida todos los calculos. + + SELECT COUNT(*) > 0 INTO v_valid FROM cache_valid; + + IF !v_valid + THEN + DELETE FROM cache_calc; + INSERT INTO cache_valid (valid) VALUES (TRUE); + END IF; + + -- Obtiene un bloqueo exclusivo para que no haya problemas de concurrencia. + + SET v_lock_id = CONCAT_WS('/', v_cache_name, v_params); + + IF !GET_LOCK(v_lock_id, 30) + THEN + SET v_calc = NULL; + SET v_refresh = FALSE; + LEAVE proc; + END IF; + + -- Comprueba si el calculo solicitado existe y esta actualizado. + + SELECT c.id, ca.id, ca.expires, ca.last_refresh + INTO v_cache_id, v_calc, v_expires, vLastRefresh + FROM cache c + LEFT JOIN cache_calc ca + ON ca.cache_id = c.id AND ca.params = v_params COLLATE 'utf8_general_ci' + WHERE c.name = v_cache_name COLLATE 'utf8_general_ci'; + + -- Si existe una calculo valido libera el bloqueo y devuelve su identificador. + + IF !v_refresh AND NOW() < v_expires AND vLastRefresh >= CURDATE() + THEN + DO RELEASE_LOCK(v_lock_id); + SET v_refresh = FALSE; + LEAVE proc; + END IF; + + -- Si el calculo no existe le crea una entrada en la tabla de calculos. + + IF v_calc IS NULL + THEN + INSERT INTO cache_calc SET + cache_id = v_cache_id, + cacheName = v_cache_name, + params = v_params, + last_refresh = NULL, + expires = NULL, + connection_id = CONNECTION_ID(); + + SET v_calc = LAST_INSERT_ID(); + ELSE + UPDATE cache_calc + SET + last_refresh = NULL, + expires = NULL, + connection_id = CONNECTION_ID() + WHERE id = v_calc; + END IF; + + -- Si se debe recalcular mantiene el bloqueo y devuelve su identificador. + + SET v_refresh = TRUE; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -10228,524 +10047,524 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `floramondo_offerRefresh`() -proc: BEGIN - DECLARE vLanded DATETIME; - DECLARE vDone INT DEFAULT FALSE; - DECLARE vFreeId INT; - DECLARE vSupplyResponseFk INT; - DECLARE vLastInserted DATETIME; - DECLARE vIsAuctionDay BOOLEAN; - DECLARE vMaxNewItems INT DEFAULT 10000; - DECLARE vStartingTime DATETIME; - DECLARE vAalsmeerMarketPlaceID VARCHAR(13) DEFAULT '8713783439043'; - DECLARE vDayRange INT; - - DECLARE cur1 CURSOR FOR - SELECT id - FROM edi.item_free; - - DECLARE cur2 CURSOR FOR - SELECT srId - FROM itemToInsert; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - DECLARE EXIT HANDLER FOR SQLSTATE '45000' - BEGIN - ROLLBACK; - RESIGNAL; - END; - - DECLARE CONTINUE HANDLER FOR SQLEXCEPTION - BEGIN - DO RELEASE_LOCK('edi.floramondo_offerRefresh'); - SET @isTriggerDisabled = FALSE; - RESIGNAL; - END; - - IF 'test' = (SELECT environment FROM util.config) THEN - LEAVE proc; - END IF; - - IF !GET_LOCK('edi.floramondo_offerRefresh', 0) THEN - LEAVE proc; - END IF; - - SELECT dayRange INTO vDayRange - FROM offerRefreshConfig; - - IF vDayRange IS NULL THEN - CALL util.throw("Variable vDayRange not declared"); - END IF; - - SET vStartingTime = util.VN_NOW(); - - TRUNCATE edi.offerList; - - INSERT INTO edi.offerList(supplier, total) - SELECT v.name, COUNT(DISTINCT sr.ID) total - FROM edi.supplyResponse sr - JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID - WHERE sr.NumberOfUnits > 0 - AND sr.EmbalageCode != 999 - GROUP BY sr.vmpID; - - UPDATE edi.offerList o - JOIN (SELECT v.name, COUNT(*) total - FROM edi.supplyOffer sr - JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID - GROUP BY sr.vmpID) sub ON o.supplier = sub.name - SET o.`filter` = sub.total; - - -- Elimina de la lista de items libres aquellos que ya existen - DELETE itf.* - FROM edi.item_free itf - JOIN vn.item i ON i.id = itf.id; - - CREATE OR REPLACE TEMPORARY TABLE tmp - (INDEX (`Item_ArticleCode`)) - ENGINE = MEMORY - SELECT t.* - FROM ( - SELECT * - FROM edi.supplyOffer - ORDER BY (MarketPlaceID = vAalsmeerMarketPlaceID) DESC, - NumberOfUnits DESC LIMIT 10000000000000000000) t - GROUP BY t.srId; - - CREATE OR REPLACE TEMPORARY TABLE edi.offer (INDEX (`srID`), INDEX (`EmbalageCode`), - INDEX (`ef1`), INDEX (`ef2`), INDEX (`ef3`), INDEX (`ef4`),INDEX (`ef5`), INDEX (`ef6`), - INDEX (`s1Value`), INDEX (`s2Value`), INDEX (`s3Value`), INDEX (`s4Value`),INDEX (`s5Value`), INDEX (`s6Value`)) - ENGINE = MEMORY - SELECT so.*, - ev1.type_description s1Value, - ev2.type_description s2Value, - ev3.type_description s3Value, - ev4.type_description s4Value, - ev5.type_description s5Value, - ev6.type_description s6Value, - eif1.feature ef1, - eif2.feature ef2, - eif3.feature ef3, - eif4.feature ef4, - eif5.feature ef5, - eif6.feature ef6 - FROM tmp so - LEFT JOIN edi.item_feature eif1 ON eif1.item_id = so.Item_ArticleCode - AND eif1.presentation_order = 1 - AND eif1.expiry_date IS NULL - LEFT JOIN edi.item_feature eif2 ON eif2.item_id = so.Item_ArticleCode - AND eif2.presentation_order = 2 - AND eif2.expiry_date IS NULL - LEFT JOIN edi.item_feature eif3 ON eif3.item_id = so.Item_ArticleCode - AND eif3.presentation_order = 3 - AND eif3.expiry_date IS NULL - LEFT JOIN edi.item_feature eif4 ON eif4.item_id = so.Item_ArticleCode - AND eif4.presentation_order = 4 - AND eif4.expiry_date IS NULL - LEFT JOIN edi.item_feature eif5 ON eif5.item_id = so.Item_ArticleCode - AND eif5.presentation_order = 5 - AND eif5.expiry_date IS NULL - LEFT JOIN edi.item_feature eif6 ON eif6.item_id = so.Item_ArticleCode - AND eif6.presentation_order = 6 - AND eif6.expiry_date IS NULL - LEFT JOIN edi.`value` ev1 ON ev1.type_id = eif1.feature - AND so.s1 = ev1.type_value - LEFT JOIN edi.`value` ev2 ON ev2.type_id = eif2.feature - AND so.s2 = ev2.type_value - LEFT JOIN edi.`value` ev3 ON ev3.type_id = eif3.feature - AND so.s3 = ev3.type_value - LEFT JOIN edi.`value` ev4 ON ev4.type_id = eif4.feature - AND so.s4 = ev4.type_value - LEFT JOIN edi.`value` ev5 ON ev5.type_id = eif5.feature - AND so.s5 = ev5.type_value - LEFT JOIN edi.`value` ev6 ON ev6.type_id = eif6.feature - AND so.s6 = ev6.type_value - ORDER BY Price; - - DROP TEMPORARY TABLE tmp; - - DELETE o - FROM edi.offer o - LEFT JOIN vn.tag t1 ON t1.ediTypeFk = o.ef1 AND t1.overwrite = 'size' - LEFT JOIN vn.tag t2 ON t2.ediTypeFk = o.ef2 AND t2.overwrite = 'size' - LEFT JOIN vn.tag t3 ON t3.ediTypeFk = o.ef3 AND t3.overwrite = 'size' - LEFT JOIN vn.tag t4 ON t4.ediTypeFk = o.ef4 AND t4.overwrite = 'size' - LEFT JOIN vn.tag t5 ON t5.ediTypeFk = o.ef5 AND t5.overwrite = 'size' - LEFT JOIN vn.tag t6 ON t6.ediTypeFk = o.ef6 AND t6.overwrite = 'size' - JOIN vn.floramondoConfig fc ON TRUE - WHERE (t1.id IS NOT NULL AND CONVERT(s1Value, UNSIGNED) > fc.itemMaxSize) - OR (t2.id IS NOT NULL AND CONVERT(s2Value, UNSIGNED) > fc.itemMaxSize) - OR (t3.id IS NOT NULL AND CONVERT(s3Value, UNSIGNED) > fc.itemMaxSize) - OR (t4.id IS NOT NULL AND CONVERT(s4Value, UNSIGNED) > fc.itemMaxSize) - OR (t5.id IS NOT NULL AND CONVERT(s5Value, UNSIGNED) > fc.itemMaxSize) - OR (t6.id IS NOT NULL AND CONVERT(s6Value, UNSIGNED) > fc.itemMaxSize); - - START TRANSACTION; - - -- Actualizamos el campo supplyResponseFk para aquellos articulos que ya estan creados y reutilizamos - UPDATE IGNORE edi.offer o - JOIN vn.item i - ON i.name = o.product_name - AND i.subname <=> o.company_name - AND i.value5 <=> o.s1Value - AND i.value6 <=> o.s2Value - AND i.value7 <=> o.s3Value - AND i.value8 <=> o.s4Value - AND i.value9 <=> o.s5Value - AND i.value10 <=> o.s6Value - AND i.NumberOfItemsPerCask <=> o.NumberOfItemsPerCask - AND i.EmbalageCode <=> o.EmbalageCode - AND i.quality <=> o.Quality - JOIN vn.itemType it ON it.id = i.typeFk - LEFT JOIN vn.sale s ON s.itemFk = i.id - LEFT JOIN vn.ticket t ON t.id = s.ticketFk - AND t.shipped > (util.VN_CURDATE() - INTERVAL 1 WEEK) - LEFT JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk - LEFT JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID - LEFT JOIN edi.putOrder po ON po.supplyResponseID = i.supplyResponseFk - AND po.OrderTradeLineDateTime > (util.VN_CURDATE() - INTERVAL 1 WEEK) - SET i.supplyResponseFk = o.srID - WHERE (sr.ID IS NULL - OR sr.NumberOfUnits = 0 - OR di.LatestOrderDateTime < util.VN_NOW() - OR di.ID IS NULL) - AND it.isInventory - AND t.id IS NULL - AND po.id IS NULL; - - CREATE OR REPLACE TEMPORARY TABLE itemToInsert - ENGINE = MEMORY - SELECT o.*, CAST(NULL AS DECIMAL(6,0)) itemFk - FROM edi.offer o - LEFT JOIN vn.item i ON i.supplyResponseFk = o.srId - WHERE i.id IS NULL - LIMIT vMaxNewItems; - - -- Reciclado de nº de item - OPEN cur1; - OPEN cur2; - - read_loop: LOOP - - FETCH cur2 INTO vSupplyResponseFk; - FETCH cur1 INTO vFreeId; - - IF vDone THEN - LEAVE read_loop; - END IF; - - UPDATE itemToInsert - SET itemFk = vFreeId - WHERE srId = vSupplyResponseFk; - - END LOOP; - - CLOSE cur1; - CLOSE cur2; - - -- Insertamos todos los items en Articles de la oferta - INSERT INTO vn.item(id, - `name`, - longName, - subName, - expenseFk, - typeFk, - intrastatFk, - originFk, - supplyResponseFk, - numberOfItemsPerCask, - embalageCode, - quality, - isFloramondo) - SELECT iti.itemFk, - iti.product_name, - iti.product_name, - iti.company_name, - iti.expenseFk, - iti.itemTypeFk, - iti.intrastatFk, - iti.originFk, - iti.`srId`, - iti.NumberOfItemsPerCask, - iti.EmbalageCode, - iti.Quality, - TRUE - FROM itemToInsert iti; - - -- Inserta la foto de los articulos nuevos (prioridad alta) - INSERT IGNORE INTO vn.itemImageQueue(itemFk, url) - SELECT i.id, PictureReference - FROM itemToInsert ii - JOIN vn.item i ON i.supplyResponseFk = ii.srId - WHERE PictureReference IS NOT NULL - AND i.image IS NULL; - - INSERT INTO edi.`log`(tableName, fieldName,fieldValue) - SELECT 'itemImageQueue','NumImagenesPtes', COUNT(*) - FROM vn.itemImageQueue - WHERE attempts = 0; - - -- Inserta si se añadiesen tags nuevos - INSERT IGNORE INTO vn.tag (name, ediTypeFk) - SELECT description, type_id FROM edi.type; - - -- Desabilita el trigger para recalcular los tags al final - SET @isTriggerDisabled = TRUE; - - -- Inserta los tags sólo en los articulos nuevos - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , ii.product_name, 1 - FROM itemToInsert ii - JOIN vn.tag t ON t.`name` = 'Producto' - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT ii.product_name IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , ii.Quality, 3 - FROM itemToInsert ii - JOIN vn.tag t ON t.`name` = 'Calidad' - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT ii.Quality IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , ii.company_name, 4 - FROM itemToInsert ii - JOIN vn.tag t ON t.`name` = 'Productor' - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT ii.company_name IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s1Value, 5 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef1 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s1Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s2Value, 6 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef2 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s2Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s3Value, 7 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef3 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s3Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s4Value, 8 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef4 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s4Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s5Value, 9 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef5 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s5Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s6Value, 10 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef6 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s6Value IS NULL; - - INSERT IGNORE INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id, IFNULL(ink.name, ik.color), 11 - FROM itemToInsert ii - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - JOIN vn.tag t ON t.`name` = 'Color' - LEFT JOIN edi.feature f ON f.item_id = ii.Item_ArticleCode - LEFT JOIN edi.`type` tp ON tp.type_id = f.feature_type_id - AND tp.`description` = 'Hoofdkleur 1' - LEFT JOIN vn.ink ON ink.dutchCode = f.feature_value - LEFT JOIN vn.itemInk ik ON ik.longName = i.longName - WHERE ink.name IS NOT NULL - OR ik.color IS NOT NULL; - - CREATE OR REPLACE TABLE tmp.item - (PRIMARY KEY (id)) - SELECT i.id FROM vn.item i - JOIN itemToInsert ii ON i.supplyResponseFk = ii.`srId`; - - CALL vn.item_refreshTags(); - - DROP TABLE tmp.item; - - SELECT MIN(LatestDeliveryDateTime) INTO vLanded - FROM edi.supplyResponse sr - JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID - JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID - JOIN vn.floramondoConfig fc - WHERE mp.isLatestOrderDateTimeRelevant - AND di.LatestOrderDateTime > IF( - fc.MaxLatestOrderHour > HOUR(util.VN_NOW()), - util.VN_CURDATE(), - util.VN_CURDATE() + INTERVAL 1 DAY); - - UPDATE vn.floramondoConfig - SET nextLanded = vLanded - WHERE vLanded IS NOT NULL; - - -- Elimina la oferta obsoleta - UPDATE vn.buy b - JOIN vn.entry e ON e.id = b.entryFk - JOIN vn.travel tr ON tr.id = e.travelFk - JOIN vn.agencyMode am ON am.id = tr.agencyModeFk - JOIN vn.item i ON i.id = b.itemFk - LEFT JOIN edi.supplyResponse sr ON i.supplyResponseFk = sr.ID - LEFT JOIN edi.deliveryInformation di ON di.ID = b.deliveryFk - SET b.quantity = 0 - WHERE (IFNULL(di.LatestOrderDateTime,util.VN_NOW()) <= util.VN_NOW() - OR i.supplyResponseFk IS NULL - OR sr.NumberOfUnits = 0) - AND am.name = 'LOGIFLORA' - AND e.isRaid; - - -- Localiza las entradas de cada almacen - UPDATE edi.warehouseFloramondo - SET entryFk = vn.entry_getForLogiflora(vLanded + INTERVAL travellingDays DAY, warehouseFk); - - IF vLanded IS NOT NULL THEN - -- Actualiza la oferta existente - UPDATE vn.buy b - JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk - JOIN vn.item i ON i.id = b.itemFk - JOIN edi.offer o ON i.supplyResponseFk = o.`srId` - SET b.quantity = o.NumberOfUnits * o.NumberOfItemsPerCask, - b.buyingValue = o.price - WHERE (b.quantity <> o.NumberOfUnits * o.NumberOfItemsPerCask - OR b.buyingValue <> o.price); - - -- Inserta el resto - SET vLastInserted := util.VN_NOW(); - - -- Inserta la oferta - INSERT INTO vn.buy ( - entryFk, - itemFk, - quantity, - buyingValue, - stickers, - packing, - `grouping`, - groupingMode, - packagingFk, - deliveryFk) - SELECT wf.entryFk, - i.id, - o.NumberOfUnits * o.NumberOfItemsPerCask quantity, - o.Price, - o.NumberOfUnits etiquetas, - o.NumberOfItemsPerCask packing, - GREATEST(1, IFNULL(o.MinimumQuantity,0)) * o.NumberOfItemsPerCask `grouping`, - 'packing', - o.embalageCode, - o.diId - FROM edi.offer o - JOIN vn.item i ON i.supplyResponseFk = o.srId - JOIN edi.warehouseFloramondo wf - JOIN vn.packaging p ON p.id - LIKE o.embalageCode - LEFT JOIN vn.buy b ON b.itemFk = i.id - AND b.entryFk = wf.entryFk - WHERE b.id IS NULL; -- Quitar esta linea y mirar de crear los packages a tiempo REAL - - INSERT INTO vn.itemCost( - itemFk, - warehouseFk, - cm3, - cm3delivery) - SELECT b.itemFk, - wf.warehouseFk, - @cm3 := vn.buy_getUnitVolume(b.id), - IFNULL((vc.standardFlowerBox * 1000) / i.packingOut, @cm3) - FROM warehouseFloramondo wf - JOIN vn.volumeConfig vc - JOIN vn.buy b ON b.entryFk = wf.entryFk - JOIN vn.item i ON i.id = b.itemFk - LEFT JOIN vn.itemCost ic ON ic.itemFk = b.itemFk - AND ic.warehouseFk = wf.warehouseFk - WHERE (ic.cm3 IS NULL OR ic.cm3 = 0) - ON DUPLICATE KEY UPDATE cm3 = @cm3, cm3delivery = IFNULL((vc.standardFlowerBox * 1000) / i.packingOut, @cm3); - - CREATE OR REPLACE TEMPORARY TABLE tmp.buyRecalc - SELECT b.id - FROM vn.buy b - JOIN warehouseFloramondo wf ON wf.entryFk = b.entryFk - WHERE b.created >= vLastInserted; - - CALL vn.buy_recalcPrices(); - - UPDATE edi.offerList o - JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total - FROM vn.buy b - JOIN vn.item i ON i.id = b.itemFk - JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk - JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID - JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk - JOIN vn.warehouse w ON w.id = wf.warehouseFk - WHERE w.name = 'VNH' - AND b.quantity > 0 - GROUP BY sr.vmpID) sub ON o.supplier = sub.name - SET o.vnh = sub.total; - - UPDATE edi.offerList o - JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total - FROM vn.buy b - JOIN vn.item i ON i.id = b.itemFk - JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk - JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID - JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk - JOIN vn.warehouse w ON w.id = wf.warehouseFk - WHERE w.name = 'ALGEMESI' - AND b.quantity > 0 - GROUP BY sr.vmpID) sub ON o.supplier = sub.name - SET o.algemesi = sub.total; - END IF; - - DROP TEMPORARY TABLE - edi.offer, - itemToInsert; - - SET @isTriggerDisabled = FALSE; - - COMMIT; - - -- Esto habria que pasarlo a procesos programados o trabajar con tags y dejar las familias - UPDATE vn.item i - SET typeFk = 121 - WHERE i.longName LIKE 'Rosa Garden %' - AND typeFk = 17; - - UPDATE vn.item i - SET typeFk = 156 - WHERE i.longName LIKE 'Rosa ec %' - AND typeFk = 17; - - -- Refresca las fotos de los items existentes que mostramos (prioridad baja) - INSERT IGNORE INTO vn.itemImageQueue(itemFk, url, priority) - SELECT i.id, sr.PictureReference, 100 - FROM edi.supplyResponse sr - JOIN vn.item i ON i.supplyResponseFk = sr.ID - JOIN edi.supplyOffer so ON so.srId = sr.ID - JOIN hedera.image i2 ON i2.name = i.image - AND i2.collectionFk = 'catalog' - WHERE i2.updated <= (UNIX_TIMESTAMP(util.VN_NOW()) - vDayRange) - AND sr.NumberOfUnits; - - INSERT INTO edi.`log` - SET tableName = 'floramondo_offerRefresh', - fieldName = 'Tiempo de proceso', - fieldValue = TIMEDIFF(util.VN_NOW(), vStartingTime); - - DO RELEASE_LOCK('edi.floramondo_offerRefresh'); +proc: BEGIN + DECLARE vLanded DATETIME; + DECLARE vDone INT DEFAULT FALSE; + DECLARE vFreeId INT; + DECLARE vSupplyResponseFk INT; + DECLARE vLastInserted DATETIME; + DECLARE vIsAuctionDay BOOLEAN; + DECLARE vMaxNewItems INT DEFAULT 10000; + DECLARE vStartingTime DATETIME; + DECLARE vAalsmeerMarketPlaceID VARCHAR(13) DEFAULT '8713783439043'; + DECLARE vDayRange INT; + + DECLARE cur1 CURSOR FOR + SELECT id + FROM edi.item_free; + + DECLARE cur2 CURSOR FOR + SELECT srId + FROM itemToInsert; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + DECLARE EXIT HANDLER FOR SQLSTATE '45000' + BEGIN + ROLLBACK; + RESIGNAL; + END; + + DECLARE CONTINUE HANDLER FOR SQLEXCEPTION + BEGIN + DO RELEASE_LOCK('edi.floramondo_offerRefresh'); + SET @isTriggerDisabled = FALSE; + RESIGNAL; + END; + + IF 'test' = (SELECT environment FROM util.config) THEN + LEAVE proc; + END IF; + + IF !GET_LOCK('edi.floramondo_offerRefresh', 0) THEN + LEAVE proc; + END IF; + + SELECT dayRange INTO vDayRange + FROM offerRefreshConfig; + + IF vDayRange IS NULL THEN + CALL util.throw("Variable vDayRange not declared"); + END IF; + + SET vStartingTime = util.VN_NOW(); + + TRUNCATE edi.offerList; + + INSERT INTO edi.offerList(supplier, total) + SELECT v.name, COUNT(DISTINCT sr.ID) total + FROM edi.supplyResponse sr + JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID + WHERE sr.NumberOfUnits > 0 + AND sr.EmbalageCode != 999 + GROUP BY sr.vmpID; + + UPDATE edi.offerList o + JOIN (SELECT v.name, COUNT(*) total + FROM edi.supplyOffer sr + JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID + GROUP BY sr.vmpID) sub ON o.supplier = sub.name + SET o.`filter` = sub.total; + + -- Elimina de la lista de items libres aquellos que ya existen + DELETE itf.* + FROM edi.item_free itf + JOIN vn.item i ON i.id = itf.id; + + CREATE OR REPLACE TEMPORARY TABLE tmp + (INDEX (`Item_ArticleCode`)) + ENGINE = MEMORY + SELECT t.* + FROM ( + SELECT * + FROM edi.supplyOffer + ORDER BY (MarketPlaceID = vAalsmeerMarketPlaceID) DESC, + NumberOfUnits DESC LIMIT 10000000000000000000) t + GROUP BY t.srId; + + CREATE OR REPLACE TEMPORARY TABLE edi.offer (INDEX (`srID`), INDEX (`EmbalageCode`), + INDEX (`ef1`), INDEX (`ef2`), INDEX (`ef3`), INDEX (`ef4`),INDEX (`ef5`), INDEX (`ef6`), + INDEX (`s1Value`), INDEX (`s2Value`), INDEX (`s3Value`), INDEX (`s4Value`),INDEX (`s5Value`), INDEX (`s6Value`)) + ENGINE = MEMORY + SELECT so.*, + ev1.type_description s1Value, + ev2.type_description s2Value, + ev3.type_description s3Value, + ev4.type_description s4Value, + ev5.type_description s5Value, + ev6.type_description s6Value, + eif1.feature ef1, + eif2.feature ef2, + eif3.feature ef3, + eif4.feature ef4, + eif5.feature ef5, + eif6.feature ef6 + FROM tmp so + LEFT JOIN edi.item_feature eif1 ON eif1.item_id = so.Item_ArticleCode + AND eif1.presentation_order = 1 + AND eif1.expiry_date IS NULL + LEFT JOIN edi.item_feature eif2 ON eif2.item_id = so.Item_ArticleCode + AND eif2.presentation_order = 2 + AND eif2.expiry_date IS NULL + LEFT JOIN edi.item_feature eif3 ON eif3.item_id = so.Item_ArticleCode + AND eif3.presentation_order = 3 + AND eif3.expiry_date IS NULL + LEFT JOIN edi.item_feature eif4 ON eif4.item_id = so.Item_ArticleCode + AND eif4.presentation_order = 4 + AND eif4.expiry_date IS NULL + LEFT JOIN edi.item_feature eif5 ON eif5.item_id = so.Item_ArticleCode + AND eif5.presentation_order = 5 + AND eif5.expiry_date IS NULL + LEFT JOIN edi.item_feature eif6 ON eif6.item_id = so.Item_ArticleCode + AND eif6.presentation_order = 6 + AND eif6.expiry_date IS NULL + LEFT JOIN edi.`value` ev1 ON ev1.type_id = eif1.feature + AND so.s1 = ev1.type_value + LEFT JOIN edi.`value` ev2 ON ev2.type_id = eif2.feature + AND so.s2 = ev2.type_value + LEFT JOIN edi.`value` ev3 ON ev3.type_id = eif3.feature + AND so.s3 = ev3.type_value + LEFT JOIN edi.`value` ev4 ON ev4.type_id = eif4.feature + AND so.s4 = ev4.type_value + LEFT JOIN edi.`value` ev5 ON ev5.type_id = eif5.feature + AND so.s5 = ev5.type_value + LEFT JOIN edi.`value` ev6 ON ev6.type_id = eif6.feature + AND so.s6 = ev6.type_value + ORDER BY Price; + + DROP TEMPORARY TABLE tmp; + + DELETE o + FROM edi.offer o + LEFT JOIN vn.tag t1 ON t1.ediTypeFk = o.ef1 AND t1.overwrite = 'size' + LEFT JOIN vn.tag t2 ON t2.ediTypeFk = o.ef2 AND t2.overwrite = 'size' + LEFT JOIN vn.tag t3 ON t3.ediTypeFk = o.ef3 AND t3.overwrite = 'size' + LEFT JOIN vn.tag t4 ON t4.ediTypeFk = o.ef4 AND t4.overwrite = 'size' + LEFT JOIN vn.tag t5 ON t5.ediTypeFk = o.ef5 AND t5.overwrite = 'size' + LEFT JOIN vn.tag t6 ON t6.ediTypeFk = o.ef6 AND t6.overwrite = 'size' + JOIN vn.floramondoConfig fc ON TRUE + WHERE (t1.id IS NOT NULL AND CONVERT(s1Value, UNSIGNED) > fc.itemMaxSize) + OR (t2.id IS NOT NULL AND CONVERT(s2Value, UNSIGNED) > fc.itemMaxSize) + OR (t3.id IS NOT NULL AND CONVERT(s3Value, UNSIGNED) > fc.itemMaxSize) + OR (t4.id IS NOT NULL AND CONVERT(s4Value, UNSIGNED) > fc.itemMaxSize) + OR (t5.id IS NOT NULL AND CONVERT(s5Value, UNSIGNED) > fc.itemMaxSize) + OR (t6.id IS NOT NULL AND CONVERT(s6Value, UNSIGNED) > fc.itemMaxSize); + + START TRANSACTION; + + -- Actualizamos el campo supplyResponseFk para aquellos articulos que ya estan creados y reutilizamos + UPDATE IGNORE edi.offer o + JOIN vn.item i + ON i.name = o.product_name + AND i.subname <=> o.company_name + AND i.value5 <=> o.s1Value + AND i.value6 <=> o.s2Value + AND i.value7 <=> o.s3Value + AND i.value8 <=> o.s4Value + AND i.value9 <=> o.s5Value + AND i.value10 <=> o.s6Value + AND i.NumberOfItemsPerCask <=> o.NumberOfItemsPerCask + AND i.EmbalageCode <=> o.EmbalageCode + AND i.quality <=> o.Quality + JOIN vn.itemType it ON it.id = i.typeFk + LEFT JOIN vn.sale s ON s.itemFk = i.id + LEFT JOIN vn.ticket t ON t.id = s.ticketFk + AND t.shipped > (util.VN_CURDATE() - INTERVAL 1 WEEK) + LEFT JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk + LEFT JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID + LEFT JOIN edi.putOrder po ON po.supplyResponseID = i.supplyResponseFk + AND po.OrderTradeLineDateTime > (util.VN_CURDATE() - INTERVAL 1 WEEK) + SET i.supplyResponseFk = o.srID + WHERE (sr.ID IS NULL + OR sr.NumberOfUnits = 0 + OR di.LatestOrderDateTime < util.VN_NOW() + OR di.ID IS NULL) + AND it.isInventory + AND t.id IS NULL + AND po.id IS NULL; + + CREATE OR REPLACE TEMPORARY TABLE itemToInsert + ENGINE = MEMORY + SELECT o.*, CAST(NULL AS DECIMAL(6,0)) itemFk + FROM edi.offer o + LEFT JOIN vn.item i ON i.supplyResponseFk = o.srId + WHERE i.id IS NULL + LIMIT vMaxNewItems; + + -- Reciclado de nº de item + OPEN cur1; + OPEN cur2; + + read_loop: LOOP + + FETCH cur2 INTO vSupplyResponseFk; + FETCH cur1 INTO vFreeId; + + IF vDone THEN + LEAVE read_loop; + END IF; + + UPDATE itemToInsert + SET itemFk = vFreeId + WHERE srId = vSupplyResponseFk; + + END LOOP; + + CLOSE cur1; + CLOSE cur2; + + -- Insertamos todos los items en Articles de la oferta + INSERT INTO vn.item(id, + `name`, + longName, + subName, + expenseFk, + typeFk, + intrastatFk, + originFk, + supplyResponseFk, + numberOfItemsPerCask, + embalageCode, + quality, + isFloramondo) + SELECT iti.itemFk, + iti.product_name, + iti.product_name, + iti.company_name, + iti.expenseFk, + iti.itemTypeFk, + iti.intrastatFk, + iti.originFk, + iti.`srId`, + iti.NumberOfItemsPerCask, + iti.EmbalageCode, + iti.Quality, + TRUE + FROM itemToInsert iti; + + -- Inserta la foto de los articulos nuevos (prioridad alta) + INSERT IGNORE INTO vn.itemImageQueue(itemFk, url) + SELECT i.id, PictureReference + FROM itemToInsert ii + JOIN vn.item i ON i.supplyResponseFk = ii.srId + WHERE PictureReference IS NOT NULL + AND i.image IS NULL; + + INSERT INTO edi.`log`(tableName, fieldName,fieldValue) + SELECT 'itemImageQueue','NumImagenesPtes', COUNT(*) + FROM vn.itemImageQueue + WHERE attempts = 0; + + -- Inserta si se añadiesen tags nuevos + INSERT IGNORE INTO vn.tag (name, ediTypeFk) + SELECT description, type_id FROM edi.type; + + -- Desabilita el trigger para recalcular los tags al final + SET @isTriggerDisabled = TRUE; + + -- Inserta los tags sólo en los articulos nuevos + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , ii.product_name, 1 + FROM itemToInsert ii + JOIN vn.tag t ON t.`name` = 'Producto' + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT ii.product_name IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , ii.Quality, 3 + FROM itemToInsert ii + JOIN vn.tag t ON t.`name` = 'Calidad' + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT ii.Quality IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , ii.company_name, 4 + FROM itemToInsert ii + JOIN vn.tag t ON t.`name` = 'Productor' + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT ii.company_name IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s1Value, 5 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef1 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s1Value IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s2Value, 6 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef2 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s2Value IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s3Value, 7 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef3 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s3Value IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s4Value, 8 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef4 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s4Value IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s5Value, 9 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef5 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s5Value IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s6Value, 10 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef6 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s6Value IS NULL; + + INSERT IGNORE INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id, IFNULL(ink.name, ik.color), 11 + FROM itemToInsert ii + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + JOIN vn.tag t ON t.`name` = 'Color' + LEFT JOIN edi.feature f ON f.item_id = ii.Item_ArticleCode + LEFT JOIN edi.`type` tp ON tp.type_id = f.feature_type_id + AND tp.`description` = 'Hoofdkleur 1' + LEFT JOIN vn.ink ON ink.dutchCode = f.feature_value + LEFT JOIN vn.itemInk ik ON ik.longName = i.longName + WHERE ink.name IS NOT NULL + OR ik.color IS NOT NULL; + + CREATE OR REPLACE TABLE tmp.item + (PRIMARY KEY (id)) + SELECT i.id FROM vn.item i + JOIN itemToInsert ii ON i.supplyResponseFk = ii.`srId`; + + CALL vn.item_refreshTags(); + + DROP TABLE tmp.item; + + SELECT MIN(LatestDeliveryDateTime) INTO vLanded + FROM edi.supplyResponse sr + JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID + JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID + JOIN vn.floramondoConfig fc + WHERE mp.isLatestOrderDateTimeRelevant + AND di.LatestOrderDateTime > IF( + fc.MaxLatestOrderHour > HOUR(util.VN_NOW()), + util.VN_CURDATE(), + util.VN_CURDATE() + INTERVAL 1 DAY); + + UPDATE vn.floramondoConfig + SET nextLanded = vLanded + WHERE vLanded IS NOT NULL; + + -- Elimina la oferta obsoleta + UPDATE vn.buy b + JOIN vn.entry e ON e.id = b.entryFk + JOIN vn.travel tr ON tr.id = e.travelFk + JOIN vn.agencyMode am ON am.id = tr.agencyModeFk + JOIN vn.item i ON i.id = b.itemFk + LEFT JOIN edi.supplyResponse sr ON i.supplyResponseFk = sr.ID + LEFT JOIN edi.deliveryInformation di ON di.ID = b.deliveryFk + SET b.quantity = 0 + WHERE (IFNULL(di.LatestOrderDateTime,util.VN_NOW()) <= util.VN_NOW() + OR i.supplyResponseFk IS NULL + OR sr.NumberOfUnits = 0) + AND am.name = 'LOGIFLORA' + AND e.isRaid; + + -- Localiza las entradas de cada almacen + UPDATE edi.warehouseFloramondo + SET entryFk = vn.entry_getForLogiflora(vLanded + INTERVAL travellingDays DAY, warehouseFk); + + IF vLanded IS NOT NULL THEN + -- Actualiza la oferta existente + UPDATE vn.buy b + JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk + JOIN vn.item i ON i.id = b.itemFk + JOIN edi.offer o ON i.supplyResponseFk = o.`srId` + SET b.quantity = o.NumberOfUnits * o.NumberOfItemsPerCask, + b.buyingValue = o.price + WHERE (b.quantity <> o.NumberOfUnits * o.NumberOfItemsPerCask + OR b.buyingValue <> o.price); + + -- Inserta el resto + SET vLastInserted := util.VN_NOW(); + + -- Inserta la oferta + INSERT INTO vn.buy ( + entryFk, + itemFk, + quantity, + buyingValue, + stickers, + packing, + `grouping`, + groupingMode, + packagingFk, + deliveryFk) + SELECT wf.entryFk, + i.id, + o.NumberOfUnits * o.NumberOfItemsPerCask quantity, + o.Price, + o.NumberOfUnits etiquetas, + o.NumberOfItemsPerCask packing, + GREATEST(1, IFNULL(o.MinimumQuantity,0)) * o.NumberOfItemsPerCask `grouping`, + 'packing', + o.embalageCode, + o.diId + FROM edi.offer o + JOIN vn.item i ON i.supplyResponseFk = o.srId + JOIN edi.warehouseFloramondo wf + JOIN vn.packaging p ON p.id + LIKE o.embalageCode + LEFT JOIN vn.buy b ON b.itemFk = i.id + AND b.entryFk = wf.entryFk + WHERE b.id IS NULL; -- Quitar esta linea y mirar de crear los packages a tiempo REAL + + INSERT INTO vn.itemCost( + itemFk, + warehouseFk, + cm3, + cm3delivery) + SELECT b.itemFk, + wf.warehouseFk, + @cm3 := vn.buy_getUnitVolume(b.id), + IFNULL((vc.standardFlowerBox * 1000) / i.packingOut, @cm3) + FROM warehouseFloramondo wf + JOIN vn.volumeConfig vc + JOIN vn.buy b ON b.entryFk = wf.entryFk + JOIN vn.item i ON i.id = b.itemFk + LEFT JOIN vn.itemCost ic ON ic.itemFk = b.itemFk + AND ic.warehouseFk = wf.warehouseFk + WHERE (ic.cm3 IS NULL OR ic.cm3 = 0) + ON DUPLICATE KEY UPDATE cm3 = @cm3, cm3delivery = IFNULL((vc.standardFlowerBox * 1000) / i.packingOut, @cm3); + + CREATE OR REPLACE TEMPORARY TABLE tmp.buyRecalc + SELECT b.id + FROM vn.buy b + JOIN warehouseFloramondo wf ON wf.entryFk = b.entryFk + WHERE b.created >= vLastInserted; + + CALL vn.buy_recalcPrices(); + + UPDATE edi.offerList o + JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total + FROM vn.buy b + JOIN vn.item i ON i.id = b.itemFk + JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk + JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID + JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk + JOIN vn.warehouse w ON w.id = wf.warehouseFk + WHERE w.name = 'VNH' + AND b.quantity > 0 + GROUP BY sr.vmpID) sub ON o.supplier = sub.name + SET o.vnh = sub.total; + + UPDATE edi.offerList o + JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total + FROM vn.buy b + JOIN vn.item i ON i.id = b.itemFk + JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk + JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID + JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk + JOIN vn.warehouse w ON w.id = wf.warehouseFk + WHERE w.name = 'ALGEMESI' + AND b.quantity > 0 + GROUP BY sr.vmpID) sub ON o.supplier = sub.name + SET o.algemesi = sub.total; + END IF; + + DROP TEMPORARY TABLE + edi.offer, + itemToInsert; + + SET @isTriggerDisabled = FALSE; + + COMMIT; + + -- Esto habria que pasarlo a procesos programados o trabajar con tags y dejar las familias + UPDATE vn.item i + SET typeFk = 121 + WHERE i.longName LIKE 'Rosa Garden %' + AND typeFk = 17; + + UPDATE vn.item i + SET typeFk = 156 + WHERE i.longName LIKE 'Rosa ec %' + AND typeFk = 17; + + -- Refresca las fotos de los items existentes que mostramos (prioridad baja) + INSERT IGNORE INTO vn.itemImageQueue(itemFk, url, priority) + SELECT i.id, sr.PictureReference, 100 + FROM edi.supplyResponse sr + JOIN vn.item i ON i.supplyResponseFk = sr.ID + JOIN edi.supplyOffer so ON so.srId = sr.ID + JOIN hedera.image i2 ON i2.name = i.image + AND i2.collectionFk = 'catalog' + WHERE i2.updated <= (UNIX_TIMESTAMP(util.VN_NOW()) - vDayRange) + AND sr.NumberOfUnits; + + INSERT INTO edi.`log` + SET tableName = 'floramondo_offerRefresh', + fieldName = 'Tiempo de proceso', + fieldValue = TIMEDIFF(util.VN_NOW(), vStartingTime); + + DO RELEASE_LOCK('edi.floramondo_offerRefresh'); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -11170,38 +10989,6 @@ CREATE TABLE `recipe` ( -- -- Dumping events for database 'floranet' -- -/*!50106 SET @save_time_zone= @@TIME_ZONE */ ; -/*!50106 DROP EVENT IF EXISTS `clean` */; -DELIMITER ;; -/*!50003 SET @saved_cs_client = @@character_set_client */ ;; -/*!50003 SET @saved_cs_results = @@character_set_results */ ;; -/*!50003 SET @saved_col_connection = @@collation_connection */ ;; -/*!50003 SET character_set_client = utf8mb4 */ ;; -/*!50003 SET character_set_results = utf8mb4 */ ;; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;; -/*!50003 SET @saved_time_zone = @@time_zone */ ;; -/*!50003 SET time_zone = 'SYSTEM' */ ;; -/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `clean` ON SCHEDULE EVERY 1 DAY STARTS '2024-01-01 23:00:00' ON COMPLETION PRESERVE ENABLE DO BEGIN - DELETE - FROM `order` - WHERE created < CURDATE() - AND isPaid = FALSE; - - DELETE c.* - FROM catalogue c - LEFT JOIN `order` o ON o.catalogueFk = c.id - WHERE c.created < CURDATE() - AND o.id IS NULL; -END */ ;; -/*!50003 SET time_zone = @saved_time_zone */ ;; -/*!50003 SET sql_mode = @saved_sql_mode */ ;; -/*!50003 SET character_set_client = @saved_cs_client */ ;; -/*!50003 SET character_set_results = @saved_cs_results */ ;; -/*!50003 SET collation_connection = @saved_col_connection */ ;; -DELIMITER ; -/*!50106 SET TIME_ZONE= @save_time_zone */ ; -- -- Dumping routines for database 'floranet' @@ -11245,11 +11032,12 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `catalogue_get`(vLanded DATE, vPosta READS SQL DATA proc:BEGIN /** - * Returns list, price and all the stuff regarding the floranet items. + * Returns list, price and all the stuff regarding the floranet items, for the designed shop * * @param vLanded Delivery date * @param vPostalCode Delivery address postal code */ + DECLARE vAddressFk INT; DECLARE vLastCatalogueFk INT; DECLARE vLockName VARCHAR(20); DECLARE vLockTime INT; @@ -11260,7 +11048,7 @@ proc:BEGIN RESIGNAL; END; - + SET vLockName = 'catalogue_get'; SET vLockTime = 15; @@ -11271,6 +11059,15 @@ proc:BEGIN SELECT MAX(id) INTO vLastCatalogueFk FROM catalogue; + SELECT addressFk + INTO vAddressFk + FROM addressPostCode apc + WHERE apc.dayOfWeek = dayOfWeek(vLanded) + AND NOW() < vLanded - INTERVAL apc.hoursInAdvance HOUR + AND apc.postCode = vPostalCode + -- Aquí hay que incluir los criterios de selección de tienda + LIMIT 1; + INSERT INTO catalogue( name, price, @@ -11290,17 +11087,14 @@ proc:BEGIN it.name, CONCAT('https://cdn.verdnatura.es/image/catalog/1600x900/', i.image), i.description, - apc.addressFk + vAddressFk FROM vn.item i JOIN (SELECT itemFk, SUM(quantity * cost) price FROM recipe GROUP BY itemFk) r ON r.itemFk = i.id JOIN vn.itemType it ON it.id = i.typeFk - JOIN addressPostCode apc - ON apc.dayOfWeek = dayOfWeek(vLanded) - AND NOW() < vLanded - INTERVAL apc.hoursInAdvance HOUR - AND apc.postCode = vPostalCode - JOIN vn.address a ON a.id = apc.addressFk; + JOIN addressPostCode apc ON addressFk = vAddressFk + JOIN vn.address a ON a.id = vAddressFk; SELECT * FROM catalogue @@ -11324,28 +11118,28 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `contact_request`( - vName VARCHAR(100), - vPhone VARCHAR(15), - vEmail VARCHAR(100), +CREATE DEFINER=`root`@`localhost` PROCEDURE `contact_request`( + vName VARCHAR(100), + vPhone VARCHAR(15), + vEmail VARCHAR(100), vMessage TEXT) READS SQL DATA -BEGIN -/** - * Set actions for contact request - * - * @param vName Name - * @param vPhone Phone number - * @param vEmail e-mail - * @param vMessage text of the message - */ - - CALL vn.mail_insert( - 'floranet@verdnatura.es', - vEmail, - 'Contact request', - CONCAT('Phone: ',vPhone, ' Message: ', vMessage) - ); +BEGIN +/** + * Set actions for contact request + * + * @param vName Name + * @param vPhone Phone number + * @param vEmail e-mail + * @param vMessage text of the message + */ + + CALL vn.mail_insert( + 'floranet@verdnatura.es', + vEmail, + 'Contact request', + CONCAT('Phone: ',vPhone, ' Message: ', vMessage) + ); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -11364,27 +11158,27 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `deliveryDate_get`(vPostalCode VARCHAR(15)) READS SQL DATA -BEGIN -/** - * Returns available dates for this postalCode, in the next seven days. - * - * @param vPostalCode Delivery address postal code - */ - DECLARE vCurrentDayOfWeek INT; - - SET vCurrentDayOfWeek = DAYOFWEEK(NOW()); - - SELECT DISTINCT nextDay - FROM ( - SELECT CURDATE() + INTERVAL IF( - apc.dayOfWeek >= vCurrentDayOfWeek, - apc.dayOfWeek - vCurrentDayOfWeek, - 7 - apc.dayOfWeek - ) DAY nextDay, - NOW() + INTERVAL apc.hoursInAdvance HOUR minDeliveryTime - FROM addressPostCode apc - WHERE apc.postCode = vPostalCode - HAVING nextDay > minDeliveryTime) sub; +BEGIN +/** + * Returns available dates for this postalCode, in the next seven days. + * + * @param vPostalCode Delivery address postal code + */ + DECLARE vCurrentDayOfWeek INT; + + SET vCurrentDayOfWeek = DAYOFWEEK(NOW()); + + SELECT DISTINCT nextDay + FROM ( + SELECT CURDATE() + INTERVAL IF( + apc.dayOfWeek >= vCurrentDayOfWeek, + apc.dayOfWeek - vCurrentDayOfWeek, + 7 - apc.dayOfWeek + ) DAY nextDay, + NOW() + INTERVAL apc.hoursInAdvance HOUR minDeliveryTime + FROM addressPostCode apc + WHERE apc.postCode = vPostalCode + HAVING nextDay > minDeliveryTime) sub; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -11500,7 +11294,7 @@ proc:BEGIN vNewTicketFk, c.itemFk, CONCAT('Entrega: ',c.name), - - c.price, + - apc.deliveryCost, 1 FROM catalogue c JOIN addressPostCode apc @@ -11518,7 +11312,7 @@ proc:BEGIN vNewTicketFk, r.elementFk, i.longName, - r.cost, + 0, r.quantity FROM catalogue c JOIN recipe r ON r.itemFk = c.itemFk @@ -28090,6 +27884,8 @@ DROP TABLE IF EXISTS `claimConfig`; CREATE TABLE `claimConfig` ( `id` int(10) unsigned NOT NULL, `maxResponsibility` int(11) DEFAULT NULL, + `monthsToRefund` int(11) DEFAULT NULL, + `minShipped` date DEFAULT NULL, PRIMARY KEY (`id`), CONSTRAINT `claimConfig_check` CHECK (`id` = 1) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; @@ -28426,7 +28222,7 @@ CREATE TABLE `client` ( `transferorFk` int(11) DEFAULT NULL COMMENT 'Cliente que le ha transmitido la titularidad de la empresa', `lastSalesPersonFk` int(10) unsigned DEFAULT NULL COMMENT 'ultimo comercial que tuvo, para el calculo del peso en los rankings de equipo', `businessTypeFk` varchar(20) NOT NULL DEFAULT 'florist', - `hasIncoterms` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Received incoterms authorization from client', + `hasIncoterms__` tinyint(1) NOT NULL DEFAULT 0 COMMENT '@deprecated 2024-06-12 refs #7545 Received incoterms authorization from client', `rating` int(10) unsigned DEFAULT NULL COMMENT 'información proporcionada por Informa', `recommendedCredit` int(10) unsigned DEFAULT NULL COMMENT 'información proporcionada por Informa', `editorFk` int(10) unsigned DEFAULT NULL, @@ -28880,7 +28676,10 @@ CREATE TABLE `clientUnpaid` ( `clientFk` int(11) NOT NULL, `dated` date NOT NULL, `amount` double DEFAULT 0, + `editorFk` int(10) unsigned DEFAULT NULL, PRIMARY KEY (`clientFk`), + KEY `ClientUnpaid_editorFk` (`editorFk`), + CONSTRAINT `ClientUnpaid_editorFk` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`), CONSTRAINT `clientUnpaid_clientFk` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -33212,6 +33011,7 @@ CREATE TABLE `itemShelving` ( `isChecked` tinyint(1) DEFAULT NULL COMMENT 'Este valor cambia al escanear un carro. True: Existe. False: Nuevo. Null: No escaneado', `buyFk` int(11) DEFAULT NULL, `editorFk` int(10) unsigned DEFAULT NULL, + `available` int(11) DEFAULT NULL, PRIMARY KEY (`id`), KEY `itemShelving_fk1_idx` (`itemFk`), KEY `itemShelving_fk2_idx` (`shelvingFk`), @@ -33381,6 +33181,21 @@ CREATE TABLE `itemShelvingSale` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Detalle del producto que se retira de los carros, relacionando la linea de movimiento correspondiente'; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `itemShelvingSaleReserve` +-- + +DROP TABLE IF EXISTS `itemShelvingSaleReserve`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `itemShelvingSaleReserve` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `saleFk` int(11) NOT NULL, + PRIMARY KEY (`id`), + KEY `itemShelvingSaleReserve_ibfk_1` (`saleFk`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Queue of changed itemShelvingSale to reserve'; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Temporary table structure for view `itemShelvingSaleSum` -- @@ -34371,6 +34186,8 @@ CREATE TABLE `mrwConfig` ( `counterWidth` int(10) unsigned DEFAULT NULL COMMENT 'If it does not reach the required value, it will be padded with zeros on the left to meet the specified length.', `serviceTypeWidth` int(10) unsigned DEFAULT NULL COMMENT 'If it does not reach the required value, it will be padded with zeros on the left to meet the specified length.', `portugalPostCodeTrim` int(10) unsigned DEFAULT NULL COMMENT 'It will trim the last characters of the postal code', + `notified` timestamp NULL DEFAULT NULL COMMENT 'Date when it was notified that the web service deadline was exceeded', + `clientTypeWidth` int(10) unsigned DEFAULT NULL COMMENT 'If it does not reach the required value, it will be padded with zeros on the left to meet the specified length.', PRIMARY KEY (`id`), CONSTRAINT `mrwConfig_check` CHECK (`id` = 1) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; @@ -34528,6 +34345,7 @@ CREATE TABLE `operator` ( `labelerFk` int(10) unsigned DEFAULT NULL, `linesLimit` int(11) DEFAULT 20 COMMENT 'Límite de lineas en una colección para la asignación de pedidos', `volumeLimit` decimal(10,6) DEFAULT 0.500000 COMMENT 'Límite de volumen en una colección para la asignación de pedidos', + `isOnReservationMode` tinyint(1) NOT NULL DEFAULT 0, PRIMARY KEY (`workerFk`), KEY `operator_FK` (`workerFk`), KEY `operator_FK_1` (`trainFk`), @@ -35019,7 +34837,7 @@ CREATE TABLE `parking` ( UNIQUE KEY `code_UNIQUE` (`code`), KEY `parking_fk1_idx` (`sectorFk`), CONSTRAINT `parking_fk1` FOREIGN KEY (`sectorFk`) REFERENCES `sector` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `chkParkingCodeFormat` CHECK (char_length(`code`) > 4 and `code` like '%-%') + CONSTRAINT `chkParkingCodeFormat` CHECK (char_length(`code`) > 4 and `code` regexp '^[^ ]+-[^ ]+$') ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tabla con los parkings del altillo'; /*!40101 SET character_set_client = @saved_cs_client */; @@ -35807,7 +35625,6 @@ CREATE TABLE `productionConfig` ( `pendingCollectionsAge` tinyint(3) unsigned DEFAULT 6, `maxNotAssignedCollectionLifeTime` time NOT NULL DEFAULT '00:10:00' COMMENT 'Tiempo de vida de las colecciones sin asignar. Cuando se supera son eliminadas', `maxProductionScopeDays` int(11) NOT NULL DEFAULT 1 COMMENT 'maximo numero de dias en F11', - `orderMode` enum('Location','Age') NOT NULL DEFAULT 'Location', `stockScopeDays` int(11) DEFAULT 1 COMMENT 'Días a futuro al revisar el stock', `shortageAddressFk` int(11) DEFAULT NULL COMMENT 'Consignatario por defecto para añadir un item de alta', `clientSelfConsumptionFk` int(11) DEFAULT NULL COMMENT 'Cliente para crear el ticket de autoconsumo', @@ -35823,6 +35640,7 @@ CREATE TABLE `productionConfig` ( `itemOlderReviewHours` int(11) NOT NULL DEFAULT 0 COMMENT 'Horas que se tienen en cuenta para comprobar si un ítem es más viejo.', `sectorFromCode` varchar(15) DEFAULT NULL COMMENT 'Sector origen que se revisa ítems más nuevos al parkinear', `sectorToCode` varchar(15) DEFAULT NULL COMMENT 'Sector destino que se revisa ítems más nuevos al parkinear', + `orderMode` enum('Location','Age') NOT NULL DEFAULT 'Location', PRIMARY KEY (`id`), KEY `productionConfig_FK` (`shortageAddressFk`), KEY `productionConfig_FK_1` (`clientSelfConsumptionFk`), @@ -36488,6 +36306,10 @@ CREATE TABLE `roadmap` ( `userFk` int(10) unsigned DEFAULT NULL, `price` decimal(10,2) DEFAULT NULL, `driverName` varchar(45) DEFAULT NULL, + `kmStart` mediumint(9) DEFAULT NULL, + `kmEnd` mediumint(9) DEFAULT NULL, + `started` datetime DEFAULT NULL, + `finished` datetime DEFAULT NULL, PRIMARY KEY (`id`), KEY `userFk` (`userFk`), KEY `roadmap_supplierFk` (`supplierFk`), @@ -36915,7 +36737,6 @@ CREATE TABLE `routesMonitor` ( `bufferFk` int(11) DEFAULT NULL COMMENT 'Buffer del sorter por el que se quiere sacar esa ruta', `isPickingAllowed` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Los tickets de esta ruta se pueden preparar', `editorFk` int(10) unsigned DEFAULT NULL, - `expeditionTruckFk` int(11) GENERATED ALWAYS AS (`roadmapStopFk`) VIRTUAL, PRIMARY KEY (`routeFk`), KEY `routesMonitor_FK` (`bufferFk`), KEY `routesMonitor_FK_2` (`beachFk`), @@ -39167,16 +38988,13 @@ CREATE TABLE `ticketPackaging` ( `quantity` int(10) DEFAULT 0, `created` timestamp NOT NULL DEFAULT current_timestamp(), `pvp` double DEFAULT NULL, - `workerFk` int(10) unsigned DEFAULT NULL, `editorFk` int(10) unsigned DEFAULT NULL, PRIMARY KEY (`id`), KEY `ticketPackaging_fk1_idx` (`ticketFk`), KEY `ticketPackaging_fk2_idx` (`packagingFk`), - KEY `ticketPackaging_fk3_idx` (`workerFk`), KEY `ticketPackaging_fk_editor` (`editorFk`), CONSTRAINT `ticketPackaging_fk1` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `ticketPackaging_fk2` FOREIGN KEY (`packagingFk`) REFERENCES `packaging` (`id`) ON UPDATE CASCADE, - CONSTRAINT `ticketPackaging_fk3` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `ticketPackaging_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -39593,6 +39411,21 @@ CREATE TABLE `tillConfig` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `tillSerial` +-- + +DROP TABLE IF EXISTS `tillSerial`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `tillSerial` ( + `code` varchar(2) NOT NULL, + `description` varchar(30) DEFAULT NULL, + `account` varchar(10) DEFAULT NULL, + PRIMARY KEY (`code`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `time` -- @@ -41995,15 +41828,33 @@ 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 `itemImageQueue_check` ON SCHEDULE EVERY 1 HOUR STARTS '2023-07-28 00:00:00' ON COMPLETION PRESERVE ENABLE DO BEGIN - DELETE FROM itemImageQueue - WHERE attempts >= (SELECT downloadMaxAttempts FROM itemConfig); +/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `itemImageQueue_check` ON SCHEDULE EVERY 1 HOUR STARTS '2023-07-28 00:00:00' ON COMPLETION PRESERVE ENABLE DO BEGIN + DELETE FROM itemImageQueue + WHERE attempts >= (SELECT downloadMaxAttempts FROM itemConfig); END */ ;; /*!50003 SET time_zone = @saved_time_zone */ ;; /*!50003 SET sql_mode = @saved_sql_mode */ ;; /*!50003 SET character_set_client = @saved_cs_client */ ;; /*!50003 SET character_set_results = @saved_cs_results */ ;; /*!50003 SET collation_connection = @saved_col_connection */ ;; +/*!50106 DROP EVENT IF EXISTS `itemShelvingSale_doReserve` */;; +DELIMITER ;; +/*!50003 SET @saved_cs_client = @@character_set_client */ ;; +/*!50003 SET @saved_cs_results = @@character_set_results */ ;; +/*!50003 SET @saved_col_connection = @@collation_connection */ ;; +/*!50003 SET character_set_client = utf8mb4 */ ;; +/*!50003 SET character_set_results = utf8mb4 */ ;; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;; +/*!50003 SET @saved_time_zone = @@time_zone */ ;; +/*!50003 SET time_zone = 'SYSTEM' */ ;; +/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `itemShelvingSale_doReserve` ON SCHEDULE EVERY 15 SECOND STARTS '2023-10-16 00:00:00' ON COMPLETION PRESERVE ENABLE DO CALL vn.itemShelvingSale_doReserve */ ;; +/*!50003 SET time_zone = @saved_time_zone */ ;; +/*!50003 SET sql_mode = @saved_sql_mode */ ;; +/*!50003 SET character_set_client = @saved_cs_client */ ;; +/*!50003 SET character_set_results = @saved_cs_results */ ;; +/*!50003 SET collation_connection = @saved_col_connection */ ;; /*!50106 DROP EVENT IF EXISTS `mysqlConnectionsSorter_kill` */;; DELIMITER ;; /*!50003 SET @saved_cs_client = @@character_set_client */ ;; @@ -42689,37 +42540,37 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `client_getDebt`(`vClient` INT, `vDate` DATE) RETURNS decimal(10,2) READS SQL DATA -BEGIN -/** - * Returns the risk of a customer. - * - * @param vClient client id - * @param vDate date to check the risk - * @return Client risk - */ - 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; - - CREATE OR REPLACE TEMPORARY TABLE tmp.clientGetDebt (clientFk INT); - INSERT INTO tmp.clientGetDebt SET clientFk = vClient; - - CALL vn.client_getDebt(vDate); - - SELECT risk INTO vDebt FROM tmp.risk; - - DROP TEMPORARY TABLE - tmp.clientGetDebt, - tmp.risk; - - RETURN vDebt; +BEGIN +/** + * Returns the risk of a customer. + * + * @param vClient client id + * @param vDate date to check the risk + * @return Client risk + */ + 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; + + CREATE OR REPLACE TEMPORARY TABLE tmp.clientGetDebt (clientFk INT); + INSERT INTO tmp.clientGetDebt SET clientFk = vClient; + + CALL vn.client_getDebt(vDate); + + SELECT risk INTO vDebt FROM tmp.risk; + + DROP TEMPORARY TABLE + tmp.clientGetDebt, + tmp.risk; + + RETURN vDebt; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -43744,8 +43595,8 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `getInventoryDate`() RETURNS date DETERMINISTIC -BEGIN - RETURN (SELECT inventoried FROM config LIMIT 1); +BEGIN + RETURN (SELECT inventoried FROM config LIMIT 1); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -45248,6 +45099,44 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP FUNCTION IF EXISTS `sectorCollection_hasSalesReserved` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` FUNCTION `sectorCollection_hasSalesReserved`(vSelf INT) RETURNS tinyint(1) + DETERMINISTIC +BEGIN +/** + * Devuelve si sectorCollection tiene reservas + * @param vSelf Id de sectorCollection + * + * returns BOOLEAN + */ + DECLARE vHasSalesReserved BOOLEAN; + + SELECT DISTINCT COUNT(*) INTO vHasSalesReserved + FROM sectorCollection sc + JOIN sectorCollectionSaleGroup scsg ON sc.id = scsg.sectorCollectionFk + JOIN saleGroup sg ON sg.id = scsg.saleGroupFk + JOIN saleGroupDetail sgd ON sgd.saleGroupFk = sg.id + JOIN sale s ON s.id = sgd.saleFk + JOIN itemShelvingSale iss ON iss.saleFk = s.id + JOIN saleTracking st ON st.saleFk = s.id + WHERE sc.id = vSelf; + + RETURN vHasSalesReserved; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP FUNCTION IF EXISTS `specie_IsForbidden` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -45819,62 +45708,42 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `ticket_get`(vParamFk INT) RETURNS int(11) READS SQL DATA -proc:BEGIN - - /* Devuelve el número de ticket o collection consultando en varias tablas posibles - * - * @param vParamFk Número a validar - * @return vValidFk Identificador validado - */ - - DECLARE vValidFk INT; +BEGIN +/** + * Devuelve el número de ticket / collection / sectorCollection consultando + * en que tabla se encuantra en la última semana + * + * @param vParamFk Número a validar + * @return vReturn Identificador validado + */ + DECLARE vReturn INT DEFAULT NULL; + DECLARE vDated DATE; - -- Tabla vn.saleGroup - SELECT s.ticketFk INTO vValidFk - FROM vn.sale s - JOIN vn.saleGroupDetail sgd ON sgd.saleFk = s.id - JOIN vn.saleGroup sg ON sg.id = sgd.saleGroupFk - WHERE sg.id = vParamFk - AND sg.created > TIMESTAMPADD(WEEK,-1, util.VN_CURDATE()) - LIMIT 1; - - IF vValidFk THEN - - RETURN vValidFk; - - LEAVE proc; - - END IF; + SET vDated = util.VN_CURDATE() - INTERVAL 1 WEEK; - -- Tabla vn.collection - SELECT c.id INTO vValidFk - FROM vn.collection c - WHERE c.id = vParamFk - AND c.created > TIMESTAMPADD(WEEK,-1, util.VN_CURDATE()); - - IF vValidFk THEN - - RETURN vValidFk; - - LEAVE proc; - - END IF; + SELECT COALESCE( + (SELECT s.ticketFk + FROM sale s + JOIN saleGroupDetail sgd ON sgd.saleFk = s.id + JOIN saleGroup sg ON sg.id = sgd.saleGroupFk + WHERE sg.id = vParamFk + AND sg.created > vDated + LIMIT 1), + (SELECT c.id + FROM collection c + WHERE c.id = vParamFk + AND c.created > vDated), + (SELECT id + FROM ticket + WHERE id = vParamFk + AND shipped > vDated), + (SELECT id + FROM sectorCollection + WHERE id = vParamFk + AND created > vDated) + ) INTO vReturn; - -- Tabla vn.ticket - SELECT t.id INTO vValidFk - FROM vn.ticket t - WHERE t.id = vParamFk - AND t.shipped > TIMESTAMPADD(WEEK,-1, util.VN_CURDATE()); - - IF vValidFk THEN - - RETURN vValidFk; - - LEAVE proc; - - END IF; - - RETURN NULL; + RETURN vReturn; END ;; DELIMITER ; @@ -49618,6 +49487,209 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `claimRatio_add` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `claimRatio_add`() +BEGIN +/* +* Añade a la tabla greuges todos los cargos necesario y +* que luego lo utilizamos para calcular el recobro. +*/ + DECLARE vMonthToRefund INT + DEFAULT (SELECT monthsToRefund FROM claimConfig); + DECLARE vRecoveryGreugeType INT + DEFAULT (SELECT id FROM greugeType WHERE code = 'recovery'); + DECLARE vManaGreugeType INT + DEFAULT (SELECT id FROM greugeType WHERE code = 'mana'); + DECLARE vClaimGreugeType INT + DEFAULT (SELECT id FROM greugeType WHERE code = 'claim'); + DECLARE vDebtComponentType INT + DEFAULT (SELECT id FROM component WHERE code = 'debtCollection'); + + IF vMonthToRefund IS NULL + OR vRecoveryGreugeType IS NULL + OR vManaGreugeType IS NULL + OR vClaimGreugeType IS NULL + OR vDebtComponentType IS NULL THEN + + CALL util.throw('Required variables not found'); + END IF; + + -- Reclamaciones demasiado sensibles + INSERT INTO greuge( + shipped, + clientFk, + `description`, + amount, + greugeTypeFk, + ticketFk + ) + SELECT c.ticketCreated, + c.clientFk, + CONCAT('Claim ', c.id,' : ', s.concept), + ROUND(-1 * ((c.responsibility - 1) / 4) * s.quantity * + s.price * (100 - s.discount) / 100, 2), + vClaimGreugeType, + s.ticketFk + FROM sale s + JOIN claimEnd ce ON ce.saleFk = s.id + JOIN claimDestination cd ON cd.id = ce.claimDestinationFk + JOIN claim c ON c.id = ce.claimFk + JOIN claimState cs ON cs.id = c.claimStateFk + WHERE cd.description NOT IN ('Bueno', 'Corregido') + AND NOT ce.isGreuge + AND cs.code = 'resolved'; + + -- Reclamaciones que pasan a Maná + INSERT INTO greuge( + shipped, + clientFk, + `description`, + amount, + greugeTypeFk, + ticketFk + ) + SELECT c.ticketCreated, + c.clientFk, + CONCAT('Claim_mana ', c.id,' : ', s.concept), + ROUND(((c.responsibility - 1) / 4) * s.quantity * + s.price * (100 - s.discount) / 100, 2), + vManaGreugeType, + s.ticketFk + FROM sale s + JOIN claimEnd ce ON ce.saleFk = s.id + JOIN claimDestination cd ON cd.id = ce.claimDestinationFk + JOIN claim c ON c.id = ce.claimFk + JOIN claimState cs ON cs.id = c.claimStateFk + WHERE cd.description NOT IN ('Bueno', 'Corregido') + AND NOT ce.isGreuge + AND cs.code = 'resolved' + AND c.isChargedToMana; + + -- Marcamos para no repetir + UPDATE claimEnd ce + JOIN claimDestination cd ON cd.id = ce.claimDestinationFk + JOIN claim c ON c.id = ce.claimFk + JOIN claimState cs ON cs.id = c.claimStateFk + SET ce.isGreuge = TRUE + WHERE cd.description NOT IN ('Bueno', 'Corregido') + AND NOT ce.isGreuge + AND cs.code = 'resolved'; + + -- Recobros + CREATE OR REPLACE TEMPORARY TABLE tTicketList + (PRIMARY KEY (ticketFk)) + ENGINE = MEMORY + SELECT DISTINCT s.ticketFk + FROM saleComponent sc + JOIN sale s ON sc.saleFk = s.id + JOIN ticket t ON t.id = s.ticketFk + JOIN ticketLastState ts ON ts.ticketFk = t.id + JOIN ticketTracking tt ON tt.id = ts.ticketTrackingFk + JOIN state st ON st.id = tt.stateFk + JOIN alertLevel al ON al.id = st.alertLevel + WHERE sc.componentFk = vDebtComponentType + AND NOT sc.isGreuge + AND t.shipped >= (SELECT minShipped FROM claimConfig) + AND t.shipped < util.VN_CURDATE() + AND al.code = 'DELIVERED'; + + DELETE g.* + FROM greuge g + JOIN tTicketList t ON t.ticketFk = g.ticketFk + WHERE g.greugeTypeFk = vRecoveryGreugeType; + + INSERT INTO greuge( + clientFk, + `description`, + amount, + shipped, + greugeTypeFk, + ticketFk + ) + SELECT t.clientFk, + 'Recobro', + - ROUND(SUM(sc.value * s.quantity), 2) dif, + DATE(t.shipped), + vRecoveryGreugeType, + tl.ticketFk + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + JOIN tTicketList tl ON tl.ticketFk = t.id + JOIN saleComponent sc ON sc.saleFk = s.id + AND sc.componentFk = vDebtComponentType + GROUP BY t.id + HAVING ABS(dif) > 1; + + UPDATE saleComponent sc + JOIN sale s ON s.id = sc.saleFk + JOIN tTicketList tl ON tl.ticketFk = s.ticketFk + SET sc.isGreuge = TRUE + WHERE sc.componentFk = vDebtComponentType; + + REPLACE claimRatio( + clientFk, + yearSale, + claimAmount, + claimingRate, + priceIncreasing + ) + SELECT c.id, + 12 * cac.invoiced, + totalClaims, + ROUND(totalClaims / (12 * cac.invoiced), 4), + 0 + FROM client c + LEFT JOIN bs.clientAnnualConsumption cac ON cac.clientFk = c.id + LEFT JOIN ( + SELECT c.clientFk, + ROUND(SUM(-1 * ((c.responsibility - 1) / 4) * + s.quantity * s.price * (100 - s.discount) + / 100)) totalClaims + FROM sale s + JOIN claimEnd ce ON ce.saleFk = s.id + JOIN claimDestination cd ON cd.id = ce.claimDestinationFk + JOIN claim c ON c.id = ce.claimFk + JOIN claimState cs ON cs.id = c.claimStateFk + WHERE cd.description NOT IN ('Bueno', 'Corregido') + AND cs.code = 'resolved' + AND c.ticketCreated >= util.VN_CURDATE() - INTERVAL 1 YEAR + GROUP BY c.clientFk + ) sub ON sub.clientFk = c.id; + + -- Calculamos el porcentaje del recobro para añadirlo al precio de venta + UPDATE claimRatio cr + JOIN ( + SELECT clientFk, IFNULL(SUM(amount), 0) greuge + FROM greuge + WHERE shipped <= util.VN_CURDATE() + GROUP BY clientFk + ) sub ON sub.clientFk = cr.clientFk + SET cr.priceIncreasing = GREATEST(0, ROUND(IFNULL(sub.greuge, 0) / + (IFNULL(cr.yearSale, 0) * vMonthToRefund / 12 ), 3)); + + -- Protección neonatos + UPDATE claimRatio cr + JOIN firstTicketShipped fts ON fts.clientFk = cr.clientFk + SET cr.priceIncreasing = 0, + cr.claimingRate = 0 + WHERE fts.shipped > util.VN_CURDATE() - INTERVAL 1 MONTH; + + DROP TEMPORARY TABLE tTicketList; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `clean` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -51008,6 +51080,7 @@ BEGIN JOIN province p ON p.id = c.provinceFk LEFT JOIN autonomy a ON a.id = p.autonomyFk JOIN country co ON co.id = p.countryFk + JOIN bs.clientDiedPeriod cdp ON cdp.countryFk = co.id WHERE cd.warning = 'third' AND cp.clientFk IS NULL AND sp.salesPersonFk IS NULL @@ -51370,6 +51443,108 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `collection_addWithReservation` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_addWithReservation`( + vItemFk INT, + vQuantity INT, + vTicketFk INT, + vSaleGroupFk INT +) +BEGIN +/** + * En el ámbito de las colecciones se añade una línea de sale a un ticket + * de una colección en caso de tener disponible y se realiza la reserva. + * + * @param vItemFk id of item + * @param vQuantity quantity to be added to the ticket + * @param vTicketFk ticket to which the sales line is added + * @param vSaleGroupFk saleGroupFk id to add saleGroupDetail + */ + + DECLARE vWarehouseFk INT; + DECLARE vCacheAvailableFk INT; + DECLARE vAvailable INT; + DECLARE vSaleFk INT; + DECLARE vConcept VARCHAR(50); + DECLARE vItemName VARCHAR(50); + DECLARE vHasThrow BOOLEAN DEFAULT FALSE; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + SELECT t.warehouseFk INTO vWarehouseFk + FROM ticket t + JOIN ticketCollection tc ON tc.ticketFk = t.id + WHERE t.id = vTicketFk; + + CALL cache.available_refresh( + vCacheAvailableFk, + FALSE, + vWarehouseFk, + util.VN_CURDATE()); + + SELECT available INTO vAvailable + FROM cache.available + WHERE calc_id = vCacheAvailableFk + AND item_id = vItemFk; + + IF vAvailable < vQuantity THEN + SET vHasThrow = TRUE; + ELSE + SELECT `name`, + CONCAT(getUser(), ' ', DATE_FORMAT(util.VN_NOW(), '%H:%i'), ' ', name) + INTO vItemName, vConcept + FROM item + WHERE id = vItemFk; + + START TRANSACTION; + + INSERT INTO sale + SET itemFk = vItemFk, + ticketFk = vTicketFk, + concept = vConcept, + quantity = vQuantity, + isAdded = TRUE; + + SELECT LAST_INSERT_ID() INTO vSaleFk; + + CALL sale_calculateComponent(vSaleFk, NULL); + CALL itemShelvingSale_addBySale(vSaleFk); + + IF NOT EXISTS (SELECT TRUE FROM itemShelvingSale WHERE saleFk = vSaleFk LIMIT 1) THEN + SET vHasThrow = TRUE; + END IF; + END IF; + + IF vHasThrow THEN + CALL util.throw("There is no available for the selected item"); + END IF; + + IF vSaleGroupFk THEN + INSERT INTO saleGroupDetail + SET saleFk = vSaleFk, + saleGroupFk = vSaleGroupFk; + END IF; + + COMMIT; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `collection_assign` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -51378,82 +51553,126 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_assign`( - vUserFk INT, - OUT vCollectionFk INT +CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_assign`( + vUserFk INT, + OUT vCollectionFk INT ) -BEGIN -/** - * Comprueba si existen colecciones libres que se ajustan - * al perfil del usuario y le asigna la más antigua. - * Añade un registro al semillero de colecciones. - * - * @param vUserFk Id de usuario - * @param vCollectionFk Id de colección - */ - DECLARE vHasTooMuchCollections BOOL; - - -- Si hay colecciones sin terminar, sale del proceso - CALL collection_get(vUserFk); - - SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0 - INTO vHasTooMuchCollections - FROM productionConfig pc - LEFT JOIN tmp.collection ON TRUE; - - DROP TEMPORARY TABLE tmp.collection; - - IF vHasTooMuchCollections THEN - CALL util.throw('Hay colecciones pendientes'); - END IF; - - -- Se eliminan las colecciones sin asignar que estan obsoletas - INSERT INTO ticketTracking(stateFk, ticketFk) - SELECT s.id, tc.ticketFk - FROM `collection` c - JOIN ticketCollection tc ON tc.collectionFk = c.id - JOIN `state` s ON s.code = 'PRINTED_AUTO' - JOIN productionConfig pc - WHERE c.workerFk IS NULL - AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; - - DELETE c.* - FROM `collection` c - JOIN productionConfig pc - WHERE c.workerFk IS NULL - AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; - - -- Se añade registro al semillero - INSERT INTO collectionHotbed(userFk) - VALUES(vUserFk); - - -- Comprueba si hay colecciones disponibles que se ajustan a su configuracion - SELECT MIN(c.id) INTO vCollectionFk - FROM `collection` c - JOIN operator o - ON (o.itemPackingTypeFk = c.itemPackingTypeFk OR c.itemPackingTypeFk IS NULL) - AND o.numberOfWagons = c.wagons - AND o.trainFk = c.trainFk - AND o.warehouseFk = c.warehouseFk - AND c.workerFk IS NULL - AND (c.saleTotalCount <= o.linesLimit OR o.linesLimit IS NULL) - JOIN ( - SELECT tc.collectionFk, SUM(sv.volume) volume - FROM ticketCollection tc - JOIN saleVolume sv ON sv.ticketFk = tc.ticketFk - WHERE sv.shipped >= util.VN_CURDATE() - GROUP BY tc.collectionFk - ) sub ON sub.collectionFk = c.id - AND (volume <= o.volumeLimit OR o.volumeLimit IS NULL) - WHERE o.workerFk = vUserFk; - - IF vCollectionFk IS NULL THEN - CALL collection_new(vUserFk, vCollectionFk); - END IF; - - UPDATE `collection` - SET workerFk = vUserFk - WHERE id = vCollectionFk; +BEGIN +/** + * Comprueba si existen colecciones libres que se ajustan + * al perfil del usuario y le asigna la más antigua. + * Añade un registro al semillero de colecciones. + * + * @param vUserFk Id de usuario + * @param vCollectionFk Id de colección + */ + DECLARE vHasTooMuchCollections BOOL; + DECLARE vItemPackingTypeFk VARCHAR(1); + DECLARE vWarehouseFk INT; + DECLARE vLockName VARCHAR(215); + DECLARE vLockTime INT DEFAULT 30; + DECLARE vErrorNumber INT; + DECLARE vErrorMsg TEXT; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + GET DIAGNOSTICS CONDITION 1 + vErrorNumber = MYSQL_ERRNO, + vErrorMsg = MESSAGE_TEXT; + + IF vLockName IS NOT NULL THEN + DO RELEASE_LOCK(vLockName); + CALL util.debugAdd('collection_assign', JSON_OBJECT( + 'errorNumber', vErrorNumber, + 'errorMsg', vErrorMsg, + 'lockName', vLockName, + 'userFk', vUserFk + )); -- Tmp + END IF; + + RESIGNAL; + END; + + -- Si hay colecciones sin terminar, sale del proceso + CALL collection_get(vUserFk); + + SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0, + collection_assign_lockname + INTO vHasTooMuchCollections, + vLockName + FROM productionConfig pc + LEFT JOIN tmp.collection ON TRUE; + + DROP TEMPORARY TABLE tmp.collection; + + IF vHasTooMuchCollections THEN + CALL util.throw('Hay colecciones pendientes'); + END IF; + + SELECT warehouseFk, itemPackingTypeFk + INTO vWarehouseFk, vItemPackingTypeFk + FROM operator + WHERE workerFk = vUserFk; + + SET vLockName = CONCAT_WS('/', + vLockName, + vWarehouseFk, + vItemPackingTypeFk + ); + + IF NOT GET_LOCK(vLockName, vLockTime) THEN + CALL util.throw(CONCAT('Cannot get lock: ', vLockName)); + END IF; + + -- Se eliminan las colecciones sin asignar que estan obsoletas + INSERT INTO ticketTracking(stateFk, ticketFk) + SELECT s.id, tc.ticketFk + FROM `collection` c + JOIN ticketCollection tc ON tc.collectionFk = c.id + JOIN `state` s ON s.code = 'PRINTED_AUTO' + JOIN productionConfig pc + WHERE c.workerFk IS NULL + AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; + + DELETE c.* + FROM `collection` c + JOIN productionConfig pc + WHERE c.workerFk IS NULL + AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; + + -- Se añade registro al semillero + INSERT INTO collectionHotbed(userFk) + VALUES(vUserFk); + + -- Comprueba si hay colecciones disponibles que se ajustan a su configuracion + SELECT MIN(c.id) INTO vCollectionFk + FROM `collection` c + JOIN operator o + ON (o.itemPackingTypeFk = c.itemPackingTypeFk OR c.itemPackingTypeFk IS NULL) + AND o.numberOfWagons = c.wagons + AND o.trainFk = c.trainFk + AND o.warehouseFk = c.warehouseFk + AND c.workerFk IS NULL + AND (c.saleTotalCount <= o.linesLimit OR o.linesLimit IS NULL) + JOIN ( + SELECT tc.collectionFk, SUM(sv.volume) volume + FROM ticketCollection tc + JOIN saleVolume sv ON sv.ticketFk = tc.ticketFk + WHERE sv.shipped >= util.VN_CURDATE() + GROUP BY tc.collectionFk + ) sub ON sub.collectionFk = c.id + AND (volume <= o.volumeLimit OR o.volumeLimit IS NULL) + WHERE o.workerFk = vUserFk; + + IF vCollectionFk IS NULL THEN + CALL collection_new(vUserFk, vCollectionFk); + END IF; + + UPDATE `collection` + SET workerFk = vUserFk + WHERE id = vCollectionFk; + + DO RELEASE_LOCK(vLockName); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -51478,26 +51697,31 @@ BEGIN * @param vWorkerFk id del worker. * @table Devuelve tabla temporal con las colecciones pendientes */ - DROP TEMPORARY TABLE IF EXISTS tmp.collection; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + RESIGNAL; + END; - CREATE TEMPORARY TABLE tmp.collection - SELECT c.id collectionFk, - date(c.created) created, - COUNT(DISTINCT tc.ticketFk) ticketTotalCount - FROM collection c - JOIN ticketCollection tc ON tc.collectionFk = c.id - JOIN sale s ON s.ticketFk = tc.ticketFk - JOIN ticketState ts ON ts.ticketFk = tc.ticketFk - JOIN state s2 ON s2.id = ts.stateFk - JOIN productionConfig pc - JOIN vn.state ss on ss.code = 'PREPARED' - LEFT JOIN vn.saleTracking st on st.saleFk = s.id AND st.stateFk = ss.id - WHERE c.workerFk = vWorkerFk - AND TIMESTAMPDIFF(HOUR, c.created , util.VN_NOW()) < pc.pendingCollectionsAge - AND s.quantity != 0 - AND s2.order < pc.pendingCollectionsOrder - GROUP BY c.id - HAVING COUNT(*) > COUNT(DISTINCT st.id); + CREATE OR REPLACE TEMPORARY TABLE tmp.collection + ENGINE = MEMORY + SELECT c.id collectionFk, + DATE(c.created) created, + COUNT(DISTINCT tc.ticketFk) ticketTotalCount + FROM collection c + JOIN ticketCollection tc ON tc.collectionFk = c.id + JOIN sale s ON s.ticketFk = tc.ticketFk + JOIN ticketState ts ON ts.ticketFk = tc.ticketFk + JOIN state s2 ON s2.id = ts.stateFk + JOIN productionConfig pc + JOIN vn.state ss ON ss.code = 'PREPARED' + LEFT JOIN vn.saleTracking st ON st.saleFk = s.id + AND st.stateFk = ss.id + WHERE c.workerFk = vWorkerFk + AND TIMESTAMPDIFF(HOUR, c.created , util.VN_NOW()) < pc.pendingCollectionsAge + AND s.quantity + AND s2.order < pc.pendingCollectionsOrder + GROUP BY c.id + HAVING COUNT(*) > COUNT(DISTINCT st.id); SELECT * FROM tmp.collection; END ;; @@ -51508,6 +51732,123 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `collection_getAssigned` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_getAssigned`( + vUserFk INT, + OUT vCollectionFk INT +) +BEGIN +/** + * Comprueba si existen colecciones libres que se ajustan al perfil del usuario + * y le asigna la más antigua. + * Añade un registro al semillero de colecciones y hace la reserva para la colección + * + * @param vUserFk Id de usuario + * @param vCollectionFk Id de colección + */ + DECLARE vHasTooMuchCollections BOOL; + DECLARE vItemPackingTypeFk VARCHAR(1); + DECLARE vWarehouseFk INT; + DECLARE vLockName VARCHAR(215); + DECLARE vLockTime INT DEFAULT 30; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + IF vLockName IS NOT NULL THEN + DO RELEASE_LOCK(vLockName); + END IF; + + RESIGNAL; + END; + + -- Si hay colecciones sin terminar, sale del proceso + CALL collection_get(vUserFk); + + SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0, + pc.collection_assign_lockname + INTO vHasTooMuchCollections, + vLockName + FROM tmp.collection c + JOIN productionConfig pc; + + DROP TEMPORARY TABLE tmp.collection; + + IF vHasTooMuchCollections THEN + CALL util.throw('There are pending collections'); + END IF; + + SELECT warehouseFk, itemPackingTypeFk + INTO vWarehouseFk, vItemPackingTypeFk + FROM operator + WHERE workerFk = vUserFk; + + SET vLockName = CONCAT_WS('/', + vLockName, + vWarehouseFk, + vItemPackingTypeFk + ); + + IF NOT GET_LOCK(vLockName, vLockTime) THEN + CALL util.throw(CONCAT('Cannot get lock: ', vLockName)); + END IF; + + -- Se eliminan las colecciones sin asignar que estan obsoletas + INSERT INTO ticketTracking(stateFk, ticketFk) + SELECT s.id, tc.ticketFk + FROM collection c + JOIN ticketCollection tc ON tc.collectionFk = c.id + JOIN state s ON s.code = 'PRINTED_AUTO' + JOIN productionConfig pc + WHERE c.workerFk IS NULL + AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; + + DELETE c + FROM collection c + JOIN productionConfig pc + WHERE c.workerFk IS NULL + AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; + + -- Se añade registro al semillero + INSERT INTO collectionHotbed + SET userFk = vUserFk; + + -- Comprueba si hay colecciones disponibles que se ajustan a su configuracion + SELECT MIN(c.id) INTO vCollectionFk + FROM collection c + JOIN operator o ON (o.itemPackingTypeFk = c.itemPackingTypeFk + OR c.itemPackingTypeFk IS NULL) + AND o.numberOfWagons = c.wagons + AND o.trainFk = c.trainFk + AND o.warehouseFk = c.warehouseFk + AND c.workerFk IS NULL + WHERE o.workerFk = vUserFk; + + IF vCollectionFk IS NULL THEN + CALL collection_new(vUserFk, vCollectionFk); + END IF; + + UPDATE collection + SET workerFk = vUserFk + WHERE id = vCollectionFk; + + CALL itemShelvingSale_addByCollection(vCollectionFk); + + DO RELEASE_LOCK(vLockName); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `collection_getTickets` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -51519,62 +51860,89 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_getTickets`(vParamFk INT) BEGIN /** - * Selecciona los tickets de una colección/ticket - * @param vParamFk ticketFk/collectionFk - * @return Retorna ticketFk, level, agencyName, warehouseFk, salesPersonFk, observaciones + * Selecciona los tickets de una colección/ticket/sectorCollection + * @param vParamFk ticketFk/collectionFk/sectorCollection + * @return Retorna ticketFk, level, agencyName, warehouseFk, salesPersonFk, observation */ DECLARE vItemPackingTypeFk VARCHAR(1); + DECLARE vYesterday DATE; -- Si los sacadores son los de pruebas, pinta los colores - SELECT itemPackingTypeFk INTO vItemPackingTypeFk - FROM vn.collection + SELECT itemPackingTypeFk + INTO vItemPackingTypeFk + FROM collection WHERE id = vParamFk; + + SET vYesterday = util.yesterday(); - SELECT t.id ticketFk, - IF (!(vItemPackingTypeFk <=> 'V'), cc.code,CONCAT(SUBSTRING('ABCDEFGH',tc.wagon, 1),'-',tc.`level` )) `level`, - am.name agencyName, - t.warehouseFk, - w.id salesPersonFk, - IFNULL(tob.description,'') observaciones, - cc.rgb - FROM vn.ticket t - LEFT JOIN vn.ticketCollection tc ON t.id = tc.ticketFk - LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk -- PAK 23/12/21 - LEFT JOIN vn.collectionColors cc - ON cc.wagon = tc.wagon - AND cc.shelve = tc.`level` - AND cc.trainFk = c2.trainFk -- PAK 23/12/21 - LEFT JOIN vn.zone z ON z.id = t.zoneFk - LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk - LEFT JOIN vn.client c ON c.id = t.clientFk - LEFT JOIN vn.worker w ON w.id = c.salesPersonFk - LEFT JOIN vn.ticketObservation tob ON tob.ticketFk = t.id - AND tob.observationTypeFk = 1 - WHERE t.id = vParamFk - AND t.shipped >= util.yesterday() - UNION ALL + WITH observation AS ( + SELECT tob.ticketFk, tob.description + FROM vn.ticketObservation tob + JOIN vn.ticketCollection tc ON tc.ticketFk = tob.ticketFk + LEFT JOIN vn.observationType ot ON ot.id = tob.observationTypeFk + WHERE ot.`code` = 'itemPicker' + AND tc.collectionFk = vParamFk + ) SELECT t.id ticketFk, IF(!(vItemPackingTypeFk <=> 'V'), cc.code, CONCAT(SUBSTRING('ABCDEFGH', tc.wagon, 1), '-', tc.`level`)) `level`, am.name agencyName, t.warehouseFk, - w.id salesPersonFk, - IFNULL(tob.description, '') observaciones, - IF(!(vItemPackingTypeFk <=> 'V'), cc.rgb, NULL) `rgb` + w.id salesPersonFk, + IFNULL(ob.description,'') observaciones, + cc.rgb FROM vn.ticket t - JOIN vn.ticketCollection tc ON t.id = tc.ticketFk - LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk -- PAK 23/12/21 + LEFT JOIN vn.ticketCollection tc ON t.id = tc.ticketFk + LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk LEFT JOIN vn.collectionColors cc ON cc.wagon = tc.wagon - AND cc.shelve = tc.`level` - AND cc.trainFk = c2.trainFk -- PAK 23/12/21 + AND cc.shelve = tc.`level` + AND cc.trainFk = c2.trainFk LEFT JOIN vn.zone z ON z.id = t.zoneFk LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk LEFT JOIN vn.client c ON c.id = t.clientFk LEFT JOIN vn.worker w ON w.id = c.salesPersonFk - LEFT JOIN vn.ticketObservation tob ON tob.ticketFk = t.id - AND tob.observationTypeFk = 1 - WHERE tc.collectionFk = vParamFk; - + LEFT JOIN observation ob ON ob.ticketFk = t.id + WHERE t.id = vParamFk + AND t.shipped >= vYesterday + UNION ALL + SELECT t.id ticketFk, + IF(NOT(vItemPackingTypeFk <=> 'V'), cc.code, CONCAT(SUBSTRING('ABCDEFGH', tc.wagon, 1), '-', tc.`level`)) `level`, + am.name agencyName, + t.warehouseFk, + w.id salesPersonFk, + ob.description, + IF(NOT (vItemPackingTypeFk <=> 'V'), cc.rgb, NULL) `rgb` + FROM vn.ticket t + JOIN vn.ticketCollection tc ON t.id = tc.ticketFk + LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk + LEFT JOIN vn.collectionColors cc + ON cc.wagon = tc.wagon + AND cc.shelve = tc.`level` + AND cc.trainFk = c2.trainFk + LEFT JOIN vn.zone z ON z.id = t.zoneFk + LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk + LEFT JOIN vn.client c ON c.id = t.clientFk + LEFT JOIN vn.worker w ON w.id = c.salesPersonFk + LEFT JOIN observation ob ON ob.ticketFk = t.id + WHERE tc.collectionFk = vParamFk + UNION ALL + SELECT sg.ticketFk, + NULL `level`, + am.name agencyName, + t.warehouseFk, + c.salesPersonFk, + ob.description, + NULL `rgb` + FROM vn.sectorCollection sc + JOIN vn.sectorCollectionSaleGroup ss ON ss.sectorCollectionFk = sc.id + JOIN vn.saleGroup sg ON sg.id = ss.saleGroupFk + JOIN vn.ticket t ON t.id = sg.ticketFk + LEFT JOIN vn.zone z ON z.id = t.zoneFk + LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk + LEFT JOIN observation ob ON ob.ticketFk = t.id + LEFT JOIN vn.client c ON c.id = t.clientFk + WHERE sc.id = vParamFk + AND t.shipped >= vYesterday; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -51761,7 +52129,8 @@ BEGIN 'errorNumber', vErrorNumber, 'errorMsg', vErrorMsg, 'lockName', vLockName, - 'userFk', vUserFk + 'userFk', vUserFk, + 'ticketFk', vTicketFk )); -- Tmp END IF; @@ -53527,7 +53896,9 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `duaInvoiceInBooking`(vDuaFk INT) +CREATE DEFINER=`root`@`localhost` PROCEDURE `duaInvoiceInBooking`( + vDuaFk INT +) BEGIN /** * Genera el asiento de un DUA y marca las entradas como confirmadas @@ -53557,27 +53928,25 @@ BEGIN SET ii.booked = IFNULL(ii.booked, d.booked), ii.operated = IFNULL(ii.operated, d.operated), ii.issued = IFNULL(ii.issued, d.issued), - ii.bookEntried = IFNULL(ii.bookEntried, d.bookEntried), - e.isBooked = TRUE, - e.isConfirmed = TRUE + ii.bookEntried = IFNULL(ii.bookEntried, d.bookEntried) WHERE d.id = vDuaFk; SELECT ASIEN INTO vBookEntry FROM dua WHERE id = vDuaFk; - IF vBookEntry IS NULL THEN + IF vBookEntry IS NULL THEN SELECT YEAR(IFNULL(ii.bookEntried, d.bookEntried)) INTO vFiscalYear FROM invoiceIn ii - JOIN entry e ON e.invoiceInFk = ii.id + JOIN `entry` e ON e.invoiceInFk = ii.id JOIN duaEntry de ON de.entryFk = e.id JOIN dua d ON d.id = de.duaFk WHERE d.id = vDuaFk LIMIT 1; CALL ledger_nextTx(vFiscalYear, vBookEntry); - END IF; + END IF; OPEN vInvoicesIn; -l: LOOP + l: LOOP SET vDone = FALSE; FETCH vInvoicesIn INTO vInvoiceFk; @@ -53598,6 +53967,29 @@ l: LOOP JOIN duaInvoiceIn dii ON dii.invoiceInFk = ii.id SET ii.isBooked = TRUE WHERE dii.duaFk = vDuaFk; + + UPDATE `entry` e + JOIN ( + WITH entries AS ( + SELECT e.id, de.duaFk + FROM vn.`entry` e + JOIN vn.duaEntry de ON de.entryFk = e.id + WHERE de.duaFk = vDuaFk + AND (NOT e.isBooked OR NOT e.isConfirmed) + ), + notBookedEntries AS ( + SELECT e.id + FROM vn.duaEntry + WHERE duaFk = vDuaFk + AND NOT customsValue + ) + SELECT e.id + FROM entries e + LEFT JOIN notBookedEntries nbe ON nbe.entryFk = e.id + WHERE nbe.entryFk IS NULL + ) sub ON sub.id = e.id + SET e.isBooked = TRUE, + e.isConfirmed = TRUE; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -55487,14 +55879,14 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `expeditionPallet_printLabel` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb3 */ ; -/*!50003 SET character_set_results = utf8mb3 */ ; -/*!50003 SET collation_connection = utf8mb3_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionPallet_printLabel`(vSelf INT) BEGIN @@ -55506,7 +55898,16 @@ BEGIN */ DECLARE vPrinterFk INT; DECLARE vUserFk INT DEFAULT account.myUser_getId(); - + DECLARE vIsInExpeditionPallet BOOL; + + SELECT COUNT(id) INTO vIsInExpeditionPallet + FROM expeditionPallet + WHERE id = vSelf; + + IF NOT vIsInExpeditionPallet THEN + CALL util.throw("ExpeditionPallet not exists"); + END IF; + SELECT o.labelerFk INTO vPrinterFk FROM operator o WHERE o.workerFk = vUserFk; @@ -57145,7 +57546,6 @@ BEGIN */ DECLARE vTaxRowLimit INT; DECLARE vLines INT; - DECLARE vHasDistinctTransactions INT; SELECT taxRowLimit INTO vTaxRowLimit FROM invoiceInConfig; @@ -57157,18 +57557,6 @@ BEGIN IF vLines >= vTaxRowLimit THEN CALL util.throw (CONCAT('The maximum number of lines is ', vTaxRowLimit)); END IF; - - SELECT COUNT(DISTINCT transactionTypeSageFk) INTO vHasDistinctTransactions - FROM invoiceIn ii - JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id - JOIN invoiceInSerial iis ON iis.code = ii.serial - WHERE ii.id = vInvoiceInFk - AND iis.taxAreaFk = 'CEE' - AND transactionTypeSageFk; - - IF vHasDistinctTransactions > 1 THEN - CALL util.throw ('This invoice does not allow different types of transactions'); - END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -57381,6 +57769,19 @@ BEGIN * @param vBookEntry Id de asiento, si es NULL se genera uno nuevo */ DECLARE vFiscalYear INT; + DECLARE vHasDistinctTransactions INT; + + SELECT COUNT(DISTINCT transactionTypeSageFk) INTO vHasDistinctTransactions + FROM invoiceIn ii + JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id + JOIN invoiceInSerial iis ON iis.code = ii.serial + WHERE ii.id = vSelf + AND iis.taxAreaFk = 'CEE' + AND transactionTypeSageFk; + + IF vHasDistinctTransactions > 1 THEN + CALL util.throw ('This invoice does not allow different types of transactions'); + END IF; CREATE OR REPLACE TEMPORARY TABLE tInvoiceIn ENGINE = MEMORY @@ -59784,7 +60185,7 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_reserve` */; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_addByCollection` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -59792,302 +60193,53 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_reserve`() -BEGIN -/** - * Reserva cantidades con ubicaciones para un conjunto de sales del mismo - * almacen. - * - * @table tmp.sale(saleFk, userFk) - */ - DECLARE vCalcFk INT; - DECLARE vWarehouseFk INT; - DECLARE vCurrentYear INT DEFAULT YEAR(util.VN_NOW()); - DECLARE vLastPickingOrder INT; - - SELECT t.warehouseFk, MAX(p.pickingOrder) - INTO vWarehouseFk, vLastPickingOrder - FROM ticket t - JOIN sale s ON s.ticketFk = t.id - JOIN tmp.sale ts ON ts.saleFk = s.id - LEFT JOIN itemShelvingSale iss ON iss.saleFk = ts.saleFk - LEFT JOIN itemShelving ish ON ish.id = iss.itemShelvingFk - LEFT JOIN shelving sh ON sh.code = ish.shelvingFk - LEFT JOIN parking p ON p.id = sh.parkingFk - WHERE t.warehouseFk IS NOT NULL; - - IF vWarehouseFk IS NULL THEN - CALL util.throw('Warehouse not set'); - END IF; - - CALL cache.visible_refresh(vCalcFk, FALSE, vWarehouseFk); - - SET @outstanding = 0; - SET @oldsaleFk = 0; - - CREATE OR REPLACE TEMPORARY TABLE tSalePlacementQuantity - (INDEX(saleFk)) - ENGINE = MEMORY - SELECT saleFk, userFk, quantityToReserve, itemShelvingFk - FROM( SELECT saleFk, - sub.userFk, - itemShelvingFk , - IF(saleFk <> @oldsaleFk, @outstanding := quantity, @outstanding), - @qtr := LEAST(@outstanding, available) quantityToReserve, - @outStanding := @outStanding - @qtr, - @oldsaleFk := saleFk - FROM( - SELECT ts.saleFk, - ts.userFk, - s.quantity, - ish.id itemShelvingFk, - ish.visible - IFNULL(ishr.reservedQuantity, 0) available - FROM tmp.sale ts - JOIN sale s ON s.id = ts.saleFk - JOIN itemShelving ish ON ish.itemFk = s.itemFk - LEFT JOIN ( - SELECT itemShelvingFk, SUM(quantity) reservedQuantity - FROM itemShelvingSale - WHERE NOT isPicked - GROUP BY itemShelvingFk) ishr ON ishr.itemShelvingFk = ish.id - JOIN shelving sh ON sh.code = ish.shelvingFk - JOIN parking p ON p.id = sh.parkingFk - JOIN sector sc ON sc.id = p.sectorFk - JOIN warehouse w ON w.id = sc.warehouseFk - JOIN productionConfig pc - WHERE w.id = vWarehouseFk - AND NOT sc.isHideForPickers - ORDER BY - s.id, - p.pickingOrder >= vLastPickingOrder, - sh.priority DESC, - ish.visible >= s.quantity DESC, - s.quantity MOD ish.grouping = 0 DESC, - ish.grouping DESC, - IF(pc.orderMode = 'Location', p.pickingOrder, ish.created) - )sub - )sub2 - WHERE quantityToReserve > 0; - - INSERT INTO itemShelvingSale( - itemShelvingFk, - saleFk, - quantity, - userFk) - SELECT itemShelvingFk, - saleFk, - quantityToReserve, - IFNULL(userFk, getUser()) - FROM tSalePlacementQuantity spl; - - DROP TEMPORARY TABLE tmp.sale; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_reserveByCollection` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb3 */ ; -/*!50003 SET character_set_results = utf8mb3 */ ; -/*!50003 SET collation_connection = utf8mb3_general_ci */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_reserveByCollection`( - vCollectionFk INT(11) +CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_addByCollection`( + vCollectionFk INT(11) ) -BEGIN -/** - * Reserva cantidades con ubicaciones para el contenido de una colección - * - * @param vCollectionFk Identificador de collection - */ - CREATE OR REPLACE TEMPORARY TABLE tmp.sale - (INDEX(saleFk)) - ENGINE = MEMORY - SELECT s.id saleFk, NULL userFk - FROM ticketCollection tc - JOIN sale s ON s.ticketFk = tc.ticketFk - LEFT JOIN ( - SELECT DISTINCT saleFk - FROM saleTracking st - JOIN state s ON s.id = st.stateFk - WHERE st.isChecked - AND s.semaphore = 1)st ON st.saleFk = s.id - WHERE tc.collectionFk = vCollectionFk - AND st.saleFk IS NULL - AND NOT s.isPicked; - - CALL itemShelvingSale_reserve(); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_reserveBySale` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb3 */ ; -/*!50003 SET character_set_results = utf8mb3 */ ; -/*!50003 SET collation_connection = utf8mb3_general_ci */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_reserveBySale`( - vSelf INT , - vQuantity INT, - vUserFk INT -) -BEGIN -/** - * Reserva cantida y ubicación para una saleFk - * - * @param vSelf Identificador de la venta - * @param vQuantity Cantidad a reservar - * @param vUserFk Id de usuario que realiza la reserva - */ - CREATE OR REPLACE TEMPORARY TABLE tmp.sale - ENGINE = MEMORY - SELECT vSelf saleFk, vUserFk userFk; - - CALL itemShelvingSale_reserve(); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_setQuantity` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb3 */ ; -/*!50003 SET character_set_results = utf8mb3 */ ; -/*!50003 SET collation_connection = utf8mb3_general_ci */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_setQuantity`( - vItemShelvingSaleFk INT(10), - vQuantity DECIMAL(10,0), - vIsItemShelvingSaleEmpty BOOLEAN -) -BEGIN -/** - * Gestiona la reserva de un itemShelvingFk, actualizando isPicked y quantity - * en vn.itemShelvingSale y vn.sale.isPicked en caso necesario. - * Si la reserva de la ubicación es fallida, se regulariza la situación - * - * @param vItemShelvingSaleFk Id itemShelvingSaleFK - * @param vQuantity Cantidad real que se ha cogido de la ubicación - * @param vIsItemShelvingSaleEmpty determina si ka ubicación itemShelvingSale se ha - * quedado vacio tras el movimiento - */ - DECLARE vSaleFk INT; - DECLARE vCursorSaleFk INT; - DECLARE vItemShelvingFk INT; - DECLARE vReservedQuantity INT; - DECLARE vRemainingQuantity INT; - DECLARE vItemFk INT; - DECLARE vUserFk INT; - DECLARE vDone BOOLEAN DEFAULT FALSE; - DECLARE vSales CURSOR FOR - SELECT iss.saleFk, iss.userFk - FROM itemShelvingSale iss - JOIN sale s ON s.id = iss.saleFk - WHERE iss.id = vItemShelvingSaleFk - AND s.itemFk = vItemFk - AND NOT iss.isPicked; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - IF (SELECT isPicked FROM itemShelvingSale WHERE id = vItemShelvingSaleFk) THEN - CALL util.throw('Booking completed'); - END IF; - - SELECT s.itemFk, iss.saleFk, iss.itemShelvingFk - INTO vItemFk, vSaleFk, vItemShelvingFk - FROM itemShelvingSale iss - JOIN sale s ON s.id = iss.saleFk - WHERE iss.id = vItemShelvingSaleFk - AND NOT iss.isPicked; - - UPDATE itemShelvingSale - SET isPicked = TRUE, - quantity = vQuantity - WHERE id = vItemShelvingSaleFk; - - UPDATE itemShelving - SET visible = IF(vIsItemShelvingSaleEmpty, 0, GREATEST(0,visible - vQuantity)) - WHERE id = vItemShelvingFk; - - IF vIsItemShelvingSaleEmpty THEN - OPEN vSales; -l: LOOP - SET vDone = FALSE; - FETCH vSales INTO vCursorSaleFk, vUserFk; - IF vDone THEN - LEAVE l; - END IF; - - CREATE OR REPLACE TEMPORARY TABLE tmp.sale - (INDEX(saleFk, userFk)) - ENGINE = MEMORY - SELECT vCursorSaleFk, vUserFk; - - CALL itemShelvingSale_reserveWhitUser(); - DROP TEMPORARY TABLE tmp.sale; - - END LOOP; - CLOSE vSales; - - DELETE iss - FROM itemShelvingSale iss - JOIN sale s ON s.id = iss.saleFk - WHERE iss.id = vItemShelvingSaleFk - AND s.itemFk = vItemFk - AND NOT iss.isPicked; - END IF; - - SELECT SUM(quantity) INTO vRemainingQuantity - FROM itemShelvingSale - WHERE saleFk = vSaleFk - AND NOT isPicked; - - IF vRemainingQuantity THEN - CALL itemShelvingSale_reserveBySale (vSaleFk, vRemainingQuantity, NULL); - - SELECT SUM(quantity) INTO vRemainingQuantity - FROM itemShelvingSale - WHERE saleFk = vSaleFk - AND NOT isPicked; - - IF NOT vRemainingQuantity <=> 0 THEN - SELECT SUM(iss.quantity) - INTO vReservedQuantity - FROM itemShelvingSale iss - WHERE iss.saleFk = vSaleFk; - - CALL saleTracking_new( - vSaleFk, - TRUE, - vReservedQuantity, - `account`.`myUser_getId`(), - NULL, - 'PREPARED', - TRUE); - - UPDATE sale s - SET s.quantity = vReservedQuantity - WHERE s.id = vSaleFk ; - END IF; - END IF; +BEGIN +/** + * Reserva cantidades con ubicaciones para el contenido de una colección + * + * @param vCollectionFk Identificador de collection + */ + DECLARE vDone BOOL DEFAULT FALSE; + DECLARE vSaleFk INT; + DECLARE vSales CURSOR FOR + WITH sales AS ( + SELECT s.id saleFk, s.quantity, SUM(IFNULL(iss.quantity, 0)) quantityReserved + FROM vn.ticketCollection tc + JOIN vn.sale s ON s.ticketFk = tc.ticketFk + LEFT JOIN vn.itemShelvingSale iss ON iss.saleFk = s.id + WHERE tc.collectionFk = vCollectionFk + GROUP BY s.id + HAVING quantity <> quantityReserved + ), trackedSales AS ( + SELECT sa.saleFk + FROM sales sa + JOIN vn.saleTracking st ON st.saleFk = sa.saleFk + JOIN vn.`state` s ON s.id = st.stateFk + WHERE st.isChecked + AND s.`code` IN ('PREVIOUS_PREPARATION', 'OK PREVIOUS', 'OK STOWAWAY') + GROUP BY sa.saleFk + ) SELECT s.saleFk + FROM sales s + LEFT JOIN trackedSales ts ON ts.saleFk = s.saleFk + WHERE ts.saleFk IS NULL; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + OPEN vSales; + l: LOOP + SET vDone = FALSE; + FETCH vSales INTO vSaleFk; + + IF vDone THEN + LEAVE l; + END IF; + + CALL itemShelvingSale_addBySale(vSaleFk); + END LOOP; + CLOSE vSales; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60096,7 +60248,7 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingTransfer` */; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_addBySale` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -60104,50 +60256,512 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingTransfer`(vItemShelvingFk INT, vShelvingFk VARCHAR(3)) +CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_addBySale`( + vSaleFk INT +) +proc: BEGIN +/** + * Reserva una línea de venta en la ubicación más óptima + * + * @param vSaleFk Id de sale + * @param vItemShelvingSaleFk Id de reserva + */ + DECLARE vLastPickingOrder INT; + DECLARE vDone INT DEFAULT FALSE; + DECLARE vItemShelvingFk INT; + DECLARE vAvailable INT; + DECLARE vReservedQuantity INT; + DECLARE vOutStanding INT; + DECLARE vUserFk INT; + + DECLARE vItemShelvingAvailable CURSOR FOR + SELECT ish.id itemShelvingFk, + ish.available + FROM sale s + JOIN itemShelving ish ON ish.itemFk = s.itemFk + JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN parking p ON p.id = sh.parkingFk + JOIN sector sc ON sc.id = p.sectorFk + JOIN productionConfig pc + WHERE s.id = vSaleFk + AND NOT sc.isHideForPickers + ORDER BY s.id, + p.pickingOrder >= vLastPickingOrder, + sh.priority DESC, + ish.available >= s.quantity DESC, + s.quantity MOD ish.grouping = 0 DESC, + ish.grouping DESC, + IF(pc.orderMode = 'Location', p.pickingOrder, ish.created); + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + SELECT MAX(p.pickingOrder), s.quantity - SUM(IFNULL(iss.quantity, 0)) + INTO vLastPickingOrder, vOutStanding + FROM sale s + LEFT JOIN itemShelvingSale iss ON iss.saleFk = s.id + LEFT JOIN itemShelving ish ON ish.id = iss.itemShelvingFk + LEFT JOIN shelving sh ON sh.code = ish.shelvingFk + LEFT JOIN parking p ON p.id = sh.parkingFk + WHERE s.id = vSaleFk; + + IF vOutStanding <= 0 THEN + LEAVE proc; + END IF; + + SELECT getUser() INTO vUserFk; + + OPEN vItemShelvingAvailable; + l: LOOP + SET vDone = FALSE; + FETCH vItemShelvingAvailable INTO vItemShelvingFk, vAvailable; + + IF vOutStanding <= 0 OR vDone THEN + LEAVE l; + END IF; + + START TRANSACTION; + + SELECT id INTO vItemShelvingFk + FROM itemShelving + WHERE id = vItemShelvingFk + FOR UPDATE; + + SELECT LEAST(vOutStanding, vAvailable) INTO vReservedQuantity; + SET vOutStanding = vOutStanding - vReservedQuantity; + + IF vReservedQuantity > 0 THEN + + INSERT INTO itemShelvingSale( + itemShelvingFk, + saleFk, + quantity, + userFk) + SELECT vItemShelvingFk, + vSaleFk, + vReservedQuantity, + vUserFk; + + UPDATE itemShelving + SET available = available - vReservedQuantity + WHERE id = vItemShelvingFk; + + END IF; + + COMMIT; + END LOOP; + CLOSE vItemShelvingAvailable; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_addBySectorCollection` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_addBySectorCollection`(vSectorCollectionFk INT(11)) BEGIN /** - * Transfiere producto de una ubicación a otra, fusionando si coincide el - * packing y la fecha. + * Reserva cantidades con ubicaciones para el contenido de una preparación previa + * de la cual ya tiene generada la asociación del saleGroup con sectorCollection * - * @param vItemShelvingFk Identificador de itemShelving - * @param vShelvingFk Identificador de shelving + * @param vSectorCollectionFk Identificador de sectorCollection */ - DECLARE vNewItemShelvingFk INT DEFAULT 0; + DECLARE vDone BOOL DEFAULT FALSE; + DECLARE vSaleFk INT; + DECLARE vSales CURSOR FOR + SELECT s.id + FROM sectorCollectionSaleGroup sc + JOIN saleGroupDetail sg ON sg.saleGroupFk = sc.saleGroupFk + JOIN sale s ON sg.saleFk = s.id + JOIN saleTracking str ON str.saleFk = s.id + JOIN `state` st ON st.id = str.stateFk + AND st.code = 'PREVIOUS_PREPARATION' + LEFT JOIN itemShelvingSale iss ON iss.saleFk = s.id + WHERE sc.sectorCollectionFk = vSectorCollectionFk + AND str.workerFk = account.myUser_getId() + AND iss.id IS NULL; - SELECT MAX(ish.id) - INTO vNewItemShelvingFk - FROM itemShelving ish - JOIN ( - SELECT - itemFk, - packing, - created, - buyFk - FROM itemShelving - WHERE id = vItemShelvingFk - ) ish2 - ON ish2.itemFk = ish.itemFk - AND ish2.packing = ish.packing - AND date(ish2.created) = date(ish.created) - AND ish2.buyFk = ish.buyFk - WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci; + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - IF vNewItemShelvingFk THEN - UPDATE itemShelving ish - JOIN itemShelving ish2 ON ish2.id = vItemShelvingFk - SET ish.visible = ish.visible + ish2.visible - WHERE ish.id = vNewItemShelvingFk; + OPEN vSales; + l: LOOP + SET vDone = FALSE; + FETCH vSales INTO vSaleFk; - DELETE FROM itemShelving - WHERE id = vItemShelvingFk; - ELSE - UPDATE itemShelving - SET shelvingFk = vShelvingFk - WHERE id = vItemShelvingFk; - END IF; + IF vDone THEN + LEAVE l; + END IF; - SELECT true; + CALL itemShelvingSale_addBySale(vSaleFk); + END LOOP; + CLOSE vSales; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_doReserve` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_doReserve`() +proc: BEGIN +/** + * Genera reservas de la tabla vn.itemShelvingSaleReserve + */ + DECLARE vDone BOOL; + DECLARE vSaleFk INT; + + DECLARE vSales CURSOR FOR + SELECT DISTINCT saleFk FROM tSale; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + DECLARE CONTINUE HANDLER FOR SQLEXCEPTION + BEGIN + DO RELEASE_LOCK('vn.itemShelvingSale_doReserve'); + ROLLBACK; + RESIGNAL; + END; + + IF !GET_LOCK('vn.itemShelvingSale_doReserve', 0) THEN + LEAVE proc; + END IF; + + CREATE OR REPLACE TEMPORARY TABLE tSale + ENGINE = MEMORY + SELECT id, saleFk FROM itemShelvingSaleReserve; + + OPEN vSales; + + myLoop: LOOP + SET vDone = FALSE; + FETCH vSales INTO vSaleFk; + + IF vDone THEN + LEAVE myLoop; + END IF; + + CALL itemShelvingSale_addBySale (vSaleFk); + END LOOP; + + CLOSE vSales; + + DELETE iss FROM itemShelvingSaleReserve iss JOIN tSale s ON s.id = iss.id; + + DROP TEMPORARY TABLE tSale; + + DO RELEASE_LOCK('vn.itemShelvingSale_doReserve'); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_reallocate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_reallocate`( + vItemShelvingFk INT(10), + vItemFk INT(10) +) +BEGIN +/** + * Elimina reservas de un itemShelving e intenta reservar en otra ubicación + * + * @param vItemShelvingFk Id itemShelving + */ + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + START TRANSACTION; + + SELECT id INTO vItemShelvingFk + FROM itemShelving + WHERE id = vItemShelvingFk + FOR UPDATE; + + UPDATE itemShelving + SET visible = 0, + available = 0 + WHERE id = vItemShelvingFk + AND itemFk = vItemFk; + + INSERT INTO itemShelvingSaleReserve (saleFk) + SELECT DISTINCT iss.saleFk + FROM itemShelvingSale iss + JOIN itemShelving ish ON ish.id = iss.itemShelvingFk + WHERE iss.itemShelvingFk = vItemShelvingFk + AND ish.itemFk = vItemFk + AND NOT iss.isPicked; + + DELETE iss + FROM itemShelvingSale iss + JOIN itemShelving ish ON ish.id = iss.itemShelvingFk + WHERE iss.itemShelvingFk = vItemShelvingFk + AND ish.itemFk = vItemFk + AND NOT iss.isPicked; + COMMIT; + + CALL itemShelvingSale_doReserve(); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_setPicked` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_setPicked`( + vSaleGroupFk INT(10) +) +BEGIN +/** + * Gestiona la reserva de un vn.saleGroup actualizando vn.itemShelvingSale.isPicked + * y cambiando el estado de la vn.sale + * + * @param vSaleGroupFk Id saleGroupFk + */ + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + IF NOT (SELECT COUNT(*) FROM saleGroup WHERE id = vSaleGroupFk) THEN + CALL util.throw('Sale group not exists'); + END IF; + + START TRANSACTION; + + UPDATE itemShelvingSale iss + JOIN sale s ON s.id = iss.saleFk + JOIN saleGroupDetail sg ON sg.saleFk = s.id + SET iss.isPicked = TRUE + WHERE sg.saleGroupFk = vSaleGroupFk; + + CALL saleTracking_addPreparedSaleGroup(vSaleGroupFk); + + COMMIT; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_setQuantity` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_setQuantity`( + vItemShelvingSaleFk INT(10), + vQuantity DECIMAL(10,0), + vIsItemShelvingSaleEmpty BOOLEAN +) +BEGIN +/** + * Gestiona la reserva de un itemShelvingFk, actualizando isPicked y quantity + * en itemShelvingSale y sale.isPicked en caso necesario. + * Si la reserva de la ubicación es fallida, se regulariza la situación + * + * @param vItemShelvingSaleFk Id itemShelvingSaleFK + * @param vQuantity Cantidad real que se ha cogido de la ubicación + * @param vIsItemShelvingSaleEmpty determina si la ubicación itemShelvingSale se ha + * quedado vacio tras el movimiento + */ + DECLARE vSaleFk INT; + DECLARE vItemShelvingFk INT; + DECLARE vReservedQuantity INT; + DECLARE vRemainingQuantity INT; + DECLARE vItemFk INT; + DECLARE vTotalQuantity INT; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + IF (SELECT isPicked FROM itemShelvingSale WHERE id = vItemShelvingSaleFk) THEN + CALL util.throw('Reservation completed'); + END IF; + + SELECT s.itemFk, iss.saleFk, iss.itemShelvingFk, SUM(IFNULL(iss.quantity,0)) + INTO vItemFk, vSaleFk, vItemShelvingFk, vReservedQuantity + FROM itemShelvingSale iss + JOIN sale s ON s.id = iss.saleFk + WHERE iss.id = vItemShelvingSaleFk + AND NOT iss.isPicked; + + IF vQuantity > vReservedQuantity + OR (vQuantity < vReservedQuantity AND + (NOT vIsItemShelvingSaleEmpty OR vIsItemShelvingSaleEmpty IS NULL)) + OR (vIsItemShelvingSaleEmpty IS NOT NULL AND vQuantity = vReservedQuantity) THEN + CALL util.throw('The quantity cannot be different from the reserved'); + END IF; + + START TRANSACTION; + + UPDATE itemShelvingSale + SET isPicked = TRUE, + quantity = vQuantity + WHERE id = vItemShelvingSaleFk; + + SELECT id INTO vItemShelvingFk + FROM itemShelving + WHERE id = vItemShelvingFk + FOR UPDATE; + + UPDATE itemShelving + SET visible = GREATEST(0, visible - vQuantity) + WHERE id = vItemShelvingFk; + + SELECT SUM(IF(isPicked, 0, quantity)), SUM(quantity) + INTO vRemainingQuantity, vTotalQuantity + FROM itemShelvingSale + WHERE saleFk = vSaleFk; + + IF vRemainingQuantity = 0 AND NOT vIsItemShelvingSaleEmpty THEN + CALL saleTracking_new( + vSaleFk, + TRUE, + vTotalQuantity, + `account`.`myUser_getId`(), + NULL, + 'PREPARED', + TRUE); + + UPDATE sale s + SET s.quantity = vTotalQuantity, + isPicked = TRUE + WHERE s.id = vSaleFk; + END IF; + + COMMIT; + + IF vIsItemShelvingSaleEmpty AND vQuantity <> vReservedQuantity THEN + INSERT INTO itemShelvingSaleReserve (saleFk) + SELECT vSaleFk; + CALL itemShelvingSale_reallocate(vItemShelvingFk, vItemFk); + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_unpicked` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_unpicked`( + vSelf INT(11) +) +BEGIN +/** + * Desmarca una línea que ya estaba sacada, devolviendo la cantidad al itemShelving + * + * @param vSelf Identificador del itemShelvingSale + */ + DECLARE vSaleFk INT; + DECLARE vReservedQuantity INT; + DECLARE vIsSaleGroup BOOL; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + IF (SELECT NOT isPicked FROM itemShelvingSale WHERE id = vSelf) THEN + CALL util.throw('Reserva no completada'); + END IF; + + SELECT ish.saleFk, ish.quantity, IF(sg.id, TRUE, FALSE) + INTO vSaleFk, vReservedQuantity, vIsSaleGroup + FROM itemShelvingSale ish + LEFT JOIN saleGroupDetail sg ON sg.saleFk = ish.saleFk + WHERE ish.id = vSelf; + + /*IF vIsSaleGroup THEN + CALL util.throw('Can not unpicked a sale group'); + END IF;*/ + + START TRANSACTION; + + UPDATE itemShelvingSale + SET isPicked = FALSE + WHERE id = vSelf; + + UPDATE sale s + JOIN itemShelvingSale ish ON ish.saleFk = s.id + SET s.isPicked = FALSE + WHERE ish.id = vSelf; + + UPDATE itemShelvingSale iss + JOIN itemShelving ish ON ish.id = iss.itemShelvingFk + SET ish.visible = ish.visible + iss.quantity + WHERE iss.id = vSelf; + + CALL saleTracking_new( + vSaleFk, + FALSE, + vReservedQuantity, + `account`.`myUser_getId`(), + NULL, + 'ON_PREPARATION', + TRUE); + COMMIT; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60375,7 +60989,8 @@ proc:BEGIN sub.downstairs, sub.visible, CAST(visible - upstairs - downstairs AS DECIMAL(10,0)) nicho, - sub.name itemColour + sub.name itemColour, + CAST(sub2.pendiente AS DECIMAL(10,0)) pendingAmount FROM (SELECT iss.itemFk, CONCAT(i.longName, ' ', IFNULL(i.size, ''),' ', IFNULL(i.subName, '') ) longName, '' size, @@ -60412,7 +61027,8 @@ proc:BEGIN 0, v.visible, v.visible nicho, - ik.name itemColour + ik.name itemColour, + CAST(sub5.pendiente AS DECIMAL(10,0)) pendingAmount FROM cache.visible v JOIN item i ON i.id = v.item_id LEFT JOIN ink ik ON ik.id = i.inkFk @@ -60631,167 +61247,167 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_getSaleDate`(vShelvingFk VARCHAR(3)) -BEGIN - - /* Devuelve la mínima fecha en que se necesita cada producto en esa matrícula. - * - * @param vShelvingFk Matrícula del carro o pallet - */ - - DECLARE vWarehouseFk INT; - DECLARE vStockScopeDays INT; - - SELECT s.warehouseFk, stockScopeDays - INTO vWarehouseFk, vStockScopeDays - FROM sector s - JOIN operator o ON s.id = o.sectorFk - JOIN productionConfig pc - WHERE o.workerFk = account.myUser_getId(); - - IF vWarehouseFk IS NULL - THEN CALL util.throw('WarehouseFk not setted'); - END IF; - - IF vStockScopeDays IS NULL - THEN CALL util.throw('StockScopeDays not setted'); - END IF; - - CREATE OR REPLACE TEMPORARY TABLE tmp.tItems - (PRIMARY KEY (itemFk)) - ENGINE = MEMORY - SELECT itemFk, SUM(visible) visible - FROM itemShelving - WHERE shelvingFk = vShelvingFk COLLATE utf8_unicode_ci - GROUP BY itemFk; - - CREATE OR REPLACE TEMPORARY TABLE tmp.tStockByDay - (INDEX (itemFk, dated)) - ENGINE = MEMORY - SELECT dated, - SUM(t3.amount) OVER (PARTITION BY t3.itemFk ORDER BY dated) stock, - t3.itemFk - FROM ( - SELECT t.itemFk, dated, SUM(amount) amount - FROM ( - SELECT t2.itemFk, t2.amount, t2.dated - FROM ( - SELECT item_id itemFk, amount, util.VN_CURDATE() dated - FROM cache.stock s - JOIN tmp.tItems i ON i.itemFk = s.item_id - WHERE s.warehouse_id = vWarehouseFk - UNION ALL - SELECT ish.itemFk, - SUM(ish.visible), util.VN_CURDATE() - FROM itemShelving ish - JOIN tmp.tItems i ON i.itemFk = ish.itemFk - JOIN shelving sh ON sh.code = ish.shelvingFk - JOIN parking p ON sh.parkingFk = p.id - JOIN sector s ON s.id = p.sectorFk - WHERE s.isReserve - GROUP BY ish.itemFk - UNION ALL - SELECT iei.itemFk, SUM(quantity), landed - FROM itemEntryIn iei - JOIN tmp.tItems i ON i.itemFk = iei.itemFk - WHERE iei.landed BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY - AND iei.warehouseInFk = vWarehouseFk - AND NOT isVirtualStock - GROUP BY iei.itemFk, iei.landed - UNION ALL - SELECT ieo.itemFk, SUM(quantity), shipped - FROM itemEntryOut ieo - JOIN tmp.tItems i ON i.itemFk = ieo.itemFk - WHERE ieo.shipped BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY - AND ieo.warehouseOutFk = vWarehouseFk - GROUP BY ieo.itemFk, ieo.shipped - UNION ALL - SELECT i.itemFk, SUM(ito.quantity), DATE(ito.shipped) - FROM itemTicketOut ito - JOIN tmp.tItems i ON i.itemFk = ito.itemFk - WHERE ito.shipped BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY - AND ito.warehouseFk = vWarehouseFk - GROUP BY ito.itemFk, ito.shipped - ) t2 - JOIN tmp.tItems i ON i.itemFk = t2.itemFk)t - GROUP BY t.itemFk, dated - ) t3; - - -- Se restan las entradas de hoy - UPDATE tmp.tStockByDay sbd - JOIN (SELECT iei.itemFk, SUM(quantity) todayEntry - FROM itemEntryIn iei - JOIN tmp.tItems i ON i.itemFk = iei.itemFk - WHERE iei.landed = util.VN_CURDATE() - AND iei.warehouseInFk = vWarehouseFk - AND NOT iei.isVirtualStock) sub ON sub.itemFk = sbd.itemFk - SET sbd.stock = sbd.stock - sub.todayEntry - WHERE sbd.dated = util.VN_CURDATE(); - - -- Se añaden las lineas de venta servidas - UPDATE tmp.tStockByDay sbd - JOIN (SELECT s.itemFK, SUM(quantity) amount - FROM sale s - JOIN ticket t ON t.id = s.ticketFk - WHERE t.warehouseFk = vWarehouseFk - AND t.shipped BETWEEN util.VN_CURDATE() AND util.midnight() - AND s.isPicked - GROUP BY s.itemFk) sub ON sub.itemFk = sbd.itemFk - SET sbd.stock = sbd.stock + sub.amount; - - -- Se añaden los items ubicados hoy - UPDATE tmp.tStockByDay sbd - JOIN (SELECT ish.itemFK, SUM(ish.visible) amount - FROM itemShelving ish - JOIN shelving sh ON sh.code = ish.shelvingFk - JOIN parking p ON p.id = sh.parkingFk - JOIN sector s ON s.id = p.sectorFk - WHERE s.warehouseFk = vWarehouseFk - AND NOT s.isReserve - AND ish.created BETWEEN util.VN_CURDATE() AND util.midnight() - GROUP BY ish.itemFk) sub ON sub.itemFk = sbd.itemFk - SET sbd.stock = sbd.stock + sub.amount; - - SELECT ts.itemFk, - i.longName, - IF(ts.stock<=0, ts.dated, NULL) dated, - ts.stock, - sub4.visible, - sub4.shelvingFk - FROM( - SELECT IFNULL(sub2.minDated, sub.minDated) dated, - IFNULL(sub2.itemFk, sub.itemFk) itemFk - FROM(SELECT sbd.itemFk, - MIN(dated) minDated, - sbd.stock - FROM tmp.tItems ti - LEFT JOIN tmp.tStockByDay sbd ON sbd.itemFk = ti.itemFk - GROUP BY itemFk)sub - LEFT JOIN ( - SELECT sbd.itemFk, - MIN(dated) minDated, - sbd.stock - FROM tmp.tItems ti - LEFT JOIN tmp.tStockByDay sbd ON sbd.itemFk = ti.itemFk - WHERE sbd.stock <= 0 - GROUP BY itemFk)sub2 ON sub2.itemFk =sub.itemFk - WHERE sub2.itemFk IS NOT NULL - OR (sub2.itemFk IS NULL AND sub.itemFk IS NOT NULL)) sub3 - LEFT JOIN tmp.tStockByDay ts ON ts.itemFk = sub3.itemFk AND ts.dated = sub3.dated - JOIN (SELECT ish.itemFk, - ish.visible, - p.sectorFk, - ish.shelvingFk - FROM itemShelving ish - JOIN vn.shelving sh ON sh.code = ish.shelvingFk - LEFT JOIN parking p ON p.id = parkingFk - LEFT JOIN vn.sector s ON s.id = p.sectorFk - WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci - ) sub4 ON sub4.itemFk = ts.itemFk - LEFT JOIN sector s ON s.id = sub4.sectorFk - LEFT JOIN item i ON i.id = ts.itemFk - WHERE NOT s.isReserve; - - DROP TEMPORARY TABLE tmp.tStockByDay, tmp.tItems; - +BEGIN + + /* Devuelve la mínima fecha en que se necesita cada producto en esa matrícula. + * + * @param vShelvingFk Matrícula del carro o pallet + */ + + DECLARE vWarehouseFk INT; + DECLARE vStockScopeDays INT; + + SELECT s.warehouseFk, stockScopeDays + INTO vWarehouseFk, vStockScopeDays + FROM sector s + JOIN operator o ON s.id = o.sectorFk + JOIN productionConfig pc + WHERE o.workerFk = account.myUser_getId(); + + IF vWarehouseFk IS NULL + THEN CALL util.throw('WarehouseFk not setted'); + END IF; + + IF vStockScopeDays IS NULL + THEN CALL util.throw('StockScopeDays not setted'); + END IF; + + CREATE OR REPLACE TEMPORARY TABLE tmp.tItems + (PRIMARY KEY (itemFk)) + ENGINE = MEMORY + SELECT itemFk, SUM(visible) visible + FROM itemShelving + WHERE shelvingFk = vShelvingFk COLLATE utf8_unicode_ci + GROUP BY itemFk; + + CREATE OR REPLACE TEMPORARY TABLE tmp.tStockByDay + (INDEX (itemFk, dated)) + ENGINE = MEMORY + SELECT dated, + SUM(t3.amount) OVER (PARTITION BY t3.itemFk ORDER BY dated) stock, + t3.itemFk + FROM ( + SELECT t.itemFk, dated, SUM(amount) amount + FROM ( + SELECT t2.itemFk, t2.amount, t2.dated + FROM ( + SELECT item_id itemFk, amount, util.VN_CURDATE() dated + FROM cache.stock s + JOIN tmp.tItems i ON i.itemFk = s.item_id + WHERE s.warehouse_id = vWarehouseFk + UNION ALL + SELECT ish.itemFk, - SUM(ish.visible), util.VN_CURDATE() + FROM itemShelving ish + JOIN tmp.tItems i ON i.itemFk = ish.itemFk + JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN parking p ON sh.parkingFk = p.id + JOIN sector s ON s.id = p.sectorFk + WHERE s.isReserve + GROUP BY ish.itemFk + UNION ALL + SELECT iei.itemFk, SUM(quantity), landed + FROM itemEntryIn iei + JOIN tmp.tItems i ON i.itemFk = iei.itemFk + WHERE iei.landed BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY + AND iei.warehouseInFk = vWarehouseFk + AND NOT isVirtualStock + GROUP BY iei.itemFk, iei.landed + UNION ALL + SELECT ieo.itemFk, SUM(quantity), shipped + FROM itemEntryOut ieo + JOIN tmp.tItems i ON i.itemFk = ieo.itemFk + WHERE ieo.shipped BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY + AND ieo.warehouseOutFk = vWarehouseFk + GROUP BY ieo.itemFk, ieo.shipped + UNION ALL + SELECT i.itemFk, SUM(ito.quantity), DATE(ito.shipped) + FROM itemTicketOut ito + JOIN tmp.tItems i ON i.itemFk = ito.itemFk + WHERE ito.shipped BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY + AND ito.warehouseFk = vWarehouseFk + GROUP BY ito.itemFk, ito.shipped + ) t2 + JOIN tmp.tItems i ON i.itemFk = t2.itemFk)t + GROUP BY t.itemFk, dated + ) t3; + + -- Se restan las entradas de hoy + UPDATE tmp.tStockByDay sbd + JOIN (SELECT iei.itemFk, SUM(quantity) todayEntry + FROM itemEntryIn iei + JOIN tmp.tItems i ON i.itemFk = iei.itemFk + WHERE iei.landed = util.VN_CURDATE() + AND iei.warehouseInFk = vWarehouseFk + AND NOT iei.isVirtualStock) sub ON sub.itemFk = sbd.itemFk + SET sbd.stock = sbd.stock - sub.todayEntry + WHERE sbd.dated = util.VN_CURDATE(); + + -- Se añaden las lineas de venta servidas + UPDATE tmp.tStockByDay sbd + JOIN (SELECT s.itemFK, SUM(quantity) amount + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + WHERE t.warehouseFk = vWarehouseFk + AND t.shipped BETWEEN util.VN_CURDATE() AND util.midnight() + AND s.isPicked + GROUP BY s.itemFk) sub ON sub.itemFk = sbd.itemFk + SET sbd.stock = sbd.stock + sub.amount; + + -- Se añaden los items ubicados hoy + UPDATE tmp.tStockByDay sbd + JOIN (SELECT ish.itemFK, SUM(ish.visible) amount + FROM itemShelving ish + JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN parking p ON p.id = sh.parkingFk + JOIN sector s ON s.id = p.sectorFk + WHERE s.warehouseFk = vWarehouseFk + AND NOT s.isReserve + AND ish.created BETWEEN util.VN_CURDATE() AND util.midnight() + GROUP BY ish.itemFk) sub ON sub.itemFk = sbd.itemFk + SET sbd.stock = sbd.stock + sub.amount; + + SELECT ts.itemFk, + i.longName, + IF(ts.stock<=0, ts.dated, NULL) dated, + ts.stock, + sub4.visible, + sub4.shelvingFk + FROM( + SELECT IFNULL(sub2.minDated, sub.minDated) dated, + IFNULL(sub2.itemFk, sub.itemFk) itemFk + FROM(SELECT sbd.itemFk, + MIN(dated) minDated, + sbd.stock + FROM tmp.tItems ti + LEFT JOIN tmp.tStockByDay sbd ON sbd.itemFk = ti.itemFk + GROUP BY itemFk)sub + LEFT JOIN ( + SELECT sbd.itemFk, + MIN(dated) minDated, + sbd.stock + FROM tmp.tItems ti + LEFT JOIN tmp.tStockByDay sbd ON sbd.itemFk = ti.itemFk + WHERE sbd.stock <= 0 + GROUP BY itemFk)sub2 ON sub2.itemFk =sub.itemFk + WHERE sub2.itemFk IS NOT NULL + OR (sub2.itemFk IS NULL AND sub.itemFk IS NOT NULL)) sub3 + LEFT JOIN tmp.tStockByDay ts ON ts.itemFk = sub3.itemFk AND ts.dated = sub3.dated + JOIN (SELECT ish.itemFk, + ish.visible, + p.sectorFk, + ish.shelvingFk + FROM itemShelving ish + JOIN vn.shelving sh ON sh.code = ish.shelvingFk + LEFT JOIN parking p ON p.id = parkingFk + LEFT JOIN vn.sector s ON s.id = p.sectorFk + WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci + ) sub4 ON sub4.itemFk = ts.itemFk + LEFT JOIN sector s ON s.id = sub4.sectorFk + LEFT JOIN item i ON i.id = ts.itemFk + WHERE NOT s.isReserve; + + DROP TEMPORARY TABLE tmp.tStockByDay, tmp.tItems; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60978,6 +61594,67 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelving_transfer` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_transfer`( + vItemShelvingFk INT, + vShelvingFk VARCHAR(10) +) +BEGIN +/** + * Transfiere producto de una ubicación a otra, fusionando si coincide el + * packing y la fecha. + * + * @param vItemShelvingFk Identificador de itemShelving + * @param vShelvingFk Identificador de shelving + */ + DECLARE vNewItemShelvingFk INT DEFAULT 0; + + SELECT MAX(ish.id) + INTO vNewItemShelvingFk + FROM itemShelving ish + JOIN ( + SELECT + itemFk, + packing, + created, + buyFk + FROM itemShelving + WHERE id = vItemShelvingFk + ) ish2 ON ish2.itemFk = ish.itemFk + AND ish2.packing = ish.packing + AND date(ish2.created) = date(ish.created) + AND ish2.buyFk = ish.buyFk + WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci; + + IF vNewItemShelvingFk THEN + UPDATE itemShelving ish + JOIN itemShelving ish2 ON ish2.id = vItemShelvingFk + SET ish.visible = ish.visible + ish2.visible + WHERE ish.id = vNewItemShelvingFk; + + DELETE FROM itemShelving + WHERE id = vItemShelvingFk; + ELSE + UPDATE itemShelving + SET shelvingFk = vShelvingFk + WHERE id = vItemShelvingFk; + END IF; + SELECT true; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `itemShelving_update` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -62333,50 +63010,50 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getAtp`(vDated DATE) -BEGIN -/** - * Calcula el valor mínimo acumulado para cada artículo ordenado por fecha y - * almacén. - * - * @param vDated Si no hay movimientos en la fecha indicada, debe devolver 0 - * @table tmp.itemCalc(itemFk, wareHouseFk, dated, quantity) - * @return tmp.itemAtp(itemFk, warehouseFk, quantity) - */ - CREATE OR REPLACE TEMPORARY TABLE tItemOrdered - (UNIQUE(itemFk, warehouseFk, dated)) - ENGINE = MEMORY - SELECT itemFk, warehouseFk, dated, SUM(quantity) quantity - FROM ( - SELECT itemFk, warehouseFk, dated, quantity - FROM tmp.itemCalc - UNION ALL - SELECT itemFk, warehouseFk, vDated, 0 - FROM (SELECT DISTINCT itemFk, warehouseFk FROM tmp.itemCalc) t2 - ) t1 - GROUP BY itemFk, warehouseFk, dated - ORDER BY itemFk, warehouseFk, dated; - - SET @lastItemFk := 0; - SET @lastWareHouseFk := 0; - SET @lastQuantity := 0; - - CREATE OR REPLACE TEMPORARY TABLE tmp.itemAtp - (INDEX (itemFk, wareHouseFk)) - SELECT itemFk, wareHouseFk, MIN(quantityAccumulated) quantity - FROM ( - SELECT - itemFk, - IF(itemFk <> @lastItemFk OR wareHouseFk <> @lastWareHouseFk, - @lastQuantity := quantity, - @lastQuantity := @lastQuantity + quantity) quantityAccumulated, - wareHouseFk, - @lastItemFk := itemFk, - @lastWareHouseFk := wareHouseFk - FROM tItemOrdered - )sub - GROUP BY itemFk, wareHouseFk; - - DROP TEMPORARY TABLE tItemOrdered; +BEGIN +/** + * Calcula el valor mínimo acumulado para cada artículo ordenado por fecha y + * almacén. + * + * @param vDated Si no hay movimientos en la fecha indicada, debe devolver 0 + * @table tmp.itemCalc(itemFk, wareHouseFk, dated, quantity) + * @return tmp.itemAtp(itemFk, warehouseFk, quantity) + */ + CREATE OR REPLACE TEMPORARY TABLE tItemOrdered + (UNIQUE(itemFk, warehouseFk, dated)) + ENGINE = MEMORY + SELECT itemFk, warehouseFk, dated, SUM(quantity) quantity + FROM ( + SELECT itemFk, warehouseFk, dated, quantity + FROM tmp.itemCalc + UNION ALL + SELECT itemFk, warehouseFk, vDated, 0 + FROM (SELECT DISTINCT itemFk, warehouseFk FROM tmp.itemCalc) t2 + ) t1 + GROUP BY itemFk, warehouseFk, dated + ORDER BY itemFk, warehouseFk, dated; + + SET @lastItemFk := 0; + SET @lastWareHouseFk := 0; + SET @lastQuantity := 0; + + CREATE OR REPLACE TEMPORARY TABLE tmp.itemAtp + (INDEX (itemFk, wareHouseFk)) + SELECT itemFk, wareHouseFk, MIN(quantityAccumulated) quantity + FROM ( + SELECT + itemFk, + IF(itemFk <> @lastItemFk OR wareHouseFk <> @lastWareHouseFk, + @lastQuantity := quantity, + @lastQuantity := @lastQuantity + quantity) quantityAccumulated, + wareHouseFk, + @lastItemFk := itemFk, + @lastWareHouseFk := wareHouseFk + FROM tItemOrdered + )sub + GROUP BY itemFk, wareHouseFk; + + DROP TEMPORARY TABLE tItemOrdered; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -62970,14 +63647,13 @@ BEGIN * @param vDated Fecha * @param vShowType Mostrar tipos */ - DECLARE vCalcFk INT; + DECLARE vAvailableCalcFk INT; + DECLARE vVisibleCalcFk INT; DECLARE vTypeFk INT; DECLARE vPriority INT DEFAULT 1; - CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, vDated); - - -- Añadido temporalmente para que no se cuelgue la db - SET vShowType = TRUE; + CALL cache.available_refresh(vAvailableCalcFk, FALSE, vWarehouseFk, vDated); + CALL cache.visible_refresh(vVisibleCalcFk, FALSE, vWarehouseFk); WITH itemTags AS ( SELECT i.id, @@ -63020,21 +63696,21 @@ BEGIN WHEN b.groupingMode = 'packing' THEN b.packing ELSE 1 END AS minQuantity, - iss.visible located, + v.visible located, b.price2 FROM vn.item i JOIN cache.available a ON a.item_id = i.id - AND a.calc_id = vCalcFk + AND a.calc_id = vAvailableCalcFk + LEFT JOIN cache.visible v ON v.item_id = i.id + AND v.calc_id = vVisibleCalcFk + LEFT JOIN cache.last_buy lb ON lb.item_id = i.id + AND lb.warehouse_id = vWarehouseFk LEFT JOIN vn.itemProposal ip ON ip.mateFk = i.id AND ip.itemFk = vSelf LEFT JOIN vn.itemTag it ON it.itemFk = i.id AND it.priority = vPriority LEFT JOIN vn.tag t ON t.id = it.tagFk - LEFT JOIN cache.last_buy lb ON lb.item_id = i.id - AND lb.warehouse_id = vWarehouseFk LEFT JOIN vn.buy b ON b.id = lb.buy_id - LEFT JOIN vn.itemShelvingStock iss ON iss.itemFk = i.id - AND iss.warehouseFk = vWarehouseFk JOIN itemTags its WHERE a.available > 0 AND (i.typeFk = its.typeFk OR NOT vShowType) @@ -64541,197 +65217,206 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `multipleInventory`( - vDate DATE, - vWarehouseFk TINYINT, - vMaxDays TINYINT +CREATE DEFINER=`root`@`localhost` PROCEDURE `multipleInventory`( + vDate DATE, + vWarehouseFk TINYINT, + vMaxDays TINYINT ) -proc: BEGIN - DECLARE vDateTomorrow DATE DEFAULT vDate + INTERVAL 1 DAY; - DECLARE vDateFrom DATE DEFAULT vDate; - DECLARE vDateTo DATETIME; - DECLARE vDateToTomorrow DATETIME; - DECLARE vDefaultDayRange INT; - - IF vDate < util.VN_CURDATE() THEN - LEAVE proc; - END IF; - - IF vDate = util.VN_CURDATE() THEN - SELECT inventoried INTO vDateFrom - FROM config; - END IF; - - SELECT defaultDayRange INTO vDefaultDayRange - FROM comparativeConfig; - - SET vDateTo = vDate + INTERVAL IFNULL(vMaxDays, vDefaultDayRange) DAY; - SET vDateToTomorrow = vDateTo + INTERVAL 1 DAY; - - ALTER TABLE tmp.itemInventory - ADD `avalaible` INT NOT NULL, - ADD `sd` INT NOT NULL, - ADD `rest` INT NOT NULL, - ADD `expected` INT NOT NULL, - ADD `inventory` INT NOT NULL, - ADD `visible` INT NOT NULL, - ADD `life` TINYINT NOT NULL DEFAULT '0'; - - -- Calculo del inventario - UPDATE tmp.itemInventory ai - JOIN ( - SELECT itemFk Id_Article, SUM(quantity) Subtotal - FROM ( - SELECT s.itemFk, - s.quantity quantity - FROM sale s - JOIN ticket t ON t.id = s.ticketFk - JOIN warehouse w ON w.id = t.warehouseFk - WHERE t.shipped BETWEEN vDateFrom AND util.dayEnd(vDate) - AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk - AND w.isComparative - UNION ALL - SELECT b.itemFk, b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseInFk - WHERE t.landed BETWEEN vDateFrom AND util.dayEnd(vDate) - AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk - AND w.isComparative - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - UNION ALL - SELECT b.itemFk, - b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseOutFk - WHERE t.shipped BETWEEN vDateFrom AND util.dayEnd(vDate) - AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk - AND w.isComparative - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - ) sub2 - GROUP BY itemFk - ) sub ON ai.id = sub.Id_Article - SET ai.inventory = sub.Subtotal, - ai.visible = sub.Subtotal, - ai.avalaible = sub.Subtotal, - ai.sd = sub.Subtotal; - - -- Cálculo del visible - UPDATE tmp.itemInventory ai - JOIN ( - SELECT itemFk Id_Article, SUM(quantity) Subtotal - FROM ( - SELECT s.itemFk, s.quantity - FROM sale s - JOIN ticket t ON t.id = s.ticketFk - JOIN warehouse w ON w.id = t.warehouseFk - WHERE t.shipped >= vDate - AND t.shipped < vDateTomorrow - AND (NOT isPicked AND NOT t.isLabeled AND t.refFk IS NULL) - AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk - AND w.isComparative - UNION ALL - SELECT b.itemFk, - b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseInFk - WHERE t.landed = vDate - AND NOT t.isReceived - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk - AND w.isComparative - UNION ALL - SELECT b.itemFk, b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseOutFk - WHERE t.shipped = vDate - AND NOT t.isReceived - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk - AND w.isComparative - ) sub2 - GROUP BY itemFk - ) sub ON ai.id = sub.Id_Article - SET ai.visible = ai.visible + sub.Subtotal; - - -- Calculo del disponible - CREATE OR REPLACE TEMPORARY TABLE tmp.itemCalc - (INDEX (itemFk, warehouseFk)) - ENGINE = MEMORY - SELECT sub.itemFk, - vWarehouseFk warehouseFk, - sub.dated, - SUM(sub.quantity) quantity - FROM ( - SELECT s.itemFk, - DATE(t.shipped) dated, - - s.quantity quantity - FROM sale s - JOIN ticket t ON t.id = s.ticketFk - JOIN warehouse w ON w.id = t.warehouseFk - WHERE t.shipped BETWEEN vDateTomorrow AND vDateTo - AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk - AND w.isComparative - UNION ALL - SELECT b.itemFk, t.landed, b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseInFk - WHERE t.landed BETWEEN vDateTomorrow AND vDateTo - AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk - AND w.isComparative - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - UNION ALL - SELECT b.itemFk, t.shipped, - b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseOutFk - WHERE t.shipped BETWEEN vDateTomorrow AND vDateTo - AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk - AND w.isComparative - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - ) sub - GROUP BY sub.itemFk, sub.dated; - - CALL item_getAtp(vDate); - CALL travel_upcomingArrivals(vWarehouseFk, vDate); - - UPDATE tmp.itemInventory ai - JOIN ( - SELECT it.itemFk, - SUM(it.quantity) quantity, - im.quantity minQuantity - FROM tmp.itemCalc it - JOIN tmp.itemAtp im ON im.itemFk = it.itemFk - JOIN item i ON i.id = it.itemFk - LEFT JOIN origin o ON o.id = i.originFk - LEFT JOIN tmp.itemTravel t ON t.wh = o.warehouseFk - WHERE it.dated < IF(vMaxDays < 0 AND t.landing IS NOT NULL, - t.landing, - vDateToTomorrow) - GROUP BY it.itemFk - ) sub ON sub.itemFk = ai.id - SET ai.avalaible = IF(sub.minQuantity > 0, - ai.avalaible, - ai.avalaible + sub.minQuantity), - ai.sd = ai.inventory + sub.quantity; - - DROP TEMPORARY TABLE - tmp.itemTravel, - tmp.itemCalc, - tmp.itemAtp; +proc: BEGIN + DECLARE vDateTomorrow DATE DEFAULT vDate + INTERVAL 1 DAY; + DECLARE vDateFrom DATE DEFAULT vDate; + DECLARE vDateTo DATETIME; + DECLARE vDateToTomorrow DATETIME; + DECLARE vDefaultDayRange INT; + + IF vDate < util.VN_CURDATE() THEN + LEAVE proc; + END IF; + + IF vDate = util.VN_CURDATE() THEN + SELECT inventoried INTO vDateFrom + FROM config; + END IF; + + SELECT defaultDayRange INTO vDefaultDayRange + FROM comparativeConfig; + + SET vDateTo = vDate + INTERVAL IFNULL(vMaxDays, vDefaultDayRange) DAY; + SET vDateToTomorrow = vDateTo + INTERVAL 1 DAY; + + ALTER TABLE tmp.itemInventory + ADD `avalaible` INT NOT NULL, + ADD `sd` INT NOT NULL, + ADD `rest` INT NOT NULL, + ADD `expected` INT NOT NULL, + ADD `inventory` INT NOT NULL, + ADD `visible` INT NOT NULL, + ADD `life` TINYINT NOT NULL DEFAULT '0'; + + -- Calculo del inventario + CREATE OR REPLACE TEMPORARY TABLE tItemInventoryCalc + (PRIMARY KEY (itemFk)) + ENGINE = MEMORY + SELECT itemFk, + SUM(quantity) quantity + FROM ( + SELECT s.itemFk, - s.quantity quantity + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + JOIN warehouse w ON w.id = t.warehouseFk + WHERE t.shipped BETWEEN vDateFrom AND util.dayEnd(vDate) + AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk + AND w.isComparative + UNION ALL + SELECT b.itemFk, b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseInFk + WHERE t.landed BETWEEN vDateFrom AND util.dayEnd(vDate) + AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk + AND w.isComparative + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + UNION ALL + SELECT b.itemFk, - b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseOutFk + WHERE t.shipped BETWEEN vDateFrom AND util.dayEnd(vDate) + AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk + AND w.isComparative + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + ) sub + GROUP BY itemFk; + + UPDATE tmp.itemInventory ai + JOIN tItemInventoryCalc iic ON iic.itemFk = ai.id + SET ai.inventory = iic.quantity, + ai.visible = iic.quantity, + ai.avalaible = iic.quantity, + ai.sd = iic.quantity; + + -- Cálculo del visible + CREATE OR REPLACE TEMPORARY TABLE tItemVisibleCalc + (PRIMARY KEY (itemFk)) + ENGINE = MEMORY + SELECT itemFk, SUM(quantity) visible + FROM ( + SELECT s.itemFk, s.quantity + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + JOIN warehouse w ON w.id = t.warehouseFk + WHERE t.shipped >= vDate + AND t.shipped < vDateTomorrow + AND (NOT isPicked AND NOT t.isLabeled AND t.refFk IS NULL) + AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk + AND w.isComparative + UNION ALL + SELECT b.itemFk, - b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseInFk + WHERE t.landed = vDate + AND NOT t.isReceived + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk + AND w.isComparative + UNION ALL + SELECT b.itemFk, b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseOutFk + WHERE t.shipped = vDate + AND NOT t.isReceived + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk + AND w.isComparative + ) sub2 + GROUP BY itemFk; + + UPDATE tmp.itemInventory ai + JOIN tItemVisibleCalc ivc ON ivc.itemFk = ai.id + SET ai.visible = ai.visible + ivc.visible; + + -- Calculo del disponible + CREATE OR REPLACE TEMPORARY TABLE tmp.itemCalc + (INDEX (itemFk, warehouseFk)) + ENGINE = MEMORY + SELECT sub.itemFk, + vWarehouseFk warehouseFk, + sub.dated, + SUM(sub.quantity) quantity + FROM ( + SELECT s.itemFk, + DATE(t.shipped) dated, + - s.quantity quantity + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + JOIN warehouse w ON w.id = t.warehouseFk + WHERE t.shipped BETWEEN vDateTomorrow AND vDateTo + AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk + AND w.isComparative + UNION ALL + SELECT b.itemFk, t.landed, b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseInFk + WHERE t.landed BETWEEN vDateTomorrow AND vDateTo + AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk + AND w.isComparative + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + UNION ALL + SELECT b.itemFk, t.shipped, - b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseOutFk + WHERE t.shipped BETWEEN vDateTomorrow AND vDateTo + AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk + AND w.isComparative + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + ) sub + GROUP BY sub.itemFk, sub.dated; + + CALL item_getAtp(vDate); + CALL travel_upcomingArrivals(vWarehouseFk, vDate); + + UPDATE tmp.itemInventory ai + JOIN ( + SELECT it.itemFk, + SUM(it.quantity) quantity, + im.quantity minQuantity + FROM tmp.itemCalc it + JOIN tmp.itemAtp im ON im.itemFk = it.itemFk + JOIN item i ON i.id = it.itemFk + LEFT JOIN origin o ON o.id = i.originFk + LEFT JOIN tmp.itemTravel t ON t.wh = o.warehouseFk + WHERE it.dated < IF(vMaxDays < 0 AND t.landing IS NOT NULL, + t.landing, + vDateToTomorrow) + GROUP BY it.itemFk + ) sub ON sub.itemFk = ai.id + SET ai.avalaible = IF(sub.minQuantity > 0, + ai.avalaible, + ai.avalaible + sub.minQuantity), + ai.sd = ai.inventory + sub.quantity; + + DROP TEMPORARY TABLE + tmp.itemTravel, + tmp.itemCalc, + tItemInventoryCalc, + tItemVisibleCalc, + tmp.itemAtp; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -65662,6 +66347,11 @@ proc: BEGIN DECLARE vEndingDate DATETIME; DECLARE vIsTodayRelative BOOLEAN; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + RESIGNAL; + END; + SELECT util.dayEnd(util.VN_CURDATE()) + INTERVAL LEAST(vScopeDays, maxProductionScopeDays) DAY INTO vEndingDate FROM productionConfig; @@ -65678,7 +66368,8 @@ proc: BEGIN CALL prepareClientList(); CREATE OR REPLACE TEMPORARY TABLE tmp.sale_getProblems - (INDEX (ticketFk)) ENGINE = MEMORY + (INDEX (ticketFk)) + ENGINE = MEMORY SELECT tt.ticketFk, tt.clientFk, t.warehouseFk, t.shipped FROM tmp.productionTicket tt JOIN ticket t ON t.id = tt.ticketFk; @@ -67555,43 +68246,43 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sales_merge`(vTicketFk INT) -BEGIN - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - CREATE OR REPLACE TEMPORARY TABLE tSalesToPreserve - (PRIMARY KEY (id)) - ENGINE = MEMORY - SELECT s.id, s.itemFk, SUM(s.quantity) newQuantity - FROM sale s - JOIN item i ON i.id = s.itemFk - JOIN itemType it ON it.id = i.typeFk - WHERE s.ticketFk = vTicketFk - AND it.isMergeable - GROUP BY s.itemFk, s.price, s.discount; - - START TRANSACTION; - - UPDATE sale s - JOIN tSalesToPreserve stp ON stp.id = s.id - SET s.quantity = newQuantity - WHERE s.ticketFk = vTicketFk; - - DELETE s.* - FROM sale s - LEFT JOIN tSalesToPreserve stp ON stp.id = s.id - JOIN item i ON i.id = s.itemFk - JOIN itemType it ON it.id = i.typeFk - WHERE s.ticketFk = vTicketFk - AND stp.id IS NULL - AND it.isMergeable; - - COMMIT; - - DROP TEMPORARY TABLE tSalesToPreserve; +BEGIN + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + CREATE OR REPLACE TEMPORARY TABLE tSalesToPreserve + (PRIMARY KEY (id)) + ENGINE = MEMORY + SELECT s.id, s.itemFk, SUM(s.quantity) newQuantity + FROM sale s + JOIN item i ON i.id = s.itemFk + JOIN itemType it ON it.id = i.typeFk + WHERE s.ticketFk = vTicketFk + AND it.isMergeable + GROUP BY s.itemFk, s.price, s.discount; + + START TRANSACTION; + + UPDATE sale s + JOIN tSalesToPreserve stp ON stp.id = s.id + SET s.quantity = newQuantity + WHERE s.ticketFk = vTicketFk; + + DELETE s.* + FROM sale s + LEFT JOIN tSalesToPreserve stp ON stp.id = s.id + JOIN item i ON i.id = s.itemFk + JOIN itemType it ON it.id = i.typeFk + WHERE s.ticketFk = vTicketFk + AND stp.id IS NULL + AND it.isMergeable; + + COMMIT; + + DROP TEMPORARY TABLE tSalesToPreserve; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -68705,12 +69396,11 @@ BEGIN -- Redondeo: Cantidad pedida incorrecta en al grouping de la última compra CALL buyUltimate(vWarehouseFk, vDate); INSERT INTO tmp.sale_problems(ticketFk, hasRounding, saleFk) - SELECT ticketFk, problem, saleFk + SELECT ticketFk, problem ,saleFk FROM ( SELECT tl.ticketFk, - s.id saleFk , - LEFT(GROUP_CONCAT('RE: ',i.id, ' ', IFNULL(i.longName,''), ' '), 250) problem, - MOD(s.quantity, b.`grouping`) hasRounding + s.id saleFk, + LEFT(GROUP_CONCAT('RE: ',i.id, ' ', IFNULL(i.longName,'') SEPARATOR ', '), 250) problem FROM tmp.ticket_list tl JOIN ticket t ON t.id = tl.ticketFk AND t.warehouseFk = vWarehouseFk @@ -68718,9 +69408,9 @@ BEGIN JOIN item i ON i.id = s.itemFk JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk JOIN buy b ON b.id = bu.buyFk + WHERE MOD(s.quantity, b.`grouping`) GROUP BY tl.ticketFk - HAVING hasRounding - ) sub + )sub ON DUPLICATE KEY UPDATE hasRounding = sub.problem, saleFk = sub.saleFk; END LOOP; CLOSE vCursor; @@ -69350,6 +70040,37 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `sectorCollection_getMyPartial` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `sectorCollection_getMyPartial`() +BEGIN +/** + * Devuelve las colecciones del sector que corresponden al usuario conectado, y que estan incompletas + * + */ + SELECT DISTINCT sc.id collectionFk, sc.created + FROM vn.sectorCollection sc + LEFT JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id + LEFT JOIN vn.saleGroupDetail sgd ON sgd.saleGroupFk = scsg.saleGroupFk + LEFT JOIN vn.sale sl ON sl.id = sgd.saleFk + LEFT JOIN itemShelvingSale iss ON iss.saleFk = sl.id + WHERE sc.userFk = account.myUser_getId() + AND (scsg.sectorCollectionFk IS NULL OR NOT iss.isPicked) + AND sc.created > util.VN_CURDATE() - INTERVAL 1 DAY; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `sectorCollection_getSale` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -69404,30 +70125,30 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sectorCollection_new`(vSectorFk INT) -BEGIN -/** - * Inserta una nueva colección, si el usuario no tiene ninguna vacia. - * Esto se hace para evitar que por error se generen colecciones sin sentido. - * - * @param vSectorFk Identificador de #vn.sector - */ - DECLARE hasEmptyCollections BOOL; - DECLARE vUserFk INT; - - SET vUserFk = account.myUser_getId(); - - SELECT (COUNT(sc.id) > 0) INTO hasEmptyCollections - FROM vn.sectorCollection sc - LEFT JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id - WHERE ISNULL(scsg.id) - AND sc.userFk = vUserFk - AND sc.sectorFk = vSectorFk - AND sc.created >= util.VN_CURDATE(); - - IF NOT hasEmptyCollections THEN - INSERT INTO vn.sectorCollection(userFk, sectorFk) - VALUES(vUserFk, vSectorFk); - END IF; +BEGIN +/** + * Inserta una nueva colección, si el usuario no tiene ninguna vacia. + * Esto se hace para evitar que por error se generen colecciones sin sentido. + * + * @param vSectorFk Identificador de #vn.sector + */ + DECLARE hasEmptyCollections BOOL; + DECLARE vUserFk INT; + + SET vUserFk = account.myUser_getId(); + + SELECT (COUNT(sc.id) > 0) INTO hasEmptyCollections + FROM vn.sectorCollection sc + LEFT JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id + WHERE ISNULL(scsg.id) + AND sc.userFk = vUserFk + AND sc.sectorFk = vSectorFk + AND sc.created >= util.VN_CURDATE(); + + IF NOT hasEmptyCollections THEN + INSERT INTO vn.sectorCollection(userFk, sectorFk) + VALUES(vUserFk, vSectorFk); + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -69577,41 +70298,43 @@ proc: BEGIN CALL util.throw('parkingNotExist'); LEAVE proc; END IF; + + IF vParam REGEXP '^[0-9]+$' THEN + -- Se comprueba si es una preparación previa + SELECT COUNT(*) INTO vIsSaleGroup + FROM vn.saleGroup sg + WHERE sg.id = vParam; - -- Se comprueba si es una preparación previa - SELECT COUNT(*) INTO vIsSaleGroup - FROM vn.saleGroup sg - WHERE sg.id = vParam; + IF vIsSaleGroup THEN + CALL vn.saleGroup_setParking(vParam, vParkingFk); + LEAVE proc; + END IF; - IF vIsSaleGroup THEN - CALL vn.saleGroup_setParking(vParam, vParkingFk); - LEAVE proc; + -- Se comprueba si es un ticket + SELECT COUNT(*) INTO vIsTicket + FROM vn.ticket t + WHERE t.id = vParam + AND t.shipped >= TIMESTAMPADD(WEEK,-1,util.VN_CURDATE()); + + IF vIsTicket THEN + CALL vn.ticket_setParking(vParam, vParkingFk); + LEAVE proc; + END IF; + + -- Se comprueba si es una coleccion de tickets + SELECT COUNT(*) INTO vIsCollection + FROM vn.collection c + WHERE c.id = vParam + AND c.created >= TIMESTAMPADD(WEEK,-1,util.VN_CURDATE()); + + IF vIsCollection THEN + CALL vn.collection_setParking(vParam, vParkingFk); + LEAVE proc; + END IF; + ELSE + -- Por descarte, se considera una matrícula + CALL vn.shelving_setParking(vParam, vParkingFk); END IF; - - -- Se comprueba si es un ticket - SELECT COUNT(*) INTO vIsTicket - FROM vn.ticket t - WHERE t.id = vParam - AND t.shipped >= TIMESTAMPADD(WEEK,-1,util.VN_CURDATE()); - - IF vIsTicket THEN - CALL vn.ticket_setParking(vParam, vParkingFk); - LEAVE proc; - END IF; - - -- Se comprueba si es una coleccion de tickets - SELECT COUNT(*) INTO vIsCollection - FROM vn.collection c - WHERE c.id = vParam - AND c.created >= TIMESTAMPADD(WEEK,-1,util.VN_CURDATE()); - - IF vIsCollection THEN - CALL vn.collection_setParking(vParam, vParkingFk); - LEAVE proc; - END IF; - - -- Por descarte, se considera una matrícula - CALL vn.shelving_setParking(vParam, vParkingFk); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -72571,14 +73294,14 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `ticket_Clone` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb3 */ ; -/*!50003 SET character_set_results = utf8mb3 */ ; -/*!50003 SET collation_connection = utf8mb3_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_Clone`(vOriginalTicket INT, OUT vNewTicket INT) BEGIN @@ -72590,6 +73313,11 @@ BEGIN */ DECLARE vStateFk INT; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + RESIGNAL; + END; + INSERT INTO ticket ( clientFk, shipped, @@ -72722,7 +73450,10 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_cloneWeekly`(vDateFrom DATE, vDateTo DATE) +CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_cloneWeekly`( + vDateFrom DATE, + vDateTo DATE +) BEGIN DECLARE vIsDone BOOL; DECLARE vLanding DATE; @@ -72762,9 +73493,16 @@ BEGIN DECLARE vIsDuplicateMail BOOL; DECLARE vSubject VARCHAR(150); DECLARE vMessage TEXT; - + SET vIsDone = FALSE; - FETCH rsTicket INTO vTicketFk,vClientFk, vWarehouseFk, vCompanyFk, vAddressFk, vAgencyModeFk,vShipment; + FETCH rsTicket INTO + vTicketFk, + vClientFk, + vWarehouseFk, + vCompanyFk, + vAddressFk, + vAgencyModeFk, + vShipment; IF vIsDone THEN LEAVE myLoop; @@ -72790,7 +73528,7 @@ BEGIN AND isDefaultAddress; END IF; - CALL zone_getLanded(vShipment, vAddressFk, vAgencyModeFk, vWarehouseFk,FALSE); + CALL zone_getLanded(vShipment, vAddressFk, vAgencyModeFk, vWarehouseFk, FALSE); SET vLanding = NULL; SELECT landed INTO vLanding FROM tmp.zoneGetLanded LIMIT 1; @@ -72811,16 +73549,22 @@ BEGIN SET clonedFrom = vTicketFk WHERE id = vNewTicket; - INSERT INTO sale (ticketFk, itemFk, concept, quantity, price, - discount, priceFixed, isPriceFixed) + INSERT INTO sale (ticketFk, + itemFk, + concept, + quantity, + price, + discount, + priceFixed, + isPriceFixed) SELECT vNewTicket, - saleOrig.itemFk, - saleOrig.concept, - saleOrig.quantity, - saleOrig.price, - saleOrig.discount, - saleOrig.priceFixed, - saleOrig.isPriceFixed + saleOrig.itemFk, + saleOrig.concept, + saleOrig.quantity, + saleOrig.price, + saleOrig.discount, + saleOrig.priceFixed, + saleOrig.isPriceFixed FROM sale saleOrig WHERE saleOrig.ticketFk = vTicketFk; @@ -72846,20 +73590,20 @@ BEGIN ,attenderFk, ticketFk) SELECT description, - ordered, - shipped, - quantity, - price, - itemFk, - clientFk, - response, - total, - buyed, - requesterFk, - attenderFk, - vNewTicket + ordered, + shipped, + quantity, + price, + itemFk, + clientFk, + response, + total, + buyed, + requesterFk, + attenderFk, + vNewTicket FROM ticketRequest - WHERE ticketFk =vTicketFk; + WHERE ticketFk =vTicketFk; SELECT id INTO vSalesPersonFK FROM observationType @@ -72912,7 +73656,7 @@ BEGIN IF NOT vIsDuplicateMail THEN CALL mail_insert(vSalesPersonEmail, NULL, vSubject, vMessage); END IF; - CALL ticketStateUpdate (vNewTicket, 'FIXING'); + CALL ticket_setState(vNewTicket, 'FIXING'); ELSE CALL ticketCalculateClon(vNewTicket, vTicketFk); END IF; @@ -73366,60 +74110,62 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_DelayTruckSplit`(vTicketFk INT) -BEGIN -/** - * Splita las lineas de ticket que no estan ubicadas - * - * @param vTicketFk Id ticket - */ - DECLARE vNewTicketFk INT; - DECLARE vTotalLines INT; - DECLARE vLinesToSplit INT; - - DROP TEMPORARY TABLE IF EXISTS tmp.SalesToSplit; - - SELECT COUNT(*) INTO vTotalLines - FROM sale - WHERE ticketFk = vTicketFk; - - CREATE TEMPORARY TABLE tmp.SalesToSplit - SELECT s.id saleFk - FROM ticket t - JOIN sale s ON t.id = s.ticketFk - LEFT JOIN ( - SELECT ish.itemFk itemFk, - SUM(ish.visible) visible, - s.warehouseFk warehouseFk - FROM itemShelving ish - JOIN shelving sh ON sh.code = ish.shelvingFk - JOIN parking p ON p.id = sh.parkingFk - JOIN sector s ON s.id = p.sectorFk - GROUP BY ish.itemFk, - s.warehouseFk - ) issw ON issw.itemFk = s.itemFk - AND issw.warehouseFk = t.warehouseFk - WHERE s.quantity > IFNULL(issw.visible, 0) - AND s.quantity > 0 - AND NOT s.isPicked - AND NOT s.reserved - AND t.id = vTicketFk; - - SELECT COUNT(*) INTO vLinesToSplit - FROM tmp.SalesToSplit; - - IF vLinesToSplit = vTotalLines AND vLinesToSplit > 0 THEN - SET vNewTicketFk = vTicketFk; - ELSE - CALL ticket_Clone(vTicketFk, vNewTicketFk); - UPDATE sale s - JOIN tmp.SalesToSplit sts ON sts.saleFk = s.id - SET s.ticketFk = vNewTicketFk; - END IF; - - CALL ticketStateUpdate(vNewTicketFk, 'FIXING'); - - DROP TEMPORARY TABLE tmp.SalesToSplit; +CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_DelayTruckSplit`( + vTicketFk INT +) +BEGIN +/** + * Splita las lineas de ticket que no estan ubicadas + * + * @param vTicketFk Id ticket + */ + DECLARE vNewTicketFk INT; + DECLARE vTotalLines INT; + DECLARE vLinesToSplit INT; + + DROP TEMPORARY TABLE IF EXISTS tmp.SalesToSplit; + + SELECT COUNT(*) INTO vTotalLines + FROM sale + WHERE ticketFk = vTicketFk; + + CREATE TEMPORARY TABLE tmp.SalesToSplit + SELECT s.id saleFk + FROM ticket t + JOIN sale s ON t.id = s.ticketFk + LEFT JOIN ( + SELECT ish.itemFk itemFk, + SUM(ish.visible) visible, + s.warehouseFk warehouseFk + FROM itemShelving ish + JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN parking p ON p.id = sh.parkingFk + JOIN sector s ON s.id = p.sectorFk + GROUP BY ish.itemFk, + s.warehouseFk + ) issw ON issw.itemFk = s.itemFk + AND issw.warehouseFk = t.warehouseFk + WHERE s.quantity > IFNULL(issw.visible, 0) + AND s.quantity > 0 + AND NOT s.isPicked + AND NOT s.reserved + AND t.id = vTicketFk; + + SELECT COUNT(*) INTO vLinesToSplit + FROM tmp.SalesToSplit; + + IF vLinesToSplit = vTotalLines AND vLinesToSplit > 0 THEN + SET vNewTicketFk = vTicketFk; + ELSE + CALL ticket_Clone(vTicketFk, vNewTicketFk); + UPDATE sale s + JOIN tmp.SalesToSplit sts ON sts.saleFk = s.id + SET s.ticketFk = vNewTicketFk; + END IF; + + CALL ticket_setState(vNewTicketFk, 'FIXING'); + + DROP TEMPORARY TABLE tmp.SalesToSplit; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -73437,84 +74183,84 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_doCmr`(vSelf INT) -BEGIN -/** -* Crea u actualiza la información del CMR asociado con -* un ticket específico en caso de que sea necesario. -* -* @param vSelf El id del ticket -*/ - DECLARE vCmrFk INT; - SELECT cmrFk INTO vCmrFk - FROM ticket - WHERE id = vSelf; - - CREATE OR REPLACE TEMPORARY TABLE tTicket - SELECT wo.firstName, - v.numberPlate, - com.id companyFk, - a.id addressFk, - c2.defaultAddressFk, - IFNULL(sat.supplierFk, su.id) supplierFk, - t.landed - FROM ticket t - JOIN ticketState ts ON ts.ticketFk = t.id - JOIN `state` s ON s.id = ts.stateFk - JOIN alertLevel al ON al.id = s.alertLevel - JOIN client c ON c.id = t.clientFk - JOIN `address` a ON a.id = t.addressFk - JOIN province p ON p.id = a.provinceFk - JOIN country co ON co.id = p.countryFk - JOIN warehouse w ON w.id = t.warehouseFk - JOIN company com ON com.id = t.companyFk - JOIN client c2 ON c2.id = com.clientFk - JOIN supplierAccount sa ON sa.id = com.supplierAccountFk - JOIN supplier su ON su.id = sa.supplierFk - LEFT JOIN route r ON r.id = t.routeFk - LEFT JOIN worker wo ON wo.id = r.workerFk - LEFT JOIN vehicle v ON v.id = r.vehicleFk - LEFT JOIN agencyMode am ON am.id = r.agencyModeFk - LEFT JOIN agency ag ON ag.id = am.agencyFk - LEFT JOIN supplierAgencyTerm sat ON sat.agencyFk = ag.id - AND wo.isFreelance - WHERE al.code IN ('PACKED', 'DELIVERED') - AND co.code <> 'ES' - AND am.name <> 'ABONO' - AND w.code = 'ALG' - AND t.id = vSelf - GROUP BY t.id; - - IF vCmrFk THEN - UPDATE cmr c - JOIN tTicket t - SET c.senderInstruccions = t.firstName, - c.truckPlate = t.numberPlate, - c.companyFk = t.companyFk, - c.addressToFk = t.addressFk, - c.addressFromFk = t.defaultAddressFk, - c.supplierFk = t.supplierFk, - c.ead = t.landed - WHERE id = vCmrFk; - ELSE - INSERT INTO cmr ( - senderInstruccions, - truckPlate, - companyFk, - addressToFk, - addressFromFk, - supplierFk, - ead - ) - SELECT * FROM tTicket; - - IF (SELECT EXISTS(SELECT * FROM tTicket)) THEN - UPDATE ticket - SET cmrFk = LAST_INSERT_ID() - WHERE id = vSelf; - END IF; - END IF; - - DROP TEMPORARY TABLE tTicket; +BEGIN +/** +* Crea u actualiza la información del CMR asociado con +* un ticket específico en caso de que sea necesario. +* +* @param vSelf El id del ticket +*/ + DECLARE vCmrFk INT; + SELECT cmrFk INTO vCmrFk + FROM ticket + WHERE id = vSelf; + + CREATE OR REPLACE TEMPORARY TABLE tTicket + SELECT wo.firstName, + v.numberPlate, + com.id companyFk, + a.id addressFk, + c2.defaultAddressFk, + IFNULL(sat.supplierFk, su.id) supplierFk, + t.landed + FROM ticket t + JOIN ticketState ts ON ts.ticketFk = t.id + JOIN `state` s ON s.id = ts.stateFk + JOIN alertLevel al ON al.id = s.alertLevel + JOIN client c ON c.id = t.clientFk + JOIN `address` a ON a.id = t.addressFk + JOIN province p ON p.id = a.provinceFk + JOIN country co ON co.id = p.countryFk + JOIN warehouse w ON w.id = t.warehouseFk + JOIN company com ON com.id = t.companyFk + JOIN client c2 ON c2.id = com.clientFk + JOIN supplierAccount sa ON sa.id = com.supplierAccountFk + JOIN supplier su ON su.id = sa.supplierFk + LEFT JOIN route r ON r.id = t.routeFk + LEFT JOIN worker wo ON wo.id = r.workerFk + LEFT JOIN vehicle v ON v.id = r.vehicleFk + LEFT JOIN agencyMode am ON am.id = r.agencyModeFk + LEFT JOIN agency ag ON ag.id = am.agencyFk + LEFT JOIN supplierAgencyTerm sat ON sat.agencyFk = ag.id + AND wo.isFreelance + WHERE al.code IN ('PACKED', 'DELIVERED') + AND co.code <> 'ES' + AND am.name <> 'ABONO' + AND w.code = 'ALG' + AND t.id = vSelf + GROUP BY t.id; + + IF vCmrFk THEN + UPDATE cmr c + JOIN tTicket t + SET c.senderInstruccions = t.firstName, + c.truckPlate = t.numberPlate, + c.companyFk = t.companyFk, + c.addressToFk = t.addressFk, + c.addressFromFk = t.defaultAddressFk, + c.supplierFk = t.supplierFk, + c.ead = t.landed + WHERE id = vCmrFk; + ELSE + INSERT INTO cmr ( + senderInstruccions, + truckPlate, + companyFk, + addressToFk, + addressFromFk, + supplierFk, + ead + ) + SELECT * FROM tTicket; + + IF (SELECT EXISTS(SELECT * FROM tTicket)) THEN + UPDATE ticket + SET cmrFk = LAST_INSERT_ID() + WHERE id = vSelf; + END IF; + END IF; + + DROP TEMPORARY TABLE tTicket; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -75115,7 +75861,11 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_split`(vTicketFk INT, vTicketFutureFk INT, vDated DATE) +CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_split`( + vTicketFk INT, + vTicketFutureFk INT, + vDated DATE +) proc:BEGIN /** * Mueve las lineas con problemas a otro ticket existente o a uno nuevo. @@ -75133,61 +75883,57 @@ proc:BEGIN FROM tmp.salesToSplit WHERE ticketFk = vTicketFk; - SELECT count(*) INTO vTotalLines - FROM vn.sale s + SELECT COUNT(*) INTO vTotalLines + FROM sale s WHERE s.ticketFk = vTicketFk; SET vHasFullProblem = (vTotalLines = vProblemLines); -- Ticket completo IF vHasFullProblem THEN - - UPDATE vn.ticket - SET landed = vDated + INTERVAL 1 DAY, + UPDATE ticket + SET landed = vDated + INTERVAL 1 DAY, shipped = vDated, - nickname = CONCAT('(',DAY(util.VN_CURDATE()),') ', nickname ) + nickname = CONCAT('(',DAY(util.VN_CURDATE()),') ', nickname) WHERE id = vTicketFk; - SELECT "moved" message, NULL ticketFuture; + SELECT 'moved' message, NULL ticketFuture; LEAVE proc; - END IF; -- Ticket a futuro existe IF vTicketFutureFk THEN - - UPDATE vn.sale s - JOIN tmp.salesToSplit ss ON s.id = ss.saleFk + UPDATE sale s + JOIN tmp.salesToSplit ss ON s.id = ss.saleFk SET s.ticketFk = vTicketFutureFk, s.concept = CONCAT('(s) ', s.concept) WHERE ss.ticketFk = vTicketFk; - SELECT "future" message, NULL ticketFuture; + SELECT 'future' message, NULL ticketFuture; LEAVE proc; - END IF; -- Ticket nuevo - CALL vn.ticket_Clone(vTicketFk, vTicketFutureFk); + CALL ticket_Clone(vTicketFk, vTicketFutureFk); - UPDATE vn.ticket t - JOIN vn.productionConfig pc + UPDATE ticket t + JOIN productionConfig pc SET t.routeFk = IF(t.shipped = vDated , t.routeFk, NULL), - t.landed = vDated + INTERVAL 1 DAY, + t.landed = vDated + INTERVAL 1 DAY, t.shipped = vDated, t.agencyModeFk = pc.defautlAgencyMode, t.zoneFk = pc.defaultZone WHERE t.id = vTicketFutureFk; - - UPDATE vn.sale s - JOIN tmp.salesToSplit sts ON sts.saleFk = s.id + + UPDATE sale s + JOIN tmp.salesToSplit sts ON sts.saleFk = s.id SET s.ticketFk = vTicketFutureFk, s.concept = CONCAT('(s) ', s.concept) WHERE sts.ticketFk = vTicketFk; - CALL vn.ticketStateUpdate(vTicketFutureFk, 'FIXING'); + CALL ticket_setState(vTicketFutureFk, 'FIXING'); - SELECT "new" message,vTicketFutureFk ticketFuture; + SELECT 'new' message, vTicketFutureFk ticketFuture; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -75204,8 +75950,11 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_splitItemPackingType`(vTicketFk INT, vOriginalItemPackingTypeFk VARCHAR(1)) -proc:BEGIN +CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_splitItemPackingType`( + vTicketFk INT, + vOriginalItemPackingTypeFk VARCHAR(1) +) +BEGIN /** * Clona y reparte las ventas de un ticket en funcion del tipo de empaquetado. * Respeta el id inicial para el tipo propuesto. @@ -75227,22 +75976,27 @@ proc:BEGIN DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + RESIGNAL; + END; + DELETE FROM vn.sale WHERE quantity = 0 AND ticketFk = vTicketFk; - DROP TEMPORARY TABLE IF EXISTS tmp.sale; - CREATE TEMPORARY TABLE tmp.sale + CREATE OR REPLACE TEMPORARY TABLE tmp.sale (PRIMARY KEY (id)) + ENGINE = MEMORY SELECT s.id, i.itemPackingTypeFk , IFNULL(sv.litros, 0) litros FROM vn.sale s JOIN vn.item i ON i.id = s.itemFk LEFT JOIN vn.saleVolume sv ON sv.saleFk = s.id WHERE s.ticketFk = vTicketFk; - DROP TEMPORARY TABLE IF EXISTS tmp.saleGroup; - CREATE TEMPORARY TABLE tmp.saleGroup - SELECT itemPackingTypeFk , sum(litros) AS totalLitros + CREATE OR REPLACE TEMPORARY TABLE tmp.saleGroup + ENGINE = MEMORY + SELECT itemPackingTypeFk, SUM(litros) totalLitros FROM tmp.sale GROUP BY itemPackingTypeFk; @@ -75250,10 +76004,10 @@ proc:BEGIN FROM tmp.saleGroup WHERE itemPackingTypeFk IS NOT NULL; - DROP TEMPORARY TABLE IF EXISTS tmp.ticketIPT; - CREATE TEMPORARY TABLE tmp.ticketIPT - (ticketFk INT, - itemPackingTypeFk VARCHAR(1)); + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketIPT ( + ticketFk INT, + itemPackingTypeFk VARCHAR(1) + ) ENGINE = MEMORY; CASE vPackingTypesToSplit WHEN 0 THEN @@ -75294,7 +76048,7 @@ proc:BEGIN SELECT itemPackingTypeFk INTO vItemPackingTypeFk FROM tmp.saleGroup sg - WHERE NOT ISNULL(sg.itemPackingTypeFk) + WHERE sg.itemPackingTypeFk IS NOT NULL ORDER BY sg.itemPackingTypeFk LIMIT 1; @@ -75305,8 +76059,9 @@ proc:BEGIN WHERE ts.itemPackingTypeFk IS NULL; END CASE; - DROP TEMPORARY TABLE tmp.sale; - DROP TEMPORARY TABLE tmp.saleGroup; + DROP TEMPORARY TABLE + tmp.sale, + tmp.saleGroup; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -80930,126 +81685,126 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getLeaves`( - vSelf INT, - vParentFk INT, - vSearch VARCHAR(255), - vHasInsert BOOL +CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getLeaves`( + vSelf INT, + vParentFk INT, + vSearch VARCHAR(255), + vHasInsert BOOL ) -BEGIN -/** - * Devuelve las ubicaciones incluidas en la ruta y que sean hijos de parentFk. - * @param vSelf Id de la zona - * @param vParentFk Id del geo a calcular - * @param vSearch Cadena a buscar - * @param vHasInsert Indica si inserta en tmp.zoneNodes - * Optional @table tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) - */ - DECLARE vIsNumber BOOL; - DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch <> ''; - - CREATE OR REPLACE TEMPORARY TABLE tNodes - (UNIQUE (id)) - ENGINE = MEMORY - SELECT id - FROM zoneGeo - LIMIT 0; - - IF vIsSearch THEN - SET vIsNumber = vSearch REGEXP '^[0-9]+$'; - - INSERT INTO tNodes - SELECT id - FROM zoneGeo - WHERE (vIsNumber AND `name` = vSearch) - OR (!vIsNumber AND `name` LIKE CONCAT('%', vSearch, '%')) - LIMIT 1000; - - ELSEIF vParentFk IS NULL THEN - INSERT INTO tNodes - SELECT geoFk - FROM zoneIncluded - WHERE zoneFk = vSelf; - END IF; - - IF vParentFk IS NULL THEN - CREATE OR REPLACE TEMPORARY TABLE tChilds - (INDEX(id)) - ENGINE = MEMORY - SELECT id FROM tNodes; - - CREATE OR REPLACE TEMPORARY TABLE tParents - (INDEX(id)) - ENGINE = MEMORY - SELECT id FROM zoneGeo LIMIT 0; - - myLoop: LOOP - DELETE FROM tParents; - INSERT INTO tParents - SELECT parentFk id - FROM zoneGeo g - JOIN tChilds c ON c.id = g.id - WHERE g.parentFk IS NOT NULL; - - INSERT IGNORE INTO tNodes - SELECT id FROM tParents; - - IF NOT ROW_COUNT() THEN - LEAVE myLoop; - END IF; - - DELETE FROM tChilds; - INSERT INTO tChilds - SELECT id FROM tParents; - END LOOP; - - DROP TEMPORARY TABLE tChilds, tParents; - END IF; - - IF NOT vIsSearch THEN - INSERT IGNORE INTO tNodes - SELECT id - FROM zoneGeo - WHERE parentFk <=> vParentFk; - END IF; - - CREATE OR REPLACE TEMPORARY TABLE tZones - SELECT g.id, - g.name, - g.parentFk, - g.sons, - NOT g.sons OR `type` = 'country' isChecked, - i.isIncluded selected, - g.`depth`, - vSelf - FROM zoneGeo g - JOIN tNodes n ON n.id = g.id - LEFT JOIN zoneIncluded i ON i.geoFk = g.id - AND i.zoneFk = vSelf - ORDER BY g.`depth`, selected DESC, g.name; - - IF vHasInsert THEN - INSERT IGNORE INTO tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) - SELECT id, - name, - parentFk, - sons, - isChecked, - vSelf - FROM tZones - WHERE selected - OR (selected IS NULL AND vParentFk IS NOT NULL); - ELSE - SELECT id, - name, - parentFk, - sons, - selected - FROM tZones - ORDER BY `depth`, selected DESC, name; - END IF; - - DROP TEMPORARY TABLE tNodes, tZones; +BEGIN +/** + * Devuelve las ubicaciones incluidas en la ruta y que sean hijos de parentFk. + * @param vSelf Id de la zona + * @param vParentFk Id del geo a calcular + * @param vSearch Cadena a buscar + * @param vHasInsert Indica si inserta en tmp.zoneNodes + * Optional @table tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) + */ + DECLARE vIsNumber BOOL; + DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch <> ''; + + CREATE OR REPLACE TEMPORARY TABLE tNodes + (UNIQUE (id)) + ENGINE = MEMORY + SELECT id + FROM zoneGeo + LIMIT 0; + + IF vIsSearch THEN + SET vIsNumber = vSearch REGEXP '^[0-9]+$'; + + INSERT INTO tNodes + SELECT id + FROM zoneGeo + WHERE (vIsNumber AND `name` = vSearch) + OR (!vIsNumber AND `name` LIKE CONCAT('%', vSearch, '%')) + LIMIT 1000; + + ELSEIF vParentFk IS NULL THEN + INSERT INTO tNodes + SELECT geoFk + FROM zoneIncluded + WHERE zoneFk = vSelf; + END IF; + + IF vParentFk IS NULL THEN + CREATE OR REPLACE TEMPORARY TABLE tChilds + (INDEX(id)) + ENGINE = MEMORY + SELECT id FROM tNodes; + + CREATE OR REPLACE TEMPORARY TABLE tParents + (INDEX(id)) + ENGINE = MEMORY + SELECT id FROM zoneGeo LIMIT 0; + + myLoop: LOOP + DELETE FROM tParents; + INSERT INTO tParents + SELECT parentFk id + FROM zoneGeo g + JOIN tChilds c ON c.id = g.id + WHERE g.parentFk IS NOT NULL; + + INSERT IGNORE INTO tNodes + SELECT id FROM tParents; + + IF NOT ROW_COUNT() THEN + LEAVE myLoop; + END IF; + + DELETE FROM tChilds; + INSERT INTO tChilds + SELECT id FROM tParents; + END LOOP; + + DROP TEMPORARY TABLE tChilds, tParents; + END IF; + + IF NOT vIsSearch THEN + INSERT IGNORE INTO tNodes + SELECT id + FROM zoneGeo + WHERE parentFk <=> vParentFk; + END IF; + + CREATE OR REPLACE TEMPORARY TABLE tZones + SELECT g.id, + g.name, + g.parentFk, + g.sons, + NOT g.sons OR `type` = 'country' isChecked, + i.isIncluded selected, + g.`depth`, + vSelf + FROM zoneGeo g + JOIN tNodes n ON n.id = g.id + LEFT JOIN zoneIncluded i ON i.geoFk = g.id + AND i.zoneFk = vSelf + ORDER BY g.`depth`, selected DESC, g.name; + + IF vHasInsert THEN + INSERT IGNORE INTO tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) + SELECT id, + name, + parentFk, + sons, + isChecked, + vSelf + FROM tZones + WHERE selected + OR (selected IS NULL AND vParentFk IS NOT NULL); + ELSE + SELECT id, + name, + parentFk, + sons, + selected + FROM tZones + ORDER BY `depth`, selected DESC, name; + END IF; + + DROP TEMPORARY TABLE tNodes, tZones; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -81232,48 +81987,48 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getPostalCode`(vSelf INT) -BEGIN -/** - * Devuelve los códigos postales incluidos en una zona - */ - DECLARE vGeoFk INT DEFAULT NULL; - - CREATE OR REPLACE TEMPORARY TABLE tmp.zoneNodes ( - geoFk INT, - name VARCHAR(100), - parentFk INT, - sons INT, - isChecked BOOL DEFAULT 0, - zoneFk INT, - PRIMARY KEY zoneNodesPk (zoneFk, geoFk), - INDEX(geoFk)) - ENGINE = MEMORY; - - CALL zone_getLeaves(vSelf, NULL , NULL, TRUE); - - UPDATE tmp.zoneNodes - SET isChecked = 0 - WHERE parentFk IS NULL; - - myLoop: LOOP - SET vGeoFk = NULL; - SELECT geoFk INTO vGeoFk - FROM tmp.zoneNodes - WHERE NOT isChecked - LIMIT 1; - - CALL zone_getLeaves(vSelf, vGeoFk, NULL, TRUE); - UPDATE tmp.zoneNodes - SET isChecked = TRUE - WHERE geoFk = vGeoFk; - - IF vGeoFk IS NULL THEN - LEAVE myLoop; - END IF; - END LOOP; - - DELETE FROM tmp.zoneNodes - WHERE sons > 0; +BEGIN +/** + * Devuelve los códigos postales incluidos en una zona + */ + DECLARE vGeoFk INT DEFAULT NULL; + + CREATE OR REPLACE TEMPORARY TABLE tmp.zoneNodes ( + geoFk INT, + name VARCHAR(100), + parentFk INT, + sons INT, + isChecked BOOL DEFAULT 0, + zoneFk INT, + PRIMARY KEY zoneNodesPk (zoneFk, geoFk), + INDEX(geoFk)) + ENGINE = MEMORY; + + CALL zone_getLeaves(vSelf, NULL , NULL, TRUE); + + UPDATE tmp.zoneNodes + SET isChecked = 0 + WHERE parentFk IS NULL; + + myLoop: LOOP + SET vGeoFk = NULL; + SELECT geoFk INTO vGeoFk + FROM tmp.zoneNodes + WHERE NOT isChecked + LIMIT 1; + + CALL zone_getLeaves(vSelf, vGeoFk, NULL, TRUE); + UPDATE tmp.zoneNodes + SET isChecked = TRUE + WHERE geoFk = vGeoFk; + + IF vGeoFk IS NULL THEN + LEAVE myLoop; + END IF; + END LOOP; + + DELETE FROM tmp.zoneNodes + WHERE sons > 0; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -89804,4 +90559,4 @@ USE `vn2008`; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2024-06-25 7:26:45 +-- Dump completed on 2024-07-09 5:48:04 diff --git a/db/dump/.dump/triggers.sql b/db/dump/.dump/triggers.sql index 90ff6b30d..41525b2eb 100644 --- a/db/dump/.dump/triggers.sql +++ b/db/dump/.dump/triggers.sql @@ -3616,6 +3616,46 @@ 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`.`clientUnpaid_beforeInsert` + BEFORE INSERT ON `clientUnpaid` + FOR EACH ROW +BEGIN + SET NEW.editorFk = account.myUser_getId(); +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`clientUnpaid_beforeUpdate` + BEFORE UPDATE ON `clientUnpaid` + FOR EACH ROW +BEGIN + SET NEW.editorFk = account.myUser_getId(); +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`cmr_beforeDelete` BEFORE DELETE ON `cmr` FOR EACH ROW @@ -4671,11 +4711,9 @@ BEGIN IF NEW.isBooked = OLD.isBooked AND ( NOT (NEW.supplierFk <=> OLD.supplierFk) OR NOT (NEW.dated <=> OLD.dated) OR - NOT (NEW.invoiceNumber <=> OLD.invoiceNumber) OR NOT (NEW.travelFk <=> OLD.travelFk) OR NOT (NEW.companyFk <=> OLD.companyFk) OR NOT (NEW.invoiceInFk <=> OLD.invoiceInFk) OR - NOT (NEW.invoiceAmount <=> OLD.invoiceAmount) OR NOT (NEW.typeFk <=> OLD.typeFk) ) THEN @@ -6144,6 +6182,7 @@ DELIMITER ;; BEGIN SET NEW.editorFk = account.myUser_getId(); SET NEW.userFk = account.myUser_getId(); + SET NEW.available = NEW.visible; END */;; DELIMITER ; @@ -6160,48 +6199,20 @@ 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`.`itemShelving_afterInsert` - AFTER INSERT ON `itemShelving` - FOR EACH ROW -INSERT INTO vn.itemShelvingLog( itemShelvingFk, - workerFk, - accion, - itemFk, - shelvingFk, - visible, - `grouping`, - packing) - VALUES( NEW.id, - NEW.userFk, - 'CREA REGISTRO', - NEW.itemFk, - NEW.shelvingFk, - NEW.visible, - NEW.`grouping`, - NEW.packing - ) */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemShelving_beforeUpdate` BEFORE UPDATE ON `itemShelving` FOR EACH ROW BEGIN + SET NEW.editorFk = account.myUser_getId(); IF NEW.userFk IS NULL THEN SET NEW.userFk = account.myUser_getId(); END IF; + + IF (NEW.visible <> OLD.visible) THEN + SET NEW.available = GREATEST(NEW.available + NEW.visible - OLD.visible, 0); + END IF; + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -6220,7 +6231,8 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemShelving_afterUpdate` AFTER UPDATE ON `itemShelving` FOR EACH ROW -INSERT INTO itemShelvingLog +BEGIN + INSERT INTO itemShelvingLog SET itemShelvingFk = NEW.id, workerFk = account.myUser_getId(), accion = 'CAMBIO', @@ -6228,7 +6240,10 @@ INSERT INTO itemShelvingLog shelvingFk = NEW.shelvingFk, visible = NEW.visible, `grouping` = NEW.`grouping`, - packing = NEW.packing */;; + packing = NEW.packing, + available = NEW.available; + +END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; /*!50003 SET character_set_client = @saved_cs_client */ ; @@ -6297,12 +6312,12 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemShelvingSale_afterInsert` AFTER INSERT ON `itemShelvingSale` FOR EACH ROW -BEGIN - - UPDATE vn.sale - SET isPicked = TRUE - WHERE id = NEW.saleFk; - +BEGIN + + UPDATE sale s + JOIN operator o ON o.workerFk = account.myUser_getId() + SET s.isPicked = IF(o.isOnReservationMode, s.isPicked, TRUE) + WHERE id = NEW.saleFk; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -10924,4 +10939,4 @@ USE `vn2008`; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2024-06-25 7:27:06 +-- Dump completed on 2024-07-09 5:48:24 From 3f0335cf37e4fe4a9f83d50c51683e269e9ec5f5 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 9 Jul 2024 08:37:36 +0200 Subject: [PATCH 080/170] feat: refs #7644 Added with recursive buy-label --- print/templates/reports/buy-label/buy-label.js | 2 +- print/templates/reports/buy-label/sql/buys.sql | 17 +++++++++++++++-- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/print/templates/reports/buy-label/buy-label.js b/print/templates/reports/buy-label/buy-label.js index b6e0a5031..7d626c052 100755 --- a/print/templates/reports/buy-label/buy-label.js +++ b/print/templates/reports/buy-label/buy-label.js @@ -7,7 +7,7 @@ module.exports = { name: 'buy-label', mixins: [vnReport], async serverPrefetch() { - this.buys = await this.rawSqlFromDef('buys', [this.id]); + this.buys = await this.rawSqlFromDef('buys', [this.id, this.id]); this.maxLabelNum = Math.max(...this.buys.map(buy => buy.labelNum)); const date = new Date(); this.weekNum = moment(date).isoWeek(); diff --git a/print/templates/reports/buy-label/sql/buys.sql b/print/templates/reports/buy-label/sql/buys.sql index 41fd3556b..e05ca2a66 100644 --- a/print/templates/reports/buy-label/sql/buys.sql +++ b/print/templates/reports/buy-label/sql/buys.sql @@ -1,4 +1,15 @@ -SELECT ROW_NUMBER() OVER(ORDER BY b.id) labelNum, +WITH RECURSIVE numbers AS ( + SELECT 1 n + UNION ALL + SELECT n + 1 + FROM numbers + WHERE n < ( + SELECT MAX(stickers) + FROM buy + WHERE entryFk = ? + ) +) +SELECT ROW_NUMBER() OVER(ORDER BY b.id, num.n) labelNum, i.name, i.`size`, i.category, @@ -15,4 +26,6 @@ SELECT ROW_NUMBER() OVER(ORDER BY b.id) labelNum, LEFT JOIN producer p ON p.id = i.producerFk LEFT JOIN ink ON ink.id = i.inkFk LEFT JOIN origin o ON o.id = i.originFk - WHERE b.entryFk = ? \ No newline at end of file + JOIN numbers num + WHERE b.entryFk = ? + AND num.n <= b.stickers \ No newline at end of file From 6430fb5b5178b1ce2046250d51d0d9a025cb0e30 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 9 Jul 2024 08:43:02 +0200 Subject: [PATCH 081/170] refactor: refs #7662 Requested changes --- db/routines/vn/procedures/ticket_splitItemPackingType.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/routines/vn/procedures/ticket_splitItemPackingType.sql b/db/routines/vn/procedures/ticket_splitItemPackingType.sql index 87fbafe13..db2d1e4c1 100644 --- a/db/routines/vn/procedures/ticket_splitItemPackingType.sql +++ b/db/routines/vn/procedures/ticket_splitItemPackingType.sql @@ -10,6 +10,7 @@ BEGIN * * @param vSelf Id ticket * @param vItemPackingTypeFk Tipo para el que se reserva el número de ticket original + * @return table tmp.ticketIPT(ticketFk, itemPackingTypeFk) */ DECLARE vItemPackingTypeFk VARCHAR(1) DEFAULT 'H'; DECLARE vNewTicketFk INT; @@ -101,7 +102,6 @@ BEGIN FROM sale s JOIN tSale ts ON ts.id = s.id JOIN tmp.ticketIPT t ON t.itemPackingTypeFk = ts.itemPackingTypeFk - WHERE s.ticketFk = vSelf FOR UPDATE; UPDATE sale s From 7279feab12f6050cd4aa4840c370082db48304c6 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 9 Jul 2024 09:33:31 +0200 Subject: [PATCH 082/170] feat: refs #7505 Changes --- .../cache/procedures/visible_refresh.sql | 2 +- .../vn/procedures/item_calcVisible.sql | 22 +++++++++---------- .../vn/procedures/multipleInventory.sql | 19 ++++++++-------- 3 files changed, 21 insertions(+), 22 deletions(-) diff --git a/db/routines/cache/procedures/visible_refresh.sql b/db/routines/cache/procedures/visible_refresh.sql index b200e86f2..4feffde8e 100644 --- a/db/routines/cache/procedures/visible_refresh.sql +++ b/db/routines/cache/procedures/visible_refresh.sql @@ -25,7 +25,7 @@ proc: BEGIN WHERE warehouse_id = v_warehouse; -- Calculamos los movimientos confirmados de hoy - CALL vn.item_calcVisible(v_warehouse, util.VN_CURDATE(), NULL); + CALL vn.item_calcVisible(NULL, util.VN_CURDATE(), v_warehouse); DELETE FROM visible WHERE calc_id = v_calc; INSERT INTO visible (calc_id, item_id,visible) diff --git a/db/routines/vn/procedures/item_calcVisible.sql b/db/routines/vn/procedures/item_calcVisible.sql index f7eee661b..728c94276 100644 --- a/db/routines/vn/procedures/item_calcVisible.sql +++ b/db/routines/vn/procedures/item_calcVisible.sql @@ -1,8 +1,8 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_calcVisible`( - vWarehouseFk INT, - vDated INT, - vItemFk INT + vSelf INT, + vDated DATE, + vWarehouseFk INT ) BEGIN /** @@ -10,12 +10,12 @@ BEGIN * * @param vWarehouse Warehouse id * @param vDated Max date to filter - * @param vItemFk Item id + * @param vSelf Item id * @param tmp.itemVisible(item_id, stock, visible) */ DECLARE vTomorrow DATETIME DEFAULT vDated + INTERVAL 1 DAY; - INSERT INTO tmp.itemVisible (item_id, visible) + INSERT INTO tmp.itemVisible(item_id, visible) SELECT itemFk, SUM(quantity) FROM ( SELECT i.itemFk, i.quantity @@ -29,8 +29,8 @@ BEGIN WHERE st.created > vDated AND (s.isPicked OR st.isChecked) ) stPrevious ON `stPrevious`.`saleFk` = i.saleFk - WHERE i.warehouseFk = vWarehouseFk - AND (vItemFk IS NULL OR i.itemFk = vItemFk) + WHERE IFNULL(vWarehouseFk, i.warehouseFk) = i.warehouseFk + AND (vSelf IS NULL OR i.itemFk = vSelf) AND (s.isPicked OR i.reserved OR stPrevious.saleFk) AND i.shipped >= vDated AND i.shipped < vTomorrow UNION ALL @@ -38,8 +38,8 @@ BEGIN FROM itemEntryIn WHERE isReceived AND landed >= vDated AND landed < vTomorrow - AND warehouseInFk = vWarehouseFk - AND (vItemFk IS NULL OR itemFk = vItemFk) + AND IFNULL(vWarehouseFk, warehouseInFk) = warehouseInFk + AND (vSelf IS NULL OR itemFk = vSelf) AND NOT isVirtualStock UNION ALL SELECT itemFk, quantity @@ -47,8 +47,8 @@ BEGIN WHERE isDelivered AND shipped >= vDated AND shipped < vTomorrow - AND warehouseOutFk = vWarehouseFk - AND (vItemFk IS NULL OR itemFk = vItemFk) + AND IFNULL(vWarehouseFk, warehouseOutFk) = warehouseOutFk + AND (vSelf IS NULL OR itemFk = vSelf) ) t GROUP BY itemFk ON DUPLICATE KEY UPDATE diff --git a/db/routines/vn/procedures/multipleInventory.sql b/db/routines/vn/procedures/multipleInventory.sql index dd3bd6f17..3e0cf72c7 100644 --- a/db/routines/vn/procedures/multipleInventory.sql +++ b/db/routines/vn/procedures/multipleInventory.sql @@ -83,19 +83,19 @@ proc: BEGIN ai.sd = iic.quantity; -- Cálculo del visible - CALL cache.visible_refresh(vCalc, FALSE, vWarehouseFk); + CALL cache.stock_refresh(false); - CREATE OR REPLACE TEMPORARY TABLE tItemVisibleCalc + CREATE OR REPLACE TEMPORARY TABLE tmp.itemVisible (PRIMARY KEY (item_id)) ENGINE = MEMORY - SELECT item_id, visible - FROM cache.visible - WHERE calc_id = vCalc; + SELECT item_id, amount stock, amount visible + FROM cache.stock + WHERE warehouse_id = vWarehouseFk; - CALL item_calcVisible(vWarehouseFk, util.VN_CURDATE(), NULL); + CALL item_calcVisible(NULL, vWarehouseFk, util.VN_CURDATE()); UPDATE tmp.itemInventory it - JOIN tItemVisibleCalc ivc ON ivc.item_id = it.id - SET it.visible = it.visible + ivc.visible; + JOIN tmp.itemVisible iv ON iv.item_id = it.id + SET it.visible = it.visible + iv.visible; -- Calculo del disponible CREATE OR REPLACE TEMPORARY TABLE tmp.itemCalc @@ -168,7 +168,6 @@ proc: BEGIN tmp.itemCalc, tmp.itemAtp, tItemInventoryCalc, - tItemVisibleCalc, - tmp.itemAtp; + tmp.itemVisible; END$$ DELIMITER ; From 86acc644fea1069e7f94ec52b76ef7a4bafaa635 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 9 Jul 2024 09:38:07 +0200 Subject: [PATCH 083/170] feat: refs #7505 Changes --- db/routines/vn/procedures/multipleInventory.sql | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/db/routines/vn/procedures/multipleInventory.sql b/db/routines/vn/procedures/multipleInventory.sql index 3e0cf72c7..33eb0b0ed 100644 --- a/db/routines/vn/procedures/multipleInventory.sql +++ b/db/routines/vn/procedures/multipleInventory.sql @@ -83,7 +83,7 @@ proc: BEGIN ai.sd = iic.quantity; -- Cálculo del visible - CALL cache.stock_refresh(false); + CALL cache.stock_refresh(false); CREATE OR REPLACE TEMPORARY TABLE tmp.itemVisible (PRIMARY KEY (item_id)) @@ -92,7 +92,7 @@ proc: BEGIN FROM cache.stock WHERE warehouse_id = vWarehouseFk; - CALL item_calcVisible(NULL, vWarehouseFk, util.VN_CURDATE()); + CALL item_calcVisible(NULL, vWarehouseFk, vDate); UPDATE tmp.itemInventory it JOIN tmp.itemVisible iv ON iv.item_id = it.id SET it.visible = it.visible + iv.visible; From 29f9fa0ce36d6c1b9eab9c220b48d9454451f953 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 9 Jul 2024 09:45:55 +0200 Subject: [PATCH 084/170] feat: refs #7505 Optimization --- .../vn/procedures/multipleInventory.sql | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/db/routines/vn/procedures/multipleInventory.sql b/db/routines/vn/procedures/multipleInventory.sql index 33eb0b0ed..6cd584c6e 100644 --- a/db/routines/vn/procedures/multipleInventory.sql +++ b/db/routines/vn/procedures/multipleInventory.sql @@ -10,7 +10,7 @@ proc: BEGIN DECLARE vDateTo DATETIME; DECLARE vDateToTomorrow DATETIME; DECLARE vDefaultDayRange INT; - DECLARE vCalc INT; + DECLARE vCalcFk INT; IF vDate < util.VN_CURDATE() THEN LEAVE proc; @@ -83,19 +83,18 @@ proc: BEGIN ai.sd = iic.quantity; -- Cálculo del visible - CALL cache.stock_refresh(false); + CALL cache.visible_refresh(vCalcFk, FALSE, vWarehouseFk); - CREATE OR REPLACE TEMPORARY TABLE tmp.itemVisible + CREATE OR REPLACE TEMPORARY TABLE tItemVisibleCalc (PRIMARY KEY (item_id)) ENGINE = MEMORY - SELECT item_id, amount stock, amount visible - FROM cache.stock - WHERE warehouse_id = vWarehouseFk; + SELECT item_id, visible + FROM cache.visible + WHERE calc_id = vCalcFk; - CALL item_calcVisible(NULL, vWarehouseFk, vDate); UPDATE tmp.itemInventory it - JOIN tmp.itemVisible iv ON iv.item_id = it.id - SET it.visible = it.visible + iv.visible; + JOIN tItemVisibleCalc ivc ON ivc.item_id = it.id + SET it.visible = it.visible + ivc.visible; -- Calculo del disponible CREATE OR REPLACE TEMPORARY TABLE tmp.itemCalc @@ -168,6 +167,6 @@ proc: BEGIN tmp.itemCalc, tmp.itemAtp, tItemInventoryCalc, - tmp.itemVisible; + tItemVisibleCalc; END$$ DELIMITER ; From 4dcc8b02a597eb818d79029aa8a3ee6e6cbdc643 Mon Sep 17 00:00:00 2001 From: robert Date: Tue, 9 Jul 2024 10:01:32 +0200 Subject: [PATCH 085/170] feat: refs #7685 delivery coordinates --- .../procedures/address_updateCorordinates.sql | 30 +++++++++++++++++++ .../vn/triggers/delivery_beforeInsert.sql | 12 ++------ .../vn/triggers/delivery_beforeUpdate.sql | 12 ++------ 3 files changed, 34 insertions(+), 20 deletions(-) create mode 100644 db/routines/vn/procedures/address_updateCorordinates.sql diff --git a/db/routines/vn/procedures/address_updateCorordinates.sql b/db/routines/vn/procedures/address_updateCorordinates.sql new file mode 100644 index 000000000..2004cd180 --- /dev/null +++ b/db/routines/vn/procedures/address_updateCorordinates.sql @@ -0,0 +1,30 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`address_updateCorordinates`( + vTicketFk INT, + vLongitude INT, + vLatitude INT) +BEGIN +/** + * Actualiza las coordenadas de una direccion + * + * @param vTicketFk id del ticket + * @param vLongitude longitud de la direccion + * @param vLatitude latitud de la dirrecion + */ + DECLARE vAddressFK INT; + + START TRANSACTION; + + SELECT addressFK INTO vAddressFK + FROM ticket + WHERE id = vTicketFk + FOR UPDATE; + + UPDATE address + SET longitude = vLongitude, + latitude = vLatitude + WHERE id = vAddressFK; + + COMMIT; +END$$ +DELIMITER ; diff --git a/db/routines/vn/triggers/delivery_beforeInsert.sql b/db/routines/vn/triggers/delivery_beforeInsert.sql index 89431c30f..c9679ed13 100644 --- a/db/routines/vn/triggers/delivery_beforeInsert.sql +++ b/db/routines/vn/triggers/delivery_beforeInsert.sql @@ -4,16 +4,8 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`delivery_beforeInsert FOR EACH ROW BEGIN - IF (NEW.longitude IS NOT NULL AND NEW.latitude IS NOT NULL AND NEW.ticketFK IS NOT NULL) - THEN - UPDATE address - SET longitude = NEW.longitude, - latitude = NEW.latitude - WHERE id IN ( - SELECT addressFK - FROM ticket - WHERE id = NEW.ticketFk - ); + IF (NEW.longitude IS NOT NULL AND NEW.latitude IS NOT NULL AND NEW.ticketFK IS NOT NULL) THEN + CALL address_updateCorordinates(NEW.ticketFk,NEW.longitude,NEW.latitude); END IF; END$$ diff --git a/db/routines/vn/triggers/delivery_beforeUpdate.sql b/db/routines/vn/triggers/delivery_beforeUpdate.sql index 7e6aa7d4c..dda0e9dd2 100644 --- a/db/routines/vn/triggers/delivery_beforeUpdate.sql +++ b/db/routines/vn/triggers/delivery_beforeUpdate.sql @@ -4,16 +4,8 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`delivery_beforeUpdate FOR EACH ROW BEGIN -IF (NEW.longitude IS NOT NULL AND NEW.latitude IS NOT NULL AND NEW.ticketFK IS NOT NULL) - THEN - UPDATE address - SET longitude = NEW.longitude, - latitude = NEW.latitude - WHERE id IN ( - SELECT addressFK - FROM ticket - WHERE id = NEW.ticketFk - ); + IF (NEW.longitude IS NOT NULL AND NEW.latitude IS NOT NULL AND NEW.ticketFK IS NOT NULL) THEN + CALL address_updateCorordinates(NEW.ticketFk,NEW.longitude,NEW.latitude); END IF; END$$ From 02c2ccd62ee3648d2341058ef6c7efa088ee41f5 Mon Sep 17 00:00:00 2001 From: carlossa Date: Tue, 9 Jul 2024 11:00:02 +0200 Subject: [PATCH 086/170] stash filterState --- modules/ticket/back/methods/ticket/filter.js | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/modules/ticket/back/methods/ticket/filter.js b/modules/ticket/back/methods/ticket/filter.js index 899fe05cd..8d93fb993 100644 --- a/modules/ticket/back/methods/ticket/filter.js +++ b/modules/ticket/back/methods/ticket/filter.js @@ -347,6 +347,17 @@ module.exports = Self => { if (hasWhere) stmt.merge(conn.makeWhere(problems)); + if (filter.order) { + const index = filter.order.findIndex(o => o.includes('stateFk')); + if (index > -1) { + filter.order = [ + ...filter.order.slice(0, index), + 'refFk ' + filter.order[index].split(' ')[1], + ...filter.order.slice(index) + ]; + } + } + stmt.merge(conn.makeOrderBy(filter.order)); stmt.merge(conn.makeLimit(filter)); const ticketsIndex = stmts.push(stmt) - 1; From 3e4bf55eedfd296acf536e505af37d3958eea445 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 9 Jul 2024 11:03:17 +0200 Subject: [PATCH 087/170] fix: refs #7490 Correction --- db/routines/vn/procedures/duaInvoiceInBooking.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/routines/vn/procedures/duaInvoiceInBooking.sql b/db/routines/vn/procedures/duaInvoiceInBooking.sql index 6d0c9f517..10c0714e5 100644 --- a/db/routines/vn/procedures/duaInvoiceInBooking.sql +++ b/db/routines/vn/procedures/duaInvoiceInBooking.sql @@ -81,7 +81,7 @@ BEGIN AND (NOT e.isBooked OR NOT e.isConfirmed) ), notBookedEntries AS ( - SELECT e.id + SELECT entryFk FROM vn.duaEntry WHERE duaFk = vDuaFk AND NOT customsValue From be83fa672957c57014cce14e8d20ef497e706985 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 9 Jul 2024 11:13:55 +0200 Subject: [PATCH 088/170] fix: refs #7622 Fix --- modules/client/back/model-config.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/client/back/model-config.json b/modules/client/back/model-config.json index fc1254dd8..e6690ee5f 100644 --- a/modules/client/back/model-config.json +++ b/modules/client/back/model-config.json @@ -5,7 +5,7 @@ "AddressObservation": { "dataSource": "vn" }, - "AddressShortage": { + "AddressWaste": { "dataSource": "vn" }, "BankEntity": { From 944cf3baa3ef35b0a30c22eeea1f1bcb54bb0545 Mon Sep 17 00:00:00 2001 From: carlossa Date: Tue, 9 Jul 2024 11:44:43 +0200 Subject: [PATCH 089/170] refs #7694 hotfix filter --- modules/ticket/back/methods/ticket/filter.js | 1 + 1 file changed, 1 insertion(+) diff --git a/modules/ticket/back/methods/ticket/filter.js b/modules/ticket/back/methods/ticket/filter.js index 8d93fb993..0823b38b8 100644 --- a/modules/ticket/back/methods/ticket/filter.js +++ b/modules/ticket/back/methods/ticket/filter.js @@ -348,6 +348,7 @@ module.exports = Self => { stmt.merge(conn.makeWhere(problems)); if (filter.order) { + if (typeof filter.order == 'string') filter.order = [filter.order]; const index = filter.order.findIndex(o => o.includes('stateFk')); if (index > -1) { filter.order = [ From d8f3a045533db4f43892c4cf2c87b99af618b75a Mon Sep 17 00:00:00 2001 From: robert Date: Tue, 9 Jul 2024 11:45:58 +0200 Subject: [PATCH 090/170] fix: refs #6738 restore column grupotarifa --- db/versions/11145-pinkLaurel/00-firstScript.sql | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 db/versions/11145-pinkLaurel/00-firstScript.sql diff --git a/db/versions/11145-pinkLaurel/00-firstScript.sql b/db/versions/11145-pinkLaurel/00-firstScript.sql new file mode 100644 index 000000000..741a41f5b --- /dev/null +++ b/db/versions/11145-pinkLaurel/00-firstScript.sql @@ -0,0 +1,3 @@ +-- Place your SQL code here +ALTER TABLE vn.payrollWorker CHANGE grupotarifa__ grupotarifa int(10) NOT NULL; +ALTER TABLE vn.payrollWorker MODIFY COLUMN grupotarifa int(10) NOT NULL; \ No newline at end of file From 8f86ffbc3895bcb989c119c35992cb40842a8c91 Mon Sep 17 00:00:00 2001 From: robert Date: Tue, 9 Jul 2024 11:47:02 +0200 Subject: [PATCH 091/170] fix: refs #6738 --- db/versions/11145-pinkLaurel/00-firstScript.sql | 1 - 1 file changed, 1 deletion(-) diff --git a/db/versions/11145-pinkLaurel/00-firstScript.sql b/db/versions/11145-pinkLaurel/00-firstScript.sql index 741a41f5b..ba1946d3b 100644 --- a/db/versions/11145-pinkLaurel/00-firstScript.sql +++ b/db/versions/11145-pinkLaurel/00-firstScript.sql @@ -1,3 +1,2 @@ --- Place your SQL code here ALTER TABLE vn.payrollWorker CHANGE grupotarifa__ grupotarifa int(10) NOT NULL; ALTER TABLE vn.payrollWorker MODIFY COLUMN grupotarifa int(10) NOT NULL; \ No newline at end of file From f8169b3034e24ebc217c9bce76f9ce54975afbab Mon Sep 17 00:00:00 2001 From: robert Date: Tue, 9 Jul 2024 12:46:50 +0200 Subject: [PATCH 092/170] feat: refs #7544 chages required --- db/routines/vn/events/claim_changeState.sql | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/db/routines/vn/events/claim_changeState.sql b/db/routines/vn/events/claim_changeState.sql index 790ef0c34..5d94170a0 100644 --- a/db/routines/vn/events/claim_changeState.sql +++ b/db/routines/vn/events/claim_changeState.sql @@ -6,15 +6,15 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` EVENT `vn`.`claim_changeState` ENABLE DO BEGIN - DECLARE vClaimStete INT; + DECLARE vClaimState INT; - SELECT id INTO vClaimStete + SELECT id INTO vClaimState FROM claimState cs WHERE cs.code = 'canceled'; UPDATE claim c JOIN claimState cs ON cs.id = c.claimStateFk - SET c.claimStateFk = vClaimStete + SET c.claimStateFk = vClaimState WHERE c.created < util.VN_CURDATE() - INTERVAL 2 MONTH AND cs.code IN('incomplete','coming','waiting','out'); From c2e9095ccdae2ac6d7b0940916c186259dc43abe Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 9 Jul 2024 14:22:32 +0200 Subject: [PATCH 093/170] feat: refs #7505 Requested changes --- db/routines/cache/procedures/visible_refresh.sql | 2 +- db/routines/vn/procedures/item_calcVisible.sql | 5 ++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/db/routines/cache/procedures/visible_refresh.sql b/db/routines/cache/procedures/visible_refresh.sql index 4feffde8e..a59669ff6 100644 --- a/db/routines/cache/procedures/visible_refresh.sql +++ b/db/routines/cache/procedures/visible_refresh.sql @@ -25,7 +25,7 @@ proc: BEGIN WHERE warehouse_id = v_warehouse; -- Calculamos los movimientos confirmados de hoy - CALL vn.item_calcVisible(NULL, util.VN_CURDATE(), v_warehouse); + CALL vn.item_calcVisible(NULL, v_warehouse); DELETE FROM visible WHERE calc_id = v_calc; INSERT INTO visible (calc_id, item_id,visible) diff --git a/db/routines/vn/procedures/item_calcVisible.sql b/db/routines/vn/procedures/item_calcVisible.sql index 728c94276..820e73a7e 100644 --- a/db/routines/vn/procedures/item_calcVisible.sql +++ b/db/routines/vn/procedures/item_calcVisible.sql @@ -1,7 +1,6 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_calcVisible`( vSelf INT, - vDated DATE, vWarehouseFk INT ) BEGIN @@ -9,11 +8,11 @@ BEGIN * Calcula el visible de un artículo o de todos. * * @param vWarehouse Warehouse id - * @param vDated Max date to filter * @param vSelf Item id * @param tmp.itemVisible(item_id, stock, visible) */ - DECLARE vTomorrow DATETIME DEFAULT vDated + INTERVAL 1 DAY; + DECLARE vDated DATE DEFAULT util.VN_CURDATE(); + DECLARE vTomorrow DATETIME DEFAULT util.tomorrow(); INSERT INTO tmp.itemVisible(item_id, visible) SELECT itemFk, SUM(quantity) From 470c9bc8720dc1db1a84c47acabe00da23cb29d3 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 9 Jul 2024 14:24:17 +0200 Subject: [PATCH 094/170] feat: refs #7505 Minor changes --- db/routines/cache/procedures/visible_refresh.sql | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/db/routines/cache/procedures/visible_refresh.sql b/db/routines/cache/procedures/visible_refresh.sql index a59669ff6..d7e02ad96 100644 --- a/db/routines/cache/procedures/visible_refresh.sql +++ b/db/routines/cache/procedures/visible_refresh.sql @@ -1,13 +1,13 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `cache`.`visible_refresh`(OUT v_calc INT, v_refresh BOOL, v_warehouse INT) -proc: BEGIN +BEGIN DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN CALL cache_calc_unlock (v_calc); RESIGNAL; END; - CALL cache_calc_start (v_calc, v_refresh, 'visible', v_warehouse); + CALL cache_calc_start (v_calc, v_refresh, 'visible', v_warehouse); IF !v_refresh THEN LEAVE proc; @@ -15,13 +15,13 @@ proc: BEGIN -- Calculamos el stock hasta ayer - CALL `cache`.stock_refresh(false); + CALL cache.stock_refresh(false); CREATE OR REPLACE TEMPORARY TABLE tmp.itemVisible (PRIMARY KEY (item_id)) ENGINE = MEMORY SELECT item_id, amount stock, amount visible - FROM `cache`.stock + FROM cache.stock WHERE warehouse_id = v_warehouse; -- Calculamos los movimientos confirmados de hoy @@ -31,7 +31,7 @@ proc: BEGIN INSERT INTO visible (calc_id, item_id,visible) SELECT v_calc, item_id, visible FROM tmp.itemVisible; - CALL cache_calc_end (v_calc); + CALL cache_calc_end (v_calc); DROP TEMPORARY TABLE tmp.itemVisible; END$$ From e2b6473831e2211406e8f5c35fbecb9c9c271bbb Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 9 Jul 2024 14:24:35 +0200 Subject: [PATCH 095/170] feat: refs #7505 Minor changes --- db/routines/cache/procedures/visible_refresh.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/routines/cache/procedures/visible_refresh.sql b/db/routines/cache/procedures/visible_refresh.sql index d7e02ad96..78d23dbfb 100644 --- a/db/routines/cache/procedures/visible_refresh.sql +++ b/db/routines/cache/procedures/visible_refresh.sql @@ -1,6 +1,6 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `cache`.`visible_refresh`(OUT v_calc INT, v_refresh BOOL, v_warehouse INT) -BEGIN +proc:BEGIN DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN CALL cache_calc_unlock (v_calc); From 64ed96c8ae3b90699cb60451193bd5be97343808 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 9 Jul 2024 14:47:12 +0200 Subject: [PATCH 096/170] feat: refs #7486 More debug --- db/routines/vn/procedures/collection_assign.sql | 14 +++++++------- db/routines/vn/procedures/collection_new.sql | 16 ++++++++-------- .../procedures/ticket_splitItemPackingType.sql | 11 +++++++++++ 3 files changed, 26 insertions(+), 15 deletions(-) diff --git a/db/routines/vn/procedures/collection_assign.sql b/db/routines/vn/procedures/collection_assign.sql index bf130b2c6..f9032a91d 100644 --- a/db/routines/vn/procedures/collection_assign.sql +++ b/db/routines/vn/procedures/collection_assign.sql @@ -26,16 +26,16 @@ BEGIN vErrorNumber = MYSQL_ERRNO, vErrorMsg = MESSAGE_TEXT; + CALL util.debugAdd('collection_assign', JSON_OBJECT( + 'errorNumber', vErrorNumber, + 'errorMsg', vErrorMsg, + 'lockName', vLockName, + 'userFk', vUserFk + )); -- Tmp + IF vLockName IS NOT NULL THEN DO RELEASE_LOCK(vLockName); - CALL util.debugAdd('collection_assign', JSON_OBJECT( - 'errorNumber', vErrorNumber, - 'errorMsg', vErrorMsg, - 'lockName', vLockName, - 'userFk', vUserFk - )); -- Tmp END IF; - RESIGNAL; END; diff --git a/db/routines/vn/procedures/collection_new.sql b/db/routines/vn/procedures/collection_new.sql index 029427306..0bd6e1b25 100644 --- a/db/routines/vn/procedures/collection_new.sql +++ b/db/routines/vn/procedures/collection_new.sql @@ -53,17 +53,17 @@ BEGIN vErrorNumber = MYSQL_ERRNO, vErrorMsg = MESSAGE_TEXT; + CALL util.debugAdd('collection_new', JSON_OBJECT( + 'errorNumber', vErrorNumber, + 'errorMsg', vErrorMsg, + 'lockName', vLockName, + 'userFk', vUserFk, + 'ticketFk', vTicketFk + )); -- Tmp + IF vLockName IS NOT NULL THEN DO RELEASE_LOCK(vLockName); - CALL util.debugAdd('collection_new', JSON_OBJECT( - 'errorNumber', vErrorNumber, - 'errorMsg', vErrorMsg, - 'lockName', vLockName, - 'userFk', vUserFk, - 'ticketFk', vTicketFk - )); -- Tmp END IF; - RESIGNAL; END; diff --git a/db/routines/vn/procedures/ticket_splitItemPackingType.sql b/db/routines/vn/procedures/ticket_splitItemPackingType.sql index d6e8e8a53..e2c55e28a 100644 --- a/db/routines/vn/procedures/ticket_splitItemPackingType.sql +++ b/db/routines/vn/procedures/ticket_splitItemPackingType.sql @@ -16,6 +16,8 @@ BEGIN DECLARE vNewTicketFk INT; DECLARE vPackingTypesToSplit INT; DECLARE vDone INT DEFAULT FALSE; + DECLARE vErrorNumber INT; + DECLARE vErrorMsg TEXT; DECLARE cur1 CURSOR FOR SELECT itemPackingTypeFk @@ -27,6 +29,15 @@ BEGIN DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN + GET DIAGNOSTICS CONDITION 1 + vErrorNumber = MYSQL_ERRNO, + vErrorMsg = MESSAGE_TEXT; + + CALL util.debugAdd('ticket_splitItemPackingType', JSON_OBJECT( + 'errorNumber', vErrorNumber, + 'errorMsg', vErrorMsg, + 'ticketFk', vTicketFk + )); -- Tmp RESIGNAL; END; From 1ca95678dfdc3eb08816c5f949e89da3146c95ae Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 9 Jul 2024 14:53:09 +0200 Subject: [PATCH 097/170] Fix --- db/routines/vn/procedures/ticket_splitItemPackingType.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/routines/vn/procedures/ticket_splitItemPackingType.sql b/db/routines/vn/procedures/ticket_splitItemPackingType.sql index 8eeec551a..c2ec50fd9 100644 --- a/db/routines/vn/procedures/ticket_splitItemPackingType.sql +++ b/db/routines/vn/procedures/ticket_splitItemPackingType.sql @@ -36,7 +36,7 @@ BEGIN CALL util.debugAdd('ticket_splitItemPackingType', JSON_OBJECT( 'errorNumber', vErrorNumber, 'errorMsg', vErrorMsg, - 'ticketFk', vTicketFk + 'ticketFk', vSelf )); -- Tmp ROLLBACK; RESIGNAL; From 004dcb67ff3a5486cb2ae89d1d910faae5d5a862 Mon Sep 17 00:00:00 2001 From: robert Date: Wed, 10 Jul 2024 07:13:57 +0200 Subject: [PATCH 098/170] feat: refs #7116 insert into agencyIncoming --- db/routines/vn/events/claim_changeState.sql | 22 +++++++++++++++++++ .../10960-silverRoebelini/00-firstScript.sql | 17 +++++++++++++- 2 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 db/routines/vn/events/claim_changeState.sql diff --git a/db/routines/vn/events/claim_changeState.sql b/db/routines/vn/events/claim_changeState.sql new file mode 100644 index 000000000..9197f2a56 --- /dev/null +++ b/db/routines/vn/events/claim_changeState.sql @@ -0,0 +1,22 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` EVENT `vn`.`claim_changeState` + ON SCHEDULE EVERY 1 DAY + STARTS '2024-06-06 07:52:46.000' + ON COMPLETION PRESERVE + ENABLE +DO BEGIN + + DECLARE vClaimState INT; + + SELECT id INTO vClaimState + FROM claimState cs + WHERE cs.code = 'canceled'; + + UPDATE claim c + JOIN claimState cs ON cs.id = c.claimStateFk + SET c.claimStateFk = vClaimState + WHERE c.created < util.VN_CURDATE() - INTERVAL 2 MONTH + AND cs.code IN('incomplete','coming','waiting','out'); + +END$$ +DELIMITER ; diff --git a/db/versions/10960-silverRoebelini/00-firstScript.sql b/db/versions/10960-silverRoebelini/00-firstScript.sql index 228e0b014..c53a09549 100644 --- a/db/versions/10960-silverRoebelini/00-firstScript.sql +++ b/db/versions/10960-silverRoebelini/00-firstScript.sql @@ -5,4 +5,19 @@ CREATE TABLE IF NOT EXISTS `vn`.`agencyIncoming` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 -COLLATE=utf8mb3_unicode_ci COMMENT='Agencias de entrada de mercancias';; \ No newline at end of file +COLLATE=utf8mb3_unicode_ci COMMENT='Agencias de entrada de mercancias'; + +INSERT IGNORE INTO vn.agencyIncoming (agencyModeFk) VALUES +(1343), (1002), (1282), (841), (1303), (714), (556), (1786), (1785), (1784), +(1780), (1783), (1758), (1782), (1772), (1789), (1776), (1791), (1778), (1792), +(1779), (1362), (681), (1765), (15), (1594), (1706), (1707), (907), (1260), +(1715), (1371), (1372), (53), (689), (1375), (738), (742), (1307), (1700), (608), +(1311), (1315), (1339), (1433), (1338), (1332), (1844), (842), (1382), (1466), +(1719), (1723), (1725), (1720), (1732), (1736), (1728), (1724), (1726), (1727), +(1767), (1734), (1730), (1845), (1729), (1746), (1699), (2), (671), (1379), (614), +(1718), (1697), (62), (1529), (1392), (1378), (1438), (1796), (1688), (686), +(1326), (1691), (1), (1560), (1695), (1696), (1558), (1648), (1649), (1598), +(1680), (1694), (1600), (1601), (1602), (1712), (1603), (1604), (1641), (1692), +(1693), (1650), (1683), (1682), (1681), (1713), (1826), (1768), (1769), (1770), +(1593), (1443), (1244), (1679), (1006), (1361), (1102), (1655), (1744), (1225), +(1007); From 64bddd4f63273063b7d35f63c993a0c491f62836 Mon Sep 17 00:00:00 2001 From: pablone Date: Wed, 10 Jul 2024 10:41:52 +0200 Subject: [PATCH 099/170] feat: refs #6403 add dynamic clientType --- back/methods/mrw-config/cancelShipment.ejs | 2 +- back/methods/mrw-config/cancelShipment.js | 4 +-- back/methods/mrw-config/createShipment.ejs | 2 +- back/methods/mrw-config/createShipment.js | 11 +++---- back/methods/mrw-config/getLabel.ejs | 2 +- back/methods/mrw-config/getLabel.js | 16 +++++++-- .../mrw-config/specs/createShipment.spec.js | 18 +++++----- back/methods/viaexpress-config/renderer.js | 4 +-- back/model-config.json | 3 ++ back/models/mrw-config.js | 25 ++++++++++++++ back/models/mrw-config.json | 3 ++ back/models/mrw-service.json | 33 +++++++++++++++++++ modules/zone/back/models/agency-mode.json | 5 +++ 13 files changed, 101 insertions(+), 27 deletions(-) create mode 100644 back/models/mrw-service.json diff --git a/back/methods/mrw-config/cancelShipment.ejs b/back/methods/mrw-config/cancelShipment.ejs index 9ef401bc8..bc0662981 100644 --- a/back/methods/mrw-config/cancelShipment.ejs +++ b/back/methods/mrw-config/cancelShipment.ejs @@ -2,7 +2,7 @@ <%= mrw.franchiseCode %> - <%= mrw.subscriberCode %> + <%= clientType %> <%= mrw.user %> <%= mrw.password %> diff --git a/back/methods/mrw-config/cancelShipment.js b/back/methods/mrw-config/cancelShipment.js index 86bbb7410..10d556575 100644 --- a/back/methods/mrw-config/cancelShipment.js +++ b/back/methods/mrw-config/cancelShipment.js @@ -27,9 +27,9 @@ module.exports = Self => { const mrw = await models.MrwConfig.findOne(); const {externalId} = await models.Expedition.findById(expeditionFk); - + const clientType = await models.MrwConfig.getClientType(expeditionFk); const template = fs.readFileSync(__dirname + '/cancelShipment.ejs', 'utf-8'); - const renderedXml = ejs.render(template, {mrw, externalId}); + const renderedXml = ejs.render(template, {mrw, externalId, clientType}); const response = await axios.post(mrw.url, renderedXml, { headers: { 'Content-Type': 'application/soap+xml; charset=utf-8' diff --git a/back/methods/mrw-config/createShipment.ejs b/back/methods/mrw-config/createShipment.ejs index 8e123ddd9..65326112b 100644 --- a/back/methods/mrw-config/createShipment.ejs +++ b/back/methods/mrw-config/createShipment.ejs @@ -3,7 +3,7 @@ <%= mrw.franchiseCode %> - <%= expeditionData.clientType %> + <%= clientType %> <%= mrw.user %> <%= mrw.password %> diff --git a/back/methods/mrw-config/createShipment.js b/back/methods/mrw-config/createShipment.js index 9b23cc370..ab25113dc 100644 --- a/back/methods/mrw-config/createShipment.js +++ b/back/methods/mrw-config/createShipment.js @@ -22,6 +22,7 @@ module.exports = Self => { Self.createShipment = async expeditionFk => { const models = Self.app.models; const mrw = await Self.getConfig(); + const clientType = await models.MrwConfig.getClientType(expeditionFk); const today = Date.vnNew(); const [hours, minutes] = mrw?.expeditionDeadLine ? mrw.expeditionDeadLine.split(':').map(Number) : [0, 0]; @@ -52,8 +53,7 @@ module.exports = Self => { CONCAT( e.ticketFk, LPAD(e.counter, mc.counterWidth, '0')) reference, LPAD(IF(mw.serviceType IS NULL, ms.serviceType, mw.serviceType), mc.serviceTypeWidth, '0') serviceType, IF(mw.weekdays, 'S', 'N') weekDays, - oa.description deliveryObservation, - LPAD(ms.clientType, mc.clientTypeWidth, '0') clientType + oa.description deliveryObservation FROM expedition e JOIN ticket t ON e.ticketFk = t.id JOIN agencyMode am ON am.id = t.agencyModeFk @@ -73,22 +73,19 @@ module.exports = Self => { const [expeditionData] = await Self.rawSql(query, [expeditionFk]); - if (!expeditionData) - throw new UserError(`This expedition is not a MRW shipment`); - if (expeditionData?.shipped.setHours(0, 0, 0, 0) < today.setHours(0, 0, 0, 0)) throw new UserError(`This ticket has a shipped date earlier than today`); const shipmentResponse = await Self.sendXmlDoc( __dirname + `/createShipment.ejs`, - {mrw, expeditionData}, + {mrw, expeditionData, clientType}, 'application/soap+xml' ); const shipmentId = Self.getTextByTag(shipmentResponse, 'NumeroEnvio'); if (!shipmentId) throw new UserError(Self.getTextByTag(shipmentResponse, 'Mensaje')); - const file = await models.MrwConfig.getLabel(shipmentId); + const file = await models.MrwConfig.getLabel(shipmentId, clientType); return {shipmentId, file}; }; diff --git a/back/methods/mrw-config/getLabel.ejs b/back/methods/mrw-config/getLabel.ejs index 09bdb3f6c..b0dae17c8 100644 --- a/back/methods/mrw-config/getLabel.ejs +++ b/back/methods/mrw-config/getLabel.ejs @@ -2,7 +2,7 @@ <%= mrw.franchiseCode %> - <%= mrw.subscriberCode %> + <%= clientType %> <%= mrw.user %> <%= mrw.password %> diff --git a/back/methods/mrw-config/getLabel.js b/back/methods/mrw-config/getLabel.js index aa9b87af1..4af3276bb 100644 --- a/back/methods/mrw-config/getLabel.js +++ b/back/methods/mrw-config/getLabel.js @@ -6,7 +6,13 @@ module.exports = Self => { arg: 'shipmentId', type: 'string', required: true - }], + }, + { + arg: 'clientType', + type: 'string', + required: true + }, + ], returns: { type: 'string', root: true @@ -17,10 +23,14 @@ module.exports = Self => { } }); - Self.getLabel = async shipmentId => { + Self.getLabel = async(shipmentId, clientType) => { const mrw = await Self.getConfig(); - const getLabelResponse = await Self.sendXmlDoc(__dirname + `/getLabel.ejs`, {mrw, shipmentId}, 'text/xml'); + const getLabelResponse = await Self.sendXmlDoc( + __dirname + `/getLabel.ejs`, + {mrw, shipmentId, clientType}, + 'text/xml' + ); return Self.getTextByTag(getLabelResponse, 'EtiquetaFile'); }; diff --git a/back/methods/mrw-config/specs/createShipment.spec.js b/back/methods/mrw-config/specs/createShipment.spec.js index 883dd8f6f..1ab77f608 100644 --- a/back/methods/mrw-config/specs/createShipment.spec.js +++ b/back/methods/mrw-config/specs/createShipment.spec.js @@ -40,15 +40,12 @@ describe('MRWConfig createShipment()', () => { ); + await models.MrwService.create( + {'agencyModeCodeFk': 'mrw', 'clientType': '000001', 'serviceType': 105, 'kg': 10} + ); + await createMrwConfig(); - await models.Application.rawSql( - `INSERT INTO vn.mrwService - SET agencyModeCodeFk = 'mrw', - clientType = 1, - serviceType = 1, - kg = 1`, null - ); await models.Ticket.create(ticket1); await models.Expedition.create(expedition1); }); @@ -82,7 +79,8 @@ describe('MRWConfig createShipment()', () => { 'user': 'user', 'password': 'password', 'franchiseCode': 'franchiseCode', - 'subscriberCode': 'subscriberCode' + 'subscriberCode': 'subscriberCode', + 'clientTypeWidth': 6 } ); } @@ -115,10 +113,10 @@ describe('MRWConfig createShipment()', () => { it('should fail if expeditionFk is not a MrwExpedition', async() => { let error; - await models.MrwConfig.createShipment(undefined).catch(e => { + await models.MrwConfig.createShipment(15).catch(e => { error = e; }).finally(async() => { - expect(error.message).toEqual(`This expedition is not a MRW shipment`); + expect(error.message).toEqual(`ClientType not available`); }); }); diff --git a/back/methods/viaexpress-config/renderer.js b/back/methods/viaexpress-config/renderer.js index c8533ea6b..5d83b5870 100644 --- a/back/methods/viaexpress-config/renderer.js +++ b/back/methods/viaexpress-config/renderer.js @@ -20,7 +20,7 @@ module.exports = Self => { } }); - Self.renderer = async (expeditionFk) => { + Self.renderer = async expeditionFk => { const models = Self.app.models; const viaexpressConfig = await models.ViaexpressConfig.findOne({ @@ -109,7 +109,7 @@ module.exports = Self => { const ticket = expedition.ticket(); const sender = ticket.company().client(); const shipped = ticket.shipped.toISOString(); - const isInterdia = (ticket.agencyModeFk === viaexpressConfig.agencyModeFk) + const isInterdia = (ticket.agencyModeFk === viaexpressConfig.agencyModeFk); const data = { viaexpressConfig, sender, diff --git a/back/model-config.json b/back/model-config.json index 58fa86797..a16fe4e8a 100644 --- a/back/model-config.json +++ b/back/model-config.json @@ -192,5 +192,8 @@ }, "RouteConfig": { "dataSource": "vn" + }, + "MrwService": { + "dataSource": "vn" } } \ No newline at end of file diff --git a/back/models/mrw-config.js b/back/models/mrw-config.js index c738c9c0e..8bb24dbe5 100644 --- a/back/models/mrw-config.js +++ b/back/models/mrw-config.js @@ -31,5 +31,30 @@ module.exports = Self => { }); return parser.parseFromString(data.data, 'text/xml'); }; + + Self.getClientType = async function(expeditionFk) { + if (!expeditionFk) throw new UserError(`No expeditionFk defined`); + + const {clientTypeWidth} = await Self.getConfig(); + const result = await Self.app.models.Expedition.findById(expeditionFk, + {include: [{ + relation: 'ticket', + scope: { + include: { + relation: 'agencyMode', + scope: { + include: { + relation: 'mrwService', + } + } + } + } + }]} + ); + const clientType = result?.ticket()?.agencyMode()?.mrwService()?.clientType; + if (!clientType || !clientTypeWidth) throw new UserError(`ClientType not available`); + + return clientType.toString().padStart(clientTypeWidth, '0'); + }; }; diff --git a/back/models/mrw-config.json b/back/models/mrw-config.json index c96b68cf3..60c0ca2a2 100644 --- a/back/models/mrw-config.json +++ b/back/models/mrw-config.json @@ -45,6 +45,9 @@ }, "notified":{ "type": "date" + }, + "clientTypeWidth": { + "type": "number" } } } diff --git a/back/models/mrw-service.json b/back/models/mrw-service.json new file mode 100644 index 000000000..1ad72d060 --- /dev/null +++ b/back/models/mrw-service.json @@ -0,0 +1,33 @@ +{ + "name": "MrwService", + "base": "VnModel", + "options": { + "mysql": { + "table": "mrwService" + } + }, + "properties": { + "agencyModeCodeFk": { + "id": true, + "type": "string", + "required": true + }, + "clientType": { + "type": "number", + "required": true + }, + "serviceType": { + "type": "number" + }, + "kg": { + "type": "number" + } + }, + "relations": { + "agency": { + "type": "hasOne", + "model": "AgencyMode", + "foreignKey": "code" + } + } +} diff --git a/modules/zone/back/models/agency-mode.json b/modules/zone/back/models/agency-mode.json index 99ed43b97..6033e26c6 100644 --- a/modules/zone/back/models/agency-mode.json +++ b/modules/zone/back/models/agency-mode.json @@ -60,6 +60,11 @@ "type": "hasMany", "model": "Zone", "foreignKey": "agencyModeFk" + }, + "mrwService": { + "type": "belongsTo", + "model": "MrwService", + "foreignKey": "code" } }, "acls": [ From 3c975aa9c47bc0e6c83b3704d6af981c24bd61fb Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 10 Jul 2024 11:32:41 +0200 Subject: [PATCH 100/170] refactor: refs #7580 Requested changes --- db/routines/vn/procedures/setParking.sql | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/db/routines/vn/procedures/setParking.sql b/db/routines/vn/procedures/setParking.sql index 107ef66f4..087fb4c07 100644 --- a/db/routines/vn/procedures/setParking.sql +++ b/db/routines/vn/procedures/setParking.sql @@ -28,7 +28,9 @@ BEGIN IF vParkingFk IS NULL THEN CALL util.throw('parkingNotExist'); END IF; - + + START TRANSACTION; + IF vParam REGEXP '^[0-9]+$' THEN SET vLastWeek = util.VN_CURDATE() - INTERVAL 1 WEEK; From 27f9001e344ca45654aa762c32564bbf44417c0f Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 10 Jul 2024 11:35:05 +0200 Subject: [PATCH 101/170] refactor: refs #7378 Requested changes --- db/versions/11130-crimsonIvy/00-firstScript.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/versions/11130-crimsonIvy/00-firstScript.sql b/db/versions/11130-crimsonIvy/00-firstScript.sql index 3bde55f55..c93f2f6b7 100644 --- a/db/versions/11130-crimsonIvy/00-firstScript.sql +++ b/db/versions/11130-crimsonIvy/00-firstScript.sql @@ -16,7 +16,7 @@ CREATE OR REPLACE TABLE `vn`.`productionConfigLog` ( `changedModelId` int(11) NOT NULL, `changedModelValue` varchar(45) DEFAULT NULL, PRIMARY KEY (`id`), - KEY `logRateuserFk` (`userFk`), + KEY `productionConfigLog_userFk` (`userFk`), KEY `productionConfigLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`), KEY `productionConfigLog_originFk` (`originFk`,`creationDate`), CONSTRAINT `productionConfigUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE From 203db3ec3a34921a533a8e8a0dc61be49603899f Mon Sep 17 00:00:00 2001 From: sergiodt Date: Wed, 10 Jul 2024 12:47:09 +0200 Subject: [PATCH 102/170] feat solvePrintLabel refs #7269 --- print/templates/reports/collection-label/collection-label.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/print/templates/reports/collection-label/collection-label.html b/print/templates/reports/collection-label/collection-label.html index 752a31185..143efc525 100644 --- a/print/templates/reports/collection-label/collection-label.html +++ b/print/templates/reports/collection-label/collection-label.html @@ -19,7 +19,7 @@ {{dashIfEmpty(labelData.workerCode)}} - {{labelData.labelCount || 0}} + {{this.labelCount || labelData.labelCount || 0}} {{labelData.code == 'V' ? (labelData.size || 0) + 'cm' : (labelData.volume || 0) + 'm³'}} From 5304929f57593a9d477bf5238172f54aff8b11a3 Mon Sep 17 00:00:00 2001 From: jgallego Date: Thu, 11 Jul 2024 08:52:07 +0200 Subject: [PATCH 103/170] feat: #refs 7348 schema --- db/versions/11126-blueCamellia/00-firstScript.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/versions/11126-blueCamellia/00-firstScript.sql b/db/versions/11126-blueCamellia/00-firstScript.sql index 45c2ed2dc..40c5e2b37 100644 --- a/db/versions/11126-blueCamellia/00-firstScript.sql +++ b/db/versions/11126-blueCamellia/00-firstScript.sql @@ -1,2 +1,2 @@ -ALTER TABLE `client` +ALTER TABLE `vn`.`client` ADD COLUMN `hasDailyInvoice` TINYINT(1) NOT NULL DEFAULT 0 COMMENT 'Indica si el cliente requiere facturación diaria por defecto se copiará lo que tenga country.hasDailyInvoice'; From 02bcfd9be38d21199ee12defadffda57efd3d035 Mon Sep 17 00:00:00 2001 From: guillermo Date: Thu, 11 Jul 2024 08:57:45 +0200 Subject: [PATCH 104/170] feat: refs #7704 Major changes --- .../hedera/procedures/order_addItem.sql | 15 +++-- db/routines/vn/procedures/item_getSimilar.sql | 2 +- db/routines/vn2008/views/buySource.sql | 3 +- .../11149-silverSalal/00-firstScript.sql | 20 +++++++ modules/item/back/model-config.json | 3 + .../back/models/item-minimum-quantity.json | 57 +++++++++++++++++++ modules/item/back/models/item.json | 4 -- modules/item/front/summary/index.html | 3 - .../order/back/methods/order/catalogFilter.js | 19 +++++-- modules/order/front/catalog-view/index.html | 12 ---- .../order/front/catalog-view/locale/es.yml | 3 +- modules/ticket/back/models/sale.js | 28 ++++++++- 12 files changed, 134 insertions(+), 35 deletions(-) create mode 100644 db/versions/11149-silverSalal/00-firstScript.sql create mode 100644 modules/item/back/models/item-minimum-quantity.json diff --git a/db/routines/hedera/procedures/order_addItem.sql b/db/routines/hedera/procedures/order_addItem.sql index d9c15c0eb..d47d8b870 100644 --- a/db/routines/hedera/procedures/order_addItem.sql +++ b/db/routines/hedera/procedures/order_addItem.sql @@ -56,11 +56,18 @@ BEGIN CALL util.throw ('ORDER_ROW_UNAVAILABLE'); END IF; - SELECT IFNULL(minQuantity, 0) INTO vMinQuantity - FROM vn.item - WHERE id = vItem; + SELECT quantity + FROM vn.itemMinimalQuantity + WHERE itemFk = vItem + AND ( + util.VN_CURDATE() BETWEEN `started` AND `ended` + OR + (util.VN_CURDATE() >= `started` AND `ended` IS NULL) + ) + AND (warehouseFk = vWarehouse OR warehouseFk IS NULL) + LIMIT 1; - IF vAmount < LEAST(vMinQuantity, vAvailable) THEN + IF vAmount < LEAST(IFNULL(vMinQuantity, 0), vAvailable) THEN CALL util.throw ('quantityLessThanMin'); END IF; diff --git a/db/routines/vn/procedures/item_getSimilar.sql b/db/routines/vn/procedures/item_getSimilar.sql index 557d77bdf..72c543b40 100644 --- a/db/routines/vn/procedures/item_getSimilar.sql +++ b/db/routines/vn/procedures/item_getSimilar.sql @@ -63,7 +63,7 @@ BEGIN WHEN b.groupingMode = 'grouping' THEN b.grouping WHEN b.groupingMode = 'packing' THEN b.packing ELSE 1 - END AS minQuantity, + END minQuantity, v.visible located, b.price2 FROM vn.item i diff --git a/db/routines/vn2008/views/buySource.sql b/db/routines/vn2008/views/buySource.sql index 33226a1dc..850483833 100644 --- a/db/routines/vn2008/views/buySource.sql +++ b/db/routines/vn2008/views/buySource.sql @@ -54,8 +54,7 @@ AS SELECT `b`.`entryFk` AS `Id_Entrada`, `i`.`packingOut` AS `packingOut`, `b`.`itemOriginalFk` AS `itemOriginalFk`, `io`.`longName` AS `itemOriginalName`, - `it`.`gramsMax` AS `gramsMax`, - `i`.`minQuantity` AS `minQuantity` + `it`.`gramsMax` AS `gramsMax` FROM ( ( ( diff --git a/db/versions/11149-silverSalal/00-firstScript.sql b/db/versions/11149-silverSalal/00-firstScript.sql new file mode 100644 index 000000000..3225f137f --- /dev/null +++ b/db/versions/11149-silverSalal/00-firstScript.sql @@ -0,0 +1,20 @@ +ALTER TABLE vn.item CHANGE minQuantity minQuantity__ int(10) unsigned DEFAULT + NULL NULL COMMENT '@deprecated 2024-07-11 refs #7704 Cantidad mínima para una línea de venta'; + +CREATE TABLE `vn`.`itemMinimumQuantity` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `itemFk` int(10) NOT NULL, + `quantity` int(10) NOT NULL, + `started` date NOT NULL, + `ended` date DEFAULT NULL, + `warehouseFk` smallint(5) unsigned DEFAULT NULL, + `created` timestamp NOT NULL DEFAULT current_timestamp(), + PRIMARY KEY (`id`), + UNIQUE KEY `itemMinimumQuantity_UNIQUE` (`itemFk`, `started`, `ended`, `warehouseFk`), + KEY `itemFk` (`itemFk`), + KEY `started` (`started`), + KEY `ended` (`ended`), + KEY `warehouseFk` (`warehouseFk`), + CONSTRAINT `itemMinimumQuantity_ibfk_1` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `itemMinimumQuantity_ibfk_2` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; diff --git a/modules/item/back/model-config.json b/modules/item/back/model-config.json index 2d06e1ada..5dbe4d62a 100644 --- a/modules/item/back/model-config.json +++ b/modules/item/back/model-config.json @@ -32,6 +32,9 @@ "ItemLog": { "dataSource": "vn" }, + "ItemMinimumQuantity": { + "dataSource": "vn" + }, "ItemPackingType": { "dataSource": "vn" }, diff --git a/modules/item/back/models/item-minimum-quantity.json b/modules/item/back/models/item-minimum-quantity.json new file mode 100644 index 000000000..848b42a3f --- /dev/null +++ b/modules/item/back/models/item-minimum-quantity.json @@ -0,0 +1,57 @@ +{ + "name": "ItemMinimumQuantity", + "base": "VnModel", + "options": { + "mysql": { + "table": "itemMinimumQuantity" + } + }, + "properties": { + "id": { + "type": "number", + "id": true, + "description": "Id" + }, + "itemFk": { + "type": "number", + "required": true + }, + "quantity": { + "type": "number", + "required": true + }, + "started": { + "type": "date", + "required": true + }, + "ended": { + "type": "date" + }, + "warehouseFk": { + "type": "number" + }, + "created": { + "type": "date" + } + }, + "relations": { + "item": { + "type": "belongsTo", + "model": "Item", + "foreignKey": "itemFk" + }, + "warehouse": { + "type": "belongsTo", + "model": "Warehouse", + "foreignKey": "warehouseFk" + } + }, + "acls": [ + { + "accessType": "READ", + "principalType": "ROLE", + "principalId": "buyer", + "permission": "ALLOW" + } + ] +} \ No newline at end of file diff --git a/modules/item/back/models/item.json b/modules/item/back/models/item.json index 10cff3e04..eda56e938 100644 --- a/modules/item/back/models/item.json +++ b/modules/item/back/models/item.json @@ -152,10 +152,6 @@ "columnName": "doPhoto" } }, - "minQuantity": { - "type": "number", - "description": "Min quantity" - }, "photoMotivation": { "type": "string" } diff --git a/modules/item/front/summary/index.html b/modules/item/front/summary/index.html index 13c671d29..0e4cfc955 100644 --- a/modules/item/front/summary/index.html +++ b/modules/item/front/summary/index.html @@ -128,9 +128,6 @@ - -

diff --git a/modules/order/back/methods/order/catalogFilter.js b/modules/order/back/methods/order/catalogFilter.js index ab1d7784e..3d67e080c 100644 --- a/modules/order/back/methods/order/catalogFilter.js +++ b/modules/order/back/methods/order/catalogFilter.js @@ -101,6 +101,14 @@ module.exports = Self => { )); stmt = new ParameterizedSQL(` + WITH minQuantity AS ( + SELECT itemFk, quantity, warehouseFk + FROM vn.itemMinimalQuantity + WHERE (util.VN_CURDATE() BETWEEN started AND ended + OR (util.VN_CURDATE() >= started AND ended IS NULL)) + GROUP BY itemFk, warehouseFk + ORDER BY warehouseFk DESC + ) SELECT i.id, i.name, i.subName, @@ -125,6 +133,9 @@ module.exports = Self => { JOIN vn.itemType it ON it.id = i.typeFk JOIN vn.worker w on w.id = it.workerFk LEFT JOIN vn.ink ON ink.id = i.inkFk + LEFT JOIN tmp.ticketComponentPrice tcp ON tcp.itemFk = i.id + LEFT JOIN minQuantity mq ON mq.itemFk = i.id + AND (mq.warehouseFk = tpc.warehouseFk OR mq.warehouseFk IS NULL) `); // Apply order by tag @@ -158,21 +169,19 @@ module.exports = Self => { // Apply item prices const pricesIndex = stmts.push( - `SELECT - tcp.itemFk, + `SELECT tcp.itemFk, tcp.grouping, tcp.price, tcp.rate, tcp.warehouseFk, tcp.priceKg, - w.name AS warehouse + w.name warehouse FROM tmp.ticketComponentPrice tcp JOIN vn.warehouse w ON w.id = tcp.warehouseFk`) - 1; // Get tags from all items const itemTagsIndex = stmts.push( - `SELECT - t.id, + `SELECT t.id, t.name, t.isFree, t.sourceTable, diff --git a/modules/order/front/catalog-view/index.html b/modules/order/front/catalog-view/index.html index 081ce05a0..562723cf7 100644 --- a/modules/order/front/catalog-view/index.html +++ b/modules/order/front/catalog-view/index.html @@ -37,18 +37,6 @@ value="{{::item.value7}}"> - - - - - - {{::item.minQuantity}} -