DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`ticket_mergeSales`(
	vSelf INT
)
BEGIN
/**
 * 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;
	DECLARE EXIT HANDLER FOR SQLEXCEPTION
	BEGIN
		ROLLBACK;
		RESIGNAL;
	END;

	START TRANSACTION;

	SELECT id INTO vSelf
		FROM ticket
		WHERE id = vSelf FOR UPDATE;

	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 = vSelf
				AND it.isMergeable
			GROUP BY s.itemFk, s.price, s.discount
			HAVING COUNT(*) > 1;

	SELECT COUNT(*) INTO vHasSalesToMerge FROM tSalesToPreserve;

	IF vHasSalesToMerge THEN 
		UPDATE sale s 
				JOIN tSalesToPreserve stp ON stp.id = s.id
			SET s.quantity = newQuantity;

		DELETE s
			FROM sale s
				JOIN tSalesToPreserve stp ON stp.itemFk = s.itemFk
			WHERE s.ticketFk = vSelf
				AND s.id <> stp.id;
	END IF;

	COMMIT;
	DROP TEMPORARY TABLE tSalesToPreserve;
END$$
DELIMITER ;
