DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `hedera`.`order_getAvailable`(vSelf INT)
BEGIN
/**
 * Gets the available items list.
 *
 * @param vSelf The order id
 * @table tmp.itemAvailable
 */
	DECLARE vDelivery DATE;
	DECLARE vAddress INT;
	DECLARE vAgencyMode INT;

	SELECT date_send, address_id, agency_id
		INTO vDelivery, vAddress, vAgencyMode
		FROM `order`
		WHERE id = vSelf;
		
	CALL vn.available_calc(vDelivery, vAddress, vAgencyMode);

	DROP TEMPORARY TABLE IF EXISTS tmp.itemAvailable;
	CREATE TEMPORARY TABLE tmp.itemAvailable
		(INDEX (id))
		ENGINE = MEMORY
		SELECT DISTINCT a.item_id id
			FROM `cache`.available a
				JOIN tmp.availableCalc c ON c.calcFk = a.calc_id
			WHERE a.available > 0;

	DROP TEMPORARY TABLE tmp.availableCalc;
END$$
DELIMITER ;
