DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`recibidaIvaInsert`(IN vId INT)
BEGIN

	DECLARE vRate DOUBLE DEFAULT 1;
	DECLARE vDated DATE;

	SELECT MAX(rr.date) INTO vDated
		FROM reference_rate rr
			JOIN recibida r ON r.id = vId
		WHERE rr.date <= r.fecha 
			AND rr.moneda_id = r.moneda_id ;

	IF vDated THEN

		SELECT rate INTO vRate
			FROM reference_rate
			WHERE `date` = vDated;
	END IF;

	DELETE FROM recibida_iva WHERE recibida_id = vId;

	INSERT INTO recibida_iva(recibida_id, bi, gastos_id, divisa, taxTypeSageFk, transactionTypeSageFk)
		SELECT r.id,  
			SUM(Costefijo * Cantidad) / IFNULL(vRate,1) bi,
			6003000000,  
			IF(r.moneda_id = 1,NULL,SUM(Costefijo * Cantidad )) divisa,
			taxTypeSageFk,
			transactionTypeSageFk
			FROM recibida r 
				JOIN Entradas e ON e.recibida_id = r.id
				JOIN Proveedores p ON p.Id_Proveedor = e.Id_Proveedor
				JOIN Compres c ON c.Id_Entrada = e.Id_Entrada
				LEFT JOIN reference_rate rr ON rr.moneda_id = r.moneda_id AND rr.date = r.fecha
			WHERE r.id = vId 
			HAVING bi IS NOT NULL;

END$$
DELIMITER ;
