DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`ticket_recalcByScope`(
	vScope VARCHAR(255),
	vId INT
)
BEGIN
/**
 * Recalculates tickets in an scope.
 *
 * @param vScope The scope name
 * @param vId The scope id
 */
	DECLARE vDone BOOL;
	DECLARE vTicketFk INT;

	DECLARE cTickets CURSOR FOR
		SELECT DISTINCT t.id
			FROM ticket t
				LEFT JOIN tItems ti ON ti.id = t.id
			WHERE t.refFk IS NULL
				AND ((vScope = 'client' AND t.clientFk = vId)
					OR (vScope = 'address' AND t.addressFk = vId)
					OR (vScope = 'item' AND ti.id)
				);

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;

	CREATE OR REPLACE TEMPORARY TABLE tItems
		(PRIMARY KEY (id))
		ENGINE = MEMORY
		SELECT DISTINCT t.id
			FROM ticket t
				JOIN sale s ON s.ticketFk = t.id
				JOIN itemTaxCountry itc ON itc.itemFk = s.itemFk
			WHERE t.refFk IS NULL
				AND (vScope = 'item' AND itc.itemFk = vId);

	OPEN cTickets;
	myLoop: LOOP
		SET vDone = FALSE;
		FETCH cTickets INTO vTicketFk;

		IF vDone THEN
			LEAVE myLoop;
		END IF;

		CALL ticket_recalc(vTicketFk, NULL);
	END LOOP;
	CLOSE cTickets;

	DROP TEMPORARY TABLE tItems;
END$$
DELIMITER ;
