DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bs`.`salesByClientDepartments_add`(vDatedFrom DATE)
BEGIN
/**
 * Agrupa las ventas por cliente/departamento/fecha en la tabla bs.salesByClientDepartment
 * El asociación cliente/comercial/fecha, se mantiene correcta en el tiempo
 * 
 * @param vDatedFrom el cálculo se realizará desde la fecha introducida hasta ayer
 */

	IF vDatedFrom IS NULL THEN
		SET vDatedFrom = util.VN_CURDATE() - INTERVAL 1 MONTH;
	END IF;

	UPDATE salesByClientDepartment
		SET amount = 0,
			equalizationTax = 0,
			amountNewBorn = 0
		WHERE dated BETWEEN vDatedFrom AND util.yesterday();
	
	INSERT INTO salesByClientDepartment( 
			dated, 
			salesDepartmentFk, 
			clientFk, 
			amount, 
			equalizationTax)
		SELECT s.dated,
				c.salesDepartmentFk,
				s.clientFk,
				SUM(s.amount),
				SUM(s.surcharge)
			FROM sale s
				JOIN vn.client c on s.clientFk = c.id
			WHERE s.dated BETWEEN vDatedFrom AND util.yesterday() 
			GROUP BY s.dated, c.salesDepartmentFk, s.clientFk
		ON DUPLICATE KEY UPDATE amount= VALUES(amount),
			equalizationTax= VALUES(equalizationTax);

	UPDATE salesByClientDepartment s
		JOIN vn.newBornSales n ON n.dated = s.dated AND
			n.clientFk = s.clientFk
		SET s.amountNewBorn = n.amount
		WHERE n.dated BETWEEN vDatedFrom AND util.yesterday();

END$$
DELIMITER ;
