
USE `vn`;
DROP procedure IF EXISTS `vn`.`zoneGetFirstShipped`;

DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetFirstShipped__`(vAgencyModeFk INT, vAddress INT, vWarehouseFk INT)
BEGIN
/**
* Devuelve la primera fecha de envio disponible para una agencia en una direccion y un warehouse
*
* @param vAgencyMode id de la agencia en  vn.agencyMode
* @param vAddress id de la direccion
* @param vWarehouse id del warehouse
* @return vShipped la primera fecha disponible y vLanded la fecha de llegada/recojida
*/    


	DECLARE vGeoFk INT;
    
    SELECT p.geoFk INTO vGeoFk
		FROM address a 
			JOIN town t ON t.provinceFk = a.provinceFk
			JOIN postCode p ON p.townFk = t.id AND p.code = a.postalCode
	WHERE a.id = vAddress
	ORDER BY (a.city SOUNDS LIKE t.`name`) DESC
	LIMIT 1;

	SELECT * FROM (
		SELECT TIMESTAMPADD(DAY,-z.travelingDays, zc.delivered) shipped, 
				zc.delivered landed, 
                zi.isIncluded
			FROM zoneGeo zgSon
				JOIN zoneGeo zgFather ON zgSon.lft BETWEEN zgFather.lft AND zgFather.rgt
				JOIN zoneIncluded zi ON zi.geoFk = zgFather.id
				JOIN zone z ON z.id = zi.zoneFk
				JOIN zoneCalendar zc ON zc.zoneFk = z.id
			WHERE zgSon.`id` = vGeoFk
                AND z.agencyModeFk = vAgencyModeFk
                AND  z.warehouseFk = vWarehouseFk
                AND TIMESTAMPADD(DAY,-z.travelingDays, zc.delivered) >= CURDATE()
				AND IF(TIMESTAMPADD(DAY,-z.travelingDays, zc.delivered) = CURDATE(), hour(now()) < hour(z.`hour`),TRUE)
			ORDER BY landed ASC, zgFather.depth DESC) t 
		HAVING isIncluded > 0 LIMIT 1;
END$$

DELIMITER ;
;
