DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`travel_upcomingArrivals`(
    vWarehouseFk INT,
    vDate DATETIME
)
BEGIN
/**
 * Procedure to track and organize the movement of items between warehouses,
 * where 'warehouseINFk' is @vWarehouseFk.
 * Uses temporary tables to process and store the travel data of the items.
 *
 * @params vWarehouseFk warehouse id
 * @params vDate selected landed date
 * @return tmp.itemTravel
 */
	DECLARE vTravelFk INT;
	DECLARE vWarehouseOutFk INT;
	DECLARE vShipment DATETIME;
	DECLARE vDateStart DATETIME;

	CREATE OR REPLACE TEMPORARY TABLE tTravelTop
        (PRIMARY KEY (wh_in,wh_out,landing,shipment))
            ENGINE = MEMORY
            SELECT 0 id,
                vWarehouseFk wh_in,
                vWarehouseFk wh_out,
                FALSE ok,
                vDate landing,
                vDate shipment;

	REPEAT
		SET vTravelFk = NULL;

		SELECT id,
                wh_out,
                shipment,
                landing
			    INTO vTravelFk,
                vWarehouseOutFk,
                vShipment,
                vDateStart
			FROM tTravelTop 
            WHERE ok = FALSE LIMIT 1;

		UPDATE tTravelTop 
            SET ok = TRUE 
            WHERE id = vTravelFk;

		INSERT IGNORE INTO tTravelTop
            SELECT id, 
                    vWarehouseFk,
                    warehouseOutFk,
                    FALSE,
                    IF(vTravelFk, vDateStart, landed),
                    shipped shipment
                FROM travel
                WHERE warehouseOutFk = vWarehouseOutFk
                    AND IF(vTravelFk, landed <= vShipment, landed >= vShipment)
                    AND shipped >= util.VN_CURDATE()
                    AND NOT isDelivered;
	UNTIL vTravelFk IS NULL END REPEAT;

	DELETE FROM tTravelTop WHERE id = 0;

	CREATE OR REPLACE TEMPORARY TABLE tmp.itemTravel
        (KEY (wh))
        ENGINE = MEMORY
        SELECT * 
            FROM (
                SELECT wh_out wh,
                        landing
                    FROM tTravelTop
                    WHERE wh_out <> vWarehouseFk
                    ORDER BY landing
                    LIMIT 10000000000000000000
            ) t
        GROUP BY wh;

	DROP TEMPORARY TABLE tTravelTop;
END$$
DELIMITER ;
