DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`greuge_add`()
BEGIN
/**
 * Group inserts into vn.greuge and then deletes the records just inserted
 */
	DECLARE vDated DATE;

	SELECT DATE_SUB(util.VN_CURDATE(), INTERVAL yearsToDelete YEAR) INTO vDated
		FROM vn.greugeConfig;
		
	INSERT INTO vn.greuge(clientFk, description, amount, shipped, created, greugeTypeFk)
		SELECT clientFk, 'Suma agrupada', SUM(amount), MAX(shipped), MAX(created), greugeTypeFk
			FROM vn.greuge
			WHERE shipped <= vDated AND description <> 'Suma agrupada'
			GROUP BY clientFk, greugeTypeFk;

	DELETE
		FROM vn.greuge
		WHERE shipped <= vDated AND description <> 'Suma agrupada';
END$$
DELIMITER ;
