CREATE OR REPLACE PROCEDURE CONSULTA_CFOP(
	P_ENTSAICFOP  IN CODFISCOPER.IDENTSAICFOP%TYPE,
	P_EMPRESA     IN CODFISCOPER.CDEMPRESA%TYPE,
	P_CDARVPROD   IN PRODUTO.CDARVPROD%TYPE,
	P_INSCESTA    IN CODFISCOPER.CDINSCESTA%TYPE,
  	P_TIPOOPER    IN CODFISCOPER.CDTIPOOPER%TYPE,
	P_PAISORIG    IN PAIS.CDPAIS%TYPE,
	P_ESTAORIG    IN ESTADO.SGESTADO%TYPE,
	P_PAISDEST    IN PAIS.CDPAIS%TYPE,
	P_ESTADEST    IN ESTADO.SGESTADO%TYPE,
   P_FILIAL      IN VARCHAR2,
   P_LANCTONF    IN VARCHAR2,
   P_CDGRUPOFISC IN CODFISCOPER.CDGRUPOFISC%TYPE,
   P_DTVALIDCFOP IN CODFISCOPER.DTVALIDCFOP%TYPE,
   P_IDORIGEMPROD IN VARCHAR2 DEFAULT 'N')

IS

   V_SEQUENCIA      VARCHAR2(02);
   V_CFOP1DIGT      VARCHAR2(1);
   V_CDARVPROD      VARCHAR2(20);
   V_CONTADOR       NUMBER;
   V_CDGRUPOFISC CODFISCOPER.CDGRUPOFISC%TYPE;
   V_COUNTMENS      INTEGER;
   V_DSMENSCFOP     VARCHAR2(120);
   V_IDINTEREST     VARCHAR2(01);
   V_IDENDCFOP      VARCHAR2(01);
   V_CDEMPRESA      VARCHAR2(02);
   V_CDINSCESTA     VARCHAR2(16);
   V_INIVALID       DATE;
   V_PAISORIG       VARCHAR2(04); -- Pais de origem (utiliza UF de Origem)
   V_ESTAORIG       VARCHAR2(02); -- Estado de origem (utiliza UF de Origem)
   V_MUNIORIG       VARCHAR2(04); -- Municipio de origem (utiliza municipio)
   V_PAISDEST       VARCHAR2(04);
   V_ESTADEST       VARCHAR2(02);
   V_MUNIDEST       VARCHAR2(04);
   V_IDORIGDESTNF   VARCHAR2(01);
   V_CDCLIENTE      CLIENTE.CDCLIENTE%TYPE;
   V_CDORIGDESTNF   VARCHAR2(21);
   V_IDENDEMIS      VARCHAR2(01);
   V_CDFILIRECE     VARCHAR2(04);
   V_CDFORNECED     FORNECEDOR.CDFORNECED%TYPE;
   V_CDFILIEMIT     VARCHAR2(04);
   V_VRITEM         FLOAT;
   V_EXISTE         INTEGER;
   V_ORIGDESTOP     VARCHAR2(01);
BEGIN

   DELETE CFOPTEMP
   WHERE NRCFOPTEMP = P_FILIAL||P_LANCTONF;

   V_IDINTEREST := 'N';
   V_CONTADOR   := 0;

	IF (P_ENTSAICFOP = 'E') THEN
		IF P_PAISORIG = P_PAISDEST THEN
			IF P_ESTAORIG = P_ESTADEST THEN
				V_CFOP1DIGT := '1';
			ELSE
				V_CFOP1DIGT := '2';
			END IF;
		ELSE
			V_CFOP1DIGT := '3';
         V_IDINTEREST := 'S';
		END IF;
 	ELSE
		IF P_PAISORIG = P_PAISDEST THEN
			IF P_ESTAORIG = P_ESTADEST THEN
				V_CFOP1DIGT := '5';
			ELSE
				V_CFOP1DIGT := '6';
			END IF;
		ELSE
			V_CFOP1DIGT := '7';
         V_IDINTEREST := 'S';
		END IF;
	END IF;

	V_SEQUENCIA := '01';


