DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`ticket_get`(vParamFk INT)
	RETURNS int(11)
	NOT DETERMINISTIC
	READS SQL DATA
proc:BEGIN
	
	/* Devuelve el número de ticket o collection consultando en varias tablas posibles
	 * 
	 * @param vParamFk Número a validar
	 * @return vValidFk Identificador validado
	 */
	
	DECLARE vValidFk INT;

	-- Tabla vn.saleGroup
	SELECT s.ticketFk INTO vValidFk
		FROM vn.sale s
			JOIN vn.saleGroupDetail sgd ON sgd.saleFk = s.id
			JOIN vn.saleGroup sg ON sg.id = sgd.saleGroupFk 
		WHERE sg.id = vParamFk
			AND sg.created > TIMESTAMPADD(WEEK,-1, util.VN_CURDATE())
		LIMIT 1;
	
	IF vValidFk THEN
	
		RETURN vValidFk;
	
		LEAVE proc;
	
	END IF;

	-- Tabla vn.collection
	SELECT c.id INTO vValidFk
		FROM vn.collection c 
		WHERE c.id = vParamFk
			AND c.created > TIMESTAMPADD(WEEK,-1, util.VN_CURDATE());
	
	IF vValidFk THEN
	
		RETURN vValidFk;
	
		LEAVE proc;
	
	END IF;

	-- Tabla vn.ticket
	SELECT t.id INTO vValidFk
		FROM vn.ticket t
		WHERE t.id = vParamFk
			AND t.shipped > TIMESTAMPADD(WEEK,-1, util.VN_CURDATE());
	
	IF vValidFk THEN
	
		RETURN vValidFk;
	
		LEAVE proc;
	
	END IF;

	RETURN NULL;
	
END$$
DELIMITER ;
