DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketCalculateClon`(IN vTicketNew INT, vTicketOld INT)
BEGIN
/*
 * Recalcula los componentes un ticket clonado,
 * las lineas a precio cero fuerza para que tengan precio, el resto lo respeta
 * @param vTicketNew nuevo ticket clonado
 * @param vTicketOld icket original, a partir del qual se clonara el nuevo
*/

	REPLACE INTO orderTicket(orderFk,ticketFk)
		SELECT orderFk, vTicketNew 
			FROM orderTicket 
				WHERE ticketFk = vTicketOld;

	-- Bionizamos lineas con Preu = 0
	CREATE OR REPLACE TEMPORARY TABLE tmp.recalculateSales
				(PRIMARY KEY (id)) ENGINE = MEMORY
			SELECT id
				FROM sale
				WHERE ticketFk = vTicketNew AND price = 0;

	CALL sale_recalcComponent('renewPrices');

	-- Bionizamos lineas con Preu > 0
	CREATE OR REPLACE TEMPORARY TABLE tmp.recalculateSales
				(PRIMARY KEY (id)) ENGINE = MEMORY
			SELECT id 
				FROM sale
				WHERE ticketFk = vTicketNew AND price > 0;

	CALL sale_recalcComponent('imbalance');

	DROP TEMPORARY TABLE IF EXISTS tmp.recalculateSales;

END$$
DELIMITER ;
