DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelving_add`(IN vShelvingFk VARCHAR(8), IN vBarcode VARCHAR(22), IN vQuantity INT, IN vPackagingFk VARCHAR(10), IN vGrouping INT, IN vPacking INT, IN vWarehouseFk INT)
BEGIN
	

/**
 * Añade registro o lo actualiza si ya existe.
 *
 * @param vShelvingFk matrícula del carro
 * @param vBarcode el id del registro
 * @param vQuantity indica la cantidad del producto
 * @param vPackagingFk el packaging del producto en itemShelving, NULL para coger el de la ultima compra
 * @param vGrouping el grouping del producto en itemShelving, NULL para coger el de la ultima compra
 * @param vPacking el packing del producto, NULL para coger el de la ultima compra
 * @param vWarehouseFk indica el sector
 * 
 **/

	DECLARE vItemFk INT;

	SELECT barcodeToItem(vBarcode) INTO vItemFk;
	
	IF vPacking IS NULL
	THEN 
		SET vPacking = itemPacking(vBarcode, vWarehouseFk);
		SET vQuantity = vQuantity * vPacking;
	END IF;

	IF (SELECT COUNT(*) FROM shelving WHERE code = vShelvingFk COLLATE utf8_unicode_ci) = 0 THEN

		INSERT IGNORE INTO parking(code) VALUES(vShelvingFk);
		INSERT INTO shelving(code, parkingFk) 
			SELECT vShelvingFk, id
				FROM parking 
				WHERE `code` = vShelvingFk COLLATE utf8_unicode_ci;

	END IF;

	IF (SELECT COUNT(*) FROM itemShelving 
			WHERE shelvingFk COLLATE utf8_unicode_ci  = vShelvingFk 
				AND itemFk  = vItemFk 
				AND packing  = vPacking) = 1 THEN

		UPDATE itemShelving
			SET visible = visible+vQuantity
			WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk AND itemFk = vItemFk AND packing = vPacking; 

	ELSE
		CALL cache.last_buy_refresh(FALSE);
		INSERT INTO itemShelving(   itemFk,
                                    shelvingFk,
                                    visible,
                                    grouping,
                                    packing,
                                    packagingFk)

		SELECT  vItemFk,
                vShelvingFk,
                vQuantity,
                IFNULL(vGrouping, b.grouping),
                IFNULL(vPacking, b.packing),
                IFNULL(vPackagingFk, b.packagingFk)
            FROM item i
				LEFT JOIN cache.last_buy lb ON i.id = lb.item_id AND lb.warehouse_id = vWarehouseFk
				LEFT JOIN buy b ON b.id = lb.buy_id
			WHERE i.id = vItemFk;
	END IF;
END$$
DELIMITER ;
