DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_setVolumeItemCost`(
	vItemFk INT
)
BEGIN
/**
 * Update the volume of tickets containing the item.
 *
 * @param vItemFk Item id
 */
	DECLARE vTicket INT;
	DECLARE vDone BOOL;

	DECLARE vTickets CURSOR FOR
		SELECT DISTINCT t.id
			FROM sale s
				JOIN ticket t ON t.id = s.ticketFk
				JOIN itemCost ic ON ic.itemFk = s.itemFk
					AND ic.warehouseFk = t.warehouseFk
			WHERE s.itemFk = vItemFk
				AND t.shipped >= util.VN_CURDATE()
				AND t.refFk IS NULL;

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;

	OPEN vTickets;
	l: LOOP
		FETCH vTickets INTO vTicket;

		IF vDone THEN
			LEAVE l;
		END IF;

		CALL ticket_setVolume(vTicket);

	END LOOP l;
	CLOSE vTickets;
END$$
DELIMITER ;
