DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bi`.`defaultersFromDate`(
	IN vDated DATE
)
BEGIN
/**
 * Retorna la info de clientes morosos a una fecha
 *
 * @param vDated Fecha a comprobar
 */
	WITH todayDefaulters AS(
	SELECT client, amount, defaulterSince
		FROM bi.defaulters
		WHERE date = vDated 
			AND hasChanged
	), yesterdayDefaulters AS(
	SELECT client, amount
		FROM bi.defaulters
		WHERE date = vDated - INTERVAL 1 DAY
	), newDefaulters AS(
	SELECT td.client, 
			td.amount todayAmount, 
			yd.amount yesterdayAmount, 
			ROUND(yd.amount - td.amount, 2) difference, 
			defaulterSince
		FROM todayDefaulters td
			JOIN yesterdayDefaulters yd ON yd.client = td.client
		WHERE td.amount > 0 
		HAVING difference <> 0
	) SELECT nd.client,
			nd.todayAmount,
			nd.yesterdayAmount,
			nd.difference,
			nd.defaulterSince,
			c.name Cliente, 
			d.name salesDepartmentName,
			c.payMethodFk pay_met_id, 
			c.dueDay Vencimiento
		FROM newDefaulters nd
			LEFT JOIN vn.client c ON c.id = nd.client
			LEFT JOIN vn.department d ON d.id = c.salesDepartmentFk;
END$$
DELIMITER ;
