DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_addByClaim`(
	vClaimFk INT,
	vShelvingCode VARCHAR(10)
)
BEGIN
/**
 * Insert items of claim into itemShelving.
 *
 * @param vClaimFk The claim
 * @param vShelvingCode The shelving code
 * @table tmp.buyUltimate
 */
	DECLARE vWarehouseFk INT;
	DECLARE vShelvingFk INT;

	SELECT t.warehouseFk INTO vWarehouseFk
		FROM claim c
			JOIN ticket t ON t.id = c.ticketFk
		WHERE c.id = vClaimFk;

	SELECT id INTO vShelvingFk
		FROM shelving
		WHERE code COLLATE utf8_unicode_ci = vShelvingCode;

	CALL buy_getUltimate(NULL, vWarehouseFk, util.VN_CURDATE());

	INSERT INTO itemShelving (itemFk, shelvingFk, packing, `grouping`, visible)
		SELECT s.itemFk, vShelvingFk, b.packing, b.`grouping`, cb.quantity visible
			FROM claim c
				JOIN claimBeginning cb ON c.id = cb.claimFk
				JOIN sale s ON s.id = cb.saleFk
				JOIN ticket t ON t.id = s.ticketFk
				JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk
					AND bu.warehouseFk = t.warehouseFk
				JOIN buy b ON b.id = bu.buyFk
			WHERE c.id = vClaimFk;
END$$
DELIMITER ;
