diff --git a/db/routines/vn/procedures/ticket_splitItemPackingType.sql b/db/routines/vn/procedures/ticket_splitItemPackingType.sql index 95b734b44..1a1e1ff07 100644 --- a/db/routines/vn/procedures/ticket_splitItemPackingType.sql +++ b/db/routines/vn/procedures/ticket_splitItemPackingType.sql @@ -18,19 +18,34 @@ BEGIN DECLARE vDefaultPackingType VARCHAR(1); DECLARE vHasOriginalPackingType BOOLEAN; DECLARE vNewTicketFk INT; + DECLARE vThrowAway INT; DECLARE vItemPackingTypes CURSOR FOR SELECT DISTINCT itemPackingTypeFk FROM tSalesToMove; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vIsDone = TRUE; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + CREATE OR REPLACE TEMPORARY TABLE tSalesToMove ( ticketFk INT, saleFk INT, itemPackingTypeFk VARCHAR(1) ) ENGINE=MEMORY; - SELECT vDefaultPackingTypeFk INTO vDefaultPackingType FROM itemConfig LIMIT 1; + SELECT defaultPackingTypeFk INTO vDefaultPackingType FROM itemConfig LIMIT 1; + + START TRANSACTION; + + SELECT t.id INTO vThrowAway + FROM ticket t + JOIN sale s ON s.id = t.id + WHERE t.id = vSelf + FOR UPDATE; SELECT EXISTS ( SELECT TRUE @@ -48,11 +63,12 @@ BEGIN SELECT s.id, i.itemPackingTypeFk FROM sale s JOIN item i ON i.id = s.itemFk - WHERE s.ticketFk = vSelf - AND i.itemPackingTypeFk <> vOriginalItemPackingTypeFk; + WHERE s.ticketFk = vSelf + AND i.itemPackingTypeFk <> vOriginalItemPackingTypeFk; OPEN vItemPackingTypes; l: LOOP + SET vIsDone = FALSE; FETCH vItemPackingTypes INTO vCurrentPackingType; IF vIsDone THEN @@ -61,6 +77,11 @@ BEGIN CALL ticket_Clone(vSelf, vNewTicketFk); + SELECT id INTO vThrowAway + FROM ticket t + WHERE t.id = vNewTicketFk + FOR UPDATE; + UPDATE tSalesToMove SET ticketFk = vNewTicketFk WHERE itemPackingTypeFk = vCurrentPackingType; @@ -73,25 +94,27 @@ BEGIN WHERE s.ticketFk = vSelf AND i.itemPackingTypeFk IS NULL; END IF; + END LOOP; CLOSE vItemPackingTypes; UPDATE sale s JOIN tSalesToMove t ON t.saleFk = s.id - SET s.ticketFk = t.ticketFk - WHERE t.ticketFk IS NOT NULL; + SET s.ticketFk = t.ticketFk; CREATE OR REPLACE TEMPORARY TABLE tmp.ticketIPT ENGINE=MEMORY - SELECT s.ticketFk, i.itemPackingTypeFk + SELECT s.ticketFk, MAX(i.itemPackingTypeFk) itemPackingTypeFk FROM sale s JOIN item i ON i.id = s.itemFk WHERE s.ticketFk = vSelf - GROUP BY s.ticketFk, i.itemPackingTypeFk + GROUP BY s.ticketFk UNION - SELECT ticketFk, itemPackingTypeFk + SELECT ticketFk, MAX(itemPackingTypeFk) FROM tSalesToMove - GROUP BY ticketFk, itemPackingTypeFk; + GROUP BY ticketFk; + + COMMIT; DROP TEMPORARY TABLE tSalesToMove; END$$