USE `inventory`;
-- --------------------------------------------------------
-- Versi server:                 8.0.11 - MySQL Community Server - GPL
-- OS Server:                    Win64
-- HeidiSQL Versi:               9.2.0.4947
-- --------------------------------------------------------


-- Dumping structure for function inventory.getHargaPenerimaanTerakhir
DROP FUNCTION IF EXISTS `getHargaPenerimaanTerakhir`;
DELIMITER //
CREATE DEFINER=`root`@`localhost` FUNCTION `getHargaPenerimaanTerakhir`(`PBARANG` INT
) RETURNS decimal(20,2)
    DETERMINISTIC
BEGIN
	DECLARE VHRG DECIMAL(20,2);
	
	SELECT pbd.HARGA INTO VHRG 
	FROM inventory.penerimaan_barang_detil pbd
		, inventory.penerimaan_barang pb
	WHERE pbd.BARANG=PBARANG AND pbd.PENERIMAAN=pb.ID AND pbd.`STATUS` = 2
	ORDER BY pb.TANGGAL DESC LIMIT 1;
	
	IF FOUND_ROWS() > 0 THEN
		RETURN VHRG;
	ELSE
		SELECT d.HARGA INTO VHRG
		FROM inventory.hibah h
			, inventory.hibah_detil d
		WHERE d.HIBAH = h.ID AND d.BARANG = PBARANG and h.`STATUS` = 2 AND h.JENIS = 1
		ORDER BY h.TANGGAL DESC LIMIT 1;
		IF FOUND_ROWS() > 0 THEN
			RETURN VHRG;
		ELSE
			SELECT h.HARGA INTO VHRG
				FROM inventory.harga_estimasi_barang h WHERE h.BARANG=PBARANG AND h.`STATUS` = 1 ORDER BY h.UPDATE_TIME DESC LIMIT 1;
			IF FOUND_ROWS() > 0 THEN
				RETURN VHRG;
			ELSE
				RETURN 0;
			END IF;
		END IF;
	END IF;
END//
DELIMITER ;
