USE `vn`;
DROP procedure IF EXISTS `ticket_withoutComponents`;
DROP procedure IF EXISTS `ticket_checkNoComponents`;

DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `ticket_checkNoComponents`(vShippedFrom DATETIME, vShippedTo DATETIME)
BEGIN

/**
 * Comprueba que los tickets entre un rango de fechas tienen componentes
 *
 * @param vDatedFrom Id del ticket
 * @param vIsTicketEditable si no se quiere forzar llamar con NULL
 */
	DECLARE v_done BOOL DEFAULT FALSE;
	DECLARE vSaleFk INTEGER;
	DECLARE vCur CURSOR FOR
	SELECT s.id
		FROM ticket t
			JOIN client clt ON clt.id = t.clientFk
			JOIN sale s ON s.ticketFk = t.id
			JOIN item i ON i.id = s.itemFk
			JOIN itemType tp ON tp.id = i.typeFk
			JOIN itemCategory ic ON ic.id = tp.categoryFk
			LEFT JOIN tmp.coste c ON c.id = s.id
		WHERE t.shipped  >= vDatedFrom AND  t.shipped  <= vDatedTo
			AND c.id IS NULL
			AND clt.isActive != 0
			AND ic.merchandise != 0
		GROUP BY s.id;
	   
	  DECLARE CONTINUE HANDLER FOR NOT FOUND
		SET v_done = TRUE; 

	DROP TEMPORARY TABLE IF EXISTS tmp.coste;

	DROP TEMPORARY TABLE IF EXISTS tmp.coste;
	CREATE TEMPORARY TABLE tmp.coste
		 (primary key (id)) ENGINE = MEMORY
		SELECT s.id
		FROM ticket t
			JOIN client clt ON clt.id = t.clientFk
			JOIN sale s ON s.ticketFk = t.id
			JOIN item i ON i.id = s.itemFk
			JOIN itemType tp ON tp.id = i.typeFk
			JOIN itemCategory ic ON ic.id = tp.categoryFk
			JOIN saleComponent sc ON sc.saleFk = s.id
			JOIN component c ON c.id = sc.componentFk
			JOIN componentType ct ON ct.id = c.typeFk AND ct.id = 1
		WHERE t.shipped  >= vDatedFrom
			AND ic.merchandise != 0;
		
	OPEN vCur;

	l: LOOP
		SET v_done = FALSE;
		FETCH vCur INTO vSaleFk;

		IF v_done THEN
			LEAVE l;
		END IF;

		CALL sale_calculateComponent(vSaleFk, 1);
	END LOOP;

	CLOSE vCur; 
	DROP TEMPORARY TABLE tmp.coste;	
 END$$

DELIMITER ;

