DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`creditRecovery`()
BEGIN
/**
 * Actualiza el crédito de los clientes 
 */

	DECLARE EXIT HANDLER FOR SQLSTATE '45000'
	BEGIN
		ROLLBACK;
		RESIGNAL;
	END;

	START TRANSACTION;

	UPDATE `client` c
			JOIN payMethod pm ON pm.id = c.payMethodFk
		SET c.credit = 0
		WHERE pm.`code` = 'card';

	DROP TEMPORARY TABLE IF EXISTS tCreditClients;
	CREATE TEMPORARY TABLE tCreditClients
		SELECT clientFk, IF(credit > recovery, credit - recovery, 0) newCredit
			FROM (
				SELECT r.clientFk,
					r.amount recovery,
					(sub2.created + INTERVAL r.period DAY) deadLine,
					sub2.amount credit
					FROM recovery r
						JOIN (
							SELECT clientFk, amount, created
								FROM (
									SELECT clientFk, amount, created
										FROM clientCredit
										ORDER BY created DESC
										LIMIT 10000000000000000000
								) sub
							GROUP BY clientFk
						) sub2 ON sub2.clientFk = r.clientFk
					WHERE r.finished IS NULL OR r.finished >= util.VN_CURDATE()
					GROUP BY r.clientFk
					HAVING deadLine <= util.VN_CURDATE()
			) sub3
			WHERE credit > 0;

	UPDATE client c
			JOIN tCreditClients cc ON cc.clientFk = c.id
		SET c.credit = newCredit;
	
	DROP TEMPORARY TABLE tCreditClients;
	COMMIT;

END$$
DELIMITER ;
