CREATE OR REPLACE FUNCTION VALIDA_NATUREC_SPED(
   P_CDSITUTRIBITNFE VARCHAR2,
   P_CDNATUREC       IN RELACPRODITGEN.CDNATUREC%TYPE,
   P_DTEMISSAO       IN NOTAFISCAL.DTEMISSAO%TYPE,
   P_VRALIQIT        IN ITEMPROIMPOS.VRALIQITEM%TYPE) RETURN VARCHAR2
AS
   V_NATUREZA    VARCHAR2(500);
BEGIN
   /*Caso seja necessario alterar as descricoes do retorno verificar os pontos onde a funcao
     e utilizada, pois a comparacao e feita com o texto do retorno*/
   SELECT MAX(CDNATUREC)
     INTO V_NATUREZA
     FROM CODNATURECSPEDCONTR CR, CODTABELASPED CD
    WHERE CD.CDSITUTRIBITNFE = P_CDSITUTRIBITNFE
      AND CR.CDNATUREC       = P_CDNATUREC
      AND CR.CDTABELASPED    = CD.CDTABELASPED 
      AND P_DTEMISSAO BETWEEN DTINIVALID AND NVL(DTFINVALID,P_DTEMISSAO);

   IF ((V_NATUREZA IS NULL) AND (P_CDSITUTRIBITNFE IN ('04','05','06','07','08','09'))) THEN
      IF P_CDNATUREC IS NULL THEN
         V_NATUREZA := 'Natureza da Receita nao cadastrada';
      ELSE
         V_NATUREZA := 'Natureza da Receita invalida para o CST';
      END IF;
   ELSIF (((V_NATUREZA IS NULL) AND(P_CDSITUTRIBITNFE NOT IN ('04','05','06','07','08','09'))) OR (P_CDNATUREC IS NOT NULL)) THEN
      V_NATUREZA := 'CST nao exige cadastro de Natureza da Receita';
   ELSE
      V_NATUREZA := 'Valida';
   END IF;
   RETURN V_NATUREZA;
END;
/