DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`client_userDisable`()
BEGIN
/**
* Desactiva los clientes inactivos en los Ășltimos X meses.
*/
	DECLARE vMonths INT;

	SELECT monthsToDisableUser INTO vMonths
		FROM clientConfig;

	IF vMonths IS NULL THEN
		CALL util.throw('Config parameter not set');
	END IF;

	UPDATE account.user u
			JOIN client c ON c.id = u.id
			LEFT JOIN account.account a ON a.id = u.id
		SET u.active = FALSE
		WHERE c.typeFk = 'normal'
			AND a.id IS NULL
			AND u.active
			AND c.created < util.VN_CURDATE() - INTERVAL vMonths MONTH
			AND NOT u.role = (SELECT id FROM `role` WHERE name = 'supplier')
			AND u.id NOT IN (
				SELECT DISTINCT c.id
					FROM client c
						LEFT JOIN ticket t ON t.clientFk = c.id
					WHERE c.salesPersonFk IS NOT NULL
						OR t.created > util.VN_CURDATE() - INTERVAL vMonths MONTH
						OR shipped > util.VN_CURDATE() - INTERVAL vMonths MONTH
			);
END$$
DELIMITER ;