DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bs`.`salesDepartmentEvolution_add`()
BEGIN
/**
 * Calcula los datos para los gráficos de evolución agrupado por departmentFk 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(
				departmentFk,
				dated,
				amount,
				equalizationTax,
				amountNewBorn
			)
			SELECT departmentFk,
					dated,
					amount,
					equalizationTax,
					amountNewBorn
				FROM salesByClientDepartment
				WHERE dated = vDated
				GROUP BY departmentFk;

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

	WHILE vDated < util.VN_CURDATE() DO

		REPLACE salesByClientDepartment(departmentFk, dated, amount)
			SELECT departmentFk, vDated, amount
				FROM(SELECT departmentFk, SUM(amount) amount
						FROM(SELECT departmentFk, amount
								FROM salesByClientDepartment
								WHERE dated = vDated - INTERVAL 1 DAY
							UNION ALL
							SELECT departmentFk, amount
								FROM salesByClientDepartment
								WHERE dated = vDated
							UNION ALL
							SELECT departmentFk, - amount
								FROM salesByClientDepartment
								WHERE dated = vDated - INTERVAL 1 YEAR
							)sub
						GROUP BY departmentFk
					)sub
				GROUP BY departmentFk;

		SET vDated = vDated + INTERVAL 1 DAY;

	END WHILE;
END$$
DELIMITER ;
