DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelvingMatch`(vEntryFk INT, vAllTravel BOOLEAN, vFromTimed DATETIME, vToTimed DATETIME)
BEGIN

	DECLARE vTravelFk INT;
    
    SELECT travelFk INTO vTravelFk 
		FROM entry 
        WHERE id = vEntryFk;

	SELECT i.id, i.longName, i.size, i.subName, b.stickers, ish.etiquetas, b.printed
		FROM item i
		JOIN (
					SELECT itemFk, sum(stickers) AS stickers, sum(printedStickers) as printed
						FROM buy b
							JOIN entry e ON e.id = b.entryFk
						WHERE IF(vAllTravel , travelFk = vTravelFk, b.entryFk = vEntryFk)
						GROUP BY itemFk
				  ) b ON b.itemFk = i.id
		LEFT JOIN (
					SELECT itemFk, sum(cast(visible / packing AS DECIMAL(10,0))) AS etiquetas 
						FROM itemShelving ish
							JOIN shelving sh ON sh.code = ish.shelvingFk
                            LEFT JOIN parking pk ON pk.id = sh.parkingFk
						WHERE ish.created BETWEEN vFromTimed AND vToTimed
						GROUP BY itemFk
				  ) ish ON ish.itemFk = id
		WHERE b.stickers OR ish.etiquetas;

END$$
DELIMITER ;
