salix/db/changes/10100-AllSaints/02-zoneGetShippedWarehouse_...

55 lines
1.6 KiB
SQL

USE `vn`;
DROP procedure IF EXISTS `vn`.`zoneGetShippedWarehouse`;
DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetShippedWarehouse__`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT)
BEGIN
/**
* Devuelve la mínima fecha de envío para cada warehouse
*
* @param vLanded La fecha de recepcion
* @param vAddressFk Id del consignatario
* @param vAgencyModeFk Id de la agencia
* @return tmp.zoneGetShipped
*/
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 = vAddressFk
ORDER BY (a.city SOUNDS LIKE t.`name`) DESC
LIMIT 1;
DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetShipped;
CREATE TEMPORARY TABLE tmp.zoneGetShipped
ENGINE = MEMORY
SELECT * FROM (
SELECT * FROM (
SELECT z.id,
TIMESTAMPADD(DAY,-z.travelingDays, vLanded) shipped,
zi.isIncluded,z.warehouseFk
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 zc.delivered = vLanded
AND z.agencyModeFk = vAgencyModeFk
AND IF(TIMESTAMPADD(DAY,-z.travelingDays, vLanded) = CURDATE(), hour(now()) < hour(z.`hour`),TRUE)
ORDER BY z.id, shipped ASC, zgFather.depth DESC, zi.isIncluded DESC) t
GROUP BY warehouseFk, id
HAVING isIncluded > 0
ORDER BY shipped) t
GROUP BY warehouseFk;
END$$
DELIMITER ;
;