DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `bs`.`salesPersonEvolution_add`()
BEGIN
/**
 * Calcula los datos para los gráficos de evolución agrupado por salesPersonFk y día. 
 * Recalcula automáticamente los 3 últimos meses para comprobar si hay algún cambio.
 */
	DECLARE vDated DATE;
	DECLARE vCont INT DEFAULT 1;

	SELECT MAX(dated) - INTERVAL 3 MONTH INTO vDated 
		FROM salesPersonEvolution;

	DELETE FROM salesPersonEvolution 
		WHERE dated >= vDated;

	IF ISNULL(vDated) THEN
		SELECT MIN(dated) INTO vDated 
			FROM salesByclientSalesPerson;
		
		INSERT INTO salesPersonEvolution(
				salesPersonFk, 
				dated, 
				amount, 
				equalizationTax, 
				amountNewBorn
			)
			SELECT salesPersonFk, 
				dated, 
				amount, 
				equalizationTax, 
				amountNewBorn
				FROM salesByclientSalesPerson 
				WHERE dated = vDated
				GROUP BY salesPersonFk;

		SET vDated = vDated + INTERVAL 1 DAY;
	END IF;

	WHILE vDated < util.VN_CURDATE() DO
		
		SET vCont = vCont + 1;
		REPLACE salesPersonEvolution(salesPersonFk, dated, amount)
			SELECT salesPersonFk, vDated, amount
				FROM(SELECT salesPersonFk, SUM(amount) amount
						FROM(SELECT salesPersonFk, amount
								FROM salesPersonEvolution 
								WHERE dated = vDated - INTERVAL 1 DAY
							UNION ALL
							SELECT salesPersonFk, amount 
								FROM salesByclientSalesPerson 
								WHERE dated = vDated
							UNION ALL
							SELECT salesPersonFk, - amount
								FROM salesByclientSalesPerson 
								WHERE dated = vDated - INTERVAL 1 YEAR
							)sub
						GROUP BY salesPersonFk
					)sub
				GROUP BY salesPersonFk;

		SET vDated = vDated + INTERVAL 1 DAY;
	END WHILE;
END$$
DELIMITER ;
