CREATE OR REPLACE PROCEDURE IMPOSTO_ENTRADA
(
        P_EMPRESA  IN ALIQUOTA.CDEMPRESA%TYPE,                    --EMPRESA
        P_INSCESTA IN ALIQUOTA.CDINSCESTA%TYPE,                   --INSCRIÇÃO ESTADUAL
        P_TIPOOPER IN INCIDENCIA.CDTIPOOPER%TYPE,                 --TIPO DE OPERAÇÃO
        P_FORNECED IN FORNECEDOR.CDFORNECED%TYPE,                 --CÓDIGO FORNECEDOR
        P_FILIAL   IN NOTAFISCAL.CDFILIAL%TYPE,                   --FILIAL
        P_LANCTONF IN NOTAFISCAL.NRLANCTONF%TYPE,                 --Nº LANCAMENTO
        P_INIVALID IN ALIQUOTA.DTINIVALID%TYPE,                   --DATA DE INICIO DE VALIDADDE
        P_VRNOTAFISC OUT NUMBER,                                  --VALOR DA NF RETORNADO
        P_LANCESTQ IN LANCTOESTOQ.NRLANCESTQ%TYPE DEFAULT NULL,   --Nº LANCAMENTO DE ESTOQUE. SE NULO, NÃO ATUALIZA ESTOQUE
        P_ENTRSAID IN NOTAFISCAL.IDENTRSAIDOP%TYPE DEFAULT 'E',   --PARÂMETRO P/ IMPORTACAO DE NOTAS DE SAÍDA
        P_CDOPERADOR IN LANCTOESTOQ.CDOPERADOR%TYPE DEFAULT NULL,
        P_AUDIT      IN VARCHAR2 DEFAULT NULL) --CÓDIGO OPERADOR
IS
   V_PAISORIG     VARCHAR2(04);
   V_ESTAORIG     VARCHAR2(02);
   V_MUNIORIG     VARCHAR2(04);
   V_PAISDEST     VARCHAR2(04);
   V_ESTADEST     VARCHAR2(02);
   V_MUNIDEST     VARCHAR2(04);
   V_PAISCFOP     VARCHAR2(04);
   V_ESTACFOP     VARCHAR2(02);
   V_CDPAISST     VARCHAR2(04);
   V_SGESTADOST   VARCHAR2(02);
   V_CDMUNICIPIOST VARCHAR2(04);
   V_CDINSCESTAST VARCHAR2(16);
   V_ALIQTEMP     VARCHAR2(14);
   V_INCITEMP     VARCHAR2(14);
   V_CSTTEMP      VARCHAR2(14);
   V_CFOPTEMP     VARCHAR2(14);
   V_FISOPEITEM   VARCHAR2(11);
   V_SUFXCFOPPR   VARCHAR2(03);
   V_SITUTRIBPR   VARCHAR2(03);
   V_IDTRIMPSTII  CHAR(1);
   V_CDIMPOSTRIB  VARCHAR2(250);
   V_IMPOSTRIBCOMPLANC VARCHAR2(02);
   V_NRINSJURNF   VARCHAR2(20);
   V_SERIE        VARCHAR2(05);
   V_TIPOMOVI     CHAR(1);
   V_CDFILIRECE   VARCHAR2(04);
   V_CDFILIEMIT   VARCHAR2(04);
   V_INTEGRACAO   VARCHAR2(16);
   V_CDFISOPENTF  VARCHAR2(11);
   V_IDVALORINFO  CHAR(1);
   V_NRNOTAFISC   VARCHAR2(20);
   V_NRSEQITPROD  VARCHAR2(04);
   V_CDPRGENEREV  VARCHAR2(10);
   V_IDDOCFINANC  CHAR(1);
   V_IDSTATUS     CHAR(1);
   V_IDORIGDESTNF CHAR(1);
   V_NMTIPOOPER   VARCHAR2(30);
   V_NMFILIEMIT   VARCHAR2(60);
   V_DESCLANC     VARCHAR2(60);
   V_IDDOCREPLIC  VARCHAR2(14);
   V_IDSISTEMA    VARCHAR2(03);
   V_IDRETPROEXP  CHAR(1);
   V_FILIORIG     VARCHAR2(04);
   V_DEVOLORIG    VARCHAR2(10);
   V_IDCTRLESTQ   CHAR(1);
   V_IDORDPRIMDFENT VARCHAR2(02);
   V_IDTPFORPGTFO CHAR(1);
   V_IDFORMAPUR   CHAR(1);
   V_IDATUEST     CHAR(1);
   V_IDTPIJURNF   CHAR(1);
   V_DTENTRSAID   DATE;
   V_NOTAFISC     NUMBER;
   V_IDVRIMPSTRIB CHAR(1);
   V_CDSITTRIBTMP    CODSITUTRIBNFE.CDSITUTRIBNFE%TYPE;
   V_IDMODBCNFE      CODSITUTRIBNFE.IDMODBCNFE%TYPE;
   V_IDMODBCSTNFE    CODSITUTRIBNFE.IDMODBCSTNFE%TYPE;
   V_CDTPCRPICOSTNFE CODSITUTRIBNFE.CDTPCRPICOSTNFE%TYPE;
   V_CDNATUBCPCSTNFE CODSITUTRIBNFE.CDNATUBCPCSTNFE%TYPE;
   V_IDMOTIDESSTNFE  CODSITUTRIBNFE.IDMOTIDESSTNFE%TYPE;

   --VARIÁVEIS PARA NOTA DE COMPLEMENTO
   V_CDFISCALCOMP     VARCHAR2(01);
   V_SITUTRIBCOMP     CODSITUTRIBNFE.CDSITUTRIBNFE%TYPE;
   V_IDMODBCNFECOMP   CODSITUTRIBNFE.IDMODBCNFE%TYPE;
   V_IDMODBCSTNFECOMP CODSITUTRIBNFE.IDMODBCSTNFE%TYPE;
   V_TOTALITEMCOMP    NUMBER;

   V_IDINTEREST   VARCHAR2(01);
   V_IDINTERNAC   VARCHAR2(01);

   V_PARDEDTMP    NUMBER;
   V_PREDBCTMP    NUMBER;
   V_PREDBCTMP1   NUMBER;
   V_ALIQUTMP     NUMBER;
   V_PBCSUBTRIB   NUMBER;
   V_TAXABCSUBSTR NUMBER;
   V_VRIMPOSTOST  NUMBER;
   V_VRPPRIIMPST  NUMBER;
   V_COUNT        NUMBER;
   V_LIQUIITEM    NUMBER;
   V_LIQUIDOPROD  NUMBER;
   V_TOTALNOTA    NUMBER;
   V_LIQUIDO      NUMBER;
   V_VRPRODUTOS   NUMBER;
   V_VRCOMPLEMEN  NUMBER;
   V_SOMAENCA     NUMBER;
   V_MENOENCA     NUMBER;
   V_SOMAIMPO     NUMBER;
   V_MENOIMPO     NUMBER;
   V_TOTAPRODENCA NUMBER;
   V_TOTAPRENIMPO NUMBER;
   V_TOTAIMPBCALC NUMBER;
   V_TOTAIMPBCINF NUMBER;
   V_TAXABASECALC NUMBER;
   V_TOTAIMPBCDES NUMBER;
   V_TAXAALIQFECP NUMBER;   
   V_TAXAALIQUOTA NUMBER;
   V_PRODUENCARGO NUMBER;
   V_SEQUIMPOSTNF NUMBER;
   V_SOMAITEM     NUMBER;
   V_DESCITEM     NUMBER;
   V_BASECALCIT   NUMBER;
   V_IMPOSTOIT    NUMBER;
   V_IMPOSTORED1  NUMBER;
   V_FATOCONV     NUMBER;
   V_TOTABRUT     NUMBER;
   V_QTDELANCTO   NUMBER;
   V_VRUNITLANCTO NUMBER;
   V_VRTOTALANCTO NUMBER;
   V_TOTACONTAB   NUMBER;
   V_VRBRUTO      NUMBER;
   V_VRCONTAB     NUMBER;
   V_IMPOCONTAB   NUMBER;
   V_TOTIMPOCONT  NUMBER;
   V_TOTIMPOBRUT  NUMBER;
   V_CONTIMPO     NUMBER;
   V_ALIQINFO     NUMBER;
   V_TAXAALIQINFO NUMBER;
   V_IMPOSINFO    NUMBER;
   V_VRPERREDBCIT NUMBER;
   V_VRBASECALCIT NUMBER;
   V_CONTABCALC   NUMBER;
   V_PERDBCALC    NUMBER;
   V_TOTAPROD     NUMBER;
   V_VRDIFERENCA  NUMBER;
   V_VRNOTAFISC   NUMBER;
   V_VRTOTIMPONF  NUMBER;
   V_IMPOSRETI    NUMBER;
   V_VRCONTAREC   NUMBER;
   V_NRDECITOTANF NUMBER;
   V_EXISTE_ROT   NUMBER;
   V_VRCUSTENTR   NUMBER;
   V_VALRDESCITEM NUMBER;
   V_VRIMPOSCONT  NUMBER;
   V_VRREDUCAO    NUMBER;
   V_NRIMPOSTO    NUMBER;
   V_MINBCPROD    NUMBER;
   V_VRTOTAITEM   NUMBER;
   V_SOMATOTAITEM NUMBER;
   V_PERCENTITEM  NUMBER;

   /*VARIÁVEIS PARA DIFERENCIAL DE ALÍQUOTA*/
   V_ALIQDIFE     NUMBER;
   V_ALIQDEST     NUMBER;
   V_IMPOSTODIFE  NUMBER;
   V_BCALCDIFCOMP NUMBER;
   V_IDCALCDIFENTFISC VARCHAR2(01);

   V_CDGRUPOFISC  VARCHAR2(03);
   V_CDGRPFISCSV  VARCHAR2(03);
   V_UTGRUPFISCS  VARCHAR2(01);

   V_CDORIGDESTNF VARCHAR2(21);

   V_CDALMOXARIFE VARCHAR2(06);
   V_CDLOCALESTOQ VARCHAR2(06);

   V_DIFALIQITEM      CHAR(01);
   V_IDDIFALIQCUSPRC  CHAR(01);

   V_CDCSTDIGI    VARCHAR2(03);
   V_IMPOSITEM    VARCHAR2(14);

   V_IDOPERDEVONF CHAR(1);
   V_IDUTCUSORIGEST CHAR(1);   
   V_IDNFOUTRASNF CHAR(1);
   V_QTDEREGTRAB  NUMBER;
   V_IDACRPRODENTRNF VARCHAR2(01);

   /* NOTA FISCAL DE IMPORTAÇÃO */
   V_IDNFIMPORTACAO VARCHAR2(01);

   /*VARIÁVEIS PARA CALCULO DO CUSTO LOGISTICO*/
   V_VRPESOBRUTPR   NUMBER;
   V_VRPECUSTOLOG   NUMBER;
   V_VRVRCUSTOLOG   NUMBER;
   V_VRPESEGURLOG   NUMBER;
   V_VRCUSTOLOG     NUMBER;
   V_VRCUSTOSEG     NUMBER;

   V_CDFORNECED     VARCHAR2(21);
   V_IDENDCFOP      VARCHAR2(01);
   V_DSCDFISOPEIT   VARCHAR2(100);

   V_DADOADIC       VARCHAR(03);
   V_CDEMPRESA      VARCHAR(02);
   V_CDINSCESTA     VARCHAR(16);
   V_VRFRETEITEM        FLOAT;
   V_VRSEGURITEM        FLOAT;
   V_VRENCARGODESC      FLOAT;
   V_DIFERENCA          FLOAT;
   V_VROUTRASDESPITEM   FLOAT;
   V_VRDESPADUANEIRA    FLOAT;
   V_SUMVRDESCITEM      FLOAT;
   V_IMPOSDESONERA      FLOAT;


   W_F              CHAR(1) := 'F';
   W_S              CHAR(1) := 'S';
   W_N              CHAR(1) := 'N';
   W_DFE            CHAR(3) := 'DFE';
   W_L              CHAR(1) := 'L';
   W_C              CHAR(1) := 'C';
   W_E              CHAR(1) := 'E';
   W_P              CHAR(1) := 'P';
   W_R              CHAR(1) := 'R';
   W_D              CHAR(1) := 'D';
   W_A              CHAR(1) := 'A';
   W_V              CHAR(1) := 'V';
   W_M              CHAR(1) := 'M';
   W_1              CHAR(1) := '1';
   W_2              CHAR(1) := '2';
   W_3              CHAR(1) := '3';
   W_00000          CHAR(5) := '00000';
   W_000            CHAR(3) := '000';
   W_EXP            CHAR(3) := 'EXP';
   W_PDV            CHAR(3) := 'PDV';
   W_VMN            CHAR(3) := 'VMN';
   W_I              CHAR(1) := 'I';

   V_VRIMPDIFALIQ   NUMBER;

   V_CDTIPCUSTEST   NUMBER;
   V_DTSAIDNFORIG   DATE;
   V_DTATUAL        DATE;

   V_NRSEQITIMP     VARCHAR2(04);
   V_NRIMPOSNF      VARCHAR2(02);
   V_CDFISCOPERSN   VARCHAR2(04);
   V_IMPOICMS       VARCHAR(02);

   V_VRFATOCONV     NUMBER;

   V_IDIMPOBCALTPOP  VARCHAR2(01);
   V_IDIMBCALTPOPDE  VARCHAR2(01);
   V_CDIMPOBCALC     VARCHAR2(02);
   V_IDNOTADEVO      VARCHAR2(01);
   V_IDPERALTCSTFENF VARCHAR2(01);

   V_CDSITUTRIBIT  VARCHAR2(03);
   V_CDFISCOPERIT  VARCHAR2(11);
   V_CDSUFXCFOPIT  VARCHAR2(03);

   V_CFOP1DIGT     VARCHAR2(01);

   V_CDFILIREDU    VARCHAR2(04);
   V_VRCONTITIMP   FLOAT;

   V_IDREDUCAO     VARCHAR2(01);
   V_CDGRUPOFISCAUX  VARCHAR2(03);

   V_CDREGRAITALIQ VARCHAR2(10);

   V_IDSUGMODNF    VARCHAR2(01);

   V_VRTOTBRUT     FLOAT;
   V_VRTOTANF      FLOAT;
   V_DIFBRUTNF     FLOAT;
   V_ICMS          VARCHAR2(01);
   V_CDCFOPINFUSU  VARCHAR2(11);
   V_DSCFOPINFUSU  VARCHAR2(50);
   V_CST1DIGT      VARCHAR2(1);
   V_IDNFGERADAVIAXML VARCHAR2(01);
   V_IDGERNFIGUALXML VARCHAR2(01);

   V_POSSUIFINANC   FLOAT;
   P_RESULTADO      VARCHAR2(50);
   V_IDUTILVENC     VARCHAR2(01);

   V_IDUTILPVRIMPBC VARCHAR2(01);

   V_ALIQPISIMP     FLOAT;
   V_CALCPISIMP     VARCHAR2(01);
   V_CDPISIMP       VARCHAR2(02);
   V_NRITPISIMP     VARCHAR2(01);
   V_CDPISNFE       VARCHAR2(02);
   V_PRODPISIMP     VARCHAR2(04);
   V_VRPISIMP       FLOAT;

   V_ALIQCOFIMP     FLOAT;
   V_CALCCOFIMP     VARCHAR2(01);
   V_CDCOFIMP       VARCHAR2(02);
   V_NRITCOFIMP     VARCHAR2(01);
   V_CDCOFNFE       VARCHAR2(02);
   V_PRODCOFIMP     VARCHAR2(04);
   V_VRCOFIMP       FLOAT;

   V_ALIQIMPII      FLOAT;
   V_CALCIIIMP      VARCHAR2(01);
   V_CDIIIMP        VARCHAR2(02);
   V_NRITIIIMP      VARCHAR2(01);
   V_CDIINFE        VARCHAR2(02);
   V_PRODIIIMP      VARCHAR2(04);
   V_VRIIIMP        FLOAT;

   V_ALIQIPIIMP     FLOAT;
   V_CALCIPIIMP     VARCHAR2(01);
   V_CDIPIIMP       VARCHAR2(02);
   V_NRITIPIIMP     VARCHAR2(01);
   V_CDIPINFE       VARCHAR2(02);
   V_PRODIPIIMP     VARCHAR2(04);
   V_VRIPIIMP       FLOAT;

   V_ALIQICMSIMP    FLOAT;
   V_CALCICMSIMP    VARCHAR2(01);
   V_CDICMSIMP      VARCHAR2(02);
   V_NRITICMSIMP    VARCHAR2(01);
   V_CDICMSNFE      VARCHAR2(02);
   V_PRODICMSIMP    VARCHAR2(04);
   V_VRICMSIMP      FLOAT;
   V_IDNFPRESTSERV  VARCHAR2(01);
   V_IDEMISFILNFSERV VARCHAR2(01);
   V_IDUTLOCPRESTSERV VARCHAR2(01);
   V_ESTAPRESTSERV    VARCHAR2(02);
   V_MUNIPRESTSERV    VARCHAR2(04);
   V_IDCOMPRABONI   VARCHAR2(01);
   V_COMPCUSTPROD   VARCHAR2(01);
   V_CARGA          FLOAT;

   V_IDENDEMIS     VARCHAR2(01);

   V_CDFISCOPERREGRA     VARCHAR2(10);
   V_DSCDFISOPEITREGRA   VARCHAR2(50);
   V_IDDIFEALIQREGRA     VARCHAR2(10);
   V_IDDIFALIQCUSPRREGRA VARCHAR2(10);

   V_IDIMPORTAIMPXML     VARCHAR2(01);
   
   --VARIÁVEIS PARA ATUALIZAR ESTOQUE POR CFOP
   V_ATUPORCFOP    VARCHAR2(01);
   V_CFOPTPOPER    FLOAT;
   V_CFOPATUEST    FLOAT;
   V_IDNFRETIND    VARCHAR2(01);

   V_CDPRODORIG    VARCHAR2(10);

   V_DSENDEDEVOEMBA    VARCHAR2(255);
   V_RESULT_GERA_EST   VARCHAR2(50);

   V_NRACESSONFE       VARCHAR2(44);
   V_ENCIMPXML         VARCHAR2(05);

   /* variáveis para geração de saída no estoque (filial agente de terceiração) */
   V_CDFILIAGENT       VARCHAR2(04);
   V_BOLANESTSAIDAG    BOOLEAN := TRUE;
   V_NRLANESTENTRAG    NOVOCODIGO.NRSEQUENCIAL%TYPE;
   V_CDALMOXARIFEAG    ALMOXARIFADO.CDALMOXARIFE%TYPE;
   V_CDLOCALESTOQAG    LOCALESTOQUE.CDLOCALESTOQ%TYPE;
   V_IDUTILLOTEAG      VARCHAR2(01);
   V_NRLOTEESTQAG      VARCHAR2(20);
   V_NRSUBLOTEAG       VARCHAR2(04);
   V_NRLANCTONFAG      VARCHAR2(20);
   V_CDEMPRESAAG       VARCHAR2(02);
   V_CDINSCESTAAG      VARCHAR2(16);
   V_CDINSCMUNIAG      VARCHAR2(16);
   V_CDFORNAGETERC     VARCHAR2(21);
   V_IDUTORIGPROD      VARCHAR2(01);
   V_TPOPERREMESSA     VARCHAR2(02);

   V_VRPERDIFERE       FLOAT;
   V_PERDIFERE         FLOAT;
   V_IMPOSTOOPERA      FLOAT;
   V_IMPOSTODIFER      FLOAT;

   V_VRIMPOSTOOPERAIT  FLOAT;
   V_VRPERDIFEREIT     FLOAT;
   V_VRIMPOSTODIFERIT  FLOAT;
   
   V_CDFILIALSAGA      VARCHAR2(20);
   V_IDATUESTLANCNFE   VARCHAR2(1);

   V_CDFILIOLAGETERC   VARCHAR2(04);

   V_IDTRATIMPO        VARCHAR2(01);
   V_VRIMPANTE         FLOAT;
   V_VRIMPAPOS         FLOAT;
   V_IDNFAJUSTE        VARCHAR2(01);

   V_IDIMPDESONERA     VARCHAR2(01);
   V_IDENTEMIS         VARCHAR2(01);

   V_VRADICALIQFECP    FLOAT;
   V_VRADICFECP        FLOAT;
   V_SOMAVRADICFECP    FLOAT;

   V_VRIMPORETNF       FLOAT;
   V_VRIMPORELAC       FLOAT;

   V_IDCALCVRTOTANFE   VARCHAR2(01);

   V_CDBENEFFISCAL     VARCHAR2(10);
   V_CDCEST            VARCHAR2(09);
   V_CASASDEC     NUMBER;
   V_DSNOTAFISORIGOL VARCHAR2(14);
   V_IDCONSDIFALIQ     VARCHAR2(01);
   V_VRICMSNF          NUMBER;
   V_VRALIQICMSINT     NUMBER;
   V_ALIQICMS          NUMBER;
   V_CDIMPOSTOICMS     VARCHAR2(02);
   V_ALIQSTDIF         NUMBER;
   V_BASECALCDIF       NUMBER;
   V_IMPOSTODIF        NUMBER;
BEGIN
   V_CDCFOPINFUSU := '';

--VARIÁVEIS COM A CHAVE PARA AS TABELAS TEMPORÁRIAS

   V_ALIQTEMP := P_FILIAL||P_LANCTONF;
   V_INCITEMP := P_FILIAL||P_LANCTONF;
   V_CSTTEMP  := P_FILIAL||P_LANCTONF;
   V_CFOPTEMP := P_FILIAL||P_LANCTONF;
---------------------------------------------------------------------------------------------------------

   BEGIN
      SELECT
         IDTPIJURNF,             NRINSJURNF,     CDSERIEENTR,    CDFILIRECE,
         CDINTEGRACAO,           NVL(VRNOTAFISC,0),     CDFILIEMIT,     DTENTRSAID,
         NRNOTAFISC,             IDDOCFINANC,    IDSTATUS,
         NVL(IDORIGDESTNF, W_F), IDDOCREPLIC,
         NVL(P.IDCTRLESTQ, W_S), NVL(IDSISTEMA, W_DFE), NVL(TO_NUMBER(P.CDTIPCUSTEST),3), NVL(P.DTPROCESSA, SYSDATE),
         IDNFGERADAVIAXML, CDFILIALSAGA, IDATUESTLANCNFE, SGESTADO, CDMUNICIPIO, NRACESSONFE, DSNOTAFISORIGOL,
         CDCFOPINFUSU, DSCFOPINFUSU
      INTO V_IDTPIJURNF,   V_NRINSJURNF,  V_SERIE,       V_CDFILIRECE,
           V_INTEGRACAO,   V_NOTAFISC,    V_CDFILIEMIT,  V_DTENTRSAID,
           V_NRNOTAFISC,   V_IDDOCFINANC, V_IDSTATUS,
           V_IDORIGDESTNF, V_IDDOCREPLIC,
           V_IDCTRLESTQ,   V_IDSISTEMA, V_CDTIPCUSTEST, V_DTATUAL,
           V_IDNFGERADAVIAXML, V_CDFILIALSAGA, V_IDATUESTLANCNFE, V_ESTAPRESTSERV, V_MUNIPRESTSERV, V_NRACESSONFE, V_DSNOTAFISORIGOL,
           V_CDCFOPINFUSU,    V_DSCFOPINFUSU
      FROM NOTAFISCAL N, PARAMFILIAL P
      WHERE N.CDFILIAL = P_FILIAL      AND
            NRLANCTONF = P_LANCTONF    AND
            CDFILIRECE = P.CDFILIAL(+);
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_IDTPIJURNF   := NULL;  V_NRINSJURNF    := NULL;   V_SERIE      := NULL;   V_CDFILIRECE := NULL;
         V_INTEGRACAO   := NULL;  V_NOTAFISC      := 0;      V_CDFILIEMIT := NULL;   V_DTENTRSAID := NULL;
         V_NRNOTAFISC   := NULL;  V_IDDOCFINANC   := NULL;   V_IDSTATUS   := NULL;
         V_IDORIGDESTNF := W_F;   V_IDDOCREPLIC   := NULL;
         V_IDCTRLESTQ   := W_S;   V_IDSISTEMA     := W_DFE;  V_CDTIPCUSTEST := 3; V_DTATUAL := SYSDATE;
         V_ESTAPRESTSERV := NULL; V_MUNIPRESTSERV := NULL;   V_NRACESSONFE := NULL; V_DSNOTAFISORIGOL := NULL;
         V_CDCFOPINFUSU  := NULL; V_DSCFOPINFUSU  := NULL;
   END;

   BEGIN
      SELECT CDFILIAL||NRLANCESTQ
      INTO V_IDDOCREPLIC
      FROM LANCTOESTOQ
      WHERE CDFILIAL   = SUBSTR(V_IDDOCREPLIC, 1, 4) AND
            NRLANCTONF = SUBSTR(V_IDDOCREPLIC, 5, 10);
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_IDDOCREPLIC := NULL;
   END;

   --SE O DOCUMENTO NÃO FOI CRIADO POR REPLICAÇÃO DE DOCUMENTOS
   IF V_IDDOCREPLIC IS NULL THEN
      BEGIN
         SELECT CDFILIAL||NRLANCESTQ
         INTO V_IDDOCREPLIC
         FROM LANCTOESTOQ
         WHERE CDFILIAL   = SUBSTR(V_INTEGRACAO, 1, 4) AND
               NRLANCTONF = SUBSTR(V_INTEGRACAO, 5, 10);
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_IDDOCREPLIC := NULL;
      END;
   END IF;

   --VARIÁVEIS PARA ARMAZENAMENTO DOS PARÂMETROS DE FATURAMENTO GERAIS,
   --NÚMERO DE CASAS DECIMAIS UTILIZADO NAS TOTALIZAÇÕES DAS NF´S
   --IDENTIFICADOR DE PERMISSÃO DE LANÇAMENTO DE NF ATRAVÉS DE OUTRAS NF´S (ESNF X ATRASADA)
   BEGIN
      SELECT SUBSTR(DSPARAMFATGE,73,10), NVL(NRDECITOTANF, 2), NVL(IDNFOUTRASNF, W_N), IDPERALTCSTFENF, NVL(IDSUGMODNF, W_N),
             NVL(IDGERNFIGUALXML, 'N'), NVL(IDUTORIGPROD, 'N') AS IDUTORIGPROD, NVL(IDCALCVRTOTANFE, 'N') AS IDCALCVRTOTANFE
      INTO   V_CDPRGENEREV,              V_NRDECITOTANF,       V_IDNFOUTRASNF,         V_IDPERALTCSTFENF, V_IDSUGMODNF,
             V_IDGERNFIGUALXML, V_IDUTORIGPROD, V_IDCALCVRTOTANFE

      FROM PARAMGERAL;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_CDPRGENEREV := NULL; V_NRDECITOTANF := 2; V_IDNFOUTRASNF := W_N; V_IDPERALTCSTFENF := W_N; V_IDUTORIGPROD := 'N';
         V_IDCALCVRTOTANFE := 'N';
   END;

   IF V_INTEGRACAO IS NOT NULL THEN
      IF P_ENTRSAID = W_S THEN
         V_CDFILIRECE := V_CDFILIEMIT;
      END IF;
   END IF;

-------------------------------------------------------------------------------------------------------
--MAIOR REGISTRO DA TABELA DE DADOS ADICIONAIS
   SELECT MAX(NRDADOADIC)
     INTO   V_DADOADIC
     FROM DADOSADIC
    WHERE (CDFILIAL   = P_FILIAL) AND
          (NRLANCTONF = P_LANCTONF);

   IF (V_DADOADIC IS NULL) THEN
      V_DADOADIC := '001';
   ELSE
      V_DADOADIC := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_DADOADIC) + 1)),3,0);
      /*GERA O PROXIMO SEQUENCIAL A SER INSERIDO*/
   END IF;

   FOR C_MENSINSC IN (SELECT M.CDMENSAGEM, M.DSMENSAGEM
                        FROM MENSINSCRESTAD I, MENSAGEM M
                       WHERE (I.CDEMPRESA = P_EMPRESA)
                         AND (I.CDINSCESTA = P_INSCESTA)
                         AND (I.CDMENSAGEM = M.CDMENSAGEM)
                         AND (I.IDENTRSAIDMENS <> 'S')
                         AND (M.IDSITUACAOMENS  = 'A')
                         AND (I.DSMENSINSCRESTA NOT IN (SELECT DSDADOADIC
                                                          FROM DADOSADIC
                                                         WHERE (CDFILIAL = P_FILIAL)
                                                           AND (NRLANCTONF = P_LANCTONF)))) LOOP

      /*PREENCHE AS MENSAGENS ATRELADAS A INSCRICAO ESTADUAL*/

      INSERT INTO DADOSADIC(CDFILIAL, NRLANCTONF, NRDADOADIC, CDMENSAGEM, DSDADOADIC)
                     VALUES(P_FILIAL, P_LANCTONF, V_DADOADIC, C_MENSINSC.CDMENSAGEM, C_MENSINSC.DSMENSAGEM);

      V_DADOADIC := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_DADOADIC) + 1)),3,0);

   END LOOP;
----------------------------------------------------------------------------------------------------------

   IF V_IDORIGDESTNF = 'C' THEN
      FOR C_MENSCLIENTE IN (SELECT M.CDMENSAGEM, C.DSMENSCLIENTE
                              FROM MENSCLIENTE C LEFT JOIN MENSAGEM M ON (M.CDMENSAGEM = C.CDMENSAGEM)
                             WHERE C.CDCLIENTE = P_FORNECED
                               AND C.IDENTRSAIDMENS <> 'S'
                               AND (((C.CDMENSAGEM IS NOT NULL) AND (M.IDSITUACAOMENS  = 'A')) OR (C.CDMENSAGEM IS NULL))
                               AND NOT EXISTS (SELECT DSDADOADIC
                                                 FROM DADOSADIC
                                                WHERE (CDFILIAL = P_FILIAL)
                                                  AND (NRLANCTONF = P_LANCTONF)
                                                  AND (DSDADOADIC LIKE C.DSMENSCLIENTE || '%'))
                             ORDER BY C.NRMENSCLIENTE)
      LOOP

         INSERT INTO DADOSADIC
            (CDFILIAL,
             NRLANCTONF,
             NRDADOADIC,
             CDMENSAGEM,
             DSDADOADIC)
         VALUES
            (P_FILIAL,
             P_LANCTONF,
             V_DADOADIC,
             C_MENSCLIENTE.CDMENSAGEM,
             C_MENSCLIENTE.DSMENSCLIENTE);

         V_DADOADIC := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_DADOADIC) + 1)),3,0);
      END LOOP;
   END IF;

   BEGIN
      SELECT TRANSLATE(SUBSTR('Devolver as embalagens vazias no seguinte endereço: ' ||
             PRE.DSPOSTORECEMB ||
             ', ' || PRE.DSENDERECEMB ||
             CASE NVL(PRE.DSCOMPENDERECEMB, '!X!X!') WHEN '!X!X!' THEN '' ELSE ', ' || PRE.DSCOMPENDERECEMB END ||
             ', ' || B.NMBAIRRO ||
             ', CEP:' || PRE.NRCEPRECEMB ||
             ', ' || M.NMMUNICIPIO ||
             ', ' || E.SGESTADO ||
             ', ' || P.NMPAIS ||
             CASE NVL(PRE.NRTELERECEMB, '!X!X!') WHEN '!X!X!' THEN '' ELSE '. Telefone: ' || PRE.NRTELERECEMB END ||
             CASE NVL(PRE.NRFAXRECEMB, '!X!X!') WHEN '!X!X!' THEN '' ELSE '. FAX: ' || PRE.NRFAXRECEMB END, 1, 255), 'áâãäæèïéìëíîçåñòóôöõàøúüûùýÁÂÃÄÆÈÏÉÌËÍÎÅÑÒÓÔÖÕÀØÚÜÛÙÝÇ', 'aaaaaeieieiicanoooooaouuuuyAAAAAEIEIEIIANOOOOOAOUUUUYC') AS DSENDEDEVOEMBA
        INTO V_DSENDEDEVOEMBA
        FROM NOTAFISCAL N JOIN ITEMPRODUTO I ON (N.CDFILIAL = I.CDFILIAL) AND
                                                (N.NRLANCTONF = I.NRLANCTONF)
                          JOIN PRODUTO PR ON (I.CDPRODUTO = PR.CDPRODUTO)
                          JOIN (SELECT P.CDPOSTORECEMB, PR.CDARVPROD
                                  FROM PRODPOSTORECEMB P JOIN PRODUTO PR ON (P.CDPRODUTO = PR.CDPRODUTO)) PPRE ON (INSTR(PR.CDARVPROD, NVL(RTRIM(PPRE.CDARVPROD), PR.CDARVPROD)) = 1)
                          JOIN CLIEPOSTORECEMB C ON (N.CDCLIENTE = C.CDCLIENTE) AND
                                                    (PPRE.CDPOSTORECEMB = C.CDPOSTORECEMB)
                          JOIN POSTORECEMB PRE ON (C.CDPOSTORECEMB = PRE.CDPOSTORECEMB)
                          JOIN PAIS P ON (PRE.CDPAIS = P.CDPAIS)
                          JOIN ESTADO E ON (PRE.CDPAIS = E.CDPAIS) AND
                                           (PRE.SGESTADO = E.SGESTADO)
                          JOIN MUNICIPIO M ON (PRE.CDPAIS = M.CDPAIS) AND
                                              (PRE.SGESTADO = M.SGESTADO) AND
                                              (PRE.CDMUNICIPIO = M.CDMUNICIPIO)
                          JOIN BAIRRO B ON (PRE.CDPAIS = B.CDPAIS) AND
                                           (PRE.SGESTADO = B.SGESTADO) AND
                                           (PRE.CDMUNICIPIO = B.CDMUNICIPIO) AND
                                           (PRE.CDBAIRRO = B.CDBAIRRO)
       WHERE N.CDFILIAL = P_FILIAL
         AND N.NRLANCTONF = P_LANCTONF
         AND NOT EXISTS (SELECT DSDADOADIC
                           FROM DADOSADIC
                          WHERE (CDFILIAL = P_FILIAL)
                            AND (NRLANCTONF = P_LANCTONF)
                            AND (DSDADOADIC LIKE TRANSLATE(SUBSTR('Devolver as embalagens vazias no seguinte endereço: ' ||
                                                 PRE.DSPOSTORECEMB ||
                                                 ', ' || PRE.DSENDERECEMB ||
                                                 CASE NVL(PRE.DSCOMPENDERECEMB, '!X!X!') WHEN '!X!X!' THEN '' ELSE ', ' || PRE.DSCOMPENDERECEMB END ||
                                                 ', ' || B.NMBAIRRO ||
                                                 ', CEP:' || PRE.NRCEPRECEMB ||
                                                 ', ' || M.NMMUNICIPIO ||
                                                 ', ' || E.SGESTADO ||
                                                 ', ' || P.NMPAIS ||
                                                 CASE NVL(PRE.NRTELERECEMB, '!X!X!') WHEN '!X!X!' THEN '' ELSE '. Telefone: ' || PRE.NRTELERECEMB END ||
                                                 CASE NVL(PRE.NRFAXRECEMB, '!X!X!') WHEN '!X!X!' THEN '' ELSE '. FAX: ' || PRE.NRFAXRECEMB END, 1, 255), 'áâãäæèïéìëíîçåñòóôöõàøúüûùýÁÂÃÄÆÈÏÉÌËÍÎÅÑÒÓÔÖÕÀØÚÜÛÙÝÇ', 'aaaaaeieieiicanoooooaouuuuyAAAAAEIEIEIIANOOOOOAOUUUUYC') || '%'));
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_DSENDEDEVOEMBA := NULL;
      WHEN TOO_MANY_ROWS THEN
         RAISE_APPLICATION_ERROR(-20501, 'Operação bloqueada. Existem mais de um posto de recolhimento de embalagens cadastradas no sistema.', TRUE);
   END;

   IF (V_DSENDEDEVOEMBA IS NOT NULL) THEN
      INSERT INTO DADOSADIC
         (CDFILIAL,
          NRLANCTONF,
          NRDADOADIC,
          CDMENSAGEM,
          DSDADOADIC)
      VALUES
         (P_FILIAL,
          P_LANCTONF,
          V_DADOADIC,
          '',
          V_DSENDEDEVOEMBA);

      V_DADOADIC := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_DADOADIC) + 1)),3,0);
   END IF;

   --VARIÁVEIS (IDENTIFICADOR PARA OPERAÇÃO DE DEVOLUÇÃO,)
   BEGIN
      SELECT NVL(IDOPERDEVONF, W_N), NVL(IDATUESTTPOP, V_IDCTRLESTQ), NVL(IDUTCUSORIGEST, W_N),
             NVL(IDNOTADEVO, W_N),   NVL(IDNFPRESTSERV, W_N),         NVL(IDCMPVNDBONI, W_N),
             NVL(IDUTLOCPRESTSERV, W_N),  NVL(IDUTILVENC, 'N'), NVL(IDNFAJUSTE, 'N'),
             NVL(IDNFIMPORTACAO, 'N')
        INTO V_IDOPERDEVONF, V_IDCTRLESTQ,    V_IDUTCUSORIGEST,
             V_IDNOTADEVO,   V_IDNFPRESTSERV, V_IDCOMPRABONI,
             V_IDUTLOCPRESTSERV, V_IDUTILVENC, V_IDNFAJUSTE,
             V_IDNFIMPORTACAO
        FROM TIPOOPERAC
       WHERE IDENTRSAIDOP = P_ENTRSAID
         AND CDTIPOOPER   = P_TIPOOPER;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_IDOPERDEVONF   := W_N; V_IDCTRLESTQ       := V_IDCTRLESTQ;
         V_IDUTCUSORIGEST := W_N; V_IDNOTADEVO       := W_N;
         V_IDNFPRESTSERV  := W_N; V_IDUTLOCPRESTSERV := W_N;
         V_IDUTILVENC     := W_N; V_IDNFAJUSTE       := W_N;
         V_IDNFIMPORTACAO := W_N;
   END;

   --VARIÁVEIS PARA CONSULTA DE ALÍQUOTA, INCIDÊNCIA, CFOP
   BEGIN
      SELECT CDPAIS,     SGESTADO,   CDMUNICIPIO, IDCALCDIFENTFISC
      INTO   V_PAISDEST, V_ESTADEST, V_MUNIDEST, V_IDCALCDIFENTFISC
      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; V_IDCALCDIFENTFISC := 'N';
   END;

   IF V_IDNFPRESTSERV = 'S' THEN
      BEGIN
         SELECT NVL(MAX(IDEMISFILNFSERV),'P')
           INTO V_IDEMISFILNFSERV
           FROM FILIAL
          WHERE (CDFILIAL     = V_CDFILIRECE);
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_IDEMISFILNFSERV := 'P';
      END;

      IF (V_IDEMISFILNFSERV <> 'I') THEN
         BEGIN
            SELECT MAX(CDPAIS), MAX(SGESTADO), MAX(CDMUNICIPIO)
              INTO V_PAISDEST, V_ESTADEST, V_MUNIDEST
              FROM ENDEFILI
             WHERE (CDFILIAL     = V_CDFILIRECE) AND
                   (IDTPENDEFILI = V_IDEMISFILNFSERV);
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_PAISDEST := NULL; V_ESTADEST := NULL; V_MUNIDEST := NULL;
         END;
      END IF;
   END IF;
   IF (V_IDNFPRESTSERV = 'S') AND (V_IDUTLOCPRESTSERV = 'S') THEN
      V_ESTADEST := NVL(V_ESTAPRESTSERV , V_ESTADEST);
      V_MUNIDEST := NVL(V_MUNIPRESTSERV, V_MUNIDEST);
   END IF;

   V_CDORIGDESTNF := P_FORNECED;

   --SE O IDENTIFICADOR DE ORIGEM DO LANÇAMENTO FOR IGUAL A FILIAL
   IF V_IDORIGDESTNF = W_L THEN
      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;

      SELECT MAX(CDPAIS), MAX(SGESTADO), MAX(CDMUNICIPIO)
        INTO V_CDPAISST, V_SGESTADOST, V_CDMUNICIPIOST
        FROM ENDEFILI
       WHERE CDFILIAL = V_CDFILIEMIT
         AND IDTPENDEFILI = 'P';

      SELECT MAX(CDINSCESTAST)
        INTO V_CDINSCESTAST
        FROM INSCRESTADST
       WHERE CDEMPRESA = P_EMPRESA
         AND CDINSCESTA = P_INSCESTA
         AND CDPAIS = V_CDPAISST
         AND SGESTADO = V_SGESTADOST;

      IF V_IDENDCFOP = W_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 ENDEFILI
            WHERE (CDFILIAL     = V_CDFILIEMIT) AND
                  (IDTPENDEFILI = V_IDENDCFOP);
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_PAISCFOP := NULL; V_ESTACFOP := NULL;
         END;
      END IF;

      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;

      V_CDORIGDESTNF := V_CDFILIEMIT;

   --SE O IDENTIFICADOR DE ORIGEM DO LANÇAMENTO FOR IGUAL A CLIENTE
   ELSIF V_IDORIGDESTNF = W_C THEN
      BEGIN
         SELECT NVL(MAX(IDENDCFOPCLI),W_P)
           INTO   V_IDENDCFOP
           FROM CLIENTE
          WHERE (CDCLIENTE = P_FORNECED);
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_IDENDCFOP := W_P;
      END;

      SELECT MAX(CDPAIS), MAX(SGESTADO), MAX(CDMUNICIPIO)
        INTO V_CDPAISST, V_SGESTADOST, V_CDMUNICIPIOST
        FROM ENDECLIE
       WHERE CDCLIENTE = P_FORNECED
         AND IDTPENDECLIE = 'P';

      SELECT MAX(CDINSCESTAST)
        INTO V_CDINSCESTAST
        FROM INSCRESTADST
       WHERE CDEMPRESA = P_EMPRESA
         AND CDINSCESTA = P_INSCESTA
         AND CDPAIS = V_CDPAISST
         AND SGESTADO = V_SGESTADOST;

      IF V_IDENDCFOP = W_I THEN
         BEGIN
            SELECT CDPAIS    , SGESTADO
            INTO   V_PAISCFOP, V_ESTACFOP
            FROM INSCRESTAD
            WHERE CDEMPRESA  = P_EMPRESA AND
                  CDINSCESTA = P_INSCESTA;
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_PAISCFOP := NULL; V_ESTACFOP := NULL;
         END;
      ELSE
         BEGIN
            SELECT CDPAIS, SGESTADO
            INTO V_PAISCFOP, V_ESTACFOP
            FROM ENDECLIE
            WHERE (CDCLIENTE    = P_FORNECED) AND
                  (IDTPENDECLIE = 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 ENDECLIE
         WHERE (CDCLIENTE    = P_FORNECED) AND
               (IDTPENDECLIE = W_P);
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_PAISORIG := NULL; V_ESTAORIG := NULL; V_MUNIORIG := NULL;
      END;
   --SE O IDENTIFICADOR DE ORIGEM DO LANÇAMENTO FOR IGUAL A FORNECEDOR
   ELSIF V_IDORIGDESTNF = W_F THEN
      BEGIN
         SELECT NVL(IDENDCFOPFOR,W_P)
         INTO   V_IDENDCFOP
         FROM FORNECEDOR
         WHERE (CDFORNECED = P_FORNECED);
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_IDENDCFOP := W_P;
      END;

      SELECT MAX(CDPAIS), MAX(SGESTADO), MAX(CDMUNICIPIO)
        INTO V_CDPAISST, V_SGESTADOST, V_CDMUNICIPIOST
        FROM ENDEFORN
       WHERE CDFORNECED = P_FORNECED
         AND IDTPENDEFORN = 'P';

      SELECT MAX(CDINSCESTAST)
        INTO V_CDINSCESTAST
        FROM INSCRESTADST
       WHERE CDEMPRESA = P_EMPRESA
         AND CDINSCESTA = P_INSCESTA
         AND CDPAIS = V_CDPAISST
         AND SGESTADO = V_SGESTADOST;

      IF V_IDENDCFOP = W_I THEN
         BEGIN
            SELECT CDPAIS    , SGESTADO
            INTO   V_PAISCFOP, V_ESTACFOP
            FROM INSCRESTAD
            WHERE CDEMPRESA  = P_EMPRESA AND
                  CDINSCESTA = P_INSCESTA;
         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   = P_FORNECED) 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   = P_FORNECED) AND
                (IDTPENDEFORN = W_P);
       EXCEPTION
          WHEN NO_DATA_FOUND THEN
             V_PAISORIG := NULL; V_ESTAORIG := NULL; V_MUNIORIG := NULL;
       END;
   ELSE
      --SE O IDENTIFICADOR DE ORIGEM DO LANÇAMENTO FOR IGUAL A LICENCA DE USO OU OUTRO VALOR DIFERENTE DE L,C,F
      IF P_ENTRSAID = W_E THEN
         BEGIN
            SELECT CDPAIS, SGESTADO, CDMUNICIPIO
            INTO V_PAISORIG, V_ESTAORIG, V_MUNIORIG
            FROM ENDEFORN
            WHERE (CDFORNECED   = P_FORNECED) AND
                  (IDTPENDEFORN = W_P);
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_PAISORIG := NULL; V_ESTAORIG := NULL; V_MUNIORIG := NULL;
         END;

         SELECT MAX(CDPAIS), MAX(SGESTADO), MAX(CDMUNICIPIO)
           INTO V_CDPAISST, V_SGESTADOST, V_CDMUNICIPIOST
           FROM ENDEFORN
          WHERE CDFORNECED = P_FORNECED
            AND IDTPENDEFORN = 'P';

         SELECT MAX(CDINSCESTAST)
           INTO V_CDINSCESTAST
           FROM INSCRESTADST
          WHERE CDEMPRESA = P_EMPRESA
            AND CDINSCESTA = P_INSCESTA
            AND CDPAIS = V_CDPAISST
            AND SGESTADO = V_SGESTADOST;

      ELSIF P_ENTRSAID = W_S THEN
         BEGIN
            SELECT CDPAIS, SGESTADO, CDMUNICIPIO
            INTO V_PAISORIG, V_ESTAORIG, V_MUNIORIG
            FROM ENDECLIE
            WHERE (CDCLIENTE    = P_FORNECED) AND
                  (IDTPENDECLIE = W_P);
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_PAISORIG := NULL; V_ESTAORIG := NULL; V_MUNIORIG := NULL;

         END;

         SELECT MAX(CDPAIS), MAX(SGESTADO), MAX(CDMUNICIPIO)
           INTO V_CDPAISST, V_SGESTADOST, V_CDMUNICIPIOST
           FROM ENDECLIE
          WHERE CDCLIENTE = P_FORNECED
            AND IDTPENDECLIE = 'P';

         SELECT MAX(CDINSCESTAST)
           INTO V_CDINSCESTAST
           FROM INSCRESTADST
          WHERE CDEMPRESA = P_EMPRESA
            AND CDINSCESTA = P_INSCESTA
            AND CDPAIS = V_CDPAISST
            AND SGESTADO = V_SGESTADOST;
      END IF;
   END IF;

   IF (V_CDINSCESTAST IS NOT NULL) OR (V_CDINSCESTAST = '')  THEN
      UPDATE NOTAFISCAL
         SET CDINSCESTAST = V_CDINSCESTAST
       WHERE CDFILIAL = P_FILIAL
         AND NRLANCTONF = P_LANCTONF;

      FOR C_MENSINSCESTAST IN (SELECT M.CDMENSAGEM, I.DSMENSINSCESTAST
                                 FROM MENSINSCESTAST I LEFT JOIN MENSAGEM M ON (M.CDMENSAGEM = I.CDMENSAGEM)
                                WHERE I.CDEMPRESA = P_EMPRESA
                                  AND I.CDINSCESTA = P_INSCESTA
                                  AND I.CDINSCESTAST = V_CDINSCESTAST
                                  AND I.IDENTRSAIDMENSST <> 'S'
                                  AND (((I.CDMENSAGEM IS NOT NULL) AND (M.IDSITUACAOMENS  = 'A')) OR (I.CDMENSAGEM IS NULL))
                                  AND NOT EXISTS (SELECT DSDADOADIC
                                                    FROM DADOSADIC
                                                   WHERE (CDFILIAL = P_FILIAL)
                                                     AND (NRLANCTONF = P_LANCTONF)
                                                     AND (DSDADOADIC LIKE I.DSMENSINSCESTAST || '%'))
                                ORDER BY NRMENSINSCESTAST) LOOP

         /*PREENCHE AS MENSAGENS ATRELADAS A INSCRICAO ESTADUAL DO SUBSTITUTO TRIBUTÁRIO*/
         INSERT INTO DADOSADIC(CDFILIAL, NRLANCTONF, NRDADOADIC, CDMENSAGEM, DSDADOADIC)
                        VALUES(P_FILIAL, P_LANCTONF, V_DADOADIC, C_MENSINSCESTAST.CDMENSAGEM, C_MENSINSCESTAST.DSMENSINSCESTAST);

         V_DADOADIC := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_DADOADIC) + 1)),3,0);

      END LOOP;
   END IF;

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

   -- RETORNA O VALOR LÍQUIDO TOTAL DA NOTA FISCAL

   SELECT SUM(VRLIQUIDO)
     INTO V_LIQUIDO
     FROM (SELECT DECODE(QTITEMPROD, 0, (VRTOTAITEM - VRDESCITEM), (ROUND(QTITEMPROD,4) * ROUND(VRUNITITEM,10)) - ROUND(VRDESCITEM, 2)) AS VRLIQUIDO
             FROM ITEMPRODUTO
            WHERE CDFILIAL   = P_FILIAL
              AND NRLANCTONF = P_LANCTONF);

   -- PREENCHER CLASSIFICACAO FISCAL NCM NA TABELA ITEMPRODUTO
   FOR C_ITEMPRODUTO IN (SELECT I.CDFILIAL, I.NRLANCTONF, I.NRSEQITPROD, P.CDCLASFISC
                           FROM ITEMPRODUTO I, PRODUTO P
                          WHERE I.CDFILIAL   = P_FILIAL
                            AND I.NRLANCTONF = P_LANCTONF
                            AND I.CDPRODUTO = P.CDPRODUTO)
   LOOP
     UPDATE ITEMPRODUTO
        SET CDPRODNCMTRANS = C_ITEMPRODUTO.CDCLASFISC
      WHERE CDFILIAL    = C_ITEMPRODUTO.CDFILIAL
        AND NRLANCTONF  = C_ITEMPRODUTO.NRLANCTONF
        AND NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;
   END LOOP;

   --INSERE TODOS OS ENCARGOS QUE NÃO POSSUEM NA NOTA FISCAL COM O VALOR IGUAL A ZERO (0)
   INSERT INTO ITEMENCARGO
      (CDFILIAL, NRLANCTONF, CDENCARGO, VRITEMENCA)
      (SELECT P_FILIAL, P_LANCTONF, CDENCARGO, 0
         FROM ENCARGO
        WHERE NOT EXISTS(SELECT CDENCARGO
                           FROM ITEMENCARGO
                          WHERE CDFILIAL   = P_FILIAL
                            AND NRLANCTONF = P_LANCTONF
                            AND CDENCARGO  = ENCARGO.CDENCARGO));


   CONSULTA_GRUPOFISCAL(V_IDORIGDESTNF, V_CDORIGDESTNF, V_CDFILIRECE, W_E, P_TIPOOPER, V_CDGRUPOFISC);

   -- TIPO DE OPERAÇÃO 11 COM PARÂMETRO PARA GERAR NOTA FISCAL INFORMANDO APENAS AS NOTAS FISCAIS 10 DEVE SER GRAVADO IMPOSTO NA TRABITPROIMPOS
   IF (P_TIPOOPER = '11' AND V_IDNFOUTRASNF = W_S) THEN

      SELECT COUNT(*)
        INTO V_QTDEREGTRAB
        FROM TRABITPROIMPOS
       WHERE CDFILIMPOIT  = P_FILIAL
         AND NRLANCIMPOIT = P_LANCTONF;

      IF V_QTDEREGTRAB = 0 THEN

         DELETE
           FROM TRABITPROIMPOS
          WHERE CDFILIMPOIT  = P_FILIAL
            AND NRLANCIMPOIT = P_LANCTONF;

         DELETE
           FROM ALIQTEMPPROD
          WHERE NRALIQTEMP = P_FILIAL||P_LANCTONF;

         DELETE
           FROM INCITEMP
          WHERE NRINCITEMP = P_FILIAL||P_LANCTONF;

         FOR C_ITENSSEMNF IN (SELECT PR.CDARVPROD,  I.VRUNITITEM, I.VRDESCITEM,
                                     I.NRSEQITPROD, I.VRTOTAITEM, PR.CDPRODUTO,
                                     I.QTITEMPROD,  NVL(I.IDORIGEMPROD, 'N') AS IDORIGEMPROD
                                FROM ITEMPRODUTO I, PRODUTO PR
                               WHERE I.CDFILIAL   = P_FILIAL
                                 AND I.NRLANCTONF = P_LANCTONF
                                 AND PR.CDPRODUTO = I.CDPRODUTO) LOOP


            IMPOSTO_ENTRADA_PRODUTO(P_EMPRESA, P_INSCESTA, P_TIPOOPER, P_FORNECED, P_FILIAL, P_LANCTONF,
                                    P_INIVALID, 'E', P_CDOPERADOR, V_CDGRUPOFISC, V_IDINTEREST, C_ITENSSEMNF.CDARVPROD,
                                    '', 'F', V_CDFILIRECE, NULL, NULL, C_ITENSSEMNF.VRTOTAITEM, C_ITENSSEMNF.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  = P_FILIAL||P_LANCTONF
                                 AND I.NRINCITEMP  = AL.NRALIQTEMP(+)
                                 AND I.CDIMPOTEMP  = AL.CDIMPOTEMP(+)
                                 AND IM.IDPRODNOTA <> 'C') LOOP


               INSERT INTO TRABITPROIMPOS
                  (CDFILIMPOIT, NRLANCIMPOIT, NRSEQIMPOIT, CDIMPOSTOIT, VRCONTIMPOIT,
                   VRREDBCIMPOIT, VRBCALCIMPOIT, VRALIQIMPOIT, VRPDEDIMPOIT, VRIMPOSIT,
                   CDFISCIMPOIT,  NRSEQITPRO, IDVALORINFO,
                   VR1REDBCIMPOIT, IDTRIMPSTTI, VRIMPOSVISUIT, VRADICALIQFECP)

               VALUES
                  (P_FILIAL, P_LANCTONF,   LPAD(C_ITENSSEMNF.NRSEQITPROD, 4, '0'), C_ALIQITEM.CDIMPOSTO, (C_ITENSSEMNF.VRTOTAITEM - C_ITENSSEMNF.VRDESCITEM),
                   0, C_ITENSSEMNF.VRTOTAITEM, C_ALIQITEM.VRALIQUOTA, 0, 0,
                   C_ALIQITEM.CDFISCTEMP, '1', 'N',
                   0, '0', 0, C_ALIQITEM.VRADICALIQFECP);
            END LOOP;

            DELETE
              FROM ALIQTEMPPROD
             WHERE NRALIQTEMP = P_FILIAL||P_LANCTONF;

            DELETE
              FROM INCITEMP
             WHERE NRINCITEMP = P_FILIAL||P_LANCTONF;

         END LOOP;
         DELETE TRABIMPOSNFTOT WHERE CDFILIMPTOT = P_FILIAL AND NRLANCIMPTOT = P_LANCTONF;
         FOR C_TRABIMPOTOTSEMNF IN (SELECT SUM(T.VRIMPOSIT) VRTOTAIMPO, T.CDIMPOSTOIT
                                      FROM TRABITPROIMPOS T, IMPOSTO I
                                     WHERE CDFILIMPOIT  = P_FILIAL
                                       AND NRLANCIMPOIT = P_LANCTONF
                                       AND IDPRODNOTA <> 'C'
                                       AND T.CDIMPOSTOIT = I.CDIMPOSTO
                                     GROUP BY CDIMPOSTOIT
                                     ORDER BY CDIMPOSTOIT)LOOP

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

                  VALUES(P_FILIAL, P_LANCTONF, C_TRABIMPOTOTSEMNF.CDIMPOSTOIT, (0 + C_TRABIMPOTOTSEMNF.VRTOTAIMPO), 0);
         END LOOP;
      END IF;   
   END IF;
   -- TIPO DE OPERAÇÃO 11 COM PARÂMETRO PARA GERAR NOTA FISCAL INFORMANDO APENAS AS NOTAS FISCAIS 10 DEVE SER GRAVADO IMPOSTO NA TRABITPROIMPOS

   --SE O TIPO DE OPERAÇÃO DA NOTA FISCAL FOR DEVOLUÇÃO
   IF V_IDOPERDEVONF = W_S THEN
      SELECT MAX(CDFILIALIT), MAX(NRLANCTONFIT)
      INTO V_FILIORIG, V_DEVOLORIG
      FROM ITEMNOTAFISC
      WHERE CDFILIAL   = P_FILIAL   AND
            NRLANCTONF = P_LANCTONF;

      BEGIN
         SELECT MAX(IDIMPDESONERAIT)
           INTO V_IDIMPDESONERA
           FROM ITEMPROIMPOS
          WHERE CDFILIAL   = V_FILIORIG
            AND NRLANCTONF = V_DEVOLORIG
            AND IDIMPDESONERAIT = 'S';
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_IDIMPDESONERA := 'N';
      END;
   END IF;

   IF (V_DEVOLORIG IS NOT NULL) THEN
      UPDATE ITEMPRODUTO
         SET VRTOTAITEM = ROUND(VRTOTAITEM, 2)
       WHERE CDFILIAL   = P_FILIAL
         AND NRLANCTONF = P_LANCTONF;

      SELECT (SUM(VRTOTAITEM) - SUM(VRDESCITEM))
        INTO V_LIQUIDO
        FROM ITEMPRODUTO
       WHERE CDFILIAL   = P_FILIAL AND
             NRLANCTONF = P_LANCTONF;
   END IF;

   -- PARA DOCUMENTOS DE ENTRADA QUE NÃO SEJAM DEVOLUÇÃO SERÁ SUBTRAÍDO AO VALOR TOTAL
   -- E AO VALOR CONTÁBIL O VALOR DO DESCONTO
   IF ((V_INTEGRACAO IS NULL) OR (P_ENTRSAID = W_E)) AND (V_DEVOLORIG IS NULL) THEN
      UPDATE ITEMPRODUTO
      SET VRBRUTITEM   = ROUND((VRTOTAITEM - VRDESCITEM) + NVL(VRICMSSTITORIG, 0), 5),
          VRCONTITEM   = ROUND((VRTOTAITEM - VRDESCITEM) + NVL(VRICMSSTITORIG, 0), 5),
          IDUTVRPAUTAPROD = NULL  
      WHERE CDFILIAL   = P_FILIAL    AND
            NRLANCTONF = P_LANCTONF;
   END IF;

   V_IDNFRETIND   := 'N';
   SELECT NVL(IDNFRETIND, 'N')
     INTO V_IDNFRETIND
     FROM TIPOOPERAC
    WHERE CDTIPOOPER   = P_TIPOOPER
      AND IDENTRSAIDOP = w_E;

   IF (V_IDNFRETIND = 'S') THEN
      UPDATE ITEMPRODUTO
      SET VRBRUTITEM   = ROUND((VRTOTAITEM - VRDESCITEM), 5),
          VRCONTITEM   = ROUND((VRTOTAITEM - VRDESCITEM), 5)
      WHERE CDFILIAL   = P_FILIAL    AND
            NRLANCTONF = P_LANCTONF;
   END IF;

   -- ATUALIZAÇÃO DAS TABELAS DE NOTAFISCAL, ITEMPRODUTO E DADOS ADICIONAIS

   -- PARA OS TIPOS DE OPERAÇÕES DIFERENTES DE ENTRADA SEM NF, VALE DE TRANSFERÊNCIA E OUTRAS SAÍDAS

   IF ((NOT P_TIPOOPER IN ('07','09','10')) AND (V_IDOPERDEVONF <> W_S)) OR ((V_IDOPERDEVONF = W_S) AND (V_DEVOLORIG IS NULL)) OR (V_IDNFRETIND = 'S') THEN

      --IMPORTAÇÃO DE NFS DE ENTRADA NÃO ORIUNDAS DOS
      IF (V_INTEGRACAO IS NULL) OR (P_ENTRSAID = W_E) THEN

         FOR C_ITEMPRODUTO IN (SELECT VRTOTAITEM, VRDESCITEM, I.CDPRODUTO, NRSEQITPROD, P.CDARVPROD,
                                      QTITEMPROD, CDFISOPEITEM, CDSITUTRIBPR, IDORIGEMPROD
                               FROM ITEMPRODUTO I, PRODUTO P
                               WHERE CDFILIAL    = P_FILIAL   AND
                                     NRLANCTONF  = P_LANCTONF AND
                                     I.CDPRODUTO = P.CDPRODUTO) LOOP

            V_LIQUIDOPROD := C_ITEMPRODUTO.VRTOTAITEM - C_ITEMPRODUTO.VRDESCITEM;

            CONSULTA_CST(P_ENTRSAID, P_EMPRESA, C_ITEMPRODUTO.CDARVPROD, P_INSCESTA, P_TIPOOPER, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC, V_IDINTEREST, V_IDINTERNAC, NULL, C_ITEMPRODUTO.IDORIGEMPROD);

            IF V_IDCOMPRABONI = 'N' THEN
               CONSULTA_CFOP(P_ENTRSAID, P_EMPRESA, C_ITEMPRODUTO.CDARVPROD, P_INSCESTA, P_TIPOOPER, V_PAISCFOP,
                              V_ESTACFOP, V_PAISDEST, V_ESTADEST, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC, P_INIVALID, C_ITEMPRODUTO.IDORIGEMPROD );
            END IF;

            -- ALTERA NATUREZA DE OPERAÇÃO DA NOTA FISCAL CASO NÃO EXISTA  E SE O USUARIO NAO INFORMOU

            IF C_ITEMPRODUTO.CDFISOPEITEM IS NULL THEN
               UPDATE NOTAFISCAL
               SET DSCDFISOPENF = (SELECT MAX(DSCFOPTMP) FROM CFOPTEMP
                                     WHERE NRCFOPTEMP = V_CFOPTEMP)
               WHERE CDFILIAL   = P_FILIAL   AND
                     NRLANCTONF = P_LANCTONF AND
                     DSCDFISOPENF IS NULL    AND
                     DSCFOPINFUSU IS NULL;
            END IF;

            SELECT MAX(CDFISOPETMP), MAX(CDSUFCFOPTMP), MAX(IDDIFALIQTMP),
                   MAX(DSCFOPTMP), NVL(MAX(IDDIFALIQCUSPRC),W_N)
            INTO V_FISOPEITEM, V_SUFXCFOPPR, V_DIFALIQITEM,
                 V_DSCDFISOPEIT, V_IDDIFALIQCUSPRC
            FROM CFOPTEMP
            WHERE NRCFOPTEMP = V_CFOPTEMP;

            SELECT MAX(IDORDPRIMDFENT)
              INTO V_IDORDPRIMDFENT
              FROM PARAMGERAL;

            V_FISOPEITEM        := NVL(V_CDFISCOPERREGRA, V_FISOPEITEM);
            V_DSCDFISOPEIT      := NVL(V_DSCDFISOPEITREGRA, V_DSCDFISOPEIT);
            V_DIFALIQITEM       := NVL(V_IDDIFEALIQREGRA, V_DIFALIQITEM);
            V_IDDIFALIQCUSPRC   := NVL(V_IDDIFALIQCUSPRREGRA, V_IDDIFALIQCUSPRC);

            CONSULTA_CSOSN(P_ENTRSAID, P_EMPRESA, C_ITEMPRODUTO.CDARVPROD, P_INSCESTA, P_TIPOOPER, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC, V_IDINTEREST, V_CDFISCOPERSN);

            -- ALTERA O CFOP DO ITEM E
               
            IF (V_FISOPEITEM IS NULL) AND (C_ITEMPRODUTO.CDFISOPEITEM IS NOT NULL) AND (V_IDGERNFIGUALXML = 'S') AND (V_IDNFGERADAVIAXML = 'S') THEN
               V_FISOPEITEM := C_ITEMPRODUTO.CDFISOPEITEM;
            END IF;
               
            UPDATE ITEMPRODUTO
            SET CDFISOPEITEM = V_FISOPEITEM,
                CDSUFXCFOPPR = V_SUFXCFOPPR,
                DSCDFISOPEIT =  V_DSCDFISOPEIT,
                CDFISCOPERSN = V_CDFISCOPERSN
            WHERE CDFILIAL    = P_FILIAL   AND
                  NRLANCTONF  = P_LANCTONF AND
                  NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;

            DELETE CFOPTEMP
            WHERE NRCFOPTEMP = V_CFOPTEMP;

            SELECT MAX(CDSITTRIBTMP) INTO V_SITUTRIBPR
            FROM CSTTEMP
            WHERE NRCSTTEMP = V_CSTTEMP;

            BEGIN
               SELECT CDSITUTRIBPR INTO V_CDCSTDIGI
               FROM ITEMPRODUTO
               WHERE CDFILIAL    = P_FILIAL   AND
                     NRLANCTONF  = P_LANCTONF AND
                     NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;
            EXCEPTION
               WHEN NO_DATA_FOUND THEN
                  V_CDCSTDIGI := NULL;
            END;

            IF (SUBSTR(V_CDCSTDIGI,1,1) = SUBSTR(V_SITUTRIBPR,1,1)) OR
               (V_CDCSTDIGI IS NULL) THEN

               UPDATE ITEMPRODUTO
               SET CDSITUTRIBPR  = V_SITUTRIBPR
               WHERE CDFILIAL    = P_FILIAL   AND
                     NRLANCTONF  = P_LANCTONF AND
                     NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;
            ELSE
               V_SITUTRIBPR := V_CDCSTDIGI;
            END IF;

            DELETE CSTTEMP
            WHERE NRCSTTEMP = V_CSTTEMP;

            -- VERIFICA SE HÁ GRUPO FISCAL POR SERVICO
            SELECT MAX(CDGRUPOFISC)
            INTO V_CDGRPFISCSV
            FROM SERVCLIE SC, SERVICO S
            WHERE SC.CDFILIAL   = V_CDFILIEMIT AND
                  SC.CDCLIENTE  = P_FORNECED    AND
                  SC.CDFILIAL   = S.CDFILIAL   AND
                  SC.CDSERVFILI = S.CDSERVFILI AND
                  S.CDPRODUTO   = C_ITEMPRODUTO.CDPRODUTO;

            IF V_CDGRPFISCSV IS NULL THEN
               -- VERIFICA SE HÁ GRUPO FISCAL POR CLIENTE DA FILIAL
               SELECT MAX(CDGRUPOFISC)
               INTO V_CDGRPFISCSV
               FROM CLIENFILIAL
               WHERE CDFILIAL   = V_CDFILIEMIT AND
                     CDCLIENTE  = P_FORNECED;
            END IF;

            CONSULTA_INCIDENCIA(P_ENTRSAID, P_EMPRESA, C_ITEMPRODUTO.CDARVPROD, P_INSCESTA, P_TIPOOPER, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC,
                                V_CDGRPFISCSV, V_IDINTEREST, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, C_ITEMPRODUTO.IDORIGEMPROD,
                                V_ESTAPRESTSERV, V_MUNIPRESTSERV);
            FOR C_INCITEMP IN (SELECT DSMENSINCTMP
                            FROM INCITEMP
                            WHERE (NRINCITEMP = V_INCITEMP)  AND
                                  (DSMENSINCTMP IS NOT NULL) AND
                                  (NOT EXISTS(SELECT DSDADOADIC
                                              FROM DADOSADIC
                                              WHERE (CDFILIAL   = P_FILIAL)   AND
                                                    (NRLANCTONF = P_LANCTONF) AND
                                                    (DSDADOADIC LIKE INCITEMP.DSMENSINCTMP || '%')))) LOOP

               IF NOT(C_INCITEMP.DSMENSINCTMP IS NULL) THEN
               /*PREENCHE AS MENSAGENS ATRELADAS A INCIDENCIA*/
                  INSERT INTO DADOSADIC(CDFILIAL, NRLANCTONF, NRDADOADIC, DSDADOADIC)
                                 VALUES(P_FILIAL, P_LANCTONF, V_DADOADIC, C_INCITEMP.DSMENSINCTMP);

                  V_DADOADIC := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_DADOADIC) + 1)),3,0);
               END IF;
            END LOOP;
            --ATUALIZAÇÃO DA TABELA DE IMPOSTOS POR ITEM.

            DELETE ITEMPROIMPOS
            WHERE (CDFILIAL    = P_FILIAL)   AND
                  (NRLANCTONF  = P_LANCTONF) AND
                  (NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD);

            FOR C_INCIDENCIA IN (SELECT IT.CDIMPOTEMP, MAX(IT.CDFISCTEMP) AS CDFISCTEMP,
                                        MAX(IT.IDTRATIMPTMP) AS IDTRATIMPTMP, MAX(IP.IDCONSISTENT) AS IDCONSISTENT, MAX(NVL(IP.IDUTMUNIORIG, W_N)) AS IDUTMUNIORIG,
                                        MAX(IP.IDIMPORECUP)  AS IDIMPORECUP, MAX(NVL(IP.IDPREIMPENTR, W_N)) AS IDPREIMPENTR,
                                        MAX(IP.IDORGARRECAD) AS IDORGARRECAD, MAX(IDUTVLRQTDEIMPO) AS IDUTVLRQTDEIMPO,
                                        MAX(IP.IDUTVRPAUTA) AS IDUTVRPAUTA,
                                        MAX(IT.CDDETALHEPROD) AS CDDETALHEPROD,
                                        MAX(CDENQLEGALIPI)   AS CDENQLEGALIPI,
                                        MAX(IP.CDIMPOSTONFE) AS CDIMPOSTONFE,
                                        MAX(IP.CDIMPOBASERET) AS CDIMPOBASERET, MAX(IP.IDDESCRFONTE) AS IDDESCRFONTE,
                                        MAX(IT.CDCEST) AS CDCEST
                                 FROM INCITEMP IT, IMPOSTO IP
                                 WHERE (IT.NRINCITEMP = V_INCITEMP)    AND
                                       (IP.CDIMPOSTO  = IT.CDIMPOTEMP) AND
                                       (IP.IDPRODNOTA = W_P)
                                 GROUP BY IT.CDIMPOTEMP
                                 ORDER BY IT.CDIMPOTEMP) LOOP

               V_MINBCPROD := 0;

               IF C_INCIDENCIA.IDUTVRPAUTA = 'S' THEN
                  CALCULO_MINBCPRODUTO(P_EMPRESA, P_TIPOOPER, P_INSCESTA, P_ENTRSAID, V_PAISORIG, V_ESTAORIG,
                                       C_ITEMPRODUTO.CDPRODUTO, V_CDGRUPOFISC, P_INIVALID, P_LANCTONF, P_FILIAL,
                                       C_ITEMPRODUTO.NRSEQITPROD, V_MINBCPROD);
               END IF;

               -- Desconsidera valor do desconto para cáculo do valor do ST
               BEGIN
                  SELECT MAX(CDIMPOSTO), MAX(IDVRIMPSTRIB)
                    INTO V_CDIMPOSTRIB, V_IDVRIMPSTRIB
                    FROM IMPOSTO
                   WHERE CDIMPOSTRIB = C_INCIDENCIA.CDIMPOTEMP;
               EXCEPTION
                   WHEN NO_DATA_FOUND THEN
                      V_CDIMPOSTRIB := NULL; V_IDVRIMPSTRIB := NULL;
               END;

               IF (V_CDIMPOSTRIB IS NOT NULL) THEN
                  IF V_MINBCPROD = 0 THEN
                     V_LIQUIITEM := C_ITEMPRODUTO.VRTOTAITEM;
                  ELSE
                     V_LIQUIITEM := V_MINBCPROD;
                     IF (C_INCIDENCIA.IDUTVRPAUTA = 'S') THEN
                        UPDATE ITEMPRODUTO
                           SET IDUTVRPAUTAPROD = 'S'
                         WHERE CDFILIAL    = P_FILIAL
                           AND NRLANCTONF  = P_LANCTONF
                           AND NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;
                     END IF;
                  END IF;
               ELSE
                  -- Se o imposto é retido (valor NF) e se utiliza o valor de outro imposto como base de cálculo
                  IF ((C_INCIDENCIA.IDTRATIMPTMP = 'R') AND (C_INCIDENCIA.CDIMPOBASERET IS NOT NULL) AND (C_INCIDENCIA.IDDESCRFONTE = 'N')) THEN
                     SELECT NVL(MAX(VRIMPOSIT),0)
                       INTO V_VRIMPORELAC
                       FROM TRABITPROIMPOS
                      WHERE CDFILIMPOIT  = P_FILIAL
                        AND NRLANCIMPOIT = P_LANCTONF
                        AND NRSEQIMPOIT  = C_ITEMPRODUTO.NRSEQITPROD
                        AND CDIMPOSTOIT  = C_INCIDENCIA.CDIMPOBASERET
                        AND NRSEQITPRO   = W_1;

                     IF V_VRIMPORELAC <> 0 THEN
                        V_LIQUIITEM := V_VRIMPORELAC;
                     ELSE
                        V_LIQUIITEM := C_ITEMPRODUTO.VRTOTAITEM - C_ITEMPRODUTO.VRDESCITEM;
                     END IF;
                  ELSE
                     IF V_MINBCPROD = 0 THEN
                        V_LIQUIITEM := C_ITEMPRODUTO.VRTOTAITEM - C_ITEMPRODUTO.VRDESCITEM;
                     ELSE
                        V_LIQUIITEM := V_MINBCPROD - C_ITEMPRODUTO.VRDESCITEM;
                        IF (C_INCIDENCIA.IDUTVRPAUTA = 'S') THEN
                           UPDATE ITEMPRODUTO
                              SET IDUTVRPAUTAPROD = 'S'
                            WHERE CDFILIAL    = P_FILIAL
                              AND NRLANCTONF  = P_LANCTONF
                              AND NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;
                        END IF;
                     END IF;
                  END IF;
               END IF;

               -- Desconsidera valor do desconto para cáculo do valor do ST
               IF C_INCIDENCIA.IDUTMUNIORIG = W_D THEN
                  /* CONSIDERA O MUNICIPIO DE DESTINO */
                  IF V_UTGRUPFISCS = 'S' THEN
                     V_CDGRPFISCSV := NULL;
                     SELECT MAX(CDGRUPOFISC)
                     INTO V_CDGRPFISCSV
                     FROM SERVCLIE SC, SERVICO S
                     WHERE SC.CDFILIAL   = V_CDFILIEMIT AND
                           SC.CDCLIENTE  = P_FORNECED    AND
                           SC.CDFILIAL   = S.CDFILIAL   AND
                           SC.CDSERVFILI = S.CDSERVFILI AND
                           S.CDPRODUTO   = C_ITEMPRODUTO.CDPRODUTO;
                     IF V_CDGRPFISCSV IS NULL THEN
                        SELECT MAX(CDGRUPOFISC)
                        INTO V_CDGRPFISCSV
                        FROM CLIENFILIAL
                       WHERE CDFILIAL   = V_CDFILIEMIT AND
                             CDCLIENTE  = P_FORNECED;
                     END IF;
                     CONSULTA_ALIQUOTA(C_INCIDENCIA.CDIMPOTEMP, P_ENTRSAID, P_EMPRESA, C_ITEMPRODUTO.CDARVPROD, P_INSCESTA, V_PAISORIG,
                                       V_ESTAORIG, V_PAISDEST, V_ESTADEST, V_MUNIDEST, V_LIQUIITEM, P_INIVALID, P_FILIAL, P_LANCTONF, V_CDGRPFISCSV,P_TIPOOPER,
                                       NULL, NULL, NULL, NULL, P_FORNECED, NULL, C_ITEMPRODUTO.IDORIGEMPROD);
                  ELSE
                     CONSULTA_ALIQUOTA(C_INCIDENCIA.CDIMPOTEMP, P_ENTRSAID, P_EMPRESA, C_ITEMPRODUTO.CDARVPROD, P_INSCESTA, V_PAISORIG,
                                       V_ESTAORIG, V_PAISDEST, V_ESTADEST, V_MUNIDEST, V_LIQUIITEM, P_INIVALID, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC, P_TIPOOPER,
                                       NULL, NULL, NULL, NULL, P_FORNECED, NULL, C_ITEMPRODUTO.IDORIGEMPROD);
                  END IF;
               ELSE
                 /* CONSIDERA O MUNICIPIO DE ORIGEM */

                  SELECT MAX(IDGRUPFISSRV)
                  INTO V_UTGRUPFISCS
                  FROM IMPOSTO
                  WHERE CDIMPOSTO   = C_INCIDENCIA.CDIMPOTEMP;

                  IF V_UTGRUPFISCS = 'S' THEN
                     V_CDGRPFISCSV := NULL;
                     SELECT MAX(CDGRUPOFISC)
                     INTO V_CDGRPFISCSV
                     FROM SERVCLIE SC, SERVICO S
                     WHERE SC.CDFILIAL   = V_CDFILIEMIT AND
                           SC.CDCLIENTE  = P_FORNECED    AND
                           SC.CDFILIAL   = S.CDFILIAL   AND
                           SC.CDSERVFILI = S.CDSERVFILI AND
                           S.CDPRODUTO   = C_ITEMPRODUTO.CDPRODUTO;
                     IF V_CDGRPFISCSV IS NULL THEN
                        SELECT MAX(CDGRUPOFISC)
                        INTO V_CDGRPFISCSV
                        FROM CLIENFILIAL
                       WHERE CDFILIAL   = V_CDFILIEMIT AND
                             CDCLIENTE  = P_FORNECED;
                     END IF;

                     CONSULTA_ALIQUOTA(C_INCIDENCIA.CDIMPOTEMP, P_ENTRSAID, P_EMPRESA, C_ITEMPRODUTO.CDARVPROD, P_INSCESTA, V_PAISORIG,
                                       V_ESTAORIG, V_PAISDEST, V_ESTADEST, V_MUNIORIG, V_LIQUIITEM, P_INIVALID, P_FILIAL, P_LANCTONF, V_CDGRPFISCSV, P_TIPOOPER,
                                       NULL, NULL, NULL, NULL, P_FORNECED, NULL, C_ITEMPRODUTO.IDORIGEMPROD);
                  ELSE
                     CONSULTA_ALIQUOTA(C_INCIDENCIA.CDIMPOTEMP, P_ENTRSAID, P_EMPRESA, C_ITEMPRODUTO.CDARVPROD, P_INSCESTA, V_PAISORIG,
                                       V_ESTAORIG, V_PAISDEST, V_ESTADEST, V_MUNIORIG, V_LIQUIITEM, P_INIVALID, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC, P_TIPOOPER,
                                       NULL, NULL, NULL, NULL, P_FORNECED, NULL, C_ITEMPRODUTO.IDORIGEMPROD);


                  END IF;
               END IF;

               V_PARDEDTMP    := 0;
               V_PREDBCTMP1   := 0;
               V_PREDBCTMP    := 0;
               V_ALIQUTMP     := 0;
               V_IMPOSTOIT    := 0;
               V_IMPOSTORED1  := 0;
               V_ALIQINFO     := 0;
               V_IMPOSINFO    := 0;
               V_VRPERREDBCIT := 0;
               V_VRBASECALCIT := 0;
               V_VRIMPOSTOST  := 0;
               V_VRPPRIIMPST  := 0;
               V_IDREDUCAO    := 'N';

               /*VERIFICA CST POR IMPOSTO*/
               V_IMPOICMS := NULL;
               V_CDGRUPOFISCAUX := NULL;

               SELECT MAX(G.CDGRUPOFISC)
                 INTO V_CDGRUPOFISCAUX
                 FROM GRUPOFISCIMPFIL G,
                      (SELECT DECODE('E', 'E', CDFILIRECE, CDFILIEMIT) AS CDFILIAL
                         FROM NOTAFISCAL
                        WHERE CDFILIAL = P_FILIAL
                              AND NRLANCTONF = P_LANCTONF) F
                WHERE G.CDFILIAL = F.CDFILIAL
                  AND NOT G.CDGRUPOFISC IS NULL
                  AND G.CDIMPOSTO = C_INCIDENCIA.CDIMPOTEMP;

               IF V_IDORIGDESTNF = 'F' THEN
                  SELECT NVL(MAX(G.CDGRUPOFISC), V_CDGRUPOFISCAUX)
                    INTO V_CDGRUPOFISCAUX
                    FROM GRFISIMPIEFORN G,
                         (SELECT CDFORNECED
                            FROM NOTAFISCAL
                           WHERE CDFILIAL = P_FILIAL
                             AND NRLANCTONF = P_LANCTONF) N
                   WHERE G.CDFORNECED = N.CDFORNECED
                     AND G.CDEMPRESA = P_EMPRESA
                     AND G.CDINSCESTA = P_INSCESTA
                     AND NOT G.CDGRUPOFISC IS NULL
                     AND G.CDIMPOSTO = C_INCIDENCIA.CDIMPOTEMP;
               ELSE
                  SELECT NVL(MAX(G.CDGRUPOFISC), V_CDGRUPOFISCAUX)
                    INTO V_CDGRUPOFISCAUX
                    FROM GRFISIMPIECLIE G,
                         (SELECT CDCLIENTE
                            FROM NOTAFISCAL
                           WHERE CDFILIAL = P_FILIAL
                             AND NRLANCTONF = P_LANCTONF) N
                   WHERE G.CDCLIENTE = N.CDCLIENTE
                     AND G.CDEMPRESA = P_EMPRESA
                     AND G.CDINSCESTA = P_INSCESTA
                     AND NOT G.CDGRUPOFISC IS NULL
                     AND G.CDIMPOSTO = C_INCIDENCIA.CDIMPOTEMP;
               END IF;

               IF V_CDGRUPOFISCAUX IS NULL THEN
                  CONSULTA_CST_NFE(W_E, P_EMPRESA, C_ITEMPRODUTO.CDARVPROD, P_INSCESTA, P_TIPOOPER, V_CDGRUPOFISC,C_INCIDENCIA.CDIMPOTEMP, V_IDINTEREST, V_IDINTERNAC,  P_FILIAL, P_LANCTONF, '', V_CDSITTRIBTMP, V_IDMODBCNFE, V_IDMODBCSTNFE, V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, V_IDMOTIDESSTNFE, C_ITEMPRODUTO.IDORIGEMPROD);
               ELSE
                  CONSULTA_CST_NFE(W_E, P_EMPRESA, C_ITEMPRODUTO.CDARVPROD, P_INSCESTA, P_TIPOOPER, V_CDGRUPOFISCAUX,C_INCIDENCIA.CDIMPOTEMP, V_IDINTEREST, V_IDINTERNAC,  P_FILIAL, P_LANCTONF, '', V_CDSITTRIBTMP, V_IDMODBCNFE, V_IDMODBCSTNFE, V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, V_IDMOTIDESSTNFE, C_ITEMPRODUTO.IDORIGEMPROD);
               END IF;

               V_ICMS := 'N';
               FOR C_ICMS IN (SELECT CDIMPOSTO
                                FROM IMPOSTONFE N, IMPOSTO I
                               WHERE N.CDIMPOSTONFE = I.CDIMPOSTONFE
                                 AND N.CDIMPOSTONFE = '00'
                                 AND I.CDIMPOSTO = C_INCIDENCIA.CDIMPOTEMP
                              UNION ALL
                              SELECT CDIMPOSTO
                                FROM IMPOSTO
                               WHERE CDIMPOSTRIB = C_INCIDENCIA.CDIMPOTEMP)
               LOOP
                  V_ICMS := 'S';
               END LOOP;

               --IF (C_ITEMPRODUTO.CDSITUTRIBPR IS NOT NULL) AND (V_ICMS = 'S')  THEN
               --   V_CDSITTRIBTMP := SUBSTR(C_ITEMPRODUTO.CDSITUTRIBPR, 2, LENGTH(C_ITEMPRODUTO.CDSITUTRIBPR));
               --END IF;                   

               V_CDREGRAITALIQ  := NULL;

               SELECT MAX(CDIMPOSTO)
                 INTO V_IMPOICMS
                 FROM IMPOSTONFE N, IMPOSTO I
                WHERE N.CDIMPOSTONFE = I.CDIMPOSTONFE
                  AND N.CDIMPOSTONFE = '00'
                  AND I.CDIMPOSTO = C_INCIDENCIA.CDIMPOTEMP;

               SELECT NVL(MAX(VRPARDEDTMP),0), NVL(MAX(VRPREDBCTMP),0),     NVL(MAX(VRALIQUTMP),0),
                      NVL(MAX(VRPBCSTTMP),0),  NVL(MAX(IDTRIMPSTTMP), '0'), NVL(MAX(VR1PREDBCTMP), '0'),
                      MAX(CDREGRATMP),         MAX(CDFISCOPER),             MAX(IDDIFEALIQ),
                      MAX(IDDIFALIQCUSPR),     MAX(CDBENEFFISCAL),          MAX(IDCONSDIFALIQ)
                 INTO V_PARDEDTMP, V_PREDBCTMP, V_ALIQUTMP,
                      V_PBCSUBTRIB, V_IDTRIMPSTII, V_PREDBCTMP1,
                      V_CDREGRAITALIQ, V_CDFISCOPERREGRA, V_IDDIFEALIQREGRA,
                      V_IDDIFALIQCUSPRREGRA, V_CDBENEFFISCAL, V_IDCONSDIFALIQ
                 FROM ALIQTEMP
                WHERE (NRALIQTEMP = V_ALIQTEMP);

               V_IDCONSDIFALIQ := NVL(V_IDCONSDIFALIQ, 'N'); 

               IF V_PREDBCTMP > 0 THEN
                  V_IDREDUCAO := '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;

               IF (V_CDFISCOPERREGRA IS NOT NULL) AND (V_IDCOMPRABONI <> 'S') THEN
                  V_CDFISCOPERREGRA := V_CFOP1DIGT||V_CDFISCOPERREGRA;
                  V_DSCDFISOPEITREGRA := SUBSTR(DESCRICAO_CFOP(V_CDFISCOPERREGRA),1,45);
               END IF;

               IF (V_IDCOMPRABONI = 'S') THEN
                  V_FISOPEITEM        := C_ITEMPRODUTO.CDFISOPEITEM;
                  V_CDFISCOPERREGRA   := V_FISOPEITEM;
                  V_DSCDFISOPEITREGRA := SUBSTR(DESCRICAO_CFOP(V_FISOPEITEM),1,45);
               END IF;

               V_FISOPEITEM      := NVL(V_CDFISCOPERREGRA, V_FISOPEITEM);
               V_DSCDFISOPEIT    := NVL(V_DSCDFISOPEITREGRA, V_DSCDFISOPEIT);

               V_DIFALIQITEM     := NVL(V_IDDIFEALIQREGRA, V_DIFALIQITEM);
               V_IDDIFALIQCUSPRC := NVL(V_IDDIFALIQCUSPRREGRA, V_IDDIFALIQCUSPRC);

               IF (V_CDFISCOPERREGRA IS NOT NULL) THEN
                  IF (LENGTH(V_CDFISCOPERREGRA) < 4) THEN
                     V_CDFISCOPERREGRA := V_CFOP1DIGT||V_CDFISCOPERREGRA;
                  END IF;

                  UPDATE ITEMPRODUTO
                     SET CDFISOPEITEM = V_CDFISCOPERREGRA
                   WHERE CDFILIAL     = P_FILIAL
                     AND NRLANCTONF  = P_LANCTONF
                     AND NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;
               END IF;

               SELECT NVL(MAX(VRALIQIMPOIT),0), NVL(MAX(VRIMPOSIT),0),
                      NVL(MAX(IDVALORINFO),W_N), COUNT(*),
                      NVL(MAX(VRREDBCIMPOIT),0), NVL(MAX(VRBCALCIMPOIT),0),
                      NVL(MAX(CDFISCIMPOIT), '3'), MAX(CDSTRIBITNFE),
                      NVL(MAX(IDMODBCITEMNFE), '3'), NVL(MAX(IDMODBCSTITENFE), '4'),
                      NVL(MAX(VRADICALIQFECP), 0),  NVL(MAX(VRADICFECP),0)
               INTO V_ALIQINFO, V_IMPOSINFO, V_IDVALORINFO, V_NRIMPOSTO,
                    V_VRPERREDBCIT, V_VRBASECALCIT, V_CDFISCALCOMP,
                    V_SITUTRIBCOMP, V_IDMODBCNFECOMP, V_IDMODBCSTNFECOMP,
                    V_VRADICALIQFECP, V_VRADICFECP
               FROM TRABITPROIMPOS
               WHERE CDFILIMPOIT  = P_FILIAL                  AND
                     NRLANCIMPOIT = P_LANCTONF                AND
                     NRSEQIMPOIT  = C_ITEMPRODUTO.NRSEQITPROD AND
                     CDIMPOSTOIT  = C_INCIDENCIA.CDIMPOTEMP;

               V_TAXABASECALC := (100 - V_PREDBCTMP1)/100;
               V_BASECALCIT   := V_LIQUIITEM * V_TAXABASECALC;

               V_TAXABASECALC := (100 - V_PREDBCTMP)/100;
               V_TAXAALIQUOTA := (V_ALIQUTMP/100);
               V_TAXAALIQFECP := (V_VRADICALIQFECP/100);
               V_TAXAALIQINFO := (V_ALIQINFO/100);
               V_TAXABCSUBSTR := 1 + (V_PBCSUBTRIB/100);

               IF V_PREDBCTMP1 <> 0 THEN
                  V_IMPOSTORED1 := V_BASECALCIT * V_TAXAALIQUOTA;
                  V_BASECALCIT  := V_BASECALCIT * V_TAXABASECALC;
               ELSE
                  V_BASECALCIT := V_LIQUIITEM * V_TAXABASECALC;
               END IF;

               V_PERDBCALC    := 100 - V_PREDBCTMP;

               IF V_PBCSUBTRIB > 0 THEN
                  V_BASECALCIT := (V_BASECALCIT * V_TAXABCSUBSTR);
                  V_PREDBCTMP  := V_PBCSUBTRIB;
                  V_PERDBCALC  := 0;
               END IF;

               V_VRPPRIIMPST := 0;
               V_CDIMPOSTRIB := NULL;
               V_VRIMPOSTOST := 0;


               IF (V_IDCONSDIFALIQ = 'S') AND (C_INCIDENCIA.CDIMPOSTONFE = '80') THEN

                  SELECT II.VRIMPOSIT, II.CDIMPOSTOIT, II.VRALIQIMPOIT
                    INTO V_VRICMSNF, V_CDIMPOSTOICMS, V_ALIQICMS
                    FROM TRABITPROIMPOS II, IMPOSTO I
                   WHERE (II.CDFILIMPOIT  = P_FILIAL)
                     AND (II.NRLANCIMPOIT = P_LANCTONF)
                     AND (II.NRSEQIMPOIT  = C_ITEMPRODUTO.NRSEQITPROD)
                     AND (II.NRSEQITPRO   = W_1)
                     AND (I.CDIMPOSTONFE  = '00')
                     AND (II.CDIMPOSTOIT  = I.CDIMPOSTO);

                  DELETE ALIQTEMP
                   WHERE NRALIQTEMP = V_ALIQTEMP;

                  CONSULTA_ALIQUOTA(V_CDIMPOSTOICMS, P_ENTRSAID, P_EMPRESA, C_ITEMPRODUTO.CDARVPROD, P_INSCESTA, V_PAISDEST,
                                       V_ESTADEST, V_PAISDEST, V_ESTADEST, V_MUNIDEST, V_LIQUIITEM, P_INIVALID, P_FILIAL, P_LANCTONF, V_CDGRPFISCSV,P_TIPOOPER,
                                       NULL, NULL, NULL, NULL, P_FORNECED, NULL, C_ITEMPRODUTO.IDORIGEMPROD);

                  SELECT MAX(VRALIQUTMP)
                    INTO V_VRALIQICMSINT
                    FROM ALIQTEMP
                   WHERE (NRALIQTEMP = V_ALIQTEMP);
                
                  IF ((V_VRALIQICMSINT IS NULL) OR (V_VRALIQICMSINT < V_ALIQICMS)) THEN
                     BEGIN
                        SELECT NVL(CONSULTA_QUADRO_ALIQUOTAS(V_ESTADEST, V_ESTADEST), 0)
                          INTO V_VRALIQICMSINT
                          FROM DUAL;
                     EXCEPTION
                        WHEN NO_DATA_FOUND THEN
                           V_VRALIQICMSINT := 0;
                     END;
                  END IF;

                  V_ALIQSTDIF   := V_VRALIQICMSINT;
                  V_BASECALCDIF :=  ROUND((V_BASECALCIT - V_VRICMSNF)/(1-(V_VRALIQICMSINT/100)), 2);
                  V_IMPOSTODIF  := ROUND(((V_BASECALCDIF * (V_VRALIQICMSINT/100)) - V_VRICMSNF), 2);

                  IF (V_IMPOSTODIF < 0) THEN
                     V_IMPOSTODIF := 0;
                  END IF;

                  DELETE ALIQTEMP
                   WHERE NRALIQTEMP = V_ALIQTEMP;   

               ELSE

                  /* Caso o st esteja relacionado a mais de um ICMS, o sistema calculo sobre o ICMS que incide na NF */
                  FOR C_ICMSST IN (SELECT CDIMPOSTO
                                          FROM IMPOSTO
                                         WHERE CDIMPOSTRIB = C_INCIDENCIA.CDIMPOTEMP)
                  LOOP
                     V_CDIMPOSTRIB := V_CDIMPOSTRIB||C_ICMSST.CDIMPOSTO||'_';
                  END LOOP;

                  IF V_CDIMPOSTRIB IS NOT NULL THEN
                     SELECT NVL(MAX(IDVRIMPSTRIB), 'N')
                       INTO V_IDVRIMPSTRIB
                       FROM TRABITPROIMPOS I, IMPOSTO II
                      WHERE (CDFILIMPOIT     = P_FILIAL)
                        AND (NRLANCIMPOIT   = P_LANCTONF)
                        AND (NRSEQIMPOIT  = C_ITEMPRODUTO.NRSEQITPROD)
                        AND (INSTR(V_CDIMPOSTRIB,II.CDIMPOSTO||'_') > 0)
                        AND (I.CDIMPOSTOIT = II.CDIMPOSTO);

                     IF (V_IDTRIMPSTII = W_1) OR (NVL(V_IDVRIMPSTRIB,W_N) = W_N) THEN
                        V_VRIMPOSTOST := 0;
                        V_VRPPRIIMPST := 0;
                     ELSE
                        BEGIN
                           SELECT NVL(VRIMPOSIT,0), NVL(VR1IMPOSTOIT, 0)
                           INTO V_VRIMPOSTOST, V_VRPPRIIMPST
                           FROM TRABITPROIMPOS I
                           WHERE (CDFILIMPOIT  = P_FILIAL)                   AND
                                 (NRLANCIMPOIT = P_LANCTONF)                 AND
                                 (NRSEQIMPOIT  = C_ITEMPRODUTO.NRSEQITPROD)  AND
                                 (INSTR(V_CDIMPOSTRIB,CDIMPOSTOIT||'_') > 0) AND
                                 (NRSEQITPRO   = W_1);
                        EXCEPTION
                        WHEN NO_DATA_FOUND THEN
                           V_VRIMPOSTOST := 0;
                           V_VRPPRIIMPST := 0;
                        END;
                     END IF;
                  END IF;
               END IF;

               IF (C_INCIDENCIA.IDUTVLRQTDEIMPO = W_S) THEN
                  V_IMPOSTOIT := (C_ITEMPRODUTO.QTITEMPROD * V_ALIQUTMP) - V_PARDEDTMP;

                  IF V_VRPPRIIMPST <> 0 THEN
                     V_IMPOSTOIT := V_IMPOSTOIT - V_VRPPRIIMPST;
                  ELSE
                     V_IMPOSTOIT := V_IMPOSTOIT - V_VRIMPOSTOST;
                  END IF;
               ELSE
                  V_IMPOSTOIT := (V_BASECALCIT * V_TAXAALIQUOTA) - V_PARDEDTMP;
                  IF NOT(V_VRADICFECP > 0) THEN
                     V_VRADICFECP := (V_BASECALCIT * V_TAXAALIQFECP);
                  END IF;

                  IF V_VRPPRIIMPST <> 0 THEN
                     V_IMPOSTOIT := V_IMPOSTOIT - V_VRPPRIIMPST;
                  ELSE
                     V_IMPOSTOIT := V_IMPOSTOIT - V_VRIMPOSTOST;
                  END IF;
               END IF;

               IF P_AUDIT = W_S THEN

                  IF (V_IDVALORINFO <> W_S) THEN
                     IF (C_INCIDENCIA.IDUTVLRQTDEIMPO = W_S) THEN
                        V_IMPOSINFO := (V_ALIQINFO * C_ITEMPRODUTO.QTITEMPROD) - V_PARDEDTMP;

                        IF V_VRPPRIIMPST <> 0 THEN
                           V_IMPOSINFO := V_IMPOSINFO - V_VRPPRIIMPST;
                        ELSE
                           V_IMPOSINFO := V_IMPOSINFO - V_VRIMPOSTOST;
                        END IF;
                     ELSE
                        V_IMPOSINFO := (V_BASECALCIT * V_TAXAALIQINFO) - V_PARDEDTMP;

                        IF V_VRPPRIIMPST <> 0 THEN
                           V_IMPOSINFO := V_IMPOSINFO - V_VRPPRIIMPST;
                        ELSE
                           V_IMPOSINFO := V_IMPOSINFO - V_VRIMPOSTOST;
                        END IF;
                     END IF;
                  ELSE
                     V_ALIQUTMP := V_ALIQINFO;
                     V_IMPOSTOIT := V_IMPOSINFO;

                     BEGIN
                        SELECT NVL(IDVALORINFO, 'N')
                          INTO V_IDIMPORTAIMPXML
                          FROM TRABITPROIMPOS
                         WHERE CDFILIMPOIT  = P_FILIAL
                           AND NRLANCIMPOIT = P_LANCTONF
                           AND NRSEQIMPOIT  = C_ITEMPRODUTO.NRSEQITPROD
                           AND CDIMPOSTOIT  = C_INCIDENCIA.CDIMPOTEMP
                           AND NRSEQITPRO   = '1';
                     EXCEPTION
                        WHEN NO_DATA_FOUND THEN
                           V_IDIMPORTAIMPXML := 'N';
                     END;

                     IF (V_IDNFGERADAVIAXML = 'S') AND ((V_IDIMPORTAIMPXML = 'S') OR (V_IDGERNFIGUALXML = 'S')) THEN
                        V_PREDBCTMP  := V_VRPERREDBCIT;
                        V_BASECALCIT := V_VRBASECALCIT;
                     END IF;
                     --NF DE COMPLEMENTO
                     IF (P_TIPOOPER = '03') THEN
                        V_PREDBCTMP    := V_VRPERREDBCIT;
                        V_BASECALCIT   := V_VRBASECALCIT;
                        V_CDSITTRIBTMP := V_SITUTRIBCOMP;
                        V_IDMODBCNFE   := V_IDMODBCNFECOMP;
                        V_IDMODBCSTNFE := V_IDMODBCSTNFECOMP;
                     END IF;
                  END IF;
               ELSE
                  IF (V_IDVALORINFO <> W_S) THEN
                     IF (C_INCIDENCIA.IDUTVLRQTDEIMPO = W_S) THEN
                        V_IMPOSINFO := (V_ALIQINFO * C_ITEMPRODUTO.QTITEMPROD) - V_PARDEDTMP;

                        IF V_VRPPRIIMPST <> 0 THEN
                           V_IMPOSINFO := V_IMPOSINFO - V_VRPPRIIMPST;
                        ELSE
                           V_IMPOSINFO := V_IMPOSINFO - V_VRIMPOSTOST;
                        END IF;
                     ELSE
                        V_IMPOSINFO := (V_BASECALCIT * V_TAXAALIQINFO) - V_PARDEDTMP;

                        IF V_VRPPRIIMPST <> 0 THEN
                           V_IMPOSINFO := V_IMPOSINFO - V_VRPPRIIMPST;
                        ELSE
                           V_IMPOSINFO := V_IMPOSINFO - V_VRIMPOSTOST;
                        END IF;
                     END IF;
                  ELSE
                     V_ALIQUTMP := V_ALIQINFO;
                     V_IMPOSTOIT := V_IMPOSINFO;

                     BEGIN
                        SELECT NVL(IDVALORINFO, 'N')
                          INTO V_IDIMPORTAIMPXML
                          FROM TRABITPROIMPOS
                         WHERE CDFILIMPOIT  = P_FILIAL
                           AND NRLANCIMPOIT = P_LANCTONF
                           AND NRSEQIMPOIT  = C_ITEMPRODUTO.NRSEQITPROD
                           AND CDIMPOSTOIT  = C_INCIDENCIA.CDIMPOTEMP
                           AND NRSEQITPRO   = '1';
                     EXCEPTION
                        WHEN NO_DATA_FOUND THEN
                           V_IDIMPORTAIMPXML := 'N';
                     END;

                     IF (V_IDNFGERADAVIAXML = 'S') AND ((V_IDIMPORTAIMPXML = 'S') OR (V_IDGERNFIGUALXML = 'S')) THEN
                        V_PREDBCTMP  := V_VRPERREDBCIT;
                        V_BASECALCIT := V_VRBASECALCIT;     
                     END IF;
                     --NF DE COMPLEMENTO
                     IF (P_TIPOOPER = '03') THEN
                        V_PREDBCTMP    := V_VRPERREDBCIT;
                        V_BASECALCIT   := V_VRBASECALCIT;
                        V_CDSITTRIBTMP := V_SITUTRIBCOMP;
                        V_IDMODBCNFE   := V_IDMODBCNFECOMP;
                        V_IDMODBCSTNFE := V_IDMODBCSTNFECOMP;
                     END IF;
                  END IF;
               END IF;

               V_CONTABCALC := V_LIQUIDOPROD - (V_LIQUIDOPROD * V_TAXABASECALC);

               /* ROTINA PARA CALCULAR O DIFERIMENTO DO IMPOSTO */
               V_PERDIFERE    := NULL;
               V_IMPOSTOOPERA := NULL;
               V_IMPOSTODIFER := NULL;

               IF C_INCIDENCIA.CDIMPOSTONFE = '00' THEN
                  IF V_CDSITTRIBTMP = '51' THEN
                     BEGIN
                        SELECT PD.VRPERDIFERE
                          INTO V_VRPERDIFERE
                          FROM PRODDIFEREIMPOS PD, PRODUTO PR
                         WHERE PD.CDPRODUTO = PR.CDPRODUTO
                           AND PD.CDPAIS = V_PAISORIG
                           AND PD.SGESTADO = V_ESTAORIG
                           AND PR.CDARVPROD IN (SELECT MAX(PR.CDARVPROD) AS CDARVPROD
                                                  FROM PRODDIFEREIMPOS PD, PRODUTO PR
                                                 WHERE PD.CDPRODUTO = PR.CDPRODUTO
                                                   AND PD.CDPAIS = V_PAISORIG
                                                   AND PD.SGESTADO = V_ESTAORIG
                                                   AND INSTR(NVL(RTRIM(C_ITEMPRODUTO.CDARVPROD), PR.CDARVPROD), PR.CDARVPROD) = 1);
                     EXCEPTION
                        WHEN NO_DATA_FOUND THEN
                           V_VRPERDIFERE := NULL;
                    END;

                     IF V_VRPERDIFERE IS NOT NULL THEN
                        V_PERDIFERE    := ROUND(V_VRPERDIFERE, 2);
                        V_IMPOSTOOPERA := ROUND(V_IMPOSTOIT, 2);
                        IF ((V_IDNFGERADAVIAXML = 'S') AND ((NVL(V_IDIMPORTAIMPXML, 'N') = 'S') OR (V_IDGERNFIGUALXML = 'S'))) THEN
                           V_IMPOSTOOPERA := ROUND((V_BASECALCIT * V_ALIQUTMP/100), 2);
                        END IF;
                        V_IMPOSTODIFER := ROUND(((V_BASECALCIT * V_ALIQUTMP/100) * (V_VRPERDIFERE/100)), 2);
                        IF NOT((V_IDNFGERADAVIAXML = 'S') AND ((NVL(V_IDIMPORTAIMPXML, 'N') = 'S') OR (V_IDGERNFIGUALXML = 'S'))) THEN
                           V_IMPOSTOIT := ROUND(V_IMPOSTOOPERA, 2) - ROUND(V_IMPOSTODIFER, 2);
                        END IF;

                        V_IMPOSINFO := V_IMPOSTOIT;

                     END IF;
                  END IF;
               END IF;

               IF (V_IMPOSTOIT < 0) THEN
                  V_IMPOSTOIT := 0;
               END IF;

               IF (V_IMPOSINFO < 0) THEN
                  V_IMPOSINFO := 0;
               END IF;

               BEGIN
                  SELECT CDFISOPEITEM, CDSUFXCFOPPR
                  INTO V_FISOPEITEM, V_SUFXCFOPPR
                  FROM ITEMPRODUTO
                  WHERE CDFILIAL    = P_FILIAL   AND
                        NRLANCTONF  = P_LANCTONF AND
                        NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_FISOPEITEM := NULL; V_SUFXCFOPPR := NULL;
               END;

               V_IMPOICMS := NULL;
               V_CST1DIGT := NULL;

               SELECT MAX(CDIMPOSTO)
                 INTO V_IMPOICMS
                 FROM IMPOSTONFE N, IMPOSTO I
                WHERE N.CDIMPOSTONFE = I.CDIMPOSTONFE
                  AND N.CDIMPOSTONFE = '00'
                  AND I.CDIMPOSTO = C_INCIDENCIA.CDIMPOTEMP;

               IF (V_IMPOICMS IS NOT NULL) THEN
                  IF V_IDORIGDESTNF = 'L' THEN
                     Begin
                        SELECT MAX(CDCSTDIG1PROD)
                          INTO V_CST1DIGT
                          FROM PRODUTO
                         WHERE (CDARVPROD = C_ITEMPRODUTO.CDARVPROD);

                        IF V_CST1DIGT IS NULL THEN
                           SELECT MAX(CDCSTDIG1SAI)
                           INTO   V_CST1DIGT
                           FROM INSCRESTAD
                           WHERE CDEMPRESA  = P_EMPRESA AND
                                 CDINSCESTA = P_INSCESTA;
                        END IF;
                     Exception
                        When No_Data_Found Then
                           V_CST1DIGT := Null;
                     End;
                  ELSIF V_IDORIGDESTNF = 'C' THEN
                     Begin
                        SELECT MAX(CDCSTDIG1PROD)
                          INTO V_CST1DIGT
                          FROM PRODUTO
                         WHERE (CDARVPROD = C_ITEMPRODUTO.CDARVPROD);

                        IF V_CST1DIGT IS NULL THEN
                           SELECT MAX(CDCSTDIG1CLI)
                             INTO V_CST1DIGT
                             FROM NOTAFISCAL N, CLIENTE C
                            WHERE CDFILIAL     = P_FILIAL    AND
                                  NRLANCTONF   = P_LANCTONF  AND
                                  N.CDCLIENTE  = C.CDCLIENTE;
                        END IF;
                     Exception
                        When No_Data_Found Then
                           V_CST1DIGT := Null;
                     End;
                  ELSE
                     Begin
                        SELECT MAX(CDCSTDIG1PROD)
                          INTO V_CST1DIGT
                          FROM PRODUTO
                         WHERE (CDARVPROD = C_ITEMPRODUTO.CDARVPROD);

                        IF V_CST1DIGT IS NULL THEN
                           SELECT MAX(CDCSTDIG1ENT)
                             INTO   V_CST1DIGT
                             FROM NOTAFISCAL N, FORNECEDOR F
                            WHERE CDFILIAL     = P_FILIAL   AND
                                 NRLANCTONF    = P_LANCTONF AND
                                 N.CDFORNECED  = F.CDFORNECED;
                        END IF;
                     Exception
                        When No_Data_Found Then
                           V_CST1DIGT := Null;
                     End;
                  END IF;

                  IF (V_IDUTORIGPROD = 'S') AND (C_ITEMPRODUTO.IDORIGEMPROD = 'E') AND (NVL(V_IDNFGERADAVIAXML, 'N') <> 'S') THEN
                     V_CST1DIGT := '2';
                  END IF;       

                  IF (V_CDSITTRIBTMP IS NOT NULL) THEN

                     UPDATE ITEMPRODUTO
                        SET CDSITUTRIBPR  = V_CST1DIGT||V_CDSITTRIBTMP

                      WHERE CDFILIAL      = P_FILIAL AND
                            NRLANCTONF    = P_LANCTONF AND
                            NRSEQITPROD   = C_ITEMPRODUTO.NRSEQITPROD;

                     V_SITUTRIBPR := V_CST1DIGT||V_CDSITTRIBTMP;
                  END IF;

                  V_CDGRUPOFISCAUX := NULL;

                  SELECT MAX(G.CDGRUPOFISC)
                    INTO V_CDGRUPOFISCAUX
                    FROM GRUPOFISCIMPFIL G,
                         (SELECT DECODE('E', 'E', CDFILIRECE, CDFILIEMIT) AS CDFILIAL
                            FROM NOTAFISCAL
                           WHERE CDFILIAL = P_FILIAL
                                 AND NRLANCTONF = P_LANCTONF) F
                   WHERE G.CDFILIAL = F.CDFILIAL
                     AND NOT G.CDGRUPOFISC IS NULL
                     AND G.CDIMPOSTO = C_INCIDENCIA.CDIMPOTEMP;

                  IF V_IDORIGDESTNF = 'F' THEN
                     SELECT NVL(MAX(G.CDGRUPOFISC), V_CDGRUPOFISCAUX)
                       INTO V_CDGRUPOFISCAUX
                       FROM GRFISIMPIEFORN G,
                            (SELECT CDFORNECED
                               FROM NOTAFISCAL
                              WHERE CDFILIAL = P_FILIAL
                                AND NRLANCTONF = P_LANCTONF) N
                      WHERE G.CDFORNECED = N.CDFORNECED
                        AND G.CDEMPRESA = P_EMPRESA
                        AND G.CDINSCESTA = P_INSCESTA
                        AND NOT G.CDGRUPOFISC IS NULL
                        AND G.CDIMPOSTO = C_INCIDENCIA.CDIMPOTEMP;
                  ELSE
                     SELECT NVL(MAX(G.CDGRUPOFISC), V_CDGRUPOFISCAUX)
                       INTO V_CDGRUPOFISCAUX
                       FROM GRFISIMPIECLIE G,
                            (SELECT CDCLIENTE
                               FROM NOTAFISCAL
                              WHERE CDFILIAL = P_FILIAL
                                AND NRLANCTONF = P_LANCTONF) N
                      WHERE G.CDCLIENTE = N.CDCLIENTE
                        AND G.CDEMPRESA = P_EMPRESA
                        AND G.CDINSCESTA = P_INSCESTA
                        AND NOT G.CDGRUPOFISC IS NULL
                        AND G.CDIMPOSTO = C_INCIDENCIA.CDIMPOTEMP;
                  END IF;

                  IF (V_IDCOMPRABONI = 'N') THEN
                     IF (V_CDGRUPOFISCAUX IS NOT NULL) THEN
                        CONSULTA_CFOP(P_ENTRSAID, P_EMPRESA, C_ITEMPRODUTO.CDARVPROD, P_INSCESTA, P_TIPOOPER, V_PAISCFOP,
                                      V_ESTACFOP, V_PAISDEST, V_ESTADEST, P_FILIAL, P_LANCTONF, V_CDGRUPOFISCAUX, P_INIVALID, C_ITEMPRODUTO.IDORIGEMPROD);

                     ELSE
                        CONSULTA_CFOP(P_ENTRSAID, P_EMPRESA, C_ITEMPRODUTO.CDARVPROD, P_INSCESTA, P_TIPOOPER, V_PAISCFOP,
                                      V_ESTACFOP, V_PAISDEST, V_ESTADEST, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC, P_INIVALID, C_ITEMPRODUTO.IDORIGEMPROD);

                     END IF;

                     SELECT MAX(CDFISOPETMP), MAX(CDSUFCFOPTMP), MAX(IDDIFALIQTMP),
                            MAX(DSCFOPTMP), NVL(MAX(IDDIFALIQCUSPRC),W_N)
                       INTO V_FISOPEITEM, V_SUFXCFOPPR, V_DIFALIQITEM,
                            V_DSCDFISOPEIT, V_IDDIFALIQCUSPRC
                       FROM CFOPTEMP
                      WHERE NRCFOPTEMP = V_CFOPTEMP;

                      V_FISOPEITEM      := NVL(V_CDFISCOPERREGRA, V_FISOPEITEM);
                      V_DSCDFISOPEIT    := NVL(V_DSCDFISOPEITREGRA, V_DSCDFISOPEIT);
                      V_DIFALIQITEM     := NVL(V_IDDIFEALIQREGRA, V_DIFALIQITEM);
                      V_IDDIFALIQCUSPRC := NVL(V_IDDIFALIQCUSPRREGRA, V_IDDIFALIQCUSPRC);

                      -- ALTERA NATUREZA DE OPERAÇÃO DA NOTA FISCAL CASO NÃO EXISTA
                      IF (V_DSCDFISOPEITREGRA IS NOT NULL) THEN
                         UPDATE NOTAFISCAL
                            SET DSCDFISOPENF = V_DSCDFISOPEITREGRA
                          WHERE CDFILIAL   = P_FILIAL   AND
                                NRLANCTONF = P_LANCTONF;
                      ELSE
                         UPDATE NOTAFISCAL
                            SET DSCDFISOPENF = (SELECT MAX(DSCFOPTMP)
                                                  FROM CFOPTEMP
                                                 WHERE NRCFOPTEMP = V_CFOPTEMP)
                          WHERE CDFILIAL   = P_FILIAL
                            AND NRLANCTONF = P_LANCTONF
                            AND DSCDFISOPENF IS NULL;

                      END IF;

                      -- ALTERA O CFOP DO ITEM E
                      UPDATE ITEMPRODUTO
                      SET CDFISOPEITEM = NVL(V_CDFISCOPERREGRA, V_FISOPEITEM),
                          CDSUFXCFOPPR = V_SUFXCFOPPR,
                          DSCDFISOPEIT = NVL(V_DSCDFISOPEITREGRA, V_DSCDFISOPEIT)
                      WHERE CDFILIAL    = P_FILIAL   AND
                            NRLANCTONF  = P_LANCTONF AND
                            NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;

                     DELETE CFOPTEMP
                      WHERE NRCFOPTEMP = V_CFOPTEMP;
                  END IF;

               END IF;


               INSERT INTO ITEMPROIMPOS(
                  CDFILIAL, NRLANCTONF, NRSEQITPROD, CDIMPOSTO, NRITPROIMPOS, CDFISCALIT, CDSITUTRIBIT,
                  CDFISCOPERIT, CDSUFXCFOPIT, VRALIQITEM, VRPERREDBCIT, VRPARDEDIT, VRCONTITIMP,
                  VRBASECALCIT, VRIMPOSTOIT, IDERROSIMPIT, IDAVISIMPIT, IDTRIMPSTII, CDSITUTRIBITNFE, IDMODBCITNFE, IDMODBCSTITNFE,
                  VR1PERREDBCIT, VR1IMPREDBCIT, CDTPCREDPICOITE, CDNATUBCALPCIT, IDMOTDESONERAIT, CDREGRAIT, VRBCALCIRRF, CDDETALHEPROD,
                  VRPERDIFEREIT, VRIMPOSTOOPERAIT, VRIMPOSTODIFERIT, VRADICALIQFECP, VRADICFECP, CDBENEFFISCAL, IDCONSDIFALIQ, CDCEST)
               VALUES(
                  P_FILIAL, P_LANCTONF, C_ITEMPRODUTO.NRSEQITPROD, C_INCIDENCIA.CDIMPOTEMP, W_1, C_INCIDENCIA.CDFISCTEMP,
                  V_SITUTRIBPR, NVL(V_CDFISCOPERREGRA, V_FISOPEITEM), V_SUFXCFOPPR, V_ALIQUTMP, V_PREDBCTMP, V_PARDEDTMP, ROUND(V_BASECALCIT, 5), ROUND(V_BASECALCIT, 2), V_IMPOSTOIT,
                  W_00000, W_00000, V_IDTRIMPSTII, V_CDSITTRIBTMP, V_IDMODBCNFE, V_IDMODBCSTNFE, V_PREDBCTMP1, V_IMPOSTORED1,
                  V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, V_IDMOTIDESSTNFE, V_CDREGRAITALIQ, V_BASECALCIT, C_INCIDENCIA.CDDETALHEPROD,
                  V_PERDIFERE, V_IMPOSTOOPERA, V_IMPOSTODIFER, V_VRADICALIQFECP, V_VRADICFECP, V_CDBENEFFISCAL, V_IDCONSDIFALIQ,
                  C_INCIDENCIA.CDCEST);

               IF (P_TIPOOPER = '03') THEN
                  V_CDFISCALCOMP := NVL(V_CDFISCALCOMP, C_INCIDENCIA.CDFISCTEMP);
               ELSE
                  V_CDFISCALCOMP := C_INCIDENCIA.CDFISCTEMP;
               END IF;

               IF (V_IDCONSDIFALIQ = 'S') AND (C_INCIDENCIA.CDIMPOSTONFE = '80') THEN
                  V_BASECALCIT := V_BASECALCDIF;
                  V_ALIQINFO   := V_ALIQSTDIF;
                  V_IMPOSINFO  := V_IMPOSTODIF;
               END IF;

               UPDATE TRABITPROIMPOS
               SET VRALIQIMPOIT     = V_ALIQINFO,
                   VRCONTIMPOIT     = ROUND(V_BASECALCIT, 5),
                   VRREDBCIMPOIT    = V_PREDBCTMP,
                   VRBCALCIMPOIT    = ROUND(V_BASECALCIT, 2),
                   VRPDEDIMPOIT     = V_PARDEDTMP,
                   VRIMPOSIT        = V_IMPOSINFO,
                   CDFISCIMPOIT     = V_CDFISCALCOMP,
                   CDSTRIBIMPOIT    = V_SITUTRIBPR,
                   CDFOPERIMPOIT    = NVL(V_CDFISCOPERREGRA, V_FISOPEITEM),
                   CDSCFOPIMPOIT    = V_SUFXCFOPPR,
                   IDERRIMPOIT      = W_00000,
                   IDAVISIMPOIT     = W_00000,
                   IDTRIMPSTTI      = V_IDTRIMPSTII,
                   CDSTRIBITNFE     = V_CDSITTRIBTMP,
                   IDMODBCITEMNFE   = V_IDMODBCNFE,
                   IDMODBCSTITENFE  = V_IDMODBCSTNFE,
                   VR1REDBCIMPOIT   = V_PREDBCTMP1,
                   VR1IMPOSTOIT     = V_IMPOSTORED1,
                   CDTPCREDPICOITE  = V_CDTPCRPICOSTNFE,
                   CDNATUBCALPCIT   = V_CDNATUBCPCSTNFE,
                   IDMOTDESOTRABIT  = V_IDMOTIDESSTNFE,
                   CDREGRATRABIT    = V_CDREGRAITALIQ,
                   VRBCALCIRRF      = V_BASECALCIT,
                   CDDETALHEPROD    = C_INCIDENCIA.CDDETALHEPROD,
                   CDENQLEGALIPI    = C_INCIDENCIA.CDENQLEGALIPI,
                   VRPERDIFEREIT    = V_PERDIFERE,
                   VRIMPOSTOOPERAIT = V_IMPOSTOOPERA,
                   VRIMPOSTODIFERIT = V_IMPOSTODIFER,
                   VRADICALIQFECP   = V_VRADICALIQFECP,
                   VRADICFECP       = V_VRADICFECP,
                   CDBENEFFISCAL    = V_CDBENEFFISCAL,
                   IDCONSDIFALIQ    = V_IDCONSDIFALIQ,
                   CDCEST           = C_INCIDENCIA.CDCEST
               WHERE CDFILIMPOIT  = P_FILIAL                  AND
                     NRLANCIMPOIT = P_LANCTONF                AND
                     NRSEQIMPOIT  = C_ITEMPRODUTO.NRSEQITPROD AND
                     CDIMPOSTOIT  = C_INCIDENCIA.CDIMPOTEMP   AND
                     NRSEQITPRO   = W_1;

               IF V_IDREDUCAO = 'S' THEN
                  INSERT INTO ITEMPROIMPOS(
                     CDFILIAL, NRLANCTONF, NRSEQITPROD, CDIMPOSTO, NRITPROIMPOS, CDFISCALIT, CDSITUTRIBIT,
                     CDFISCOPERIT, CDSUFXCFOPIT, VRALIQITEM, VRPERREDBCIT, VRPARDEDIT, VRCONTITIMP,
                     VRBASECALCIT, VRIMPOSTOIT, IDERROSIMPIT, IDAVISIMPIT, CDSITUTRIBITNFE, IDMODBCITNFE, IDMODBCSTITNFE,
                     CDTPCREDPICOITE, CDNATUBCALPCIT, IDMOTDESONERAIT, CDREGRAIT, CDCEST)
                  VALUES(
                     P_FILIAL, P_LANCTONF, C_ITEMPRODUTO.NRSEQITPROD, C_INCIDENCIA.CDIMPOTEMP, W_2, W_2,
                     V_SITUTRIBPR, NVL(V_CDFISCOPERREGRA, V_FISOPEITEM), V_SUFXCFOPPR, 0, V_PERDBCALC, V_PARDEDTMP, ROUND(V_CONTABCALC,5), 0, 0,
                     W_00000, W_00000, V_CDSITTRIBTMP, V_IDMODBCNFE, V_IDMODBCSTNFE,
                     V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, V_IDMOTIDESSTNFE, V_CDREGRAITALIQ, C_INCIDENCIA.CDCEST);

                  DELETE TRABITPROIMPOS
                  WHERE CDFILIMPOIT  = P_FILIAL   AND
                        NRLANCIMPOIT = P_LANCTONF AND
                        NRSEQIMPOIT  = C_ITEMPRODUTO.NRSEQITPROD AND
                        CDIMPOSTOIT  = C_INCIDENCIA.CDIMPOTEMP   AND
                        NRSEQITPRO   = W_2;

                  IF  V_NRIMPOSTO  > 0 THEN

                     INSERT INTO TRABITPROIMPOS(
                        CDFILIMPOIT, NRLANCIMPOIT, NRSEQIMPOIT, CDIMPOSTOIT, NRSEQITPRO, CDFISCIMPOIT,
                        CDSTRIBIMPOIT, CDFOPERIMPOIT, CDSCFOPIMPOIT, VRALIQIMPOIT, VRREDBCIMPOIT, VRPDEDIMPOIT,
                        VRCONTIMPOIT, VRBCALCIMPOIT, VRIMPOSIT, IDERRIMPOIT, IDAVISIMPOIT, IDVALORINFO,
                        CDSTRIBITNFE, IDMODBCITEMNFE, IDMODBCSTITENFE, CDTPCREDPICOITE, CDNATUBCALPCIT, IDMOTDESOTRABIT, CDREGRATRABIT, CDCEST)
                     VALUES(
                        P_FILIAL, P_LANCTONF, C_ITEMPRODUTO.NRSEQITPROD, C_INCIDENCIA.CDIMPOTEMP, W_2, W_2,
                        V_SITUTRIBPR, NVL(V_CDFISCOPERREGRA, V_FISOPEITEM), V_SUFXCFOPPR, 0, V_PERDBCALC, V_PARDEDTMP, ROUND(V_CONTABCALC, 5), 0, 0,
                        W_00000, W_00000, V_IDVALORINFO, V_CDSITTRIBTMP, V_IDMODBCNFE, V_IDMODBCSTNFE,
                        V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, V_IDMOTIDESSTNFE, V_CDREGRAITALIQ, C_INCIDENCIA.CDCEST);
                  END IF;
               ELSE
                  DELETE TRABITPROIMPOS
                  WHERE CDFILIMPOIT  = P_FILIAL   AND
                        NRLANCIMPOIT = P_LANCTONF AND
                        NRSEQIMPOIT  = C_ITEMPRODUTO.NRSEQITPROD AND
                        CDIMPOSTOIT  = C_INCIDENCIA.CDIMPOTEMP   AND
                        NRSEQITPRO   = W_2;
               END IF;

               DELETE ALIQTEMP
               WHERE NRALIQTEMP = V_ALIQTEMP;

               IF (V_DIFALIQITEM = W_S)             AND
                  (C_INCIDENCIA.IDIMPORECUP = W_S)  AND
                  (C_INCIDENCIA.IDORGARRECAD = W_E) THEN

                  V_ALIQDIFE    := 0;
                  V_ALIQDEST    := 0;
                  V_IMPOSTODIFE := 0;

                  IF C_INCIDENCIA.IDUTMUNIORIG = W_D THEN
                     /* CONSIDERA O MUNICIPIO DE DESTINO */
                     CONSULTA_ALIQUOTA(C_INCIDENCIA.CDIMPOTEMP, P_ENTRSAID, P_EMPRESA, C_ITEMPRODUTO.CDARVPROD, P_INSCESTA, V_PAISORIG,
                                       V_ESTAORIG, V_PAISDEST, V_ESTADEST, V_MUNIDEST, V_LIQUIITEM, P_INIVALID, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC,P_TIPOOPER,
                                       NULL, NULL, NULL, NULL, P_FORNECED, NULL, C_ITEMPRODUTO.IDORIGEMPROD);
                  ELSE
                     /* CONSIDERA O MUNICIPIO DE ORIGEM */
                     CONSULTA_ALIQUOTA(C_INCIDENCIA.CDIMPOTEMP, W_E, P_EMPRESA, C_ITEMPRODUTO.CDARVPROD, P_INSCESTA, V_PAISDEST,
                                       V_ESTADEST, V_PAISDEST, V_ESTADEST, V_MUNIORIG, V_LIQUIITEM, P_INIVALID, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC, P_TIPOOPER,
                                       NULL, NULL, NULL, NULL, P_FORNECED, NULL, C_ITEMPRODUTO.IDORIGEMPROD);
                  END IF;

                  SELECT MAX(VRALIQUTMP)
                  INTO V_ALIQDEST
                  FROM ALIQTEMP
                  WHERE (NRALIQTEMP = V_ALIQTEMP);

                  IF V_ALIQDEST IS NULL THEN
                     V_ALIQDEST := 0;
                  END IF;

                  IF V_ALIQUTMP < V_ALIQDEST THEN
                     V_ALIQDIFE     := V_ALIQDEST - V_ALIQUTMP;
                     V_BCALCDIFCOMP := 0;

                     IF (V_IDCALCDIFENTFISC = 'S') THEN
                        V_BCALCDIFCOMP := ROUND(((V_BASECALCIT - V_IMPOSTOIT) / ((100 - V_ALIQDEST)/100)) , V_NRDECITOTANF);
                        V_IMPOSTODIFE  := ROUND(((V_BCALCDIFCOMP * (V_ALIQDEST/100)) - V_IMPOSTOIT), V_NRDECITOTANF);
                      ELSE
                        V_IMPOSTODIFE  := ROUND((V_BASECALCIT * (V_ALIQDIFE/100)), V_NRDECITOTANF);
                        V_BCALCDIFCOMP := V_BASECALCIT;
                     END IF;

                     INSERT INTO ITEMPROIMPOS(
                        CDFILIAL, NRLANCTONF, NRSEQITPROD, CDIMPOSTO, NRITPROIMPOS, CDFISCALIT, CDSITUTRIBIT,
                        CDFISCOPERIT, CDSUFXCFOPIT, VRALIQITEM, VRPERREDBCIT, VRPARDEDIT, VRCONTITIMP,
                        VRBASECALCIT, VRIMPOSTOIT, IDERROSIMPIT, IDAVISIMPIT, IDVALORINFIT,
                        CDSITUTRIBITNFE, IDMODBCITNFE, IDMODBCSTITNFE, IDDIFALIQCUSPRI,
                        CDTPCREDPICOITE, CDNATUBCALPCIT, IDMOTDESONERAIT, CDREGRAIT,
                        VRPERDIFEREIT, VRIMPOSTOOPERAIT, VRIMPOSTODIFERIT, CDCEST)
                     VALUES(
                        P_FILIAL, P_LANCTONF, C_ITEMPRODUTO.NRSEQITPROD, C_INCIDENCIA.CDIMPOTEMP, W_3, C_INCIDENCIA.CDFISCTEMP,
                        V_SITUTRIBPR, NVL(V_CDFISCOPERREGRA, V_FISOPEITEM), V_SUFXCFOPPR, V_ALIQDIFE, V_PREDBCTMP, V_PARDEDTMP, ROUND(V_BCALCDIFCOMP, 5), ROUND(V_BCALCDIFCOMP, 2),
                        V_IMPOSTODIFE, W_00000, W_00000, V_IDVALORINFO, V_CDSITTRIBTMP, V_IDMODBCNFE, V_IDMODBCSTNFE, V_IDDIFALIQCUSPRC,
                        V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, V_IDMOTIDESSTNFE, V_CDREGRAITALIQ,
                        V_PERDIFERE, V_IMPOSTOOPERA, V_IMPOSTODIFER, C_INCIDENCIA.CDCEST);
                  END IF;

                  IF V_ALIQINFO < V_ALIQDEST THEN
                     V_ALIQDIFE     := V_ALIQDEST - V_ALIQINFO;
                     V_BCALCDIFCOMP := 0;

                     IF (V_IDCALCDIFENTFISC = 'S') THEN
                        V_BCALCDIFCOMP  := ROUND(((V_BASECALCIT - (V_BASECALCIT * (V_ALIQINFO/100))) / ((100 - V_ALIQDEST)/100)) , V_NRDECITOTANF);
                        V_IMPOSTODIFE  := ROUND(((V_BCALCDIFCOMP * (V_ALIQDEST/100)) - V_IMPOSTOIT), V_NRDECITOTANF);
                     ELSE
                        V_IMPOSTODIFE  := ROUND((V_BASECALCIT * (V_ALIQDIFE/100)), V_NRDECITOTANF);
                        V_BCALCDIFCOMP := V_BASECALCIT;
                     END IF;

                     DELETE TRABITPROIMPOS
                     WHERE CDFILIMPOIT  = P_FILIAL                  AND
                           NRLANCIMPOIT = P_LANCTONF                AND
                           NRSEQIMPOIT  = C_ITEMPRODUTO.NRSEQITPROD AND
                           CDIMPOSTOIT  = C_INCIDENCIA.CDIMPOTEMP   AND
                           NRSEQITPRO   = W_3;

                     INSERT INTO TRABITPROIMPOS(
                        CDFILIMPOIT, NRLANCIMPOIT, NRSEQIMPOIT, CDIMPOSTOIT, NRSEQITPRO, CDFISCIMPOIT,
                        CDSTRIBIMPOIT, CDFOPERIMPOIT, CDSCFOPIMPOIT, VRALIQIMPOIT, VRREDBCIMPOIT, VRPDEDIMPOIT,
                        VRCONTIMPOIT, VRBCALCIMPOIT, VRIMPOSIT, IDERRIMPOIT, IDAVISIMPOIT, IDVALORINFO,
                        CDSTRIBITNFE, IDMODBCITEMNFE, IDMODBCSTITENFE, IDDIFALIQCUSPTI, CDTPCREDPICOITE, CDNATUBCALPCIT, IDMOTDESOTRABIT, CDREGRATRABIT,
                        VRPERDIFEREIT, VRIMPOSTOOPERAIT, VRIMPOSTODIFERIT, CDCEST)
                     VALUES(
                        P_FILIAL, P_LANCTONF, C_ITEMPRODUTO.NRSEQITPROD, C_INCIDENCIA.CDIMPOTEMP, W_3, C_INCIDENCIA.CDFISCTEMP,
                        V_SITUTRIBPR, NVL(V_CDFISCOPERREGRA, V_FISOPEITEM), V_SUFXCFOPPR, V_ALIQDIFE, V_PREDBCTMP, V_PARDEDTMP, ROUND(V_BCALCDIFCOMP,5),
                        ROUND(V_BCALCDIFCOMP, 2), V_IMPOSTODIFE, W_00000, W_00000, V_IDVALORINFO, V_CDSITTRIBTMP, V_IDMODBCNFE, V_IDMODBCSTNFE, V_IDDIFALIQCUSPRC,
                        V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, V_IDMOTIDESSTNFE, V_CDREGRAITALIQ,
                        V_PERDIFERE, V_IMPOSTOOPERA, V_IMPOSTODIFER, C_INCIDENCIA.CDCEST);
                  ELSE
                     DELETE TRABITPROIMPOS
                     WHERE CDFILIMPOIT  = P_FILIAL                  AND
                           NRLANCIMPOIT = P_LANCTONF                AND
                           NRSEQIMPOIT  = C_ITEMPRODUTO.NRSEQITPROD AND
                           CDIMPOSTOIT  = C_INCIDENCIA.CDIMPOTEMP   AND
                           NRSEQITPRO   = W_3;
                  END IF;
               ELSE
                  DELETE TRABITPROIMPOS
                  WHERE CDFILIMPOIT  = P_FILIAL                  AND
                        NRLANCIMPOIT = P_LANCTONF                AND
                        NRSEQIMPOIT  = C_ITEMPRODUTO.NRSEQITPROD AND
                        CDIMPOSTOIT  = C_INCIDENCIA.CDIMPOTEMP   AND
                        NRSEQITPRO   = W_3;
               END IF;

               DELETE ALIQTEMP
               WHERE NRALIQTEMP = V_ALIQTEMP;
            END LOOP;

            DELETE INCITEMP
            WHERE NRINCITEMP = V_INCITEMP;
         END LOOP;
      ELSE
         V_LIQUIDOPROD := 0;
         V_LIQUIITEM   := 0;
         V_MINBCPROD   := 0;

         DELETE ITEMPROIMPOS
         WHERE (CDFILIAL    = P_FILIAL)   AND
               (NRLANCTONF  = P_LANCTONF);
      END IF;


      IF (V_INTEGRACAO IS NOT NULL) AND (P_ENTRSAID = W_S) THEN
         INSERT INTO ITEMPROIMPOS(
            CDFILIAL, NRLANCTONF, NRSEQITPROD, CDIMPOSTO, NRITPROIMPOS, CDFISCALIT, CDSITUTRIBIT,
            CDFISCOPERIT, CDSUFXCFOPIT, VRALIQITEM, VRPERREDBCIT, VRPARDEDIT, VRCONTITIMP,
            VRBASECALCIT, VRIMPOSTOIT, IDERROSIMPIT, IDAVISIMPIT, CDTPCREDPICOITE, CDNATUBCALPCIT, IDMOTDESONERAIT, CDREGRAIT,
            VRPERDIFEREIT, VRIMPOSTOOPERAIT, VRIMPOSTODIFERIT, CDCEST)
            (SELECT CDFILIMPOIT, NRLANCIMPOIT, NRSEQIMPOIT, CDIMPOSTOIT, NRSEQITPRO, CDFISCIMPOIT, CDSTRIBIMPOIT,
                    CDFOPERIMPOIT, CDSCFOPIMPOIT, VRALIQIMPOIT, VRREDBCIMPOIT, VRPDEDIMPOIT, ROUND(VRCONTIMPOIT,5),
                    ROUND(VRBCALCIMPOIT, 2), VRIMPOSIT, IDERRIMPOIT, IDAVISIMPOIT, CDTPCREDPICOITE, CDNATUBCALPCIT, IDMOTDESOTRABIT, CDREGRATRABIT,
                    VRPERDIFEREIT, VRIMPOSTOOPERAIT, VRIMPOSTODIFERIT, CDCEST
             FROM TRABITPROIMPOS
             WHERE CDFILIMPOIT  = P_FILIAL   AND
                   NRLANCIMPOIT = P_LANCTONF);

         SELECT SUM(VRTOTAITEM - VRDESCITEM) INTO V_TOTAPROD
         FROM ITEMPRODUTO
         WHERE CDFILIAL   = P_FILIAL   AND
               NRLANCTONF = P_LANCTONF;

         IF V_TOTAPROD IS NULL THEN
            V_TOTAPROD := 0;
         END IF;

         IF V_TOTAPROD > 0 THEN
            UPDATE ITEMPRODUTO
            SET VRBRUTITEM   = ROUND((V_NOTAFISC/V_TOTAPROD) * (VRTOTAITEM - VRDESCITEM), 5)
            WHERE CDFILIAL   = P_FILIAL   AND
                  NRLANCTONF = P_LANCTONF;
         END IF;
      END IF;

      ----------------------------------------------------------------------------------------------------
      --RATEIO DOS ENCARGOS.

      IF (V_INTEGRACAO IS NULL) OR (P_ENTRSAID = W_E) THEN
         FOR C_ITEMENCARGO IN (SELECT IE.CDENCARGO AS CDENCARGO, (VRITEMENCA-NVL(I.VRICMSSTITORIG,0)) VRITEMENCA, IDENCARGO,
                                      EN.CDCTBLENTREN, EN.CDCTBLSAIDEN
                                 FROM ENCARGO EN, ITEMENCARGO IE, (SELECT SUM(VRICMSSTITORIG) VRICMSSTITORIG
                                                                     FROM ITEMPRODUTO
                                                                    WHERE CDFILIAL   = P_FILIAL
                                                                      AND NRLANCTONF = P_LANCTONF) I
                                WHERE (IE.CDFILIAL   = P_FILIAL)
                                  AND (IE.NRLANCTONF = P_LANCTONF)
                                  AND (IE.VRITEMENCA-NVL(I.VRICMSSTITORIG,0) > 0)
                                  AND (EN.CDENCARGO  = IE.CDENCARGO)) LOOP

            V_TOTAPRODENCA := 0;

            FOR C_VRLIQRATEIO IN (SELECT DISTINCT(IP.NRSEQITPROD) AS NRSEQITPROD, (VRTOTAITEM - VRDESCITEM) AS VRLIQUIDO
                                  FROM ITEMPRODUTO IP, ITEMPROIMPOS II
                                  WHERE (IP.CDFILIAL     = P_FILIAL)       AND
                                        (IP.NRLANCTONF   = P_LANCTONF)     AND
                                        (II.CDFILIAL     = IP.CDFILIAL)    AND
                                        (II.NRLANCTONF   = IP.NRLANCTONF)  AND
                                        (II.NRSEQITPROD  = IP.NRSEQITPROD) AND
                                        (II.NRITPROIMPOS = W_1)            AND
                                        (EXISTS(SELECT BC.CDIMPOSTO
                                                FROM BASECALC BC
                                                WHERE (BC.CDENCARGO = C_ITEMENCARGO.CDENCARGO) AND
                                                      (BC.CDIMPOSTO = II.CDIMPOSTO)            AND
                                                      (BC.CDIMPOSTO IN (SELECT (B.CDIMPOSTO)
                                                                       FROM BASECALC B
                                                                       WHERE B.CDENCARGO = C_ITEMENCARGO.CDENCARGO))))) LOOP

               IF NOT (C_VRLIQRATEIO.VRLIQUIDO IS NULL) THEN
                  V_TOTAPRODENCA := V_TOTAPRODENCA + C_VRLIQRATEIO.VRLIQUIDO;
               END IF;
            END LOOP;

            IF V_TOTAPRODENCA = 0 THEN

               IF (V_IDNFRETIND = 'S') OR (V_IDCOMPRABONI = 'S') THEN /* Retorno de industrialização ou Compra/Bonificação grava encargo no brutitem do item que vai para o vencimento */

                  SELECT SUM(IP.VRTOTAITEM - IP.VRDESCITEM) INTO V_TOTAPRODENCA
                    FROM ITEMPRODUTO IP, TPOPERCFOP T, NOTAFISCAL N
                   WHERE IP.CDFILIAL     = P_FILIAL
                     AND IP.NRLANCTONF   = P_LANCTONF
                     AND IP.CDFILIAL     = N.CDFILIAL
                     AND IP.NRLANCTONF   = N.NRLANCTONF
                     AND IP.CDFISOPEITEM = T.CDFISCOPER
                     AND N.CDTIPOOPER    = T.CDTIPOOPER
                     AND T.IDCOMPOEVENC  = w_S;

                  IF V_TOTAPRODENCA <> 0 THEN
                     FOR C_ATUAVRCONT IN (SELECT IP.NRSEQITPROD, (IP.VRTOTAITEM - IP.VRDESCITEM) AS VRLIQUIDO,
                                                 IP.CDFISOPEITEM, IP.CDPRODUTO
                                            FROM ITEMPRODUTO IP, TPOPERCFOP T, NOTAFISCAL N
                                           WHERE IP.CDFILIAL     = P_FILIAL
                                             AND IP.NRLANCTONF   = P_LANCTONF
                                             AND IP.CDFILIAL     = N.CDFILIAL
                                             AND IP.NRLANCTONF   = N.NRLANCTONF
                                             AND IP.CDFISOPEITEM = T.CDFISCOPER
                                             AND N.CDTIPOOPER    = T.CDTIPOOPER
                                             AND T.IDCOMPOEVENC  = w_S) LOOP

                        IF (C_ITEMENCARGO.IDENCARGO = W_A) THEN
                           V_VRBRUTO := (C_ITEMENCARGO.VRITEMENCA/V_TOTAPRODENCA);
                        ELSIF (C_ITEMENCARGO.IDENCARGO = W_D) THEN
                           V_VRBRUTO := - (C_ITEMENCARGO.VRITEMENCA/V_TOTAPRODENCA);
                        ELSE
                           V_VRBRUTO := 0;
                        END IF;

                        IF (C_ITEMENCARGO.CDCTBLENTREN IS NULL) THEN
                           V_VRCONTAB := V_VRBRUTO;
                        ELSE
                           V_VRCONTAB := 0;
                        END IF;

                        BEGIN
                           SELECT (VRTOTAITEM - VRDESCITEM)
                           INTO V_VALRDESCITEM
                           FROM ITEMPRODUTO
                           WHERE CDFILIAL    = P_FILIAL   AND
                                 NRLANCTONF  = P_LANCTONF AND
                                 NRSEQITPROD = C_ATUAVRCONT.NRSEQITPROD;
                        EXCEPTION
                            WHEN NO_DATA_FOUND THEN
                               V_VALRDESCITEM := 0;
                        END;

                        UPDATE ITEMPRODUTO
                        SET VRBRUTITEM = ROUND(VRBRUTITEM + (V_VRBRUTO  * (VRTOTAITEM - VRDESCITEM)), 5),
                            VRCONTITEM = ROUND(VRCONTITEM + (V_VRCONTAB * (VRTOTAITEM - VRDESCITEM)), 5)
                        WHERE CDFILIAL    = P_FILIAL   AND
                              NRLANCTONF  = P_LANCTONF AND
                              NRSEQITPROD = C_ATUAVRCONT.NRSEQITPROD;

                        UPDATE TRABITPROIMPOS
                        SET VRCONTIMPOIT = ROUND(VRCONTIMPOIT + ((V_VRBRUTO * V_VALRDESCITEM) * ((100 - VRREDBCIMPOIT)/100)),5)
                        WHERE CDFILIMPOIT  = P_FILIAL   AND
                              NRLANCIMPOIT = P_LANCTONF AND
                              NRSEQIMPOIT  = C_ATUAVRCONT.NRSEQITPROD;

                     END LOOP;
                  END IF;
               ELSE
                  SELECT SUM(VRTOTAITEM - VRDESCITEM) INTO V_TOTAPRODENCA
                  FROM ITEMPRODUTO IP
                  WHERE (IP.CDFILIAL   = P_FILIAL)   AND
                        (IP.NRLANCTONF = P_LANCTONF);

                  IF V_TOTAPRODENCA <> 0 THEN

                     V_ENCIMPXML   := NULL;
                     IF (V_IDNFGERADAVIAXML = 'S') THEN
                        IF (V_NRACESSONFE IS NOT NULL) THEN
                           BEGIN
                              SELECT MAX(CDENCARGOIMPXML)
                                INTO V_ENCIMPXML
                                FROM INTG_TRABITPROIMPOS IT, IMPOSTO I
                               WHERE NRACESSONFE = V_NRACESSONFE
                                 AND IT.CDIMPOSTOIT    = I.CDIMPOSTO
                                 AND I.CDENCARGOIMPXML IS NOT NULL
                                 AND I.IDIMPORTAIMPXML = 'S'
                                 AND IT.VRIMPOSTOIT > 0
                                 AND I.CDENCARGOIMPXML = C_ITEMENCARGO.CDENCARGO;
                           EXCEPTION
                              WHEN NO_DATA_FOUND THEN
                                 V_ENCIMPXML := NULL;
                           END;
                        END IF;
                     END IF;

                     IF V_ENCIMPXML IS NULL THEN
                        FOR C_ATUAVRCONT IN (SELECT IP.NRSEQITPROD, (VRTOTAITEM - VRDESCITEM) AS VRLIQUIDO
                                               FROM ITEMPRODUTO IP
                                              WHERE (IP.CDFILIAL    = P_FILIAL)
                                                AND (IP.NRLANCTONF  = P_LANCTONF)) LOOP


                           IF (C_ITEMENCARGO.IDENCARGO = W_A) THEN
                              V_VRBRUTO := (C_ITEMENCARGO.VRITEMENCA/V_TOTAPRODENCA);
                           ELSIF (C_ITEMENCARGO.IDENCARGO = W_D) THEN
                              V_VRBRUTO := - (C_ITEMENCARGO.VRITEMENCA/V_TOTAPRODENCA);
                           ELSE
                              V_VRBRUTO := 0;
                           END IF;

                           IF (C_ITEMENCARGO.CDCTBLENTREN IS NULL) THEN
                              V_VRCONTAB := V_VRBRUTO;
                           ELSE
                              V_VRCONTAB := 0;
                           END IF;

                           BEGIN
                              SELECT (VRTOTAITEM - VRDESCITEM)
                              INTO V_VALRDESCITEM
                              FROM ITEMPRODUTO
                              WHERE CDFILIAL    = P_FILIAL   AND
                                    NRLANCTONF  = P_LANCTONF AND
                                    NRSEQITPROD = C_ATUAVRCONT.NRSEQITPROD;
                           EXCEPTION
                               WHEN NO_DATA_FOUND THEN
                                  V_VALRDESCITEM := 0;
                           END;

                           UPDATE ITEMPRODUTO
                           SET VRBRUTITEM = ROUND(VRBRUTITEM + (V_VRBRUTO  * (VRTOTAITEM - VRDESCITEM)), 5),
                               VRCONTITEM = ROUND(VRCONTITEM + (V_VRCONTAB * (VRTOTAITEM - VRDESCITEM)), 5)
                           WHERE CDFILIAL    = P_FILIAL   AND
                                 NRLANCTONF  = P_LANCTONF AND
                                 NRSEQITPROD = C_ATUAVRCONT.NRSEQITPROD;

                           UPDATE TRABITPROIMPOS
                           SET VRCONTIMPOIT = ROUND(VRCONTIMPOIT + ((V_VRBRUTO * V_VALRDESCITEM) * ((100 - VRREDBCIMPOIT)/100)),5)
                           WHERE CDFILIMPOIT  = P_FILIAL   AND
                                 NRLANCIMPOIT = P_LANCTONF AND
                                 NRSEQIMPOIT  = C_ATUAVRCONT.NRSEQITPROD;

                        END LOOP;
                     ELSE     /*Rateio encargo/imposto xml*/
                        FOR C_ATUAVRCONT IN (SELECT VRIMPOSTOIT + NVL(VRADICFECP, 0) AS VRIMPOSTOIT, LPAD(NRSEQIMPOIT, 4, '0') AS NRSEQITPROD
                                               FROM INTG_TRABITPROIMPOS IT, IMPOSTO I
                                              WHERE NRACESSONFE = V_NRACESSONFE
                                                AND IT.CDIMPOSTOIT    = I.CDIMPOSTO
                                                AND I.CDENCARGOIMPXML IS NOT NULL
                                                AND I.IDIMPORTAIMPXML = 'S'
                                                AND IT.VRIMPOSTOIT > 0
                                                AND I.CDENCARGOIMPXML = C_ITEMENCARGO.CDENCARGO) LOOP

                           IF (C_ITEMENCARGO.IDENCARGO = W_A) THEN
                              V_VRBRUTO := C_ATUAVRCONT.VRIMPOSTOIT;
                           ELSIF (C_ITEMENCARGO.IDENCARGO = W_D) THEN
                              V_VRBRUTO := - (C_ATUAVRCONT.VRIMPOSTOIT);
                           ELSE
                              V_VRBRUTO := 0;
                           END IF;

                           IF (C_ITEMENCARGO.CDCTBLENTREN IS NULL) THEN
                              V_VRCONTAB := V_VRBRUTO;
                           ELSE
                              V_VRCONTAB := 0;
                           END IF;

                           BEGIN
                              SELECT (VRTOTAITEM - VRDESCITEM)
                              INTO V_VALRDESCITEM
                              FROM ITEMPRODUTO
                              WHERE CDFILIAL    = P_FILIAL   AND
                                    NRLANCTONF  = P_LANCTONF AND
                                    NRSEQITPROD = C_ATUAVRCONT.NRSEQITPROD;
                           EXCEPTION
                               WHEN NO_DATA_FOUND THEN
                                  V_VALRDESCITEM := 0;
                           END;

                           UPDATE ITEMPRODUTO
                              SET VRBRUTITEM = ROUND((VRBRUTITEM + V_VRBRUTO), 5),
                                  VRCONTITEM = ROUND((VRCONTITEM + V_VRCONTAB), 5)
                            WHERE CDFILIAL    = P_FILIAL   AND
                                  NRLANCTONF  = P_LANCTONF AND
                                  NRSEQITPROD = C_ATUAVRCONT.NRSEQITPROD;

                           UPDATE TRABITPROIMPOS
                           SET VRCONTIMPOIT = ROUND((VRCONTIMPOIT + V_VRBRUTO),5)
                           WHERE CDFILIMPOIT  = P_FILIAL   AND
                                 NRLANCIMPOIT = P_LANCTONF AND
                                 NRSEQIMPOIT  = C_ATUAVRCONT.NRSEQITPROD;
                        END LOOP;
                     END IF;  /*Rateio encargo/imposto xml*/
                  END IF;
               END IF;   -- Coloquei isso
            ELSE
               IF (V_IDNFRETIND = 'S') OR (V_IDCOMPRABONI = 'S') THEN /* Retorno de industrialização ou Compra/Bonificação grava encargo no brutitem do item que vai para o vencimento */

                  SELECT SUM(IP.VRTOTAITEM - IP.VRDESCITEM) INTO V_TOTAPRODENCA
                    FROM ITEMPRODUTO IP, TPOPERCFOP T, NOTAFISCAL N
                   WHERE IP.CDFILIAL     = P_FILIAL
                     AND IP.NRLANCTONF   = P_LANCTONF
                     AND IP.CDFILIAL     = N.CDFILIAL
                     AND IP.NRLANCTONF   = N.NRLANCTONF
                     AND IP.CDFISOPEITEM = T.CDFISCOPER
                     AND N.CDTIPOOPER    = T.CDTIPOOPER
                     AND T.IDCOMPOEVENC  = w_S;

                  IF V_TOTAPRODENCA <> 0 THEN
                     FOR C_ATUAVRCONT IN (SELECT IP.NRSEQITPROD, (IP.VRTOTAITEM - IP.VRDESCITEM) AS VRLIQUIDO,
                                                 IP.CDFISOPEITEM, IP.CDPRODUTO
                                            FROM ITEMPRODUTO IP, TPOPERCFOP T, NOTAFISCAL N
                                           WHERE IP.CDFILIAL     = P_FILIAL
                                             AND IP.NRLANCTONF   = P_LANCTONF
                                             AND IP.CDFILIAL     = N.CDFILIAL
                                             AND IP.NRLANCTONF   = N.NRLANCTONF
                                             AND IP.CDFISOPEITEM = T.CDFISCOPER
                                             AND N.CDTIPOOPER    = T.CDTIPOOPER
                                             AND T.IDCOMPOEVENC  = w_S) LOOP

                        IF (C_ITEMENCARGO.IDENCARGO = W_A) THEN
                           V_VRBRUTO := (C_ITEMENCARGO.VRITEMENCA/V_TOTAPRODENCA);
                        ELSIF (C_ITEMENCARGO.IDENCARGO = W_D) THEN
                           V_VRBRUTO := - (C_ITEMENCARGO.VRITEMENCA/V_TOTAPRODENCA);
                        ELSE
                           V_VRBRUTO := 0;
                        END IF;

                        IF (C_ITEMENCARGO.CDCTBLENTREN IS NULL) THEN
                           V_VRCONTAB := V_VRBRUTO;
                        ELSE
                           V_VRCONTAB := 0;
                        END IF;

                        BEGIN
                           SELECT (VRTOTAITEM - VRDESCITEM)
                           INTO V_VALRDESCITEM
                           FROM ITEMPRODUTO
                           WHERE CDFILIAL    = P_FILIAL   AND
                                 NRLANCTONF  = P_LANCTONF AND
                                 NRSEQITPROD = C_ATUAVRCONT.NRSEQITPROD;
                        EXCEPTION
                            WHEN NO_DATA_FOUND THEN
                               V_VALRDESCITEM := 0;
                        END;

                        UPDATE ITEMPRODUTO
                        SET VRBRUTITEM = ROUND(VRBRUTITEM + (V_VRBRUTO  * (VRTOTAITEM - VRDESCITEM)), 5),
                            VRCONTITEM = ROUND(VRCONTITEM + (V_VRCONTAB * (VRTOTAITEM - VRDESCITEM)), 5)
                        WHERE CDFILIAL    = P_FILIAL   AND
                              NRLANCTONF  = P_LANCTONF AND
                              NRSEQITPROD = C_ATUAVRCONT.NRSEQITPROD;

                        UPDATE TRABITPROIMPOS
                        SET VRCONTIMPOIT = ROUND(VRCONTIMPOIT + ((V_VRBRUTO * V_VALRDESCITEM) * ((100 - VRREDBCIMPOIT)/100)),5)
                        WHERE CDFILIMPOIT  = P_FILIAL   AND
                              NRLANCIMPOIT = P_LANCTONF AND
                              NRSEQIMPOIT  = C_ATUAVRCONT.NRSEQITPROD;

                     END LOOP;
                  END IF;
               ELSE
                  V_ENCIMPXML   := NULL;
                  IF (V_IDNFGERADAVIAXML = 'S') THEN
                     IF (V_NRACESSONFE IS NOT NULL) THEN
                        BEGIN
                           SELECT MAX(CDENCARGOIMPXML)
                             INTO V_ENCIMPXML
                             FROM INTG_TRABITPROIMPOS IT, IMPOSTO I
                            WHERE NRACESSONFE = V_NRACESSONFE
                              AND IT.CDIMPOSTOIT    = I.CDIMPOSTO
                              AND I.CDENCARGOIMPXML IS NOT NULL
                              AND I.IDIMPORTAIMPXML = 'S'
                              AND IT.VRIMPOSTOIT > 0
                              AND I.CDENCARGOIMPXML = C_ITEMENCARGO.CDENCARGO;
                        EXCEPTION
                           WHEN NO_DATA_FOUND THEN
                              V_ENCIMPXML := NULL;
                        END;
                     END IF;
                  END IF;

                  IF V_ENCIMPXML IS NULL THEN

                     FOR C_ATUAVRCONT IN (SELECT DISTINCT(IP.NRSEQITPROD) AS NRSEQITPROD, (VRTOTAITEM - VRDESCITEM) AS VRLIQUIDO,
                                                 NRITPROIMPOS
                                           FROM ITEMPRODUTO IP, ITEMPROIMPOS II
                                           WHERE (IP.CDFILIAL     = P_FILIAL)       AND
                                                 (IP.NRLANCTONF   = P_LANCTONF)     AND
                                                 (II.CDFILIAL     = IP.CDFILIAL)    AND
                                                 (II.NRLANCTONF   = IP.NRLANCTONF)  AND
                                                 (II.NRSEQITPROD  = IP.NRSEQITPROD) AND
                                                 (II.NRITPROIMPOS = W_1)            AND
                                                 (EXISTS(SELECT BC.CDIMPOSTO
                                                         FROM BASECALC BC
                                                         WHERE (BC.CDENCARGO = C_ITEMENCARGO.CDENCARGO) AND
                                                               (BC.CDIMPOSTO = II.CDIMPOSTO)            AND
                                                               (BC.CDIMPOSTO IN (SELECT B.CDIMPOSTO
                                                                                FROM BASECALC B
                                                                                WHERE B.CDENCARGO = C_ITEMENCARGO.CDENCARGO))))) LOOP



                        IF (C_ITEMENCARGO.IDENCARGO = W_A) THEN
                           V_VRBRUTO := (C_ITEMENCARGO.VRITEMENCA/V_TOTAPRODENCA);
                        ELSIF (C_ITEMENCARGO.IDENCARGO = W_D) THEN
                           V_VRBRUTO := - (C_ITEMENCARGO.VRITEMENCA/V_TOTAPRODENCA);
                        ELSE
                           V_VRBRUTO := 0;
                        END IF;

                        IF (C_ITEMENCARGO.CDCTBLENTREN IS NULL) THEN
                           V_VRCONTAB := V_VRBRUTO;
                        ELSE
                           V_VRCONTAB := 0;
                        END IF;

                        UPDATE ITEMPRODUTO
                        SET VRBRUTITEM = ROUND(VRBRUTITEM + (V_VRBRUTO  * (VRTOTAITEM - VRDESCITEM)), 5),
                            VRCONTITEM = ROUND(VRCONTITEM + (V_VRCONTAB * (VRTOTAITEM - VRDESCITEM)), 5)
                        WHERE CDFILIAL    = P_FILIAL   AND
                              NRLANCTONF  = P_LANCTONF AND
                              NRSEQITPROD = C_ATUAVRCONT.NRSEQITPROD;
                     END LOOP;
                  ELSE     /*Rateio encargo/imposto xml*/
                     FOR C_ATUAVRCONT IN (SELECT VRIMPOSTOIT + NVL(VRADICFECP, 0) AS VRIMPOSTOIT, LPAD(NRSEQIMPOIT, 4, '0') AS NRSEQITPROD
                                            FROM INTG_TRABITPROIMPOS IT, IMPOSTO I
                                           WHERE NRACESSONFE = V_NRACESSONFE
                                             AND IT.CDIMPOSTOIT    = I.CDIMPOSTO
                                             AND I.CDENCARGOIMPXML IS NOT NULL
                                             AND I.IDIMPORTAIMPXML = 'S'
                                             AND IT.VRIMPOSTOIT > 0
                                             AND I.CDENCARGOIMPXML = C_ITEMENCARGO.CDENCARGO) LOOP

                        IF (C_ITEMENCARGO.IDENCARGO = W_A) THEN
                           V_VRBRUTO := C_ATUAVRCONT.VRIMPOSTOIT;
                        ELSIF (C_ITEMENCARGO.IDENCARGO = W_D) THEN
                           V_VRBRUTO := - (C_ATUAVRCONT.VRIMPOSTOIT);
                        ELSE
                           V_VRBRUTO := 0;
                        END IF;

                        IF (C_ITEMENCARGO.CDCTBLENTREN IS NULL) THEN
                           V_VRCONTAB := V_VRBRUTO;
                        ELSE
                           V_VRCONTAB := 0;
                        END IF;

                        BEGIN
                           SELECT (VRTOTAITEM - VRDESCITEM)
                           INTO V_VALRDESCITEM
                           FROM ITEMPRODUTO
                           WHERE CDFILIAL    = P_FILIAL   AND
                                 NRLANCTONF  = P_LANCTONF AND
                                 NRSEQITPROD = C_ATUAVRCONT.NRSEQITPROD;
                        EXCEPTION
                            WHEN NO_DATA_FOUND THEN
                               V_VALRDESCITEM := 0;
                        END;

                        UPDATE ITEMPRODUTO
                           SET VRBRUTITEM = ROUND((VRBRUTITEM + V_VRBRUTO), 5),
                               VRCONTITEM = ROUND((VRCONTITEM + V_VRCONTAB), 5)    --PAREI AQUI
                         WHERE CDFILIAL    = P_FILIAL   AND
                               NRLANCTONF  = P_LANCTONF AND
                               NRSEQITPROD = C_ATUAVRCONT.NRSEQITPROD;

                        UPDATE TRABITPROIMPOS
                        SET VRCONTIMPOIT = ROUND((VRCONTIMPOIT + V_VRBRUTO),5)
                        WHERE CDFILIMPOIT  = P_FILIAL   AND
                              NRLANCIMPOIT = P_LANCTONF AND
                              NRSEQIMPOIT  = C_ATUAVRCONT.NRSEQITPROD;
                     END LOOP;
                  END IF;  /*Rateio encargo/imposto xml*/
               END IF;
               FOR C_ITEMPROIMPOS IN (
                                      SELECT /*+ index (II,PK_ITEMPROIMPOS)*/
                                             II.NRSEQITPROD, II.NRITPROIMPOS, II.CDIMPOSTO, II.VRPERREDBCIT, II.VRALIQITEM,
                                             II.VRPARDEDIT, TI.VRALIQIMPOIT, (VRTOTAITEM - VRDESCITEM) AS VRLIQUIDO,
                                             TI.IDVALORINFO, TI.VRIMPOSIT, II.IDTRIMPSTII, TI.IDCONSDIFALIQ
                                      FROM ITEMPROIMPOS II, ITEMPRODUTO IP, BASECALC BC, TRABITPROIMPOS TI
                                      WHERE
                                            (IP.CDFILIAL     = P_FILIAL)                AND
                                            (IP.NRLANCTONF   = P_LANCTONF)              AND
                                            (II.CDFILIAL     = IP.CDFILIAL)             AND
                                            (II.NRLANCTONF   = IP.NRLANCTONF)           AND
                                            (II.NRSEQITPROD  = IP.NRSEQITPROD)          AND
                                            (TI.CDFILIMPOIT  = II.CDFILIAL)             AND
                                            (TI.NRLANCIMPOIT = II.NRLANCTONF)           AND
                                            (TI.NRSEQIMPOIT  = II.NRSEQITPROD)          AND
                                            (TI.CDIMPOSTOIT  = II.CDIMPOSTO)            AND
                                            (TI.NRSEQITPRO   = II.NRITPROIMPOS)         AND
                                            (BC.CDIMPOSTO    = II.CDIMPOSTO)            AND
                                            (BC.CDENCARGO    = C_ITEMENCARGO.CDENCARGO)
                                      ORDER BY 1, 2, 3) LOOP

                  SELECT SUM(VRTOTAITEM - VRDESCITEM)
                    INTO V_TOTAPRENIMPO
                    FROM ITEMPRODUTO IP, ITEMPROIMPOS II
                   WHERE (IP.CDFILIAL     = P_FILIAL)       AND
                         (IP.NRLANCTONF   = P_LANCTONF)     AND
                         (II.CDFILIAL     = IP.CDFILIAL)    AND
                         (II.NRLANCTONF   = IP.NRLANCTONF)  AND
                         (II.NRSEQITPROD  = IP.NRSEQITPROD) AND
                         (II.NRITPROIMPOS = W_1)            AND
                         (II.CDIMPOSTO    = C_ITEMPROIMPOS.CDIMPOSTO);

                  IF (C_ITEMENCARGO.IDENCARGO = W_A) THEN
                     V_PRODUENCARGO := +ROUND((C_ITEMENCARGO.VRITEMENCA/V_TOTAPRENIMPO)*C_ITEMPROIMPOS.VRLIQUIDO,2);
                  ELSIF (C_ITEMENCARGO.IDENCARGO = W_D) THEN
                     V_PRODUENCARGO := -ROUND((C_ITEMENCARGO.VRITEMENCA/V_TOTAPRENIMPO)*C_ITEMPROIMPOS.VRLIQUIDO,2);
                  ELSE
                     V_PRODUENCARGO := 0;
                  END IF;

                  BEGIN
                     SELECT NVL(IDVALORINFO, 'N')
                       INTO V_IDIMPORTAIMPXML
                       FROM TRABITPROIMPOS
                      WHERE CDFILIMPOIT  = P_FILIAL
                        AND NRLANCIMPOIT = P_LANCTONF
                        AND CDIMPOSTOIT  = C_ITEMPROIMPOS.CDIMPOSTO
                        AND NRSEQIMPOIT  = C_ITEMPROIMPOS.NRSEQITPROD
                        AND NRSEQITPRO   = '1';
                  EXCEPTION
                     WHEN NO_DATA_FOUND THEN
                        V_IDIMPORTAIMPXML := 'N';
                  END;

                  IF (V_IDNFGERADAVIAXML = 'S') AND ((V_IDIMPORTAIMPXML = 'S') OR (V_IDGERNFIGUALXML = 'S')) THEN
                     V_PRODUENCARGO := 0;
                  END IF;

                  V_TAXAALIQUOTA := (C_ITEMPROIMPOS.VRALIQITEM/100);
                  V_TAXAALIQINFO := (C_ITEMPROIMPOS.VRALIQIMPOIT/100);

                  V_CDIMPOSTRIB := NULL;
                  V_VRIMPOSTOST := 0;

                  FOR C_ICMSST IN (SELECT CDIMPOSTO
                                     FROM IMPOSTO
                                    WHERE CDIMPOSTRIB = C_ITEMPROIMPOS.CDIMPOSTO)
                  LOOP
                     V_CDIMPOSTRIB := V_CDIMPOSTRIB||C_ICMSST.CDIMPOSTO||'_';
                  END LOOP;

                  IF V_CDIMPOSTRIB IS NULL THEN
                     V_TAXABASECALC := (100 - C_ITEMPROIMPOS.VRPERREDBCIT)/100;
                  ELSE
                     V_TAXABASECALC := 1 + (C_ITEMPROIMPOS.VRPERREDBCIT)/100;
                  END IF;

                  V_VRIMPOSTOST := 0;

                  IF V_CDIMPOSTRIB IS NOT NULL THEN
                     SELECT NVL(MAX(IDVRIMPSTRIB), 'N')
                       INTO V_IDVRIMPSTRIB
                       FROM TRABITPROIMPOS I, IMPOSTO II
                      WHERE (CDFILIMPOIT     = P_FILIAL)
                        AND (NRLANCIMPOIT    = P_LANCTONF)
                        AND (NRSEQIMPOIT     = C_ITEMPROIMPOS.NRSEQITPROD)
                        AND (INSTR(V_CDIMPOSTRIB,II.CDIMPOSTO||'_') > 0)
                        AND (I.CDIMPOSTOIT = II.CDIMPOSTO);

                     IF (C_ITEMPROIMPOS.IDTRIMPSTII = W_1) OR (NVL(V_IDVRIMPSTRIB,W_N) = W_N) OR (NVL(V_IDCONSDIFALIQ , W_N) = 'S') THEN
                        V_VRIMPOSTOST := 0;
                     ELSE
                        BEGIN
                           SELECT NVL(VRIMPOSIT,0)
                           INTO V_VRIMPOSTOST
                           FROM TRABITPROIMPOS I
                           WHERE (CDFILIMPOIT  = P_FILIAL)                   AND
                                 (NRLANCIMPOIT = P_LANCTONF)                 AND
                                 (NRSEQIMPOIT  = C_ITEMPROIMPOS.NRSEQITPROD) AND
                                 (INSTR(V_CDIMPOSTRIB,CDIMPOSTOIT||'_') > 0) AND
                                 (NRSEQITPRO   = W_1);
                        EXCEPTION
                           WHEN NO_DATA_FOUND THEN
                              V_VRIMPOSTOST := 0;
                        END;
                     END IF;
                  END IF;

                  IF C_ITEMPROIMPOS.IDVALORINFO = W_S THEN
                     V_IMPOSTOIT := 0;
                  ELSE
                     V_IMPOSTOIT := ((V_PRODUENCARGO * V_TAXABASECALC) * V_TAXAALIQUOTA);
                     V_IMPOSTOIT := V_IMPOSTOIT - ((V_VRIMPOSTOST * V_TAXABASECALC) * V_TAXAALIQUOTA);
                  END IF;

                  UPDATE ITEMPROIMPOS
                     SET VRBASECALCIT = ROUND(VRBASECALCIT + (V_PRODUENCARGO * V_TAXABASECALC), 2),
                         VRCONTITIMP  = ROUND(VRCONTITIMP  + (V_PRODUENCARGO * V_TAXABASECALC),5),
                         VRIMPOSTOIT  = VRIMPOSTOIT  + V_IMPOSTOIT
                   WHERE (NRLANCTONF   = P_LANCTONF) AND
                         (CDFILIAL     = P_FILIAL)   AND
                         (NRSEQITPROD  = C_ITEMPROIMPOS.NRSEQITPROD) AND
                         (CDIMPOSTO    = C_ITEMPROIMPOS.CDIMPOSTO)   AND
                         (NRITPROIMPOS = C_ITEMPROIMPOS.NRITPROIMPOS);

                  IF C_ITEMPROIMPOS.IDVALORINFO = W_S THEN
                     V_IMPOSTOIT := 0;
                  ELSE
                     V_IMPOSTOIT := ((V_PRODUENCARGO * V_TAXABASECALC) * V_TAXAALIQINFO);
                     V_IMPOSTOIT := V_IMPOSTOIT - ((V_VRIMPOSTOST * V_TAXABASECALC) * V_TAXAALIQINFO);
                  END IF;

                  UPDATE TRABITPROIMPOS
                  SET VRBCALCIMPOIT  = ROUND(VRBCALCIMPOIT + (V_PRODUENCARGO * V_TAXABASECALC), 2),
                      VRCONTIMPOIT   = ROUND(VRCONTIMPOIT  + (V_PRODUENCARGO * V_TAXABASECALC),5),
                      VRIMPOSIT      = VRIMPOSIT     + V_IMPOSTOIT
                  WHERE CDFILIMPOIT  = P_FILIAL                   AND
                        NRLANCIMPOIT = P_LANCTONF                 AND
                        NRSEQIMPOIT  = C_ITEMPROIMPOS.NRSEQITPROD AND
                        CDIMPOSTOIT  = C_ITEMPROIMPOS.CDIMPOSTO   AND
                        NRSEQITPRO   = C_ITEMPROIMPOS.NRITPROIMPOS;

                  /* ROTINA PARA RECALCULAR O DIFERIMENTO DO IMPOSTO */
                  IF NOT ((V_IDNFGERADAVIAXML = 'S') AND ((V_IDIMPORTAIMPXML = 'S') OR (V_IDGERNFIGUALXML = 'S'))) THEN
                     BEGIN
                        SELECT MAX(VRIMPOSTOOPERAIT), MAX(VRPERDIFEREIT)
                          INTO V_VRIMPOSTOOPERAIT, V_VRPERDIFEREIT
                          FROM ITEMPROIMPOS
                         WHERE (CDFILIAL     = P_FILIAL)                    AND
                               (NRLANCTONF   = P_LANCTONF)                  AND
                               (NRSEQITPROD  = C_ITEMPROIMPOS.NRSEQITPROD)  AND
                               (CDIMPOSTO    = C_ITEMPROIMPOS.CDIMPOSTO)    AND
                               (NRITPROIMPOS = C_ITEMPROIMPOS.NRITPROIMPOS) AND
                               (IDVALORINFIT = 'N') AND
                               (VRPERDIFEREIT <> 0);
                     EXCEPTION
                        When No_Data_Found Then
                           V_VRIMPOSTOOPERAIT := 0; V_VRPERDIFEREIT := 0;
                     END;

                     IF V_VRPERDIFEREIT <> 0 THEN
                        V_VRIMPOSTOOPERAIT := ROUND((V_VRIMPOSTOOPERAIT + ((V_PRODUENCARGO * V_TAXABASECALC) * V_TAXAALIQUOTA)) - ((V_VRIMPOSTOST * V_TAXABASECALC) * V_TAXAALIQUOTA),2);
                        V_VRIMPOSTODIFERIT := ROUND((V_VRIMPOSTOOPERAIT * V_VRPERDIFEREIT/100), 2);

                        IF NOT ((V_IDNFGERADAVIAXML = 'S') AND ((V_IDIMPORTAIMPXML = 'S') OR (V_IDGERNFIGUALXML = 'S'))) THEN
                           UPDATE ITEMPROIMPOS
                              SET VRIMPOSTOOPERAIT = V_VRIMPOSTOOPERAIT,
                                  VRIMPOSTODIFERIT = V_VRIMPOSTODIFERIT
                            WHERE (CDFILIAL     = P_FILIAL)                    AND
                                  (NRLANCTONF   = P_LANCTONF)                  AND
                                  (NRSEQITPROD  = C_ITEMPROIMPOS.NRSEQITPROD)  AND
                                  (CDIMPOSTO    = C_ITEMPROIMPOS.CDIMPOSTO)    AND
                                  (NRITPROIMPOS = C_ITEMPROIMPOS.NRITPROIMPOS) AND
                                  (VRPERDIFEREIT <> 0);

                           UPDATE TRABITPROIMPOS
                              SET VRIMPOSTOOPERAIT = V_VRIMPOSTOOPERAIT,
                                  VRIMPOSTODIFERIT = V_VRIMPOSTODIFERIT
                            WHERE CDFILIMPOIT  = P_FILIAL                    AND
                                  NRLANCIMPOIT = P_LANCTONF                  AND
                                  NRSEQIMPOIT  = C_ITEMPROIMPOS.NRSEQITPROD  AND
                                  CDIMPOSTOIT  = C_ITEMPROIMPOS.CDIMPOSTO    AND
                                  NRSEQITPRO   = C_ITEMPROIMPOS.NRITPROIMPOS AND
                                  VRPERDIFEREIT <> 0;
                        END IF;
                     END IF;
                  ELSE
                     BEGIN
                        SELECT MAX(VRIMPOSTOOPERAIT), MAX(VRPERDIFEREIT)
                          INTO V_VRIMPOSTOOPERAIT, V_VRPERDIFEREIT
                          FROM ITEMPROIMPOS
                         WHERE (CDFILIAL     = P_FILIAL)                    AND
                               (NRLANCTONF   = P_LANCTONF)                  AND
                               (NRSEQITPROD  = C_ITEMPROIMPOS.NRSEQITPROD)  AND
                               (CDIMPOSTO    = C_ITEMPROIMPOS.CDIMPOSTO)    AND
                               (NRITPROIMPOS = C_ITEMPROIMPOS.NRITPROIMPOS) AND
                               (IDVALORINFIT = 'N') AND
                               (VRPERDIFEREIT <> 0);
                     EXCEPTION
                        When No_Data_Found Then
                           V_VRIMPOSTOOPERAIT := 0; V_VRPERDIFEREIT := 0;
                     END;

                     IF V_VRPERDIFEREIT <> 0 THEN
                        V_VRIMPOSTOOPERAIT := ROUND((V_VRIMPOSTOOPERAIT + ((V_PRODUENCARGO * V_TAXABASECALC) * V_TAXAALIQUOTA)) - ((V_VRIMPOSTOST * V_TAXABASECALC) * V_TAXAALIQUOTA),2);
                        V_VRIMPOSTODIFERIT := ROUND((V_VRIMPOSTOOPERAIT * V_VRPERDIFEREIT/100), 2);

                        UPDATE ITEMPROIMPOS
                           SET VRIMPOSTOOPERAIT = V_VRIMPOSTOOPERAIT,
                               VRIMPOSTODIFERIT = V_VRIMPOSTODIFERIT,
                               VRIMPOSTOIT = (V_VRIMPOSTOOPERAIT - V_VRIMPOSTODIFERIT),
                               VRIMPOSTOVISUIT = (V_VRIMPOSTOOPERAIT - V_VRIMPOSTODIFERIT)
                         WHERE (CDFILIAL     = P_FILIAL)                    AND
                               (NRLANCTONF   = P_LANCTONF)                  AND
                               (NRSEQITPROD  = C_ITEMPROIMPOS.NRSEQITPROD)  AND
                               (CDIMPOSTO    = C_ITEMPROIMPOS.CDIMPOSTO)    AND
                               (NRITPROIMPOS = C_ITEMPROIMPOS.NRITPROIMPOS) AND
                               (VRPERDIFEREIT <> 0);

                         UPDATE TRABITPROIMPOS
                            SET VRIMPOSTOOPERAIT = V_VRIMPOSTOOPERAIT,
                                VRIMPOSTODIFERIT = V_VRIMPOSTODIFERIT,
                                VRIMPOSIT = (V_VRIMPOSTOOPERAIT - V_VRIMPOSTODIFERIT)
                          WHERE CDFILIMPOIT  = P_FILIAL                    AND
                                NRLANCIMPOIT = P_LANCTONF                  AND
                                NRSEQIMPOIT  = C_ITEMPROIMPOS.NRSEQITPROD  AND
                                CDIMPOSTOIT  = C_ITEMPROIMPOS.CDIMPOSTO    AND
                                NRSEQITPRO   = C_ITEMPROIMPOS.NRITPROIMPOS AND
                                VRPERDIFEREIT <> 0;

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

         UPDATE ITEMPROIMPOS
         SET VRIMPOSTOIT = 0
         WHERE (CDFILIAL    = P_FILIAL)   AND
               (NRLANCTONF  = P_LANCTONF) AND
               (VRIMPOSTOIT < 0);

         UPDATE TRABITPROIMPOS
         SET VRIMPOSIT      = 0
         WHERE CDFILIMPOIT  = P_FILIAL   AND
               NRLANCIMPOIT = P_LANCTONF AND
               VRIMPOSIT    < 0;

         UPDATE ITEMPROIMPOS
         SET VRBASECALCIT = 0
         WHERE (CDFILIAL    = P_FILIAL)   AND
               (NRLANCTONF  = P_LANCTONF) AND
               (VRBASECALCIT < 0);

         UPDATE TRABITPROIMPOS
         SET VRBCALCIMPOIT = 0
         WHERE CDFILIMPOIT  = P_FILIAL   AND
               NRLANCIMPOIT = P_LANCTONF AND
               (VRBCALCIMPOIT < 0);

         ---------------------------------------------------------------------------------------------------------
         -- CÁLCULO DO VALOR DOS IMPOSTOS QUE CONTÉM OUTROS IMPOSTOS NA SUA BASE DE CÁLCULO

         IF (V_IDNFIMPORTACAO = 'N') THEN
            FOR C_PRODUTO IN (
                              SELECT /*+ index (II,PK_ITEMPROIMPOS)*/
                                     IP.NRSEQITPROD AS NRSEQITPROD, TI.CDIMPOSTOIT AS CDIMPOSTO,
                                     NVL(II.VRPERREDBCIT, 0) VRPERREDBCIT, NVL(II.VRALIQITEM, 0) VRALIQITEM,
                                     NVL(II.VRPARDEDIT, 0) VRPARDEDIT, II.CDFISCALIT, NVL(TI.VRIMPOSIT, 0) VRIMPOSIT,
                                     IM.IDTRATIMPO, IM.IDIMPORECUP, IM.CDCCTBLPASS, IM.CDCCTBLATIV, TI.VRALIQIMPOIT,
                                     II.NRITPROIMPOS, TI.NRSEQITPRO, NVL(TI.IDVALORINFO,W_N) AS IDVALORINFO,
                                     II.IDTRIMPSTII, IM.IDTIPCONTAB, NVL(II.VRBASECALCIT, 0) VRBASECALCIT, NVL(TI.VRADICFECP, 0) VRADICFECP,
                                     P.CDARVPROD, P.CDPRODUTO, IP.VRTOTAITEM, IP.VRDESCITEM, NVL(IM.IDCONTAIMPADIC, 'N')IDCONTAIMPADIC,
                                     IP.IDORIGEMPROD, IM.IDDESCRFONTE, TI.IDCONSDIFALIQ
                              FROM ITEMPRODUTO IP, ITEMPROIMPOS II, TRABITPROIMPOS TI, IMPOSTO IM, PRODUTO P
                              WHERE (IP.CDFILIAL     = P_FILIAL)           AND
                                    (IP.NRLANCTONF   = P_LANCTONF)         AND
                                    (TI.CDFILIMPOIT  = IP.CDFILIAL)        AND
                                    (TI.NRLANCIMPOIT = IP.NRLANCTONF)      AND
                                    (TI.NRSEQIMPOIT  = IP.NRSEQITPROD)     AND
                                    (TI.CDIMPOSTOIT  = IM.CDIMPOSTO)       AND
                                    (TI.NRSEQITPRO   = W_1)                AND
                                    (TI.CDFILIMPOIT  = II.CDFILIAL(+))     AND
                                    (TI.NRLANCIMPOIT = II.NRLANCTONF(+))   AND
                                    (TI.NRSEQIMPOIT  = II.NRSEQITPROD(+))  AND
                                    (TI.CDIMPOSTOIT  = II.CDIMPOSTO(+))    AND
                                    (TI.NRSEQITPRO   = II.NRITPROIMPOS(+)) AND
                                    (IP.CDPRODUTO    = P.CDPRODUTO)

                              UNION ALL

                              SELECT /*+ index (II,PK_ITEMPROIMPOS)*/
                                     IP.NRSEQITPROD AS NRSEQITPROD, II.CDIMPOSTO AS CDIMPOSTO,
                                     NVL(II.VRPERREDBCIT, 0) VRPERREDBCIT, NVL(II.VRALIQITEM, 0) VRALIQITEM,
                                     NVL(II.VRPARDEDIT, 0) VRPARDEDIT, II.CDFISCALIT, NVL(II.VRIMPOSTOIT, 0) AS VRIMPOSIT,
                                     IM.IDTRATIMPO, IM.IDIMPORECUP, IM.CDCCTBLPASS, IM.CDCCTBLATIV, II.VRALIQITEM AS VRALIQIMPOIT,
                                     II.NRITPROIMPOS, II.NRSEQITPROD AS NRSEQITPRO, NVL(II.IDVALORINFIT,W_N) AS IDVALORINFO,
                                     II.IDTRIMPSTII, IM.IDTIPCONTAB, NVL(II.VRBASECALCIT, 0) VRBASECALCIT, NVL(II.VRADICFECP, 0) VRADICFECP,
                                     P.CDARVPROD, P.CDPRODUTO, IP.VRTOTAITEM, IP.VRDESCITEM, NVL(IM.IDCONTAIMPADIC, 'N')IDCONTAIMPADIC,
                                     IP.IDORIGEMPROD, IM.IDDESCRFONTE, II.IDCONSDIFALIQ
                              FROM ITEMPRODUTO IP, ITEMPROIMPOS II, IMPOSTO IM, PRODUTO P
                              WHERE (IP.CDFILIAL     = P_FILIAL)           AND
                                    (IP.NRLANCTONF   = P_LANCTONF)         AND
                                    (II.CDFILIAL     = IP.CDFILIAL)        AND
                                    (II.NRLANCTONF   = IP.NRLANCTONF)      AND
                                    (II.NRSEQITPROD  = IP.NRSEQITPROD)     AND
                                    (II.CDIMPOSTO    = IM.CDIMPOSTO)       AND
                                    (II.NRITPROIMPOS = W_1)                AND
                                    (IP.CDPRODUTO    = P.CDPRODUTO)        AND
                                    NOT EXISTS (SELECT T.CDFILIMPOIT
                                                FROM  TRABITPROIMPOS T
                                                WHERE T.CDFILIMPOIT  = IP.CDFILIAL    AND
                                                      T.NRLANCIMPOIT = IP.NRLANCTONF)
                              ORDER BY NRSEQITPROD, CDIMPOSTO) LOOP

               V_IDIMPOBCALTPOP := NULL;

               SELECT TO_CHAR(MAX('S')), NVL(SUM(TI.VRIMPOSIT),0) AS VRIMPOBCALC, NVL(SUM(TI.VRIMPOSIT),0) AS VRIMPOBCINF
                 INTO V_IDIMPOBCALTPOP, V_TOTAIMPBCALC, V_TOTAIMPBCINF
                 FROM ITEMPRODUTO IP, ITEMPROIMPOS II, TRABITPROIMPOS TI, BASECALCTPOPER BC, IMPOSTO I
                WHERE BC.IDENTRSAIDOP = P_ENTRSAID
                  AND BC.CDTIPOOPER = P_TIPOOPER
                  AND BC.CDIMPOSTO = C_PRODUTO.CDIMPOSTO
                  AND IP.CDFILIAL     = P_FILIAL
                  AND IP.NRLANCTONF   = P_LANCTONF
                  AND IP.NRSEQITPROD  = C_PRODUTO.NRSEQITPROD
                  AND TI.CDFILIMPOIT  = P_FILIAL
                  AND TI.NRLANCIMPOIT = P_LANCTONF
                  AND TI.NRSEQIMPOIT  = C_PRODUTO.NRSEQITPROD
                  AND TI.CDIMPOSTOIT  = BC.CDIMPOBCALC
                  AND II.CDIMPOSTO    = BC.CDIMPOBCALC
                  AND TI.CDFILIMPOIT  = II.CDFILIAL(+)
                  AND TI.NRLANCIMPOIT = II.NRLANCTONF(+)
                  AND TI.NRSEQIMPOIT  = II.NRSEQITPROD(+)
                  AND (NVL(IP.IDUTVRPAUTAPROD, 'N') = 'N')
                  AND ((SUBSTR(IP.CDSITUTRIBPR,2,2) = BC.CDCSTIMPOTPOP)  OR (BC.CDCSTIMPOTPOP IS NULL))
                  AND ((SUBSTR(IP.CDFISOPEITEM,2,10) = BC.CDCFOPIMPOTPOP) OR (BC.CDCFOPIMPOTPOP IS NULL))
                  AND ((C_PRODUTO.CDFISCALIT        = BC.CDFISCIMPOTPOP) OR (BC.CDFISCIMPOTPOP IS NULL))
                  AND BC.CDIMPOBCALC = I.CDIMPOSTO
                  AND I.IDTRATIMPO <> 'D';

               IF V_IDIMPOBCALTPOP IS NULL THEN

                  SELECT NVL(SUM(TI.VRIMPOSIT),0) AS VRIMPOBCALC, NVL(SUM(TI.VRIMPOSIT),0) AS VRIMPOBCINF
                  INTO V_TOTAIMPBCALC, V_TOTAIMPBCINF
                  FROM ITEMPRODUTO IP, ITEMPROIMPOS II, TRABITPROIMPOS TI, BASECALC BC, IMPOSTO I
                  WHERE (BC.CDIMPOSTO    = C_PRODUTO.CDIMPOSTO)    AND
                        (IP.CDFILIAL     = P_FILIAL)               AND
                        (IP.NRLANCTONF   = P_LANCTONF)             AND
                        (IP.NRSEQITPROD  = C_PRODUTO.NRSEQITPROD)  AND
                        (TI.CDFILIMPOIT  = P_FILIAL)               AND
                        (TI.NRLANCIMPOIT = P_LANCTONF)             AND
                        (TI.NRSEQIMPOIT  = C_PRODUTO.NRSEQITPROD)  AND
                        (TI.CDIMPOSTOIT  = BC.CDIMPOBCALC)         AND
                        (II.CDIMPOSTO    = BC.CDIMPOBCALC)         AND
                        (TI.CDFILIMPOIT  = II.CDFILIAL(+))         AND
                        (TI.NRLANCIMPOIT = II.NRLANCTONF(+))       AND
                        (TI.NRSEQIMPOIT  = II.NRSEQITPROD(+))      AND
                        (NVL(IP.IDUTVRPAUTAPROD, 'N') = 'N')       AND
                        ((SUBSTR(IP.CDSITUTRIBPR,2,2) = BC.CDCSTIMPO)  OR (BC.CDCSTIMPO  IS NULL)) AND
                        ((SUBSTR(IP.CDFISOPEITEM,2,10) = BC.CDCFOPIMPO) OR (BC.CDCFOPIMPO IS NULL)) AND
                        ((C_PRODUTO.CDFISCALIT        = BC.CDFISCIMPO) OR (BC.CDFISCIMPO IS NULL)) AND
                        (BC.IDTIPOBCALC   = 'I')        AND
                        (BC.CDIMPOBCALC = I.CDIMPOSTO)  AND
                        (I.IDTRATIMPO <> 'D');
               END IF;

               V_IDIMBCALTPOPDE := NULL;

               SELECT TO_CHAR(MAX('S')), (NVL(SUM(VRIMPOSTOIT),0)*-1) AS VRIMPOBCALC
                 INTO V_IDIMBCALTPOPDE, V_TOTAIMPBCDES
                 FROM ITEMPRODUTO IP, ITEMPROIMPOS II, TRABITPROIMPOS TI, BASECALCTPOPER BC, IMPOSTO I
                WHERE BC.IDENTRSAIDOP = P_ENTRSAID
                  AND BC.CDTIPOOPER = P_TIPOOPER
                  AND BC.CDIMPOSTO = C_PRODUTO.CDIMPOSTO
                  AND IP.CDFILIAL     = P_FILIAL
                  AND IP.NRLANCTONF   = P_LANCTONF
                  AND IP.NRSEQITPROD  = C_PRODUTO.NRSEQITPROD
                  AND TI.CDFILIMPOIT  = P_FILIAL
                  AND TI.NRLANCIMPOIT = P_LANCTONF
                  AND TI.NRSEQIMPOIT  = C_PRODUTO.NRSEQITPROD
                  AND TI.CDIMPOSTOIT  = BC.CDIMPOBCALC
                  AND II.CDIMPOSTO    = BC.CDIMPOBCALC
                  AND TI.CDFILIMPOIT  = II.CDFILIAL(+)
                  AND TI.NRLANCIMPOIT = II.NRLANCTONF(+)
                  AND TI.NRSEQIMPOIT  = II.NRSEQITPROD(+)
                  AND (NVL(IP.IDUTVRPAUTAPROD, 'N') = 'N')
                  AND ((SUBSTR(IP.CDSITUTRIBPR,2,2) = BC.CDCSTIMPOTPOP)  OR (BC.CDCSTIMPOTPOP IS NULL))
                  AND ((SUBSTR(IP.CDFISOPEITEM,2,10) = BC.CDCFOPIMPOTPOP) OR (BC.CDCFOPIMPOTPOP IS NULL))
                  AND ((C_PRODUTO.CDFISCALIT        = BC.CDFISCIMPOTPOP) OR (BC.CDFISCIMPOTPOP IS NULL))
                  AND BC.CDIMPOBCALC = I.CDIMPOSTO
                  AND I.IDTRATIMPO = 'D';

               IF V_IDIMBCALTPOPDE IS NULL THEN

                  SELECT (NVL(SUM(VRIMPOSTOIT),0)*-1) AS VRIMPOBCALC INTO V_TOTAIMPBCDES
                  FROM ITEMPRODUTO IP, ITEMPROIMPOS II, TRABITPROIMPOS TI, BASECALC BC, IMPOSTO I
                  WHERE (BC.CDIMPOSTO    = C_PRODUTO.CDIMPOSTO)    AND
                        (IP.CDFILIAL     = P_FILIAL)               AND
                        (IP.NRLANCTONF   = P_LANCTONF)             AND
                        (IP.NRSEQITPROD  = C_PRODUTO.NRSEQITPROD)  AND
                        (TI.CDFILIMPOIT  = P_FILIAL)               AND
                        (TI.NRLANCIMPOIT = P_LANCTONF)             AND
                        (TI.NRSEQIMPOIT  = C_PRODUTO.NRSEQITPROD)  AND
                        (TI.CDIMPOSTOIT  = BC.CDIMPOBCALC)         AND
                        (II.CDIMPOSTO    = BC.CDIMPOBCALC)         AND
                        (TI.CDFILIMPOIT  = II.CDFILIAL(+))         AND
                        (TI.NRLANCIMPOIT = II.NRLANCTONF(+))       AND
                        (TI.NRSEQIMPOIT  = II.NRSEQITPROD(+))      AND
                        (NVL(IP.IDUTVRPAUTAPROD, 'N') = 'N')       AND
                        ((SUBSTR(IP.CDSITUTRIBPR,2,2) = BC.CDCSTIMPO)  OR (BC.CDCSTIMPO  IS NULL)) AND
                        ((SUBSTR(IP.CDFISOPEITEM,2,10) = BC.CDCFOPIMPO) OR (BC.CDCFOPIMPO IS NULL)) AND
                        ((C_PRODUTO.CDFISCALIT        = BC.CDFISCIMPO) OR (BC.CDFISCIMPO IS NULL)) AND
                        (BC.IDTIPOBCALC   = 'I')        AND
                        (BC.CDIMPOBCALC = I.CDIMPOSTO)  AND
                        (I.IDTRATIMPO = 'D');
               END IF;

               V_IMPOSINFO := C_PRODUTO.VRIMPOSIT;

               V_CDIMPOSTRIB := NULL;
               V_VRIMPOSTOST := 0;

               FOR C_ICMSST IN (SELECT CDIMPOSTO
                                       FROM IMPOSTO
                                      WHERE CDIMPOSTRIB = C_PRODUTO.CDIMPOSTO)
               LOOP
                  V_CDIMPOSTRIB := V_CDIMPOSTRIB||C_ICMSST.CDIMPOSTO||'_';
               END LOOP;

               V_IMPOSTRIBCOMPLANC := NULL;

               IF (V_CDIMPOSTRIB IS NOT NULL)  THEN
                  SELECT MAX(CDIMPOSTOIT)
                    INTO V_IMPOSTRIBCOMPLANC
                    FROM TRABITPROIMPOS
                   WHERE CDFILIMPOIT  = P_FILIAL
                     AND NRLANCIMPOIT = P_LANCTONF
                     AND (INSTR(V_CDIMPOSTRIB,CDIMPOSTOIT||'_') > 0);
               END IF;

               IF (V_IMPOSTRIBCOMPLANC IS NULL) THEN
                  V_CDIMPOSTRIB := NULL;
               END IF;

               IF ((V_IDGERNFIGUALXML = 'N') AND (C_PRODUTO.IDVALORINFO <> W_S)) OR (V_IDNFGERADAVIAXML = 'N') THEN
                  /*ALTERAÇÃO 01/02/2011*/
                  IF (NOT(V_TOTAIMPBCALC IS NULL) OR (V_TOTAIMPBCALC <> 0)) OR
                     (NOT(V_TOTAIMPBCDES IS NULL) OR (V_TOTAIMPBCDES <> 0)) OR
                     (V_CDIMPOSTRIB IS NOT NULL) THEN

                     IF (C_PRODUTO.IDCONSDIFALIQ = 'S') THEN
                        V_CDIMPOSTRIB := NULL;
                     END IF;

                     IF V_CDIMPOSTRIB IS NULL THEN

                        IF (C_PRODUTO.IDCONSDIFALIQ = 'N') THEN
                           V_TAXABASECALC := (100 - C_PRODUTO.VRPERREDBCIT)/100;
                           V_TAXAALIQUOTA := (C_PRODUTO.VRALIQITEM/100);
                           V_IMPOSINFO    := V_IMPOSINFO + (((V_TOTAIMPBCALC + V_TOTAIMPBCDES) * V_TAXABASECALC) * V_TAXAALIQUOTA);
   
                           UPDATE ITEMPROIMPOS
                              SET VRBASECALCIT = VRBASECALCIT + ((V_TOTAIMPBCALC + V_TOTAIMPBCDES) * V_TAXABASECALC),
                                  VRIMPOSTOIT  = VRIMPOSTOIT  + (((V_TOTAIMPBCALC + V_TOTAIMPBCDES) * V_TAXABASECALC) * V_TAXAALIQUOTA)
                            WHERE (CDFILIAL     = P_FILIAL)              AND
                                  (NRLANCTONF   = P_LANCTONF)            AND
                                  (NRSEQITPROD  = C_PRODUTO.NRSEQITPROD) AND
                                  (CDIMPOSTO    = C_PRODUTO.CDIMPOSTO)   AND
                                  (NRITPROIMPOS = C_PRODUTO.NRITPROIMPOS);
   
                           UPDATE TRABITPROIMPOS
                              SET VRBCALCIMPOIT  = VRBCALCIMPOIT + (V_TOTAIMPBCINF * V_TAXABASECALC),
                                  VRIMPOSIT      = V_IMPOSINFO
                              WHERE CDFILIMPOIT  = P_FILIAL              AND
                                    NRLANCIMPOIT = P_LANCTONF            AND
                                    NRSEQIMPOIT  = C_PRODUTO.NRSEQITPROD AND
                                    CDIMPOSTOIT  = C_PRODUTO.CDIMPOSTO   AND
                                    NRSEQITPRO   = C_PRODUTO.NRSEQITPRO;
   
                           UPDATE ITEMPROIMPOS
                              SET VRBASECALCIT = VRBASECALCIT + (V_TOTAIMPBCALC * ((100 - VRPERREDBCIT)/100)),
                                  VRIMPOSTOIT  = VRIMPOSTOIT  + ((V_TOTAIMPBCALC * ((100 - VRPERREDBCIT)/100)) * (VRALIQITEM/100))
                            WHERE (CDFILIAL     = P_FILIAL)              AND
                                  (NRLANCTONF   = P_LANCTONF)            AND
                                  (NRSEQITPROD  = C_PRODUTO.NRSEQITPROD) AND
                                  (CDIMPOSTO    = C_PRODUTO.CDIMPOSTO)   AND
                                  (NRITPROIMPOS = W_2);
   
                           UPDATE TRABITPROIMPOS
                              SET VRBCALCIMPOIT  = VRBCALCIMPOIT + (V_TOTAIMPBCINF * ((100 - VRREDBCIMPOIT)/100)),
                                  VRIMPOSIT      = VRIMPOSIT + ((V_TOTAIMPBCINF * ((100 - VRREDBCIMPOIT)/100)) * (VRALIQIMPOIT/100))
                            WHERE CDFILIMPOIT  = P_FILIAL              AND
                                  NRLANCIMPOIT = P_LANCTONF            AND
                                  NRSEQIMPOIT  = C_PRODUTO.NRSEQITPROD AND
                                  CDIMPOSTOIT  = C_PRODUTO.CDIMPOSTO   AND
                                  NRSEQITPRO   = W_2;
   
                           UPDATE TRABITPROIMPOS
                              SET VRBCALCIMPOIT  = VRBCALCIMPOIT + (V_TOTAIMPBCINF * V_TAXABASECALC),
                                  VRIMPOSIT      = VRIMPOSIT + ((V_TOTAIMPBCINF * V_TAXABASECALC) * (VRALIQIMPOIT/100))
                            WHERE CDFILIMPOIT  = P_FILIAL              AND
                                  NRLANCIMPOIT = P_LANCTONF            AND
                                  NRSEQIMPOIT  = C_PRODUTO.NRSEQITPROD AND
                                  CDIMPOSTOIT  = C_PRODUTO.CDIMPOSTO   AND
                                  NRSEQITPRO   = W_3;
                        ELSE
                           -- SE CONSIDERA DIFERENÇA DE ALÍQUOTA DE ICMS PARA CÁLCULO DO ICMS-ST
                           SELECT VRIMPOSIT, CDIMPOSTOIT, VRBCALCIMPOIT, II.VRALIQIMPOIT
                             INTO V_VRICMSNF, V_CDIMPOSTOICMS, V_BASECALCDIF, V_ALIQICMS
                             FROM TRABITPROIMPOS II, IMPOSTO I
                            WHERE (II.CDFILIMPOIT  = P_FILIAL)
                              AND (II.NRLANCIMPOIT = P_LANCTONF)
                              AND (II.NRSEQIMPOIT  = C_PRODUTO.NRSEQITPROD)
                              AND (II.NRSEQITPRO   = W_1)
                              AND (I.CDIMPOSTONFE  = '00')
                              AND (II.CDIMPOSTOIT  = I.CDIMPOSTO);

                           DELETE ALIQTEMP
                            WHERE NRALIQTEMP = V_ALIQTEMP;

                           CONSULTA_ALIQUOTA(V_CDIMPOSTOICMS, P_ENTRSAID, P_EMPRESA, C_PRODUTO.CDARVPROD, P_INSCESTA, V_PAISDEST,
                                                V_ESTADEST, V_PAISDEST, V_ESTADEST, V_MUNIDEST, V_LIQUIITEM, P_INIVALID, P_FILIAL, P_LANCTONF, V_CDGRPFISCSV,P_TIPOOPER,
                                                NULL, NULL, NULL, NULL, P_FORNECED, NULL, C_PRODUTO.IDORIGEMPROD);

                           SELECT MAX(VRALIQUTMP)
                             INTO V_VRALIQICMSINT
                             FROM ALIQTEMP
                            WHERE (NRALIQTEMP = V_ALIQTEMP);

                           IF ((V_VRALIQICMSINT IS NULL) OR (V_VRALIQICMSINT < V_ALIQICMS)) THEN
                              BEGIN
                                 SELECT NVL(CONSULTA_QUADRO_ALIQUOTAS(V_ESTADEST, V_ESTADEST), 0)
                                   INTO V_VRALIQICMSINT
                                   FROM DUAL;
                              EXCEPTION
                                 WHEN NO_DATA_FOUND THEN
                                    V_VRALIQICMSINT := 0;
                              END;
                           END IF;

                           V_ALIQSTDIF   := V_VRALIQICMSINT;
                           V_BASECALCDIF :=  ROUND((V_BASECALCDIF - V_VRICMSNF)/(1-(V_VRALIQICMSINT/100)), 2);
                           V_IMPOSTODIF  := ROUND(((V_BASECALCDIF * (V_VRALIQICMSINT/100)) - V_VRICMSNF), 2);

                           IF (V_IMPOSTODIF < 0) THEN
                              V_IMPOSTODIF := 0;
                           END IF;
                           
                           V_IMPOSINFO   := V_IMPOSTODIF;

                           DELETE ALIQTEMP
                            WHERE NRALIQTEMP = V_ALIQTEMP;

                           UPDATE ITEMPROIMPOS
                              SET VRBASECALCIT = V_BASECALCDIF,
                                  VRIMPOSTOIT  = V_IMPOSTODIF,
                                  VRALIQITEM   = V_ALIQSTDIF
                            WHERE (CDFILIAL     = P_FILIAL)              AND
                                  (NRLANCTONF   = P_LANCTONF)            AND
                                  (NRSEQITPROD  = C_PRODUTO.NRSEQITPROD) AND
                                  (CDIMPOSTO    = C_PRODUTO.CDIMPOSTO)   AND
                                  (NRITPROIMPOS = C_PRODUTO.NRITPROIMPOS);

                           UPDATE TRABITPROIMPOS
                              SET VRBCALCIMPOIT  = V_BASECALCDIF,
                                  VRIMPOSIT      = V_IMPOSTODIF,
                                  VRALIQIMPOIT   = V_ALIQSTDIF
                            WHERE CDFILIMPOIT  = P_FILIAL              AND
                                  NRLANCIMPOIT = P_LANCTONF            AND
                                  NRSEQIMPOIT  = C_PRODUTO.NRSEQITPROD AND
                                  CDIMPOSTOIT  = C_PRODUTO.CDIMPOSTO   AND
                                  NRSEQITPRO   = C_PRODUTO.NRSEQITPRO;

                           UPDATE ITEMPROIMPOS
                              SET VRBASECALCIT = V_BASECALCDIF + (V_TOTAIMPBCALC * ((100 - VRPERREDBCIT)/100)),
                                  VRIMPOSTOIT  = V_IMPOSTODIF  + ((V_TOTAIMPBCALC * ((100 - VRPERREDBCIT)/100)) * (VRALIQITEM/100))
                            WHERE (CDFILIAL     = P_FILIAL)              AND
                                  (NRLANCTONF   = P_LANCTONF)            AND
                                  (NRSEQITPROD  = C_PRODUTO.NRSEQITPROD) AND
                                  (CDIMPOSTO    = C_PRODUTO.CDIMPOSTO)   AND
                                  (NRITPROIMPOS = W_2);

                           UPDATE TRABITPROIMPOS
                              SET VRBCALCIMPOIT  = V_BASECALCDIF + (V_TOTAIMPBCINF * ((100 - VRREDBCIMPOIT)/100)),
                                  VRIMPOSIT      = V_IMPOSTODIF + ((V_TOTAIMPBCINF * ((100 - VRREDBCIMPOIT)/100)) * (VRALIQIMPOIT/100))
                            WHERE CDFILIMPOIT  = P_FILIAL              AND
                                  NRLANCIMPOIT = P_LANCTONF            AND
                                  NRSEQIMPOIT  = C_PRODUTO.NRSEQITPROD AND
                                  CDIMPOSTOIT  = C_PRODUTO.CDIMPOSTO   AND
                                  NRSEQITPRO   = W_2;

                           UPDATE TRABITPROIMPOS
                              SET VRBCALCIMPOIT  = V_BASECALCDIF + (V_TOTAIMPBCINF * V_TAXABASECALC),
                                  VRIMPOSIT      = V_IMPOSTODIF + ((V_TOTAIMPBCINF * V_TAXABASECALC) * (VRALIQIMPOIT/100))
                            WHERE CDFILIMPOIT  = P_FILIAL              AND
                                  NRLANCIMPOIT = P_LANCTONF            AND
                                  NRSEQIMPOIT  = C_PRODUTO.NRSEQITPROD AND
                                  CDIMPOSTOIT  = C_PRODUTO.CDIMPOSTO   AND
                                  NRSEQITPRO   = W_3;
                        END IF;
                     ELSE
                        SELECT NVL(MAX(IDVRIMPSTRIB), 'N')
                          INTO V_IDVRIMPSTRIB
                          FROM TRABITPROIMPOS I, IMPOSTO II
                         WHERE (CDFILIMPOIT  = P_FILIAL)
                           AND (NRLANCIMPOIT = P_LANCTONF)
                           AND (NRSEQIMPOIT  = C_PRODUTO.NRSEQITPROD)
                           AND (INSTR(V_CDIMPOSTRIB,II.CDIMPOSTO||'_') > 0)
                           AND (I.CDIMPOSTOIT = II.CDIMPOSTO);

                        IF (C_PRODUTO.IDTRIMPSTII = '1') OR (NVL(V_IDVRIMPSTRIB,'N') = 'N') OR (NVL(V_IDCONSDIFALIQ , W_N) = 'S') THEN
                           V_VRIMPOSTOST := 0;
                        ELSE
                           BEGIN
                              SELECT NVL(VRIMPOSIT,0)
                              INTO V_VRIMPOSTOST
                              FROM TRABITPROIMPOS I
                              WHERE (CDFILIMPOIT  = P_FILIAL)               AND
                                    (NRLANCIMPOIT = P_LANCTONF)             AND
                                    (NRSEQIMPOIT  = C_PRODUTO.NRSEQITPROD)  AND
                                    (INSTR(V_CDIMPOSTRIB,CDIMPOSTOIT||'_') > 0) AND
                                    (NRSEQITPRO   = W_1);
                           EXCEPTION
                              WHEN NO_DATA_FOUND THEN
                                 V_VRIMPOSTOST := 0;
                           END;
                        END IF;

                        -- VERIFICA SE POSSUI PERCENTUAL DE REDUÇÃO

                        V_UTGRUPFISCS := NULL;
                        V_LIQUIITEM   := 0;

                        V_LIQUIITEM := C_PRODUTO.VRTOTAITEM - C_PRODUTO.VRDESCITEM;

                        SELECT MAX(IDGRUPFISSRV)
                          INTO V_UTGRUPFISCS
                          FROM IMPOSTO
                         WHERE CDIMPOSTO = C_PRODUTO.CDIMPOSTO;

                        IF V_UTGRUPFISCS = 'S' THEN
                           V_CDGRPFISCSV := NULL;
                           SELECT MAX(CDGRUPOFISC)
                             INTO V_CDGRPFISCSV
                             FROM SERVCLIE SC, SERVICO S
                            WHERE SC.CDFILIAL = V_CDFILIEMIT
                              AND SC.CDCLIENTE = P_FORNECED
                              AND SC.CDFILIAL = S.CDFILIAL
                              AND SC.CDSERVFILI = S.CDSERVFILI
                              AND S.CDPRODUTO = C_PRODUTO.CDPRODUTO;

                           IF V_CDGRPFISCSV IS NULL THEN
                              SELECT MAX(CDGRUPOFISC)
                                INTO V_CDGRPFISCSV
                                FROM CLIENFILIAL
                               WHERE CDFILIAL = V_CDFILIEMIT
                                 AND CDCLIENTE = P_FORNECED;
                           END IF;

                           CONSULTA_ALIQUOTA(C_PRODUTO.CDIMPOSTO, P_ENTRSAID, P_EMPRESA, C_PRODUTO.CDARVPROD, P_INSCESTA, V_PAISORIG,
                                             V_ESTAORIG, V_PAISDEST, V_ESTADEST, V_MUNIDEST, V_LIQUIITEM, P_INIVALID, P_FILIAL, P_LANCTONF, V_CDGRPFISCSV, P_TIPOOPER,
                                             NULL, NULL, NULL, NULL, P_FORNECED, NULL, C_PRODUTO.IDORIGEMPROD);
                        ELSE
                           CONSULTA_ALIQUOTA(C_PRODUTO.CDIMPOSTO, P_ENTRSAID, P_EMPRESA, C_PRODUTO.CDARVPROD, P_INSCESTA, V_PAISORIG,
                                             V_ESTAORIG, V_PAISDEST, V_ESTADEST, V_MUNIDEST, V_LIQUIITEM, P_INIVALID, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC, P_TIPOOPER,
                                             NULL, NULL, NULL, NULL, P_FORNECED, NULL, C_PRODUTO.IDORIGEMPROD);
                        END IF;

                        V_PREDBCTMP  := 0;
                        V_PBCSUBTRIB := 0;

                        SELECT (100 - (NVL(MAX(VRPREDBCTMP),0)))/100, NVL(MAX(VRPBCSTTMP),0)
                          INTO V_PREDBCTMP, V_PBCSUBTRIB
                          FROM ALIQTEMP
                         WHERE NRALIQTEMP = V_ALIQTEMP;

                        V_TAXABASECALC := 1 + (C_PRODUTO.VRPERREDBCIT)/100;
                        V_TAXAALIQUOTA := (C_PRODUTO.VRALIQITEM/100);

                        IF V_PBCSUBTRIB <> 0 THEN
                           IF (V_IDVALORINFO <> 'S') THEN
                              V_IMPOSINFO := ((C_PRODUTO.VRBASECALCIT+ ((V_TOTAIMPBCALC + V_TOTAIMPBCDES) * V_TAXABASECALC * V_PREDBCTMP)) * V_TAXAALIQUOTA);
                           END IF;
                        ELSE
                           IF (V_IDVALORINFO <> 'S') THEN
                              V_IMPOSINFO := ((C_PRODUTO.VRBASECALCIT+ ((V_TOTAIMPBCALC + V_TOTAIMPBCDES) * V_TAXABASECALC)) * V_TAXAALIQUOTA);
                           END IF;
                        END IF;

                        DELETE ALIQTEMP
                        WHERE NRALIQTEMP = V_ALIQTEMP;

                        IF V_VRIMPOSTOST > V_IMPOSINFO THEN
                           V_IMPOSINFO := 0;

                           UPDATE ITEMPROIMPOS
                           SET VRBASECALCIT = VRBASECALCIT + ((V_TOTAIMPBCALC + V_TOTAIMPBCDES) * V_TAXABASECALC),
                               VRIMPOSTOIT  = V_IMPOSINFO
                           WHERE (CDFILIAL     = P_FILIAL)              AND
                                 (NRLANCTONF   = P_LANCTONF)            AND
                                 (NRSEQITPROD  = C_PRODUTO.NRSEQITPROD) AND
                                 (CDIMPOSTO    = C_PRODUTO.CDIMPOSTO)   AND
                                 (NRITPROIMPOS = C_PRODUTO.NRITPROIMPOS);

                           UPDATE TRABITPROIMPOS
                              SET VRBCALCIMPOIT  = VRBCALCIMPOIT + (V_TOTAIMPBCINF * V_TAXABASECALC),
                                  VRIMPOSIT      = V_IMPOSINFO
                            WHERE CDFILIMPOIT  = P_FILIAL               AND
                                   NRLANCIMPOIT = P_LANCTONF            AND
                                   NRSEQIMPOIT  = C_PRODUTO.NRSEQITPROD AND
                                   CDIMPOSTOIT  = C_PRODUTO.CDIMPOSTO   AND
                                   NRSEQITPRO   = C_PRODUTO.NRSEQITPRO;

                           UPDATE ITEMPROIMPOS
                              SET VRBASECALCIT = VRBASECALCIT + (V_TOTAIMPBCALC * ((100 - VRPERREDBCIT)/100)),
                                  VRIMPOSTOIT  = VRIMPOSTOIT  + ((V_TOTAIMPBCALC * ((100 - VRPERREDBCIT)/100)) * (VRALIQITEM/100))
                            WHERE (CDFILIAL     = P_FILIAL)              AND
                                  (NRLANCTONF   = P_LANCTONF)            AND
                                  (NRSEQITPROD  = C_PRODUTO.NRSEQITPROD) AND
                                  (CDIMPOSTO    = C_PRODUTO.CDIMPOSTO)   AND
                                  (NRITPROIMPOS = W_2);

                           UPDATE TRABITPROIMPOS
                              SET VRBCALCIMPOIT  = VRBCALCIMPOIT + (V_TOTAIMPBCINF * ((100 - VRREDBCIMPOIT)/100)),
                                  VRIMPOSIT      = VRIMPOSIT + ((V_TOTAIMPBCINF * ((100 - VRREDBCIMPOIT)/100)) * (VRALIQIMPOIT/100))
                            WHERE CDFILIMPOIT  = P_FILIAL              AND
                                  NRLANCIMPOIT = P_LANCTONF            AND
                                  NRSEQIMPOIT  = C_PRODUTO.NRSEQITPROD AND
                                  CDIMPOSTOIT  = C_PRODUTO.CDIMPOSTO   AND
                                  NRSEQITPRO   = W_2;

                           UPDATE TRABITPROIMPOS
                              SET VRBCALCIMPOIT  = VRBCALCIMPOIT + (V_TOTAIMPBCINF * V_TAXABASECALC),
                                  VRIMPOSIT      = VRIMPOSIT + ((V_TOTAIMPBCINF * V_TAXABASECALC) * (VRALIQIMPOIT/100))
                            WHERE CDFILIMPOIT  = P_FILIAL              AND
                                  NRLANCIMPOIT = P_LANCTONF            AND
                                  NRSEQIMPOIT  = C_PRODUTO.NRSEQITPROD AND
                                  CDIMPOSTOIT  = C_PRODUTO.CDIMPOSTO   AND
                                  NRSEQITPRO   = W_3;

                        ELSE
                           IF (V_IDVALORINFO <> 'S') THEN
                              V_IMPOSINFO := V_IMPOSINFO - V_VRIMPOSTOST;
                           END IF;

                           UPDATE ITEMPROIMPOS
                              SET VRBASECALCIT = VRBASECALCIT + ((V_TOTAIMPBCALC + V_TOTAIMPBCDES) * V_TAXABASECALC),
                                  VRIMPOSTOIT  = V_IMPOSINFO
                            WHERE (CDFILIAL     = P_FILIAL)              AND
                                  (NRLANCTONF   = P_LANCTONF)            AND
                                  (NRSEQITPROD  = C_PRODUTO.NRSEQITPROD) AND
                                  (CDIMPOSTO    = C_PRODUTO.CDIMPOSTO)   AND
                                  (NRITPROIMPOS = C_PRODUTO.NRITPROIMPOS);

                           UPDATE TRABITPROIMPOS
                              SET VRBCALCIMPOIT  = VRBCALCIMPOIT + (V_TOTAIMPBCINF * V_TAXABASECALC),
                                  VRIMPOSIT      = V_IMPOSINFO
                            WHERE CDFILIMPOIT  = P_FILIAL              AND
                                  NRLANCIMPOIT = P_LANCTONF            AND
                                  NRSEQIMPOIT  = C_PRODUTO.NRSEQITPROD AND
                                  CDIMPOSTOIT  = C_PRODUTO.CDIMPOSTO   AND
                                  NRSEQITPRO   = C_PRODUTO.NRSEQITPRO;

                           UPDATE ITEMPROIMPOS
                              SET VRBASECALCIT = VRBASECALCIT + (V_TOTAIMPBCALC * ((100 - VRPERREDBCIT)/100)),
                                  VRIMPOSTOIT  = VRIMPOSTOIT  + ((V_TOTAIMPBCALC * ((100 - VRPERREDBCIT)/100)) * (VRALIQITEM/100))
                            WHERE (CDFILIAL     = P_FILIAL)              AND
                                  (NRLANCTONF   = P_LANCTONF)            AND
                                  (NRSEQITPROD  = C_PRODUTO.NRSEQITPROD) AND
                                  (CDIMPOSTO    = C_PRODUTO.CDIMPOSTO)   AND
                                  (NRITPROIMPOS = W_2);

                           UPDATE TRABITPROIMPOS
                              SET VRBCALCIMPOIT  = VRBCALCIMPOIT + (V_TOTAIMPBCINF * ((100 - VRREDBCIMPOIT)/100)),
                                  VRIMPOSIT      = VRIMPOSIT + ((V_TOTAIMPBCINF * ((100 - VRREDBCIMPOIT)/100)) * (VRALIQIMPOIT/100))
                            WHERE CDFILIMPOIT  = P_FILIAL              AND
                                  NRLANCIMPOIT = P_LANCTONF            AND
                                  NRSEQIMPOIT  = C_PRODUTO.NRSEQITPROD AND
                                  CDIMPOSTOIT  = C_PRODUTO.CDIMPOSTO   AND
                                  NRSEQITPRO   = W_2;

                           UPDATE TRABITPROIMPOS
                              SET VRBCALCIMPOIT  = VRBCALCIMPOIT + (V_TOTAIMPBCINF * V_TAXABASECALC),
                                  VRIMPOSIT      = VRIMPOSIT + ((V_TOTAIMPBCINF * V_TAXABASECALC) * (VRALIQIMPOIT/100))
                            WHERE CDFILIMPOIT  = P_FILIAL              AND
                                  NRLANCIMPOIT = P_LANCTONF            AND
                                  NRSEQIMPOIT  = C_PRODUTO.NRSEQITPROD AND
                                  CDIMPOSTOIT  = C_PRODUTO.CDIMPOSTO   AND
                                  NRSEQITPRO   = W_3;
                        END IF;
                     END IF;
                  END IF;
               END IF;

               /* Utiliza o próprio valor do imposto na sua base de cálculo */
               SELECT NVL(MAX(IDUTILPVRIMPBC), 'N'), MAX(IDTRATIMPO)
                 INTO V_IDUTILPVRIMPBC, V_IDTRATIMPO
                 FROM IMPOSTO
                WHERE CDIMPOSTO = C_PRODUTO.CDIMPOSTO;

               IF V_IDUTILPVRIMPBC = 'S' THEN

                  IF V_CDIMPOSTRIB IS NULL THEN
                     BEGIN
                        SELECT VRIMPOSTOIT
                          INTO V_VRIMPANTE
                          FROM ITEMPROIMPOS T
                         WHERE CDFILIAL     = P_FILIAL
                           AND NRLANCTONF   = P_LANCTONF
                           AND NRSEQITPROD  = C_PRODUTO.NRSEQITPROD
                           AND CDIMPOSTO    = C_PRODUTO.CDIMPOSTO
                           AND NRITPROIMPOS = C_PRODUTO.NRITPROIMPOS;
                     EXCEPTION
                        WHEN NO_DATA_FOUND THEN
                           V_VRIMPANTE := 0;
                     END;

                     UPDATE ITEMPROIMPOS
                        SET VRBASECALCIT = (VRBASECALCIT )/((100 -VRALIQITEM)/100),
                            VRIMPOSTOIT  = ((VRBASECALCIT)/((100 -VRALIQITEM)/100))*(VRALIQITEM/100)
                      WHERE CDFILIAL     = P_FILIAL
                        AND NRLANCTONF   = P_LANCTONF
                        AND NRSEQITPROD  = C_PRODUTO.NRSEQITPROD
                        AND CDIMPOSTO    = C_PRODUTO.CDIMPOSTO
                        AND NRITPROIMPOS = C_PRODUTO.NRITPROIMPOS;

                     UPDATE TRABITPROIMPOS
                        SET VRBCALCIMPOIT = (VRBCALCIMPOIT )/((100 -VRALIQIMPOIT)/100),
                            VRIMPOSIT     = ((VRBCALCIMPOIT)/((100 -VRALIQIMPOIT)/100))*(VRALIQIMPOIT/100)
                      WHERE CDFILIMPOIT  = P_FILIAL
                        AND NRLANCIMPOIT = P_LANCTONF
                        AND NRSEQIMPOIT  = C_PRODUTO.NRSEQITPROD
                        AND CDIMPOSTOIT  = C_PRODUTO.CDIMPOSTO
                        AND NRSEQITPRO   = C_PRODUTO.NRSEQITPRO;

                     BEGIN
                        SELECT VRIMPOSTOIT
                          INTO V_VRIMPAPOS
                          FROM ITEMPROIMPOS
                         WHERE CDFILIAL     = P_FILIAL
                           AND NRLANCTONF   = P_LANCTONF
                           AND NRSEQITPROD  = C_PRODUTO.NRSEQITPROD
                           AND CDIMPOSTO    = C_PRODUTO.CDIMPOSTO
                           AND NRITPROIMPOS = C_PRODUTO.NRITPROIMPOS;
                     EXCEPTION
                        WHEN NO_DATA_FOUND THEN
                           V_VRIMPAPOS := 0;
                     END;

                     IF V_IDTRATIMPO = 'A' THEN
                        UPDATE ITEMPRODUTO
                           SET VRBRUTITEM = VRBRUTITEM + (V_VRIMPAPOS - V_VRIMPANTE)
                         WHERE CDFILIAL     = P_FILIAL
                           AND NRLANCTONF   = P_LANCTONF
                           AND NRSEQITPROD  = C_PRODUTO.NRSEQITPROD;
                     END IF;
                  END IF;
               END IF;

               V_IMPOCONTAB := 0;

               IF (P_TIPOOPER = '03') THEN
                  SELECT NVL(MAX(VRTOTAITEM),0)
                    INTO V_TOTALITEMCOMP
                    FROM ITEMPRODUTO
                   WHERE CDFILIAL    = P_FILIAL
                     AND NRLANCTONF  = P_LANCTONF
                     AND NRSEQITPROD = C_PRODUTO.NRSEQITPROD;
               END IF;

               IF NOT(P_TIPOOPER = '03' AND V_TOTALITEMCOMP = 0 AND C_PRODUTO.IDTRATIMPO <> W_A) THEN
                  IF (C_PRODUTO.IDIMPORECUP = W_S) THEN
                     IF (C_PRODUTO.CDFISCALIT = W_1) THEN
                        IF (C_PRODUTO.CDCCTBLATIV IS NOT NULL) THEN
                           IF C_PRODUTO.IDTRATIMPO = W_V THEN
                              V_IMPOCONTAB := - (V_IMPOSINFO + C_PRODUTO.VRADICFECP);
                           END IF;
                        END IF;
                     ELSE
                        IF C_PRODUTO.IDTRATIMPO = W_A THEN
                           IF ((V_CDIMPOSTRIB IS NOT NULL) AND (C_PRODUTO.IDTRIMPSTII = '0')) OR
                              (V_CDIMPOSTRIB IS NULL) THEN
                              V_IMPOCONTAB := V_IMPOSINFO + C_PRODUTO.VRADICFECP;
                           ELSE
                              V_IMPOCONTAB := 0;
                              V_IMPOSINFO  := 0;
                           END IF;
                        ELSIF C_PRODUTO.IDTRATIMPO IN (W_D,W_R) THEN
                           V_IMPOCONTAB := - (V_IMPOSINFO + C_PRODUTO.VRADICFECP);
                        END IF;
                     END IF;
                  ELSE
                     IF NOT(C_PRODUTO.CDCCTBLPASS IS NULL) THEN
                        IF C_PRODUTO.IDTRATIMPO = W_V THEN
                           IF C_PRODUTO.IDCONTAIMPADIC = 'N' THEN
                              V_IMPOCONTAB := - (V_IMPOSINFO + C_PRODUTO.VRADICFECP);
                           END IF;
                        ELSE
                           IF C_PRODUTO.IDTRATIMPO = W_A THEN
                               SELECT NVL(MAX(IDACRPRODENTRNF), 'N')
                               INTO V_IDACRPRODENTRNF
                               FROM IMPOSTO
                               WHERE CDIMPOSTO = C_PRODUTO.CDIMPOSTO;

                               IF V_IDACRPRODENTRNF = 'S' THEN
                                  V_IMPOCONTAB := V_IMPOSINFO + C_PRODUTO.VRADICFECP;
                               END IF;
                           ELSIF (C_PRODUTO.IDTRATIMPO = W_R) AND (C_PRODUTO.IDDESCRFONTE = 'N') THEN
                              V_IMPOCONTAB := - (V_IMPOSINFO + C_PRODUTO.VRADICFECP);
                           END IF;
                        END IF;
                     ELSE
                        IF C_PRODUTO.IDTRATIMPO = W_A THEN
                           IF ((V_CDIMPOSTRIB IS NOT NULL) AND (C_PRODUTO.IDTRIMPSTII = '0')) OR
                              (V_CDIMPOSTRIB IS NULL) THEN
                              V_IMPOCONTAB := V_IMPOSINFO + C_PRODUTO.VRADICFECP;
                           ELSE
                              V_IMPOCONTAB := 0;
                              V_IMPOSINFO  := 0;
                           END IF;
                        ELSIF C_PRODUTO.IDTRATIMPO IN (W_D,W_R) THEN
                           V_IMPOCONTAB := - (V_IMPOSINFO + C_PRODUTO.VRADICFECP);
                        END IF;
                     END IF;
                  END IF;

                  IF (V_IDOPERDEVONF = W_S) OR (P_TIPOOPER = '16') THEN
                     IF (C_PRODUTO.IDTRATIMPO = W_A) THEN
                       IF NOT (((C_PRODUTO.IDIMPORECUP = W_S)  AND (C_PRODUTO.CDFISCALIT = W_1)) OR
                               ((C_PRODUTO.IDIMPORECUP <> W_S) AND (C_PRODUTO.CDCCTBLATIV IS NOT NULL))) THEN
                          IF ((V_CDIMPOSTRIB IS NOT NULL) AND (C_PRODUTO.IDTRIMPSTII = '0')) OR
                             (V_CDIMPOSTRIB IS NULL) THEN
                             V_IMPOCONTAB := V_IMPOSINFO + C_PRODUTO.VRADICFECP;
                          ELSE
                             V_IMPOCONTAB := 0;
                             V_IMPOSINFO  := 0;
                          END IF;
                       END IF;
                     ELSIF (C_PRODUTO.IDTRATIMPO = W_D) THEN
                       IF NOT(((C_PRODUTO.IDIMPORECUP = W_S) AND (C_PRODUTO.CDFISCALIT = W_1)) OR
                              ((C_PRODUTO.IDIMPORECUP <> W_S) AND (C_PRODUTO.CDCCTBLATIV IS NOT NULL))) THEN
                          V_IMPOCONTAB := - (V_IMPOSINFO + C_PRODUTO.VRADICFECP);
                       END IF;
                     ELSIF (C_PRODUTO.IDTRATIMPO = W_R) THEN
                       IF (C_PRODUTO.IDIMPORECUP = W_S) THEN
                          IF (C_PRODUTO.CDCCTBLATIV IS NULL) OR
                             (C_PRODUTO.CDFISCALIT <> W_1) THEN

                             V_IMPOCONTAB := - (V_IMPOSINFO + C_PRODUTO.VRADICFECP);
                          END IF;
                       ELSE
                          IF (C_PRODUTO.CDCCTBLATIV IS NULL) THEN
                             V_IMPOCONTAB := - (V_IMPOSINFO + C_PRODUTO.VRADICFECP);
                          END IF;
                       END IF;
                     ELSE
                        V_IMPOCONTAB := 0;
                     END IF;
                  END IF;

                  IF C_PRODUTO.IDTRATIMPO = W_A THEN
                     IF C_PRODUTO.IDTIPCONTAB = W_D THEN
                        UPDATE ITEMPRODUTO
                        SET VRCONTITEM = VRCONTITEM + V_IMPOCONTAB,
                            VRBRUTITEM = VRBRUTITEM + V_IMPOSINFO + C_PRODUTO.VRADICFECP
                        WHERE CDFILIAL    = P_FILIAL   AND
                              NRLANCTONF  = P_LANCTONF AND
                              NRSEQITPROD = C_PRODUTO.NRSEQITPROD;
                     ELSE
                        UPDATE ITEMPRODUTO
                        SET VRBRUTITEM = VRBRUTITEM + V_IMPOSINFO + C_PRODUTO.VRADICFECP
                        WHERE CDFILIAL    = P_FILIAL   AND
                              NRLANCTONF  = P_LANCTONF AND
                              NRSEQITPROD = C_PRODUTO.NRSEQITPROD;
                     END IF;

                  ELSIF C_PRODUTO.IDTRATIMPO = W_D THEN
                     IF C_PRODUTO.IDTIPCONTAB = W_D THEN
                        UPDATE ITEMPRODUTO
                        SET VRBRUTITEM = VRBRUTITEM - V_IMPOSINFO,
                            VRCONTITEM = VRCONTITEM + V_IMPOCONTAB
                        WHERE CDFILIAL    = P_FILIAL   AND
                              NRLANCTONF  = P_LANCTONF AND
                              NRSEQITPROD = C_PRODUTO.NRSEQITPROD;
                     ELSE
                        UPDATE ITEMPRODUTO
                        SET VRBRUTITEM = VRBRUTITEM - V_IMPOSINFO
                        WHERE CDFILIAL    = P_FILIAL   AND
                              NRLANCTONF  = P_LANCTONF AND
                              NRSEQITPROD = C_PRODUTO.NRSEQITPROD;
                     END IF;
                  ELSE
                     IF C_PRODUTO.IDTIPCONTAB = W_D THEN
                        UPDATE ITEMPRODUTO
                        SET VRCONTITEM = VRCONTITEM + V_IMPOCONTAB
                        WHERE CDFILIAL    = P_FILIAL   AND
                              NRLANCTONF  = P_LANCTONF AND
                              NRSEQITPROD = C_PRODUTO.NRSEQITPROD;
                     END IF;
                     IF (C_PRODUTO.IDTRATIMPO = 'R') AND (C_PRODUTO.IDDESCRFONTE = 'N') THEN
                        UPDATE ITEMPRODUTO
                        SET VRBRUTITEM = VRBRUTITEM - V_IMPOSINFO
                        WHERE CDFILIAL    = P_FILIAL   AND
                              NRLANCTONF  = P_LANCTONF AND
                              NRSEQITPROD = C_PRODUTO.NRSEQITPROD;
                     END IF;
                  END IF;
               END IF; -- NAO ALTERAR VALOR CONTÁBIL DO PRODUTO SE O VALOR DOS PRODUTOS FOR ZERO
            END LOOP;

         ELSE
            FOR C_PRODUTO IN (
                              SELECT /*+ index (II,PK_ITEMPROIMPOS)*/
                                     IP.NRSEQITPROD AS NRSEQITPROD, TI.CDIMPOSTOIT AS CDIMPOSTO,
                                     NVL(II.VRPERREDBCIT, 0) VRPERREDBCIT, NVL(II.VRALIQITEM, 0) VRALIQITEM,
                                     NVL(II.VRPARDEDIT, 0) VRPARDEDIT, II.CDFISCALIT, NVL(TI.VRIMPOSIT, 0) VRIMPOSIT,
                                     IM.IDTRATIMPO, IM.IDIMPORECUP, IM.CDCCTBLPASS, IM.CDCCTBLATIV, TI.VRALIQIMPOIT,
                                     II.NRITPROIMPOS, TI.NRSEQITPRO, NVL(TI.IDVALORINFO,W_N) AS IDVALORINFO,
                                     II.IDTRIMPSTII, IM.IDTIPCONTAB, NVL(II.VRBASECALCIT, 0) VRBASECALCIT, NVL(TI.VRADICFECP, 0) VRADICFECP,
                                     P.CDARVPROD, P.CDPRODUTO, IP.VRTOTAITEM, IP.VRDESCITEM, NVL(IM.IDCONTAIMPADIC, 'N')IDCONTAIMPADIC,
                                     IP.IDORIGEMPROD, IM.IDDESCRFONTE
                              FROM ITEMPRODUTO IP, ITEMPROIMPOS II, TRABITPROIMPOS TI, IMPOSTO IM, PRODUTO P
                              WHERE (IP.CDFILIAL     = P_FILIAL)           AND
                                    (IP.NRLANCTONF   = P_LANCTONF)         AND
                                    (TI.CDFILIMPOIT  = IP.CDFILIAL)        AND
                                    (TI.NRLANCIMPOIT = IP.NRLANCTONF)      AND
                                    (TI.NRSEQIMPOIT  = IP.NRSEQITPROD)     AND
                                    (TI.CDIMPOSTOIT  = IM.CDIMPOSTO)       AND
                                    (TI.NRSEQITPRO   = W_1)                AND
                                    (TI.CDFILIMPOIT  = II.CDFILIAL(+))     AND
                                    (TI.NRLANCIMPOIT = II.NRLANCTONF(+))   AND
                                    (TI.NRSEQIMPOIT  = II.NRSEQITPROD(+))  AND
                                    (TI.CDIMPOSTOIT  = II.CDIMPOSTO(+))    AND
                                    (TI.NRSEQITPRO   = II.NRITPROIMPOS(+)) AND
                                    (IP.CDPRODUTO    = P.CDPRODUTO)

                              UNION ALL

                              SELECT /*+ index (II,PK_ITEMPROIMPOS)*/
                                     IP.NRSEQITPROD AS NRSEQITPROD, II.CDIMPOSTO AS CDIMPOSTO,
                                     NVL(II.VRPERREDBCIT, 0) VRPERREDBCIT, NVL(II.VRALIQITEM, 0) VRALIQITEM,
                                     NVL(II.VRPARDEDIT, 0) VRPARDEDIT, II.CDFISCALIT, NVL(II.VRIMPOSTOIT, 0) AS VRIMPOSIT,
                                     IM.IDTRATIMPO, IM.IDIMPORECUP, IM.CDCCTBLPASS, IM.CDCCTBLATIV, II.VRALIQITEM AS VRALIQIMPOIT,
                                     II.NRITPROIMPOS, II.NRSEQITPROD AS NRSEQITPRO, NVL(II.IDVALORINFIT,W_N) AS IDVALORINFO,
                                     II.IDTRIMPSTII, IM.IDTIPCONTAB, NVL(II.VRBASECALCIT, 0) VRBASECALCIT, NVL(II.VRADICFECP, 0) VRADICFECP,
                                     P.CDARVPROD, P.CDPRODUTO, IP.VRTOTAITEM, IP.VRDESCITEM, NVL(IM.IDCONTAIMPADIC, 'N')IDCONTAIMPADIC,
                                     IP.IDORIGEMPROD, IM.IDDESCRFONTE
                              FROM ITEMPRODUTO IP, ITEMPROIMPOS II, IMPOSTO IM, PRODUTO P
                              WHERE (IP.CDFILIAL     = P_FILIAL)           AND
                                    (IP.NRLANCTONF   = P_LANCTONF)         AND
                                    (II.CDFILIAL     = IP.CDFILIAL)        AND
                                    (II.NRLANCTONF   = IP.NRLANCTONF)      AND
                                    (II.NRSEQITPROD  = IP.NRSEQITPROD)     AND
                                    (II.CDIMPOSTO    = IM.CDIMPOSTO)       AND
                                    (II.NRITPROIMPOS = W_1)                AND
                                    (IP.CDPRODUTO    = P.CDPRODUTO)        AND
                                    NOT EXISTS (SELECT T.CDFILIMPOIT
                                                FROM  TRABITPROIMPOS T
                                                WHERE T.CDFILIMPOIT  = IP.CDFILIAL    AND
                                                      T.NRLANCIMPOIT = IP.NRLANCTONF)
                              ORDER BY NRSEQITPROD, CDIMPOSTO DESC) LOOP

               V_IDIMPOBCALTPOP := NULL;

               SELECT TO_CHAR(MAX('S')), NVL(SUM(TI.VRIMPOSIT),0) AS VRIMPOBCALC, NVL(SUM(TI.VRIMPOSIT),0) AS VRIMPOBCINF
                 INTO V_IDIMPOBCALTPOP, V_TOTAIMPBCALC, V_TOTAIMPBCINF
                 FROM ITEMPRODUTO IP, ITEMPROIMPOS II, TRABITPROIMPOS TI, BASECALCTPOPER BC, IMPOSTO I
                WHERE BC.IDENTRSAIDOP = P_ENTRSAID
                  AND BC.CDTIPOOPER = P_TIPOOPER
                  AND BC.CDIMPOSTO = C_PRODUTO.CDIMPOSTO
                  AND IP.CDFILIAL     = P_FILIAL
                  AND IP.NRLANCTONF   = P_LANCTONF
                  AND IP.NRSEQITPROD  = C_PRODUTO.NRSEQITPROD
                  AND TI.CDFILIMPOIT  = P_FILIAL
                  AND TI.NRLANCIMPOIT = P_LANCTONF
                  AND TI.NRSEQIMPOIT  = C_PRODUTO.NRSEQITPROD
                  AND TI.CDIMPOSTOIT  = BC.CDIMPOBCALC
                  AND II.CDIMPOSTO    = BC.CDIMPOBCALC
                  AND TI.CDFILIMPOIT  = II.CDFILIAL(+)
                  AND TI.NRLANCIMPOIT = II.NRLANCTONF(+)
                  AND TI.NRSEQIMPOIT  = II.NRSEQITPROD(+)
                  AND (NVL(IP.IDUTVRPAUTAPROD, 'N') = 'N')
                  AND ((SUBSTR(IP.CDSITUTRIBPR,2,2) = BC.CDCSTIMPOTPOP)  OR (BC.CDCSTIMPOTPOP IS NULL))
                  AND ((SUBSTR(IP.CDFISOPEITEM,2,10) = BC.CDCFOPIMPOTPOP) OR (BC.CDCFOPIMPOTPOP IS NULL))
                  AND ((C_PRODUTO.CDFISCALIT        = BC.CDFISCIMPOTPOP) OR (BC.CDFISCIMPOTPOP IS NULL))
                  AND BC.CDIMPOBCALC = I.CDIMPOSTO
                  AND I.IDTRATIMPO <> 'D';

               IF V_IDIMPOBCALTPOP IS NULL THEN

                  SELECT NVL(SUM(TI.VRIMPOSIT),0) AS VRIMPOBCALC, NVL(SUM(TI.VRIMPOSIT),0) AS VRIMPOBCINF
                  INTO V_TOTAIMPBCALC, V_TOTAIMPBCINF
                  FROM ITEMPRODUTO IP, ITEMPROIMPOS II, TRABITPROIMPOS TI, BASECALC BC, IMPOSTO I
                  WHERE (BC.CDIMPOSTO    = C_PRODUTO.CDIMPOSTO)    AND
                        (IP.CDFILIAL     = P_FILIAL)               AND
                        (IP.NRLANCTONF   = P_LANCTONF)             AND
                        (IP.NRSEQITPROD  = C_PRODUTO.NRSEQITPROD)  AND
                        (TI.CDFILIMPOIT  = P_FILIAL)               AND
                        (TI.NRLANCIMPOIT = P_LANCTONF)             AND
                        (TI.NRSEQIMPOIT  = C_PRODUTO.NRSEQITPROD)  AND
                        (TI.CDIMPOSTOIT  = BC.CDIMPOBCALC)         AND
                        (II.CDIMPOSTO    = BC.CDIMPOBCALC)         AND
                        (TI.CDFILIMPOIT  = II.CDFILIAL(+))         AND
                        (TI.NRLANCIMPOIT = II.NRLANCTONF(+))       AND
                        (TI.NRSEQIMPOIT  = II.NRSEQITPROD(+))      AND
                        (NVL(IP.IDUTVRPAUTAPROD, 'N') = 'N')       AND
                        ((SUBSTR(IP.CDSITUTRIBPR,2,2) = BC.CDCSTIMPO)  OR (BC.CDCSTIMPO  IS NULL)) AND
                        ((SUBSTR(IP.CDFISOPEITEM,2,10) = BC.CDCFOPIMPO) OR (BC.CDCFOPIMPO IS NULL)) AND
                        ((C_PRODUTO.CDFISCALIT        = BC.CDFISCIMPO) OR (BC.CDFISCIMPO IS NULL)) AND
                        (BC.IDTIPOBCALC   = 'I')        AND
                        (BC.CDIMPOBCALC = I.CDIMPOSTO)  AND
                        (I.IDTRATIMPO <> 'D');
               END IF;

               V_IDIMBCALTPOPDE := NULL;

               SELECT TO_CHAR(MAX('S')), (NVL(SUM(VRIMPOSTOIT),0)*-1) AS VRIMPOBCALC
                 INTO V_IDIMBCALTPOPDE, V_TOTAIMPBCDES
                 FROM ITEMPRODUTO IP, ITEMPROIMPOS II, TRABITPROIMPOS TI, BASECALCTPOPER BC, IMPOSTO I
                WHERE BC.IDENTRSAIDOP = P_ENTRSAID
                  AND BC.CDTIPOOPER = P_TIPOOPER
                  AND BC.CDIMPOSTO = C_PRODUTO.CDIMPOSTO
                  AND IP.CDFILIAL     = P_FILIAL
                  AND IP.NRLANCTONF   = P_LANCTONF
                  AND IP.NRSEQITPROD  = C_PRODUTO.NRSEQITPROD
                  AND TI.CDFILIMPOIT  = P_FILIAL
                  AND TI.NRLANCIMPOIT = P_LANCTONF
                  AND TI.NRSEQIMPOIT  = C_PRODUTO.NRSEQITPROD
                  AND TI.CDIMPOSTOIT  = BC.CDIMPOBCALC
                  AND II.CDIMPOSTO    = BC.CDIMPOBCALC
                  AND TI.CDFILIMPOIT  = II.CDFILIAL(+)
                  AND TI.NRLANCIMPOIT = II.NRLANCTONF(+)
                  AND TI.NRSEQIMPOIT  = II.NRSEQITPROD(+)
                  AND (NVL(IP.IDUTVRPAUTAPROD, 'N') = 'N')
                  AND ((SUBSTR(IP.CDSITUTRIBPR,2,2) = BC.CDCSTIMPOTPOP)  OR (BC.CDCSTIMPOTPOP IS NULL))
                  AND ((SUBSTR(IP.CDFISOPEITEM,2,10) = BC.CDCFOPIMPOTPOP) OR (BC.CDCFOPIMPOTPOP IS NULL))
                  AND ((C_PRODUTO.CDFISCALIT        = BC.CDFISCIMPOTPOP) OR (BC.CDFISCIMPOTPOP IS NULL))
                  AND BC.CDIMPOBCALC = I.CDIMPOSTO
                  AND I.IDTRATIMPO = 'D';

               IF V_IDIMBCALTPOPDE IS NULL THEN

                  SELECT (NVL(SUM(VRIMPOSTOIT),0)*-1) AS VRIMPOBCALC INTO V_TOTAIMPBCDES
                  FROM ITEMPRODUTO IP, ITEMPROIMPOS II, TRABITPROIMPOS TI, BASECALC BC, IMPOSTO I
                  WHERE (BC.CDIMPOSTO    = C_PRODUTO.CDIMPOSTO)    AND
                        (IP.CDFILIAL     = P_FILIAL)               AND
                        (IP.NRLANCTONF   = P_LANCTONF)             AND
                        (IP.NRSEQITPROD  = C_PRODUTO.NRSEQITPROD)  AND
                        (TI.CDFILIMPOIT  = P_FILIAL)               AND
                        (TI.NRLANCIMPOIT = P_LANCTONF)             AND
                        (TI.NRSEQIMPOIT  = C_PRODUTO.NRSEQITPROD)  AND
                        (TI.CDIMPOSTOIT  = BC.CDIMPOBCALC)         AND
                        (II.CDIMPOSTO    = BC.CDIMPOBCALC)         AND
                        (TI.CDFILIMPOIT  = II.CDFILIAL(+))         AND
                        (TI.NRLANCIMPOIT = II.NRLANCTONF(+))       AND
                        (TI.NRSEQIMPOIT  = II.NRSEQITPROD(+))      AND
                        (NVL(IP.IDUTVRPAUTAPROD, 'N') = 'N')       AND
                        ((SUBSTR(IP.CDSITUTRIBPR,2,2) = BC.CDCSTIMPO)  OR (BC.CDCSTIMPO  IS NULL)) AND
                        ((SUBSTR(IP.CDFISOPEITEM,2,10) = BC.CDCFOPIMPO) OR (BC.CDCFOPIMPO IS NULL)) AND
                        ((C_PRODUTO.CDFISCALIT        = BC.CDFISCIMPO) OR (BC.CDFISCIMPO IS NULL)) AND
                        (BC.IDTIPOBCALC   = 'I')        AND
                        (BC.CDIMPOBCALC = I.CDIMPOSTO)  AND
                        (I.IDTRATIMPO = 'D');
               END IF;

               V_IMPOSINFO := C_PRODUTO.VRIMPOSIT;

               V_CDIMPOSTRIB := NULL;
               V_VRIMPOSTOST := 0;

               FOR C_ICMSST IN (SELECT CDIMPOSTO
                                       FROM IMPOSTO
                                      WHERE CDIMPOSTRIB = C_PRODUTO.CDIMPOSTO)
               LOOP
                  V_CDIMPOSTRIB := V_CDIMPOSTRIB||C_ICMSST.CDIMPOSTO||'_';
               END LOOP;

               V_IMPOSTRIBCOMPLANC := NULL;

               IF (V_CDIMPOSTRIB IS NOT NULL)  THEN
                  SELECT MAX(CDIMPOSTOIT)
                    INTO V_IMPOSTRIBCOMPLANC
                    FROM TRABITPROIMPOS
                   WHERE CDFILIMPOIT  = P_FILIAL
                     AND NRLANCIMPOIT = P_LANCTONF
                     AND (INSTR(V_CDIMPOSTRIB,CDIMPOSTOIT||'_') > 0);
               END IF;

               IF V_IMPOSTRIBCOMPLANC IS NULL THEN
                  V_CDIMPOSTRIB := NULL;
               END IF;

               IF ((V_IDGERNFIGUALXML = 'N') AND (C_PRODUTO.IDVALORINFO <> W_S)) OR (V_IDNFGERADAVIAXML = 'N') THEN
                  /*ALTERAÇÃO 01/02/2011*/
                  IF (NOT(V_TOTAIMPBCALC IS NULL) OR (V_TOTAIMPBCALC <> 0)) OR
                     (NOT(V_TOTAIMPBCDES IS NULL) OR (V_TOTAIMPBCDES <> 0)) OR
                     (V_CDIMPOSTRIB IS NOT NULL) THEN

                     IF V_CDIMPOSTRIB IS NULL THEN
                        V_TAXABASECALC := (100 - C_PRODUTO.VRPERREDBCIT)/100;
                        V_TAXAALIQUOTA := (C_PRODUTO.VRALIQITEM/100);
                        V_IMPOSINFO    := V_IMPOSINFO + (((V_TOTAIMPBCALC + V_TOTAIMPBCDES) * V_TAXABASECALC) * V_TAXAALIQUOTA);

                        UPDATE ITEMPROIMPOS
                           SET VRBASECALCIT = VRBASECALCIT + ((V_TOTAIMPBCALC + V_TOTAIMPBCDES) * V_TAXABASECALC),
                               VRIMPOSTOIT  = VRIMPOSTOIT  + (((V_TOTAIMPBCALC + V_TOTAIMPBCDES) * V_TAXABASECALC) * V_TAXAALIQUOTA)
                         WHERE (CDFILIAL     = P_FILIAL)              AND
                               (NRLANCTONF   = P_LANCTONF)            AND
                               (NRSEQITPROD  = C_PRODUTO.NRSEQITPROD) AND
                               (CDIMPOSTO    = C_PRODUTO.CDIMPOSTO)   AND
                               (NRITPROIMPOS = C_PRODUTO.NRITPROIMPOS);

                        UPDATE TRABITPROIMPOS
                           SET VRBCALCIMPOIT  = VRBCALCIMPOIT + (V_TOTAIMPBCINF * V_TAXABASECALC),
                               VRIMPOSIT      = V_IMPOSINFO
                           WHERE CDFILIMPOIT  = P_FILIAL              AND
                                 NRLANCIMPOIT = P_LANCTONF            AND
                                 NRSEQIMPOIT  = C_PRODUTO.NRSEQITPROD AND
                                 CDIMPOSTOIT  = C_PRODUTO.CDIMPOSTO   AND
                                 NRSEQITPRO   = C_PRODUTO.NRSEQITPRO;

                        UPDATE ITEMPROIMPOS
                           SET VRBASECALCIT = VRBASECALCIT + (V_TOTAIMPBCALC * ((100 - VRPERREDBCIT)/100)),
                               VRIMPOSTOIT  = VRIMPOSTOIT  + ((V_TOTAIMPBCALC * ((100 - VRPERREDBCIT)/100)) * (VRALIQITEM/100))
                         WHERE (CDFILIAL     = P_FILIAL)              AND
                               (NRLANCTONF   = P_LANCTONF)            AND
                               (NRSEQITPROD  = C_PRODUTO.NRSEQITPROD) AND
                               (CDIMPOSTO    = C_PRODUTO.CDIMPOSTO)   AND
                               (NRITPROIMPOS = W_2);

                        UPDATE TRABITPROIMPOS
                           SET VRBCALCIMPOIT  = VRBCALCIMPOIT + (V_TOTAIMPBCINF * ((100 - VRREDBCIMPOIT)/100)),
                               VRIMPOSIT      = VRIMPOSIT + ((V_TOTAIMPBCINF * ((100 - VRREDBCIMPOIT)/100)) * (VRALIQIMPOIT/100))
                         WHERE CDFILIMPOIT  = P_FILIAL              AND
                               NRLANCIMPOIT = P_LANCTONF            AND
                               NRSEQIMPOIT  = C_PRODUTO.NRSEQITPROD AND
                               CDIMPOSTOIT  = C_PRODUTO.CDIMPOSTO   AND
                               NRSEQITPRO   = W_2;

                        UPDATE TRABITPROIMPOS
                           SET VRBCALCIMPOIT  = VRBCALCIMPOIT + (V_TOTAIMPBCINF * V_TAXABASECALC),
                               VRIMPOSIT      = VRIMPOSIT + ((V_TOTAIMPBCINF * V_TAXABASECALC) * (VRALIQIMPOIT/100))
                         WHERE CDFILIMPOIT  = P_FILIAL              AND
                               NRLANCIMPOIT = P_LANCTONF            AND
                               NRSEQIMPOIT  = C_PRODUTO.NRSEQITPROD AND
                               CDIMPOSTOIT  = C_PRODUTO.CDIMPOSTO   AND
                               NRSEQITPRO   = W_3;

                     ELSE
                        SELECT NVL(MAX(IDVRIMPSTRIB), 'N')
                          INTO V_IDVRIMPSTRIB
                          FROM TRABITPROIMPOS I, IMPOSTO II
                         WHERE (CDFILIMPOIT  = P_FILIAL)
                           AND (NRLANCIMPOIT = P_LANCTONF)
                           AND (NRSEQIMPOIT  = C_PRODUTO.NRSEQITPROD)
                           AND (INSTR(V_CDIMPOSTRIB,II.CDIMPOSTO||'_') > 0)
                           AND (I.CDIMPOSTOIT = II.CDIMPOSTO);

                        IF (C_PRODUTO.IDTRIMPSTII = '1') OR (NVL(V_IDVRIMPSTRIB,'N') = 'N') OR (NVL(V_IDCONSDIFALIQ , W_N) = 'S') THEN
                           V_VRIMPOSTOST := 0;
                        ELSE
                           BEGIN
                              SELECT NVL(VRIMPOSIT,0)
                              INTO V_VRIMPOSTOST
                              FROM TRABITPROIMPOS I
                              WHERE (CDFILIMPOIT  = P_FILIAL)               AND
                                    (NRLANCIMPOIT = P_LANCTONF)             AND
                                    (NRSEQIMPOIT  = C_PRODUTO.NRSEQITPROD)  AND
                                    (INSTR(V_CDIMPOSTRIB,CDIMPOSTOIT||'_') > 0) AND
                                    (NRSEQITPRO   = W_1);
                           EXCEPTION
                              WHEN NO_DATA_FOUND THEN
                                 V_VRIMPOSTOST := 0;
                           END;
                        END IF;


                        -- VERIFICA SE POSSUI PERCENTUAL DE REDUÇÃO

                        V_UTGRUPFISCS := NULL;
                        V_LIQUIITEM   := 0;

                        V_LIQUIITEM := C_PRODUTO.VRTOTAITEM - C_PRODUTO.VRDESCITEM;

                        SELECT MAX(IDGRUPFISSRV)
                          INTO V_UTGRUPFISCS
                          FROM IMPOSTO
                         WHERE CDIMPOSTO = C_PRODUTO.CDIMPOSTO;

                        IF V_UTGRUPFISCS = 'S' THEN
                           V_CDGRPFISCSV := NULL;
                           SELECT MAX(CDGRUPOFISC)
                             INTO V_CDGRPFISCSV
                             FROM SERVCLIE SC, SERVICO S
                            WHERE SC.CDFILIAL = V_CDFILIEMIT
                              AND SC.CDCLIENTE = P_FORNECED
                              AND SC.CDFILIAL = S.CDFILIAL
                              AND SC.CDSERVFILI = S.CDSERVFILI
                              AND S.CDPRODUTO = C_PRODUTO.CDPRODUTO;

                           IF V_CDGRPFISCSV IS NULL THEN
                              SELECT MAX(CDGRUPOFISC)
                                INTO V_CDGRPFISCSV
                                FROM CLIENFILIAL
                               WHERE CDFILIAL = V_CDFILIEMIT
                                 AND CDCLIENTE = P_FORNECED;
                           END IF;

                           CONSULTA_ALIQUOTA(C_PRODUTO.CDIMPOSTO, P_ENTRSAID, P_EMPRESA, C_PRODUTO.CDARVPROD, P_INSCESTA, V_PAISORIG,
                                             V_ESTAORIG, V_PAISDEST, V_ESTADEST, V_MUNIDEST, V_LIQUIITEM, P_INIVALID, P_FILIAL, P_LANCTONF, V_CDGRPFISCSV, P_TIPOOPER,
                                             NULL, NULL, NULL, NULL, P_FORNECED, NULL, C_PRODUTO.IDORIGEMPROD);
                        ELSE
                           CONSULTA_ALIQUOTA(C_PRODUTO.CDIMPOSTO, P_ENTRSAID, P_EMPRESA, C_PRODUTO.CDARVPROD, P_INSCESTA, V_PAISORIG,
                                             V_ESTAORIG, V_PAISDEST, V_ESTADEST, V_MUNIDEST, V_LIQUIITEM, P_INIVALID, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC, P_TIPOOPER,
                                             NULL, NULL, NULL, NULL, P_FORNECED, NULL, C_PRODUTO.IDORIGEMPROD);
                        END IF;

                        V_PREDBCTMP  := 0;
                        V_PBCSUBTRIB := 0;

                        SELECT (100 - (NVL(MAX(VRPREDBCTMP),0)))/100, NVL(MAX(VRPBCSTTMP),0)
                          INTO V_PREDBCTMP, V_PBCSUBTRIB
                          FROM ALIQTEMP
                         WHERE NRALIQTEMP = V_ALIQTEMP;

                        V_TAXABASECALC := 1 + (C_PRODUTO.VRPERREDBCIT)/100;
                        V_TAXAALIQUOTA := (C_PRODUTO.VRALIQITEM/100);

                        IF V_PBCSUBTRIB <> 0 THEN
                           IF (V_IDVALORINFO <> 'S') THEN
                              V_IMPOSINFO := ((C_PRODUTO.VRBASECALCIT+ ((V_TOTAIMPBCALC + V_TOTAIMPBCDES) * V_TAXABASECALC * V_PREDBCTMP)) * V_TAXAALIQUOTA);
                           END IF;
                        ELSE
                           IF (V_IDVALORINFO <> 'S') THEN
                              V_IMPOSINFO := ((C_PRODUTO.VRBASECALCIT+ ((V_TOTAIMPBCALC + V_TOTAIMPBCDES) * V_TAXABASECALC)) * V_TAXAALIQUOTA);
                           END IF;
                        END IF;

                        DELETE ALIQTEMP
                        WHERE NRALIQTEMP = V_ALIQTEMP;

                        IF V_VRIMPOSTOST > V_IMPOSINFO THEN
                           V_IMPOSINFO := 0;

                           UPDATE ITEMPROIMPOS
                           SET VRBASECALCIT = VRBASECALCIT + ((V_TOTAIMPBCALC + V_TOTAIMPBCDES) * V_TAXABASECALC),
                               VRIMPOSTOIT  = V_IMPOSINFO
                           WHERE (CDFILIAL     = P_FILIAL)              AND
                                 (NRLANCTONF   = P_LANCTONF)            AND
                                 (NRSEQITPROD  = C_PRODUTO.NRSEQITPROD) AND
                                 (CDIMPOSTO    = C_PRODUTO.CDIMPOSTO)   AND
                                 (NRITPROIMPOS = C_PRODUTO.NRITPROIMPOS);

                           UPDATE TRABITPROIMPOS
                              SET VRBCALCIMPOIT  = VRBCALCIMPOIT + (V_TOTAIMPBCINF * V_TAXABASECALC),
                                  VRIMPOSIT      = V_IMPOSINFO
                            WHERE CDFILIMPOIT  = P_FILIAL               AND
                                   NRLANCIMPOIT = P_LANCTONF            AND
                                   NRSEQIMPOIT  = C_PRODUTO.NRSEQITPROD AND
                                   CDIMPOSTOIT  = C_PRODUTO.CDIMPOSTO   AND
                                   NRSEQITPRO   = C_PRODUTO.NRSEQITPRO;

                           UPDATE ITEMPROIMPOS
                              SET VRBASECALCIT = VRBASECALCIT + (V_TOTAIMPBCALC * ((100 - VRPERREDBCIT)/100)),
                                  VRIMPOSTOIT  = VRIMPOSTOIT  + ((V_TOTAIMPBCALC * ((100 - VRPERREDBCIT)/100)) * (VRALIQITEM/100))
                            WHERE (CDFILIAL     = P_FILIAL)              AND
                                  (NRLANCTONF   = P_LANCTONF)            AND
                                  (NRSEQITPROD  = C_PRODUTO.NRSEQITPROD) AND
                                  (CDIMPOSTO    = C_PRODUTO.CDIMPOSTO)   AND
                                  (NRITPROIMPOS = W_2);

                           UPDATE TRABITPROIMPOS
                              SET VRBCALCIMPOIT  = VRBCALCIMPOIT + (V_TOTAIMPBCINF * ((100 - VRREDBCIMPOIT)/100)),
                                  VRIMPOSIT      = VRIMPOSIT + ((V_TOTAIMPBCINF * ((100 - VRREDBCIMPOIT)/100)) * (VRALIQIMPOIT/100))
                            WHERE CDFILIMPOIT  = P_FILIAL              AND
                                  NRLANCIMPOIT = P_LANCTONF            AND
                                  NRSEQIMPOIT  = C_PRODUTO.NRSEQITPROD AND
                                  CDIMPOSTOIT  = C_PRODUTO.CDIMPOSTO   AND
                                  NRSEQITPRO   = W_2;

                           UPDATE TRABITPROIMPOS
                              SET VRBCALCIMPOIT  = VRBCALCIMPOIT + (V_TOTAIMPBCINF * V_TAXABASECALC),
                                  VRIMPOSIT      = VRIMPOSIT + ((V_TOTAIMPBCINF * V_TAXABASECALC) * (VRALIQIMPOIT/100))
                            WHERE CDFILIMPOIT  = P_FILIAL              AND
                                  NRLANCIMPOIT = P_LANCTONF            AND
                                  NRSEQIMPOIT  = C_PRODUTO.NRSEQITPROD AND
                                  CDIMPOSTOIT  = C_PRODUTO.CDIMPOSTO   AND
                                  NRSEQITPRO   = W_3;

                        ELSE
                           IF (V_IDVALORINFO <> 'S') THEN
                              V_IMPOSINFO := V_IMPOSINFO - V_VRIMPOSTOST;
                           END IF;

                           UPDATE ITEMPROIMPOS
                              SET VRBASECALCIT = VRBASECALCIT + ((V_TOTAIMPBCALC + V_TOTAIMPBCDES) * V_TAXABASECALC),
                                  VRIMPOSTOIT  = V_IMPOSINFO
                            WHERE (CDFILIAL     = P_FILIAL)              AND
                                  (NRLANCTONF   = P_LANCTONF)            AND
                                  (NRSEQITPROD  = C_PRODUTO.NRSEQITPROD) AND
                                  (CDIMPOSTO    = C_PRODUTO.CDIMPOSTO)   AND
                                  (NRITPROIMPOS = C_PRODUTO.NRITPROIMPOS);

                           UPDATE TRABITPROIMPOS
                              SET VRBCALCIMPOIT  = VRBCALCIMPOIT + (V_TOTAIMPBCINF * V_TAXABASECALC),
                                  VRIMPOSIT      = V_IMPOSINFO
                            WHERE CDFILIMPOIT  = P_FILIAL              AND
                                  NRLANCIMPOIT = P_LANCTONF            AND
                                  NRSEQIMPOIT  = C_PRODUTO.NRSEQITPROD AND
                                  CDIMPOSTOIT  = C_PRODUTO.CDIMPOSTO   AND
                                  NRSEQITPRO   = C_PRODUTO.NRSEQITPRO;

                           UPDATE ITEMPROIMPOS
                              SET VRBASECALCIT = VRBASECALCIT + (V_TOTAIMPBCALC * ((100 - VRPERREDBCIT)/100)),
                                  VRIMPOSTOIT  = VRIMPOSTOIT  + ((V_TOTAIMPBCALC * ((100 - VRPERREDBCIT)/100)) * (VRALIQITEM/100))
                            WHERE (CDFILIAL     = P_FILIAL)              AND
                                  (NRLANCTONF   = P_LANCTONF)            AND
                                  (NRSEQITPROD  = C_PRODUTO.NRSEQITPROD) AND
                                  (CDIMPOSTO    = C_PRODUTO.CDIMPOSTO)   AND
                                  (NRITPROIMPOS = W_2);

                           UPDATE TRABITPROIMPOS
                              SET VRBCALCIMPOIT  = VRBCALCIMPOIT + (V_TOTAIMPBCINF * ((100 - VRREDBCIMPOIT)/100)),
                                  VRIMPOSIT      = VRIMPOSIT + ((V_TOTAIMPBCINF * ((100 - VRREDBCIMPOIT)/100)) * (VRALIQIMPOIT/100))
                            WHERE CDFILIMPOIT  = P_FILIAL              AND
                                  NRLANCIMPOIT = P_LANCTONF            AND
                                  NRSEQIMPOIT  = C_PRODUTO.NRSEQITPROD AND
                                  CDIMPOSTOIT  = C_PRODUTO.CDIMPOSTO   AND
                                  NRSEQITPRO   = W_2;

                           UPDATE TRABITPROIMPOS
                              SET VRBCALCIMPOIT  = VRBCALCIMPOIT + (V_TOTAIMPBCINF * V_TAXABASECALC),
                                  VRIMPOSIT      = VRIMPOSIT + ((V_TOTAIMPBCINF * V_TAXABASECALC) * (VRALIQIMPOIT/100))
                            WHERE CDFILIMPOIT  = P_FILIAL              AND
                                  NRLANCIMPOIT = P_LANCTONF            AND
                                  NRSEQIMPOIT  = C_PRODUTO.NRSEQITPROD AND
                                  CDIMPOSTOIT  = C_PRODUTO.CDIMPOSTO   AND
                                  NRSEQITPRO   = W_3;
                        END IF;
                     END IF;
                  END IF;
               END IF;

               /* Utiliza o próprio valor do imposto na sua base de cálculo */
               SELECT NVL(MAX(IDUTILPVRIMPBC), 'N'), MAX(IDTRATIMPO)
                 INTO V_IDUTILPVRIMPBC, V_IDTRATIMPO
                 FROM IMPOSTO
                WHERE CDIMPOSTO = C_PRODUTO.CDIMPOSTO;

               IF V_IDUTILPVRIMPBC = 'S' THEN

                  IF V_CDIMPOSTRIB IS NULL THEN
                     BEGIN
                        SELECT VRIMPOSTOIT
                          INTO V_VRIMPANTE
                          FROM ITEMPROIMPOS T
                         WHERE CDFILIAL     = P_FILIAL
                           AND NRLANCTONF   = P_LANCTONF
                           AND NRSEQITPROD  = C_PRODUTO.NRSEQITPROD
                           AND CDIMPOSTO    = C_PRODUTO.CDIMPOSTO
                           AND NRITPROIMPOS = C_PRODUTO.NRITPROIMPOS;
                     EXCEPTION
                        WHEN NO_DATA_FOUND THEN
                           V_VRIMPANTE := 0;
                     END;

                     UPDATE ITEMPROIMPOS
                        SET VRBASECALCIT = (VRBASECALCIT )/((100 -VRALIQITEM)/100),
                            VRIMPOSTOIT  = ((VRBASECALCIT)/((100 -VRALIQITEM)/100))*(VRALIQITEM/100)
                      WHERE CDFILIAL     = P_FILIAL
                        AND NRLANCTONF   = P_LANCTONF
                        AND NRSEQITPROD  = C_PRODUTO.NRSEQITPROD
                        AND CDIMPOSTO    = C_PRODUTO.CDIMPOSTO
                        AND NRITPROIMPOS = C_PRODUTO.NRITPROIMPOS;

                     UPDATE TRABITPROIMPOS
                        SET VRBCALCIMPOIT = (VRBCALCIMPOIT )/((100 -VRALIQIMPOIT)/100),
                            VRIMPOSIT     = ((VRBCALCIMPOIT)/((100 -VRALIQIMPOIT)/100))*(VRALIQIMPOIT/100)
                      WHERE CDFILIMPOIT  = P_FILIAL
                        AND NRLANCIMPOIT = P_LANCTONF
                        AND NRSEQIMPOIT  = C_PRODUTO.NRSEQITPROD
                        AND CDIMPOSTOIT  = C_PRODUTO.CDIMPOSTO
                        AND NRSEQITPRO   = C_PRODUTO.NRSEQITPRO;

                     BEGIN
                        SELECT VRIMPOSTOIT
                          INTO V_VRIMPAPOS
                          FROM ITEMPROIMPOS
                         WHERE CDFILIAL     = P_FILIAL
                           AND NRLANCTONF   = P_LANCTONF
                           AND NRSEQITPROD  = C_PRODUTO.NRSEQITPROD
                           AND CDIMPOSTO    = C_PRODUTO.CDIMPOSTO
                           AND NRITPROIMPOS = C_PRODUTO.NRITPROIMPOS;
                     EXCEPTION
                        WHEN NO_DATA_FOUND THEN
                           V_VRIMPAPOS := 0;
                     END;

                     IF V_IDTRATIMPO = 'A' THEN
                        UPDATE ITEMPRODUTO
                           SET VRBRUTITEM = VRBRUTITEM + (V_VRIMPAPOS - V_VRIMPANTE)
                         WHERE CDFILIAL     = P_FILIAL
                           AND NRLANCTONF   = P_LANCTONF
                           AND NRSEQITPROD  = C_PRODUTO.NRSEQITPROD;
                     END IF;
                  END IF;
               END IF;

               V_IMPOCONTAB := 0;

               IF (P_TIPOOPER = '03') THEN
                  SELECT NVL(MAX(VRTOTAITEM),0)
                    INTO V_TOTALITEMCOMP
                    FROM ITEMPRODUTO
                   WHERE CDFILIAL    = P_FILIAL
                     AND NRLANCTONF  = P_LANCTONF
                     AND NRSEQITPROD = C_PRODUTO.NRSEQITPROD;
               END IF;

               IF NOT(P_TIPOOPER = '03' AND V_TOTALITEMCOMP = 0 AND C_PRODUTO.IDTRATIMPO <> W_A) THEN
                  IF (C_PRODUTO.IDIMPORECUP = W_S) THEN
                     IF (C_PRODUTO.CDFISCALIT = W_1) THEN
                        IF (C_PRODUTO.CDCCTBLATIV IS NOT NULL) THEN
                           IF C_PRODUTO.IDTRATIMPO = W_V THEN
                              V_IMPOCONTAB := - (V_IMPOSINFO + C_PRODUTO.VRADICFECP);
                           END IF;
                        END IF;
                     ELSE
                        IF C_PRODUTO.IDTRATIMPO = W_A THEN
                           IF ((V_CDIMPOSTRIB IS NOT NULL) AND (C_PRODUTO.IDTRIMPSTII = '0')) OR
                              (V_CDIMPOSTRIB IS NULL) THEN
                              V_IMPOCONTAB := (V_IMPOSINFO + C_PRODUTO.VRADICFECP);
                           ELSE
                              V_IMPOCONTAB := 0;
                              V_IMPOSINFO  := 0;
                           END IF;
                        ELSIF C_PRODUTO.IDTRATIMPO IN (W_D,W_R) THEN
                           V_IMPOCONTAB := - (V_IMPOSINFO + C_PRODUTO.VRADICFECP);
                        END IF;
                     END IF;
                  ELSE
                     IF NOT(C_PRODUTO.CDCCTBLPASS IS NULL) THEN
                        IF C_PRODUTO.IDTRATIMPO = W_V THEN
                           IF C_PRODUTO.IDCONTAIMPADIC = 'N' THEN
                              V_IMPOCONTAB := - (V_IMPOSINFO + C_PRODUTO.VRADICFECP);
                           END IF;
                        ELSE
                           IF C_PRODUTO.IDTRATIMPO = W_A THEN
                               SELECT NVL(MAX(IDACRPRODENTRNF), 'N')
                               INTO V_IDACRPRODENTRNF
                               FROM IMPOSTO
                               WHERE CDIMPOSTO = C_PRODUTO.CDIMPOSTO;

                               IF V_IDACRPRODENTRNF = 'S' THEN
                                  V_IMPOCONTAB := (V_IMPOSINFO + C_PRODUTO.VRADICFECP);
                               END IF;
                           ELSIF (C_PRODUTO.IDTRATIMPO = W_R) AND (C_PRODUTO.IDDESCRFONTE = 'N') THEN
                              V_IMPOCONTAB := - (V_IMPOSINFO + C_PRODUTO.VRADICFECP);
                           END IF;
                        END IF;
                     ELSE
                        IF C_PRODUTO.IDTRATIMPO = W_A THEN
                           IF ((V_CDIMPOSTRIB IS NOT NULL) AND (C_PRODUTO.IDTRIMPSTII = '0')) OR
                              (V_CDIMPOSTRIB IS NULL) THEN
                              V_IMPOCONTAB := (V_IMPOSINFO + C_PRODUTO.VRADICFECP);
                           ELSE
                              V_IMPOCONTAB := 0;
                              V_IMPOSINFO  := 0;
                           END IF;
                        ELSIF C_PRODUTO.IDTRATIMPO IN (W_D,W_R) THEN
                           V_IMPOCONTAB := - (V_IMPOSINFO + C_PRODUTO.VRADICFECP);
                        END IF;
                     END IF;
                  END IF;

                  IF (V_IDOPERDEVONF = W_S) OR (P_TIPOOPER = '16') THEN
                     IF (C_PRODUTO.IDTRATIMPO = W_A) THEN
                       IF NOT (((C_PRODUTO.IDIMPORECUP = W_S)  AND (C_PRODUTO.CDFISCALIT = W_1)) OR
                               ((C_PRODUTO.IDIMPORECUP <> W_S) AND (C_PRODUTO.CDCCTBLATIV IS NOT NULL))) THEN
                          IF ((V_CDIMPOSTRIB IS NOT NULL) AND (C_PRODUTO.IDTRIMPSTII = '0')) OR
                             (V_CDIMPOSTRIB IS NULL) THEN
                             V_IMPOCONTAB := (V_IMPOSINFO + C_PRODUTO.VRADICFECP);
                          ELSE
                             V_IMPOCONTAB := 0;
                             V_IMPOSINFO  := 0;
                          END IF;
                       END IF;
                     ELSIF (C_PRODUTO.IDTRATIMPO = W_D) THEN
                       IF NOT(((C_PRODUTO.IDIMPORECUP = W_S) AND (C_PRODUTO.CDFISCALIT = W_1)) OR
                              ((C_PRODUTO.IDIMPORECUP <> W_S) AND (C_PRODUTO.CDCCTBLATIV IS NOT NULL))) THEN
                          V_IMPOCONTAB := - (V_IMPOSINFO + C_PRODUTO.VRADICFECP);
                       END IF;
                     ELSIF (C_PRODUTO.IDTRATIMPO = W_R) THEN
                       IF (C_PRODUTO.IDIMPORECUP = W_S) THEN
                          IF (C_PRODUTO.CDCCTBLATIV IS NULL) OR
                             (C_PRODUTO.CDFISCALIT <> W_1) THEN

                             V_IMPOCONTAB := - (V_IMPOSINFO + C_PRODUTO.VRADICFECP);
                          END IF;
                       ELSE
                          IF (C_PRODUTO.CDCCTBLATIV IS NULL) THEN
                             V_IMPOCONTAB := - (V_IMPOSINFO + C_PRODUTO.VRADICFECP);
                          END IF;
                       END IF;
                     ELSE
                        V_IMPOCONTAB := 0;
                     END IF;
                  END IF;

                  IF C_PRODUTO.IDTRATIMPO = W_A THEN
                     IF C_PRODUTO.IDTIPCONTAB = W_D THEN
                        UPDATE ITEMPRODUTO
                        SET VRCONTITEM = VRCONTITEM + V_IMPOCONTAB,
                            VRBRUTITEM = VRBRUTITEM + V_IMPOSINFO
                        WHERE CDFILIAL    = P_FILIAL   AND
                              NRLANCTONF  = P_LANCTONF AND
                              NRSEQITPROD = C_PRODUTO.NRSEQITPROD;
                     ELSE
                        UPDATE ITEMPRODUTO
                        SET VRBRUTITEM = VRBRUTITEM + V_IMPOSINFO
                        WHERE CDFILIAL    = P_FILIAL   AND
                              NRLANCTONF  = P_LANCTONF AND
                              NRSEQITPROD = C_PRODUTO.NRSEQITPROD;
                     END IF;

                  ELSIF C_PRODUTO.IDTRATIMPO = W_D THEN
                     IF C_PRODUTO.IDTIPCONTAB = W_D THEN
                        UPDATE ITEMPRODUTO
                        SET VRBRUTITEM = VRBRUTITEM - V_IMPOSINFO,
                            VRCONTITEM = VRCONTITEM + V_IMPOCONTAB
                        WHERE CDFILIAL    = P_FILIAL   AND
                              NRLANCTONF  = P_LANCTONF AND
                              NRSEQITPROD = C_PRODUTO.NRSEQITPROD;
                     ELSE
                        UPDATE ITEMPRODUTO
                        SET VRBRUTITEM = VRBRUTITEM - V_IMPOSINFO
                        WHERE CDFILIAL    = P_FILIAL   AND
                              NRLANCTONF  = P_LANCTONF AND
                              NRSEQITPROD = C_PRODUTO.NRSEQITPROD;
                     END IF;
                  ELSE
                     IF C_PRODUTO.IDTIPCONTAB = W_D THEN
                        UPDATE ITEMPRODUTO
                        SET VRCONTITEM = VRCONTITEM + V_IMPOCONTAB
                        WHERE CDFILIAL    = P_FILIAL   AND
                              NRLANCTONF  = P_LANCTONF AND
                              NRSEQITPROD = C_PRODUTO.NRSEQITPROD;
                     END IF;

                     IF (C_PRODUTO.IDTRATIMPO = 'R') AND (C_PRODUTO.IDDESCRFONTE = 'N') THEN
                        UPDATE ITEMPRODUTO
                        SET VRBRUTITEM = VRBRUTITEM - V_IMPOSINFO
                        WHERE CDFILIAL    = P_FILIAL   AND
                              NRLANCTONF  = P_LANCTONF AND
                              NRSEQITPROD = C_PRODUTO.NRSEQITPROD;
                     END IF;
                  END IF;
               END IF; -- NAO ALTERAR VALOR CONTÁBIL DO PRODUTO SE O VALOR DOS PRODUTOS FOR ZERO
            END LOOP;
         END IF;
      END IF;

      ---------------------------------------------------------------------------------------------------------
      --FIM DA ATUALIZAÇÃO NA TABELA DE ITEMPROIMPOS
      ---------------------------------------------------------------------------------------------------------
      --TOTALIZAÇÃO DOS IMPOSTOS
      DELETE IMPOSNFTOT
      WHERE (CDFILIAL   = P_FILIAL) AND
            (NRLANCTONF = P_LANCTONF);

      IF (V_INTEGRACAO IS NULL) OR (P_ENTRSAID = W_E) THEN
         FOR C_IMPOSNFTOT IN (
            SELECT /*+ index (IP,PK_ITEMPROIMPOS)*/
                   IP.CDIMPOSTO, CDIMPOSTOIT, SUM(ROUND(NVL(VRIMPOSIT,0),V_NRDECITOTANF)) AS VRIMPOSTOIT, NVL(SUM(VRBASECALCIT),0) AS VRBASECALCIT,
                   NVL(SUM(VRBCALCIMPOIT),0) AS VRBCALCIMPOIT, MAX(NVL(IDPREIMPENTR, W_N)) AS IDPREIMPENTR
            FROM ITEMPROIMPOS IP, TRABITPROIMPOS TI, IMPOSTO I
            WHERE (IP.CDFILIAL     = P_FILIAL)       AND
                  (IP.NRLANCTONF   = P_LANCTONF)     AND
                  (TI.CDFILIMPOIT  = IP.CDFILIAL)    AND
                  (TI.NRLANCIMPOIT = IP.NRLANCTONF)  AND
                  (TI.NRSEQIMPOIT  = IP.NRSEQITPROD) AND
                  (TI.NRSEQITPRO   = IP.NRITPROIMPOS)  AND
                  (TI.CDIMPOSTOIT  = IP.CDIMPOSTO) AND
                  (I.CDIMPOSTO     = TI.CDIMPOSTOIT) AND
                  (IP.NRITPROIMPOS = 1)
            GROUP BY IP.CDIMPOSTO, TI.CDIMPOSTOIT) LOOP

            INSERT INTO IMPOSNFTOT(CDFILIAL, NRLANCTONF, CDIMPOSTO, VRTOTIMPONF, VRTOTBCALCNF)
                           VALUES (P_FILIAL, P_LANCTONF, C_IMPOSNFTOT.CDIMPOSTO, NVL(C_IMPOSNFTOT.VRIMPOSTOIT,0), NVL(C_IMPOSNFTOT.VRBASECALCIT,0));

            IF C_IMPOSNFTOT.IDPREIMPENTR = W_N THEN
               UPDATE TRABIMPOSNFTOT
               SET VRBCALIMPTOT   = NVL(C_IMPOSNFTOT.VRBCALCIMPOIT,0)
               WHERE CDFILIMPTOT  = P_FILIAL   AND
                     NRLANCIMPTOT = P_LANCTONF AND
                     CDIMPOSTOT   = C_IMPOSNFTOT.CDIMPOSTO;
            ELSE
               UPDATE TRABIMPOSNFTOT
               SET VRBCALIMPTOT = NVL(C_IMPOSNFTOT.VRBCALCIMPOIT,0),
                   VRIMPOSTOT   = NVL(C_IMPOSNFTOT.VRIMPOSTOIT,0)
               WHERE CDFILIMPTOT  = P_FILIAL   AND
                     NRLANCIMPTOT = P_LANCTONF AND
                     CDIMPOSTOT   = C_IMPOSNFTOT.CDIMPOSTO;
            END IF;
         END LOOP;

         --INCLUSÃO DOS IMPOSTOS DE CORPO DE NOTA EM CASO DE NOTA FISCAL DE ENTRADA

         V_SEQUIMPOSTNF := '01';

         DELETE IMPOSTONF
         WHERE (CDFILIAL = P_FILIAL) AND
               (NRLANCTONF = P_LANCTONF);

         CONSULTA_INCIDENCIA(P_ENTRSAID, P_EMPRESA, '', P_INSCESTA, P_TIPOOPER, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC, NULL, V_IDINTEREST);
         FOR C_INCITEMP IN (SELECT DSMENSINCTMP
                              FROM INCITEMP
                             WHERE (NRINCITEMP = V_INCITEMP)  AND
                                   (DSMENSINCTMP IS NOT NULL) AND
                                   (NOT EXISTS(SELECT DSDADOADIC
                                                 FROM DADOSADIC
                                                WHERE (CDFILIAL   = P_FILIAL)   AND
                                                      (NRLANCTONF = P_LANCTONF) AND
                                                      (DSDADOADIC LIKE INCITEMP.DSMENSINCTMP || '%')))) LOOP

            IF NOT(C_INCITEMP.DSMENSINCTMP IS NULL) THEN
               /*PREENCHE AS MENSAGENS ATRELADAS A INCIDENCIA*/

               INSERT INTO DADOSADIC(CDFILIAL, NRLANCTONF, NRDADOADIC, DSDADOADIC)
                              VALUES(P_FILIAL, P_LANCTONF, V_DADOADIC, C_INCITEMP.DSMENSINCTMP);

               V_DADOADIC := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_DADOADIC) + 1)),3,0);
            END IF;
         END LOOP;


         FOR C_INCIDENCIA IN (SELECT DISTINCT (IT.CDIMPOTEMP) AS CDIMPOTEMP, IT.CDFISCTEMP, IP.IDUTMUNIORIG,
                                     IT.IDTRATIMPTMP, IP.IDIMPORECUP, NVL(IP.IDPREIMPENTR, W_N) AS IDPREIMPENTR
                              FROM INCITEMP IT, IMPOSTO IP
                              WHERE (IT.NRINCITEMP  = V_INCITEMP)       AND
                                    (IT.CDIMPOTEMP  = IP.CDIMPOSTO)     AND
                                    (IP.IDPRODNOTA  = W_C)) LOOP

            V_ALIQUTMP   := 0;
            V_PARDEDTMP  := 0;
            V_PREDBCTMP1 := 0;
            V_PREDBCTMP  := 0;
            V_ALIQUTMP   := 0;

            /*VERIFICA CST POR IMPOSTO*/
            V_IMPOICMS := NULL;
            V_CDGRUPOFISCAUX := NULL;

            SELECT MAX(G.CDGRUPOFISC)
              INTO V_CDGRUPOFISCAUX
              FROM GRUPOFISCIMPFIL G,
                   (SELECT DECODE('E', 'E', CDFILIRECE, CDFILIEMIT) AS CDFILIAL
                      FROM NOTAFISCAL
                     WHERE CDFILIAL = P_FILIAL
                           AND NRLANCTONF = P_LANCTONF) F
             WHERE G.CDFILIAL = F.CDFILIAL
               AND NOT G.CDGRUPOFISC IS NULL
               AND G.CDIMPOSTO = C_INCIDENCIA.CDIMPOTEMP;

            IF V_IDORIGDESTNF = 'F' THEN
               SELECT NVL(MAX(G.CDGRUPOFISC), V_CDGRUPOFISCAUX)
                 INTO V_CDGRUPOFISCAUX
                 FROM GRFISIMPIEFORN G,
                      (SELECT CDFORNECED
                         FROM NOTAFISCAL
                        WHERE CDFILIAL = P_FILIAL
                          AND NRLANCTONF = P_LANCTONF) N
                WHERE G.CDFORNECED = N.CDFORNECED
                  AND G.CDEMPRESA = P_EMPRESA
                  AND G.CDINSCESTA = P_INSCESTA
                  AND NOT G.CDGRUPOFISC IS NULL
                  AND G.CDIMPOSTO = C_INCIDENCIA.CDIMPOTEMP;
            ELSE
               SELECT NVL(MAX(G.CDGRUPOFISC), V_CDGRUPOFISCAUX)
                 INTO V_CDGRUPOFISCAUX
                 FROM GRFISIMPIECLIE G,
                      (SELECT CDCLIENTE
                         FROM NOTAFISCAL
                        WHERE CDFILIAL = P_FILIAL
                          AND NRLANCTONF = P_LANCTONF) N
                WHERE G.CDCLIENTE = N.CDCLIENTE
                  AND G.CDEMPRESA = P_EMPRESA
                  AND G.CDINSCESTA = P_INSCESTA
                  AND NOT G.CDGRUPOFISC IS NULL
                  AND G.CDIMPOSTO = C_INCIDENCIA.CDIMPOTEMP;
            END IF;

            IF V_CDGRUPOFISCAUX IS NULL THEN
               CONSULTA_CST_NFE(W_E, P_EMPRESA, '', P_INSCESTA, P_TIPOOPER, V_CDGRUPOFISC,C_INCIDENCIA.CDIMPOTEMP, V_IDINTEREST, V_IDINTERNAC, P_FILIAL, P_LANCTONF, '', V_CDSITTRIBTMP, V_IDMODBCNFE, V_IDMODBCSTNFE, V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, V_IDMOTIDESSTNFE);
            ELSE
               CONSULTA_CST_NFE(W_E, P_EMPRESA, '', P_INSCESTA, P_TIPOOPER, V_CDGRUPOFISCAUX,C_INCIDENCIA.CDIMPOTEMP, V_IDINTEREST, V_IDINTERNAC, P_FILIAL, P_LANCTONF, '', V_CDSITTRIBTMP, V_IDMODBCNFE, V_IDMODBCSTNFE, V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, V_IDMOTIDESSTNFE);
            END IF;

            SELECT MAX(CDIMPOSTO)
              INTO V_IMPOICMS
              FROM IMPOSTONFE N, IMPOSTO I
             WHERE N.CDIMPOSTONFE = I.CDIMPOSTONFE
               AND N.CDIMPOSTONFE = '00'
               AND I.CDIMPOSTO = C_INCIDENCIA.CDIMPOTEMP;

            IF C_INCIDENCIA.IDUTMUNIORIG = W_D THEN
              /* CONSIDERA MUNICIPIO DE DESTINO */
              CONSULTA_ALIQUOTA(C_INCIDENCIA.CDIMPOTEMP, P_ENTRSAID, P_EMPRESA, '', P_INSCESTA, V_PAISORIG,
                                V_ESTAORIG, V_PAISDEST, V_ESTADEST, V_MUNIDEST, V_LIQUIITEM, P_INIVALID, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC,P_TIPOOPER);
            ELSE
              /* CONSIDERA MUNICIPIO DE ORIGEM */
              CONSULTA_ALIQUOTA(C_INCIDENCIA.CDIMPOTEMP, P_ENTRSAID, P_EMPRESA, '', P_INSCESTA, V_PAISORIG,
                                V_ESTAORIG, V_PAISDEST, V_ESTADEST, V_MUNIORIG, V_LIQUIITEM, P_INIVALID, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC,P_TIPOOPER);
            END IF;

            SELECT MAX(VRPARDEDTMP), MAX(VRPREDBCTMP), MAX(VRALIQUTMP), MAX(VR1PREDBCTMP)
            INTO V_PARDEDTMP, V_PREDBCTMP, V_ALIQUTMP, V_PREDBCTMP1
            FROM ALIQTEMP
            WHERE (NRALIQTEMP = V_ALIQTEMP);

            IF (V_PREDBCTMP IS NULL) THEN
               V_PREDBCTMP := 0;
            END IF;

            IF (V_PARDEDTMP IS NULL) THEN
               V_PARDEDTMP := 0;
            END IF;

            IF (V_ALIQUTMP IS NULL) THEN --VERIFICAR VALOR DA ALÍQUOTA P/ IMPOSTO RECUPERÁVEL COM COD. FISCAL = W_3
               V_ALIQUTMP := 0;
            END IF;

            IF (V_PREDBCTMP1 IS NULL) THEN
               V_PREDBCTMP1 := 0;
            END IF;   

            V_PRODUENCARGO := 0;        

            SELECT SUM(VRITEMENCA) AS VRSOMAITEM INTO V_SOMAITEM
            FROM ENCARGO EN, ITEMENCARGO IE, BASECALC BC
            WHERE (IE.CDFILIAL   = P_FILIAL)                AND
                  (IE.NRLANCTONF = P_LANCTONF)              AND
                  (EN.CDENCARGO  = IE.CDENCARGO)            AND
                  (BC.CDENCARGO  = IE.CDENCARGO)            AND
                  (BC.CDIMPOSTO  = C_INCIDENCIA.CDIMPOTEMP) AND
                  (EN.IDENCARGO  = W_A);

            SELECT SUM(VRITEMENCA) AS VRDESCITEM INTO V_DESCITEM
            FROM ENCARGO EN, ITEMENCARGO IE, BASECALC BC
            WHERE (IE.CDFILIAL   = P_FILIAL)                AND
                  (IE.NRLANCTONF = P_LANCTONF)              AND
                  (EN.CDENCARGO  = IE.CDENCARGO)            AND
                  (BC.CDENCARGO  = IE.CDENCARGO)            AND
                  (BC.CDIMPOSTO  = C_INCIDENCIA.CDIMPOTEMP) AND
                  (EN.IDENCARGO  = W_D);

            IF V_SOMAITEM IS NULL THEN
               V_SOMAITEM := 0;
            END IF;

            IF V_DESCITEM IS NULL THEN
               V_DESCITEM := 0;
            END IF;

            V_PRODUENCARGO := V_SOMAITEM - V_DESCITEM;

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

            IF (V_IDNFGERADAVIAXML = 'S') AND ((V_IDIMPORTAIMPXML = 'S') OR (V_IDGERNFIGUALXML = 'S')) THEN
               V_PRODUENCARGO := 0;
            END IF;

            V_TAXABASECALC := (100 - V_PREDBCTMP)/100;
            V_TAXAALIQUOTA := (V_ALIQUTMP/100);
            V_BASECALCIT   := (V_LIQUIDO + V_PRODUENCARGO) * V_TAXABASECALC;
            V_CONTIMPO     := V_BASECALCIT;
            V_IMPOSTOIT    := ROUND((V_BASECALCIT * V_TAXAALIQUOTA) - V_PARDEDTMP, V_NRDECITOTANF);

            V_CONTABCALC := (V_LIQUIDO + V_PRODUENCARGO) - ((V_LIQUIDO + V_PRODUENCARGO) * V_TAXABASECALC);
            V_PERDBCALC  := 100 - V_PREDBCTMP;

            BEGIN
               SELECT VRIMPOSTOT INTO V_IMPOSINFO
               FROM TRABIMPOSNFTOT
               WHERE CDIMPOSTOT   = C_INCIDENCIA.CDIMPOTEMP AND
                     CDFILIMPTOT  = P_FILIAL                AND
                     NRLANCIMPTOT = P_LANCTONF;
            EXCEPTION
               WHEN NO_DATA_FOUND THEN
                  V_IMPOSINFO := 0;
            END;

            IF (V_BASECALCIT < 0) OR (V_BASECALCIT IS NULL) THEN
               V_BASECALCIT := 0;
            END IF;

            IF (V_IMPOSTOIT < 0) OR (V_IMPOSTOIT IS NULL) THEN
               V_IMPOSTOIT := 0;
            END IF;

            --SE O IMPOSTO FOI INFORMADO NO CORPO DA NF SERÁ CALCULADO O VALOR DA ALIQUOTA E O VALOR DO IMPOSTO.
            IF V_IMPOSINFO > 0 THEN
               V_ALIQUTMP  := ROUND((V_IMPOSINFO * 100)/ V_BASECALCIT,2);
               V_IMPOSTOIT := V_IMPOSINFO;
            END IF;

            --SE O IDENTIFICADOR DE PREENCHIMENTO DE IMPOSTOS NA ENTRADA DE DOCUMENTOS FOR IGUAL A NÃO
            IF C_INCIDENCIA.IDPREIMPENTR = W_N THEN
               UPDATE TRABIMPOSNFTOT
               SET VRBCALIMPTOT   = NVL(V_BASECALCIT,0)
               WHERE CDIMPOSTOT   = C_INCIDENCIA.CDIMPOTEMP AND
                     CDFILIMPTOT  = P_FILIAL                AND
                     NRLANCIMPTOT = P_LANCTONF;
            ELSE
               UPDATE TRABIMPOSNFTOT
               SET VRBCALIMPTOT   = NVL(V_BASECALCIT,0),
                   VRIMPOSTOT     = ROUND(NVL(V_IMPOSTOIT,0), V_NRDECITOTANF)
               WHERE CDIMPOSTOT   = C_INCIDENCIA.CDIMPOTEMP AND
                     CDFILIMPTOT  = P_FILIAL                AND
                     NRLANCIMPTOT = P_LANCTONF;
            END IF;

            INSERT INTO IMPOSNFTOT(CDFILIAL, NRLANCTONF, CDIMPOSTO, VRTOTIMPONF, VRTOTBCALCNF)
                            VALUES (P_FILIAL, P_LANCTONF, C_INCIDENCIA.CDIMPOTEMP, NVL(V_IMPOSTOIT,0), NVL(V_BASECALCIT,0));


            IF (C_INCIDENCIA.IDIMPORECUP = W_S) OR (C_INCIDENCIA.IDIMPORECUP <> W_S AND V_ALIQUTMP <> 0) THEN
               IF (C_INCIDENCIA.IDIMPORECUP = W_S) AND
                  (C_INCIDENCIA.CDFISCTEMP <> W_1) THEN
                  V_BASECALCIT := 0;
                  V_ALIQUTMP   := 0;
                  V_IMPOSTOIT  := 0;
                  V_PREDBCTMP1 := 0;
                  V_PREDBCTMP  := 0;
                  V_PARDEDTMP  := 0;
               END IF;

               BEGIN
                  SELECT IDFORMAPUR
                  INTO V_IDFORMAPUR
                  FROM IMPOSTO
                  WHERE CDIMPOSTO = C_INCIDENCIA.CDIMPOTEMP;
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_IDFORMAPUR := NULL;
               END;

               IF V_IDFORMAPUR = W_P THEN
                  INSERT INTO IMPOSTONF(
                     CDFILIAL, NRLANCTONF, CDIMPOSTO, NRIMPOSNF, VRCONTABILNF, VRPERREDBCNF, VRBASECALCNF,
                     VRALIQNF, VRPARDEDNF, VRIMPOSTONF, CDFISCALNF, IDIMPOSTONF, CDSITUTRIBIMNFE,
                     CDTPCREDPICONF, CDNATUBCALPCNF, IDMOTDESONERANF)
                  VALUES(
                     P_FILIAL, P_LANCTONF, C_INCIDENCIA.CDIMPOTEMP, V_SEQUIMPOSTNF, ROUND(V_CONTIMPO,2), V_PREDBCTMP,
                     V_BASECALCIT, V_ALIQUTMP, V_PARDEDTMP, V_IMPOSTOIT, C_INCIDENCIA.CDFISCTEMP, W_1, V_CDSITTRIBTMP,
                     V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, V_IDMOTIDESSTNFE);

                  V_SEQUIMPOSTNF := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_SEQUIMPOSTNF) + 1)),2,0);
               ELSE
                  INSERT INTO IMPOSTONF(
                     CDFILIAL, NRLANCTONF, CDIMPOSTO, NRIMPOSNF, VRCONTABILNF, VRPERREDBCNF, VRBASECALCNF,
                     VRALIQNF, VRPARDEDNF, VRIMPOSTONF, CDFISCALNF, IDIMPOSTONF, CDSITUTRIBIMNFE,
                     CDTPCREDPICONF, CDNATUBCALPCNF, IDMOTDESONERANF)
                  VALUES(
                     P_FILIAL, P_LANCTONF, C_INCIDENCIA.CDIMPOTEMP, V_SEQUIMPOSTNF, ROUND(V_CONTIMPO,2), V_PREDBCTMP,
                     V_BASECALCIT, V_ALIQUTMP, V_PARDEDTMP, V_IMPOSTOIT, C_INCIDENCIA.CDFISCTEMP, W_1, V_CDSITTRIBTMP,
                     V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, V_IDMOTIDESSTNFE);

                  V_SEQUIMPOSTNF := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_SEQUIMPOSTNF) + 1)),2,0);
               END IF;

               IF (C_INCIDENCIA.IDIMPORECUP = W_S) AND
                  (V_PREDBCTMP > 0)                AND
                  (C_INCIDENCIA.CDFISCTEMP = W_1)  THEN
                  INSERT INTO IMPOSTONF(
                     CDFILIAL, NRLANCTONF, CDIMPOSTO, NRIMPOSNF, VRCONTABILNF, VRPERREDBCNF, VRBASECALCNF,
                     VRALIQNF, VRPARDEDNF, VRIMPOSTONF, CDFISCALNF, IDIMPOSTONF, CDSITUTRIBIMNFE,
                     CDTPCREDPICONF, CDNATUBCALPCNF, IDMOTDESONERANF)
                  VALUES(
                     P_FILIAL, P_LANCTONF, C_INCIDENCIA.CDIMPOTEMP, V_SEQUIMPOSTNF, ROUND(V_CONTABCALC,2), V_PERDBCALC,
                     0, 0, V_PARDEDTMP, 0, W_2, W_2, V_CDSITTRIBTMP, V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, V_IDMOTIDESSTNFE);

                  V_SEQUIMPOSTNF := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_SEQUIMPOSTNF) + 1)),2,0);
               END IF;
            END IF;

            DELETE ALIQTEMP
            WHERE NRALIQTEMP = V_ALIQTEMP;
         END LOOP;

         V_TOTIMPOCONT := 0;
         V_TOTIMPOBRUT := 0;

         FOR C_IMPOSCONTAB IN (SELECT VRIMPOSTOT, IDIMPORECUP, CDCCTBLPASS, CDCCTBLATIV,
                                      IDTRATIMPO,  CDFISCTEMP, IDTIPCONTAB
                               FROM TRABIMPOSNFTOT INF, IMPOSTO IP, INCITEMP IT
                               WHERE INF.CDFILIMPTOT   = P_FILIAL    AND
                                     INF.NRLANCIMPTOT  = P_LANCTONF  AND
                                     IP.CDIMPOSTO  = INF.CDIMPOSTOT  AND
                                     IT.CDIMPOTEMP = IP.CDIMPOSTO    AND
                                     IT.NRINCITEMP = V_INCITEMP      AND
                                     IP.IDPRODNOTA = W_C) LOOP

            IF C_IMPOSCONTAB.IDTIPCONTAB = W_D THEN
               IF (C_IMPOSCONTAB.IDIMPORECUP = W_S) THEN
                  IF (NOT(C_IMPOSCONTAB.CDCCTBLATIV IS NULL)) AND
                     (C_IMPOSCONTAB.CDFISCTEMP = W_1) THEN

                     IF C_IMPOSCONTAB.IDTRATIMPO = W_V THEN
                        V_TOTIMPOCONT := V_TOTIMPOCONT - C_IMPOSCONTAB.VRIMPOSTOT;
                     END IF;
                  ELSE
                     IF C_IMPOSCONTAB.IDTRATIMPO = W_A THEN
                        IF C_IMPOSCONTAB.CDCCTBLPASS IS NULL THEN
                           V_TOTIMPOCONT := V_TOTIMPOCONT + C_IMPOSCONTAB.VRIMPOSTOT;
                        END IF;
                     ELSIF C_IMPOSCONTAB.IDTRATIMPO IN (W_D,W_R) THEN
                        V_TOTIMPOCONT := V_TOTIMPOCONT - C_IMPOSCONTAB.VRIMPOSTOT;
                     END IF;
                  END IF;
               ELSE
                  IF NOT(C_IMPOSCONTAB.CDCCTBLPASS IS NULL) THEN
                     IF C_IMPOSCONTAB.IDTRATIMPO = W_V THEN
                        V_TOTIMPOCONT := V_TOTIMPOCONT - C_IMPOSCONTAB.VRIMPOSTOT;
                     END IF;
                  ELSE
                     IF C_IMPOSCONTAB.IDTRATIMPO = W_A THEN
                        IF C_IMPOSCONTAB.CDCCTBLATIV IS NULL THEN
                           V_TOTIMPOCONT := V_TOTIMPOCONT + C_IMPOSCONTAB.VRIMPOSTOT;
                        END IF;
                     ELSIF C_IMPOSCONTAB.IDTRATIMPO IN (W_D,W_R) THEN
                        V_TOTIMPOCONT := V_TOTIMPOCONT - C_IMPOSCONTAB.VRIMPOSTOT;
                     END IF;
                  END IF;
               END IF;
            END IF;

            IF C_IMPOSCONTAB.IDTRATIMPO = W_A THEN
               V_TOTIMPOBRUT := V_TOTIMPOBRUT + C_IMPOSCONTAB.VRIMPOSTOT;

            ELSIF C_IMPOSCONTAB.IDTRATIMPO = W_D THEN
               V_TOTIMPOBRUT := V_TOTIMPOBRUT - C_IMPOSCONTAB.VRIMPOSTOT;
            END IF;
         END LOOP;

         IF (V_TOTIMPOBRUT <> 0) OR (V_TOTIMPOCONT <> 0) THEN
            FOR C_ITPRODUTO IN (SELECT NRSEQITPROD, (VRTOTAITEM - VRDESCITEM) AS VRLIQUIDO
                                  FROM ITEMPRODUTO
                                  WHERE CDFILIAL   = P_FILIAL   AND
                                        NRLANCTONF = P_LANCTONF)LOOP


               UPDATE ITEMPRODUTO
               SET VRBRUTITEM = VRBRUTITEM + ((V_TOTIMPOBRUT / V_LIQUIDO) * C_ITPRODUTO.VRLIQUIDO),
                   VRCONTITEM = VRCONTITEM + ((V_TOTIMPOCONT / V_LIQUIDO) * C_ITPRODUTO.VRLIQUIDO)
               WHERE CDFILIAL    = P_FILIAL   AND
                     NRLANCTONF  = P_LANCTONF AND
                     NRSEQITPROD = C_ITPRODUTO.NRSEQITPROD;

            END LOOP;
         END IF;

         DELETE INCITEMP
         WHERE NRINCITEMP = V_INCITEMP;
      ELSE
         DELETE IMPOSTONF
         WHERE (CDFILIAL   = P_FILIAL) AND
               (NRLANCTONF = P_LANCTONF);
      END IF;

   --FIM DA TOTALIZAÇÃO DOS IMPOSTOS
   ---------------------------------------------------------------------------------------------------------
   -- NOTA FISCAL DE MOVIMENTAÇÃO - 07
   ELSIF P_TIPOOPER IN ('07','10') OR (V_IDOPERDEVONF = W_S) THEN

      IF (V_INTEGRACAO IS NULL) OR (P_ENTRSAID = W_E) THEN
         FOR C_ITEMPROD IN (SELECT I.VRTOTAITEM, I.VRDESCITEM, I.CDSITUTRIBPR, I.NRSEQITPROD,
                                   P.CDARVPROD, I.VRUNITITEM, I.NRLOTEESTQ, I.NRSUBLOTE, I.CDPRODUTO,
                                   I.QTITEMPROD, I.CDFISCOPERSN, NVL(I.IDORIGEMPROD, 'N') AS IDORIGEMPROD, N.IDNFDEVOOL
                            FROM PRODUTO P, ITEMPRODUTO I, NOTAFISCAL N
                            WHERE N.CDFILIAL    = P_FILIAL      AND
                                  N.NRLANCTONF  = P_LANCTONF    AND
                                  I.CDFILIAL  = N.CDFILIAL    AND
                                  I.NRLANCTONF = N.NRLANCTONF AND
                                  P.CDPRODUTO = I.CDPRODUTO) LOOP

            V_LIQUIITEM := C_ITEMPROD.VRTOTAITEM - C_ITEMPROD.VRDESCITEM;

            CONSULTA_CST(P_ENTRSAID, P_EMPRESA, C_ITEMPROD.CDARVPROD, P_INSCESTA, P_TIPOOPER, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC,V_IDINTEREST, V_IDINTERNAC, NULL, C_ITEMPROD.IDORIGEMPROD);

            SELECT MAX(CDSITTRIBTMP) INTO V_SITUTRIBPR
            FROM CSTTEMP
            WHERE (NRCSTTEMP = V_CSTTEMP);

            IF V_IDOPERDEVONF <> w_S THEN
               IF NOT (SUBSTR(C_ITEMPROD.CDSITUTRIBPR,1,1) = SUBSTR(V_SITUTRIBPR,1,1)) AND
                  NOT (C_ITEMPROD.CDSITUTRIBPR IS NULL) THEN
                  V_SITUTRIBPR := C_ITEMPROD.CDSITUTRIBPR;
               END IF;
            ELSE
               IF V_SITUTRIBPR IS NULL THEN
                  V_SITUTRIBPR := C_ITEMPROD.CDSITUTRIBPR;
               END IF;
            END IF;

            /* VERIFICA IMPOSTOS POR REDUCAO REFERENTE A NOTA FISCAL DE ORIGEM */
            IF (V_IDOPERDEVONF = W_S) THEN

               V_VRFATOCONV := 0;

               /* Verifica se é uma devolução ao Operador Logístico */

               V_CDPRODORIG := NULL;

               IF C_ITEMPROD.IDNFDEVOOL = 'S' THEN
                  BEGIN
                     SELECT MAX(CDPRARVORIG)
                       INTO V_CDPRODORIG
                       FROM RELACPRODOL
                      WHERE CDPRODARVOL = C_ITEMPROD.CDPRODUTO;
                  EXCEPTION
                     WHEN NO_DATA_FOUND THEN
                        V_CDPRODORIG := C_ITEMPROD.CDPRODUTO;
                  END;
               ELSE
                  V_CDPRODORIG := C_ITEMPROD.CDPRODUTO;
               END IF;

               FOR C_IMPOSORIG IN (SELECT VRPERREDBCIT, NRITPROIMPOS, CDIMPOSTO, CDFISCALIT,
                                          VRALIQITEM, VRPARDEDIT, IDVALORINFIT, SUM(QTITEMPROD) AS QTITEMPROD,
                                          CDSITUTRIBITNFE, IDMODBCITNFE, IDMODBCSTITNFE,
                                          CDFISCOPERIT, CDSUFXCFOPIT,
                                          SUM(VRCONTITIMP) AS VRCONTITIMP,
                                          SUM(VRBASECALCIT) AS VRBASECALCIT, SUM(VRIMPOSTOIT) AS VRIMPOSTOIT, IDMOTDESONERAIT,
                                          VRPERDIFEREIT, NVL(VRIMPOSTOOPERAIT, 0) AS VRIMPOSTOOPERAIT,
                                          NVL(VRIMPOSTODIFERIT, 0) AS VRIMPOSTODIFERIT, 
                                          IT.CDBENEFFISCAL, IT.CDCEST, IT.VRADICALIQFECP, IT.VRADICFECP
                                     FROM ITEMPROIMPOS IT, ITEMPRODUTO I
                                    WHERE IT.CDFILIAL  = V_FILIORIG
                                      AND IT.NRLANCTONF = V_DEVOLORIG
                                      AND I.CDFILIAL    = V_FILIORIG
                                      AND I.NRLANCTONF  = V_DEVOLORIG
                                      AND IT.NRSEQITPROD = I.NRSEQITPROD
                                      AND I.CDPRODUTO = V_CDPRODORIG
                                      AND ROUND(I.VRUNITITEM, V_NRDECITOTANF) = ROUND(C_ITEMPROD.VRUNITITEM, V_NRDECITOTANF)
                                      AND (NVL(I.NRLOTEESTQ  , ' ') = (NVL(C_ITEMPROD.NRLOTEESTQ, ' ')))
                                      AND (NVL(I.NRSUBLOTE , ' ')   = (NVL(C_ITEMPROD.NRSUBLOTE,  ' ')))
                                      AND NVL(I.IDORIGEMPROD, 'N')  = C_ITEMPROD.IDORIGEMPROD
                                    GROUP BY VRPERREDBCIT, NRITPROIMPOS, CDIMPOSTO, CDFISCALIT,
                                             VRALIQITEM, VRPARDEDIT, IDVALORINFIT,
                                             CDSITUTRIBITNFE, IDMODBCITNFE, IDMODBCSTITNFE,
                                             CDFISCOPERIT, CDSUFXCFOPIT, IDMOTDESONERAIT,
                                             VRPERDIFEREIT, VRIMPOSTOOPERAIT, VRIMPOSTODIFERIT,
                                             IT.CDBENEFFISCAL, IT.CDCEST, IT.VRADICALIQFECP, IT.VRADICFECP)
               LOOP

                  V_VRFATOCONV := NVL(C_ITEMPROD.QTITEMPROD, 0) / C_IMPOSORIG.QTITEMPROD;

                  DELETE FROM TRABITPROIMPOS
                   WHERE CDFILIMPOIT = P_FILIAL
                     AND NRLANCIMPOIT = P_LANCTONF
                     AND NRSEQIMPOIT = C_ITEMPROD.NRSEQITPROD
                     AND CDIMPOSTOIT = C_IMPOSORIG.CDIMPOSTO
                     AND NRSEQITPRO = C_IMPOSORIG.NRITPROIMPOS;

                  DELETE FROM ITEMPROIMPOS
                   WHERE CDFILIAL = P_FILIAL
                     AND NRLANCTONF = P_LANCTONF
                     AND NRSEQITPROD = C_ITEMPROD.NRSEQITPROD
                     AND CDIMPOSTO = C_IMPOSORIG.CDIMPOSTO
                     AND NRITPROIMPOS = C_IMPOSORIG.NRITPROIMPOS;

                  V_IMPOICMS := NULL;
                  V_CST1DIGT := NULL;

                  V_CDGRUPOFISCAUX := NULL;
                  SELECT MAX(G.CDGRUPOFISC)
                    INTO V_CDGRUPOFISCAUX
                    FROM GRUPOFISCIMPFIL G,
                         (SELECT DECODE('E', 'E', CDFILIRECE, CDFILIEMIT) AS CDFILIAL
                            FROM NOTAFISCAL
                           WHERE CDFILIAL = P_FILIAL
                             AND NRLANCTONF = P_LANCTONF) F
                   WHERE G.CDFILIAL = F.CDFILIAL
                     AND NOT G.CDGRUPOFISC IS NULL
                     AND G.CDIMPOSTO = C_IMPOSORIG.CDIMPOSTO;

                  IF V_IDORIGDESTNF = 'F' THEN
                     SELECT NVL(MAX(G.CDGRUPOFISC), V_CDGRUPOFISCAUX)
                       INTO V_CDGRUPOFISCAUX
                       FROM GRFISIMPIEFORN G,
                            (SELECT CDFORNECED
                               FROM NOTAFISCAL
                              WHERE CDFILIAL = P_FILIAL
                                AND NRLANCTONF = P_LANCTONF) N
                      WHERE G.CDFORNECED = N.CDFORNECED
                        AND G.CDEMPRESA = P_EMPRESA
                        AND G.CDINSCESTA = P_INSCESTA
                        AND NOT G.CDGRUPOFISC IS NULL
                        AND G.CDIMPOSTO = C_IMPOSORIG.CDIMPOSTO;
                  ELSE
                     SELECT NVL(MAX(G.CDGRUPOFISC), V_CDGRUPOFISCAUX)
                       INTO V_CDGRUPOFISCAUX
                       FROM GRFISIMPIECLIE G,
                            (SELECT CDCLIENTE
                               FROM NOTAFISCAL
                              WHERE CDFILIAL = P_FILIAL
                                AND NRLANCTONF = P_LANCTONF) N
                      WHERE G.CDCLIENTE = N.CDCLIENTE
                        AND G.CDEMPRESA = P_EMPRESA
                        AND G.CDINSCESTA = P_INSCESTA
                        AND NOT G.CDGRUPOFISC IS NULL
                        AND G.CDIMPOSTO = C_IMPOSORIG.CDIMPOSTO;
                  END IF;

                  IF V_CDGRUPOFISCAUX IS NULL THEN
                     CONSULTA_CST_NFE(W_E, P_EMPRESA, C_ITEMPROD.CDARVPROD, P_INSCESTA, P_TIPOOPER, V_CDGRUPOFISC,C_IMPOSORIG.CDIMPOSTO, V_IDINTEREST, V_IDINTERNAC, P_FILIAL, P_LANCTONF, '', V_CDSITTRIBTMP, V_IDMODBCNFE, V_IDMODBCSTNFE, V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, V_IDMOTIDESSTNFE, C_ITEMPROD.IDORIGEMPROD);
                  ELSE
                     CONSULTA_CST_NFE(W_E, P_EMPRESA, C_ITEMPROD.CDARVPROD, P_INSCESTA, P_TIPOOPER, V_CDGRUPOFISCAUX,C_IMPOSORIG.CDIMPOSTO, V_IDINTEREST, V_IDINTERNAC, P_FILIAL, P_LANCTONF, '', V_CDSITTRIBTMP, V_IDMODBCNFE, V_IDMODBCSTNFE, V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, V_IDMOTIDESSTNFE, C_ITEMPROD.IDORIGEMPROD);
                  END IF;

                  SELECT MAX(CDIMPOSTO)
                    INTO V_IMPOICMS
                    FROM IMPOSTONFE N, IMPOSTO I
                   WHERE N.CDIMPOSTONFE = I.CDIMPOSTONFE
                     AND N.CDIMPOSTONFE = '00'
                     AND I.CDIMPOSTO = C_IMPOSORIG.CDIMPOSTO;

                  IF (V_IMPOICMS IS NOT NULL) THEN
                     IF V_IDORIGDESTNF = 'L' THEN
                        Begin
                           SELECT MAX(CDCSTDIG1PROD)
                             INTO V_CST1DIGT
                             FROM PRODUTO
                            WHERE (CDARVPROD = C_ITEMPROD.CDARVPROD);

                           IF V_CST1DIGT IS NULL THEN
                              SELECT MAX(CDCSTDIG1SAI)
                              INTO   V_CST1DIGT
                              FROM INSCRESTAD
                              WHERE CDEMPRESA  = P_EMPRESA AND
                                    CDINSCESTA = P_INSCESTA;
                           END IF;
                        Exception
                           When No_Data_Found Then
                              V_CST1DIGT := Null;
                        End;
                     ELSIF V_IDORIGDESTNF = 'C' THEN
                        Begin
                           SELECT MAX(CDCSTDIG1PROD)
                             INTO V_CST1DIGT
                             FROM PRODUTO
                            WHERE (CDARVPROD = C_ITEMPROD.CDARVPROD);

                           IF V_CST1DIGT IS NULL THEN
                              SELECT MAX(CDCSTDIG1CLI)
                                INTO V_CST1DIGT
                                FROM NOTAFISCAL N, CLIENTE C
                               WHERE CDFILIAL     = P_FILIAL    AND
                                     NRLANCTONF   = P_LANCTONF  AND
                                     N.CDCLIENTE  = C.CDCLIENTE;
                           END IF;
                        Exception
                           When No_Data_Found Then
                              V_CST1DIGT := Null;
                        End;
                     ELSE
                        Begin
                           SELECT MAX(CDCSTDIG1PROD)
                             INTO V_CST1DIGT
                             FROM PRODUTO
                            WHERE (CDARVPROD = C_ITEMPROD.CDARVPROD);

                           IF V_CST1DIGT IS NULL THEN
                              SELECT MAX(CDCSTDIG1ENT)
                                INTO   V_CST1DIGT
                                FROM NOTAFISCAL N, FORNECEDOR F
                               WHERE CDFILIAL     = P_FILIAL   AND
                                    NRLANCTONF    = P_LANCTONF AND
                                    N.CDFORNECED  = F.CDFORNECED;
                           END IF;
                        Exception
                           When No_Data_Found Then
                              V_CST1DIGT := Null;
                        End;
                     END IF;

                     IF (V_IDUTORIGPROD = 'S') AND (C_ITEMPROD.IDORIGEMPROD = 'E') AND (NVL(V_IDNFGERADAVIAXML, 'N') <> 'S') THEN
                        V_CST1DIGT := '2';
                     END IF;

                     IF (V_CDSITTRIBTMP IS NOT NULL) THEN

                        UPDATE ITEMPRODUTO
                           SET CDSITUTRIBPR  = V_CST1DIGT||V_CDSITTRIBTMP
                         WHERE CDFILIAL      = P_FILIAL AND
                               NRLANCTONF    = P_LANCTONF AND
                               NRSEQITPROD   = C_ITEMPROD.NRSEQITPROD;

                        V_SITUTRIBPR := V_CST1DIGT||V_CDSITTRIBTMP;
                     END IF;

                     V_CDGRUPOFISCAUX := NULL;

                     SELECT MAX(G.CDGRUPOFISC)
                       INTO V_CDGRUPOFISCAUX
                       FROM GRUPOFISCIMPFIL G,
                            (SELECT DECODE('E', 'E', CDFILIRECE, CDFILIEMIT) AS CDFILIAL
                               FROM NOTAFISCAL
                              WHERE CDFILIAL = P_FILIAL
                                    AND NRLANCTONF = P_LANCTONF) F
                      WHERE G.CDFILIAL = F.CDFILIAL
                        AND NOT G.CDGRUPOFISC IS NULL
                        AND G.CDIMPOSTO = C_IMPOSORIG.CDIMPOSTO;

                     IF V_IDORIGDESTNF = 'F' THEN
                        SELECT NVL(MAX(G.CDGRUPOFISC), V_CDGRUPOFISCAUX)
                          INTO V_CDGRUPOFISCAUX
                          FROM GRFISIMPIEFORN G,
                               (SELECT CDFORNECED
                                  FROM NOTAFISCAL
                                 WHERE CDFILIAL = P_FILIAL
                                   AND NRLANCTONF = P_LANCTONF) N
                         WHERE G.CDFORNECED = N.CDFORNECED
                           AND G.CDEMPRESA = P_EMPRESA
                           AND G.CDINSCESTA = P_INSCESTA
                           AND NOT G.CDGRUPOFISC IS NULL
                           AND G.CDIMPOSTO = C_IMPOSORIG.CDIMPOSTO;
                     ELSE
                        SELECT NVL(MAX(G.CDGRUPOFISC), V_CDGRUPOFISCAUX)
                          INTO V_CDGRUPOFISCAUX
                          FROM GRFISIMPIECLIE G,
                               (SELECT CDCLIENTE
                                  FROM NOTAFISCAL
                                 WHERE CDFILIAL = P_FILIAL
                                   AND NRLANCTONF = P_LANCTONF) N
                         WHERE G.CDCLIENTE = N.CDCLIENTE
                           AND G.CDEMPRESA = P_EMPRESA
                           AND G.CDINSCESTA = P_INSCESTA
                           AND NOT G.CDGRUPOFISC IS NULL
                           AND G.CDIMPOSTO = C_IMPOSORIG.CDIMPOSTO;
                     END IF;


                     IF (V_CDGRUPOFISCAUX IS NOT NULL) THEN
                        CONSULTA_CFOP(P_ENTRSAID, P_EMPRESA, C_ITEMPROD.CDARVPROD, P_INSCESTA, P_TIPOOPER, V_PAISCFOP,
                                      V_ESTACFOP, V_PAISDEST, V_ESTADEST, P_FILIAL, P_LANCTONF, V_CDGRUPOFISCAUX, P_INIVALID, C_ITEMPROD.IDORIGEMPROD);
                     ELSE
                        CONSULTA_CFOP(P_ENTRSAID, P_EMPRESA, C_ITEMPROD.CDARVPROD, P_INSCESTA, P_TIPOOPER, V_PAISCFOP,
                                      V_ESTACFOP, V_PAISDEST, V_ESTADEST, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC, P_INIVALID, C_ITEMPROD.IDORIGEMPROD);
                     END IF;

                     -- ALTERA NATUREZA DE OPERAÇÃO DA NOTA FISCAL CASO NÃO EXISTA
                     IF (V_DSCDFISOPEITREGRA IS NOT NULL) THEN
                        UPDATE NOTAFISCAL
                           SET DSCDFISOPENF = V_DSCDFISOPEITREGRA
                         WHERE CDFILIAL   = P_FILIAL   AND
                               NRLANCTONF = P_LANCTONF;
                     ELSE
                        UPDATE NOTAFISCAL
                           SET DSCDFISOPENF = (SELECT MAX(DSCFOPTMP)
                                                 FROM CFOPTEMP
                                                WHERE NRCFOPTEMP = V_CFOPTEMP)
                         WHERE CDFILIAL   = P_FILIAL
                           AND NRLANCTONF = P_LANCTONF
                           AND DSCDFISOPENF IS NULL;

                     END IF;

                     SELECT MAX(CDFISOPETMP), MAX(CDSUFCFOPTMP), MAX(IDDIFALIQTMP),
                            MAX(DSCFOPTMP), NVL(MAX(IDDIFALIQCUSPRC),W_N)
                      INTO V_FISOPEITEM, V_SUFXCFOPPR, V_DIFALIQITEM,
                           V_DSCDFISOPEIT, V_IDDIFALIQCUSPRC
                      FROM CFOPTEMP
                      WHERE NRCFOPTEMP = V_CFOPTEMP;

                      V_FISOPEITEM      := NVL(V_CDFISCOPERREGRA, V_FISOPEITEM);
                      V_DSCDFISOPEIT    := NVL(V_DSCDFISOPEITREGRA, V_DSCDFISOPEIT);
                      V_DIFALIQITEM     := NVL(V_IDDIFEALIQREGRA, V_DIFALIQITEM);
                      V_IDDIFALIQCUSPRC := NVL(V_IDDIFALIQCUSPRREGRA, V_IDDIFALIQCUSPRC);

                      -- ALTERA O CFOP DO ITEM E
                      UPDATE ITEMPRODUTO
                      SET CDFISOPEITEM = NVL(V_CDFISCOPERREGRA, V_FISOPEITEM),
                          CDSUFXCFOPPR = V_SUFXCFOPPR,
                          DSCDFISOPEIT = V_DSCDFISOPEIT
                      WHERE CDFILIAL    = P_FILIAL   AND
                            NRLANCTONF  = P_LANCTONF AND
                            NRSEQITPROD = C_ITEMPROD.NRSEQITPROD;

                     DELETE CFOPTEMP
                      WHERE NRCFOPTEMP = V_CFOPTEMP;

                  END IF;

                  INSERT INTO TRABITPROIMPOS(
                     CDFILIMPOIT, NRLANCIMPOIT, NRSEQIMPOIT, CDIMPOSTOIT, NRSEQITPRO, CDFISCIMPOIT,
                     CDSTRIBIMPOIT, CDFOPERIMPOIT, CDSCFOPIMPOIT, VRALIQIMPOIT, VRREDBCIMPOIT, VRPDEDIMPOIT,
                     VRCONTIMPOIT, VRBCALCIMPOIT, VRIMPOSIT, IDERRIMPOIT, IDAVISIMPOIT, IDVALORINFO,
                     CDSTRIBITNFE, IDMODBCITEMNFE, IDMODBCSTITENFE, CDTPCREDPICOITE, CDNATUBCALPCIT, IDMOTDESOTRABIT, CDREGRATRABIT,
                     VRPERDIFEREIT, VRIMPOSTOOPERAIT, VRIMPOSTODIFERIT, 
                     CDBENEFFISCAL, CDCEST, VRADICALIQFECP, VRADICFECP)
                  VALUES(
                     P_FILIAL, P_LANCTONF, C_ITEMPROD.NRSEQITPROD, C_IMPOSORIG.CDIMPOSTO, C_IMPOSORIG.NRITPROIMPOS, C_IMPOSORIG.CDFISCALIT,
                     V_SITUTRIBPR, NVL(V_FISOPEITEM, C_IMPOSORIG.CDFISCOPERIT), NVL(V_SUFXCFOPPR, C_IMPOSORIG.CDSUFXCFOPIT), C_IMPOSORIG.VRALIQITEM, C_IMPOSORIG.VRPERREDBCIT, (C_IMPOSORIG.VRPARDEDIT * V_VRFATOCONV),
                     ROUND((C_IMPOSORIG.VRCONTITIMP * V_VRFATOCONV),5), ROUND((C_IMPOSORIG.VRBASECALCIT * V_VRFATOCONV), 2), (C_IMPOSORIG.VRIMPOSTOIT * V_VRFATOCONV), W_00000, W_00000, C_IMPOSORIG.IDVALORINFIT,
                     V_CDSITTRIBTMP, NVL(V_IDMODBCNFE, C_IMPOSORIG.IDMODBCITNFE), NVL(V_IDMODBCSTNFE, C_IMPOSORIG.IDMODBCSTITNFE),
                     V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, NVL(V_IDMOTIDESSTNFE, C_IMPOSORIG.IDMOTDESONERAIT), V_CDREGRAITALIQ,
                     C_IMPOSORIG.VRPERDIFEREIT, ROUND((C_IMPOSORIG.VRIMPOSTOOPERAIT * V_VRFATOCONV),2), ROUND((C_IMPOSORIG.VRIMPOSTODIFERIT * V_VRFATOCONV),2), 
                     C_IMPOSORIG.CDBENEFFISCAL, C_IMPOSORIG.CDCEST, C_IMPOSORIG.VRADICALIQFECP, ROUND((C_IMPOSORIG.VRADICFECP * V_VRFATOCONV),2));

                  INSERT INTO ITEMPROIMPOS(
                     CDFILIAL, NRLANCTONF, NRSEQITPROD, CDIMPOSTO, NRITPROIMPOS, CDFISCALIT,
                     CDSITUTRIBIT, CDFISCOPERIT, CDSUFXCFOPIT, VRALIQITEM, VRPERREDBCIT, VRPARDEDIT,
                     VRCONTITIMP, VRBASECALCIT, VRIMPOSTOIT, IDERROSIMPIT, IDAVISIMPIT, CDSITUTRIBITNFE,
                     IDMODBCITNFE, IDMODBCSTITNFE, CDTPCREDPICOITE, CDNATUBCALPCIT, IDMOTDESONERAIT, CDREGRAIT,
                     VRPERDIFEREIT, VRIMPOSTOOPERAIT, VRIMPOSTODIFERIT, 
                     CDBENEFFISCAL, CDCEST, VRADICALIQFECP, VRADICFECP)
                  VALUES(
                     P_FILIAL, P_LANCTONF, C_ITEMPROD.NRSEQITPROD, C_IMPOSORIG.CDIMPOSTO, C_IMPOSORIG.NRITPROIMPOS, C_IMPOSORIG.CDFISCALIT,
                     V_SITUTRIBPR, NVL(V_FISOPEITEM, C_IMPOSORIG.CDFISCOPERIT), NVL(V_SUFXCFOPPR, C_IMPOSORIG.CDSUFXCFOPIT), C_IMPOSORIG.VRALIQITEM, C_IMPOSORIG.VRPERREDBCIT, (C_IMPOSORIG.VRPARDEDIT * V_VRFATOCONV),
                     ROUND((C_IMPOSORIG.VRCONTITIMP * V_VRFATOCONV),5), ROUND((C_IMPOSORIG.VRBASECALCIT * V_VRFATOCONV), 2), (C_IMPOSORIG.VRIMPOSTOIT * V_VRFATOCONV), W_00000, W_00000, V_CDSITTRIBTMP,
                     NVL(V_IDMODBCNFE, C_IMPOSORIG.IDMODBCITNFE), NVL(V_IDMODBCSTNFE, C_IMPOSORIG.IDMODBCSTITNFE), V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, NVL(V_IDMOTIDESSTNFE, C_IMPOSORIG.IDMOTDESONERAIT), V_CDREGRAITALIQ,
                     C_IMPOSORIG.VRPERDIFEREIT, ROUND((C_IMPOSORIG.VRIMPOSTOOPERAIT * V_VRFATOCONV),2), ROUND((C_IMPOSORIG.VRIMPOSTODIFERIT * V_VRFATOCONV),2),
                     C_IMPOSORIG.CDBENEFFISCAL, C_IMPOSORIG.CDCEST, C_IMPOSORIG.VRADICALIQFECP, ROUND((C_IMPOSORIG.VRADICFECP * V_VRFATOCONV),2));
               END LOOP;
            END IF;

            IF (V_IDOPERDEVONF = W_S) THEN
               CONSULTA_INCIDENCIA(P_ENTRSAID, P_EMPRESA, C_ITEMPROD.CDARVPROD, P_INSCESTA, P_TIPOOPER, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC,
                                   NULL, V_IDINTEREST, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, C_ITEMPROD.IDORIGEMPROD);

               FOR C_INCIDITEM IN (SELECT IT.CDIMPOTEMP, MAX(IT.CDFISCTEMP) AS CDFISCTEMP,
                                        MAX(IT.IDTRATIMPTMP) AS IDTRATIMPTMP, MAX(IP.IDCONSISTENT) AS IDCONSISTENT, MAX(NVL(IP.IDUTMUNIORIG, W_N)) AS IDUTMUNIORIG,
                                        MAX(IP.IDIMPORECUP)  AS IDIMPORECUP, MAX(NVL(IP.IDPREIMPENTR, W_N)) AS IDPREIMPENTR,
                                        MAX(IP.IDORGARRECAD) AS IDORGARRECAD, MAX(IDUTVLRQTDEIMPO) AS IDUTVLRQTDEIMPO,
                                        MAX(IP.IDUTVRPAUTA) AS IDUTVRPAUTA,   MAX(CDENQLEGALIPI)   AS CDENQLEGALIPI,
                                        MAX(IT.CDCEST) AS CDCEST
                                 FROM INCITEMP IT, IMPOSTO IP
                                 WHERE (IT.NRINCITEMP = V_INCITEMP)    AND
                                       (IP.CDIMPOSTO  = IT.CDIMPOTEMP)
                                 GROUP BY IT.CDIMPOTEMP
                                 ORDER BY IT.CDIMPOTEMP) LOOP


                  /*VERIFICA CST POR IMPOSTO*/
                  V_IMPOICMS := NULL;
                  V_CDGRUPOFISCAUX := NULL;

                  IF (C_INCIDITEM.CDCEST IS NOT NULL) THEN
                     V_CDCEST := C_INCIDITEM.CDCEST;
                  END IF;

                  SELECT MAX(G.CDGRUPOFISC)
                    INTO V_CDGRUPOFISCAUX
                    FROM GRUPOFISCIMPFIL G,
                         (SELECT DECODE('E', 'E', CDFILIRECE, CDFILIEMIT) AS CDFILIAL
                            FROM NOTAFISCAL
                           WHERE CDFILIAL = P_FILIAL
                                 AND NRLANCTONF = P_LANCTONF) F
                   WHERE G.CDFILIAL = F.CDFILIAL
                     AND NOT G.CDGRUPOFISC IS NULL
                     AND G.CDIMPOSTO = C_INCIDITEM.CDIMPOTEMP;

                  IF V_IDORIGDESTNF = 'F' THEN
                     SELECT NVL(MAX(G.CDGRUPOFISC), V_CDGRUPOFISCAUX)
                       INTO V_CDGRUPOFISCAUX
                       FROM GRFISIMPIEFORN G,
                            (SELECT CDFORNECED
                               FROM NOTAFISCAL
                              WHERE CDFILIAL = P_FILIAL
                                AND NRLANCTONF = P_LANCTONF) N
                      WHERE G.CDFORNECED = N.CDFORNECED
                        AND G.CDEMPRESA = P_EMPRESA
                        AND G.CDINSCESTA = P_INSCESTA
                        AND NOT G.CDGRUPOFISC IS NULL
                        AND G.CDIMPOSTO = C_INCIDITEM.CDIMPOTEMP;
                  ELSE
                     SELECT NVL(MAX(G.CDGRUPOFISC), V_CDGRUPOFISCAUX)
                       INTO V_CDGRUPOFISCAUX
                       FROM GRFISIMPIECLIE G,
                            (SELECT CDCLIENTE
                               FROM NOTAFISCAL
                              WHERE CDFILIAL = P_FILIAL
                                AND NRLANCTONF = P_LANCTONF) N
                      WHERE G.CDCLIENTE = N.CDCLIENTE
                        AND G.CDEMPRESA = P_EMPRESA
                        AND G.CDINSCESTA = P_INSCESTA
                        AND NOT G.CDGRUPOFISC IS NULL
                        AND G.CDIMPOSTO = C_INCIDITEM.CDIMPOTEMP;
                  END IF;

                  DELETE ALIQTEMP
                  WHERE NRALIQTEMP = V_ALIQTEMP;


                  IF C_INCIDITEM.IDUTMUNIORIG = W_D THEN
                     /* CONSIDERA O MUNICIPIO DE DESTINO */
                     IF V_UTGRUPFISCS = 'S' THEN
                        V_CDGRPFISCSV := NULL;
                        SELECT MAX(CDGRUPOFISC)
                        INTO V_CDGRPFISCSV
                        FROM SERVCLIE SC, SERVICO S
                        WHERE SC.CDFILIAL   = V_CDFILIEMIT AND
                              SC.CDCLIENTE  = P_FORNECED    AND
                              SC.CDFILIAL   = S.CDFILIAL   AND
                              SC.CDSERVFILI = S.CDSERVFILI AND
                              S.CDPRODUTO   = V_CDPRODORIG;
                        IF V_CDGRPFISCSV IS NULL THEN
                           SELECT MAX(CDGRUPOFISC)
                           INTO V_CDGRPFISCSV
                           FROM CLIENFILIAL
                          WHERE CDFILIAL   = V_CDFILIEMIT AND
                                CDCLIENTE  = P_FORNECED;
                        END IF;
                        CONSULTA_ALIQUOTA(C_INCIDITEM.CDIMPOTEMP, P_ENTRSAID, P_EMPRESA, C_ITEMPROD.CDARVPROD, P_INSCESTA, V_PAISORIG,
                                          V_ESTAORIG, V_PAISDEST, V_ESTADEST, V_MUNIDEST, V_LIQUIITEM, P_INIVALID, P_FILIAL, P_LANCTONF, V_CDGRPFISCSV,P_TIPOOPER,
                                          NULL, NULL, NULL, NULL, P_FORNECED, NULL, C_ITEMPROD.IDORIGEMPROD);
                     ELSE
                        CONSULTA_ALIQUOTA(C_INCIDITEM.CDIMPOTEMP, P_ENTRSAID, P_EMPRESA, C_ITEMPROD.CDARVPROD, P_INSCESTA, V_PAISORIG,
                                          V_ESTAORIG, V_PAISDEST, V_ESTADEST, V_MUNIDEST, V_LIQUIITEM, P_INIVALID, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC, P_TIPOOPER,
                                          NULL, NULL, NULL, NULL, P_FORNECED, NULL, C_ITEMPROD.IDORIGEMPROD);
                     END IF;
                  ELSE
                    /* CONSIDERA O MUNICIPIO DE ORIGEM */

                     SELECT MAX(IDGRUPFISSRV)
                     INTO V_UTGRUPFISCS
                     FROM IMPOSTO
                     WHERE CDIMPOSTO   = C_INCIDITEM.CDIMPOTEMP;

                     IF V_UTGRUPFISCS = 'S' THEN
                        V_CDGRPFISCSV := NULL;
                        SELECT MAX(CDGRUPOFISC)
                        INTO V_CDGRPFISCSV
                        FROM SERVCLIE SC, SERVICO S
                        WHERE SC.CDFILIAL   = V_CDFILIEMIT AND
                              SC.CDCLIENTE  = P_FORNECED    AND
                              SC.CDFILIAL   = S.CDFILIAL   AND
                              SC.CDSERVFILI = S.CDSERVFILI AND
                              S.CDPRODUTO   = V_CDPRODORIG;
                        IF V_CDGRPFISCSV IS NULL THEN
                           SELECT MAX(CDGRUPOFISC)
                           INTO V_CDGRPFISCSV
                           FROM CLIENFILIAL
                          WHERE CDFILIAL   = V_CDFILIEMIT AND
                                CDCLIENTE  = P_FORNECED;
                        END IF;

                        CONSULTA_ALIQUOTA(C_INCIDITEM.CDIMPOTEMP, P_ENTRSAID, P_EMPRESA, C_ITEMPROD.CDARVPROD, P_INSCESTA, V_PAISORIG,
                                          V_ESTAORIG, V_PAISDEST, V_ESTADEST, V_MUNIORIG, V_LIQUIITEM, P_INIVALID, P_FILIAL, P_LANCTONF, V_CDGRPFISCSV, P_TIPOOPER,
                                          NULL, NULL, NULL, NULL, P_FORNECED, NULL, C_ITEMPROD.IDORIGEMPROD);
                     ELSE
                        CONSULTA_ALIQUOTA(C_INCIDITEM.CDIMPOTEMP, P_ENTRSAID, P_EMPRESA, C_ITEMPROD.CDARVPROD, P_INSCESTA, V_PAISORIG,
                                          V_ESTAORIG, V_PAISDEST, V_ESTADEST, V_MUNIORIG, V_LIQUIITEM, P_INIVALID, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC, P_TIPOOPER,
                                          NULL, NULL, NULL, NULL, P_FORNECED, NULL, C_ITEMPROD.IDORIGEMPROD);

                     END IF;
                  END IF;

                  SELECT NVL(MAX(VRPARDEDTMP),0), NVL(MAX(VRPREDBCTMP),0), NVL(MAX(VRALIQUTMP),0),
                         NVL(MAX(VRPBCSTTMP),0),  NVL(MAX(IDTRIMPSTTMP), '0'), NVL(MAX(VR1PREDBCTMP), '0'),
                         MAX(CDREGRATMP), MAX(CDFISCOPER), MAX(IDDIFEALIQ),
                         MAX(IDDIFALIQCUSPR), MAX(CDBENEFFISCAL)
                    INTO V_PARDEDTMP, V_PREDBCTMP, V_ALIQUTMP,
                         V_PBCSUBTRIB, V_IDTRIMPSTII, V_PREDBCTMP1,
                         V_CDREGRAITALIQ, V_CDFISCOPERREGRA, V_IDDIFEALIQREGRA,
                         V_IDDIFALIQCUSPRREGRA, V_CDBENEFFISCAL
                    FROM ALIQTEMP
                   WHERE (NRALIQTEMP = V_ALIQTEMP);

                  /* 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;

                  SELECT MAX(CDIMPOSTO)
                    INTO V_IMPOICMS
                    FROM IMPOSTONFE N, IMPOSTO I
                   WHERE N.CDIMPOSTONFE = I.CDIMPOSTONFE
                     AND N.CDIMPOSTONFE = '00'
                     AND I.CDIMPOSTO = C_INCIDITEM.CDIMPOTEMP;

                  IF (V_IMPOICMS IS NOT NULL) THEN
                     IF (V_CDFISCOPERREGRA IS NOT NULL) THEN
                        IF (LENGTH(V_CDFISCOPERREGRA) < 4) THEN
                           V_CDFISCOPERREGRA := V_CFOP1DIGT||V_CDFISCOPERREGRA;
                        END IF;
                        V_FISOPEITEM := V_CDFISCOPERREGRA;
                        UPDATE ITEMPRODUTO
                           SET CDFISOPEITEM = V_CDFISCOPERREGRA
                         WHERE CDFILIAL     = P_FILIAL
                           AND NRLANCTONF  = P_LANCTONF
                           AND NRSEQITPROD = C_ITEMPROD.NRSEQITPROD;
                     END IF;
                  END IF;

                  IF V_CDGRUPOFISCAUX IS NULL THEN
                     CONSULTA_CST_NFE(W_E, P_EMPRESA, C_ITEMPROD.CDARVPROD, P_INSCESTA, P_TIPOOPER, V_CDGRUPOFISC,C_INCIDITEM.CDIMPOTEMP, V_IDINTEREST, V_IDINTERNAC, P_FILIAL, P_LANCTONF, '', V_CDSITTRIBTMP, V_IDMODBCNFE, V_IDMODBCSTNFE, V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, V_IDMOTIDESSTNFE, C_ITEMPROD.IDORIGEMPROD);
                  ELSE
                     CONSULTA_CST_NFE(W_E, P_EMPRESA, C_ITEMPROD.CDARVPROD, P_INSCESTA, P_TIPOOPER, V_CDGRUPOFISCAUX,C_INCIDITEM.CDIMPOTEMP, V_IDINTEREST, V_IDINTERNAC, P_FILIAL, P_LANCTONF, '', V_CDSITTRIBTMP, V_IDMODBCNFE, V_IDMODBCSTNFE, V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, V_IDMOTIDESSTNFE, C_ITEMPROD.IDORIGEMPROD);
                  END IF;

                  V_IMPOICMS := NULL;
                  V_CST1DIGT := NULL;

                  SELECT MAX(CDIMPOSTO)
                    INTO V_IMPOICMS
                    FROM IMPOSTONFE N, IMPOSTO I
                   WHERE N.CDIMPOSTONFE = I.CDIMPOSTONFE
                     AND N.CDIMPOSTONFE = '00'
                     AND I.CDIMPOSTO = C_INCIDITEM.CDIMPOTEMP;

                  IF (V_IMPOICMS IS NOT NULL) THEN
                     IF V_IDORIGDESTNF = 'L' THEN
                        Begin
                           SELECT MAX(CDCSTDIG1PROD)
                             INTO V_CST1DIGT
                             FROM PRODUTO
                            WHERE (CDARVPROD = C_ITEMPROD.CDARVPROD);

                           IF V_CST1DIGT IS NULL THEN
                              SELECT MAX(CDCSTDIG1SAI)
                              INTO   V_CST1DIGT
                              FROM INSCRESTAD
                              WHERE CDEMPRESA  = P_EMPRESA AND
                                    CDINSCESTA = P_INSCESTA;
                           END IF;
                        Exception
                           When No_Data_Found Then
                              V_CST1DIGT := Null;
                        End;
                     ELSIF V_IDORIGDESTNF = 'C' THEN
                        Begin
                           SELECT MAX(CDCSTDIG1PROD)
                             INTO V_CST1DIGT
                             FROM PRODUTO
                            WHERE (CDARVPROD = C_ITEMPROD.CDARVPROD);

                           IF V_CST1DIGT IS NULL THEN
                              SELECT MAX(CDCSTDIG1CLI)
                                INTO V_CST1DIGT
                                FROM NOTAFISCAL N, CLIENTE C
                               WHERE CDFILIAL     = P_FILIAL    AND
                                     NRLANCTONF   = P_LANCTONF  AND
                                     N.CDCLIENTE  = C.CDCLIENTE;
                           END IF;
                        Exception
                           When No_Data_Found Then
                              V_CST1DIGT := Null;
                        End;
                     ELSE
                        Begin
                           SELECT MAX(CDCSTDIG1PROD)
                             INTO V_CST1DIGT
                             FROM PRODUTO
                            WHERE (CDARVPROD = C_ITEMPROD.CDARVPROD);

                           IF V_CST1DIGT IS NULL THEN
                              SELECT MAX(CDCSTDIG1ENT)
                                INTO   V_CST1DIGT
                                FROM NOTAFISCAL N, FORNECEDOR F
                               WHERE CDFILIAL     = P_FILIAL   AND
                                    NRLANCTONF    = P_LANCTONF AND
                                    N.CDFORNECED  = F.CDFORNECED;
                           END IF;
                        Exception
                           When No_Data_Found Then
                              V_CST1DIGT := Null;
                        End;
                     END IF;

                     IF (V_IDUTORIGPROD = 'S') AND (C_ITEMPROD.IDORIGEMPROD = 'E') AND (NVL(V_IDNFGERADAVIAXML, 'N') <> 'S') THEN
                        V_CST1DIGT := '2';
                     END IF;

                     IF (V_IMPOICMS IS NOT NULL) THEN
                        IF (V_CDSITTRIBTMP IS NOT NULL) THEN

                           UPDATE ITEMPRODUTO
                              SET CDSITUTRIBPR  = V_CST1DIGT||V_CDSITTRIBTMP

                            WHERE CDFILIAL      = P_FILIAL AND
                                  NRLANCTONF    = P_LANCTONF AND
                                  NRSEQITPROD   = C_ITEMPROD.NRSEQITPROD;

                           V_SITUTRIBPR := V_CST1DIGT||V_CDSITTRIBTMP;
                        END IF;
                     END IF;
                  END IF;

                  SELECT MAX(CDIMPOSTO)
                    INTO V_IMPOICMS
                    FROM IMPOSTONFE N, IMPOSTO I
                   WHERE N.CDIMPOSTONFE = I.CDIMPOSTONFE
                     AND N.CDIMPOSTONFE = '00'
                     AND I.CDIMPOSTO = C_INCIDITEM.CDIMPOTEMP;

                  UPDATE ITEMPROIMPOS
                  SET CDFISCALIT = C_INCIDITEM.CDFISCTEMP,
                      CDSITUTRIBITNFE = V_CDSITTRIBTMP,
                      IDMODBCITNFE    = V_IDMODBCNFE,
                      IDMODBCSTITNFE  = V_IDMODBCSTNFE,
                      CDTPCREDPICOITE = V_CDTPCRPICOSTNFE,
                      CDNATUBCALPCIT  = V_CDNATUBCPCSTNFE,
                      IDMOTDESONERAIT = V_IDMOTIDESSTNFE,
                      CDREGRAIT       = V_CDREGRAITALIQ,
                      CDENQLEGALIPI   = C_INCIDITEM.CDENQLEGALIPI,
                      CDBENEFFISCAL   = V_CDBENEFFISCAL,
                      CDCEST          = NVL(V_CDCEST, CDCEST)
                  WHERE CDFILIAL      = P_FILIAL                AND
                        NRLANCTONF    = P_LANCTONF              AND
                        NRSEQITPROD   = C_ITEMPROD.NRSEQITPROD  AND
                        CDIMPOSTO     = C_INCIDITEM.CDIMPOTEMP;

                  UPDATE TRABITPROIMPOS
                  SET CDFISCIMPOIT    = C_INCIDITEM.CDFISCTEMP,
                      CDSTRIBITNFE    = V_CDSITTRIBTMP,
                      IDMODBCITEMNFE  = V_IDMODBCNFE,
                      IDMODBCSTITENFE = V_IDMODBCSTNFE,
                      CDTPCREDPICOITE = V_CDTPCRPICOSTNFE,
                      CDNATUBCALPCIT  = V_CDNATUBCPCSTNFE,
                      IDMOTDESOTRABIT = V_IDMOTIDESSTNFE,
                      CDREGRATRABIT   = V_CDREGRAITALIQ,
                      CDENQLEGALIPI   = C_INCIDITEM.CDENQLEGALIPI,
                      CDBENEFFISCAL   = V_CDBENEFFISCAL,
                      CDCEST          = NVL(V_CDCEST, CDCEST)
                  WHERE CDFILIMPOIT   = P_FILIAL               AND
                        NRLANCIMPOIT  = P_LANCTONF             AND
                        NRSEQIMPOIT   = C_ITEMPROD.NRSEQITPROD AND
                        CDIMPOSTOIT   = C_INCIDITEM.CDIMPOTEMP;

                  UPDATE ITEMPROIMPOS
                  SET CDFISCALIT = '2'
                  WHERE CDFILIAL    = P_FILIAL    AND
                        NRLANCTONF  = P_LANCTONF  AND
                        VRPERREDBCIT > 0.00       AND
                        NRITPROIMPOS = '2';

                  UPDATE TRABITPROIMPOS
                  SET CDFISCIMPOIT = '2'
                  WHERE CDFILIMPOIT  = P_FILIAL   AND
                        NRLANCIMPOIT = P_LANCTONF AND
                        VRREDBCIMPOIT > 0.00      AND
                        NRSEQITPRO = '2';

                  DELETE INCITEMP
                  WHERE NRINCITEMP = V_INCITEMP;

                  V_FISOPEITEM      := NVL(V_CDFISCOPERREGRA, V_FISOPEITEM);
                  V_DSCDFISOPEIT    := NVL(V_DSCDFISOPEITREGRA, V_DSCDFISOPEIT);
                  V_DIFALIQITEM     := NVL(V_IDDIFEALIQREGRA, V_DIFALIQITEM);
                  V_IDDIFALIQCUSPRC := NVL(V_IDDIFALIQCUSPRREGRA, V_IDDIFALIQCUSPRC);

                  IF (V_IMPOICMS IS NOT NULL) THEN
                     IF NOT V_FISOPEITEM IS NULL THEN
                        UPDATE NOTAFISCAL
                        SET CDFISOPENTF = NVL(V_CDFISCOPERREGRA, V_FISOPEITEM),
                            DSCDFISOPENF = NVL(V_DSCDFISOPEITREGRA, V_DSCDFISOPEIT)
                        WHERE CDFILIAL   = P_FILIAL   AND
                              NRLANCTONF = P_LANCTONF;
                     END IF;
                  END IF;

                  V_CDGRUPOFISCAUX := NULL;

                  SELECT MAX(G.CDGRUPOFISC)
                    INTO V_CDGRUPOFISCAUX
                    FROM GRUPOFISCIMPFIL G,
                         (SELECT DECODE('E', 'E', CDFILIRECE, CDFILIEMIT) AS CDFILIAL
                            FROM NOTAFISCAL
                           WHERE CDFILIAL = P_FILIAL
                                 AND NRLANCTONF = P_LANCTONF) F
                   WHERE G.CDFILIAL = F.CDFILIAL
                     AND NOT G.CDGRUPOFISC IS NULL
                     AND G.CDIMPOSTO = C_INCIDITEM.CDIMPOTEMP;

                  IF V_IDORIGDESTNF = 'F' THEN
                     SELECT NVL(MAX(G.CDGRUPOFISC), V_CDGRUPOFISCAUX)
                       INTO V_CDGRUPOFISCAUX
                       FROM GRFISIMPIEFORN G,
                            (SELECT CDFORNECED
                               FROM NOTAFISCAL
                              WHERE CDFILIAL = P_FILIAL
                                AND NRLANCTONF = P_LANCTONF) N
                      WHERE G.CDFORNECED = N.CDFORNECED
                        AND G.CDEMPRESA = P_EMPRESA
                        AND G.CDINSCESTA = P_INSCESTA
                        AND NOT G.CDGRUPOFISC IS NULL
                        AND G.CDIMPOSTO = C_INCIDITEM.CDIMPOTEMP;
                  ELSE
                     SELECT NVL(MAX(G.CDGRUPOFISC), V_CDGRUPOFISCAUX)
                       INTO V_CDGRUPOFISCAUX
                       FROM GRFISIMPIECLIE G,
                            (SELECT CDCLIENTE
                               FROM NOTAFISCAL
                              WHERE CDFILIAL = P_FILIAL
                                AND NRLANCTONF = P_LANCTONF) N
                      WHERE G.CDCLIENTE = N.CDCLIENTE
                        AND G.CDEMPRESA = P_EMPRESA
                        AND G.CDINSCESTA = P_INSCESTA
                        AND NOT G.CDGRUPOFISC IS NULL
                        AND G.CDIMPOSTO = C_INCIDITEM.CDIMPOTEMP;
                  END IF;

                  IF (V_CDGRUPOFISCAUX IS NOT NULL) THEN
                     CONSULTA_CFOP(P_ENTRSAID, P_EMPRESA, C_ITEMPROD.CDARVPROD, P_INSCESTA, P_TIPOOPER, V_PAISCFOP,
                                   V_ESTACFOP, V_PAISDEST, V_ESTADEST, P_FILIAL, P_LANCTONF, V_CDGRUPOFISCAUX, P_INIVALID, C_ITEMPROD.IDORIGEMPROD);
                  ELSE
                     CONSULTA_CFOP(P_ENTRSAID, P_EMPRESA, C_ITEMPROD.CDARVPROD, P_INSCESTA, P_TIPOOPER, V_PAISCFOP,
                                   V_ESTACFOP, V_PAISDEST, V_ESTADEST, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC, P_INIVALID, C_ITEMPROD.IDORIGEMPROD);
                  END IF;

                  -- ALTERA NATUREZA DE OPERAÇÃO DA NOTA FISCAL CASO NÃO EXISTA
                  IF (V_DSCDFISOPEITREGRA IS NOT NULL) THEN
                     UPDATE NOTAFISCAL
                        SET DSCDFISOPENF = V_DSCDFISOPEITREGRA
                      WHERE CDFILIAL   = P_FILIAL   AND
                            NRLANCTONF = P_LANCTONF;
                  ELSE
                     UPDATE NOTAFISCAL
                        SET DSCDFISOPENF = (SELECT MAX(DSCFOPTMP)
                                              FROM CFOPTEMP
                                             WHERE NRCFOPTEMP = V_CFOPTEMP)
                      WHERE CDFILIAL   = P_FILIAL
                        AND NRLANCTONF = P_LANCTONF
                        AND DSCDFISOPENF IS NULL;

                  END IF;

                  SELECT MAX(CDFISOPETMP), MAX(CDSUFCFOPTMP), MAX(IDDIFALIQTMP),
                         MAX(DSCFOPTMP), NVL(MAX(IDDIFALIQCUSPRC),W_N)
                   INTO V_FISOPEITEM, V_SUFXCFOPPR, V_DIFALIQITEM,
                        V_DSCDFISOPEIT, V_IDDIFALIQCUSPRC
                   FROM CFOPTEMP
                   WHERE NRCFOPTEMP = V_CFOPTEMP;

                   V_FISOPEITEM      := NVL(V_CDFISCOPERREGRA, V_FISOPEITEM);
                   V_DSCDFISOPEIT    := NVL(V_DSCDFISOPEITREGRA, V_DSCDFISOPEIT);
                   V_DIFALIQITEM     := NVL(V_IDDIFEALIQREGRA, V_DIFALIQITEM);
                   V_IDDIFALIQCUSPRC := NVL(V_IDDIFALIQCUSPRREGRA, V_IDDIFALIQCUSPRC);

                   -- ALTERA O CFOP DO ITEM E
                   UPDATE ITEMPRODUTO
                   SET CDFISOPEITEM = NVL(V_CDFISCOPERREGRA, V_FISOPEITEM),
                       CDSUFXCFOPPR = V_SUFXCFOPPR,
                       DSCDFISOPEIT = V_DSCDFISOPEIT
                   WHERE CDFILIAL    = P_FILIAL   AND
                         NRLANCTONF  = P_LANCTONF AND
                         NRSEQITPROD = C_ITEMPROD.NRSEQITPROD;

                  DELETE CFOPTEMP
                   WHERE NRCFOPTEMP = V_CFOPTEMP;


                  SELECT MAX(IDORDPRIMDFENT)
                    INTO V_IDORDPRIMDFENT
                    FROM PARAMGERAL;


                  CONSULTA_CSOSN(P_ENTRSAID, P_EMPRESA, C_ITEMPROD.CDARVPROD, P_INSCESTA, P_TIPOOPER, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC, V_IDINTEREST, V_CDFISCOPERSN);

                  IF (NOT V_CDFISCOPERSN IS NULL) AND (LENGTH(V_CDFISCOPERSN) = 4) THEN
                     UPDATE ITEMPRODUTO
                        SET CDFISCOPERSN = V_CDFISCOPERSN
                      WHERE CDFILIAL    = P_FILIAL
                        AND NRLANCTONF  = P_LANCTONF
                        AND NRSEQITPROD = C_ITEMPROD.NRSEQITPROD;
                  ELSE
                     UPDATE ITEMPRODUTO
                        SET CDFISCOPERSN = (SELECT MAX(I.CDFISCOPERSN)
                                              FROM ITEMPRODUTO I
                                             WHERE I.CDFILIAL   = V_FILIORIG
                                               AND I.NRLANCTONF = V_DEVOLORIG
                                               AND I.CDPRODUTO  = V_CDPRODORIG)
                      WHERE CDFILIAL    = P_FILIAL
                        AND NRLANCTONF  = P_LANCTONF
                        AND NRSEQITPROD = C_ITEMPROD.NRSEQITPROD;
                  END IF;

                  IF (V_CDFISCOPERREGRA IS NOT NULL) THEN
                     V_DSCDFISOPEITREGRA := SUBSTR(DESCRICAO_CFOP(V_CDFISCOPERREGRA),1,45);
                  END IF;

                  IF (V_IMPOICMS IS NOT NULL) THEN
                     IF NOT V_FISOPEITEM IS NULL THEN
                        UPDATE ITEMPRODUTO
                        SET CDFISOPEITEM = NVL(V_CDFISCOPERREGRA, V_FISOPEITEM),
                            CDSUFXCFOPPR = V_SUFXCFOPPR,
                            DSCDFISOPEIT =  NVL(V_DSCDFISOPEITREGRA, V_DSCDFISOPEIT)
                        WHERE CDFILIAL    = P_FILIAL                 AND
                              NRLANCTONF  = P_LANCTONF               AND
                              NRSEQITPROD = C_ITEMPROD.NRSEQITPROD;

                        IF (V_IDOPERDEVONF = w_S) THEN
                           UPDATE TRABITPROIMPOS
                           SET CDSTRIBIMPOIT = V_SITUTRIBPR,
                               CDFOPERIMPOIT = NVL(V_CDFISCOPERREGRA, V_FISOPEITEM),
                               CDSCFOPIMPOIT = V_SUFXCFOPPR
                           WHERE CDFILIMPOIT = P_FILIAL                AND
                                 NRLANCIMPOIT = P_LANCTONF             AND
                                 NRSEQIMPOIT = C_ITEMPROD.NRSEQITPROD;
                        END IF;
                     ELSE
                        UPDATE ITEMPRODUTO
                           SET CDFISOPEITEM = NVL(V_CDFISCOPERREGRA, V_CFOP1DIGT || SUBSTR(CDFISOPEITEM,2,10))
                         WHERE CDFILIAL    = P_FILIAL                 AND
                               NRLANCTONF  = P_LANCTONF               AND
                               NRSEQITPROD = C_ITEMPROD.NRSEQITPROD;

                        IF (V_IDOPERDEVONF = w_S) THEN
                           UPDATE TRABITPROIMPOS
                           SET CDFOPERIMPOIT = V_CFOP1DIGT || SUBSTR(CDFOPERIMPOIT,2,10)
                           WHERE CDFILIMPOIT = P_FILIAL                AND
                                 NRLANCIMPOIT = P_LANCTONF             AND
                                 NRSEQIMPOIT = C_ITEMPROD.NRSEQITPROD;
                        END IF;
                     END IF;
                  END IF;

                  DELETE CFOPTEMP
                  WHERE NRCFOPTEMP = V_CFOPTEMP;

                  SELECT MAX(CDSITTRIBTMP) INTO V_SITUTRIBPR
                  FROM CSTTEMP
                  WHERE NRCSTTEMP = V_CSTTEMP;

                  IF V_CDSITTRIBTMP IS NOT NULL THEN
                     V_SITUTRIBPR := V_CST1DIGT||V_CDSITTRIBTMP;
                  END IF;

                  IF P_ENTRSAID = W_E THEN
                     IF (SUBSTR(C_ITEMPROD.CDSITUTRIBPR,1,1) = SUBSTR(V_SITUTRIBPR,1,1)) OR
                        (C_ITEMPROD.CDSITUTRIBPR IS NULL) THEN

                        IF (V_IMPOICMS IS NOT NULL) THEN
                           UPDATE ITEMPRODUTO
                           SET CDSITUTRIBPR  = V_SITUTRIBPR
                           WHERE CDFILIAL    = P_FILIAL   AND
                                 NRLANCTONF  = P_LANCTONF AND
                                 NRSEQITPROD = C_ITEMPROD.NRSEQITPROD;
                        END IF;
                     END IF;
                  ELSIF P_ENTRSAID = W_S THEN
                     IF (SUBSTR(C_ITEMPROD.CDSITUTRIBPR,1,1) = SUBSTR(V_SITUTRIBPR,1,1)) OR
                        (C_ITEMPROD.CDSITUTRIBPR IS NULL) THEN

                        UPDATE ITEMPRODUTO
                        SET CDSITUTRIBPR  = V_SITUTRIBPR
                        WHERE CDFILIAL    = P_FILIAL               AND
                              NRLANCTONF  = P_LANCTONF             AND
                              NRSEQITPROD = C_ITEMPROD.NRSEQITPROD AND
                              CDSITUTRIBPR IS NULL;
                     END IF;
                  END IF;

                  DELETE CSTTEMP
                  WHERE NRCSTTEMP = V_CSTTEMP;
               END LOOP;
            END IF;
         END LOOP;

         IF (V_IDOPERDEVONF <> 'S') OR ( V_IDNFRETIND = 'S') OR (V_IDCOMPRABONI = 'S')THEN
            IF (V_IDNFRETIND = 'S') OR (V_IDCOMPRABONI = 'S') THEN
               FOR C_ITEMENCARGO IN (SELECT IE.CDENCARGO AS CDENCARGO, (VRITEMENCA-NVL(I.VRICMSSTITORIG,0)) VRITEMENCA, IDENCARGO,
                                            EN.CDCTBLENTREN, EN.CDCTBLSAIDEN
                                       FROM ENCARGO EN, ITEMENCARGO IE, (SELECT SUM(VRICMSSTITORIG) VRICMSSTITORIG
                                                                           FROM ITEMPRODUTO
                                                                          WHERE CDFILIAL   = P_FILIAL
                                                                            AND NRLANCTONF = P_LANCTONF) I
                                      WHERE (IE.CDFILIAL   = P_FILIAL)
                                        AND (IE.NRLANCTONF = P_LANCTONF)
                                        AND (IE.VRITEMENCA-NVL(I.VRICMSSTITORIG,0) > 0)
                                        AND (EN.CDENCARGO  = IE.CDENCARGO)) LOOP

                  SELECT SUM(VRTOTAITEM - VRDESCITEM) INTO V_TOTAPRODENCA
                  FROM ITEMPRODUTO IP
                  WHERE (IP.CDFILIAL   = P_FILIAL)   AND
                        (IP.NRLANCTONF = P_LANCTONF);

                  IF V_TOTAPRODENCA <> 0 THEN
                     FOR C_ATUAVRCONT IN(SELECT IP.NRSEQITPROD, (IP.VRTOTAITEM - IP.VRDESCITEM) AS VRLIQUIDO,
                                                IP.CDFISOPEITEM, IP.CDPRODUTO
                                           FROM ITEMPRODUTO IP, TPOPERCFOP T, NOTAFISCAL N
                                          WHERE IP.CDFILIAL     = P_FILIAL
                                            AND IP.NRLANCTONF   = P_LANCTONF
                                            AND IP.CDFILIAL     = N.CDFILIAL
                                            AND IP.NRLANCTONF   = N.NRLANCTONF
                                            AND IP.CDFISOPEITEM = T.CDFISCOPER
                                            AND N.CDTIPOOPER    = T.CDTIPOOPER
                                            AND T.IDCOMPOEVENC  = w_S)LOOP

                        IF (C_ITEMENCARGO.IDENCARGO = W_A) THEN
                           V_VRBRUTO := (C_ITEMENCARGO.VRITEMENCA/V_TOTAPRODENCA);
                        ELSIF (C_ITEMENCARGO.IDENCARGO = W_D) THEN
                           V_VRBRUTO := - (C_ITEMENCARGO.VRITEMENCA/V_TOTAPRODENCA);
                        ELSE
                           V_VRBRUTO := 0;
                        END IF;

                        IF (C_ITEMENCARGO.CDCTBLENTREN IS NULL) THEN
                           V_VRCONTAB := V_VRBRUTO;
                        ELSE
                           V_VRCONTAB := 0;
                        END IF;

                        UPDATE ITEMPRODUTO
                        SET VRBRUTITEM = VRBRUTITEM + (V_VRBRUTO  * (VRTOTAITEM - VRDESCITEM)),
                            VRCONTITEM = VRCONTITEM + (V_VRCONTAB * (VRTOTAITEM - VRDESCITEM))
                        WHERE CDFILIAL    = P_FILIAL   AND
                              NRLANCTONF  = P_LANCTONF AND
                              NRSEQITPROD = C_ATUAVRCONT.NRSEQITPROD;

                     END LOOP;
                  END IF;
               END LOOP;
            ELSE
               FOR C_ITEMENCARGO IN (SELECT IE.CDENCARGO AS CDENCARGO, (VRITEMENCA-NVL(I.VRICMSSTITORIG,0)) VRITEMENCA, IDENCARGO,
                                            EN.CDCTBLENTREN, EN.CDCTBLSAIDEN
                                       FROM ENCARGO EN, ITEMENCARGO IE, (SELECT SUM(VRICMSSTITORIG) VRICMSSTITORIG
                                                                           FROM ITEMPRODUTO
                                                                          WHERE CDFILIAL   = P_FILIAL
                                                                            AND NRLANCTONF = P_LANCTONF) I
                                      WHERE (IE.CDFILIAL   = P_FILIAL)
                                        AND (IE.NRLANCTONF = P_LANCTONF)
                                        AND (IE.VRITEMENCA-NVL(I.VRICMSSTITORIG,0) > 0)
                                        AND (EN.CDENCARGO  = IE.CDENCARGO)) LOOP

                  SELECT SUM(VRTOTAITEM - VRDESCITEM) INTO V_TOTAPRODENCA
                  FROM ITEMPRODUTO IP
                  WHERE (IP.CDFILIAL   = P_FILIAL)   AND
                        (IP.NRLANCTONF = P_LANCTONF);

                  IF V_TOTAPRODENCA <> 0 THEN
                     FOR C_ATUAVRCONT IN (SELECT IP.NRSEQITPROD, (VRTOTAITEM - VRDESCITEM) AS VRLIQUIDO
                                           FROM ITEMPRODUTO IP
                                           WHERE (IP.CDFILIAL    = P_FILIAL) AND
                                                 (IP.NRLANCTONF  = P_LANCTONF)) LOOP

                        IF (C_ITEMENCARGO.IDENCARGO = W_A) THEN
                           V_VRBRUTO := (C_ITEMENCARGO.VRITEMENCA/V_TOTAPRODENCA);
                        ELSIF (C_ITEMENCARGO.IDENCARGO = W_D) THEN
                           V_VRBRUTO := - (C_ITEMENCARGO.VRITEMENCA/V_TOTAPRODENCA);
                        ELSE
                           V_VRBRUTO := 0;
                        END IF;

                        IF (C_ITEMENCARGO.CDCTBLENTREN IS NULL) THEN
                           V_VRCONTAB := V_VRBRUTO;
                        ELSE
                           V_VRCONTAB := 0;
                        END IF;

                        UPDATE ITEMPRODUTO
                        SET VRBRUTITEM = VRBRUTITEM + (V_VRBRUTO  * (VRTOTAITEM - VRDESCITEM)),
                            VRCONTITEM = VRCONTITEM + (V_VRCONTAB * (VRTOTAITEM - VRDESCITEM))
                        WHERE CDFILIAL    = P_FILIAL   AND
                              NRLANCTONF  = P_LANCTONF AND
                              NRSEQITPROD = C_ATUAVRCONT.NRSEQITPROD;

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

         FOR C_QTITEM IN (SELECT NRSEQITPROD
                          FROM ITEMPRODUTO
                          WHERE (CDFILIAL   = P_FILIAL)   AND
                                (NRLANCTONF = P_LANCTONF) AND
                                (QTITEMPROD = 0)) LOOP

            DELETE TRABITPROIMPOS
            WHERE (CDFILIMPOIT  = P_FILIAL) AND
                  (NRLANCIMPOIT = P_LANCTONF) AND
                  (NRSEQIMPOIT = C_QTITEM.NRSEQITPROD);
         END LOOP;

         SELECT MAX(CDFILIMPOIT||NRLANCIMPOIT) AS IMPOSITEM
         INTO V_IMPOSITEM
         FROM TRABITPROIMPOS
         WHERE (CDFILIMPOIT  = P_FILIAL) AND
               (NRLANCIMPOIT = P_LANCTONF);

         IF V_IMPOSITEM IS NULL THEN
            DELETE TRABIMPOSNFTOT
            WHERE (CDFILIMPTOT  = P_FILIAL) AND
                  (NRLANCIMPTOT = P_LANCTONF);
         END IF;

         DELETE ITEMPRODUTO
         WHERE (CDFILIAL   = P_FILIAL)   AND
               (NRLANCTONF = P_LANCTONF) AND
               (QTITEMPROD = 0);

         FOR C_IMPOSPROD IN (SELECT IT.CDIMPOSTOIT,
                                    NVL(SUM(IT.VRIMPOSIT),0)  AS VRIMPOSTOIT,
                                    NVL(SUM(IT.VRBCALCIMPOIT),0) AS VRBASECALCIT
                             FROM TRABITPROIMPOS IT
                             WHERE (IT.CDFILIMPOIT  = P_FILIAL) AND
                                   (IT.NRLANCIMPOIT = P_LANCTONF)
                             GROUP BY IT.CDIMPOSTOIT) LOOP

            UPDATE TRABIMPOSNFTOT
            SET VRIMPOSTOT   = C_IMPOSPROD.VRIMPOSTOIT,
                VRBCALIMPTOT = C_IMPOSPROD.VRBASECALCIT
            WHERE (CDFILIMPTOT  = P_FILIAL)   AND
                  (NRLANCIMPTOT = P_LANCTONF) AND
                  (CDIMPOSTOT   = C_IMPOSPROD.CDIMPOSTOIT);
         END LOOP;

         IF V_IDOPERDEVONF <> 'S' THEN
            FOR C_PREDBCALC IN (SELECT NRSEQIMPOIT, CDIMPOSTOIT, CDSTRIBIMPOIT, CDFOPERIMPOIT,
                                       CDSCFOPIMPOIT, VRCONTIMPOIT, VRREDBCIMPOIT, VRBCALCIMPOIT,
                                       IDVALORINFO, P.CDARVPROD, I.IDORIGEMPROD, T.CDCEST
                                FROM TRABITPROIMPOS T, ITEMPRODUTO I, PRODUTO P
                                WHERE (CDFILIMPOIT   = P_FILIAL)   AND
                                      (NRLANCIMPOIT  = P_LANCTONF) AND
                                      (T.CDFILIMPOIT = I.CDFILIAL) AND
                                      (T.NRLANCIMPOIT = I.NRLANCTONF) AND
                                      (T.NRSEQIMPOIT = I.NRSEQITPROD) AND
                                      (I.CDPRODUTO = P.CDPRODUTO) AND
                                      (VRREDBCIMPOIT > 0)) LOOP

               DELETE ITEMPROIMPOS
               WHERE CDFILIAL     = P_FILIAL                AND
                     NRLANCTONF   = P_LANCTONF              AND
                     NRSEQITPROD  = C_PREDBCALC.NRSEQIMPOIT AND
                     CDIMPOSTO    = C_PREDBCALC.CDIMPOSTOIT AND
                     NRITPROIMPOS = W_2;

               /*VERIFICA CST POR IMPOSTO*/
               V_IMPOICMS := NULL;
               V_CDGRUPOFISCAUX := NULL;


               SELECT MAX(G.CDGRUPOFISC)
                 INTO V_CDGRUPOFISCAUX
                 FROM GRUPOFISCIMPFIL G,
                      (SELECT DECODE('E', 'E', CDFILIRECE, CDFILIEMIT) AS CDFILIAL
                         FROM NOTAFISCAL
                        WHERE CDFILIAL = P_FILIAL
                              AND NRLANCTONF = P_LANCTONF) F
                WHERE G.CDFILIAL = F.CDFILIAL
                  AND NOT G.CDGRUPOFISC IS NULL
                  AND G.CDIMPOSTO = C_PREDBCALC.CDIMPOSTOIT;

               IF V_IDORIGDESTNF = 'F' THEN
                  SELECT NVL(MAX(G.CDGRUPOFISC), V_CDGRUPOFISCAUX)
                    INTO V_CDGRUPOFISCAUX
                    FROM GRFISIMPIEFORN G,
                         (SELECT CDFORNECED
                            FROM NOTAFISCAL
                           WHERE CDFILIAL = P_FILIAL
                             AND NRLANCTONF = P_LANCTONF) N
                   WHERE G.CDFORNECED = N.CDFORNECED
                     AND G.CDEMPRESA = P_EMPRESA
                     AND G.CDINSCESTA = P_INSCESTA
                     AND NOT G.CDGRUPOFISC IS NULL
                     AND G.CDIMPOSTO = C_PREDBCALC.CDIMPOSTOIT;
               ELSE
                  SELECT NVL(MAX(G.CDGRUPOFISC), V_CDGRUPOFISCAUX)
                    INTO V_CDGRUPOFISCAUX
                    FROM GRFISIMPIECLIE G,
                         (SELECT CDCLIENTE
                            FROM NOTAFISCAL
                           WHERE CDFILIAL = P_FILIAL
                             AND NRLANCTONF = P_LANCTONF) N
                   WHERE G.CDCLIENTE = N.CDCLIENTE
                     AND G.CDEMPRESA = P_EMPRESA
                     AND G.CDINSCESTA = P_INSCESTA
                     AND NOT G.CDGRUPOFISC IS NULL
                     AND G.CDIMPOSTO = C_PREDBCALC.CDIMPOSTOIT;
               END IF;

               IF V_CDGRUPOFISCAUX IS NULL THEN
                  CONSULTA_CST_NFE(W_E, P_EMPRESA, C_PREDBCALC.CDARVPROD, P_INSCESTA, P_TIPOOPER, V_CDGRUPOFISC,C_PREDBCALC.CDIMPOSTOIT, V_IDINTEREST, V_IDINTERNAC, P_FILIAL, P_LANCTONF, '', V_CDSITTRIBTMP, V_IDMODBCNFE, V_IDMODBCSTNFE, V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, V_IDMOTIDESSTNFE, C_PREDBCALC.IDORIGEMPROD);
               ELSE
                  CONSULTA_CST_NFE(W_E, P_EMPRESA, C_PREDBCALC.CDARVPROD, P_INSCESTA, P_TIPOOPER, V_CDGRUPOFISCAUX,C_PREDBCALC.CDIMPOSTOIT, V_IDINTEREST, V_IDINTERNAC, P_FILIAL, P_LANCTONF, '',V_CDSITTRIBTMP, V_IDMODBCNFE, V_IDMODBCSTNFE, V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, V_IDMOTIDESSTNFE, C_PREDBCALC.IDORIGEMPROD);
               END IF;

               SELECT MAX(CDIMPOSTO)
                 INTO V_IMPOICMS
                 FROM IMPOSTONFE N, IMPOSTO I
                WHERE N.CDIMPOSTONFE = I.CDIMPOSTONFE
                  AND N.CDIMPOSTONFE = '00'
                  AND I.CDIMPOSTO = C_PREDBCALC.CDIMPOSTOIT;

               INSERT INTO ITEMPROIMPOS(
                  CDFILIAL, NRLANCTONF, NRSEQITPROD, CDIMPOSTO, NRITPROIMPOS, CDFISCALIT, CDSITUTRIBIT,
                  CDFISCOPERIT, CDSUFXCFOPIT, VRALIQITEM, VRPERREDBCIT, VRPARDEDIT, VRCONTITIMP,
                  VRBASECALCIT, VRIMPOSTOIT, IDERROSIMPIT, IDAVISIMPIT, CDSITUTRIBITNFE, IDMODBCITNFE, IDMODBCSTITNFE,
                  CDTPCREDPICOITE, CDNATUBCALPCIT, IDMOTDESONERAIT, CDREGRAIT, CDCEST)
               VALUES(
                  P_FILIAL, P_LANCTONF, C_PREDBCALC.NRSEQIMPOIT, C_PREDBCALC.CDIMPOSTOIT, W_2, W_2,
                  C_PREDBCALC.CDSTRIBIMPOIT, C_PREDBCALC.CDFOPERIMPOIT, C_PREDBCALC.CDSCFOPIMPOIT, 0,
                  0, 0, ROUND(C_PREDBCALC.VRCONTIMPOIT - C_PREDBCALC.VRBCALCIMPOIT,5), 0, 0, W_00000, W_00000,
                  V_CDSITTRIBTMP, V_IDMODBCNFE, V_IDMODBCSTNFE, V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, V_IDMOTIDESSTNFE, V_CDREGRAITALIQ, C_PREDBCALC.CDCEST);

               DELETE TRABITPROIMPOS
               WHERE CDFILIMPOIT  = P_FILIAL   AND
                     NRLANCIMPOIT = P_LANCTONF AND
                     NRSEQIMPOIT  = C_PREDBCALC.NRSEQIMPOIT AND
                     CDIMPOSTOIT  = C_PREDBCALC.CDIMPOSTOIT AND
                     NRSEQITPRO   = W_2;

               INSERT INTO TRABITPROIMPOS(
                  CDFILIMPOIT, NRLANCIMPOIT, NRSEQIMPOIT, CDIMPOSTOIT, NRSEQITPRO, CDFISCIMPOIT,
                  CDSTRIBIMPOIT, CDFOPERIMPOIT, CDSCFOPIMPOIT, VRALIQIMPOIT, VRREDBCIMPOIT, VRPDEDIMPOIT,
                  VRCONTIMPOIT, VRBCALCIMPOIT, VRIMPOSIT, IDERRIMPOIT, IDAVISIMPOIT, IDVALORINFO,
                  CDSTRIBITNFE, IDMODBCITEMNFE, IDMODBCSTITENFE, CDTPCREDPICOITE, CDNATUBCALPCIT, IDMOTDESOTRABIT, CDREGRATRABIT, CDCEST)
               VALUES(
                  P_FILIAL, P_LANCTONF, C_PREDBCALC.NRSEQIMPOIT, C_PREDBCALC.CDIMPOSTOIT, W_2, W_2,
                  C_PREDBCALC.CDSTRIBIMPOIT, C_PREDBCALC.CDFOPERIMPOIT, C_PREDBCALC.CDSCFOPIMPOIT, 0,
                  0, 0, ROUND(C_PREDBCALC.VRCONTIMPOIT - C_PREDBCALC.VRBCALCIMPOIT,5), 0, 0, W_00000, W_00000,
                  C_PREDBCALC.IDVALORINFO, V_CDSITTRIBTMP, V_IDMODBCNFE, V_IDMODBCSTNFE,
                  V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, V_IDMOTIDESSTNFE, V_CDREGRAITALIQ, C_PREDBCALC.CDCEST);
            END LOOP;
         END IF;

         DELETE IMPOSTONF
         WHERE (CDFILIAL   = P_FILIAL)   AND
               (NRLANCTONF = P_LANCTONF);

         FOR C_IMPOSUBTRIB IN (SELECT NRSEQITPROD, CDIMPOSTO, IDTRIMPSTII
                               FROM ITEMPROIMPOS I
                               WHERE CDFILIAL     = V_FILIORIG  AND
                                     NRLANCTONF   = V_DEVOLORIG AND
                                     NRITPROIMPOS = W_1         AND
                                     EXISTS (SELECT CDIMPOSTO
                                             FROM IMPOSTO
                                             WHERE CDIMPOSTRIB = I.CDIMPOSTO)) LOOP

            UPDATE TRABITPROIMPOS
            SET IDTRIMPSTTI = C_IMPOSUBTRIB.IDTRIMPSTII
            WHERE CDFILIMPOIT  = P_FILIAL                  AND
                  NRLANCIMPOIT = P_LANCTONF                AND
                  NRSEQIMPOIT  = C_IMPOSUBTRIB.NRSEQITPROD AND
                  CDIMPOSTOIT  = C_IMPOSUBTRIB.CDIMPOSTO   AND
                  NRSEQITPRO   = W_1;
         END LOOP;

      ELSE
         SELECT NVL(SUM(VRTOTAITEM - VRDESCITEM),0) INTO V_TOTAPROD
         FROM ITEMPRODUTO
         WHERE CDFILIAL   = P_FILIAL   AND
               NRLANCTONF = P_LANCTONF;
      END IF;
   ELSE
      SELECT NVL(SUM(VRTOTAITEM - VRDESCITEM),0) INTO V_TOTAPROD
      FROM ITEMPRODUTO
      WHERE CDFILIAL   = P_FILIAL   AND
            NRLANCTONF = P_LANCTONF;
   END IF;

   IF P_TIPOOPER = '11' AND V_IDNFOUTRASNF = W_S THEN
      SELECT COUNT(*)
      INTO V_QTDEREGTRAB
      FROM TRABITPROIMPOS
      WHERE CDFILIMPOIT  = P_FILIAL   AND
            NRLANCIMPOIT = P_LANCTONF;

      IF V_QTDEREGTRAB = 0 THEN
         INSERT INTO TRABITPROIMPOS(
            CDFILIMPOIT, NRLANCIMPOIT, NRSEQIMPOIT, CDIMPOSTOIT, NRSEQITPRO, CDFISCIMPOIT, CDSTRIBIMPOIT,
            CDFOPERIMPOIT, CDSCFOPIMPOIT, VRALIQIMPOIT, VRREDBCIMPOIT, VRPDEDIMPOIT, VRCONTIMPOIT,
            VRBCALCIMPOIT, VRIMPOSIT, IDERRIMPOIT, IDAVISIMPOIT, IDVALORINFO,
            CDSTRIBITNFE, IDMODBCITEMNFE, IDMODBCSTITENFE,
            CDTPCREDPICOITE, CDNATUBCALPCIT, IDMOTDESOTRABIT, CDREGRATRABIT,
            VRPERDIFEREIT, VRIMPOSTOOPERAIT, VRIMPOSTODIFERIT, CDCEST)
            (SELECT CDFILIAL, NRLANCTONF, NRSEQITPROD, CDIMPOSTO, NRITPROIMPOS, CDFISCALIT, CDSITUTRIBIT,
                    CDFISCOPERIT, CDSUFXCFOPIT, VRALIQITEM, VRPERREDBCIT, VRPARDEDIT, ROUND(VRCONTITIMP,5) AS VRCONTITIMP,
                    ROUND(VRBASECALCIT, 2), VRIMPOSTOIT, IDERROSIMPIT, IDAVISIMPIT, NVL(IDVALORINFIT, W_N),
                    CDSITUTRIBITNFE, IDMODBCITNFE, IDMODBCSTITNFE,
                    CDTPCREDPICOITE, CDNATUBCALPCIT, IDMOTDESONERAIT, CDREGRAIT,
                    VRPERDIFEREIT, VRIMPOSTOOPERAIT, VRIMPOSTODIFERIT, CDCEST
             FROM ITEMPROIMPOS
             WHERE CDFILIAL   = P_FILIAL   AND
                   NRLANCTONF = P_LANCTONF);


         FOR C_IMPOSNFTOT IN (
            SELECT /*+ index (IP,PK_ITEMPROIMPOS)*/
                   IP.CDIMPOSTO, CDIMPOSTOIT, ROUND(SUM(NVL(VRIMPOSIT,0)),V_NRDECITOTANF) AS VRIMPOSTOIT, NVL(SUM(VRBASECALCIT),0) AS VRBASECALCIT,
                   NVL(SUM(VRBCALCIMPOIT),0) AS VRBCALCIMPOIT, MAX(NVL(IDPREIMPENTR, W_N)) AS IDPREIMPENTR
            FROM ITEMPROIMPOS IP, TRABITPROIMPOS TI, IMPOSTO I
            WHERE (IP.CDFILIAL     = P_FILIAL)        AND
                  (IP.NRLANCTONF   = P_LANCTONF)      AND
                  (TI.CDFILIMPOIT  = IP.CDFILIAL)     AND
                  (TI.NRLANCIMPOIT = IP.NRLANCTONF)   AND
                  (TI.NRSEQIMPOIT  = IP.NRSEQITPROD)  AND
                  (TI.NRSEQITPRO   = IP.NRITPROIMPOS) AND
                  (TI.CDIMPOSTOIT  = IP.CDIMPOSTO)    AND
                  (I.CDIMPOSTO     = TI.CDIMPOSTOIT)  AND
                  (IP.NRITPROIMPOS = 1)
            GROUP BY IP.CDIMPOSTO, TI.CDIMPOSTOIT) LOOP

            INSERT INTO IMPOSNFTOT(CDFILIAL, NRLANCTONF, CDIMPOSTO, VRTOTIMPONF, VRTOTBCALCNF)
                           VALUES (P_FILIAL, P_LANCTONF, C_IMPOSNFTOT.CDIMPOSTO, NVL(C_IMPOSNFTOT.VRIMPOSTOIT,0), NVL(C_IMPOSNFTOT.VRBASECALCIT,0));
         END LOOP;

         DELETE TRABIMPOSNFTOT WHERE CDFILIMPTOT = P_FILIAL AND NRLANCIMPTOT = P_LANCTONF;

         INSERT INTO TRABIMPOSNFTOT(
            CDFILIMPTOT, NRLANCIMPTOT, CDIMPOSTOT, VRIMPOSTOT, VRBCALIMPTOT,
                    IDERROSTOT, IDAVISOSTOT)
            (SELECT CDFILIAL, NRLANCTONF, CDIMPOSTO, VRTOTIMPONF, VRTOTBCALCNF,
                    IDERROSIMPTT, IDAVISIMPTT
                     FROM IMPOSNFTOT
                     WHERE CDFILIAL   = P_FILIAL AND
                           NRLANCTONF = P_LANCTONF);
      END IF;
   END IF;

   /* Altera CFOP e CST para as tabelas NOTAFISCAL e ITEMPRODUTO para nf's de devolução e complemento */
   IF (V_IDOPERDEVONF = w_S) OR (P_TIPOOPER = '03') THEN

      FOR C_ITPROD IN (SELECT NRSEQITPROD
                         FROM ITEMPRODUTO
                        WHERE CDFILIAL = P_FILIAL
                          AND NRLANCTONF = P_LANCTONF)

      LOOP
         V_CDSITUTRIBIT := '';
         V_CDFISCOPERIT := '';
         V_CDSUFXCFOPIT := '';

         SELECT MAX(CDSTRIBIMPOIT), MAX(CDFOPERIMPOIT), MAX(CDSCFOPIMPOIT)
           INTO V_CDSITUTRIBIT, V_CDFISCOPERIT, V_CDSUFXCFOPIT
           FROM TRABITPROIMPOS
          WHERE CDFILIMPOIT = P_FILIAL
            AND NRLANCIMPOIT = P_LANCTONF
            AND NRSEQIMPOIT = C_ITPROD.NRSEQITPROD;

      UPDATE ITEMPRODUTO
         SET CDSITUTRIBPR = V_CDSITUTRIBIT,
             CDFISOPEITEM = V_CDFISCOPERIT,
             CDSUFXCFOPPR = V_CDSUFXCFOPIT
       WHERE CDFILIAL = P_FILIAL
         AND NRLANCTONF = P_LANCTONF
         AND NRSEQITPROD = C_ITPROD.NRSEQITPROD;

      END LOOP;
   END IF;

   V_DIFERENCA := 0;
   /* RATEIO DOS ENCARGOS PARA OS PRODUTOS DA NOTA. ESTE RATEIO É NECESSÁRIO PARA A NOTA FISCAL ELETRÔNICA */

   FOR C_ITEMENCARGO IN (SELECT ENCARGO.CDENCARGONFE, SUM(ITEMENCARGO.VRITEMENCA) AS VRITEMENCA
                           FROM ITEMENCARGO, ENCARGO
                          WHERE ITEMENCARGO.CDENCARGO = ENCARGO.CDENCARGO
                            AND ENCARGO.CDENCARGONFE IN ('01', '02', '03', '04', '05')
                            AND NVL(ITEMENCARGO.VRITEMENCA, 0) >= 0
                            AND CDFILIAL = P_FILIAL
                            AND NRLANCTONF = P_LANCTONF
                          GROUP BY ENCARGO.CDENCARGONFE) LOOP
      /* ENCARGO FRETE */
      IF (C_ITEMENCARGO.CDENCARGONFE = '01') THEN
         IF (C_ITEMENCARGO.VRITEMENCA > 0) THEN
            FOR C_ITEMPRODUTO IN (SELECT NRSEQITPROD, VRTOTAITEM
                                    FROM ITEMPRODUTO
                                   WHERE CDFILIAL = P_FILIAL
                                     AND NRLANCTONF = P_LANCTONF) LOOP

               SELECT ITEMPRODUTO.VRTOTAITEM,
                      TOTAL.SOMATOTAITEM,
                      DECODE(TOTAL.SOMATOTAITEM, 0, 0, ((100 * ITEMPRODUTO.VRTOTAITEM) / TOTAL.SOMATOTAITEM)) AS PERCENTITEM
                 INTO V_VRTOTAITEM, V_SOMATOTAITEM, V_PERCENTITEM
                 FROM ITEMPRODUTO, (SELECT CDFILIAL, NRLANCTONF, SUM(VRTOTAITEM) SOMATOTAITEM
                                      FROM ITEMPRODUTO
                                     WHERE CDFILIAL = P_FILIAL
                                       AND NRLANCTONF = P_LANCTONF
                                     GROUP BY CDFILIAL, NRLANCTONF) TOTAL
                WHERE ITEMPRODUTO.CDFILIAL = TOTAL.CDFILIAL
                  AND ITEMPRODUTO.NRLANCTONF = TOTAL.NRLANCTONF
                  AND ITEMPRODUTO.NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;

               IF (V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV') THEN
                  UPDATE ITEMPRODUTO
                     SET VRFRETEITEM = TRUNC(C_ITEMENCARGO.VRITEMENCA * (V_PERCENTITEM / 100), 2)
                   WHERE CDFILIAL  = P_FILIAL
                     AND NRLANCTONF = P_LANCTONF
                     AND NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;
               ELSE
                  UPDATE ITEMPRODUTO
                     SET VRFRETEITEM = ROUND(C_ITEMENCARGO.VRITEMENCA * (V_PERCENTITEM / 100), 2)
                   WHERE CDFILIAL  = P_FILIAL
                     AND NRLANCTONF = P_LANCTONF
                     AND NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;
               END IF;
            END LOOP;
            /*AJUSTE DE VALORES*/
            SELECT SUM(VRFRETEITEM)
              INTO V_VRFRETEITEM
              FROM ITEMPRODUTO
             WHERE CDFILIAL = P_FILIAL
               AND NRLANCTONF = P_LANCTONF;

            V_DIFERENCA := C_ITEMENCARGO.VRITEMENCA - V_VRFRETEITEM;

            IF V_DIFERENCA <> 0 THEN
               UPDATE ITEMPRODUTO
                  SET VRFRETEITEM = VRFRETEITEM + V_DIFERENCA
                WHERE CDFILIAL = P_FILIAL
                  AND NRLANCTONF = P_LANCTONF
                  AND NRSEQITPROD = (SELECT MAX(NRSEQITPROD)
                                      FROM ITEMPRODUTO
                                      WHERE CDFILIAL = P_FILIAL
                                        AND NRLANCTONF = P_LANCTONF
                                        AND VRTOTAITEM = (SELECT MAX(VRTOTAITEM)
                                                           FROM ITEMPRODUTO
                                                          WHERE CDFILIAL = P_FILIAL
                                                            AND NRLANCTONF = P_LANCTONF));

            END IF;
         ELSE
            UPDATE ITEMPRODUTO
               SET VRFRETEITEM = 0
             WHERE CDFILIAL  = P_FILIAL
               AND NRLANCTONF = P_LANCTONF;
         END IF;
      END IF;

      /* ENCARGO SEGURO */
      IF (C_ITEMENCARGO.CDENCARGONFE = '02') THEN
         IF (C_ITEMENCARGO.VRITEMENCA > 0) THEN
            FOR C_ITEMPRODUTO IN (SELECT NRSEQITPROD, VRTOTAITEM
                                    FROM ITEMPRODUTO
                                   WHERE CDFILIAL = P_FILIAL
                                     AND NRLANCTONF = P_LANCTONF) LOOP

               SELECT ITEMPRODUTO.VRTOTAITEM,
                      TOTAL.SOMATOTAITEM,
                      DECODE(TOTAL.SOMATOTAITEM, 0, 0, ((100 * ITEMPRODUTO.VRTOTAITEM) / TOTAL.SOMATOTAITEM)) AS PERCENTITEM
                 INTO V_VRTOTAITEM, V_SOMATOTAITEM, V_PERCENTITEM
                 FROM ITEMPRODUTO, (SELECT CDFILIAL, NRLANCTONF, SUM(VRTOTAITEM) SOMATOTAITEM
                                      FROM ITEMPRODUTO
                                     WHERE CDFILIAL = P_FILIAL
                                       AND NRLANCTONF = P_LANCTONF
                                     GROUP BY CDFILIAL, NRLANCTONF) TOTAL
                WHERE ITEMPRODUTO.CDFILIAL = TOTAL.CDFILIAL
                  AND ITEMPRODUTO.NRLANCTONF = TOTAL.NRLANCTONF
                  AND ITEMPRODUTO.NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;

               IF (V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV') THEN
                  UPDATE ITEMPRODUTO
                     SET VRSEGURITEM = TRUNC(C_ITEMENCARGO.VRITEMENCA * (V_PERCENTITEM / 100), 2)
                   WHERE CDFILIAL  = P_FILIAL
                     AND NRLANCTONF = P_LANCTONF
                     AND NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;
               ELSE
                  UPDATE ITEMPRODUTO
                     SET VRSEGURITEM = ROUND(C_ITEMENCARGO.VRITEMENCA * (V_PERCENTITEM / 100), 2)
                   WHERE CDFILIAL  = P_FILIAL
                     AND NRLANCTONF = P_LANCTONF
                     AND NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;
               END IF;
            END LOOP;
            /*AJUSTE DE VALORES*/
            SELECT SUM(VRSEGURITEM)
              INTO V_VRSEGURITEM
              FROM ITEMPRODUTO
             WHERE CDFILIAL = P_FILIAL
               AND NRLANCTONF = P_LANCTONF;

            V_DIFERENCA := C_ITEMENCARGO.VRITEMENCA - V_VRSEGURITEM;

            IF V_DIFERENCA <> 0 THEN
               UPDATE ITEMPRODUTO
                  SET VRSEGURITEM = VRSEGURITEM + V_DIFERENCA
                WHERE CDFILIAL = P_FILIAL
                  AND NRLANCTONF = P_LANCTONF
                  AND NRSEQITPROD = (SELECT MAX(NRSEQITPROD)
                                      FROM ITEMPRODUTO
                                      WHERE CDFILIAL = P_FILIAL
                                        AND NRLANCTONF = P_LANCTONF
                                        AND VRTOTAITEM = (SELECT MAX(VRTOTAITEM)
                                                           FROM ITEMPRODUTO
                                                          WHERE CDFILIAL = P_FILIAL
                                                            AND NRLANCTONF = P_LANCTONF));

            END IF;
         ELSE
            UPDATE ITEMPRODUTO
               SET VRSEGURITEM = 0
             WHERE CDFILIAL  = P_FILIAL
               AND NRLANCTONF = P_LANCTONF;
         END IF;
      END IF;

      /* ENCARGO DESCONTO */
      IF (C_ITEMENCARGO.CDENCARGONFE = '03') THEN
         IF (C_ITEMENCARGO.VRITEMENCA > 0) THEN
            FOR C_ITEMPRODUTO IN (SELECT NRSEQITPROD, VRTOTAITEM
                                    FROM ITEMPRODUTO
                                   WHERE CDFILIAL = P_FILIAL
                                     AND NRLANCTONF = P_LANCTONF) LOOP

               SELECT ITEMPRODUTO.VRTOTAITEM,
                      TOTAL.SOMATOTAITEM,
                      DECODE(TOTAL.SOMATOTAITEM, 0, 0, ((100 * ITEMPRODUTO.VRTOTAITEM) / TOTAL.SOMATOTAITEM)) AS PERCENTITEM
                 INTO V_VRTOTAITEM, V_SOMATOTAITEM, V_PERCENTITEM
                 FROM ITEMPRODUTO, (SELECT CDFILIAL, NRLANCTONF, SUM(VRTOTAITEM) SOMATOTAITEM
                                      FROM ITEMPRODUTO
                                     WHERE CDFILIAL = P_FILIAL
                                       AND NRLANCTONF = P_LANCTONF
                                     GROUP BY CDFILIAL, NRLANCTONF) TOTAL
                WHERE ITEMPRODUTO.CDFILIAL = TOTAL.CDFILIAL
                  AND ITEMPRODUTO.NRLANCTONF = TOTAL.NRLANCTONF
                  AND ITEMPRODUTO.NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;

               IF (V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV') THEN
                  UPDATE ITEMPRODUTO
                     SET VRENCARGODESC = TRUNC(VRDESCITEM + (C_ITEMENCARGO.VRITEMENCA * (V_PERCENTITEM / 100)), 2)
                   WHERE CDFILIAL  = P_FILIAL
                     AND NRLANCTONF = P_LANCTONF
                     AND NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;
               ELSE
                  UPDATE ITEMPRODUTO
                     SET VRENCARGODESC = ROUND(VRDESCITEM + (C_ITEMENCARGO.VRITEMENCA * (V_PERCENTITEM / 100)), 2)
                   WHERE CDFILIAL  = P_FILIAL
                     AND NRLANCTONF = P_LANCTONF
                     AND NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;
               END IF;
            END LOOP;
            /*AJUSTE DE VALORES*/
            SELECT SUM(VRENCARGODESC)
              INTO V_VRENCARGODESC
              FROM ITEMPRODUTO
             WHERE CDFILIAL = P_FILIAL
               AND NRLANCTONF = P_LANCTONF;

            SELECT SUM(VRDESCITEM)
              INTO V_SUMVRDESCITEM
              FROM ITEMPRODUTO
             WHERE CDFILIAL  = P_FILIAL
               AND NRLANCTONF = P_LANCTONF;

            V_DIFERENCA := (C_ITEMENCARGO.VRITEMENCA+V_SUMVRDESCITEM) - V_VRENCARGODESC;

            IF V_DIFERENCA <> 0 THEN
               UPDATE ITEMPRODUTO
                  SET VRENCARGODESC = VRENCARGODESC + V_DIFERENCA
                WHERE CDFILIAL = P_FILIAL
                  AND NRLANCTONF = P_LANCTONF
                  AND NRSEQITPROD = (SELECT MAX(NRSEQITPROD)
                                      FROM ITEMPRODUTO
                                      WHERE CDFILIAL = P_FILIAL
                                        AND NRLANCTONF = P_LANCTONF
                                        AND VRTOTAITEM = (SELECT MAX(VRTOTAITEM)
                                                           FROM ITEMPRODUTO
                                                          WHERE CDFILIAL = P_FILIAL
                                                            AND NRLANCTONF = P_LANCTONF));

            END IF;
         ELSE
            UPDATE ITEMPRODUTO
               SET VRENCARGODESC = VRDESCITEM + 0
             WHERE CDFILIAL  = P_FILIAL
               AND NRLANCTONF = P_LANCTONF;
         END IF;
      END IF;

      /*ENCARGO OUTRAS DESPESAS*/
      IF (C_ITEMENCARGO.CDENCARGONFE = '04') THEN
         IF (C_ITEMENCARGO.VRITEMENCA > 0) THEN
            FOR C_ITEMPRODUTO IN (SELECT NRSEQITPROD, VRTOTAITEM
                                    FROM ITEMPRODUTO
                                   WHERE CDFILIAL = P_FILIAL
                                     AND NRLANCTONF = P_LANCTONF) LOOP

               SELECT ITEMPRODUTO.VRTOTAITEM,
                      TOTAL.SOMATOTAITEM,
                      DECODE(TOTAL.SOMATOTAITEM, 0, 0, ((100 * ITEMPRODUTO.VRTOTAITEM) / TOTAL.SOMATOTAITEM)) AS PERCENTITEM
                 INTO V_VRTOTAITEM, V_SOMATOTAITEM, V_PERCENTITEM
                 FROM ITEMPRODUTO, (SELECT CDFILIAL, NRLANCTONF, SUM(VRTOTAITEM) SOMATOTAITEM
                                      FROM ITEMPRODUTO
                                     WHERE CDFILIAL = P_FILIAL
                                       AND NRLANCTONF = P_LANCTONF
                                     GROUP BY CDFILIAL, NRLANCTONF) TOTAL
                WHERE ITEMPRODUTO.CDFILIAL = TOTAL.CDFILIAL
                  AND ITEMPRODUTO.NRLANCTONF = TOTAL.NRLANCTONF
                  AND ITEMPRODUTO.NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;

               IF (V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV') THEN
                  UPDATE ITEMPRODUTO
                     SET VROUTRASDESPITEM = TRUNC((C_ITEMENCARGO.VRITEMENCA * (V_PERCENTITEM / 100)), 2)
                   WHERE CDFILIAL  = P_FILIAL
                     AND NRLANCTONF = P_LANCTONF
                     AND NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;
               ELSE
                  UPDATE ITEMPRODUTO
                     SET VROUTRASDESPITEM = ROUND((C_ITEMENCARGO.VRITEMENCA * (V_PERCENTITEM / 100)), 2)
                   WHERE CDFILIAL  = P_FILIAL
                     AND NRLANCTONF = P_LANCTONF
                     AND NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;
               END IF;
            END LOOP;
            /*AJUSTE DE VALORES*/
            SELECT SUM(VROUTRASDESPITEM)
              INTO V_VROUTRASDESPITEM
              FROM ITEMPRODUTO
             WHERE CDFILIAL = P_FILIAL
               AND NRLANCTONF = P_LANCTONF;

            V_DIFERENCA := C_ITEMENCARGO.VRITEMENCA - V_VROUTRASDESPITEM;

            IF V_DIFERENCA <> 0 THEN
               UPDATE ITEMPRODUTO
                  SET VROUTRASDESPITEM = VROUTRASDESPITEM + V_DIFERENCA
                WHERE CDFILIAL = P_FILIAL
                  AND NRLANCTONF = P_LANCTONF
                  AND NRSEQITPROD = (SELECT MAX(NRSEQITPROD)
                                      FROM ITEMPRODUTO
                                      WHERE CDFILIAL = P_FILIAL
                                        AND NRLANCTONF = P_LANCTONF
                                        AND VRTOTAITEM = (SELECT MAX(VRTOTAITEM)
                                                           FROM ITEMPRODUTO
                                                          WHERE CDFILIAL = P_FILIAL
                                                            AND NRLANCTONF = P_LANCTONF));

            END IF;
         ELSE
            UPDATE ITEMPRODUTO
               SET VROUTRASDESPITEM = 0
             WHERE CDFILIAL  = P_FILIAL
               AND NRLANCTONF = P_LANCTONF;
         END IF;
      END IF;

      /*ENCARGO DESPESAS ADUANEIRAS*/
      IF (C_ITEMENCARGO.CDENCARGONFE = '05') THEN
        /*REFAZ O RATEIO DO ENCARGO VERIFICANDO A INCIDENCIA DO IMPOSTO DE IMPORTACAO*/
         UPDATE ITEMPRODUTO
            SET VRDESPADUANEIRA = 0
          WHERE CDFILIAL  = P_FILIAL
            AND NRLANCTONF = P_LANCTONF;
         IF (C_ITEMENCARGO.VRITEMENCA > 0) THEN
            FOR C_ITEMPRODUTO IN (SELECT DISTINCT(I.NRSEQITPROD)
                                    FROM ITEMPROIMPOS I, IMPOSTO II
                                   WHERE I.NRLANCTONF    = P_LANCTONF
                                     AND I.CDFILIAL      = P_FILIAL
                                     AND I.CDIMPOSTO     = II.CDIMPOSTO
                                     AND II.CDIMPOSTONFE = '20') LOOP

               SELECT ITEMPRODUTO.VRTOTAITEM,
                      TOTAL.SOMATOTAITEM,
                      DECODE(TOTAL.SOMATOTAITEM, 0, 0, ((100 * ITEMPRODUTO.VRTOTAITEM) / TOTAL.SOMATOTAITEM)) AS PERCENTITEM
                 INTO V_VRTOTAITEM, V_SOMATOTAITEM, V_PERCENTITEM
                 FROM ITEMPRODUTO, (SELECT CDFILIAL, NRLANCTONF, SUM(VRTOTAITEM) SOMATOTAITEM
                                      FROM ITEMPRODUTO
                                     WHERE CDFILIAL = P_FILIAL
                                       AND NRLANCTONF = P_LANCTONF
                                     GROUP BY CDFILIAL, NRLANCTONF) TOTAL
                WHERE ITEMPRODUTO.CDFILIAL = TOTAL.CDFILIAL
                  AND ITEMPRODUTO.NRLANCTONF = TOTAL.NRLANCTONF
                  AND ITEMPRODUTO.NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;

               IF (V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV') THEN
                  UPDATE ITEMPRODUTO
                     SET VRDESPADUANEIRA = TRUNC((C_ITEMENCARGO.VRITEMENCA * (V_PERCENTITEM / 100)), 2)
                   WHERE CDFILIAL  = P_FILIAL
                     AND NRLANCTONF = P_LANCTONF
                     AND NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;
               ELSE
                  UPDATE ITEMPRODUTO
                     SET VRDESPADUANEIRA = ROUND((C_ITEMENCARGO.VRITEMENCA * (V_PERCENTITEM / 100)), 2)
                   WHERE CDFILIAL  = P_FILIAL
                     AND NRLANCTONF = P_LANCTONF
                     AND NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;
               END IF;
            END LOOP;
            /*AJUSTE DE VALORES*/
            SELECT SUM(VRDESPADUANEIRA)
              INTO V_VRDESPADUANEIRA
              FROM ITEMPRODUTO
             WHERE CDFILIAL = P_FILIAL
               AND NRLANCTONF = P_LANCTONF;

            V_DIFERENCA := C_ITEMENCARGO.VRITEMENCA - V_VRDESPADUANEIRA;

            IF V_DIFERENCA <> 0 THEN
               UPDATE ITEMPRODUTO
                  SET VRDESPADUANEIRA = VRDESPADUANEIRA + V_DIFERENCA
                WHERE CDFILIAL = P_FILIAL
                  AND NRLANCTONF = P_LANCTONF
                  AND NRSEQITPROD = (SELECT MAX(II.NRSEQITPROD)
                                       FROM ITEMPRODUTO I, ITEMPROIMPOS II, IMPOSTO S
                                      WHERE I.CDFILIAL     = P_FILIAL
                                        AND I.NRLANCTONF   = P_LANCTONF
                                        AND I.CDFILIAL     = II.CDFILIAL
                                        AND I.NRLANCTONF   = II.NRLANCTONF
                                        AND I.NRSEQITPROD  = II.NRSEQITPROD
                                        AND II.CDIMPOSTO   = S.CDIMPOSTO
                                        AND S.CDIMPOSTONFE = '20'
                                        AND VRTOTAITEM = (SELECT MAX(VRTOTAITEM)
                                                            FROM ITEMPRODUTO I, ITEMPROIMPOS II, IMPOSTO S
                                                           WHERE I.CDFILIAL     = P_FILIAL
                                                             AND I.NRLANCTONF   = P_LANCTONF
                                                             AND I.CDFILIAL     = II.CDFILIAL
                                                             AND I.NRLANCTONF   = II.NRLANCTONF
                                                             AND I.NRSEQITPROD  = II.NRSEQITPROD
                                                             AND II.CDIMPOSTO   = S.CDIMPOSTO
                                                             AND S.CDIMPOSTONFE = '20'));

            END IF;
         ELSE
            UPDATE ITEMPRODUTO
               SET VRDESPADUANEIRA = 0
             WHERE CDFILIAL  = P_FILIAL
               AND NRLANCTONF = P_LANCTONF;
         END IF;
      END IF;
   END LOOP;
   --CÁLCULO DO VALOR TOTAL DA NOTA FISCAL

   SELECT SUM(VRITEMENCA) INTO V_SOMAENCA
   FROM ITEMENCARGO IE, ENCARGO EN
   WHERE IE.CDFILIAL   = P_FILIAL     AND
         IE.NRLANCTONF = P_LANCTONF   AND
         EN.CDENCARGO  = IE.CDENCARGO AND
         EN.IDENCARGO  = W_A;

   SELECT SUM(VRITEMENCA) INTO V_MENOENCA
   FROM ITEMENCARGO IE, ENCARGO EN
   WHERE IE.CDFILIAL   = P_FILIAL     AND
         IE.NRLANCTONF = P_LANCTONF   AND
         EN.CDENCARGO  = IE.CDENCARGO AND
         EN.IDENCARGO  = W_D;

   SELECT SUM(VRIMPOSTOT) INTO V_SOMAIMPO
   FROM TRABIMPOSNFTOT T, IMPOSTO I
   WHERE CDFILIMPTOT  = P_FILIAL     AND
         NRLANCIMPTOT = P_LANCTONF   AND
         I.CDIMPOSTO  = T.CDIMPOSTOT AND
         IDTRATIMPO   = W_A          AND
         NVL(IDACRPRODENTRNF, 'N') = 'N' AND
         NOT EXISTS(SELECT CDIMPOSTO
                    FROM IMPOSTO
                    WHERE IMPOSTO.CDIMPOSTRIB = T.CDIMPOSTOT);

   SELECT NVL(SUM(VRADICFECP), 0)
     INTO V_SOMAVRADICFECP
     FROM TRABITPROIMPOS T, IMPOSTO I
    WHERE T.CDFILIMPOIT  = P_FILIAL     AND
          T.NRLANCIMPOIT = P_LANCTONF   AND
          I.CDIMPOSTO  = T.CDIMPOSTOIT  AND
          IDTRATIMPO   = 'A'            AND
          NRSEQITPRO   = '1';

   V_SOMAIMPO := NVL(V_SOMAIMPO, 0) + V_SOMAVRADICFECP;

   SELECT SUM(VRIMPOSTOT) INTO V_MENOIMPO
   FROM TRABIMPOSNFTOT T, IMPOSTO I
   WHERE CDFILIMPTOT  = P_FILIAL     AND
         NRLANCIMPTOT = P_LANCTONF   AND
         I.CDIMPOSTO  = T.CDIMPOSTOT AND
         IDTRATIMPO   = W_D;



   IF NOT (V_LIQUIDO IS NULL) THEN
      V_TOTALNOTA := V_LIQUIDO;
   END IF;

   IF NOT (V_SOMAIMPO IS NULL) THEN
      V_TOTALNOTA := V_TOTALNOTA + ROUND(V_SOMAIMPO, 2);
   END IF;

   IF NOT (V_MENOIMPO IS NULL) THEN
      V_TOTALNOTA := V_TOTALNOTA - ROUND(V_MENOIMPO, 2);
   END IF;

   IF NOT (V_SOMAENCA IS NULL) THEN
      V_TOTALNOTA := V_TOTALNOTA + V_SOMAENCA;
   END IF;

   IF NOT (V_MENOENCA IS NULL) THEN
      V_TOTALNOTA := V_TOTALNOTA - V_MENOENCA;
   END IF;

   --VALOR SUBSTITUIÇÃO TRIBUTÁRIA COM IDENTIFICAÇÃO PARA ACRESCER AO TOTAL DA NF
   SELECT COUNT(*), NVL(SUM(ROUND(T.VRIMPOSIT, V_NRDECITOTANF)),0)
   INTO V_COUNT, V_SOMAIMPO
   FROM TRABITPROIMPOS T, IMPOSTO I
   WHERE T.CDFILIMPOIT  = P_FILIAL   AND
         T.NRLANCIMPOIT = P_LANCTONF AND
         NVL(T.IDTRIMPSTTI, '0')  = '0'        AND
         T.CDIMPOSTOIT    = I.CDIMPOSTO AND
         NVL(I.IDACRPRODENTRNF, 'N') = 'N' AND
         EXISTS(SELECT CDIMPOSTO
                FROM IMPOSTO
                WHERE CDIMPOSTRIB = T.CDIMPOSTOIT);

   IF NOT (V_SOMAIMPO IS NULL) THEN
      V_TOTALNOTA := V_TOTALNOTA + ROUND(V_SOMAIMPO, 2);
   END IF;

   -- Subtrai o valor dos importos a reter no valor da nota fiscal
   BEGIN
      SELECT SUM(VRIMPOSTOT)
        INTO V_VRIMPORETNF
        FROM TRABIMPOSNFTOT T, IMPOSTO I
       WHERE CDFILIMPTOT  = P_FILIAL
         AND NRLANCIMPTOT = P_LANCTONF
         AND I.CDIMPOSTO  = T.CDIMPOSTOT
         AND IDTRATIMPO   = 'R'
         AND IDDESCRFONTE = 'N';
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_VRIMPORETNF := 0;
   END;

   IF NOT (V_VRIMPORETNF IS NULL) THEN
      V_TOTALNOTA := V_TOTALNOTA - ROUND(V_VRIMPORETNF, 2);
   END IF;

   IF (V_INTEGRACAO IS NULL) OR (P_ENTRSAID = W_E) THEN
      IF ((V_TOTALNOTA <> 0) AND (NVL(V_LIQUIDO,0) = 0)) THEN
         SELECT NVL(MAX(VRPRODUTOS),0)
         INTO V_VRPRODUTOS
         FROM NOTAFISCAL
         WHERE CDFILIAL   = P_FILIAL    AND
               NRLANCTONF = P_LANCTONF;
      ELSE
         V_VRPRODUTOS := NVL(V_LIQUIDO, 0);

         UPDATE NOTAFISCAL
         SET VRPRODUTOS = NVL(V_LIQUIDO, 0)
         WHERE CDFILIAL   = P_FILIAL    AND
               NRLANCTONF = P_LANCTONF;
      END IF;
   ELSE
      UPDATE NOTAFISCAL
      SET VRPRODUTOS = NVL(V_TOTAPROD, 0)
      WHERE CDFILIAL   = P_FILIAL    AND
            NRLANCTONF = P_LANCTONF;
   END IF;

   /* Cálculo do valor total da nf de importação*/
   IF (V_IDNFIMPORTACAO = 'S') THEN
      UPDATE NOTAFISCAL
         SET VRNOTAFISC = ROUND(V_TOTALNOTA, 2)
       WHERE CDFILIAL   = P_FILIAL    AND
             NRLANCTONF = P_LANCTONF;

      /*Chamar a procedure para gerar financeiro. */
      V_POSSUIFINANC := 0;
      V_IDUTILVENC   := 'N';

      SELECT NVL(IDUTILVENC, 'N')
        INTO V_IDUTILVENC
        FROM TIPOOPERAC
       WHERE CDTIPOOPER    = P_TIPOOPER
         AND IDENTRSAIDOP = 'E';

      IF (V_IDUTILVENC = 'S') THEN
         SELECT COUNT(*)
           INTO V_POSSUIFINANC
           FROM CONTAPAGAR
          WHERE CDFILIAL   = P_FILIAL
            AND NRLANCTONF = P_LANCTONF;

         IF NOT(V_POSSUIFINANC > 0) THEN
            GERA_DADOS_FINANCEIRO(P_FILIAL, P_LANCTONF, P_FILIAL, 'L', P_RESULTADO);
         END IF;
      END IF;
   END IF;

   CONSULTA_DESONERACAO(P_FILIAL, 
                        P_LANCTONF,
                        V_PAISDEST,
                        V_ESTADEST,
                        V_IMPOSDESONERA);

   IF V_IDIMPDESONERA = 'N' THEN
      P_VRNOTAFISC := ROUND(V_TOTALNOTA, 2);
      V_TOTALNOTA  := ROUND(V_TOTALNOTA, 2);
   ELSE
      P_VRNOTAFISC := ROUND(V_TOTALNOTA - V_IMPOSDESONERA, 2);
      V_TOTALNOTA  := ROUND(V_TOTALNOTA - V_IMPOSDESONERA, 2);
   END IF;


   V_TOTALNOTA := ROUND(V_TOTALNOTA, 2);
   P_VRNOTAFISC := V_TOTALNOTA;

   IF P_TIPOOPER = '08' THEN
      UPDATE NOTAFISCAL
      SET VRNOTAFISC = NVL(V_TOTALNOTA,0),
          VRPRODUTOS = NVL(V_LIQUIDO,0),
          IDERROS    = W_000
      WHERE CDFILIAL   = P_FILIAL    AND
            NRLANCTONF = P_LANCTONF;
   END IF;         

   IF (V_IDOPERDEVONF <> 'S') OR ((V_IDOPERDEVONF = W_S) AND (V_DEVOLORIG IS NULL)) THEN
      FOR C_VRIMPOSTO IN (SELECT II.CDIMPOSTOIT, SUM(II.VRIMPOSIT) AS VRIMPOSIT
                          FROM IMPOSTO I, TRABITPROIMPOS II
                          WHERE II.CDFILIMPOIT  = P_FILIAL        AND
                                II.NRLANCIMPOIT = P_LANCTONF      AND
                                II.NRSEQITPRO   = W_1             AND
                                I.CDIMPOSTO     = II.CDIMPOSTOIT  AND
                                ((I.IDTRATIMPO = W_A) OR (I.IDTRATIMPO = W_D))
                          GROUP BY II.CDIMPOSTOIT) LOOP

         BEGIN
            SELECT VRIMPOSTOT
            INTO V_VRTOTIMPONF
            FROM TRABIMPOSNFTOT
            WHERE CDIMPOSTOT   = C_VRIMPOSTO.CDIMPOSTOIT  AND
                  CDFILIMPTOT  = P_FILIAL                 AND
                  NRLANCIMPTOT = P_LANCTONF;
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_VRTOTIMPONF := 0;
         END;

         V_VRDIFERENCA := V_VRTOTIMPONF - C_VRIMPOSTO.VRIMPOSIT;

         SELECT SUM(I.VRBRUTITEM)
         INTO V_VRBRUTO
         FROM ITEMPRODUTO I, TRABITPROIMPOS II
         WHERE I.CDFILIAL      = P_FILIAL      AND
               I.NRLANCTONF    = P_LANCTONF    AND
               II.CDFILIMPOIT  = I.CDFILIAL    AND
               II.NRLANCIMPOIT = I.NRLANCTONF  AND
               II.NRSEQIMPOIT  = I.NRSEQITPROD AND
               II.NRSEQITPRO   = W_1           AND
               II.CDIMPOSTOIT  = C_VRIMPOSTO.CDIMPOSTOIT;

         FOR C_ATUALIZA IN (SELECT NRSEQIMPOIT
                            FROM TRABITPROIMPOS
                            WHERE CDFILIMPOIT  = P_FILIAL                 AND
                                  NRLANCIMPOIT = P_LANCTONF               AND
                                  CDIMPOSTOIT  = C_VRIMPOSTO.CDIMPOSTOIT  AND
                                  NRSEQITPRO   = W_1
                            ORDER BY NRSEQIMPOIT) LOOP

            IF V_VRBRUTO > 0 THEN
               UPDATE ITEMPRODUTO
               SET VRBRUTITEM = VRBRUTITEM + ((VRBRUTITEM/V_VRBRUTO) * NVL(V_VRDIFERENCA,0))
               WHERE CDFILIAL    = P_FILIAL                AND
                     NRLANCTONF  = P_LANCTONF              AND
                     NRSEQITPROD = C_ATUALIZA.NRSEQIMPOIT;
            END IF;
         END LOOP;
      END LOOP;

      SELECT SUM(VRBRUTITEM)
      INTO V_VRBRUTO
      FROM ITEMPRODUTO
      WHERE CDFILIAL   = P_FILIAL AND
            NRLANCTONF = P_LANCTONF;

      BEGIN
         SELECT VRNOTAFISC
         INTO V_VRNOTAFISC
         FROM NOTAFISCAL
         WHERE CDFILIAL   = P_FILIAL AND
               NRLANCTONF = P_LANCTONF;
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_VRNOTAFISC := 0;
      END;

      V_VRDIFERENCA := V_VRNOTAFISC - V_VRBRUTO;

      IF (V_VRDIFERENCA <> 0) AND (ABS(V_VRDIFERENCA) <= 0.05) THEN
         SELECT MAX(NRSEQITPROD)
         INTO V_NRSEQITPROD
         FROM ITEMPRODUTO
         WHERE CDFILIAL   = P_FILIAL   AND
               NRLANCTONF = P_LANCTONF AND
               VRBRUTITEM = (SELECT MAX(VRBRUTITEM)
                             FROM ITEMPRODUTO
                             WHERE CDFILIAL = P_FILIAL AND
                                   NRLANCTONF = P_LANCTONF);

         UPDATE ITEMPRODUTO
         SET VRBRUTITEM    = ROUND((VRBRUTITEM + V_VRDIFERENCA), 5)
         WHERE CDFILIAL    = P_FILIAL   AND
               NRLANCTONF  = P_LANCTONF AND
               NRSEQITPROD = V_NRSEQITPROD;

      END IF;


   -- RECALCULO DO VALOR CONTABIL DO ITEM

      IF (P_TIPOOPER <> '03') THEN
         
         UPDATE ITEMPRODUTO
            SET VRBRUTITEM = ROUND(VRBRUTITEM, 5)
          WHERE CDFILIAL   = P_FILIAL
            AND NRLANCTONF = P_LANCTONF;

         V_VRTOTBRUT := 0;
         V_VRTOTANF  := 0;
         V_DIFBRUTNF := 0;

         SELECT SUM(VRBRUTITEM)
           INTO V_VRTOTBRUT
           FROM ITEMPRODUTO
          WHERE CDFILIAL   = P_FILIAL
            AND NRLANCTONF = P_LANCTONF;

         IF V_VRTOTBRUT IS NULL THEN
            V_VRTOTBRUT := 0;
         END IF;

         IF V_VRNOTAFISC = 0 THEN
            IF (V_VRTOTBRUT <> ROUND(V_TOTALNOTA, 5)) THEN
               V_DIFBRUTNF :=  ROUND(V_TOTALNOTA, 5) - V_VRTOTBRUT;

               IF (ABS(V_DIFBRUTNF) <= 0.3) THEN
                  UPDATE ITEMPRODUTO
                     SET VRBRUTITEM = (VRBRUTITEM + (V_DIFBRUTNF))
                   WHERE CDFILIAL   = P_FILIAL
                     AND NRLANCTONF = P_LANCTONF
                     AND ROWNUM     = '1'
                     AND VRBRUTITEM = (SELECT MAX(VRBRUTITEM)
                                         FROM ITEMPRODUTO
                                        WHERE CDFILIAL   = P_FILIAL
                                          AND NRLANCTONF = P_LANCTONF);
               END IF;
            END IF;
         ELSE
            UPDATE NOTAFISCAL
               SET VRNOTAFISC = ROUND(VRNOTAFISC, 5)
             WHERE CDFILIAL   = P_FILIAL
               AND NRLANCTONF = P_LANCTONF;

            SELECT ROUND(VRNOTAFISC, 5)
              INTO V_VRTOTANF
              FROM NOTAFISCAL
             WHERE CDFILIAL   = P_FILIAL
               AND NRLANCTONF = P_LANCTONF;

            IF (V_VRTOTBRUT <> V_VRTOTANF) THEN
               V_DIFBRUTNF :=  V_VRTOTANF - V_VRTOTBRUT;

               IF (ABS(V_DIFBRUTNF) <= 0.3) THEN
                  UPDATE ITEMPRODUTO
                     SET VRBRUTITEM = (VRBRUTITEM + (V_DIFBRUTNF))
                   WHERE CDFILIAL   = P_FILIAL
                     AND NRLANCTONF = P_LANCTONF
                     AND ROWNUM     = '1'
                     AND VRBRUTITEM = (SELECT MAX(VRBRUTITEM)
                                         FROM ITEMPRODUTO
                                        WHERE CDFILIAL   = P_FILIAL
                                          AND NRLANCTONF = P_LANCTONF);
               END IF;
            END IF;
         END IF;
      END IF;

      FOR C_ITEMPRODUTO IN (SELECT ROUND(VRBRUTITEM,5) AS VRBRUTITEM, NRSEQITPROD
                            FROM ITEMPRODUTO I
                            WHERE CDFILIAL   = P_FILIAL   AND
                                  NRLANCTONF = P_LANCTONF) LOOP


         FOR C_ITEMPROIMPOS IN (
            SELECT CDIMPOSTOIT
            FROM TRABITPROIMPOS
            WHERE (CDFILIMPOIT  = P_FILIAL)                   AND
                  (NRLANCIMPOIT = P_LANCTONF)                 AND
                  (NRSEQIMPOIT  = C_ITEMPRODUTO.NRSEQITPROD)) LOOP

            UPDATE TRABITPROIMPOS
            SET VRCONTIMPOIT = ROUND(VRCONTIMPOIT,5)
            WHERE (CDFILIMPOIT  = P_FILIAL)                   AND
                  (NRLANCIMPOIT = P_LANCTONF)                 AND
                  (NRSEQIMPOIT  = C_ITEMPRODUTO.NRSEQITPROD)  AND
                  (CDIMPOSTOIT  = C_ITEMPROIMPOS.CDIMPOSTOIT) AND
                  (NRSEQITPRO   = W_2);

            SELECT MAX(NVL(VRCONTIMPOIT,0))
            INTO V_VRREDUCAO
            FROM TRABITPROIMPOS
            WHERE (CDFILIMPOIT  = P_FILIAL)                   AND
                  (NRLANCIMPOIT = P_LANCTONF)                 AND
                  (NRSEQIMPOIT  = C_ITEMPRODUTO.NRSEQITPROD)  AND
                  (CDIMPOSTOIT  = C_ITEMPROIMPOS.CDIMPOSTOIT) AND
                  (NRSEQITPRO   = W_2);

            IF V_VRREDUCAO IS NULL THEN
               V_VRREDUCAO := 0;
            END IF;

            UPDATE TRABITPROIMPOS
            SET VRCONTIMPOIT  = ROUND((C_ITEMPRODUTO.VRBRUTITEM - V_VRREDUCAO),5)
            WHERE CDFILIMPOIT  = P_FILIAL                   AND
                  NRLANCIMPOIT = P_LANCTONF                 AND
                  NRSEQIMPOIT  = C_ITEMPRODUTO.NRSEQITPROD  AND
                  CDIMPOSTOIT  = C_ITEMPROIMPOS.CDIMPOSTOIT AND
                  NRSEQITPRO   = W_1;

            UPDATE ITEMPROIMPOS
            SET VRCONTITIMP = ROUND((C_ITEMPRODUTO.VRBRUTITEM - V_VRREDUCAO),5)
            WHERE (NRLANCTONF   = P_LANCTONF)                 AND
                  (CDFILIAL     = P_FILIAL)                   AND
                  (NRSEQITPROD  = C_ITEMPRODUTO.NRSEQITPROD)  AND
                  (CDIMPOSTO    = C_ITEMPROIMPOS.CDIMPOSTOIT) AND
                  (NRITPROIMPOS = W_1);

            /*ESTE UPDATE ESTA SENDO REALIZADO PARA EVITAR QUE EXISTAM LANCAMENTOS COM BASE DE CÁLCULO E SEM IMPOSTO E SEM ALIQUOTA*/
            UPDATE TRABITPROIMPOS
            SET VRBCALCIMPOIT = 0
            WHERE CDFILIMPOIT  = P_FILIAL                   AND
                  NRLANCIMPOIT = P_LANCTONF                 AND
                  NRSEQIMPOIT  = C_ITEMPRODUTO.NRSEQITPROD  AND
                  CDIMPOSTOIT  = C_ITEMPROIMPOS.CDIMPOSTOIT AND
                  NRSEQITPRO   = W_1                        AND
                  CDFISCIMPOIT = W_1                        AND
                  VRALIQIMPOIT = 0.00                       AND
                  VRIMPOSIT = 0.00;
         END LOOP;
      END LOOP;
   END IF;
  
   ARREDONDA_BASECALC(W_E, P_FILIAL, P_LANCTONF);

   IF V_SEQUIMPOSTNF IS NULL THEN
      V_SEQUIMPOSTNF := '01';
   END IF;

   IF V_SEQUIMPOSTNF = '01' THEN
      DELETE IMPOSTONF
      WHERE (CDFILIAL = P_FILIAL) AND
            (NRLANCTONF = P_LANCTONF);
   END IF;

   FOR C_TRABITPROIMPOS IN (SELECT NRSEQITPROD, CDIMPOSTO, VRALIQITEM
                              FROM ITEMPROIMPOS
                             WHERE CDFILIAL = P_FILIAL
                               AND NRLANCTONF = P_LANCTONF
                               AND NRITPROIMPOS = '3') LOOP

      V_CDFILIREDU := NULL;

      SELECT MAX(CDFILIAL)
        INTO V_CDFILIREDU
        FROM ITEMPROIMPOS
       WHERE CDFILIAL = P_FILIAL
         AND NRLANCTONF = P_LANCTONF
         AND NRSEQITPROD = C_TRABITPROIMPOS.NRSEQITPROD
         AND CDIMPOSTO = C_TRABITPROIMPOS.CDIMPOSTO
         AND NRITPROIMPOS = '2';

      IF ((V_CDFILIREDU IS NULL) AND (NVL(V_IDORIGDESTNF, 'F') <> 'L')) THEN

         V_VRCONTITIMP := 0;

         SELECT MAX(VRCONTITIMP), MAX(VRIMPOSTOIT), MAX(VRALIQITEM)
           INTO V_VRCONTITIMP, V_IMPOSTOIT, V_ALIQINFO
           FROM ITEMPROIMPOS
          WHERE CDFILIAL = P_FILIAL
            AND NRLANCTONF = P_LANCTONF
            AND NRSEQITPROD = C_TRABITPROIMPOS.NRSEQITPROD
            AND CDIMPOSTO = C_TRABITPROIMPOS.CDIMPOSTO
            AND NRITPROIMPOS = '1';

         IF (V_IDCALCDIFENTFISC = 'N') THEN

            UPDATE TRABITPROIMPOS
               SET VRCONTIMPOIT  = V_VRCONTITIMP,
                   VRBCALCIMPOIT = ROUND(V_VRCONTITIMP, 2),
                   VRIMPOSIT     =  ROUND((V_VRCONTITIMP * (VRALIQIMPOIT / 100)), V_NRDECITOTANF)
             WHERE CDFILIMPOIT   = P_FILIAL
               AND NRLANCIMPOIT  = P_LANCTONF
               AND NRSEQIMPOIT   = C_TRABITPROIMPOS.NRSEQITPROD
               AND CDIMPOSTOIT   = C_TRABITPROIMPOS.CDIMPOSTO
               AND NRSEQITPRO    = '3';

            UPDATE ITEMPROIMPOS
               SET VRCONTITIMP  = V_VRCONTITIMP,
                   VRBASECALCIT = ROUND(V_VRCONTITIMP, 2) ,
                   VRIMPOSTOIT  = ROUND((V_VRCONTITIMP * (VRALIQITEM / 100)), V_NRDECITOTANF)
             WHERE CDFILIAL     = P_FILIAL
               AND NRLANCTONF   = P_LANCTONF
               AND NRSEQITPROD  = C_TRABITPROIMPOS.NRSEQITPROD
               AND CDIMPOSTO    = C_TRABITPROIMPOS.CDIMPOSTO
               AND NRITPROIMPOS = '3';
         ELSE
            V_ALIQDEST     := 0;
            V_ALIQDEST     := V_ALIQINFO + C_TRABITPROIMPOS.VRALIQITEM;
            V_BCALCDIFCOMP := ROUND(((V_VRCONTITIMP - V_IMPOSTOIT) / ((100 - V_ALIQDEST)/100)) , V_NRDECITOTANF);
            V_IMPOSTODIFE  := ROUND(((V_BCALCDIFCOMP * (V_ALIQDEST/100)) - V_IMPOSTOIT), V_NRDECITOTANF);

            UPDATE TRABITPROIMPOS
               SET VRCONTIMPOIT  = V_VRCONTITIMP,
                   VRBCALCIMPOIT = V_BCALCDIFCOMP,
                   VRIMPOSIT     = V_IMPOSTODIFE
             WHERE CDFILIMPOIT = P_FILIAL
               AND NRLANCIMPOIT = P_LANCTONF
               AND NRSEQIMPOIT = C_TRABITPROIMPOS.NRSEQITPROD
               AND CDIMPOSTOIT = C_TRABITPROIMPOS.CDIMPOSTO
               AND NRSEQITPRO   = '3';

            UPDATE ITEMPROIMPOS
               SET VRCONTITIMP  = V_VRCONTITIMP,
                   VRBASECALCIT = V_BCALCDIFCOMP,
                   VRIMPOSTOIT  = V_IMPOSTODIFE
             WHERE CDFILIAL = P_FILIAL
               AND NRLANCTONF = P_LANCTONF
               AND NRSEQITPROD = C_TRABITPROIMPOS.NRSEQITPROD
               AND CDIMPOSTO = C_TRABITPROIMPOS.CDIMPOSTO
               AND NRITPROIMPOS = '3';
         END IF;
      END IF;

      IF ((V_CDFILIREDU IS NULL) AND (NVL(V_IDORIGDESTNF, 'F') = 'L')) THEN

         V_VRCONTITIMP := 0;

         SELECT MAX(VRCONTITIMP)
           INTO V_VRCONTITIMP
           FROM ITEMPROIMPOS
          WHERE CDFILIAL = P_FILIAL
            AND NRLANCTONF = P_LANCTONF
            AND NRSEQITPROD = C_TRABITPROIMPOS.NRSEQITPROD
            AND CDIMPOSTO = C_TRABITPROIMPOS.CDIMPOSTO
            AND NRITPROIMPOS = '1';

         UPDATE TRABITPROIMPOS
            SET VRCONTIMPOIT = V_VRCONTITIMP
          WHERE CDFILIMPOIT = P_FILIAL
            AND NRLANCIMPOIT = P_LANCTONF
            AND NRSEQIMPOIT = C_TRABITPROIMPOS.NRSEQITPROD
            AND CDIMPOSTOIT = C_TRABITPROIMPOS.CDIMPOSTO
            AND NRSEQITPRO   = '3';

         UPDATE ITEMPROIMPOS
            SET VRCONTITIMP = V_VRCONTITIMP
          WHERE CDFILIAL = P_FILIAL
            AND NRLANCTONF = P_LANCTONF
            AND NRSEQITPROD = C_TRABITPROIMPOS.NRSEQITPROD
            AND CDIMPOSTO = C_TRABITPROIMPOS.CDIMPOSTO
            AND NRITPROIMPOS = '3';

      END IF;
   END LOOP;

   FOR C_TRABITPROIMPOS IN (SELECT CDIMPOSTO, VRALIQITEM, VRPERREDBCIT, VRPARDEDIT,
                                   CDFISCALIT, CDSITUTRIBIT, CDFISCOPERIT, CDSUFXCFOPIT,
                                   IDDIFALIQCUSPRI,
                                   SUM(VRCONTITIMP) AS VRCONTITIMP,
                                   SUM(VRBASECALCIT) AS VRBASECALCIT,
                                   SUM(VRIMPOSTOIT) AS VRIMPOSTOIT
                              FROM ITEMPROIMPOS
                             WHERE CDFILIAL = P_FILIAL
                               AND NRLANCTONF = P_LANCTONF
                               AND NRITPROIMPOS = '3'
                             GROUP BY CDIMPOSTO, VRALIQITEM, VRPERREDBCIT, VRPARDEDIT,
                                      CDFISCALIT, CDSITUTRIBIT, CDFISCOPERIT, CDSUFXCFOPIT,
                                      IDDIFALIQCUSPRI) LOOP

      UPDATE IMPOSTONF
         SET VRCONTABILNF = C_TRABITPROIMPOS.VRCONTITIMP,
             VRBASECALCNF = C_TRABITPROIMPOS.VRBASECALCIT,
             VRIMPOSTONF  = C_TRABITPROIMPOS.VRIMPOSTOIT
       WHERE CDFILIAL = P_FILIAL
         AND NRLANCTONF = P_LANCTONF
         AND CDIMPOSTO = C_TRABITPROIMPOS.CDIMPOSTO
         AND IDIMPOSTONF = '3'
         AND VRALIQNF = C_TRABITPROIMPOS.VRALIQITEM
         AND VRPERREDBCNF = C_TRABITPROIMPOS.VRPERREDBCIT
         AND VRPARDEDNF = C_TRABITPROIMPOS.VRPARDEDIT
         AND CDFISCALNF = C_TRABITPROIMPOS.CDFISCALIT
         AND CDSITUTRIBNF = C_TRABITPROIMPOS.CDSITUTRIBIT
         AND CDFISCOPERNF = C_TRABITPROIMPOS.CDFISCOPERIT
         AND NVL(IDDIFALIQCUSPRN, 'N') = NVL(C_TRABITPROIMPOS.IDDIFALIQCUSPRI, 'N')
         AND NVL(CDSUFXCFOPNF, 'N') = NVL(C_TRABITPROIMPOS.CDSUFXCFOPIT, 'N');
   END LOOP;

   FOR C_IMPOSTONF IN (
      SELECT IT.CDIMPOSTOIT, VRALIQIMPOIT, VRREDBCIMPOIT, VRPDEDIMPOIT, CDFISCIMPOIT,
             CDSTRIBIMPOIT, CDFOPERIMPOIT, CDSCFOPIMPOIT, NRSEQITPRO, SUM(VRCONTIMPOIT) AS VRCONTIMPOIT,
             SUM(VRBCALCIMPOIT) AS VRBCALCIMPOIT, SUM(VRIMPOSIT) AS VRIMPOSIT, I.IDTRATIMPO,
             SUM(VRIMPOSIT) AS VRIMPOSCONT, NVL(IDDIFALIQCUSPTI, 'N') IDDIFALIQCUSPTI,
             IDMOTDESOTRABIT
      FROM TRABITPROIMPOS IT, IMPOSTO I, NOTAFISCAL N
      WHERE (IT.CDFILIMPOIT  = P_FILIAL)    AND
            (IT.NRLANCIMPOIT = P_LANCTONF)  AND
            (IT.CDFILIMPOIT  = N.CDFILIAL)    AND
            (IT.NRLANCIMPOIT = N.NRLANCTONF)  AND
            (N.CDTIPOOPER    <> '03')         AND
            (I.CDIMPOSTO  = CDIMPOSTOIT) AND
            ((((CDFISCIMPOIT = W_1)) AND (IDIMPORECUP = W_S)) OR
             ((IDIMPORECUP <> W_S) AND (VRIMPOSIT <> 0)) OR (NRSEQITPRO = W_3)) AND
            IT.VRCONTIMPOIT > 0
      GROUP BY IT.CDIMPOSTOIT, VRALIQIMPOIT, VRREDBCIMPOIT, VRPDEDIMPOIT, CDFISCIMPOIT,
               CDSTRIBIMPOIT, CDFOPERIMPOIT, CDSCFOPIMPOIT, NRSEQITPRO, I.IDTRATIMPO,
               NVL(IDDIFALIQCUSPTI, 'N'), IDMOTDESOTRABIT
      UNION
      SELECT IT.CDIMPOSTOIT, 0 AS VRALIQIMPOIT, 0 AS VRREDBCIMPOIT, 0 AS VRPDEDIMPOIT, CDFISCIMPOIT,
             CDSTRIBIMPOIT, CDFOPERIMPOIT, CDSCFOPIMPOIT, NRSEQITPRO, SUM(VRCONTIMPOIT) AS VRCONTIMPOIT,
             0 AS VRBCALCIMPOIT, 0 AS VRIMPOSIT, I.IDTRATIMPO,
             SUM(VRIMPOSIT) AS VRIMPOSCONT, NVL(IDDIFALIQCUSPTI, 'N') IDDIFALIQCUSPTI,
             IDMOTDESOTRABIT
      FROM TRABITPROIMPOS IT, IMPOSTO I, NOTAFISCAL N
      WHERE (CDFILIMPOIT  = P_FILIAL)    AND
            (NRLANCIMPOIT = P_LANCTONF)  AND
            (IT.CDFILIMPOIT  = N.CDFILIAL)    AND
            (IT.NRLANCIMPOIT = N.NRLANCTONF)  AND
            (N.CDTIPOOPER    <> '03')         AND
            (I.CDIMPOSTO  = CDIMPOSTOIT) AND
            (NRSEQITPRO   <> W_3)        AND
            ((((CDFISCIMPOIT <> W_1)) AND (IDIMPORECUP = W_S)) OR
             ((IDIMPORECUP  <> W_S) AND (VRIMPOSIT = 0))) AND
            IT.VRCONTIMPOIT > 0
      GROUP BY IT.CDIMPOSTOIT, CDFISCIMPOIT, CDSTRIBIMPOIT,
               CDFOPERIMPOIT, CDSCFOPIMPOIT, NRSEQITPRO, I.IDTRATIMPO,
               NVL(IDDIFALIQCUSPTI, 'N'), IDMOTDESOTRABIT
      UNION
      SELECT IT.CDIMPOSTOIT, VRALIQIMPOIT, VRREDBCIMPOIT, VRPDEDIMPOIT, CDFISCIMPOIT,
             CDSTRIBIMPOIT, CDFOPERIMPOIT, CDSCFOPIMPOIT, NRSEQITPRO, SUM(VRCONTIMPOIT) AS VRCONTIMPOIT,
             SUM(VRBCALCIMPOIT) AS VRBCALCIMPOIT, SUM(VRIMPOSIT) AS VRIMPOSIT, I.IDTRATIMPO,
             SUM(VRIMPOSIT) AS VRIMPOSCONT, NVL(IDDIFALIQCUSPTI, 'N') IDDIFALIQCUSPTI,
             IDMOTDESOTRABIT
      FROM TRABITPROIMPOS IT, IMPOSTO I, NOTAFISCAL N
      WHERE (IT.CDFILIMPOIT  = P_FILIAL)    AND
            (IT.NRLANCIMPOIT = P_LANCTONF)  AND
            (IT.CDFILIMPOIT  = N.CDFILIAL)    AND
            (IT.NRLANCIMPOIT = N.NRLANCTONF)  AND
            (N.CDTIPOOPER    = '03')         AND
            (I.CDIMPOSTO  = CDIMPOSTOIT) AND
            ((((CDFISCIMPOIT = W_1)) AND (IDIMPORECUP = W_S)) OR
             ((IDIMPORECUP <> W_S) AND (VRIMPOSIT <> 0)) OR (NRSEQITPRO = W_3))
      GROUP BY IT.CDIMPOSTOIT, VRALIQIMPOIT, VRREDBCIMPOIT, VRPDEDIMPOIT, CDFISCIMPOIT,
               CDSTRIBIMPOIT, CDFOPERIMPOIT, CDSCFOPIMPOIT, NRSEQITPRO, I.IDTRATIMPO,
               NVL(IDDIFALIQCUSPTI, 'N'), IDMOTDESOTRABIT
      UNION

      SELECT IT.CDIMPOSTOIT, 0 AS VRALIQIMPOIT, 0 AS VRREDBCIMPOIT, 0 AS VRPDEDIMPOIT, CDFISCIMPOIT,
             CDSTRIBIMPOIT, CDFOPERIMPOIT, CDSCFOPIMPOIT, NRSEQITPRO, SUM(VRCONTIMPOIT) AS VRCONTIMPOIT,
             0 AS VRBCALCIMPOIT, 0 AS VRIMPOSIT, I.IDTRATIMPO,
             SUM(VRIMPOSIT) AS VRIMPOSCONT, NVL(IDDIFALIQCUSPTI, 'N') IDDIFALIQCUSPTI,
             IDMOTDESOTRABIT
      FROM TRABITPROIMPOS IT, IMPOSTO I, NOTAFISCAL N
      WHERE (IT.CDFILIMPOIT  = P_FILIAL)    AND
            (IT.NRLANCIMPOIT = P_LANCTONF)  AND
            (IT.CDFILIMPOIT  = N.CDFILIAL)    AND
            (IT.NRLANCIMPOIT = N.NRLANCTONF)  AND
            (N.CDTIPOOPER    = '03')         AND
            (I.CDIMPOSTO  = CDIMPOSTOIT) AND
            (NRSEQITPRO   <> W_3)        AND
            ((((CDFISCIMPOIT <> W_1)) AND (IDIMPORECUP = W_S)) OR
             ((IDIMPORECUP  <> W_S) AND (VRIMPOSIT = 0)))
      GROUP BY IT.CDIMPOSTOIT, CDFISCIMPOIT, CDSTRIBIMPOIT,
               CDFOPERIMPOIT, CDSCFOPIMPOIT, NRSEQITPRO, I.IDTRATIMPO,
               NVL(IDDIFALIQCUSPTI, 'N'), IDMOTDESOTRABIT
      UNION
      SELECT IT.CDIMPOSTOIT, VRALIQIMPOIT, VRREDBCIMPOIT, VRPDEDIMPOIT, CDFISCIMPOIT,
             CDSTRIBIMPOIT, CDFOPERIMPOIT, CDSCFOPIMPOIT, NRSEQITPRO, SUM(VRCONTIMPOIT) AS VRCONTIMPOIT,
             SUM(VRBCALCIMPOIT) AS VRBCALCIMPOIT, SUM(VRIMPOSIT) AS VRIMPOSIT, I.IDTRATIMPO,
             SUM(VRIMPOSIT) AS VRIMPOSCONT, NVL(IDDIFALIQCUSPTI, 'N') IDDIFALIQCUSPTI,
             IDMOTDESOTRABIT
      FROM TRABITPROIMPOS IT, IMPOSTO I, NOTAFISCAL N, TIPOOPERAC T
      WHERE (IT.CDFILIMPOIT  = P_FILIAL)    AND
            (IT.NRLANCIMPOIT = P_LANCTONF)  AND
            (IT.CDFILIMPOIT  = N.CDFILIAL)    AND
            (IT.NRLANCIMPOIT = N.NRLANCTONF)  AND
            (N.CDTIPOOPER    = T.CDTIPOOPER)  AND
            (N.IDENTRSAIDOP  = T.IDENTRSAIDOP) AND
            (T.IDNFAJUSTE    = 'S')           AND
            (I.CDIMPOSTO  = CDIMPOSTOIT) AND
            ((((CDFISCIMPOIT = W_1)) AND (IDIMPORECUP = W_S)) OR
             ((IDIMPORECUP <> W_S) AND (VRIMPOSIT <> 0)) OR (NRSEQITPRO = W_3))
      GROUP BY IT.CDIMPOSTOIT, VRALIQIMPOIT, VRREDBCIMPOIT, VRPDEDIMPOIT, CDFISCIMPOIT,
               CDSTRIBIMPOIT, CDFOPERIMPOIT, CDSCFOPIMPOIT, NRSEQITPRO, I.IDTRATIMPO,
               NVL(IDDIFALIQCUSPTI, 'N'), IDMOTDESOTRABIT
      UNION

      SELECT IT.CDIMPOSTOIT, 0 AS VRALIQIMPOIT, 0 AS VRREDBCIMPOIT, 0 AS VRPDEDIMPOIT, CDFISCIMPOIT,
             CDSTRIBIMPOIT, CDFOPERIMPOIT, CDSCFOPIMPOIT, NRSEQITPRO, SUM(VRCONTIMPOIT) AS VRCONTIMPOIT,
             0 AS VRBCALCIMPOIT, 0 AS VRIMPOSIT, I.IDTRATIMPO,
             SUM(VRIMPOSIT) AS VRIMPOSCONT, NVL(IDDIFALIQCUSPTI, 'N') IDDIFALIQCUSPTI,
             IDMOTDESOTRABIT
      FROM TRABITPROIMPOS IT, IMPOSTO I, NOTAFISCAL N, TIPOOPERAC T
      WHERE (IT.CDFILIMPOIT  = P_FILIAL)    AND
            (IT.NRLANCIMPOIT = P_LANCTONF)  AND
            (IT.CDFILIMPOIT  = N.CDFILIAL)    AND
            (IT.NRLANCIMPOIT = N.NRLANCTONF)  AND
            (N.CDTIPOOPER    = T.CDTIPOOPER)  AND
            (N.IDENTRSAIDOP  = T.IDENTRSAIDOP) AND
            (T.IDNFAJUSTE    = 'S')           AND
            (I.CDIMPOSTO  = CDIMPOSTOIT) AND
            (NRSEQITPRO   <> W_3)        AND
            ((((CDFISCIMPOIT <> W_1)) AND (IDIMPORECUP = W_S)) OR
             ((IDIMPORECUP  <> W_S) AND (VRIMPOSIT = 0)))
      GROUP BY IT.CDIMPOSTOIT, CDFISCIMPOIT, CDSTRIBIMPOIT,
               CDFOPERIMPOIT, CDSCFOPIMPOIT, NRSEQITPRO, I.IDTRATIMPO,
               NVL(IDDIFALIQCUSPTI, 'N'), IDMOTDESOTRABIT) LOOP


      BEGIN
         SELECT IDFORMAPUR
         INTO V_IDFORMAPUR
         FROM IMPOSTO
         WHERE CDIMPOSTO = C_IMPOSTONF.CDIMPOSTOIT;
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_IDFORMAPUR := NULL;
      END;

      V_VRIMPOSCONT := 0;
      IF C_IMPOSTONF.IDTRATIMPO = W_A THEN
         V_VRIMPOSCONT := C_IMPOSTONF.VRIMPOSCONT;
      ELSIF C_IMPOSTONF.IDTRATIMPO = W_D THEN
         V_VRIMPOSCONT := - C_IMPOSTONF.VRIMPOSCONT;
      END IF;

      IF V_IDFORMAPUR = W_P THEN
         INSERT INTO IMPOSTONF(
            CDFILIAL, NRLANCTONF, CDIMPOSTO, NRIMPOSNF, VRCONTABILNF, VRPERREDBCNF, VRBASECALCNF,
            VRALIQNF, VRPARDEDNF, VRIMPOSTONF, CDFISCALNF, CDSITUTRIBNF, CDFISCOPERNF, CDSUFXCFOPNF,
            IDIMPOSTONF, IDDIFALIQCUSPRN, CDTPCREDPICONF, CDNATUBCALPCNF, IDMOTDESONERANF)
         VALUES(
            P_FILIAL, P_LANCTONF, C_IMPOSTONF.CDIMPOSTOIT, V_SEQUIMPOSTNF, ROUND(C_IMPOSTONF.VRCONTIMPOIT,5),
            C_IMPOSTONF.VRREDBCIMPOIT, C_IMPOSTONF.VRBCALCIMPOIT, C_IMPOSTONF.VRALIQIMPOIT,
            C_IMPOSTONF.VRPDEDIMPOIT, C_IMPOSTONF.VRIMPOSIT, C_IMPOSTONF.CDFISCIMPOIT,
            C_IMPOSTONF.CDSTRIBIMPOIT, C_IMPOSTONF.CDFOPERIMPOIT, C_IMPOSTONF.CDSCFOPIMPOIT,
            C_IMPOSTONF.NRSEQITPRO, C_IMPOSTONF.IDDIFALIQCUSPTI, V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, C_IMPOSTONF.IDMOTDESOTRABIT);

         V_SEQUIMPOSTNF := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_SEQUIMPOSTNF) + 1)),2,0);
      ELSE
         V_CDGRUPOFISCAUX := NULL;

         SELECT MAX(G.CDGRUPOFISC)
           INTO V_CDGRUPOFISCAUX
           FROM GRUPOFISCIMPFIL G,
                (SELECT DECODE('E', 'E', CDFILIRECE, CDFILIEMIT) AS CDFILIAL
                   FROM NOTAFISCAL
                  WHERE CDFILIAL = P_FILIAL
                        AND NRLANCTONF = P_LANCTONF) F
          WHERE G.CDFILIAL = F.CDFILIAL
            AND NOT G.CDGRUPOFISC IS NULL
            AND G.CDIMPOSTO = C_IMPOSTONF.CDIMPOSTOIT;

         IF V_IDORIGDESTNF = 'F' THEN
            SELECT NVL(MAX(G.CDGRUPOFISC), V_CDGRUPOFISCAUX)
              INTO V_CDGRUPOFISCAUX
              FROM GRFISIMPIEFORN G,
                   (SELECT CDFORNECED
                      FROM NOTAFISCAL
                     WHERE CDFILIAL = P_FILIAL
                       AND NRLANCTONF = P_LANCTONF) N
             WHERE G.CDFORNECED = N.CDFORNECED
               AND G.CDEMPRESA = P_EMPRESA
               AND G.CDINSCESTA = P_INSCESTA
               AND NOT G.CDGRUPOFISC IS NULL
               AND G.CDIMPOSTO = C_IMPOSTONF.CDIMPOSTOIT;
         ELSE
            SELECT NVL(MAX(G.CDGRUPOFISC), V_CDGRUPOFISCAUX)
              INTO V_CDGRUPOFISCAUX
              FROM GRFISIMPIECLIE G,
                   (SELECT CDCLIENTE
                      FROM NOTAFISCAL
                     WHERE CDFILIAL = P_FILIAL
                       AND NRLANCTONF = P_LANCTONF) N
             WHERE G.CDCLIENTE = N.CDCLIENTE
               AND G.CDEMPRESA = P_EMPRESA
               AND G.CDINSCESTA = P_INSCESTA
               AND NOT G.CDGRUPOFISC IS NULL
               AND G.CDIMPOSTO = C_IMPOSTONF.CDIMPOSTOIT;
         END IF;

         IF V_CDGRUPOFISCAUX IS NULL THEN
            CONSULTA_CST_NFE(W_E, P_EMPRESA, '', P_INSCESTA, P_TIPOOPER, V_CDGRUPOFISC,C_IMPOSTONF.CDIMPOSTOIT, V_IDINTEREST, V_IDINTERNAC, P_FILIAL, P_LANCTONF, '', V_CDSITTRIBTMP, V_IDMODBCNFE, V_IDMODBCSTNFE, V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, V_IDMOTIDESSTNFE);
         ELSE
            CONSULTA_CST_NFE(W_E, P_EMPRESA, '', P_INSCESTA, P_TIPOOPER, V_CDGRUPOFISCAUX,C_IMPOSTONF.CDIMPOSTOIT, V_IDINTEREST, V_IDINTERNAC, P_FILIAL, P_LANCTONF, '', V_CDSITTRIBTMP, V_IDMODBCNFE, V_IDMODBCSTNFE, V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, V_IDMOTIDESSTNFE);
         END IF;

         INSERT INTO IMPOSTONF(
            CDFILIAL, NRLANCTONF, CDIMPOSTO, NRIMPOSNF, VRCONTABILNF, VRPERREDBCNF, VRBASECALCNF,
            VRALIQNF, VRPARDEDNF, VRIMPOSTONF, CDFISCALNF, CDSITUTRIBNF, CDFISCOPERNF, CDSUFXCFOPNF,
            IDIMPOSTONF, IDDIFALIQCUSPRN, CDTPCREDPICONF, CDNATUBCALPCNF, IDMOTDESONERANF)
         VALUES(
            P_FILIAL, P_LANCTONF, C_IMPOSTONF.CDIMPOSTOIT, V_SEQUIMPOSTNF, ROUND(C_IMPOSTONF.VRCONTIMPOIT,5),
            C_IMPOSTONF.VRREDBCIMPOIT, C_IMPOSTONF.VRBCALCIMPOIT, C_IMPOSTONF.VRALIQIMPOIT,
            C_IMPOSTONF.VRPDEDIMPOIT, C_IMPOSTONF.VRIMPOSIT, C_IMPOSTONF.CDFISCIMPOIT,
            C_IMPOSTONF.CDSTRIBIMPOIT, C_IMPOSTONF.CDFOPERIMPOIT, C_IMPOSTONF.CDSCFOPIMPOIT,
            C_IMPOSTONF.NRSEQITPRO, C_IMPOSTONF.IDDIFALIQCUSPTI, V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, C_IMPOSTONF.IDMOTDESOTRABIT);

         V_SEQUIMPOSTNF := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_SEQUIMPOSTNF) + 1)),2,0);
      END IF;

   END LOOP;

   FOR C_IMPOSTORETI IN (SELECT P_EMPRESA AS CDEMPRESA, I.CDIMPOSTO, V_IDTPIJURNF AS IDTPIJURNF,
                                V_NRINSJURNF AS NRINSJURNF, V_DTENTRSAID AS DTENTRSAID
                         FROM IMPOSTO I, IMPOSTONF IP
                         WHERE I.IDTRATIMPO   = W_R          AND
                               I.IDUTVRMENSBC = W_S          AND
                               IP.CDFILIAL    = P_FILIAL     AND
                               IP.NRLANCTONF  = P_LANCTONF   AND
                               I.CDIMPOSTO    = IP.CDIMPOSTO
                         GROUP BY
                            P_EMPRESA, I.CDIMPOSTO, V_IDTPIJURNF, V_NRINSJURNF, V_DTENTRSAID) LOOP

      BASECALC_RETIDO('S', P_FILIAL, P_LANCTONF, C_IMPOSTORETI.IDTPIJURNF, C_IMPOSTORETI.NRINSJURNF,
                      C_IMPOSTORETI.DTENTRSAID,  C_IMPOSTORETI.CDIMPOSTO, W_E, C_IMPOSTORETI.CDEMPRESA,
                      P_INSCESTA, V_PAISORIG, V_ESTAORIG, V_PAISDEST, V_ESTADEST, V_CDGRUPOFISC, V_CDGRPFISCSV, P_TIPOOPER);
   END LOOP;

   /* SE O IPI COMPOR A BASE DE CALCULO DO ICMS E O ICMS TIVER O CODIGO FISCAL IGUAL A 1 SERA ATUALIZADO COM O IDENTIFICADOR 4 */
   FOR C_IMPFISC IN (SELECT CDFILIAL, NRLANCTONF, CDIMPOSTO, CDSITUTRIBNF, CDFISCOPERNF, CDFISCALNF
                       FROM IMPOSTONF IP
                      WHERE IP.CDFILIAL = P_FILIAL
                        AND IP.NRLANCTONF = P_LANCTONF
                        AND IP.IDIMPOSTONF = W_1
                        AND IP.CDFISCALNF = W_1) LOOP

      SELECT MAX(BC.CDIMPOBCALC) AS CDIMPOBCALC
        INTO V_CDIMPOBCALC
        FROM BASECALCTPOPER BC
       WHERE BC.IDENTRSAIDOP = P_ENTRSAID
         AND BC.CDTIPOOPER = P_TIPOOPER
         AND BC.CDIMPOSTO = C_IMPFISC.CDIMPOSTO
         AND BC.CDIMPOBCALC IS NOT NULL
         AND ((SUBSTR(C_IMPFISC.CDSITUTRIBNF,2,2)  = BC.CDCSTIMPOTPOP)  OR (BC.CDCSTIMPOTPOP IS NULL))
         AND ((SUBSTR(C_IMPFISC.CDFISCOPERNF,2,10) = BC.CDCFOPIMPOTPOP) OR (BC.CDCFOPIMPOTPOP IS NULL))
         AND (C_IMPFISC.CDFISCALNF = BC.CDFISCIMPOTPOP) OR (BC.CDFISCIMPOTPOP IS NULL);

      IF V_CDIMPOBCALC IS NULL THEN
         SELECT MAX(BC.CDIMPOBCALC) AS CDIMPOBCALC
           INTO V_CDIMPOBCALC
           FROM BASECALC BC
          WHERE BC.CDIMPOSTO = C_IMPFISC.CDIMPOSTO
            AND BC.CDIMPOBCALC IS NOT NULL
            AND ((SUBSTR(C_IMPFISC.CDSITUTRIBNF,2,2)  = BC.CDCSTIMPO)  OR (BC.CDCSTIMPO  IS NULL))
            AND ((SUBSTR(C_IMPFISC.CDFISCOPERNF,2,10) = BC.CDCFOPIMPO) OR (BC.CDCFOPIMPO IS NULL))
            AND (C_IMPFISC.CDFISCALNF = BC.CDFISCIMPO) OR (BC.CDFISCIMPO IS NULL)
            AND BC.IDTIPOBCALC = 'I';

         IF NOT V_CDIMPOBCALC IS NULL THEN
            UPDATE IMPOSTONF
               SET IDIMPOSTONF = '4'
             WHERE CDFILIAL = C_IMPFISC.CDFILIAL
               AND NRLANCTONF = C_IMPFISC.NRLANCTONF
               AND CDIMPOSTO = V_CDIMPOBCALC
               AND IDIMPOSTONF = '1';
         END IF;
      ELSE
         UPDATE IMPOSTONF
         SET IDIMPOSTONF = '4'
         WHERE CDFILIAL   = C_IMPFISC.CDFILIAL   AND
               NRLANCTONF = C_IMPFISC.NRLANCTONF AND
               CDIMPOSTO  = V_CDIMPOBCALC        AND
               IDIMPOSTONF = '1';
      END IF;
   END LOOP;

--INCLUSÃO DOS ENCARGOS DA NF EM CASO DE IMPORTAÇÃO
   IF (V_INTEGRACAO IS NOT NULL) THEN
      INSERT INTO ITEMENCARGO
      (CDFILIAL, NRLANCTONF, CDENCARGO, VRITEMENCA)
      (SELECT P_FILIAL, P_LANCTONF, CDENCARGO, 0 AS VRITEMENCA
       FROM ENCARGO
       MINUS
       SELECT CDFILIAL, NRLANCTONF, CDENCARGO, 0 AS VRITEMENCA
       FROM ITEMENCARGO
       WHERE CDFILIAL   = P_FILIAL AND
             NRLANCTONF = P_LANCTONF);
   END IF;

   --ATUALIZAÇÃO DO CÓDIGO FISCAL DA OPERAÇÃO NA TABELA DE NOTA FISCAL

   IF (V_INTEGRACAO IS NULL) OR (P_ENTRSAID = W_E) THEN

      IF NOT(P_TIPOOPER  = '09') THEN
         IF (V_CDCFOPINFUSU IS NULL) OR (V_CDCFOPINFUSU = '***') THEN
            SELECT COUNT(DISTINCT CDFISOPEITEM), MAX(CDFISOPEITEM)
              INTO   V_COUNT                     , V_CDFISOPENTF
              FROM ITEMPRODUTO
             WHERE (CDFILIAL   = P_FILIAL) AND
                   (NRLANCTONF = P_LANCTONF);

            IF (V_COUNT > 1) THEN
               UPDATE NOTAFISCAL
                  SET CDFISOPENTF  = '***'
                WHERE CDFILIAL     = P_FILIAL
                  AND NRLANCTONF   = P_LANCTONF;

               UPDATE NOTAFISCAL
                  SET DSCDFISOPENF = NVL(V_DSCDFISOPEITREGRA, V_DSCDFISOPEIT)
                WHERE (CDFILIAL    = P_FILIAL)
                  AND (NRLANCTONF  = P_LANCTONF)
                  AND DSCDFISOPENF IS NULL;

            ELSIF (V_COUNT = 1) THEN
               UPDATE NOTAFISCAL
                  SET CDFISOPENTF  = V_CDFISOPENTF
                WHERE (CDFILIAL    = P_FILIAL)
                  AND (NRLANCTONF  = P_LANCTONF);

               UPDATE NOTAFISCAL
                  SET DSCDFISOPENF = NVL(V_DSCDFISOPEITREGRA, V_DSCDFISOPEIT)
                WHERE (CDFILIAL    = P_FILIAL)
                  AND (NRLANCTONF  = P_LANCTONF)
                  AND DSCDFISOPENF IS NULL;
            END IF;
         ELSE
            SELECT COUNT(DISTINCT CDFISOPEITEM), MAX(CDFISOPEITEM)
              INTO   V_COUNT , V_CDFISOPENTF
              FROM ITEMPRODUTO
             WHERE (CDFILIAL   = P_FILIAL) AND
                   (NRLANCTONF = P_LANCTONF);

            IF (V_COUNT > 1) THEN
               UPDATE NOTAFISCAL
                  SET CDFISOPENTF  = '***',
                      CDCFOPINFUSU = '***'
                WHERE CDFILIAL   = P_FILIAL
                  AND NRLANCTONF = P_LANCTONF;
            ELSIF (V_COUNT = 1) THEN
               UPDATE NOTAFISCAL
                  SET CDFISOPENTF  = V_CDFISOPENTF,
                      DSCDFISOPENF = NVL(V_DSCDFISOPEITREGRA, V_DSCDFISOPEIT),
                      CDCFOPINFUSU = V_CDCFOPINFUSU,
                      DSCFOPINFUSU = V_DSCFOPINFUSU

                WHERE (CDFILIAL    = P_FILIAL)
                  AND (NRLANCTONF  = P_LANCTONF);
            END IF;
         END IF;
         IF (V_DSCFOPINFUSU IS NOT NULL) THEN
            UPDATE NOTAFISCAL
               SET DSCDFISOPENF = V_DSCFOPINFUSU
             WHERE (CDFILIAL    = P_FILIAL)
               AND (NRLANCTONF  = P_LANCTONF);
         END IF;
      END IF;

   END IF;

   IF (V_INTEGRACAO IS NOT NULL) THEN
      IF (P_ENTRSAID = W_S) THEN
         SELECT NVL(SUM(VRORIGREC),0)
         INTO V_VRCONTAREC
         FROM CONTARECEBER
         WHERE CDFILIAL   = P_FILIAL AND
               NRLANCTONF = P_LANCTONF;

         SELECT NVL(SUM(IT.VRIMPOSTOT),0)
         INTO V_IMPOSRETI
         FROM TRABIMPOSNFTOT IT, IMPOSTO I
         WHERE IT.CDFILIMPTOT  = P_FILIAL      AND
               IT.NRLANCIMPTOT = P_LANCTONF    AND
               I.CDIMPOSTO     = IT.CDIMPOSTOT AND
               I.IDDESCRFONTE  <> W_A          AND
               I.IDTRATIMPO    = W_R;

         IF (V_VRCONTAREC = V_VRNOTAFISC) AND (V_IMPOSRETI > 0) THEN
            APURAC_VENC(P_FILIAL, P_FORNECED, P_LANCTONF);
         END IF;
      ELSE
         IF (V_IDDOCFINANC <> W_L) AND (V_IDSTATUS NOT IN (W_A, W_E)) AND
            (SUBSTR(V_INTEGRACAO,1,1) IN (W_F, W_M)) THEN
            IF V_IDORIGDESTNF = W_F THEN
               BEGIN
                  SELECT IDTPFORPGTFO
                  INTO V_IDTPFORPGTFO
                  FROM FORNECEDOR
                  WHERE CDFORNECED = P_FORNECED;
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_IDTPFORPGTFO := NULL;
               END;

               IF V_IDTPFORPGTFO IS NOT NULL THEN
                  GERA_CONTAPAGAR(P_FILIAL, P_FORNECED, P_LANCTONF, W_F);
               END IF;
            END IF;
         END IF;
      END IF;

      BEGIN
         SELECT CDPRODUTO
         INTO V_CDPRGENEREV
         FROM ITEMPRODUTO
         WHERE CDFILIAL   = P_FILIAL      AND
               NRLANCTONF = P_LANCTONF    AND
               CDPRODUTO  = V_CDPRGENEREV;
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_CDPRGENEREV := NULL;
      END;

      IF V_CDPRGENEREV IS NOT NULL THEN
         DELETE IMPOSINFUSU
         WHERE CDFILIAL   = P_FILIAL AND
               NRLANCTONF = P_LANCTONF;

         INSERT INTO IMPOSINFUSU
            (CDFILIAL, NRLANCTONF, NRSEQITPROD, CDIMPOSTO,
             CDFISCINFUSU, VRALIQINFUSU, VRRDBCINFUSU, VRPDEDINFUSU)
         (SELECT CDFILIMPOIT, NRLANCIMPOIT, NRSEQIMPOIT, CDIMPOSTOIT,
                 NVL(CDFISCIMPOIT,' '), NVL(VRALIQIMPOIT,0), VRREDBCIMPOIT,
                 VRPDEDIMPOIT
          FROM TRABITPROIMPOS
          WHERE CDFILIMPOIT  = P_FILIAL   AND
                NRLANCIMPOIT = P_LANCTONF AND
                NRSEQITPRO   = W_1);
      END IF;
   END IF;


   /* ESTA ROTINA ABAIXO SERVE PARA ATUALIZAR O VALOR CONTÁBIL E BRUTO DOS PRODUTOS COM A DIFERENÇA
      DE CENTAVOS ENTRE O VALOR DOS IMPOSTOS POR ÍTEM E A SUA RESPECTIVA TOTALIZAÇÃO. ESTA DIFERENÇA
      É IGNORADA NO FECHAMENTO DA NF CASO O CLIENTE TRABALHE COM UM NÚMERO MENOR DE CASAS DECIMAIS E
      PROVOCA ERROS NA CONTABILIZAÇÃO*/

   IF V_NRDECITOTANF <> 2 THEN
      FOR C_ATUAVRCONT IN (SELECT T.CDIMPOSTOIT, SUM(T.VRIMPOSIT) AS VRIMPOSIT, T.CDFISCIMPOIT,
                                  I.IDIMPORECUP, I.CDCCTBLATIV, I.CDCCTBLPASS, I.IDTRATIMPO
                           FROM TRABITPROIMPOS T, IMPOSTO I
                           WHERE T.CDFILIMPOIT  = P_FILIAL      AND
                                 T.NRLANCIMPOIT = P_LANCTONF    AND
                                 T.NRSEQITPRO   = W_1           AND
                                 I.CDIMPOSTO    = T.CDIMPOSTOIT AND
                                 I.IDTIPCONTAB  = W_D
                           GROUP BY T.CDIMPOSTOIT, T.CDFISCIMPOIT, I.IDIMPORECUP,
                                    I.CDCCTBLATIV, I.CDCCTBLPASS, I.IDTRATIMPO) LOOP

         SELECT SUM(VRIMPOSTOT) - C_ATUAVRCONT.VRIMPOSIT
         INTO V_VRDIFERENCA
         FROM TRABIMPOSNFTOT
         WHERE CDFILIMPTOT  = P_FILIAL   AND
               NRLANCIMPTOT = P_LANCTONF AND
               CDIMPOSTOT   = C_ATUAVRCONT.CDIMPOSTOIT;

         SELECT SUM(VRBRUTITEM), SUM(VRCONTITEM)
         INTO V_VRBRUTO, V_VRCONTAB
         FROM ITEMPRODUTO I, TRABITPROIMPOS T
         WHERE I.CDFILIAL     = P_FILIAL                  AND
               I.NRLANCTONF   = P_LANCTONF                AND
               T.CDFILIMPOIT  = I.CDFILIAL                AND
               T.NRLANCIMPOIT = I.NRLANCTONF              AND
               T.NRSEQIMPOIT  = I.NRSEQITPROD             AND
               T.CDIMPOSTOIT  = C_ATUAVRCONT.CDIMPOSTOIT  AND
               T.NRSEQITPRO   = W_1;

         IF V_VRDIFERENCA <> 0 THEN
            V_IMPOCONTAB := 0;

            IF (C_ATUAVRCONT.IDIMPORECUP = W_S) THEN
               IF (C_ATUAVRCONT.CDFISCIMPOIT = W_1) THEN
                  IF (C_ATUAVRCONT.CDCCTBLATIV IS NOT NULL) THEN
                     IF C_ATUAVRCONT.IDTRATIMPO = W_V THEN
                        V_IMPOCONTAB := - V_VRDIFERENCA;
                     END IF;
                  END IF;
               ELSE
                  IF C_ATUAVRCONT.IDTRATIMPO = W_A THEN
                     V_IMPOCONTAB := V_VRDIFERENCA;
                  ELSIF C_ATUAVRCONT.IDTRATIMPO IN (W_D,W_R) THEN
                     V_IMPOCONTAB := - V_VRDIFERENCA;
                  END IF;
               END IF;
            ELSE
               IF NOT(C_ATUAVRCONT.CDCCTBLPASS IS NULL) THEN
                  IF C_ATUAVRCONT.IDTRATIMPO = W_V THEN
                     V_IMPOCONTAB := - V_VRDIFERENCA;
                  END IF;
               ELSE
                  IF C_ATUAVRCONT.IDTRATIMPO = W_A THEN
                     V_IMPOCONTAB := V_VRDIFERENCA;
                  ELSIF C_ATUAVRCONT.IDTRATIMPO IN (W_D,W_R) THEN
                     V_IMPOCONTAB := - V_VRDIFERENCA;
                  END IF;
               END IF;
            END IF;

            IF C_ATUAVRCONT.IDTRATIMPO = W_A THEN
               UPDATE ITEMPRODUTO
               SET VRCONTITEM = VRCONTITEM + ((V_IMPOCONTAB  / V_VRCONTAB) * VRCONTITEM)
               WHERE EXISTS(SELECT CDFILIMPOIT, NRLANCIMPOIT, NRSEQIMPOIT
                            FROM TRABITPROIMPOS T
                            WHERE T.CDFILIMPOIT  = P_FILIAL                 AND
                                  T.NRLANCIMPOIT = P_LANCTONF               AND
                                  T.CDIMPOSTOIT  = C_ATUAVRCONT.CDIMPOSTOIT AND
                                  T.CDFILIMPOIT  = ITEMPRODUTO.CDFILIAL     AND
                                  T.NRLANCIMPOIT = ITEMPRODUTO.NRLANCTONF   AND
                                  T.NRSEQIMPOIT  = ITEMPRODUTO.NRSEQITPROD);

            ELSIF C_ATUAVRCONT.IDTRATIMPO = W_D THEN
               UPDATE ITEMPRODUTO
               SET VRCONTITEM = VRCONTITEM + ((V_IMPOCONTAB  / V_VRCONTAB) * VRCONTITEM)
               WHERE EXISTS(SELECT CDFILIMPOIT, NRLANCIMPOIT, NRSEQIMPOIT
                            FROM TRABITPROIMPOS T
                            WHERE T.CDFILIMPOIT  = P_FILIAL                 AND
                                  T.NRLANCIMPOIT = P_LANCTONF               AND
                                  T.CDIMPOSTOIT  = C_ATUAVRCONT.CDIMPOSTOIT AND
                                  T.CDFILIMPOIT  = ITEMPRODUTO.CDFILIAL     AND
                                  T.NRLANCIMPOIT = ITEMPRODUTO.NRLANCTONF   AND
                                  T.NRSEQIMPOIT  = ITEMPRODUTO.NRSEQITPROD);

            ELSE
               UPDATE ITEMPRODUTO
               SET VRCONTITEM = VRCONTITEM + ((V_IMPOCONTAB  / V_VRCONTAB) * VRCONTITEM)
               WHERE EXISTS(SELECT CDFILIMPOIT, NRLANCIMPOIT, NRSEQIMPOIT
                            FROM TRABITPROIMPOS T
                            WHERE T.CDFILIMPOIT  = P_FILIAL                 AND
                                  T.NRLANCIMPOIT = P_LANCTONF               AND
                                  T.CDIMPOSTOIT  = C_ATUAVRCONT.CDIMPOSTOIT AND
                                  T.CDFILIMPOIT  = ITEMPRODUTO.CDFILIAL     AND
                                  T.NRLANCIMPOIT = ITEMPRODUTO.NRLANCTONF   AND
                                  T.NRSEQIMPOIT  = ITEMPRODUTO.NRSEQITPROD);

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

   IF NOT(P_LANCESTQ IS NULL) AND (V_IDCTRLESTQ <> W_N) THEN

      IF (V_IDOPERDEVONF = W_S) THEN
         IF (V_DEVOLORIG IS NOT NULL) THEN

            V_DTSAIDNFORIG := NULL;

            SELECT MAX(IDSISTEMA), MAX(DTENTRSAID)
            INTO V_IDSISTEMA, V_DTSAIDNFORIG
            FROM NOTAFISCAL N, ITEMNOTAFISC I
            WHERE I.CDFILIAL     = P_FILIAL      AND
                  I.NRLANCTONF   = P_LANCTONF    AND
                  I.CDFILIALIT   = N.CDFILIAL    AND
                  I.NRLANCTONFIT = N.NRLANCTONF;
         ELSE
            V_IDSISTEMA := W_EXP;
            V_DTSAIDNFORIG := V_DTATUAL;
         END IF;

         IF (V_IDSISTEMA = W_EXP) THEN
            SELECT MAX(NVL(IDRETPROEXP,1))
            INTO V_IDRETPROEXP
            FROM PAREXPEDICAO;
         END IF;
      END IF;

      DELETE FROM ITLANCTOEST
      WHERE CDFILIAL   = P_FILIAL    AND
            NRLANCESTQ = P_LANCESTQ;

      IF V_IDSISTEMA <> W_VMN THEN
         DELETE FROM LANCTOESTOQ
         WHERE CDFILIAL   = P_FILIAL    AND
               NRLANCESTQ = P_LANCESTQ;

         DELETE FROM LANCTOESTOQ
         WHERE CDFILIAL   = P_FILIAL    AND
               NRLANCTONF = P_LANCTONF;
      ELSE
         UPDATE LANCTOESTOQ
         SET DTLANCESTQ   = P_INIVALID
         WHERE CDFILIAL   = P_FILIAL    AND
               NRLANCESTQ = P_LANCESTQ;
      END IF;

      IF P_ENTRSAID = W_S THEN
         IF (P_TIPOOPER = '06') THEN
            V_TIPOMOVI := '5';
         ELSE
            V_TIPOMOVI := '4';
         END IF;
      ELSE
         V_TIPOMOVI := W_2;
      END IF;

      SELECT T.NMTIPOOPER, F.NMFILIAL
      INTO V_NMTIPOOPER, V_NMFILIEMIT
      FROM NOTAFISCAL N, TIPOOPERAC T, FILIAL F
      WHERE
         (N.CDFILIAL     = P_FILIAL)       AND
         (N.NRLANCTONF   = P_LANCTONF)     AND
         (T.CDTIPOOPER   = N.CDTIPOOPER)   AND
         (T.IDENTRSAIDOP = N.IDENTRSAIDOP) AND
         (N.CDFILIEMIT   = F.CDFILIAL(+));

      IF V_IDORIGDESTNF = W_L THEN
         V_DESCLANC := SUBSTR('NF: '||P_LANCTONF||' - '||SUBSTR(V_NMTIPOOPER,1,25)||' - '||SUBSTR(V_NMFILIEMIT,1,15),1,60);
      ELSE
         V_DESCLANC := SUBSTR('LANC. ORIGEM: '||V_NRINSJURNF||' Nº'||V_NRNOTAFISC||' SERIE '||V_SERIE,1,60);
      END IF;

      SELECT COUNT(*)
      INTO V_COUNT
      FROM LANCTOESTOQ
      WHERE CDFILIAL   = P_FILIAL    AND
            NRLANCESTQ = P_LANCESTQ;

      IF V_COUNT = 0 THEN
         INSERT INTO LANCTOESTOQ(CDFILIAL,NRLANCESTQ,NRLANCTONF,DSLANCESTQ,IDTPLANCTO,DTLANCESTQ,CDOPERADOR,CDFILIMOVI)
                          VALUES(P_FILIAL, P_LANCESTQ, P_LANCTONF, V_DESCLANC, P_ENTRSAID, P_INIVALID,P_CDOPERADOR, V_CDFILIRECE);
      END IF;


      IF (V_IDSISTEMA = W_PDV) THEN
         SELECT NVL(MAX(IDATUEST),1)
         INTO V_IDATUEST
         FROM PARAVEND
         WHERE CDFILIAL = P_FILIAL;
      END IF;

      IF ((V_IDSISTEMA = W_EXP) AND (V_IDRETPROEXP = W_2)) OR ((V_IDSISTEMA = W_PDV) AND (V_IDATUEST = W_1)) THEN
         FOR C_ITLANCTOEST IN (SELECT NRSEQITPROD,IP.CDPRODUTO,VRUNITITEM,VRTOTAITEM,
                                      QTITEMPROD,CDPRODESTO,VRBRUTITEM,VRDESCITEM,VRCONTITEM,
                                      NVL(IP.CDALMOXARIFE, ' ') CDALMOXARIFE,
                                      NVL(IP.CDLOCALESTOQ, ' ') CDLOCALESTOQ,
                                      NVL(NRLOTEESTQ, ' ') NRLOTEESTQ,
                                      NVL(NRSUBLOTE, ' ') NRSUBLOTE, CDFILIMOVI,
                                      CDFISOPEITEM,
                                      NVL(IDORIGEMPROD, 'N') IDORIGEMPROD
                               FROM ITEMPRODUTO IP, PRODUTO P, PRODFILI PF
                               WHERE IP.CDFILIAL    = P_FILIAL     AND
                                     IP.NRLANCTONF  = P_LANCTONF   AND
                                     P.CDPRODUTO    = IP.CDPRODUTO AND
                                     PF.CDFILIAL    = V_CDFILIRECE AND
                                     PF.CDPRODUTO   = P.CDPRODESTO AND
                                     NVL(IDCNTRESTOQ, W_S) <> W_N) LOOP

            INSERT INTO LOTE
            (CDFILIAL, NRLOTEESTQ, NRSUBLOTE, CDPRODUTO, IDSTATLOTE, DTENTRLOTE)
            (SELECT C_ITLANCTOEST.CDFILIMOVI,  C_ITLANCTOEST.NRLOTEESTQ,
                    C_ITLANCTOEST.NRSUBLOTE,   C_ITLANCTOEST.CDPRODESTO, W_L , SYSDATE
             FROM PARAMGERAL
             MINUS
             SELECT CDFILIAL,      NRLOTEESTQ,  NRSUBLOTE,
                    C_ITLANCTOEST.CDPRODESTO, W_L, SYSDATE
             FROM LOTE
             WHERE  C_ITLANCTOEST.CDFILIMOVI = CDFILIAL     AND
                    C_ITLANCTOEST.NRLOTEESTQ = NRLOTEESTQ   AND
                    C_ITLANCTOEST.NRSUBLOTE  = NRSUBLOTE    AND
                    C_ITLANCTOEST.CDPRODESTO = CDPRODUTO);

            UPDATE ITEMPRODUTO
            SET CDPRODMOVI = C_ITLANCTOEST.CDPRODESTO
            WHERE (CDFILIAL    = P_FILIAL)    AND
                  (NRLANCTONF  = P_LANCTONF)  AND
                  (NRSEQITPROD = C_ITLANCTOEST.NRSEQITPROD);

            SELECT COUNT(*)
            INTO V_EXISTE_ROT
            FROM ROTFABRICA
            WHERE CDPRODUTO = C_ITLANCTOEST.CDPRODUTO;

            IF (V_EXISTE_ROT) > 0 THEN

               INSERE_SUBPRODMAN(P_FILIAL,P_LANCESTQ,P_TIPOOPER,C_ITLANCTOEST.CDPRODUTO,
                                 C_ITLANCTOEST.QTITEMPROD,
                                 C_ITLANCTOEST.VRTOTAITEM, C_ITLANCTOEST.VRDESCITEM,
                                 C_ITLANCTOEST.VRBRUTITEM, C_ITLANCTOEST.VRCONTITEM,
                                 V_VRTOTALANCTO, V_QTDELANCTO, V_TIPOMOVI, P_INIVALID,
                                 C_ITLANCTOEST.CDPRODESTO, '', '', 'F');
            ELSE
               BEGIN
                  SELECT VRFATOCONV INTO V_FATOCONV
                  FROM PRODUTO P, ITEMPRODUTO IP
                  WHERE IP.CDFILIAL    = P_FILIAL                  AND
                        IP.NRLANCTONF  = P_LANCTONF                AND
                        IP.NRSEQITPROD = C_ITLANCTOEST.NRSEQITPROD AND
                        P.CDPRODUTO    = IP.CDPRODUTO;
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_FATOCONV := 0;
               END;

               IF (V_FATOCONV IS NULL) OR (V_FATOCONV = 0) THEN
                  V_FATOCONV := 1;
               END IF;

               V_QTDELANCTO   := C_ITLANCTOEST.QTITEMPROD;
               V_VRTOTALANCTO := (C_ITLANCTOEST.VRTOTAITEM - C_ITLANCTOEST.VRDESCITEM);

               IF NOT(V_QTDELANCTO = 0) THEN
                  V_VRUNITLANCTO := V_VRTOTALANCTO/V_QTDELANCTO;
               ELSE
                  V_VRUNITLANCTO := V_VRTOTALANCTO;
               END IF;

               IF (P_TIPOOPER = '06') THEN
                  V_TOTABRUT   := 0;
                  V_TOTACONTAB := 0;
                  V_VRCUSTENTR := 0;
               ELSIF (V_IDCOMPRABONI = 'S') THEN
                  SELECT NVL(MAX(IDCOMPOEVENC),'S')
                    INTO V_COMPCUSTPROD
                    FROM TPOPERCFOP
                   WHERE CDTIPOOPER   = P_TIPOOPER
                     AND IDENTRSAIDOP = P_ENTRSAID
                     AND CDFISCOPER   = C_ITLANCTOEST.CDFISOPEITEM;

                  IF (V_COMPCUSTPROD = 'N') THEN
                     V_TOTABRUT   := 0;
                     V_TOTACONTAB := 0;
                     V_VRCUSTENTR := 0;
                  ELSE
                     IF NOT(V_IDNFRETIND = w_S) THEN
                        IF NOT(V_QTDELANCTO = 0) THEN
                           V_TOTABRUT   := (C_ITLANCTOEST.VRBRUTITEM/V_QTDELANCTO)/V_FATOCONV;
                           V_TOTACONTAB := (C_ITLANCTOEST.VRCONTITEM/V_QTDELANCTO)/V_FATOCONV;
                        ELSE
                           V_TOTABRUT   := C_ITLANCTOEST.VRBRUTITEM;
                           V_TOTACONTAB := C_ITLANCTOEST.VRCONTITEM;
                        END IF;
                        V_VRCUSTENTR := C_ITLANCTOEST.VRCONTITEM;
                     ELSE
                        V_VRCUSTENTR := V_TOTACONTAB;
                     END IF;
                  END IF;
               ELSE
                  IF NOT(V_IDNFRETIND = w_S) THEN
                     IF NOT(V_QTDELANCTO = 0) THEN
                        V_TOTABRUT   := (C_ITLANCTOEST.VRBRUTITEM/V_QTDELANCTO)/V_FATOCONV;
                        V_TOTACONTAB := (C_ITLANCTOEST.VRCONTITEM/V_QTDELANCTO)/V_FATOCONV;
                     ELSE
                        V_TOTABRUT   := C_ITLANCTOEST.VRBRUTITEM;
                        V_TOTACONTAB := C_ITLANCTOEST.VRCONTITEM;
                     END IF;
                     V_VRCUSTENTR := C_ITLANCTOEST.VRCONTITEM;
                  ELSE
                     V_VRCUSTENTR := V_TOTACONTAB;
                  END IF;
               END IF;

               IF (V_IDOPERDEVONF = W_S AND V_IDUTCUSORIGEST = W_S) THEN
                  V_VRCUSTENTR := ROUND(CUSTO_PRODUTO_LCEST(V_CDFILIRECE, C_ITLANCTOEST.CDPRODESTO, V_CDTIPCUSTEST, P_INIVALID,
                                                            V_DTATUAL, C_ITLANCTOEST.CDALMOXARIFE, C_ITLANCTOEST.CDLOCALESTOQ,
                                                            C_ITLANCTOEST.NRLOTEESTQ, C_ITLANCTOEST.NRSUBLOTE), 5);

                  IF V_VRCUSTENTR = 0 THEN
                     V_TOTABRUT   := C_ITLANCTOEST.VRUNITITEM;
                     V_TOTACONTAB := C_ITLANCTOEST.VRUNITITEM;
                  ELSE
                     V_TOTABRUT   := V_VRCUSTENTR;
                     V_TOTACONTAB := V_VRCUSTENTR;
                  END IF;
               END IF;

               SELECT NVL(MAX(NRSEQUITEM),0) + 1
               INTO V_NRSEQITPROD
               FROM ITLANCTOEST
               WHERE CDFILIAL   = P_FILIAL    AND
                     NRLANCESTQ = P_LANCESTQ;

               IF V_IDORIGDESTNF = W_L THEN
                  BEGIN
                     SELECT CDFORNOPELOG
                     INTO V_CDFORNECED
                     FROM FILIAL
                     WHERE CDFILIAL = V_CDFILIEMIT;
                  EXCEPTION
                     WHEN NO_DATA_FOUND THEN
                        V_CDFORNECED := NULL;
                  END;
               ELSE
                  V_CDFORNECED := P_FORNECED;
               END IF;

               SELECT NVL(MAX(X.VRPESOBRUTPR),0),NVL(MAX(VRPECUSTOLOG),0), NVL(MAX(VRVRCUSTOLOG),0),
                      NVL(MAX(VRPESEGURLOG),0)
               INTO V_VRPESOBRUTPR, V_VRPECUSTOLOG,V_VRVRCUSTOLOG,
                    V_VRPESEGURLOG
               FROM PRODUTO P, CUSTOLOGIST C,
                    (SELECT NVL(MAX(A.VRPESOBRUTPR),0) VRPESOBRUTPR,
                           MAX(P.CDARVPROD) CDPRODUTO, MAX(C.DTINIVIGCLOG) DTINIVIGCLOG
                     FROM PRODUTO P, CUSTOLOGIST C, PRODUTO A
                     WHERE
                        (INSTR(A.CDARVPROD,P.CDARVPROD) = 1)         AND
                        A.CDPRODUTO    = C_ITLANCTOEST.CDPRODUTO     AND
                        P.CDPRODUTO    = C.CDPRODUTO                 AND
                        C.CDFILIAL     = C_ITLANCTOEST.CDFILIMOVI    AND
                        C.CDFORNECED   = V_CDFORNECED                AND
                        C.DTINIVIGCLOG = (SELECT MAX(DTINIVIGCLOG)
                                          FROM CUSTOLOGIST A, PRODUTO B, PRODUTO Q
                                          WHERE
                                             A.CDFILIAL     = C.CDFILIAL    AND
                                             A.CDFORNECED   = C.CDFORNECED  AND
                                             (INSTR(B.CDARVPROD,Q.CDARVPROD) = 1)         AND
                                             B.CDPRODUTO    = C_ITLANCTOEST.CDPRODUTO     AND
                                             Q.CDPRODUTO    = A.CDPRODUTO                 AND
                                             A.DTINIVIGCLOG <= P_INIVALID))X
               WHERE C.CDFILIAL     = C_ITLANCTOEST.CDFILIMOVI  AND
                     C.CDPRODUTO    = P.CDPRODUTO               AND
                     C.CDPRODUTO    = X.CDPRODUTO               AND
                     C.CDFORNECED   = V_CDFORNECED              AND
                     C.DTINIVIGCLOG = X.DTINIVIGCLOG;

               V_VRCUSTOLOG := 0;
               V_VRCUSTOSEG := 0;

               IF (V_VRVRCUSTOLOG > 0) AND (V_VRPESOBRUTPR > 0) THEN
                  V_VRCUSTOLOG := (C_ITLANCTOEST.QTITEMPROD*V_VRPESOBRUTPR)*V_VRVRCUSTOLOG;
               END IF;

               IF (V_VRPECUSTOLOG > 0) THEN
                  V_VRCUSTOLOG := (C_ITLANCTOEST.VRTOTAITEM * V_VRPECUSTOLOG)/100;
               END IF;

               IF (V_VRPESEGURLOG > 0) THEN
                  V_VRCUSTOSEG := (C_ITLANCTOEST.VRTOTAITEM * V_VRPESEGURLOG)/100;
               END IF;

               INSERT INTO ITLANCTOEST
                  (CDFILIAL,     NRLANCESTQ, NRSEQUITEM,   CDPRODUTO,    QTTOTLANCTO, VRUNILANCTO,   VRTOTLANCTO,
                   IDTIPOMOVI,   DTLANCMOVI, IDORDEMCLC,   CDPRODMOVI,   QTLANCTOEST, VRLANCTOBRUT,  VRLANCTOEST,
                   VRCUSTENTR,   CDFILIMOVI, CDALMOXARIFE, CDLOCALESTOQ, NRLOTEESTQ,  NRSUBLOTE,     NRLANCORIGRP,
                   VRCUSTLOGLAN, VRSEGULOGLAN, IDORIGEMPROD)
               VALUES
                  (P_FILIAL,       P_LANCESTQ,LPAD(V_NRSEQITPROD,4,'0'),  C_ITLANCTOEST.CDPRODUTO, V_QTDELANCTO,
                   V_VRUNITLANCTO, V_VRTOTALANCTO,  V_TIPOMOVI,   P_INIVALID, W_2, C_ITLANCTOEST.CDPRODESTO,
                   (V_QTDELANCTO * V_FATOCONV), V_TOTABRUT,    V_TOTACONTAB,  V_VRCUSTENTR, V_CDFILIRECE,
                   C_ITLANCTOEST.CDALMOXARIFE,C_ITLANCTOEST.CDLOCALESTOQ,C_ITLANCTOEST.NRLOTEESTQ, C_ITLANCTOEST.NRSUBLOTE,
                   V_IDDOCREPLIC, V_VRCUSTOLOG, V_VRCUSTOSEG, C_ITLANCTOEST.IDORIGEMPROD);

            END IF;
         END LOOP;
      ELSE
         FOR C_ITLANCTOEST IN (SELECT NRSEQITPROD,IP.CDPRODUTO,VRUNITITEM,VRTOTAITEM,
                                      QTITEMPROD,CDPRODESTO,VRBRUTITEM,VRDESCITEM,VRCONTITEM,
                                      NVL(IP.CDALMOXARIFE, ' ') CDALMOXARIFE,
                                      NVL(IP.CDLOCALESTOQ, ' ') CDLOCALESTOQ,
                                      NVL(NRLOTEESTQ, ' ') NRLOTEESTQ,
                                      NVL(NRSUBLOTE, ' ') NRSUBLOTE, CDFILIMOVI,
                                      CDFISOPEITEM, NVL(IDORIGEMPROD, 'N') IDORIGEMPROD
                               FROM ITEMPRODUTO IP, PRODUTO P, PRODFILI PF
                               WHERE IP.CDFILIAL    = P_FILIAL     AND
                                     IP.NRLANCTONF  = P_LANCTONF   AND
                                     P.CDPRODUTO    = IP.CDPRODUTO AND
                                     PF.CDFILIAL    = V_CDFILIRECE AND
                                     PF.CDPRODUTO   = P.CDPRODESTO AND
                                     NVL(IDCNTRESTOQ, W_S) <> W_N) LOOP

            --Alteração para verificar se o CFOP atualiza estoque

            V_ATUPORCFOP := w_S;
            V_CFOPTPOPER := 0;
            V_CFOPATUEST := 0;

            SELECT COUNT(CDFISCOPER)
              INTO V_CFOPTPOPER
              FROM TPOPERCFOP
             WHERE IDENTRSAIDOP = w_E
               AND CDTIPOOPER   = P_TIPOOPER
               AND CDFISCOPER   = C_ITLANCTOEST.CDFISOPEITEM;

            IF(V_CFOPTPOPER > 0) THEN

               SELECT COUNT(CDFISCOPER)
                 INTO V_CFOPATUEST
                 FROM(SELECT CDFISCOPER
                        FROM TPOPERCFOP T
                       WHERE T.IDENTRSAIDOP   = w_E
                         AND T.CDTIPOOPER     = P_TIPOOPER
                         AND T.IDATUESTTPCFOP = w_S
                         AND T.CDFISCOPER     = C_ITLANCTOEST.CDFISOPEITEM
                         AND C_ITLANCTOEST.CDPRODUTO NOT IN (SELECT CDPRODUTO
                                                               FROM TPOPERCFOPEXCP TE
                                                              WHERE TE.IDENTRSAIDOP = w_E
                                                                AND TE.CDTIPOOPER   = P_TIPOOPER
                                                                AND TE.CDFISCOPER   = C_ITLANCTOEST.CDFISOPEITEM
                                                                AND TE.CDPRODUTO    = C_ITLANCTOEST.CDPRODUTO)

                       UNION ALL
                      SELECT CDFISCOPER
                        FROM TPOPERCFOP T
                       WHERE T.IDENTRSAIDOP   = w_E
                         AND T.CDTIPOOPER     = P_TIPOOPER
                         AND T.IDATUESTTPCFOP = w_N
                         AND T.CDFISCOPER     = C_ITLANCTOEST.CDFISOPEITEM
                         AND C_ITLANCTOEST.CDPRODUTO IN (SELECT CDPRODUTO
                                                           FROM TPOPERCFOPEXCP TE
                                                          WHERE TE.IDENTRSAIDOP = w_E
                                                            AND TE.CDTIPOOPER   = P_TIPOOPER
                                                            AND TE.CDFISCOPER   = C_ITLANCTOEST.CDFISOPEITEM
                                                            AND TE.CDPRODUTO    = C_ITLANCTOEST.CDPRODUTO));

               IF NOT (V_CFOPATUEST > 0) THEN
                  V_ATUPORCFOP := w_N;
               END IF;
            END IF;
            --Alteração para verificar se o CFOP atualiza estoque

            IF (V_ATUPORCFOP = w_S) THEN
               IF ((V_CDFILIALSAGA IS NULL) OR ((V_CDFILIALSAGA IS NOT NULL) AND (V_IDATUESTLANCNFE = 'S'))) THEN
                  GERA_EST_DISTRIBUICAO(P_FILIAL, P_LANCTONF, C_ITLANCTOEST.NRSEQITPROD, P_LANCESTQ,
                                        P_TIPOOPER, V_TIPOMOVI, P_INIVALID, C_ITLANCTOEST.CDFILIMOVI,
                                        C_ITLANCTOEST.CDPRODUTO, C_ITLANCTOEST.QTITEMPROD, C_ITLANCTOEST.CDALMOXARIFE, C_ITLANCTOEST.CDLOCALESTOQ,
                                        NULL, NULL, V_RESULT_GERA_EST);
               END IF;
            END IF;

         END LOOP;
      END IF;
   END IF;

   IF P_TIPOOPER = '03' THEN
      V_VRCOMPLEMEN := 0;
      FOR C_ENCARGO IN (SELECT EN.IDENCARGO, SUM(VRITEMENCA) AS VRITEMENCA
                        FROM ITEMENCARGO IE, ENCARGO EN
                        WHERE (IE.CDFILIAL   = P_FILIAL)     AND
                              (IE.NRLANCTONF = P_LANCTONF)   AND
                              (IE.VRITEMENCA > 0)            AND
                              (EN.CDENCARGO  = IE.CDENCARGO) AND
                              (EN.CDCTBLENTREN IS NULL)
                        GROUP BY IDENCARGO) LOOP
         IF C_ENCARGO.IDENCARGO = W_A THEN
            V_VRCOMPLEMEN := V_VRCOMPLEMEN + C_ENCARGO.VRITEMENCA;
         ELSIF C_ENCARGO.IDENCARGO = W_D THEN
            V_VRCOMPLEMEN := V_VRCOMPLEMEN - C_ENCARGO.VRITEMENCA;
         END IF;
      END LOOP;

      IF (V_VRCOMPLEMEN > 0) AND (V_LIQUIDO = 0) THEN
         ATUALIZA_CUSTO_COMPLEMENTO(P_FILIAL, P_LANCTONF, (V_VRCOMPLEMEN - V_VRPRODUTOS));
      END IF;

      IF V_VRNOTAFISC = 0 THEN
         UPDATE NOTAFISCAL
            SET VRNOTAFISC = ROUND(V_TOTALNOTA, 2)
          WHERE CDFILIAL   = P_FILIAL    AND
                NRLANCTONF = P_LANCTONF;
      ELSE
         UPDATE NOTAFISCAL
            SET VRNOTAFISC = ROUND(VRNOTAFISC, 2)
          WHERE CDFILIAL   = P_FILIAL    AND
                NRLANCTONF = P_LANCTONF;
      END IF;

      IF V_VRPRODUTOS = 0 THEN
         UPDATE NOTAFISCAL
         SET VRPRODUTOS = V_VRCOMPLEMEN
         WHERE CDFILIAL   = P_FILIAL    AND
               NRLANCTONF = P_LANCTONF;
      END IF;
   END IF;

   IF V_IDOPERDEVONF = 'S' THEN

      V_TOTALNOTA := ROUND(V_TOTALNOTA, 2);

      UPDATE NOTAFISCAL
         SET VRNOTAFISC = ROUND(VRNOTAFISC, 2)
       WHERE CDFILIAL   = P_FILIAL
         AND NRLANCTONF = P_LANCTONF;
   END IF;

   -- Recalcula diferencial de aliquota considerando valor contabil quando não possuir redução de base de cálculo

   FOR C_TRABITPROIMPOS IN (SELECT NRSEQITPROD, CDIMPOSTO, VRALIQITEM
                              FROM ITEMPROIMPOS
                             WHERE CDFILIAL = P_FILIAL
                               AND NRLANCTONF = P_LANCTONF
                               AND NRITPROIMPOS = '3') LOOP

      V_CDFILIREDU := NULL;

      SELECT MAX(CDFILIAL)
        INTO V_CDFILIREDU
        FROM ITEMPROIMPOS
       WHERE CDFILIAL = P_FILIAL
         AND NRLANCTONF = P_LANCTONF
         AND NRSEQITPROD = C_TRABITPROIMPOS.NRSEQITPROD
         AND CDIMPOSTO = C_TRABITPROIMPOS.CDIMPOSTO
         AND NRITPROIMPOS = '2';

      IF ((V_CDFILIREDU IS NULL) AND (NVL(V_IDORIGDESTNF, 'F') <> 'L')) THEN

         V_VRCONTITIMP := 0;

         SELECT MAX(VRCONTITIMP), MAX(VRIMPOSTOIT), MAX(VRALIQITEM)
           INTO V_VRCONTITIMP, V_IMPOSTOIT, V_ALIQINFO
           FROM ITEMPROIMPOS 
          WHERE CDFILIAL = P_FILIAL 
            AND NRLANCTONF = P_LANCTONF 
            AND NRSEQITPROD = C_TRABITPROIMPOS.NRSEQITPROD
            AND CDIMPOSTO = C_TRABITPROIMPOS.CDIMPOSTO 
            AND NRITPROIMPOS = '1';

         IF (V_IDCALCDIFENTFISC = 'N') THEN

            UPDATE TRABITPROIMPOS
               SET VRCONTIMPOIT  = ROUND(V_VRCONTITIMP, 5),
                   VRBCALCIMPOIT = ROUND(V_VRCONTITIMP, 2),
                   VRIMPOSIT = ROUND((V_VRCONTITIMP * (VRALIQIMPOIT / 100)), V_NRDECITOTANF)
             WHERE CDFILIMPOIT = P_FILIAL
               AND NRLANCIMPOIT = P_LANCTONF
               AND NRSEQIMPOIT = C_TRABITPROIMPOS.NRSEQITPROD
               AND CDIMPOSTOIT = C_TRABITPROIMPOS.CDIMPOSTO
               AND NRSEQITPRO   = '3';

            UPDATE ITEMPROIMPOS
               SET VRCONTITIMP = ROUND(V_VRCONTITIMP, 5),
                   VRBASECALCIT = ROUND(V_VRCONTITIMP, 2),
                   VRIMPOSTOIT = ROUND((V_VRCONTITIMP * (VRALIQITEM / 100)), V_NRDECITOTANF)
             WHERE CDFILIAL = P_FILIAL
               AND NRLANCTONF = P_LANCTONF
               AND NRSEQITPROD = C_TRABITPROIMPOS.NRSEQITPROD
               AND CDIMPOSTO = C_TRABITPROIMPOS.CDIMPOSTO
               AND NRITPROIMPOS = '3';
         ELSE
            V_ALIQDEST     := 0;
            V_ALIQDEST     := V_ALIQINFO + C_TRABITPROIMPOS.VRALIQITEM;
            V_BCALCDIFCOMP := ROUND(((V_VRCONTITIMP - V_IMPOSTOIT) / ((100 - V_ALIQDEST)/100)) , V_NRDECITOTANF);
            V_IMPOSTODIFE  := ROUND(((V_BCALCDIFCOMP * (V_ALIQDEST/100)) - V_IMPOSTOIT), V_NRDECITOTANF);

            UPDATE TRABITPROIMPOS
               SET VRCONTIMPOIT  = ROUND(V_VRCONTITIMP, 5),
                   VRBCALCIMPOIT = ROUND(V_BCALCDIFCOMP, 2),
                   VRIMPOSIT     = V_IMPOSTODIFE
             WHERE CDFILIMPOIT = P_FILIAL
               AND NRLANCIMPOIT = P_LANCTONF
               AND NRSEQIMPOIT = C_TRABITPROIMPOS.NRSEQITPROD
               AND CDIMPOSTOIT = C_TRABITPROIMPOS.CDIMPOSTO
               AND NRSEQITPRO   = '3';

             UPDATE ITEMPROIMPOS
               SET VRCONTITIMP  = ROUND(V_VRCONTITIMP, 5),
                   VRBASECALCIT = ROUND(V_BCALCDIFCOMP, 2),
                   VRIMPOSTOIT  = V_IMPOSTODIFE
             WHERE CDFILIAL = P_FILIAL
               AND NRLANCTONF = P_LANCTONF
               AND NRSEQITPROD = C_TRABITPROIMPOS.NRSEQITPROD
               AND CDIMPOSTO = C_TRABITPROIMPOS.CDIMPOSTO
               AND NRITPROIMPOS = '3';
         END IF;
      END IF;
         
      IF ((V_CDFILIREDU IS NULL) AND (NVL(V_IDORIGDESTNF, 'F') = 'L')) THEN

         V_VRCONTITIMP := 0;

         SELECT MAX(VRCONTITIMP)
           INTO V_VRCONTITIMP
           FROM ITEMPROIMPOS
          WHERE CDFILIAL = P_FILIAL
            AND NRLANCTONF = P_LANCTONF
            AND NRSEQITPROD = C_TRABITPROIMPOS.NRSEQITPROD
            AND CDIMPOSTO = C_TRABITPROIMPOS.CDIMPOSTO
            AND NRITPROIMPOS = '1';

         UPDATE TRABITPROIMPOS
            SET VRCONTIMPOIT = V_VRCONTITIMP
          WHERE CDFILIMPOIT = P_FILIAL
            AND NRLANCIMPOIT = P_LANCTONF
            AND NRSEQIMPOIT = C_TRABITPROIMPOS.NRSEQITPROD
            AND CDIMPOSTOIT = C_TRABITPROIMPOS.CDIMPOSTO
            AND NRSEQITPRO   = '3';

         UPDATE ITEMPROIMPOS
            SET VRCONTITIMP = V_VRCONTITIMP
          WHERE CDFILIAL = P_FILIAL
            AND NRLANCTONF = P_LANCTONF
            AND NRSEQITPROD = C_TRABITPROIMPOS.NRSEQITPROD
            AND CDIMPOSTO = C_TRABITPROIMPOS.CDIMPOSTO
            AND NRITPROIMPOS = '3';

      END IF;
   END LOOP;

   FOR C_TRABITPROIMPOS IN (SELECT CDIMPOSTO, VRALIQITEM, VRPERREDBCIT, VRPARDEDIT,
                                   CDFISCALIT, CDSITUTRIBIT, CDFISCOPERIT, CDSUFXCFOPIT,
                                   IDDIFALIQCUSPRI,
                                   SUM(VRCONTITIMP) AS VRCONTITIMP,
                                   SUM(VRBASECALCIT) AS VRBASECALCIT,
                                   SUM(VRIMPOSTOIT) AS VRIMPOSTOIT
                              FROM ITEMPROIMPOS
                             WHERE CDFILIAL = P_FILIAL
                               AND NRLANCTONF = P_LANCTONF
                               AND NRITPROIMPOS = '3'
                             GROUP BY CDIMPOSTO, VRALIQITEM, VRPERREDBCIT, VRPARDEDIT,
                                      CDFISCALIT, CDSITUTRIBIT, CDFISCOPERIT, CDSUFXCFOPIT,
                                      IDDIFALIQCUSPRI) LOOP

      UPDATE IMPOSTONF
         SET VRCONTABILNF = C_TRABITPROIMPOS.VRCONTITIMP,
             VRBASECALCNF = C_TRABITPROIMPOS.VRBASECALCIT,
             VRIMPOSTONF  = C_TRABITPROIMPOS.VRIMPOSTOIT
       WHERE CDFILIAL = P_FILIAL
         AND NRLANCTONF = P_LANCTONF
         AND CDIMPOSTO = C_TRABITPROIMPOS.CDIMPOSTO
         AND IDIMPOSTONF = '3'
         AND VRALIQNF = C_TRABITPROIMPOS.VRALIQITEM
         AND VRPERREDBCNF = C_TRABITPROIMPOS.VRPERREDBCIT
         AND VRPARDEDNF = C_TRABITPROIMPOS.VRPARDEDIT
         AND CDFISCALNF = C_TRABITPROIMPOS.CDFISCALIT
         AND CDSITUTRIBNF = C_TRABITPROIMPOS.CDSITUTRIBIT
         AND CDFISCOPERNF = C_TRABITPROIMPOS.CDFISCOPERIT
         AND NVL(IDDIFALIQCUSPRN, 'N') = NVL(C_TRABITPROIMPOS.IDDIFALIQCUSPRI, 'N')
         AND NVL(CDSUFXCFOPNF, 'N') = NVL(C_TRABITPROIMPOS.CDSUFXCFOPIT, 'N');
   END LOOP;

   -- Atualiza custo do produto em estoque caso o diferencial compoem o custo do produto
   FOR C_ITLANCTOEST IN (SELECT NRSEQITPROD, VRBRUTITEM, P.VRFATOCONV, QTITEMPROD, VRCONTITEM
                         FROM ITEMPRODUTO IP, PRODUTO P, PRODFILI PF
                         WHERE IP.CDFILIAL    = P_FILIAL     AND
                               IP.NRLANCTONF  = P_LANCTONF   AND
                               P.CDPRODUTO    = IP.CDPRODUTO AND
                               PF.CDFILIAL    = V_CDFILIRECE AND
                               PF.CDPRODUTO   = P.CDPRODESTO) LOOP

      V_VRIMPDIFALIQ := 0;

      SELECT NVL(SUM(VRIMPOSTOIT), 0)
        INTO V_VRIMPDIFALIQ
        FROM ITEMPROIMPOS
       WHERE CDFILIAL = P_FILIAL
         AND NRLANCTONF = P_LANCTONF
         AND NRSEQITPROD = C_ITLANCTOEST.NRSEQITPROD
         AND IDDIFALIQCUSPRI = 'S';

      IF V_VRIMPDIFALIQ > 0 THEN

         UPDATE ITEMPRODUTO
            SET VRCONTITEM   = VRCONTITEM + V_VRIMPDIFALIQ
          WHERE (CDFILIAL    = P_FILIAL)    AND
                (NRLANCTONF  = P_LANCTONF ) AND
                (NRSEQITPROD = C_ITLANCTOEST.NRSEQITPROD);

         IF (P_TIPOOPER = '06') THEN
            UPDATE ITLANCTOEST
               SET VRLANCTOBRUT = (V_VRIMPDIFALIQ / C_ITLANCTOEST.QTITEMPROD) / C_ITLANCTOEST.VRFATOCONV,
                   VRLANCTOEST = (V_VRIMPDIFALIQ / C_ITLANCTOEST.QTITEMPROD) / C_ITLANCTOEST.VRFATOCONV,
                   VRCUSTENTR = VRCUSTENTR + V_VRIMPDIFALIQ
             WHERE CDFILIAL = P_FILIAL
               AND NRLANCESTQ = P_LANCESTQ
               AND NRSEQUITEM = C_ITLANCTOEST.NRSEQITPROD;
         ELSE
            UPDATE ITLANCTOEST
               SET VRLANCTOBRUT = ((C_ITLANCTOEST.VRBRUTITEM + V_VRIMPDIFALIQ) / C_ITLANCTOEST.QTITEMPROD) / C_ITLANCTOEST.VRFATOCONV,
                   VRLANCTOEST = ((C_ITLANCTOEST.VRCONTITEM + V_VRIMPDIFALIQ) / C_ITLANCTOEST.QTITEMPROD) / C_ITLANCTOEST.VRFATOCONV,
                   VRCUSTENTR = VRCUSTENTR + V_VRIMPDIFALIQ
             WHERE CDFILIAL = P_FILIAL
               AND NRLANCESTQ = P_LANCESTQ
               AND NRSEQUITEM = C_ITLANCTOEST.NRSEQITPROD;
         END IF;
      END IF;
   END LOOP;

   DELETE FROM REGRANOTA
    WHERE CDFILIAL = P_FILIAL
      AND NRLANCTONF = P_LANCTONF;

   FOR C_IMPOSNOTA IN (SELECT DISTINCT CDREGRAIT
                         FROM ITEMPROIMPOS
                        WHERE CDFILIAL = P_FILIAL
                          AND NRLANCTONF = P_LANCTONF
                          AND CDREGRAIT IS NOT NULL
                        ORDER BY CDREGRAIT)
   LOOP

      FOR C_REGRAMSG IN (SELECT CDREGRAFISC, DSMENSREGRAFISC
                           FROM TABLE(MSG_REGRAFISCAL(C_IMPOSNOTA.CDREGRAIT, P_EMPRESA, 'E', P_TIPOOPER, P_INSCESTA)) M
                          WHERE NOT EXISTS(SELECT DSDADOADIC
                                             FROM DADOSADIC
                                            WHERE (CDFILIAL   = P_FILIAL)   AND
                                                  (NRLANCTONF = P_LANCTONF) AND
                                                  (DSDADOADIC = M.DSMENSREGRAFISC))) LOOP

          INSERT INTO DADOSADIC(CDFILIAL, NRLANCTONF, NRDADOADIC, DSDADOADIC)
                         VALUES(P_FILIAL, P_LANCTONF, V_DADOADIC, C_REGRAMSG.DSMENSREGRAFISC);

          V_DADOADIC := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_DADOADIC) + 1)),3,0);
      END LOOP;

      INSERT INTO REGRANOTA(CDFILIAL, NRLANCTONF, CDREGRAFISC)
                         VALUES(P_FILIAL, P_LANCTONF, C_IMPOSNOTA.CDREGRAIT);
   END LOOP;

   IF (V_IDCALCVRTOTANFE = 'S') THEN
      UPDATE NOTAFISCAL
         SET VRNOTAFISC = NVL(V_TOTALNOTA,0)
       WHERE CDFILIAL   = P_FILIAL
         AND NRLANCTONF = P_LANCTONF;
      IF (V_IDUTILVENC = 'S') THEN
         SELECT COUNT(*)
           INTO V_POSSUIFINANC
           FROM CONTAPAGAR
          WHERE CDFILIAL   = P_FILIAL
            AND NRLANCTONF = P_LANCTONF;

         IF NOT(V_POSSUIFINANC > 0) THEN
            GERA_DADOS_FINANCEIRO(P_FILIAL, P_LANCTONF, P_FILIAL, 'L', P_RESULTADO);
         END IF;
      END IF;
   END IF;   

   /*Chamar a procedure para gerar financeiro. */
   IF (V_IDNFRETIND = 'S') OR (V_IDSTATUS = 'I') THEN
      V_POSSUIFINANC := 0;

      IF (V_IDUTILVENC = 'S') THEN
         SELECT COUNT(*)
           INTO V_POSSUIFINANC
           FROM CONTAPAGAR
          WHERE CDFILIAL   = P_FILIAL
            AND NRLANCTONF = P_LANCTONF;

         IF NOT(V_POSSUIFINANC > 0) THEN
            GERA_DADOS_FINANCEIRO(P_FILIAL, P_LANCTONF, P_FILIAL, 'L', P_RESULTADO);
         END IF;
      END IF;
   END IF;

   DELETE
     FROM INFOPAGANFE
    WHERE CDFILIAL = P_FILIAL
      AND NRLANCTONF = P_LANCTONF;

   IF (NVL(P_AUDIT, 'N') <> 'S') THEN
      CONFERE_ERROS_NF(P_FILIAL, P_LANCTONF, V_TOTALNOTA);
   END IF;

   IF P_TIPOOPER = '01' THEN
      CONHECIMENTO_TRANSPORTE(P_FILIAL, P_LANCTONF, P_LANCESTQ);
   END IF;

   UPDATE TRABITPROIMPOS
      SET CDFISCIMPOIT = '2',
          VRBCALCIMPOIT = 0
    WHERE CDFILIMPOIT = P_FILIAL
      AND NRLANCIMPOIT = P_LANCTONF
      AND VRREDBCIMPOIT > 0.00
      AND NRSEQITPRO = '2';

   FOR C_CARGA IN (SELECT DISTINCT CDIMPOSTO
                     FROM IMPOSTONF
                    WHERE CDFILIAL = P_FILIAL
                      AND NRLANCTONF = P_LANCTONF) LOOP

      V_CARGA := VALOR_CARGA_TRIBUTARIA(C_CARGA.CDIMPOSTO, P_FILIAL, P_LANCTONF);
      IF V_CARGA > 0 THEN
         UPDATE IMPOSTONF
            SET VRIMPCARGATRIBI = V_CARGA
           WHERE CDFILIAL = P_FILIAL
             AND NRLANCTONF = P_LANCTONF
             AND CDIMPOSTO = C_CARGA.CDIMPOSTO
             AND NRIMPOSNF = (SELECT MAX(NRIMPOSNF)
                                      FROM IMPOSTONF
                                     WHERE CDFILIAL = P_FILIAL
                                       AND NRLANCTONF = P_LANCTONF
                                       AND CDIMPOSTO = C_CARGA.CDIMPOSTO);

      END IF;
   END LOOP;

   DELETE ALIQTEMP
   WHERE  NRALIQTEMP = P_FILIAL||P_LANCTONF;

   /* Rotina para geração de saída no estoque (filial agente de terceirização) */
   IF (NVL(P_AUDIT, 'N') <> 'S') THEN
      BEGIN
         SELECT MAX(CDFORNAGETERC)
           INTO V_CDFORNAGETERC
           FROM ITEMNOTAFISC I, NOTAFISCAL N, FILIAL F
          WHERE I.CDFILIALIT   = P_FILIAL
            AND I.NRLANCTONFIT = P_LANCTONF
            AND N.CDFILIAL     = I.CDFILIAL
            AND N.NRLANCTONF   = I.NRLANCTONF
            AND F.CDFILIAL     = N.CDFILIEMIT;
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_CDFORNAGETERC := NULL;
      END;

      IF (V_CDFORNAGETERC IS NULL) AND (V_IDORIGDESTNF = 'F') THEN

         BEGIN
            SELECT CDFILIAL, CDFILIOLAGETERC
              INTO V_CDFILIAGENT, V_CDFILIOLAGETERC
              FROM FILIAL
             WHERE CDFORNAGETERC = P_FORNECED;
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_CDFILIAGENT := NULL; V_CDFILIOLAGETERC := NULL;
         END;

         IF NOT V_CDFILIAGENT IS NULL THEN

            BEGIN
               SELECT CDEMPRESA, CDINSCESTA, CDINSCMUNI
                 INTO V_CDEMPRESAAG, V_CDINSCESTAAG, V_CDINSCMUNIAG
                 FROM FILIAL
                WHERE CDFILIAL  = V_CDFILIAGENT;
            EXCEPTION
               WHEN NO_DATA_FOUND THEN
                  V_CDEMPRESAAG  := NULL;
                  V_CDINSCESTAAG := NULL;
                  V_CDINSCMUNIAG := NULL;
            END;

            IF (V_IDCTRLESTQ = 'S') THEN
               FOR C_ITLANCTOEST IN (SELECT IP.NRSEQITPROD, IP.VRBRUTITEM, IP.QTITEMPROD, IP.CDPRODUTO,
                                            IP.VRCONTITEM, IP.VRUNITITEM, IP.VRTOTAITEM, P.CDARVPROD,
                                            P.NMPRODUTO, IP.VRDESCITEM, P.CDPRODESTO, NVL(P.VRFATOCONV, 1) AS VRFATOCONV,
                                            NVL(IDORIGEMPROD, 'N') IDORIGEMPROD
                                       FROM ITEMPRODUTO IP, PRODUTO P, PRODFILI PF
                                      WHERE IP.CDFILIAL    = P_FILIAL
                                        AND IP.NRLANCTONF  = P_LANCTONF
                                        AND P.CDPRODUTO    = IP.CDPRODUTO
                                        AND PF.CDFILIAL    = V_CDFILIRECE
                                        AND PF.CDPRODUTO   = P.CDPRODESTO
                                        AND NVL(PF.IDCNTRESTOQ, W_S) <> W_N) LOOP

                  BEGIN
                     SELECT NVL(NVL(P.CDALMOXARIFE, F.CDALMOXARIFE), ' ') AS CDALMOXARIFE, NVL(NVL(P.CDLOCALESTOQ, F.CDLOCALESTOQ), ' ') AS CDLOCALESTOQ,
                            NVL(F.IDUTILLOTE, 'N') AS IDUTILLOTE
                       INTO V_CDALMOXARIFEAG, V_CDLOCALESTOQAG, V_IDUTILLOTEAG
                       FROM PARAMFILIAL F, PRODFILI P
                      WHERE F.CDFILIAL  = V_CDFILIAGENT
                        AND P.CDFILIAL  = V_CDFILIAGENT
                        AND P.CDPRODUTO = C_ITLANCTOEST.CDPRODESTO;
                  EXCEPTION
                     WHEN NO_DATA_FOUND THEN
                        V_CDALMOXARIFEAG := ' ';
                        V_CDLOCALESTOQAG := ' ';
                        V_IDUTILLOTEAG   := 'N';
                  END;

                  IF V_IDUTILLOTEAG = 'S' THEN
                     IF (V_NRLOTEESTQAG IS NULL) OR (V_NRLOTEESTQAG = ' ') THEN
                        PRXLOTEPRODEST(V_CDFILIAGENT, P_INIVALID, C_ITLANCTOEST.CDPRODESTO, V_NRLOTEESTQAG);
                        V_NRSUBLOTEAG := ' ';
                     END IF;
                  ELSE
                     V_NRLOTEESTQAG := ' ';
                     V_NRSUBLOTEAG  := ' ';
                  END IF;

                  IF V_BOLANESTSAIDAG THEN
                     /* Gerando o registro na tabela LANCTOESTOQ para a entrada na filial relacionada ao agente de terceirização */
                     NOVO_CODIGO_NT('LANCNF/FILIAL' || V_CDFILIAGENT, V_NRLANCTONFAG);
                     V_NRLANCTONFAG := SUBSTR(V_NRLANCTONFAG, 11, 10);

                     NOVO_CODIGO_NT('LANCTOEST'||V_CDFILIAGENT, V_NRLANESTENTRAG);
                     V_NRLANESTENTRAG := SUBSTR(V_NRLANESTENTRAG, 11, 10);

                     V_TPOPERREMESSA := NULL;
                     BEGIN
                        SELECT CDTPOOPREMESSA
                          INTO V_TPOPERREMESSA
                          FROM PARAMGERAL
                         WHERE CDPARGERAL = '0001';
                     EXCEPTION
                     WHEN NO_DATA_FOUND THEN
                        V_TPOPERREMESSA := NULL;
                     END;

                     IF (V_TPOPERREMESSA IS NULL) THEN
                        RAISE_APPLICATION_ERROR(-20501, 'Tipo de operação para geração de lançamento de estoque deve ser informado - (Parâmetros para Documentos Fiscais de Saída - Operador Logístico)', TRUE);
                     END IF;

                     INSERT INTO NOTAFISCAL
                        (CDFILIAL, CDEMPRESA, CDINSCESTA, CDINSCMUNI, NRLANCTONF, NRINSJURNF,
                         IDTPIJURNF, DTEMISSAO, NRNOTAFISC, CDSERIE, IDBLOQUEADO, IDDOCFISCAL,
                         IDDOCFINANC, VRPRODUTOS, VRNOTAFISC, IDENTRSAIDOP, CDTIPOOPER, CDCLIENTE,
                         DTENTRSAID, CDFILIEMIT, IDORIGDESTNF, CDFORNECED, CDFILIRECE, NRAPURACFAT)

                     VALUES
                        (V_CDFILIAGENT, V_CDEMPRESAAG, V_CDINSCESTAAG, V_CDINSCMUNIAG, V_NRLANCTONFAG, V_NRINSJURNF,
                         V_IDTPIJURNF, P_INIVALID, NULL, NULL, 'N', 'N',
                         'S', V_VRPRODUTOS, V_VRNOTAFISC, 'S', V_TPOPERREMESSA, P_FORNECED,
                         P_INIVALID, V_CDFILIAGENT, 'C', NULL, NULL, NULL);

                     INSERT INTO ITEMNOTAFISC
                        (CDFILIAL, NRLANCTONF, NRSEQUITNOTA, CDFILIALIT, NRLANCTONFIT)
                     VALUES
                        (V_CDFILIAGENT, V_NRLANCTONFAG, '001', P_FILIAL, P_LANCTONF);

                     INSERT INTO LANCTOESTOQ
                        (CDFILIAL, CDFILIMOVI, NRLANCESTQ, IDTPLANCTO,
                         DTLANCESTQ, DSLANCESTQ,
                         NRLANCTONF, CDOPERADOR, CDALMOXARIFE, CDLOCALESTOQ)
                     VALUES
                        (V_CDFILIAGENT, V_CDFILIAGENT, V_NRLANESTENTRAG, '4',
                         P_INIVALID, 'NF Retorno Armazenagem - lanç. ' || V_CDFILIRECE || ' ' || P_LANCTONF,
                         V_NRLANCTONFAG, P_CDOPERADOR, NULL, NULL);

                     V_BOLANESTSAIDAG := FALSE;
                  END IF;

                  INSERT INTO ITEMPRODUTO
                     (CDFILIAL, NRLANCTONF, NRSEQITPROD, CDPRODUTO,
                      CDPRODEMIS, DSPRODEMIS, IDATUVRESTOQ, QTITEMPROD,
                      VRUNITITEM, VRDESCITEM, VRTOTAITEM, VRCONTITEM,
                      VRBRUTITEM, IDCONFORITEM, CDFILIMOVI,
                      CDALMOXARIFE, CDLOCALESTOQ, NRLOTEESTQ, NRSUBLOTE, CDPRODMOVI)
                  VALUES
                     (V_CDFILIAGENT, V_NRLANCTONFAG, C_ITLANCTOEST.NRSEQITPROD, C_ITLANCTOEST.CDPRODUTO,
                      C_ITLANCTOEST.CDARVPROD, C_ITLANCTOEST.NMPRODUTO, 'S', C_ITLANCTOEST.QTITEMPROD,
                      C_ITLANCTOEST.VRUNITITEM, C_ITLANCTOEST.VRDESCITEM, C_ITLANCTOEST.VRTOTAITEM, C_ITLANCTOEST.VRCONTITEM,
                      C_ITLANCTOEST.VRBRUTITEM, 'S', V_CDFILIAGENT,
                      V_CDALMOXARIFEAG, V_CDLOCALESTOQAG, V_NRLOTEESTQAG, V_NRSUBLOTEAG,
                      C_ITLANCTOEST.CDPRODESTO);

                  INSERT INTO ITLANCTOEST
                     (CDFILIAL, NRLANCESTQ, NRSEQUITEM, CDPRODUTO,
                      CDPRODMOVI, VRUNILANCTO, VRTOTLANCTO, QTTOTLANCTO,
                      QTLANCTOEST, IDTIPOMOVI, DTLANCMOVI, IDORDEMCLC,
                      VRLANCTOBRUT, VRLANCTOEST, CDFILIMOVI, CDALMOXARIFE,
                      CDLOCALESTOQ, NRLOTEESTQ, NRSUBLOTE, IDORIGEMPROD)
                  VALUES
                     (V_CDFILIAGENT, V_NRLANESTENTRAG, C_ITLANCTOEST.NRSEQITPROD, C_ITLANCTOEST.CDPRODUTO,
                       C_ITLANCTOEST.CDPRODESTO, C_ITLANCTOEST.VRUNITITEM, C_ITLANCTOEST.VRTOTAITEM, C_ITLANCTOEST.QTITEMPROD,
                      C_ITLANCTOEST.QTITEMPROD * C_ITLANCTOEST.VRFATOCONV, '4', P_INIVALID, '9',
                      C_ITLANCTOEST.VRBRUTITEM, C_ITLANCTOEST.VRTOTAITEM, V_CDFILIAGENT, V_CDALMOXARIFEAG,
                      V_CDLOCALESTOQAG, V_NRLOTEESTQAG, V_NRSUBLOTEAG, C_ITLANCTOEST.IDORIGEMPROD);
               END LOOP;
            END IF;  
            -- se possuir agente de terceirização e filial OL será efetuada alteração no pedido OL e na reserva do pedido
            IF NOT V_CDFILIOLAGETERC IS NULL THEN

               FOR C_INTG_ITENS IN (SELECT I.NRAUTOFORN, P.CDPRODUTO, SUM(I.QTITEMPROD) AS QTITEMPROD
                                      FROM INTG_NOTAFISCAL N, INTG_ITEMPRODUTO I, PRODFORNXML P
                                     WHERE N.NRACESSONFE = V_NRACESSONFE
                                       AND I.NRACESSONFE = N.NRACESSONFE
                                       AND P.CDFORNECED   = N.CDFORNECED
                                       AND P.CDPRODUTOXML = I.CDPRODUTO
                                     GROUP BY I.NRAUTOFORN, P.CDPRODUTO)
               LOOP
                  FOR C_ITEM_PED IN (SELECT IT.CDFILDEST, IT.CDFILLANC, IT.NRPEDEXOL, IT.CDMARCA, IT.CDPRODUTO, IT.DTPROGENPEOL
                                       FROM PEDIDOEXOL P, ITEMPEDEXOL IT, RELACPRODOL R
                                      WHERE P.USR_NRPEDIDO = C_INTG_ITENS.NRAUTOFORN
                                        AND IT.CDFILDEST = P.CDFILDEST
                                        AND IT.CDFILLANC = P.CDFILLANC
                                        AND IT.NRPEDEXOL = P.NRPEDEXOL
                                        AND IT.IDBAIXENPEOL IS NULL
                                        AND R.CDPRARVORIG = C_INTG_ITENS.CDPRODUTO
                                        AND IT.CDPRODUTO  = R.CDPRARVORIG
                                        AND IT.CDMARCA    = R.CDMARCA
                                      ORDER BY IT.CDPRODUTO, IT.DTPROGENPEOL)
                  LOOP
                     -- altera a qtde atendida do pedido OL com a qtde. da nota fiscal somente para a primeira data de entrega
                     UPDATE ITEMPEDEXOL
                        SET QTATENDPEDOL = C_INTG_ITENS.QTITEMPROD
                      WHERE CDFILDEST    = C_ITEM_PED.CDFILDEST
                        AND CDFILLANC    = C_ITEM_PED.CDFILLANC
                        AND NRPEDEXOL    = C_ITEM_PED.NRPEDEXOL
                        AND CDMARCA      = C_ITEM_PED.CDMARCA
                        AND CDPRODUTO    = C_ITEM_PED.CDPRODUTO
                        AND DTPROGENPEOL = C_ITEM_PED.DTPROGENPEOL;

                     -- altera a qtde reservada do pedido OL e a filial da reserva do pedido para a filial OL
                     UPDATE RESERVAPEDEXOL
                        SET CDFILRESOL    = V_CDFILIOLAGETERC,
                            QTRESERVESTOL = C_INTG_ITENS.QTITEMPROD,
                            CDFILIAL      = P_FILIAL,
                            NRLANCTONF    = P_LANCTONF
                      WHERE CDFILDEST    = C_ITEM_PED.CDFILDEST
                        AND CDFILLANC    = C_ITEM_PED.CDFILLANC
                        AND NRPEDEXOL    = C_ITEM_PED.NRPEDEXOL
                        AND CDMARCA      = C_ITEM_PED.CDMARCA
                        AND CDPRODUTO    = C_ITEM_PED.CDPRODUTO
                        AND DTPROGENPEOL = C_ITEM_PED.DTPROGENPEOL;

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

         -- Atualiza valor contábil do produto considerando o custo médio do produto em estoque caso o parâmetro esteja marcado
         IF (V_IDOPERDEVONF = W_S AND V_IDUTCUSORIGEST = W_S) THEN
            FOR C_ITLANCTOEST IN (SELECT CDFILIMOVI, NRSEQITPROD,IP.CDPRODUTO,VRUNITITEM,VRTOTAITEM,
                                         QTITEMPROD,CDPRODESTO,VRBRUTITEM,VRDESCITEM,VRCONTITEM,
                                         NVL(IP.CDALMOXARIFE, ' ') CDALMOXARIFE,
                                         NVL(IP.CDLOCALESTOQ, ' ') CDLOCALESTOQ,
                                         NVL(NRLOTEESTQ, ' ') NRLOTEESTQ,
                                         NVL(NRSUBLOTE, ' ') NRSUBLOTE,
                                         P.VRFATOCONV
                                   FROM ITEMPRODUTO IP, PRODUTO P
                                  WHERE IP.CDFILIAL    = P_FILIAL     AND
                                        IP.NRLANCTONF  = P_LANCTONF   AND
                                        P.CDPRODUTO    = IP.CDPRODUTO) LOOP


               V_VRCUSTENTR := ROUND(CUSTO_PRODUTO_LCEST(C_ITLANCTOEST.CDFILIMOVI, C_ITLANCTOEST.CDPRODESTO, V_CDTIPCUSTEST, P_INIVALID,
                                                         V_DTATUAL, C_ITLANCTOEST.CDALMOXARIFE, C_ITLANCTOEST.CDLOCALESTOQ,
                                                         C_ITLANCTOEST.NRLOTEESTQ, C_ITLANCTOEST.NRSUBLOTE), 5);

               UPDATE ITEMPRODUTO
                  SET VRCONTITEM = ((C_ITLANCTOEST.QTITEMPROD * C_ITLANCTOEST.VRFATOCONV) * V_VRCUSTENTR)
                WHERE CDFILIAL =  P_FILIAL
                  AND NRLANCTONF = P_LANCTONF
                  AND NRSEQITPROD = C_ITLANCTOEST.NRSEQITPROD;
            END LOOP;
         END IF;
      END IF;
   END IF;

---------------------------------------------------------------------------------------------------------
END;