salix/db/routines/vn/procedures/ticket_mergeSales.sql

55 lines
1.2 KiB
MySQL
Raw Normal View History

2024-08-27 08:47:09 +00:00
DELIMITER $$
2024-10-01 06:51:03 +00:00
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`ticket_mergeSales`(
2024-08-27 08:47:09 +00:00
vSelf INT
)
BEGIN
2024-09-26 08:36:19 +00:00
/**
* Para un ticket se agrupa las diferentes líneas de venta de un mismo artículo en una sola
* siempre y cuando tengan el mismo precio y dto.
*
* @param vSelf Id de ticket
*/
DECLARE vHasSalesToMerge BOOL;
2024-08-27 08:47:09 +00:00
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RESIGNAL;
END;
2024-09-26 08:36:19 +00:00
START TRANSACTION;
SELECT id INTO vSelf
FROM ticket
WHERE id = vSelf FOR UPDATE;
2024-08-27 08:47:09 +00:00
CREATE OR REPLACE TEMPORARY TABLE tSalesToPreserve
(PRIMARY KEY (id))
ENGINE = MEMORY
2024-09-17 07:30:40 +00:00
SELECT s.id, s.itemFk, SUM(s.quantity) newQuantity
2024-08-27 08:47:09 +00:00
FROM sale s
JOIN item i ON i.id = s.itemFk
JOIN itemType it ON it.id = i.typeFk
2024-09-17 07:37:25 +00:00
WHERE s.ticketFk = vSelf
2024-08-27 08:47:09 +00:00
AND it.isMergeable
2024-09-26 08:36:19 +00:00
GROUP BY s.itemFk, s.price, s.discount
HAVING COUNT(*) > 1;
2024-08-27 08:47:09 +00:00
2024-09-26 08:36:19 +00:00
SELECT COUNT(*) INTO vHasSalesToMerge FROM tSalesToPreserve;
2024-08-27 08:47:09 +00:00
2024-09-26 08:36:19 +00:00
IF vHasSalesToMerge THEN
UPDATE sale s
JOIN tSalesToPreserve stp ON stp.id = s.id
SET s.quantity = newQuantity;
2024-08-27 08:47:09 +00:00
2024-09-26 08:36:19 +00:00
DELETE s
FROM sale s
JOIN tSalesToPreserve stp ON stp.itemFk = s.itemFk
WHERE s.ticketFk = vSelf
AND s.id <> stp.id;
END IF;
2024-08-27 08:47:09 +00:00
COMMIT;
DROP TEMPORARY TABLE tSalesToPreserve;
END$$
DELIMITER ;