
DROP procedure IF EXISTS `vn`.`zoneGetWarehouse`;

DELIMITER $$
CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`zoneGetWarehouse`(vAddress INT, vLanded DATE, vWarehouse INT)
BEGIN
/**
* Devuelve el listado de agencias disponibles para la fecha,
 * dirección y warehouse pasadas
 * 
 * @param vAddress
 * @param vWarehouse warehouse
 * @param vLanded Fecha de recogida
 * @select Listado de agencias disponibles
 */
 
 	DECLARE vPostalCode varchar(10);

	SELECT postalCode INTO vPostalCode 
		FROM address WHERE id = vAddress;
	SELECT * FROM (
		SELECT * FROM (
			SELECT am.id agencyModeFk, 
					am.name agencyMode, 
					am.description, 
					am.deliveryMethodFk,
					TIMESTAMPADD(DAY,-z.travelingDays, vLanded) shipped, 
					z.warehouseFk,
					zi.isIncluded,
                    z.id zoneFk
				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
					JOIN agencyMode am ON am.id = z.agencyModeFk
				WHERE zgSon.`name` LIKE vPostalCode
					AND delivered = vLanded
					AND z.warehouseFk = vWarehouse
					AND IF(TIMESTAMPADD(DAY,-z.travelingDays, vLanded) = CURDATE(), hour(now()) < hour(z.`hour`),TRUE)
				ORDER BY z.id, zgFather.depth DESC) t 
			GROUP BY zoneFk 
			HAVING isIncluded > 0) t
		GROUP BY agencyModeFk;

END$$

DELIMITER ;

