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

    SELECT vn.barcodeToItem(vBarcode) INTO vItemFk;

    SELECT itemFk INTO vItemFk
        FROM vn.buy b
        WHERE b.id = vItemFk;

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

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

    END IF;

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

        UPDATE vn.itemShelving
            SET visible = visible+vQuantity,
                created = vCreated
            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,
                                    created,
                                    `grouping`,
                                    packing,
                                    packagingFk)
            SELECT     vItemFk,
                    vShelvingFk,
                    vQuantity,
                    vCreated,
                    IF(vGrouping = 0, IFNULL(b.packing, vPacking), vGrouping) `grouping`,
                    IF(vPacking = 0, b.packing, vPacking) packing,
                    IF(vPackagingFk = '', b.packagingFk, vPackagingFk) packaging
            FROM vn.item i
                LEFT JOIN cache.last_buy lb ON i.id = lb.item_id AND lb.warehouse_id = vWarehouseFk
                LEFT JOIN vn.buy b ON b.id = lb.buy_id
            WHERE i.id = vItemFk;
    END IF;      
			
END$$
DELIMITER ;
