DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `bs`.`clientNewBorn_recalc`()
BLOCK1: BEGIN

	DECLARE vClientFk INT;
	DECLARE vShipped DATE; 
	DECLARE vPreviousShipped DATE;
	DECLARE vDone boolean;  

	DECLARE cur CURSOR FOR  
		SELECT clientFk, firstShipped  
			FROM bs.clientNewBorn;    
        
	DECLARE continue HANDLER FOR NOT FOUND SET vDone = TRUE;      
	SET vDone := FALSE;  

	DELETE FROM	bs.clientNewBorn WHERE isModified = FALSE;

	INSERT INTO clientNewBorn(clientFk, firstShipped, lastShipped)
		SELECT  c.id, DATE(MAX(t.shipped)), DATE(MAX(t.shipped))
			FROM vn.client c
				JOIN vn.ticket t ON t.clientFk =  c.id
				LEFT JOIN clientNewBorn cb ON cb.clientFk = c.id
			WHERE t.shipped BETWEEN util.VN_CURDATE() - INTERVAL 1 YEAR 
					AND util.VN_CURDATE() 
				AND cb.isModified IS NULL
			GROUP BY c.id;

	OPEN cur;
	LOOP1: LOOP
		SET vDone := FALSE;
		FETCH cur INTO vClientFk, vShipped;

		IF vDone THEN
			CLOSE cur;
			LEAVE LOOP1;
		END IF;

		BLOCK2: BEGIN
			DECLARE vCurrentShipped DATE;  
			DECLARE vDone2 boolean;  
			DECLARE cur2 CURSOR FOR
				SELECT shipped 
					FROM vn.ticket 
						WHERE clientFk = vClientFk AND shipped <=  util.VN_CURDATE()
						ORDER BY shipped DESC;
		 
		   DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone2 = TRUE;
				SET vDone2 := FALSE;
		   OPEN cur2;
		   
			SET vPreviousShipped := vShipped;
			LOOP2: LOOP
				SET vDone2 := FALSE;
				FETCH cur2 INTO vCurrentShipped;
				
				IF DATEDIFF(vPreviousShipped,vCurrentShipped) > 365 THEN
					UPDATE bs.clientNewBorn 
						SET firstShipped = vPreviousShipped 
						WHERE clientFk= vClientFk;
					
					CLOSE cur2;
					LEAVE LOOP2;    
				END IF;
				
				SET vPreviousShipped := vCurrentShipped;

				IF vDone2 THEN
					UPDATE bs.clientNewBorn 
						SET firstShipped = vCurrentShipped 
						WHERE clientFk= vClientFk;
					CLOSE cur2;
					LEAVE LOOP2;
				END IF;

			END LOOP LOOP2;
		END BLOCK2;
	END LOOP LOOP1;

	UPDATE bs.clientNewBorn cnb 
		LEFT JOIN (SELECT DISTINCT t.clientFk
						FROM vn.ticket t
							JOIN vn.productionConfig pc
						WHERE t.shipped BETWEEN util.VN_CURDATE() + INTERVAL -(`notBuyingMonths`) MONTH
						AND util.VN_CURDATE() + INTERVAL -(`pc`.`rookieDays`) DAY) notRookie ON notRookie.clientFk = cnb.clientFk
		SET cnb.isRookie = ISNULL(notRookie.clientFk); 
	
END BLOCK1$$
DELIMITER ;
