USE vn;
DELIMITER $$
$$
CREATE OR REPLACE
ALGORITHM = UNDEFINED VIEW `vn`.`saleVolume` AS
select
    `s`.`ticketFk` AS `ticketFk`,
    `s`.`id` AS `saleFk`,
    round(`ic`.`cm3delivery` * `s`.`quantity` / 1000, 0) AS `litros`,
    `t`.`routeFk` AS `routeFk`,
    `t`.`shipped` AS `shipped`,
    `t`.`landed` AS `landed`,
    `s`.`quantity` * `ic`.`cm3delivery` / 1000000 AS `volume`,
    `s`.`quantity` * `ic`.`grams` / 1000 AS `physicalWeight`,
    `s`.`quantity` * `ic`.`cm3delivery` * greatest(`i`.`density`, 167) / 1000000 AS `weight`,
    `s`.`quantity` * `ic`.`cm3delivery` / 1000000 AS `physicalVolume`,
    `s`.`quantity` * `ic`.`cm3delivery` * ifnull(`t`.`zonePrice`, `z`.`price`) / (`vc`.`standardFlowerBox` * 1000) AS `freight`,
    `t`.`zoneFk` AS `zoneFk`,
    `t`.`clientFk` AS `clientFk`,
    `s`.`isPicked` AS `isPicked`,
    `s`.`quantity` * `s`.`price` * (100 - `s`.`discount`) / 100 AS `eurosValue`,
    `i`.`itemPackingTypeFk` AS `itemPackingTypeFk`
from
    (((((`sale` `s`
join `item` `i` on
    (`i`.`id` = `s`.`itemFk`))
join `ticket` `t` on
    (`t`.`id` = `s`.`ticketFk`))
join `zone` `z` on
    (`z`.`id` = `t`.`zoneFk`))
join `volumeConfig` `vc`)
join `itemCost` `ic` on
    (`ic`.`itemFk` = `s`.`itemFk`
        and `ic`.`warehouseFk` = `t`.`warehouseFk`))
where
    `s`.`quantity` > 0;
$$
DELIMITER ;