/* Retorna o grupo fiscal para as operacoes interestaduais */
   IF V_CFOP1DIGT = '2' OR
      V_CFOP1DIGT = '6' THEN
      SELECT SUBSTR(DSPARGERFIS,3,3)
      INTO V_CDGRUPOFISC
      FROM PARAMGERAL;

      V_IDINTEREST := 'S';
   END IF;

   IF  (V_CDGRUPOFISC IS NULL) or (V_CDGRUPOFISC = '') THEN
       V_CDGRUPOFISC := P_CDGRUPOFISC;
   END IF;

   Begin
      SELECT N.DTENTRSAID,   N.CDFILIEMIT,   N.IDORIGDESTNF,   N.CDCLIENTE,
             N.CDFILIRECE,   N.CDFORNECED, (IT.VRTOTAITEM - IT.VRDESCITEM)
        INTO V_INIVALID,   V_CDFILIEMIT, V_IDORIGDESTNF, V_CDCLIENTE,
             V_CDFILIRECE, V_CDFORNECED, V_VRITEM
      FROM NOTAFISCAL N, ITEMPRODUTO IT, PRODUTO P
      WHERE N.CDFILIAL = P_FILIAL
        AND N.NRLANCTONF = P_LANCTONF
        AND N.CDFILIAL = IT.CDFILIAL
        AND N.NRLANCTONF = IT.NRLANCTONF
        AND IT.CDPRODUTO = P.CDPRODUTO
        AND P.CDARVPROD  = P_CDARVPROD
        AND ROWNUM = '1';
   Exception
      When No_Data_Found Then
         V_INIVALID  := Null; V_CDFILIEMIT  := Null; V_IDORIGDESTNF:= Null; V_CDCLIENTE:= Null;
         V_CDFILIRECE := Null; V_CDFORNECED:= Null; V_VRITEM := 0;
   End;

   IF (P_ENTSAICFOP = 'S') THEN
      Begin
         SELECT NVL(MAX(IDENDCFOPFIL),'I'), MAX(CDEMPRESA),   MAX(CDINSCESTA)
         INTO   V_IDENDCFOP,           V_CDEMPRESA, V_CDINSCESTA
         FROM FILIAL
         WHERE (CDFILIAL = V_CDFILIEMIT);
      Exception
         When No_Data_Found Then
            V_IDENDCFOP:= 'I'; V_CDEMPRESA:= Null; V_CDINSCESTA:= Null;
      End;

      IF V_IDENDCFOP = 'I' THEN
         Begin
            SELECT MAX(CDPAIS), MAX(SGESTADO)  , MAX(CDMUNICIPIO)
            INTO   V_PAISORIG, V_ESTAORIG, V_MUNIORIG
            FROM INSCRESTAD
            WHERE CDEMPRESA  = P_EMPRESA AND
                  CDINSCESTA = P_INSCESTA;
         Exception
            When No_Data_Found Then
               V_PAISORIG := Null; V_ESTAORIG := Null; V_MUNIORIG := Null;
         End;
      ELSE
         Begin
            SELECT MAX(CDPAIS)    , MAX(SGESTADO)  , MAX(CDMUNICIPIO)
            INTO   V_PAISORIG, V_ESTAORIG, V_MUNIORIG
            FROM ENDEFILI
            WHERE (CDFILIAL     = V_CDFILIEMIT) AND
                  (IDTPENDEFILI = V_IDENDCFOP);
         Exception
            When No_Data_Found Then
               V_PAISORIG := Null; V_ESTAORIG := Null; V_MUNIORIG := Null;
         End;
      END IF;

      /*DESTINATARIO-REMETENTE DA NOTA*/
      IF V_IDORIGDESTNF IS NULL THEN
         Begin
            SELECT MAX(IDORIGDESTOP)
            INTO   V_ORIGDESTOP
            FROM TIPOOPERAC
            WHERE IDENTRSAIDOP = 'S' AND
                  CDTIPOOPER   = P_TIPOOPER;
         Exception
            When No_Data_Found Then
               V_ORIGDESTOP := Null;
         End;
      ELSE
         V_ORIGDESTOP := V_IDORIGDESTNF;
      END IF;

      IF V_ORIGDESTOP = 'L' THEN /*DESTINATARIO -> FILIAL */
         V_CDORIGDESTNF := V_CDFILIRECE;

         Begin
            SELECT NVL(MAX(IDENDCFOPFIL),'I'), NVL(MAX(IDENDEMISFIL),'I'), MAX(CDEMPRESA)  , MAX(CDINSCESTA)
            INTO   V_IDENDCFOP          , V_IDENDEMIS          , V_CDEMPRESA, V_CDINSCESTA
            FROM FILIAL
            WHERE (CDFILIAL = V_CDFILIRECE);
         Exception
            When No_Data_Found Then
               V_IDENDCFOP := 'I'; V_IDENDEMIS := 'I'; V_CDEMPRESA := Null; V_CDINSCESTA := Null;
         End;

         IF V_IDENDEMIS = 'I' THEN
            Begin
               SELECT MAX(CDPAIS)    , MAX(SGESTADO) , MAX(CDMUNICIPIO)
               INTO   V_PAISDEST, V_ESTADEST, V_MUNIDEST
               FROM INSCRESTAD
               WHERE CDEMPRESA  = P_EMPRESA AND
                     CDINSCESTA = P_INSCESTA;
            Exception
               When No_Data_Found Then
                  V_PAISDEST := Null; V_ESTADEST := Null; V_MUNIDEST := Null;
            End;
         ELSE
            Begin
               SELECT MAX(CDPAIS)    , MAX(SGESTADO)  , MAX(CDMUNICIPIO)
               INTO   V_PAISDEST, V_ESTADEST, V_MUNIDEST
               FROM ENDEFILI
               WHERE CDFILIAL     = V_CDFILIRECE AND
                     IDTPENDEFILI = V_IDENDEMIS;
            Exception
               When No_Data_Found Then
                  V_PAISDEST := Null; V_ESTADEST := Null; V_MUNIDEST := Null;
            End;
         END IF;
      ELSIF V_ORIGDESTOP = 'F' THEN /*DESTINATARIO -> FORNECEDOR */
         V_CDORIGDESTNF := V_CDFORNECED;
         Begin
            SELECT NVL(MAX(IDENDCFOPFOR),'P'), NVL(MAX(IDENDEMISFOR),'P')
            INTO   V_IDENDCFOP          , V_IDENDEMIS
            FROM FORNECEDOR
            WHERE (CDFORNECED = V_CDORIGDESTNF);
         Exception
            When No_Data_Found Then
               V_IDENDCFOP := 'P'; V_IDENDEMIS := 'P';
         End;

         Begin
            SELECT MAX(CDPAIS),     MAX(SGESTADO),   MAX(CDMUNICIPIO)
            INTO   V_PAISDEST, V_ESTADEST, V_MUNIDEST
            FROM ENDEFORN
            WHERE (CDFORNECED   = V_CDORIGDESTNF) AND
                  (IDTPENDEFORN = V_IDENDEMIS);
         Exception
            When No_Data_Found Then
               V_PAISDEST := Null; V_ESTADEST := Null; V_MUNIDEST := Null;
         End;
      ELSE /*DESTINATARIO -> CLIENTE(DEFAULT) */
         V_CDORIGDESTNF := V_CDCLIENTE;
         Begin
            SELECT NVL(MAX(IDENDCFOPCLI),'P'), NVL(MAX(IDENDEMISCLI),'P')
            INTO   V_IDENDCFOP          , V_IDENDEMIS
            FROM CLIENTE
            WHERE (CDCLIENTE = V_CDORIGDESTNF);
         Exception
            When No_Data_Found Then
               V_IDENDCFOP := 'P'; V_IDENDEMIS := 'P';
         End;

         IF V_IDENDCFOP = 'I' THEN
            Begin
               SELECT MAX(CDPAIS)    , MAX(SGESTADO), MAX(CDMUNICIPIO)
               INTO   V_PAISDEST, V_ESTADEST, V_MUNIDEST
               FROM INSCRESTAD
               WHERE CDEMPRESA  = P_EMPRESA AND
                     CDINSCESTA = P_INSCESTA;
            Exception
               When No_Data_Found Then
                  V_PAISDEST := Null; V_ESTADEST := Null;  V_MUNIDEST := Null;
            End;
         ELSE

            Begin
               SELECT MAX(CDPAIS)    , MAX(SGESTADO)  , MAX(CDMUNICIPIO)
               INTO   V_PAISDEST, V_ESTADEST, V_MUNIDEST
               FROM ENDECLIE
               WHERE (CDCLIENTE    = V_CDORIGDESTNF) AND
                     (IDTPENDECLIE = V_IDENDEMIS);
            Exception
               When No_Data_Found Then
                  V_PAISDEST := Null; V_ESTADEST := Null; V_MUNIDEST := Null;
            End;
         END IF;
      END IF;
   END IF;

   IF (P_ENTSAICFOP = 'E') THEN
      Begin
         SELECT NVL(MAX(IDENDCFOPFIL),'I'), MAX(CDEMPRESA),   MAX(CDINSCESTA)
         INTO   V_IDENDCFOP,           V_CDEMPRESA, V_CDINSCESTA
         FROM FILIAL
         WHERE (CDFILIAL = V_CDFILIRECE);
      Exception
         When No_Data_Found Then
            V_IDENDCFOP:= 'I'; V_CDEMPRESA:= Null; V_CDINSCESTA:= Null;
      End;

      Begin
         SELECT MAX(CDPAIS)    , MAX(SGESTADO)  , MAX(CDMUNICIPIO)
         INTO   V_PAISDEST, V_ESTADEST, V_MUNIDEST
         FROM INSCRESTAD
         WHERE CDEMPRESA  = P_EMPRESA AND
               CDINSCESTA = P_INSCESTA;
      Exception
         When No_Data_Found Then
            V_PAISDEST := Null; V_ESTADEST := Null; V_MUNIDEST := Null;
      End;

      /*DESTINATARIO-REMETENTE DA NOTA*/
      IF V_IDORIGDESTNF IS NULL THEN
         Begin
            SELECT NVL(MAX(IDORIGDESTOP), 'F')
            INTO   V_ORIGDESTOP
            FROM TIPOOPERAC
            WHERE IDENTRSAIDOP = 'E' AND
                 CDTIPOOPER   = P_TIPOOPER;
         Exception
            When No_Data_Found Then
               V_ORIGDESTOP := Null;
         End;
      ELSE
        V_ORIGDESTOP := V_IDORIGDESTNF;
      END IF;

      IF V_ORIGDESTOP = 'L' THEN /*Remetente -> FILIAL */
         V_CDORIGDESTNF := V_CDFILIEMIT;

         Begin
            SELECT NVL(MAX(IDENDCFOPFIL),'I'), NVL(MAX(IDENDEMISFIL),'I'), MAX(CDEMPRESA)  , MAX(CDINSCESTA)
            INTO   V_IDENDCFOP          , V_IDENDEMIS          , V_CDEMPRESA, V_CDINSCESTA
            FROM FILIAL
            WHERE (CDFILIAL = V_CDFILIEMIT);
         Exception
            When No_Data_Found Then
               V_IDENDCFOP := 'I'; V_IDENDEMIS := 'I'; V_CDEMPRESA := Null; V_CDINSCESTA := Null;
         End;

         IF V_IDENDEMIS = 'I' THEN
            Begin
               SELECT MAX(CDPAIS)    , MAX(SGESTADO)  , MAX(CDMUNICIPIO)
               INTO   V_PAISORIG, V_ESTAORIG, V_MUNIORIG
               FROM INSCRESTAD
               WHERE CDEMPRESA  = V_CDEMPRESA AND
                     CDINSCESTA = V_CDINSCESTA;
            Exception
               When No_Data_Found Then
                  V_PAISORIG := Null; V_ESTAORIG := Null; V_MUNIORIG := Null;
            End;
         ELSE
            Begin
               SELECT MAX(CDPAIS)    , MAX(SGESTADO)  , MAX(CDMUNICIPIO)
               INTO   V_PAISORIG, V_ESTAORIG, V_MUNIORIG
               FROM ENDEFILI
               WHERE CDFILIAL     = V_CDFILIEMIT AND
                     IDTPENDEFILI = V_IDENDEMIS;
            Exception
               When No_Data_Found Then
                  V_PAISORIG := Null; V_ESTAORIG := Null; V_MUNIORIG := Null;
            End;
         END IF;
      ELSIF V_ORIGDESTOP = 'F' THEN /*DESTINATARIO -> FORNECEDOR */
         V_CDORIGDESTNF := V_CDFORNECED;
         Begin
            SELECT NVL(MAX(IDENDCFOPFOR),'P'), NVL(MAX(IDENDEMISFOR),'P')
            INTO   V_IDENDCFOP          , V_IDENDEMIS
            FROM FORNECEDOR
            WHERE (CDFORNECED = V_CDORIGDESTNF);
         Exception
            When No_Data_Found Then
               V_IDENDCFOP := 'P'; V_IDENDEMIS := 'P';
         End;

         Begin
            SELECT MAX(CDPAIS)    , MAX(SGESTADO)  , MAX(CDMUNICIPIO)
            INTO   V_PAISORIG, V_ESTAORIG, V_MUNIORIG
            FROM ENDEFORN
            WHERE (CDFORNECED   = V_CDORIGDESTNF) AND
                  (IDTPENDEFORN = V_IDENDCFOP);
         Exception
            When No_Data_Found Then
               V_PAISORIG := Null; V_ESTAORIG := Null; V_MUNIORIG := Null;
         End;
      ELSE /*DESTINATARIO -> CLIENTE */
         V_CDORIGDESTNF := V_CDCLIENTE;
         Begin
            SELECT NVL(MAX(IDENDCFOPCLI),'P'), NVL(MAX(IDENDEMISCLI),'P')
            INTO   V_IDENDCFOP          , V_IDENDEMIS
            FROM CLIENTE
            WHERE (CDCLIENTE = V_CDORIGDESTNF);
         Exception
            When No_Data_Found Then
               V_IDENDCFOP := 'P'; V_IDENDEMIS := 'P';
         End;

         IF V_IDENDCFOP = 'I' THEN
            Begin
               SELECT MAX(CDPAIS)    , MAX(SGESTADO), MAX(CDMUNICIPIO)
               INTO   V_PAISORIG, V_ESTAORIG, V_MUNIORIG
               FROM INSCRESTAD
               WHERE CDEMPRESA  = P_EMPRESA AND
                     CDINSCESTA = P_INSCESTA;
            Exception
               When No_Data_Found Then
                  V_PAISORIG := Null; V_ESTAORIG := Null; V_MUNIORIG := Null;
            End;
         ELSE

            Begin
               SELECT MAX(CDPAIS), MAX(SGESTADO), MAX(CDMUNICIPIO)
               INTO   V_PAISORIG, V_ESTAORIG, V_MUNIORIG
               FROM ENDECLIE
               WHERE (CDCLIENTE    = V_CDORIGDESTNF) AND
                     (IDTPENDECLIE = V_IDENDEMIS);
            Exception
               When No_Data_Found Then
                  V_PAISORIG := Null; V_ESTAORIG := Null; V_MUNIORIG := Null;
            End;
         END IF;
      END IF;
   END IF;

   FOR C_REGRA IN (SELECT DISTINCT CDREGRAFISC, CDFISCOPER, IDDIFEALIQ, IDDIFALIQCUSPR, IDTIPOREGISTRO, IDMENSAGEM, CDCLASFISC, IDCFOPINTEREST, CDPRODUTO
                     FROM TABLE(CONSULTA_REGRA_FISCAL(null, P_EMPRESA, V_CDGRUPOFISC, P_ENTSAICFOP, P_TIPOOPER, P_INSCESTA, P_CDARVPROD, P_DTVALIDCFOP,
                                                      P_PAISORIG, P_ESTAORIG, NULL, P_PAISDEST, P_ESTADEST, NULL, 0, 'S', P_IDORIGEMPROD))
                    WHERE CDFISCOPER IS NOT NULL) LOOP
      IF (C_REGRA.CDFISCOPER IS NOT NULL) THEN
         IF C_REGRA.IDMENSAGEM = 'S' THEN 
            IF C_REGRA.IDTIPOREGISTRO = 'PAD' THEN
               FOR C_MSGREGRA IN (SELECT *
                                    FROM MSGCFOPADRAO
                                   WHERE CDREGRAFISC = C_REGRA.CDREGRAFISC
                                     AND IDCFOPINTEREST = C_REGRA.IDCFOPINTEREST) LOOP
                  INSERT INTO CFOPTEMP
                     (NRCFOPTEMP, NRSEQUCFOP, CDFISOPETMP, CDSUFCFOPTMP,
                      DSCFOPTMP, DSMENSCFOTMP, DTVDCFOPTMP, IDDIFALIQTMP,
                      IDDIFALIQCUSPRC, CDREGRATMP)
                  VALUES
                     (P_FILIAL||P_LANCTONF, V_SEQUENCIA, V_CFOP1DIGT||C_REGRA.CDFISCOPER, NULL,
                      SUBSTR(DESCRICAO_CFOP(V_CFOP1DIGT||C_REGRA.CDFISCOPER),1,50), C_MSGREGRA.DSMENSAGEM, NULL, C_REGRA.IDDIFEALIQ,
                      C_REGRA.IDDIFALIQCUSPR, C_REGRA.CDREGRAFISC);

                  V_SEQUENCIA := LPAD(RTRIM(V_SEQUENCIA + '01'),2,0);
               END LOOP;
            ELSE
               IF C_REGRA.IDTIPOREGISTRO = 'NCM' THEN
                  FOR C_MSGREGRA IN (SELECT *
                                       FROM MSGCFOPNCM
                                      WHERE CDREGRAFISC = C_REGRA.CDREGRAFISC
                                        AND CDCLASFISC = C_REGRA.CDCLASFISC
                                        AND IDCFOPINTEREST = C_REGRA.IDCFOPINTEREST) LOOP
                     INSERT INTO CFOPTEMP
                        (NRCFOPTEMP, NRSEQUCFOP, CDFISOPETMP, CDSUFCFOPTMP,
                         DSCFOPTMP, DSMENSCFOTMP, DTVDCFOPTMP, IDDIFALIQTMP,
                         IDDIFALIQCUSPRC, CDREGRATMP)
                     VALUES
                        (P_FILIAL||P_LANCTONF, V_SEQUENCIA, V_CFOP1DIGT||C_REGRA.CDFISCOPER, NULL,
                         SUBSTR(DESCRICAO_CFOP(V_CFOP1DIGT||C_REGRA.CDFISCOPER),1,50), C_MSGREGRA.DSMENSAGEM, NULL, C_REGRA.IDDIFEALIQ,
                         C_REGRA.IDDIFALIQCUSPR, C_REGRA.CDREGRAFISC);

                     V_SEQUENCIA := LPAD(RTRIM(V_SEQUENCIA + '01'),2,0);
                  END LOOP;
               ELSE
                  IF C_REGRA.IDTIPOREGISTRO = 'PROD' THEN
                     FOR C_MSGREGRA IN (SELECT *
                                          FROM MSGCFOPREGFISC
                                         WHERE CDREGRAFISC = C_REGRA.CDREGRAFISC
                                           AND CDPRODUTO = C_REGRA.CDPRODUTO) LOOP
                        INSERT INTO CFOPTEMP
                           (NRCFOPTEMP, NRSEQUCFOP, CDFISOPETMP, CDSUFCFOPTMP,
                            DSCFOPTMP, DSMENSCFOTMP, DTVDCFOPTMP, IDDIFALIQTMP,
                            IDDIFALIQCUSPRC, CDREGRATMP)
                        VALUES
                           (P_FILIAL||P_LANCTONF, V_SEQUENCIA, V_CFOP1DIGT||C_REGRA.CDFISCOPER, NULL,
                            SUBSTR(DESCRICAO_CFOP(V_CFOP1DIGT||C_REGRA.CDFISCOPER),1,50), C_MSGREGRA.DSMENSAGEM, NULL, C_REGRA.IDDIFEALIQ,
                            C_REGRA.IDDIFALIQCUSPR, C_REGRA.CDREGRAFISC);

                        V_SEQUENCIA := LPAD(RTRIM(V_SEQUENCIA + '01'),2,0);
                     END LOOP;
                  END IF;
               END IF;
            END IF;
         ELSE
            INSERT INTO CFOPTEMP
               (NRCFOPTEMP, NRSEQUCFOP, CDFISOPETMP, CDSUFCFOPTMP,
                DSCFOPTMP, DSMENSCFOTMP, DTVDCFOPTMP, IDDIFALIQTMP,
                IDDIFALIQCUSPRC, CDREGRATMP)
            VALUES
               (P_FILIAL||P_LANCTONF, V_SEQUENCIA, V_CFOP1DIGT||C_REGRA.CDFISCOPER, NULL,
                SUBSTR(DESCRICAO_CFOP(V_CFOP1DIGT||C_REGRA.CDFISCOPER),1,50), NULL, NULL, C_REGRA.IDDIFEALIQ,
                C_REGRA.IDDIFALIQCUSPR, C_REGRA.CDREGRAFISC);

            V_SEQUENCIA := LPAD(RTRIM(V_SEQUENCIA + '01'),2,0);
         END IF;

      END IF;
   END LOOP;

   V_EXISTE := 0;

   SELECT COUNT(*)
     INTO V_EXISTE
     FROM CFOPTEMP
    WHERE NRCFOPTEMP = P_FILIAL||P_LANCTONF
      AND CDREGRATMP IS NOT NULL;

   IF NOT(V_EXISTE > 0) THEN
      IF V_IDINTEREST = 'S' THEN
         IF V_CDGRUPOFISC IS NOT NULL THEN
            IF P_CDARVPROD IS NOT NULL THEN
               SELECT MAX(P.CDARVPROD), COUNT(*)
               INTO V_CDARVPROD, V_CONTADOR
               FROM CODFISCOPER C, PRODUTO P
               WHERE (IDENTSAICFOP = P_ENTSAICFOP)    AND
                     (CDEMPRESA    = P_EMPRESA)       AND
                     (CDTIPOOPER   = P_TIPOOPER)      AND
                     (CDINSCESTA   = P_INSCESTA)      AND
                     (CDGRUPOFISC  = V_CDGRUPOFISC)   AND
                     (IDCFOPINTEREST = 'S')           AND
                     (C.CDPRODUTO  = P.CDPRODUTO(+))  AND
                     (INSTR(P_CDARVPROD,NVL(RTRIM(P.CDARVPROD),P_CDARVPROD)) = 1);
            ELSE
               SELECT MAX(C.CDPRODUTO), COUNT(*)
               INTO V_CDARVPROD, V_CONTADOR
               FROM CODFISCOPER C
               WHERE (IDENTSAICFOP = P_ENTSAICFOP)    AND
                     (CDEMPRESA    = P_EMPRESA)       AND
                     (CDTIPOOPER   = P_TIPOOPER)      AND
                     (CDINSCESTA   = P_INSCESTA)      AND
                     (CDGRUPOFISC  = V_CDGRUPOFISC)   AND
                     (IDCFOPINTEREST = 'S')           AND
                     (CDPRODUTO   IS NULL);
            END IF;
         END IF;

         IF V_CONTADOR > 0 THEN
            IF NOT (V_CDARVPROD IS NULL) THEN
               FOR C_CFOP IN
                  (SELECT CDFISCOPER, DSCDFISCOPER, CDSUFXCFOP, DSMENSCFOP,DTVALIDCFOP,
                          DECODE(V_CFOP1DIGT,'2',IDDIFEALIQ,'6',IDDIFEALIQ,NULL) AS IDDIFEALIQ,
                          DECODE(V_CFOP1DIGT,'2',IDDIFALIQCUSPR,'6',IDDIFALIQCUSPR,'N') AS IDDIFALIQCUSPR,
                          CDMENSAGEM
                   FROM CODFISCOPER C, MENSCFOP M, PRODUTO P
                   WHERE (C.IDENTSAICFOP = P_ENTSAICFOP)     AND
                         (C.CDEMPRESA    = P_EMPRESA)        AND
                         (C.CDTIPOOPER   = P_TIPOOPER)       AND
                         (C.CDINSCESTA   = P_INSCESTA)       AND
                         (C.CDGRUPOFISC  = V_CDGRUPOFISC)    AND
                         (IDCFOPINTEREST = 'S')              AND
                         (C.NRINCIDCFOP  = M.NRINCIDCFOP(+)) AND
                         (C.CDPRODUTO    = P.CDPRODUTO(+))   AND
                         (P.CDARVPROD    = V_CDARVPROD)      AND
                         (C.DTVALIDCFOP  = (SELECT MAX(DTVALIDCFOP)
                                            FROM CODFISCOPER C, PRODUTO P
                                            WHERE (C.IDENTSAICFOP = P_ENTSAICFOP)     AND
                                                  (C.CDEMPRESA    = P_EMPRESA)        AND
                                                  (C.CDTIPOOPER   = P_TIPOOPER)       AND
                                                  (C.CDINSCESTA   = P_INSCESTA)       AND
                                                  (C.CDGRUPOFISC  = V_CDGRUPOFISC)    AND
                                                  (IDCFOPINTEREST = 'S')              AND
                                                  (C.CDPRODUTO    = P.CDPRODUTO(+))   AND
                                                  (P.CDARVPROD    = V_CDARVPROD)      AND
                                                  (C.DTVALIDCFOP <= P_DTVALIDCFOP)))) LOOP

                  SELECT COUNT(*)
                    INTO V_COUNTMENS
                    FROM MENSAGEM
                   WHERE CDMENSAGEM = C_CFOP.CDMENSAGEM
                     AND IDSITUACAOMENS = 'I';

                  IF V_COUNTMENS > 0 THEN
                     V_DSMENSCFOP := NULL;
                  ELSE
                     V_DSMENSCFOP := C_CFOP.DSMENSCFOP;
                  END IF;

                  INSERT INTO CFOPTEMP(NRCFOPTEMP, NRSEQUCFOP, CDFISOPETMP, CDSUFCFOPTMP,
                                       DSCFOPTMP, DSMENSCFOTMP, DTVDCFOPTMP, IDDIFALIQTMP,
                                       IDDIFALIQCUSPRC)
                  VALUES(P_FILIAL||P_LANCTONF, V_SEQUENCIA, V_CFOP1DIGT||C_CFOP.CDFISCOPER, C_CFOP.CDSUFXCFOP,
                         SUBSTR(C_CFOP.DSCDFISCOPER, 1, 50), V_DSMENSCFOP, C_CFOP.DTVALIDCFOP, C_CFOP.IDDIFEALIQ,
                         C_CFOP.IDDIFALIQCUSPR);

                  V_SEQUENCIA := LPAD(RTRIM(V_SEQUENCIA + '01'),2,0);
               END LOOP;
            ELSIF (V_CDARVPROD IS NULL) THEN
               FOR C_CFOPNULL IN
                  (SELECT CDFISCOPER, DSCDFISCOPER, CDSUFXCFOP, DSMENSCFOP, DTVALIDCFOP,
                          DECODE(V_CFOP1DIGT,'2',IDDIFEALIQ,'6',IDDIFEALIQ,NULL) AS IDDIFEALIQ,
                          DECODE(V_CFOP1DIGT,'2',IDDIFALIQCUSPR,'6',IDDIFALIQCUSPR,'N') AS IDDIFALIQCUSPR,
                          CDMENSAGEM
                   FROM CODFISCOPER C, MENSCFOP M
                   WHERE (C.IDENTSAICFOP = P_ENTSAICFOP)     AND
                         (C.CDEMPRESA    = P_EMPRESA)        AND
                         (C.CDTIPOOPER   = P_TIPOOPER)       AND
                         (C.CDINSCESTA   = P_INSCESTA)       AND
                         (C.CDGRUPOFISC  = V_CDGRUPOFISC)    AND
                         (IDCFOPINTEREST = 'S')              AND
                         (C.NRINCIDCFOP  = M.NRINCIDCFOP(+)) AND
                         (C.CDPRODUTO IS NULL)               AND
                         (C.DTVALIDCFOP  = (SELECT MAX(DTVALIDCFOP)
                                            FROM CODFISCOPER C
                                            WHERE (C.IDENTSAICFOP = P_ENTSAICFOP)     AND
                                                  (C.CDEMPRESA    = P_EMPRESA)        AND
                                                  (C.CDTIPOOPER   = P_TIPOOPER)       AND
                                                  (C.CDINSCESTA   = P_INSCESTA)       AND
                                                  (C.CDGRUPOFISC  = V_CDGRUPOFISC)    AND
                                                  (IDCFOPINTEREST = 'S')              AND
                                                  (C.CDPRODUTO   IS NULL)             AND
                                                  (C.DTVALIDCFOP <= P_DTVALIDCFOP)))) LOOP

                   SELECT COUNT(*)
                     INTO V_COUNTMENS
                     FROM MENSAGEM
                    WHERE CDMENSAGEM = C_CFOPNULL.CDMENSAGEM
                      AND IDSITUACAOMENS = 'I';

                   IF V_COUNTMENS > 0 THEN
                      V_DSMENSCFOP := NULL;
                   ELSE
                      V_DSMENSCFOP := C_CFOPNULL.DSMENSCFOP;
                   END IF;

                  INSERT INTO CFOPTEMP(NRCFOPTEMP, NRSEQUCFOP, CDFISOPETMP, CDSUFCFOPTMP,
                                       DSCFOPTMP, DSMENSCFOTMP, DTVDCFOPTMP, IDDIFALIQTMP,
                                       IDDIFALIQCUSPRC)
                  VALUES(P_FILIAL||P_LANCTONF, V_SEQUENCIA, V_CFOP1DIGT||C_CFOPNULL.CDFISCOPER, C_CFOPNULL.CDSUFXCFOP,
                         SUBSTR(C_CFOPNULL.DSCDFISCOPER, 1, 50), V_DSMENSCFOP, C_CFOPNULL.DTVALIDCFOP, C_CFOPNULL.IDDIFEALIQ,
                         C_CFOPNULL.IDDIFALIQCUSPR);

                  V_SEQUENCIA := LPAD(RTRIM(V_SEQUENCIA + '01'),2,0);
               END LOOP;
            END IF;

         ELSE
            IF P_CDARVPROD IS NOT NULL THEN
               SELECT MAX(P.CDARVPROD) INTO V_CDARVPROD
               FROM CODFISCOPER C, PRODUTO P
               WHERE (IDENTSAICFOP = P_ENTSAICFOP)    AND
                     (CDEMPRESA    = P_EMPRESA)       AND
                     (CDTIPOOPER   = P_TIPOOPER)      AND
                     (CDINSCESTA   = P_INSCESTA)      AND
                     (CDGRUPOFISC IS NULL)            AND
                     (IDCFOPINTEREST = 'S')           AND
                     (C.CDPRODUTO  = P.CDPRODUTO(+))  AND
                     (INSTR(P_CDARVPROD,NVL(RTRIM(P.CDARVPROD),P_CDARVPROD)) = 1);
            ELSE
               SELECT MAX(C.CDPRODUTO) INTO V_CDARVPROD
               FROM CODFISCOPER C
               WHERE (IDENTSAICFOP = P_ENTSAICFOP)    AND
                     (CDEMPRESA    = P_EMPRESA)       AND
                     (CDTIPOOPER   = P_TIPOOPER)      AND
                     (CDINSCESTA   = P_INSCESTA)      AND
                     (CDGRUPOFISC IS NULL)            AND
                     (IDCFOPINTEREST = 'S')           AND
                     (CDPRODUTO IS NULL);
            END IF;
            IF NOT (V_CDARVPROD IS NULL) THEN
               FOR C_CFOP IN
                  (SELECT CDFISCOPER, SUBSTR(DSCDFISCOPER, 1, 50) DSCDFISCOPER, CDSUFXCFOP, DSMENSCFOP, DTVALIDCFOP,
                          DECODE(V_CFOP1DIGT,'2',IDDIFEALIQ,'6',IDDIFEALIQ,NULL) AS IDDIFEALIQ,
                          DECODE(V_CFOP1DIGT,'2',IDDIFALIQCUSPR,'6',IDDIFALIQCUSPR,'N') AS IDDIFALIQCUSPR,
                          CDMENSAGEM
                   FROM CODFISCOPER C, MENSCFOP M, PRODUTO P
                   WHERE (C.IDENTSAICFOP = P_ENTSAICFOP)     AND
                         (C.CDEMPRESA    = P_EMPRESA)        AND
                         (C.CDTIPOOPER   = P_TIPOOPER)       AND
                         (C.CDINSCESTA   = P_INSCESTA)       AND
                         (C.NRINCIDCFOP  = M.NRINCIDCFOP(+)) AND
                         (C.CDGRUPOFISC IS NULL)             AND
                         (IDCFOPINTEREST = 'S')              AND
                         (C.CDPRODUTO    = P.CDPRODUTO(+))   AND
                         (P.CDARVPROD    = V_CDARVPROD)      AND
                         (C.DTVALIDCFOP  = (SELECT MAX(DTVALIDCFOP)
                                            FROM CODFISCOPER C, PRODUTO P
                                            WHERE (C.IDENTSAICFOP = P_ENTSAICFOP)     AND
                                                  (C.CDEMPRESA    = P_EMPRESA)        AND
                                                  (C.CDTIPOOPER   = P_TIPOOPER)       AND
                                                  (C.CDINSCESTA   = P_INSCESTA)       AND
                                                  (C.CDGRUPOFISC  IS NULL)            AND
                                                  (IDCFOPINTEREST = 'S')              AND
                                                  (C.CDPRODUTO    = P.CDPRODUTO(+))   AND
                                                  (P.CDARVPROD    = V_CDARVPROD)      AND
                                                  (C.DTVALIDCFOP <= P_DTVALIDCFOP)))) LOOP

                  SELECT COUNT(*)
                    INTO V_COUNTMENS
                    FROM MENSAGEM
                   WHERE CDMENSAGEM = C_CFOP.CDMENSAGEM
                     AND IDSITUACAOMENS = 'I';

                  IF V_COUNTMENS > 0 THEN
                     V_DSMENSCFOP := NULL;
                  ELSE
                     V_DSMENSCFOP := C_CFOP.DSMENSCFOP;
                  END IF;

                  INSERT INTO CFOPTEMP(NRCFOPTEMP, NRSEQUCFOP, CDFISOPETMP, CDSUFCFOPTMP,
                                       DSCFOPTMP, DSMENSCFOTMP, DTVDCFOPTMP, IDDIFALIQTMP,
                                       IDDIFALIQCUSPRC)
                  VALUES(P_FILIAL||P_LANCTONF, V_SEQUENCIA, V_CFOP1DIGT||C_CFOP.CDFISCOPER, C_CFOP.CDSUFXCFOP,
                         SUBSTR(C_CFOP.DSCDFISCOPER, 1, 50), V_DSMENSCFOP, C_CFOP.DTVALIDCFOP, C_CFOP.IDDIFEALIQ,
                         C_CFOP.IDDIFALIQCUSPR);

                  V_SEQUENCIA := LPAD(RTRIM(V_SEQUENCIA + '01'),2,0);
               END LOOP;
            ELSIF (V_CDARVPROD IS NULL) THEN
               FOR C_CFOPNULL IN
                  (SELECT CDFISCOPER, SUBSTR(DSCDFISCOPER, 1, 50) DSCDFISCOPER, CDSUFXCFOP, DSMENSCFOP, DTVALIDCFOP,
                          DECODE(V_CFOP1DIGT,'2',IDDIFEALIQ,'6',IDDIFEALIQ,NULL) AS IDDIFEALIQ,
                          DECODE(V_CFOP1DIGT,'2',IDDIFALIQCUSPR,'6',IDDIFALIQCUSPR,'N') AS IDDIFALIQCUSPR,
                          CDMENSAGEM
                   FROM CODFISCOPER C, MENSCFOP M
                   WHERE (C.IDENTSAICFOP = P_ENTSAICFOP)     AND
                         (C.CDEMPRESA    = P_EMPRESA)        AND
                         (C.CDTIPOOPER   = P_TIPOOPER)       AND
                         (C.CDINSCESTA   = P_INSCESTA)       AND
                         (C.NRINCIDCFOP  = M.NRINCIDCFOP(+)) AND
                         (C.CDGRUPOFISC IS NULL)             AND
                         (IDCFOPINTEREST = 'S')              AND
                         (C.CDPRODUTO IS NULL)               AND
                         (C.DTVALIDCFOP  = (SELECT MAX(DTVALIDCFOP)
                                            FROM CODFISCOPER C
                                            WHERE (C.IDENTSAICFOP = P_ENTSAICFOP)     AND
                                                  (C.CDEMPRESA    = P_EMPRESA)        AND
                                                  (C.CDTIPOOPER   = P_TIPOOPER)       AND
                                                  (C.CDINSCESTA   = P_INSCESTA)       AND
                                                  (C.CDGRUPOFISC  IS NULL)            AND
                                                  (IDCFOPINTEREST = 'S')              AND
                                                  (C.CDPRODUTO    IS NULL)            AND
                                                  (C.DTVALIDCFOP <= P_DTVALIDCFOP)))) LOOP

                  SELECT COUNT(*)
                    INTO V_COUNTMENS
                    FROM MENSAGEM
                   WHERE CDMENSAGEM = C_CFOPNULL.CDMENSAGEM
                     AND IDSITUACAOMENS = 'I';

                  IF V_COUNTMENS > 0 THEN
                     V_DSMENSCFOP := NULL;
                  ELSE
                     V_DSMENSCFOP := C_CFOPNULL.DSMENSCFOP;
                  END IF;

                  INSERT INTO CFOPTEMP(NRCFOPTEMP, NRSEQUCFOP, CDFISOPETMP, CDSUFCFOPTMP,
                                       DSCFOPTMP, DSMENSCFOTMP, DTVDCFOPTMP, IDDIFALIQTMP,
                                       IDDIFALIQCUSPRC)
                  VALUES(P_FILIAL||P_LANCTONF, V_SEQUENCIA, V_CFOP1DIGT||C_CFOPNULL.CDFISCOPER, C_CFOPNULL.CDSUFXCFOP,
                         SUBSTR(C_CFOPNULL.DSCDFISCOPER, 1, 50), V_DSMENSCFOP, C_CFOPNULL.DTVALIDCFOP, C_CFOPNULL.IDDIFEALIQ,
                         C_CFOPNULL.IDDIFALIQCUSPR);

                  V_SEQUENCIA := LPAD(RTRIM(V_SEQUENCIA + '01'),2,0);
               END LOOP;
            END IF;
         END IF;
      END IF;
      /**************************************************************/

      SELECT COUNT(*)
        INTO V_CONTADOR
        FROM CFOPTEMP
       WHERE NRCFOPTEMP = P_FILIAL||P_LANCTONF;

      IF V_CONTADOR = 0 THEN
         V_IDINTEREST := 'N';
      END IF;

      IF V_IDINTEREST = 'N' THEN
         IF V_CDGRUPOFISC IS NOT NULL THEN
            IF P_CDARVPROD IS NOT NULL THEN
               SELECT MAX(P.CDARVPROD), COUNT(*)
               INTO V_CDARVPROD, V_CONTADOR
               FROM CODFISCOPER C, PRODUTO P
               WHERE (IDENTSAICFOP = P_ENTSAICFOP)    AND
                     (CDEMPRESA    = P_EMPRESA)       AND
                     (CDTIPOOPER   = P_TIPOOPER)      AND
                     (CDINSCESTA   = P_INSCESTA)      AND
                     (CDGRUPOFISC  = V_CDGRUPOFISC)   AND
                     (IDCFOPINTEREST = 'N')           AND
                     (C.CDPRODUTO  = P.CDPRODUTO(+))  AND
                     (INSTR(P_CDARVPROD,NVL(RTRIM(P.CDARVPROD),P_CDARVPROD)) = 1);
            ELSE
               SELECT MAX(C.CDPRODUTO), COUNT(*)
               INTO V_CDARVPROD, V_CONTADOR
               FROM CODFISCOPER C
               WHERE (IDENTSAICFOP = P_ENTSAICFOP)    AND
                     (CDEMPRESA    = P_EMPRESA)       AND
                     (CDTIPOOPER   = P_TIPOOPER)      AND
                     (CDINSCESTA   = P_INSCESTA)      AND
                     (CDGRUPOFISC  = V_CDGRUPOFISC)   AND
                     (IDCFOPINTEREST = 'N')           AND
                     (CDPRODUTO  IS NULL);
            END IF;
         END IF;

         IF V_CONTADOR > 0 THEN
            IF NOT (V_CDARVPROD IS NULL) THEN
               FOR C_CFOP IN
                  (SELECT CDFISCOPER, SUBSTR(DSCDFISCOPER, 1, 50) DSCDFISCOPER, CDSUFXCFOP, DSMENSCFOP, DTVALIDCFOP,
                          DECODE(V_CFOP1DIGT,'2',IDDIFEALIQ,'6',IDDIFEALIQ,NULL) AS IDDIFEALIQ,
                          DECODE(V_CFOP1DIGT,'2',IDDIFALIQCUSPR,'6',IDDIFALIQCUSPR,'N') AS IDDIFALIQCUSPR,
                          CDMENSAGEM
                   FROM CODFISCOPER C, MENSCFOP M, PRODUTO P
                   WHERE (C.IDENTSAICFOP = P_ENTSAICFOP)     AND
                         (C.CDEMPRESA    = P_EMPRESA)        AND
                         (C.CDTIPOOPER   = P_TIPOOPER)       AND
                         (C.CDINSCESTA   = P_INSCESTA)       AND
                         (C.CDGRUPOFISC  = V_CDGRUPOFISC)    AND
                         (IDCFOPINTEREST = 'N')              AND
                         (C.NRINCIDCFOP  = M.NRINCIDCFOP(+)) AND
                         (C.CDPRODUTO    = P.CDPRODUTO(+))   AND
                         (P.CDARVPROD    = V_CDARVPROD)      AND
                         (C.DTVALIDCFOP  = (SELECT MAX(DTVALIDCFOP)
                                            FROM CODFISCOPER C, PRODUTO P
                                            WHERE (C.IDENTSAICFOP = P_ENTSAICFOP)     AND
                                                  (C.CDEMPRESA    = P_EMPRESA)        AND
                                                  (C.CDTIPOOPER   = P_TIPOOPER)       AND
                                                  (C.CDINSCESTA   = P_INSCESTA)       AND
                                                  (C.CDGRUPOFISC  = V_CDGRUPOFISC)    AND
                                                  (IDCFOPINTEREST = 'N')              AND
                                                  (C.CDPRODUTO    = P.CDPRODUTO(+))   AND
                                                  (P.CDARVPROD    = V_CDARVPROD)      AND
                                                  (C.DTVALIDCFOP <= P_DTVALIDCFOP)))) LOOP

                  SELECT COUNT(*)
                    INTO V_COUNTMENS
                    FROM MENSAGEM
                   WHERE CDMENSAGEM = C_CFOP.CDMENSAGEM
                     AND IDSITUACAOMENS = 'I';

                  IF V_COUNTMENS > 0 THEN
                     V_DSMENSCFOP := NULL;
                  ELSE
                     V_DSMENSCFOP := C_CFOP.DSMENSCFOP;
                  END IF;

                  INSERT INTO CFOPTEMP(NRCFOPTEMP, NRSEQUCFOP, CDFISOPETMP, CDSUFCFOPTMP,
                                       DSCFOPTMP, DSMENSCFOTMP, DTVDCFOPTMP, IDDIFALIQTMP,
                                       IDDIFALIQCUSPRC)
                  VALUES(P_FILIAL||P_LANCTONF, V_SEQUENCIA, V_CFOP1DIGT||C_CFOP.CDFISCOPER, C_CFOP.CDSUFXCFOP,
                         SUBSTR(C_CFOP.DSCDFISCOPER, 1, 50), V_DSMENSCFOP, C_CFOP.DTVALIDCFOP, C_CFOP.IDDIFEALIQ,
                         C_CFOP.IDDIFALIQCUSPR);

                  V_SEQUENCIA := LPAD(RTRIM(V_SEQUENCIA + '01'),2,0);
               END LOOP;
            ELSIF (V_CDARVPROD IS NULL) THEN
               FOR C_CFOPNULL IN
                  (SELECT CDFISCOPER, SUBSTR(DSCDFISCOPER, 1, 50) DSCDFISCOPER, CDSUFXCFOP, DSMENSCFOP, DTVALIDCFOP,
                          DECODE(V_CFOP1DIGT,'2',IDDIFEALIQ,'6',IDDIFEALIQ,NULL) AS IDDIFEALIQ,
                          DECODE(V_CFOP1DIGT,'2',IDDIFALIQCUSPR,'6',IDDIFALIQCUSPR,'N') AS IDDIFALIQCUSPR,
                          CDMENSAGEM
                   FROM CODFISCOPER C, MENSCFOP M
                   WHERE (C.IDENTSAICFOP = P_ENTSAICFOP)     AND
                         (C.CDEMPRESA    = P_EMPRESA)        AND
                         (C.CDTIPOOPER   = P_TIPOOPER)       AND
                         (C.CDINSCESTA   = P_INSCESTA)       AND
                         (C.CDGRUPOFISC  = V_CDGRUPOFISC)    AND
                         (IDCFOPINTEREST = 'N')              AND
                         (C.NRINCIDCFOP  = M.NRINCIDCFOP(+)) AND
                         (C.CDPRODUTO IS NULL)               AND
                         (C.DTVALIDCFOP  = (SELECT MAX(DTVALIDCFOP)
                                            FROM CODFISCOPER C
                                            WHERE (C.IDENTSAICFOP = P_ENTSAICFOP)     AND
                                                  (C.CDEMPRESA    = P_EMPRESA)        AND
                                                  (C.CDTIPOOPER   = P_TIPOOPER)       AND
                                                  (C.CDINSCESTA   = P_INSCESTA)       AND
                                                  (C.CDGRUPOFISC  = V_CDGRUPOFISC)    AND
                                                  (IDCFOPINTEREST = 'N')              AND
                                                  (C.CDPRODUTO   IS NULL)             AND
                                                  (C.DTVALIDCFOP <= P_DTVALIDCFOP)))) LOOP

                  SELECT COUNT(*)
                    INTO V_COUNTMENS
                    FROM MENSAGEM
                   WHERE CDMENSAGEM = C_CFOPNULL.CDMENSAGEM
                     AND IDSITUACAOMENS = 'I';

                  IF V_COUNTMENS > 0 THEN
                     V_DSMENSCFOP := NULL;
                  ELSE
                     V_DSMENSCFOP := C_CFOPNULL.DSMENSCFOP;
                  END IF;

                  INSERT INTO CFOPTEMP(NRCFOPTEMP, NRSEQUCFOP, CDFISOPETMP, CDSUFCFOPTMP,
                                       DSCFOPTMP, DSMENSCFOTMP, DTVDCFOPTMP, IDDIFALIQTMP,
                                       IDDIFALIQCUSPRC)
                  VALUES(P_FILIAL||P_LANCTONF, V_SEQUENCIA, V_CFOP1DIGT||C_CFOPNULL.CDFISCOPER, C_CFOPNULL.CDSUFXCFOP,
                         SUBSTR(C_CFOPNULL.DSCDFISCOPER, 1, 50), V_DSMENSCFOP, C_CFOPNULL.DTVALIDCFOP, C_CFOPNULL.IDDIFEALIQ,
                         C_CFOPNULL.IDDIFALIQCUSPR);

                  V_SEQUENCIA := LPAD(RTRIM(V_SEQUENCIA + '01'),2,0);
               END LOOP;
            END IF;

         ELSE
            IF P_CDARVPROD IS NOT NULL THEN
               SELECT MAX(P.CDARVPROD) INTO V_CDARVPROD
               FROM CODFISCOPER C, PRODUTO P
               WHERE (IDENTSAICFOP = P_ENTSAICFOP)    AND
                     (CDEMPRESA    = P_EMPRESA)       AND
                     (CDTIPOOPER   = P_TIPOOPER)      AND
                     (CDINSCESTA   = P_INSCESTA)      AND
                     (CDGRUPOFISC IS NULL)            AND
                     (IDCFOPINTEREST = 'N')           AND
                     (C.CDPRODUTO  = P.CDPRODUTO(+))  AND
                     (INSTR(P_CDARVPROD,NVL(RTRIM(P.CDARVPROD),P_CDARVPROD)) = 1);
            ELSE
               SELECT MAX(C.CDPRODUTO) INTO V_CDARVPROD
               FROM CODFISCOPER C
               WHERE (IDENTSAICFOP = P_ENTSAICFOP)    AND
                     (CDEMPRESA    = P_EMPRESA)       AND
                     (CDTIPOOPER   = P_TIPOOPER)      AND
                     (CDINSCESTA   = P_INSCESTA)      AND
                     (CDGRUPOFISC IS NULL)            AND
                     (IDCFOPINTEREST = 'N')           AND
                     (C.CDPRODUTO  IS NULL);
            END IF;

            IF NOT (V_CDARVPROD IS NULL) THEN
               FOR C_CFOP IN
                  (SELECT CDFISCOPER, SUBSTR(DSCDFISCOPER, 1, 50) DSCDFISCOPER, CDSUFXCFOP, DSMENSCFOP, DTVALIDCFOP,
                          DECODE(V_CFOP1DIGT,'2',IDDIFEALIQ,'6',IDDIFEALIQ,NULL) AS IDDIFEALIQ,
                          DECODE(V_CFOP1DIGT,'2',IDDIFALIQCUSPR,'6',IDDIFALIQCUSPR,'N') AS IDDIFALIQCUSPR,
                          CDMENSAGEM
                   FROM CODFISCOPER C, MENSCFOP M, PRODUTO P
                   WHERE (C.IDENTSAICFOP = P_ENTSAICFOP)     AND
                         (C.CDEMPRESA    = P_EMPRESA)        AND
                         (C.CDTIPOOPER   = P_TIPOOPER)       AND
                         (C.CDINSCESTA   = P_INSCESTA)       AND
                         (C.NRINCIDCFOP  = M.NRINCIDCFOP(+)) AND
                         (C.CDGRUPOFISC IS NULL)             AND
                         (IDCFOPINTEREST = 'N')              AND
                         (C.CDPRODUTO    = P.CDPRODUTO(+))   AND
                         (P.CDARVPROD    = V_CDARVPROD)      AND
                         (C.DTVALIDCFOP  = (SELECT MAX(DTVALIDCFOP)
                                            FROM CODFISCOPER C, PRODUTO P
                                            WHERE (C.IDENTSAICFOP = P_ENTSAICFOP)     AND
                                                  (C.CDEMPRESA    = P_EMPRESA)        AND
                                                  (C.CDTIPOOPER   = P_TIPOOPER)       AND
                                                  (C.CDINSCESTA   = P_INSCESTA)       AND
                                                  (C.CDGRUPOFISC  IS NULL)            AND
                                                  (IDCFOPINTEREST = 'N')              AND
                                                  (C.CDPRODUTO    = P.CDPRODUTO(+))   AND
                                                  (P.CDARVPROD    = V_CDARVPROD)      AND
                                                  (C.DTVALIDCFOP <= P_DTVALIDCFOP)))) LOOP

                  SELECT COUNT(*)
                    INTO V_COUNTMENS
                    FROM MENSAGEM
                   WHERE CDMENSAGEM = C_CFOP.CDMENSAGEM
                     AND IDSITUACAOMENS = 'I';

                  IF V_COUNTMENS > 0 THEN
                     V_DSMENSCFOP := NULL;
                  ELSE
                     V_DSMENSCFOP := C_CFOP.DSMENSCFOP;
                  END IF;

                  INSERT INTO CFOPTEMP(NRCFOPTEMP, NRSEQUCFOP, CDFISOPETMP, CDSUFCFOPTMP,
                                       DSCFOPTMP, DSMENSCFOTMP, DTVDCFOPTMP, IDDIFALIQTMP,
                                       IDDIFALIQCUSPRC)
                  VALUES(P_FILIAL||P_LANCTONF, V_SEQUENCIA, V_CFOP1DIGT||C_CFOP.CDFISCOPER, C_CFOP.CDSUFXCFOP,
                         SUBSTR(C_CFOP.DSCDFISCOPER, 1, 50), V_DSMENSCFOP, C_CFOP.DTVALIDCFOP, C_CFOP.IDDIFEALIQ,
                         C_CFOP.IDDIFALIQCUSPR);

                  V_SEQUENCIA := LPAD(RTRIM(V_SEQUENCIA + '01'),2,0);
               END LOOP;
            ELSIF (V_CDARVPROD IS NULL) THEN
               FOR C_CFOPNULL IN
                  (SELECT CDFISCOPER, SUBSTR(DSCDFISCOPER, 1, 50) DSCDFISCOPER, CDSUFXCFOP, DSMENSCFOP, DTVALIDCFOP,
                          DECODE(V_CFOP1DIGT,'2',IDDIFEALIQ,'6',IDDIFEALIQ,NULL) AS IDDIFEALIQ,
                          DECODE(V_CFOP1DIGT,'2',IDDIFALIQCUSPR,'6',IDDIFALIQCUSPR,'N') AS IDDIFALIQCUSPR,
                          CDMENSAGEM
                   FROM CODFISCOPER C, MENSCFOP M
                   WHERE (C.IDENTSAICFOP = P_ENTSAICFOP)     AND
                         (C.CDEMPRESA    = P_EMPRESA)        AND
                         (C.CDTIPOOPER   = P_TIPOOPER)       AND
                         (C.CDINSCESTA   = P_INSCESTA)       AND
                         (C.NRINCIDCFOP  = M.NRINCIDCFOP(+)) AND
                         (C.CDGRUPOFISC IS NULL)             AND
                         (IDCFOPINTEREST = 'N')              AND
                         (C.CDPRODUTO IS NULL)               AND
                         (C.DTVALIDCFOP  = (SELECT MAX(DTVALIDCFOP)
                                            FROM CODFISCOPER C
                                            WHERE (C.IDENTSAICFOP = P_ENTSAICFOP)     AND
                                                  (C.CDEMPRESA    = P_EMPRESA)        AND
                                                  (C.CDTIPOOPER   = P_TIPOOPER)       AND
                                                  (C.CDINSCESTA   = P_INSCESTA)       AND
                                                  (C.CDGRUPOFISC  IS NULL)            AND
                                                  (IDCFOPINTEREST = 'N')              AND
                                                  (C.CDPRODUTO    IS NULL)            AND
                                                  (C.DTVALIDCFOP <= P_DTVALIDCFOP)))) LOOP

                  SELECT COUNT(*)
                    INTO V_COUNTMENS
                    FROM MENSAGEM
                   WHERE CDMENSAGEM = C_CFOPNULL.CDMENSAGEM
                     AND IDSITUACAOMENS = 'I';

                  IF V_COUNTMENS > 0 THEN
                     V_DSMENSCFOP := NULL;
                  ELSE
                     V_DSMENSCFOP := C_CFOPNULL.DSMENSCFOP;
                  END IF;

                  INSERT INTO CFOPTEMP(NRCFOPTEMP, NRSEQUCFOP, CDFISOPETMP, CDSUFCFOPTMP,
                                       DSCFOPTMP, DSMENSCFOTMP, DTVDCFOPTMP, IDDIFALIQTMP,
                                       IDDIFALIQCUSPRC)
                  VALUES(P_FILIAL||P_LANCTONF, V_SEQUENCIA, V_CFOP1DIGT||C_CFOPNULL.CDFISCOPER, C_CFOPNULL.CDSUFXCFOP,
                         SUBSTR(C_CFOPNULL.DSCDFISCOPER, 1, 50), V_DSMENSCFOP, C_CFOPNULL.DTVALIDCFOP, C_CFOPNULL.IDDIFEALIQ,
                         C_CFOPNULL.IDDIFALIQCUSPR);

                  V_SEQUENCIA := LPAD(RTRIM(V_SEQUENCIA + '01'),2,0);
               END LOOP;
            END IF;
         END IF;
      END IF;
   END IF;
END; 
/