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

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

	DELETE FROM salesDepartmentEvolution 
		WHERE dated >= vDated;

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

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

	WHILE vDated < util.VN_CURDATE() DO
	
		REPLACE salesByClientDepartment(salesDepartmentFk, dated, amount)
			SELECT salesDepartmentFk, vDated, amount
				FROM(SELECT salesDepartmentFk, SUM(amount) amount
						FROM(SELECT salesDepartmentFk, amount
								FROM salesByClientDepartment 
								WHERE dated = vDated - INTERVAL 1 DAY
							UNION ALL
							SELECT salesDepartmentFk, amount 
								FROM salesByClientDepartment 
								WHERE dated = vDated
							UNION ALL
							SELECT salesDepartmentFk, - amount
								FROM salesByClientDepartment 
								WHERE dated = vDated - INTERVAL 1 YEAR
							)sub
						GROUP BY salesDepartmentFk
					)sub
				GROUP BY salesDepartmentFk;

		SET vDated = vDated + INTERVAL 1 DAY;

	END WHILE;
END$$
DELIMITER ;
