CREATE OR REPLACE PROCEDURE IMPOSTO_SAIDA(
   P_EMPRESA    IN ALIQUOTA.CDEMPRESA%TYPE,
   P_INSCESTA   IN ALIQUOTA.CDINSCESTA%TYPE,
   P_TIPOOPER   IN INCIDENCIA.CDTIPOOPER%TYPE,
   P_CLIENTE    IN CLIENTE.CDCLIENTE%TYPE,
   P_FILIAL     IN NOTAFISCAL.CDFILIAL%TYPE,
   P_LANCTONF   IN NOTAFISCAL.NRLANCTONF%TYPE,
   P_INIVALID   IN ALIQUOTA.DTINIVALID%TYPE,
   P_VRNOTAFISC OUT NUMBER,
   P_LANCESTQ   IN LANCTOESTOQ.NRLANCESTQ%TYPE DEFAULT NULL,
   P_CDOPERADOR IN LANCTOESTOQ.CDOPERADOR%TYPE DEFAULT NULL)
IS
   V_TESTE          NUMBER;
   V_IDTRATIMPO     VARCHAR2(01);
   V_PAISORIG       VARCHAR2(04); -- Pais de origem (utiliza UF de Origem)
   V_ESTAORIG       VARCHAR2(02); -- Estado de origem (utiliza UF de Origem)
   V_MUNIORIG       VARCHAR2(04); -- Municipio de origem (utiliza municipio)
   V_PAISDEST       VARCHAR2(04);
   V_ESTADEST       VARCHAR2(02);
   V_MUNIDEST       VARCHAR2(04);
   V_IDUTMUNIORIG   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_NRALIQTEMP     VARCHAR2(14);
   V_DADOADIC       VARCHAR2(03);
   V_DADOADICFISCO  VARCHAR2(03);
   V_INCITEMP       VARCHAR2(14);
   V_CST1DIGT       VARCHAR2(1);
   V_CSTTEMP        VARCHAR2(14);
   V_FISCALIT       VARCHAR2(20);
   V_CFOPTEMP       VARCHAR2(14);
   V_FISOPEITEM     VARCHAR2(11);
   V_SUFXCFOPPR     VARCHAR2(03);
   V_SITUTRIBPR     VARCHAR2(03);
   V_NRINSJURNF     VARCHAR2(20);
   V_SERIE          VARCHAR2(05);
   V_TIPOMOVI       VARCHAR2(01);
   V_CDFISCOPER     VARCHAR2(11);
   V_CDFILIEMIT     VARCHAR2(04);
   V_CDFILIRECE     VARCHAR2(04);
   V_ORIGDESTOP     VARCHAR2(01);
   V_CDFISOPENTF    VARCHAR2(11);
   V_IDENDCFOP      VARCHAR2(01);
   V_IDENDEMIS      VARCHAR2(01);
   V_CDEMPRESA      VARCHAR2(02);
   V_CDINSCESTA     VARCHAR2(16);
   V_CDINTEGRACAO   VARCHAR2(16);
   V_IDORIGDESTNF   VARCHAR2(01);
   V_NRLANBOLREC    VARCHAR2(10);
   V_IDDOCFINANC    VARCHAR2(01);
   V_IDERROAVISO    VARCHAR2(01);
   V_IDDOCREPLIC    VARCHAR2(14);
   V_IDDOCESTOQ     VARCHAR2(14);
   V_IDSISTEMA      VARCHAR2(03);
   V_IDRETPROEXP    VARCHAR2(01);
   V_IDATUEST       VARCHAR2(01);
   V_NMTIPOOPER     VARCHAR2(30);
   V_NMFILIRECE     VARCHAR2(60);
   V_DESCLANC       VARCHAR2(60);
   V_CDFISCTEMP     VARCHAR2(01);
   V_CDDETALHEPRODTEMP VARCHAR2(05);
   V_TRATIMPST      VARCHAR2(01);
   V_IDTRIMPSTII    VARCHAR2(01);
   V_CDIMPOSTRIB    VARCHAR2(250);
   V_CDIMPOSICMS    VARCHAR2(250);
   V_IDCTRLESTQ     VARCHAR2(01);
   V_CDFILIAPFATU   VARCHAR2(04);
   V_NRAPFATUTNF    VARCHAR2(10);
   V_IDITEMISSAO    VARCHAR2(01);
   V_CDIMPOBCALC    VARCHAR2(02);
   V_IDIMPOSTONF    VARCHAR2(01);
   V_IDVRIMPSTRIB   VARCHAR2(01);
   V_IDDEVOLIST     VARCHAR2(01);
   V_IDUTILALMOX    VARCHAR2(01);
   V_IDUTILLCESTQ   VARCHAR2(01);
   V_IDUTILLOTE     VARCHAR2(01);
   V_IDPMCBASECAL   VARCHAR2(01);
   V_IDTPCOMPPROD   VARCHAR2(01);
   V_NRINSJURCLIE   VARCHAR2(20);
   V_UTIBB          VARCHAR2(01);
   V_IDNTRANSCREICMS VARCHAR2(01);
   V_CDSITTRIBTMP    CODSITUTRIBNFE.CDSITUTRIBNFE%TYPE;
   V_IDMODBCNFE      CODSITUTRIBNFE.IDMODBCNFE%TYPE;
   V_IDMOTIDESSTNFE  CODSITUTRIBNFE.IDMOTIDESSTNFE%TYPE;
   V_IDMODBCSTNFE    CODSITUTRIBNFE.IDMODBCSTNFE%TYPE;
   V_CDTPCRPICOSTNFE CODSITUTRIBNFE.CDTPCRPICOSTNFE%TYPE;
   V_CDNATUBCPCSTNFE CODSITUTRIBNFE.CDNATUBCPCSTNFE%TYPE;
   V_CDSITUTRIBNFE     CODSITUTRIBNFE.CDSITUTRIBNFE%TYPE;
   V_IDMODBCNFEIT      CODSITUTRIBNFE.IDMODBCNFE%TYPE;
   V_IDMODBCSTNFEIT    CODSITUTRIBNFE.IDMODBCSTNFE%TYPE;
   V_CDTPCRPICOSTNFEIT CODSITUTRIBNFE.CDTPCRPICOSTNFE%TYPE;
   V_CDNATUBCPCSTNFEIT CODSITUTRIBNFE.CDNATUBCPCSTNFE%TYPE;
   V_IDINTEREST   VARCHAR2(01);
   V_IDCONSPARFIS VARCHAR2(01);
   V_CDFISCOPERSN ITEMPRODUTO.CDFISCOPERSN%TYPE;
   V_IDINTERNA VARCHAR2(01);
   V_PARDEDTMP    NUMBER;
   V_PREDBCTMP    NUMBER;
   V_PREDBCSTIT   NUMBER;
   V_ALIQUTMP     NUMBER;
   V_VRIMPOSTOREP NUMBER;
   V_COUNT        NUMBER;
   V_ERROAVISO    NUMBER;
   V_LIQUIITEM    NUMBER;
   V_TOTALNOTA    NUMBER;
   V_LIQUIDO      NUMBER;
   V_SOMAENCA     NUMBER;
   V_MENOENCA     NUMBER;
   V_SOMAIMPO     NUMBER;
   V_MENOIMPO     NUMBER;
   V_TOTAPRODENCA NUMBER;
   V_TOTAPRENIMPO NUMBER;
   V_TOTAIMPBCALC NUMBER;
   V_TOTAIMPBCDES NUMBER;
   V_TAXABASECALC NUMBER;
   V_TAXABCSUBSTR NUMBER;
   V_TAXAALIQUOTA NUMBER;
   V_PRODUENCARGO NUMBER;
   V_SEQUIMPOSTNF NUMBER;
   V_SOMAITEM     NUMBER;
   V_DESCITEM     NUMBER;
   V_BASECALCIT   NUMBER;
   V_BASECALCTO   NUMBER;
   V_BASECALCIRRF NUMBER;
   V_PBCSUBTRIB   NUMBER;
   V_IMPOSTOIT    NUMBER;
   V_VRIMPOSTO    NUMBER;
   V_FATOCONV     NUMBER;
   V_TOTABRUT     NUMBER;
   V_SOMAIMPONF   NUMBER;
   V_DESCIMPONF   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_IMPOSRETI    NUMBER;
   V_CONTABCALC   NUMBER;
   V_PERDBCALC    NUMBER;
   V_FAIXATOLER   NUMBER;
   V_NRDECITOTANF NUMBER;
   V_IMPOSINFUSU  NUMBER;
   V_VRCONTAREC   NUMBER;
   V_VRDIFERENCA  NUMBER;
   V_EXISTE_ROT   NUMBER;
   V_NRSEQITPROD  NUMBER;
   V_VRFATOCONV   NUMBER;
   V_VRLIQUORIG   NUMBER;
   V_VRPESOBRUTO  NUMBER;
   V_VRIMPOSTOST  NUMBER;
   V_VRREDUCAO    NUMBER;
   V_VALOR        NUMBER;
   V_VRTOTAITEM   NUMBER;
   V_SOMATOTAITEM NUMBER;
   V_PERCENTITEM  NUMBER;
   V_SOMAQITEMPROD  NUMBER;
   V_SOMAVRBRUTITEM NUMBER;
   V_SOMAVRCONTITEM NUMBER;
   V_CDGRUPOFISC  VARCHAR2(03);
   V_CDGRPFISCSV  VARCHAR2(03);
   V_UTGRUPFISCS  VARCHAR2(01);
   V_CDORIGDESTNF VARCHAR2(21);
   V_IDOPERDEVONF VARCHAR2(01);
   V_CHAVE        VARCHAR2(21);
   V_IMPOSTO      VARCHAR2(02);
   V_IDRECALCULO  VARCHAR2(01);
   V_CDFILIMOVI   VARCHAR2(04);
   V_CDTIPOOPER   VARCHAR2(02);
   V_CDENCDESCBONDEV VARCHAR2(02);
   V_CDAJUCTPAG   VARCHAR2(04);
   V_VRPEDESCFORN FLOAT;
   V_VRENCARBONI  FLOAT;
   V_IDCONDESBONFORN VARCHAR2(01);
   V_DTINIVRPDESC DATE;
   V_IMPOSDESONERA NUMBER;
   V_DIFERENCA     FLOAT;
   V_VRFRETEITEM   FLOAT;
   V_VRSEGURITEM   FLOAT;
   V_VRENCARGODESC FLOAT;
   V_SUMVRDESCITEM FLOAT;
   V_VROUTRASDESPITEM FLOAT;
   V_VRDESPADUANEIRA  FLOAT;
   V_TOTAENCIMPXML FLOAT;
   V_DSCDFISOPEIT VARCHAR2(450);
   V_DTVINGENTE   DATE;
   V_DTINIREFEFAT DATE;
   V_ICMS         VARCHAR2(01);
   V_IMPOICMS     VARCHAR2(02);
   V_CDSITUCRT         VARCHAR2(01);
   V_CDSIMPLESNACIONAL VARCHAR2(5);
   V_RBT12             FLOAT; --RECEITA BRUTA TOTAL DOS ULTIMOS 12 MESES
   V_RBA               FLOAT; --RECEITA BRUTA ACUMULADA
   V_VRSUBLIMITESN     FLOAT;
   V_VRALIQSIMPLES     FLOAT;
   V_APROVICMS         FLOAT;
   V_ALIQAPROVICMS     FLOAT;
   V_SIMPLES           VARCHAR2(01);
   V_CDFAIXA           VARCHAR2(5);
   V_ESTORNOCANC       VARCHAR2(01);
   /*Aliquota do imposto que possui diferencial de aliquota*/
   V_DIFALIQ           FLOAT;
   V_CDFISCOPERREGRA     VARCHAR2(10);
   V_DSCDFISOPEITREGRA   VARCHAR2(50);
   V_IDDIFEALIQREGRA     VARCHAR2(10);
   V_IDDIFALIQCUSPRREGRA VARCHAR2(10);
   V_CFOPINFUSU          VARCHAR2(01);
   V_CFOP1DIGT           VARCHAR2(01);
   w_A            CHAR(1):= 'A';
   w_C            CHAR(1):= 'C';
   w_D            CHAR(1):= 'D';
   w_N            CHAR(1):= 'N';
   w_S            CHAR(1):= 'S';
   w_R            CHAR(1):= 'R';
   w_P            CHAR(1):= 'P';
   w_I            CHAR(1):= 'I';
   w_L            CHAR(1):= 'L';
   w_V            CHAR(1):= 'V';
   w_O            CHAR(1):= 'O';
   w_F            CHAR(1):= 'F';
   w_U            CHAR(1):= 'U';
   w_0            CHAR(1):= '0';
   w_1            CHAR(1):= '1';
   w_2            CHAR(1):= '2';
   w_3            CHAR(1):= '3';
   w_4            CHAR(1):= '4';
   w_5            CHAR(1):= '5';
   w_8            CHAR(1):= '8';
   w_9            CHAR(1):= '9';
   w_01           CHAR(2):= '01';
   w_03           CHAR(2):= '03';
   w_09           CHAR(2):= '09';
   w_11           CHAR(2):= '11';
   w_12           CHAR(2):= '12';
   w_90           CHAR(2):= '90';
   w_000          CHAR(3):= '000';
   w_001          CHAR(3):= '001';
   w_101          CHAR(3):= '101';
   w_00000        CHAR(5):= '00000';
   w_VMN          CHAR(3):= 'VMN';
   w_EXP          CHAR(3):= 'EXP';
   w_VND          CHAR(3):= 'VND';
   w_Av04         CHAR(4):= 'AV04';
   w_Av05         CHAR(4):= 'AV05';
   w_Av06         CHAR(4):= 'AV06';
   w_Av09         CHAR(4):= 'AV09';
   w_Av10         CHAR(4):= 'AV10';
   w_Er03         CHAR(4):= 'ER03';
   w_Er04         CHAR(4):= 'ER04';
   w_Er06         CHAR(4):= 'ER06';
   V_IDIMPOBCALTPOP  VARCHAR2(01);
   V_IDIMBCALTPOPDE  VARCHAR2(01);
   V_QTITEMPROD      FLOAT;
   V_CDIMPOSTO       VARCHAR2(02);
   V_IDUTCTRLLOTE    VARCHAR2(01);
   V_MEDIA           NUMBER;
   V_BCICMSSTRETIDO  FLOAT;
   V_VRICMSSTRETIDO  FLOAT;
   V_NRLOTEESTQ      VARCHAR2(20);
   V_EXISTDSDADOSADIC  INTEGER;
   V_BCICMSRET       FLOAT;
   V_ICMSRET         FLOAT;
   V_IDCALCPESONF    VARCHAR2(01);
   V_IDUTDESCICMS    VARCHAR2(01);
   V_CDREGRAITALIQ    VARCHAR2(10);
   V_CARGA            FLOAT;
   V_CDIMPOSRECALC    VARCHAR2(200);
   V_CDCFOPINFUSU     VARCHAR2(11);
   V_DSCFOPINFUSU     VARCHAR2(50);
   V_IDUTVLRQTDEIMPO  VARCHAR2(01);
   V_VRFATOCONVES     FLOAT;
   V_DTENTRSAID       DATE;
   V_CDIMPOSTOI       VARCHAR2(02);
   V_CDPRODUTO        VARCHAR2(10);
   V_VRIMPOSTOVISUIT  FLOAT;
   V_IDALTERADO_ENCA  VARCHAR2(01);
   V_CDGRUPOFISCAUX   VARCHAR2(03);
   V_CDIMPOSIPI        VARCHAR2(02);
   V_IDGERIPIDESPA     VARCHAR2(01);
   V_IDGERICMSTDESPA   VARCHAR2(01);
   V_VRTOTALIPI        FLOAT;
   V_CDENCARGOOD       VARCHAR2(02);
   V_VRTOTALICMSST     FLOAT;
   V_CDENCARGOICMST    VARCHAR2(02);
   V_IDPEINFICMSTDEME  VARCHAR2(01);
   V_VRENCAICMSSTIT    FLOAT;
   V_VRICMSST          FLOAT;
   V_VRBASECALC        FLOAT;
   V_SOMAVRNOTAFISC    FLOAT;
   V_IDUTCTRLFISSAID   VARCHAR2(01);
   V_IDUTCTRLFISFIL    VARCHAR2(01);
   V_IDUTCTRLFIS       VARCHAR2(01);
   V_IDPERVISIMPSCRE   VARCHAR2(01);
   V_VRIMPOSST         FLOAT;
   V_VRADICFECPST      FLOAT;
   V_VRADICFECPSTAUX   FLOAT;
   V_DIFEVRBRUTO       FLOAT;
   V_VRPERDIFERE       FLOAT;
   V_PERDIFERE         FLOAT;
   V_IMPOSTOOPERA      FLOAT;
   V_IMPOSTODIFER      FLOAT;
   V_IDCONTCONFORIG    VARCHAR2(01);
   V_IDDESCIMPRECCONT  VARCHAR2(01);
   V_IDIMPORECUP       VARCHAR2(01);
   V_CDCCTBLATIV       VARCHAR2(20);
   V_IDATUESTTPOP      TIPOOPERAC.IDATUESTTPOP%TYPE;
   V_IDREMESSAINDU     TIPOOPERAC.IDREMESSAINDU%TYPE;
   V_CDALMOXINFO       AGENTETERCECLI.CDALMOXINFOCLI%TYPE;
   V_CDLOCALINFO       AGENTETERCECLI.CDLOCALINFOCLI%TYPE;
   V_CDFILIALENTR      CTRLMOVIESTQ.CDFILIALENTR%TYPE;
   V_NRLANESTENTR      NOVOCODIGO.NRSEQUENCIAL%TYPE;
   V_NRCTRLMOVEST      NOVOCODIGO.NRSEQUENCIAL%TYPE;
   V_BOLANESTENTR      BOOLEAN := TRUE;
   V_DSENDEDEVOEMBA    VARCHAR2(255);
   V_CDENQLEGALIPI     VARCHAR2(03);
   V_CDCEST            VARCHAR2(09);
   /* variaveis para geracao de entrada no estoque (filial agente de terceiracao */
   V_CDFILIAGENT       VARCHAR2(04);
   V_BOLANESTENTRAG    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_IDTPIJURNF        VARCHAR2(01);
   V_CDEMPRESAAG       VARCHAR2(02);
   V_CDINSCESTAAG      VARCHAR2(16);
   V_CDINSCMUNIAG      VARCHAR2(16);
   V_CDFILIORIG        VARCHAR2(04);
   V_TPOPERRETORNO     VARCHAR2(02);
   V_IDUTORIGPROD       VARCHAR2(01);
   V_VRPRODUTOBC       FLOAT;
   V_VRALIQUTMPDEST    VARCHAR2(14);
   V_CDIMPOSTOICMS     VARCHAR2(02);
   V_VRIMPOSTOICMS     FLOAT;
   V_VRBASECALCICMS    FLOAT;
   V_IDIMPSTCARGTRIB   VARCHAR2(01);
   V_VRIMPOSTOOPERAIT  FLOAT;
   V_VRPERDIFEREIT     FLOAT;
   V_VRIMPOSTODIFERIT  FLOAT;
   V_CDPAISFCT      VARCHAR2(04);
   V_SGESTADOFCT    VARCHAR2(02);
   V_CDMUNICIPIOFCT VARCHAR2(04);
   V_QTDREGFCT      FLOAT;
   V_IDPRESENCIAL      VARCHAR2(01);
   V_IDUTILPVRIMPBC    VARCHAR2(01);
   V_VRADICALIQFECP    FLOAT(126);
   V_VRADICFECP        FLOAT(126);
   V_IDCONSFINAL       VARCHAR2(01);
   V_STRVRADICALIQFECP VARCHAR2(15);
   V_STRVRADICFECP     VARCHAR2(15);
   V_NRINSESTDESNF     VARCHAR2(20);
   V_IDCONTRIBICMS     VARCHAR2(01);
   V_IDCONTRIBICMSAUX  VARCHAR2(01);
   V_ALIQICMSDEST      FLOAT;
   V_ALIQFECPDEST      FLOAT;
   V_CDIMPOSTOFECP     VARCHAR2(02);
   V_IDDIFECLI         VARCHAR2(01);
   V_CDFILIALPED       VARCHAR2(04);
   V_NRPEDIDO          VARCHAR2(10);
   V_DADOSADICENDPED   VARCHAR2(400);
   V_IDPRODPERIG       VARCHAR2(01);
   V_MSGPRODPERIG      VARCHAR2(500);
   V_GRAVAMSGPRODPERIG INTEGER;
   V_IDCALCDIFALDENT   VARCHAR2(01);
   V_IDUTILVENC        VARCHAR2(01);
   V_IDNOTADEVO        VARCHAR2(01);
   V_IDNFAJUSTE        VARCHAR2(01);
   V_IDVERLEIAUTENFE   VARCHAR2(04);
   V_MAJORAOUREDUZ     VARCHAR2(01);
   /* Variaveis para geracao dos encargos de acordo com os impostos relacionados na nota fiscal de origem(importacao de XML) */
   V_VRENCARGOIMPXML NUMBER;
   V_VRIMPENCXMLORIG NUMBER;
   V_UPDENCIMPXML    VARCHAR2(01);
   V_NRSEQITORIG     VARCHAR2(04);
   V_NRACESSONFORIG  VARCHAR2(44);
   V_IDNFORIGVIAXML  VARCHAR2(01);
   V_IDOPTANTESNCLIE VARCHAR2(01);
   V_CDCNAECLIE      VARCHAR2(07);
   V_VRMVA           FLOAT;
   V_IDENDCFOPCLIPRES VARCHAR2(01);
   V_IDOPPRESENDDIF   VARCHAR2(01);
   V_IDUTILNFSE      VARCHAR2(01);
   V_VRIMPORETNF     FLOAT;
   V_VRIMPORELAC     FLOAT;
   V_IDENDEMISTPOPFIL VARCHAR2(01);
   /* Variaveis prestacao de servico */
   V_CDPAISSERV      VARCHAR2(04);
   V_SGESTADOSERV    VARCHAR2(02);
   V_CDMUNICIPIOSERV VARCHAR2(04);
   V_QTDREGSERV      NUMBER;
   V_IDIMPODESONERA  VARCHAR2(01);
   V_IDCONSDESONVRNF VARCHAR2(01);
   V_CDPAISEMIT      VARCHAR2(04);
   V_SGESTADOEMIT    VARCHAR2(02);
   V_CDBENEFFISCAL    VARCHAR2(10);
   V_DSINFADICPROD   VARCHAR2(4000);
     V_IPIDEVOLMSG   VARCHAR2(4000);
   V_VRADICFECPNFTOT FLOAT;
   V_DADOSVENDEDOR   VARCHAR2(255);
   V_IDADICVENDEDOR  VARCHAR2(01);
   V_DESCNRPEDIDO    VARCHAR2(255);
   V_IDADICNRPEDIDO  VARCHAR2(01);   
   V_IDCONSMVAPMC    VARCHAR2(01);
   V_IDCONSCOMPBCPMC VARCHAR2(01);
   V_FECPPMCAUX      FLOAT;
   V_IDCONSDIFALIQ   VARCHAR2(01);
   V_CDCOMPST        VARCHAR2(20);
   V_CDRESTST        VARCHAR2(20);
   V_CDNATUREC       VARCHAR2(10);
   /*variaveis mensagem ICMS 60*/
   V_VRBCITENTR      FLOAT;
   V_VRIMPITENTR     FLOAT;
   V_ENCARGOLIQUIDO  VARCHAR2(350);
   V_EXISTEENCARGO   NUMBER;
   V_CDTIPOOPERBONIF VARCHAR2(02);
   --VARIAVEIS PARA ATUALIZAR ESTOQUE POR CFOP
   V_ATUPORCFOP    VARCHAR2(01);
   V_CFOPTPOPER    FLOAT;
   V_CFOPATUEST    FLOAT;
   /*FET*/
   V_FETBASECALC   FLOAT;
   V_FETVRIMPOSTO  FLOAT;
   V_FETALIQUOTA   VARCHAR(15);
   V_DSDADOFISCO   VARCHAR2(255);
BEGIN
--VARIAVEIS COM A CHAVE PARA AS TABELAS TEMPORARIAS
   V_ALIQTEMP := P_FILIAL||P_LANCTONF;/* ALIQUOTA */
   V_INCITEMP := P_FILIAL||P_LANCTONF;/* INCIDENCIA */
   V_CSTTEMP  := P_FILIAL||P_LANCTONF;/* CST */
   V_CFOPTEMP := P_FILIAL||P_LANCTONF;/* CFOP */
   V_TOTALNOTA  := 0; /*VALOR TOTAL DA NOTA*/
   V_FAIXATOLER := 0.02; /* FAIXA DE TOLERANCIA DE VALORES (CONSISTE VRNOTAFISC X VRPRODUTOS E VENCIMENTOS X VALOR TOTAL DA NOTA)*/
   V_VRADICALIQFECP := NULL;
   V_VRADICFECP     := NULL;
   V_CDBENEFFISCAL  := NULL;
   V_DADOADIC       := NULL;
   V_DADOADICFISCO  := NULL;
   Begin
      SELECT N.NRINSJURNF,
             N.CDSERIE,
             N.CDFILIEMIT,
             N.CDFILIRECE,
             NVL(P.IDUTILALMOX, w_N),
             NVL(P.IDUTILLCESTQ, w_N),
             NVL(P.IDUTILLOTE, w_N),
             N.CDINTEGRACAO,
             N.IDORIGDESTNF,
             N.IDDOCFINANC,
             N.IDDOCREPLIC,
             N.IDSISTEMA,
             NVL(P.IDCTRLESTQ, w_S),
             N.DTINIREFEFAT,
             N.CDINSCESTA,
             N.CDEMPRESA,
             N.IDTPIJURNF,
             NVL(N.IDPRESENCIAL, w_9),
             NVL(I.IDVERLEIAUTENFE, '3.10'),
             NVL(CDSITUCRT, '3'),
             NVL(VRSUBLIMITESN, 0),
             I.CDPAIS,
             I.SGESTADO
        INTO V_NRINSJURNF,
             V_SERIE,
             V_CDFILIEMIT,
             V_CDFILIRECE,
             V_IDUTILALMOX,
             V_IDUTILLCESTQ,
             V_IDUTILLOTE,
             V_CDINTEGRACAO,
             V_IDORIGDESTNF,
             V_IDDOCFINANC,
             V_IDDOCREPLIC,
             V_IDSISTEMA,
             V_IDCTRLESTQ,
             V_DTINIREFEFAT,
             V_CDINSCESTA,
             V_CDEMPRESA,
             V_IDTPIJURNF,
             V_IDPRESENCIAL,
             V_IDVERLEIAUTENFE,
             V_CDSITUCRT,
             V_VRSUBLIMITESN,
             V_CDPAISEMIT,
             V_SGESTADOEMIT
        FROM NOTAFISCAL N, PARAMFILIAL P, INSCRESTAD I, PARAMEMPRESA PE
       WHERE N.CDFILIAL = P_FILIAL
         AND N.NRLANCTONF = P_LANCTONF
         AND N.CDFILIEMIT = P.CDFILIAL(+)
         AND N.CDEMPRESA = I.CDEMPRESA
         AND N.CDINSCESTA = I.CDINSCESTA
         AND N.CDEMPRESA = PE.CDEMPRESA(+);
   Exception
      When No_Data_Found Then
         V_NRINSJURNF := Null;
         V_SERIE := Null;
         V_CDFILIEMIT := Null;
         V_CDFILIRECE := Null;
         V_IDUTILALMOX := w_N;
         V_IDUTILLCESTQ := w_N;
         V_IDUTILLOTE := w_N;
         V_CDINTEGRACAO := Null;
         V_IDORIGDESTNF:= Null;
         V_IDDOCFINANC := Null;
         V_IDDOCREPLIC := Null;
         V_IDSISTEMA := Null;
         V_IDCTRLESTQ := w_S;
         V_DTINIREFEFAT := Null;
         V_CDINSCESTA := Null;
         V_CDEMPRESA := Null;
         V_IDTPIJURNF := NULL;
         V_IDPRESENCIAL := w_9;
         V_IDVERLEIAUTENFE := '3.10';
         V_CDSITUCRT := '3';
         V_VRSUBLIMITESN := 0;
         V_CDPAISEMIT := Null;
         V_SGESTADOEMIT := Null;
   End;
   /* LANCAMENTO DE ESTOQUE DO DOCUMENTO GERADO ATRAVES DE REPLICACAO */
   Begin
      SELECT CDFILIAL||NRLANCESTQ
      INTO   V_IDDOCESTOQ
      FROM LANCTOESTOQ
      WHERE CDFILIAL   = SUBSTR(V_IDDOCREPLIC, 1, 4) AND
            NRLANCTONF = SUBSTR(V_IDDOCREPLIC, 5, 10);
   Exception
      When No_Data_Found Then
         V_IDDOCESTOQ := Null;
   End;
   IF V_IDDOCESTOQ IS NULL THEN
      /* LANCAMENTO DE ESTOQUE DO DOCUMENTO GERADO ATRAVES DE INTEGRACAO (EX: IMPORTACAO DE NFS)*/
      Begin
         SELECT CDFILIAL||NRLANCESTQ
         INTO   V_IDDOCESTOQ
         FROM LANCTOESTOQ
         WHERE CDFILIAL   = SUBSTR(V_CDINTEGRACAO, 1, 4) AND
               NRLANCTONF = SUBSTR(V_CDINTEGRACAO, 5, 10);
      Exception
         When No_Data_Found Then
            V_IDDOCESTOQ := Null;
      End;
   END IF;
   SELECT NVL(NRDECITOTANF,2), 
          NVL(IDUTORIGPROD, 'N'), 
          NVL(IDOPPRESENDDIF, 'N'), 
          NVL(IDADICVENDEDOR, 'N'),
          NVL(IDPERVISIMPSCRE,'S'),
		  NVL(IDADICNRPEDIDO,'N')
     INTO V_NRDECITOTANF, 
          V_IDUTORIGPROD, 
          V_IDOPPRESENDDIF, 
          V_IDADICVENDEDOR,
          V_IDPERVISIMPSCRE,
		  V_IDADICNRPEDIDO
     FROM PARAMGERAL;
   --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 := W_001;
   ELSE
      V_DADOADIC := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_DADOADIC) + 1)),3,0);
      /*GERA O PROXIMO SEQUENCIAL A SER INSERIDO*/
   END IF;
   --MAIOR REGISTRO DA TABELA DE DADOS ADICIONAIS DO FISCO
   SELECT MAX(NRDADOADICFISCO)
     INTO V_DADOADICFISCO
     FROM DADOSADICFISCO
    WHERE (CDFILIAL   = P_FILIAL) AND
          (NRLANCTONF = P_LANCTONF);
   IF (V_DADOADICFISCO IS NULL) THEN
      V_DADOADICFISCO := W_001;
   ELSE
      V_DADOADICFISCO := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_DADOADICFISCO) + 1)),3,0);
      /*GERA O PROXIMO SEQUENCIAL A SER INSERIDO*/
   END IF;
   FOR C_MENSINSC IN (SELECT M.CDMENSAGEM, I.DSMENSINSCRESTA
                        FROM MENSINSCRESTAD I LEFT JOIN MENSAGEM M ON (M.CDMENSAGEM = I.CDMENSAGEM)
                       WHERE (I.CDEMPRESA = P_EMPRESA)
                         AND (I.CDINSCESTA = P_INSCESTA)
                         AND (I.IDENTRSAIDMENS <> 'E')
                         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.DSMENSINSCRESTA || '%'))
                       ORDER BY I.NRMENSINSCRESTA) 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.DSMENSINSCRESTA);
      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_CLIENTE
                               AND C.IDENTRSAIDMENS <> 'E'
                               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 endereco: ' || 
             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), 'aaaaeaeeieieiicanooooeoaoeuueuuyAAAAEAEEIEIEIIANOOOOEOAOEUUEUUYC', '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 endereco: ' || 
                                                 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), 'aaaaeaeeieieiicanooooeoaoeuueuuyAAAAEAEEIEIEIIANOOOOEOAOEUUEUUYC', 'aaaaaeieieiicanoooooaouuuuyAAAAAEIEIEIIANOOOOOAOUUUUYC') || '%'));
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_DSENDEDEVOEMBA := NULL;
      WHEN TOO_MANY_ROWS THEN
         RAISE_APPLICATION_ERROR(-20501, 'Operacao 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;
   --VARIAVEIS PARA CONSULTA DE ALIQUOTA, INCIDENCIA, CFOP
   Begin
      SELECT NVL(IDENDCFOPFIL,w_I), CDEMPRESA,   CDINSCESTA
      INTO   V_IDENDCFOP,           V_CDEMPRESA, V_CDINSCESTA
      FROM FILIAL
      WHERE (CDFILIAL = V_CDFILIEMIT);
   Exception
      When No_Data_Found Then
         V_IDENDCFOP:= w_I; V_CDEMPRESA:= Null; V_CDINSCESTA:= Null;
   End;
      BEGIN
      SELECT NVL(IDENDEMISTPOPFIL, w_P)
        INTO V_IDENDEMISTPOPFIL
        FROM TIPOOPERACFIL
       WHERE IDENTRSAIDOP = w_S
         AND CDTIPOOPER = P_TIPOOPER
         AND CDFILIAL = V_CDFILIEMIT;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_IDENDEMISTPOPFIL := w_P;
   END;
   IF V_IDENDEMISTPOPFIL <> w_P THEN
      IF V_IDENDEMISTPOPFIL = w_I THEN
         BEGIN
            SELECT CDPAIS, 
                   SGESTADO,
                   CDMUNICIPIO
              INTO V_PAISORIG,
                   V_ESTAORIG,
                   V_MUNIORIG
              FROM INSCRESTAD
             WHERE CDEMPRESA  = P_EMPRESA 
               AND CDINSCESTA = P_INSCESTA;
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_PAISORIG := NULL; 
               V_ESTAORIG := NULL; 
               V_MUNIORIG := NULL;
         END;
      ELSE
         BEGIN
            SELECT CDPAIS,
                   SGESTADO,
                   CDMUNICIPIO
              INTO V_PAISORIG,
                   V_ESTAORIG,
                   V_MUNIORIG
              FROM ENDEFILI
             WHERE CDFILIAL     = V_CDFILIEMIT
               AND IDTPENDEFILI = V_IDENDEMISTPOPFIL;
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_PAISORIG := NULL;
               V_ESTAORIG := NULL;
               V_MUNIORIG := NULL;
         END;
      END IF;
   ELSE   
      IF V_IDENDCFOP = w_I THEN
         Begin
            SELECT CDPAIS    , SGESTADO  , CDMUNICIPIO
            INTO   V_PAISORIG, V_ESTAORIG, V_MUNIORIG
            FROM INSCRESTAD
            WHERE CDEMPRESA  = P_EMPRESA AND
                  CDINSCESTA = P_INSCESTA;
         Exception
            When No_Data_Found Then
               V_PAISORIG := Null; V_ESTAORIG := Null; V_MUNIORIG := Null;
         End;
      ELSE
         Begin
            SELECT CDPAIS    , SGESTADO  , CDMUNICIPIO
            INTO   V_PAISORIG, V_ESTAORIG, V_MUNIORIG
            FROM ENDEFILI
            WHERE (CDFILIAL     = V_CDFILIEMIT) AND
                  (IDTPENDEFILI = V_IDENDCFOP);
         Exception
            When No_Data_Found Then
               V_PAISORIG := Null; V_ESTAORIG := Null; V_MUNIORIG := Null;
         End;
      END IF;
   END IF;
   /*DESTINATARIO-REMETENTE DA NOTA*/
   IF V_IDORIGDESTNF IS NULL THEN
      Begin
         SELECT IDORIGDESTOP
         INTO   V_ORIGDESTOP
         FROM TIPOOPERAC
         WHERE IDENTRSAIDOP = w_S AND
               CDTIPOOPER   = P_TIPOOPER;
      Exception
         When No_Data_Found Then
            V_ORIGDESTOP := Null;
      End;
   ELSE
      V_ORIGDESTOP := V_IDORIGDESTNF;
   END IF;
   V_CDORIGDESTNF := P_CLIENTE;
   V_IDCONSFINAL := w_N;
   IF V_ORIGDESTOP = w_L THEN /*DESTINATARIO -> FILIAL */
      Begin
         SELECT NVL(IDENDCFOPFIL,w_I), NVL(IDENDEMISFIL,w_I), CDEMPRESA  , CDINSCESTA
         INTO   V_IDENDCFOP          , V_IDENDEMIS          , V_CDEMPRESA, V_CDINSCESTA
         FROM FILIAL
         WHERE (CDFILIAL = V_CDFILIRECE);
      Exception
         When No_Data_Found Then
            V_IDENDCFOP := w_I; V_IDENDEMIS := w_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_CDFILIRECE
         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_CDFILIRECE) AND
                  (IDTPENDEFILI = V_IDENDCFOP);
         Exception
            When No_Data_Found Then
               V_PAISCFOP := Null; V_ESTACFOP := Null;
         End;
      END IF;
      IF V_IDENDEMIS = w_I THEN
         Begin
            SELECT CDPAIS    , SGESTADO  , CDMUNICIPIO
            INTO   V_PAISDEST, V_ESTADEST, V_MUNIDEST
            FROM INSCRESTAD
            WHERE CDEMPRESA  = V_CDEMPRESA AND
                  CDINSCESTA = V_CDINSCESTA;
         Exception
            When No_Data_Found Then
               V_PAISDEST := Null; V_ESTADEST := Null; V_MUNIDEST := Null;
         End;
      ELSE
         Begin
            SELECT CDPAIS    , SGESTADO  , CDMUNICIPIO
            INTO   V_PAISDEST, V_ESTADEST, V_MUNIDEST
            FROM ENDEFILI
            WHERE CDFILIAL     = V_CDFILIRECE AND
                  IDTPENDEFILI = V_IDENDEMIS;
         Exception
            When No_Data_Found Then
               V_PAISDEST := Null; V_ESTADEST := Null; V_MUNIDEST := Null;
         End;
      END IF;
      V_CDORIGDESTNF := V_CDFILIRECE;
   ELSIF V_ORIGDESTOP = w_F THEN /*DESTINATARIO -> FORNECEDOR */
      BEGIN
         SELECT NVL(IDENDCFOPFOR,w_P), 
                NVL(IDENDEMISFOR,w_P),
                NVL(IDCONSFINAL,w_N),
                NRINSESTFORN,
                NVL(IDCONTRIBICMS,w_N)
           INTO V_IDENDCFOP,
                V_IDENDEMIS,
                V_IDCONSFINAL,
                V_NRINSESTDESNF,
                V_IDCONTRIBICMS
           FROM FORNECEDOR
          WHERE (CDFORNECED = P_CLIENTE);
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_IDENDCFOP := w_P; 
            V_IDENDEMIS := w_P;
            V_IDCONSFINAL := w_N;
            V_NRINSESTDESNF := NULL;
            V_IDCONTRIBICMS := w_N;
      END;
      SELECT MAX(CDPAIS), MAX(SGESTADO), MAX(CDMUNICIPIO)
        INTO V_CDPAISST, V_SGESTADOST, V_CDMUNICIPIOST
        FROM ENDEFORN
       WHERE CDFORNECED = P_CLIENTE
         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_CLIENTE) 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_PAISDEST, V_ESTADEST, V_MUNIDEST
         FROM ENDEFORN
         WHERE (CDFORNECED   = P_CLIENTE) AND
               (IDTPENDEFORN = V_IDENDEMIS);
      Exception
         When No_Data_Found Then
            V_PAISDEST := Null; V_ESTADEST := Null; V_MUNIDEST := Null;
      End;
   ELSE /*DESTINATARIO -> CLIENTE(DEFAULT) */
      BEGIN
         SELECT NVL(IDENDCFOPCLI,w_P),
                NVL(IDENDEMISCLI,w_P), 
                NVL(IDUTDESCICMS, w_N),
                NVL(IDCONSFINAL,w_N),
                NRINSESTCLIE,
                NVL(IDCONTRIBICMS,w_N),
                CDCNAECLIE,
                NVL(IDOPTANTESNCLIE,w_N),
                NVL(IDENDCFOPCLIPRES, 'I')
           INTO V_IDENDCFOP,
                V_IDENDEMIS,
                V_IDUTDESCICMS,
                V_IDCONSFINAL,
                V_NRINSESTDESNF,
                V_IDCONTRIBICMS,
                V_CDCNAECLIE,
                V_IDOPTANTESNCLIE,
                V_IDENDCFOPCLIPRES
           FROM CLIENTE
          WHERE (CDCLIENTE = P_CLIENTE);
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_IDENDCFOP := w_P;
            V_IDENDEMIS := w_P;
            V_IDUTDESCICMS := w_N;
            V_IDCONSFINAL := w_N;
            V_NRINSESTDESNF := NULL;
            V_IDCONTRIBICMS := w_N;
            V_CDCNAECLIE := NULL;
            V_IDOPTANTESNCLIE := w_N;
            V_IDENDCFOPCLIPRES := 'I';
      END;
      SELECT MAX(CDPAIS), MAX(SGESTADO), MAX(CDMUNICIPIO)
        INTO V_CDPAISST, V_SGESTADOST, V_CDMUNICIPIOST
        FROM ENDECLIE
       WHERE CDCLIENTE = P_CLIENTE
         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, CDMUNICIPIO
            INTO   V_PAISCFOP, V_ESTACFOP, V_MUNIDEST
            FROM INSCRESTAD
            WHERE CDEMPRESA  = P_EMPRESA AND
                  CDINSCESTA = P_INSCESTA;
         Exception
            When No_Data_Found Then
               V_PAISCFOP := Null; V_ESTACFOP := Null; V_MUNIDEST := Null;
         End;
         V_PAISDEST := V_PAISCFOP;
         V_ESTADEST := V_ESTACFOP;
      ELSE
         Begin
            SELECT CDPAIS    , SGESTADO
            INTO   V_PAISCFOP, V_ESTACFOP
            FROM ENDECLIE
            WHERE (CDCLIENTE    = P_CLIENTE) AND
                  (IDTPENDECLIE = V_IDENDCFOP);
         Exception
            When No_Data_Found Then
               V_PAISCFOP := Null; V_ESTACFOP := Null;
         End;
         Begin
            SELECT CDPAIS    , SGESTADO  , CDMUNICIPIO
            INTO   V_PAISDEST, V_ESTADEST, V_MUNIDEST
            FROM ENDECLIE
            WHERE (CDCLIENTE    = P_CLIENTE) AND
                  (IDTPENDECLIE = V_IDENDEMIS);
         Exception
            When No_Data_Found Then
               V_PAISDEST := Null; V_ESTADEST := Null; V_MUNIDEST := Null;
         End;
      END IF;
   END IF;
   IF (V_NRINSESTDESNF IS NULL) OR (V_NRINSESTDESNF = '') THEN
      V_IDCONTRIBICMSAUX := 'N';
   ELSE
      V_IDCONTRIBICMSAUX := V_IDCONTRIBICMS;
   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 <> 'E'
                                  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 TRIBUTARIO*/
         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;
    -- 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;
   /*
   ROTINA PARA VERIFICAR AS NOTAS DO SISTEMA FACILITIES. NESTAS NOTAS O SISTEMA
   NAO VERIFICARA O PAIS, O ESTADO E NEM O MUNICIPIO DO DESTINATARIO DA NOTA FISCAL 
   E SIM DO LOCAL DE ATENDIMENTO DAQUELA PRESTACAO DE SERVICO
   */
   V_QTDREGFCT := 0;
   BEGIN
      SELECT CDPAIS, 
             SGESTADO, 
             CDMUNICIPIO,
             COUNT(*)
        INTO V_CDPAISFCT,
             V_SGESTADOFCT,
             V_CDMUNICIPIOFCT,
             V_QTDREGFCT
        FROM FCT_DADOSNF
       WHERE CDFILIAL = P_FILIAL
         AND NRLANCTONF = P_LANCTONF
       GROUP BY CDPAIS, 
             SGESTADO,
             CDMUNICIPIO;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_CDPAISFCT := NULL;
         V_SGESTADOFCT := NULL;
         V_CDMUNICIPIOFCT := NULL;
         V_QTDREGFCT := 0;
   END;
   IF (V_QTDREGFCT > 0) THEN
      V_PAISDEST := V_CDPAISFCT;
      V_ESTADEST := V_SGESTADOFCT;
      V_MUNIDEST := V_CDMUNICIPIOFCT;
   END IF;
   /* Operacao Presencial - Se considera endereco de destino igual ao endereco de origem */
   IF V_IDOPPRESENDDIF = 'N' THEN
      /*
      QUANDO A OPERACAO DA NOTA FISCAL FOR PRESENCIAL O SISTEMA USARA COMO ENDERECO
      DE DESTINO O MESMO ENDERECO DA ORIGEM. ESTA CONDICAO FOI NECESSARIA PARA ATENDER
      A NOTA TECNICA 2015/003
      */
      IF V_IDPRESENCIAL = W_1 THEN
         V_PAISDEST := V_PAISORIG;
         V_ESTADEST := V_ESTAORIG;
         V_MUNIDEST := V_MUNIORIG;
         -- Verificar identificador de endereco CFOP conforme operacao presencial
         IF (NVL(V_IDORIGDESTNF, 'C') = 'C') THEN
            IF V_IDENDCFOPCLIPRES = 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_CLIENTE
                     AND IDTPENDECLIE = V_IDENDCFOPCLIPRES;
               Exception
                  When No_Data_Found Then
                     V_PAISCFOP := Null; V_ESTACFOP := Null;
               End;
            END IF;
         END IF;
      END IF;
   END IF;
   V_IDINTEREST := 'N';
   V_IDINTERNA  := 'N';
   IF ((V_PAISDEST = V_PAISORIG) AND (V_ESTADEST <> V_ESTAORIG)) THEN
      V_IDINTEREST := 'S';
   ELSIF (V_PAISDEST <> V_PAISORIG) THEN
      V_IDINTERNA := 'S';
   END IF;
   UPDATE ITEMPRODUTO
      SET VRFATCONTRIBXML = NULL,
          QTITPRODTRIBXML = NULL
    WHERE CDFILIAL   = P_FILIAL
      AND NRLANCTONF = P_LANCTONF
      AND VRFATCONTRIBXML = 0;
   IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (NVL(V_IDORIGDESTNF, 'C') <> 'L') THEN
      UPDATE ITEMPRODUTO
      SET VRTOTAITEM = TRUNC(VRTOTAITEM,2)
      WHERE CDFILIAL   = P_FILIAL AND
            NRLANCTONF = P_LANCTONF;
   ELSE
      UPDATE ITEMPRODUTO
      SET VRTOTAITEM = ROUND(VRTOTAITEM,2)
      WHERE CDFILIAL   = P_FILIAL AND
            NRLANCTONF = P_LANCTONF;
   END IF;
   SELECT (SUM(VRTOTAITEM) - SUM(VRDESCITEM))
   INTO V_LIQUIDO
   FROM ITEMPRODUTO
   WHERE CDFILIAL   = P_FILIAL AND
         NRLANCTONF = P_LANCTONF;
   /*PREENCHE O GRUPO FISCAL*/
   IF V_IDORIGDESTNF = w_U THEN /*LICENCA DE USO*/
      CONSULTA_GRUPOFISCAL(w_C           , V_CDORIGDESTNF, V_CDFILIEMIT, w_S, P_TIPOOPER, V_CDGRUPOFISC);
   ELSE /*DEMAIS DESTINATARIOS*/
      CONSULTA_GRUPOFISCAL(V_IDORIGDESTNF, V_CDORIGDESTNF, V_CDFILIEMIT, w_S, P_TIPOOPER, V_CDGRUPOFISC);
   END IF;
   /*VERIFICA SE A NOTA UTILIZA DOCUMENTO DE ORIGEM E SE O TIPO DE OPERACAO E DE ESTORNO DE CANCELAMENTO*/
   BEGIN
      SELECT IDOPERDEVONF, 
             IDCONSPARFIS, 
             IDNFESTCANC,
             IDCALCDIFALDENT,
             IDUTILVENC,
             IDNOTADEVO,
             IDNFAJUSTE,
             IDUTILNFSE,
             NVL(IDCONTCONFORIG, 'S'),
			          IDNTRANSCREICMS,
             NVL(DSOPERENCRATPL, 'N') AS  DSOPERENCRATPL,
             NVL(CDTIPOOPERBONIF, 'N') AS CDTIPOOPERBONIF
        INTO V_IDOPERDEVONF,
             V_IDCONSPARFIS, 
             V_ESTORNOCANC,
             V_IDCALCDIFALDENT,
             V_IDUTILVENC,
             V_IDNOTADEVO,
             V_IDNFAJUSTE,
             V_IDUTILNFSE,
             V_IDCONTCONFORIG,
			          V_IDNTRANSCREICMS,
             V_ENCARGOLIQUIDO,
             V_CDTIPOOPERBONIF
        FROM TIPOOPERAC
       WHERE IDENTRSAIDOP = w_S 
         AND CDTIPOOPER = P_TIPOOPER;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_IDOPERDEVONF := w_N; 
         V_IDCONSPARFIS := w_S; 
         V_ESTORNOCANC := w_N;
         V_IDCALCDIFALDENT := w_N;
         V_IDUTILVENC := w_N;
         V_IDNOTADEVO := w_N;
         V_IDNFAJUSTE := w_N;
         V_IDUTILNFSE := w_N;
         V_IDCONTCONFORIG := w_S;
		       V_IDNTRANSCREICMS := w_N;
         V_ENCARGOLIQUIDO  := w_N;
         V_CDTIPOOPERBONIF := w_N;
   END;
   IF (V_CDTIPOOPERBONIF = 'N') THEN
      UPDATE ITEMPRODUTO
         SET IDPRODBONIF = 'N'
       WHERE CDFILIAL   = P_FILIAL
         AND NRLANCTONF = P_LANCTONF;
   END IF;
   IF (V_IDUTILNFSE = 'S') THEN
      V_QTDREGSERV := 0;
      BEGIN
         SELECT CDPAISPRESSERV,
                SGESTADOPRESSERV,
                CDMUNICIPRESSERV,
                COUNT(*)
           INTO V_CDPAISSERV,
                V_SGESTADOSERV,
                V_CDMUNICIPIOSERV,
                V_QTDREGSERV
           FROM DADOSERVPRES
          WHERE CDFILIAL   = P_FILIAL
            AND NRLANCTONF = P_LANCTONF
          GROUP BY CDPAISPRESSERV,
                   SGESTADOPRESSERV,
                   CDMUNICIPRESSERV;
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_CDPAISSERV      := NULL;
            V_SGESTADOSERV    := NULL;
            V_CDMUNICIPIOSERV := NULL;
            V_QTDREGSERV      := 0;
      END;
       IF (V_QTDREGSERV > 0) THEN
         V_PAISDEST := V_CDPAISSERV;
         V_ESTADEST := V_SGESTADOSERV;
         V_MUNIDEST := V_CDMUNICIPIOSERV;
      END IF;
   END IF;
   IF V_IDOPERDEVONF <> w_S THEN  /*SE NAO UTILIZA DOCUMENTO DE ORIGEM*/
      IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (NVL(V_IDORIGDESTNF, 'C') <> 'L') THEN
         UPDATE ITEMPRODUTO
         SET VRBRUTITEM   = TRUNC((VRTOTAITEM - VRDESCITEM),2),
             VRCONTITEM   = TRUNC((VRTOTAITEM - VRDESCITEM),2)
         WHERE CDFILIAL   = P_FILIAL   AND
               NRLANCTONF = P_LANCTONF;
      ELSE
         UPDATE ITEMPRODUTO
         SET VRBRUTITEM   = ROUND((VRTOTAITEM - VRDESCITEM),2),
             VRCONTITEM   = ROUND((VRTOTAITEM - VRDESCITEM),2)
         WHERE CDFILIAL   = P_FILIAL   AND
               NRLANCTONF = P_LANCTONF;
      END IF;
      V_IDOPERDEVONF := w_N;
   ELSE
      IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (NVL(V_IDORIGDESTNF, 'C') <> 'L') THEN
         UPDATE ITEMPRODUTO
         SET VRBRUTITEM   = TRUNC((VRTOTAITEM - VRDESCITEM),2),
             VRCONTITEM   = TRUNC((VRTOTAITEM - VRDESCITEM),2)
         WHERE CDFILIAL   = P_FILIAL   AND
               NRLANCTONF = P_LANCTONF;
      ELSE
         UPDATE ITEMPRODUTO
         SET VRBRUTITEM   = ROUND((VRTOTAITEM - VRDESCITEM),2),
             VRCONTITEM   = ROUND((VRTOTAITEM - VRDESCITEM),2)
         WHERE CDFILIAL   = P_FILIAL   AND
               NRLANCTONF = P_LANCTONF;
      END IF;
      SELECT COUNT(*)
      INTO   V_COUNT
      FROM ITEMNOTAFISC
      WHERE CDFILIAL   = P_FILIAL AND
            NRLANCTONF = P_LANCTONF;
      V_IDDEVOLIST := w_N; /*SE O DOCUMENTO DE ORIGEM E DE LISTA OU NAO*/
      IF (V_COUNT > 1) THEN
         V_IDDEVOLIST := w_S;
      END IF;
      IF (V_COUNT = 0) THEN
         V_IDOPERDEVONF := w_N;
         IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (NVL(V_IDORIGDESTNF, 'C') <> 'L') THEN
            UPDATE ITEMPRODUTO
            SET VRBRUTITEM   = TRUNC((VRTOTAITEM - VRDESCITEM),2),
                VRCONTITEM   = TRUNC((VRTOTAITEM - VRDESCITEM),2)
            WHERE CDFILIAL   = P_FILIAL   AND
                  NRLANCTONF = P_LANCTONF;
         ELSE
            UPDATE ITEMPRODUTO
            SET VRBRUTITEM   = ROUND((VRTOTAITEM - VRDESCITEM),2),
                VRCONTITEM   = ROUND((VRTOTAITEM - VRDESCITEM),2)
            WHERE CDFILIAL   = P_FILIAL   AND
                  NRLANCTONF = P_LANCTONF;
         END IF;
      ELSE
         V_IDOPERDEVONF := w_S;
         IF (P_TIPOOPER = '03') OR (P_TIPOOPER = '05') OR (P_TIPOOPER = '11') THEN
            V_IDOPERDEVONF := w_N;
         END IF;
      END IF;
   END IF;
   DELETE 
     FROM DETESPCOMBNFE
    WHERE CDFILIAL = P_FILIAL
      AND NRLANCTONF = P_LANCTONF;
   /* GRAVA INFORMACOES ADICIONAIS DO PRODUTO */
   V_IDPRODPERIG := 'N';
   FOR C_ITEMPRODINF IN (SELECT I.NRSEQITPROD,
                             P.IDPRODPERIG,
                             TRANSLATE(P.DSINFADICPROD,  'SZszYACEIOUAEIOUAEIOUAOEUEIOENYaaceiouaeiouaeiouaoeueioenyy',
                                                         'SZszYACEIOUAEIOUAEIOUAOEUIONYaaceiouaeiouaeiouaoeuionyy') AS DSINFADICPROD,
                             I.CDPRODUTO,
                             TRANSLATE(INF.NRONU,         'SZszYACEIOUAEIOUAEIOUAOEUEIOENYaaceiouaeiouaeiouaoeueioenyy',
                                                          'SZszYACEIOUAEIOUAEIOUAOEUIONYaaceiouaeiouaeiouaoeuionyy') AS NRONU,
                             TRANSLATE(INF.NRRISCO,       'SZszYACEIOUAEIOUAEIOUAOEUEIOENYaaceiouaeiouaeiouaoeueioenyy',
                                                          'SZszYACEIOUAEIOUAEIOUAOEUIONYaaceiouaeiouaeiouaoeuionyy') AS NRRISCO,
                             TRANSLATE(G.NMGRUPO,         'SZszYACEIOUAEIOUAEIOUAOEUEIOENYaaceiouaeiouaeiouaoeueioenyy',
                                                          'SZszYACEIOUAEIOUAEIOUAOEUIONYaaceiouaeiouaeiouaoeuionyy') AS NMGRUPO,
                             TRANSLATE(INF.NRREGISTROANP, 'SZszYACEIOUAEIOUAEIOUAOEUEIOENYaaceiouaeiouaeiouaoeueioenyy',
                                                          'SZszYACEIOUAEIOUAEIOUAOEUIONYaaceiouaeiouaeiouaoeuionyy') AS NRREGISTROANP,
                             TRANSLATE(INF.DSREGISTROANP, 'SZszYACEIOUAEIOUAEIOUAOEUEIOENYaaceiouaeiouaeiouaoeueioenyy',
                                                          'SZszYACEIOUAEIOUAEIOUAOEUIONYaaceiouaeiouaeiouaoeuionyy') AS DSREGISTROANP,
                             TRANSLATE(INF.NMTECNICO,     'SZszYACEIOUAEIOUAEIOUAOEUEIOENYaaceiouaeiouaeiouaoeueioenyy',
                                                          'SZszYACEIOUAEIOUAEIOUAOEUIONYaaceiouaeiouaeiouaoeuionyy') AS NMTECNICO,
                             TRANSLATE(I.DSINFADICPROD,   'SZszYACEIOUAEIOUAEIOUAOEUEIOENYaaceiouaeiouaeiouaoeueioenyy',
                                                          'SZszYACEIOUAEIOUAEIOUAOEUIONYaaceiouaeiouaeiouaoeuionyy') AS DSINFADICPRODITEM
                        FROM ITEMPRODUTO I LEFT JOIN PRODUTO P ON (I.CDPRODUTO = P.CDPRODUTO)
                                           LEFT JOIN INFADICPROD INF ON (P.CDPRODUTO = INF.CDPRODUTO)
                                           LEFT JOIN GREMBALAGEM G ON (INF.CDGREMBALAGEM = G.CDGRUPO)
                       WHERE I.CDFILIAL = P_FILIAL
                         AND I.NRLANCTONF = P_LANCTONF)
   LOOP
      V_DSINFADICPROD := C_ITEMPRODINF.DSINFADICPRODITEM;
      IF (C_ITEMPRODINF.NRONU IS NOT NULL) OR (TRIM(C_ITEMPRODINF.NRONU) <> '') THEN
         IF (NVL(INSTR(V_DSINFADICPROD, C_ITEMPRODINF.NRONU) = 0, TRUE)) THEN
            V_DSINFADICPROD := 'ONU: ' || C_ITEMPRODINF.NRONU || ' | ' ;
         END IF;
      END IF;
      IF (C_ITEMPRODINF.NMTECNICO IS NOT NULL) OR (TRIM(C_ITEMPRODINF.NMTECNICO) <> '') THEN
         IF (NVL(INSTR(V_DSINFADICPROD, C_ITEMPRODINF.NMTECNICO) = 0, TRUE)) THEN
            V_DSINFADICPROD := V_DSINFADICPROD || 'Nome para Embarque: ' || C_ITEMPRODINF.NMTECNICO || ' | ' ;
         END IF;
      END IF;
      IF (C_ITEMPRODINF.NRRISCO IS NOT NULL) OR (TRIM(C_ITEMPRODINF.NRRISCO) <> '') THEN
         IF (NVL(INSTR(V_DSINFADICPROD, C_ITEMPRODINF.NRRISCO) = 0, TRUE)) THEN
            V_DSINFADICPROD := V_DSINFADICPROD || 'Classe de Risco: ' || C_ITEMPRODINF.NRRISCO || ' | ' ;
         END IF;
      END IF;
      IF (C_ITEMPRODINF.NMGRUPO IS NOT NULL) OR (TRIM(C_ITEMPRODINF.NMGRUPO) <> '') THEN
         IF (NVL(INSTR(V_DSINFADICPROD, C_ITEMPRODINF.NMGRUPO) = 0, TRUE)) THEN
            V_DSINFADICPROD := V_DSINFADICPROD || 'Grupo de Embalagem: ' || C_ITEMPRODINF.NMGRUPO || ' | ' ;
         END IF;
      END IF;
      IF (C_ITEMPRODINF.IDPRODPERIG = 'N') OR (C_ITEMPRODINF.IDPRODPERIG IS NULL) THEN
         V_DSINFADICPROD := '';
      END IF;	  
      IF (C_ITEMPRODINF.DSINFADICPROD IS NOT NULL) OR (TRIM(C_ITEMPRODINF.DSINFADICPROD) <> '') THEN
         IF (NVL(INSTR(V_DSINFADICPROD, C_ITEMPRODINF.DSINFADICPROD) = 0, TRUE)) THEN
            V_DSINFADICPROD := V_DSINFADICPROD || ' ' || C_ITEMPRODINF.DSINFADICPROD || ' | ' ;
         END IF;
      END IF;
      --ESSA CONDICAO FOI COLOCADA APENAS PARA TIRAR O  |  NO FINAL DA VARIAVEL
      IF (V_DSINFADICPROD IS NOT NULL) OR (TRIM(V_DSINFADICPROD) <> '') THEN
         IF (TRIM(SUBSTR(V_DSINFADICPROD, LENGTH(V_DSINFADICPROD)- 2, 3)) = '|') THEN
            V_DSINFADICPROD := TRIM(SUBSTR(V_DSINFADICPROD, 1, LENGTH(V_DSINFADICPROD) - 3));
         END IF;
      END IF;
      UPDATE ITEMPRODUTO
         SET DSINFADICPROD = V_DSINFADICPROD
       WHERE CDFILIAL = P_FILIAL
         AND NRLANCTONF = P_LANCTONF
         AND NRSEQITPROD = C_ITEMPRODINF.NRSEQITPROD;
      IF C_ITEMPRODINF.NRREGISTROANP IS NOT NULL THEN
         INSERT INTO DETESPCOMBNFE
            (CDFILIAL, NRLANCTONF, NRSEQITPROD, CDPAIS, 
             SGESTADO, CDPRODANP, DSPRODANP)
         VALUES
            (P_FILIAL, P_LANCTONF, C_ITEMPRODINF.NRSEQITPROD, V_PAISORIG, 
             V_ESTAORIG, SUBSTR(C_ITEMPRODINF.NRREGISTROANP, 1, 9), SUBSTR(C_ITEMPRODINF.DSREGISTROANP, 1, 255));
      END IF;
      IF C_ITEMPRODINF.IDPRODPERIG = 'S' THEN
         V_IDPRODPERIG := 'S';
      END IF;
   END LOOP;
   /* GRAVA MENSAGEM REFERENTE A PRODUTO PERIGOSO */
   IF V_IDPRODPERIG = 'S' THEN
      V_MSGPRODPERIG := 'Declaro que os produtos perigosos estao adequadamente ' ||
                        'classificados, embalados, identificados, e estivados ' ||
                        'para suportar os riscos das operacoes de transporte e ' ||
                        'que atendem as exigencias da regulamentacao.';
      BEGIN
         SELECT COUNT(DSDADOADIC)
           INTO V_GRAVAMSGPRODPERIG
           FROM DADOSADIC
          WHERE (CDFILIAL = P_FILIAL)
            AND (NRLANCTONF = P_LANCTONF)
            AND (DSDADOADIC LIKE SUBSTR(V_MSGPRODPERIG, 1, LENGTH(V_MSGPRODPERIG) - 19) || '%');
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_GRAVAMSGPRODPERIG := 0;
      END;
      IF (V_GRAVAMSGPRODPERIG = 0) THEN
         INSERT INTO DADOSADIC(CDFILIAL, NRLANCTONF, NRDADOADIC, CDMENSAGEM, DSDADOADIC)
                        VALUES(P_FILIAL, P_LANCTONF, V_DADOADIC, NULL, V_MSGPRODPERIG);
         V_DADOADIC := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_DADOADIC) + 1)),3,0);
      END IF;
   End If;
   DELETE FROM DADOSADIC
    WHERE CDFILIAL = P_FILIAL
      AND NRLANCTONF = P_LANCTONF
      AND DSDADOADIC LIKE 'ICMS retido anteriormente por substituicao tributaria: BC %';
   DELETE FROM DADOSADIC
     WHERE CDFILIAL = P_FILIAL
       AND NRLANCTONF = P_LANCTONF
       AND DSDADOADIC LIKE 'Permite o aproveitamento do credito do ICMS no valor de R$ %';
-- ATUALIZACAO DAS TABELAS DE NOTAFISCAL, ITEMPRODUTO E DADOS ADICIONAIS
   IF NOT(P_TIPOOPER IN ('03','07','09','10','12')) AND (V_IDOPERDEVONF <> w_S) AND (V_IDNFAJUSTE <> w_S) OR (V_IDDEVOLIST = w_S) THEN
   /*AS NOTAS QUE NAO UTILIZAM DOCUMENTO DE ORIGEM*/
      FOR C_ITEMPRODUTO IN (SELECT VRTOTAITEM, VRDESCITEM, IT.CDPRODUTO, NRSEQITPROD,
                                   CDCSTINFUSU, CDCFOPINFUSU, CDSUFXINFUSU, P.CDARVPROD,
                                   IT.QTITEMPROD, IT.IDORIGEMPROD, IT.VRUNITITEM, NVL(IDPRODBONIF , 'N') AS IDPRODBONIF 
                            FROM ITEMPRODUTO IT, PRODUTO P
                            WHERE IT.CDFILIAL   = P_FILIAL   AND
                                  IT.NRLANCTONF = P_LANCTONF AND
                                  IT.CDPRODUTO  = P.CDPRODUTO) LOOP
         V_LIQUIITEM := C_ITEMPRODUTO.VRTOTAITEM - C_ITEMPRODUTO.VRDESCITEM;
         /*VERIFICA O CST POR ITEM*/
         IF (C_ITEMPRODUTO.IDPRODBONIF = 'N') OR (V_CDTIPOOPERBONIF = 'N') THEN
            CONSULTA_CST(w_S, P_EMPRESA, C_ITEMPRODUTO.CDARVPROD, P_INSCESTA, P_TIPOOPER, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC, V_IDINTEREST, V_IDINTERNA, NULL, C_ITEMPRODUTO.IDORIGEMPROD);
         ELSE
            CONSULTA_CST(w_S, P_EMPRESA, C_ITEMPRODUTO.CDARVPROD, P_INSCESTA, V_CDTIPOOPERBONIF, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC, V_IDINTEREST, V_IDINTERNA, NULL, C_ITEMPRODUTO.IDORIGEMPROD);
         END IF;
         FOR C_CSTTEMP IN (SELECT DSMENSCSTTMP
                           FROM CSTTEMP
                           WHERE (NRCSTTEMP = V_CSTTEMP)    AND
                                 (DSMENSCSTTMP IS NOT NULL) AND
                                 (NOT EXISTS(SELECT DSDADOADIC
                                             FROM DADOSADIC
                                             WHERE (CDFILIAL   = P_FILIAL)   AND
                                                   (NRLANCTONF = P_LANCTONF) AND
                                                   (DSDADOADIC LIKE CSTTEMP.DSMENSCSTTMP || '%')))) LOOP
            IF NOT (C_CSTTEMP.DSMENSCSTTMP IS NULL) THEN
               /*PREENCHE AS MENSAGENS ATRELADAS AO CST*/
               INSERT INTO DADOSADIC(CDFILIAL, NRLANCTONF, NRDADOADIC, DSDADOADIC)
               VALUES(P_FILIAL, P_LANCTONF, V_DADOADIC, C_CSTTEMP.DSMENSCSTTMP);
               V_DADOADIC := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_DADOADIC) + 1)),3,0);
            END IF;
         END LOOP;
         IF V_PAISORIG = V_PAISCFOP THEN
            IF V_ESTAORIG = V_ESTACFOP THEN
               V_CFOP1DIGT := '5';
            ELSE
               V_CFOP1DIGT := '6';
            END IF;
         ELSE
            V_CFOP1DIGT := '7';
         END IF;
         /*VERIFICA CFOP POR ITEM*/
         IF (C_ITEMPRODUTO.IDPRODBONIF = 'N') OR (V_CDTIPOOPERBONIF = 'N') THEN
            CONSULTA_CFOP(w_S, P_EMPRESA, C_ITEMPRODUTO.CDARVPROD, P_INSCESTA, P_TIPOOPER, V_PAISORIG,
                           V_ESTAORIG, V_PAISCFOP, V_ESTACFOP, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC, P_INIVALID, C_ITEMPRODUTO.IDORIGEMPROD );
         ELSE
            CONSULTA_CFOP(w_S, P_EMPRESA, C_ITEMPRODUTO.CDARVPROD, P_INSCESTA, V_CDTIPOOPERBONIF, V_PAISORIG,
                           V_ESTAORIG, V_PAISCFOP, V_ESTACFOP, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC, P_INIVALID, C_ITEMPRODUTO.IDORIGEMPROD );
         END IF;
         FOR C_CFOPTEMP IN (SELECT DSMENSCFOTMP
                            FROM CFOPTEMP
                            WHERE (NRCFOPTEMP = V_CFOPTEMP)  AND
                                  (DSMENSCFOTMP IS NOT NULL) AND
                                  (NOT EXISTS(SELECT DSDADOADIC
                                              FROM DADOSADIC
                                              WHERE (CDFILIAL   = P_FILIAL)   AND
                                                    (NRLANCTONF = P_LANCTONF) AND
                                                    (DSDADOADIC LIKE CFOPTEMP.DSMENSCFOTMP || '%')))) LOOP
            IF NOT (C_CFOPTEMP.DSMENSCFOTMP IS NULL) THEN
               /*PREENCHE AS MENSAGENS ATRELADAS AO CFOP*/
               INSERT INTO DADOSADIC(CDFILIAL, NRLANCTONF, NRDADOADIC, DSDADOADIC)
                              VALUES(P_FILIAL, P_LANCTONF, V_DADOADIC, C_CFOPTEMP.DSMENSCFOTMP);
               V_DADOADIC := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_DADOADIC) + 1)),3,0);
            END IF;
         END LOOP;
         V_CFOPINFUSU := 'N';         
         IF C_ITEMPRODUTO.CDCFOPINFUSU IS NULL THEN /*SE NAO HOUVER CFOP INFORMADO PELO USUARIO PARA O PRODUTO*/
            /*SE A DESCRICAO DO CFOP NAO TIVER SIDO INFORMADA PELO USUARIO O SISTEMA ASSUME A DESCRICAO DO CFOP DOS ITENS*/
            UPDATE NOTAFISCAL
               SET DSCDFISOPENF = (SELECT MAX(DSCFOPTMP) FROM CFOPTEMP
                                  WHERE NRCFOPTEMP = V_CFOPTEMP)
            WHERE CDFILIAL   = P_FILIAL   AND
                  NRLANCTONF = P_LANCTONF;
            SELECT MAX(CDFISOPETMP), MAX(CDSUFCFOPTMP), SUBSTR(MAX(DSCFOPTMP),1,50)
            INTO   V_FISOPEITEM    , V_SUFXCFOPPR, V_DSCDFISOPEIT
            FROM CFOPTEMP
            WHERE NRCFOPTEMP = V_CFOPTEMP;
            SELECT MAX(CDSITTRIBTMP)
            INTO   V_SITUTRIBPR
            FROM CSTTEMP
            WHERE NRCSTTEMP = V_CSTTEMP;
         ELSE /*SE HOUVER CFOP INFORMADO PELO USUARIO PARA O PRODUTO*/
            V_CFOPINFUSU := 'S';
            V_FISOPEITEM := C_ITEMPRODUTO.CDCFOPINFUSU;
            V_SUFXCFOPPR := C_ITEMPRODUTO.CDSUFXINFUSU;
            V_SITUTRIBPR := C_ITEMPRODUTO.CDCSTINFUSU;
         END IF;
         IF V_IDDOCREPLIC IS NOT NULL THEN /*SE A NF FOI REPLICADA*/
            IF LENGTH(V_SITUTRIBPR) = 3 THEN
               V_SITUTRIBPR := SUBSTR(V_SITUTRIBPR,1,1) || w_90;
            ELSE
               V_SITUTRIBPR := w_90;
            END IF;
         END IF;
         /*VERIFICA CSOSN POR IMPOSTO*/
         IF (C_ITEMPRODUTO.IDPRODBONIF = 'N') OR (V_CDTIPOOPERBONIF = 'N') THEN
            CONSULTA_CSOSN('S', P_EMPRESA, C_ITEMPRODUTO.CDARVPROD, P_INSCESTA, P_TIPOOPER, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC, V_IDINTEREST, V_CDFISCOPERSN);
         ELSE
            CONSULTA_CSOSN('S', P_EMPRESA, C_ITEMPRODUTO.CDARVPROD, P_INSCESTA, V_CDTIPOOPERBONIF, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC, V_IDINTEREST, V_CDFISCOPERSN);
         END IF;
         UPDATE ITEMPRODUTO
         SET CDFISOPEITEM  = V_FISOPEITEM,
             CDSUFXCFOPPR  = V_SUFXCFOPPR,
             CDSITUTRIBPR  = V_SITUTRIBPR,
             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;
         DELETE CSTTEMP
         WHERE NRCSTTEMP = V_CSTTEMP;
   -- ATUALIZACAO DA TABELA DE IMPOSTOS POR ITEM.
         DELETE ITEMPROIMPOS
         WHERE (CDFILIAL    = P_FILIAL)   AND
               (NRLANCTONF  = P_LANCTONF) AND
               (NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD);
         DELETE ITEMPROIMPOSORIG
         WHERE (CDFILIAL    = P_FILIAL)   AND
               (NRLANCTONF  = P_LANCTONF) AND
               (NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD);
         SELECT COUNT(*)
         INTO   V_IMPOSINFUSU
         FROM IMPOSINFUSU
         WHERE (CDFILIAL    = P_FILIAL)   AND
               (NRLANCTONF  = P_LANCTONF) AND
               (NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD);
         IF V_IMPOSINFUSU = 0 THEN
         -- Verifica se ha grupo fiscal por servico
            SELECT MAX(CDGRUPOFISC)
            INTO V_CDGRPFISCSV
            FROM SERVCLIE SC, SERVICO S
            WHERE SC.CDFILIAL   = V_CDFILIEMIT AND
                  SC.CDCLIENTE  = P_CLIENTE    AND
                  SC.CDFILIAL   = S.CDFILIAL   AND
                  SC.CDSERVFILI = S.CDSERVFILI AND
                  S.CDPRODUTO   = C_ITEMPRODUTO.CDPRODUTO;
            IF V_CDGRPFISCSV IS NULL THEN
               -- Verifica se ha grupo fiscal por cliente da filial
               SELECT MAX(CDGRUPOFISC)
               INTO V_CDGRPFISCSV
               FROM CLIENFILIAL
               WHERE CDFILIAL   = V_CDFILIEMIT AND
                     CDCLIENTE  = P_CLIENTE;
            END IF;
            IF (C_ITEMPRODUTO.IDPRODBONIF = 'N') OR (V_CDTIPOOPERBONIF = 'N') THEN
                  CONSULTA_INCIDENCIA(w_S, 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);
            ELSE
               CONSULTA_INCIDENCIA(w_S, P_EMPRESA, C_ITEMPRODUTO.CDARVPROD, P_INSCESTA, V_CDTIPOOPERBONIF, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC, V_CDGRPFISCSV,
                                      V_IDINTEREST, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, C_ITEMPRODUTO.IDORIGEMPROD);
            END IF;
            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 (CDIMPOTEMP) AS CDIMPOTEMP, CDFISCTEMP, IDTRATIMPTMP, IDUTMUNIORIG,
                                        IDCONSISTENT, IDIMPORECUP, IDUTVLRQTDEIMPO, CDDETALHEPROD,
                                        CDREGRATMP, IP.CDIMPOSTONFE, IT.CDENQLEGALIPI, IT.CDCEST,
                                        IT.VRADICALIQFECP, IP.IDDESONERAIMPO, IP.CDIMPOBASERET, IP.IDDESCRFONTE
                                 FROM INCITEMP IT, IMPOSTO IP
                                 WHERE (IT.NRINCITEMP = V_INCITEMP)    AND
                                       (IP.CDIMPOSTO  = IT.CDIMPOTEMP) AND
                                       (IP.IDPRODNOTA = w_P)
                                 ORDER BY CDIMPOTEMP) LOOP
               -- Se o imposto e retido (valor NF) e se utiliza o valor de outro imposto como base de calculo
               IF ((C_INCIDENCIA.IDTRATIMPTMP = 'R') AND (C_INCIDENCIA.CDIMPOBASERET IS NOT NULL)) THEN
                  V_VRIMPORELAC := 0;
                  SELECT NVL(MAX(VRIMPOSTOIT),0)
                    INTO V_VRIMPORELAC
                    FROM ITEMPROIMPOS
                   WHERE CDFILIAL     = P_FILIAL
                     AND NRLANCTONF   = P_LANCTONF
                     AND NRSEQITPROD  = C_ITEMPRODUTO.NRSEQITPROD
                     AND CDIMPOSTO    = C_INCIDENCIA.CDIMPOBASERET
                     AND NRITPROIMPOS = W_1;
                  IF V_VRIMPORELAC <> 0 THEN
                     V_LIQUIITEM := V_VRIMPORELAC;
                  END IF;
               ELSE
                  V_LIQUIITEM := C_ITEMPRODUTO.VRTOTAITEM - C_ITEMPRODUTO.VRDESCITEM;   
               END IF;
               V_ALIQUTMP := 0;
               V_SIMPLES  := 'N';
               V_UTIBB    := 'N';
               V_VRADICALIQFECP := C_INCIDENCIA.VRADICALIQFECP;
               V_CDBENEFFISCAL := NULL;
--integracao fiscal especifica com Compass_Argentina atraves da importacao de aliquota do imposto IBB
--A aliquota de imposto 03(ibb) sera cadastrada na tabela paramintegraibb e tera prioridade sobre o
-- cadastro de aliquota realizado em sistema
               IF C_INCIDENCIA.CDIMPOTEMP = '03' THEN
                  IF V_IDORIGDESTNF = 'C' THEN
                     V_ALIQUTMP := 0;
                     V_DTVINGENTE := NVL(V_DTINIREFEFAT, P_INIVALID);
                     SELECT NVL(MAX(VRALIQUOTAIBB),NULL)
                     INTO   V_ALIQUTMP
                     FROM PARAMINTEGRAIBB
                     WHERE CDCLIENTE = P_CLIENTE AND
                           V_DTVINGENTE BETWEEN DTVIGINICIALIBB AND DTVIGFINALIBB;
                     IF V_ALIQUTMP IS NOT NULL THEN
                        V_NRALIQTEMP   := 0;
                        V_PARDEDTMP    := 0;
                        V_PREDBCTMP    := 0;
                        V_TRATIMPST    := w_0;
                        V_PBCSUBTRIB   := 0;
                        V_IDPMCBASECAL := 'N';
                        V_UTIBB        := 'S';
                     END IF;
                  END IF;
               END IF;
               /*VERIFICA CST POR IMPOSTO*/
               V_IMPOICMS := NULL;
               V_CDGRUPOFISCAUX := NULL;
               SELECT MAX(G.CDGRUPOFISC)
                 INTO V_CDGRUPOFISCAUX
                 FROM GRUPOFISCIMPFIL G,
                      (SELECT 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 = 'C' THEN
                  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;
               ELSE
                  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;
               END IF;
               IF V_CDGRUPOFISCAUX IS NULL THEN
                  IF (C_ITEMPRODUTO.IDPRODBONIF = 'N') OR (V_CDTIPOOPERBONIF = 'N') THEN
                     CONSULTA_CST_NFE(w_S, P_EMPRESA, C_ITEMPRODUTO.CDARVPROD, P_INSCESTA, P_TIPOOPER, V_CDGRUPOFISC,C_INCIDENCIA.CDIMPOTEMP, V_IDINTEREST, V_IDINTERNA, P_FILIAL, P_LANCTONF, '', V_CDSITTRIBTMP, V_IDMODBCNFE, V_IDMODBCSTNFE, V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, V_IDMOTIDESSTNFE, C_ITEMPRODUTO.IDORIGEMPROD);
                  ELSE
                     CONSULTA_CST_NFE(w_S, P_EMPRESA, C_ITEMPRODUTO.CDARVPROD, P_INSCESTA, V_CDTIPOOPERBONIF, V_CDGRUPOFISC,C_INCIDENCIA.CDIMPOTEMP, V_IDINTEREST, V_IDINTERNA, P_FILIAL, P_LANCTONF, '', V_CDSITTRIBTMP, V_IDMODBCNFE, V_IDMODBCSTNFE, V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, V_IDMOTIDESSTNFE, C_ITEMPRODUTO.IDORIGEMPROD);
                  END IF;
               ELSE
                  IF (C_ITEMPRODUTO.IDPRODBONIF = 'N') OR (V_CDTIPOOPERBONIF = 'N') THEN
                     CONSULTA_CST_NFE(w_S, P_EMPRESA, C_ITEMPRODUTO.CDARVPROD, P_INSCESTA, P_TIPOOPER, V_CDGRUPOFISCAUX,C_INCIDENCIA.CDIMPOTEMP, V_IDINTEREST, V_IDINTERNA, P_FILIAL, P_LANCTONF, '', V_CDSITTRIBTMP, V_IDMODBCNFE, V_IDMODBCSTNFE, V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, V_IDMOTIDESSTNFE, C_ITEMPRODUTO.IDORIGEMPROD);
                  ELSE
                     CONSULTA_CST_NFE(w_S, P_EMPRESA, C_ITEMPRODUTO.CDARVPROD, P_INSCESTA, V_CDTIPOOPERBONIF, V_CDGRUPOFISCAUX,C_INCIDENCIA.CDIMPOTEMP, V_IDINTEREST, V_IDINTERNA, P_FILIAL, P_LANCTONF, '', V_CDSITTRIBTMP, V_IDMODBCNFE, V_IDMODBCSTNFE, V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, V_IDMOTIDESSTNFE, C_ITEMPRODUTO.IDORIGEMPROD);
                  END IF;
               END IF;
               V_CDSIMPLESNACIONAL := NULL;
               V_CDFAIXA := NULL;
               V_BCICMSSTRETIDO := 0;
               V_VRICMSSTRETIDO := 0;
               V_CDREGRAITALIQ  := NULL;
               /*SIMPLES NACIONAL*/
               IF (V_CDSITUCRT <> '3') THEN
                  CALCULA_ALIQUOTA_SN(P_EMPRESA, 
                                      P_TIPOOPER, 
                                      P_INIVALID, 
                                      SUBSTR(V_FISOPEITEM, 2, 3), 
                                      C_INCIDENCIA.CDIMPOSTONFE, 
                                      V_VRSUBLIMITESN,
                                      'N',
                                      V_RBT12,
                                      V_RBA,
                                      V_CDSIMPLESNACIONAL,
                                      V_CDFAIXA,
                                      V_VRALIQSIMPLES);
                  IF (V_CDFAIXA IS NOT NULL) OR ((C_INCIDENCIA.CDIMPOSTONFE IN ('00', '31')) AND (V_RBT12 >= 3600000)) THEN
                     UPDATE ITEMPRODUTO
                        SET CDSIMPLESNACIONAL = V_CDSIMPLESNACIONAL
                      WHERE CDFILIAL    = P_FILIAL
                        AND NRLANCTONF  = P_LANCTONF
                        AND NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;
                     V_ALIQUTMP      := V_VRALIQSIMPLES;
                     V_CDREGRAITALIQ := C_INCIDENCIA.CDREGRATMP;
                     V_NRALIQTEMP    := 0;
                     V_PARDEDTMP     := 0;
                     V_PREDBCTMP     := 0;
                     V_TRATIMPST     := w_0;
                     V_PBCSUBTRIB    := 0;
                     V_IDPMCBASECAL  := 'N';
                     V_SIMPLES       := 'S';
                  END IF;
                  IF (V_CDFISCOPERSN = '500') OR (SUBSTR(V_CDFISCOPERSN,2, 3) = '500') THEN
                     V_CDIMPOSICMS  := null;
                     SELECT MAX(CDIMPOSTO)
                       INTO V_CDIMPOSICMS
                       FROM IMPOSTO
                      WHERE CDIMPOSTONFE = '00'
                        AND CDIMPOSTO = C_INCIDENCIA.CDIMPOTEMP;
                     IF V_CDIMPOSICMS IS NOT NULL THEN
                        V_ALIQUTMP := 0;
                     END IF;
                     /*Verifica se o imposto de st (hj o sistema so aceita o icms st)*/
                     /*IMPOSTO DE SUBSTITUICAO TRIBUTARIA*/
                     V_CDIMPOSTRIB  := null;
                     V_IDVRIMPSTRIB := null;
                     FOR C_ICMSST IN (SELECT CDIMPOSTRIB
                                        FROM IMPOSTO
                                       WHERE CDIMPOSTRIB = C_INCIDENCIA.CDIMPOTEMP)
                     LOOP
                        V_CDIMPOSTRIB := V_CDIMPOSTRIB||C_ICMSST.CDIMPOSTRIB||'_';
                     END LOOP;
                     V_BCICMSSTRETIDO := 0;
                     V_VRICMSSTRETIDO := 0;
                     IF V_CDIMPOSTRIB IS NOT NULL THEN
                        IF V_IDUTILLOTE = 'S' THEN
                           SELECT MAX(IDUTCTRLLOTE)
                             INTO V_IDUTCTRLLOTE
                             FROM PRODFILI
                            WHERE CDFILIAL  = V_CDFILIEMIT
                              AND CDPRODUTO = C_ITEMPRODUTO.CDPRODUTO;
                           IF V_IDUTCTRLLOTE = 'S' THEN
                              SELECT MAX(NRLOTEESTQ)
                                INTO V_NRLOTEESTQ
                                FROM ITEMPRODUTO
                               WHERE CDFILIAL    = P_FILIAL
                                 AND NRLANCTONF  = P_LANCTONF
                                 AND NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;
                              V_MEDIA := 0;
                              V_BCICMSSTRETIDO := 0;
                              V_VRICMSSTRETIDO := 0;
                              FOR C_ICMSSTRETIDO IN (SELECT II.CDFILIAL, II.NRLANCTONF, II.NRSEQITPROD, II.CDIMPOSTO,
                                                            ROUND(II.VRBASECALCIT/I.QTITEMPROD,2) AS VRBASE, ROUND(II.VRIMPOSTOIT/I.QTITEMPROD,2) AS VRIMPOSTO
                                                       FROM NOTAFISCAL N, ITEMPRODUTO I, ITEMPROIMPOS II
                                                      WHERE N.CDFILIAL = I.CDFILIAL
                                                        AND N.NRLANCTONF = I.NRLANCTONF
                                                        AND I.CDFILIAL = II.CDFILIAL
                                                        AND I.NRLANCTONF = II.NRLANCTONF
                                                        AND I.NRSEQITPROD = II.NRSEQITPROD
                                                        AND II.NRITPROIMPOS = '1'
                                                        AND N.IDENTRSAIDOP = 'E'
                                                        AND I.CDPRODUTO = C_ITEMPRODUTO.CDPRODUTO
                                                        AND I.NRLOTEESTQ = V_NRLOTEESTQ
                                                        AND N.DTENTRSAID <= P_INIVALID
                                                        AND (INSTR(V_CDIMPOSTRIB,II.CDIMPOSTO||'_') > 0))
                              LOOP
                                  V_MEDIA := V_MEDIA + 1;
                                  V_BCICMSSTRETIDO := V_BCICMSSTRETIDO + C_ICMSSTRETIDO.VRBASE;
                                  V_VRICMSSTRETIDO := V_VRICMSSTRETIDO + C_ICMSSTRETIDO.VRIMPOSTO;
                              END LOOP;
                              IF V_MEDIA > 0 THEN
                                 V_BCICMSSTRETIDO := ROUND(V_BCICMSSTRETIDO/V_MEDIA,2);
                                 V_VRICMSSTRETIDO := ROUND(V_VRICMSSTRETIDO/V_MEDIA,2);
                              ELSE
                                 V_BCICMSSTRETIDO := 0;
                                 V_VRICMSSTRETIDO := 0;
                              END IF;
                              V_BCICMSSTRETIDO := ROUND(V_BCICMSSTRETIDO * C_ITEMPRODUTO.QTITEMPROD,2);
                              V_VRICMSSTRETIDO := ROUND(V_VRICMSSTRETIDO * C_ITEMPRODUTO.QTITEMPROD,2);
                              IF V_BCICMSSTRETIDO <> 0 THEN
                                 SELECT COUNT(*)
                                   INTO V_EXISTDSDADOSADIC
                                   FROM DADOSADIC
                                  WHERE CDFILIAL = P_FILIAL
                                    AND NRLANCTONF = P_LANCTONF
                                    AND DSDADOADIC LIKE 'ICMS retido anteriormente por substituicao tributaria: BC %';
                                 IF V_EXISTDSDADOSADIC = 0 THEN
                                    /*PREENCHE AS MENSAGENS ATRELADAS A INSCRICAO ESTADUAL*/
                                    INSERT INTO DADOSADIC(CDFILIAL, NRLANCTONF, NRDADOADIC, DSDADOADIC)
                                                   VALUES(P_FILIAL, P_LANCTONF, V_DADOADIC, 'ICMS retido anteriormente por substituicao tributaria: BC '||DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(V_BCICMSSTRETIDO, 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(V_BCICMSSTRETIDO, 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(V_BCICMSSTRETIDO, 2), '9999999999999.99')))|| ' Valor '|| DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(V_VRICMSSTRETIDO, 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(V_VRICMSSTRETIDO, 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(V_VRICMSSTRETIDO, 2), '9999999999999.99'))));
                                    V_DADOADIC := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_DADOADIC) + 1)),3,0);
                                 ELSE
                                    UPDATE DADOSADIC
                                       SET DSDADOADIC = 'ICMS retido anteriormente por substituicao tributaria: BC '||DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(V_BCICMSSTRETIDO, 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(V_BCICMSSTRETIDO, 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(V_BCICMSSTRETIDO, 2), '9999999999999.99')))|| ' Valor '|| DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(V_VRICMSSTRETIDO, 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(V_VRICMSSTRETIDO, 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(V_VRICMSSTRETIDO, 2), '9999999999999.99')))
                                      WHERE CDFILIAL = P_FILIAL
                                        AND NRLANCTONF = P_LANCTONF
                                        AND DSDADOADIC LIKE 'ICMS retido anteriormente por substituicao tributaria: BC %';
                                 END IF;
                              END IF;
                           END IF;
                        ELSE
                           V_MEDIA := 0;
                           V_BCICMSSTRETIDO := 0;
                           V_VRICMSSTRETIDO := 0;
                           SELECT MAX(N.DTENTRSAID), MAX(II.CDIMPOSTO), MAX(I.CDPRODUTO),
                                  ROUND(SUM(II.VRBASECALCIT)/SUM(I.QTITEMPROD),2) AS VRBASE, ROUND(SUM(II.VRIMPOSTOIT)/SUM(I.QTITEMPROD),2) AS VRIMPOSTO
                             INTO V_DTENTRSAID, V_CDIMPOSTOI, V_CDPRODUTO, V_BCICMSSTRETIDO, V_VRICMSSTRETIDO
                             FROM NOTAFISCAL N, ITEMPRODUTO I, ITEMPROIMPOS II
                            WHERE N.CDFILIAL = I.CDFILIAL
                              AND N.NRLANCTONF = I.NRLANCTONF
                              AND I.CDFILIAL = II.CDFILIAL
                              AND I.NRLANCTONF = II.NRLANCTONF
                              AND I.NRSEQITPROD = II.NRSEQITPROD
                              AND II.NRITPROIMPOS = '1'
                              AND N.IDENTRSAIDOP = 'E'
                              AND I.CDPRODUTO = C_ITEMPRODUTO.CDPRODUTO
                              AND N.DTENTRSAID <= P_INIVALID
                              AND (INSTR(V_CDIMPOSTRIB,II.CDIMPOSTO||'_') > 0);
                           V_BCICMSSTRETIDO := ROUND(V_BCICMSSTRETIDO * C_ITEMPRODUTO.QTITEMPROD,2);
                           V_VRICMSSTRETIDO := ROUND(V_VRICMSSTRETIDO * C_ITEMPRODUTO.QTITEMPROD,2);
                           IF V_BCICMSSTRETIDO <> 0 THEN
                              SELECT COUNT(*)
                                INTO V_EXISTDSDADOSADIC
                                FROM DADOSADIC
                               WHERE CDFILIAL = P_FILIAL
                                 AND NRLANCTONF = P_LANCTONF
                                 AND DSDADOADIC LIKE 'ICMS retido anteriormente por substituicao tributaria: BC %';
                              IF V_EXISTDSDADOSADIC = 0 THEN
                                 /*PREENCHE AS MENSAGENS ATRELADAS A INSCRICAO ESTADUAL*/
                                 INSERT INTO DADOSADIC(CDFILIAL, NRLANCTONF, NRDADOADIC, DSDADOADIC)
                                                VALUES(P_FILIAL, P_LANCTONF, V_DADOADIC, 'ICMS retido anteriormente por substituicao tributaria: BC '||DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(V_BCICMSSTRETIDO, 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(V_BCICMSSTRETIDO, 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(V_BCICMSSTRETIDO, 2), '9999999999999.99')))|| ' Valor '|| DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(V_VRICMSSTRETIDO, 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(V_VRICMSSTRETIDO, 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(V_VRICMSSTRETIDO, 2), '9999999999999.99'))));
                                 V_DADOADIC := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_DADOADIC) + 1)),3,0);
                              ELSE
                                 UPDATE DADOSADIC
                                    SET DSDADOADIC = 'ICMS retido anteriormente por substituicao tributaria: BC '||DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(V_BCICMSSTRETIDO, 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(V_BCICMSSTRETIDO, 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(V_BCICMSSTRETIDO, 2), '9999999999999.99')))|| ' Valor '|| DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(V_VRICMSSTRETIDO, 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(V_VRICMSSTRETIDO, 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(V_VRICMSSTRETIDO, 2), '9999999999999.99')))
                                  WHERE CDFILIAL = P_FILIAL
                                    AND NRLANCTONF = P_LANCTONF
                                    AND DSDADOADIC LIKE 'ICMS retido anteriormente por substituicao tributaria: BC %';
                              END IF;
                           END IF;
                        END IF;
                     END IF;
                  END IF;
               END IF;
               IF (V_SIMPLES = 'N') OR ((V_SIMPLES = 'S') AND (C_INCIDENCIA.CDIMPOSTONFE = '00') AND (V_RBA > (V_VRSUBLIMITESN * 1.2))) THEN
                  DELETE ALIQTEMP
                   WHERE NRALIQTEMP = V_ALIQTEMP;
                  V_CDSIMPLESNACIONAL := NULL;
                  V_CDFAIXA := NULL;
                  V_VRADICALIQFECP := NULL;
                  IF (V_UTIBB = 'N')  THEN
                     IF C_INCIDENCIA.IDUTMUNIORIG = w_D THEN
                        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_CLIENTE    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_CLIENTE ;
                           END IF;
                           IF (C_ITEMPRODUTO.IDPRODBONIF = 'N') OR (V_CDTIPOOPERBONIF = 'N') THEN
                              CONSULTA_ALIQUOTA(C_INCIDENCIA.CDIMPOTEMP, w_S, 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, NULL, NULL, C_ITEMPRODUTO.IDORIGEMPROD);
                           ELSE
                              CONSULTA_ALIQUOTA(C_INCIDENCIA.CDIMPOTEMP, w_S, 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,V_CDTIPOOPERBONIF,
                                                NULL, NULL, NULL, NULL, NULL, NULL, C_ITEMPRODUTO.IDORIGEMPROD);
                           END IF;
                        ELSE
                            /* CONSIDERA O MUNICIPIO DE DESTINO */
                            IF (C_ITEMPRODUTO.IDPRODBONIF = 'N') OR (V_CDTIPOOPERBONIF = 'N') THEN
                               CONSULTA_ALIQUOTA(C_INCIDENCIA.CDIMPOTEMP, w_S, 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, NULL, NULL, C_ITEMPRODUTO.IDORIGEMPROD);
                            ELSE
                               CONSULTA_ALIQUOTA(C_INCIDENCIA.CDIMPOTEMP, w_S, 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, V_CDTIPOOPERBONIF,
                                                 NULL, NULL, NULL, NULL, NULL, NULL, C_ITEMPRODUTO.IDORIGEMPROD);
                            END IF;
                        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_CLIENTE    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_CLIENTE ;
                           END IF;
                           IF (C_ITEMPRODUTO.IDPRODBONIF = 'N') OR (V_CDTIPOOPERBONIF = 'N') THEN
                              CONSULTA_ALIQUOTA(C_INCIDENCIA.CDIMPOTEMP, w_S, 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, NULL, NULL, C_ITEMPRODUTO.IDORIGEMPROD);
                           ELSE
                              CONSULTA_ALIQUOTA(C_INCIDENCIA.CDIMPOTEMP, w_S, 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, V_CDTIPOOPERBONIF,
                                                NULL, NULL, NULL, NULL, NULL, NULL, C_ITEMPRODUTO.IDORIGEMPROD);
                           END IF;
                        ELSE
                            IF (C_ITEMPRODUTO.IDPRODBONIF = 'N') OR (V_CDTIPOOPERBONIF = 'N') THEN
                               CONSULTA_ALIQUOTA(C_INCIDENCIA.CDIMPOTEMP, w_S, 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, NULL, NULL, C_ITEMPRODUTO.IDORIGEMPROD);
                            ELSE
                               CONSULTA_ALIQUOTA(C_INCIDENCIA.CDIMPOTEMP, w_S, 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, V_CDTIPOOPERBONIF,
                                                 NULL, NULL, NULL, NULL, NULL, NULL, C_ITEMPRODUTO.IDORIGEMPROD);
                            END IF;
                        END IF;
                     END IF;
                     V_NRALIQTEMP      := 0;
                     V_PARDEDTMP       := 0;
                     V_PREDBCTMP       := 0;
                     V_ALIQUTMP        := 0;
                     V_IMPOSTOIT       := 0;
                     V_VRADICALIQFECP  := NULL;
                     V_IDIMPODESONERA  := w_N;
                     V_IDCONSDESONVRNF := w_N;
                     V_IDCONSMVAPMC    := '3';
                     V_IDCONSCOMPBCPMC := '3';
                     SELECT NVL(MAX(NRALIQTEMP),0),
                            NVL(MAX(VRPARDEDTMP),0), 
                            NVL(MAX(VRPREDBCTMP),0),
                            NVL(MAX(VRALIQUTMP),0),
                            NVL(MAX(IDTRIMPSTTMP), W_0),
                            NVL(MAX(VRPBCSTTMP),0),
                            NVL(MAX(IDPMCBSCALTMP), W_S),
                            MAX(CDREGRATMP),
                            MAX(CDFISCOPER),
                            MAX(IDDIFEALIQ),
                            MAX(IDDIFALIQCUSPR),
                            MAX(VRADICALIQFECP),
                            NVL(MAX(IDIMPODESONERA), 'N'),
                            NVL(MAX(IDCONSDESONVRNF), 'N'),
                            MAX(CDBENEFFISCAL),
                            NVL(MAX(IDCONSMVAPMC), '3'),
                            NVL(MAX(IDCONSCOMPBCPMC), '3'),
                            NVL(MAX(IDCONSDIFALIQ), 'N'),
                            MAX(CDCOMPST),
                            MAX(CDRESTST),
                            MAX(CDNATUREC),
                            MAX(VRIMPOSTOREP)
                       INTO V_NRALIQTEMP,
                            V_PARDEDTMP,
                            V_PREDBCTMP,
                            V_ALIQUTMP,
                            V_TRATIMPST,
                            V_PBCSUBTRIB,
                            V_IDPMCBASECAL,
                            V_CDREGRAITALIQ,
                            V_CDFISCOPERREGRA,
                            V_IDDIFEALIQREGRA,
                            V_IDDIFALIQCUSPRREGRA,
                            V_VRADICALIQFECP,
                            V_IDIMPODESONERA,
                            V_IDCONSDESONVRNF,
                            V_CDBENEFFISCAL,
                            V_IDCONSMVAPMC,
                            V_IDCONSCOMPBCPMC,
                            V_IDCONSDIFALIQ,
                            V_CDCOMPST,
                            V_CDRESTST,
                            V_CDNATUREC,
                            V_VRIMPOSTOREP
                       FROM ALIQTEMP
                      WHERE (NRALIQTEMP = V_ALIQTEMP);
                     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)
                     LOOP
                        V_ICMS := 'S';
                     END LOOP;
                     IF V_ICMS = 'S' THEN
                        IF (V_CDFISCOPERREGRA IS NOT NULL) THEN
                           V_CDFISCOPERREGRA   := V_CFOP1DIGT||V_CDFISCOPERREGRA;
                           V_DSCDFISOPEITREGRA := SUBSTR(DESCRICAO_CFOP(V_CDFISCOPERREGRA),1,45);
                           IF V_CFOPINFUSU <> 'S' THEN
                              V_FISOPEITEM := V_CDFISCOPERREGRA;
                           END IF;
                        END IF;
                        IF V_CFOPINFUSU <> 'S' THEN
                           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;
                           END IF;
                        END IF;
                        UPDATE ITEMPRODUTO
                           SET CDFISOPEITEM  = V_FISOPEITEM,
                               CDSUFXCFOPPR  = V_SUFXCFOPPR,
                               CDSITUTRIBPR  = V_SITUTRIBPR,
                               DSCDFISOPEIT  = V_DSCDFISOPEIT,
                               CDFISCOPERSN  = V_CDFISCOPERSN
                         WHERE CDFILIAL    = P_FILIAL AND
                               NRLANCTONF  = P_LANCTONF AND
                               NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;
                     END IF;
                  END IF;
               END IF;
               V_CDIMPOSTRIB  := null;
               V_IDVRIMPSTRIB := null;
               /*IMPOSTO DE SUBSTITUICAO TRIBUTARIA*/
               FOR C_ICMSST IN (SELECT CDIMPOSTO
                                      FROM IMPOSTO
                                     WHERE CDIMPOSTRIB = C_INCIDENCIA.CDIMPOTEMP)
               LOOP
                  V_CDIMPOSTRIB := V_CDIMPOSTRIB||C_ICMSST.CDIMPOSTO||'_';
               END LOOP;
               -- UTILIZA O PROPRIO VALOR DO IMPOSTO NA SUA BASE DE CALCULO (IMPOSTO POR DENTRO)
               BEGIN
                  SELECT NVL(MAX(IDUTILPVRIMPBC), 'N')
                    INTO V_IDUTILPVRIMPBC
                    FROM IMPOSTO
                   WHERE CDIMPOSTO = C_INCIDENCIA.CDIMPOTEMP;
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_IDUTILPVRIMPBC := 'N';
               END;
               V_TAXABASECALC := (100 - V_PREDBCTMP)/100;
               V_TAXAALIQUOTA := (V_ALIQUTMP/100);
               V_TAXABCSUBSTR := 1 + (V_PBCSUBTRIB/100);
               V_BASECALCIT   := V_LIQUIITEM * V_TAXABASECALC;
               IF (V_VRIMPOSTOREP IS NOT NULL) THEN  /* Caso esteja cadastrao Valor a ser Repassado, a base de Calculo e o valor do imposto e calculado de acordo com este cadastro */
                  IF (V_VRIMPOSTOREP > 0) THEN
                     V_IMPOSTOIT  := (C_ITEMPRODUTO.QTITEMPROD * V_VRIMPOSTOREP);
                     V_BASECALCTO := (C_ITEMPRODUTO.VRTOTAITEM * (V_IMPOSTOIT)) / (C_ITEMPRODUTO.VRTOTAITEM * (V_ALIQUTMP/100));
                  END IF;
               ELSE
                  IF V_CDIMPOSTRIB IS NULL THEN
                     V_IDTRIMPSTII := '';
                     V_PERDBCALC := 100 - V_PREDBCTMP;
                     IF V_PBCSUBTRIB > 0 THEN
                        V_BASECALCIT := (V_BASECALCIT * V_TAXABCSUBSTR);
                        V_PREDBCSTIT := V_PREDBCTMP;
                        V_PREDBCTMP  := V_PBCSUBTRIB;
                        V_PERDBCALC  := 0;
                     ELSE
                        V_PREDBCSTIT := V_PREDBCTMP;
                     END IF;
                     IF (C_INCIDENCIA.IDUTVLRQTDEIMPO = 'S') THEN
                        SELECT NVL(MAX(VRFATOCONVES), 1)
                          INTO V_VRFATOCONVES
                          FROM CONVPRODUTO
                         WHERE CDPRODUTO = C_ITEMPRODUTO.CDPRODUTO;
                        V_BASECALCTO  := (C_ITEMPRODUTO.QTITEMPROD * V_VRFATOCONVES);
                        V_IMPOSTOIT   := ((C_ITEMPRODUTO.QTITEMPROD * V_VRFATOCONVES) * V_ALIQUTMP) - V_PARDEDTMP;
                     ELSE
                        V_BASECALCTO  := V_BASECALCIT;
                        V_IMPOSTOIT   := (V_BASECALCIT * V_TAXAALIQUOTA) - V_PARDEDTMP;
                     END IF;
                  ELSE
                     IF V_CDSITUCRT = '1' THEN
                        IF SUBSTR(V_CDFISCOPERSN, 2, 3) = '500' THEN
                           V_IDTRIMPSTII := w_2;
                        ELSE
                           V_IDTRIMPSTII := V_TRATIMPST;
                        END IF;
                     ELSE
                        IF SUBSTR(V_SITUTRIBPR, 2, 2) = '60' THEN  
                           V_IDTRIMPSTII := w_2;
                        ELSE
                           V_IDTRIMPSTII := V_TRATIMPST;
                        END IF;
                     END IF;
                     IF NVL(V_IDPMCBASECAL, W_N) = W_S THEN
                        CALCULA_BC_PMC(P_FILIAL,
                                       P_LANCTONF,
                                       C_ITEMPRODUTO.NRSEQITPROD,
                                       C_INCIDENCIA.CDIMPOTEMP,
                                       V_IDCONSMVAPMC,
                                       V_IDCONSCOMPBCPMC,
                                       V_PAISDEST,
                                       V_ESTADEST,
                                       C_ITEMPRODUTO.CDPRODUTO,
                                       C_ITEMPRODUTO.QTITEMPROD,
                                       C_ITEMPRODUTO.VRUNITITEM,
                                       C_ITEMPRODUTO.VRDESCITEM,
                                       V_PBCSUBTRIB,
                                       V_PREDBCTMP,
                                       NULL,
                                       NULL,
                                       NULL,
                                       NULL,
                                       NULL,
                                       NULL,
                                       'N',
                                       V_BASECALCTO);
                        V_IMPOSTOIT := (V_BASECALCTO * V_TAXAALIQUOTA) - V_PARDEDTMP;
                     ELSIF (V_IDCONSDIFALIQ = 'S') AND (C_INCIDENCIA.CDIMPOSTONFE = '80') THEN
                        CONSIDERA_DIFAL_ICMS(P_FILIAL,
                                             P_LANCTONF,
                                             C_ITEMPRODUTO.NRSEQITPROD,
                                             V_CDGRPFISCSV,
                                             V_PAISDEST,
                                             V_ESTADEST,
                                             V_MUNIDEST,
                                             V_PBCSUBTRIB,
                                             V_PREDBCTMP,
                                             V_BASECALCTO,
                                             V_IMPOSTOIT,
                                             V_VRADICFECP);
                     ELSE
                        UPDATE ITEMPRODUTO
                           SET IDUTILBCPMC = 'N'
                         WHERE CDFILIAL = P_FILIAL
                           AND NRLANCTONF = P_LANCTONF
                           AND NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;
                        V_PERDBCALC := 100 - V_PREDBCTMP;
                        IF V_PBCSUBTRIB > 0 THEN
                           V_BASECALCIT := (V_BASECALCIT * V_TAXABCSUBSTR);
                           V_PREDBCSTIT := V_PREDBCTMP;
                           V_PREDBCTMP  := V_PBCSUBTRIB;
                           V_PERDBCALC  := 0;
                        ELSE
                          V_PREDBCSTIT := V_PREDBCTMP;
                        END IF;
                        V_BASECALCTO  := V_BASECALCIT;
                        V_IMPOSTOIT   := (V_BASECALCIT * V_TAXAALIQUOTA) - V_PARDEDTMP;
                     END IF;
                  END IF;
               END IF;
               V_CONTABCALC  := V_LIQUIITEM - (V_LIQUIITEM * V_TAXABASECALC);
               IF (V_IMPOSTOIT < 0) THEN
                  V_IMPOSTOIT := 0;
               END IF;
               IF (V_IDCONSDIFALIQ = 'N') THEN
                  V_VRADICFECPST := 0;
                  V_VRADICFECPSTAUX := 0;
                  IF (V_VRADICALIQFECP IS NOT NULL) AND (V_VRADICALIQFECP > 0) THEN
                     V_VRADICFECP := ROUND(V_BASECALCTO*(V_VRADICALIQFECP/100), 2);
                  END IF;
                  IF (V_CDIMPOSTRIB IS NOT NULL) THEN
                     V_VRIMPOSST   := 0;
                     V_VRIMPOSTOST := 0;
                     FOR C_SUBSTRIB IN (SELECT NVL(IDVRIMPSTRIB, 'N') IDVRIMPSTRIB, I.CDIMPOSTO
                                          FROM ITEMPROIMPOS I, IMPOSTO II
                                         WHERE (CDFILIAL     = P_FILIAL)
                                           AND (NRLANCTONF   = P_LANCTONF)
                                           AND (NRSEQITPROD  = C_ITEMPRODUTO.NRSEQITPROD)
                                           AND (NRITPROIMPOS = '1')
                                           AND (INSTR(V_CDIMPOSTRIB,II.CDIMPOSTO||'_') > 0)
                                           AND (I.CDIMPOSTO = II.CDIMPOSTO))
                     LOOP
                        IF (C_SUBSTRIB.IDVRIMPSTRIB = w_S) THEN
                           Begin
                              SELECT NVL(ROUND(MAX(VRIMPOSTOIT), 2),0),
                                     NVL(ROUND(MAX(VRADICFECP), 2),0)
                              INTO   V_VRIMPOSST,
                                     V_VRADICFECPSTAUX
                              FROM ITEMPROIMPOS I
                              WHERE (CDFILIAL     = P_FILIAL)                   AND
                                    (NRLANCTONF   = P_LANCTONF)                 AND
                                    (NRSEQITPROD  = C_ITEMPRODUTO.NRSEQITPROD)  AND
                                    (CDIMPOSTO    = C_SUBSTRIB.CDIMPOSTO)       AND
                                    (INSTR(V_CDIMPOSTRIB,CDIMPOSTO||'_') > 0)   AND
                                    (NRITPROIMPOS = w_1);
                           Exception
                              When No_Data_Found Then
                                 V_VRIMPOSST := 0;
                                 V_VRADICFECPSTAUX := 0;
                           End;
                        ELSE
                           V_VRIMPOSST := 0;
                           V_VRADICFECPSTAUX := 0;
                        END IF;
                        V_VRIMPOSTOST := V_VRIMPOSTOST + V_VRIMPOSST;
                        V_VRADICFECPST := V_VRADICFECPST + V_VRADICFECPSTAUX;
                     END LOOP;
                     V_IMPOSTOIT := V_IMPOSTOIT - V_VRIMPOSTOST;
                     IF V_IMPOSTOIT < 0 THEN
                        V_IMPOSTOIT := 0;
                     END IF;
                  END IF;
                  IF (V_VRADICALIQFECP IS NOT NULL) AND (V_VRADICALIQFECP > 0) THEN
                     V_VRADICFECP := V_VRADICFECP - V_VRADICFECPST;
                  END IF;
               END IF;
               /* Rotina para calcular o ICMS ST considerando % carga tributaria media */
               V_IDIMPSTCARGTRIB := 'N';
               IF V_CDIMPOSTRIB IS NOT NULL THEN
                  BEGIN
                     SELECT NVL(VRCNAEBC, 0),
                            NVL(VRMVA, 0)
                       INTO V_VRPRODUTOBC,
                            V_VRMVA
                       FROM VRPERCCARGTRIBCNAE
                      WHERE IDENTRSAIDOP = w_S
                        AND CDTIPOOPER   = P_TIPOOPER
                        AND CDPAIS       = V_PAISDEST
                        AND SGESTADO     = V_ESTADEST
                        AND CDCNAE       = V_CDCNAECLIE
                        AND IDOPTANTESN  = V_IDOPTANTESNCLIE;
                  EXCEPTION
                     WHEN NO_DATA_FOUND THEN
                        V_VRPRODUTOBC := 0;
                        V_VRMVA := 0;
                  END;
                  IF V_VRPRODUTOBC = 0 THEN
                     BEGIN
                        SELECT NVL(VRPRODUTOBC, 0)
                          INTO V_VRPRODUTOBC
                          FROM VRPERCCARGTRIB
                         WHERE IDENTRSAIDOP = w_S
                           AND CDTIPOOPER   = P_TIPOOPER
                           AND CDPAIS       = V_PAISDEST
                           AND SGESTADO     = V_ESTADEST
                           AND CDPRODUTO    = C_ITEMPRODUTO.CDPRODUTO;
                     EXCEPTION
                        WHEN NO_DATA_FOUND THEN
                           V_VRPRODUTOBC := 0;
                     END;
                  END IF;
                  IF (V_VRPRODUTOBC > 0) THEN
                     BEGIN
                        SELECT I.CDIMPOSTO, I.VRIMPOSTOIT
                          INTO V_CDIMPOSTOICMS, V_VRIMPOSTOICMS
                          FROM IMPOSTONFE N, IMPOSTO P, ITEMPROIMPOS I
                         WHERE N.CDIMPOSTONFE = P.CDIMPOSTONFE
                           AND N.CDIMPOSTONFE = '00'
                           AND I.CDFILIAL     = P_FILIAL
                           AND I.NRLANCTONF   = P_LANCTONF
                           AND I.NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD
                           AND I.CDIMPOSTO = P.CDIMPOSTO
                           AND NOT P.CDIMPOSTRIB IS NULL
                           AND I.NRITPROIMPOS = '1';
                     EXCEPTION
                        When No_Data_Found Then
                           V_CDIMPOSTOICMS := NULL; V_VRIMPOSTOICMS := 0;
                     END;
                     DELETE ALIQTEMP
                      WHERE NRALIQTEMP = V_ALIQTEMP;
                     /* Verifica grupo fiscal */
                     SELECT MAX(IDGRUPFISSRV)
                     INTO V_UTGRUPFISCS
                     FROM IMPOSTO
                     WHERE CDIMPOSTO = V_CDIMPOSTOICMS;
                     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_CLIENTE    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_CLIENTE;
                        END IF;
                        CONSULTA_ALIQUOTA(V_CDIMPOSTOICMS, w_S, 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, NULL, NULL, C_ITEMPRODUTO.IDORIGEMPROD);
                     ELSE
                        CONSULTA_ALIQUOTA(V_CDIMPOSTOICMS, w_S, 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_CDGRUPOFISC, P_TIPOOPER,
                                          NULL, NULL, NULL, NULL, NULL, NULL, C_ITEMPRODUTO.IDORIGEMPROD);
                     END IF;
                     SELECT NVL(MAX(VRALIQUTMP),0)
                       INTO V_VRALIQUTMPDEST
                       FROM ALIQTEMP
                      WHERE (NRALIQTEMP = V_ALIQTEMP);
                     IF (V_VRALIQUTMPDEST <> 0) THEN
                        V_IMPOSTOIT  :=  ROUND(V_BASECALCIT * (V_VRPRODUTOBC/100), 2);
                        V_BASECALCTO :=  ROUND(((V_VRIMPOSTOICMS + V_IMPOSTOIT) / (V_VRALIQUTMPDEST/100)),2);
                        V_IDIMPSTCARGTRIB := 'S';
                     END IF;
                     DELETE ALIQTEMP
                      WHERE NRALIQTEMP = V_ALIQTEMP;
                  END IF;
               END IF;
               /* 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, 'S' 
                          INTO V_VRPERDIFERE, V_IDDIFECLI
                          FROM PRODDIFEREIMPCLI PD, PRODUTO PR
                         WHERE PD.CDPRODUTO = PR.CDPRODUTO
                           AND PD.CDPAIS = V_PAISORIG
                           AND PD.SGESTADO = V_ESTAORIG
                           AND PD.CDCLIENTE = P_CLIENTE
                           AND PR.CDARVPROD IN (SELECT MAX(PR.CDARVPROD) AS CDARVPROD
                                                  FROM PRODDIFEREIMPCLI PD, PRODUTO PR
                                                 WHERE PD.CDPRODUTO = PR.CDPRODUTO
                                                   AND PD.CDPAIS = V_PAISORIG
                                                   AND PD.SGESTADO = V_ESTAORIG
                                                   AND PD.CDCLIENTE = P_CLIENTE
                                                   AND INSTR(NVL(RTRIM(C_ITEMPRODUTO.CDARVPROD), PR.CDARVPROD), PR.CDARVPROD) = 1);
                     EXCEPTION
                        WHEN NO_DATA_FOUND THEN
                           V_VRPERDIFERE := NULL; V_IDDIFECLI := 'N';
                     END;
                     IF V_IDDIFECLI = 'N' 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;
                     END IF;
                     IF V_VRPERDIFERE IS NOT NULL THEN
                        V_PERDIFERE    := ROUND(V_VRPERDIFERE, 2);
                        V_IMPOSTOOPERA := ROUND(V_IMPOSTOIT, 2);
                        /* 
                           Foi comentado este calculo pois ao implementa-lo de acordo com a resolucao n13 de 14 de fevereiro de 2019
                           a sefaz passou a rejeitar as notas com a rejeicao 352 (Rejeicao: Valor do ICMS Diferido no CST=51 difere do 
                           produto Valor ICMS Operacao e percentual diferimento)
                        */
                        --IF (V_CDPAISEMIT = 0055) AND (V_SGESTADOEMIT = RJ) THEN
                        --   V_IMPOSTODIFER := ROUND((((V_BASECALCTO / (1 - V_TAXAALIQUOTA)) * V_TAXAALIQUOTA) * (V_VRPERDIFERE/100)), 2);
                        --ELSE
                           V_IMPOSTODIFER := ROUND((V_IMPOSTOOPERA * (V_VRPERDIFERE/100)), 2);
                        --END IF;
                        V_IMPOSTOIT := ROUND(V_IMPOSTOOPERA, 2) - ROUND(V_IMPOSTODIFER, 2);
                     END IF;
                  END IF;
               END IF;
               V_BASECALCIRRF := V_BASECALCTO;
               IF (V_ALIQUTMP = 0) AND (V_IMPOSTOIT = 0) THEN
                  V_BASECALCTO := 0;
               END IF;
               IF V_IDPERVISIMPSCRE = 'S' THEN
                  V_VRIMPOSTOVISUIT := V_IMPOSTOIT;
               ELSE
                  IF (C_INCIDENCIA.CDFISCTEMP = '1') THEN
                     V_VRIMPOSTOVISUIT := V_IMPOSTOIT;
                  ELSE
                     V_VRIMPOSTOVISUIT := 0;
                  END IF;
               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)
               LOOP
                  V_ICMS := 'S';
               END LOOP;
               Begin
                  SELECT CDFILIAL
                  INTO   V_CHAVE
                  FROM ITEMPROIMPOS
                  WHERE CDFILIAL     = P_FILIAL                 AND
                        NRLANCTONF   = P_LANCTONF               AND
                        NRSEQITPROD  = C_ITEMPRODUTO.NRSEQITPROD  AND
                        CDIMPOSTO    = C_INCIDENCIA.CDIMPOTEMP AND
                        NRITPROIMPOS = w_1;
               Exception
                  When No_Data_Found Then
                     V_CHAVE := Null;
               End;
               IF V_CHAVE IS NULL THEN
                  IF (V_ICMS = 'S') THEN
                     IF C_ITEMPRODUTO.CDCFOPINFUSU IS NULL THEN
                        V_CDGRUPOFISCAUX := NULL;
                        SELECT MAX(G.CDGRUPOFISC)
                          INTO V_CDGRUPOFISCAUX
                          FROM GRUPOFISCIMPFIL G,
                               (SELECT 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 = 'C' THEN
                           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;
                        ELSE
                           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;
                        END IF;
                        IF (V_CDGRUPOFISCAUX IS NOT NULL) THEN
                           IF (C_ITEMPRODUTO.IDPRODBONIF = 'N') OR (V_CDTIPOOPERBONIF = 'N') THEN
                              CONSULTA_CFOP(w_S, P_EMPRESA, C_ITEMPRODUTO.CDARVPROD, P_INSCESTA, P_TIPOOPER, V_PAISORIG,
                                            V_ESTAORIG, V_PAISCFOP, V_ESTACFOP, P_FILIAL, P_LANCTONF, V_CDGRUPOFISCAUX, P_INIVALID, C_ITEMPRODUTO.IDORIGEMPROD);
                           ELSE
                              CONSULTA_CFOP(w_S, P_EMPRESA, C_ITEMPRODUTO.CDARVPROD, P_INSCESTA, V_CDTIPOOPERBONIF, V_PAISORIG,
                                            V_ESTAORIG, V_PAISCFOP, V_ESTACFOP, P_FILIAL, P_LANCTONF, V_CDGRUPOFISCAUX, P_INIVALID, C_ITEMPRODUTO.IDORIGEMPROD);
                           END IF;
                        ELSE
                           IF (C_ITEMPRODUTO.IDPRODBONIF = 'N') OR (V_CDTIPOOPERBONIF = 'N') THEN
                              CONSULTA_CFOP(w_S, P_EMPRESA, C_ITEMPRODUTO.CDARVPROD, P_INSCESTA, P_TIPOOPER, V_PAISORIG,
                                            V_ESTAORIG, V_PAISCFOP, V_ESTACFOP, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC, P_INIVALID, C_ITEMPRODUTO.IDORIGEMPROD);
                           ELSE
                              CONSULTA_CFOP(w_S, P_EMPRESA, C_ITEMPRODUTO.CDARVPROD, P_INSCESTA, V_CDTIPOOPERBONIF, V_PAISORIG,
                                            V_ESTAORIG, V_PAISCFOP, V_ESTACFOP, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC, P_INIVALID, C_ITEMPRODUTO.IDORIGEMPROD);
                           END IF;
                        END IF;
                        IF (V_CDFISCOPERREGRA IS NOT NULL) THEN
                           IF (LENGTH(V_CDFISCOPERREGRA) < 4) THEN
                              V_CDFISCOPERREGRA := V_CFOP1DIGT||V_CDFISCOPERREGRA;
                           END IF;
                           V_DSCDFISOPEITREGRA := SUBSTR(DESCRICAO_CFOP(V_CDFISCOPERREGRA),1,45);
                        END IF;
                        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;
                        END IF;
                        SELECT MAX(CDFISOPETMP), MAX(CDSUFCFOPTMP), SUBSTR(MAX(DSCFOPTMP),1,50)
                          INTO V_FISOPEITEM    , V_SUFXCFOPPR, V_DSCDFISOPEIT
                          FROM CFOPTEMP
                         WHERE NRCFOPTEMP = V_CFOPTEMP;
                        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;
                     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;
                     IF (V_IDUTORIGPROD = 'S') AND (C_ITEMPRODUTO.IDORIGEMPROD = 'E') THEN
                        V_CST1DIGT := '2';
                     END IF;
                     UPDATE ITEMPRODUTO
                        SET CDSITUTRIBPR  = V_CST1DIGT||NVL(V_CDSITTRIBTMP, SUBSTR(V_SITUTRIBPR, 2,2))
                      WHERE CDFILIAL    = P_FILIAL AND
                            NRLANCTONF  = P_LANCTONF AND
                            NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;
                     V_SITUTRIBPR := V_CST1DIGT||NVL(V_CDSITTRIBTMP, SUBSTR(V_SITUTRIBPR, 2,2));
                  END IF;
                  IF (NVL(V_CFOPINFUSU, 'N') <> 'S') AND (V_CDFISCOPERREGRA IS NOT NULL) THEN
                     V_FISOPEITEM := NVL(V_CDFISCOPERREGRA, V_FISOPEITEM);
                     V_DSCDFISOPEITREGRA := SUBSTR(DESCRICAO_CFOP(V_CDFISCOPERREGRA),1,45);
                  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, CDTPCREDPICOITE, CDNATUBCALPCIT, IDMOTDESONERAIT,
                     CDSIMPLESNACIONAL, CDFAIXA, VRBCICMSSTRETIDO, VRICMSSTRETIDO, CDREGRAIT, CDDETALHEPROD,
                     VRIMPOSTOVISUIT, VRBCALCIRRF, VRPERDIFEREIT, VRIMPOSTOOPERAIT, VRIMPOSTODIFERIT,
                     CDENQLEGALIPI, CDCEST, IDIMPSTCARGTRIB, VRADICALIQFECP, VRADICFECP, 
                     VRALIQINTEDEST, VRALIQFCP, IDDESONERAREGRA, IDCONSDESONVRNF, CDBENEFFISCAL,
                     IDCONSDIFALIQ, CDCOMPST, CDRESTST, CDNATUREC, VRPERREDBCSTIT, VRIMPOSTOREP)
                  VALUES(
                     P_FILIAL, P_LANCTONF, C_ITEMPRODUTO.NRSEQITPROD, C_INCIDENCIA.CDIMPOTEMP, w_1, C_INCIDENCIA.CDFISCTEMP,
                     V_SITUTRIBPR, V_FISOPEITEM, V_SUFXCFOPPR, V_ALIQUTMP, V_PREDBCTMP, V_PARDEDTMP,
                     V_BASECALCTO, V_BASECALCTO, V_IMPOSTOIT, w_00000, w_00000, V_IDTRIMPSTII,
                     V_CDSITTRIBTMP, V_IDMODBCNFE, V_IDMODBCSTNFE, V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, V_IDMOTIDESSTNFE,
                     V_CDSIMPLESNACIONAL, V_CDFAIXA, V_BCICMSSTRETIDO, V_VRICMSSTRETIDO, V_CDREGRAITALIQ, C_INCIDENCIA.CDDETALHEPROD,
                     V_VRIMPOSTOVISUIT, V_BASECALCIRRF, V_PERDIFERE, V_IMPOSTOOPERA, V_IMPOSTODIFER,
                     C_INCIDENCIA.CDENQLEGALIPI, C_INCIDENCIA.CDCEST, V_IDIMPSTCARGTRIB, V_VRADICALIQFECP, V_VRADICFECP,
                     V_ALIQICMSDEST, V_ALIQFECPDEST, NVL(V_IDIMPODESONERA, 'N'), NVL(V_IDCONSDESONVRNF, 'N'), V_CDBENEFFISCAL,
                     NVL(V_IDCONSDIFALIQ, 'N'), V_CDCOMPST, V_CDRESTST, V_CDNATUREC, V_PREDBCSTIT, V_VRIMPOSTOREP);
                  IF (V_PREDBCTMP > 0) AND (V_PBCSUBTRIB = 0) THEN
                     IF V_SITUTRIBPR = '060' 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, CDSIMPLESNACIONAL,
                           CDFAIXA, VRBCICMSSTRETIDO, VRICMSSTRETIDO, CDREGRAIT, CDDETALHEPROD,
                           VRIMPOSTOVISUIT, CDENQLEGALIPI, CDCEST, IDIMPSTCARGTRIB)
                        VALUES(
                           P_FILIAL, P_LANCTONF, C_ITEMPRODUTO.NRSEQITPROD, C_INCIDENCIA.CDIMPOTEMP, w_2, w_2,
                           V_SITUTRIBPR, V_FISOPEITEM, V_SUFXCFOPPR, 0, V_PERDBCALC, V_PARDEDTMP,
                           V_CONTABCALC, 0, 0, w_00000, w_00000, V_CDSITTRIBTMP,
                           V_IDMODBCNFE, V_IDMODBCSTNFE, V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, V_IDMOTIDESSTNFE, V_CDSIMPLESNACIONAL,
                           V_CDFAIXA, V_BCICMSSTRETIDO, V_VRICMSSTRETIDO, V_CDREGRAITALIQ, C_INCIDENCIA.CDDETALHEPROD,
                           V_VRIMPOSTOVISUIT, C_INCIDENCIA.CDENQLEGALIPI, C_INCIDENCIA.CDCEST, V_IDIMPSTCARGTRIB);
                     ELSE
                        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, CDSIMPLESNACIONAL,
                           CDFAIXA, VRBCICMSSTRETIDO, VRICMSSTRETIDO, CDREGRAIT, CDDETALHEPROD,
                           VRIMPOSTOVISUIT, CDENQLEGALIPI, CDCEST, IDIMPSTCARGTRIB, VRPERREDBCSTIT, VRIMPOSTOREP)
                        VALUES(
                           P_FILIAL, P_LANCTONF, C_ITEMPRODUTO.NRSEQITPROD, C_INCIDENCIA.CDIMPOTEMP, w_2, w_2,
                           V_SITUTRIBPR, V_FISOPEITEM, V_SUFXCFOPPR, 0, V_PERDBCALC, V_PARDEDTMP,
                           V_CONTABCALC, 0, 0, w_00000, w_00000, V_CDSITTRIBTMP,
                           V_IDMODBCNFE, V_IDMODBCSTNFE, V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, V_IDMOTIDESSTNFE, V_CDSIMPLESNACIONAL,
                           V_CDFAIXA, V_BCICMSSTRETIDO, V_VRICMSSTRETIDO, V_CDREGRAITALIQ, C_INCIDENCIA.CDDETALHEPROD,
                           V_VRIMPOSTOVISUIT, C_INCIDENCIA.CDENQLEGALIPI, C_INCIDENCIA.CDCEST, V_IDIMPSTCARGTRIB, V_PREDBCSTIT, V_VRIMPOSTOREP);
                     END IF;
                  END IF;
               END IF;
               FOR C_ALIQTEMP IN (SELECT DSMENSALITMP
                                  FROM ALIQTEMP
                                  WHERE (NRALIQTEMP = V_ALIQTEMP)  AND
                                        (DSMENSALITMP IS NOT NULL) AND
                                        (NOT EXISTS(SELECT DSDADOADIC
                                                    FROM DADOSADIC
                                                    WHERE (CDFILIAL   = P_FILIAL)   AND
                                                          (NRLANCTONF = P_LANCTONF) AND
                                                          (DSDADOADIC LIKE ALIQTEMP.DSMENSALITMP || '%')))) LOOP
                  IF NOT(C_ALIQTEMP.DSMENSALITMP IS NULL) THEN
                     /*PREENCHE AS MENSAGENS ATRELADAS A ALIQUOTA*/
                     INSERT INTO DADOSADIC(CDFILIAL, NRLANCTONF, NRDADOADIC, DSDADOADIC)
                                    VALUES(P_FILIAL, P_LANCTONF, V_DADOADIC, C_ALIQTEMP.DSMENSALITMP);
                     V_DADOADIC := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_DADOADIC) + 1)),3,0);
                  END IF;
               END LOOP;
               DELETE ALIQTEMP
                WHERE NRALIQTEMP = V_ALIQTEMP;
               V_VRADICALIQFECP := NULL;
               V_VRADICFECP := NULL;
			IF (SUBSTR(V_SITUTRIBPR, 2, 2) = '60') THEN
               CALCULA_ICMS60(P_FILIAL,
                              P_LANCTONF,
                              C_ITEMPRODUTO.NRSEQITPROD,
                              V_TAXAALIQUOTA);
			END IF;
   /*Preenchendo a infAdFisco com os dados do FET*/
            IF C_INCIDENCIA.CDIMPOSTONFE = '04' THEN
               DELETE
                 FROM DADOSADICFISCO
                WHERE CDFILIAL = P_FILIAL
                  AND NRLANCTONF = P_LANCTONF
                  AND DSDADOADICFISCO LIKE '%FET:%';
               BEGIN
                  SELECT SUM(VRBASECALCIT), SUM(VRIMPOSTOIT)
                    INTO V_FETBASECALC, V_FETVRIMPOSTO
                    FROM ITEMPROIMPOS IT, IMPOSTO I
                   WHERE IT.CDIMPOSTO = I.CDIMPOSTO
                     AND I.CDIMPOSTONFE = '04'
                     AND IT.CDFILIAL = P_FILIAL
                     AND IT.NRLANCTONF = P_LANCTONF;
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN BEGIN
                     V_FETBASECALC := 0;
                     V_FETVRIMPOSTO := 0;
                  END;
               END;
               FOR C_FETALIQUOTA IN (SELECT DISTINCT (DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(VRALIQITEM, 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(VRALIQITEM, 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(VRALIQITEM, 2), '9999999999999.99')))) AS ALIQFET
                                       FROM ITEMPROIMPOS IT, IMPOSTO I
                                      WHERE IT.CDIMPOSTO = I.CDIMPOSTO
                                        AND I.CDIMPOSTONFE = '04'
                                        AND IT.CDFILIAL = P_FILIAL
                                        AND IT.NRLANCTONF = P_LANCTONF) LOOP
                  IF (C_FETALIQUOTA.ALIQFET IS NOT NULL) AND (C_FETALIQUOTA.ALIQFET <> '0') THEN
                     V_FETALIQUOTA := C_FETALIQUOTA.ALIQFET||' - '||V_FETALIQUOTA;
                  END IF;
                  IF (V_FETALIQUOTA IS NOT NULL) OR (TRIM(V_FETALIQUOTA) <> '') THEN
                     IF (TRIM(SUBSTR(V_FETALIQUOTA, LENGTH(V_FETALIQUOTA) - 2, 3)) = '-') THEN
                        V_FETALIQUOTA := TRIM(SUBSTR(V_FETALIQUOTA, 1, LENGTH(V_FETALIQUOTA) - 3));
                     END IF;
                  END IF;
               END LOOP;
               IF V_FETVRIMPOSTO > 0 THEN
                  INSERT INTO DADOSADICFISCO (CDFILIAL, NRLANCTONF, NRDADOADICFISCO, DSDADOADICFISCO)
                       VALUES (P_FILIAL, P_LANCTONF, V_DADOADICFISCO, 'Base de Calculo: R$ '||DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(V_FETBASECALC, 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(V_FETBASECALC, 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(V_FETBASECALC, 2), '9999999999999.99')))||
                                                                      ' Aliquota: '||V_FETALIQUOTA||
                                                                      '% FET: R$ '||DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(V_FETVRIMPOSTO, 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(V_FETVRIMPOSTO, 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(V_FETVRIMPOSTO, 2), '9999999999999.99'))));
                  V_DADOADICFISCO := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_DADOADICFISCO) + 1)),3,0);
               END IF;
            END IF;
            END LOOP; --FIM DO LOOP DAS INCIDENCIAS
            DELETE INCITEMP
            WHERE NRINCITEMP = V_INCITEMP;
         ELSE
            /*IMPOSTOS INFORMADOS PELO USUARIO*/
            FOR C_IMPOSINFUSU IN (SELECT II.CDIMPOSTO, II.CDFISCINFUSU,
                                         II.VRALIQINFUSU, II.VRRDBCINFUSU, II.VRPDEDINFUSU,
                                         I.IDTRATIMPO, I.IDCONSISTENT, I.IDIMPORECUP
                                  FROM IMPOSINFUSU II, IMPOSTO I
                                  WHERE (II.CDFILIAL    = P_FILIAL)                  AND
                                        (II.NRLANCTONF  = P_LANCTONF)                AND
                                        (II.NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD) AND
                                        (II.CDIMPOSTO   = I.CDIMPOSTO)) LOOP
               V_TAXABASECALC := (100 - C_IMPOSINFUSU.VRRDBCINFUSU)/100;
               V_TAXAALIQUOTA := (C_IMPOSINFUSU.VRALIQINFUSU/100);
               V_IMPOSTOIT  := ((V_LIQUIITEM * V_TAXABASECALC) * V_TAXAALIQUOTA) - C_IMPOSINFUSU.VRPDEDINFUSU;
               V_CONTABCALC := V_LIQUIITEM - (V_LIQUIITEM * V_TAXABASECALC);
               V_PERDBCALC  := 100 - C_IMPOSINFUSU.VRRDBCINFUSU;
               IF (V_IMPOSTOIT < 0) THEN
                  V_IMPOSTOIT := 0;
               END IF;
               IF (C_IMPOSINFUSU.VRALIQINFUSU = 0) AND (V_IMPOSTOIT = 0) THEN
                  V_BASECALCIT := 0;
               ELSE
                  V_BASECALCIT := V_LIQUIITEM * V_TAXABASECALC;
               END IF;
               BEGIN
                  SELECT CDFILIAL
                  INTO   V_CHAVE
                  FROM ITEMPROIMPOS
                  WHERE CDFILIAL     = P_FILIAL                 AND
                        NRLANCTONF   = P_LANCTONF               AND
                        NRSEQITPROD  = C_ITEMPRODUTO.NRSEQITPROD  AND
                        CDIMPOSTO    = C_IMPOSINFUSU.CDIMPOSTO AND
                        NRITPROIMPOS = w_1;
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN BEGIN
                     V_CHAVE := NULL;
                  END;
               END;
               IF V_IDPERVISIMPSCRE = 'S' THEN
                  V_VRIMPOSTOVISUIT := V_IMPOSTOIT;
               ELSE
                  IF (C_IMPOSINFUSU.CDFISCINFUSU = '1') THEN
                     V_VRIMPOSTOVISUIT := V_IMPOSTOIT;
                  ELSE
                     V_VRIMPOSTOVISUIT := 0;
                  END IF;
               END IF;
               IF V_CHAVE IS NULL THEN
                  INSERT INTO ITEMPROIMPOS(
                     CDFILIAL, NRLANCTONF, NRSEQITPROD, CDIMPOSTO, NRITPROIMPOS, CDFISCALIT, CDSITUTRIBIT,
                     CDFISCOPERIT, CDSUFXCFOPIT, VRALIQITEM, VRPERREDBCIT, VRPARDEDIT, VRCONTITIMP,
                     VRBASECALCIT, VRIMPOSTOIT, IDERROSIMPIT, IDAVISIMPIT, VRIMPOSTOVISUIT)
                  VALUES(
                     P_FILIAL, P_LANCTONF, C_ITEMPRODUTO.NRSEQITPROD, C_IMPOSINFUSU.CDIMPOSTO, w_1, C_IMPOSINFUSU.CDFISCINFUSU, V_SITUTRIBPR,
                     V_FISOPEITEM, V_SUFXCFOPPR, C_IMPOSINFUSU.VRALIQINFUSU, C_IMPOSINFUSU.VRRDBCINFUSU, C_IMPOSINFUSU.VRPDEDINFUSU, V_BASECALCIT,
                     V_BASECALCIT, V_IMPOSTOIT, w_00000, w_00000, V_VRIMPOSTOVISUIT);
                  IF V_PREDBCTMP > 0 THEN
                     INSERT INTO ITEMPROIMPOS(
                        CDFILIAL, NRLANCTONF, NRSEQITPROD, CDIMPOSTO, NRITPROIMPOS, CDFISCALIT, CDSITUTRIBIT,
                        CDFISCOPERIT, CDSUFXCFOPIT, VRALIQITEM, VRPERREDBCIT, VRPARDEDIT, VRCONTITIMP,
                        VRBASECALCIT, VRIMPOSTOIT, IDERROSIMPIT, IDAVISIMPIT, VRIMPOSTOVISUIT, VRPERREDBCSTIT)
                     VALUES(
                        P_FILIAL, P_LANCTONF, C_ITEMPRODUTO.NRSEQITPROD, C_IMPOSINFUSU.CDIMPOSTO, w_2, w_2, V_SITUTRIBPR,
                        V_FISOPEITEM, V_SUFXCFOPPR, 0, V_PERDBCALC, C_IMPOSINFUSU.VRPDEDINFUSU, ROUND(V_CONTABCALC,2),
                        0, 0, w_00000, w_00000, 0, V_PREDBCSTIT);
                  END IF;
               END IF;
            END LOOP; --FIM DO LOOP DOS IMPOSTOS INFORMADOS PELO USUARIO
         END IF;
      END LOOP; --FIM DO LOOP DOS PRODUTOS
      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, 'S', 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;
      --RATEIO DOS ENCARGOS--------------------------------------------------------------------------------------------------------
      /* VERIFICAR SE EXISTE ENCARGO COM VALOR SOMENTE SE TIVER ALGUM ENCARGO PARAMETRIZADO PARA RATEAR PELO PESO LIQUIDO */
      IF NOT(V_ENCARGOLIQUIDO = 'N') THEN
         V_EXISTEENCARGO := 0;
         BEGIN
            SELECT COUNT(CDENCARGO)
              INTO V_EXISTEENCARGO
              FROM ITEMENCARGO
             WHERE VRITEMENCA > 0
               AND CDFILIAL   = P_FILIAL
               AND NRLANCTONF = P_LANCTONF;
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_EXISTEENCARGO := 0;
         END;
         IF (V_EXISTEENCARGO = 0) THEN
            V_ENCARGOLIQUIDO := 'N';
         END IF;
         /* VERIFICAR SE ALGUM ENCARGO QUE TEM VALOR ESTA PARAMETRIZADO PARA SER RATEADO POR PESO LIQUIDO CASO SEJA OPCAO LISTA */
         IF (V_EXISTEENCARGO > 0) THEN
            IF NOT(V_ENCARGOLIQUIDO = 'T') THEN
               BEGIN
                  SELECT COUNT(CDENCARGO)
                    INTO V_EXISTEENCARGO
                    FROM ITEMENCARGO
                   WHERE VRITEMENCA > 0
                     AND CDFILIAL   = P_FILIAL
                     AND NRLANCTONF = P_LANCTONF
                     AND INSTR(V_ENCARGOLIQUIDO, CDENCARGO) > 0;
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_EXISTEENCARGO := 0;
               END;
               /* SE HOUVER ENCARGO COM VALOR MAS NENHUM ESTEJA PARAMETRIZADO NA LISTA PARA RATEAR POR PESO LIQUIDO, A VARIAVEL V_ENCARGOLIQUIDO E PASSADA PARA N PARA QUE OS ENCARGOS QUE TENHAM
                  VALOR SEJAM RATEADOS DE FORMA PROPORCIONAL AO VALOR DOS PRODUTOS */
               IF (V_EXISTEENCARGO = 0) THEN
                  V_ENCARGOLIQUIDO := 'N';
               END IF;
            END IF;
         END IF;
      END IF;
      FOR C_ITEMENCARGO IN (SELECT IE.CDENCARGO AS CDENCARGO, VRITEMENCA, IDENCARGO,
                                   EN.CDCTBLENTREN, EN.CDCTBLSAIDEN
                            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
                                  (V_ENCARGOLIQUIDO <> 'T')   AND
                                  (NOT(INSTR(V_ENCARGOLIQUIDO, IE.CDENCARGO) > 0))) 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
                                     (NVL(IP.IDPRODBONIF, 'N') = 'N')  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
            SELECT SUM(VRTOTAITEM - VRDESCITEM)
            INTO   V_TOTAPRODENCA
            FROM ITEMPRODUTO IP
            WHERE (IP.CDFILIAL   = P_FILIAL)   AND
                  (IP.NRLANCTONF = P_LANCTONF) AND
                  (NVL(IP.IDPRODBONIF, 'N') = 'N');
            IF NOT V_TOTAPRODENCA 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) AND
                                          (NVL(IP.IDPRODBONIF, 'N') = 'N')) 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.CDCTBLSAIDEN IS NULL) THEN
                     V_VRCONTAB := V_VRBRUTO;
                  ELSE
                     V_VRCONTAB := 0;
                  END IF;
                  IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (NVL(V_IDORIGDESTNF, 'C') <> 'L') THEN
                     UPDATE ITEMPRODUTO
                     SET VRBRUTITEM = TRUNC(VRBRUTITEM + (V_VRBRUTO  * (VRTOTAITEM - VRDESCITEM)),2),
                         VRCONTITEM = TRUNC(VRCONTITEM + (V_VRCONTAB * (VRTOTAITEM - VRDESCITEM)),2)
                     WHERE CDFILIAL    = P_FILIAL   AND
                           NRLANCTONF  = P_LANCTONF AND
                           NRSEQITPROD = C_ATUAVRCONT.NRSEQITPROD;
                  ELSE
                     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 IF;
               END LOOP;
            END IF;
         ELSE
            FOR C_ATUAVRCONT 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
                                       (NVL(IP.IDPRODBONIF, 'N') = 'N')  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.CDCTBLSAIDEN IS NULL) THEN
                  V_VRCONTAB := V_VRBRUTO;
               ELSE
                  V_VRCONTAB := 0;
               END IF;
               IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (NVL(V_IDORIGDESTNF, 'C') <> 'L') THEN
                  UPDATE ITEMPRODUTO
                  SET VRBRUTITEM = TRUNC(VRBRUTITEM + (V_VRBRUTO  * (VRTOTAITEM - VRDESCITEM)),2),
                      VRCONTITEM = TRUNC(VRCONTITEM + (V_VRCONTAB * (VRTOTAITEM - VRDESCITEM)),2)
                  WHERE CDFILIAL    = P_FILIAL   AND
                        NRLANCTONF  = P_LANCTONF AND
                        NRSEQITPROD = C_ATUAVRCONT.NRSEQITPROD;
               ELSE
                  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 IF;
            END LOOP;
            FOR C_ITEMPROIMPOS IN (SELECT II.NRSEQITPROD,
                                          II.NRITPROIMPOS,
                                          II.CDIMPOSTO,
                                          II.VRPERREDBCIT,
                                          II.VRALIQITEM,
                                          II.VRPARDEDIT,
                                          II.IDTRIMPSTII,
                                          (VRTOTAITEM - VRDESCITEM) AS VRLIQUIDO,
                                          NVL(II.VRALIQINTEDEST, 0) AS VRALIQINTEDEST,
                                          NVL(II.VRALIQFCP, 0) AS VRALIQFCP,
                                          NVL(IP.IDUTILBCPMC, 'N') AS IDUTILBCPMC,
                                          I.CDIMPOSTONFE,
                                          NVL(II.IDCONSDIFALIQ, 'N') AS IDCONSDIFALIQ,
                                          II.VRIMPOSTOREP,
                                          II.VRPERREDBCSTIT
                                     FROM ITEMPROIMPOS II, ITEMPRODUTO IP, BASECALC BC, IMPOSTO I
                                    WHERE (II.CDFILIAL = P_FILIAL)
                                      AND (II.NRLANCTONF = P_LANCTONF)
                                      AND (IP.CDFILIAL = P_FILIAL)
                                      AND (IP.NRLANCTONF = P_LANCTONF)
                                      AND (IP.NRSEQITPROD = II.NRSEQITPROD)
                                      AND (BC.CDIMPOSTO = II.CDIMPOSTO)
                                      AND (II.CDIMPOSTO = I.CDIMPOSTO)
                                      AND (NVL(IP.IDPRODBONIF, 'N') = 'N')
                                      AND (BC.CDENCARGO = C_ITEMENCARGO.CDENCARGO)
                                    ORDER BY II.NRSEQITPROD,
                                          II.NRITPROIMPOS,
                                          II.CDIMPOSTO) LOOP
               IF NOT((C_ITEMPROIMPOS.IDUTILBCPMC = W_S) AND (C_ITEMPROIMPOS.CDIMPOSTONFE = '80')) OR (C_ITEMPROIMPOS.IDUTILBCPMC <> W_S) THEN
                  IF (C_ITEMPROIMPOS.IDCONSDIFALIQ <> W_S) AND (C_ITEMPROIMPOS.VRIMPOSTOREP IS NULL) THEN
                     SELECT SUM(VRTOTAITEM - VRDESCITEM)
                       INTO V_TOTAPRENIMPO
                       FROM ITEMPRODUTO IP
                      WHERE IP.CDFILIAL   = P_FILIAL
                        AND IP.NRLANCTONF = P_LANCTONF
                        AND (NVL(IP.IDPRODBONIF, 'N') = 'N');
                     IF (V_TOTAPRODENCA <> 0) THEN
                        IF (C_ITEMENCARGO.IDENCARGO = w_A) THEN
                           V_PRODUENCARGO := +(C_ITEMENCARGO.VRITEMENCA/V_TOTAPRENIMPO)*C_ITEMPROIMPOS.VRLIQUIDO;
                        ELSIF (C_ITEMENCARGO.IDENCARGO = w_D) THEN
                           V_PRODUENCARGO := -(C_ITEMENCARGO.VRITEMENCA/V_TOTAPRENIMPO)*C_ITEMPROIMPOS.VRLIQUIDO;
                        ELSE
                           V_PRODUENCARGO := 0;
                        END IF;
                     END IF;
                     V_IDVRIMPSTRIB := null;
                     BEGIN
                        SELECT CASE COUNT(*) WHEN 0 THEN 'M' ELSE 'R' END
                          INTO V_MAJORAOUREDUZ
                          FROM ITEMPROIMPOS
                         WHERE CDFILIAL = P_FILIAL
                           AND NRLANCTONF = P_LANCTONF
                           AND NRSEQITPROD = C_ITEMPROIMPOS.NRSEQITPROD
                           AND CDIMPOSTO = C_ITEMPROIMPOS.CDIMPOSTO
                           AND NRITPROIMPOS = w_2;
                     EXCEPTION
                        WHEN NO_DATA_FOUND THEN
                           V_MAJORAOUREDUZ := 'M';
                     END;
                     V_VRIMPOSTOST := 0;
                     IF V_MAJORAOUREDUZ = 'R' THEN
                        V_TAXABASECALC := (100 - C_ITEMPROIMPOS.VRPERREDBCIT)/100;
                        V_TAXAALIQUOTA := (C_ITEMPROIMPOS.VRALIQITEM/100);
                     ELSE
                        V_TAXABASECALC :=(100 - NVL(C_ITEMPROIMPOS.VRPERREDBCSTIT, 0))/100; /*Alterado por Lucas Lindo*/
                        V_PRODUENCARGO :=  (V_PRODUENCARGO * V_TAXABASECALC); /*Calcular o valor do encargo retirando reducao da base para no update abaixo utilize o valor adicionando a majoracao*/
                        V_TAXABASECALC := 1 + (C_ITEMPROIMPOS.VRPERREDBCIT)/100;
                        V_TAXAALIQUOTA := (C_ITEMPROIMPOS.VRALIQITEM/100);
                        SELECT NVL(MAX(IDVRIMPSTRIB), 'N')
                          INTO V_IDVRIMPSTRIB
                          FROM ITEMPROIMPOS I, IMPOSTO II
                         WHERE (CDFILIAL     = P_FILIAL)
                           AND (NRLANCTONF   = P_LANCTONF)
                           AND (NRSEQITPROD  = C_ITEMPROIMPOS.NRSEQITPROD)
                           AND (INSTR(V_CDIMPOSTRIB,II.CDIMPOSTO||'_') > 0)
                           AND (I.CDIMPOSTO = II.CDIMPOSTO);
                        IF (C_ITEMPROIMPOS.IDTRIMPSTII <> w_1) AND (NVL(V_IDVRIMPSTRIB,w_N) = w_S) THEN
                           BEGIN
                              SELECT NVL(MAX(VRIMPOSTOIT),0)
                              INTO   V_VRIMPOSTOST
                              FROM ITEMPROIMPOS I
                              WHERE (CDFILIAL     = P_FILIAL)                   AND
                                    (NRLANCTONF   = P_LANCTONF)                 AND
                                    (INSTR(V_CDIMPOSTRIB,CDIMPOSTO||'_') > 0)   AND
                                    (NRITPROIMPOS = C_ITEMPROIMPOS.NRITPROIMPOS);
                           EXCEPTION
                              WHEN NO_DATA_FOUND THEN BEGIN
                                 V_VRIMPOSTOST := 0;
                              END;
                           END;
                        END IF;
                     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_ITEMPROIMPOS.CDIMPOSTO)
                     LOOP
                        V_ICMS := 'S';
                     END LOOP;
                     UPDATE ITEMPROIMPOS
                        SET VRCONTITIMP  = VRCONTITIMP  + (V_PRODUENCARGO * V_TAXABASECALC),
                            VRBASECALCIT = VRBASECALCIT + ((V_PRODUENCARGO * V_TAXABASECALC) / (1 - ((C_ITEMPROIMPOS.VRALIQINTEDEST + C_ITEMPROIMPOS.VRALIQFCP) / 100))),
                            VRIMPOSTOIT  = (VRIMPOSTOIT  + (((V_PRODUENCARGO * V_TAXABASECALC) / (1 - ((C_ITEMPROIMPOS.VRALIQINTEDEST + C_ITEMPROIMPOS.VRALIQFCP) / 100))) * V_TAXAALIQUOTA)) - (((V_VRIMPOSTOST * V_TAXABASECALC) / (1 - ((C_ITEMPROIMPOS.VRALIQINTEDEST + C_ITEMPROIMPOS.VRALIQFCP) / 100))) * V_TAXAALIQUOTA),
                            VRIMPOSTOVISUIT = DECODE(V_IDPERVISIMPSCRE, 'S', (VRIMPOSTOIT  + ((V_PRODUENCARGO * V_TAXABASECALC) * V_TAXAALIQUOTA)) - ((V_VRIMPOSTOST * V_TAXABASECALC) * V_TAXAALIQUOTA),  DECODE(CDFISCALIT , '1', (VRIMPOSTOIT  + ((V_PRODUENCARGO * V_TAXABASECALC) * V_TAXAALIQUOTA)) - ((V_VRIMPOSTOST * V_TAXABASECALC) * V_TAXAALIQUOTA),0)),
                            VRADICFECP  = VRADICFECP  + ROUND((V_PRODUENCARGO * (VRADICALIQFECP / 100) * V_TAXABASECALC),2)
                      WHERE (CDFILIAL     = P_FILIAL)                   AND
                            (NRLANCTONF   = P_LANCTONF)                 AND
                            (NRSEQITPROD  = C_ITEMPROIMPOS.NRSEQITPROD) AND
                            (CDIMPOSTO    = C_ITEMPROIMPOS.CDIMPOSTO)   AND
                            (NRITPROIMPOS = C_ITEMPROIMPOS.NRITPROIMPOS);
                  END IF;
               END IF;
               /* ROTINA PARA RECALCULAR O DIFERIMENTO DO IMPOSTO */
               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
                         (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 + ((ROUND(V_PRODUENCARGO, 2) * V_TAXABASECALC) * V_TAXAALIQUOTA)) - ((V_VRIMPOSTOST * V_TAXABASECALC) * V_TAXAALIQUOTA),2);
                  /*
                     Foi comentado este calculo pois ao implementa-lo de acordo com a resolucao n13 de 14 de fevereiro de 2019
                     a sefaz passou a rejeitar as notas com a rejeicao 352 (Rejeicao: Valor do ICMS Diferido no CST=51 difere do
                     produto Valor ICMS Operacao e percentual diferimento)
                  */
                  --IF (V_CDPAISEMIT = 0055) AND (V_SGESTADOEMIT = RJ) THEN
                  --   V_VRIMPOSTODIFERIT := ROUND((((V_TAXABASECALC / (1 - V_TAXAALIQUOTA)) * V_TAXAALIQUOTA) * (V_VRPERDIFEREIT/100)), 2);
                  --ELSE
                     V_VRIMPOSTODIFERIT := ROUND((V_VRIMPOSTOOPERAIT * V_VRPERDIFEREIT/100), 2);
                  --END IF;
                  UPDATE ITEMPROIMPOS
                     SET VRIMPOSTOOPERAIT = VRIMPOSTOOPERAIT + V_VRIMPOSTOOPERAIT,
                         VRIMPOSTODIFERIT = VRIMPOSTODIFERIT + V_VRIMPOSTODIFERIT,
                         VRIMPOSTOIT = VRIMPOSTOIT + (V_VRIMPOSTOOPERAIT - V_VRIMPOSTODIFERIT),
                         VRIMPOSTOVISUIT = 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);
               END IF;
            END LOOP;
         END IF;
      END LOOP;
      /*FAZER AQUI HOJE*/
      /* ROTINA PARA REALIZAR RATEIO DOS ENCARGOS PARAMETRIZADOS POR PESO LIQUIDO DOS PRODUTOS*/
      IF NOT (V_ENCARGOLIQUIDO = 'N') THEN
         FOR C_ITEMENCARGO IN (SELECT IE.CDENCARGO AS CDENCARGO, VRITEMENCA, IDENCARGO,
                                      EN.CDCTBLENTREN, EN.CDCTBLSAIDEN
                               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
                                     ((V_ENCARGOLIQUIDO = 'T') OR (INSTR(V_ENCARGOLIQUIDO, IE.CDENCARGO) > 0 ))
                                     ) LOOP
            V_TOTAPRODENCA := 0;
            FOR C_VRLIQRATEIO IN (SELECT DISTINCT(IP.NRSEQITPROD) AS NRSEQITPROD, (VRTOTAITEM - VRDESCITEM) AS VRLIQUIDOPROD,
                                         (PR.VRPESOLIQUPR * IP.QTITEMPROD) AS VRLIQUIDO
                                  FROM ITEMPRODUTO IP, ITEMPROIMPOS II, PRODUTO PR
                                  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
                                        (IP.CDPRODUTO   = PR.CDPRODUTO)   AND
                                        (NVL(PR.VRPESOLIQUPR, 0) > 0)     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
               SELECT SUM(QTITEMPROD * VRPESOLIQUPR)
                 INTO V_TOTAPRODENCA
                 FROM ITEMPRODUTO IP, PRODUTO PR
                WHERE (IP.CDFILIAL   = P_FILIAL)
                  AND (IP.NRLANCTONF = P_LANCTONF)
                  AND (IP.CDPRODUTO    = PR.CDPRODUTO)
                  AND (NVL(PR.VRPESOLIQUPR, 0) > 0);
               IF NOT V_TOTAPRODENCA IS NULL THEN
                  FOR C_ATUAVRCONT IN (SELECT IP.NRSEQITPROD, (VRTOTAITEM - VRDESCITEM) AS VRLIQUIDO,
                                             (PR.VRPESOLIQUPR * IP.QTITEMPROD) AS PESOTOTALPROD
                                       FROM ITEMPRODUTO IP, PRODUTO PR
                                       WHERE (IP.CDFILIAL    = P_FILIAL)
                                         AND (IP.NRLANCTONF  = P_LANCTONF)
                                         AND (IP.CDPRODUTO    = PR.CDPRODUTO)
                                         AND (NVL(PR.VRPESOLIQUPR, 0) > 0)) 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.CDCTBLSAIDEN IS NULL) THEN
                        V_VRCONTAB := V_VRBRUTO;
                     ELSE
                        V_VRCONTAB := 0;
                     END IF;
                     IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (NVL(V_IDORIGDESTNF, 'C') <> 'L') THEN
                        UPDATE ITEMPRODUTO
                        SET VRBRUTITEM = TRUNC(VRBRUTITEM + (V_VRBRUTO  * C_ATUAVRCONT.PESOTOTALPROD),2),
                            VRCONTITEM = TRUNC(VRCONTITEM + (V_VRCONTAB * C_ATUAVRCONT.PESOTOTALPROD),2)
                        WHERE CDFILIAL    = P_FILIAL   AND
                              NRLANCTONF  = P_LANCTONF AND
                              NRSEQITPROD = C_ATUAVRCONT.NRSEQITPROD;
                     ELSE
                        UPDATE ITEMPRODUTO
                        SET VRBRUTITEM = VRBRUTITEM + (V_VRBRUTO  * C_ATUAVRCONT.PESOTOTALPROD),
                            VRCONTITEM = VRCONTITEM + (V_VRCONTAB * C_ATUAVRCONT.PESOTOTALPROD)
                        WHERE CDFILIAL    = P_FILIAL   AND
                              NRLANCTONF  = P_LANCTONF AND
                              NRSEQITPROD = C_ATUAVRCONT.NRSEQITPROD;
                     END IF;
                  END LOOP;
               END IF;
            ELSE
               FOR C_ATUAVRCONT IN (SELECT DISTINCT(IP.NRSEQITPROD) AS NRSEQITPROD, (VRTOTAITEM - VRDESCITEM) AS VRLIQUIDO,
                                         (PR.VRPESOLIQUPR * IP.QTITEMPROD) AS PESOTOTALPROD
                                    FROM ITEMPRODUTO IP, ITEMPROIMPOS II, PRODUTO PR
                                    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
                                          (IP.CDPRODUTO   = PR.CDPRODUTO)   AND
                                          (NVL(PR.VRPESOLIQUPR, 0) > 0)     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.CDCTBLSAIDEN IS NULL) THEN
                     V_VRCONTAB := V_VRBRUTO;
                  ELSE
                     V_VRCONTAB := 0;
                  END IF;
                  IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (NVL(V_IDORIGDESTNF, 'C') <> 'L') THEN
                     UPDATE ITEMPRODUTO
                     SET VRBRUTITEM = TRUNC(VRBRUTITEM + (V_VRBRUTO  * C_ATUAVRCONT.PESOTOTALPROD),2),
                         VRCONTITEM = TRUNC(VRCONTITEM + (V_VRCONTAB * C_ATUAVRCONT.PESOTOTALPROD),2)
                     WHERE CDFILIAL    = P_FILIAL   AND
                           NRLANCTONF  = P_LANCTONF AND
                           NRSEQITPROD = C_ATUAVRCONT.NRSEQITPROD;
                  ELSE
                     UPDATE ITEMPRODUTO
                     SET VRBRUTITEM = VRBRUTITEM + (V_VRBRUTO  * C_ATUAVRCONT.PESOTOTALPROD),
                         VRCONTITEM = VRCONTITEM + (V_VRCONTAB * C_ATUAVRCONT.PESOTOTALPROD)
                     WHERE CDFILIAL    = P_FILIAL   AND
                           NRLANCTONF  = P_LANCTONF AND
                           NRSEQITPROD = C_ATUAVRCONT.NRSEQITPROD;
                  END IF;
               END LOOP;
               FOR C_ITEMPROIMPOS IN (SELECT II.NRSEQITPROD,
                                             II.NRITPROIMPOS,
                                             II.CDIMPOSTO,
                                             II.VRPERREDBCIT,
                                             II.VRALIQITEM,
                                             II.VRPARDEDIT,
                                             II.IDTRIMPSTII,
                                             (VRTOTAITEM - VRDESCITEM) AS VRLIQUIDO,
                                             NVL(II.VRALIQINTEDEST, 0) AS VRALIQINTEDEST,
                                             NVL(II.VRALIQFCP, 0) AS VRALIQFCP,
                                             NVL(IP.IDUTILBCPMC, 'N') AS IDUTILBCPMC,
                                             I.CDIMPOSTONFE,
                                             NVL(II.IDCONSDIFALIQ, 'N') AS IDCONSDIFALIQ,
                                             II.VRIMPOSTOREP,
                                             II.VRPERREDBCSTIT,
                                             (PR.VRPESOLIQUPR * IP.QTITEMPROD) AS PESOTOTALPROD
                                        FROM ITEMPROIMPOS II, ITEMPRODUTO IP, BASECALC BC, IMPOSTO I, PRODUTO PR
                                       WHERE (II.CDFILIAL = P_FILIAL)
                                         AND (II.NRLANCTONF = P_LANCTONF)
                                         AND (IP.CDFILIAL = P_FILIAL)
                                         AND (IP.NRLANCTONF = P_LANCTONF)
                                         AND (IP.NRSEQITPROD = II.NRSEQITPROD)
                                         AND (PR.CDPRODUTO    = IP.CDPRODUTO)            
                                         AND (NVL(PR.VRPESOLIQUPR, 0) > 0)
                                         AND (BC.CDIMPOSTO = II.CDIMPOSTO)
                                         AND (II.CDIMPOSTO = I.CDIMPOSTO)
                                         AND (BC.CDENCARGO = C_ITEMENCARGO.CDENCARGO)
                                       ORDER BY II.NRSEQITPROD,
                                             II.NRITPROIMPOS,
                                             II.CDIMPOSTO) LOOP
                  IF NOT((C_ITEMPROIMPOS.IDUTILBCPMC = W_S) AND (C_ITEMPROIMPOS.CDIMPOSTONFE = '80')) OR (C_ITEMPROIMPOS.IDUTILBCPMC <> W_S) THEN
                     IF (C_ITEMPROIMPOS.IDCONSDIFALIQ <> W_S) AND (C_ITEMPROIMPOS.VRIMPOSTOREP IS NULL) THEN
                        SELECT SUM(QTITEMPROD * VRPESOLIQUPR)
                          INTO V_TOTAPRENIMPO
                          FROM ITEMPRODUTO IP, PRODUTO PR
                         WHERE IP.CDFILIAL   = P_FILIAL
                           AND IP.NRLANCTONF = P_LANCTONF
                           AND IP.CDPRODUTO  = PR.CDPRODUTO
                           AND (NVL(PR.VRPESOLIQUPR, 0) > 0);
                        IF (V_TOTAPRODENCA <> 0) THEN
                           IF (C_ITEMENCARGO.IDENCARGO = w_A) THEN
                              V_PRODUENCARGO := +(C_ITEMENCARGO.VRITEMENCA/V_TOTAPRENIMPO)*C_ITEMPROIMPOS.PESOTOTALPROD;
                           ELSIF (C_ITEMENCARGO.IDENCARGO = w_D) THEN
                              V_PRODUENCARGO := -(C_ITEMENCARGO.VRITEMENCA/V_TOTAPRENIMPO)*C_ITEMPROIMPOS.PESOTOTALPROD;
                           ELSE
                              V_PRODUENCARGO := 0;
                           END IF;
                        END IF;
                        V_IDVRIMPSTRIB := null;
                        BEGIN
                           SELECT CASE COUNT(*) WHEN 0 THEN 'M' ELSE 'R' END
                             INTO V_MAJORAOUREDUZ
                             FROM ITEMPROIMPOS
                            WHERE CDFILIAL = P_FILIAL
                              AND NRLANCTONF = P_LANCTONF
                              AND NRSEQITPROD = C_ITEMPROIMPOS.NRSEQITPROD
                              AND CDIMPOSTO = C_ITEMPROIMPOS.CDIMPOSTO
                              AND NRITPROIMPOS = w_2;
                        EXCEPTION
                           WHEN NO_DATA_FOUND THEN
                              V_MAJORAOUREDUZ := 'M';
                        END;
                        V_VRIMPOSTOST := 0;
                        IF V_MAJORAOUREDUZ = 'R' THEN
                           V_TAXABASECALC := (100 - C_ITEMPROIMPOS.VRPERREDBCIT)/100;
                           V_TAXAALIQUOTA := (C_ITEMPROIMPOS.VRALIQITEM/100);
                        ELSE
                           V_TAXABASECALC :=(100 - NVL(C_ITEMPROIMPOS.VRPERREDBCSTIT, 0))/100; /*Alterado por Lucas Lindo*/
                           V_PRODUENCARGO :=  (V_PRODUENCARGO * V_TAXABASECALC); /*Calcular o valor do encargo retirando reducao da base para no update abaixo utilize o valor adicionando a majoracao*/
                           V_TAXABASECALC := 1 + (C_ITEMPROIMPOS.VRPERREDBCIT)/100;
                           V_TAXAALIQUOTA := (C_ITEMPROIMPOS.VRALIQITEM/100);
                           SELECT NVL(MAX(IDVRIMPSTRIB), 'N')
                             INTO V_IDVRIMPSTRIB
                             FROM ITEMPROIMPOS I, IMPOSTO II
                            WHERE (CDFILIAL     = P_FILIAL)
                              AND (NRLANCTONF   = P_LANCTONF)
                              AND (NRSEQITPROD  = C_ITEMPROIMPOS.NRSEQITPROD) 
                              AND (INSTR(V_CDIMPOSTRIB,II.CDIMPOSTO||'_') > 0)
                              AND (I.CDIMPOSTO = II.CDIMPOSTO);
                           IF (C_ITEMPROIMPOS.IDTRIMPSTII <> w_1) AND (NVL(V_IDVRIMPSTRIB,w_N) = w_S) THEN
                              BEGIN
                                 SELECT NVL(MAX(VRIMPOSTOIT),0)
                                 INTO   V_VRIMPOSTOST
                                 FROM ITEMPROIMPOS I
                                 WHERE (CDFILIAL     = P_FILIAL)                    AND
                                       (NRLANCTONF   = P_LANCTONF)                  AND
                                       (INSTR(V_CDIMPOSTRIB,CDIMPOSTO||'_') > 0)    AND
                                       (NRITPROIMPOS = C_ITEMPROIMPOS.NRITPROIMPOS) AND
                                       (NRSEQITPROD  = C_ITEMPROIMPOS.NRSEQITPROD); 
                              EXCEPTION
                                 WHEN NO_DATA_FOUND THEN BEGIN
                                    V_VRIMPOSTOST := 0;
                                 END;
                              END;
                           END IF;
                        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_ITEMPROIMPOS.CDIMPOSTO)
                        LOOP
                           V_ICMS := 'S';
                        END LOOP;
                        UPDATE ITEMPROIMPOS
                           SET VRCONTITIMP  = VRCONTITIMP  + (V_PRODUENCARGO * V_TAXABASECALC),
                               VRBASECALCIT = VRBASECALCIT + ((V_PRODUENCARGO * V_TAXABASECALC) / (1 - ((C_ITEMPROIMPOS.VRALIQINTEDEST + C_ITEMPROIMPOS.VRALIQFCP) / 100))),
                               VRIMPOSTOIT  = (VRIMPOSTOIT  + (((V_PRODUENCARGO * V_TAXABASECALC) / (1 - ((C_ITEMPROIMPOS.VRALIQINTEDEST + C_ITEMPROIMPOS.VRALIQFCP) / 100))) * V_TAXAALIQUOTA)) - (((V_VRIMPOSTOST * V_TAXABASECALC) / (1 - ((C_ITEMPROIMPOS.VRALIQINTEDEST + C_ITEMPROIMPOS.VRALIQFCP) / 100))) * V_TAXAALIQUOTA),
                               VRIMPOSTOVISUIT = DECODE(V_IDPERVISIMPSCRE, 'S', (VRIMPOSTOIT  + ((V_PRODUENCARGO * V_TAXABASECALC) * V_TAXAALIQUOTA)) - ((V_VRIMPOSTOST * V_TAXABASECALC) * V_TAXAALIQUOTA),  DECODE(CDFISCALIT , '1', (VRIMPOSTOIT  + ((V_PRODUENCARGO * V_TAXABASECALC) * V_TAXAALIQUOTA)) - ((V_VRIMPOSTOST * V_TAXABASECALC) * V_TAXAALIQUOTA),0)),
                               VRADICFECP  = VRADICFECP  + ROUND((V_PRODUENCARGO * (VRADICALIQFECP / 100) * V_TAXABASECALC),2)
                         WHERE (CDFILIAL     = P_FILIAL)                   AND
                               (NRLANCTONF   = P_LANCTONF)                 AND
                               (NRSEQITPROD  = C_ITEMPROIMPOS.NRSEQITPROD) AND
                               (CDIMPOSTO    = C_ITEMPROIMPOS.CDIMPOSTO)   AND
                               (NRITPROIMPOS = C_ITEMPROIMPOS.NRITPROIMPOS);
                     END IF;
                  END IF;
                  /* ROTINA PARA RECALCULAR O DIFERIMENTO DO IMPOSTO */
                  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
                            (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 + ((ROUND(V_PRODUENCARGO, 2) * V_TAXABASECALC) * V_TAXAALIQUOTA)) - ((V_VRIMPOSTOST * V_TAXABASECALC) * V_TAXAALIQUOTA),2);
                     /*
                        Foi comentado este calculo pois ao implementa-lo de acordo com a resolucao n13 de 14 de fevereiro de 2019
                        a sefaz passou a rejeitar as notas com a rejeicao 352 (Rejeicao: Valor do ICMS Diferido no CST=51 difere do
                        produto Valor ICMS Operacao e percentual diferimento)
                     */
                     --IF (V_CDPAISEMIT = 0055) AND (V_SGESTADOEMIT = RJ) THEN
                     --   V_VRIMPOSTODIFERIT := ROUND((((V_TAXABASECALC / (1 - V_TAXAALIQUOTA)) * V_TAXAALIQUOTA) * (V_VRPERDIFEREIT/100)), 2);
                     --ELSE
                        V_VRIMPOSTODIFERIT := ROUND((V_VRIMPOSTOOPERAIT * V_VRPERDIFEREIT/100), 2);
                     --END IF;
                     UPDATE ITEMPROIMPOS
                        SET VRIMPOSTOOPERAIT = VRIMPOSTOOPERAIT + V_VRIMPOSTOOPERAIT,
                            VRIMPOSTODIFERIT = VRIMPOSTODIFERIT + V_VRIMPOSTODIFERIT,
                            VRIMPOSTOIT = VRIMPOSTOIT + (V_VRIMPOSTOOPERAIT - V_VRIMPOSTODIFERIT),
                            VRIMPOSTOVISUIT = 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);
                  END IF;
               END LOOP;
            END IF;
         END LOOP;
      END IF;
      /* ROTINA PARA REALIZAR RATEIO DOS ENCARGOS PARAMETRIZADOS POR PESO LIQUIDO DOS PRODUTOS*/
      UPDATE ITEMPROIMPOS
      SET VRIMPOSTOIT = 0,
          VRIMPOSTOVISUIT = 0
      WHERE (NRLANCTONF  = P_LANCTONF) AND
            (CDFILIAL    = P_FILIAL)   AND
            (VRIMPOSTOIT < 0);
      UPDATE ITEMPROIMPOS
      SET VRBASECALCIT = 0
      WHERE (NRLANCTONF  = P_LANCTONF) AND
            (CDFILIAL    = P_FILIAL)   AND
            (VRBASECALCIT < 0);
      --CALCULO DO VALOR DOS IMPOSTOS QUE CONTEM OUTROS IMPOSTOS NA SUA BASE DE CALCULO
      FOR C_PRODUTO IN (SELECT IP.NRSEQITPROD AS NRSEQITPROD,
                               II.CDIMPOSTO,
                               VRPERREDBCIT,
                               VRALIQITEM,
                               VRPARDEDIT, 
                               CDFISCALIT, 
                               VRIMPOSTOIT, 
                               IDTRATIMPO,
                               IM.IDIMPORECUP, 
                               IM.CDCCTBLPASS,
                               IM.CDCCTBLATIV,
                               NRITPROIMPOS,
                               IDTRIMPSTII,
                               IM.IDTIPCONTAB, 
                               II.VRBASECALCIT, 
                               II.IDIMPSTCARGTRIB,
                               IP.CDPRODUTO,
                               P.CDARVPROD,
                               IP.IDORIGEMPROD,
                               IM.IDDESCRFONTE,
                               NVL(IP.IDUTILBCPMC, W_N) AS IDUTILBCPMC, 
                               NVL(VRADICFECP, 0) AS VRADICFECP,
                               NVL(VRADICALIQFECP, 0) AS VRADICALIQFECP, 
                               NVL(II.IDCONSDIFALIQ, W_N) AS IDCONSDIFALIQ,
                               II.VRIMPOSTOREP, IM.CDIMPOSTONFE, IM.IDUTMUNIORIG
                          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 (IM.CDIMPOSTO = II.CDIMPOSTO)
                           AND (II.NRITPROIMPOS = w_1)
                           AND (II.NRSEQITPROD = IP.NRSEQITPROD)
                           AND P.CDPRODUTO = IP.CDPRODUTO
                         ORDER BY NRSEQITPROD, 
                               CDIMPOSTO) LOOP
         V_IDIMPOBCALTPOP := NULL;
         V_FECPPMCAUX := 0;
         SELECT TO_CHAR(MAX('S')) , NVL(SUM(VRIMPOSTOIT),0) AS VRIMPOBCALC
           INTO   V_IDIMPOBCALTPOP, V_TOTAIMPBCALC
           FROM ITEMPRODUTO IP, ITEMPROIMPOS II, BASECALCTPOPER BC , IMPOSTO I
          WHERE (BC.CDIMPOSTO    = C_PRODUTO.CDIMPOSTO)
            AND (IP.CDFILIAL     = P_FILIAL)
            AND (IP.NRLANCTONF   = P_LANCTONF)
            AND (II.NRLANCTONF   = IP.NRLANCTONF)
            AND (II.CDFILIAL     = IP.CDFILIAL)
            AND (IP.NRSEQITPROD  = C_PRODUTO.NRSEQITPROD)
            AND (II.NRSEQITPROD  = C_PRODUTO.NRSEQITPROD)
            AND (II.NRITPROIMPOS = C_PRODUTO.NRITPROIMPOS)
            AND ((SUBSTR(IP.CDSITUTRIBPR,2,2) = BC.CDCSTIMPOTPOP)  OR (BC.CDCSTIMPOTPOP  IS NULL))
            AND ((SUBSTR(IP.CDFISOPEITEM,2,4) = BC.CDCFOPIMPOTPOP) OR (BC.CDCFOPIMPOTPOP IS NULL))
            AND ((C_PRODUTO.CDFISCALIT        = BC.CDFISCIMPOTPOP) OR (BC.CDFISCIMPOTPOP IS NULL))
            AND (BC.IDENTRSAIDOP = 'S')
            AND (BC.CDTIPOOPER = P_TIPOOPER)
            AND (II.CDIMPOSTO = BC.CDIMPOBCALC)
            AND (BC.CDIMPOBCALC = I.CDIMPOSTO)
            AND (NVL(BC.IDTRATIMPOBCTPOP, I.IDTRATIMPO) <> 'D');
         IF V_IDIMPOBCALTPOP IS NULL THEN
            SELECT NVL(SUM(VRIMPOSTOIT),0) AS VRIMPOBCALC
              INTO   V_TOTAIMPBCALC
              FROM ITEMPRODUTO IP, ITEMPROIMPOS II, BASECALC BC, IMPOSTO I
             WHERE (BC.CDIMPOSTO    = C_PRODUTO.CDIMPOSTO)    AND
                   (IP.CDFILIAL     = P_FILIAL)               AND
                   (IP.NRLANCTONF   = P_LANCTONF)             AND
                   (II.NRLANCTONF   = IP.NRLANCTONF)          AND
                   (II.CDFILIAL     = IP.CDFILIAL)            AND
                   (IP.NRSEQITPROD  = C_PRODUTO.NRSEQITPROD)  AND
                   (II.NRSEQITPROD  = C_PRODUTO.NRSEQITPROD)  AND
                   (II.NRITPROIMPOS = C_PRODUTO.NRITPROIMPOS) AND
                   ((SUBSTR(IP.CDSITUTRIBPR,2,2) = BC.CDCSTIMPO)  OR (BC.CDCSTIMPO  IS NULL)) AND
                   ((SUBSTR(IP.CDFISOPEITEM,2,4) = BC.CDCFOPIMPO) OR (BC.CDCFOPIMPO IS NULL)) AND
                   ((C_PRODUTO.CDFISCALIT        = BC.CDFISCIMPO) OR (BC.CDFISCIMPO IS NULL)) AND
                   (II.CDIMPOSTO = BC.CDIMPOBCALC) AND
                   (BC.IDTIPOBCALC   = w_I)AND
                   (BC.CDIMPOBCALC = I.CDIMPOSTO)  AND
                   (NVL(BC.IDTRATIMPOBC, 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, BASECALCTPOPER BC, IMPOSTO I
          WHERE (BC.CDIMPOSTO    = C_PRODUTO.CDIMPOSTO)
            AND (IP.CDFILIAL     = P_FILIAL)
            AND (IP.NRLANCTONF   = P_LANCTONF)
            AND (II.NRLANCTONF   = IP.NRLANCTONF)
            AND (II.CDFILIAL     = IP.CDFILIAL)
            AND (IP.NRSEQITPROD  = C_PRODUTO.NRSEQITPROD)
            AND (II.NRSEQITPROD  = C_PRODUTO.NRSEQITPROD)
            AND (II.NRITPROIMPOS = C_PRODUTO.NRITPROIMPOS)
            AND ((SUBSTR(IP.CDSITUTRIBPR,2,2) = BC.CDCSTIMPOTPOP)  OR (BC.CDCSTIMPOTPOP  IS NULL))
            AND ((SUBSTR(IP.CDFISOPEITEM,2,4) = BC.CDCFOPIMPOTPOP) OR (BC.CDCFOPIMPOTPOP IS NULL))
            AND ((C_PRODUTO.CDFISCALIT        = BC.CDFISCIMPOTPOP) OR (BC.CDFISCIMPOTPOP IS NULL))
            AND (BC.IDENTRSAIDOP = 'S')
            AND (BC.CDTIPOOPER = P_TIPOOPER)
            AND (II.CDIMPOSTO = BC.CDIMPOBCALC)
            AND (BC.CDIMPOBCALC = I.CDIMPOSTO)
            AND (NVL(BC.IDTRATIMPOBCTPOP, 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, BASECALC BC, IMPOSTO I
             WHERE (BC.CDIMPOSTO    = C_PRODUTO.CDIMPOSTO)    AND
                   (IP.CDFILIAL     = P_FILIAL)               AND
                   (IP.NRLANCTONF   = P_LANCTONF)             AND
                   (II.NRLANCTONF   = IP.NRLANCTONF)          AND
                   (II.CDFILIAL     = IP.CDFILIAL)            AND
                   (IP.NRSEQITPROD  = C_PRODUTO.NRSEQITPROD)  AND
                   (II.NRSEQITPROD  = C_PRODUTO.NRSEQITPROD)  AND
                   (II.NRITPROIMPOS = C_PRODUTO.NRITPROIMPOS) AND
                   ((SUBSTR(IP.CDSITUTRIBPR,2,2) = BC.CDCSTIMPO)  OR (BC.CDCSTIMPO  IS NULL)) AND
                   ((SUBSTR(IP.CDFISOPEITEM,2,4) = BC.CDCFOPIMPO) OR (BC.CDCFOPIMPO IS NULL)) AND
                   ((C_PRODUTO.CDFISCALIT        = BC.CDFISCIMPO) OR (BC.CDFISCIMPO IS NULL)) AND
                   (II.CDIMPOSTO = BC.CDIMPOBCALC) AND
                   (BC.IDTIPOBCALC   = 'I')        AND
                   (BC.CDIMPOBCALC = I.CDIMPOSTO)  AND
                   (NVL(BC.IDTRATIMPOBC, I.IDTRATIMPO) = 'D');
         END IF;
         V_VRIMPOSTO := C_PRODUTO.VRIMPOSTOIT;
         /*IMPOSTO PARA SUBSTITUICAO TRIBUTARIA*/
         V_CDIMPOSTRIB  := null;
         V_IDVRIMPSTRIB := null;
         FOR C_ICMSST IN (SELECT CDIMPOSTO
                            FROM IMPOSTO
                           WHERE CDIMPOSTRIB = C_PRODUTO.CDIMPOSTO)
         LOOP
            V_CDIMPOSTRIB := V_CDIMPOSTRIB||C_ICMSST.CDIMPOSTO||'_';
         END LOOP;
         V_VRIMPOSTOST := 0;
         /*So ira fazer o calculo de outro imposto compondo a base de calculo,
           se o valor do mesmo nao estiver zerado OU
           se for o imposto de st, pois o icms pode ter sido recalculado(por ter alguem compondo sua bc)
           e o imposto st precisa retirar o valor final do st*/
         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_VRIMPOSTO    := V_VRIMPOSTO + (((V_TOTAIMPBCALC+V_TOTAIMPBCDES) * V_TAXABASECALC) * V_TAXAALIQUOTA);
               IF C_PRODUTO.VRIMPOSTOREP IS NULL THEN
                  UPDATE ITEMPROIMPOS
                     SET VRBASECALCIT = VRBASECALCIT + ((V_TOTAIMPBCALC+V_TOTAIMPBCDES) * V_TAXABASECALC),
                         VRIMPOSTOIT  = VRIMPOSTOIT  + (((V_TOTAIMPBCALC+V_TOTAIMPBCDES) * V_TAXABASECALC) * V_TAXAALIQUOTA),
                         VRIMPOSTOVISUIT = DECODE(V_IDPERVISIMPSCRE, 'S', VRIMPOSTOIT  + (((V_TOTAIMPBCALC+V_TOTAIMPBCDES) * V_TAXABASECALC) * V_TAXAALIQUOTA), DECODE(CDFISCALIT, '1', VRIMPOSTOIT  + (((V_TOTAIMPBCALC+V_TOTAIMPBCDES) * V_TAXABASECALC) * V_TAXAALIQUOTA), 0)),
                         VRADICFECP  = VRADICFECP + ROUND((((V_TOTAIMPBCALC+V_TOTAIMPBCDES) * V_TAXABASECALC) * (VRADICALIQFECP/100)), 2)
                   WHERE (CDFILIAL     = P_FILIAL)              AND
                         (NRLANCTONF   = P_LANCTONF)            AND
                         (NRSEQITPROD  = C_PRODUTO.NRSEQITPROD) AND
                         (CDIMPOSTO    = C_PRODUTO.CDIMPOSTO)   AND
                         (NRITPROIMPOS = C_PRODUTO.NRITPROIMPOS);
                  /* ROTINA PARA RECALCULAR O DIFERIMENTO DO IMPOSTO */
                  IF (NVL(V_TOTAIMPBCALC, 0) > 0) OR (NVL(V_TOTAIMPBCDES, 0) > 0) 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_PRODUTO.NRSEQITPROD)  AND
                               (CDIMPOSTO    = C_PRODUTO.CDIMPOSTO)    AND
                               (NRITPROIMPOS = C_PRODUTO.NRITPROIMPOS) AND
                               (VRPERDIFEREIT <> 0);
                     EXCEPTION
                        When No_Data_Found Then
                           V_VRIMPOSTOOPERAIT := 0; V_VRPERDIFEREIT := 0;
                     END;
                     IF V_VRPERDIFEREIT <> 0 THEN
                        V_VRIMPOSTOOPERAIT := ROUND(((ROUND((V_TOTAIMPBCALC + V_TOTAIMPBCDES), 2) * V_TAXABASECALC) * V_TAXAALIQUOTA),2);
                        /*
                           Foi comentado este calculo pois ao implementa-lo de acordo com a resolucao n13 de 14 de fevereiro de 2019
                           a sefaz passou a rejeitar as notas com a rejeicao 352 (Rejeicao: Valor do ICMS Diferido no CST=51 difere do
                           produto Valor ICMS Operacao e percentual diferimento)
                        */
                        --IF (V_CDPAISEMIT = 0055) AND (V_SGESTADOEMIT = RJ) THEN
                        --   V_VRIMPOSTODIFERIT := ROUND((((V_TAXABASECALC / (1 - V_TAXAALIQUOTA)) * V_TAXAALIQUOTA) * (V_VRPERDIFEREIT/100)), 2);
                        --ELSE
                           V_VRIMPOSTODIFERIT := ROUND((V_VRIMPOSTOOPERAIT * V_VRPERDIFEREIT/100), 2);
                        --END IF;
                        UPDATE ITEMPROIMPOS
                           SET VRIMPOSTOOPERAIT = VRIMPOSTOOPERAIT + V_VRIMPOSTOOPERAIT,
                               VRIMPOSTODIFERIT = VRIMPOSTODIFERIT + V_VRIMPOSTODIFERIT,
                               VRIMPOSTOIT = VRIMPOSTOIT + (V_VRIMPOSTOOPERAIT - V_VRIMPOSTODIFERIT),
                               VRIMPOSTOVISUIT = VRIMPOSTOVISUIT + (V_VRIMPOSTOOPERAIT - V_VRIMPOSTODIFERIT)
                         WHERE (CDFILIAL     = P_FILIAL)               AND
                               (NRLANCTONF   = P_LANCTONF)             AND
                               (NRSEQITPROD  = C_PRODUTO.NRSEQITPROD)  AND
                               (CDIMPOSTO    = C_PRODUTO.CDIMPOSTO)    AND
                               (NRITPROIMPOS = C_PRODUTO.NRITPROIMPOS) AND
                               (VRPERDIFEREIT <> 0);
                     END IF;
                  END IF;   
               END IF;
            ELSE
               V_VRIMPOSST   := 0;
               V_VRIMPOSTOST := 0;
               FOR C_SUBSTRIB IN (SELECT NVL(IDVRIMPSTRIB, 'N') IDVRIMPSTRIB, I.CDIMPOSTO
                                    FROM ITEMPROIMPOS I, IMPOSTO II
                                   WHERE (CDFILIAL     = P_FILIAL)
                                     AND (NRLANCTONF   = P_LANCTONF)
                                     AND (NRSEQITPROD  = C_PRODUTO.NRSEQITPROD)
                                     AND (NRITPROIMPOS = '1')
                                     AND (INSTR(V_CDIMPOSTRIB,II.CDIMPOSTO||'_') > 0)
                                     AND (I.CDIMPOSTO = II.CDIMPOSTO))
               LOOP
                  IF (C_SUBSTRIB.IDVRIMPSTRIB = w_S) THEN
                     Begin
                        SELECT NVL(ROUND(MAX(VRIMPOSTOIT), 2),0)
                        INTO   V_VRIMPOSST
                        FROM ITEMPROIMPOS I
                        WHERE (CDFILIAL     = P_FILIAL)                   AND
                              (NRLANCTONF   = P_LANCTONF)                 AND
                              (NRSEQITPROD  = C_PRODUTO.NRSEQITPROD)  AND
                              (CDIMPOSTO    = C_SUBSTRIB.CDIMPOSTO)       AND
                              (INSTR(V_CDIMPOSTRIB,CDIMPOSTO||'_') > 0)   AND
                              (NRITPROIMPOS = w_1);
                     Exception
                        When No_Data_Found Then
                           V_VRIMPOSST := 0;
                     End;
                  ELSE
                     V_VRIMPOSST := 0;
                  END IF;
                  V_VRIMPOSTOST := V_VRIMPOSTOST + V_VRIMPOSST;
               END LOOP;
               IF (C_PRODUTO.IDUTILBCPMC = W_S) THEN
                  V_TAXAALIQUOTA := C_PRODUTO.VRALIQITEM / 100;
                  V_VRIMPOSTO := C_PRODUTO.VRBASECALCIT * V_TAXAALIQUOTA;
               ELSIF ((C_PRODUTO.IDCONSDIFALIQ = W_S) OR (C_PRODUTO.VRIMPOSTOREP IS NOT NULL)) THEN  /* Caso esteja cadastrao Valor a ser Repassado, a base de Calculo e o valor do imposto e calculado de acordo com este cadastro */
                  V_TAXAALIQUOTA := C_PRODUTO.VRALIQITEM / 100;
                  V_VRIMPOSTO := C_PRODUTO.VRIMPOSTOIT;
               ELSE
                  BEGIN
                     SELECT CASE COUNT(*) WHEN 0 THEN 'M' ELSE 'R' END
                       INTO V_MAJORAOUREDUZ
                       FROM ITEMPROIMPOS
                      WHERE CDFILIAL = P_FILIAL 
                        AND NRLANCTONF = P_LANCTONF
                        AND NRSEQITPROD = C_PRODUTO.NRSEQITPROD
                        AND CDIMPOSTO = C_PRODUTO.CDIMPOSTO
                        AND NRITPROIMPOS = w_2;
                  EXCEPTION
                     WHEN NO_DATA_FOUND THEN
                        V_MAJORAOUREDUZ := 'M';
                  END;
                  IF V_MAJORAOUREDUZ = 'R' THEN
                     V_TAXABASECALC := (100 - C_PRODUTO.VRPERREDBCIT)/100;
                  ELSE
                     V_TAXABASECALC := 1 + (C_PRODUTO.VRPERREDBCIT)/100;
                  END IF;
                  V_TAXAALIQUOTA := (C_PRODUTO.VRALIQITEM/100);
                  V_VRIMPOSTO := ((C_PRODUTO.VRBASECALCIT + ((V_TOTAIMPBCALC + V_TOTAIMPBCDES) * V_TAXABASECALC)) * V_TAXAALIQUOTA);
               END IF;
               -- ESSA CONDICAO SERA FEITA PORQUE A BASE DE CALCULO NAO SERA ALTERADO QUANDO O PRODUTO TIVER CONSIDERANDO 
               -- O DIFERENCIAL DE ALIQUOTA DO ICMS, ISTO PORQUE A BASE DE CALCULO JA FOI CALCULADA NA PROCEDURE CONSIDERA_DIFAL_ICMS
               IF ((C_PRODUTO.IDCONSDIFALIQ = W_S) OR (C_PRODUTO.VRIMPOSTOREP IS NOT NULL)) THEN     
                  UPDATE ITEMPROIMPOS
                     SET VRIMPOSTOVISUIT = DECODE(V_IDPERVISIMPSCRE, 'S', (VRIMPOSTOIT), DECODE(CDFISCALIT, '1', (VRIMPOSTOIT),0))
                   WHERE (CDFILIAL     = P_FILIAL)              AND
                         (NRLANCTONF   = P_LANCTONF)            AND
                         (NRSEQITPROD  = C_PRODUTO.NRSEQITPROD) AND
                         (CDIMPOSTO    = C_PRODUTO.CDIMPOSTO)   AND
                         (NRITPROIMPOS = C_PRODUTO.NRITPROIMPOS);
               ELSIF C_PRODUTO.IDIMPSTCARGTRIB <> 'S' THEN
                  IF V_VRIMPOSTOST > V_VRIMPOSTO THEN
                     UPDATE ITEMPROIMPOS
                     SET VRBASECALCIT = VRBASECALCIT + ((V_TOTAIMPBCALC+V_TOTAIMPBCDES) * V_TAXABASECALC),
                         VRIMPOSTOIT  = 0,
                         VRIMPOSTOVISUIT = 0
                     WHERE (CDFILIAL     = P_FILIAL)              AND
                           (NRLANCTONF   = P_LANCTONF)            AND
                           (NRSEQITPROD  = C_PRODUTO.NRSEQITPROD) AND
                           (CDIMPOSTO    = C_PRODUTO.CDIMPOSTO)   AND
                           (NRITPROIMPOS = C_PRODUTO.NRITPROIMPOS);
                     V_VRIMPOSTO := 0;
                  ELSE
                     -- ESSA CONDICAO SERA FEITA PORQUE A BASE DE CALCULO NAO SERA ALTERADO QUANDO O PRODUTO TIVER PMC,
                     -- ISTO PORQUE A BASE DE CALCULO JA FOI CALCULADA NA PROCEDURE CALCULA_BC_PMC
                     IF (C_PRODUTO.IDUTILBCPMC = W_S) THEN
                        V_FECPPMCAUX := 0;
                        UPDATE ITEMPROIMPOS
                           SET VRBASECALCIT = VRBASECALCIT,
                               VRIMPOSTOIT  = V_VRIMPOSTO - V_VRIMPOSTOST,
                               VRIMPOSTOVISUIT = DECODE(V_IDPERVISIMPSCRE, 'S', (V_VRIMPOSTO - V_VRIMPOSTOST), DECODE(CDFISCALIT, '1', (V_VRIMPOSTO - V_VRIMPOSTOST),0))
                         WHERE (CDFILIAL     = P_FILIAL)              AND
                               (NRLANCTONF   = P_LANCTONF)            AND
                               (NRSEQITPROD  = C_PRODUTO.NRSEQITPROD) AND
                               (CDIMPOSTO    = C_PRODUTO.CDIMPOSTO)   AND
                               (NRITPROIMPOS = C_PRODUTO.NRITPROIMPOS);
                     ELSE
                        V_FECPPMCAUX := ROUND((((V_TOTAIMPBCALC+V_TOTAIMPBCDES) * V_TAXABASECALC) * (C_PRODUTO.VRADICALIQFECP/100)),2);
                        UPDATE ITEMPROIMPOS
                           SET VRBASECALCIT = VRBASECALCIT + ((V_TOTAIMPBCALC+V_TOTAIMPBCDES) * V_TAXABASECALC),
                               VRIMPOSTOIT  = V_VRIMPOSTO - V_VRIMPOSTOST,
                               VRIMPOSTOVISUIT = DECODE(V_IDPERVISIMPSCRE, 'S', (V_VRIMPOSTO - V_VRIMPOSTOST), DECODE(CDFISCALIT, '1', (V_VRIMPOSTO - V_VRIMPOSTOST),0)),
                               VRADICFECP  = VRADICFECP + ROUND((((V_TOTAIMPBCALC+V_TOTAIMPBCDES) * V_TAXABASECALC) * (VRADICALIQFECP/100)),2)
                         WHERE (CDFILIAL     = P_FILIAL)              AND
                               (NRLANCTONF   = P_LANCTONF)            AND
                               (NRSEQITPROD  = C_PRODUTO.NRSEQITPROD) AND
                               (CDIMPOSTO    = C_PRODUTO.CDIMPOSTO)   AND
                               (NRITPROIMPOS = C_PRODUTO.NRITPROIMPOS);
                     END IF;
                     V_VRIMPOSTO := V_VRIMPOSTO - V_VRIMPOSTOST;
                  END IF;
               END IF;
            END IF;
            /* Rotina para calcular o ICMS ST considerando % carga tributaria media */
            IF V_CDIMPOSTRIB IS NOT NULL THEN
               BEGIN
                  SELECT NVL(VRCNAEBC, 0),
                         NVL(VRMVA, 0)
                    INTO V_VRPRODUTOBC,
                         V_VRMVA
                    FROM VRPERCCARGTRIBCNAE
                   WHERE IDENTRSAIDOP = w_S
                     AND CDTIPOOPER   = P_TIPOOPER
                     AND CDPAIS       = V_PAISDEST
                     AND SGESTADO     = V_ESTADEST
                     AND CDCNAE       = V_CDCNAECLIE
                     AND IDOPTANTESN  = V_IDOPTANTESNCLIE;
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_VRPRODUTOBC := 0;
                     V_VRMVA := 0;
               END;
               IF V_VRPRODUTOBC = 0 THEN
                  BEGIN
                     SELECT NVL(VRPRODUTOBC, 0)
                       INTO V_VRPRODUTOBC
                       FROM VRPERCCARGTRIB
                      WHERE IDENTRSAIDOP = w_S
                        AND CDTIPOOPER   = P_TIPOOPER
                        AND CDPAIS       = V_PAISDEST
                        AND SGESTADO     = V_ESTADEST
                        AND CDPRODUTO    = C_PRODUTO.CDPRODUTO;
                  EXCEPTION
                     When No_Data_Found Then
                        V_VRPRODUTOBC := 0;
                  END;
               END IF;
               IF (V_VRPRODUTOBC > 0) THEN
                  BEGIN
                     SELECT I.CDIMPOSTO, I.VRIMPOSTOIT, I.VRBASECALCIT
                       INTO V_CDIMPOSTOICMS, V_VRIMPOSTOICMS, V_VRBASECALCICMS
                       FROM IMPOSTONFE N, IMPOSTO P, ITEMPROIMPOS I
                      WHERE N.CDIMPOSTONFE = P.CDIMPOSTONFE
                        AND N.CDIMPOSTONFE = '00'
                        AND I.CDFILIAL     = P_FILIAL
                        AND I.NRLANCTONF   = P_LANCTONF
                        AND I.NRSEQITPROD = C_PRODUTO.NRSEQITPROD
                        AND I.CDIMPOSTO = P.CDIMPOSTO
                        AND NOT P.CDIMPOSTRIB IS NULL
                        AND I.NRITPROIMPOS = '1';
                  EXCEPTION
                     When No_Data_Found Then
                        V_CDIMPOSTOICMS := NULL; V_VRIMPOSTOICMS := 0; V_VRBASECALCICMS := 0;
                  END;
                  DELETE ALIQTEMP
                   WHERE NRALIQTEMP = V_ALIQTEMP;
                  /* Verifica grupo fiscal */
                  SELECT MAX(IDGRUPFISSRV)
                  INTO V_UTGRUPFISCS
                  FROM IMPOSTO
                  WHERE CDIMPOSTO = V_CDIMPOSTOICMS;
                  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_CLIENTE    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_CLIENTE;
                     END IF;
                     CONSULTA_ALIQUOTA(V_CDIMPOSTOICMS, w_S, 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, NULL, NULL, C_PRODUTO.IDORIGEMPROD);
                  ELSE
                     CONSULTA_ALIQUOTA(V_CDIMPOSTOICMS, w_S, 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_CDGRUPOFISC, P_TIPOOPER,
                                       NULL, NULL, NULL, NULL, NULL, NULL, C_PRODUTO.IDORIGEMPROD);
                  END IF;
                  SELECT NVL(MAX(VRALIQUTMP),0)
                    INTO V_VRALIQUTMPDEST
                    FROM ALIQTEMP
                   WHERE (NRALIQTEMP = V_ALIQTEMP);
                  IF (V_VRALIQUTMPDEST <> 0) THEN
                     IF V_VRMVA > 0 THEN
                        V_VRBASECALCICMS :=  V_VRBASECALCICMS + (V_VRBASECALCICMS * (V_VRMVA/100));
                     END IF;
                     V_IMPOSTOIT  :=  ROUND(V_VRBASECALCICMS * (V_VRPRODUTOBC/100), 2);
                     V_BASECALCTO :=  ROUND(((V_VRIMPOSTOICMS + V_IMPOSTOIT) / (V_VRALIQUTMPDEST/100)),2);
                     UPDATE ITEMPROIMPOS
                        SET VRBASECALCIT = V_BASECALCTO,
                            VRIMPOSTOIT  = V_IMPOSTOIT,
                            VRIMPOSTOVISUIT = DECODE(V_IDPERVISIMPSCRE, 'S', V_IMPOSTOIT, DECODE(CDFISCALIT, '1', V_IMPOSTOIT,0))
                      WHERE (CDFILIAL     = P_FILIAL)              AND
                            (NRLANCTONF   = P_LANCTONF)            AND
                            (NRSEQITPROD  = C_PRODUTO.NRSEQITPROD) AND
                            (CDIMPOSTO    = C_PRODUTO.CDIMPOSTO)   AND
                            (NRITPROIMPOS = C_PRODUTO.NRITPROIMPOS);
                  END IF;
                  DELETE ALIQTEMP
                   WHERE NRALIQTEMP = V_ALIQTEMP;
               END IF;
            END IF;
         END IF;
         V_IMPOCONTAB := 0;
         IF (C_PRODUTO.IDTRATIMPO = w_A) THEN
            IF (((C_PRODUTO.IDIMPORECUP = w_S)  AND (C_PRODUTO.CDFISCALIT = w_1)) OR
                ((C_PRODUTO.IDIMPORECUP <> w_S) AND (C_PRODUTO.CDCCTBLPASS IS NOT NULL))) AND
               (V_CDIMPOSTRIB IS NULL) AND (C_PRODUTO.IDTIPCONTAB = w_D) THEN
               IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (NVL(V_IDORIGDESTNF, 'C') <> 'L') THEN
                  UPDATE ITEMPRODUTO
                  SET VRBRUTITEM = TRUNC((VRBRUTITEM + V_VRIMPOSTO),2)
                  WHERE CDFILIAL    = P_FILIAL   AND
                        NRLANCTONF  = P_LANCTONF AND
                        NRSEQITPROD = C_PRODUTO.NRSEQITPROD;
               ELSE
                  UPDATE ITEMPRODUTO
                  SET VRBRUTITEM = (VRBRUTITEM + V_VRIMPOSTO)
                  WHERE CDFILIAL    = P_FILIAL   AND
                        NRLANCTONF  = P_LANCTONF AND
                        NRSEQITPROD = C_PRODUTO.NRSEQITPROD;
               END IF;
            ELSE
               IF ((V_CDIMPOSTRIB IS NOT NULL) AND (C_PRODUTO.IDTRIMPSTII = w_0)) OR
                   (V_CDIMPOSTRIB IS NULL) THEN
                  IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (NVL(V_IDORIGDESTNF, 'C') <> 'L') THEN
                     UPDATE ITEMPRODUTO
                     SET VRBRUTITEM = TRUNC((VRBRUTITEM + V_VRIMPOSTO + C_PRODUTO.VRADICFECP + V_FECPPMCAUX), 2),
                         VRCONTITEM = TRUNC((VRCONTITEM + V_VRIMPOSTO + C_PRODUTO.VRADICFECP + V_FECPPMCAUX), 2)
                     WHERE CDFILIAL    = P_FILIAL   AND
                           NRLANCTONF  = P_LANCTONF AND
                           NRSEQITPROD = C_PRODUTO.NRSEQITPROD;
                  ELSE
                     UPDATE ITEMPRODUTO
                     SET VRBRUTITEM = ROUND(VRBRUTITEM + V_VRIMPOSTO + C_PRODUTO.VRADICFECP + V_FECPPMCAUX, 2),
                         VRCONTITEM = ROUND(VRCONTITEM + V_VRIMPOSTO + C_PRODUTO.VRADICFECP + V_FECPPMCAUX, 2)
                     WHERE CDFILIAL    = P_FILIAL   AND
                           NRLANCTONF  = P_LANCTONF AND
                           NRSEQITPROD = C_PRODUTO.NRSEQITPROD;
                  END IF;
               END IF;
            END IF;
         ELSIF (C_PRODUTO.IDTRATIMPO = w_D) THEN
            IF ((C_PRODUTO.IDIMPORECUP = w_S) AND (C_PRODUTO.CDFISCALIT = w_1)) OR
               ((C_PRODUTO.IDIMPORECUP <> w_S) AND (C_PRODUTO.CDCCTBLATIV IS NOT NULL)) AND
               (C_PRODUTO.IDTIPCONTAB = w_D) THEN
               IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (NVL(V_IDORIGDESTNF, 'C') <> 'L') THEN
                  UPDATE ITEMPRODUTO
                  SET VRBRUTITEM = TRUNC((VRBRUTITEM - V_VRIMPOSTO),2)
                  WHERE CDFILIAL    = P_FILIAL   AND
                        NRLANCTONF  = P_LANCTONF AND
                        NRSEQITPROD = C_PRODUTO.NRSEQITPROD;
               ELSE
                  UPDATE ITEMPRODUTO
                  SET VRBRUTITEM = VRBRUTITEM - V_VRIMPOSTO
                  WHERE CDFILIAL    = P_FILIAL   AND
                        NRLANCTONF  = P_LANCTONF AND
                        NRSEQITPROD = C_PRODUTO.NRSEQITPROD;
               END IF;
            ELSE
               IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (NVL(V_IDORIGDESTNF, 'C') <> 'L') THEN
                  UPDATE ITEMPRODUTO
                  SET VRBRUTITEM = TRUNC((VRBRUTITEM - V_VRIMPOSTO),2),
                      VRCONTITEM = TRUNC((VRCONTITEM - V_VRIMPOSTO),2)
                  WHERE CDFILIAL    = P_FILIAL   AND
                        NRLANCTONF  = P_LANCTONF AND
                        NRSEQITPROD = C_PRODUTO.NRSEQITPROD;
               ELSE
                  UPDATE ITEMPRODUTO
                  SET VRBRUTITEM = VRBRUTITEM - V_VRIMPOSTO,
                      VRCONTITEM = VRCONTITEM - V_VRIMPOSTO
                  WHERE CDFILIAL    = P_FILIAL   AND
                        NRLANCTONF  = P_LANCTONF AND
                        NRSEQITPROD = C_PRODUTO.NRSEQITPROD;
               END IF;
            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_VRIMPOSTO;
               END IF;
            ELSE
               IF (C_PRODUTO.CDCCTBLATIV IS NULL) THEN
                  V_IMPOCONTAB := - V_VRIMPOSTO;
               ELSE
                  IF C_PRODUTO.IDDESCRFONTE = 'N' THEN
                     V_IMPOCONTAB := - V_VRIMPOSTO;
                     UPDATE ITEMPRODUTO
                     SET VRBRUTITEM = ROUND(VRBRUTITEM - V_VRIMPOSTO,5)
                     WHERE CDFILIAL    = P_FILIAL   AND
                           NRLANCTONF  = P_LANCTONF AND
                           NRSEQITPROD = C_PRODUTO.NRSEQITPROD;
                  END IF;
               END IF;
            END IF;
            IF C_PRODUTO.IDTIPCONTAB = w_D THEN
               IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (NVL(V_IDORIGDESTNF, 'C') <> 'L') THEN
                  UPDATE ITEMPRODUTO
                  SET VRCONTITEM = TRUNC((VRCONTITEM + V_IMPOCONTAB),2)
                  WHERE CDFILIAL    = P_FILIAL   AND
                        NRLANCTONF  = P_LANCTONF AND
                        NRSEQITPROD = C_PRODUTO.NRSEQITPROD;
               ELSE
                  UPDATE ITEMPRODUTO
                  SET VRCONTITEM = VRCONTITEM + V_IMPOCONTAB
                  WHERE CDFILIAL    = P_FILIAL   AND
                        NRLANCTONF  = P_LANCTONF AND
                        NRSEQITPROD = C_PRODUTO.NRSEQITPROD;
               END IF;
            END IF;
         ELSIF C_PRODUTO.IDTRATIMPO = w_V THEN
            IF (V_ORIGDESTOP = w_L) THEN
               V_IDDESCIMPRECCONT := 'N';
               BEGIN
                  SELECT NVL(IDDESCIMPRECCOFI, 'N')
                    INTO V_IDDESCIMPRECCONT
                    FROM TIPOOPERAC
                   WHERE CDTIPOOPER   = P_TIPOOPER
                     AND IDORIGDESTOP = w_L
                     AND IDENTRSAIDOP = w_S;
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_IDDESCIMPRECCONT := 'N';
               END;
            END IF;
            IF (C_PRODUTO.IDIMPORECUP = w_S) AND (V_IDORIGDESTNF = w_L) AND (V_IDDESCIMPRECCONT = 'N')THEN
               IF (C_PRODUTO.CDCCTBLPASS IS NOT NULL) AND
                  (C_PRODUTO.CDFISCALIT = w_1) THEN
                  V_IMPOCONTAB := - V_VRIMPOSTO;
               END IF;
            END IF;
            IF C_PRODUTO.IDTIPCONTAB = w_D THEN
               IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (NVL(V_IDORIGDESTNF, 'C') <> 'L') THEN
                  UPDATE ITEMPRODUTO
                  SET VRCONTITEM = TRUNC((VRCONTITEM + V_IMPOCONTAB),2)
                  WHERE CDFILIAL    = P_FILIAL   AND
                        NRLANCTONF  = P_LANCTONF AND
                        NRSEQITPROD = C_PRODUTO.NRSEQITPROD;
               ELSE
                  UPDATE ITEMPRODUTO
                  SET VRCONTITEM = VRCONTITEM + V_IMPOCONTAB
                  WHERE CDFILIAL    = P_FILIAL   AND
                        NRLANCTONF  = P_LANCTONF AND
                        NRSEQITPROD = C_PRODUTO.NRSEQITPROD;
               END IF;
            END IF;
         END IF;
         -- EM MG O CALCULO DA BASE E REALIZADO DE UMA FORMA DIFERENTE DE ACORDO COM A
         -- ORIENTACAO TRIBUTARIA DOLT/SUTRI N 003/2016. PARA ESTE PROCESSO E NECESSARIO
         -- CALCULAR O IMPOSTO POR DENTRO (ELE COMPONDO A BASE DE CALCULO DELE MESMO)
         IF (V_IDCALCDIFALDENT = 'S') THEN
            IF ((V_PAISDEST = '0055') AND (UPPER(V_ESTADEST) = 'MG')) AND ((V_PAISORIG = '0055') AND (UPPER(V_ESTAORIG) = 'MG')) THEN
               IF (V_IDCONSFINAL = 'S') THEN
                  IF (V_VRADICALIQFECP IS NOT NULL) AND (V_VRADICALIQFECP > 0) THEN
                     IF (V_IDUTILPVRIMPBC = 'S') THEN
                        IF C_PRODUTO.CDIMPOSTONFE = '00' THEN
                           --V_BASECALCIT := V_BASECALCIT/((100-V_ALIQUTMP)/100);
                           UPDATE ITEMPROIMPOS
                              SET VRBASECALCIT = VRBASECALCIT/((100-V_ALIQUTMP)/100)
                            WHERE (CDFILIAL     = P_FILIAL)              AND
                                  (NRLANCTONF   = P_LANCTONF)            AND
                                  (NRSEQITPROD  = C_PRODUTO.NRSEQITPROD) AND
                                  (CDIMPOSTO    = C_PRODUTO.CDIMPOSTO)   AND
                                  (NRITPROIMPOS = C_PRODUTO.NRITPROIMPOS);
                        END IF;
                     END IF;
                  END IF;
              END IF;
            ELSIF ((V_PAISORIG = '0055') AND (UPPER(V_ESTAORIG) = 'MG')) THEN
               V_ALIQICMSDEST := 0;
               V_ALIQFECPDEST := 0;
               IF (V_IDINTEREST = 'S') AND (V_IDCONSFINAL = 'S') AND (V_IDCONTRIBICMSAUX = 'N') AND (V_IDPRESENCIAL <> '1') THEN
                  IF C_PRODUTO.CDIMPOSTONFE = '00' THEN
                     -- CONSULTANDO A ALIQUOTA INTERNA DO IMPOSTO
                     DELETE
                       FROM ALIQTEMP
                      WHERE NRALIQTEMP = V_ALIQTEMP;
                     IF C_PRODUTO.IDUTMUNIORIG = w_D THEN
                        CONSULTA_ALIQUOTA(C_PRODUTO.CDIMPOSTO, w_S, 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, NULL, NULL, C_PRODUTO.IDORIGEMPROD);
                     ELSE
                        CONSULTA_ALIQUOTA(C_PRODUTO.CDIMPOSTO, w_S, P_EMPRESA, C_PRODUTO.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, NULL, NULL, C_PRODUTO.IDORIGEMPROD);
                     END IF;
                     BEGIN
                        SELECT MAX(VRALIQUTMP), MAX(VRADICALIQFECP)
                          INTO V_ALIQICMSDEST, V_ALIQFECPDEST
                          FROM ALIQTEMP
                         WHERE NRALIQTEMP = V_ALIQTEMP;
                     EXCEPTION
                        WHEN NO_DATA_FOUND THEN
                           V_ALIQICMSDEST := NULL;
                           V_ALIQFECPDEST := NULL;
                     END;
                     IF V_ALIQICMSDEST IS NULL THEN
                        BEGIN
                           SELECT NVL(CONSULTA_QUADRO_ALIQUOTAS(V_ESTADEST, V_ESTADEST), 0)
                             INTO V_ALIQICMSDEST
                             FROM DUAL;
                        EXCEPTION
                           WHEN NO_DATA_FOUND THEN
                              V_ALIQICMSDEST := 0;
                        END;
                     END IF;
                     -- CONSULTANDO A ALIQUOTA DO FCP (FUNDO DE COMBATE A POBREZA) QUANDO ELE ESTA CADASTRADO COMO IMPOSTO
                     IF (V_ALIQFECPDEST = 0) OR (V_ALIQFECPDEST IS NULL) THEN
                        BEGIN
                           SELECT CDIMPOSTO
                             INTO V_CDIMPOSTOFECP
                             FROM IMPOSTO
                            WHERE CDIMPOSTONFE = '01';
                        EXCEPTION
                           WHEN NO_DATA_FOUND THEN
                              V_CDIMPOSTOFECP := NULL;
                        END;
                        IF V_CDIMPOSTOFECP IS NOT NULL THEN
                           DELETE
                             FROM ALIQTEMP
                            WHERE NRALIQTEMP = V_ALIQTEMP;
                           --VERIFICANDO SE EXISTE A INCIDENCIA DE FECP PARA O PRODUTO
                           IF C_PRODUTO.IDUTMUNIORIG = w_D THEN
                              CONSULTA_ALIQUOTA(V_CDIMPOSTOFECP, w_S, 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, NULL, NULL, C_PRODUTO.IDORIGEMPROD);
                           ELSE
                              CONSULTA_ALIQUOTA(V_CDIMPOSTOFECP, w_S, P_EMPRESA, C_PRODUTO.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, NULL, NULL, C_PRODUTO.IDORIGEMPROD);
                           END IF;
                           BEGIN
                              SELECT NVL(MAX(VRALIQUTMP), 0)
                                INTO V_ALIQFECPDEST
                                FROM ALIQTEMP
                               WHERE NRALIQTEMP = V_ALIQTEMP;
                           EXCEPTION
                              WHEN NO_DATA_FOUND THEN
                                 V_ALIQFECPDEST := 0;
                           END;
                        ELSE
                           V_ALIQFECPDEST := 0;
                        END IF;
                     END IF;
                     -- REALIZANDO O CALCULO DA BASE COM O IMPOSTO POR DENTRO
                     -- BASE DE CALCULO REAL = BASE DE CALCULO / (1 - ((ALIQUOTA DO IMPOSTO + ALIQUOTA DO FCP) / 100)
                     BEGIN
                     SELECT MAX(VRBASECALCIT)
                       INTO V_BASECALCIT
                       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_BASECALCIT := 0;
                     END;
                     IF V_BASECALCIT > 0 THEN
                        V_BASECALCIT := V_BASECALCIT/((100-(V_ALIQICMSDEST+V_ALIQFECPDEST))/100);
                        V_IMPOSTOIT := V_BASECALCIT * V_TAXAALIQUOTA;
                        UPDATE ITEMPROIMPOS
                           SET VRBASECALCIT = V_BASECALCIT,
                               VRIMPOSTOIT  = V_IMPOSTOIT,
                               VRIMPOSTOVISUIT = DECODE(V_IDPERVISIMPSCRE, 'S', V_IMPOSTOIT, DECODE(CDFISCALIT, '1', V_IMPOSTOIT,0))
                         WHERE (CDFILIAL     = P_FILIAL)              AND
                               (NRLANCTONF   = P_LANCTONF)            AND
                               (NRSEQITPROD  = C_PRODUTO.NRSEQITPROD) AND
                               (CDIMPOSTO    = C_PRODUTO.CDIMPOSTO)   AND
                               (NRITPROIMPOS = C_PRODUTO.NRITPROIMPOS);
                     END IF;
                  END IF;
               END IF;
            END IF;
         END IF;
      END LOOP; --fim do loop c_produto
      FOR C_ITEM IN (SELECT II.CDIMPOSTO,  I.NRSEQITPROD, II.NRITPROIMPOS
                  FROM ITEMPRODUTO I, ITEMPROIMPOS II
                  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 ) LOOP
         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_ITEM.CDIMPOSTO)
         LOOP
            V_ICMS := 'S';
         END LOOP;
         IF (V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')  AND (V_ICMS = 'S') THEN
            UPDATE ITEMPROIMPOS
               SET VRCONTITIMP  = TRUNC(VRCONTITIMP,2),
                   VRBASECALCIT = TRUNC(VRBASECALCIT,2),
                   VRIMPOSTOIT  = TRUNC(VRIMPOSTOIT,2),
                   VRIMPOSTOVISUIT = TRUNC(VRIMPOSTOVISUIT,2)
             WHERE (CDFILIAL     = P_FILIAL) AND
                   (NRLANCTONF   = P_LANCTONF) AND
                   (CDIMPOSTO    = C_ITEM.CDIMPOSTO) AND
                   (NRSEQITPROD  = C_ITEM.NRSEQITPROD) AND
                   (NRITPROIMPOS = C_ITEM.NRITPROIMPOS);
         ELSE
           UPDATE ITEMPROIMPOS
               SET VRCONTITIMP  = ROUND(VRCONTITIMP,2),
                   VRBASECALCIT = ROUND(VRBASECALCIT,2),
                   VRIMPOSTOIT  = ROUND(VRIMPOSTOIT,2),
                   VRIMPOSTOVISUIT = ROUND(VRIMPOSTOVISUIT,2)
             WHERE (CDFILIAL     = P_FILIAL) AND
                   (NRLANCTONF   = P_LANCTONF) AND
                   (CDIMPOSTO    = C_ITEM.CDIMPOSTO) AND
                   (NRSEQITPROD  = C_ITEM.NRSEQITPROD) AND
                   (NRITPROIMPOS = C_ITEM.NRITPROIMPOS);
         END IF;
      END LOOP;
   --FIM DA ATUALIZACAO NA TABELA DE ITEMPROIMPOS
   --TOTALIZACAO DOS IMPOSTOS
      DELETE IMPOSNFTOT
      WHERE (CDFILIAL = P_FILIAL) AND
            (NRLANCTONF = P_LANCTONF);
      FOR C_IMPOSNFTOT IN (SELECT IT.CDIMPOSTO
                           FROM ITEMPROIMPOS IT
                           WHERE (IT.CDFILIAL   = P_FILIAL) AND
                                 (IT.NRLANCTONF = P_LANCTONF)
                           GROUP BY IT.CDIMPOSTO) LOOP
         V_IMPOSTOIT  := 0;
         V_BASECALCIT := 0;
         SELECT NVL(SUM(IT.VRIMPOSTOIT),0),
                NVL(SUM(IT.VRBASECALCIT),0),
                NVL(SUM(IT.VRADICFECP),0)
         INTO   V_IMPOSTOIT,
                V_BASECALCIT,
                V_VRADICFECPNFTOT
         FROM ITEMPROIMPOS IT, IMPOSTO I
         WHERE (IT.CDFILIAL   = P_FILIAL)               AND
               (IT.NRLANCTONF = P_LANCTONF)             AND
               (IT.CDIMPOSTO  = C_IMPOSNFTOT.CDIMPOSTO) AND
               (IT.CDIMPOSTO  = I.CDIMPOSTO);
         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_IMPOSNFTOT.CDIMPOSTO)
         LOOP
            V_ICMS := 'S';
         END LOOP;
         IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (V_ICMS = 'S') THEN
            INSERT INTO IMPOSNFTOT(CDFILIAL, NRLANCTONF, CDIMPOSTO, VRTOTIMPONF, VRTOTBCALCNF,
                                   VRADICFECP)
                           VALUES (P_FILIAL, P_LANCTONF, C_IMPOSNFTOT.CDIMPOSTO, TRUNC(V_IMPOSTOIT ,V_NRDECITOTANF), TRUNC(V_BASECALCIT, V_NRDECITOTANF),
                                   V_VRADICFECPNFTOT);
         ELSE
            INSERT INTO IMPOSNFTOT(CDFILIAL, NRLANCTONF, CDIMPOSTO, VRTOTIMPONF, VRTOTBCALCNF,
                                   VRADICFECP)
                           VALUES (P_FILIAL, P_LANCTONF, C_IMPOSNFTOT.CDIMPOSTO, ROUND(V_IMPOSTOIT ,V_NRDECITOTANF), ROUND(V_BASECALCIT, V_NRDECITOTANF),
                                   V_VRADICFECPNFTOT);
         END IF;
      END LOOP;
   --INCLUSAO DOS IMPOSTOS DE CORPO DE NOTA EM CASO DE NOTA FISCAL--------------------------------------------------------------------------
      V_SEQUIMPOSTNF := w_01;
      DELETE IMPOSTONF
      WHERE (CDFILIAL   = P_FILIAL) AND
            (NRLANCTONF = P_LANCTONF);
      CONSULTA_INCIDENCIA(w_S, P_EMPRESA, '', P_INSCESTA, P_TIPOOPER, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC, NULL, V_IDINTEREST);
      FOR C_INCIDENCIA IN (SELECT DISTINCT (CDIMPOTEMP) AS CDIMPOTEMP, CDFISCTEMP, IDUTMUNIORIG,
                                  IDTRATIMPTMP, IDIMPORECUP, CDDETALHEPROD, IP.CDIMPOSTONFE
                           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_UTIBB    := 'N';
         V_SIMPLES  := 'N';
--integracao fiscal especifica com Compass_Argentina atraves da importacao de aliquota do imposto IBB
--A aliquota de imposto 03(ibb) sera cadastrada na tabela paramintegraibb e tera prioridade sobre o
-- cadastro de aliquota realizado em sistema
         /*VERIFICA CST POR IMPOSTO*/
         V_IMPOICMS := NULL;
         V_CDGRUPOFISCAUX := NULL;
         SELECT MAX(G.CDGRUPOFISC)
           INTO V_CDGRUPOFISCAUX
           FROM GRUPOFISCIMPFIL G,
                (SELECT 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 = 'C' THEN
            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;
         ELSE
            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;
         END IF;
         IF V_CDGRUPOFISCAUX IS NULL THEN
            CONSULTA_CST_NFE(w_S, P_EMPRESA, '', P_INSCESTA, P_TIPOOPER, V_CDGRUPOFISC,C_INCIDENCIA.CDIMPOTEMP, V_IDINTEREST, V_IDINTERNA, P_FILIAL, P_LANCTONF, '', V_CDSITTRIBTMP, V_IDMODBCNFE, V_IDMODBCSTNFE, V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, V_IDMOTIDESSTNFE);
         ELSE
            CONSULTA_CST_NFE(w_S, P_EMPRESA, '', P_INSCESTA, P_TIPOOPER, V_CDGRUPOFISCAUX,C_INCIDENCIA.CDIMPOTEMP, V_IDINTEREST, V_IDINTERNA, P_FILIAL, P_LANCTONF, '', V_CDSITTRIBTMP, V_IDMODBCNFE, V_IDMODBCSTNFE, V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, V_IDMOTIDESSTNFE);
         END IF;
         V_CDSIMPLESNACIONAL := NULL;
         V_CDFAIXA := NULL;
         /*SIMPLES NACIONAL*/
         IF (V_CDSITUCRT <> '3') THEN
            CALCULA_ALIQUOTA_SN(P_EMPRESA,
                                P_TIPOOPER,
                                P_INIVALID,
                                SUBSTR(V_FISOPEITEM, 2, 3),
                                C_INCIDENCIA.CDIMPOSTONFE,
                                V_VRSUBLIMITESN,
                                'N',
                                V_RBT12,
                                V_RBA,
                                V_CDSIMPLESNACIONAL,
                                V_CDFAIXA,
                                V_VRALIQSIMPLES);
            IF (V_CDFAIXA IS NOT NULL) OR ((C_INCIDENCIA.CDIMPOSTONFE IN ('00', '31')) AND (V_RBT12 >= 3600000)) THEN
               V_ALIQUTMP     := V_VRALIQSIMPLES;
               V_NRALIQTEMP   := 0;
               V_PARDEDTMP    := 0;
               V_PREDBCTMP    := 0;
               V_TRATIMPST    := w_0;
               V_PBCSUBTRIB   := 0;
               V_IDPMCBASECAL := 'N';
               V_SIMPLES      := 'S';
            END IF;
         END IF;
         IF C_INCIDENCIA.CDIMPOTEMP = '03' THEN
            IF V_IDORIGDESTNF = 'C' THEN
               V_ALIQUTMP := NULL;
               V_DTVINGENTE := NVL(V_DTINIREFEFAT, P_INIVALID);
               SELECT NVL(MAX(VRALIQUOTAIBB),NULL)
               INTO   V_ALIQUTMP
               FROM PARAMINTEGRAIBB
               WHERE CDCLIENTE = P_CLIENTE AND
                     V_DTVINGENTE BETWEEN DTVIGINICIALIBB AND DTVIGFINALIBB;
               IF V_ALIQUTMP IS NOT NULL THEN
                  V_NRALIQTEMP   := 0;
                  V_PARDEDTMP    := 0;
                  V_PREDBCTMP    := 0;
                  V_TRATIMPST    := w_0;
                  V_PBCSUBTRIB   := 0;
                  V_IDPMCBASECAL := 'N';
                  V_UTIBB        := 'S';
               END IF;
            END IF;
         END IF;
         IF (V_SIMPLES = 'N') THEN
            V_CDSIMPLESNACIONAL := NULL;
            V_CDFAIXA := NULL;
            IF (V_UTIBB = 'N')  THEN
               V_ALIQUTMP  := 0;
               V_PARDEDTMP := 0;
               V_PREDBCTMP := 0;
               V_ALIQUTMP  := 0;
               IF C_INCIDENCIA.IDUTMUNIORIG = w_D THEN
                  /* CONSIDERA O MUNICIPIO DE DESTINO */
                  CONSULTA_ALIQUOTA(C_INCIDENCIA.CDIMPOTEMP, w_S, 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 O MUNICIPIO DE ORIGEM*/
                  CONSULTA_ALIQUOTA(C_INCIDENCIA.CDIMPOTEMP, w_S, 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(NRALIQTEMP), MAX(VRPARDEDTMP),            MAX(VRPREDBCTMP),
                      MAX(VRALIQUTMP), NVL(MAX(IDTRIMPSTTMP), w_0), NVL(MAX(VRPBCSTTMP),0)
               INTO   V_NRALIQTEMP, V_PARDEDTMP, V_PREDBCTMP,
                      V_ALIQUTMP,   V_TRATIMPST, V_PBCSUBTRIB
               FROM ALIQTEMP
               WHERE (NRALIQTEMP = V_ALIQTEMP);
               IF (V_ALIQUTMP IS NULL) THEN
                  V_ALIQUTMP := 0;
               END IF;
            END IF;
         END IF;
         V_PRODUENCARGO := 0;
         SELECT SUM(VRITEMENCA) AS VRSOMAITEM
         INTO   V_SOMAITEM
         FROM ITEMENCARGO IE, ENCARGO EN, 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 ITEMENCARGO IE, ENCARGO EN, 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;
         IF (V_ALIQUTMP IS NULL) THEN --VERIFICAR VALOR DA ALIQUOTA P/ IMPOSTO RECUPERAVEL COM COD. FISCAL = 3
            V_ALIQUTMP := 0;
         END IF;
         IF (V_PREDBCTMP IS NULL) THEN
            V_PREDBCTMP := 0;
         END IF;
         IF (V_PARDEDTMP IS NULL) THEN
             V_PARDEDTMP := 0;
         END IF;
         V_PRODUENCARGO := V_SOMAITEM - V_DESCITEM;
         V_TAXABASECALC := (100 - V_PREDBCTMP)/100;
         V_TAXAALIQUOTA := (V_ALIQUTMP/100);
         V_TAXABCSUBSTR := 1 + (V_PBCSUBTRIB/100);
         V_BASECALCIT   := (V_LIQUIDO + V_PRODUENCARGO) * V_TAXABASECALC;
         V_PERDBCALC    := 100 - V_PREDBCTMP;
         IF V_PBCSUBTRIB > 0 THEN
            V_BASECALCIT := (V_BASECALCIT * V_TAXABCSUBSTR);
			   V_PREDBCSTIT := V_PREDBCTMP;
            V_PREDBCTMP  := V_PBCSUBTRIB;
            V_PERDBCALC  := 0;
         ELSE
            V_PREDBCSTIT := V_PREDBCTMP;
         END IF;
         V_CONTIMPO     := V_BASECALCIT;
         V_IMPOSTOIT    := (V_BASECALCIT * V_TAXAALIQUOTA) - V_PARDEDTMP;
         IF V_BASECALCIT < 0 THEN
            V_BASECALCIT := 0;
         END IF;
         V_CONTABCALC := (V_LIQUIDO + V_PRODUENCARGO) - ((V_LIQUIDO + V_PRODUENCARGO) * V_TAXABASECALC);
         V_PERDBCALC  := 100 - V_PREDBCTMP;
         IF V_IMPOSTOIT < 0 THEN
            V_IMPOSTOIT := 0;
         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)
         LOOP
            V_ICMS := 'S';
         END LOOP;
         IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (V_ICMS = 'S') THEN
            INSERT INTO IMPOSNFTOT(CDFILIAL, NRLANCTONF, CDIMPOSTO              , VRTOTIMPONF                              , VRTOTBCALCNF)
                           VALUES (P_FILIAL, P_LANCTONF, C_INCIDENCIA.CDIMPOTEMP, TRUNC(NVL(V_IMPOSTOIT,0), V_NRDECITOTANF), TRUNC(NVL(V_BASECALCIT,0),V_NRDECITOTANF));
         ELSE
            INSERT INTO IMPOSNFTOT(CDFILIAL, NRLANCTONF, CDIMPOSTO              , VRTOTIMPONF                              , VRTOTBCALCNF)
                           VALUES (P_FILIAL, P_LANCTONF, C_INCIDENCIA.CDIMPOTEMP, ROUND(NVL(V_IMPOSTOIT,0), V_NRDECITOTANF), ROUND(NVL(V_BASECALCIT,0),V_NRDECITOTANF));
         END IF;
         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_PREDBCTMP  := 0;
               V_PARDEDTMP  := 0;
            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)
            LOOP
               V_ICMS := 'S';
            END LOOP;
            IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (V_ICMS = 'S') THEN
               INSERT INTO IMPOSTONF(
                  CDFILIAL, NRLANCTONF, CDIMPOSTO, NRIMPOSNF, VRCONTABILNF, VRPERREDBCNF, VRBASECALCNF,
                  VRALIQNF, VRPARDEDNF, VRIMPOSTONF, CDFISCALNF, IDTRIMPOSTNF, CDSITUTRIBIMNFE,  CDTPCREDPICONF, CDNATUBCALPCNF, IDMOTDESONERANF)
               VALUES(
                  P_FILIAL, P_LANCTONF, C_INCIDENCIA.CDIMPOTEMP, V_SEQUIMPOSTNF, TRUNC(V_CONTIMPO,2), V_PREDBCTMP,
                  TRUNC(V_BASECALCIT,2), V_ALIQUTMP, TRUNC(V_PARDEDTMP,2), TRUNC(V_IMPOSTOIT,2), C_INCIDENCIA.CDFISCTEMP, V_TRATIMPST, V_CDSITTRIBTMP, V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, V_IDMOTIDESSTNFE);
            ELSE
               INSERT INTO IMPOSTONF(
                  CDFILIAL, NRLANCTONF, CDIMPOSTO, NRIMPOSNF, VRCONTABILNF, VRPERREDBCNF, VRBASECALCNF,
                  VRALIQNF, VRPARDEDNF, VRIMPOSTONF, CDFISCALNF, IDTRIMPOSTNF, CDSITUTRIBIMNFE, CDTPCREDPICONF, CDNATUBCALPCNF, IDMOTDESONERANF)
               VALUES(
                  P_FILIAL, P_LANCTONF, C_INCIDENCIA.CDIMPOTEMP, V_SEQUIMPOSTNF, ROUND(V_CONTIMPO,2), V_PREDBCTMP,
                  ROUND(V_BASECALCIT,2), V_ALIQUTMP, ROUND(V_PARDEDTMP,2), ROUND(V_IMPOSTOIT,2), C_INCIDENCIA.CDFISCTEMP, V_TRATIMPST, V_CDSITTRIBTMP, V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, V_IDMOTIDESSTNFE);
            END IF;
            V_SEQUIMPOSTNF := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_SEQUIMPOSTNF) + 1)),2,0);
            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, CDSITUTRIBIMNFE,
				      CDTPCREDPICONF, CDNATUBCALPCNF, IDMOTDESONERANF)
               VALUES(
                  P_FILIAL, P_LANCTONF, C_INCIDENCIA.CDIMPOTEMP, V_SEQUIMPOSTNF, V_CONTABCALC, V_PERDBCALC,
                  0, 0, V_PARDEDTMP, 0, 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;
      /*CONTABILIZACAO DOS IMPOSTOS DE CORPO DE NOTA*/
      FOR C_IMPOSCONTAB IN (SELECT VRTOTIMPONF, IDIMPORECUP, CDCCTBLPASS, CDCCTBLATIV,
                                   IDTRATIMPO,  CDFISCTEMP, IDTIPCONTAB
                            FROM IMPOSNFTOT INF, IMPOSTO IP, INCITEMP IT
                            WHERE CDFILIAL      = P_FILIAL      AND
                                  NRLANCTONF    = P_LANCTONF    AND
                                  IP.CDIMPOSTO  = INF.CDIMPOSTO AND
                                  IT.CDIMPOTEMP = IP.CDIMPOSTO  AND
                                  IT.NRINCITEMP = V_INCITEMP    AND
                                  IP.IDPRODNOTA = w_C) LOOP
         IF (C_IMPOSCONTAB.IDTRATIMPO = w_A) THEN
            IF C_IMPOSCONTAB.IDTIPCONTAB = w_D THEN
               V_TOTIMPOCONT := V_TOTIMPOCONT + C_IMPOSCONTAB.VRTOTIMPONF;
            END IF;
            V_TOTIMPOBRUT := V_TOTIMPOBRUT + C_IMPOSCONTAB.VRTOTIMPONF;
         ELSIF (C_IMPOSCONTAB.IDTRATIMPO = w_D) THEN
            IF C_IMPOSCONTAB.IDTIPCONTAB = w_D THEN
               V_TOTIMPOCONT := V_TOTIMPOCONT - C_IMPOSCONTAB.VRTOTIMPONF;
            END IF;
            V_TOTIMPOBRUT := V_TOTIMPOBRUT - C_IMPOSCONTAB.VRTOTIMPONF;
         ELSIF (C_IMPOSCONTAB.IDTRATIMPO = w_R) THEN
            IF (C_IMPOSCONTAB.IDIMPORECUP = w_S) THEN
               IF (C_IMPOSCONTAB.CDCCTBLATIV IS NULL) OR
                  (C_IMPOSCONTAB.CDFISCTEMP <> w_1) AND (C_IMPOSCONTAB.IDTIPCONTAB = w_D) THEN
                  V_TOTIMPOCONT := V_TOTIMPOCONT - C_IMPOSCONTAB.VRTOTIMPONF;
               END IF;
            ELSE
               IF (C_IMPOSCONTAB.CDCCTBLATIV IS NULL) AND (C_IMPOSCONTAB.IDTIPCONTAB = w_D) THEN
                  V_TOTIMPOCONT := V_TOTIMPOCONT - C_IMPOSCONTAB.VRTOTIMPONF;
               END IF;
            END IF;
         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
            IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (NVL(V_IDORIGDESTNF, 'C') <> 'L') THEN
               UPDATE ITEMPRODUTO
               SET VRBRUTITEM = TRUNC(VRBRUTITEM + ((V_TOTIMPOBRUT / V_LIQUIDO) * C_ITPRODUTO.VRLIQUIDO),2),
                   VRCONTITEM = TRUNC(VRCONTITEM + ((V_TOTIMPOCONT / V_LIQUIDO) * C_ITPRODUTO.VRLIQUIDO),2)
               WHERE CDFILIAL    = P_FILIAL   AND
                     NRLANCTONF  = P_LANCTONF AND
                     NRSEQITPROD = C_ITPRODUTO.NRSEQITPROD;
            ELSE
               UPDATE ITEMPRODUTO
               SET VRBRUTITEM = ROUND(VRBRUTITEM + ((V_TOTIMPOBRUT / V_LIQUIDO) * C_ITPRODUTO.VRLIQUIDO),2),
                   VRCONTITEM = ROUND(VRCONTITEM + ((V_TOTIMPOCONT / V_LIQUIDO) * C_ITPRODUTO.VRLIQUIDO),2)
               WHERE CDFILIAL    = P_FILIAL   AND
                     NRLANCTONF  = P_LANCTONF AND
                     NRSEQITPROD = C_ITPRODUTO.NRSEQITPROD;
            END IF;
         END LOOP;
      END IF;
      DELETE INCITEMP
      WHERE NRINCITEMP = V_INCITEMP;
      SELECT SUM(NVL(VRBCICMSSTRETIDO,0)), SUM(NVL(VRICMSSTRETIDO,0))
        INTO V_BCICMSRET, V_ICMSRET
        FROM ITEMPROIMPOS
       WHERE CDFILIAL = P_FILIAL
         AND NRLANCTONF = P_LANCTONF;
      IF V_ICMSRET <> 0 THEN
         SELECT COUNT(*)
           INTO V_EXISTDSDADOSADIC
           FROM DADOSADIC
          WHERE CDFILIAL = P_FILIAL
            AND NRLANCTONF = P_LANCTONF
            AND DSDADOADIC LIKE 'ICMS retido anteriormente por substituicao tributaria: BC %';
         IF V_EXISTDSDADOSADIC = 0 THEN
            /*PREENCHE AS MENSAGENS ATRELADAS A INSCRICAO ESTADUAL*/
            INSERT INTO DADOSADIC(CDFILIAL, NRLANCTONF, NRDADOADIC, DSDADOADIC)
                           VALUES(P_FILIAL, P_LANCTONF, V_DADOADIC, 'ICMS retido anteriormente por substituicao tributaria: BC '||DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(V_BCICMSRET, 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(V_BCICMSRET, 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(V_BCICMSRET, 2), '9999999999999.99')))|| ' Valor '|| DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(V_ICMSRET, 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(V_ICMSRET, 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(V_ICMSRET, 2), '9999999999999.99'))));
            V_DADOADIC := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_DADOADIC) + 1)),3,0);
         ELSE
            UPDATE DADOSADIC
               SET DSDADOADIC = 'ICMS retido anteriormente por substituicao tributaria: BC '||DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(V_BCICMSRET, 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(V_BCICMSRET, 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(V_BCICMSRET, 2), '9999999999999.99')))|| ' Valor '|| DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(V_ICMSRET, 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(V_ICMSRET, 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(V_ICMSRET, 2), '9999999999999.99')))
             WHERE CDFILIAL = P_FILIAL
               AND NRLANCTONF = P_LANCTONF
               AND DSDADOADIC LIKE 'ICMS retido anteriormente por substituicao tributaria: BC %';
         END IF;
      END IF;
      FOR C_ITEMPRODUTO_DIFAL IN (SELECT NRSEQITPROD
                                    FROM ITEMPRODUTO
                                   WHERE CDFILIAL = P_FILIAL
                                     AND NRLANCTONF = P_LANCTONF) LOOP
         GERA_ICMS_INTERESTADUAL(P_FILIAL, P_LANCTONF, C_ITEMPRODUTO_DIFAL.NRSEQITPROD, P_INIVALID);
      END LOOP;
      SELECT MAX(NRDADOADIC)
        INTO V_DADOADIC
        FROM DADOSADIC
       WHERE (CDFILIAL = P_FILIAL)
         AND (NRLANCTONF = P_LANCTONF);
      IF (V_DADOADIC IS NULL) THEN
         V_DADOADIC := W_001;
      ELSE
         V_DADOADIC := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_DADOADIC) + 1)),3,0);
      END IF;
      -- FIM DA TOTALIZACAO DOS IMPOSTOS
      -- NOTAS COM DOCUMENTO DE ORIGEM
      IF (V_IDDEVOLIST = 'S') THEN
         DELETE FROM DADOSADIC
                   WHERE CDFILIAL = P_FILIAL
                     AND NRLANCTONF = P_LANCTONF
                     AND DSDADOADIC LIKE 'Nota de Origem:%';
      -- gravar dados adicionais
                  FOR C_ITEMNOTAFISC IN (SELECT IT.CDFILIALIT, IT.NRLANCTONFIT, NVL(N.NRNOTAFISCALELE, N.NRNOTAFISC) AS NRNOTA,
                                       TO_CHAR(N.DTEMISSAO,  'DD/MM/YYYY') AS DTEMISSAO, N.VRNOTAFISC
                             FROM ITEMNOTAFISC IT, NOTAFISCAL N
                             WHERE IT.CDFILIAL   = P_FILIAL
                               AND IT.NRLANCTONF = P_LANCTONF
                               AND IT.CDFILIALIT   = N.CDFILIAL
                               AND IT.NRLANCTONFIT = N.NRLANCTONF) LOOP
                        INSERT INTO DADOSADIC(CDFILIAL, NRLANCTONF, NRDADOADIC, DSDADOADIC)
                           VALUES(P_FILIAL, P_LANCTONF, V_DADOADIC, 'Nota de Origem: '||C_ITEMNOTAFISC.NRNOTA||' (Emissao: '||C_ITEMNOTAFISC.DTEMISSAO||' Total: '||DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(C_ITEMNOTAFISC.VRNOTAFISC, 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(C_ITEMNOTAFISC.VRNOTAFISC, 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(C_ITEMNOTAFISC.VRNOTAFISC, 2), '9999999999999.99')))|| ' )');
                                  V_DADOADIC := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_DADOADIC) + 1)),3,0);
                  -- dados adicionais para devolucao em lista
                  END LOOP;
      END IF;
	  ELSIF (P_TIPOOPER IN ('07','10')) OR (V_IDOPERDEVONF = w_S) OR (V_ESTORNOCANC = w_S) AND (V_IDNFAJUSTE <> w_S) THEN
      DELETE FROM ITEMPROIMPOS
      WHERE CDFILIAL   = P_FILIAL AND
            NRLANCTONF = P_LANCTONF;
      DELETE FROM ITEMPROIMPOSORIG
      WHERE CDFILIAL   = P_FILIAL AND
            NRLANCTONF = P_LANCTONF;
      V_VRTOTALIPI := 0;
      V_VRTOTALICMSST := 0;
      V_CDENCARGOICMST := NULL;
      V_CDENQLEGALIPI := NULL;
      V_CDCEST := NULL;
      SELECT NVL(MAX(IDGERICMSTDESPA), 'N'), MAX(CDENCARGOICMST), NVL(MAX(IDPEINFICMSTDEME), 'N'), NVL(MAX(IDGERIPIDESPA), 'N')
        INTO V_IDGERICMSTDESPA, V_CDENCARGOICMST, V_IDPEINFICMSTDEME, V_IDGERIPIDESPA
        FROM TIPOOPERAC
       WHERE IDENTRSAIDOP = 'S'
         AND CDTIPOOPER = P_TIPOOPER;
      SELECT MAX(IDUTCTRLFISSAID)
        INTO V_IDUTCTRLFISSAID
        FROM PARAMGERAL;
      SELECT MAX(IDUTCTRLFISSAID)
        INTO V_IDUTCTRLFISFIL
        FROM PARAMFILIAL
       WHERE CDFILIAL = V_CDFILIEMIT;
      IF V_IDUTCTRLFISSAID = 'S' THEN
         V_IDUTCTRLFIS := 'S';
      ELSE
         IF V_IDUTCTRLFISFIL = 'S' THEN
            V_IDUTCTRLFIS := 'S';
         ELSE
            V_IDUTCTRLFIS := 'N';
         END IF;
      END IF;
      V_UPDENCIMPXML := 'N';
      FOR C_ITEMPROD IN (SELECT IT.*, P.CDARVPROD
                         FROM ITEMPRODUTO IT, PRODUTO P
                         WHERE IT.CDFILIAL   = P_FILIAL   AND
                               IT.NRLANCTONF = P_LANCTONF AND
                               IT.CDPRODUTO  = P.CDPRODUTO) LOOP
         V_LIQUIITEM := C_ITEMPROD.VRTOTAITEM - C_ITEMPROD.VRDESCITEM;
         IF (C_ITEMPROD.IDPRODBONIF = 'N') OR (V_CDTIPOOPERBONIF = 'N') THEN
            CONSULTA_CST(w_S, P_EMPRESA, C_ITEMPROD.CDARVPROD, P_INSCESTA, P_TIPOOPER, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC, V_IDINTEREST, V_IDINTERNA, NULL, C_ITEMPROD.IDORIGEMPROD);
         ELSE
            CONSULTA_CST(w_S, P_EMPRESA, C_ITEMPROD.CDARVPROD, P_INSCESTA, V_CDTIPOOPERBONIF, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC, V_IDINTEREST, V_IDINTERNA, NULL, C_ITEMPROD.IDORIGEMPROD);
         END IF;
         SELECT MAX(CDSITTRIBTMP)
         INTO   V_SITUTRIBPR
         FROM CSTTEMP
         WHERE (NRCSTTEMP = V_CSTTEMP);
         IF (V_IDOPERDEVONF <> w_S) THEN
            FOR C_CSTTEMP IN (SELECT DSMENSCSTTMP
                              FROM CSTTEMP
                              WHERE (NRCSTTEMP = V_CSTTEMP) AND
                                    (DSMENSCSTTMP IS NOT NULL) AND
                                    (NOT EXISTS(SELECT DSDADOADIC
                                                FROM DADOSADIC
                                                WHERE (CDFILIAL   = P_FILIAL)   AND
                                                      (NRLANCTONF = P_LANCTONF) AND
                                                      (DSDADOADIC LIKE CSTTEMP.DSMENSCSTTMP || '%')))) LOOP
               IF NOT (C_CSTTEMP.DSMENSCSTTMP IS NULL) THEN
                  /*PREENCHE AS MENSAGENS ATRELADAS AO CST*/
                  INSERT INTO DADOSADIC(CDFILIAL, NRLANCTONF, NRDADOADIC, DSDADOADIC)
                                 VALUES(P_FILIAL, P_LANCTONF, V_DADOADIC, C_CSTTEMP.DSMENSCSTTMP);
                  V_DADOADIC := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_DADOADIC) + 1)),3,0);
               END IF;
            END LOOP;
         END IF;
         IF (C_ITEMPROD.IDPRODBONIF = 'N') OR (V_CDTIPOOPERBONIF = 'N') THEN
            CONSULTA_CFOP(w_S, P_EMPRESA, C_ITEMPROD.CDARVPROD, P_INSCESTA, P_TIPOOPER, V_PAISORIG,
                           V_ESTAORIG, V_PAISCFOP, V_ESTACFOP, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC, P_INIVALID, C_ITEMPROD.IDORIGEMPROD);
         ELSE
            CONSULTA_CFOP(w_S, P_EMPRESA, C_ITEMPROD.CDARVPROD, P_INSCESTA, V_CDTIPOOPERBONIF, V_PAISORIG,
                           V_ESTAORIG, V_PAISCFOP, V_ESTACFOP, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC, P_INIVALID, C_ITEMPROD.IDORIGEMPROD);
         END IF;
         FOR C_CFOPTEMP IN (SELECT DSMENSCFOTMP
                            FROM CFOPTEMP
                            WHERE (NRCFOPTEMP = V_CFOPTEMP) AND
                                  (DSMENSCFOTMP IS NOT NULL) AND
                                  (NOT EXISTS(SELECT DSDADOADIC
                                              FROM DADOSADIC
                                              WHERE (CDFILIAL   = P_FILIAL)   AND
                                                    (NRLANCTONF = P_LANCTONF) AND
                                                    (DSDADOADIC LIKE CFOPTEMP.DSMENSCFOTMP || '%')))) LOOP
            IF NOT(C_CFOPTEMP.DSMENSCFOTMP IS NULL) THEN
               /*PREENCHE AS MENSAGENS ATRELADAS AO CFOP*/
               INSERT INTO DADOSADIC(CDFILIAL, NRLANCTONF, NRDADOADIC, DSDADOADIC)
                              VALUES(P_FILIAL, P_LANCTONF, V_DADOADIC, C_CFOPTEMP.DSMENSCFOTMP);
               V_DADOADIC := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_DADOADIC) + 1)),3,0);
            END IF;
         END LOOP;
         IF (NVL(V_CFOPINFUSU, 'N') <> 'S') AND (V_CDFISCOPERREGRA IS NOT NULL) THEN
            V_DSCDFISOPEITREGRA := SUBSTR(DESCRICAO_CFOP(V_CDFISCOPERREGRA),1,45);
         END IF;
         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;
         END IF;
         SELECT MAX(CDFISOPETMP), MAX(CDSUFCFOPTMP),SUBSTR(MAX(DSCFOPTMP),1,50)
         INTO   V_FISOPEITEM,     V_SUFXCFOPPR,     V_DSCDFISOPEIT
         FROM CFOPTEMP
         WHERE NRCFOPTEMP = V_CFOPTEMP;
         IF (C_ITEMPROD.IDPRODBONIF = 'N') OR (V_CDTIPOOPERBONIF = 'N') THEN
            CONSULTA_CSOSN('S', P_EMPRESA, C_ITEMPROD.CDARVPROD, P_INSCESTA, P_TIPOOPER, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC,V_IDINTEREST, V_CDFISCOPERSN);
         ELSE
            CONSULTA_CSOSN('S', P_EMPRESA, C_ITEMPROD.CDARVPROD, P_INSCESTA, V_CDTIPOOPERBONIF, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC,V_IDINTEREST, V_CDFISCOPERSN);
         END IF;
         IF (NVL(V_CFOPINFUSU, 'N') <> 'S') AND (V_CDFISCOPERREGRA IS NOT NULL) THEN
            V_FISOPEITEM := NVL(V_CDFISCOPERREGRA, V_FISOPEITEM);
            V_DSCDFISOPEITREGRA := SUBSTR(DESCRICAO_CFOP(V_CDFISCOPERREGRA),1,45);
         END IF;
         UPDATE ITEMPRODUTO
         SET CDFISOPEITEM = V_FISOPEITEM,
             CDSUFXCFOPPR = V_SUFXCFOPPR,
             CDSITUTRIBPR  = NVL(V_SITUTRIBPR, C_ITEMPROD.CDSITUTRIBPR),
             DSCDFISOPEIT = V_DSCDFISOPEIT,
             CDFISCOPERSN = V_CDFISCOPERSN
         WHERE CDFILIAL    = P_FILIAL     AND
               NRLANCTONF  = P_LANCTONF   AND
               NRSEQITPROD = C_ITEMPROD.NRSEQITPROD;
         IF V_IDOPERDEVONF = w_S THEN
            FOR C_ITEMNOTAFISC IN (SELECT CDFILIALIT, NRLANCTONFIT
                                   FROM ITEMNOTAFISC
                                   WHERE CDFILIAL   = P_FILIAL AND
                                         NRLANCTONF = P_LANCTONF) LOOP
               Begin
                  SELECT SUM(I.QTITEMPROD)
                    INTO V_SOMAQITEMPROD
                    FROM ITEMPRODUTO I
                   WHERE CDFILIAL    = C_ITEMNOTAFISC.CDFILIALIT                                          AND
                         NRLANCTONF  = C_ITEMNOTAFISC.NRLANCTONFIT                                        AND
                         CDPRODUTO   = C_ITEMPROD.CDPRODUTO                                               AND
                         ROUND(VRUNITITEM, V_NRDECITOTANF) = ROUND(C_ITEMPROD.VRUNITITEM, V_NRDECITOTANF) AND
                         (NVL(NRLOTEESTQ, ' ')  = (NVL(C_ITEMPROD.NRLOTEESTQ, ' ')))                      AND
                         (NVL(NRSUBLOTE , ' ')  = (NVL(C_ITEMPROD.NRSUBLOTE , ' ')));
                  SELECT NVL(MAX(C_ITEMPROD.QTITEMPROD / V_SOMAQITEMPROD),1) AS VRFATOCONV,
                         NVL(SUM(VRBRUTITEM),0), NVL(SUM(VRCONTITEM),0), NVL(SUM(VRENCARGOIMPXML), 0)
                    INTO V_VRFATOCONV, V_VRBRUTO, V_VRCONTAB, V_VRENCARGOIMPXML
                    FROM ITEMPRODUTO I
                   WHERE CDFILIAL    = C_ITEMNOTAFISC.CDFILIALIT                                          AND
                         NRLANCTONF  = C_ITEMNOTAFISC.NRLANCTONFIT                                        AND
                         CDPRODUTO   = C_ITEMPROD.CDPRODUTO                                               AND
                         ROUND(VRUNITITEM, V_NRDECITOTANF) = ROUND(C_ITEMPROD.VRUNITITEM, V_NRDECITOTANF) AND
                         (NVL(NRLOTEESTQ, ' ')  = (NVL(C_ITEMPROD.NRLOTEESTQ, ' ')))                      AND
                         (NVL(NRSUBLOTE , ' ')  = (NVL(C_ITEMPROD.NRSUBLOTE , ' ')));
               Exception
                  When No_Data_Found Then
                     V_VRFATOCONV := 1; V_VRBRUTO := 0; V_VRCONTAB := 0;
               End;
              /*IF P_TIPOOPER = 03 THEN
                 Begin
                    SELECT NVL(C_ITEMPROD.VRTOTAITEM / SUM(I.VRTOTAITEM) ,1) AS VRFATOCONV,
                           NVL(SUM(VRBRUTITEM),0), NVL(SUM(VRCONTITEM),0)
                    INTO   V_VRFATOCONV, V_VRBRUTO, V_VRCONTAB
                    FROM ITEMPRODUTO I
                    WHERE CDFILIAL    = C_ITEMNOTAFISC.CDFILIALIT                                          AND
                          NRLANCTONF  = C_ITEMNOTAFISC.NRLANCTONFIT                                        AND
                          CDPRODUTO   = C_ITEMPROD.CDPRODUTO                                               AND
                          ROUND(VRUNITITEM, V_NRDECITOTANF) = ROUND(C_ITEMPROD.VRUNITITEM, V_NRDECITOTANF) AND
                          (NVL(NRLOTEESTQ,  )  = (NVL(C_ITEMPROD.NRLOTEESTQ,  )))                      AND
                          (NVL(NRSUBLOTE ,  )  = (NVL(C_ITEMPROD.NRSUBLOTE ,  )));
                 Exception
                    When No_Data_Found Then
                       V_VRFATOCONV := 1; V_VRBRUTO := 0; V_VRCONTAB := 0;
                 End;
              END IF;*/
               IF P_TIPOOPER <> '03' THEN
                 UPDATE ITEMPRODUTO
                    SET VRCONTITEMORIG = ROUND(V_VRCONTAB * V_VRFATOCONV,2),
                        VRBRUTITEMORIG = ROUND(V_VRBRUTO * V_VRFATOCONV,2),
                        VRCONTITEM = ROUND(V_VRCONTAB * V_VRFATOCONV,2),
                        VRBRUTITEM = ROUND(V_VRBRUTO * V_VRFATOCONV,2),
                        VRENCARGOIMPXML = ROUND(V_VRENCARGOIMPXML * V_VRFATOCONV,2),
                        VRPERDEVOL      = (V_VRFATOCONV * 100)
                  WHERE CDFILIAL    = P_FILIAL                                                           AND
                        NRLANCTONF  = P_LANCTONF                                                         AND
                        CDPRODUTO   = C_ITEMPROD.CDPRODUTO                                               AND
                        ROUND(VRUNITITEM, V_NRDECITOTANF) = ROUND(C_ITEMPROD.VRUNITITEM, V_NRDECITOTANF) AND
                        (NVL(NRLOTEESTQ, ' ') = (NVL(C_ITEMPROD.NRLOTEESTQ, ' ')))                       AND
                        (NVL(NRSUBLOTE , ' ') = (NVL(C_ITEMPROD.NRSUBLOTE , ' ')));
               END IF;
               IF V_CDINTEGRACAO IS NOT NULL THEN
                  IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (NVL(V_IDORIGDESTNF, 'C') <> 'L') THEN
                     UPDATE ITEMPRODUTO
                     SET VRCONTITEM = TRUNC((V_VRCONTAB * V_VRFATOCONV),2),
                         VRBRUTITEM = TRUNC((V_VRBRUTO * V_VRFATOCONV),2)
                     WHERE CDFILIAL    = P_FILIAL                                                           AND
                           NRLANCTONF  = P_LANCTONF                                                         AND
                           CDPRODUTO   = C_ITEMPROD.CDPRODUTO                                               AND
                           ROUND(VRUNITITEM, V_NRDECITOTANF) = ROUND(C_ITEMPROD.VRUNITITEM, V_NRDECITOTANF) AND
                          (NVL(NRLOTEESTQ, ' ') = (NVL(C_ITEMPROD.NRLOTEESTQ, ' ')))                        AND
                          (NVL(NRSUBLOTE , ' ') = (NVL(C_ITEMPROD.NRSUBLOTE , ' ')));
                  ELSE
                     UPDATE ITEMPRODUTO
                     SET VRCONTITEM = ROUND(V_VRCONTAB * V_VRFATOCONV,2),
                         VRBRUTITEM = ROUND(V_VRBRUTO * V_VRFATOCONV,2)
                     WHERE CDFILIAL    = P_FILIAL                                                           AND
                           NRLANCTONF  = P_LANCTONF                                                         AND
                           CDPRODUTO   = C_ITEMPROD.CDPRODUTO                                               AND
                           ROUND(VRUNITITEM, V_NRDECITOTANF) = ROUND(C_ITEMPROD.VRUNITITEM, V_NRDECITOTANF) AND
                          (NVL(NRLOTEESTQ, ' ') = (NVL(C_ITEMPROD.NRLOTEESTQ, ' ')))                        AND
                          (NVL(NRSUBLOTE , ' ') = (NVL(C_ITEMPROD.NRSUBLOTE , ' ')));
                  END IF;
               END IF;
               V_CDIMPOSRECALC := NULL;
               UPDATE ITEMPRODUTO
                  SET IDUTILBCPMC = 'N'
                WHERE CDFILIAL = P_FILIAL
                  AND NRLANCTONF = P_LANCTONF
                  AND NRSEQITPROD = C_ITEMPROD.NRSEQITPROD;
               IF (V_IDCONTCONFORIG = 'N') THEN
                  UPDATE ITEMPRODUTO
                     SET VRCONTITEMORIG = (VRTOTAITEM - VRDESCITEM),
                         VRCONTITEM     = (VRTOTAITEM - VRDESCITEM),
                         VRBRUTITEMORIG = VRTOTAITEM,
                         VRBRUTITEM     = VRTOTAITEM
                   WHERE CDFILIAL       = P_FILIAL
                     AND NRLANCTONF     = P_LANCTONF
                     AND NRSEQITPROD    = C_ITEMPROD.NRSEQITPROD;
               END IF;
               /*IMPOSTOS POR ITEM DA NOTA DE ORIGEM*/
               FOR C_ITEMPROIMPOS IN (SELECT VRPERREDBCIT,  NRITPROIMPOS,       IT.CDIMPOSTO,CDFISCALIT,                 VRALIQITEM,                                                                                                           VRPARDEDIT,                                             SUM(VRCONTITIMP) AS VRCONTITIMP,                                                                                      SUM(VRBASECALCIT) AS VRBASECALCIT,
                                             SUM(VRIMPOSTOIT) AS VRIMPOSTOIT,                                                                                      CDSITUTRIBITNFE AS CDSITUTRIBNFE,
                                             IDMODBCITNFE AS IDMODBCNFE,                                                                                           IDMODBCSTITNFE AS IDMODBCSTNFE,                                             CDTPCREDPICOITE,                                                                                                      CDNATUBCALPCIT,
                                             IDMOTDESONERAIT,                                                                                                      IDTRIMPSTII,                                                                NVL(IDDIFALIQCUSPRI, 'N') AS IDDIFALIQCUSPRI,                                                                        IM.CDIMPOSTONFE,
                                             IT.CDENQLEGALIPI,                                                                                                    IT.CDCEST,
                                             NVL(I.IDUTVRPAUTAPROD, 'N') AS IDUTVRPAUTAPROD,                                                                      NVL(I.VRPAUTAMINPROD, 1) AS VRPAUTAMINPROD,                                             I.QTITEMPROD,                                                                                                         IM.IDUTVRPAUTA,                                             NVL(IT.VRADICALIQFECP, 0) AS VRADICALIQFECP,                                                                          NVL(SUM(IT.VRADICFECP), 0) AS VRADICFECP,
                                             I.CDFISOPEITEM,                                                                                                      IT.CDBENEFFISCAL,
                                             NVL(IT.IDVALORINFIT, W_N) AS IDVALORINFIT
                                        FROM ITEMPROIMPOS IT, ITEMPRODUTO I, IMPOSTO IM
                                       WHERE IT.CDFILIAL = C_ITEMNOTAFISC.CDFILIALIT
                                         AND IT.NRLANCTONF = C_ITEMNOTAFISC.NRLANCTONFIT
                                         AND I.CDFILIAL = C_ITEMNOTAFISC.CDFILIALIT
                                         AND I.NRLANCTONF = C_ITEMNOTAFISC.NRLANCTONFIT
                                         AND IT.NRSEQITPROD = I.NRSEQITPROD
                                         AND IT.CDIMPOSTO = IM.CDIMPOSTO
                                         AND I.CDPRODUTO = C_ITEMPROD.CDPRODUTO
                                         AND IT.NRITPROIMPOS = '1'
                                         AND ROUND(I.VRUNITITEM, 5) = ROUND(C_ITEMPROD.VRUNITITEM, 5) 
                                         AND (NVL(I.NRLOTEESTQ, ' ') = (NVL(C_ITEMPROD.NRLOTEESTQ, ' ')))
                                         AND (NVL(I.NRSUBLOTE, ' ') = (NVL(C_ITEMPROD.NRSUBLOTE,  ' ')))
                                       GROUP BY VRPERREDBCIT, 
                                             IT.CDIMPOSTO, 
                                             NRITPROIMPOS,
                                             CDFISCALIT, 
                                             VRALIQITEM,
                                             VRPARDEDIT,   
                                             CDSITUTRIBITNFE, 
                                             IDMODBCITNFE, 
                                             IDMODBCSTITNFE,
                                             CDTPCREDPICOITE, 
                                             CDNATUBCALPCIT, 
                                             IDMOTDESONERAIT, 
                                             IDTRIMPSTII, 
                                             IDDIFALIQCUSPRI,
                                             IM.CDIMPOSTONFE, 
                                             IT.CDENQLEGALIPI,
                                             IT.CDCEST, 
                                             NVL(I.IDUTVRPAUTAPROD, 'N'),
                                             NVL(I.VRPAUTAMINPROD, 1), 
                                             I.QTITEMPROD, 
                                             IM.IDUTVRPAUTA,
                                             NVL(IT.VRADICALIQFECP, 0), 
                                             I.CDFISOPEITEM,
                                             IT.CDBENEFFISCAL, 
                                             NVL(IT.IDVALORINFIT, W_N)
                                       ORDER BY CDIMPOSTO) LOOP
                  /*IMPOSTO DE SUBSTITUICAO TRIBUTARIA*/
                  V_CDIMPOSTRIB  := null;
                  V_CDBENEFFISCAL := NULL;
                  FOR C_ICMSST IN (SELECT CDIMPOSTO
                                     FROM IMPOSTO
                                    WHERE CDIMPOSTRIB = C_ITEMPROIMPOS.CDIMPOSTO)
                  LOOP
                     V_CDIMPOSTRIB := V_CDIMPOSTRIB||C_ICMSST.CDIMPOSTO||'_';
                  END LOOP;
                  V_CDIMPOSIPI := null;
                  SELECT NVL(MAX(IDGERIPIDESPA), 'N'), MAX(CDIMPOSTOIPI)
                    INTO V_IDGERIPIDESPA, V_CDIMPOSIPI
                    FROM TIPOOPERAC
                   WHERE IDENTRSAIDOP = 'S'
                     AND CDTIPOOPER = P_TIPOOPER
                     AND CDIMPOSTOIPI = C_ITEMPROIMPOS.CDIMPOSTO;
                  IF (V_IDGERICMSTDESPA = 'S') AND (V_CDIMPOSTRIB IS NOT NULL) AND (V_IDUTCTRLFIS = 'S') THEN
                     IF NOT((C_ITEMPROIMPOS.VRPERREDBCIT > 0.00) AND (C_ITEMPROIMPOS.NRITPROIMPOS = w_2)) THEN
                        V_VRTOTALICMSST := V_VRTOTALICMSST + (C_ITEMPROIMPOS.VRIMPOSTOIT * V_VRFATOCONV);
                     END IF;
                     IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (V_ICMS = 'S') THEN
                        INSERT INTO ITEMPROIMPOSORIG(CDFILIAL,     NRLANCTONF,     NRSEQITPROD,     CDIMPOSTO,      NRITPROIMPOS,    CDFISCALIT,
                                                 CDSITUTRIBIT, CDFISCOPERIT,   CDSUFXCFOPIT,    VRALIQITEM,     VRPERREDBCIT,    VRPARDEDIT,
                                                 VRCONTITIMP,  VRBASECALCIT,   VRIMPOSTOIT,     IDERROSIMPIT,   IDAVISIMPIT,     CDSITUTRIBITNFE,
                                                 IDMODBCITNFE, IDMODBCSTITNFE, CDTPCREDPICOITE, CDNATUBCALPCIT, IDMOTDESONERAIT, IDTRIMPSTII,
                                                 CDDETALHEPROD, CDENQLEGALIPI, CDCEST,          CDBENEFFISCAL)
                        VALUES(P_FILIAL, P_LANCTONF, C_ITEMPROD.NRSEQITPROD, C_ITEMPROIMPOS.CDIMPOSTO, C_ITEMPROIMPOS.NRITPROIMPOS, C_ITEMPROIMPOS.CDFISCALIT,
                               C_ITEMPROD.CDSITUTRIBPR, V_FISOPEITEM, V_SUFXCFOPPR, C_ITEMPROIMPOS.VRALIQITEM, C_ITEMPROIMPOS.VRPERREDBCIT, TRUNC((C_ITEMPROIMPOS.VRPARDEDIT * V_VRFATOCONV),2),
                               TRUNC((C_ITEMPROIMPOS.VRCONTITIMP * V_VRFATOCONV),2), TRUNC((C_ITEMPROIMPOS.VRBASECALCIT * V_VRFATOCONV),2),
                               TRUNC((C_ITEMPROIMPOS.VRIMPOSTOIT * V_VRFATOCONV),2), w_00000, w_00000, C_ITEMPROIMPOS.CDSITUTRIBNFE,
                               C_ITEMPROIMPOS.IDMODBCNFE, C_ITEMPROIMPOS.IDMODBCSTNFE, C_ITEMPROIMPOS.CDTPCREDPICOITE, C_ITEMPROIMPOS.CDNATUBCALPCIT, NVL(C_ITEMPROIMPOS.IDMOTDESONERAIT,'9'), C_ITEMPROIMPOS.IDTRIMPSTII,
                               V_CDDETALHEPRODTEMP, C_ITEMPROIMPOS.CDENQLEGALIPI, C_ITEMPROIMPOS.CDCEST, C_ITEMPROIMPOS.CDBENEFFISCAL);
                     ELSE
                        INSERT INTO ITEMPROIMPOSORIG(CDFILIAL,     NRLANCTONF,     NRSEQITPROD,     CDIMPOSTO,      NRITPROIMPOS,    CDFISCALIT,
                                                 CDSITUTRIBIT, CDFISCOPERIT,   CDSUFXCFOPIT,    VRALIQITEM,     VRPERREDBCIT,    VRPARDEDIT,
                                                 VRCONTITIMP,  VRBASECALCIT,   VRIMPOSTOIT,     IDERROSIMPIT,   IDAVISIMPIT,     CDSITUTRIBITNFE,
                                                 IDMODBCITNFE, IDMODBCSTITNFE, CDTPCREDPICOITE, CDNATUBCALPCIT, IDMOTDESONERAIT, IDTRIMPSTII,
                                                 CDDETALHEPROD, CDENQLEGALIPI, CDCEST,          CDBENEFFISCAL)
                        VALUES(P_FILIAL, P_LANCTONF, C_ITEMPROD.NRSEQITPROD, C_ITEMPROIMPOS.CDIMPOSTO, C_ITEMPROIMPOS.NRITPROIMPOS, C_ITEMPROIMPOS.CDFISCALIT,
                               C_ITEMPROD.CDSITUTRIBPR, V_FISOPEITEM, V_SUFXCFOPPR, C_ITEMPROIMPOS.VRALIQITEM, C_ITEMPROIMPOS.VRPERREDBCIT, (C_ITEMPROIMPOS.VRPARDEDIT * V_VRFATOCONV),
                               ROUND((C_ITEMPROIMPOS.VRCONTITIMP * V_VRFATOCONV),2), (C_ITEMPROIMPOS.VRBASECALCIT * V_VRFATOCONV),
                               (C_ITEMPROIMPOS.VRIMPOSTOIT * V_VRFATOCONV), w_00000, w_00000, C_ITEMPROIMPOS.CDSITUTRIBNFE,
                               C_ITEMPROIMPOS.IDMODBCNFE, C_ITEMPROIMPOS.IDMODBCSTNFE, C_ITEMPROIMPOS.CDTPCREDPICOITE, C_ITEMPROIMPOS.CDNATUBCALPCIT, NVL(C_ITEMPROIMPOS.IDMOTDESONERAIT,'9'), C_ITEMPROIMPOS.IDTRIMPSTII,
                               V_CDDETALHEPRODTEMP, C_ITEMPROIMPOS.CDENQLEGALIPI, C_ITEMPROIMPOS.CDCEST, C_ITEMPROIMPOS.CDBENEFFISCAL);
                     END IF;
                  END IF;
                  IF (V_IDGERIPIDESPA = 'S') AND (V_CDIMPOSIPI IS NOT NULL) AND (V_IDUTCTRLFIS = 'S') THEN
                     IF NOT((C_ITEMPROIMPOS.VRPERREDBCIT > 0.00) AND (C_ITEMPROIMPOS.NRITPROIMPOS = w_2)) THEN
                        V_VRTOTALIPI := V_VRTOTALIPI + (C_ITEMPROIMPOS.VRIMPOSTOIT * V_VRFATOCONV);
                     END IF;
                     IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (V_ICMS = 'S') THEN
                        INSERT INTO ITEMPROIMPOSORIG(CDFILIAL,     NRLANCTONF,     NRSEQITPROD,     CDIMPOSTO,      NRITPROIMPOS,    CDFISCALIT,
                                                 CDSITUTRIBIT, CDFISCOPERIT,   CDSUFXCFOPIT,    VRALIQITEM,     VRPERREDBCIT,    VRPARDEDIT,
                                                 VRCONTITIMP,  VRBASECALCIT,   VRIMPOSTOIT,     IDERROSIMPIT,   IDAVISIMPIT,     CDSITUTRIBITNFE,
                                                 IDMODBCITNFE, IDMODBCSTITNFE, CDTPCREDPICOITE, CDNATUBCALPCIT, IDMOTDESONERAIT, IDTRIMPSTII,
                                                 CDDETALHEPROD, CDENQLEGALIPI, CDCEST, CDBENEFFISCAL)
                        VALUES(P_FILIAL, P_LANCTONF, C_ITEMPROD.NRSEQITPROD, C_ITEMPROIMPOS.CDIMPOSTO, C_ITEMPROIMPOS.NRITPROIMPOS, C_ITEMPROIMPOS.CDFISCALIT,
                               C_ITEMPROD.CDSITUTRIBPR, V_FISOPEITEM, V_SUFXCFOPPR, C_ITEMPROIMPOS.VRALIQITEM, C_ITEMPROIMPOS.VRPERREDBCIT, TRUNC((C_ITEMPROIMPOS.VRPARDEDIT * V_VRFATOCONV),2),
                               TRUNC((C_ITEMPROIMPOS.VRCONTITIMP * V_VRFATOCONV),2), TRUNC((C_ITEMPROIMPOS.VRBASECALCIT * V_VRFATOCONV),2),
                               TRUNC((C_ITEMPROIMPOS.VRIMPOSTOIT * V_VRFATOCONV),2), w_00000, w_00000, C_ITEMPROIMPOS.CDSITUTRIBNFE,
                               C_ITEMPROIMPOS.IDMODBCNFE, C_ITEMPROIMPOS.IDMODBCSTNFE, C_ITEMPROIMPOS.CDTPCREDPICOITE, C_ITEMPROIMPOS.CDNATUBCALPCIT, NVL(C_ITEMPROIMPOS.IDMOTDESONERAIT,'9'), C_ITEMPROIMPOS.IDTRIMPSTII,
                               V_CDDETALHEPRODTEMP, C_ITEMPROIMPOS.CDENQLEGALIPI, C_ITEMPROIMPOS.CDCEST, C_ITEMPROIMPOS.CDBENEFFISCAL);
                     ELSE
                        INSERT INTO ITEMPROIMPOSORIG(CDFILIAL,     NRLANCTONF,     NRSEQITPROD,     CDIMPOSTO,      NRITPROIMPOS,    CDFISCALIT,
                                                 CDSITUTRIBIT, CDFISCOPERIT,   CDSUFXCFOPIT,    VRALIQITEM,     VRPERREDBCIT,    VRPARDEDIT,
                                                 VRCONTITIMP,  VRBASECALCIT,   VRIMPOSTOIT,     IDERROSIMPIT,   IDAVISIMPIT,     CDSITUTRIBITNFE,
                                                 IDMODBCITNFE, IDMODBCSTITNFE, CDTPCREDPICOITE, CDNATUBCALPCIT, IDMOTDESONERAIT, IDTRIMPSTII,
                                                 CDDETALHEPROD, CDENQLEGALIPI, CDCEST, CDBENEFFISCAL)
                        VALUES(P_FILIAL, P_LANCTONF, C_ITEMPROD.NRSEQITPROD, C_ITEMPROIMPOS.CDIMPOSTO, C_ITEMPROIMPOS.NRITPROIMPOS, C_ITEMPROIMPOS.CDFISCALIT,
                               C_ITEMPROD.CDSITUTRIBPR, V_FISOPEITEM, V_SUFXCFOPPR, C_ITEMPROIMPOS.VRALIQITEM, C_ITEMPROIMPOS.VRPERREDBCIT, (C_ITEMPROIMPOS.VRPARDEDIT * V_VRFATOCONV),
                               ROUND((C_ITEMPROIMPOS.VRCONTITIMP * V_VRFATOCONV),2), (C_ITEMPROIMPOS.VRBASECALCIT * V_VRFATOCONV),
                               (C_ITEMPROIMPOS.VRIMPOSTOIT * V_VRFATOCONV), w_00000, w_00000, C_ITEMPROIMPOS.CDSITUTRIBNFE,
                               C_ITEMPROIMPOS.IDMODBCNFE, C_ITEMPROIMPOS.IDMODBCSTNFE, C_ITEMPROIMPOS.CDTPCREDPICOITE, C_ITEMPROIMPOS.CDNATUBCALPCIT, NVL(C_ITEMPROIMPOS.IDMOTDESONERAIT,'9'), C_ITEMPROIMPOS.IDTRIMPSTII,
                               V_CDDETALHEPRODTEMP, C_ITEMPROIMPOS.CDENQLEGALIPI, C_ITEMPROIMPOS.CDCEST, C_ITEMPROIMPOS.CDBENEFFISCAL);
                     END IF;
                  END IF;
                  IF (NOT((V_IDGERICMSTDESPA = 'S') AND (V_CDIMPOSTRIB IS NOT NULL) OR (V_IDGERIPIDESPA = 'S')
                     AND (V_CDIMPOSIPI IS NOT NULL)) AND (V_IDUTCTRLFIS = 'S')) OR (V_IDUTCTRLFIS = 'N') THEN
                     -- Verifica se ha grupo fiscal por servico
                     SELECT MAX(CDGRUPOFISC)
                     INTO V_CDGRPFISCSV
                     FROM SERVCLIE SC, SERVICO S
                     WHERE SC.CDFILIAL   = V_CDFILIEMIT AND
                           SC.CDCLIENTE  = P_CLIENTE    AND
                           SC.CDFILIAL   = S.CDFILIAL   AND
                           SC.CDSERVFILI = S.CDSERVFILI AND
                           S.CDPRODUTO   = C_ITEMPROD.CDPRODUTO;
                     IF V_CDGRPFISCSV IS NULL THEN
                     -- Verifica se ha grupo fiscal por cliente da filial
                        SELECT MAX(CDGRUPOFISC)
                        INTO V_CDGRPFISCSV
                        FROM CLIENFILIAL
                        WHERE CDFILIAL   = V_CDFILIEMIT AND
                              CDCLIENTE  = P_CLIENTE;
                     END IF;
                     IF (C_ITEMPROD.IDPRODBONIF = 'N') OR (V_CDTIPOOPERBONIF = 'N') THEN
                        CONSULTA_INCIDENCIA(w_S, P_EMPRESA, C_ITEMPROD.CDARVPROD, P_INSCESTA, P_TIPOOPER, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC,
                                            V_CDGRPFISCSV, V_IDINTEREST, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, C_ITEMPROD.IDORIGEMPROD);
                     ELSE
                        CONSULTA_INCIDENCIA(w_S, P_EMPRESA, C_ITEMPROD.CDARVPROD, P_INSCESTA, V_CDTIPOOPERBONIF, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC,
                                            V_CDGRPFISCSV, V_IDINTEREST, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, C_ITEMPROD.IDORIGEMPROD);
                     END IF;
                     BEGIN
                        SELECT MAX(CDFISCTEMP), MAX(CDDETALHEPROD), MAX(CDENQLEGALIPI), MAX(CDCEST)
                          INTO   V_CDFISCTEMP, V_CDDETALHEPRODTEMP, V_CDENQLEGALIPI, V_CDCEST
                         FROM INCITEMP IT, IMPOSTO IP
                         WHERE IT.NRINCITEMP = V_INCITEMP
                           AND IP.CDIMPOSTO  = IT.CDIMPOTEMP
                           AND IP.IDPRODNOTA = w_P
                           AND IT.CDIMPOTEMP = C_ITEMPROIMPOS.CDIMPOSTO;
                     EXCEPTION
                        WHEN NO_DATA_FOUND THEN
                           V_CDFISCTEMP        := NULL;
                           V_CDDETALHEPRODTEMP := NULL;
                           V_CDENQLEGALIPI     := NULL;
                           V_CDCEST            := NULL;
                     END;
                     IF (C_ITEMPROIMPOS.VRPERREDBCIT > 0.00) AND
                        (C_ITEMPROIMPOS.NRITPROIMPOS = w_2) THEN
                        V_CDFISCTEMP := w_2;
                     ELSE
                        IF (V_CDFISCTEMP IS NULL) THEN
                            V_CDFISCTEMP := C_ITEMPROIMPOS.CDFISCALIT;
                        END IF;
                     END IF;
                     IF V_CDENQLEGALIPI IS NULL THEN
                        V_CDENQLEGALIPI := C_ITEMPROIMPOS.CDENQLEGALIPI;
                     END IF;
                     IF V_CDCEST IS NULL THEN
                        V_CDCEST := C_ITEMPROIMPOS.CDCEST;
                     END IF;
                     DELETE INCITEMP
                      WHERE NRINCITEMP = V_INCITEMP;
                     /*VERIFICA CST POR IMPOSTO*/
                     V_IMPOICMS := NULL;
                     V_CDGRUPOFISCAUX := NULL;
                     SELECT MAX(G.CDGRUPOFISC)
                       INTO V_CDGRUPOFISCAUX
                       FROM GRUPOFISCIMPFIL G,
                            (SELECT 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_ITEMPROIMPOS.CDIMPOSTO;
                     IF V_IDORIGDESTNF = 'C' THEN
                        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_ITEMPROIMPOS.CDIMPOSTO;
                     ELSE
                        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_ITEMPROIMPOS.CDIMPOSTO;
                     END IF;
                     IF V_CDGRUPOFISCAUX IS NULL THEN
                        IF (C_ITEMPROD.IDPRODBONIF = 'N') OR (V_CDTIPOOPERBONIF = 'N') THEN
                           CONSULTA_CST_NFE(w_S, P_EMPRESA, C_ITEMPROD.CDARVPROD, P_INSCESTA, P_TIPOOPER, V_CDGRUPOFISC,C_ITEMPROIMPOS.CDIMPOSTO, V_IDINTEREST, V_IDINTERNA, P_FILIAL, P_LANCTONF, '', V_CDSITTRIBTMP, V_IDMODBCNFE, V_IDMODBCSTNFE, V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, V_IDMOTIDESSTNFE, C_ITEMPROD.IDORIGEMPROD);
                        ELSE
                           CONSULTA_CST_NFE(w_S, P_EMPRESA, C_ITEMPROD.CDARVPROD, P_INSCESTA, V_CDTIPOOPERBONIF, V_CDGRUPOFISC,C_ITEMPROIMPOS.CDIMPOSTO, V_IDINTEREST, V_IDINTERNA, P_FILIAL, P_LANCTONF, '', V_CDSITTRIBTMP, V_IDMODBCNFE, V_IDMODBCSTNFE, V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, V_IDMOTIDESSTNFE, C_ITEMPROD.IDORIGEMPROD);
                        END IF;
                     ELSE
                        IF (C_ITEMPROD.IDPRODBONIF = 'N') OR (V_CDTIPOOPERBONIF = 'N') THEN
                           CONSULTA_CST_NFE(w_S, P_EMPRESA, C_ITEMPROD.CDARVPROD, P_INSCESTA, P_TIPOOPER, V_CDGRUPOFISCAUX,C_ITEMPROIMPOS.CDIMPOSTO, V_IDINTEREST, V_IDINTERNA, P_FILIAL, P_LANCTONF, '', V_CDSITTRIBTMP, V_IDMODBCNFE, V_IDMODBCSTNFE, V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, V_IDMOTIDESSTNFE, C_ITEMPROD.IDORIGEMPROD);
                        ELSE
                           CONSULTA_CST_NFE(w_S, P_EMPRESA, C_ITEMPROD.CDARVPROD, P_INSCESTA, V_CDTIPOOPERBONIF, V_CDGRUPOFISCAUX,C_ITEMPROIMPOS.CDIMPOSTO, V_IDINTEREST, V_IDINTERNA, P_FILIAL, P_LANCTONF, '', V_CDSITTRIBTMP, V_IDMODBCNFE, V_IDMODBCSTNFE, V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, V_IDMOTIDESSTNFE, C_ITEMPROD.IDORIGEMPROD);
                        END IF;
                     END IF;
                     IF (V_CDSITTRIBTMP IS NULL) THEN
                        V_CDSITUTRIBNFE := C_ITEMPROIMPOS.CDSITUTRIBNFE;
                     ELSE
                        V_CDSITUTRIBNFE := V_CDSITTRIBTMP;
                     END IF;
                     IF (V_IDMODBCNFE IS NULL) THEN
                        V_IDMODBCNFEIT := C_ITEMPROIMPOS.IDMODBCNFE;
                     ELSE
                        V_IDMODBCNFEIT := V_IDMODBCNFE;
                     END IF;
                     IF (V_IDMODBCSTNFE IS NULL) THEN
                        V_IDMODBCSTNFEIT := C_ITEMPROIMPOS.IDMODBCSTNFE;
                     ELSE
                        V_IDMODBCSTNFEIT := V_IDMODBCSTNFE;
                     END IF;
                     IF (C_ITEMPROIMPOS.CDTPCREDPICOITE IS NULL) THEN
                        V_CDTPCRPICOSTNFEIT := V_CDTPCRPICOSTNFE;
                     ELSE
                        V_CDTPCRPICOSTNFEIT := C_ITEMPROIMPOS.CDTPCREDPICOITE;
                     END IF;
                     IF (C_ITEMPROIMPOS.CDNATUBCALPCIT IS NULL) THEN
                        V_CDNATUBCPCSTNFEIT := V_CDNATUBCPCSTNFE;
                     ELSE
                        V_CDNATUBCPCSTNFEIT := C_ITEMPROIMPOS.CDNATUBCALPCIT;
                     END IF;
                     IF (V_IDMOTIDESSTNFE IS NULL) THEN
                        V_IDMOTIDESSTNFE := C_ITEMPROIMPOS.IDMOTDESONERAIT;
                     ELSE
                        V_IDMOTIDESSTNFE := V_IDMOTIDESSTNFE;
                     END IF;
                     SELECT NVL(MAX(IDUTMUNIORIG),'N')
                       INTO V_IDUTMUNIORIG
                       FROM IMPOSTO
                      WHERE CDIMPOSTO = C_ITEMPROIMPOS.CDIMPOSTO;
                     IF (C_ITEMPROIMPOS.IDUTVRPAUTAPROD = 'S') AND (C_ITEMPROIMPOS.IDUTVRPAUTA = 'S') THEN
                        V_LIQUIITEM := (C_ITEMPROD.QTITEMPROD * C_ITEMPROIMPOS.VRPAUTAMINPROD) / C_ITEMPROIMPOS.QTITEMPROD;
                     ELSE
                        V_LIQUIITEM := C_ITEMPROD.VRTOTAITEM - C_ITEMPROD.VRDESCITEM;
                     END IF;
                     IF ((V_IDUTMUNIORIG = 'O') OR (V_IDUTMUNIORIG = 'N')) THEN
                        IF (C_ITEMPROD.IDPRODBONIF = 'N') OR (V_CDTIPOOPERBONIF = 'N') THEN
                           CONSULTA_ALIQUOTA(C_ITEMPROIMPOS.CDIMPOSTO, w_S, 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, NULL, NULL, C_ITEMPROD.IDORIGEMPROD);
                        ELSE
                           CONSULTA_ALIQUOTA(C_ITEMPROIMPOS.CDIMPOSTO, w_S, 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, V_CDTIPOOPERBONIF,
                                             NULL, NULL, NULL, NULL, NULL, NULL, C_ITEMPROD.IDORIGEMPROD);
                        END IF;
                     ELSE
                        IF (C_ITEMPROD.IDPRODBONIF = 'N') OR (V_CDTIPOOPERBONIF = 'N') THEN
                           CONSULTA_ALIQUOTA(C_ITEMPROIMPOS.CDIMPOSTO, w_S, 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, NULL, NULL, C_ITEMPROD.IDORIGEMPROD);
                        ELSE
                           CONSULTA_ALIQUOTA(C_ITEMPROIMPOS.CDIMPOSTO, w_S, 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, V_CDTIPOOPERBONIF,
                                             NULL, NULL, NULL, NULL, NULL, NULL, C_ITEMPROD.IDORIGEMPROD);
                        END IF;
                     END IF;
                     V_NRALIQTEMP := 0;
                     V_PARDEDTMP  := 0;
                     V_PREDBCTMP  := 0;
                     V_ALIQUTMP   := 0;
                     V_IMPOSTOIT  := 0;
                     V_CDTIPOOPER    := NULL;
                     V_CDREGRAITALIQ := NULL;
                     V_IDIMPODESONERA  := w_N;
                     V_IDCONSDESONVRNF := w_N;
                     SELECT NVL(MAX(NRALIQTEMP),0),      
                            NVL(MAX(VRPARDEDTMP),0), 
                            NVL(MAX(VRPREDBCTMP),0),
                            NVL(MAX(VRALIQUTMP),0),
                            NVL(MAX(IDTRIMPSTTMP), w_0), 
                            NVL(MAX(VRPBCSTTMP),0),  
                            NVL(MAX(IDPMCBSCALTMP), w_S),
                            MAX(CDTIPOOPERTMP),
                            MAX(CDREGRATMP),
                            MAX(CDFISCOPER),
                            MAX(IDDIFEALIQ),
                            MAX(IDDIFALIQCUSPR),
                            MAX(CDBENEFFISCAL),
                            NVL(MAX(IDIMPODESONERA), 'N'),
                            NVL(MAX(IDCONSDESONVRNF), 'N'),
                            NVL(MAX(IDCONSMVAPMC), '3'),
                            NVL(MAX(IDCONSCOMPBCPMC), '3')
                       INTO V_NRALIQTEMP,
                            V_PARDEDTMP,
                            V_PREDBCTMP,
                            V_ALIQUTMP,
                            V_TRATIMPST,
                            V_PBCSUBTRIB,
                            V_IDPMCBASECAL,
                            V_CDTIPOOPER,
                            V_CDREGRAITALIQ,
                            V_CDFISCOPERREGRA,
                            V_IDDIFEALIQREGRA,
                            V_IDDIFALIQCUSPRREGRA,
                            V_CDBENEFFISCAL,
                            V_IDIMPODESONERA,
                            V_IDCONSDESONVRNF,
                            V_IDCONSMVAPMC,
                            V_IDCONSCOMPBCPMC
                       FROM ALIQTEMP
                      WHERE (NRALIQTEMP = V_ALIQTEMP);
                     IF V_CDBENEFFISCAL IS NULL THEN
                        V_CDBENEFFISCAL := C_ITEMPROIMPOS.CDBENEFFISCAL;
                     END IF;
                     IF V_PAISORIG = V_PAISCFOP THEN
                        IF V_ESTAORIG = V_ESTACFOP THEN
                           V_CFOP1DIGT := '5';
                        ELSE
                           V_CFOP1DIGT := '6';
                        END IF;
                     ELSE
                        V_CFOP1DIGT := '7';
                     END IF;
                     IF V_CDFISCOPERREGRA IS NOT NULL THEN
                        IF (LENGTH(V_CDFISCOPERREGRA) < 4) THEN
                           V_CDFISCOPERREGRA := V_CFOP1DIGT||V_CDFISCOPERREGRA;
                        END IF;
                     ELSE
                        IF C_ITEMPROIMPOS.CDFISOPEITEM IS NOT NULL THEN
                           V_CDFISCOPERREGRA := V_CFOP1DIGT||SUBSTR(C_ITEMPROIMPOS.CDFISOPEITEM, 2, 3);
                        END IF;
                     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_ITEMPROIMPOS.CDIMPOSTO)
                     LOOP
                        V_ICMS := 'S';
                     END LOOP;
                     IF (V_ICMS = 'S') THEN
                        IF (NVL(V_CFOPINFUSU, 'N') <> 'S') AND (V_CDFISCOPERREGRA IS NOT NULL) THEN
                           V_FISOPEITEM        := NVL(V_CDFISCOPERREGRA, V_FISOPEITEM);
                           V_DSCDFISOPEITREGRA := SUBSTR(DESCRICAO_CFOP(V_CDFISCOPERREGRA),1,45);
                        END IF;
                        UPDATE NOTAFISCAL
                           SET DSCDFISOPENF = NVL(V_DSCDFISOPEITREGRA, (SELECT MAX(DSCFOPTMP)
                                                                            FROM CFOPTEMP
                                                                           WHERE NRCFOPTEMP = V_CFOPTEMP))
                         WHERE CDFILIAL   = P_FILIAL   AND
                               NRLANCTONF = P_LANCTONF;
                        SELECT MAX(CDFISOPETMP), MAX(CDSUFCFOPTMP), SUBSTR(MAX(DSCFOPTMP),1,50)
                          INTO V_FISOPEITEM    , V_SUFXCFOPPR, V_DSCDFISOPEIT
                          FROM CFOPTEMP
                         WHERE NRCFOPTEMP = V_CFOPTEMP;
                        IF (NVL(V_CFOPINFUSU, 'N') <> 'S') AND (V_CDFISCOPERREGRA IS NOT NULL) THEN
                           V_FISOPEITEM        := NVL(V_CDFISCOPERREGRA, V_FISOPEITEM);
                           V_DSCDFISOPEITREGRA := SUBSTR(DESCRICAO_CFOP(V_CDFISCOPERREGRA),1,45);
                        END IF;
                        UPDATE ITEMPRODUTO
                           SET CDFISOPEITEM  = V_FISOPEITEM,
                               CDSUFXCFOPPR  = V_SUFXCFOPPR,
                               DSCDFISOPEIT  = V_DSCDFISOPEIT
                         WHERE CDFILIAL    = P_FILIAL AND
                               NRLANCTONF  = P_LANCTONF AND
                               NRSEQITPROD = C_ITEMPROD.NRSEQITPROD;
                     END IF;
                     /*Verifica aliquota parametrizada por tipo de operacao desde que nao seja nota de estorno de cancelamento*/
                     V_TAXABASECALC := (100 - V_PREDBCTMP)/100;
                     V_CONTABCALC  := V_LIQUIITEM - (V_LIQUIITEM * V_TAXABASECALC);
                     IF ((V_NRALIQTEMP IS NOT NULL) AND (V_CDTIPOOPER IS NOT NULL) AND (V_ESTORNOCANC <> w_S)) THEN
                        V_CDIMPOSRECALC := V_CDIMPOSRECALC||C_ITEMPROIMPOS.CDIMPOSTO||'_';
                        IF (C_ITEMPROIMPOS.NRITPROIMPOS = w_2) THEN
                           V_CDIMPOSTRIB  := null;
                           V_IDVRIMPSTRIB := null;
                        ELSE
                           V_CDIMPOSTRIB  := null;
                           V_IDVRIMPSTRIB := null;
                           /*IMPOSTO DE SUBSTITUICAO TRIBUTARIA*/
                           FOR C_ICMSST IN (SELECT CDIMPOSTO
                                              FROM IMPOSTO
                                             WHERE CDIMPOSTRIB = C_ITEMPROIMPOS.CDIMPOSTO)
                           LOOP
                              V_CDIMPOSTRIB := V_CDIMPOSTRIB||C_ICMSST.CDIMPOSTO||'_';
                           END LOOP;
                           V_TAXABASECALC := (100 - V_PREDBCTMP)/100;
                           V_TAXAALIQUOTA := (V_ALIQUTMP/100);
                           V_TAXABCSUBSTR := 1 + (V_PBCSUBTRIB/100);
                           V_BASECALCIT   := V_LIQUIITEM * V_TAXABASECALC;
                           IF V_CDIMPOSTRIB IS NULL THEN
                              V_IDTRIMPSTII := '';
                           ELSE
                              IF V_CDSITUCRT = '1' THEN
                                 IF SUBSTR(V_CDFISCOPERSN, 2, 3) = '500' THEN
                                    V_IDTRIMPSTII := w_2;
                                 ELSE
                                    V_IDTRIMPSTII := V_TRATIMPST;
                                 END IF;
                              ELSE
                                 IF SUBSTR(V_SITUTRIBPR, 2, 2) = '60' THEN
                                    V_IDTRIMPSTII := 2;
                                 ELSE
                                    V_IDTRIMPSTII := V_TRATIMPST;
                                 END IF;
                              END IF;
                              IF NVL(V_IDPMCBASECAL, W_N) = W_S THEN
                                 CALCULA_BC_PMC(P_FILIAL,
                                                P_LANCTONF,
                                                C_ITEMPROD.NRSEQITPROD,
                                                C_ITEMPROIMPOS.CDIMPOSTO,
                                                V_IDCONSMVAPMC,
                                                V_IDCONSCOMPBCPMC,
                                                V_PAISDEST,
                                                V_ESTADEST,
                                                C_ITEMPROD.CDPRODUTO,
                                                C_ITEMPROD.QTITEMPROD,
                                                C_ITEMPROD.VRUNITITEM,
                                                C_ITEMPROD.VRDESCITEM,
                                                V_PBCSUBTRIB,
                                                V_PREDBCTMP,
                                                NULL,
                                                NULL,
                                                NULL,
                                                NULL,
                                                NULL,
                                                NULL,
                                                'N',
                                                V_BASECALCTO);
                                 V_IMPOSTOIT := (V_BASECALCTO * V_TAXAALIQUOTA) - V_PARDEDTMP;
                              ELSE
                                 V_BASECALCTO  := V_BASECALCIT;
                                 V_IMPOSTOIT   := (V_BASECALCIT * V_TAXAALIQUOTA) - V_PARDEDTMP;
                              END IF;
                              SELECT NVL(MAX(IDVRIMPSTRIB), 'N')
                                INTO V_IDVRIMPSTRIB
                                FROM ITEMPROIMPOS I, IMPOSTO II
                               WHERE (CDFILIAL = P_FILIAL)
                                 AND (NRLANCTONF = P_LANCTONF)
                                 AND (NRSEQITPROD = C_ITEMPROD.NRSEQITPROD)
                                 AND (INSTR(V_CDIMPOSTRIB,II.CDIMPOSTO||'_') > 0)
                                 AND (I.CDIMPOSTO = II.CDIMPOSTO);
                              IF (V_TRATIMPST = W_1) OR (NVL(V_IDVRIMPSTRIB, W_N) = W_N) THEN
                                 V_VRIMPOSTOST := 0;
                              ELSE
                                 BEGIN
                                    SELECT NVL(MAX(VRIMPOSTOIT),0)
                                      INTO V_VRIMPOSTOST
                                      FROM ITEMPROIMPOS I
                                     WHERE (CDFILIAL = P_FILIAL)
                                       AND (NRLANCTONF = P_LANCTONF)
                                       AND (NRSEQITPROD = C_ITEMPROD.NRSEQITPROD)
                                       AND (INSTR(V_CDIMPOSTRIB,CDIMPOSTO||'_') > 0)
                                       AND (NRITPROIMPOS = w_1);
                                 EXCEPTION
                                    WHEN NO_DATA_FOUND THEN BEGIN
                                       V_VRIMPOSTOST := 0;
                                    END;
                                 END;
                              END IF;
                              V_IMPOSTOIT := V_IMPOSTOIT - V_VRIMPOSTOST;
                              IF V_IMPOSTOIT < 0 THEN
                                 V_IMPOSTOIT := 0;
                              END IF;
                              IF (V_IDCONTCONFORIG = 'N') THEN
                                 IF NVL(V_IDPMCBASECAL, W_N) = W_S THEN
                                    UPDATE ITEMPRODUTO
                                       SET VRBRUTITEM = VRBRUTITEM + V_IMPOSTOIT,
                                           VRCONTITEM = VRCONTITEM + V_IMPOSTOIT
                                     WHERE CDFILIAL = P_FILIAL
                                       AND NRLANCTONF = P_LANCTONF
                                       AND NRSEQITPROD = C_ITEMPROD.NRSEQITPROD;
                                  END IF;
                              END IF;
                           END IF;
                           IF NVL(V_IDPMCBASECAL, W_N) = W_N THEN
                              V_PERDBCALC    := 100 - V_PREDBCTMP;
                              IF V_PBCSUBTRIB > 0 THEN
                                 V_BASECALCIT := (V_BASECALCIT * V_TAXABCSUBSTR);
								         V_PREDBCSTIT := V_PREDBCTMP;
                                 V_PREDBCTMP  := V_PBCSUBTRIB;
                                 V_PERDBCALC  := 0;
							  ELSE
							     V_PREDBCSTIT := V_PREDBCTMP;
                              END IF;
                              SELECT NVL(MAX(IDUTVLRQTDEIMPO), 'N')
                                INTO V_IDUTVLRQTDEIMPO
                                FROM IMPOSTO
                               WHERE CDIMPOSTO = C_ITEMPROIMPOS.CDIMPOSTO;
                              IF (V_IDUTVLRQTDEIMPO = 'S') THEN
                                 SELECT NVL(MAX(VRFATOCONVES), 1)
                                   INTO V_VRFATOCONVES
                                   FROM CONVPRODUTO
                                  WHERE CDPRODUTO = C_ITEMPROD.CDPRODUTO;
                                 V_BASECALCTO  := (C_ITEMPROD.QTITEMPROD * V_VRFATOCONVES);
                                 V_IMPOSTOIT   := ((C_ITEMPROD.QTITEMPROD * V_VRFATOCONVES) * V_ALIQUTMP) - V_PARDEDTMP;
                              ELSE
                                 V_BASECALCTO  := V_BASECALCIT;
                                 V_IMPOSTOIT   := (V_BASECALCIT * V_TAXAALIQUOTA) - V_PARDEDTMP;
                              END IF;
                           END IF;
                           /*Impostos importados do arquivo XML, na devolucao sempre vai gravar de acordo com a origem*/
                           IF C_ITEMPROIMPOS.IDVALORINFIT = W_S THEN
                              V_BASECALCIT := ROUND((C_ITEMPROIMPOS.VRBASECALCIT * V_VRFATOCONV), 2);
                              V_BASECALCTO := V_BASECALCIT;
                              V_ALIQUTMP := C_ITEMPROIMPOS.VRALIQITEM;
                              V_TAXAALIQUOTA := (V_ALIQUTMP/100);
                              V_IMPOSTOIT := ROUND((C_ITEMPROIMPOS.VRIMPOSTOIT * V_VRFATOCONV), 2);
                           END IF;
                           V_CONTABCALC  := V_LIQUIITEM - (V_LIQUIITEM * V_TAXABASECALC);
                           IF (V_ALIQUTMP = 0) AND (V_IMPOSTOIT = 0) THEN
                              V_BASECALCTO := 0;
                           END IF;
                           -- ALTERAR O VALOR CONTABIL CASO O PARAMETRO CONTABILIZA CONFORME NF DE ORIGEM ESTEJA DESMARCADO
                           IF (V_IDCONTCONFORIG = 'N') THEN
                              V_IMPOCONTAB  := 0;
                              V_IDIMPORECUP := NULL;
                              V_CDCCTBLATIV := NULL;
                              V_IDTRATIMPO  := NULL;
                              SELECT NVL(IDIMPORECUP, 'N'), IDTRATIMPO, CDCCTBLATIV
                                INTO V_IDIMPORECUP, V_IDTRATIMPO, V_CDCCTBLATIV
                                FROM IMPOSTO
                               WHERE CDIMPOSTO = C_ITEMPROIMPOS.CDIMPOSTO;
                              IF (V_IDIMPORECUP = W_S) THEN
                                 IF (V_CDFISCTEMP = W_1) THEN
                                    IF (V_CDCCTBLATIV IS NOT NULL) THEN
                                       IF V_IDTRATIMPO = W_V THEN
                                          V_IMPOCONTAB := - V_IMPOSTOIT;
                                       END IF;
                                    END IF;
                                 ELSE
                                    IF V_IDTRATIMPO = W_A THEN
                                       V_IMPOCONTAB := V_IMPOSTOIT;
                                    ELSIF V_IDTRATIMPO IN (W_D,W_R) THEN
                                       V_IMPOCONTAB := - V_IMPOSTOIT;
                                    END IF;
                                 END IF;
                              END IF;
                              IF (ABS(NVL(V_IMPOCONTAB, 0)) > 0) THEN    
                                 UPDATE ITEMPRODUTO
                                    SET VRCONTITEMORIG = (VRCONTITEM) + NVL(V_IMPOCONTAB, 0),
                                        VRCONTITEM     = (VRCONTITEM) + NVL(V_IMPOCONTAB, 0)
                                  WHERE CDFILIAL       = P_FILIAL
                                    AND NRLANCTONF     = P_LANCTONF
                                    AND NRSEQITPROD    = C_ITEMPROD.NRSEQITPROD;
                              END IF;   
                           END IF;
                           -- Alterar o valor contabil caso o parametro Contabiliza conforme NF de origem esteja desmarcado
                           Begin
                              SELECT CDFILIAL
                              INTO   V_CHAVE
                              FROM ITEMPROIMPOS
                              WHERE CDFILIAL     = P_FILIAL                 AND
                                    NRLANCTONF   = P_LANCTONF               AND
                                    NRSEQITPROD  = C_ITEMPROD.NRSEQITPROD   AND
                                    CDIMPOSTO    = C_ITEMPROIMPOS.CDIMPOSTO AND
                                    NRITPROIMPOS = C_ITEMPROIMPOS.NRITPROIMPOS;
                           Exception
                              When No_Data_Found Then
                                 V_CHAVE := Null;
                           End;
                           IF V_IDPERVISIMPSCRE = 'S' THEN
                              V_VRIMPOSTOVISUIT := V_IMPOSTOIT;
                           ELSE
                              IF (V_CDFISCTEMP = '1') THEN
                                 V_VRIMPOSTOVISUIT := V_IMPOSTOIT;
                              ELSE
                                 V_VRIMPOSTOVISUIT := 0;
                              END IF;
                           END IF;
                           /* ROTINA PARA CALCULAR O DIFERIMENTO DO IMPOSTO */
                           V_PERDIFERE    := NULL;
                           V_IMPOSTOOPERA := NULL;
                           V_IMPOSTODIFER := NULL;
                           IF C_ITEMPROIMPOS.CDIMPOSTONFE = '00' THEN
                              IF V_CDSITTRIBTMP = '51' THEN
                                 BEGIN
                                    SELECT PD.VRPERDIFERE, 'S'
                                      INTO V_VRPERDIFERE, V_IDDIFECLI
                                      FROM PRODDIFEREIMPCLI PD, PRODUTO PR
                                     WHERE PD.CDPRODUTO = PR.CDPRODUTO
                                       AND PD.CDPAIS = V_PAISORIG
                                       AND PD.SGESTADO = V_ESTAORIG
                                       AND PD.CDCLIENTE = P_CLIENTE
                                       AND PR.CDARVPROD IN (SELECT MAX(PR.CDARVPROD) AS CDARVPROD
                                                              FROM PRODDIFEREIMPCLI PD, PRODUTO PR
                                                             WHERE PD.CDPRODUTO = PR.CDPRODUTO
                                                               AND PD.CDPAIS = V_PAISORIG
                                                               AND PD.SGESTADO = V_ESTAORIG
                                                               AND PD.CDCLIENTE = P_CLIENTE
                                                               AND INSTR(NVL(RTRIM(C_ITEMPROD.CDARVPROD), PR.CDARVPROD), PR.CDARVPROD) = 1);
                                 EXCEPTION
                                    WHEN NO_DATA_FOUND THEN
                                       V_VRPERDIFERE := NULL; V_IDDIFECLI := 'N';
                                 END;
                                 IF V_IDDIFECLI = 'N' 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_ITEMPROD.CDARVPROD), PR.CDARVPROD), PR.CDARVPROD) = 1);
                                    EXCEPTION
                                       WHEN NO_DATA_FOUND THEN
                                          V_VRPERDIFERE := NULL;
                                    END;
                                 END IF;
                                 IF V_VRPERDIFERE IS NOT NULL THEN
                                    V_PERDIFERE    := V_VRPERDIFERE;
                                 IF V_PREDBCTMP > 0 THEN
                                    V_IMPOSTOOPERA := (V_BASECALCIT * V_TAXABASECALC) * V_TAXAALIQUOTA;
                                 ELSE
                                    V_IMPOSTOOPERA := V_BASECALCIT * V_TAXAALIQUOTA;
                                 END IF;
                                    V_IMPOSTODIFER := V_IMPOSTOOPERA * (V_VRPERDIFERE/100);
                                    V_IMPOSTOIT    := V_IMPOSTOOPERA - V_IMPOSTODIFER;
                                 END IF;
                              END IF;
                           END IF;
                           IF V_CHAVE IS NULL THEN
                              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_ITEMPROIMPOS.CDIMPOSTO)
                              LOOP
                                 V_ICMS := 'S';
                              END LOOP;
                              IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (V_ICMS = 'S') THEN
                                 INSERT INTO ITEMPROIMPOS(
                                    CDFILIAL,        NRLANCTONF,   NRSEQITPROD,    CDIMPOSTO,       NRITPROIMPOS,   CDFISCALIT,
                                    CDSITUTRIBIT,    CDFISCOPERIT, CDSUFXCFOPIT,   VRALIQITEM,      VRPERREDBCIT,   VRPARDEDIT,
                                    VRCONTITIMP,     VRBASECALCIT, VRIMPOSTOIT,    IDERROSIMPIT,    IDAVISIMPIT,    IDTRIMPSTII,
                                    CDSITUTRIBITNFE, IDMODBCITNFE, IDMODBCSTITNFE, CDTPCREDPICOITE, CDNATUBCALPCIT, IDMOTDESONERAIT,
                                    CDDETALHEPROD,   VRIMPOSTOVISUIT,   CDREGRAIT, VRPERDIFEREIT, VRIMPOSTOOPERAIT, VRIMPOSTODIFERIT,
                                    CDENQLEGALIPI,   CDCEST,            CDBENEFFISCAL, IDDESONERAREGRA, IDCONSDESONVRNF, IDVALORINFIT, VRPERREDBCSTIT, VRIMPOSTOREP)
                                 VALUES(
                                    P_FILIAL,                P_LANCTONF,     C_ITEMPROD.NRSEQITPROD, C_ITEMPROIMPOS.CDIMPOSTO, w_1,                 V_CDFISCTEMP,
                                    NVL(V_SITUTRIBPR, C_ITEMPROD.CDSITUTRIBPR), V_FISOPEITEM,   V_SUFXCFOPPR,           V_ALIQUTMP,               V_PREDBCTMP,         V_PARDEDTMP,
                                    ROUND(V_BASECALCTO,2),   V_BASECALCTO,   TRUNC(V_IMPOSTOIT,2),   w_00000,                  w_00000,             V_IDTRIMPSTII,
                                    V_CDSITUTRIBNFE,         V_IDMODBCNFEIT, V_IDMODBCSTNFEIT,       V_CDTPCRPICOSTNFEIT,      V_CDNATUBCPCSTNFEIT, V_IDMOTIDESSTNFE,
                                    V_CDDETALHEPRODTEMP, TRUNC(V_VRIMPOSTOVISUIT,2), V_CDREGRAITALIQ, V_PERDIFERE, V_IMPOSTOOPERA, V_IMPOSTODIFER,
                                    V_CDENQLEGALIPI, V_CDCEST, V_CDBENEFFISCAL, NVL(V_IDIMPODESONERA, 'N'), NVL(V_IDCONSDESONVRNF, 'N'), C_ITEMPROIMPOS.IDVALORINFIT, V_PREDBCSTIT, V_VRIMPOSTOREP);
                              ELSE
                                 IF (C_ITEMPROIMPOS.NRITPROIMPOS = w_3)  THEN
                                    /*Inserir a linha de diferencial de aliquota*/
                                    V_DIFALIQ := 0;
                                    SELECT MAX(VRALIQITEM)
                                      INTO V_DIFALIQ
                                      FROM ITEMPROIMPOS IT, ITEMPRODUTO I
                                     WHERE IT.CDFILIAL     = C_ITEMNOTAFISC.CDFILIALIT
                                       AND IT.NRLANCTONF   = C_ITEMNOTAFISC.NRLANCTONFIT
                                       AND I.CDFILIAL      = C_ITEMNOTAFISC.CDFILIALIT
                                       AND I.NRLANCTONF    = C_ITEMNOTAFISC.NRLANCTONFIT
                                       AND IT.NRSEQITPROD  = I.NRSEQITPROD
                                       AND I.CDPRODUTO     = C_ITEMPROD.CDPRODUTO
                                       AND ROUND(I.VRUNITITEM, V_NRDECITOTANF) = ROUND(C_ITEMPROD.VRUNITITEM, V_NRDECITOTANF)
                                       AND (NVL(NRLOTEESTQ, ' ') = (NVL(C_ITEMPROD.NRLOTEESTQ, ' ')))
                                       AND (NVL(NRSUBLOTE, ' ')  = (NVL(C_ITEMPROD.NRSUBLOTE , ' ')))
                                       AND IT.CDIMPOSTO    = C_ITEMPROIMPOS.CDIMPOSTO
                                       AND IT.NRITPROIMPOS = w_1;
                                    IF  (V_ALIQUTMP = V_DIFALIQ) THEN
                                       INSERT INTO ITEMPROIMPOS(
                                          CDFILIAL,        NRLANCTONF,   NRSEQITPROD,    CDIMPOSTO,       NRITPROIMPOS,   CDFISCALIT,
                                          CDSITUTRIBIT,    CDFISCOPERIT, CDSUFXCFOPIT,   VRALIQITEM,      VRPERREDBCIT,   VRPARDEDIT,
                                          VRCONTITIMP,     VRBASECALCIT, VRIMPOSTOIT,    IDERROSIMPIT,    IDAVISIMPIT,    IDTRIMPSTII,
                                          CDSITUTRIBITNFE, IDMODBCITNFE, IDMODBCSTITNFE, CDTPCREDPICOITE, CDNATUBCALPCIT, IDMOTDESONERAIT,
                                          CDDETALHEPROD,   VRIMPOSTOVISUIT, CDREGRAIT, IDDIFALIQCUSPRI,
                                          CDENQLEGALIPI,   CDCEST,          CDBENEFFISCAL, IDDESONERAREGRA, IDCONSDESONVRNF, IDVALORINFIT)
                                       VALUES(
                                          P_FILIAL, P_LANCTONF, C_ITEMPROD.NRSEQITPROD, C_ITEMPROIMPOS.CDIMPOSTO, C_ITEMPROIMPOS.NRITPROIMPOS, C_ITEMPROIMPOS.CDFISCALIT,
                                          C_ITEMPROD.CDSITUTRIBPR, V_FISOPEITEM, V_SUFXCFOPPR, C_ITEMPROIMPOS.VRALIQITEM, C_ITEMPROIMPOS.VRPERREDBCIT, (C_ITEMPROIMPOS.VRPARDEDIT * V_VRFATOCONV),
                                          ROUND((C_ITEMPROIMPOS.VRCONTITIMP * V_VRFATOCONV),2), (C_ITEMPROIMPOS.VRBASECALCIT * V_VRFATOCONV),
                                          (C_ITEMPROIMPOS.VRIMPOSTOIT * V_VRFATOCONV), w_00000, w_00000, C_ITEMPROIMPOS.IDTRIMPSTII, C_ITEMPROIMPOS.CDSITUTRIBNFE,
                                          C_ITEMPROIMPOS.IDMODBCNFE, C_ITEMPROIMPOS.IDMODBCSTNFE, C_ITEMPROIMPOS.CDTPCREDPICOITE, C_ITEMPROIMPOS.CDNATUBCALPCIT, NVL(C_ITEMPROIMPOS.IDMOTDESONERAIT,'9'),
                                          V_CDDETALHEPRODTEMP, (C_ITEMPROIMPOS.VRIMPOSTOIT * V_VRFATOCONV), V_CDREGRAITALIQ, C_ITEMPROIMPOS.IDDIFALIQCUSPRI,
                                          V_CDENQLEGALIPI, V_CDCEST, V_CDBENEFFISCAL, NVL(V_IDIMPODESONERA, 'N'), NVL(V_IDCONSDESONVRNF, 'N'), C_ITEMPROIMPOS.IDVALORINFIT);
                                    /*Inserir a linha de diferencial de aliquota*/
                                    END IF;
                                 ELSE
                                    INSERT INTO ITEMPROIMPOS(
                                       CDFILIAL,        NRLANCTONF,   NRSEQITPROD,    CDIMPOSTO,       NRITPROIMPOS,   CDFISCALIT,
                                       CDSITUTRIBIT,    CDFISCOPERIT, CDSUFXCFOPIT,   VRALIQITEM,      VRPERREDBCIT,   VRPARDEDIT,
                                       VRCONTITIMP,     VRBASECALCIT, VRIMPOSTOIT,    IDERROSIMPIT,    IDAVISIMPIT,    IDTRIMPSTII,
                                       CDSITUTRIBITNFE, IDMODBCITNFE, IDMODBCSTITNFE, CDTPCREDPICOITE, CDNATUBCALPCIT, IDMOTDESONERAIT,
                                       CDDETALHEPROD,   VRIMPOSTOVISUIT,   CDREGRAIT, IDDIFALIQCUSPRI, VRPERDIFEREIT, VRIMPOSTOOPERAIT,
                                       VRIMPOSTODIFERIT, CDENQLEGALIPI, CDCEST, VRADICFECP, VRADICALIQFECP,
                                       CDBENEFFISCAL, IDDESONERAREGRA, IDCONSDESONVRNF, IDVALORINFIT, VRPERREDBCSTIT, VRIMPOSTOREP)
                                    VALUES(
                                       P_FILIAL,                P_LANCTONF,     C_ITEMPROD.NRSEQITPROD, C_ITEMPROIMPOS.CDIMPOSTO, w_1,               V_CDFISCTEMP,
                                       NVL(V_SITUTRIBPR, C_ITEMPROD.CDSITUTRIBPR), V_FISOPEITEM,   V_SUFXCFOPPR,           V_ALIQUTMP,               V_PREDBCTMP,         V_PARDEDTMP,
                                       ROUND(V_BASECALCTO,2),   V_BASECALCTO,   ROUND(V_IMPOSTOIT,2),   w_00000,                  w_00000,             V_IDTRIMPSTII,
                                       V_CDSITUTRIBNFE,         V_IDMODBCNFEIT, V_IDMODBCSTNFEIT,       V_CDTPCRPICOSTNFEIT,      V_CDNATUBCPCSTNFEIT, V_IDMOTIDESSTNFE,
                                       V_CDDETALHEPRODTEMP,     ROUND(V_VRIMPOSTOVISUIT,2),     V_CDREGRAITALIQ, C_ITEMPROIMPOS.IDDIFALIQCUSPRI, V_PERDIFERE, V_IMPOSTOOPERA,
                                       V_IMPOSTODIFER, V_CDENQLEGALIPI, V_CDCEST, ROUND((C_ITEMPROIMPOS.VRADICFECP * V_VRFATOCONV), 2), C_ITEMPROIMPOS.VRADICALIQFECP,
                                       V_CDBENEFFISCAL, NVL(V_IDIMPODESONERA, 'N'), NVL(V_IDCONSDESONVRNF, 'N'), C_ITEMPROIMPOS.IDVALORINFIT, V_PREDBCSTIT, V_VRIMPOSTOREP);
                                 END IF;
                              END IF;
                              IF (C_ITEMPROIMPOS.NRITPROIMPOS = w_1) THEN
                                 IF (V_PREDBCTMP > 0) AND (V_PBCSUBTRIB = 0) THEN
                                    IF C_ITEMPROD.CDSITUTRIBPR = '060' THEN
                                       INSERT INTO ITEMPROIMPOS(
                                          CDFILIAL,        NRLANCTONF,     NRSEQITPROD,    CDIMPOSTO,       NRITPROIMPOS,   CDFISCALIT,
                                          CDSITUTRIBIT,    CDFISCOPERIT,   CDSUFXCFOPIT,   VRALIQITEM,      VRPERREDBCIT,   VRPARDEDIT,
                                          VRCONTITIMP,     VRBASECALCIT,   VRIMPOSTOIT,    IDERROSIMPIT,    IDAVISIMPIT,    IDTRIMPSTII,
                                          CDSITUTRIBITNFE, IDMODBCITNFE,   IDMODBCSTITNFE, CDTPCREDPICOITE, CDNATUBCALPCIT, IDMOTDESONERAIT,
                                          CDDETALHEPROD,   VRIMPOSTOVISUIT,   CDREGRAIT, CDENQLEGALIPI, CDCEST, VRADICFECP, VRADICALIQFECP,
                                          CDBENEFFISCAL,   IDDESONERAREGRA, IDCONSDESONVRNF, IDVALORINFIT)
                                       VALUES(
                                          P_FILIAL,                P_LANCTONF,     C_ITEMPROD.NRSEQITPROD, C_ITEMPROIMPOS.CDIMPOSTO, w_2,                 w_2,
                                          NVL(V_SITUTRIBPR, C_ITEMPROD.CDSITUTRIBPR), V_FISOPEITEM,   V_SUFXCFOPPR,           0,                        V_PERDBCALC,         V_PARDEDTMP,
                                          V_CONTABCALC,            0,              0,                      w_00000,                  w_00000,             V_IDTRIMPSTII,
                                          V_CDSITUTRIBNFE,         V_IDMODBCNFEIT, V_IDMODBCSTNFEIT,       V_CDTPCRPICOSTNFEIT,      V_CDNATUBCPCSTNFEIT, V_IDMOTIDESSTNFE,
                                          V_CDDETALHEPRODTEMP, 0,     V_CDREGRAITALIQ, V_CDENQLEGALIPI, V_CDCEST, ROUND((C_ITEMPROIMPOS.VRADICFECP * V_VRFATOCONV), 2), C_ITEMPROIMPOS.VRADICALIQFECP,
                                          V_CDBENEFFISCAL, NVL(V_IDIMPODESONERA, 'N'), NVL(V_IDCONSDESONVRNF, 'N'), C_ITEMPROIMPOS.IDVALORINFIT);
                                    ELSE
                                       INSERT INTO ITEMPROIMPOS(
                                          CDFILIAL,        NRLANCTONF,     NRSEQITPROD,     CDIMPOSTO,       NRITPROIMPOS,   CDFISCALIT,
                                          CDSITUTRIBIT,    CDFISCOPERIT,   CDSUFXCFOPIT,    VRALIQITEM,      VRPERREDBCIT,   VRPARDEDIT,
                                          VRCONTITIMP,     VRBASECALCIT,   VRIMPOSTOIT,     IDERROSIMPIT,    IDAVISIMPIT,    IDTRIMPSTII,
                                          CDSITUTRIBITNFE, IDMODBCITNFE,   IDMODBCSTITNFE,  CDTPCREDPICOITE, CDNATUBCALPCIT, IDMOTDESONERAIT,
                                          CDDETALHEPROD,   VRIMPOSTOVISUIT,   CDREGRAIT, CDENQLEGALIPI, CDCEST, VRADICFECP, VRADICALIQFECP,
                                          CDBENEFFISCAL,   IDDESONERAREGRA, IDCONSDESONVRNF, IDVALORINFIT, VRPERREDBCSTIT)
                                       VALUES(
                                          P_FILIAL,                P_LANCTONF,     C_ITEMPROD.NRSEQITPROD, C_ITEMPROIMPOS.CDIMPOSTO, w_2,                 w_2,
                                          NVL(V_SITUTRIBPR, C_ITEMPROD.CDSITUTRIBPR), V_FISOPEITEM,   V_SUFXCFOPPR,           0,                        V_PERDBCALC,         V_PARDEDTMP,
                                          V_CONTABCALC,            0,              0,                      w_00000,                  w_00000,             V_IDTRIMPSTII,
                                          V_CDSITUTRIBNFE,         V_IDMODBCNFEIT, V_IDMODBCSTNFEIT,       V_CDTPCRPICOSTNFEIT,      V_CDNATUBCPCSTNFEIT, V_IDMOTIDESSTNFE,
                                          V_CDDETALHEPRODTEMP,     0,     V_CDREGRAITALIQ, V_CDENQLEGALIPI, V_CDCEST, ROUND((C_ITEMPROIMPOS.VRADICFECP * V_VRFATOCONV), 2), C_ITEMPROIMPOS.VRADICALIQFECP,
                                          V_CDBENEFFISCAL, NVL(V_IDIMPODESONERA, 'N'), NVL(V_IDCONSDESONVRNF, 'N'), C_ITEMPROIMPOS.IDVALORINFIT, V_PREDBCSTIT);
                                    END IF;
                                 END IF;
                              END IF;
                              IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (V_ICMS = 'S') THEN
                                 INSERT INTO ITEMPROIMPOSORIG(CDFILIAL,     NRLANCTONF,     NRSEQITPROD,     CDIMPOSTO,      NRITPROIMPOS,    CDFISCALIT,
                                                          CDSITUTRIBIT, CDFISCOPERIT,   CDSUFXCFOPIT,    VRALIQITEM,     VRPERREDBCIT,    VRPARDEDIT,
                                                          VRCONTITIMP,  VRBASECALCIT,   VRIMPOSTOIT,     IDERROSIMPIT,   IDAVISIMPIT,     CDSITUTRIBITNFE,
                                                          IDMODBCITNFE, IDMODBCSTITNFE, CDTPCREDPICOITE, CDNATUBCALPCIT, IDMOTDESONERAIT, IDTRIMPSTII,
                                                          CDDETALHEPROD, CDENQLEGALIPI, CDCEST, CDBENEFFISCAL)
                                 VALUES(P_FILIAL, P_LANCTONF, C_ITEMPROD.NRSEQITPROD, C_ITEMPROIMPOS.CDIMPOSTO, C_ITEMPROIMPOS.NRITPROIMPOS, C_ITEMPROIMPOS.CDFISCALIT,
                                        C_ITEMPROD.CDSITUTRIBPR, V_FISOPEITEM, V_SUFXCFOPPR, C_ITEMPROIMPOS.VRALIQITEM, C_ITEMPROIMPOS.VRPERREDBCIT, TRUNC((C_ITEMPROIMPOS.VRPARDEDIT * V_VRFATOCONV),2),
                                        TRUNC((C_ITEMPROIMPOS.VRCONTITIMP * V_VRFATOCONV),2), TRUNC((C_ITEMPROIMPOS.VRBASECALCIT * V_VRFATOCONV),2),
                                        TRUNC((C_ITEMPROIMPOS.VRIMPOSTOIT * V_VRFATOCONV),2), w_00000, w_00000, C_ITEMPROIMPOS.CDSITUTRIBNFE,
                                        C_ITEMPROIMPOS.IDMODBCNFE, C_ITEMPROIMPOS.IDMODBCSTNFE, C_ITEMPROIMPOS.CDTPCREDPICOITE, C_ITEMPROIMPOS.CDNATUBCALPCIT, NVL(C_ITEMPROIMPOS.IDMOTDESONERAIT,'9'), C_ITEMPROIMPOS.IDTRIMPSTII,
                                        V_CDDETALHEPRODTEMP, V_CDENQLEGALIPI, V_CDCEST, V_CDBENEFFISCAL);
                              ELSE
                                 INSERT INTO ITEMPROIMPOSORIG(CDFILIAL,     NRLANCTONF,     NRSEQITPROD,     CDIMPOSTO,      NRITPROIMPOS,    CDFISCALIT,
                                                          CDSITUTRIBIT, CDFISCOPERIT,   CDSUFXCFOPIT,    VRALIQITEM,     VRPERREDBCIT,    VRPARDEDIT,
                                                          VRCONTITIMP,  VRBASECALCIT,   VRIMPOSTOIT,     IDERROSIMPIT,   IDAVISIMPIT,     CDSITUTRIBITNFE,
                                                          IDMODBCITNFE, IDMODBCSTITNFE, CDTPCREDPICOITE, CDNATUBCALPCIT, IDMOTDESONERAIT, IDTRIMPSTII,
                                                          CDDETALHEPROD, CDENQLEGALIPI, CDCEST, CDBENEFFISCAL)
                                 VALUES(P_FILIAL, P_LANCTONF, C_ITEMPROD.NRSEQITPROD, C_ITEMPROIMPOS.CDIMPOSTO, C_ITEMPROIMPOS.NRITPROIMPOS, C_ITEMPROIMPOS.CDFISCALIT,
                                        C_ITEMPROD.CDSITUTRIBPR, V_FISOPEITEM, V_SUFXCFOPPR, C_ITEMPROIMPOS.VRALIQITEM, C_ITEMPROIMPOS.VRPERREDBCIT, (C_ITEMPROIMPOS.VRPARDEDIT * V_VRFATOCONV),
                                        ROUND((C_ITEMPROIMPOS.VRCONTITIMP * V_VRFATOCONV),2), (C_ITEMPROIMPOS.VRBASECALCIT * V_VRFATOCONV),
                                        (C_ITEMPROIMPOS.VRIMPOSTOIT * V_VRFATOCONV), w_00000, w_00000, C_ITEMPROIMPOS.CDSITUTRIBNFE,
                                        C_ITEMPROIMPOS.IDMODBCNFE, C_ITEMPROIMPOS.IDMODBCSTNFE, C_ITEMPROIMPOS.CDTPCREDPICOITE, C_ITEMPROIMPOS.CDNATUBCALPCIT, NVL(C_ITEMPROIMPOS.IDMOTDESONERAIT,'9'), C_ITEMPROIMPOS.IDTRIMPSTII,
                                        V_CDDETALHEPRODTEMP, V_CDENQLEGALIPI, V_CDCEST, V_CDBENEFFISCAL);
                              END IF;
                           END IF;
                        END IF;
                     ELSE
                        BEGIN
                           SELECT CDFILIAL
                             INTO V_CHAVE
                             FROM ITEMPROIMPOS
                            WHERE CDFILIAL     = P_FILIAL
                              AND NRLANCTONF   = P_LANCTONF
                              AND NRSEQITPROD  = C_ITEMPROD.NRSEQITPROD
                              AND CDIMPOSTO    = C_ITEMPROIMPOS.CDIMPOSTO 
                              AND NRITPROIMPOS = C_ITEMPROIMPOS.NRITPROIMPOS;
                        EXCEPTION
                           WHEN NO_DATA_FOUND THEN BEGIN
                              V_CHAVE := NULL;
                           END;
                        END;
                        IF V_IDPERVISIMPSCRE = 'S' THEN
                           V_VRIMPOSTOVISUIT := (C_ITEMPROIMPOS.VRIMPOSTOIT * V_VRFATOCONV);
                        ELSE
                           IF (V_CDFISCTEMP = '1') THEN
                             V_VRIMPOSTOVISUIT := (C_ITEMPROIMPOS.VRIMPOSTOIT * V_VRFATOCONV);
                           ELSE
                             V_VRIMPOSTOVISUIT := 0;
                           END IF;
                        END IF;
                        -- ALTERAR O VALOR CONTABIL CASO O PARAMETRO CONTABILIZA CONFORME NF DE ORIGEM ESTEJA DESMARCADO
                        IF (V_IDCONTCONFORIG =  'N') THEN
                           V_IMPOCONTAB  := 0;
                           V_IDIMPORECUP := NULL;
                           V_CDCCTBLATIV := NULL;
                           V_IDTRATIMPO  := NULL;
                           SELECT NVL(IDIMPORECUP, 'N'), IDTRATIMPO, CDCCTBLATIV
                             INTO V_IDIMPORECUP, V_IDTRATIMPO, V_CDCCTBLATIV
                             FROM IMPOSTO
                            WHERE CDIMPOSTO = C_ITEMPROIMPOS.CDIMPOSTO;
                           IF (V_IDIMPORECUP = W_S) THEN
                              IF (V_CDFISCTEMP = W_1) THEN
                                 IF (V_CDCCTBLATIV IS NOT NULL) THEN
                                    IF V_IDTRATIMPO = W_V THEN
                                       V_IMPOCONTAB := - C_ITEMPROIMPOS.VRIMPOSTOIT;
                                    END IF;
                                 END IF;
                              ELSE
                                 IF V_IDTRATIMPO = W_A THEN
                                    V_IMPOCONTAB := V_IMPOSTOIT;
                                 ELSIF V_IDTRATIMPO IN (W_D,W_R) THEN
                                    V_IMPOCONTAB := - C_ITEMPROIMPOS.VRIMPOSTOIT;
                                 END IF;
                              END IF;
                           END IF;
                           IF (ABS(NVL(V_IMPOCONTAB, 0)) > 0) THEN
                              UPDATE ITEMPRODUTO
                                 SET VRCONTITEMORIG = (VRCONTITEM) + NVL(V_IMPOCONTAB, 0),
                                     VRCONTITEM     = (VRCONTITEM) + NVL(V_IMPOCONTAB, 0)
                               WHERE CDFILIAL       = P_FILIAL
                                 AND NRLANCTONF     = P_LANCTONF
                                 AND NRSEQITPROD    = C_ITEMPROD.NRSEQITPROD;
                           END IF;
                        END IF;
                        -- Alterar o valor contabil caso o parametro Contabiliza conforme NF de origem esteja desmarcado
                        IF V_CHAVE IS NULL THEN
                           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_ITEMPROIMPOS.CDIMPOSTO)
                           LOOP
                              V_ICMS := 'S';
                           END LOOP;
                           IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (V_ICMS = '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, IDTRIMPSTII,
                                                       CDDETALHEPROD, VRIMPOSTOVISUIT, CDENQLEGALIPI, CDCEST, CDBENEFFISCAL, IDDESONERAREGRA,
                                                       IDCONSDESONVRNF, IDVALORINFIT)
                              VALUES(P_FILIAL, P_LANCTONF, C_ITEMPROD.NRSEQITPROD, C_ITEMPROIMPOS.CDIMPOSTO, C_ITEMPROIMPOS.NRITPROIMPOS, V_CDFISCTEMP,
                                     NVL(V_SITUTRIBPR, C_ITEMPROD.CDSITUTRIBPR), V_FISOPEITEM, V_SUFXCFOPPR, C_ITEMPROIMPOS.VRALIQITEM, C_ITEMPROIMPOS.VRPERREDBCIT, TRUNC((C_ITEMPROIMPOS.VRPARDEDIT * V_VRFATOCONV),2),
                                     TRUNC((C_ITEMPROIMPOS.VRCONTITIMP * V_VRFATOCONV),2), TRUNC((C_ITEMPROIMPOS.VRBASECALCIT * V_VRFATOCONV),2),
                                     TRUNC((C_ITEMPROIMPOS.VRIMPOSTOIT * V_VRFATOCONV),2), w_00000, w_00000, V_CDSITUTRIBNFE,
                                     V_IDMODBCNFEIT, V_IDMODBCSTNFEIT, V_CDTPCRPICOSTNFEIT, V_CDNATUBCPCSTNFEIT, V_IDMOTIDESSTNFE, C_ITEMPROIMPOS.IDTRIMPSTII,
                                     V_CDDETALHEPRODTEMP, TRUNC(V_VRIMPOSTOVISUIT,2), V_CDENQLEGALIPI, V_CDCEST, V_CDBENEFFISCAL, NVL(V_IDIMPODESONERA, 'N'),
                                     NVL(V_IDCONSDESONVRNF, 'N'), C_ITEMPROIMPOS.IDVALORINFIT);
                           ELSE
                              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, IDTRIMPSTII,
                                                       CDDETALHEPROD, VRIMPOSTOVISUIT, CDENQLEGALIPI, CDCEST, VRADICFECP, VRADICALIQFECP,
                                                       CDBENEFFISCAL, IDDESONERAREGRA, IDCONSDESONVRNF, IDVALORINFIT)
                              VALUES(P_FILIAL, P_LANCTONF, C_ITEMPROD.NRSEQITPROD, C_ITEMPROIMPOS.CDIMPOSTO, C_ITEMPROIMPOS.NRITPROIMPOS, V_CDFISCTEMP,
                                     NVL(V_SITUTRIBPR, C_ITEMPROD.CDSITUTRIBPR), V_FISOPEITEM, V_SUFXCFOPPR, C_ITEMPROIMPOS.VRALIQITEM, C_ITEMPROIMPOS.VRPERREDBCIT, (C_ITEMPROIMPOS.VRPARDEDIT * V_VRFATOCONV),
                                     ROUND((C_ITEMPROIMPOS.VRCONTITIMP * V_VRFATOCONV),2), (C_ITEMPROIMPOS.VRBASECALCIT * V_VRFATOCONV),
                                     (C_ITEMPROIMPOS.VRIMPOSTOIT * V_VRFATOCONV), w_00000, w_00000, V_CDSITUTRIBNFE,
                                     V_IDMODBCNFEIT, V_IDMODBCSTNFEIT, V_CDTPCRPICOSTNFEIT, V_CDNATUBCPCSTNFEIT, V_IDMOTIDESSTNFE, C_ITEMPROIMPOS.IDTRIMPSTII,
                                     V_CDDETALHEPRODTEMP, ROUND(V_VRIMPOSTOVISUIT,2), V_CDENQLEGALIPI, V_CDCEST, ROUND((C_ITEMPROIMPOS.VRADICFECP * V_VRFATOCONV), 2), C_ITEMPROIMPOS.VRADICALIQFECP,
                                     V_CDBENEFFISCAL, NVL(V_IDIMPODESONERA, 'N'), NVL(V_IDCONSDESONVRNF, 'N'), C_ITEMPROIMPOS.IDVALORINFIT);
                           END IF;
                           IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (V_ICMS = 'S') THEN
                              INSERT INTO ITEMPROIMPOSORIG(CDFILIAL,     NRLANCTONF,     NRSEQITPROD,     CDIMPOSTO,      NRITPROIMPOS,    CDFISCALIT,
                                                       CDSITUTRIBIT, CDFISCOPERIT,   CDSUFXCFOPIT,    VRALIQITEM,     VRPERREDBCIT,    VRPARDEDIT,
                                                       VRCONTITIMP,  VRBASECALCIT,   VRIMPOSTOIT,     IDERROSIMPIT,   IDAVISIMPIT,     CDSITUTRIBITNFE,
                                                       IDMODBCITNFE, IDMODBCSTITNFE, CDTPCREDPICOITE, CDNATUBCALPCIT, IDMOTDESONERAIT, IDTRIMPSTII,
                                                       CDDETALHEPROD, CDENQLEGALIPI, CDCEST, CDBENEFFISCAL)
                              VALUES(P_FILIAL, P_LANCTONF, C_ITEMPROD.NRSEQITPROD, C_ITEMPROIMPOS.CDIMPOSTO, C_ITEMPROIMPOS.NRITPROIMPOS, C_ITEMPROIMPOS.CDFISCALIT,
                                     C_ITEMPROD.CDSITUTRIBPR, V_FISOPEITEM, V_SUFXCFOPPR, C_ITEMPROIMPOS.VRALIQITEM, C_ITEMPROIMPOS.VRPERREDBCIT, TRUNC((C_ITEMPROIMPOS.VRPARDEDIT * V_VRFATOCONV),2),
                                     TRUNC((C_ITEMPROIMPOS.VRCONTITIMP * V_VRFATOCONV),2), TRUNC((C_ITEMPROIMPOS.VRBASECALCIT * V_VRFATOCONV),2),
                                     TRUNC((C_ITEMPROIMPOS.VRIMPOSTOIT * V_VRFATOCONV),2), w_00000, w_00000, C_ITEMPROIMPOS.CDSITUTRIBNFE,
                                     C_ITEMPROIMPOS.IDMODBCNFE, C_ITEMPROIMPOS.IDMODBCSTNFE, C_ITEMPROIMPOS.CDTPCREDPICOITE, C_ITEMPROIMPOS.CDNATUBCALPCIT, NVL(C_ITEMPROIMPOS.IDMOTDESONERAIT,'9'), C_ITEMPROIMPOS.IDTRIMPSTII,
                                     V_CDDETALHEPRODTEMP, C_ITEMPROIMPOS.CDENQLEGALIPI, C_ITEMPROIMPOS.CDCEST, V_CDBENEFFISCAL);
                           ELSE
                              INSERT INTO ITEMPROIMPOSORIG(CDFILIAL,     NRLANCTONF,     NRSEQITPROD,     CDIMPOSTO,      NRITPROIMPOS,    CDFISCALIT,
                                                       CDSITUTRIBIT, CDFISCOPERIT,   CDSUFXCFOPIT,    VRALIQITEM,     VRPERREDBCIT,    VRPARDEDIT,
                                                       VRCONTITIMP,  VRBASECALCIT,   VRIMPOSTOIT,     IDERROSIMPIT,   IDAVISIMPIT,     CDSITUTRIBITNFE,
                                                       IDMODBCITNFE, IDMODBCSTITNFE, CDTPCREDPICOITE, CDNATUBCALPCIT, IDMOTDESONERAIT, IDTRIMPSTII,
                                                       CDDETALHEPROD, CDENQLEGALIPI, CDCEST, CDBENEFFISCAL)
                              VALUES(P_FILIAL, P_LANCTONF, C_ITEMPROD.NRSEQITPROD, C_ITEMPROIMPOS.CDIMPOSTO, C_ITEMPROIMPOS.NRITPROIMPOS, C_ITEMPROIMPOS.CDFISCALIT,
                                     C_ITEMPROD.CDSITUTRIBPR, V_FISOPEITEM, V_SUFXCFOPPR, C_ITEMPROIMPOS.VRALIQITEM, C_ITEMPROIMPOS.VRPERREDBCIT, (C_ITEMPROIMPOS.VRPARDEDIT * V_VRFATOCONV),
                                     ROUND((C_ITEMPROIMPOS.VRCONTITIMP * V_VRFATOCONV),2), (C_ITEMPROIMPOS.VRBASECALCIT * V_VRFATOCONV),
                                     (C_ITEMPROIMPOS.VRIMPOSTOIT * V_VRFATOCONV), w_00000, w_00000, C_ITEMPROIMPOS.CDSITUTRIBNFE,
                                     C_ITEMPROIMPOS.IDMODBCNFE, C_ITEMPROIMPOS.IDMODBCSTNFE, C_ITEMPROIMPOS.CDTPCREDPICOITE, C_ITEMPROIMPOS.CDNATUBCALPCIT, NVL(C_ITEMPROIMPOS.IDMOTDESONERAIT,'9'), C_ITEMPROIMPOS.IDTRIMPSTII,
                                     V_CDDETALHEPRODTEMP, C_ITEMPROIMPOS.CDENQLEGALIPI, C_ITEMPROIMPOS.CDCEST, V_CDBENEFFISCAL);
                           END IF;
                        END IF;
                     END IF;
                  END IF;
                  DELETE ALIQTEMP
                   WHERE NRALIQTEMP = V_ALIQTEMP;
               END LOOP;
               /*Imposto gerado como encargo na importacdo de xml */
               BEGIN
                  SELECT NVL(IDNFGERADAVIAXML, 'N')
                    INTO V_IDNFORIGVIAXML
                    FROM NOTAFISCAL N, ITEMPRODUTO IP
                   WHERE N.CDFILIAL   = C_ITEMNOTAFISC.CDFILIALIT
                     AND N.NRLANCTONF = C_ITEMNOTAFISC.NRLANCTONFIT
                     AND N.CDFILIAL   = IP.CDFILIAL
                     AND N.NRLANCTONF = IP.NRLANCTONF
                     AND IP.VRENCARGOIMPXML > 0
                     AND ROWNUM = 1;
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_IDNFORIGVIAXML := 'N';
               END;
               /*Imposto gerado como encargo na importacdo de xml*/
               IF (V_IDNFORIGVIAXML = 'S') AND (V_UPDENCIMPXML = 'N') THEN
                  FOR C_ENCARGO IN (SELECT IMP.CDENCARGOIMPXML
                                      FROM IMPOSTONFE NFE, IMPOSTO IMP
                                     WHERE IMP.CDIMPOSTOXML(+) = NFE.CDIMPOSTONFE
                                       AND IMP.CDENCARGOIMPXML IS NOT NULL
                                      ORDER BY NFE.CDIMPOSTONFE) LOOP
                     UPDATE ITEMENCARGO
                        SET VRITEMENCA = 0
                      WHERE CDFILIAL   = P_FILIAL
                        AND NRLANCTONF = P_LANCTONF
                        AND CDENCARGO  = C_ENCARGO.CDENCARGOIMPXML
                        AND IDALTERADO = 'N';
                  END LOOP;
                  V_UPDENCIMPXML := 'S';
               END IF;
               IF (V_IDNFORIGVIAXML = 'S') THEN
                  BEGIN
                     SELECT SUM(I.VRENCARGOIMPXML), SUM(VRTOTAITEM - VRDESCITEM) AS VRLIQUORIG, I.NRSEQITPROD, N.NRACESSONFE
                       INTO V_VRENCARGOIMPXML, V_VRLIQUORIG, V_NRSEQITORIG, V_NRACESSONFORIG
                       FROM ITEMPRODUTO I, NOTAFISCAL N
                      WHERE I.CDFILIAL    = C_ITEMNOTAFISC.CDFILIALIT
                        AND I.NRLANCTONF  = C_ITEMNOTAFISC.NRLANCTONFIT
                        AND I.CDPRODUTO   = C_ITEMPROD.CDPRODUTO
                        AND I.CDFILIAL    = N.CDFILIAL
                        AND I.NRLANCTONF  = N.NRLANCTONF
                        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  I.VRENCARGOIMPXML > 0
                        AND ROWNUM = 1
                      GROUP BY I.NRSEQITPROD, N.NRACESSONFE;
                  EXCEPTION
                     WHEN NO_DATA_FOUND THEN
                        V_VRENCARGOIMPXML := 0; V_VRLIQUORIG := 0; V_NRSEQITORIG := NULL; V_NRACESSONFORIG := NULL;
                  END;
                  IF (V_VRENCARGOIMPXML > 0) THEN
                     V_VRFATOCONV :=  (C_ITEMPROD.VRTOTAITEM - C_ITEMPROD.VRDESCITEM)/ V_VRLIQUORIG;
                     FOR C_ENCARGOXML IN (SELECT IMP.CDENCARGOIMPXML, IMP.CDIMPOSTO
                                            FROM IMPOSTONFE NFE, IMPOSTO IMP
                                           WHERE IMP.CDIMPOSTOXML(+) = NFE.CDIMPOSTONFE
                                             AND IMP.CDENCARGOIMPXML IS NOT NULL) LOOP
                        BEGIN
                           SELECT IT.VRIMPOSTOIT + (NVL(VRADICFECP, 0))
                             INTO V_VRIMPENCXMLORIG
                             FROM INTG_TRABITPROIMPOS IT, IMPOSTO I
                            WHERE IT.NRACESSONFE  = V_NRACESSONFORIG
                              AND IT.CDIMPOSTOIT  = I.CDIMPOSTO
                              AND LPAD(IT.NRSEQIMPOIT, 4, '0') = V_NRSEQITORIG
                              AND IT.CDIMPOSTOIT = C_ENCARGOXML.CDIMPOSTO;
                        EXCEPTION
                           WHEN NO_DATA_FOUND THEN
                              V_VRIMPENCXMLORIG := 0;
                        END;
                        IF V_VRIMPENCXMLORIG > 0 THEN
                           UPDATE ITEMENCARGO
                              SET VRITEMENCA = VRITEMENCA + (V_VRIMPENCXMLORIG * V_VRFATOCONV)
                            WHERE CDFILIAL   = P_FILIAL
                              AND NRLANCTONF = P_LANCTONF
                              AND CDENCARGO  = C_ENCARGOXML.CDENCARGOIMPXML;
                        END IF;
                     END LOOP;
                  END IF;
               END IF; -- Pegar o valor proporcional do imposto
            END LOOP;
         END IF;
         DELETE CFOPTEMP
          WHERE NRCFOPTEMP = V_CFOPTEMP;
         IF (V_IDOPERDEVONF <> w_S) THEN
            IF V_IDDOCREPLIC IS NOT NULL THEN
               IF LENGTH(V_SITUTRIBPR) = 3 THEN
                  V_SITUTRIBPR := SUBSTR(V_SITUTRIBPR,1,1) || w_90;
               ELSE
                  V_SITUTRIBPR := w_90;
               END IF;
            END IF;
            UPDATE ITEMPRODUTO
            SET CDSITUTRIBPR  = V_SITUTRIBPR
            WHERE CDFILIAL    = P_FILIAL   AND
                  NRLANCTONF  = P_LANCTONF AND
                  NRSEQITPROD = C_ITEMPROD.NRSEQITPROD;
         END IF;
         DELETE CSTTEMP
         WHERE NRCSTTEMP = V_CSTTEMP;
         V_IMPOCONTAB := 0;
      END LOOP;
      SELECT MAX(IDUTCTRLFISSAID)
        INTO V_IDUTCTRLFISSAID
        FROM PARAMGERAL;
      SELECT MAX(IDUTCTRLFISSAID)
        INTO V_IDUTCTRLFISFIL
        FROM PARAMFILIAL
       WHERE CDFILIAL = V_CDFILIEMIT;
      IF V_IDUTCTRLFISSAID = 'S' THEN
         V_IDUTCTRLFIS := 'S';
      ELSE
         IF V_IDUTCTRLFISFIL = 'S' THEN
            V_IDUTCTRLFIS := 'S';
         ELSE
            V_IDUTCTRLFIS := 'N';
         END IF;
      END IF;
      SELECT NVL(MAX(IDGERICMSTDESPA), 'N'), MAX(CDENCARGOICMST), NVL(MAX(IDPEINFICMSTDEME), 'N'), NVL(MAX(IDGERIPIDESPA), 'N')
        INTO V_IDGERICMSTDESPA, V_CDENCARGOICMST, V_IDPEINFICMSTDEME, V_IDGERIPIDESPA
        FROM TIPOOPERAC
       WHERE IDENTRSAIDOP = 'S'
         AND CDTIPOOPER = P_TIPOOPER;
      IF ((V_IDGERICMSTDESPA = 'S') OR (V_IDGERIPIDESPA = 'S')) AND (V_IDUTCTRLFIS = 'S') AND (V_IDNFORIGVIAXML = 'N') THEN
         UPDATE ITEMENCARGO
            SET VRITEMENCA = 0
          WHERE CDFILIAL = P_FILIAL
            AND NRLANCTONF = P_LANCTONF
            AND IDALTERADO = 'N';
      END IF;
      V_VRENCAICMSSTIT := 0;
      FOR C_ITEMNOTAFISC IN (SELECT CDFILIALIT, NRLANCTONFIT
                             FROM ITEMNOTAFISC
                             WHERE CDFILIAL   = P_FILIAL AND
                                   NRLANCTONF = P_LANCTONF) LOOP
         SELECT SUM(VRTOTAITEM - VRDESCITEM) AS VRLIQUORIG
         INTO   V_VRLIQUORIG
         FROM ITEMPRODUTO I
         WHERE CDFILIAL    = C_ITEMNOTAFISC.CDFILIALIT AND
               NRLANCTONF  = C_ITEMNOTAFISC.NRLANCTONFIT;
         IF V_VRLIQUORIG = 0 THEN
            V_VRFATOCONV := 0;
         ELSE
            V_VRFATOCONV := V_LIQUIDO / V_VRLIQUORIG;
         END IF;
         IF (V_IDNFORIGVIAXML = 'N') THEN
            SELECT SUM(VRITEMENCA)
              INTO V_VRENCAICMSSTIT
              FROM ITEMENCARGO
             WHERE CDFILIAL = C_ITEMNOTAFISC.CDFILIALIT
               AND NRLANCTONF = C_ITEMNOTAFISC.NRLANCTONFIT
               AND CDENCARGO = V_CDENCARGOICMST;
            FOR C_ITEMENCARGO IN (SELECT CDENCARGO, SUM(VRITEMENCA) AS VRITEMENCA
                                  FROM ITEMENCARGO
                                  WHERE CDFILIAL   = C_ITEMNOTAFISC.CDFILIALIT   AND
                                        NRLANCTONF = C_ITEMNOTAFISC.NRLANCTONFIT AND
                                        VRITEMENCA > 0
                                  GROUP BY CDENCARGO) LOOP
                SELECT NVL(MAX(IDALTERADO), 'N')
                  INTO V_IDALTERADO_ENCA
                  FROM ITEMENCARGO
                WHERE CDFILIAL   = P_FILIAL
                  AND NRLANCTONF = P_LANCTONF
                  AND CDENCARGO = C_ITEMENCARGO.CDENCARGO;
                IF V_IDALTERADO_ENCA = 'N' THEN
                   UPDATE ITEMENCARGO
                   SET VRITEMENCA = (C_ITEMENCARGO.VRITEMENCA * V_VRFATOCONV)
                   WHERE CDFILIAL   = P_FILIAL   AND
                         NRLANCTONF = P_LANCTONF AND
                         CDENCARGO  = C_ITEMENCARGO.CDENCARGO;
                END IF;
            END LOOP;
         END IF;   
      END LOOP;
      /*CALCULA DESCONTO DE BONIFICACAO NA DEVOLUCAO DE NOTAS */
      SELECT MAX(CDENCDESCBONDEV)
        INTO V_CDENCDESCBONDEV
        FROM PARAMGERAL;
      IF V_CDENCDESCBONDEV IS NOT NULL THEN
         SELECT NVL(MAX(IDCONDESBONFORN), 'S') INTO V_IDCONDESBONFORN
           FROM PARAMFILIAL
          WHERE CDFILIAL = V_CDFILIEMIT;
         SELECT MAX(F.CDAJUCTPAG), MAX(F.VRPEDESCFORN), TO_DATE(NVL(MAX(DTINIVRPDESC), '01/01/0100'))
           INTO V_CDAJUCTPAG, V_VRPEDESCFORN, V_DTINIVRPDESC
           FROM FORNECEDOR F
          WHERE (F.CDFORNECED   = P_CLIENTE)
            AND (NOT F.VRPEDESCFORN IS NULL)
            AND (F.IDTPDESCFORN = 'B');
         IF (V_VRPEDESCFORN IS NOT NULL) AND (V_VRPEDESCFORN <> 0) AND (V_IDCONDESBONFORN = 'S') THEN
            IF (P_INIVALID >= V_DTINIVRPDESC) THEN
               V_VRENCARBONI := ROUND(V_LIQUIDO * (V_VRPEDESCFORN/100),2);
               UPDATE ITEMENCARGO
               SET VRITEMENCA = V_VRENCARBONI
               WHERE CDFILIAL = P_FILIAL
                 AND NRLANCTONF = P_LANCTONF
                 AND CDENCARGO = V_CDENCDESCBONDEV;
            END IF;
         END IF;
      END IF;
      DELETE FROM DADOSADIC
       WHERE CDFILIAL   = P_FILIAL
         AND NRLANCTONF = P_LANCTONF
         AND DSDADOADIC LIKE 'Base de Calculo do ICMS ST%';
      DELETE FROM DADOSADIC
       WHERE CDFILIAL   = P_FILIAL
         AND NRLANCTONF = P_LANCTONF
         AND DSDADOADIC LIKE 'ICMS ST: R$%';
      DELETE FROM DADOSADIC
       WHERE CDFILIAL   = P_FILIAL
         AND NRLANCTONF = P_LANCTONF
         AND DSDADOADIC LIKE 'Valor de IPI: R$%';
      IF (V_IDUTCTRLFIS = 'S') THEN
         IF V_IDGERICMSTDESPA = 'S' THEN
            IF V_CDENCARGOICMST IS NOT NULL THEN
               SELECT NVL(MAX(IDALTERADO), 'N')
                 INTO V_IDALTERADO_ENCA
                 FROM ITEMENCARGO
               WHERE CDFILIAL   = P_FILIAL
                 AND NRLANCTONF = P_LANCTONF
                 AND CDENCARGO = V_CDENCARGOICMST;
               IF V_IDALTERADO_ENCA = 'N' THEN
                  UPDATE ITEMENCARGO
                     SET VRITEMENCA = 0
                   WHERE CDFILIAL = P_FILIAL
                     AND NRLANCTONF = P_LANCTONF
                     AND CDENCARGO = V_CDENCARGOICMST;
               END IF;
               SELECT MAX(CDENCARGO)
                 INTO V_CDENCARGOOD
                 FROM ENCARGO
                WHERE CDENCARGONFE = '04';
               IF V_CDENCARGOOD IS NOT NULL THEN
                  SELECT NVL(MAX(IDALTERADO), 'N')
                    INTO V_IDALTERADO_ENCA
                    FROM ITEMENCARGO
                   WHERE CDFILIAL = P_FILIAL
                     AND NRLANCTONF = P_LANCTONF
                     AND CDENCARGO = V_CDENCARGOOD;
                  IF V_IDALTERADO_ENCA = 'N' THEN
                     IF (V_VRENCAICMSSTIT > 0) OR (V_VRTOTALICMSST > 0) THEN
                        IF V_IDPEINFICMSTDEME = 'S' THEN
                           SELECT NVL(SUM(VRICMSST),0), NVL(SUM(VRBASECALC),0)
                             INTO V_VRICMSST, V_VRBASECALC
                             FROM INFICMSST
                            WHERE CDFILIAL = P_FILIAL
                              AND NRLANCTONF = P_LANCTONF;
                           IF V_VRICMSST > 0 THEN
                              UPDATE ITEMENCARGO
                                 SET VRITEMENCA = ROUND(VRITEMENCA + V_VRICMSST,2)
                               WHERE CDFILIAL = P_FILIAL
                                 AND NRLANCTONF = P_LANCTONF
                                 AND CDENCARGO = V_CDENCARGOOD;
                              IF V_VRBASECALC > 0 THEN
                                 SELECT COUNT(*)
                                   INTO V_EXISTDSDADOSADIC
                                   FROM DADOSADIC
                                  WHERE CDFILIAL = P_FILIAL
                                    AND NRLANCTONF = P_LANCTONF
                                    AND DSDADOADIC LIKE 'Base de Calculo do ICMS ST%';
                                 IF V_EXISTDSDADOSADIC = 0 THEN
                                    INSERT INTO DADOSADIC(CDFILIAL, NRLANCTONF, NRDADOADIC, DSDADOADIC)
                                                   VALUES(P_FILIAL, P_LANCTONF, V_DADOADIC, 'Base de Calculo do ICMS ST: R$'||DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(V_VRBASECALC , 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(V_VRBASECALC , 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(V_VRBASECALC , 2), '9999999999999.99')))|| ' ICMS ST: R$'|| DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(V_VRICMSST, 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(V_VRICMSST, 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(V_VRICMSST, 2), '9999999999999.99'))));
                                    V_DADOADIC := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_DADOADIC) + 1)),3,0);
                                 ELSE
                                    UPDATE DADOSADIC
                                       SET DSDADOADIC = 'Base de Calculo do ICMS ST: R$'||DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(V_VRBASECALC, 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(V_VRBASECALC, 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(V_VRBASECALC, 2), '9999999999999.99')))|| ' ICMS ST: R$'|| DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(V_VRICMSST, 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(V_VRICMSST, 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(V_VRICMSST, 2), '9999999999999.99')))
                                      WHERE CDFILIAL = P_FILIAL
                                        AND NRLANCTONF = P_LANCTONF
                                        AND DSDADOADIC LIKE 'Base de Calculo do ICMS ST%';
                                 END IF;
                              ELSE
                                 SELECT COUNT(*)
                                   INTO V_EXISTDSDADOSADIC
                                   FROM DADOSADIC
                                  WHERE CDFILIAL = P_FILIAL
                                    AND NRLANCTONF = P_LANCTONF
                                    AND DSDADOADIC LIKE 'ICMS ST: R$%';
                                 IF V_EXISTDSDADOSADIC = 0 THEN
                                    INSERT INTO DADOSADIC(CDFILIAL, NRLANCTONF, NRDADOADIC, DSDADOADIC)
                                                   VALUES(P_FILIAL, P_LANCTONF, V_DADOADIC, 'ICMS ST: R$ '||DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(V_VRICMSST, 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(V_VRICMSST, 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(V_VRICMSST, 2), '9999999999999.99'))));
                                    V_DADOADIC := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_DADOADIC) + 1)),3,0);
                                 ELSE
                                    UPDATE DADOSADIC
                                       SET DSDADOADIC = 'ICMS ST: R$ '||DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(V_VRICMSST, 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(V_VRICMSST, 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(V_VRICMSST, 2), '9999999999999.99')))
                                      WHERE CDFILIAL = P_FILIAL
                                        AND NRLANCTONF = P_LANCTONF
                                        AND DSDADOADIC LIKE 'ICMS ST: R$%';
                                 END IF;
                              END IF;
                           END IF;
                        ELSE
                           UPDATE ITEMENCARGO
                              SET VRITEMENCA = ROUND(VRITEMENCA + (V_VRENCAICMSSTIT * V_VRFATOCONV) + V_VRTOTALICMSST,2)
                            WHERE CDFILIAL = P_FILIAL
                              AND NRLANCTONF = P_LANCTONF
                              AND CDENCARGO = V_CDENCARGOOD;
                           SELECT COUNT(*)
                             INTO V_EXISTDSDADOSADIC
                             FROM DADOSADIC
                            WHERE CDFILIAL = P_FILIAL
                              AND NRLANCTONF = P_LANCTONF
                              AND DSDADOADIC LIKE 'ICMS ST: R$%';
                           IF V_EXISTDSDADOSADIC = 0 THEN
                              INSERT INTO DADOSADIC(CDFILIAL, NRLANCTONF, NRDADOADIC, DSDADOADIC)
                                             VALUES(P_FILIAL, P_LANCTONF, V_DADOADIC, 'ICMS ST: R$ '||DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(V_VRTOTALICMSST + (V_VRENCAICMSSTIT * V_VRFATOCONV), 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(V_VRTOTALICMSST + (V_VRENCAICMSSTIT * V_VRFATOCONV), 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(V_VRTOTALICMSST + (V_VRENCAICMSSTIT * V_VRFATOCONV), 2), '9999999999999.99'))));
                              V_DADOADIC := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_DADOADIC) + 1)),3,0);
                           ELSE
                              UPDATE DADOSADIC
                                 SET DSDADOADIC = 'ICMS ST: R$ '||DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(V_VRTOTALICMSST + (V_VRENCAICMSSTIT * V_VRFATOCONV), 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(V_VRTOTALICMSST + (V_VRENCAICMSSTIT * V_VRFATOCONV), 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(V_VRTOTALICMSST + (V_VRENCAICMSSTIT * V_VRFATOCONV), 2), '9999999999999.99')))
                                WHERE CDFILIAL = P_FILIAL
                                  AND NRLANCTONF = P_LANCTONF
                                  AND DSDADOADIC LIKE 'ICMS ST: R$%';
                           END IF;
                        END IF;
                     END IF;
                  END IF;
               END IF;
            END IF;
         END IF;
         IF (V_IDGERIPIDESPA = 'S') THEN
            SELECT MAX(CDENCARGO)
              INTO V_CDENCARGOOD
              FROM ENCARGO
             WHERE CDENCARGONFE = '04';
            IF V_CDENCARGOOD IS NOT NULL THEN
               SELECT NVL(MAX(IDALTERADO), 'N')
                 INTO V_IDALTERADO_ENCA
                 FROM ITEMENCARGO
                WHERE CDFILIAL   = P_FILIAL
                  AND NRLANCTONF = P_LANCTONF
                  AND CDENCARGO  = V_CDENCARGOOD;
               IF V_IDALTERADO_ENCA = 'N' THEN
                  IF (V_VRTOTALIPI > 0) THEN
                     UPDATE ITEMENCARGO
                        SET VRITEMENCA = ROUND(VRITEMENCA + V_VRTOTALIPI, 2)
                      WHERE CDFILIAL = P_FILIAL
                        AND NRLANCTONF = P_LANCTONF
                        AND CDENCARGO = V_CDENCARGOOD;
                     SELECT COUNT(*)
                       INTO V_EXISTDSDADOSADIC
                       FROM DADOSADIC
                      WHERE CDFILIAL = P_FILIAL
                        AND NRLANCTONF = P_LANCTONF
                        AND DSDADOADIC LIKE 'Valor de IPI: R$%';
                     IF (V_EXISTDSDADOSADIC = 0) THEN
                        INSERT INTO DADOSADIC(CDFILIAL, NRLANCTONF, NRDADOADIC, DSDADOADIC)
                                       VALUES(P_FILIAL, P_LANCTONF, V_DADOADIC, 'Valor de IPI: R$ '||DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(V_VRTOTALIPI, 2),'9999999999999.99')),1, 1),'.','0'||LTRIM(TO_CHAR(ROUND(V_VRTOTALIPI, 2),'9999999999999.99')),LTRIM(TO_CHAR(ROUND(V_VRTOTALIPI, 2),'9999999999999.99'))));
                        V_DADOADIC := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_DADOADIC) + 1)),3,0);
                     ELSE
                        UPDATE DADOSADIC
                           SET DSDADOADIC = 'Valor de IPI: R$ '||DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(V_VRTOTALIPI, 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(V_VRTOTALIPI, 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(V_VRTOTALIPI, 2), '9999999999999.99')))
                          WHERE CDFILIAL = P_FILIAL
                            AND NRLANCTONF = P_LANCTONF
                            AND DSDADOADIC LIKE 'Valor de IPI: R$%';
                     END IF;
                  END IF;
               END IF;
            END IF;
         END IF;
      END IF;
      --RATEIO DOS ENCARGOS--------------------------------------------------------------------------------------------------------
      /* VERIFICAR SE EXISTE ENCARGO COM VALOR SOMENTE SE TIVER ALGUM ENCARGO PARAMETRIZADO PARA RATEAR PELO PESO LIQUIDO */
      IF NOT(V_ENCARGOLIQUIDO = 'N') THEN
         V_EXISTEENCARGO := 0;
         BEGIN
            SELECT COUNT(CDENCARGO)
              INTO V_EXISTEENCARGO
              FROM ITEMENCARGO
             WHERE VRITEMENCA > 0
               AND CDFILIAL   = P_FILIAL
               AND NRLANCTONF = P_LANCTONF;
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_EXISTEENCARGO := 0;
         END;
         IF (V_EXISTEENCARGO = 0) THEN
            V_ENCARGOLIQUIDO := 'N';
         END IF;
         /* VERIFICAR SE ALGUM ENCARGO QUE TEM VALOR ESTA PARAMETRIZADO PARA SER RATEADO POR PESO LIQUIDO CASO SEJA OPCAO LISTA */
         IF (V_EXISTEENCARGO > 0) THEN
            IF NOT(V_ENCARGOLIQUIDO = 'T') THEN
               BEGIN
                  SELECT COUNT(CDENCARGO)
                    INTO V_EXISTEENCARGO
                    FROM ITEMENCARGO
                   WHERE VRITEMENCA > 0
                     AND CDFILIAL   = P_FILIAL
                     AND NRLANCTONF = P_LANCTONF
                     AND INSTR(V_ENCARGOLIQUIDO, CDENCARGO) > 0;
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_EXISTEENCARGO := 0;
               END;
               /* SE HOUVER ENCARGO COM VALOR MAS NENHUM ESTEJA PARAMETRIZADO NA LISTA PARA RATEAR POR PESO LIQUIDO, A VARIAVEL V_ENCARGOLIQUIDO E PASSADA PARA N PARA QUE OS ENCARGOS QUE TENHAM
                  VALOR SEJAM RATEADOS DE FORMA PROPORCIONAL AO VALOR DOS PRODUTOS */
               IF (V_EXISTEENCARGO = 0) THEN
                  V_ENCARGOLIQUIDO := 'N';
               END IF;
            END IF;
         END IF;
      END IF;
      /* RATEIO DOS ENCARGOS QUE NAO SAO REFERENTES A IMPOSTOS GERADOS COMO ENCARGO NA ENTRADA */
      FOR C_ITEMENCARGO IN (SELECT IE.CDENCARGO AS CDENCARGO, VRITEMENCA, IDENCARGO,
                                   EN.CDCTBLENTREN, EN.CDCTBLSAIDEN
                              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
                                   (V_ENCARGOLIQUIDO <> 'T')      AND
                                   (NOT(INSTR(V_ENCARGOLIQUIDO, IE.CDENCARGO) > 0)) AND
                              (NOT EXISTS (SELECT CDENCARGOIMPXML
                                             FROM IMPOSTO
                                            WHERE IMPOSTO.CDENCARGOIMPXML = IE.CDENCARGO) OR (NVL(V_IDNFORIGVIAXML, 'N') = 'N')
                              )
                           ) 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
                                      (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_IDCONTCONFORIG = 'N') THEN
               SELECT SUM(VRTOTAITEM - VRDESCITEM)
               INTO   V_TOTAPRODENCA
               FROM ITEMPRODUTO IP
               WHERE (IP.CDFILIAL   = P_FILIAL)   AND
                     (IP.NRLANCTONF = P_LANCTONF);
               IF NOT V_TOTAPRODENCA 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.CDCTBLSAIDEN IS NULL) THEN
                        V_VRCONTAB := V_VRBRUTO;
                     ELSE
                        V_VRCONTAB := 0;
                     END IF;
                     IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (NVL(V_IDORIGDESTNF, 'C') <> 'L') THEN
                        UPDATE ITEMPRODUTO
                        SET VRBRUTITEM = TRUNC(VRBRUTITEM + (V_VRBRUTO  * (VRTOTAITEM - VRDESCITEM)),2),
                            VRCONTITEM = TRUNC(VRCONTITEM + (V_VRCONTAB * (VRTOTAITEM - VRDESCITEM)),2)
                        WHERE CDFILIAL    = P_FILIAL   AND
                              NRLANCTONF  = P_LANCTONF AND
                              NRSEQITPROD = C_ATUAVRCONT.NRSEQITPROD;
                     ELSE
                        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 IF;
                  END LOOP;
               END IF;
            END IF;
         ELSE
            IF (V_IDCONTCONFORIG = 'N') THEN
               FOR C_ATUAVRCONT 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
                                          (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.CDCTBLSAIDEN IS NULL) THEN
                     V_VRCONTAB := V_VRBRUTO;
                  ELSE
                     V_VRCONTAB := 0;
                  END IF;
                  IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (NVL(V_IDORIGDESTNF, 'C') <> 'L') THEN
                     UPDATE ITEMPRODUTO
                     SET VRBRUTITEM = TRUNC(VRBRUTITEM + (V_VRBRUTO  * (VRTOTAITEM - VRDESCITEM)),2),
                         VRCONTITEM = TRUNC(VRCONTITEM + (V_VRCONTAB * (VRTOTAITEM - VRDESCITEM)),2)
                     WHERE CDFILIAL    = P_FILIAL   AND
                           NRLANCTONF  = P_LANCTONF AND
                           NRSEQITPROD = C_ATUAVRCONT.NRSEQITPROD;
                  ELSE
                     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 IF;
               END LOOP;
            END IF;
            FOR C_ITEMPROIMPOS IN (SELECT II.NRSEQITPROD, 
                                          II.NRITPROIMPOS, 
                                          II.CDIMPOSTO, 
                                          II.VRPERREDBCIT,
                                          II.VRALIQITEM,  
                                          II.VRPARDEDIT, 
                                          II.IDTRIMPSTII, 
                                          (VRTOTAITEM - VRDESCITEM) AS VRLIQUIDO,
                                          NVL(II.IDVALORINFIT, W_N) AS IDVALORINFIT, 
                                          NVL(II.VRALIQINTEDEST, 0) AS VRALIQINTEDEST, 
                                          NVL(II.VRALIQFCP, 0) AS VRALIQFCP, 
                                          NVL(IP.IDUTILBCPMC, 'N') AS IDUTILBCPMC,
                                          I.CDIMPOSTONFE,
                                          II.VRPERREDBCSTIT
                                     FROM ITEMPROIMPOS II, ITEMPRODUTO IP, BASECALC BC, IMPOSTO I
                                    WHERE (II.CDFILIAL = P_FILIAL)
                                      AND (II.NRLANCTONF = P_LANCTONF)
                                      AND (IP.CDFILIAL = P_FILIAL)
                                      AND (IP.NRLANCTONF = P_LANCTONF)
                                      AND (IP.NRSEQITPROD = II.NRSEQITPROD)
                                      AND (BC.CDIMPOSTO = II.CDIMPOSTO)
                                      AND (II.CDIMPOSTO = I.CDIMPOSTO)
                                      AND (BC.CDENCARGO = C_ITEMENCARGO.CDENCARGO)
                                    ORDER BY II.NRSEQITPROD, 
                                          II.NRITPROIMPOS,
                                          II.CDIMPOSTO) LOOP
               /*IMPOSTOS QUE NAO FORAM GRAVADOS DE ACORDO COM A ORIGEM NAO DEVEM EFETUAR O CALCULO*/
               IF C_ITEMPROIMPOS.IDVALORINFIT <> W_S THEN
                  IF NOT((C_ITEMPROIMPOS.IDUTILBCPMC = W_S) AND (C_ITEMPROIMPOS.CDIMPOSTONFE = '80')) OR (C_ITEMPROIMPOS.IDUTILBCPMC <> W_S) THEN
                     SELECT SUM(VRTOTAITEM - VRDESCITEM)
                       INTO V_TOTAPRENIMPO
                       FROM ITEMPRODUTO IP
                      WHERE IP.CDFILIAL   = P_FILIAL
                        AND IP.NRLANCTONF = P_LANCTONF;
                     IF (V_TOTAPRODENCA <> 0) THEN
                        IF (C_ITEMENCARGO.IDENCARGO = w_A) THEN
                           V_PRODUENCARGO := + (C_ITEMENCARGO.VRITEMENCA/V_TOTAPRENIMPO)*C_ITEMPROIMPOS.VRLIQUIDO;
                        ELSIF (C_ITEMENCARGO.IDENCARGO = w_D) THEN
                           V_PRODUENCARGO := - (C_ITEMENCARGO.VRITEMENCA/V_TOTAPRENIMPO)*C_ITEMPROIMPOS.VRLIQUIDO;
                        ELSE
                           V_PRODUENCARGO := 0;
                        END IF;
                     END IF;
                     V_IDVRIMPSTRIB := NULL;
                     BEGIN
                        SELECT CASE COUNT(*) WHEN 0 THEN 'M' ELSE 'R' END
                          INTO V_MAJORAOUREDUZ
                          FROM ITEMPROIMPOS
                         WHERE CDFILIAL = P_FILIAL 
                           AND NRLANCTONF = P_LANCTONF
                           AND NRSEQITPROD = C_ITEMPROIMPOS.NRSEQITPROD
                           AND CDIMPOSTO = C_ITEMPROIMPOS.CDIMPOSTO
                           AND NRITPROIMPOS = w_2;
                     EXCEPTION
                        WHEN NO_DATA_FOUND THEN
                           V_MAJORAOUREDUZ := 'M';
                     END;
                     V_VRIMPOSTOST := 0;
                     IF V_MAJORAOUREDUZ = 'R' THEN
                        V_TAXABASECALC := (100 - C_ITEMPROIMPOS.VRPERREDBCIT)/100;
                        V_TAXAALIQUOTA := (C_ITEMPROIMPOS.VRALIQITEM/100);
                     ELSE
                        V_TAXABASECALC :=(100 - NVL(C_ITEMPROIMPOS.VRPERREDBCSTIT, 0))/100; /*Alterado por Lucas Lindo*/
                        V_PRODUENCARGO :=  (V_PRODUENCARGO * V_TAXABASECALC); /*Calcular o valor do encargo retirando reducao da base para no update abaixo utilize o valor adicionando a majoracao*/
                        V_TAXABASECALC := 1 + (C_ITEMPROIMPOS.VRPERREDBCIT)/100;
                        V_TAXAALIQUOTA := (C_ITEMPROIMPOS.VRALIQITEM/100);
                        SELECT NVL(MAX(IDVRIMPSTRIB), 'N')
                          INTO V_IDVRIMPSTRIB
                          FROM ITEMPROIMPOS I, IMPOSTO II
                         WHERE (CDFILIAL     = P_FILIAL)
                           AND (NRLANCTONF   = P_LANCTONF)
                           AND (NRSEQITPROD  = C_ITEMPROIMPOS.NRSEQITPROD)
                           AND (INSTR(V_CDIMPOSTRIB,II.CDIMPOSTO||'_') > 0)
                           AND (I.CDIMPOSTO = II.CDIMPOSTO);
                        IF (C_ITEMPROIMPOS.IDTRIMPSTII <> w_1) AND (NVL(V_IDVRIMPSTRIB,w_N) = w_S) THEN
                           Begin
                              SELECT NVL(MAX(VRIMPOSTOIT),0)
                              INTO   V_VRIMPOSTOST
                              FROM ITEMPROIMPOS I
                              WHERE (CDFILIAL     = P_FILIAL)                   AND
                                    (NRLANCTONF   = P_LANCTONF)                 AND
                                    (INSTR(V_CDIMPOSTRIB,CDIMPOSTO||'_') > 0)   AND
                                    (NRITPROIMPOS = C_ITEMPROIMPOS.NRITPROIMPOS) AND
                                    (NRSEQITPROD  = C_ITEMPROIMPOS.NRSEQITPROD);
                           Exception
                              When No_Data_Found Then
                                 V_VRIMPOSTOST := 0;
                           End;
                        END IF;
                     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_ITEMPROIMPOS.CDIMPOSTO)
                     LOOP
                        V_ICMS := 'S';
                     END LOOP;
                     UPDATE ITEMPROIMPOS
                        SET VRCONTITIMP  = VRCONTITIMP  + (V_PRODUENCARGO * V_TAXABASECALC),
                            VRBASECALCIT = VRBASECALCIT + ((V_PRODUENCARGO * V_TAXABASECALC) / (1 - ((C_ITEMPROIMPOS.VRALIQINTEDEST + C_ITEMPROIMPOS.VRALIQFCP) / 100))),
                            VRIMPOSTOIT  = (VRIMPOSTOIT  + (((V_PRODUENCARGO * V_TAXABASECALC) / (1 - ((C_ITEMPROIMPOS.VRALIQINTEDEST + C_ITEMPROIMPOS.VRALIQFCP) / 100))) * V_TAXAALIQUOTA)) - (((V_VRIMPOSTOST * V_TAXABASECALC) / (1 - ((C_ITEMPROIMPOS.VRALIQINTEDEST + C_ITEMPROIMPOS.VRALIQFCP) / 100))) * V_TAXAALIQUOTA),
                            VRIMPOSTOVISUIT = DECODE(V_IDPERVISIMPSCRE, 'S', (VRIMPOSTOIT  + ((V_PRODUENCARGO * V_TAXABASECALC) * V_TAXAALIQUOTA)) - ((V_VRIMPOSTOST * V_TAXABASECALC) * V_TAXAALIQUOTA),  DECODE(CDFISCALIT , '1', (VRIMPOSTOIT  + ((V_PRODUENCARGO * V_TAXABASECALC) * V_TAXAALIQUOTA)) - ((V_VRIMPOSTOST * V_TAXABASECALC) * V_TAXAALIQUOTA),0)),
                            VRADICFECP  = VRADICFECP  + ROUND((V_PRODUENCARGO * (VRADICALIQFECP / 100) * V_TAXABASECALC),2)
                      WHERE (CDFILIAL     = P_FILIAL)                   AND
                            (NRLANCTONF   = P_LANCTONF)                 AND
                            (NRSEQITPROD  = C_ITEMPROIMPOS.NRSEQITPROD) AND
                            (CDIMPOSTO    = C_ITEMPROIMPOS.CDIMPOSTO)   AND
                            (NRITPROIMPOS = C_ITEMPROIMPOS.NRITPROIMPOS);
                  END IF;
                  /* ROTINA PARA RECALCULAR O DIFERIMENTO DO IMPOSTO */
                  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
                            (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 + ((ROUND(V_PRODUENCARGO, 2) * 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);
                  END IF;
               END IF;
            END LOOP;
         END IF;
      END LOOP;
      /* ROTINA PARA REALIZAR RATEIO DOS ENCARGOS PARAMETRIZADOS POR PESO LIQUIDO DOS PRODUTOS*/
      IF NOT (V_ENCARGOLIQUIDO = 'N') THEN
         FOR C_ITEMENCARGO IN (SELECT IE.CDENCARGO AS CDENCARGO, VRITEMENCA, IDENCARGO,
                                      EN.CDCTBLENTREN, EN.CDCTBLSAIDEN
                                 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
                                      ((V_ENCARGOLIQUIDO = 'T') OR (INSTR(V_ENCARGOLIQUIDO, IE.CDENCARGO) > 0 )) AND
                                 (NOT EXISTS (SELECT CDENCARGOIMPXML
                                                FROM IMPOSTO
                                               WHERE IMPOSTO.CDENCARGOIMPXML = IE.CDENCARGO) OR (NVL(V_IDNFORIGVIAXML, 'N') = 'N')
                                 )
                              ) LOOP
            V_TOTAPRODENCA := 0;
            FOR C_VRLIQRATEIO IN (SELECT DISTINCT(IP.NRSEQITPROD) AS NRSEQITPROD, (VRTOTAITEM - VRDESCITEM) AS VRLIQUIDOPROD,
                                         (PR.VRPESOLIQUPR * IP.QTITEMPROD) AS VRLIQUIDO
                                    FROM ITEMPRODUTO IP, ITEMPROIMPOS II, PRODUTO PR
                                   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
                                         (IP.CDPRODUTO   = PR.CDPRODUTO)   AND
                                         (NVL(PR.VRPESOLIQUPR, 0) > 0)     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_IDCONTCONFORIG = 'N') THEN
                  SELECT SUM(QTITEMPROD * VRPESOLIQUPR)
                    INTO V_TOTAPRODENCA
                    FROM ITEMPRODUTO IP, PRODUTO PR
                   WHERE (IP.CDFILIAL   = P_FILIAL)
                     AND (IP.NRLANCTONF = P_LANCTONF)
                     AND (IP.CDPRODUTO    = PR.CDPRODUTO)
                     AND (NVL(PR.VRPESOLIQUPR, 0) > 0);
                  IF NOT V_TOTAPRODENCA IS NULL THEN
                     FOR C_ATUAVRCONT IN (SELECT IP.NRSEQITPROD, (VRTOTAITEM - VRDESCITEM) AS VRLIQUIDO,
                                                 (PR.VRPESOLIQUPR * IP.QTITEMPROD) AS PESOTOTALPROD
                                            FROM ITEMPRODUTO IP, PRODUTO PR
                                           WHERE (IP.CDFILIAL    = P_FILIAL)
                                             AND (IP.NRLANCTONF  = P_LANCTONF)
                                             AND (IP.CDPRODUTO    = PR.CDPRODUTO)
                                             AND (NVL(PR.VRPESOLIQUPR, 0) > 0)) 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.CDCTBLSAIDEN IS NULL) THEN
                           V_VRCONTAB := V_VRBRUTO;
                        ELSE
                           V_VRCONTAB := 0;
                        END IF;
                        IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (NVL(V_IDORIGDESTNF, 'C') <> 'L') THEN
                           UPDATE ITEMPRODUTO
                           SET VRBRUTITEM = TRUNC(VRBRUTITEM + (V_VRBRUTO  * C_ATUAVRCONT.PESOTOTALPROD),2),
                               VRCONTITEM = TRUNC(VRCONTITEM + (V_VRCONTAB * C_ATUAVRCONT.PESOTOTALPROD),2)
                           WHERE CDFILIAL    = P_FILIAL   AND
                                 NRLANCTONF  = P_LANCTONF AND
                                 NRSEQITPROD = C_ATUAVRCONT.NRSEQITPROD;
                        ELSE
                           UPDATE ITEMPRODUTO
                           SET VRBRUTITEM = ROUND(VRBRUTITEM + (V_VRBRUTO  * C_ATUAVRCONT.PESOTOTALPROD),5),
                               VRCONTITEM = ROUND(VRCONTITEM + (V_VRCONTAB * C_ATUAVRCONT.PESOTOTALPROD),5)
                           WHERE CDFILIAL    = P_FILIAL   AND
                                 NRLANCTONF  = P_LANCTONF AND
                                 NRSEQITPROD = C_ATUAVRCONT.NRSEQITPROD;
                        END IF;
                     END LOOP;
                  END IF;
               END IF;
            ELSE
               IF (V_IDCONTCONFORIG = 'N') THEN
                  FOR C_ATUAVRCONT IN (SELECT DISTINCT(IP.NRSEQITPROD) AS NRSEQITPROD, (VRTOTAITEM - VRDESCITEM) AS VRLIQUIDO,
                                                      (PR.VRPESOLIQUPR * IP.QTITEMPROD) AS PESOTOTALPROD
                                       FROM ITEMPRODUTO IP, ITEMPROIMPOS II, PRODUTO PR
                                       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
                                             (IP.CDPRODUTO   = PR.CDPRODUTO)   AND
                                             (NVL(PR.VRPESOLIQUPR, 0) > 0)     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.CDCTBLSAIDEN IS NULL) THEN
                        V_VRCONTAB := V_VRBRUTO;
                     ELSE
                        V_VRCONTAB := 0;
                     END IF;
                     IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (NVL(V_IDORIGDESTNF, 'C') <> 'L') THEN
                        UPDATE ITEMPRODUTO
                        SET VRBRUTITEM = TRUNC(VRBRUTITEM + (V_VRBRUTO  * C_ATUAVRCONT.PESOTOTALPROD),2),
                            VRCONTITEM = TRUNC(VRCONTITEM + (V_VRCONTAB * C_ATUAVRCONT.PESOTOTALPROD),2)
                        WHERE CDFILIAL    = P_FILIAL   AND
                              NRLANCTONF  = P_LANCTONF AND
                              NRSEQITPROD = C_ATUAVRCONT.NRSEQITPROD;
                     ELSE
                        UPDATE ITEMPRODUTO
                        SET VRBRUTITEM = ROUND(VRBRUTITEM + (V_VRBRUTO  * C_ATUAVRCONT.PESOTOTALPROD),5),
                            VRCONTITEM = ROUND(VRCONTITEM + (V_VRCONTAB * C_ATUAVRCONT.PESOTOTALPROD),5)
                        WHERE CDFILIAL    = P_FILIAL   AND
                              NRLANCTONF  = P_LANCTONF AND
                              NRSEQITPROD = C_ATUAVRCONT.NRSEQITPROD;
                     END IF;
                  END LOOP;
               END IF;
               FOR C_ITEMPROIMPOS IN (SELECT II.NRSEQITPROD,
                                             II.NRITPROIMPOS,
                                             II.CDIMPOSTO,
                                             II.VRPERREDBCIT,
                                             II.VRALIQITEM,
                                             II.VRPARDEDIT,
                                             II.IDTRIMPSTII,
                                             (VRTOTAITEM - VRDESCITEM) AS VRLIQUIDO,
                                             NVL(II.IDVALORINFIT, W_N) AS IDVALORINFIT,
                                             NVL(II.VRALIQINTEDEST, 0) AS VRALIQINTEDEST,
                                             NVL(II.VRALIQFCP, 0) AS VRALIQFCP,
                                             NVL(IP.IDUTILBCPMC, 'N') AS IDUTILBCPMC,
                                             I.CDIMPOSTONFE,
                                             II.VRPERREDBCSTIT,
                                             (PR.VRPESOLIQUPR * IP.QTITEMPROD) AS PESOTOTALPROD
                                        FROM ITEMPROIMPOS II, ITEMPRODUTO IP, BASECALC BC, IMPOSTO I, PRODUTO PR
                                       WHERE (II.CDFILIAL = P_FILIAL)
                                         AND (II.NRLANCTONF = P_LANCTONF)
                                         AND (IP.CDFILIAL = P_FILIAL)
                                         AND (IP.NRLANCTONF = P_LANCTONF)
                                         AND (IP.NRSEQITPROD = II.NRSEQITPROD)
                                         AND (PR.CDPRODUTO    = IP.CDPRODUTO)            
                                         AND (NVL(PR.VRPESOLIQUPR, 0) > 0)
                                         AND (BC.CDIMPOSTO = II.CDIMPOSTO)
                                         AND (II.CDIMPOSTO = I.CDIMPOSTO)
                                         AND (BC.CDENCARGO = C_ITEMENCARGO.CDENCARGO)
                                       ORDER BY II.NRSEQITPROD,
                                             II.NRITPROIMPOS,
                                             II.CDIMPOSTO) LOOP
                  /*IMPOSTOS QUE NAO FORAM GRAVADOS DE ACORDO COM A ORIGEM NAO DEVEM EFETUAR O CALCULO*/
                  IF C_ITEMPROIMPOS.IDVALORINFIT <> W_S THEN
                     IF NOT((C_ITEMPROIMPOS.IDUTILBCPMC = W_S) AND (C_ITEMPROIMPOS.CDIMPOSTONFE = '80')) OR (C_ITEMPROIMPOS.IDUTILBCPMC <> W_S) THEN
                        SELECT SUM(QTITEMPROD * VRPESOLIQUPR)
                          INTO V_TOTAPRENIMPO
                          FROM ITEMPRODUTO IP, PRODUTO PR
                         WHERE IP.CDFILIAL   = P_FILIAL
                           AND IP.NRLANCTONF = P_LANCTONF
                           AND IP.CDPRODUTO  = PR.CDPRODUTO
                           AND (NVL(PR.VRPESOLIQUPR, 0) > 0);
                        IF (V_TOTAPRODENCA <> 0) THEN
                           IF (C_ITEMENCARGO.IDENCARGO = w_A) THEN
                              V_PRODUENCARGO := + (C_ITEMENCARGO.VRITEMENCA/V_TOTAPRENIMPO)*C_ITEMPROIMPOS.PESOTOTALPROD;
                           ELSIF (C_ITEMENCARGO.IDENCARGO = w_D) THEN
                              V_PRODUENCARGO := - (C_ITEMENCARGO.VRITEMENCA/V_TOTAPRENIMPO)*C_ITEMPROIMPOS.PESOTOTALPROD;
                           ELSE
                              V_PRODUENCARGO := 0;
                           END IF;
                        END IF;
                        V_IDVRIMPSTRIB := NULL;
                        BEGIN
                           SELECT CASE COUNT(*) WHEN 0 THEN 'M' ELSE 'R' END
                             INTO V_MAJORAOUREDUZ
                             FROM ITEMPROIMPOS
                            WHERE CDFILIAL = P_FILIAL
                              AND NRLANCTONF = P_LANCTONF
                              AND NRSEQITPROD = C_ITEMPROIMPOS.NRSEQITPROD
                              AND CDIMPOSTO = C_ITEMPROIMPOS.CDIMPOSTO
                              AND NRITPROIMPOS = w_2;
                        EXCEPTION
                           WHEN NO_DATA_FOUND THEN
                              V_MAJORAOUREDUZ := 'M';
                        END;
                        V_VRIMPOSTOST := 0;
                        IF V_MAJORAOUREDUZ = 'R' THEN
                           V_TAXABASECALC := (100 - C_ITEMPROIMPOS.VRPERREDBCIT)/100;
                           V_TAXAALIQUOTA := (C_ITEMPROIMPOS.VRALIQITEM/100);
                        ELSE
                           V_TAXABASECALC :=(100 - NVL(C_ITEMPROIMPOS.VRPERREDBCSTIT, 0))/100; /*Alterado por Lucas Lindo*/
                           V_PRODUENCARGO :=  (V_PRODUENCARGO * V_TAXABASECALC); /*Calcular o valor do encargo retirando reducao da base para no update abaixo utilize o valor adicionando a majoracao*/
                           V_TAXABASECALC := 1 + (C_ITEMPROIMPOS.VRPERREDBCIT)/100;
                           V_TAXAALIQUOTA := (C_ITEMPROIMPOS.VRALIQITEM/100);
                           SELECT NVL(MAX(IDVRIMPSTRIB), 'N')
                             INTO V_IDVRIMPSTRIB
                             FROM ITEMPROIMPOS I, IMPOSTO II
                            WHERE (CDFILIAL     = P_FILIAL)
                              AND (NRLANCTONF   = P_LANCTONF)
                              AND (NRSEQITPROD  = C_ITEMPROIMPOS.NRSEQITPROD)
                              AND (INSTR(V_CDIMPOSTRIB,II.CDIMPOSTO||'_') > 0)
                              AND (I.CDIMPOSTO = II.CDIMPOSTO);
                           IF (C_ITEMPROIMPOS.IDTRIMPSTII <> w_1) AND (NVL(V_IDVRIMPSTRIB,w_N) = w_S) THEN
                              Begin
                                 SELECT NVL(MAX(VRIMPOSTOIT),0)
                                 INTO   V_VRIMPOSTOST
                                 FROM ITEMPROIMPOS I
                                 WHERE (CDFILIAL     = P_FILIAL)                    AND
                                       (NRLANCTONF   = P_LANCTONF)                  AND
                                       (INSTR(V_CDIMPOSTRIB,CDIMPOSTO||'_') > 0)    AND
                                       (NRITPROIMPOS = C_ITEMPROIMPOS.NRITPROIMPOS) AND
                                       (NRSEQITPROD  = C_ITEMPROIMPOS.NRSEQITPROD);
                              Exception
                                 When No_Data_Found Then
                                    V_VRIMPOSTOST := 0;
                              End;
                           END IF;
                        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_ITEMPROIMPOS.CDIMPOSTO)
                        LOOP
                           V_ICMS := 'S';
                        END LOOP;
                        UPDATE ITEMPROIMPOS
                           SET VRCONTITIMP  = VRCONTITIMP  + (V_PRODUENCARGO * V_TAXABASECALC),
                               VRBASECALCIT = VRBASECALCIT + ((V_PRODUENCARGO * V_TAXABASECALC) / (1 - ((C_ITEMPROIMPOS.VRALIQINTEDEST + C_ITEMPROIMPOS.VRALIQFCP) / 100))),
                               VRIMPOSTOIT  = (VRIMPOSTOIT  + (((V_PRODUENCARGO * V_TAXABASECALC) / (1 - ((C_ITEMPROIMPOS.VRALIQINTEDEST + C_ITEMPROIMPOS.VRALIQFCP) / 100))) * V_TAXAALIQUOTA)) - (((V_VRIMPOSTOST * V_TAXABASECALC) / (1 - ((C_ITEMPROIMPOS.VRALIQINTEDEST + C_ITEMPROIMPOS.VRALIQFCP) / 100))) * V_TAXAALIQUOTA),
                               VRIMPOSTOVISUIT = DECODE(V_IDPERVISIMPSCRE, 'S', (VRIMPOSTOIT  + ((V_PRODUENCARGO * V_TAXABASECALC) * V_TAXAALIQUOTA)) - ((V_VRIMPOSTOST * V_TAXABASECALC) * V_TAXAALIQUOTA),  DECODE(CDFISCALIT , '1', (VRIMPOSTOIT  + ((V_PRODUENCARGO * V_TAXABASECALC) * V_TAXAALIQUOTA)) - ((V_VRIMPOSTOST * V_TAXABASECALC) * V_TAXAALIQUOTA),0)),
                               VRADICFECP  = VRADICFECP  + ROUND((V_PRODUENCARGO * (VRADICALIQFECP / 100) * V_TAXABASECALC),2)
                         WHERE (CDFILIAL     = P_FILIAL)                   AND
                               (NRLANCTONF   = P_LANCTONF)                 AND
                               (NRSEQITPROD  = C_ITEMPROIMPOS.NRSEQITPROD) AND
                               (CDIMPOSTO    = C_ITEMPROIMPOS.CDIMPOSTO)   AND
                               (NRITPROIMPOS = C_ITEMPROIMPOS.NRITPROIMPOS);
                     END IF;
                     /* ROTINA PARA RECALCULAR O DIFERIMENTO DO IMPOSTO */
