USE `vn`;
DROP procedure IF EXISTS `ticketVolume`;

DELIMITER $$
USE `vn`$$
CREATE DEFINER=`root`@`%` PROCEDURE `ticketVolume`(IN vTicketId INT)
BEGIN
	DECLARE vWarehouseId INTEGER;
	DECLARE vShippedDate DATE;

	DROP TEMPORARY TABLE IF EXISTS ticketVolume;
	SELECT warehouseFk, shipped INTO vWarehouseId,vShippedDate FROM vn.ticket WHERE id = vTicketId;

	CREATE TEMPORARY TABLE IF NOT EXISTS ticketVolume ENGINE MEMORY
    
	SELECT itemFk, saleFk, quantity, concept, VolUd as m3_uni, volume as m3, volume * quantity as volumeTimesQuantity, @m3:= @m3 + ifnull(volume,0) as m3_total
		FROM
		(
			SELECT round(r.cm3 / 1000000,3) as VolUd ,s.quantity, round(r.cm3 * s.quantity / 1000000,3) as volume,
				s.itemFk, s.id AS saleFk, s.concept, @m3:= 0, @vol:=0, t.agencyModeFk
				FROM sale s
					JOIN vn.ticket t on t.id = s.ticketFk
					JOIN bi.rotacion r ON r.Id_Article = s.itemFk AND r.warehouse_id = t.warehouseFk
				WHERE s.ticketFk = vTicketId
		) sub;
END$$

DELIMITER ;