DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelving_getItemDetails`(vBarcodeItem INT, vShelvingFK VARCHAR(10) )
BEGIN

/**
 * Obtiene el precio y visible de un item
 *
 * @param vBarcodeItem barcode de artículo
 * @param vShelvingFK Ubicación actual del artículo
 */
	DECLARE vIsItem BOOL;
	DECLARE vItemFk INT;
	DECLARE vItemCost DECIMAL(10,4);
	DECLARE vCacheVisibleFk INT;
	DECLARE vWarehouseFk INT;
	DECLARE vVisible INT;


	SELECT COUNT(*)>0 INTO vIsItem 
		FROM vn.item 
		WHERE id = vBarcodeItem;

	IF NOT vIsItem THEN 

		SELECT IFNULL(b.buyingValue, 0) +
				IFNULL(b.freightValue, 0) +
				IFNULL(b.comissionValue, 0) +
				IFNULL(b.packageValue, 0),
				SUM(is2.visible) ,
				b.itemFk
				INTO vItemCost, vVisible, vItemFk
		FROM itemShelving is2
			JOIN buy b ON b.itemFk = is2.itemFk AND b.id = vBarcodeItem
		WHERE is2.shelvingFk = vShelvingFK COLLATE utf8mb3_general_ci
		GROUP BY shelvingFK;

		SELECT vItemFk itemFk, 
				vShelvingFK shelvingFk, 
				vItemCost itemCost, 
				vVisible quantity;

	END  IF;

	IF vItemCost IS NULL THEN 

		SELECT warehouseFk INTO vWarehouseFk
			FROM operator
			WHERE workerFk = account.myUser_getId();

		SELECT barcodeToItem(vBarcodeItem) INTO vItemFk;

		IF vItemFk IS NULL THEN
			CALL util.throw ('Item not valid');
		ELSE
			CALL buyUltimate(vWarehouseFk, util.VN_CURDATE());

			SELECT IFNULL(b.buyingValue, 0) +
					IFNULL(b.freightValue, 0) +
					IFNULL(b.comissionValue, 0) +
					IFNULL(b.packageValue, 0) itemCost,
					SUM(is2.visible) visible,
					is2.itemFk
					INTO vItemCost, vVisible, vItemFk
			FROM itemShelving is2 
				JOIN tmp.buyUltimate bu ON bu.itemFk = is2.itemFk 
				JOIN buy b ON b.id = bu.buyFk
			WHERE is2.itemFk  = vBarcodeItem AND
					is2.shelvingFk = vShelvingFK COLLATE utf8mb3_general_ci;

				IF vItemFk IS NULL THEN
					CALL util.throw ('Item not valid');
				ELSE
					SELECT vItemFk itemFk, 
							vShelvingFK shelvingFk, 
							vItemCost itemCost, 
							vVisible quantity;
				END IF;

			DELETE FROM tmp.buyUltimate;

		END IF;

	END IF;

	IF vItemCost IS NULL THEN
		CALL util.throw ('Item not valid');
	END IF;

END$$
DELIMITER ;