create or replace PROCEDURE GERA_NOTAFISCAL_CORPO_NFE(
   P_NRACESSONFE  IN NOTAFISCAL.NRACESSONFE%TYPE,
   P_GERAIGUALXML IN PARAMGERAL.IDGERNFIGUALXML%TYPE,
   P_LIBERAXML    IN PARAMGERAL.IDGERNFIGUALXML%TYPE DEFAULT 'N',
   P_CDTIPOOPER   VARCHAR2 DEFAULT 'N',
   P_LIBERAOPER   VARCHAR2 DEFAULT 'N'
   )
AS

   V_IDORIGDESTNF VARCHAR2(01);
   V_IDTPIJURNF   VARCHAR2(01);
   V_NRINSJURNF   VARCHAR2(20);
   V_CDFORNECED   VARCHAR2(21);
   V_CDCLIENTE    VARCHAR2(21);
   V_CDFILIEMIT   VARCHAR2(21);
   V_CDINSCESTA   VARCHAR2(16);
   V_CDINSCMUNI   VARCHAR2(16);
   V_IDDOCFATUR   VARCHAR2(01);
   V_IDDOCFISCENT VARCHAR2(01);
   V_IDDOCESTOQUE VARCHAR2(01);
   V_CDMODDOCFISC VARCHAR2(05);
   V_NRLANCTONF   VARCHAR2(20);
   V_NRLANCESTQ   VARCHAR2(20);
   V_CDTIPOOPER   VARCHAR2(02);
   V_CDTPOPRELAC  VARCHAR2(02);
   V_CDFILIRECE   VARCHAR2(04);
   V_CDFILIAL     VARCHAR2(04);
   V_CDFILLANC    VARCHAR2(04);
   V_CDFILDEST    VARCHAR2(04);
   V_CDEMPRESA    VARCHAR2(02);
   V_ATUAESTOQUE  VARCHAR2(01);
   V_DTENTRSAID   DATE;
   V_DTEMISSAO    DATE;
   V_NRNOTAFISC   VARCHAR2(20);
   V_CDSERIEENTR  VARCHAR2(05);
   V_IDTPIJURTRAN VARCHAR2(01);
   V_VRNOTAFISC   NUMBER;
   V_VRPRODUTOS   NUMBER;
   V_TAMNOTAFISC  NUMBER;
   V_VRDESPERITEM NUMBER;
   V_QTPROGENTAF  NUMBER;
   V_QTITEMPROD   NUMBER;
   V_VRPREUNIAF   FLOAT;
   V_CDMARCA      VARCHAR2(10);
   V_INSPROD      VARCHAR2(01);
   V_IDIMPIMPOXML VARCHAR2(01);
   V_PRODATUEST   VARCHAR2(01);
   V_FILIATUEST   VARCHAR2(01);
   V_CDALMOXARIFE VARCHAR2(10);
   V_CDLOCALESTOQ VARCHAR2(10);
   V_IDUTILALMOX  VARCHAR2(01);
   V_IDUTILLCESTQ VARCHAR2(01);
   V_IDUTILLOTE   VARCHAR2(01);
   V_CLIENT_INFO  VARCHAR2(64);
   V_CDOPERADOR   VARCHAR2(20);
   V_ERRO         VARCHAR2(01);
   V_ERROAF       VARCHAR2(01);
   V_CDPAISORIG   VARCHAR2(04);
   V_CDPAISDEST   VARCHAR2(04);
   V_SGESTAORIG   VARCHAR2(02);
   V_SGESTADEST   VARCHAR2(02);
   V_CDGRUPOFISC  VARCHAR2(05);
   V_IDINTEREST   VARCHAR2(01);
   V_CDFISCALIT   VARCHAR2(01);
   V_DIG1CST      VARCHAR2(01);
   V_CODIGOCST    VARCHAR2(03);

   V_QTDCFOP      NUMBER;
   V_EXPRODAF     NUMBER;
   V_RELACAF      NUMBER;
   V_CDCFOPNF     VARCHAR2(10);
   V_CFOP1DIGT    VARCHAR2(01);
   V_CFOPXML      VARCHAR2(10);
   V_PAISDEST     VARCHAR2(04);
   V_ESTADEST     VARCHAR2(02);
   V_MUNIDEST     VARCHAR2(04);
   V_PAISORIG     VARCHAR2(04);
   V_ESTAORIG     VARCHAR2(02);
   V_MUNIORIG     VARCHAR2(04);
   V_PAISCFOP     VARCHAR2(04);
   V_ESTACFOP     VARCHAR2(02);
   V_IDENDCFOP    VARCHAR2(01);
   V_IMPVENCXML   VARCHAR2(01);
   V_ROLLBACK     VARCHAR2(01);
   V_TOTALNOTA    NUMBER;
   V_COUNTINCONS  NUMBER;
   V_NRAUTOFORN   VARCHAR2(10);
   V_QTDAFANTIGA  FLOAT;
   V_IDUTINSCNFFILORI  VARCHAR2(01); /* Utilizar a inscricao estadual para verificar a filial de destino (V_CDFILIRECE)*/
   V_IDBAIXAFTOTLANNF  VARCHAR2(01);

   V_IDFUNCAOFILI  VARCHAR2(01);
   V_CDENCARGOIMPXML  VARCHAR2(02);

   V_NRINSJURTRANXML  VARCHAR2(20);
   V_NRPLACAVEICXML   VARCHAR2(07);
   V_SGUFVEICXML      VARCHAR2(02);
   V_IDPGTOFRETEXML   VARCHAR2(01);
   V_DSQTDEVOLUXML    VARCHAR2(10);
   V_DSESPECVOLUXML   VARCHAR2(10);
   V_DSMARCAVOLUXML   VARCHAR2(120);
   V_DSNUMEVOLUXML    VARCHAR2(15);
   V_VRPBRUTOVOLUXML  FLOAT;
   V_VRPLIQUVOLUXML   FLOAT;
   V_MAISDE1AF        NUMBER;
   V_NRAUTOFORNIT     VARCHAR2(10);
   V_LIBERAOPER       VARCHAR2(01);
   V_LIBERAXML        VARCHAR2(01);
   V_QTITEMPRODAF     NUMBER;
   V_QTITEMPRODXML    NUMBER;
   V_QTITEMPRODRES    NUMBER;
   V_QTITBAIXADA      NUMBER;

   C_NRSEQINCONS   INTG_INCONSISTENCIA.NRSEQINCONS%TYPE;
   C_CDCONSISTXML  INTG_INCONSISTENCIA.CDCONSISTXML%TYPE;
   C_DSINCONSIS    INTG_INCONSISTENCIA.DSINCONSIS%TYPE;

   /*CURSOR C_INCONS IS
      SELECT NRSEQINCONS, CDCONSISTXML, DSINCONSIS
        FROM INTG_INCONSISTENCIA
       WHERE NRACESSONFE = P_NRACESSONFE
       ORDER BY NRSEQINCONS;*/

