DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`available_calc`(
	vDate DATE,
    vAddress INT,
    vAgencyMode INT)
BEGIN
/**
 * Calculates the available for all available stores
 * according to the given parameters.
 *
 * @param vDate The delivery date
 * @param vAddress The delivery address id
 * @param vAgencyMode The shipping agency
 * @return tmp.availableCalc(calcFk) The available cache ids
 */
	DECLARE vCalcFk INT;
	DECLARE vShipment DATE;
	DECLARE vWarehouse INT;
	DECLARE vDone BOOL;

	DECLARE cWarehouses CURSOR FOR
		SELECT warehouseFk, shipped FROM tmp.zoneGetShipped;
			
	DECLARE CONTINUE HANDLER FOR NOT FOUND
		SET vDone = TRUE;

	-- Establecemos los almacenes y las fechas que van a entrar al disponible

	CALL vn.zone_getShipped (vDate, vAddress, vAgencyMode, FALSE);

	DROP TEMPORARY TABLE IF EXISTS tmp.availableCalc;
	CREATE TEMPORARY TABLE tmp.availableCalc(	
		calcFk INT UNSIGNED,
		PRIMARY KEY (calcFk)
	)
	ENGINE = MEMORY;

	OPEN cWarehouses;

	l: LOOP
		SET vDone = FALSE;
		FETCH cWarehouses INTO vWarehouse, vShipment;
		
		IF vDone THEN
			LEAVE l;
		END IF;

		CALL `cache`.available_refresh(vCalcFk, FALSE, vWarehouse, vShipment);

		INSERT IGNORE INTO tmp.availableCalc
			SET calcFk = vCalcFk;
	END LOOP;

	CLOSE cWarehouses;
	DROP TEMPORARY TABLE tmp.zoneGetShipped;
END$$
DELIMITER ;
