USE `vn`;
CREATE 
     OR REPLACE ALGORITHM = UNDEFINED
    DEFINER = `root`@`%` 
    SQL SECURITY DEFINER
VIEW `vn`.`zoneEstimatedDelivery` AS
    SELECT 
        `t`.`zoneFk` AS `zoneFk`,
        CAST((CURDATE() + INTERVAL ((HOUR(`zc`.`hour`) * 60) + MINUTE(`zc`.`hour`)) MINUTE)
            AS TIME) AS `hourTheoretical`,
        CAST(SUM(`sv`.`volume`) AS DECIMAL (5 , 1 )) AS `totalVolume`,
        CAST(SUM(IF((`s`.`alertLevel` < 2),
                `sv`.`volume`,
                0))
            AS DECIMAL (5 , 1 )) AS `remainingVolume`,
        GREATEST(IFNULL(`lhp`.`m3`, 0),
                IFNULL(`dl`.`minSpeed`, 0)) AS `speed`,
        CAST((`zc`.`hour` + INTERVAL ((-(SUM(IF((`s`.`alertLevel` < 2),
                `sv`.`volume`,
                0))) * 60) / GREATEST(IFNULL(`lhp`.`m3`, 0),
                    IFNULL(`dl`.`minSpeed`, 0))) MINUTE)
            AS TIME) AS `hourEffective`,
        FLOOR(((-(SUM(IF((`s`.`alertLevel` < 2),
                    `sv`.`volume`,
                    0))) * 60) / GREATEST(IFNULL(`lhp`.`m3`, 0),
                        IFNULL(`dl`.`minSpeed`, 0)))) AS `minutesLess`,
        CAST((`zc`.`hour` + INTERVAL ((-(SUM(IF((`s`.`alertLevel` < 2),
                `sv`.`volume`,
                0))) * 60) / GREATEST(IFNULL(`lhp`.`m3`, 0),
                    IFNULL(`dl`.`minSpeed`, 0))) MINUTE)
            AS TIME) AS `etc`
    FROM
        ((((((((`ticket` `t`
        JOIN `ticketStateToday` `tst` ON ((`tst`.`ticket` = `t`.`id`)))
        JOIN `state` `s` ON ((`s`.`id` = `tst`.`state`)))
        JOIN `saleVolume` `sv` ON ((`sv`.`ticketFk` = `t`.`id`)))
        LEFT JOIN `lastHourProduction` `lhp` ON ((`lhp`.`warehouseFk` = `t`.`warehouseFk`)))
        JOIN `warehouse` `w` ON ((`w`.`id` = `t`.`warehouseFk`)))
        JOIN `warehouseAlias` `wa` ON ((`wa`.`id` = `w`.`aliasFk`)))
        LEFT JOIN `zoneClosure` `zc` ON (((`zc`.`zoneFk` = `t`.`zoneFk`)
            AND (`zc`.`dated` = CURDATE()))))
        LEFT JOIN `cache`.`departure_limit` `dl` ON (((`dl`.`warehouse_id` = `t`.`warehouseFk`)
            AND (`dl`.`fecha` = CURDATE()))))
    WHERE
        ((`wa`.`name` = 'Silla')
            AND (CAST(`t`.`shipped` AS DATE) = CURDATE()))
    GROUP BY `t`.`zoneFk`;