DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`ticket_getProblems`(
	vIsTodayRelative TINYINT(1)
)
BEGIN
/**
 * Calcula los problemas para un conjunto de tickets.
 *
 * @table tmp.ticket(ticketFk) Identificadores de los tickets a calcular
 * @return tmp.ticketProblems, tmp.saleProblems
 */
	CREATE OR REPLACE TEMPORARY TABLE tmp.sale (
		saleFk INT(11),
		PRIMARY KEY (saleFk)
	) ENGINE = MEMORY
		SELECT DISTINCT s.id saleFk 
			FROM tmp.ticket tt
				JOIN ticket t ON t.id = tt.ticketFk 
				JOIN sale s ON s.ticketFk = t.id
			WHERE t.shipped BETWEEN util.VN_CURDATE()
				AND util.dayEnd(util.VN_CURDATE() + INTERVAL IF(vIsTodayRelative, 9.9, 1.9) DAY)
			GROUP BY s.id;
		
	CALL sale_getProblems(vIsTodayRelative);

	CREATE OR REPLACE TEMPORARY TABLE tmp.ticketProblems (
		ticketFk INT(11),
		isFreezed BOOL DEFAULT FALSE,
		risk DECIMAL(10,1) DEFAULT 0,
		hasRisk BOOL DEFAULT FALSE,
		hasHighRisk BOOL DEFAULT FALSE,
		hasTicketRequest BOOL DEFAULT FALSE,
		isTaxDataChecked BOOL DEFAULT FALSE,
		isTooLittle BOOL DEFAULT FALSE,
		isVip BOOL DEFAULT FALSE,
		hasItemShortage BOOL DEFAULT FALSE,
		hasItemDelay BOOL DEFAULT FALSE,
		hasItemLost BOOL DEFAULT FALSE,
		hasComponentLack BOOL DEFAULT FALSE,
		hasRounding BOOL DEFAULT FALSE,
		PRIMARY KEY (ticketFk)
	) ENGINE = MEMORY
		SELECT tt.ticketFk,
				IF(FIND_IN_SET('isFreezed', t.problem), TRUE, FALSE) isFreezed,
				t.risk,
				IF(FIND_IN_SET('hasRisk', t.problem), TRUE, FALSE) hasRisk,
				IF(FIND_IN_SET('hasHighRisk', t.problem), TRUE, FALSE) hasHighRisk,
				IF(FIND_IN_SET('hasTicketRequest', t.problem), TRUE, FALSE) hasTicketRequest,
				IF(FIND_IN_SET('isTaxDataChecked', t.problem), FALSE, TRUE) isTaxDataChecked,
				IF(FIND_IN_SET('isTooLittle', t.problem)
					AND util.VN_NOW() < (util.VN_CURDATE() + INTERVAL HOUR(zc.`hour`) HOUR) + INTERVAL MINUTE(zc.`hour`) MINUTE,
					TRUE, FALSE) isTooLittle,
				IF(c.businessTypeFk = 'VIP', TRUE, FALSE) isVip,
				SUM(IFNULL(ts.hasItemShortage,0)) hasItemShortage,
				SUM(IFNULL(ts.hasItemDelay,0)) hasItemDelay,
				SUM(IFNULL(ts.hasItemLost,0)) hasItemLost,	
				IF(FIND_IN_SET('hasComponentLack', s.problem), TRUE, FALSE) hasComponentLack,
				SUM(IFNULL(ts.hasRounding,0)) hasRounding,
				0 totalProblems
			FROM tmp.ticket tt
				JOIN ticket t ON t.id = tt.ticketFk
				JOIN client c ON c.id = t.clientFk
				LEFT JOIN sale s ON s.ticketFk = t.id
				LEFT JOIN tmp.saleProblems ts ON ts.saleFk = s.id
				LEFT JOIN zoneClosure zc ON zc.zoneFk = t.zoneFk
					AND zc.dated = util.VN_CURDATE()
			GROUP BY t.id;
		
	UPDATE tmp.ticketProblems
		SET totalProblems = (
			(isFreezed) +
			(hasHighRisk) +
			(hasTicketRequest) +
			(!isTaxDataChecked) +
			(hasComponentLack) +
			(hasItemDelay IS NOT NULL) +
			(isTooLittle) +
			(hasItemLost IS NOT NULL) +
			(hasRounding IS NOT NULL) +
			(hasItemShortage IS NOT NULL) +
			(isVip)
		);
END$$
DELIMITER ;
