DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bs`.`compradores_evolution_add`()
BEGIN
/**
 * Inserta en la tabla compradores_evolution las ventas acumuladas en los ultimos 365 dias
 * 
 */
	DECLARE vDated DATE;
	DECLARE vCount INT DEFAULT 1;

	SELECT MAX(fecha) + INTERVAL 1 DAY INTO vDated 
		FROM compradores_evolution;

	IF vDated IS NULL THEN
		
		SELECT MIN(dated) INTO vDated 
				FROM sale;

		INSERT INTO compradores_evolution(
				Id_Trabajador,
				fecha,
				importe)
			SELECT it.workerFk,
					vDated,
					SUM(s.amount)
				FROM sale s
					JOIN vn.itemType it ON it.id = s.typeFk
				WHERE s.dated = vDated
				GROUP BY it.workerFk;

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

	WHILE vDated < util.VN_CURDATE() DO

		SET vCount = vCount + 1;
		
		REPLACE compradores_evolution(
				Id_Trabajador,
				fecha,
				importe)
			SELECT Id_Trabajador,
					vDated,
					SUM(importe)
				FROM(
					SELECT Id_Trabajador, importe
						FROM compradores_evolution
							JOIN (
								SELECT DISTINCT it.workerFk 
									FROM vn.itemType it 
							)sub2 ON sub2.workerFk = Id_Trabajador
						WHERE fecha = vDated - INTERVAL 1 DAY 
					UNION ALL
					SELECT it.workerFk, s.amount * IF(s.dated < vDated, -1, 1) 
						FROM sale s
							JOIN vn.itemType it ON it.id = s.typeFk
							JOIN vn.itemCategory ic ON ic.id = it.categoryFk
						WHERE s.dated IN (vDated, vDated - INTERVAL 1 YEAR)
							AND ic.merchandise
				)sub 
				GROUP BY Id_Trabajador;

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