USE `inventory`;
DROP PROCEDURE IF EXISTS `executeLogStatusMutasiTransaksi`;
DELIMITER //
CREATE DEFINER=`root`@`localhost` PROCEDURE `executeLogStatusMutasiTransaksi`(IN `PLIMIT` INT)
BEGIN
	DECLARE VJENIS INT;
	DECLARE VREF INT;
	DECLARE VID INT;
	DECLARE RECALC_NOT_FOUND TINYINT DEFAULT FALSE;
	
	DECLARE CR_RECALC CURSOR FOR
		SELECT ID, JENIS, REF
		FROM inventory.log_status_mutasi WHERE STATUS = 1 ORDER BY ID ASC LIMIT PLIMIT;
	DECLARE CONTINUE HANDLER FOR NOT FOUND SET RECALC_NOT_FOUND = TRUE;
	
	OPEN CR_RECALC;
	EOF: LOOP
		FETCH CR_RECALC INTO VID, VJENIS, VREF;
		
		IF RECALC_NOT_FOUND THEN
			LEAVE EOF;
		END IF;
		
		IF VJENIS = 21 THEN
			UPDATE inventory.penerimaan_barang_detil SET IS_MUTASI_FINAL = (IS_MUTASI_FINAL + 1) WHERE ID = VREF;
		END IF;
		
		IF VJENIS = 24 THEN
			UPDATE inventory.penerimaan_barang_detil SET IS_MUTASI_BATAL = (IS_MUTASI_BATAL + 1) WHERE ID = VREF;
		END IF;
		
		UPDATE inventory.log_status_mutasi SET STATUS = 2 WHERE ID = VID;
		
	END LOOP;
	CLOSE CR_RECALC;
END//
DELIMITER ;