DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`travel_tree_shipment`(v_date DATE, v_consigna INT, v_agency INT, v_warehouse INT)
BEGIN
/**
* DEPRECATED usar vn.agencyHourGetLanded
* 
 * Devuelve una tabla temporal con el dia de recepcion para v_date.
 *
 * @param v_date Fecha de preparacion de mercancia
 * @param v_consigna Id de consignatario, %NULL para recogida
 * @param v_agency Id agencia
 * @table travel_tree_shipment Datos de recepción
 */
	DROP TEMPORARY TABLE IF EXISTS travel_tree_shipment;
	CREATE TEMPORARY TABLE travel_tree_shipment
	ENGINE = MEMORY
		SELECT v_warehouse warehouse_id, v_envio landing FROM (
			SELECT * FROM (
				SELECT v_warehouse, TIMESTAMPADD(DAY, subtract_day, v_date) v_envio, subtract_day, ah.max_hour
					FROM agency_hour ah
					LEFT JOIN Consignatarios c ON c.Id_Consigna = v_consigna
						WHERE (week_day = weekday(TIMESTAMPADD(DAY, subtract_day, v_date)) OR week_day IS NULL) 
							AND (ah.agency_id = v_agency OR ah.agency_id IS NULL)
							AND ah.warehouse_id = v_warehouse
							AND (ah.province_id = c.province_id OR ah.province_id IS NULL OR v_consigna IS NULL)
							ORDER BY (
							(ah.week_day IS NOT NULL) +
							(ah.agency_id IS NOT NULL) +
                            (- ah.subtract_day) +
							((ah.province_id IS NOT NULL)*3)
						) DESC
			) t
			LIMIT 1
		) t
		WHERE IF(v_date = util.VN_CURDATE(), max_hour > HOUR(util.VN_NOW()), TRUE) AND subtract_day < 225;
END$$
DELIMITER ;
