DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`visible_getMisfit`(vSectorFk INT)
BEGIN
	
	/* Devuelve una tabla temporal con los descuadres entre el visible teórico y lo ubicado en la práctica
	 * 
	 * @param vSectorFk Identificador de vn.sector
	 * 
	 * @return tmp.stockMisfit(itemFk, visible, parked)
	 */
	
	DECLARE vCalcVisibleFk INT;
	DECLARE vWarehouseFk INT;

	SELECT warehouseFk INTO vWarehouseFk
		FROM vn.sector s 
		WHERE s.id = vSectorFk;
	
	CALL cache.visible_refresh(vCalcVisibleFk, FALSE, vWarehouseFk);

	DROP TEMPORARY TABLE IF EXISTS tmp.stockMisfit;

	CREATE TEMPORARY TABLE tmp.stockMisfit(
		itemFk INT PRIMARY KEY,
		visible INT NOT NULL DEFAULT 0,
		parked INT NOT NULL DEFAULT 0)
	ENGINE = MEMORY;

	INSERT INTO tmp.stockMisfit(itemFk, parked)
		SELECT iss.itemFk , sum(iss.visible )
			FROM vn.itemShelvingStock iss 
				JOIN vn.sector s ON s.id = iss.sectorFk 
			WHERE vSectorFk IN (s.id, s.sonFk)
			GROUP BY iss.itemFk;
			
	INSERT INTO tmp.stockMisfit(itemFk, visible)
		SELECT v.item_id , v.visible 
			FROM cache.visible v 
			WHERE v.calc_id = vCalcVisibleFk		
			ON DUPLICATE KEY UPDATE visible = v.visible;
		
	DELETE FROM tmp.stockMisfit
		WHERE visible = parked;

END$$
DELIMITER ;