BEGIN
   V_CDCLIENTE    := NULL;
   V_CDFORNECED   := NULL;
   V_CDFILIEMIT   := NULL;
   V_ERRO         := 'N';
   V_IDINTEREST   := 'N';

   V_LIBERAOPER := P_LIBERAOPER;
   V_LIBERAXML  := P_LIBERAXML;

   IF V_LIBERAOPER IS NULL THEN
      V_LIBERAOPER := 'N';
   END IF;

   IF V_LIBERAXML IS NULL THEN
      V_LIBERAXML := 'N';
   END IF;

   /*Exclui as inconsistencias referentes ao xml a ser lancado*/
   DELETE
     FROM INTG_INCONSISTENCIA
    WHERE NRACESSONFE = P_NRACESSONFE;

   VERIFICA_INCONS_NF(P_NRACESSONFE, P_GERAIGUALXML, 'N', NULL, NULL, V_LIBERAXML, P_CDTIPOOPER, V_LIBERAOPER, V_ERRO);

   IF (V_ERRO = 'N') THEN

      DBMS_APPLICATION_INFO.READ_CLIENT_INFO(V_CLIENT_INFO);
      V_CDOPERADOR := SUBSTR(V_CLIENT_INFO,45,12);

      BEGIN
         SELECT CDOPERADOR
           INTO V_CDOPERADOR
           FROM OPERADOR
          WHERE CDOPERADOR = V_CDOPERADOR;
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_CDOPERADOR := SUBSTR(V_CLIENT_INFO,1,12);
      END;

      IF (NVL(P_CDTIPOOPER, 'N') = 'N') THEN
         BEGIN
            SELECT CDTIPOOPER
              INTO V_CDTPOPRELAC
              FROM INTG_ITEMPRODUTO I, CFOPXMLTPOPER C
             WHERE I.NRACESSONFE = P_NRACESSONFE
               AND IDENTRSAIDOP  = 'E'
               AND I.CDFISOPEITEM = C.CDFISCOPER
               AND ROWNUM = 1
             ORDER BY NRSEQITPROD;
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_CDTPOPRELAC := NULL;
         END;
      ELSE
         V_CDTPOPRELAC := P_CDTIPOOPER;
      END IF;

      SELECT I.CDFORNECED,  I.CDFILIRECE, NVL(I.CDTIPOOPER, V_CDTPOPRELAC), I.CDINSCESTA,
             I.NRNOTAFISC,  I.DTEMISSAO,  I.VRNOTAFISC, I.VRPRODUTOS,
             I.CDSERIEENTR, I.CDMODDOCFISC, LPAD(IP.NRAUTOFORN, 10, '0') AS NRAUTOFORN,
             I.NRINSJURTRANXML, I.NRPLACAVEICXML, I.SGUFVEICXML,   I.IDPGTOFRETEXML,  I.DSQTDEVOLUXML,
             I.DSESPECVOLUXML,  I.DSMARCAVOLUXML, I.DSNUMEVOLUXML, I.VRPBRUTOVOLUXML, I.VRPLIQUVOLUXML
        INTO V_CDFORNECED, V_CDFILIRECE, V_CDTIPOOPER, V_CDINSCESTA,
             V_NRNOTAFISC, V_DTEMISSAO,  V_VRNOTAFISC, V_VRPRODUTOS,
             V_CDSERIEENTR, V_CDMODDOCFISC, V_NRAUTOFORN,
             V_NRINSJURTRANXML, V_NRPLACAVEICXML, V_SGUFVEICXML,   V_IDPGTOFRETEXML,  V_DSQTDEVOLUXML,
             V_DSESPECVOLUXML,  V_DSMARCAVOLUXML, V_DSNUMEVOLUXML, V_VRPBRUTOVOLUXML, V_VRPLIQUVOLUXML
        FROM INTG_NOTAFISCAL I,
                (SELECT MIN(NRAUTOFORN) AS NRAUTOFORN
                   FROM INTG_ITEMPRODUTO
                  WHERE NRACESSONFE = P_NRACESSONFE) IP
       WHERE NRACESSONFE = P_NRACESSONFE;

      IF V_NRAUTOFORN IS NULL THEN
         BEGIN
            SELECT MAX(NRAUTOFORNE)
              INTO V_NRAUTOFORN
              FROM INTG_ITEMAF
             WHERE NRACESSONFE = P_NRACESSONFE;
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_NRAUTOFORN := NULL;
         END;
      END IF;

      IF (V_NRAUTOFORN IS NOT NULL) THEN
         BEGIN
            SELECT COUNT(1)
              INTO V_QTDAFANTIGA
              FROM AUTOFORNE
             WHERE NRAUTOFORN = V_NRAUTOFORN;
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_QTDAFANTIGA := 0;
         END;

         IF (V_QTDAFANTIGA = 1) THEN
            SELECT CDFILDEST, CDFILLANC
              INTO V_CDFILIRECE, V_CDFILLANC
              FROM AUTOFORNE
             WHERE NRAUTOFORN = V_NRAUTOFORN;
             
            UPDATE INTG_NOTAFISCAL
               SET CDFILIRECE = V_CDFILIRECE
             WHERE NRACESSONFE = P_NRACESSONFE;
         END IF;
      END IF;

      /* BUSCAR A FILIAL RELACIONADA A INSCRICAO ESTADUAL DO ARQUIVO XML CASO A FILIAL
         NAO TENHA SIDO PREENCHIDA E O PARAMETRO IDUTINSCNFFILORI ESTEJA MARCADO*/
      IF (V_CDINSCESTA IS NOT NULL) AND (V_CDFILIRECE IS NULL) THEN
         BEGIN
            SELECT NVL(IDUTINSCNFFILORI, 'N') AS IDUTINSCNFFILORI, NVL(IDBAIXAFTOTLANNF, 'N') AS IDBAIXAFTOTLANNF
              INTO V_IDUTINSCNFFILORI, V_IDBAIXAFTOTLANNF
              FROM PARAMGERAL
             WHERE CDPARGERAL = '0001';
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_IDUTINSCNFFILORI := 'N'; V_IDBAIXAFTOTLANNF:= 'N';
         END;

         IF (V_IDUTINSCNFFILORI = 'S') THEN
            BEGIN
               SELECT MAX(CDFILIAL)
                 INTO V_CDFILIRECE
                 FROM FILIAL
                WHERE CDINSCESTA = V_CDINSCESTA;
            EXCEPTION
               WHEN NO_DATA_FOUND THEN
                  V_CDFILIRECE := NULL;
            END;
            IF V_CDFILIRECE IS NOT NULL THEN
               UPDATE INTG_NOTAFISCAL
                  SET CDFILIRECE = V_CDFILIRECE
                WHERE NRACESSONFE = P_NRACESSONFE;
            END IF;

         END IF;
      END IF;
      /* BUSCAR A FILIAL RELACIONADA A INSCRICAO ESTADUAL DO ARQUIVO XML CASO A FILIAL
         NAO TENHA SIDO PREENCHIDA E O PARAMETRO IDUTINSCNFFILORI ESTEJA MARCADO*/

      /* BUSCAR TIPO DE OPERACAO RELACIONADO A FILIAL */
      IF (V_CDFILIRECE IS NOT NULL) THEN
         BEGIN
            SELECT NVL(MAX(CDTIPOOPERFIL), V_CDTIPOOPER)
              INTO V_CDTIPOOPER
              FROM INTG_ITEMPRODUTO I, CFOPXMLTPOPFIL C
             WHERE I.NRACESSONFE = P_NRACESSONFE
               AND IDENTRSAIDOPFIL  = 'E'
               AND I.CDFISOPEITEM = C.CDFISCOPERFIL
               AND C.CDFILIAL = V_CDFILIRECE
               AND ROWNUM = 1
             ORDER BY NRSEQITPROD;
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_CDTIPOOPER := V_CDTIPOOPER;
         END;
      END IF;

      /* BUSCAR A FILIAL RELACIONADA A INSCRICAO ESTADUAL DO ARQUIVO XML CASO A FILIAL
         NAO TENHA SIDO PREENCHIDA E O PARAMETRO IDUTINSCNFFILORI ESTEJA MARCADO*/

      V_IDFUNCAOFILI := 'N';
      BEGIN
         SELECT NVL(IDFUNCAOFILI, 'N')
           INTO V_IDFUNCAOFILI
           FROM FILIAL
          WHERE CDFILIAL = V_CDFILIRECE;
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_IDFUNCAOFILI := 'N';
      END;

      SELECT MIN(A.CDEMPRESA), MIN(A.CDINSCMUNI)
        INTO V_CDEMPRESA, V_CDINSCMUNI
        FROM(SELECT CDEMPRESA, CDINSCMUNI
               FROM FILIAL
              WHERE CDFILIAL   = V_CDFILIRECE
                AND CDINSCESTA = V_CDINSCESTA
              UNION
             SELECT CDEMPRESA, CDINSCMUNI
               FROM EMPRCNTRFIL
              WHERE CDFILIAL   = V_CDFILIRECE
                AND CDINSCESTA = V_CDINSCESTA) A;

      --VARIAVEIS PARA CONSULTA DE ALIQUOTA, INCIDENCIA, CFOP
      BEGIN
         SELECT CDPAIS,     SGESTADO,   CDMUNICIPIO
           INTO V_PAISDEST, V_ESTADEST, V_MUNIDEST
           FROM INSCRESTAD
          WHERE (CDEMPRESA  = V_CDEMPRESA)
            AND (CDINSCESTA = V_CDINSCESTA);
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_PAISDEST := NULL; V_ESTADEST := NULL; V_MUNIDEST := NULL;
      END;

      BEGIN
         SELECT NVL(IDENDCFOPFOR, 'P')
           INTO V_IDENDCFOP
           FROM FORNECEDOR
          WHERE (CDFORNECED = V_CDFORNECED);
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_IDENDCFOP := 'P';
      END;
      IF V_IDENDCFOP = 'I' THEN
         BEGIN
            SELECT CDPAIS    , SGESTADO
              INTO   V_PAISCFOP, V_ESTACFOP
              FROM INSCRESTAD
             WHERE CDEMPRESA  = V_CDEMPRESA
               AND CDINSCESTA = V_CDINSCESTA;
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_PAISCFOP := NULL; V_ESTACFOP := NULL;
         END;
      ELSE
         BEGIN
            SELECT CDPAIS, SGESTADO
              INTO V_PAISCFOP, V_ESTACFOP
              FROM ENDEFORN
             WHERE (CDFORNECED   = V_CDFORNECED)
               AND (IDTPENDEFORN = V_IDENDCFOP);
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_PAISCFOP := NULL; V_ESTACFOP := NULL;
         END;
      END IF;

      BEGIN
         SELECT CDPAIS, SGESTADO, CDMUNICIPIO
           INTO V_PAISORIG, V_ESTAORIG, V_MUNIORIG
           FROM ENDEFORN
          WHERE (CDFORNECED   = V_CDFORNECED)
            AND (IDTPENDEFORN = 'P');
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_PAISORIG := NULL; V_ESTAORIG := NULL; V_MUNIORIG := NULL;
      END;

      IF (V_PAISORIG = V_PAISDEST) AND (V_ESTAORIG <> V_ESTADEST) THEN
         V_IDINTEREST := 'S';
      END IF;

      /* Verifica primeiro digito do CFOP */
      V_CFOP1DIGT := '';

      IF V_PAISCFOP = V_PAISDEST THEN
         IF V_ESTACFOP = V_ESTADEST THEN
            V_CFOP1DIGT := '1';
         ELSE
            V_CFOP1DIGT := '2';
         END IF;
      ELSE
         V_CFOP1DIGT := '3';
      END IF;

      BEGIN
         SELECT NVL(MAX(NRTAMNUMNFUTDFE), 9)
           INTO V_TAMNOTAFISC
           FROM PARAMFILIAL
          WHERE CDFILIAL = V_CDFILIRECE;
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_TAMNOTAFISC := 9;
      END;

      BEGIN
         SELECT MAX(IDTPIJURFORN), MAX(NRINSJURFORN)
           INTO V_IDTPIJURNF, V_NRINSJURNF
           FROM FORNECEDOR
          WHERE CDFORNECED = V_CDFORNECED;
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_IDTPIJURNF := NULL; V_NRINSJURNF := NULL;
      END;

      BEGIN
         SELECT NVL(IDCTRLESTQ, 'S')
           INTO V_ATUAESTOQUE
           FROM PARAMFILIAL
          WHERE CDFILIAL = V_CDFILIRECE;
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_ATUAESTOQUE := 'S';
      END;

      BEGIN
         SELECT NVL(IDATUESTTPOP, V_ATUAESTOQUE)
           INTO V_ATUAESTOQUE
           FROM TIPOOPERAC
          WHERE CDTIPOOPER   = V_CDTIPOOPER
            AND IDENTRSAIDOP = 'E';
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_ATUAESTOQUE := V_ATUAESTOQUE;
      END;

      BEGIN
         SELECT DECODE(PG.IDUTILDTPROC,'S',DECODE(PF.DTPROCESSA, NULL, TO_DATE(SYSDATE), PF.DTPROCESSA),TO_DATE(SYSDATE)) AS DTPROCESSA
           INTO V_DTENTRSAID
           FROM PARAMGERAL PG, PARAMFILIAL PF
          WHERE PG.CDPARGERAL = '0001'
            AND PF.CDFILIAL = V_CDFILIRECE;
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_DTENTRSAID := TO_DATE(SYSDATE);
      END;

      V_NRNOTAFISC := LPAD(V_NRNOTAFISC, V_TAMNOTAFISC, '0');

      V_IDDOCFISCENT := 'S';

      V_IDDOCESTOQUE := 'N';

      IF (V_NRAUTOFORN IS NOT NULL) THEN
         V_CDFILIAL := V_CDFILLANC;
      ELSE
         V_CDFILIAL := V_CDFILIRECE;
      END IF;

      NOVO_CODIGO('LANCNFPROD/FILIAL' || V_CDFILIAL, V_NRLANCTONF);
      NOVO_CODIGO('LANCNF/FILIAL' || V_CDFILIAL, V_NRLANCTONF);

      V_NRLANCTONF := SUBSTR(V_NRLANCTONF, 11, 10);

      IF V_ATUAESTOQUE = 'S' THEN
         NOVO_CODIGO('LANCTOEST' || V_CDFILIAL, V_NRLANCESTQ);
         V_NRLANCESTQ := SUBSTR(V_NRLANCESTQ, 11, 10);
      ELSE
         V_NRLANCESTQ := '';
      END IF;

      CONSULTA_GRUPOFISCAL('F', V_CDFORNECED, V_CDFILIRECE, 'E', V_CDTIPOOPER, V_CDGRUPOFISC);

      IF (V_NRINSJURTRANXML IS NOT NULL) THEN
         BEGIN
            SELECT NRINSJURTRAN, IDTPIJURTRAN
              INTO V_NRINSJURTRANXML, V_IDTPIJURTRAN
              FROM TRANSPORT
             WHERE NRINSJURTRAN = V_NRINSJURTRANXML
               AND ROWNUM = 1;
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_NRINSJURTRANXML := NULL; V_IDTPIJURTRAN := NULL;
         END;
      END IF;

      INSERT INTO NOTAFISCAL
         (CDFILIAL,     NRLANCTONF,   CDEMPRESA,    CDINSCESTA,   CDINSCMUNI,
          CDFILIEMIT,   CDFILIRECE,   IDTPIJURNF,   NRINSJURNF,   CDFORNECED,
          CDCLIENTE,    IDBLOQUEADO,  IDDOCFISCAL,  IDDOCFINANC,  DTENTRSAID,
          VRPRODUTOS,   VRNOTAFISC,   NRPLACAVEIC,  SGUFVEIC,     IDPGTOFRETE,
          DSQTDEVOLU,   DSESPECVOLU,  DSMARCAVOLU,  DSNUMEVOLU,   VRPBRUTOVOLU,
          VRPLIQUVOLU,  IDENTRSAIDOP, CDTIPOOPER,   CDSERIEENTR,  IDTPIJURTRAN,
          NRINSJURTRAN, IDDOCCONTAB,  IDSTATUS,     IDDOCFATUR,   IDDOCFISCENT,
          IDDOCFISCSAI, IDDOCESTOQUE, IDSISTEMA,    CDMODDOCFISC, IDORIGDESTNF,
          NRAPURACFAT,  CDINTEGRACAO, DTLANCAMENNF, NRNOTAFISC,   DTEMISSAO,
          NRACESSONFE,  CDOPERGERA,   IDNFGERADAVIAXML)
      VALUES
         (V_CDFILIAL,        V_NRLANCTONF,     V_CDEMPRESA,      V_CDINSCESTA,    V_CDINSCMUNI,
          V_CDFILIEMIT,      V_CDFILIRECE,     V_IDTPIJURNF,     V_NRINSJURNF,    V_CDFORNECED,
          V_CDCLIENTE,       'N',              'S',              'S',             TO_DATE(V_DTENTRSAID),
          0,                 V_VRNOTAFISC,     V_NRPLACAVEICXML, V_SGUFVEICXML,   V_IDPGTOFRETEXML,
          V_DSQTDEVOLUXML,   V_DSESPECVOLUXML, V_DSMARCAVOLUXML, V_DSNUMEVOLUXML, V_VRPBRUTOVOLUXML,
          V_VRPLIQUVOLUXML,  'E',              V_CDTIPOOPER,     V_CDSERIEENTR,   V_IDTPIJURTRAN,
          V_NRINSJURTRANXML, 'S',              'I',              V_IDDOCFATUR,    'N',
          V_IDDOCFISCENT,    V_IDDOCESTOQUE,   'DFE',            V_CDMODDOCFISC,  'F',
          NULL,              NULL,             SYSDATE,          V_NRNOTAFISC,    TO_DATE(V_DTEMISSAO),
          P_NRACESSONFE,     V_CDOPERADOR,     'S');

      INSERT INTO ITEMENCARGO
         (CDFILIAL, NRLANCTONF, CDENCARGO, VRITEMENCA)
         (SELECT V_CDFILIAL, V_NRLANCTONF, CDENCARGO, 0
            FROM ENCARGO
           WHERE NOT EXISTS(SELECT CDENCARGO
                              FROM ITEMENCARGO
                             WHERE CDFILIAL   = V_CDFILIAL
                               AND NRLANCTONF = V_NRLANCTONF
                               AND CDENCARGO  = ENCARGO.CDENCARGO));

      FOR C_ITEMENCARGO IN (SELECT CDFILIAL, NRLANCTONF, I.CDENCARGO, I.VRITEMENCA, E.NMENCARGO, E.IDENCARGO
                                 FROM INTG_ITEMENCARGO I, ENCARGO E
                                WHERE I.CDENCARGO = E.CDENCARGO
                                  AND I.VRITEMENCA > 0
                                  AND I.NRACESSONFE = P_NRACESSONFE)LOOP

         UPDATE ITEMENCARGO
            SET VRITEMENCA = VRITEMENCA + C_ITEMENCARGO.VRITEMENCA
          WHERE CDENCARGO  = C_ITEMENCARGO.CDENCARGO
            AND CDFILIAL   = V_CDFILIAL
            AND NRLANCTONF = V_NRLANCTONF;
            
      END LOOP;   

      FOR C_ITEMPRODUTO IN (SELECT PR.CDARVPROD, PR.NMPRODUTO,  P.CDMARCAREL, I.VRUNITITEM, P.CDPRODUTOXML,
                                   I.VRDESCITEM, I.NRSEQITPROD, I.VRTOTAITEM,
                                   PR.CDPRODUTO, I.QTITEMPROD,  LPAD(I.NRAUTOFORN, 10, '0') AS NRAUTOFORN,
                                   I.IDORIGEMPROD, I.CDFISOPEITEM, I.CDSITUTRIBPR,
                                   PR.CDPRODESTO,
                                   DECODE(NVL(P.IDUTQTDTRIB, 'N'), 'N', NVL(PR.VRFATOCONV, 1), NVL(I.VRFATOCONVTRIB, NVL(PR.VRFATOCONV, 1))) AS VRFATOCONV,
                                   DECODE(NVL(P.IDUTQTDTRIB, 'N'), 'N', NULL, I.QTITEMPRODTRIB) AS QTITEMPRODTRIB,
                                   DECODE(NVL(P.IDUTQTDTRIB, 'N'), 'N', NULL, I.VRFATOCONVTRIB) AS VRFATOCONVTRIB
                              FROM INTG_ITEMPRODUTO I, PRODFORNXML P, PRODUTO PR
                             WHERE I.NRACESSONFE = P_NRACESSONFE
                               AND I.CDPRODUTO   = P.CDPRODUTOXML
                               AND P.CDPRODUTO   = PR.CDPRODUTO
                               AND P.CDFORNECED  = V_CDFORNECED
                               AND V_IDFUNCAOFILI <> 'O'
                             UNION ALL
                            SELECT PR.CDARVPROD, PR.NMPRODUTO, P.CDMARCAREL,
                                   --I.VRTOTAITEM / (I.QTITEMPROD/NVL(P.VRFATCONVOL, 1)) AS VRUNITITEM,
                                   DECODE(NVL(P.IDUTQTDTRIB, 'N'), 'N', (I.VRTOTAITEM)/ (I.QTITEMPROD/NVL(P.VRFATCONVOL, 1)), I.VRUNITITEM) AS VRUNITITEM,
                                   P.CDPRODUTOXML,
                                   I.VRDESCITEM, I.NRSEQITPROD, I.VRTOTAITEM,
                                   PR.CDPRODUTO, --ROUND((I.QTITEMPROD/NVL(P.VRFATCONVOL, 1)), 3) AS QTITEMPROD,
                                   DECODE(NVL(P.IDUTQTDTRIB, 'N'), 'N', ROUND((I.QTITEMPROD/NVL(P.VRFATCONVOL, 1)), 3), I.QTITEMPROD) AS QTITEMPROD,
                                   LPAD(I.NRAUTOFORN, 10, '0') AS NRAUTOFORN,
                                   I.IDORIGEMPROD, I.CDFISOPEITEM, I.CDSITUTRIBPR,
                                   PR.CDPRODESTO, --NVL(P.VRFATCONVOL, 1) AS VRFATOCONV
                                   DECODE(NVL(P.IDUTQTDTRIB, 'N'), 'N', NVL(P.VRFATCONVOL, 1), NVL(I.VRFATOCONVTRIB, NVL(P.VRFATCONVOL, 1))) AS VRFATOCONV,
                                   DECODE(NVL(P.IDUTQTDTRIB, 'N'), 'N', NULL, I.QTITEMPRODTRIB) AS QTITEMPRODTRIB,
                                   DECODE(NVL(P.IDUTQTDTRIB, 'N'), 'N', NULL, I.VRFATOCONVTRIB) AS VRFATOCONVTRIB
                              FROM INTG_ITEMPRODUTO I, PRODFORNXML P, PRODUTO PR, RELACPRODOL R, PRODUTO PR2
                             WHERE I.NRACESSONFE = P_NRACESSONFE
                               AND I.CDPRODUTO   = P.CDPRODUTOXML
                               AND R.CDPRARVORIG = P.CDPRODUTO
                               AND R.CDPRODARVOL = PR.CDPRODUTO
                               AND P.CDFORNECED  = V_CDFORNECED
                               AND V_IDFUNCAOFILI = 'O'
                               AND PR2.CDPRODUTO = P.CDPRODUTO
                               AND I.NRAUTOFORN IS NULL
                             UNION ALL
                            SELECT  PR.CDARVPROD, PR.NMPRODUTO, P.CDMARCAREL,
                                   --I.VRTOTAITEM / (I.QTITEMPROD/NVL(P.VRFATCONVOL, 1)) AS VRUNITITEM,
                                   DECODE(NVL(P.IDUTQTDTRIB, 'N'), 'N', (I.VRTOTAITEM)/ (I.QTITEMPROD/NVL(P.VRFATCONVOL, 1)), I.VRUNITITEM) AS VRUNITITEM,
                                   P.CDPRODUTOXML,
                                   I.VRDESCITEM, I.NRSEQITPROD, I.VRTOTAITEM,
                                   PR.CDPRODUTO, --ROUND((I.QTITEMPROD/NVL(P.VRFATCONVOL, 1)), 3) AS QTITEMPROD,
                                   DECODE(NVL(P.IDUTQTDTRIB, 'N'), 'N', ROUND((I.QTITEMPROD/NVL(P.VRFATCONVOL, 1)), 3), I.QTITEMPROD) AS QTITEMPROD,
                                   LPAD(I.NRAUTOFORN, 10, '0') AS NRAUTOFORN,
                                   I.IDORIGEMPROD, I.CDFISOPEITEM, I.CDSITUTRIBPR,
                                   PR.CDPRODESTO, --NVL(P.VRFATCONVOL, 1) AS VRFATOCONV
                                   DECODE(NVL(P.IDUTQTDTRIB, 'N'), 'N', NVL(P.VRFATCONVOL, 1), NVL(I.VRFATOCONVTRIB, NVL(P.VRFATCONVOL, 1))) AS VRFATOCONV,
                                   DECODE(NVL(P.IDUTQTDTRIB, 'N'), 'N', NULL, I.QTITEMPRODTRIB) AS QTITEMPRODTRIB,
                                   DECODE(NVL(P.IDUTQTDTRIB, 'N'), 'N', NULL, I.VRFATOCONVTRIB) AS VRFATOCONVTRIB
                              FROM INTG_ITEMPRODUTO I, PRODFORNXML P, PRODUTO PR, RELACPRODOL R, PRODUTO PR2, ITEMAUTF IT
                             WHERE I.NRACESSONFE = P_NRACESSONFE
                               AND I.CDPRODUTO   = P.CDPRODUTOXML
                               AND R.CDPRARVORIG = P.CDPRODUTO
                               AND R.CDPRODARVOL = PR.CDPRODUTO
                               AND P.CDFORNECED  = V_CDFORNECED
                               AND V_IDFUNCAOFILI = 'O'
                               AND PR2.CDPRODUTO = P.CDPRODUTO
                               AND IT.CDPRODUTO  = R.CDPRODARVOL
                               AND IT.NRAUTOFORN = I.NRAUTOFORN
                               AND IT.CDPRODUTO  = PR.CDPRODUTO
                               AND IT.CDMARCA    = R.CDMARCA
                               AND I.NRAUTOFORN IS NOT NULL
                             ORDER BY NRSEQITPROD) LOOP


         SELECT NVL(MAX(P.IDCNTRESTOQ),NVL(MAX(F.IDCTRLESTQ),'N')) AS CNTRESTOQ,
                NVL(MAX(F.IDCTRLESTQ),'N') AS IDCTRLESTQ,
                NVL(MAX(DECODE(B.IDUTILBALANCA, 'S', DECODE(P.IDUTILPESAGEM, 'S', RTRIM(P.CDALMOCONFPESMP), RTRIM(P.CDALMOXARIFE)), RTRIM(P.CDALMOXARIFE))), ' ') AS CDALMOXARIFE,
                NVL(MAX(DECODE(B.IDUTILBALANCA, 'S', DECODE(P.IDUTILPESAGEM, 'S', RTRIM(P.CDLOCACONFPESMP), RTRIM(P.CDLOCALESTOQ)), RTRIM(P.CDLOCALESTOQ))), ' ') AS CDLOCALESTOQ,
                NVL(MAX(F.IDUTILALMOX),'N'),
                NVL(MAX(F.IDUTILLCESTQ),'N'),
                NVL(MAX(F.IDUTILLOTE),'N')
           INTO V_PRODATUEST,
                V_FILIATUEST,
                V_CDALMOXARIFE,
                V_CDLOCALESTOQ,
                V_IDUTILALMOX,
                V_IDUTILLCESTQ,
                V_IDUTILLOTE
           FROM PRODFILI P, PARAMFILIAL F, PRODUTO D, PARAMINTBALANCA B
          WHERE P.CDFILIAL    = V_CDFILIRECE
            AND P.CDFILIAL    = F.CDFILIAL
            AND D.CDPRODUTO   = C_ITEMPRODUTO.CDPRODUTO
            AND P.CDPRODUTO   = D.CDPRODESTO
            AND F.CDFILIAL    = B.CDFILIAL (+)
            AND (F.IDCTRLESTQ = 'S' OR F.IDCTRLESTQ IS NULL);

         V_CFOPXML := SUBSTR(C_ITEMPRODUTO.CDFISOPEITEM, 2, 3);

         V_MAISDE1AF := 0;

         SELECT COUNT(1)
           INTO V_MAISDE1AF
           FROM INTG_ITEMAF
          WHERE NRACESSONFE = P_NRACESSONFE;

         IF ((C_ITEMPRODUTO.NRAUTOFORN IS NULL) OR (V_MAISDE1AF > 0)) THEN
            BEGIN
               SELECT MAX(NRAUTOFORNE)
                 INTO V_NRAUTOFORNIT
                 FROM INTG_ITEMAF
                WHERE NRACESSONFE  = P_NRACESSONFE
                  AND CDPRODUTOXML = C_ITEMPRODUTO.CDPRODUTOXML
                  AND NRSEQITPROD  = C_ITEMPRODUTO.NRSEQITPROD;
            EXCEPTION
               WHEN NO_DATA_FOUND THEN
                  V_NRAUTOFORNIT := NULL;
            END;
         END IF;
         
         INSERT INTO ITEMPRODUTO
            (CDFILIAL,  CDPRODEMIS,  VRUNITITEM, IDCONFORITEM, NRLANCTONF,
             DSPRODEMIS, VRDESCITEM, NRSEQITPROD, IDATUVRESTOQ,
             VRTOTAITEM, CDPRODUTO, QTITEMPROD, VRCONTITEM, CDFISOPEITEM,
             IDAVISOSITEM, VRBRUTITEM, CDFILDEST, NRAUTOFORN, CDSITUTRIBPR,
             CDMARCA, DTPROGENTAF, CDALMOXARIFE, CDLOCALESTOQ, NRLOTEESTQ,
             NRSUBLOTE, CDFILIMOVI, VRDESPERITEM, CDOPERADOR, IDITEMORIGEM,
             IDORIGEMPROD, VRENCARGOIMPXML, QTITPRODTRIBXML, VRFATCONTRIBXML)
         VALUES
            (V_CDFILIAL, C_ITEMPRODUTO.CDARVPROD, C_ITEMPRODUTO.VRUNITITEM, 'S', V_NRLANCTONF,
             C_ITEMPRODUTO.NMPRODUTO, C_ITEMPRODUTO.VRDESCITEM, LPAD(C_ITEMPRODUTO.NRSEQITPROD, 4, '0'), V_PRODATUEST,
             C_ITEMPRODUTO.VRTOTAITEM, C_ITEMPRODUTO.CDPRODUTO,  C_ITEMPRODUTO.QTITEMPROD, 0, V_CFOP1DIGT||V_CFOPXML,
             '000000', (C_ITEMPRODUTO.VRTOTAITEM - C_ITEMPRODUTO.VRDESCITEM), V_CDFILIRECE, NVL(C_ITEMPRODUTO.NRAUTOFORN, V_NRAUTOFORNIT),
             C_ITEMPRODUTO.CDSITUTRIBPR, NULL, NULL, V_CDALMOXARIFE, V_CDLOCALESTOQ, ' ',
             ' ', V_CDFILIRECE, V_VRDESPERITEM, V_CDOPERADOR, NULL,
             C_ITEMPRODUTO.IDORIGEMPROD, 0, C_ITEMPRODUTO.QTITEMPRODTRIB, C_ITEMPRODUTO.VRFATOCONVTRIB);

         IF (C_ITEMPRODUTO.NRAUTOFORN IS NOT NULL) OR (V_NRAUTOFORNIT IS NOT NULL) THEN    /* AND EXISTE AF NO SISTEMA*/

            IF (C_ITEMPRODUTO.NRAUTOFORN IS NULL) THEN
               SELECT MAX(A.CDFILLANC), MAX(A.CDFILDEST)
                 INTO V_CDFILLANC, V_CDFILDEST
                 FROM AUTOFORNE A, INTG_ITEMAF II
                WHERE A.NRAUTOFORN = II.NRAUTOFORNE
                  AND II.NRACESSONFE = P_NRACESSONFE
                  AND II.NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD
                  AND (A.IDAFFORALIM = 'N')
                  AND (A.IDSITUATUAAF IS NULL)
                  AND (NVL(A.IDAFOPERLOG,'1') = '1')
                  AND (NVL(A.IDAFEXPIRADA, 'N') = 'N');
            ELSE
               SELECT CDFILLANC, CDFILDEST
                 INTO V_CDFILLANC, V_CDFILDEST
                 FROM AUTOFORNE
                WHERE NRAUTOFORN = C_ITEMPRODUTO.NRAUTOFORN
                  AND (IDAFFORALIM = 'N')
                  AND (IDSITUATUAAF IS NULL)
                  AND (NVL(IDAFOPERLOG,'1') = '1')
                  AND (NVL(IDAFEXPIRADA, 'N') = 'N');
            END IF;

            V_EXPRODAF := 0;

            BEGIN
               SELECT COUNT(1)
                 INTO V_EXPRODAF
                 FROM ITEMAUTF I, PRODUTO P
                WHERE I.CDFILLANC   = V_CDFILLANC
                  AND I.CDFILDEST   = V_CDFILDEST
                  AND I.NRAUTOFORN  = NVL(C_ITEMPRODUTO.NRAUTOFORN, V_NRAUTOFORNIT)
                  AND P.CDPRODESTO  = C_ITEMPRODUTO.CDPRODESTO
                  AND (IDBAIXITMAF NOT IN ('2','3') OR IDBAIXITMAF IS NULL)
                  AND (QTPROGENTAF - NVL(QTEFETENTRAF, 0)) > 0
                  AND I.CDPRODUTO = P.CDPRODUTO;
            EXCEPTION
               WHEN NO_DATA_FOUND THEN
                  V_EXPRODAF := 0;
            END;

            IF V_EXPRODAF = 0 THEN
               BEGIN
                  SELECT COUNT(1)
                    INTO V_EXPRODAF
                    FROM ITEMAUTF I, PRODUTO P, INTG_ITEMAF II
                   WHERE I.CDFILLANC     = V_CDFILLANC
                     AND I.CDFILDEST     = V_CDFILDEST
                     AND II.NRACESSONFE  = P_NRACESSONFE
                     AND II.CDPRODUTOXML = C_ITEMPRODUTO.CDPRODUTOXML
                     AND II.NRSEQITPROD  = C_ITEMPRODUTO.NRSEQITPROD
                     AND I.NRAUTOFORN    = II.NRAUTOFORNE
                     AND P.CDPRODESTO    = C_ITEMPRODUTO.CDPRODESTO
                     AND (IDBAIXITMAF NOT IN ('2','3') OR IDBAIXITMAF IS NULL)
                     AND (QTPROGENTAF - NVL(QTEFETENTRAF, 0)) > 0
                     AND I.CDPRODUTO = P.CDPRODUTO;
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_EXPRODAF := 0;
               END;
            END IF;

            IF (V_EXPRODAF > 0) THEN
               V_INSPROD := 'S';
               V_QTITEMPRODAF  := 0;
               V_QTITEMPRODXML := 0;
               V_QTITEMPRODRES := 0;
               V_QTITBAIXADA   := 0;
               V_INSPROD       := 'S';

               FOR C_INTG_RELACAF IN (SELECT NRAUTOFORNE AS NRAUTOFORN, CDPRODUTOAF
                                        FROM INTG_ITEMAF
                                       WHERE NRACESSONFE = P_NRACESSONFE
                                         AND NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD) LOOP

                  FOR C_ITEMAUTF IN(SELECT CDMARCA, DTPROGENTAF, (QTPROGENTAF - NVL(QTEFETENTRAF, 0)) AS QTPROGENTAF,
                                           VRPREUNIAF, P.CDPRODUTO, P.CDARVPROD, NVL(P.VRFATOCONV, 1) AS VRFATOCONVAF
                                      FROM ITEMAUTF I, PRODUTO P
                                     WHERE I.CDFILLANC   = V_CDFILLANC
                                       AND I.CDFILDEST   = V_CDFILDEST
                                       AND I.NRAUTOFORN  = NVL(C_INTG_RELACAF.NRAUTOFORN, V_NRAUTOFORNIT)
                                       AND P.CDPRODESTO  = C_ITEMPRODUTO.CDPRODESTO
                                       AND I.CDPRODUTO   = NVL(C_INTG_RELACAF.CDPRODUTOAF, I.CDPRODUTO)
                                       AND ((I.CDMARCA   = C_ITEMPRODUTO.CDMARCAREL) OR (NVL(C_ITEMPRODUTO.CDMARCAREL, I.CDMARCA) = I.CDMARCA))
                                       AND (IDBAIXITMAF NOT IN ('2','3') OR IDBAIXITMAF IS NULL)
                                       AND (QTPROGENTAF - NVL(QTEFETENTRAF, 0)) > 0
                                       AND I.CDPRODUTO = P.CDPRODUTO
                                     ORDER BY I.DTPROGENTAF) LOOP

                     IF V_INSPROD = 'S' THEN

                        V_INSPROD := 'N';

                        IF (C_ITEMPRODUTO.CDPRODUTO = C_ITEMAUTF.CDPRODUTO) OR (V_IDFUNCAOFILI = 'O') THEN
                           IF (C_ITEMPRODUTO.VRFATOCONVTRIB > 0) THEN
                              V_QTITEMPROD := (C_ITEMPRODUTO.QTITEMPROD * C_ITEMPRODUTO.VRFATOCONVTRIB)/C_ITEMAUTF.VRFATOCONVAF;
                           ELSE
                              V_QTITEMPROD := C_ITEMPRODUTO.QTITEMPROD;
                           END IF;
                        ELSE
                           V_QTITEMPROD := (C_ITEMPRODUTO.QTITEMPROD * C_ITEMPRODUTO.VRFATOCONV)/C_ITEMAUTF.VRFATOCONVAF;
                        END IF;

                        IF (C_INTG_RELACAF.NRAUTOFORN IS NOT NULL) THEN
                           V_RELACAF := 0;

                           BEGIN
                              SELECT COUNT(1)
                                INTO V_RELACAF
                                FROM NFRELACAF
                               WHERE CDFILIAL    = V_CDFILIAL
                                 AND CDFILLANC   = V_CDFILLANC
                                 AND NRLANCTONF  = V_NRLANCTONF
                                 AND CDFILDEST   = V_CDFILDEST
                                 AND NRAUTOFORN  = C_INTG_RELACAF.NRAUTOFORN
                                 AND CDPRODUTO   = C_ITEMAUTF.CDPRODUTO
                                 AND CDMARCA     = C_ITEMAUTF.CDMARCA
                                 AND DTPROGENTAF = C_ITEMAUTF.DTPROGENTAF;
                           EXCEPTION
                              WHEN NO_DATA_FOUND THEN
                                 V_RELACAF := 0;
                           END;

                           IF V_RELACAF = 0 THEN
                              INSERT INTO NFRELACAF
                                 (CDFILIAL, CDFILLANC, NRLANCTONF, CDFILDEST,
                                  NRAUTOFORN, CDPRODUTO, CDMARCA,
                                  DTPROGENTAF, QTNFRELACAF, VRNFRELACAF)
                                 VALUES
                                 (V_CDFILIAL, V_CDFILLANC, V_NRLANCTONF, V_CDFILDEST,
                                  C_INTG_RELACAF.NRAUTOFORN, C_ITEMAUTF.CDPRODUTO, C_ITEMAUTF.CDMARCA,
                                  C_ITEMAUTF.DTPROGENTAF, C_ITEMAUTF.QTPROGENTAF /*V_QTITEMPROD*/, C_ITEMAUTF.VRPREUNIAF);
                           END IF;
                        END IF;

                        UPDATE ITEMPRODUTO
                           SET CDMARCA     = C_ITEMAUTF.CDMARCA,
                               DTPROGENTAF = C_ITEMAUTF.DTPROGENTAF,
                               NRAUTOFORN  = NVL(C_INTG_RELACAF.NRAUTOFORN, V_NRAUTOFORNIT)
                         WHERE CDFILIAL    = V_CDFILIAL
                           AND NRLANCTONF  = V_NRLANCTONF
                           AND NRSEQITPROD = LPAD(C_ITEMPRODUTO.NRSEQITPROD, 4, '0');

                        UPDATE INTG_ITEMPRODUTO
                           SET NRAUTOFORN  = NVL(C_INTG_RELACAF.NRAUTOFORN, V_NRAUTOFORNIT)
                         WHERE NRACESSONFE = P_NRACESSONFE
                           AND NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;


                        V_CDMARCA := C_ITEMAUTF.CDMARCA;

                        IF (V_QTITEMPRODRES IS NULL) OR (V_QTITEMPRODRES = 0) THEN
                           NF_BAIXA_AF(V_CDFILIAL, V_NRLANCTONF, LPAD(C_ITEMPRODUTO.NRSEQITPROD, 4, '0'), 'I', C_ITEMAUTF.CDARVPROD, C_ITEMAUTF.CDARVPROD,
                                       C_ITEMAUTF.CDPRODUTO, C_ITEMAUTF.CDPRODUTO, V_CDMARCA, V_CDMARCA, V_QTITEMPROD, V_QTITEMPROD, V_ERROAF);
                        ELSE
                           V_QTITEMPRODRES := (V_QTITEMPRODRES/C_ITEMAUTF.VRFATOCONVAF);
                           V_QTITBAIXADA   := (V_QTITBAIXADA  /C_ITEMAUTF.VRFATOCONVAF);

                           NF_BAIXA_AF(V_CDFILIAL, V_NRLANCTONF, LPAD(C_ITEMPRODUTO.NRSEQITPROD, 4, '0'), 'I', C_ITEMAUTF.CDARVPROD, C_ITEMAUTF.CDARVPROD,
                                       C_ITEMAUTF.CDPRODUTO, C_ITEMAUTF.CDPRODUTO, V_CDMARCA, V_CDMARCA, V_QTITEMPRODRES, V_QTITEMPRODRES, V_ERROAF);
                        END IF;

                        V_QTITEMPRODAF  := C_ITEMAUTF.QTPROGENTAF;
                        V_QTITEMPRODXML := V_QTITEMPROD;

                        IF (V_QTITEMPRODAF < (V_QTITEMPROD - V_QTITBAIXADA)) THEN
                           V_QTITEMPRODRES := V_QTITEMPROD - V_QTITEMPRODAF - V_QTITBAIXADA;
                           V_QTITBAIXADA   := V_QTITBAIXADA + C_ITEMAUTF.QTPROGENTAF * C_ITEMAUTF.VRFATOCONVAF;
                           V_QTITEMPRODRES := V_QTITEMPRODRES * C_ITEMAUTF.VRFATOCONVAF;
                           V_INSPROD       := 'S';
                        ELSE
                           V_QTITEMPRODRES := NULL;
                           V_QTITEMPROD    := NULL;
                           V_QTITEMPRODAF  := NULL;
                           V_QTITBAIXADA   := NULL;
                           V_INSPROD       := 'N';
                        END IF;

                     END IF;
                  END LOOP;
               END LOOP;
            END IF;
         END IF;

         BEGIN
            SELECT NVL(NVL(P.CDCSTDIG1PROD ,F.CDCSTDIG1ENT), '0') AS CDCSTDIG1
              INTO V_DIG1CST
              FROM ITEMPRODUTO I, NOTAFISCAL N, FORNECEDOR F, PRODUTO P
             WHERE I.CDFILIAL    = V_CDFILIAL
               AND I.NRLANCTONF  = V_NRLANCTONF
               AND I.NRSEQITPROD = LPAD(C_ITEMPRODUTO.NRSEQITPROD, 4, '0')
               AND N.CDFILIAL    = I.CDFILIAL
               AND N.NRLANCTONF  = I.NRLANCTONF
               AND F.CDFORNECED  = N.CDFORNECED
               AND P.CDPRODUTO   = I.CDPRODUTO;
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_DIG1CST := 0;
         END;

         IF (P_GERAIGUALXML = 'S') THEN
            FOR C_TRABITPROIMPOS IN(SELECT IT.CDFILIAL, IT.NRLANCTONF, IT.NRSEQIMPOIT, IT.CDIMPOSTOIT,
                                           B.SGIMPOSTO, B.IDTRATIMPO, B.IDPREIMPENTR, B.IDCONSISTENT,
                                           IT.VRCONTITIMP, IT.VRPERREDBCIT, IT.VRBASECALCIT, IT.VRALIQITEM,
                                           IT.VRIMPOSTOIT, IT.CDFISCALIT, IT.CDSITUTRIBIT, IT.CDFISCOPERIT,
                                           IT.NRITPROIMPOS, IT.IDMODBCITNFE, IT.IDMODBCSTITNFE,
                                           NVL(IT.VRADICALIQFECP, 0) AS VRADICALIQFECP,
                                           NVL(IT.VRADICFECP, 0) AS VRADICFECP
                                      FROM INTG_TRABITPROIMPOS IT, IMPOSTO B
                                     WHERE NRACESSONFE    = P_NRACESSONFE
                                       AND B.CDIMPOSTO    = IT.CDIMPOSTOIT
                                       AND IT.NRSEQIMPOIT = C_ITEMPRODUTO.NRSEQITPROD
                                     ORDER BY IT.CDFILIAL, IT.NRLANCTONF, IT.NRSEQIMPOIT, IT.CDIMPOSTOIT) LOOP


               IF(C_TRABITPROIMPOS.VRIMPOSTOIT > 0) THEN
                  V_CDFISCALIT := '1';
               ELSE
                  V_CDFISCALIT := '2';
               END IF;

               IF (LENGTH(C_TRABITPROIMPOS.CDSITUTRIBIT) = 2) THEN
                  V_CODIGOCST := C_TRABITPROIMPOS.CDSITUTRIBIT;
               ELSE
                  IF (LENGTH(C_TRABITPROIMPOS.CDSITUTRIBIT) > 2) THEN
                     V_CODIGOCST := SUBSTR(C_TRABITPROIMPOS.CDSITUTRIBIT, 2,2);
                  END IF;
               END IF;

               V_CFOPXML := SUBSTR(C_ITEMPRODUTO.CDFISOPEITEM, 2, 3);

               BEGIN
                  SELECT NVL(CDENCARGOIMPXML, NULL)
                    INTO V_CDENCARGOIMPXML
                    FROM IMPOSTO
                   WHERE CDIMPOSTO = C_TRABITPROIMPOS.CDIMPOSTOIT;
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_CDENCARGOIMPXML := NULL;
               END;

               IF (V_CDENCARGOIMPXML IS NULL) THEN

                  INSERT INTO TRABITPROIMPOS
                     (CDFILIMPOIT, NRLANCIMPOIT, NRSEQIMPOIT, CDIMPOSTOIT, VRCONTIMPOIT,
                      VRREDBCIMPOIT, VRBCALCIMPOIT, VRALIQIMPOIT, VRPDEDIMPOIT, VRIMPOSIT,
                      CDFISCIMPOIT,  CDSTRIBIMPOIT, CDFOPERIMPOIT, NRSEQITPRO, IDVALORINFO,
                      VR1REDBCIMPOIT, IDTRIMPSTTI, VRIMPOSVISUIT, CDSTRIBITNFE, VRADICALIQFECP, VRADICFECP)
                  VALUES
                     (V_CDFILIAL, V_NRLANCTONF, LPAD(C_ITEMPRODUTO.NRSEQITPROD, 4, '0'), C_TRABITPROIMPOS.CDIMPOSTOIT, (C_ITEMPRODUTO.VRTOTAITEM - C_ITEMPRODUTO.VRDESCITEM),
                      NVL(C_TRABITPROIMPOS.VRPERREDBCIT,  0), NVL(C_TRABITPROIMPOS.VRBASECALCIT, 0), C_TRABITPROIMPOS.VRALIQITEM, 0, C_TRABITPROIMPOS.VRIMPOSTOIT,
                      V_CDFISCALIT, V_DIG1CST||V_CODIGOCST, V_CFOP1DIGT||V_CFOPXML, C_TRABITPROIMPOS.NRITPROIMPOS, 'S',
                       0, '0', C_TRABITPROIMPOS.VRIMPOSTOIT, V_CODIGOCST, C_TRABITPROIMPOS.VRADICALIQFECP, C_TRABITPROIMPOS.VRADICFECP);

               ELSE
                  UPDATE ITEMENCARGO
                     SET VRITEMENCA = VRITEMENCA + C_TRABITPROIMPOS.VRIMPOSTOIT + C_TRABITPROIMPOS.VRADICFECP
                   WHERE CDENCARGO  = V_CDENCARGOIMPXML
                     AND CDFILIAL   = V_CDFILIAL
                     AND NRLANCTONF = V_NRLANCTONF;

                  UPDATE ITEMPRODUTO
                     SET VRENCARGOIMPXML  = VRENCARGOIMPXML + C_TRABITPROIMPOS.VRIMPOSTOIT + C_TRABITPROIMPOS.VRADICFECP
                   WHERE NRSEQITPROD = LPAD(C_ITEMPRODUTO.NRSEQITPROD, 4, '0')
                     AND CDFILIAL    = V_CDFILIAL
                     AND NRLANCTONF  = V_NRLANCTONF;
               END IF;
            END LOOP;

         ELSE
            IMPOSTO_ENTRADA_PRODUTO(V_CDEMPRESA, V_CDINSCESTA, V_CDTIPOOPER, V_CDFORNECED, V_CDFILIAL, V_NRLANCTONF,
                                    V_DTENTRSAID, 'E', V_CDOPERADOR, V_CDGRUPOFISC, V_IDINTEREST, C_ITEMPRODUTO.CDARVPROD,
                                    '', 'F', V_CDFILIRECE, NULL, NULL, C_ITEMPRODUTO.VRTOTAITEM, C_ITEMPRODUTO.IDORIGEMPROD);


            FOR C_ALIQITEM IN(SELECT IM.CDIMPOSTO, IM.SGIMPOSTO, IM.IDTRATIMPO, IM.IDPREIMPENTR,
                                     I.CDFISCTEMP, NVL(AL.VRALIQUTMP, 0) AS VRALIQUOTA,
                                     NVL(AL.VRADICALIQFECP, 0) AS VRADICALIQFECP
                                FROM INCITEMP I, IMPOSTO IM, ALIQTEMPPROD AL
                               WHERE I.CDIMPOTEMP  = IM.CDIMPOSTO
                                 AND I.NRINCITEMP  = V_CDFILIAL||V_NRLANCTONF
                                 AND I.NRINCITEMP  = AL.NRALIQTEMP(+)
                                 AND I.CDIMPOTEMP  = AL.CDIMPOTEMP(+)
                                 AND IM.IDPRODNOTA <> 'C') LOOP

               BEGIN
                  SELECT NVL(IDIMPORTAIMPXML , 'N')
                    INTO V_IDIMPIMPOXML
                    FROM IMPOSTO
                   WHERE CDIMPOSTO = C_ALIQITEM.CDIMPOSTO;
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_IDIMPIMPOXML := 'N';
               END;

               IF (V_IDIMPIMPOXML = 'N') THEN
                  INSERT INTO TRABITPROIMPOS
                     (CDFILIMPOIT, NRLANCIMPOIT, NRSEQIMPOIT, CDIMPOSTOIT, VRCONTIMPOIT,
                     VRREDBCIMPOIT, VRBCALCIMPOIT, VRALIQIMPOIT, VRPDEDIMPOIT, VRIMPOSIT,
                     CDFISCIMPOIT,  NRSEQITPRO, IDVALORINFO,
                     VR1REDBCIMPOIT, IDTRIMPSTTI, VRIMPOSVISUIT, VRADICALIQFECP)

                  VALUES
                     (V_CDFILIAL, V_NRLANCTONF,   LPAD(C_ITEMPRODUTO.NRSEQITPROD, 4, '0'), C_ALIQITEM.CDIMPOSTO, (C_ITEMPRODUTO.VRTOTAITEM - C_ITEMPRODUTO.VRDESCITEM),
                      0, C_ITEMPRODUTO.VRTOTAITEM, C_ALIQITEM.VRALIQUOTA, 0, 0,
                      C_ALIQITEM.CDFISCTEMP, '1', 'N',
                      0, '0', 0, C_ALIQITEM.VRADICALIQFECP);
               ELSE
                  FOR C_TRABITPROIMPOS IN(SELECT IT.CDFILIAL, IT.NRLANCTONF, IT.NRSEQIMPOIT, IT.CDIMPOSTOIT,
                                                 B.SGIMPOSTO, B.IDTRATIMPO, B.IDPREIMPENTR, B.IDCONSISTENT,
                                                 IT.VRCONTITIMP, IT.VRPERREDBCIT, IT.VRBASECALCIT, IT.VRALIQITEM,
                                                 IT.VRIMPOSTOIT, IT.CDFISCALIT, IT.CDSITUTRIBIT, IT.CDFISCOPERIT,
                                                 IT.NRITPROIMPOS, IT.IDMODBCITNFE, IT.IDMODBCSTITNFE,
                                                 NVL(IT.VRADICALIQFECP, 0) AS VRADICALIQFECP,
                                                 NVL(IT.VRADICFECP, 0) AS VRADICFECP
                                            FROM INTG_TRABITPROIMPOS IT, IMPOSTO B
                                           WHERE NRACESSONFE    = P_NRACESSONFE
                                             AND B.CDIMPOSTO    = IT.CDIMPOSTOIT
                                             AND IT.NRSEQIMPOIT = C_ITEMPRODUTO.NRSEQITPROD
                                             AND IT.CDIMPOSTOIT = C_ALIQITEM.CDIMPOSTO
                                             AND B.CDENCARGOIMPXML IS NULL
                                           ORDER BY IT.CDFILIAL, IT.NRLANCTONF, IT.NRSEQIMPOIT, IT.CDIMPOSTOIT) LOOP


                     IF(C_TRABITPROIMPOS.VRIMPOSTOIT > 0) THEN
                        V_CDFISCALIT := '1';
                     ELSE
                        V_CDFISCALIT := '2';
                     END IF;

                     IF (LENGTH(C_TRABITPROIMPOS.CDSITUTRIBIT) = 2) THEN
                        V_CODIGOCST := C_TRABITPROIMPOS.CDSITUTRIBIT;
                     ELSE
                        IF (LENGTH(C_TRABITPROIMPOS.CDSITUTRIBIT) > 2) THEN
                           V_CODIGOCST := SUBSTR(C_TRABITPROIMPOS.CDSITUTRIBIT, 2,2);
                        END IF;
                     END IF;

                     V_CFOPXML := SUBSTR(C_ITEMPRODUTO.CDFISOPEITEM, 2, 3);

                     INSERT INTO TRABITPROIMPOS
                        (CDFILIMPOIT, NRLANCIMPOIT, NRSEQIMPOIT, CDIMPOSTOIT, VRCONTIMPOIT,
                         VRREDBCIMPOIT, VRBCALCIMPOIT, VRALIQIMPOIT, VRPDEDIMPOIT, VRIMPOSIT,
                         CDFISCIMPOIT,  CDSTRIBIMPOIT, CDFOPERIMPOIT, NRSEQITPRO, IDVALORINFO,
                         VR1REDBCIMPOIT, IDTRIMPSTTI, VRIMPOSVISUIT, CDSTRIBITNFE, VRADICALIQFECP, VRADICFECP)
                     VALUES
                        (V_CDFILIAL, V_NRLANCTONF, LPAD(C_ITEMPRODUTO.NRSEQITPROD, 4, '0'), C_TRABITPROIMPOS.CDIMPOSTOIT, (C_ITEMPRODUTO.VRTOTAITEM - C_ITEMPRODUTO.VRDESCITEM),
                         NVL(C_TRABITPROIMPOS.VRPERREDBCIT,  0), NVL(C_TRABITPROIMPOS.VRBASECALCIT, 0), C_TRABITPROIMPOS.VRALIQITEM, 0, C_TRABITPROIMPOS.VRIMPOSTOIT,
                         V_CDFISCALIT, V_DIG1CST||V_CODIGOCST, V_CFOP1DIGT||V_CFOPXML, C_TRABITPROIMPOS.NRITPROIMPOS, 'S',
                          0, '0', C_TRABITPROIMPOS.VRIMPOSTOIT, V_CODIGOCST, C_TRABITPROIMPOS.VRADICALIQFECP, C_TRABITPROIMPOS.VRADICFECP);

                  END LOOP;
               END IF;
            END LOOP;
            /* Caso algum imposto esteja marcado para que seja gerado como encarego */
            FOR C_TRABITPROIMPOS IN(SELECT IT.CDFILIAL, IT.NRLANCTONF, IT.NRSEQIMPOIT, IT.CDIMPOSTOIT,
                                           B.SGIMPOSTO, B.IDTRATIMPO, B.IDPREIMPENTR, B.IDCONSISTENT,
                                           IT.VRCONTITIMP, IT.VRPERREDBCIT, IT.VRBASECALCIT, IT.VRALIQITEM,
                                           IT.VRIMPOSTOIT, IT.CDFISCALIT, IT.CDSITUTRIBIT, IT.CDFISCOPERIT,
                                           IT.NRITPROIMPOS, IT.IDMODBCITNFE, IT.IDMODBCSTITNFE, B.CDENCARGOIMPXML,
                                           NVL(IT.VRADICALIQFECP, 0) AS VRADICALIQFECP,
                                           NVL(IT.VRADICFECP, 0) AS VRADICFECP
                                      FROM INTG_TRABITPROIMPOS IT, IMPOSTO B
                                     WHERE NRACESSONFE    = P_NRACESSONFE
                                       AND B.CDIMPOSTO    = IT.CDIMPOSTOIT
                                       AND IT.NRSEQIMPOIT = C_ITEMPRODUTO.NRSEQITPROD
                                       AND B.CDENCARGOIMPXML IS NOT NULL
                                     ORDER BY IT.CDFILIAL, IT.NRLANCTONF, IT.NRSEQIMPOIT, IT.CDIMPOSTOIT) LOOP


               UPDATE ITEMENCARGO
                  SET VRITEMENCA = VRITEMENCA + C_TRABITPROIMPOS.VRIMPOSTOIT + C_TRABITPROIMPOS.VRADICFECP
                WHERE CDENCARGO  = C_TRABITPROIMPOS.CDENCARGOIMPXML
                  AND CDFILIAL   = V_CDFILIAL
                  AND NRLANCTONF = V_NRLANCTONF;

               UPDATE ITEMPRODUTO
                  SET VRENCARGOIMPXML  = VRENCARGOIMPXML + C_TRABITPROIMPOS.VRIMPOSTOIT + C_TRABITPROIMPOS.VRADICFECP
                WHERE NRSEQITPROD = LPAD(C_ITEMPRODUTO.NRSEQITPROD, 4, '0')
                  AND CDFILIAL    = V_CDFILIAL
                  AND NRLANCTONF  = V_NRLANCTONF;


            END LOOP;
            /* Caso algum imposto esteja marcado para que seja gerado como encarego */

            DELETE
              FROM ALIQTEMPPROD
             WHERE NRALIQTEMP = V_CDFILIAL||V_NRLANCTONF;

            DELETE
              FROM INCITEMP
             WHERE NRINCITEMP = V_CDFILIAL||V_NRLANCTONF;
         END IF;

      END LOOP;

      /*  Baixar todos os itens da AF caso o parametro "Baixa total da AF no Lancamento da Nota Fiscal" esteja marcado*/
      BEGIN
         SELECT NVL(IDBAIXAFTOTLANNF, 'N') AS IDBAIXAFTOTLANNF
           INTO V_IDBAIXAFTOTLANNF
           FROM PARAMGERAL
          WHERE CDPARGERAL = '0001';
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_IDBAIXAFTOTLANNF:= 'N';
      END;

      IF (V_IDBAIXAFTOTLANNF = 'S') THEN
         FOR C_ITEMPRODUTO IN (SELECT DISTINCT LPAD(I.NRAUTOFORN, 10, '0') AS NRAUTOFORN,
                                               CDFILLANC, CDFILDEST
                                 FROM INTG_ITEMPRODUTO I, AUTOFORNE A
                                WHERE I.NRACESSONFE = P_NRACESSONFE
                                  AND LPAD(I.NRAUTOFORN, 10, '0') = A.NRAUTOFORN) LOOP

           UPDATE ITEMAUTF
              SET IDBAIXITMAF = '2',
                  QTEFETENTRAF = QTPROGENTAF
            WHERE CDFILDEST   = C_ITEMPRODUTO.CDFILDEST   AND
                  CDFILLANC   = C_ITEMPRODUTO.CDFILLANC   AND
                  NRAUTOFORN  = C_ITEMPRODUTO.NRAUTOFORN;

           UPDATE AUTOFORNE
              SET IDBAIXAAF = '2'
            WHERE CDFILDEST   = C_ITEMPRODUTO.CDFILDEST   AND
                  CDFILLANC   = C_ITEMPRODUTO.CDFILLANC   AND
                  NRAUTOFORN  = C_ITEMPRODUTO.NRAUTOFORN;

         END LOOP;
      END IF;


      IF (P_GERAIGUALXML = 'S') THEN
         FOR C_CONTAPAGAR IN(SELECT CDFILIAL, NRLANCTONF, NRSEQVENPAG, NRPARCELAPAG,
                                    CDTPCTPAGAR, QTDIASVENPAG, DTORIGVENPAG, VRORIGPAG
                               FROM INTG_CONTAPAGAR
                              WHERE NRACESSONFE = P_NRACESSONFE)LOOP

            INSERT INTO CONTAPAGAR
               (CDFILIAL,    NRLANCTONF,   NRSEQVENPAG,  NRPARCELAPAG,
                CDTPCTPAGAR, QTDIASVENPAG, DTORIGVENPAG, VRORIGPAG, VRATUAPAG, DTATUAVENPAG)
            VALUES
               (V_CDFILIAL, V_NRLANCTONF, LPAD(C_CONTAPAGAR.NRSEQVENPAG, 2, '0'), C_CONTAPAGAR.NRPARCELAPAG,
                C_CONTAPAGAR.CDTPCTPAGAR, (C_CONTAPAGAR.DTORIGVENPAG - SYSDATE), C_CONTAPAGAR.DTORIGVENPAG,
                C_CONTAPAGAR.VRORIGPAG, C_CONTAPAGAR.VRORIGPAG, C_CONTAPAGAR.DTORIGVENPAG);
         END LOOP;
      ELSE
         BEGIN
            SELECT NVL(IMPVENCXML, 'N')
              INTO V_IMPVENCXML
              FROM PARAMFORNE
             WHERE CDFORNECED = V_CDFORNECED;
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_IMPVENCXML := 'N';
         END;

         IF (V_IMPVENCXML = 'S') THEN
            FOR C_CONTAPAGAR IN(SELECT CDFILIAL, NRLANCTONF, NRSEQVENPAG, NRPARCELAPAG,
                                       CDTPCTPAGAR, QTDIASVENPAG, DTORIGVENPAG, VRORIGPAG
                                  FROM INTG_CONTAPAGAR
                                 WHERE NRACESSONFE = P_NRACESSONFE)LOOP
               INSERT INTO CONTAPAGAR
                  (CDFILIAL,    NRLANCTONF,   NRSEQVENPAG,  NRPARCELAPAG,
                   CDTPCTPAGAR, QTDIASVENPAG, DTORIGVENPAG, VRORIGPAG, VRATUAPAG, DTATUAVENPAG)
               VALUES
                  (V_CDFILIAL, V_NRLANCTONF, LPAD(C_CONTAPAGAR.NRSEQVENPAG, 2, '0'), C_CONTAPAGAR.NRPARCELAPAG,
                   C_CONTAPAGAR.CDTPCTPAGAR, (C_CONTAPAGAR.DTORIGVENPAG - SYSDATE), C_CONTAPAGAR.DTORIGVENPAG,
                   C_CONTAPAGAR.VRORIGPAG, C_CONTAPAGAR.VRORIGPAG, C_CONTAPAGAR.DTORIGVENPAG);
            END LOOP;
         END IF;
      END IF;   

      SELECT COUNT (DISTINCT CDFISOPEITEM), MIN(CDFISOPEITEM)
        INTO V_QTDCFOP, V_CDCFOPNF
        FROM ITEMPRODUTO
       WHERE CDFILIAL   = V_CDFILIAL
         AND NRLANCTONF = V_NRLANCTONF;

      IF (V_QTDCFOP > 1) THEN
         UPDATE NOTAFISCAL
            SET CDFISOPENTF  = '***'
          WHERE CDFILIAL     = V_CDFILIAL
            AND NRLANCTONF   = V_NRLANCTONF;

         UPDATE NOTAFISCAL
            SET DSCDFISOPENF = SUBSTR(DESCRICAO_CFOP(V_CDCFOPNF),1,45)
          WHERE (CDFILIAL    = V_CDFILIAL)
            AND (NRLANCTONF  = V_NRLANCTONF)
            AND DSCDFISOPENF IS NULL;

      ELSIF (V_QTDCFOP = 1) THEN
         UPDATE NOTAFISCAL
            SET CDFISOPENTF  = V_CDCFOPNF
          WHERE (CDFILIAL    = V_CDFILIAL)
            AND (NRLANCTONF  = V_NRLANCTONF);

         UPDATE NOTAFISCAL
            SET DSCDFISOPENF = SUBSTR(DESCRICAO_CFOP(V_CDCFOPNF),1,45)
          WHERE (CDFILIAL    = V_CDFILIAL)
            AND (NRLANCTONF  = V_NRLANCTONF)
            AND DSCDFISOPENF IS NULL;
      END IF;

      FOR C_TRABIMPOSNFTOT IN (SELECT SUM(T.VRIMPOSIT) VRTOTAIMPO, T.CDIMPOSTOIT
                                 FROM TRABITPROIMPOS T, IMPOSTO I
                                WHERE CDFILIMPOIT  = V_CDFILIAL
                                  AND NRLANCIMPOIT = V_NRLANCTONF
                                  AND IDPRODNOTA <> 'C'
                                  AND T.CDIMPOSTOIT = I.CDIMPOSTO
                                GROUP BY CDIMPOSTOIT
                                ORDER BY CDIMPOSTOIT)LOOP

          INSERT INTO TRABIMPOSNFTOT
                     (CDFILIMPTOT, NRLANCIMPTOT, CDIMPOSTOT, VRIMPOSTOT, VRBCALIMPTOT)

               VALUES(V_CDFILIAL, V_NRLANCTONF, C_TRABIMPOSNFTOT.CDIMPOSTOIT, (0 + C_TRABIMPOSNFTOT.VRTOTAIMPO), 0);
      END LOOP;

      GERA_FECHAMENTO_NFENTRADA(V_CDFILIAL, V_NRLANCTONF, V_DTENTRSAID, V_NRLANCESTQ, V_CDOPERADOR);

      UPDATE ITLANCTOEST
         SET IDEVOLESTOQ  = 'N'
       WHERE CDFILIAL     = V_CDFILIAL
         AND NRLANCESTQ   = V_NRLANCESTQ;

      VERIFICA_INCONS_NF(P_NRACESSONFE, P_GERAIGUALXML, 'S', V_NRLANCTONF, V_CDFILIAL, V_LIBERAXML, P_CDTIPOOPER, V_LIBERAOPER, V_ERRO);

      IF (V_ERRO = 'S') THEN
         V_ROLLBACK := 'S';

         FOR C_INCONS IN (SELECT NRSEQINCONS, CDCONSISTXML, DSINCONSIS
                            FROM INTG_INCONSISTENCIA
                           WHERE NRACESSONFE = P_NRACESSONFE
                           ORDER BY NRSEQINCONS)LOOP

            IF V_ROLLBACK = 'S' THEN
               ROLLBACK;
               V_ROLLBACK := 'N';
            END IF;
            INSERT
              INTO INTG_INCONSISTENCIA (NRACESSONFE, NRSEQINCONS, CDCONSISTXML, DSINCONSIS)
            VALUES (P_NRACESSONFE, C_INCONS.NRSEQINCONS, C_INCONS.CDCONSISTXML, C_INCONS.DSINCONSIS);

            UPDATE INTG_NOTAFISCAL
               SET IDSTATUS = 'I'
             WHERE NRACESSONFE = P_NRACESSONFE;
         END LOOP;

         /*OPEN C_INCONS;
         LOOP
         BEGIN
            FETCH C_INCONS INTO C_NRSEQINCONS,
                                C_CDCONSISTXML,
                                C_DSINCONSIS;

            IF V_ROLLBACK = 'S' THEN
               ROLLBACK;
               V_ROLLBACK := 'N';
            END IF;

            EXIT WHEN C_INCONS%NOTFOUND;
               INSERT
                 INTO INTG_INCONSISTENCIA (NRACESSONFE, NRSEQINCONS, CDCONSISTXML, DSINCONSIS)
               VALUES (P_NRACESSONFE, C_NRSEQINCONS, C_CDCONSISTXML, C_DSINCONSIS);

               UPDATE INTG_NOTAFISCAL
                  SET IDSTATUS = 'I'
                WHERE NRACESSONFE = P_NRACESSONFE;
         EXCEPTION
            WHEN OTHERS THEN
            IF (V_ROLLBACK = 'N') THEN
               COMMIT;
            END IF;
         END;

         END LOOP;

         CLOSE C_INCONS; */
         
      ELSE
         V_COUNTINCONS := 0;
         BEGIN
            SELECT COUNT(1)
              INTO V_COUNTINCONS
              FROM INTG_INCONSISTENCIA
             WHERE NRACESSONFE = P_NRACESSONFE;
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_COUNTINCONS := 0;
         END;
         IF (V_COUNTINCONS > 0) THEN
            UPDATE INTG_NOTAFISCAL
               SET CDFILIAL     = V_CDFILIAL,
                   NRLANCTONF   = V_NRLANCTONF,
                   DTUTILIZAXML = SYSDATE,
                   IDIMPORTADA  = 'S',
                   IDSTATUSNFE  = 'U',
                   IDSTATUS     = 'I'
             WHERE NRACESSONFE  = P_NRACESSONFE;
         ELSE
            UPDATE INTG_NOTAFISCAL
               SET CDFILIAL     = V_CDFILIAL,
                   NRLANCTONF   = V_NRLANCTONF,
                   DTUTILIZAXML = SYSDATE,
                   IDIMPORTADA  = 'S',
                   IDSTATUSNFE  = 'U',
                   IDSTATUS     = 'L'
             WHERE NRACESSONFE  = P_NRACESSONFE;

            UPDATE NOTAFISCAL
               SET IDSTATUS     = 'L'
             WHERE NRACESSONFE  = P_NRACESSONFE
               AND IDENTRSAIDOP = 'E';
         END IF;
      END IF;
   ELSE
      UPDATE INTG_NOTAFISCAL
         SET IDSTATUS = 'I'
       WHERE NRACESSONFE = P_NRACESSONFE;
   END IF;
   COMMIT;
END;
/