DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`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 id FROM ticket
			WHERE refFk IS NULL
				AND ((vScope = 'client' AND clientFk = vId)
					OR (vScope = 'address' AND addressFk = vId));

	DECLARE CONTINUE HANDLER FOR NOT FOUND
		SET vDone = TRUE;

	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;
END$$
DELIMITER ;
