DROP procedure IF EXISTS `vn`.`collection_faults`;

DELIMITER $$

CREATE DEFINER=`root`@`%` PROCEDURE  `vn`.`collection_faults`(
    vShelvingFk VARCHAR(10),
    vQuantity INT,
    vItemFk INT)
BEGIN
	DECLARE vQuantityTotal INT DEFAULT 0;
    DECLARE vshelve VARCHAR(2);
    DECLARE vdeep INT(11);
    DECLARE vpriority INT(11);
    DECLARE vgrouping SMALLINT(5);
    DECLARE vpacking INT(11);
    DECLARE vpackagingFk VARCHAR(10);
    DECLARE vlevel VARCHAR(45);
    DECLARE vuserFk INT(10);
    
    
    SELECT SUM(quantity),shelve,deep,priority,`grouping`,packing,packagingFk,`level`,userFk 
    INTO vQuantityTotal,vshelve,vdeep,vpriority,vgrouping,vpacking,vpackagingFk,vlevel,vuserFk 
    FROM vn.itemShelving 
    WHERE shelvingFk = vShelvingFk COLLATE utf8mb4_unicode_ci AND itemFk = vItemFk 
    GROUP BY itemFk;
    
    SELECT vQuantityTotal - vQuantity INTO vQuantityTotal;
    
    DELETE FROM vn.itemShelving WHERE shelvingFk = vShelvingFk COLLATE utf8mb4_unicode_ci AND itemFk = vItemFk;
    
    INSERT INTO vn.itemShelving (itemFk, shelvingFk,shelve,deep,quantity,visible,available,priority,`grouping`,packing,packagingFk,`level`,userFk )
    VALUES (vItemFk,vShelvingFk,vshelve,vdeep,vQuantityTotal,vQuantityTotal,vQuantityTotal,vpriority,vgrouping,vpacking,vpackagingFk,vlevel,vuserFk );
    
    SELECT * FROM vn.itemShelving
    WHERE shelvingFk = vShelvingFk COLLATE utf8mb4_unicode_ci AND itemFk = vItemFk;

END$$

DELIMITER ;