                     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;
      END IF;

      /* IMPOSTO GERADO COMO ENCARGO NA ENTRADA */

      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,
                               NVL(II.IDVALORINFIT, W_N) AS IDVALORINFIT,
                               IP.IDUTILBCPMC,
                               IM.CDIMPOSTONFE
                          FROM ITEMPRODUTO IP, ITEMPROIMPOS II, IMPOSTO IM
                         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 (IP.IDUTILBCPMC <> 'S')
                           AND (II.NRSEQITPROD = IP.NRSEQITPROD)
                         ORDER BY NRSEQITPROD, 
                               CDIMPOSTO) LOOP

         IF (C_PRODUTO.IDVALORINFIT <> W_S) THEN
            IF NOT((C_PRODUTO.IDUTILBCPMC = W_S) AND (C_PRODUTO.CDIMPOSTONFE = '80')) OR (C_PRODUTO.IDUTILBCPMC <> W_S) THEN
               V_IDIMPOBCALTPOP := NULL;
   
               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);
   
                     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))
                      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 */
                     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((V_VRIMPOSTOOPERAIT + ((ROUND((V_TOTAIMPBCALC+V_TOTAIMPBCDES), 2) * 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_PRODUTO.NRSEQITPROD)  AND
                               (CDIMPOSTO    = C_PRODUTO.CDIMPOSTO)    AND
                               (NRITPROIMPOS = C_PRODUTO.NRITPROIMPOS) AND
                               (VRPERDIFEREIT <> 0);
                     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;
   
                     V_TAXABASECALC := 1 + (C_PRODUTO.VRPERREDBCIT)/100;
                     V_TAXAALIQUOTA := (C_PRODUTO.VRALIQITEM/100);
                     V_VRIMPOSTO := ((C_PRODUTO.VRBASECALCIT+ ((V_TOTAIMPBCALC+V_TOTAIMPBCDES) * V_TAXABASECALC)) * V_TAXAALIQUOTA);
   
                     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
                        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))
                         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 := V_VRIMPOSTO - V_VRIMPOSTOST;
   
                        IF (V_IDCONTCONFORIG = 'N') THEN
                           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;
                  END IF;
               END IF;
            END IF;
         END IF;
      END LOOP;

      IF V_IDOPERDEVONF = w_S THEN
         V_SEQUIMPOSTNF := w_01;

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

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

         --TOTALIZACAO DOS IMPOSTOS
         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;

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

         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;

            /*IMPOSTOS DE CORPO DA NOTA DE ORIGEM*/
            FOR C_IMPOSNFTOT IN (SELECT IT.CDIMPOSTO, IT.VRTOTIMPONF, IT.VRTOTBCALCNF
                                 FROM IMPOSNFTOT IT, IMPOSTO IP
                                 WHERE IT.CDFILIAL   = C_ITEMNOTAFISC.CDFILIALIT   AND
                                       IT.NRLANCTONF = C_ITEMNOTAFISC.NRLANCTONFIT AND
                                       IT.CDIMPOSTO  = IP.CDIMPOSTO AND
                                       IP.IDPRODNOTA = w_C) LOOP

               SELECT NVL(MAX(IDUTMUNIORIG),'N')
                 INTO V_IDUTMUNIORIG
                 FROM IMPOSTO
                WHERE CDIMPOSTO = C_IMPOSNFTOT.CDIMPOSTO;

               IF ((V_IDUTMUNIORIG = 'O') OR (V_IDUTMUNIORIG = 'N')) THEN
                  CONSULTA_ALIQUOTA(C_IMPOSNFTOT.CDIMPOSTO, 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);
               ELSE
                  CONSULTA_ALIQUOTA(C_IMPOSNFTOT.CDIMPOSTO, 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);
               END IF;

               SELECT MAX(NRALIQTEMP), MAX(VRPARDEDTMP), MAX(VRPREDBCTMP), MAX(VRALIQUTMP), NVL(MAX(IDTRIMPSTTMP), w_0), MAX(CDTIPOOPERTMP)
                 INTO   V_NRALIQTEMP,    V_PARDEDTMP,      V_PREDBCTMP,      V_ALIQUTMP,      V_TRATIMPST, V_CDTIPOOPER
                 FROM ALIQTEMP
                WHERE (NRALIQTEMP = V_ALIQTEMP);

               IF ((V_NRALIQTEMP IS NOT NULL) AND (V_CDTIPOOPER IS NOT NULL) AND (V_ESTORNOCANC <> w_S)) THEN
                  IF (V_ALIQUTMP IS NULL) THEN
                     V_ALIQUTMP := 0;
                  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_IMPOSNFTOT.CDIMPOSTO)
                     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_IMPOSNFTOT.CDIMPOSTO)
                     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
                     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_BASECALCIT   := (V_LIQUIDO + V_PRODUENCARGO) * V_TAXABASECALC;

                  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_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)
                                       VALUES (P_FILIAL, P_LANCTONF, C_IMPOSNFTOT.CDIMPOSTO, TRUNC(V_IMPOSTOIT ,V_NRDECITOTANF), TRUNC(V_BASECALCIT,V_NRDECITOTANF));
                  ELSE
                     INSERT INTO IMPOSNFTOT(CDFILIAL, NRLANCTONF, CDIMPOSTO, VRTOTIMPONF, VRTOTBCALCNF)
                                       VALUES (P_FILIAL, P_LANCTONF, C_IMPOSNFTOT.CDIMPOSTO, ROUND(V_IMPOSTOIT ,V_NRDECITOTANF), ROUND(V_BASECALCIT,V_NRDECITOTANF));
                  END IF;

               ELSE
                  V_IMPOSTOIT  := (C_IMPOSNFTOT.VRTOTIMPONF * V_VRFATOCONV);
                  V_BASECALCIT := (C_IMPOSNFTOT.VRTOTBCALCNF * V_VRFATOCONV);
                  V_ALIQUTMP   := NULL;
                  V_UTIBB      := '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
                  /*IF C_IMPOSNFTOT.CDIMPOSTO = '03' THEN
                     IF V_IDORIGDESTNF = 'C' THEN

                        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_UTIBB := 'S';
                        END IF;
                     END IF;
                  END IF;

                  IF V_UTIBB = 'S' THEN
                     INSERT INTO IMPOSNFTOT(CDFILIAL, NRLANCTONF, CDIMPOSTO, VRTOTIMPONF, VRTOTBCALCNF)
                                    VALUES (P_FILIAL, P_LANCTONF, C_IMPOSNFTOT.CDIMPOSTO, ROUND((V_LIQUIDO * (V_ALIQUTMP/100))  ,V_NRDECITOTANF), ROUND(V_LIQUIDO,V_NRDECITOTANF));
                  ELSE*/
                     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)
                                       VALUES (P_FILIAL, P_LANCTONF, C_IMPOSNFTOT.CDIMPOSTO, TRUNC(V_IMPOSTOIT ,V_NRDECITOTANF), TRUNC(V_BASECALCIT,V_NRDECITOTANF));
                     ELSE
                        INSERT INTO IMPOSNFTOT(CDFILIAL, NRLANCTONF, CDIMPOSTO, VRTOTIMPONF, VRTOTBCALCNF)
                                       VALUES (P_FILIAL, P_LANCTONF, C_IMPOSNFTOT.CDIMPOSTO, ROUND(V_IMPOSTOIT ,V_NRDECITOTANF), ROUND(V_BASECALCIT,V_NRDECITOTANF));
                     END IF;

                  --END IF;
               END IF;
               DELETE ALIQTEMP
               WHERE NRALIQTEMP = V_ALIQTEMP;
            END LOOP;

            FOR C_IMPOSTONF IN (SELECT IT.CDIMPOSTO, IT.NRIMPOSNF, IT.VRCONTABILNF, IT.VRPERREDBCNF, IT.VRBASECALCNF,
                                       IT.VRALIQNF, IT.VRPARDEDNF, IT.VRIMPOSTONF, IT.CDFISCALNF, IT.CDSITUTRIBNF,
                                       IT.CDFISCOPERNF, IT.CDSUFXCFOPNF, IDTRIMPOSTNF, IT.CDSITUTRIBIMNFE, IP.IDIMPORECUP,
									                     IT.CDTPCREDPICONF, IT.CDNATUBCALPCNF, IT.IDMOTDESONERANF
                                FROM IMPOSTONF IT, IMPOSTO IP
                                WHERE IT.CDFILIAL   = C_ITEMNOTAFISC.CDFILIALIT   AND
                                      IT.NRLANCTONF = C_ITEMNOTAFISC.NRLANCTONFIT AND
                                      IT.CDIMPOSTO  = IP.CDIMPOSTO                AND
                                      IP.IDPRODNOTA = w_C) LOOP
               /*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_IMPOSTONF.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_IMPOSTONF.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_IMPOSTONF.CDIMPOSTO;
               END IF;

               IF V_CDGRUPOFISCAUX IS NULL THEN
                  CONSULTA_CST_NFE(w_S, P_EMPRESA, '', P_INSCESTA, P_TIPOOPER, V_CDGRUPOFISC,C_IMPOSTONF.CDIMPOSTO, 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_IMPOSTONF.CDIMPOSTO, V_IDINTEREST, V_IDINTERNA, P_FILIAL, P_LANCTONF, '', V_CDSITTRIBTMP, V_IDMODBCNFE, V_IDMODBCSTNFE, V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, V_IDMOTIDESSTNFE);
               END IF;

               IF (C_IMPOSTONF.CDSITUTRIBIMNFE IS NULL) THEN
                  V_CDSITUTRIBNFE := V_CDSITTRIBTMP;
               ELSE
                  V_CDSITUTRIBNFE := C_IMPOSTONF.CDSITUTRIBIMNFE;
               END IF;

               IF (C_IMPOSTONF.CDTPCREDPICONF IS NULL) THEN
                  V_CDTPCRPICOSTNFEIT := V_CDTPCRPICOSTNFE;
               ELSE
                  V_CDTPCRPICOSTNFEIT := C_IMPOSTONF.CDTPCREDPICONF;
               END IF;

               IF (C_IMPOSTONF.CDNATUBCALPCNF IS NULL) THEN
                  V_CDNATUBCPCSTNFEIT := V_CDNATUBCPCSTNFE;
               ELSE
                  V_CDNATUBCPCSTNFEIT := C_IMPOSTONF.CDNATUBCALPCNF;
               END IF;

               IF (C_IMPOSTONF.IDMOTDESONERANF IS NULL) THEN
                  V_IDMOTIDESSTNFE := V_IDMOTIDESSTNFE;
               ELSE
                  V_IDMOTIDESSTNFE := C_IMPOSTONF.IDMOTDESONERANF;
               END IF;


               SELECT NVL(MAX(IDUTMUNIORIG),'N')
                 INTO V_IDUTMUNIORIG
                 FROM IMPOSTO
                WHERE CDIMPOSTO = C_IMPOSTONF.CDIMPOSTO;

               IF ((V_IDUTMUNIORIG = 'O') OR (V_IDUTMUNIORIG = 'N')) THEN
                  CONSULTA_ALIQUOTA(C_IMPOSTONF.CDIMPOSTO, 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);
               ELSE
                  CONSULTA_ALIQUOTA(C_IMPOSTONF.CDIMPOSTO, 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);
               END IF;

               SELECT MAX(NRALIQTEMP), MAX(VRPARDEDTMP), MAX(VRPREDBCTMP), MAX(VRALIQUTMP), NVL(MAX(IDTRIMPSTTMP), w_0), MAX(CDTIPOOPERTMP)
                 INTO   V_NRALIQTEMP,    V_PARDEDTMP,      V_PREDBCTMP,      V_ALIQUTMP,      V_TRATIMPST, V_CDTIPOOPER
                 FROM ALIQTEMP
                WHERE (NRALIQTEMP = V_ALIQTEMP);

               IF ((V_NRALIQTEMP IS NOT NULL) AND (V_CDTIPOOPER IS NOT NULL)) THEN
                  IF (V_ALIQUTMP IS NULL) THEN
                     V_ALIQUTMP := 0;
                  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_IMPOSTONF.CDIMPOSTO)
                     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_IMPOSTONF.CDIMPOSTO)
                     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
                     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_BASECALCIT   := (V_LIQUIDO + V_PRODUENCARGO) * V_TAXABASECALC;

                  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;

                  IF (C_IMPOSTONF.IDIMPORECUP = w_S) OR (C_IMPOSTONF.IDIMPORECUP <> w_S AND V_ALIQUTMP <> 0) THEN
                     IF ((C_IMPOSTONF.IDIMPORECUP = w_S) AND (C_IMPOSTONF.CDFISCALNF <> 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_IMPOSTONF.CDIMPOSTO)
                     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_IMPOSTONF.CDIMPOSTO, C_IMPOSTONF.NRIMPOSNF, TRUNC(V_CONTIMPO,2), V_PREDBCTMP,
                           TRUNC(V_BASECALCIT,2), V_ALIQUTMP, TRUNC(V_PARDEDTMP,2), TRUNC(V_IMPOSTOIT,2), C_IMPOSTONF.CDSUFXCFOPNF, C_IMPOSTONF.IDTRIMPOSTNF, V_CDSITTRIBTMP, V_CDTPCRPICOSTNFEIT, V_CDNATUBCPCSTNFEIT, 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_IMPOSTONF.CDIMPOSTO, C_IMPOSTONF.NRIMPOSNF, ROUND(V_CONTIMPO,2), V_PREDBCTMP,
                           V_BASECALCIT, V_ALIQUTMP, V_PARDEDTMP, V_IMPOSTOIT, C_IMPOSTONF.CDSUFXCFOPNF, C_IMPOSTONF.IDTRIMPOSTNF, V_CDSITTRIBTMP, V_CDTPCRPICOSTNFEIT, V_CDNATUBCPCSTNFEIT, V_IDMOTIDESSTNFE);
                     END IF;

                     IF ((C_IMPOSTONF.IDIMPORECUP = w_S) AND (V_PREDBCTMP > 0) AND (C_IMPOSTONF.CDFISCALNF = 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_IMPOSTONF.CDIMPOSTO, C_IMPOSTONF.NRIMPOSNF, V_CONTABCALC, V_PERDBCALC,
                           0, 0, V_PARDEDTMP, 0, w_2, V_CDSITTRIBTMP, V_CDTPCRPICOSTNFEIT, V_CDNATUBCPCSTNFEIT, V_IDMOTIDESSTNFE);
                     END IF;
                  END IF;

                  DELETE ALIQTEMP
                  WHERE NRALIQTEMP = V_ALIQTEMP;
               ELSE
                  V_ALIQUTMP   := NULL;
                  V_UTIBB      := '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
                  /*IF C_IMPOSTONF.CDIMPOSTO = '03' THEN
                     IF V_IDORIGDESTNF = 'C' THEN
                        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_UTIBB := 'S';
                        END IF;
                     END IF;
                  END IF;*/

                  IF V_UTIBB = 'S' 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_IMPOSTONF.CDIMPOSTO)
                     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, CDSITUTRIBNF, CDFISCOPERNF, CDSUFXCFOPNF, IDTRIMPOSTNF, CDSITUTRIBIMNFE, CDTPCREDPICONF, CDNATUBCALPCNF, IDMOTDESONERANF)
                        VALUES(P_FILIAL, P_LANCTONF, C_IMPOSTONF.CDIMPOSTO, C_IMPOSTONF.NRIMPOSNF,
                               V_LIQUIDO, 0, V_LIQUIDO,
                               V_ALIQUTMP, 0, TRUNC((V_LIQUIDO * (V_ALIQUTMP/100)),2), C_IMPOSTONF.CDFISCALNF,
                               C_IMPOSTONF.CDSITUTRIBNF, C_IMPOSTONF.CDFISCOPERNF, C_IMPOSTONF.CDSUFXCFOPNF, C_IMPOSTONF.IDTRIMPOSTNF, C_IMPOSTONF.CDSITUTRIBIMNFE, V_CDTPCRPICOSTNFEIT, V_CDNATUBCPCSTNFEIT, V_IDMOTIDESSTNFE);
                     ELSE
                        INSERT INTO IMPOSTONF(
                           CDFILIAL, NRLANCTONF, CDIMPOSTO, NRIMPOSNF, VRCONTABILNF, VRPERREDBCNF, VRBASECALCNF,
                           VRALIQNF, VRPARDEDNF, VRIMPOSTONF, CDFISCALNF, CDSITUTRIBNF, CDFISCOPERNF, CDSUFXCFOPNF, IDTRIMPOSTNF, CDSITUTRIBIMNFE, CDTPCREDPICONF, CDNATUBCALPCNF, IDMOTDESONERANF)
                        VALUES(P_FILIAL, P_LANCTONF, C_IMPOSTONF.CDIMPOSTO, C_IMPOSTONF.NRIMPOSNF,
                               V_LIQUIDO, 0, V_LIQUIDO,
                               V_ALIQUTMP, 0, (V_LIQUIDO * (V_ALIQUTMP/100)), C_IMPOSTONF.CDFISCALNF,
                               C_IMPOSTONF.CDSITUTRIBNF, C_IMPOSTONF.CDFISCOPERNF, C_IMPOSTONF.CDSUFXCFOPNF, C_IMPOSTONF.IDTRIMPOSTNF, C_IMPOSTONF.CDSITUTRIBIMNFE, V_CDTPCRPICOSTNFEIT, V_CDNATUBCPCSTNFEIT, V_IDMOTIDESSTNFE);
                     END IF;
                  ELSE
                     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_IMPOSTONF.CDIMPOSTO)
                     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, CDSITUTRIBNF, CDFISCOPERNF, CDSUFXCFOPNF, IDTRIMPOSTNF, CDSITUTRIBIMNFE, CDTPCREDPICONF, CDNATUBCALPCNF, IDMOTDESONERANF)
                        VALUES(P_FILIAL, P_LANCTONF, C_IMPOSTONF.CDIMPOSTO, C_IMPOSTONF.NRIMPOSNF,
                               TRUNC((C_IMPOSTONF.VRCONTABILNF * V_VRFATOCONV),2), C_IMPOSTONF.VRPERREDBCNF, TRUNC((C_IMPOSTONF.VRBASECALCNF * V_VRFATOCONV),2),
                               C_IMPOSTONF.VRALIQNF, TRUNC((C_IMPOSTONF.VRPARDEDNF * V_VRFATOCONV),2), TRUNC((C_IMPOSTONF.VRIMPOSTONF * V_VRFATOCONV),2), C_IMPOSTONF.CDFISCALNF,
                               C_IMPOSTONF.CDSITUTRIBNF, C_IMPOSTONF.CDFISCOPERNF, C_IMPOSTONF.CDSUFXCFOPNF, C_IMPOSTONF.IDTRIMPOSTNF, C_IMPOSTONF.CDSITUTRIBIMNFE, V_CDTPCRPICOSTNFEIT, V_CDNATUBCPCSTNFEIT, V_IDMOTIDESSTNFE);
                     ELSE
                        INSERT INTO IMPOSTONF(
                           CDFILIAL, NRLANCTONF, CDIMPOSTO, NRIMPOSNF, VRCONTABILNF, VRPERREDBCNF, VRBASECALCNF,
                           VRALIQNF, VRPARDEDNF, VRIMPOSTONF, CDFISCALNF, CDSITUTRIBNF, CDFISCOPERNF, CDSUFXCFOPNF, IDTRIMPOSTNF, CDSITUTRIBIMNFE, CDTPCREDPICONF, CDNATUBCALPCNF, IDMOTDESONERANF)
                        VALUES(P_FILIAL, P_LANCTONF, C_IMPOSTONF.CDIMPOSTO, C_IMPOSTONF.NRIMPOSNF,
                               ROUND((C_IMPOSTONF.VRCONTABILNF * V_VRFATOCONV),2), C_IMPOSTONF.VRPERREDBCNF, (C_IMPOSTONF.VRBASECALCNF * V_VRFATOCONV),
                               C_IMPOSTONF.VRALIQNF, (C_IMPOSTONF.VRPARDEDNF * V_VRFATOCONV), (C_IMPOSTONF.VRIMPOSTONF * V_VRFATOCONV), C_IMPOSTONF.CDFISCALNF,
                               C_IMPOSTONF.CDSITUTRIBNF, C_IMPOSTONF.CDFISCOPERNF, C_IMPOSTONF.CDSUFXCFOPNF, C_IMPOSTONF.IDTRIMPOSTNF, C_IMPOSTONF.CDSITUTRIBIMNFE,  V_CDTPCRPICOSTNFEIT, V_CDNATUBCPCSTNFEIT, V_IDMOTIDESSTNFE);
                     END IF;

                  END IF;
                   V_SEQUIMPOSTNF := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_SEQUIMPOSTNF) + 1)),2,0);
               END IF;
               DELETE ALIQTEMP
               WHERE NRALIQTEMP = V_ALIQTEMP;
            END LOOP;
         END LOOP;

         DELETE FROM DADOSADIC
         WHERE CDFILIAL = P_FILIAL
           AND NRLANCTONF = P_LANCTONF
           AND DSDADOADIC LIKE 'Nota de Origem:%';

         IF (V_IDCONTCONFORIG = 'N') THEN
            DELETE ITEMPROIMPOSORIG
             WHERE CDFILIAL   = P_FILIAL
               AND NRLANCTONF = P_LANCTONF;

            FOR C_IMPOSTOITENS IN (SELECT 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
                                     FROM ITEMPROIMPOS
                                    WHERE CDFILIAL   = P_FILIAL
                                      AND NRLANCTONF = P_LANCTONF) LOOP

               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 (C_IMPOSTOITENS.CDFILIAL,      C_IMPOSTOITENS.NRLANCTONF,     C_IMPOSTOITENS.NRSEQITPROD,     C_IMPOSTOITENS.CDIMPOSTO,      C_IMPOSTOITENS.NRITPROIMPOS,    C_IMPOSTOITENS.CDFISCALIT,
                            C_IMPOSTOITENS.CDSITUTRIBIT,  C_IMPOSTOITENS.CDFISCOPERIT,   C_IMPOSTOITENS.CDSUFXCFOPIT,    C_IMPOSTOITENS.VRALIQITEM,     C_IMPOSTOITENS.VRPERREDBCIT,    C_IMPOSTOITENS.VRPARDEDIT,
                            C_IMPOSTOITENS.VRCONTITIMP,   C_IMPOSTOITENS.VRBASECALCIT,   C_IMPOSTOITENS.VRIMPOSTOIT,     C_IMPOSTOITENS.IDERROSIMPIT,   C_IMPOSTOITENS.IDAVISIMPIT,     C_IMPOSTOITENS.CDSITUTRIBITNFE,
                            C_IMPOSTOITENS.IDMODBCITNFE,  C_IMPOSTOITENS.IDMODBCSTITNFE, C_IMPOSTOITENS.CDTPCREDPICOITE, C_IMPOSTOITENS.CDNATUBCALPCIT, C_IMPOSTOITENS.IDMOTDESONERAIT, C_IMPOSTOITENS.IDTRIMPSTII,
                            C_IMPOSTOITENS.CDDETALHEPROD, C_IMPOSTOITENS.CDENQLEGALIPI,  C_IMPOSTOITENS.CDCEST,          C_IMPOSTOITENS.CDBENEFFISCAL);
            END LOOP;
         END IF;

         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);
         END LOOP;
      END IF;
   -------------------
   ELSIF (P_TIPOOPER = w_03) THEN /*NOTA DE COMPLEMENTO*/

      FOR C_IMPOSITEMCOM IN (SELECT II.NRSEQITPROD,  II.CDIMPOSTO,     II.NRITPROIMPOS,   II.VRCONTITIMP,
                                    II.VRPERREDBCIT, II.VRBASECALCIT,  II.VRALIQITEM,     II.VRPARDEDIT,
                                    II.VRIMPOSTOIT,  II.CDFISCALIT,    I.IDUTVLRQTDEIMPO, II.CDSITUTRIBIT ,
                                    II.CDFISCOPERIT, II.VRPERMAJBCIT,  IT.CDPRODUTO,      IT.QTITEMPROD, 
                                    P.CDARVPROD,     II.CDENQLEGALIPI, II.CDCEST
                               FROM ITEMPROIMPOS II, IMPOSTO I, ITEMPRODUTO IT, PRODUTO P
                              WHERE (II.CDFILIAL   = P_FILIAL)
                                AND (II.NRLANCTONF = P_LANCTONF)
                                AND (II.NRITPROIMPOS = '1')
                                AND (II.CDIMPOSTO = I.CDIMPOSTO)
                                AND (P.CDPRODUTO  = IT.CDPRODUTO)
                                AND (II.CDFILIAL = IT.CDFILIAL)
                                AND (II.NRLANCTONF = IT.NRLANCTONF)
                                AND (II.NRSEQITPROD = IT.NRSEQITPROD)
                           ORDER BY II.NRSEQITPROD, II.CDIMPOSTO, II.NRITPROIMPOS) LOOP

         /*VERIFICA CSOSN POR IMPOSTO*/
         CONSULTA_CSOSN('S', P_EMPRESA, C_IMPOSITEMCOM.CDARVPROD, P_INSCESTA, P_TIPOOPER, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC, V_IDINTEREST, V_CDFISCOPERSN);

         UPDATE ITEMPRODUTO
            SET CDFISCOPERSN  = V_CDFISCOPERSN
          WHERE CDFILIAL    = P_FILIAL
            AND NRLANCTONF  = P_LANCTONF
            AND NRSEQITPROD = C_IMPOSITEMCOM.NRSEQITPROD;

         IF (C_IMPOSITEMCOM.VRIMPOSTOIT = 0)  THEN
            IF (C_IMPOSITEMCOM.VRALIQITEM <> 0)  THEN

               V_TAXAALIQUOTA := (C_IMPOSITEMCOM.VRALIQITEM/100);
               V_TAXABASECALC := (100 - C_IMPOSITEMCOM.VRPERREDBCIT)/100;
               V_TAXABCSUBSTR := (100 + C_IMPOSITEMCOM.VRPERMAJBCIT)/100;

               SELECT MAX(VRTOTAITEM), MAX(QTITEMPROD)
                 INTO V_VRTOTAITEM, V_QTITEMPROD
                 FROM ITEMPRODUTO
                WHERE CDFILIAL = P_FILIAL
                  AND NRLANCTONF = P_LANCTONF
                  AND NRSEQITPROD = C_IMPOSITEMCOM.NRSEQITPROD;

               IF C_IMPOSITEMCOM.VRBASECALCIT > 0 THEN
                  V_BASECALCIT := C_IMPOSITEMCOM.VRBASECALCIT;
               ELSE
                  V_BASECALCIT := V_VRTOTAITEM * V_TAXABASECALC;
               END IF;

               V_PERDBCALC := 100 - C_IMPOSITEMCOM.VRPERREDBCIT;

               V_CONTABCALC  := V_VRTOTAITEM - (V_VRTOTAITEM * V_TAXABASECALC);

               /* GRAVAR VALOR CONTABIL PARA NOTA FISCAL DE COMPLEMENTO COMO O VALOR DA BASE DE CALCULO INFORMADA*/
               IF (V_VRTOTAITEM = 0) THEN
                  V_CONTABCALC := V_BASECALCIT;
               END IF;

               IF C_IMPOSITEMCOM.VRPERMAJBCIT > 0 THEN

                  SELECT MAX(CDIMPOSTO)
                    INTO V_CDIMPOSTO
                    FROM IMPOSTO
                   WHERE CDIMPOSTRIB = C_IMPOSITEMCOM.CDIMPOSTO;

                  IF (V_CDIMPOSTO IS NOT NULL) THEN
                     V_BASECALCIT := (V_BASECALCIT * V_TAXABCSUBSTR);
                  ELSE
                     UPDATE ITEMPROIMPOS
                     SET VRPERMAJBCIT = 0
                    WHERE CDFILIAL = P_FILIAL
                      AND NRLANCTONF = P_LANCTONF
                      AND NRSEQITPROD = C_IMPOSITEMCOM.NRSEQITPROD
                      AND CDIMPOSTO = C_IMPOSITEMCOM.CDIMPOSTO;
                  END IF;
               END IF;

               /* ICMS-ST para nota fiscal de complento */

               V_CDIMPOSTRIB  := null;
               V_IDVRIMPSTRIB := null;
               /*IMPOSTO DE SUBSTITUICAO TRIBUTARIA*/
               FOR C_ICMSST IN (SELECT CDIMPOSTO
                                      FROM IMPOSTO
                                     WHERE CDIMPOSTRIB = C_IMPOSITEMCOM.CDIMPOSTO)
               LOOP
                  V_CDIMPOSTRIB := V_CDIMPOSTRIB||C_ICMSST.CDIMPOSTO||'_';
               END LOOP;

               IF V_CDIMPOSTRIB IS NOT NULL THEN
                  SELECT NVL(MAX(IDVRIMPSTRIB), 'N')
                    INTO V_IDVRIMPSTRIB
                    FROM ITEMPROIMPOS I, IMPOSTO II
                   WHERE (CDFILIAL     = P_FILIAL)
                     AND (NRLANCTONF   = P_LANCTONF)
                     AND (NRSEQITPROD  = C_IMPOSITEMCOM.NRSEQITPROD)
                     AND (INSTR(V_CDIMPOSTRIB,II.CDIMPOSTO||'_') > 0)
                     AND (I.CDIMPOSTO = II.CDIMPOSTO);

                  IF (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_IMPOSITEMCOM.NRSEQITPROD) AND
                              (INSTR(V_CDIMPOSTRIB,CDIMPOSTO||'_') > 0)  AND
                              (NRITPROIMPOS = w_1);
                     Exception
                        When No_Data_Found Then
                           V_VRIMPOSTOST := 0;
                     End;
                  END IF;
               END IF;
               /* ICMS-ST para nota fiscal de complento */


               IF (C_IMPOSITEMCOM.IDUTVLRQTDEIMPO = 'S') THEN
                  SELECT NVL(MAX(VRFATOCONVES), 1)
                    INTO V_VRFATOCONVES
                    FROM CONVPRODUTO
                   WHERE CDPRODUTO = C_IMPOSITEMCOM.CDPRODUTO;

                  IF (NVL(V_IDVRIMPSTRIB,w_N) = w_N) THEN
                     V_BASECALCTO  := (V_QTITEMPROD * V_VRFATOCONVES);
                     V_IMPOSTOIT   := ((V_QTITEMPROD * V_VRFATOCONVES) * C_IMPOSITEMCOM.VRALIQITEM) - C_IMPOSITEMCOM.VRPARDEDIT;
                  ELSE
                     V_BASECALCTO  := (V_QTITEMPROD * V_VRFATOCONVES);
                     V_IMPOSTOIT   := ((V_QTITEMPROD * V_VRFATOCONVES) * C_IMPOSITEMCOM.VRALIQITEM) - C_IMPOSITEMCOM.VRPARDEDIT - V_VRIMPOSTOST;
                     IF V_IMPOSTOIT < 0 THEN
                        V_IMPOSTOIT := 0;
                     END IF;
                  END IF;
               ELSE
                  IF (NVL(V_IDVRIMPSTRIB,w_N) = w_N) THEN
                     V_BASECALCTO  := V_BASECALCIT;
                     V_IMPOSTOIT   := (V_BASECALCIT * V_TAXAALIQUOTA) - C_IMPOSITEMCOM.VRPARDEDIT;
                  ELSE
                     V_BASECALCTO  := V_BASECALCIT;
                     V_IMPOSTOIT   := (V_BASECALCIT * V_TAXAALIQUOTA) - C_IMPOSITEMCOM.VRPARDEDIT - V_VRIMPOSTOST;
                     IF V_IMPOSTOIT < 0 THEN
                        V_IMPOSTOIT := 0;
                     END IF;
                  END IF;
               END IF;

               IF V_IDPERVISIMPSCRE = 'S' THEN
                  V_VRIMPOSTOVISUIT := V_IMPOSTOIT;
               ELSE
                  IF C_IMPOSITEMCOM.CDFISCALIT = '1' THEN
                     V_VRIMPOSTOVISUIT := V_IMPOSTOIT;
                  ELSE
                     V_VRIMPOSTOVISUIT := 0;
                  END IF;
               END IF;

               IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (V_ICMS = 'S') THEN
                  UPDATE ITEMPROIMPOS
                     SET VRCONTITIMP = V_BASECALCTO,
                         VRBASECALCIT = V_BASECALCTO,
                         VRIMPOSTOIT = TRUNC(V_IMPOSTOIT,2),
                         VRIMPOSTOVISUIT = TRUNC(VRIMPOSTOVISUIT,2)
                    WHERE CDFILIAL = P_FILIAL
                      AND NRLANCTONF = P_LANCTONF
                      AND NRSEQITPROD = C_IMPOSITEMCOM.NRSEQITPROD
                      AND CDIMPOSTO = C_IMPOSITEMCOM.CDIMPOSTO
                      AND NRITPROIMPOS = '1';
               ELSE
                  UPDATE ITEMPROIMPOS
                     SET VRCONTITIMP = V_BASECALCTO,
                         VRBASECALCIT = V_BASECALCTO,
                         VRIMPOSTOIT = ROUND(V_IMPOSTOIT,2),
                         VRIMPOSTOVISUIT = ROUND(V_VRIMPOSTOVISUIT,2)
                    WHERE CDFILIAL = P_FILIAL
                      AND NRLANCTONF = P_LANCTONF
                      AND NRSEQITPROD = C_IMPOSITEMCOM.NRSEQITPROD
                      AND CDIMPOSTO = C_IMPOSITEMCOM.CDIMPOSTO
                      AND NRITPROIMPOS = '1';
               END IF;

               IF (C_IMPOSITEMCOM.VRPERREDBCIT > 0)  THEN

                  Begin
                     SELECT CDFILIAL
                     INTO   V_CHAVE
                     FROM ITEMPROIMPOS
                     WHERE CDFILIAL     = P_FILIAL                 AND
                           NRLANCTONF   = P_LANCTONF               AND
                           NRSEQITPROD  = C_IMPOSITEMCOM.NRSEQITPROD  AND
                           CDIMPOSTO    = C_IMPOSITEMCOM.CDIMPOSTO AND
                           NRITPROIMPOS = '2';
                  Exception
                     When No_Data_Found Then
                        V_CHAVE := Null;
                  End;

                  IF V_CHAVE IS NULL THEN
                     INSERT INTO ITEMPROIMPOS(
                        CDFILIAL, NRLANCTONF, NRSEQITPROD, CDIMPOSTO,
                        NRITPROIMPOS, CDFISCALIT, VRALIQITEM, VRPERREDBCIT,
                        VRCONTITIMP, VRBASECALCIT, VRIMPOSTOIT, VRPARDEDIT,
                        CDSITUTRIBIT, CDFISCOPERIT, VRIMPOSTOVISUIT, CDENQLEGALIPI,
                        CDCEST)
                     VALUES(
                        P_FILIAL, P_LANCTONF, C_IMPOSITEMCOM.NRSEQITPROD, C_IMPOSITEMCOM.CDIMPOSTO,
                        '2', '2', 0, V_PERDBCALC,
                        V_CONTABCALC, 0, 0, 0,
                        C_IMPOSITEMCOM.CDSITUTRIBIT, C_IMPOSITEMCOM.CDFISCOPERIT, 0, C_IMPOSITEMCOM.CDENQLEGALIPI,
                        C_IMPOSITEMCOM.CDCEST);
                  ELSE
                     UPDATE ITEMPROIMPOS
                        SET VRCONTITIMP = V_CONTABCALC,
                            VRBASECALCIT = 0,
                            VRIMPOSTOIT = 0,
                            VRPERREDBCIT = V_PERDBCALC,
                            VRIMPOSTOVISUIT = 0
                    WHERE CDFILIAL = P_FILIAL
                      AND NRLANCTONF = P_LANCTONF
                      AND NRSEQITPROD = C_IMPOSITEMCOM.NRSEQITPROD
                      AND CDIMPOSTO = C_IMPOSITEMCOM.CDIMPOSTO
                      AND NRITPROIMPOS = '2';
                  END IF;
               END IF;

            END IF;
         ELSE
            IF C_IMPOSITEMCOM.VRBASECALCIT > 0 THEN
               UPDATE ITEMPROIMPOS
                  SET VRCONTITIMP = C_IMPOSITEMCOM.VRBASECALCIT
                 WHERE CDFILIAL = P_FILIAL
                   AND NRLANCTONF = P_LANCTONF
                   AND NRSEQITPROD = C_IMPOSITEMCOM.NRSEQITPROD
                   AND CDIMPOSTO = C_IMPOSITEMCOM.CDIMPOSTO
                   AND NRITPROIMPOS = '1';
            END IF;
         END IF;
      END LOOP;

   --TOTALIZACAO DOS IMPOSTOS
      FOR C_IMPOSNFCOMP IN (SELECT IT.CDFILIAL, IT.NRLANCTONF, IT.CDIMPOSTO
                           FROM IMPOSNFTOT IT, IMPOSTO I
                           WHERE IT.CDIMPOSTO  = I.CDIMPOSTO AND
                                 I.IDPRODNOTA  <> w_C        AND
                                 IT.CDFILIAL   = P_FILIAL    AND
                                 IT.NRLANCTONF = P_LANCTONF) LOOP

          DELETE IMPOSNFTOT
          WHERE (CDFILIAL   = P_FILIAL) AND
                (NRLANCTONF = P_LANCTONF) AND
                (CDIMPOSTO = C_IMPOSNFCOMP.CDIMPOSTO);

      END LOOP;

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

      FOR C_IMPOSNFTOT IN (SELECT CDIMPOSTO, NVL(SUM(ROUND(VRIMPOSTOIT,2)),0) AS VRIMPOSTOIT, NVL(SUM(ROUND(VRBASECALCIT,2)),0) AS VRBASECALCIT, NVL(SUM(ROUND(VRADICFECP,2)),0) AS VRADICFECP
                           FROM ITEMPROIMPOS
                           WHERE (CDFILIAL   = P_FILIAL)   AND
                                 (NRLANCTONF = P_LANCTONF)
                           GROUP BY CDIMPOSTO) 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_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(C_IMPOSNFTOT.VRIMPOSTOIT,V_NRDECITOTANF), TRUNC(C_IMPOSNFTOT.VRBASECALCIT,V_NRDECITOTANF),TRUNC(C_IMPOSNFTOT.VRADICFECP,V_NRDECITOTANF));
         ELSE
            INSERT INTO IMPOSNFTOT(CDFILIAL, NRLANCTONF, CDIMPOSTO, VRTOTIMPONF, VRTOTBCALCNF, VRADICFECP)
                           VALUES (P_FILIAL, P_LANCTONF, C_IMPOSNFTOT.CDIMPOSTO, ROUND(C_IMPOSNFTOT.VRIMPOSTOIT,V_NRDECITOTANF), ROUND(C_IMPOSNFTOT.VRBASECALCIT,V_NRDECITOTANF),ROUND(C_IMPOSNFTOT.VRADICFECP,V_NRDECITOTANF));
         END IF;
      END LOOP;

      UPDATE ITEMPROIMPOS
         SET IDMODBCITNFE = '3'
       WHERE CDFILIAL = P_FILIAL
         AND NRLANCTONF = P_LANCTONF;

   ELSIF (P_TIPOOPER = w_09) OR (P_TIPOOPER = w_12) THEN /*VALE DE TRANSFERENCIA E NOTA DE DEBITO/CREDITO*/

      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;

      FOR C_ITPROD IN (SELECT I.CDPRODUTO, I.CDCFOPINFUSU, I.CDSUFXINFUSU, I.CDCSTINFUSU, I.NRSEQITPROD,
                              P.CDARVPROD, I.IDORIGEMPROD
                       FROM ITEMPRODUTO I, PRODUTO P
                       WHERE CDFILIAL   = P_FILIAL
                         AND NRLANCTONF = P_LANCTONF
                         AND I.CDPRODUTO = P.CDPRODUTO) LOOP

         CONSULTA_CST(w_S, P_EMPRESA, C_ITPROD.CDARVPROD, P_INSCESTA, P_TIPOOPER, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC, V_IDINTEREST, V_IDINTERNA, NULL, C_ITPROD.IDORIGEMPROD);

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

         CONSULTA_CFOP(w_S, P_EMPRESA, C_ITPROD.CDARVPROD, P_INSCESTA, P_TIPOOPER, V_PAISORIG,
                       V_ESTAORIG, V_PAISCFOP, V_ESTACFOP, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC, P_INIVALID, C_ITPROD.IDORIGEMPROD);

         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
               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 C_ITPROD.CDCFOPINFUSU IS NULL THEN
            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
            V_CFOPINFUSU := 'S';
            V_FISOPEITEM := C_ITPROD.CDCFOPINFUSU;
            V_SUFXCFOPPR := C_ITPROD.CDSUFXINFUSU;
            V_SITUTRIBPR := C_ITPROD.CDCSTINFUSU;
         END IF;

         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;

         CONSULTA_CSOSN('S', P_EMPRESA, C_ITPROD.CDARVPROD, P_INSCESTA, P_TIPOOPER, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC, V_IDINTEREST,V_CDFISCOPERSN);

         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_ITPROD.NRSEQITPROD;

         DELETE CFOPTEMP
         WHERE NRCFOPTEMP = V_CFOPTEMP;

         DELETE CSTTEMP
         WHERE NRCSTTEMP = V_CSTTEMP;

         /*Consulta de nfe*/
         V_CDSITTRIBTMP    := NULL;
         V_IDMODBCNFE      := NULL;
         V_IDMODBCSTNFE    := NULL;
         V_CDTPCRPICOSTNFE := NULL;
         V_CDNATUBCPCSTNFE := NULL;

         FOR C_ITPROI IN (SELECT II.CDIMPOSTO, II.NRITPROIMPOS
                            FROM ITEMPROIMPOS II, IMPOSTO I
                           WHERE II.CDFILIAL   = P_FILIAL
                             AND II.NRLANCTONF = P_LANCTONF
                             AND II.NRSEQITPROD = C_ITPROD.NRSEQITPROD
                             AND II.CDIMPOSTO = I.CDIMPOSTO
                             AND I.IDPRODNOTA = 'P'
                          ORDER BY II.CDIMPOSTO) LOOP

             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_ITPROI.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_ITPROI.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_ITPROI.CDIMPOSTO;
             END IF;

             IF V_CDGRUPOFISCAUX IS NULL THEN
               CONSULTA_CST_NFE(w_S, P_EMPRESA, C_ITPROD.CDARVPROD, P_INSCESTA, P_TIPOOPER, V_CDGRUPOFISC,C_ITPROI.CDIMPOSTO, V_IDINTEREST, V_IDINTERNA, P_FILIAL, P_LANCTONF, '', V_CDSITTRIBTMP, V_IDMODBCNFE, V_IDMODBCSTNFE, V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, V_IDMOTIDESSTNFE, C_ITPROD.IDORIGEMPROD);
             ELSE
               CONSULTA_CST_NFE(w_S, P_EMPRESA, C_ITPROD.CDARVPROD, P_INSCESTA, P_TIPOOPER, V_CDGRUPOFISCAUX,C_ITPROI.CDIMPOSTO, V_IDINTEREST, V_IDINTERNA, P_FILIAL, P_LANCTONF, '', V_CDSITTRIBTMP, V_IDMODBCNFE, V_IDMODBCSTNFE, V_CDTPCRPICOSTNFE, V_CDNATUBCPCSTNFE, V_IDMOTIDESSTNFE, C_ITPROD.IDORIGEMPROD);
             END IF;

             UPDATE ITEMPROIMPOS
               SET CDSITUTRIBITNFE = V_CDSITTRIBTMP,
                   IDMODBCITNFE = V_IDMODBCNFE,
                   IDMODBCSTITNFE = V_IDMODBCSTNFE,
                   CDTPCREDPICOITE = V_CDTPCRPICOSTNFE,
                   CDNATUBCALPCIT  = V_CDNATUBCPCSTNFE,
                   IDMOTDESONERAIT = V_IDMOTIDESSTNFE
               WHERE (CDFILIAL     = P_FILIAL)                   AND
                     (NRLANCTONF   = P_LANCTONF)                 AND
                     (NRSEQITPROD  = C_ITPROD.NRSEQITPROD) AND
                     (CDIMPOSTO    = C_ITPROI.CDIMPOSTO)   AND
                     (NRITPROIMPOS = C_ITPROI.NRITPROIMPOS);

         END LOOP;
      END LOOP;
   END IF;

   V_DIFERENCA := 0;
   /* RATEIO DOS ENCARGOS PARA OS PRODUTOS DA NOTA. ESTE RATEIO E NECESSARIO PARA A NOTA FISCAL ELETRONICA */
   FOR C_ITEMENCARGO IN (SELECT ENCARGO.CDENCARGONFE, SUM(ITEMENCARGO.VRITEMENCA) AS VRITEMENCA
                           FROM ITEMENCARGO, ENCARGO
                          WHERE ITEMENCARGO.CDENCARGO = ENCARGO.CDENCARGO
                            AND ENCARGO.CDENCARGONFE IN ('01', '02', '03', '04', '05')
                            AND NVL(ITEMENCARGO.VRITEMENCA, 0) >= 0
                            AND CDFILIAL = P_FILIAL
                            AND NRLANCTONF = P_LANCTONF
                            AND (V_ENCARGOLIQUIDO <> 'T')
                            AND (NOT(INSTR(V_ENCARGOLIQUIDO, ITEMENCARGO.CDENCARGO) > 0))
                          GROUP BY ENCARGO.CDENCARGONFE) LOOP
      /* ENCARGO FRETE */
      IF (C_ITEMENCARGO.CDENCARGONFE = '01') THEN
         IF (C_ITEMENCARGO.VRITEMENCA > 0) THEN
            FOR C_ITEMPRODUTO IN (SELECT NRSEQITPROD, VRTOTAITEM
                                    FROM ITEMPRODUTO
                                   WHERE CDFILIAL = P_FILIAL
                                     AND NRLANCTONF = P_LANCTONF) LOOP

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

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

            V_DIFERENCA := C_ITEMENCARGO.VRITEMENCA - V_VRFRETEITEM;

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

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

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

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

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

            V_DIFERENCA := C_ITEMENCARGO.VRITEMENCA - V_VRSEGURITEM;

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

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

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

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

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

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

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

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

            END IF;
         ELSE
            UPDATE ITEMPRODUTO
               SET VRENCARGODESC = VRDESCITEM + 0
             WHERE CDFILIAL  = P_FILIAL
               AND NRLANCTONF = P_LANCTONF;
         END IF;
      END IF;
           /*ENCARGO OUTRAS DESPESAS*/
      IF (C_ITEMENCARGO.CDENCARGONFE = '04') THEN
         IF (C_ITEMENCARGO.VRITEMENCA > 0) THEN
            IF (V_IDNFORIGVIAXML = 'S') THEN
               BEGIN
                  SELECT SUM(VRENCARGOIMPXML)
                    INTO V_TOTAENCIMPXML
                    FROM ITEMPRODUTO
                   WHERE CDFILIAL = P_FILIAL
                     AND NRLANCTONF = P_LANCTONF
                     AND VRENCARGOIMPXML > 0;
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_TOTAENCIMPXML := 0;
               END;

               IF (ROUND(C_ITEMENCARGO.VRITEMENCA, 2) > ROUND(V_TOTAENCIMPXML, 2)) THEN
                  FOR C_ITEMPRODUTO IN (SELECT NRSEQITPROD, VRTOTAITEM
                                          FROM ITEMPRODUTO
                                         WHERE CDFILIAL = P_FILIAL
                                           AND NRLANCTONF = P_LANCTONF) LOOP

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

                     IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (NVL(V_IDORIGDESTNF, 'C') <> 'L') THEN
                        UPDATE ITEMPRODUTO
                           SET VROUTRASDESPITEM = TRUNC(((C_ITEMENCARGO.VRITEMENCA - V_TOTAENCIMPXML) * (V_PERCENTITEM / 100)), 2)
                         WHERE CDFILIAL  = P_FILIAL
                           AND NRLANCTONF = P_LANCTONF
                           AND NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;
                     ELSE
                        UPDATE ITEMPRODUTO
                           SET VROUTRASDESPITEM = ROUND(((C_ITEMENCARGO.VRITEMENCA - V_TOTAENCIMPXML) * (V_PERCENTITEM / 100)), 2)
                         WHERE CDFILIAL  = P_FILIAL
                           AND NRLANCTONF = P_LANCTONF
                           AND NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;
                     END IF;
                  END LOOP;

                  FOR C_ITEMPRODUTO IN (SELECT NRSEQITPROD, VRTOTAITEM, VRENCARGOIMPXML
                                          FROM ITEMPRODUTO
                                         WHERE CDFILIAL = P_FILIAL
                                           AND NRLANCTONF = P_LANCTONF
                                           AND VRENCARGOIMPXML > 0) LOOP


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


                     IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (NVL(V_IDORIGDESTNF, 'C') <> 'L') THEN
                        UPDATE ITEMPRODUTO
                           SET VROUTRASDESPITEM = TRUNC((VROUTRASDESPITEM + VRENCARGOIMPXML), 2)
                         WHERE CDFILIAL  = P_FILIAL
                           AND NRLANCTONF = P_LANCTONF
                           AND NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;
                     ELSE
                        UPDATE ITEMPRODUTO
                           SET VROUTRASDESPITEM = ROUND((VROUTRASDESPITEM + VRENCARGOIMPXML), 2)
                         WHERE CDFILIAL  = P_FILIAL
                           AND NRLANCTONF = P_LANCTONF
                           AND NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;
                     END IF;
                  END LOOP;
               ELSE
                  FOR C_ITEMPRODUTO IN (SELECT NRSEQITPROD, VRTOTAITEM, VRENCARGOIMPXML
                                          FROM ITEMPRODUTO
                                         WHERE CDFILIAL = P_FILIAL
                                           AND NRLANCTONF = P_LANCTONF
                                           AND VRENCARGOIMPXML > 0) LOOP


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


                     IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (NVL(V_IDORIGDESTNF, 'C') <> 'L') THEN
                        UPDATE ITEMPRODUTO
                           SET VROUTRASDESPITEM = TRUNC(VRENCARGOIMPXML, 2)
                         WHERE CDFILIAL  = P_FILIAL
                           AND NRLANCTONF = P_LANCTONF
                           AND NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;
                     ELSE
                        UPDATE ITEMPRODUTO
                           SET VROUTRASDESPITEM = ROUND(VRENCARGOIMPXML, 2)
                         WHERE CDFILIAL  = P_FILIAL
                           AND NRLANCTONF = P_LANCTONF
                           AND NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;
                     END IF;
                  END LOOP;
               END IF;
            ELSE
               FOR C_ITEMPRODUTO IN (SELECT NRSEQITPROD, VRTOTAITEM
                                       FROM ITEMPRODUTO
                                      WHERE CDFILIAL = P_FILIAL
                                        AND NRLANCTONF = P_LANCTONF) LOOP

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

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

            V_DIFERENCA := C_ITEMENCARGO.VRITEMENCA - V_VROUTRASDESPITEM;

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

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

      /*ENCARGO DESPESAS ADUANEIRAS*/

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

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

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

            V_DIFERENCA := C_ITEMENCARGO.VRITEMENCA - V_VRDESPADUANEIRA;

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

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

   /*GRAVAR O VALOR DOS ENCARGOS NA ITEMPRODUTO DE ACORDO COM O PESO LIQUIDO*/
   IF NOT (V_ENCARGOLIQUIDO = 'N') THEN
      FOR C_ITEMENCARGO IN (SELECT ENCARGO.CDENCARGONFE, SUM(ITEMENCARGO.VRITEMENCA) AS VRITEMENCA
                              FROM ITEMENCARGO, ENCARGO
                             WHERE ITEMENCARGO.CDENCARGO = ENCARGO.CDENCARGO
                               AND ENCARGO.CDENCARGONFE IN ('01', '02', '03', '04', '05')
                               AND NVL(ITEMENCARGO.VRITEMENCA, 0) >= 0
                               AND CDFILIAL = P_FILIAL
                               AND NRLANCTONF = P_LANCTONF
                               AND ((V_ENCARGOLIQUIDO = 'T') OR (INSTR(V_ENCARGOLIQUIDO, ITEMENCARGO.CDENCARGO) > 0 ))
                             GROUP BY ENCARGO.CDENCARGONFE) LOOP
         /* ENCARGO FRETE */
         IF (C_ITEMENCARGO.CDENCARGONFE = '01') THEN
            IF (C_ITEMENCARGO.VRITEMENCA > 0) THEN
               /* UPDATE PARA ZERAR TODOS OS PRODUTOS PARA GRAVAR EM SEGUIDA SOMENTE PARA OS PRODUTOS QUE TEM PESO LIQUIDO CADASTRADO*/
               UPDATE ITEMPRODUTO
                  SET VRFRETEITEM = 0
                WHERE CDFILIAL = P_FILIAL
                  AND NRLANCTONF = P_LANCTONF;

               FOR C_ITEMPRODUTO IN (SELECT IP.NRSEQITPROD, (PR.VRPESOLIQUPR * IP.QTITEMPROD) AS VRTOTAITEM
                                       FROM ITEMPRODUTO IP, PRODUTO PR
                                      WHERE IP.CDFILIAL = P_FILIAL
                                        AND IP.NRLANCTONF = P_LANCTONF
                                        AND PR.CDPRODUTO = IP.CDPRODUTO
                                        AND (NVL(PR.VRPESOLIQUPR, 0) > 0)) LOOP

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

                  IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (NVL(V_IDORIGDESTNF, 'C') <> 'L') THEN
                     UPDATE ITEMPRODUTO
                        SET VRFRETEITEM = TRUNC(C_ITEMENCARGO.VRITEMENCA * (V_PERCENTITEM / 100), 2)
                      WHERE CDFILIAL  = P_FILIAL
                        AND NRLANCTONF = P_LANCTONF
                        AND NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;
                  ELSE
                     UPDATE ITEMPRODUTO
                        SET VRFRETEITEM = ROUND(C_ITEMENCARGO.VRITEMENCA * (V_PERCENTITEM / 100), 2)
                      WHERE CDFILIAL  = P_FILIAL
                        AND NRLANCTONF = P_LANCTONF
                        AND NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;
                  END IF;
               END LOOP;

               /*AJUSTE DE VALORES*/
               SELECT SUM(VRFRETEITEM)
                 INTO V_VRFRETEITEM
                 FROM ITEMPRODUTO
                WHERE CDFILIAL = P_FILIAL
                  AND NRLANCTONF = P_LANCTONF;

               V_DIFERENCA := C_ITEMENCARGO.VRITEMENCA - V_VRFRETEITEM;

               IF V_DIFERENCA <> 0 THEN
                  UPDATE ITEMPRODUTO
                     SET VRFRETEITEM = VRFRETEITEM + V_DIFERENCA
                   WHERE CDFILIAL = P_FILIAL
                     AND NRLANCTONF = P_LANCTONF
                     AND NRSEQITPROD = (SELECT MAX(NRSEQITPROD)
                                         FROM ITEMPRODUTO IP, PRODUTO PR
                                         WHERE IP.CDFILIAL = P_FILIAL
                                           AND IP.NRLANCTONF = P_LANCTONF
                                           AND PR.CDPRODUTO = IP.CDPRODUTO
                                           AND (NVL(PR.VRPESOLIQUPR, 0) > 0)
                                           AND VRTOTAITEM = (SELECT MAX(VRTOTAITEM)
                                                              FROM ITEMPRODUTO I, PRODUTO PR
                                                             WHERE I.CDFILIAL = P_FILIAL
                                                               AND I.NRLANCTONF = P_LANCTONF
                                                               AND (NVL(PR.VRPESOLIQUPR, 0) > 0)));

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

         /* ENCARGO SEGURO */
         IF (C_ITEMENCARGO.CDENCARGONFE = '02') THEN
            IF (C_ITEMENCARGO.VRITEMENCA > 0) THEN
               UPDATE ITEMPRODUTO
                  SET VRSEGURITEM = 0
                WHERE CDFILIAL = P_FILIAL
                  AND NRLANCTONF = P_LANCTONF;
               FOR C_ITEMPRODUTO IN (SELECT IP.NRSEQITPROD, (PR.VRPESOLIQUPR * IP.QTITEMPROD) AS VRTOTAITEM
                                       FROM ITEMPRODUTO IP, PRODUTO PR
                                      WHERE IP.CDFILIAL = P_FILIAL
                                        AND IP.NRLANCTONF = P_LANCTONF
                                        AND PR.CDPRODUTO = IP.CDPRODUTO
                                        AND (NVL(PR.VRPESOLIQUPR, 0) > 0)) LOOP

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

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

               V_DIFERENCA := C_ITEMENCARGO.VRITEMENCA - V_VRSEGURITEM;

               IF V_DIFERENCA <> 0 THEN
                  UPDATE ITEMPRODUTO
                     SET VRSEGURITEM = VRSEGURITEM + V_DIFERENCA
                   WHERE CDFILIAL = P_FILIAL
                     AND NRLANCTONF = P_LANCTONF
                     AND NRSEQITPROD = (SELECT MAX(NRSEQITPROD)
                                         FROM ITEMPRODUTO IP, PRODUTO PR
                                         WHERE IP.CDFILIAL = P_FILIAL
                                           AND IP.NRLANCTONF = P_LANCTONF
                                           AND PR.CDPRODUTO = IP.CDPRODUTO
                                           AND (NVL(PR.VRPESOLIQUPR, 0) > 0)
                                           AND VRTOTAITEM = (SELECT MAX(VRTOTAITEM)
                                                              FROM ITEMPRODUTO I, PRODUTO PR
                                                             WHERE I.CDFILIAL = P_FILIAL
                                                               AND I.NRLANCTONF = P_LANCTONF
                                                               AND (NVL(PR.VRPESOLIQUPR, 0) > 0)));

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

         /* ENCARGO DESCONTO */
         IF (C_ITEMENCARGO.CDENCARGONFE = '03') THEN
            IF (C_ITEMENCARGO.VRITEMENCA > 0) THEN
               UPDATE ITEMPRODUTO
                  SET VRENCARGODESC = 0
                WHERE CDFILIAL = P_FILIAL
                  AND NRLANCTONF = P_LANCTONF;
               FOR C_ITEMPRODUTO IN (SELECT IP.NRSEQITPROD, (PR.VRPESOLIQUPR * IP.QTITEMPROD) AS VRTOTAITEM
                                       FROM ITEMPRODUTO IP, PRODUTO PR
                                      WHERE IP.CDFILIAL = P_FILIAL
                                        AND IP.NRLANCTONF = P_LANCTONF
                                        AND PR.CDPRODUTO = IP.CDPRODUTO
                                        AND (NVL(PR.VRPESOLIQUPR, 0) > 0)) LOOP

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

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

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

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

               IF V_DIFERENCA <> 0 THEN
                  UPDATE ITEMPRODUTO
                     SET VRENCARGODESC = VRENCARGODESC + V_DIFERENCA
                   WHERE CDFILIAL = P_FILIAL
                     AND NRLANCTONF = P_LANCTONF
                     AND NRSEQITPROD = (SELECT MAX(NRSEQITPROD)
                                         FROM ITEMPRODUTO IP, PRODUTO PR
                                         WHERE IP.CDFILIAL = P_FILIAL
                                           AND IP.NRLANCTONF = P_LANCTONF
                                           AND PR.CDPRODUTO = IP.CDPRODUTO
                                           AND (NVL(PR.VRPESOLIQUPR, 0) > 0)
                                           AND VRTOTAITEM = (SELECT MAX(VRTOTAITEM)
                                                              FROM ITEMPRODUTO I, PRODUTO PR
                                                             WHERE I.CDFILIAL = P_FILIAL
                                                               AND I.NRLANCTONF = P_LANCTONF
                                                               AND (NVL(PR.VRPESOLIQUPR, 0) > 0)));

               END IF;
            ELSE
               UPDATE ITEMPRODUTO
                  SET VRENCARGODESC = VRDESCITEM + 0
                WHERE CDFILIAL  = P_FILIAL
                  AND NRLANCTONF = P_LANCTONF;
            END IF;
         END IF;
         /*ENCARGO OUTRAS DESPESAS*/
         IF (C_ITEMENCARGO.CDENCARGONFE = '04') THEN
            IF (C_ITEMENCARGO.VRITEMENCA > 0) THEN
               UPDATE ITEMPRODUTO
                  SET VROUTRASDESPITEM = 0
                WHERE CDFILIAL = P_FILIAL
                  AND NRLANCTONF = P_LANCTONF;
               IF (V_IDNFORIGVIAXML = 'S') THEN
                  BEGIN
                     SELECT SUM(VRENCARGOIMPXML)
                       INTO V_TOTAENCIMPXML
                       FROM ITEMPRODUTO
                      WHERE CDFILIAL = P_FILIAL
                        AND NRLANCTONF = P_LANCTONF
                        AND VRENCARGOIMPXML > 0;
                  EXCEPTION
                     WHEN NO_DATA_FOUND THEN
                        V_TOTAENCIMPXML := 0;
                  END;

                  IF (ROUND(C_ITEMENCARGO.VRITEMENCA, 2) > ROUND(V_TOTAENCIMPXML, 2)) THEN
                     FOR C_ITEMPRODUTO IN (SELECT NRSEQITPROD, VRTOTAITEM
                                             FROM ITEMPRODUTO
                                            WHERE CDFILIAL = P_FILIAL
                                              AND NRLANCTONF = P_LANCTONF) LOOP

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

                        IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (NVL(V_IDORIGDESTNF, 'C') <> 'L') THEN
                           UPDATE ITEMPRODUTO
                              SET VROUTRASDESPITEM = TRUNC(((C_ITEMENCARGO.VRITEMENCA - V_TOTAENCIMPXML) * (V_PERCENTITEM / 100)), 2)
                            WHERE CDFILIAL  = P_FILIAL
                              AND NRLANCTONF = P_LANCTONF
                              AND NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;
                        ELSE
                           UPDATE ITEMPRODUTO
                              SET VROUTRASDESPITEM = ROUND(((C_ITEMENCARGO.VRITEMENCA - V_TOTAENCIMPXML) * (V_PERCENTITEM / 100)), 2)
                            WHERE CDFILIAL  = P_FILIAL
                              AND NRLANCTONF = P_LANCTONF
                              AND NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;
                        END IF;
                     END LOOP;

                     FOR C_ITEMPRODUTO IN (SELECT NRSEQITPROD, VRTOTAITEM, VRENCARGOIMPXML
                                             FROM ITEMPRODUTO
                                            WHERE CDFILIAL = P_FILIAL
                                              AND NRLANCTONF = P_LANCTONF
                                              AND VRENCARGOIMPXML > 0) LOOP


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


                        IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (NVL(V_IDORIGDESTNF, 'C') <> 'L') THEN
                           UPDATE ITEMPRODUTO
                              SET VROUTRASDESPITEM = TRUNC((VROUTRASDESPITEM + VRENCARGOIMPXML), 2)
                            WHERE CDFILIAL  = P_FILIAL
                              AND NRLANCTONF = P_LANCTONF
                              AND NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;
                        ELSE
                           UPDATE ITEMPRODUTO
                              SET VROUTRASDESPITEM = ROUND((VROUTRASDESPITEM + VRENCARGOIMPXML), 2)
                            WHERE CDFILIAL  = P_FILIAL
                              AND NRLANCTONF = P_LANCTONF
                              AND NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;
                        END IF;
                     END LOOP;
                  ELSE
                     FOR C_ITEMPRODUTO IN (SELECT NRSEQITPROD, VRTOTAITEM, VRENCARGOIMPXML
                                             FROM ITEMPRODUTO
                                            WHERE CDFILIAL = P_FILIAL
                                              AND NRLANCTONF = P_LANCTONF
                                              AND VRENCARGOIMPXML > 0) LOOP


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


                        IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (NVL(V_IDORIGDESTNF, 'C') <> 'L') THEN
                           UPDATE ITEMPRODUTO
                              SET VROUTRASDESPITEM = TRUNC(VRENCARGOIMPXML, 2)
                            WHERE CDFILIAL  = P_FILIAL
                              AND NRLANCTONF = P_LANCTONF
                              AND NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;
                        ELSE
                           UPDATE ITEMPRODUTO
                              SET VROUTRASDESPITEM = ROUND(VRENCARGOIMPXML, 2)
                            WHERE CDFILIAL  = P_FILIAL
                              AND NRLANCTONF = P_LANCTONF
                              AND NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;
                        END IF;
                     END LOOP;
                  END IF;
               ELSE
                  FOR C_ITEMPRODUTO IN (SELECT IP.NRSEQITPROD, (PR.VRPESOLIQUPR * IP.QTITEMPROD) AS VRTOTAITEM
                                          FROM ITEMPRODUTO IP, PRODUTO PR
                                         WHERE IP.CDFILIAL = P_FILIAL
                                           AND IP.NRLANCTONF = P_LANCTONF
                                           AND PR.CDPRODUTO = IP.CDPRODUTO
                                           AND (NVL(PR.VRPESOLIQUPR, 0) > 0)) LOOP

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

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

               V_DIFERENCA := C_ITEMENCARGO.VRITEMENCA - V_VROUTRASDESPITEM;

               IF V_DIFERENCA <> 0 THEN
                  UPDATE ITEMPRODUTO
                     SET VROUTRASDESPITEM = VROUTRASDESPITEM + V_DIFERENCA
                   WHERE CDFILIAL = P_FILIAL
                     AND NRLANCTONF = P_LANCTONF
                     AND NRSEQITPROD = (SELECT MAX(NRSEQITPROD)
                                         FROM ITEMPRODUTO IP, PRODUTO PR
                                         WHERE IP.CDFILIAL = P_FILIAL
                                           AND IP.NRLANCTONF = P_LANCTONF
                                           AND PR.CDPRODUTO = IP.CDPRODUTO
                                           AND (NVL(PR.VRPESOLIQUPR, 0) > 0)
                                           AND VRTOTAITEM = (SELECT MAX(VRTOTAITEM)
                                                              FROM ITEMPRODUTO I, PRODUTO PR
                                                             WHERE I.CDFILIAL = P_FILIAL
                                                               AND I.NRLANCTONF = P_LANCTONF
                                                               AND (NVL(PR.VRPESOLIQUPR, 0) > 0)));

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

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

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

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

               V_DIFERENCA := C_ITEMENCARGO.VRITEMENCA - V_VRDESPADUANEIRA;

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

               END IF;
            ELSE
               UPDATE ITEMPRODUTO
                  SET VRDESPADUANEIRA = 0
                WHERE CDFILIAL  = P_FILIAL
                  AND NRLANCTONF = P_LANCTONF;
            END IF;
         END IF;      
      END LOOP;
   END IF;
   /*GRAVAR O VALOR DOS ENCARGOS NA ITEMPRODUTO DE ACORDO COM O PESO LIQUIDO*/
   
--CALCULO DO VALOR TOTAL DA NOTA FISCAL

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

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

   IF V_IDOPERDEVONF = 'S' THEN
      SELECT SUM(VRTOTIMPONF)
      INTO   V_SOMAIMPO
      FROM IMPOSNFTOT, IMPOSTO
      WHERE IMPOSNFTOT.CDFILIAL   = P_FILIAL          AND
            IMPOSNFTOT.NRLANCTONF = P_LANCTONF        AND
            IMPOSNFTOT.CDIMPOSTO  = IMPOSTO.CDIMPOSTO AND
            IDTRATIMPO            = w_A               AND
            NVL(IDACRPRODENTRNF, 'N') = 'N' AND
            NOT EXISTS(SELECT CDIMPOSTO
                       FROM IMPOSTO
                       WHERE IMPOSTO.CDIMPOSTRIB = IMPOSNFTOT.CDIMPOSTO);

   ELSE
      SELECT SUM(VRTOTIMPONF)
      INTO   V_SOMAIMPO
      FROM IMPOSNFTOT, IMPOSTO
      WHERE IMPOSNFTOT.CDFILIAL   = P_FILIAL          AND
            IMPOSNFTOT.NRLANCTONF = P_LANCTONF        AND
            IMPOSNFTOT.CDIMPOSTO  = IMPOSTO.CDIMPOSTO AND
            IDTRATIMPO            = w_A               AND
            NOT EXISTS(SELECT CDIMPOSTO
                       FROM IMPOSTO
                       WHERE IMPOSTO.CDIMPOSTRIB = IMPOSNFTOT.CDIMPOSTO);
   END IF;

   SELECT SUM(VRTOTIMPONF)
   INTO   V_MENOIMPO
   FROM IMPOSNFTOT, IMPOSTO
   WHERE IMPOSNFTOT.CDFILIAL   = P_FILIAL          AND
         IMPOSNFTOT.NRLANCTONF = P_LANCTONF        AND
         IMPOSNFTOT.CDIMPOSTO  = IMPOSTO.CDIMPOSTO AND
         IDTRATIMPO = w_D;

   IF NOT (V_LIQUIDO IS NULL) AND (P_TIPOOPER <> w_12) THEN
      V_TOTALNOTA := V_LIQUIDO;
   END IF;

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

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

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

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

   --VALOR SUBSTITUICAO TRIBUTARIA COM IDENTIFICACAO PARA ACRESCER AO TOTAL DA NF
   IF V_IDOPERDEVONF = 'S' THEN
      SELECT NVL(ROUND(SUM(VRIMPOSTOIT + NVL(VRADICFECP, 0)), V_NRDECITOTANF),0)
        INTO   V_SOMAIMPO
        FROM ITEMPROIMPOS IT, IMPOSTO I
       WHERE CDFILIAL     = P_FILIAL           AND
             NRLANCTONF   = P_LANCTONF         AND
             IT.CDIMPOSTO = I.CDIMPOSTO        AND
             NVL(I.IDACRPRODENTRNF, 'N') = 'N' AND
             NVL(IT.IDTRIMPSTII, '0')     = '0' AND
         EXISTS(SELECT CDIMPOSTO
                  FROM IMPOSTO
                 WHERE CDIMPOSTRIB = IT.CDIMPOSTO);
   ELSE
      SELECT NVL(ROUND(SUM(IT.VRIMPOSTOIT + NVL(VRADICFECP, 0)), V_NRDECITOTANF),0)
      INTO   V_SOMAIMPO
      FROM ITEMPROIMPOS IT, IMPOSTO I
      WHERE IT.CDFILIAL    = P_FILIAL    AND
            IT.NRLANCTONF  = P_LANCTONF  AND
            IT.CDIMPOSTO   = I.CDIMPOSTO AND
            NVL(IT.IDTRIMPSTII, '0')     = '0' AND
            EXISTS(SELECT CDIMPOSTO
                   FROM IMPOSTO
                   WHERE CDIMPOSTRIB = IT.CDIMPOSTO);

   END IF;


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

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

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

   IF P_TIPOOPER = w_12 THEN

      FOR C_NOTABEBICRED IN (SELECT I.CDPRODUTO, VRTOTAITEM, IDITEMISSAO, IDTPNFCREDEB
                             FROM   ITEMPRODUTO I, ITEMISSAO T
                             WHERE  I.CDFILIAL   = P_FILIAL      AND
                                    I.NRLANCTONF = P_LANCTONF    AND
                                    I.CDPRODUTO  = T.CDPRODUTO
                             ORDER BY IDITEMISSAO) LOOP

          SELECT IDITEMISSAO
          INTO V_IDITEMISSAO
          FROM ITEMISSAO
          WHERE CDPRODUTO = C_NOTABEBICRED.CDPRODUTO;

          IF (V_IDITEMISSAO = w_D) THEN
             UPDATE ITEMPRODUTO
             SET IDTPNFCREDEB = w_2
             WHERE CDFILIAL   = P_FILIAL   AND
                   NRLANCTONF = P_LANCTONF AND
                   CDPRODUTO  = C_NOTABEBICRED.CDPRODUTO;

             V_TOTALNOTA := V_TOTALNOTA + C_NOTABEBICRED.VRTOTAITEM;
          ELSIF (V_IDITEMISSAO = w_C)  THEN
             UPDATE ITEMPRODUTO
             SET IDTPNFCREDEB = w_1
             WHERE CDFILIAL   = P_FILIAL   AND
                   NRLANCTONF = P_LANCTONF AND
                   CDPRODUTO  = C_NOTABEBICRED.CDPRODUTO;

             V_TOTALNOTA := V_TOTALNOTA - C_NOTABEBICRED.VRTOTAITEM;
          ELSE
             UPDATE ITEMPRODUTO
             SET IDTPNFCREDEB = w_3
             WHERE CDFILIAL   = P_FILIAL   AND
                   NRLANCTONF = P_LANCTONF AND
                   CDPRODUTO  = C_NOTABEBICRED.CDPRODUTO;

             V_TOTALNOTA := V_TOTALNOTA - C_NOTABEBICRED.VRTOTAITEM;
          END IF;

          SELECT CDFILIAPFATU, NRAPFATUTNF
          INTO V_CDFILIAPFATU, V_NRAPFATUTNF
          FROM NOTAFISCAL
          WHERE CDFILIAL   = P_FILIAL   AND
                NRLANCTONF = P_LANCTONF;

          IF NOT(V_CDFILIAPFATU IS NULL) AND NOT(V_NRAPFATUTNF IS NULL) THEN

             IF ((C_NOTABEBICRED.IDITEMISSAO = w_D) OR  (C_NOTABEBICRED.IDITEMISSAO = w_O)) AND
                (C_NOTABEBICRED.IDTPNFCREDEB IS NULL)  THEN
                V_TOTALNOTA := V_TOTALNOTA + C_NOTABEBICRED.VRTOTAITEM;
             ELSIF (C_NOTABEBICRED.IDITEMISSAO = w_C)  THEN
                V_TOTALNOTA := V_TOTALNOTA - C_NOTABEBICRED.VRTOTAITEM;
             ELSE
                V_TOTALNOTA := V_TOTALNOTA + C_NOTABEBICRED.VRTOTAITEM;
             END IF;
          END IF;
      END LOOP;
   END IF;

   /* AJUSTANDO O VALOR DO DIFERIMENTO CASO OCORRA ALGUMA DIFERENCA DEVIDO AOS ARREDONDAMENTOS */
   FOR C_AJUSTA_DIFERIMENTO IN (SELECT IT.NRSEQITPROD, IT.VRIMPOSTOIT, IT.VRIMPOSTOOPERAIT, IT.VRIMPOSTODIFERIT, 
                                       IT.VRPERDIFEREIT
                                  FROM ITEMPROIMPOS IT JOIN IMPOSTO IM ON (IT.CDIMPOSTO = IM.CDIMPOSTO)
                                 WHERE (IT.VRIMPOSTOIT <> (IT.VRIMPOSTOOPERAIT - IT.VRIMPOSTODIFERIT))
                                   AND (IT.VRPERDIFEREIT IS NOT NULL)
                                   AND (IM.CDIMPOSTONFE = '00')
                                   AND (IT.NRITPROIMPOS = '1')
                                   AND (IT.CDFILIAL = P_FILIAL)
                                   AND (IT.NRLANCTONF = P_LANCTONF)
                                 ORDER BY IT.NRSEQITPROD)
   LOOP
      UPDATE ITEMPROIMPOS
         SET VRIMPOSTODIFERIT = VRIMPOSTODIFERIT + (C_AJUSTA_DIFERIMENTO.VRIMPOSTOOPERAIT - C_AJUSTA_DIFERIMENTO.VRIMPOSTOIT - C_AJUSTA_DIFERIMENTO.VRIMPOSTODIFERIT)
       WHERE CDFILIAL = P_FILIAL
         AND NRLANCTONF = P_LANCTONF
         AND NRSEQITPROD = C_AJUSTA_DIFERIMENTO.NRSEQITPROD;
   END LOOP;

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

   V_TOTALNOTA := V_TOTALNOTA - V_IMPOSDESONERA;

   IF V_NRDECITOTANF <> 0 THEN
      V_TOTALNOTA := ROUND(V_TOTALNOTA, 2);
   END IF;

   IF (V_IDCONTCONFORIG = 'N') OR (V_IDOPERDEVONF <> w_S) THEN
      SELECT NVL(V_TOTALNOTA,0) - SUM(ROUND(NVL(VRBRUTITEM,0), 2))
        INTO V_DIFEVRBRUTO
        FROM ITEMPRODUTO
       WHERE CDFILIAL = P_FILIAL
         AND NRLANCTONF = P_LANCTONF;
   
      IF V_DIFEVRBRUTO <> 0 THEN
         UPDATE ITEMPRODUTO
            SET VRBRUTITEM = VRBRUTITEM + V_DIFEVRBRUTO
          WHERE CDFILIAL = P_FILIAL
            AND NRLANCTONF = P_LANCTONF
            AND NRSEQITPROD = (SELECT MAX(I.NRSEQITPROD)
                                 FROM ITEMPRODUTO I
                                WHERE I.CDFILIAL     = P_FILIAL
                                  AND I.NRLANCTONF   = P_LANCTONF
                                  AND VRTOTAITEM = (SELECT MAX(VRTOTAITEM)
                                                      FROM ITEMPRODUTO I
                                                     WHERE I.CDFILIAL     = P_FILIAL
                                                       AND I.NRLANCTONF   = P_LANCTONF));
   
      END IF;
   END IF;

-- RECALCULO DO VALOR CONTABIL DO ITEM

   FOR C_ITEM IN (SELECT II.CDIMPOSTO, I.VRBRUTITEM, I.NRSEQITPROD, I.VRCONTITEM
                  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)
         WHERE (NRLANCTONF   = P_LANCTONF)         AND
               (CDFILIAL     = P_FILIAL)           AND
               (NRSEQITPROD  = C_ITEM.NRSEQITPROD) AND
               (CDIMPOSTO    = C_ITEM.CDIMPOSTO)   AND
               (NRITPROIMPOS = w_2);
      ELSE
         UPDATE ITEMPROIMPOS
         SET VRCONTITIMP = ROUND(VRCONTITIMP,2)
         WHERE (NRLANCTONF   = P_LANCTONF)         AND
               (CDFILIAL     = P_FILIAL)           AND
               (NRSEQITPROD  = C_ITEM.NRSEQITPROD) AND
               (CDIMPOSTO    = C_ITEM.CDIMPOSTO)   AND
               (NRITPROIMPOS = w_2);
      END IF;

      Begin
         SELECT NVL(VRCONTITIMP,0)
         INTO   V_VRREDUCAO
         FROM ITEMPROIMPOS
         WHERE (NRLANCTONF   = P_LANCTONF)         AND
               (CDFILIAL     = P_FILIAL)           AND
               (NRSEQITPROD  = C_ITEM.NRSEQITPROD) AND
               (CDIMPOSTO    = C_ITEM.CDIMPOSTO)   AND
               (NRITPROIMPOS = w_2);
      Exception
         When No_Data_Found Then
            V_VRREDUCAO := 0;
      End;

      IF V_VRREDUCAO IS NULL THEN
         V_VRREDUCAO := 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_ITEM.CDIMPOSTO)
      LOOP
         V_ICMS := 'S';
      END LOOP;

      IF (NVL(V_IDUTDESCICMS, 'N') <> 'S') THEN
         IF (C_ITEM.VRBRUTITEM > 0) THEN
            IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (V_ICMS = 'S') THEN
               UPDATE ITEMPROIMPOS
               SET VRCONTITIMP = TRUNC((C_ITEM.VRBRUTITEM - V_VRREDUCAO),2)
               WHERE (NRLANCTONF   = P_LANCTONF)         AND
                     (CDFILIAL     = P_FILIAL)           AND
                     (NRSEQITPROD  = C_ITEM.NRSEQITPROD) AND
                     (CDIMPOSTO    = C_ITEM.CDIMPOSTO)   AND
                     (NRITPROIMPOS = w_1)                AND
                     (NOT EXISTS(SELECT CDIMPOSTO
                                 FROM IMPOSTO
                                 WHERE CDIMPOSTRIB = ITEMPROIMPOS.CDIMPOSTO));
            ELSE
               UPDATE ITEMPROIMPOS
               SET VRCONTITIMP = ROUND((C_ITEM.VRBRUTITEM - V_VRREDUCAO),2)
               WHERE (NRLANCTONF   = P_LANCTONF)         AND
                     (CDFILIAL     = P_FILIAL)           AND
                     (NRSEQITPROD  = C_ITEM.NRSEQITPROD) AND
                     (CDIMPOSTO    = C_ITEM.CDIMPOSTO)   AND
                     (NRITPROIMPOS = w_1)                AND
                     (NOT EXISTS(SELECT CDIMPOSTO
                                 FROM IMPOSTO
                                 WHERE CDIMPOSTRIB = ITEMPROIMPOS.CDIMPOSTO));
            END IF;
         END IF;
      ELSE
         IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (V_ICMS = 'S') THEN
            UPDATE ITEMPROIMPOS
            SET VRCONTITIMP = TRUNC((C_ITEM.VRCONTITEM- V_VRREDUCAO),2)
            WHERE (NRLANCTONF   = P_LANCTONF)         AND
                  (CDFILIAL     = P_FILIAL)           AND
                  (NRSEQITPROD  = C_ITEM.NRSEQITPROD) AND
                  (CDIMPOSTO    = C_ITEM.CDIMPOSTO)   AND
                  (NRITPROIMPOS = w_1)                AND
                  (NOT EXISTS(SELECT CDIMPOSTO
                              FROM IMPOSTO
                              WHERE CDIMPOSTRIB = ITEMPROIMPOS.CDIMPOSTO));
         ELSE
            UPDATE ITEMPROIMPOS
            SET VRCONTITIMP = ROUND((C_ITEM.VRCONTITEM - V_VRREDUCAO),2)
            WHERE (NRLANCTONF   = P_LANCTONF)         AND
                  (CDFILIAL     = P_FILIAL)           AND
                  (NRSEQITPROD  = C_ITEM.NRSEQITPROD) AND
                  (CDIMPOSTO    = C_ITEM.CDIMPOSTO)   AND
                  (NRITPROIMPOS = w_1)                AND
                  (NOT EXISTS(SELECT CDIMPOSTO
                              FROM IMPOSTO
                              WHERE CDIMPOSTRIB = ITEMPROIMPOS.CDIMPOSTO));
         END IF;
      END IF;

      IF (C_ITEM.VRBRUTITEM > 0) THEN
         IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (V_ICMS = 'S') THEN
            UPDATE ITEMPROIMPOS
            SET VRCONTITIMP = TRUNC(C_ITEM.VRBRUTITEM,2)
            WHERE (NRLANCTONF   = P_LANCTONF)         AND
                  (CDFILIAL     = P_FILIAL)           AND
                  (NRSEQITPROD  = C_ITEM.NRSEQITPROD) AND
                  (CDIMPOSTO    = C_ITEM.CDIMPOSTO)   AND
                  (NRITPROIMPOS = w_1)                AND
                  (EXISTS(SELECT CDIMPOSTO
                          FROM IMPOSTO
                          WHERE CDIMPOSTRIB = ITEMPROIMPOS.CDIMPOSTO));
         ELSE
            UPDATE ITEMPROIMPOS
            SET VRCONTITIMP = ROUND(C_ITEM.VRBRUTITEM,2)
            WHERE (NRLANCTONF   = P_LANCTONF)         AND
                  (CDFILIAL     = P_FILIAL)           AND
                  (NRSEQITPROD  = C_ITEM.NRSEQITPROD) AND
                  (CDIMPOSTO    = C_ITEM.CDIMPOSTO)   AND
                  (NRITPROIMPOS = w_1)                AND
                  (EXISTS(SELECT CDIMPOSTO
                          FROM IMPOSTO
                          WHERE CDIMPOSTRIB = ITEMPROIMPOS.CDIMPOSTO));
         END IF;
      END IF;   

   END LOOP;

   ARREDONDA_BASECALC(w_S, P_FILIAL, P_LANCTONF);

   V_SEQUIMPOSTNF := w_01;

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

   /*ESTE UPDATE ESTA SENDO REALIZADO PARA EVITAR QUE EXISTAM LANCAMENTOS COM BASE DE CALCULO E SEM IMPOSTO E SEM ALIQUOTA*/
   UPDATE ITEMPROIMPOS
      SET VRBASECALCIT = 0
    WHERE CDFILIAL     = P_FILIAL
      AND NRLANCTONF   = P_LANCTONF
      AND NRITPROIMPOS = W_1
      AND CDFISCALIT   = W_1
      AND VRALIQITEM   = 0.00
      AND VRIMPOSTOIT  = 0.00;

   /* GERANDO INFORMACOES NA TABELA IMPOSTONF */
   IF V_NRDECITOTANF = 0 THEN
      IF V_IDOPERDEVONF = W_S THEN
         FOR C_IMPOSTONF IN (SELECT IT.CDIMPOSTO, 
                                    VRALIQITEM, 
                                    VRPERREDBCIT, 
                                    VRPARDEDIT, 
                                    CDFISCALIT,
                                    CDSITUTRIBIT, 
                                    CDFISCOPERIT, 
                                    CDSUFXCFOPIT, 
                                    IDTRIMPSTII, 
                                    IT.VRADICALIQFECP,
                                    SUM(VRCONTITIMP) AS VRCONTITIMP,
                                    SUM(VRBASECALCIT) AS VRBASECALCIT, 
                                    SUM(VRIMPOSTOIT) AS VRIMPOSTOIT,
                                    MAX(NRITPROIMPOS) AS NRITPROIMPOS,
                                    SUM(VRBCICMSSTRETIDO) VRBCICMSSTRETIDO, 
                                    SUM(VRICMSSTRETIDO) VRICMSSTRETIDO,
                                    SUM(IT.VRADICFECP) AS VRADICFECP,
                                    NVL(IDDIFALIQCUSPRI, 'N') AS IDDIFALIQCUSPRI,
                                    SUM(VRIMPOPARTDEST) AS VRIMPOPARTDEST
                               FROM ITEMPROIMPOS IT, IMPOSTO I
                              WHERE (CDFILIAL = P_FILIAL)    
                                AND (NRLANCTONF = P_LANCTONF)  
                                AND (IT.CDIMPOSTO = I.CDIMPOSTO) 
                                AND (((CDFISCALIT = w_1) AND (IDIMPORECUP = w_S)) OR ((IDIMPORECUP <> w_S) AND (VRALIQITEM <> 0)))
                              GROUP BY IT.CDIMPOSTO, 
                                    VRALIQITEM, 
                                    VRPERREDBCIT, 
                                    VRPARDEDIT, 
                                    CDFISCALIT,
                                    CDSITUTRIBIT, 
                                    CDFISCOPERIT, 
                                    CDSUFXCFOPIT, 
                                    IDTRIMPSTII,
                                    IT.VRADICALIQFECP,
                                    IDDIFALIQCUSPRI
                              UNION
                             SELECT IT.CDIMPOSTO, 
                                    0 AS VRALIQITEM, 
                                    0 AS VRPERREDBCIT, 
                                    0 AS VRPARDEDIT, 
                                    CDFISCALIT,
                                    CDSITUTRIBIT, 
                                    CDFISCOPERIT, 
                                    CDSUFXCFOPIT, 
                                    IDTRIMPSTII, 
                                    IT.VRADICALIQFECP,
                                    SUM(VRCONTITIMP) AS VRCONTITIMP,
                                    0 AS VRBASECALCIT, 
                                    0 AS VRIMPOSTOIT,
                                    MAX(NRITPROIMPOS) AS NRITPROIMPOS,
                                    SUM(VRBCICMSSTRETIDO) VRBCICMSSTRETIDO, 
                                    SUM(VRICMSSTRETIDO) VRICMSSTRETIDO,
                                    SUM(IT.VRADICFECP) AS VRADICFECP,
                                    NVL(IDDIFALIQCUSPRI, 'N') AS IDDIFALIQCUSPRI,
                                    SUM(VRIMPOPARTDEST) AS VRIMPOPARTDEST
                               FROM ITEMPROIMPOS IT, IMPOSTO I
                              WHERE (CDFILIAL = P_FILIAL)
                                AND (NRLANCTONF = P_LANCTONF)
                                AND (IT.CDIMPOSTO = I.CDIMPOSTO) 
                                AND (NRITPROIMPOS <> w_3)
                                AND (((CDFISCALIT <> w_1) AND (IDIMPORECUP = w_S)) OR ((IDIMPORECUP <> w_S) AND (VRALIQITEM = 0)))
                              GROUP BY IT.CDIMPOSTO, 
                                    CDFISCALIT, 
                                    CDSITUTRIBIT,
                                    CDFISCOPERIT, 
                                    CDSUFXCFOPIT, 
                                    IDTRIMPSTII, 
                                    IT.VRADICALIQFECP,
                                    IDDIFALIQCUSPRI
                              UNION
                             SELECT IT.CDIMPOSTO, 
                                    VRALIQITEM, 
                                    VRPERREDBCIT, 
                                    VRPARDEDIT, 
                                    CDFISCALIT,
                                    CDSITUTRIBIT, 
                                    CDFISCOPERIT, 
                                    CDSUFXCFOPIT, 
                                    IDTRIMPSTII, 
                                    IT.VRADICALIQFECP,
                                    SUM(VRCONTITIMP) AS VRCONTITIMP,
                                    SUM(VRBASECALCIT) AS VRBASECALCIT, 
                                    SUM(VRIMPOSTOIT) AS VRIMPOSTOIT,
                                    MAX(NRITPROIMPOS) AS NRITPROIMPOS,
                                    SUM(VRBCICMSSTRETIDO) VRBCICMSSTRETIDO, 
                                    SUM(VRICMSSTRETIDO) VRICMSSTRETIDO,
                                    SUM(IT.VRADICFECP) AS VRADICFECP,
                                    NVL(IDDIFALIQCUSPRI, 'N') AS IDDIFALIQCUSPRI,
                                    SUM(VRIMPOPARTDEST) AS VRIMPOPARTDEST
                               FROM ITEMPROIMPOS IT, IMPOSTO I
                              WHERE (CDFILIAL = P_FILIAL)
                                AND (NRLANCTONF = P_LANCTONF)  
                                AND (IT.CDIMPOSTO = I.CDIMPOSTO) 
                                AND (NRITPROIMPOS = w_3)
                              GROUP BY IT.CDIMPOSTO, 
                                    VRALIQITEM, 
                                    VRPERREDBCIT, 
                                    VRPARDEDIT, 
                                    CDFISCALIT,
                                    CDSITUTRIBIT, 
                                    CDFISCOPERIT, 
                                    CDSUFXCFOPIT, 
                                    IDTRIMPSTII,
                                    IT.VRADICALIQFECP,
                                    IDDIFALIQCUSPRI) 
         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_IMPOSTONF.CDIMPOSTO)
            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, CDSITUTRIBNF,
                  CDFISCOPERNF, CDSUFXCFOPNF, IDIMPOSTONF, VRBCICMSSTRETIDO, 
                  VRICMSSTRETIDO, IDTRIMPOSTNF, IDDIFALIQCUSPRN, VRADICALIQFECP, 
                  VRADICFECP, VRIMPOPARTDEST)
               VALUES(
                  P_FILIAL, P_LANCTONF, C_IMPOSTONF.CDIMPOSTO, V_SEQUIMPOSTNF, 
                  C_IMPOSTONF.VRCONTITIMP, C_IMPOSTONF.VRPERREDBCIT, C_IMPOSTONF.VRBASECALCIT, C_IMPOSTONF.VRALIQITEM, 
                  C_IMPOSTONF.VRPARDEDIT, TRUNC(C_IMPOSTONF.VRIMPOSTOIT,0), C_IMPOSTONF.CDFISCALIT, C_IMPOSTONF.CDSITUTRIBIT,
                  C_IMPOSTONF.CDFISCOPERIT, C_IMPOSTONF.CDSUFXCFOPIT, C_IMPOSTONF.NRITPROIMPOS, C_IMPOSTONF.VRBCICMSSTRETIDO, 
                  C_IMPOSTONF.VRICMSSTRETIDO, C_IMPOSTONF.IDTRIMPSTII, C_IMPOSTONF.IDDIFALIQCUSPRI, C_IMPOSTONF.VRADICALIQFECP, 
                  C_IMPOSTONF.VRADICFECP, C_IMPOSTONF.VRIMPOPARTDEST);
            ELSE
               INSERT INTO IMPOSTONF(
                  CDFILIAL, NRLANCTONF, CDIMPOSTO, NRIMPOSNF, 
                  VRCONTABILNF, VRPERREDBCNF, VRBASECALCNF, VRALIQNF, 
                  VRPARDEDNF, VRIMPOSTONF, CDFISCALNF, CDSITUTRIBNF,
                  CDFISCOPERNF, CDSUFXCFOPNF, IDIMPOSTONF, VRBCICMSSTRETIDO, 
                  VRICMSSTRETIDO, IDTRIMPOSTNF, IDDIFALIQCUSPRN, VRADICALIQFECP, 
                  VRADICFECP, VRIMPOPARTDEST)
               VALUES(
                  P_FILIAL, P_LANCTONF, C_IMPOSTONF.CDIMPOSTO, V_SEQUIMPOSTNF, 
                  C_IMPOSTONF.VRCONTITIMP, C_IMPOSTONF.VRPERREDBCIT, C_IMPOSTONF.VRBASECALCIT, C_IMPOSTONF.VRALIQITEM, 
                  C_IMPOSTONF.VRPARDEDIT, ROUND(C_IMPOSTONF.VRIMPOSTOIT,0), C_IMPOSTONF.CDFISCALIT, C_IMPOSTONF.CDSITUTRIBIT,
                  C_IMPOSTONF.CDFISCOPERIT, C_IMPOSTONF.CDSUFXCFOPIT, C_IMPOSTONF.NRITPROIMPOS, C_IMPOSTONF.VRBCICMSSTRETIDO, 
                  C_IMPOSTONF.VRICMSSTRETIDO, C_IMPOSTONF.IDTRIMPSTII, C_IMPOSTONF.IDDIFALIQCUSPRI, C_IMPOSTONF.VRADICALIQFECP, 
                  C_IMPOSTONF.VRADICFECP, C_IMPOSTONF.VRIMPOPARTDEST);
            END IF;

            V_SEQUIMPOSTNF := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_SEQUIMPOSTNF) + 1)),2,0);
         END LOOP;
      ELSE
         FOR C_IMPOSTONF IN (SELECT IT.CDIMPOSTO, 
                                    VRALIQITEM, 
                                    VRPERREDBCIT, 
                                    VRPARDEDIT, 
                                    CDFISCALIT, 
                                    CDSITUTRIBIT,
                                    CDFISCOPERIT, 
                                    CDSUFXCFOPIT, 
                                    IDTRIMPSTII,
                                    IT.VRADICALIQFECP,
                                    SUM(ROUND(VRCONTITIMP,2)) AS VRCONTITIMP, 
                                    SUM(VRBASECALCIT) AS VRBASECALCIT, 
                                    SUM(VRIMPOSTOIT) AS VRIMPOSTOIT,
                                    NRITPROIMPOS, 
                                    SUM(VRBCICMSSTRETIDO) VRBCICMSSTRETIDO,
                                    SUM(IT.VRADICFECP) AS VRADICFECP,
                                    SUM(VRICMSSTRETIDO) VRICMSSTRETIDO,
                                    SUM(VRIMPOPARTDEST)AS VRIMPOPARTDEST
                               FROM ITEMPROIMPOS IT, IMPOSTO I
                              WHERE (CDFILIAL = P_FILIAL)
                                AND (NRLANCTONF = P_LANCTONF)  
                                AND (IT.CDIMPOSTO = I.CDIMPOSTO) 
                                AND (((CDFISCALIT = w_1) AND (IDIMPORECUP = w_S)) OR ((IDIMPORECUP <> w_S) AND (VRALIQITEM <> 0)))
                              GROUP BY IT.CDIMPOSTO, 
                                    VRALIQITEM, 
                                    VRPERREDBCIT, 
                                    VRPARDEDIT, 
                                    CDFISCALIT,
                                    CDSITUTRIBIT, 
                                    CDFISCOPERIT, 
                                    CDSUFXCFOPIT, 
                                    IDTRIMPSTII,
                                    IT.VRADICALIQFECP,
                                    NRITPROIMPOS
                              UNION
                             SELECT IT.CDIMPOSTO, 
                                    0 AS VRALIQITEM, 
                                    0 AS VRPERREDBCIT, 
                                    0 AS VRPARDEDIT, 
                                    CDFISCALIT, 
                                    CDSITUTRIBIT,
                                    CDFISCOPERIT, 
                                    CDSUFXCFOPIT, 
                                    IDTRIMPSTII,
                                    IT.VRADICALIQFECP, 
                                    SUM(ROUND(VRCONTITIMP,2)) AS VRCONTITIMP, 
                                    0 AS VRBASECALCIT, 
                                    0 AS VRIMPOSTOIT,
                                    NRITPROIMPOS, 
                                    SUM(VRBCICMSSTRETIDO) VRBCICMSSTRETIDO, 
                                    SUM(IT.VRADICFECP) AS VRADICFECP,
                                    SUM(VRICMSSTRETIDO) VRICMSSTRETIDO,
                                   SUM(VRIMPOPARTDEST)AS VRIMPOPARTDEST
                               FROM ITEMPROIMPOS IT, IMPOSTO I
                              WHERE (CDFILIAL = P_FILIAL)
                                AND (NRLANCTONF = P_LANCTONF)
                                AND (IT.CDIMPOSTO = I.CDIMPOSTO)
                                AND (((IT.CDFISCALIT <> w_1) AND (IDIMPORECUP = w_S)) OR ((I.IDIMPORECUP <> w_S) AND (VRALIQITEM = 0)))
                              GROUP BY IT.CDIMPOSTO, 
                                    CDFISCALIT, 
                                    CDSITUTRIBIT,
                                    CDFISCOPERIT, 
                                    CDSUFXCFOPIT, 
                                    IDTRIMPSTII,
                                    IT.VRADICALIQFECP,
                                    NRITPROIMPOS) 
         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_IMPOSTONF.CDIMPOSTO)
            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, CDSITUTRIBNF,
                  CDFISCOPERNF, CDSUFXCFOPNF, IDIMPOSTONF, VRBCICMSSTRETIDO, 
                  VRICMSSTRETIDO, IDTRIMPOSTNF, VRADICALIQFECP, VRADICFECP, 
                  VRIMPOPARTDEST)
               VALUES(
                  P_FILIAL, P_LANCTONF, C_IMPOSTONF.CDIMPOSTO, V_SEQUIMPOSTNF, 
                  C_IMPOSTONF.VRCONTITIMP, C_IMPOSTONF.VRPERREDBCIT, C_IMPOSTONF.VRBASECALCIT, C_IMPOSTONF.VRALIQITEM, 
                  C_IMPOSTONF.VRPARDEDIT, TRUNC(C_IMPOSTONF.VRIMPOSTOIT,0), C_IMPOSTONF.CDFISCALIT, C_IMPOSTONF.CDSITUTRIBIT,
                  C_IMPOSTONF.CDFISCOPERIT, C_IMPOSTONF.CDSUFXCFOPIT, C_IMPOSTONF.NRITPROIMPOS, C_IMPOSTONF.VRBCICMSSTRETIDO, 
                  C_IMPOSTONF.VRICMSSTRETIDO, C_IMPOSTONF.IDTRIMPSTII, C_IMPOSTONF.VRADICALIQFECP, C_IMPOSTONF.VRADICFECP,
                  C_IMPOSTONF.VRIMPOPARTDEST);
            ELSE
               INSERT INTO IMPOSTONF(
                  CDFILIAL, NRLANCTONF, CDIMPOSTO, NRIMPOSNF, 
                  VRCONTABILNF, VRPERREDBCNF, VRBASECALCNF, VRALIQNF, 
                  VRPARDEDNF, VRIMPOSTONF, CDFISCALNF, CDSITUTRIBNF,
                  CDFISCOPERNF, CDSUFXCFOPNF, IDIMPOSTONF, VRBCICMSSTRETIDO, 
                  VRICMSSTRETIDO, IDTRIMPOSTNF, VRADICALIQFECP, VRADICFECP, 
                  VRIMPOPARTDEST)
               VALUES(
                  P_FILIAL, P_LANCTONF, C_IMPOSTONF.CDIMPOSTO, V_SEQUIMPOSTNF, 
                  C_IMPOSTONF.VRCONTITIMP, C_IMPOSTONF.VRPERREDBCIT, C_IMPOSTONF.VRBASECALCIT, C_IMPOSTONF.VRALIQITEM, 
                  C_IMPOSTONF.VRPARDEDIT, ROUND(C_IMPOSTONF.VRIMPOSTOIT,0), C_IMPOSTONF.CDFISCALIT, C_IMPOSTONF.CDSITUTRIBIT,
                  C_IMPOSTONF.CDFISCOPERIT, C_IMPOSTONF.CDSUFXCFOPIT, C_IMPOSTONF.NRITPROIMPOS, C_IMPOSTONF.VRBCICMSSTRETIDO, 
                  C_IMPOSTONF.VRICMSSTRETIDO, C_IMPOSTONF.IDTRIMPSTII, C_IMPOSTONF.VRADICALIQFECP, C_IMPOSTONF.VRADICFECP,
                  C_IMPOSTONF.VRIMPOPARTDEST);
            END IF;

            V_SEQUIMPOSTNF := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_SEQUIMPOSTNF) + 1)),2,0);
         END LOOP;
      END IF;
   ELSE
      IF V_IDOPERDEVONF = w_S THEN
         FOR C_IMPOSTONF IN (SELECT IT.CDIMPOSTO, 
                                    VRALIQITEM, 
                                    VRPERREDBCIT, 
                                    VRPARDEDIT, 
                                    CDFISCALIT, 
                                    CDSITUTRIBIT,
                                    CDFISCOPERIT, 
                                    CDSUFXCFOPIT, 
                                    IDTRIMPSTII, 
                                    IT.VRADICALIQFECP,
                                    SUM(VRCONTITIMP) AS VRCONTITIMP, 
                                    SUM(VRBASECALCIT) AS VRBASECALCIT, 
                                    SUM(VRIMPOSTOIT) AS VRIMPOSTOIT,
                                    MAX(NRITPROIMPOS) AS NRITPROIMPOS, 
                                    SUM(VRBCICMSSTRETIDO) VRBCICMSSTRETIDO, 
                                    SUM(VRICMSSTRETIDO) VRICMSSTRETIDO,
                                    SUM(IT.VRADICFECP) AS VRADICFECP,
                                    NVL(IDDIFALIQCUSPRI, 'N') AS IDDIFALIQCUSPRI,
                                    SUM(VRIMPOPARTDEST) AS VRIMPOPARTDEST
                               FROM ITEMPROIMPOS IT, IMPOSTO I
                              WHERE (CDFILIAL = P_FILIAL)
                                AND (NRLANCTONF = P_LANCTONF)
                                AND (IT.CDIMPOSTO = I.CDIMPOSTO)
                                AND (((CDFISCALIT = w_1) AND (IDIMPORECUP = w_S)) OR ((IDIMPORECUP <> w_S) AND (VRALIQITEM <> 0)))
                              GROUP BY IT.CDIMPOSTO, 
                                    VRALIQITEM, 
                                    VRPERREDBCIT, 
                                    VRPARDEDIT, 
                                    CDFISCALIT,
                                    CDSITUTRIBIT, 
                                    CDFISCOPERIT, 
                                    CDSUFXCFOPIT, 
                                    IDTRIMPSTII, 
                                    IT.VRADICALIQFECP,
                                    IDDIFALIQCUSPRI
                              UNION
                             SELECT IT.CDIMPOSTO, 
                                    0 AS VRALIQITEM, 
                                    0 AS VRPERREDBCIT, 
                                    0 AS VRPARDEDIT, 
                                    CDFISCALIT, 
                                    CDSITUTRIBIT,
                                    CDFISCOPERIT, 
                                    CDSUFXCFOPIT, 
                                    IDTRIMPSTII, 
                                    IT.VRADICALIQFECP,
                                    SUM(VRCONTITIMP) AS VRCONTITIMP, 
                                    0 AS VRBASECALCIT, 
                                    0 AS VRIMPOSTOIT,
                                    MAX(NRITPROIMPOS) AS NRITPROIMPOS, 
                                    SUM(VRBCICMSSTRETIDO) VRBCICMSSTRETIDO, 
                                    SUM(VRICMSSTRETIDO) VRICMSSTRETIDO,
                                    SUM(IT.VRADICFECP) AS VRADICFECP,
                                    NVL(IDDIFALIQCUSPRI, 'N') AS IDDIFALIQCUSPRI,
                                    SUM(VRIMPOPARTDEST) AS VRIMPOPARTDEST
                               FROM ITEMPROIMPOS IT, IMPOSTO I
                              WHERE (CDFILIAL = P_FILIAL)
                                AND (NRLANCTONF = P_LANCTONF)
                                AND (IT.CDIMPOSTO = I.CDIMPOSTO)
                                AND (NRITPROIMPOS <> w_3)
                                AND (((CDFISCALIT <> w_1) AND (IDIMPORECUP = w_S)) OR ((IDIMPORECUP  <> w_S) AND (VRALIQITEM = 0)))
                              GROUP BY IT.CDIMPOSTO, 
                                    CDFISCALIT, 
                                    CDSITUTRIBIT,
                                    CDFISCOPERIT, 
                                    CDSUFXCFOPIT, 
                                    IDTRIMPSTII, 
                                    IT.VRADICALIQFECP,
                                    IDDIFALIQCUSPRI
                              UNION
                             SELECT IT.CDIMPOSTO, 
                                    VRALIQITEM, 
                                    VRPERREDBCIT, 
                                    VRPARDEDIT, 
                                    CDFISCALIT, 
                                    CDSITUTRIBIT,
                                    CDFISCOPERIT, 
                                    CDSUFXCFOPIT, 
                                    IDTRIMPSTII, 
                                    IT.VRADICALIQFECP,
                                    SUM(VRCONTITIMP) AS VRCONTITIMP, 
                                    SUM(VRBASECALCIT) AS VRBASECALCIT, 
                                    SUM(VRIMPOSTOIT) AS VRIMPOSTOIT,
                                    MAX(NRITPROIMPOS) AS NRITPROIMPOS, 
                                    SUM(VRBCICMSSTRETIDO) VRBCICMSSTRETIDO, 
                                    SUM(VRICMSSTRETIDO) VRICMSSTRETIDO,
                                    SUM(IT.VRADICFECP) AS VRADICFECP,
                                    NVL(IDDIFALIQCUSPRI, 'N') AS IDDIFALIQCUSPRI,
                                    SUM(VRIMPOPARTDEST) AS VRIMPOPARTDEST
                               FROM ITEMPROIMPOS IT, IMPOSTO I
                              WHERE (CDFILIAL = P_FILIAL)
                                AND (NRLANCTONF = P_LANCTONF)
                                AND (IT.CDIMPOSTO = I.CDIMPOSTO)
                                AND (NRITPROIMPOS = w_3)
                              GROUP BY IT.CDIMPOSTO, 
                                    VRALIQITEM, 
                                    VRPERREDBCIT, 
                                    VRPARDEDIT, 
                                    CDFISCALIT,
                                    CDSITUTRIBIT, 
                                    CDFISCOPERIT, 
                                    CDSUFXCFOPIT, 
                                    IDTRIMPSTII, 
                                    IT.VRADICALIQFECP,
                                    IDDIFALIQCUSPRI) 
         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_IMPOSTONF.CDIMPOSTO)
            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, CDSITUTRIBNF,
                  CDFISCOPERNF, CDSUFXCFOPNF, IDIMPOSTONF, VRBCICMSSTRETIDO, 
                  VRICMSSTRETIDO, IDTRIMPOSTNF, IDDIFALIQCUSPRN, VRADICALIQFECP, 
                  VRADICFECP, VRIMPOPARTDEST)
               VALUES(
                  P_FILIAL, P_LANCTONF, C_IMPOSTONF.CDIMPOSTO, V_SEQUIMPOSTNF, 
                  TRUNC(C_IMPOSTONF.VRCONTITIMP, V_NRDECITOTANF), C_IMPOSTONF.VRPERREDBCIT, C_IMPOSTONF.VRBASECALCIT, C_IMPOSTONF.VRALIQITEM, 
                  C_IMPOSTONF.VRPARDEDIT, TRUNC(C_IMPOSTONF.VRIMPOSTOIT, V_NRDECITOTANF), C_IMPOSTONF.CDFISCALIT, C_IMPOSTONF.CDSITUTRIBIT,
                  C_IMPOSTONF.CDFISCOPERIT, C_IMPOSTONF.CDSUFXCFOPIT, C_IMPOSTONF.NRITPROIMPOS, C_IMPOSTONF.VRBCICMSSTRETIDO, 
                  C_IMPOSTONF.VRICMSSTRETIDO, C_IMPOSTONF.IDTRIMPSTII, C_IMPOSTONF.IDDIFALIQCUSPRI, C_IMPOSTONF.VRADICALIQFECP, 
                  C_IMPOSTONF.VRADICFECP, C_IMPOSTONF.VRIMPOPARTDEST);
            ELSE
               INSERT INTO IMPOSTONF(
                  CDFILIAL, NRLANCTONF, CDIMPOSTO, NRIMPOSNF, 
                  VRCONTABILNF, VRPERREDBCNF, VRBASECALCNF, VRALIQNF, 
                  VRPARDEDNF, VRIMPOSTONF, CDFISCALNF, CDSITUTRIBNF,
                  CDFISCOPERNF, CDSUFXCFOPNF, IDIMPOSTONF, VRBCICMSSTRETIDO, 
                  VRICMSSTRETIDO, IDTRIMPOSTNF, IDDIFALIQCUSPRN, VRADICALIQFECP, 
                  VRADICFECP, VRIMPOPARTDEST)
               VALUES(
                  P_FILIAL, P_LANCTONF, C_IMPOSTONF.CDIMPOSTO, V_SEQUIMPOSTNF, 
                  ROUND(C_IMPOSTONF.VRCONTITIMP, V_NRDECITOTANF), C_IMPOSTONF.VRPERREDBCIT, C_IMPOSTONF.VRBASECALCIT, C_IMPOSTONF.VRALIQITEM, 
                  C_IMPOSTONF.VRPARDEDIT, ROUND(C_IMPOSTONF.VRIMPOSTOIT, V_NRDECITOTANF), C_IMPOSTONF.CDFISCALIT, C_IMPOSTONF.CDSITUTRIBIT,
                  C_IMPOSTONF.CDFISCOPERIT, C_IMPOSTONF.CDSUFXCFOPIT, C_IMPOSTONF.NRITPROIMPOS, C_IMPOSTONF.VRBCICMSSTRETIDO, 
                  C_IMPOSTONF.VRICMSSTRETIDO, C_IMPOSTONF.IDTRIMPSTII, C_IMPOSTONF.IDDIFALIQCUSPRI, C_IMPOSTONF.VRADICALIQFECP, 
                  C_IMPOSTONF.VRADICFECP, C_IMPOSTONF.VRIMPOPARTDEST);
            END IF;

            V_SEQUIMPOSTNF := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_SEQUIMPOSTNF) + 1)),2,0);
         END LOOP;
      ELSE
         FOR C_IMPOSTONF IN (SELECT IT.CDIMPOSTO, 
                                    VRALIQITEM, 
                                    VRPERREDBCIT, 
                                    VRPARDEDIT, 
                                    CDFISCALIT, 
                                    CDSITUTRIBIT,
                                    CDFISCOPERIT, 
                                    CDSUFXCFOPIT, 
                                    IDTRIMPSTII, 
                                    IT.VRADICALIQFECP,
                                    SUM(ROUND(VRCONTITIMP,2)) AS VRCONTITIMP,
                                    SUM(VRBASECALCIT) AS VRBASECALCIT, 
                                    SUM(VRIMPOSTOIT) AS VRIMPOSTOIT,
                                    NRITPROIMPOS, 
                                    SUM(VRBCICMSSTRETIDO) VRBCICMSSTRETIDO, 
                                    SUM(IT.VRADICFECP) AS VRADICFECP,
                                    SUM(VRICMSSTRETIDO) VRICMSSTRETIDO,
                                    SUM(VRIMPOPARTDEST) AS VRIMPOPARTDEST
                               FROM ITEMPROIMPOS IT, IMPOSTO I
                              WHERE (CDFILIAL = P_FILIAL)
                                AND (NRLANCTONF = P_LANCTONF)
                                AND (IT.CDIMPOSTO = I.CDIMPOSTO)
                                AND (((CDFISCALIT = w_1) AND (IDIMPORECUP = w_S)) OR ((IDIMPORECUP <> w_S) AND (VRALIQITEM <> 0)))
                              GROUP BY IT.CDIMPOSTO, 
                                    VRALIQITEM, 
                                    VRPERREDBCIT, 
                                    VRPARDEDIT, 
                                    CDFISCALIT,
                                    CDSITUTRIBIT, 
                                    CDFISCOPERIT, 
                                    CDSUFXCFOPIT, 
                                    IDTRIMPSTII, 
                                    IT.VRADICALIQFECP,
                                    NRITPROIMPOS
                              UNION
                             SELECT IT.CDIMPOSTO, 
                                    0 AS VRALIQITEM, 
                                    0 AS VRPERREDBCIT, 
                                    0 AS VRPARDEDIT, 
                                    CDFISCALIT, 
                                    CDSITUTRIBIT,
                                    CDFISCOPERIT, 
                                    CDSUFXCFOPIT, 
                                    IDTRIMPSTII, 
                                    IT.VRADICALIQFECP,
                                    SUM(ROUND(VRCONTITIMP,2)) AS VRCONTITIMP, 
                                    0 AS VRBASECALCIT, 
                                    0 AS VRIMPOSTOIT,
                                    NRITPROIMPOS, 
                                    SUM(VRBCICMSSTRETIDO) VRBCICMSSTRETIDO, 
                                    SUM(IT.VRADICFECP) AS VRADICFECP,
                                    SUM(VRICMSSTRETIDO) VRICMSSTRETIDO,
                                    SUM(VRIMPOPARTDEST) AS VRIMPOPARTDEST
                               FROM ITEMPROIMPOS IT, IMPOSTO I
                              WHERE (CDFILIAL = P_FILIAL)
                                AND (NRLANCTONF = P_LANCTONF)
                                AND (IT.CDIMPOSTO = I.CDIMPOSTO)
                                AND (((IT.CDFISCALIT <> w_1) AND (IDIMPORECUP = w_S)) OR ((I.IDIMPORECUP  <> w_S) AND (VRALIQITEM = 0)))
                              GROUP BY IT.CDIMPOSTO, 
                                    CDFISCALIT, 
                                    CDSITUTRIBIT,
                                    CDFISCOPERIT, 
                                    CDSUFXCFOPIT, 
                                    IDTRIMPSTII, 
                                    IT.VRADICALIQFECP,
                                    NRITPROIMPOS) 
         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_IMPOSTONF.CDIMPOSTO)
            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, CDSITUTRIBNF,
                  CDFISCOPERNF, CDSUFXCFOPNF, IDIMPOSTONF, VRBCICMSSTRETIDO, 
                  VRICMSSTRETIDO, IDTRIMPOSTNF, VRADICALIQFECP, VRADICFECP,
                  VRIMPOPARTDEST)
               VALUES(
                  P_FILIAL, P_LANCTONF, C_IMPOSTONF.CDIMPOSTO, V_SEQUIMPOSTNF, 
                  C_IMPOSTONF.VRCONTITIMP, C_IMPOSTONF.VRPERREDBCIT, C_IMPOSTONF.VRBASECALCIT, C_IMPOSTONF.VRALIQITEM, 
                  C_IMPOSTONF.VRPARDEDIT, TRUNC(C_IMPOSTONF.VRIMPOSTOIT, V_NRDECITOTANF), C_IMPOSTONF.CDFISCALIT, C_IMPOSTONF.CDSITUTRIBIT, 
                  C_IMPOSTONF.CDFISCOPERIT, C_IMPOSTONF.CDSUFXCFOPIT, C_IMPOSTONF.NRITPROIMPOS, C_IMPOSTONF.VRBCICMSSTRETIDO, 
                  C_IMPOSTONF.VRICMSSTRETIDO, C_IMPOSTONF.IDTRIMPSTII, C_IMPOSTONF.VRADICALIQFECP, C_IMPOSTONF.VRADICFECP, 
                  C_IMPOSTONF.VRIMPOPARTDEST);
            ELSE
               INSERT INTO IMPOSTONF(
                  CDFILIAL, NRLANCTONF, CDIMPOSTO, NRIMPOSNF, 
                  VRCONTABILNF, VRPERREDBCNF, VRBASECALCNF, VRALIQNF, 
                  VRPARDEDNF, VRIMPOSTONF, CDFISCALNF, CDSITUTRIBNF,
                  CDFISCOPERNF, CDSUFXCFOPNF, IDIMPOSTONF, VRBCICMSSTRETIDO, 
                  VRICMSSTRETIDO, IDTRIMPOSTNF, VRADICALIQFECP, VRADICFECP, 
                  VRIMPOPARTDEST)
               VALUES(
                  P_FILIAL, P_LANCTONF, C_IMPOSTONF.CDIMPOSTO, V_SEQUIMPOSTNF, 
                  C_IMPOSTONF.VRCONTITIMP, C_IMPOSTONF.VRPERREDBCIT, C_IMPOSTONF.VRBASECALCIT, C_IMPOSTONF.VRALIQITEM, 
                  C_IMPOSTONF.VRPARDEDIT, ROUND(C_IMPOSTONF.VRIMPOSTOIT, V_NRDECITOTANF), C_IMPOSTONF.CDFISCALIT, C_IMPOSTONF.CDSITUTRIBIT,
                  C_IMPOSTONF.CDFISCOPERIT, C_IMPOSTONF.CDSUFXCFOPIT, C_IMPOSTONF.NRITPROIMPOS, C_IMPOSTONF.VRBCICMSSTRETIDO, 
                  C_IMPOSTONF.VRICMSSTRETIDO, C_IMPOSTONF.IDTRIMPSTII, C_IMPOSTONF.VRADICALIQFECP, C_IMPOSTONF.VRADICFECP,
                  C_IMPOSTONF.VRIMPOPARTDEST);
            END IF;

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

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

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

      END IF;
   END LOOP;

   FOR C_IMPOSTORETI IN (SELECT N.CDEMPRESA, I.CDIMPOSTO, N.IDTPIJURNF, N.NRINSJURNF, N.DTENTRSAID
                         FROM IMPOSTO I, NOTAFISCAL N, IMPOSTONF IP
                         WHERE N.CDFILIAL   = P_FILIAL      AND
                               N.NRLANCTONF = P_LANCTONF    AND
                               N.CDFILIAL   = IP.CDFILIAL   AND
                               N.NRLANCTONF = IP.NRLANCTONF AND
                               IP.CDIMPOSTO = I.CDIMPOSTO   AND
                               I.IDTRATIMPO   = w_R         AND
                               I.IDUTVRMENSBC = w_S) LOOP
      BASECALC_RETIDO('S', P_FILIAL, P_LANCTONF, C_IMPOSTORETI.IDTPIJURNF, C_IMPOSTORETI.NRINSJURNF,
                         C_IMPOSTORETI.DTENTRSAID, C_IMPOSTORETI.CDIMPOSTO, w_S, C_IMPOSTORETI.CDEMPRESA,
                         P_INSCESTA, V_PAISORIG, V_ESTAORIG, V_PAISDEST, V_ESTADEST, V_CDGRUPOFISC, V_CDGRPFISCSV, P_TIPOOPER);
   END LOOP;

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


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

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

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

   UPDATE NOTAFISCAL
   SET VRNOTAFISC = NVL(V_TOTALNOTA,0),
       VRPRODUTOS = NVL(V_LIQUIDO,0),
       VRDISPNFDEVO = NVL(V_TOTALNOTA,0),
       IDERROS    = w_000
   WHERE CDFILIAL   = P_FILIAL AND
         NRLANCTONF = P_LANCTONF;

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

   SELECT ROUND(NVL(SUM(IT.VRTOTIMPONF),0), V_NRDECITOTANF)
     INTO V_IMPOSRETI
     FROM IMPOSNFTOT IT, IMPOSTO I
    WHERE I.CDIMPOSTO    = IT.CDIMPOSTO
      AND IT.CDFILIAL    = P_FILIAL
      AND IT.NRLANCTONF  = P_LANCTONF
      AND ((I.IDDESCRFONTE <> w_A) AND (I.IDDESCRFONTE <> 'N'))
      AND I.IDTRATIMPO   = w_R;

   V_TOTALNOTA  := V_TOTALNOTA - V_IMPOSRETI;
   P_VRNOTAFISC := V_TOTALNOTA;

   /*
   SELECT NVL(SUM(VRORIGREC),0), MAX(NRLANBOLREC)
   INTO   V_VRCONTAREC,          V_NRLANBOLREC
   FROM CONTARECEBER
   WHERE CDFILIAL   = P_FILIAL AND
         NRLANCTONF = P_LANCTONF;

   IF (V_VRCONTAREC <> V_TOTALNOTA) AND (V_IMPOSRETI > 0) AND
      (V_IDDOCFINANC <> w_L) AND (V_NRLANBOLREC IS NULL) THEN
      APURAC_VENC(P_FILIAL, P_CLIENTE, P_LANCTONF);
   END IF;
   */

   --ATUALIZACAO DO CODIGO FISCAL DA OPERACAO NA TABELA DE NOTA FISCAL

   SELECT MAX(CDCFOPINFUSU), MAX(DSCFOPINFUSU)
     INTO V_CDCFOPINFUSU,    V_DSCFOPINFUSU
     FROM NOTAFISCAL
    WHERE CDFILIAL = P_FILIAL
      AND NRLANCTONF = P_LANCTONF;

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

      IF (V_COUNT > 1) THEN
         UPDATE NOTAFISCAL
         SET CDFISOPENTF = '***'
         WHERE CDFILIAL   = P_FILIAL
           AND NRLANCTONF = P_LANCTONF;
      ELSIF (V_COUNT <= 1) THEN
         UPDATE NOTAFISCAL
            SET CDFISOPENTF = V_CDFISOPENTF
          WHERE (CDFILIAL   = P_FILIAL)
            AND (NRLANCTONF = P_LANCTONF);
      END IF;
   ELSE
      UPDATE NOTAFISCAL
         SET CDFISOPENTF  = V_CDCFOPINFUSU
       WHERE CDFILIAL   = P_FILIAL
         AND NRLANCTONF = P_LANCTONF;

      UPDATE ITEMPRODUTO
         SET CDFISOPEITEM = V_CDCFOPINFUSU
       WHERE CDFILIAL   = P_FILIAL
         AND NRLANCTONF = P_LANCTONF;

      UPDATE ITEMPROIMPOS
         SET CDFISCOPERIT = V_CDCFOPINFUSU
       WHERE CDFILIAL   = P_FILIAL
         AND NRLANCTONF = P_LANCTONF;

      UPDATE IMPOSTONF
         SET CDFISCOPERNF = V_CDCFOPINFUSU
       WHERE CDFILIAL   = P_FILIAL
         AND NRLANCTONF = P_LANCTONF;
   END IF;

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

   UPDATE ITEMPRODUTO
   SET IDAVISOSITEM  = w_00000
   WHERE (CDFILIAL   = P_FILIAL) AND
         (NRLANCTONF = P_LANCTONF);

   UPDATE ITEMPROIMPOS
   SET IDAVISIMPIT   = w_00000,
       IDERROSIMPIT  = w_00000
   WHERE (CDFILIAL   = P_FILIAL) AND
         (NRLANCTONF = P_LANCTONF);


--IDENTIFICADOR DE ERROS E AVISOS
   IF NOT(P_TIPOOPER IN ('09', '10', '12')) THEN /*VALE DE TRANSFERENCIA, SAIDA SEM NOTA, NOTA DE CREDITO/DEBITO*/
      /* (AVISO) ITEM COM CODIGO DA SITUACAO TRIBUTARIA INVALIDO */
      Begin
         SELECT IDERROAVISOFIL
         INTO   V_IDERROAVISO
         FROM ERROAVISONFFIL
         WHERE CDERROAVISOFIL = w_Av09
           AND CDFILIAL = V_CDFILIEMIT;
      Exception
         When No_Data_Found Then
            V_IDERROAVISO := Null;
      End;

      IF V_IDERROAVISO IS NULL THEN
         Begin
            SELECT IDERROAVISO
            INTO   V_IDERROAVISO
            FROM ERROAVISONF
            WHERE CDERROAVISO = w_Av09;
         Exception
            When No_Data_Found Then
               V_IDERROAVISO := Null;
         End;
      END IF;

      UPDATE ITEMPRODUTO
      SET IDAVISOSITEM = w_1 || SUBSTR(IDAVISOSITEM,2,4)
      WHERE (CDFILIAL   = P_FILIAL)   AND
            (NRLANCTONF = P_LANCTONF) AND
            ((CDSITUTRIBPR IS NULL) OR (LENGTH(TRIM(CDSITUTRIBPR)) < 3)) AND
            (V_IDERROAVISO <> w_N) AND
            (V_IDCONSPARFIS <> w_N);

      /* (AVISO) ITEM COM CODIGO FISCAL DE OPERACAO INVALIDO */
      Begin
         SELECT IDERROAVISOFIL
         INTO   V_IDERROAVISO
         FROM ERROAVISONFFIL
         WHERE CDERROAVISOFIL = w_Av10
           AND CDFILIAL = V_CDFILIEMIT;
      Exception
         When No_Data_Found Then
            V_IDERROAVISO := Null;
      End;

      IF V_IDERROAVISO IS NULL THEN
         Begin
            SELECT IDERROAVISO
            INTO   V_IDERROAVISO
            FROM ERROAVISONF
            WHERE CDERROAVISO = w_Av10;
         Exception
            When No_Data_Found Then
               V_IDERROAVISO := Null;
         End;
      END IF;

      UPDATE ITEMPRODUTO
      SET IDAVISOSITEM = SUBSTR(IDAVISOSITEM,1,1) || w_1 || SUBSTR(IDAVISOSITEM,3,3)
      WHERE (CDFILIAL   = P_FILIAL)   AND
            (NRLANCTONF = P_LANCTONF) AND
            ((CDFISOPEITEM IS NULL) OR (LENGTH(CDFISOPEITEM) < 3)) AND
            (V_IDERROAVISO <> w_N) AND
            (V_IDCONSPARFIS <> w_N);

      IF NOT(P_TIPOOPER IN ('07', '12')) THEN
         /* (AVISO) IMPOSTO DO ITEM DA ENTRADA COM CODIGO FISCAL INVALIDO */
         Begin
            SELECT IDERROAVISOFIL
            INTO   V_IDERROAVISO
            FROM ERROAVISONFFIL
            WHERE CDERROAVISOFIL = w_Av04
              AND CDFILIAL = V_CDFILIEMIT;
         Exception
            When No_Data_Found Then
               V_IDERROAVISO := Null;
         End;

         IF V_IDERROAVISO IS NULL THEN
            Begin
               SELECT IDERROAVISO
               INTO   V_IDERROAVISO
               FROM ERROAVISONF
               WHERE CDERROAVISO = w_Av04;
            Exception
               When No_Data_Found Then
                  V_IDERROAVISO := Null;
            End;
         END IF;

         UPDATE ITEMPROIMPOS
         SET IDAVISIMPIT = SUBSTR(IDAVISIMPIT,1,1) || w_1 || SUBSTR(IDAVISIMPIT,3,3)
         WHERE (CDFILIAL   = P_FILIAL)   AND
               (NRLANCTONF = P_LANCTONF) AND
               ((CDFISCALIT IS NULL) OR LENGTH(CDFISCALIT) <> 1) AND
               (V_IDERROAVISO <> w_N);

         /* (AVISO) IMPOSTO DO ITEM COM SITUACAO TRIBUTARIA(CST) INVALIDA */
         Begin
            SELECT IDERROAVISOFIL
            INTO   V_IDERROAVISO
            FROM ERROAVISONFFIL
            WHERE CDERROAVISOFIL = w_Av05
              AND CDFILIAL = V_CDFILIEMIT;
         Exception
            When No_Data_Found Then
               V_IDERROAVISO := Null;
         End;

         IF V_IDERROAVISO IS NULL THEN
            Begin
               SELECT IDERROAVISO
               INTO   V_IDERROAVISO
               FROM ERROAVISONF
               WHERE CDERROAVISO = w_Av05;
            Exception
               When No_Data_Found Then
                  V_IDERROAVISO := Null;
            End;
         END IF;

         UPDATE ITEMPROIMPOS
         SET IDAVISIMPIT = SUBSTR(IDAVISIMPIT,1,2) || w_1 || SUBSTR(IDAVISIMPIT,4,2)
         WHERE (CDFILIAL   = P_FILIAL)   AND
               (NRLANCTONF = P_LANCTONF) AND
               ((CDSITUTRIBIT IS NULL) OR (LENGTH(CDSITUTRIBIT) < 2))AND
               (V_IDERROAVISO <> w_N)    AND
               (V_IDCONSPARFIS <> w_N);

         /* (AVISO) IMPOSTO DO ITEM COM COD. FISCAL OPERACAO - CFOP INVALIDO */
         Begin
            SELECT IDERROAVISOFIL
            INTO   V_IDERROAVISO
            FROM ERROAVISONFFIL
            WHERE CDERROAVISOFIL = w_Av06
              AND CDFILIAL = V_CDFILIEMIT;
         Exception
            When No_Data_Found Then
               V_IDERROAVISO := Null;
         End;

         IF V_IDERROAVISO IS NULL THEN
            Begin
               SELECT IDERROAVISO
               INTO   V_IDERROAVISO
               FROM ERROAVISONF
               WHERE CDERROAVISO = w_Av06;
            Exception
               When No_Data_Found Then
                  V_IDERROAVISO := Null;
            End;
         END IF;

         UPDATE ITEMPROIMPOS
         SET IDAVISIMPIT = SUBSTR(IDAVISIMPIT,1,3) || w_1 || SUBSTR(IDAVISIMPIT,5,1)
         WHERE (CDFILIAL   = P_FILIAL)   AND
               (NRLANCTONF = P_LANCTONF) AND
               ((CDFISCOPERIT IS NULL) OR (LENGTH(CDFISCOPERIT) < 3)) AND
               (V_IDERROAVISO <> w_N)    AND
               (V_IDCONSPARFIS <> w_N);

      END IF;
   END IF;

   SELECT MAX(TO_NUMBER(IDAVISOSITEM))
   INTO   V_ERROAVISO
   FROM ITEMPRODUTO
   WHERE (CDFILIAL   = P_FILIAL) AND
         (NRLANCTONF = P_LANCTONF);

   IF (V_ERROAVISO > 0) THEN
      UPDATE NOTAFISCAL
      SET IDAVISOS = w_1
      WHERE (CDFILIAL   = P_FILIAL) AND
            (NRLANCTONF = P_LANCTONF);
   ELSE
      SELECT MAX(TO_NUMBER(IDAVISIMPIT))
      INTO   V_ERROAVISO
      FROM ITEMPROIMPOS
      WHERE (CDFILIAL   = P_FILIAL) AND
            (NRLANCTONF = P_LANCTONF);

      IF (V_ERROAVISO > 0) THEN
         UPDATE NOTAFISCAL
         SET IDAVISOS = w_1
         WHERE (CDFILIAL   = P_FILIAL) AND
               (NRLANCTONF = P_LANCTONF);
      ELSE
         UPDATE NOTAFISCAL
         SET IDAVISOS = w_0
         WHERE (CDFILIAL   = P_FILIAL) AND
               (NRLANCTONF = P_LANCTONF);
      END IF;
   END IF;

   /*(ERRO) ITEM COM VALOR UNITARIO IGUAL A ZERO*/
   Begin
     SELECT IDERROAVISOFIL
      INTO  V_IDERROAVISO
      FROM ERROAVISONFFIL
      WHERE CDERROAVISOFIL = w_Er04
        AND CDFILIAL = V_CDFILIEMIT;
   Exception
      When No_Data_Found Then
         V_IDERROAVISO := Null;
   End;

   IF V_IDERROAVISO IS NULL THEN
      Begin
        SELECT IDERROAVISO
         INTO  V_IDERROAVISO
         FROM ERROAVISONF
         WHERE CDERROAVISO = w_Er04;
      Exception
         When No_Data_Found Then
            V_IDERROAVISO := Null;
      End;
   END IF;

   IF P_TIPOOPER <> '03' THEN
      UPDATE NOTAFISCAL
      SET IDERROS = w_101
      WHERE CDFILIAL   =  P_FILIAL    AND
            NRLANCTONF =  P_LANCTONF  AND
            V_IDERROAVISO <> w_N      AND
            NRLANCTONF = (SELECT MAX(NRLANCTONF)
                          FROM ITEMPRODUTO
                          WHERE CDFILIAL   =  P_FILIAL   AND
                                NRLANCTONF =  P_LANCTONF AND
                                VRUNITITEM = 0           AND
                                QTITEMPROD > 0);

   END IF;

   IF P_TIPOOPER = w_11 THEN
      Begin
         SELECT IDERROAVISOFIL
         INTO   V_IDERROAVISO
         FROM ERROAVISONFFIL
         WHERE CDERROAVISOFIL = w_Er06
           AND CDFILIAL = V_CDFILIEMIT;
      Exception
         When No_Data_Found Then
            V_IDERROAVISO := Null;
      End;

      IF V_IDERROAVISO IS NULL THEN
         Begin
            SELECT IDERROAVISO
            INTO   V_IDERROAVISO
            FROM ERROAVISONF
            WHERE CDERROAVISO = w_Er06;
         Exception
            When No_Data_Found Then
               V_IDERROAVISO := Null;
         End;
      END IF;
      /* (ERRO) SOMA DAS SAIDAS SEM NOTA FISCAL DIFERE DO VALOR TOTAL DA NOTA */
      UPDATE NOTAFISCAL
      SET IDERROS = w_1||SUBSTR(IDERROS,2,2)
      WHERE CDFILIAL   =  P_FILIAL    AND
            NRLANCTONF =  P_LANCTONF  AND
            V_IDERROAVISO <> w_N      AND
            V_FAIXATOLER < (SELECT ABS(SUM(N.VRNOTAFISC) - NOTAFISCAL.VRNOTAFISC)
                            FROM ITEMNOTAFISC I, NOTAFISCAL N
                            WHERE I.CDFILIAL   = P_FILIAL      AND
                                  I.NRLANCTONF = P_LANCTONF    AND
                                  N.CDFILIAL   = I.CDFILIALIT  AND
                                  N.NRLANCTONF = I.NRLANCTONFIT);
   END IF;

   -- CALCULANDO PESO BRUTO DOS PRODUTOS DA NOTA FISCAL
   BEGIN

      SELECT VRPBRUTOVOLU
      INTO V_VRPESOBRUTO
      FROM NOTAFISCAL
      WHERE CDFILIAL   = P_FILIAL AND
            NRLANCTONF = P_LANCTONF;

   EXCEPTION

      WHEN No_Data_Found THEN
         V_VRPESOBRUTO := Null;

   END;

   IF (V_VRPESOBRUTO IS NULL) OR (V_VRPESOBRUTO = 0) THEN

      BEGIN

         SELECT SUM(QTITEMPROD * PR.VRPESOBRUTPR)
           INTO V_VRPESOBRUTO
           FROM ITEMPRODUTO I, PRODUTO PR
          WHERE I.CDFILIAL    = P_FILIAL
            AND I.NRLANCTONF  = P_LANCTONF
            AND PR.CDPRODUTO  = I.CDPRODUTO;

      EXCEPTION

         WHEN No_Data_Found THEN
            V_VRPESOBRUTO := Null;

      END;

      IF (V_VRPESOBRUTO IS NULL) OR (V_VRPESOBRUTO = 0) THEN

         SELECT SUM(QTITEMPROD * PA.VRPESOUNID * PR.VRFATOCONV)
         INTO   V_VRPESOBRUTO
         FROM ITEMPRODUTO I, PRODUTO PR, PRODUTO PA
         WHERE I.CDFILIAL    = P_FILIAL       AND
               I.NRLANCTONF  = P_LANCTONF     AND
               PR.CDPRODUTO  = I.CDPRODUTO    AND
               PR.CDPRODESTO = PA.CDPRODUTO;

         IF (V_VRPESOBRUTO <> 0) THEN

            UPDATE NOTAFISCAL
            SET VRPBRUTOVOLU = V_VRPESOBRUTO
            WHERE (CDFILIAL   = P_FILIAL)   AND
                  (NRLANCTONF = P_LANCTONF);

         END IF;

      ELSE

         UPDATE NOTAFISCAL
            SET VRPBRUTOVOLU = V_VRPESOBRUTO
          WHERE CDFILIAL   = P_FILIAL
            AND NRLANCTONF = P_LANCTONF;

      END IF;

   END IF;

   -- CALCULANDO PESO LIQUIDO DOS PRODUTOS DA NOTA FISCAL
   BEGIN

      SELECT VRPLIQUVOLU
      INTO V_VRLIQUORIG
      FROM NOTAFISCAL
      WHERE CDFILIAL   = P_FILIAL AND
            NRLANCTONF = P_LANCTONF;

   EXCEPTION

      WHEN No_Data_Found THEN
         V_VRLIQUORIG := Null;

   END;

   IF (V_VRLIQUORIG IS NULL) OR (V_VRLIQUORIG = 0) THEN

      SELECT NVL(IDCALCPESONF,'N')
      INTO   V_IDCALCPESONF
      FROM PARAMGERAL;

      IF(V_IDCALCPESONF = 'S') THEN

         SELECT SUM(I.QTITEMPROD * NVL(P.VRPESOLIQUPR, 0)) VRPLIQUEVOLU
           INTO V_VRLIQUORIG
           FROM ITEMPRODUTO I, PRODUTO P
          WHERE I.CDPRODUTO   = P.CDPRODUTO
            AND I.CDFILIAL    = P_FILIAL
            AND I.NRLANCTONF  = P_LANCTONF;

         IF V_VRLIQUORIG IS NOT NULL AND V_VRLIQUORIG <> 0 THEN

            UPDATE NOTAFISCAL
               SET VRPLIQUVOLU = V_VRLIQUORIG
             WHERE CDFILIAL   = P_FILIAL
               AND NRLANCTONF = P_LANCTONF;

         END IF;

      END IF;

   END IF;

--ATUALIZACAO DO CODIGO FISCAL DA OPERACAO NA TABELA DE NOTA FISCAL

   SELECT COUNT(DISTINCT CDFISOPEITEM), MAX(CDFISOPEITEM)
   INTO   V_COUNT                     , V_CDFISOPENTF
   FROM ITEMPRODUTO
   WHERE (CDFILIAL   = P_FILIAL) AND
         (NRLANCTONF = P_LANCTONF);

   IF (V_COUNT > 1) THEN
      UPDATE NOTAFISCAL
      SET CDFISOPENTF = '***'
      WHERE CDFILIAL   = P_FILIAL   AND
            NRLANCTONF = P_LANCTONF AND
            CDFISOPENTF IS NULL;
   ELSIF (V_COUNT = 1) THEN
      Begin
         SELECT CDFISOPENTF
         INTO   V_CDFISOPENTF
         FROM NOTAFISCAL
         WHERE CDFILIAL   = P_FILIAL AND
               NRLANCTONF = P_LANCTONF;
      Exception
         When No_Data_Found Then
            V_CDFISOPENTF := Null;
      End;

      IF (V_CDFISOPENTF IS NULL) OR (V_CDFISOPENTF = '***') THEN
         UPDATE NOTAFISCAL
         SET (CDFISOPENTF) = (SELECT MAX(CDFISOPEITEM) AS CDFISOPEITEM
                              FROM ITEMPRODUTO
                              WHERE (CDFILIAL   = P_FILIAL) AND
                                    (NRLANCTONF = P_LANCTONF))
         WHERE (CDFILIAL   = P_FILIAL)   AND
               (NRLANCTONF = P_LANCTONF) AND
               (NVL(CDFISOPENTF, '***') = '***');
      ELSE
         UPDATE ITEMPRODUTO
         SET CDFISOPEITEM = V_CDFISOPENTF
         WHERE CDFILIAL   = P_FILIAL   AND
               NRLANCTONF = P_LANCTONF;

         UPDATE ITEMPROIMPOS
         SET CDFISCOPERIT = V_CDFISOPENTF
         WHERE CDFILIAL   = P_FILIAL   AND
               NRLANCTONF = P_LANCTONF;

         UPDATE IMPOSTONF
         SET CDFISCOPERNF = V_CDFISOPENTF
         WHERE CDFILIAL   = P_FILIAL   AND
               NRLANCTONF = P_LANCTONF;
      END IF;
   END IF;

   IF V_CDINTEGRACAO IS NOT NULL THEN
--INCLUSAO DOS ENCARGOS DA NF EM CASO DE IMPORTACAO
      INSERT INTO ITEMENCARGO
      (CDFILIAL, NRLANCTONF, CDENCARGO, VRITEMENCA)
      (SELECT P_FILIAL, P_LANCTONF, CDENCARGO, 0 AS VRITEMENCA
       FROM ENCARGO
       MINUS
       SELECT CDFILIAL, NRLANCTONF, CDENCARGO, 0 AS VRITEMENCA
       FROM ITEMENCARGO
       WHERE CDFILIAL   = P_FILIAL AND
             NRLANCTONF = P_LANCTONF);

      Begin
         SELECT IDERROAVISO
         INTO   V_IDERROAVISO
         FROM ERROAVISONF
         WHERE CDERROAVISO = w_Er03;
      Exception
         When No_Data_Found Then
            V_IDERROAVISO := Null;
      End;

      UPDATE NOTAFISCAL N
      SET IDERROS = w_11||SUBSTR(IDERROS, 3, 1)
      WHERE CDFILIAL   =  P_FILIAL   AND
            NRLANCTONF =  P_LANCTONF AND
            V_IDERROAVISO <> w_N     AND
            V_FAIXATOLER < (SELECT NVL(ABS(NVL(SUM(C.VRORIGREC), (N.VRNOTAFISC - MAX(I.VRIMPOSRETI))) - (N.VRNOTAFISC - MAX(I.VRIMPOSRETI))), V_FAIXATOLER)
                            FROM CONTARECEBER C,
                                 (SELECT NVL(SUM(IT.VRTOTIMPONF),0) AS VRIMPOSRETI
                                  FROM IMPOSNFTOT IT, IMPOSTO I
                                  WHERE I.CDIMPOSTO    = IT.CDIMPOSTO AND
                                        IT.CDFILIAL    = P_FILIAL     AND
                                        IT.NRLANCTONF  = P_LANCTONF   AND
                                        I.IDDESCRFONTE <> w_A         AND
                                        I.IDTRATIMPO   = w_R) I
                            WHERE C.CDFILIAL   = P_FILIAL AND
                                  C.NRLANCTONF = P_LANCTONF);
   END IF;


   /* ESTA ROTINA ABAIXO SERVE PARA ATUALIZAR O VALOR CONTABIL E BRUTO DOS PRODUTOS COM A DIFERENCA
      DE CENTAVOS ENTRE O VALOR DOS IMPOSTOS POR ITEM E A SUA RESPECTIVA TOTALIZACAO. ESTA DIFERENCA
      E IGNORADA NO FECHAMENTO DA NF CASO O CLIENTE TRABALHE COM UM NUMERO MENOR DE CASAS DECIMAIS E
      PROVOCA ERROS NA CONTABILIZACAO*/

   IF (V_NRDECITOTANF <> 2) AND (V_IDOPERDEVONF <> w_S) THEN
      FOR C_ATUAVRCONT IN (SELECT T.CDIMPOSTO, 
                                  SUM(T.VRIMPOSTOIT) AS VRIMPOSTOIT, 
                                  T.CDFISCALIT,
                                  I.IDIMPORECUP,
                                  I.CDCCTBLATIV,
                                  I.CDCCTBLPASS,
                                  I.IDTRATIMPO, 
                                  I.IDTIPCONTAB,
                                  I.IDDESCRFONTE
                             FROM ITEMPROIMPOS T, IMPOSTO I
                            WHERE T.CDFILIAL = P_FILIAL
                              AND T.NRLANCTONF = P_LANCTONF  
                              AND T.NRITPROIMPOS = w_1
                              AND T.CDIMPOSTO = I.CDIMPOSTO
                           GROUP BY T.CDIMPOSTO, 
                                 T.CDFISCALIT, 
                                 I.IDIMPORECUP,
                                 I.CDCCTBLATIV, 
                                 I.CDCCTBLPASS, 
                                 I.IDTRATIMPO, 
                                 I.IDTIPCONTAB, 
                                 I.IDDESCRFONTE) LOOP

         SELECT SUM(VRTOTIMPONF) - C_ATUAVRCONT.VRIMPOSTOIT
         INTO   V_VRDIFERENCA
         FROM IMPOSNFTOT
         WHERE CDFILIAL   = P_FILIAL   AND
               NRLANCTONF = P_LANCTONF AND
               CDIMPOSTO  = C_ATUAVRCONT.CDIMPOSTO;

         SELECT SUM(VRBRUTITEM), SUM(VRCONTITEM)
         INTO   V_VRBRUTO      , V_VRCONTAB
         FROM ITEMPRODUTO I, ITEMPROIMPOS T
         WHERE T.CDFILIAL     = I.CDFILIAL    AND
               T.NRLANCTONF   = I.NRLANCTONF  AND
               T.NRSEQITPROD  = I.NRSEQITPROD AND
               T.CDFILIAL     = P_FILIAL      AND
               T.NRLANCTONF   = P_LANCTONF    AND
               T.NRITPROIMPOS = w_1           AND
               T.CDIMPOSTO    = C_ATUAVRCONT.CDIMPOSTO;

         IF V_VRDIFERENCA <> 0 THEN
            IF (C_ATUAVRCONT.IDTRATIMPO = w_A) THEN
               IF ((C_ATUAVRCONT.IDIMPORECUP = w_S)  AND (C_ATUAVRCONT.CDFISCALIT = w_1)) OR
                  ((C_ATUAVRCONT.IDIMPORECUP <> w_S) AND (C_ATUAVRCONT.CDCCTBLPASS IS NOT NULL)) AND
                  (C_ATUAVRCONT.IDTIPCONTAB = w_D) 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_ATUAVRCONT.CDIMPOSTO)
                  LOOP
                     V_ICMS := 'S';
                  END LOOP;

                  IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (V_ICMS = 'S') THEN
                     UPDATE ITEMPRODUTO
                     SET VRBRUTITEM = TRUNC(VRBRUTITEM + ((V_VRDIFERENCA / V_VRBRUTO)  * VRBRUTITEM),2)
                     WHERE EXISTS(SELECT CDFILIAL, NRLANCTONF, NRSEQITPROD
                                  FROM ITEMPROIMPOS T
                                  WHERE T.CDFILIAL    = P_FILIAL                AND
                                        T.NRLANCTONF  = P_LANCTONF              AND
                                        T.NRSEQITPROD = ITEMPRODUTO.NRSEQITPROD AND
                                        T.CDIMPOSTO   = C_ATUAVRCONT.CDIMPOSTO);
                  ELSE
                     UPDATE ITEMPRODUTO
                     SET VRBRUTITEM = ROUND(VRBRUTITEM + ((V_VRDIFERENCA / V_VRBRUTO)  * VRBRUTITEM),2)
                     WHERE EXISTS(SELECT CDFILIAL, NRLANCTONF, NRSEQITPROD
                                  FROM ITEMPROIMPOS T
                                  WHERE T.CDFILIAL    = P_FILIAL                AND
                                        T.NRLANCTONF  = P_LANCTONF              AND
                                        T.NRSEQITPROD = ITEMPRODUTO.NRSEQITPROD AND
                                        T.CDIMPOSTO   = C_ATUAVRCONT.CDIMPOSTO);
                  END IF;
               ELSE
                  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_ATUAVRCONT.CDIMPOSTO)
                  LOOP
                     V_ICMS := 'S';
                  END LOOP;

                  IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (V_ICMS = 'S') THEN
                     UPDATE ITEMPRODUTO
                     SET VRBRUTITEM = TRUNC(VRBRUTITEM + ((V_VRDIFERENCA / V_VRBRUTO)  * VRBRUTITEM),2),
                         VRCONTITEM = TRUNC(VRCONTITEM + ((V_VRDIFERENCA / V_VRCONTAB) * VRCONTITEM),2)
                     WHERE EXISTS(SELECT CDFILIAL, NRLANCTONF, NRSEQITPROD
                                  FROM ITEMPROIMPOS T
                                  WHERE T.CDFILIAL    = P_FILIAL                AND
                                        T.NRLANCTONF  = P_LANCTONF              AND
                                        T.NRSEQITPROD = ITEMPRODUTO.NRSEQITPROD AND
                                        T.CDIMPOSTO   = C_ATUAVRCONT.CDIMPOSTO);
                  ELSE
                     UPDATE ITEMPRODUTO
                     SET VRBRUTITEM = ROUND(VRBRUTITEM + ((V_VRDIFERENCA / V_VRBRUTO)  * VRBRUTITEM),2),
                         VRCONTITEM = ROUND(VRCONTITEM + ((V_VRDIFERENCA / V_VRCONTAB) * VRCONTITEM),2)
                     WHERE EXISTS(SELECT CDFILIAL, NRLANCTONF, NRSEQITPROD
                                  FROM ITEMPROIMPOS T
                                  WHERE T.CDFILIAL    = P_FILIAL                AND
                                        T.NRLANCTONF  = P_LANCTONF              AND
                                        T.NRSEQITPROD = ITEMPRODUTO.NRSEQITPROD AND
                                        T.CDIMPOSTO   = C_ATUAVRCONT.CDIMPOSTO);
                  END IF;

               END IF;
            ELSIF (C_ATUAVRCONT.IDTRATIMPO = w_D) THEN
               IF ((C_ATUAVRCONT.IDIMPORECUP = w_S) AND (C_ATUAVRCONT.CDFISCALIT = w_1))  OR
                  ((C_ATUAVRCONT.IDIMPORECUP <> w_S) AND (C_ATUAVRCONT.CDCCTBLATIV IS NOT NULL)) AND
                  (C_ATUAVRCONT.IDTIPCONTAB = w_D) 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_ATUAVRCONT.CDIMPOSTO)
                  LOOP
                     V_ICMS := 'S';
                  END LOOP;

                  IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (V_ICMS = 'S') THEN
                     UPDATE ITEMPRODUTO
                     SET VRBRUTITEM = TRUNC(VRBRUTITEM - ((V_VRDIFERENCA / V_VRBRUTO)  * VRBRUTITEM),2)
                     WHERE EXISTS(SELECT CDFILIAL, NRLANCTONF, NRSEQITPROD
                                  FROM ITEMPROIMPOS T
                                  WHERE T.CDFILIAL    = P_FILIAL                AND
                                        T.NRLANCTONF  = P_LANCTONF              AND
                                        T.NRSEQITPROD = ITEMPRODUTO.NRSEQITPROD AND
                                        T.CDIMPOSTO   = C_ATUAVRCONT.CDIMPOSTO);
                  ELSE
                     UPDATE ITEMPRODUTO
                     SET VRBRUTITEM = ROUND(VRBRUTITEM - ((V_VRDIFERENCA / V_VRBRUTO)  * VRBRUTITEM),2)
                     WHERE EXISTS(SELECT CDFILIAL, NRLANCTONF, NRSEQITPROD
                                  FROM ITEMPROIMPOS T
                                  WHERE T.CDFILIAL    = P_FILIAL                AND
                                        T.NRLANCTONF  = P_LANCTONF              AND
                                        T.NRSEQITPROD = ITEMPRODUTO.NRSEQITPROD AND
                                        T.CDIMPOSTO   = C_ATUAVRCONT.CDIMPOSTO);
                  END IF;
               ELSE
                  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_ATUAVRCONT.CDIMPOSTO)
                  LOOP
                     V_ICMS := 'S';
                  END LOOP;

                  IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (V_ICMS = 'S') THEN
                     UPDATE ITEMPRODUTO
                     SET VRBRUTITEM = TRUNC(VRBRUTITEM - ((V_VRDIFERENCA / V_VRBRUTO)  * VRBRUTITEM),2),
                         VRCONTITEM = TRUNC(VRCONTITEM - ((V_VRDIFERENCA / V_VRCONTAB) * VRCONTITEM),2)
                     WHERE EXISTS(SELECT CDFILIAL, NRLANCTONF, NRSEQITPROD
                                  FROM ITEMPROIMPOS T
                                  WHERE T.CDFILIAL    = P_FILIAL                AND
                                        T.NRLANCTONF  = P_LANCTONF              AND
                                        T.NRSEQITPROD = ITEMPRODUTO.NRSEQITPROD AND
                                        T.CDIMPOSTO   = C_ATUAVRCONT.CDIMPOSTO);
                  ELSE
                     UPDATE ITEMPRODUTO
                     SET VRBRUTITEM = ROUND(VRBRUTITEM - ((V_VRDIFERENCA / V_VRBRUTO)  * VRBRUTITEM),2),
                         VRCONTITEM = ROUND(VRCONTITEM - ((V_VRDIFERENCA / V_VRCONTAB) * VRCONTITEM),2)
                     WHERE EXISTS(SELECT CDFILIAL, NRLANCTONF, NRSEQITPROD
                                  FROM ITEMPROIMPOS T
                                  WHERE T.CDFILIAL    = P_FILIAL                AND
                                        T.NRLANCTONF  = P_LANCTONF              AND
                                        T.NRSEQITPROD = ITEMPRODUTO.NRSEQITPROD AND
                                        T.CDIMPOSTO   = C_ATUAVRCONT.CDIMPOSTO);
                  END IF;
               END IF;
            ELSIF (C_ATUAVRCONT.IDTRATIMPO = w_R) THEN
               IF (C_ATUAVRCONT.IDIMPORECUP = w_S) THEN
                  IF (C_ATUAVRCONT.CDCCTBLATIV IS NULL) OR
                     (C_ATUAVRCONT.CDFISCALIT <> w_1) THEN

                     V_IMPOCONTAB := - V_VRIMPOSTO;
                  END IF;
               ELSE
                  IF (C_ATUAVRCONT.CDCCTBLATIV IS NULL) THEN
                     V_IMPOCONTAB := - V_VRIMPOSTO;
                  ELSE
                     IF C_ATUAVRCONT.IDDESCRFONTE = 'N' THEN
                        V_IMPOCONTAB := - V_VRIMPOSTO;
                     END IF;
                  END IF;
               END IF;

               IF (C_ATUAVRCONT.IDTIPCONTAB = w_D) 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_ATUAVRCONT.CDIMPOSTO)
                  LOOP
                     V_ICMS := 'S';
                  END LOOP;

                  IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (V_ICMS = 'S') THEN
                     UPDATE ITEMPRODUTO
                     SET VRCONTITEM = TRUNC(VRCONTITEM + ((V_VRDIFERENCA / V_VRCONTAB) * VRCONTITEM),2)
                     WHERE EXISTS(SELECT CDFILIAL, NRLANCTONF, NRSEQITPROD
                                  FROM ITEMPROIMPOS T
                                  WHERE T.CDFILIAL    = P_FILIAL                AND
                                        T.NRLANCTONF  = P_LANCTONF              AND
                                        T.NRSEQITPROD = ITEMPRODUTO.NRSEQITPROD AND
                                        T.CDIMPOSTO   = C_ATUAVRCONT.CDIMPOSTO);
                  ELSE
                     UPDATE ITEMPRODUTO
                     SET VRCONTITEM = ROUND(VRCONTITEM + ((V_VRDIFERENCA / V_VRCONTAB) * VRCONTITEM),2)
                     WHERE EXISTS(SELECT CDFILIAL, NRLANCTONF, NRSEQITPROD
                                  FROM ITEMPROIMPOS T
                                  WHERE T.CDFILIAL    = P_FILIAL                AND
                                        T.NRLANCTONF  = P_LANCTONF              AND
                                        T.NRSEQITPROD = ITEMPRODUTO.NRSEQITPROD AND
                                        T.CDIMPOSTO   = C_ATUAVRCONT.CDIMPOSTO);
                  END IF;
               END IF;
            END IF;
         END IF;
      END LOOP;
   END IF;


   /*PREENCHENDO A TABELA DADOSADIC DE ACORDO COM OS VALORES DO ADICIONAL DE ALIQUOTA DO FECP*/
   DELETE 
     FROM DADOSADIC
    WHERE CDFILIAL = P_FILIAL
      AND NRLANCTONF = P_LANCTONF
      AND UPPER(DSDADOADIC) LIKE 'ADICIONAL DE ALIQUOTA DO IMPOSTO % DE % (FUNDO ESTADUAL DE COMBATE A POBREZA):%';

   V_STRVRADICALIQFECP := NULL;
   V_STRVRADICFECP := NULL;

   
   /* GRAVA INFORMACOES DO IPI DEVOLVIDO DO PRODUTO */
   FOR C_IPIDEVOL IN (SELECT I.NRSEQITPROD, II.VRIMPOSTOIT, I.DSINFADICPROD
                        FROM ITEMPRODUTO I, ITEMPROIMPOS II,
                             IMPOSTONFE IP, IMPOSTO IM
                       WHERE I.CDFILIAL      = P_FILIAL
                         AND I.NRLANCTONF    = P_LANCTONF
                         AND I.NRSEQITPROD   = II.NRSEQITPROD
                         AND I.CDFILIAL      = II.CDFILIAL
                         AND I.NRLANCTONF    = II.NRLANCTONF
                         AND IP.CDIMPOSTONFE = '10'
                         AND II.CDIMPOSTO    = IM.CDIMPOSTO
                         AND IM.CDIMPOSTONFE = IP.CDIMPOSTONFE
                         AND NVL(I.VRPERDEVOL, 0) > 0)
   LOOP
      V_DSINFADICPROD := C_IPIDEVOL.DSINFADICPROD;
      V_IPIDEVOLMSG   := 'IPI, no valor de R$ '||CASE SUBSTR(LTRIM(TO_CHAR(ROUND(C_IPIDEVOL.VRIMPOSTOIT, 2),'9999999999999.99')),1, 1) WHEN '.' THEN '0'||LTRIM(TO_CHAR(ROUND(C_IPIDEVOL.VRIMPOSTOIT, 2),'9999999999999.99')) ELSE LTRIM(TO_CHAR(ROUND(C_IPIDEVOL.VRIMPOSTOIT, 2),'9999999999999.99')) END;

      IF (C_IPIDEVOL.DSINFADICPROD IS NULL) THEN         
            V_DSINFADICPROD := V_IPIDEVOLMSG;
      ELSE
        IF (NVL(INSTR(V_DSINFADICPROD, V_IPIDEVOLMSG) = 0, TRUE)) THEN
            V_DSINFADICPROD := C_IPIDEVOL.DSINFADICPROD || ' | ' || V_IPIDEVOLMSG;
        END IF;
      END IF;

      UPDATE ITEMPRODUTO
         SET DSINFADICPROD = V_DSINFADICPROD
       WHERE CDFILIAL = P_FILIAL
         AND NRLANCTONF = P_LANCTONF
         AND NRSEQITPROD = C_IPIDEVOL.NRSEQITPROD;
   END LOOP;


   FOR C_VRADICALIQFECP IN (SELECT CASE P.CDIMPOSTONFE WHEN '00' THEN 'ICMS' WHEN '80' THEN 'ICMS-ST' END AS CDIMPOSTONFE, 
                                   I.VRADICALIQFECP, 
                                   SUM(NVL(I.VRADICFECP, 0)) AS VRADICFECP
                              FROM ITEMPROIMPOS I JOIN IMPOSTO P ON (I.CDIMPOSTO = P.CDIMPOSTO)
                             WHERE I.CDFILIAL = P_FILIAL
                               AND I.NRLANCTONF = P_LANCTONF
                               AND NVL(I.VRADICALIQFECP, 0) > 0
                               AND I.NRITPROIMPOS = '1'
                               AND P.CDIMPOSTONFE IS NOT NULL
                               AND NVL(I.VRADICFECP, 0) > 0
                             GROUP BY P.CDIMPOSTONFE, 
                                   I.VRADICALIQFECP)
   LOOP
      SELECT DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(C_VRADICALIQFECP.VRADICALIQFECP, 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(C_VRADICALIQFECP.VRADICALIQFECP, 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(C_VRADICALIQFECP.VRADICALIQFECP, 2), '9999999999999.99'))),
             DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(C_VRADICALIQFECP.VRADICFECP, 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(C_VRADICALIQFECP.VRADICFECP, 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(C_VRADICALIQFECP.VRADICFECP, 2), '9999999999999.99')))
        INTO V_STRVRADICALIQFECP,
             V_STRVRADICFECP
        FROM DUAL;
      INSERT INTO DADOSADIC
         (CDFILIAL, 
          NRLANCTONF, 
          NRDADOADIC, 
          DSDADOADIC)
      VALUES
         (P_FILIAL, 
          P_LANCTONF, 
          V_DADOADIC,
          'Adicional de aliquota do imposto '||C_VRADICALIQFECP.CDIMPOSTONFE||' de '||V_STRVRADICALIQFECP||'% (Fundo Estadual de Combate a Pobreza): R$ '||V_STRVRADICFECP);

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

   -- GRAVANDO OS DADOS DO VENDEDOR NOS DADOS ADICIONAIS
   DELETE
     FROM DADOSADIC
    WHERE CDFILIAL = P_FILIAL
      AND NRLANCTONF = P_LANCTONF
      AND UPPER(DSDADOADIC) LIKE 'VENDEDOR:%';

   IF (V_IDADICVENDEDOR = 'S') THEN
      BEGIN
         SELECT 'VENDEDOR: ' || V.CDVENDEDOR || ' - ' || V.NMRAZSOCVEN
           INTO V_DADOSVENDEDOR
           FROM ITEMPRODUTO I LEFT JOIN PEDIDO P ON (I.CDFILIALPED = P.CDFILIAL)
                                                AND (I.NRPEDIDO = P.NRPEDIDO)
                                   JOIN VENDEDOR V ON (P.CDVENDEDOR = V.CDVENDEDOR)
          WHERE I.CDFILIAL = P_FILIAL
            AND I.NRLANCTONF = P_LANCTONF
            AND ROWNUM = 1;
      EXCEPTION
         WHEN NO_DATA_FOUND THEN BEGIN
            V_DADOSVENDEDOR := NULL;
         END;
      END;

      IF (V_DADOSVENDEDOR IS NOT NULL) OR (V_DADOSVENDEDOR <> '') THEN
         INSERT INTO DADOSADIC
            (CDFILIAL,
             NRLANCTONF,
             NRDADOADIC,
             DSDADOADIC)
         VALUES
            (P_FILIAL,
             P_LANCTONF,
             V_DADOADIC,
             V_DADOSVENDEDOR);

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

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

      /* INSERIDO POR LUCIANA CORREA PARA O SISTEMA DE PDV */
      IF (V_IDSISTEMA <> w_VMN) THEN
         
         BEGIN
            SELECT NRCTRLMOVEST, CDFILIALENTR, NRLANESTENTR
              INTO V_NRCTRLMOVEST, V_CDFILIALENTR, V_NRLANESTENTR
              FROM CTRLMOVIESTQ
             WHERE CDFILIALSAID = P_FILIAL
               AND NRLANESTSAID = P_LANCESTQ;
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_CDFILIALENTR := NULL;
               V_NRCTRLMOVEST := NULL;
               V_NRLANESTENTR := NULL;
         END;
         
         IF V_NRCTRLMOVEST IS NOT NULL THEN
            DELETE 
              FROM CTRLMOVIESTQ
             WHERE CDFILIAL = V_CDFILIEMIT
               AND NRCTRLMOVEST = V_NRCTRLMOVEST;
            
            DELETE 
              FROM ITLANCTOEST
             WHERE CDFILIAL = V_CDFILIALENTR
               AND NRLANCESTQ = V_NRLANESTENTR;

            DELETE 
              FROM LANCTOESTOQ
             WHERE CDFILIAL = V_CDFILIALENTR
               AND NRLANCESTQ = V_NRLANESTENTR;

         END IF;
         
         SELECT COUNT(*)
         INTO   V_COUNT
         FROM LANCTOESTOQ L, NOTAFISCAL N
         WHERE L.CDFILIAL   = P_FILIAL      AND
               L.NRLANCESTQ = P_LANCESTQ    AND
               L.NRLANCTONF = P_LANCTONF    AND
               L.CDFILIAL   = N.CDFILIAL    AND
               L.NRLANCTONF = N.NRLANCTONF;

         IF V_COUNT > 0 THEN

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

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

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

      Begin
         SELECT T.NMTIPOOPER, F.NMFILIAL
         INTO   V_NMTIPOOPER, V_NMFILIRECE
         FROM NOTAFISCAL N, TIPOOPERAC T, FILIAL F
         WHERE
            (N.CDFILIAL     = P_FILIAL)       AND
            (N.NRLANCTONF   = P_LANCTONF)     AND
            (N.CDTIPOOPER   = T.CDTIPOOPER)   AND
            (N.IDENTRSAIDOP = T.IDENTRSAIDOP) AND
            (N.CDFILIRECE   = F.CDFILIAL(+));
      Exception
         When No_Data_Found Then
            V_NMTIPOOPER := Null; V_NMFILIRECE := Null;
      End;

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

      SELECT COUNT(*)
      INTO   V_COUNT
      FROM LANCTOESTOQ L, NOTAFISCAL N
      WHERE L.CDFILIAL   = P_FILIAL      AND
            L.NRLANCESTQ = P_LANCESTQ    AND
            L.NRLANCTONF = P_LANCTONF    AND
            L.CDFILIAL   = N.CDFILIAL    AND
            L.NRLANCTONF = N.NRLANCTONF;

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


      IF (V_IDOPERDEVONF = w_S) THEN
         V_TIPOMOVI := w_5;
      ELSE
         V_TIPOMOVI := w_4;
      END IF;

      IF (V_IDSISTEMA = w_EXP) THEN
         Begin
            SELECT NVL(MAX(IDRETPROEXP),1)
              INTO V_IDRETPROEXP
              FROM PAREXPEDICAO
             WHERE CDFILIAL = V_CDFILIEMIT;
         Exception
            When No_Data_Found Then
               V_IDRETPROEXP := 1;
         End;

      END IF;

      IF (V_IDSISTEMA = w_VND) THEN
         SELECT CDFILIMOVI
         INTO   V_CDFILIMOVI
         FROM LANCTOESTOQ
         WHERE CDFILIAL   = P_FILIAL AND
               NRLANCTONF = P_LANCTONF;
         Begin
            SELECT NVL(IDATUEST,1)
            INTO   V_IDATUEST
            FROM PARAVEND
            WHERE CDFILIAL = V_CDFILIMOVI;
         Exception
            When No_Data_Found Then
               V_IDATUEST := 1;
         End;
      END IF;

      IF ((V_IDSISTEMA = w_EXP) AND (V_IDRETPROEXP = w_2)) OR ((V_IDSISTEMA = w_VND) AND (V_IDATUEST = w_1)) THEN

         FOR C_ITLANCTOEST IN (SELECT NRSEQITPROD,IP.CDPRODUTO,VRUNITITEM,VRTOTAITEM, NVL(CDFILIMOVI, CDFILIEMIT) AS CDFILIMOVI,
                                      QTITEMPROD,CDPRODESTO,VRBRUTITEM,VRDESCITEM,VRCONTITEM,
                                      NVL(IP.CDALMOXARIFE,' ') AS CDALMOXARIFE,
                                      NVL(IP.CDLOCALESTOQ,' ') AS CDLOCALESTOQ,
                                      NVL(NRLOTEESTQ,' ')      AS NRLOTEESTQ,
                                      NVL(NRSUBLOTE,' ')       AS NRSUBLOTE, IDCNTRESTOQ,
                                      IP.NRPEDIDO, IP.NRITEMPED, CDARVPROD, NMPRODUTO,
                                      NVL(IP.IDORIGEMPROD, 'N') AS IDORIGEMPROD,
                                      IP.VRFATCONTRIBXML 
                               FROM ITEMPRODUTO IP, PRODUTO P, PRODFILI PF, NOTAFISCAL N
                               WHERE IP.CDFILIAL    = P_FILIAL     AND
                                     IP.NRLANCTONF  = N.NRLANCTONF AND
                                     IP.CDFILIAL    = N.CDFILIAL   AND
                                     IP.NRLANCTONF  = P_LANCTONF   AND
                                     P.CDPRODUTO    = IP.CDPRODUTO AND
                                     PF.CDFILIAL    = V_CDFILIEMIT AND
                                     PF.CDPRODUTO   = P.CDPRODESTO AND
                                     NVL(IP.IDATUESTPROD, 'S') = 'S') LOOP
            IF (C_ITLANCTOEST.IDCNTRESTOQ = w_S) THEN
               UPDATE ITEMPRODUTO
               SET CDPRODMOVI = C_ITLANCTOEST.CDPRODESTO
               WHERE (CDFILIAL    = P_FILIAL)    AND
                     (NRLANCTONF  = P_LANCTONF ) AND
                     (NRSEQITPROD = C_ITLANCTOEST.NRSEQITPROD);
            END IF;

            IF (V_IDUTILALMOX <> w_S AND  V_IDUTILLCESTQ <> w_S AND V_IDUTILLOTE <> w_S) THEN
               UPDATE ITEMPRODUTO
               SET CDALMOXARIFE  = ' ',
                   CDLOCALESTOQ  = ' ',
                   NRLOTEESTQ    = ' ',
                   NRSUBLOTE     = ' '
               WHERE (CDFILIAL     = P_FILIAL)    AND
                     (NRLANCTONF   = P_LANCTONF ) AND
                     (NRSEQITPROD  = C_ITLANCTOEST.NRSEQITPROD)  AND
                     ((CDALMOXARIFE IS NULL)       OR
                      (CDLOCALESTOQ IS NULL)       OR
                      (NRLOTEESTQ   IS NULL)       OR
                      (NRSUBLOTE    IS NULL));
            END IF;


            IF (V_IDSISTEMA = w_EXP) THEN
               BEGIN
                  SELECT IDTPCOMPPROD
                  INTO  V_IDTPCOMPPROD
                  FROM
                     PARAMPEDIDO
                  WHERE
                     CDFILIAL  = P_FILIAL;
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN
                     V_IDTPCOMPPROD := W_F;
               END;
            ELSE
               V_IDTPCOMPPROD := W_F;
            END IF;

            SELECT COUNT(*)
            INTO   V_EXISTE_ROT
            FROM   ROTFABLOCAL
            WHERE  CDFILIAL  = C_ITLANCTOEST.CDFILIMOVI AND
                   CDPRODUTO = C_ITLANCTOEST.CDPRODUTO;

            IF (V_EXISTE_ROT > 0)AND(V_IDTPCOMPPROD = W_F) THEN
               V_EXISTE_ROT := V_EXISTE_ROT;

               INSERE_SUBPRODMAN(P_FILIAL,P_LANCESTQ,P_TIPOOPER,C_ITLANCTOEST.CDPRODUTO,
                                 C_ITLANCTOEST.QTITEMPROD,
                                 C_ITLANCTOEST.VRTOTAITEM,C_ITLANCTOEST.VRDESCITEM,
                                 C_ITLANCTOEST.VRBRUTITEM,C_ITLANCTOEST.VRCONTITEM,
                                 V_VRTOTALANCTO,V_QTDELANCTO,V_TIPOMOVI,P_INIVALID,
                                 C_ITLANCTOEST.CDPRODESTO,
                                 C_ITLANCTOEST.NRPEDIDO, C_ITLANCTOEST.NRITEMPED, V_IDTPCOMPPROD,
                                 C_ITLANCTOEST.CDALMOXARIFE,
                                 C_ITLANCTOEST.CDLOCALESTOQ, V_IDSISTEMA);
            ELSE
               SELECT COUNT(*)
               INTO   V_EXISTE_ROT
               FROM   ROTFABRICA
               WHERE  CDPRODUTO = C_ITLANCTOEST.CDPRODUTO;

               IF (V_EXISTE_ROT > 0)AND(V_IDTPCOMPPROD = W_F)  THEN
                  V_EXISTE_ROT := V_EXISTE_ROT;

                  INSERE_SUBPRODMAN(P_FILIAL,P_LANCESTQ,P_TIPOOPER,C_ITLANCTOEST.CDPRODUTO,
                                    C_ITLANCTOEST.QTITEMPROD,
                                    C_ITLANCTOEST.VRTOTAITEM,C_ITLANCTOEST.VRDESCITEM,
                                    C_ITLANCTOEST.VRBRUTITEM,C_ITLANCTOEST.VRCONTITEM,
                                    V_VRTOTALANCTO,V_QTDELANCTO,V_TIPOMOVI,P_INIVALID,
                                    C_ITLANCTOEST.CDPRODESTO,
                                    C_ITLANCTOEST.NRPEDIDO, C_ITLANCTOEST.NRITEMPED, V_IDTPCOMPPROD,
                                    C_ITLANCTOEST.CDALMOXARIFE, C_ITLANCTOEST.CDLOCALESTOQ, V_IDSISTEMA);
               ELSE
                  SELECT COUNT(*)
                  INTO V_EXISTE_ROT
                  FROM COMPITEMPED
                  WHERE
                     CDFILIAL = C_ITLANCTOEST.CDFILIMOVI  AND
                     NRPEDIDO = C_ITLANCTOEST.NRPEDIDO    AND
                     NRITEMPED  = C_ITLANCTOEST.NRITEMPED AND
                     CDPRODUTO = C_ITLANCTOEST.CDPRODUTO;

                  IF (V_EXISTE_ROT > 0)AND(V_IDTPCOMPPROD = W_V)  THEN

                     INSERE_SUBPRODMAN(P_FILIAL,P_LANCESTQ,P_TIPOOPER,C_ITLANCTOEST.CDPRODUTO,
                                       C_ITLANCTOEST.QTITEMPROD,
                                       C_ITLANCTOEST.VRTOTAITEM,C_ITLANCTOEST.VRDESCITEM,
                                       C_ITLANCTOEST.VRBRUTITEM,C_ITLANCTOEST.VRCONTITEM,
                                       V_VRTOTALANCTO,V_QTDELANCTO,V_TIPOMOVI,P_INIVALID,
                                       C_ITLANCTOEST.CDPRODESTO,
                                       C_ITLANCTOEST.NRPEDIDO, C_ITLANCTOEST.NRITEMPED, V_IDTPCOMPPROD,
                                       C_ITLANCTOEST.CDALMOXARIFE, C_ITLANCTOEST.CDLOCALESTOQ, V_IDSISTEMA);
                  ELSE

                     IF (C_ITLANCTOEST.IDCNTRESTOQ = w_S) THEN
                        Begin
                           SELECT NVL(C_ITLANCTOEST.VRFATCONTRIBXML, VRFATOCONV) AS VRFATOCONV
                           INTO   V_FATOCONV
                           FROM   PRODUTO
                           WHERE  CDPRODUTO = C_ITLANCTOEST.CDPRODUTO;
                        Exception
                           When No_Data_Found Then
                              V_FATOCONV := Null;
                        End;

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

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

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

                        IF (V_IDOPERDEVONF = w_S) THEN
                           IF (V_QTDELANCTO <> 0) THEN
                              V_TOTABRUT   := (C_ITLANCTOEST.VRBRUTITEM/V_QTDELANCTO)/V_FATOCONV;
                              V_TOTACONTAB := (C_ITLANCTOEST.VRCONTITEM/V_QTDELANCTO)/V_FATOCONV;
                           ELSE
                              V_TOTABRUT   := C_ITLANCTOEST.VRBRUTITEM/V_FATOCONV;
                              V_TOTACONTAB := C_ITLANCTOEST.VRCONTITEM/V_FATOCONV;
                           END IF;
                        ELSE
                           V_TOTABRUT   := 0;
                           V_TOTACONTAB := 0;
                        END IF;

                        IF (V_IDOPERDEVONF <> w_S) OR
                           ((V_IDOPERDEVONF = w_S) AND (V_QTDELANCTO <> 0)) THEN

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

                           INSERT INTO ITLANCTOEST
                              (CDFILIAL,NRLANCESTQ,NRSEQUITEM,CDPRODUTO,QTTOTLANCTO,VRUNILANCTO,VRTOTLANCTO,
                               IDTIPOMOVI,DTLANCMOVI,IDORDEMCLC,CDPRODMOVI,QTLANCTOEST,VRLANCTOBRUT, VRLANCTOEST,
                               CDFILIMOVI,CDALMOXARIFE,CDLOCALESTOQ,NRLOTEESTQ,NRSUBLOTE,NRLANCORIGRP, IDORIGEMPROD)
                           VALUES
                              (P_FILIAL,P_LANCESTQ,LPAD(V_NRSEQITPROD,4,w_0),C_ITLANCTOEST.CDPRODUTO,
                               V_QTDELANCTO,V_VRUNITLANCTO,V_VRTOTALANCTO,
                               V_TIPOMOVI,P_INIVALID,w_8,C_ITLANCTOEST.CDPRODESTO,
                               (V_QTDELANCTO * V_FATOCONV),V_TOTABRUT, V_TOTACONTAB,
                               V_CDFILIEMIT,C_ITLANCTOEST.CDALMOXARIFE,C_ITLANCTOEST.CDLOCALESTOQ,C_ITLANCTOEST.NRLOTEESTQ,
                               C_ITLANCTOEST.NRSUBLOTE,V_IDDOCESTOQ, C_ITLANCTOEST.IDORIGEMPROD);
                        END IF;
                     END IF;

                  END IF;

               END IF;
            END IF;     /* FIM DO IF DO SISTEMA */

         END LOOP;
      ELSE  /* DEMAIS SISTEMAS QUE NAO SEJAM EXPEDICAO NEM GESTAO DE VENDAS */
         BEGIN
            SELECT MAX(CDFILIAL)
              INTO V_CDFILIORIG
              FROM ITEMNOTAFISC
             WHERE CDFILIALIT   = P_FILIAL
               AND NRLANCTONFIT = P_LANCTONF;
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_CDFILIORIG := NULL;
         END;
         FOR C_ITLANCTOEST IN (SELECT NRSEQITPROD,
                                      IP.CDPRODUTO,
                                      VRUNITITEM,
                                      VRTOTAITEM,
                                      QTITEMPROD,
                                      CDPRODESTO,
                                      VRBRUTITEM,
                                      VRDESCITEM,
                                      VRCONTITEM,
                                      NVL(IP.CDALMOXARIFE,' ') AS CDALMOXARIFE,
                                      NVL(IP.CDLOCALESTOQ,' ') AS CDLOCALESTOQ,
                                      NVL(NRLOTEESTQ,' ')      AS NRLOTEESTQ,
                                      NVL(NRSUBLOTE,' ')       AS NRSUBLOTE,
                                      NVL(VRCONTITEMORIG, 0) VRCONTITEMORIG,
                                      NVL(VRBRUTITEMORIG, 0) VRBRUTITEMORIG,
                                      CDARVPROD,
                                      NMPRODUTO,
                                      NVL(IP.IDORIGEMPROD, 'N') AS IDORIGEMPROD,
                                      IP.VRFATCONTRIBXML
                               FROM ITEMPRODUTO IP, PRODUTO P, PRODFILI PF
                               WHERE IP.CDFILIAL    = P_FILIAL     AND
                                     IP.NRLANCTONF  = P_LANCTONF   AND
                                     P.CDPRODUTO    = IP.CDPRODUTO AND
                                     PF.CDFILIAL    = V_CDFILIEMIT AND
                                     PF.CDPRODUTO   = P.CDPRODESTO AND
                                     NVL(IDCNTRESTOQ, w_S) <> w_N AND
                                     NVL(IP.IDATUESTPROD, 'S') = 'S') LOOP

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

            BEGIN
               SELECT NVL(IDATUESTTPOP, 'S') AS IDATUESTTPOP, NVL(IDREMESSAINDU, 'N') AS IDREMESSAINDU
                 INTO V_IDATUESTTPOP, V_IDREMESSAINDU
                 FROM TIPOOPERAC
                WHERE IDENTRSAIDOP = w_S
                  AND CDTIPOOPER = P_TIPOOPER;
            EXCEPTION
               WHEN NO_DATA_FOUND THEN
                  V_IDATUESTTPOP := 'S';
                  V_IDREMESSAINDU := 'N';
            END;

            IF (V_IDUTILALMOX <> w_S AND V_IDUTILLCESTQ <> w_S AND V_IDUTILLOTE <> w_S) THEN
               UPDATE ITEMPRODUTO
               SET CDALMOXARIFE  = ' ',
                   CDLOCALESTOQ  = ' ',
                   NRLOTEESTQ    = ' ',
                   NRSUBLOTE     = ' '
               WHERE (CDFILIAL     = P_FILIAL)    AND
                     (NRLANCTONF   = P_LANCTONF ) AND
                     (NRSEQITPROD  = C_ITLANCTOEST.NRSEQITPROD)  AND
                     ((CDALMOXARIFE IS NULL)       OR
                      (CDLOCALESTOQ IS NULL)       OR
                      (NRLOTEESTQ   IS NULL)       OR
                      (NRSUBLOTE    IS NULL));
            END IF;

            BEGIN
               SELECT NVL(IP.VRFATCONTRIBXML,  VRFATOCONV) AS VRFATOCONV
               INTO   V_FATOCONV
               FROM PRODUTO P, ITEMPRODUTO IP
               WHERE P.CDPRODUTO    = IP.CDPRODUTO AND
                     IP.CDFILIAL    = P_FILIAL     AND
                     IP.NRLANCTONF  = P_LANCTONF   AND
                     IP.NRSEQITPROD = C_ITLANCTOEST.NRSEQITPROD;
            EXCEPTION
               WHEN NO_DATA_FOUND THEN
                  V_FATOCONV := NULL;
            END;

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

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

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

            IF (V_IDOPERDEVONF = w_S) OR (V_IDREMESSAINDU = w_S) THEN
               IF (V_QTDELANCTO <> 0) THEN
                  V_TOTABRUT   := (C_ITLANCTOEST.VRBRUTITEM/V_QTDELANCTO)/V_FATOCONV;
                  V_TOTACONTAB := (C_ITLANCTOEST.VRCONTITEM/V_QTDELANCTO)/V_FATOCONV;
                  IF C_ITLANCTOEST.VRBRUTITEMORIG <> 0 THEN
                     V_TOTABRUT := (C_ITLANCTOEST.VRBRUTITEMORIG/V_QTDELANCTO)/V_FATOCONV;
                  END IF;
                  IF C_ITLANCTOEST.VRCONTITEMORIG <> 0 THEN
                     V_TOTACONTAB := (C_ITLANCTOEST.VRCONTITEMORIG/V_QTDELANCTO)/V_FATOCONV;
                  END IF;
               ELSE
                  V_TOTABRUT   := C_ITLANCTOEST.VRBRUTITEM/V_FATOCONV;
                  V_TOTACONTAB := C_ITLANCTOEST.VRCONTITEM/V_FATOCONV;
               END IF;
            ELSE
               V_TOTABRUT   := 0;
               V_TOTACONTAB := 0;
            END IF;

            IF (V_IDOPERDEVONF <> w_S) OR ((V_IDOPERDEVONF = w_S) AND (V_QTDELANCTO <> 0)) THEN

               INSERT INTO ITLANCTOEST
                  (CDFILIAL, NRLANCESTQ, NRSEQUITEM,               CDPRODUTO,
                   QTTOTLANCTO, VRUNILANCTO,    VRTOTLANCTO,
                   IDTIPOMOVI, DTLANCMOVI, IDORDEMCLC,CDPRODMOVI,
                   QTLANCTOEST,               VRLANCTOBRUT, VRLANCTOEST,
                   CDFILIMOVI,  CDALMOXARIFE,               CDLOCALESTOQ,               NRLOTEESTQ,
                   NRSUBLOTE,              NRLANCORIGRP, IDORIGEMPROD)
               VALUES
                  (P_FILIAL, P_LANCESTQ, C_ITLANCTOEST.NRSEQITPROD,C_ITLANCTOEST.CDPRODUTO,
                   V_QTDELANCTO,V_VRUNITLANCTO, V_VRTOTALANCTO,
                   V_TIPOMOVI, P_INIVALID, w_8,       C_ITLANCTOEST.CDPRODESTO,
                  (V_QTDELANCTO * V_FATOCONV),V_TOTABRUT,   V_TOTACONTAB,
                   V_CDFILIEMIT,C_ITLANCTOEST.CDALMOXARIFE, C_ITLANCTOEST.CDLOCALESTOQ, C_ITLANCTOEST.NRLOTEESTQ,
                   C_ITLANCTOEST.NRSUBLOTE,V_IDDOCESTOQ, C_ITLANCTOEST.IDORIGEMPROD);
            END IF;

            /* Se NF Remessa para Industrializacao e Operacao Atualiza Estoque */
            IF (V_IDREMESSAINDU = 'S') AND (V_IDATUESTTPOP = 'S') THEN
            
               IF V_IDORIGDESTNF = 'C' THEN
                  BEGIN
                     SELECT NVL(CDALMOXINFOCLI, ' ') AS CDALMOXINFOCLI, NVL(CDLOCALINFOCLI, ' ') AS CDLOCALINFOCLI
                       INTO V_CDALMOXINFO, V_CDLOCALINFO
                       FROM AGENTETERCECLI
                      WHERE CDFILIAL = V_CDFILIEMIT
                        AND CDCLIENTE = P_CLIENTE;
                  EXCEPTION
                     WHEN NO_DATA_FOUND THEN
                        V_CDALMOXINFO := ' ';
                        V_CDLOCALINFO := ' ';
                  END;
               END IF;
               IF V_IDORIGDESTNF = 'F' THEN
                  BEGIN
                     SELECT NVL(CDALMOXINFOFOR, ' ') AS CDALMOXINFOFOR, NVL(CDLOCALINFOFOR, ' ') AS CDLOCALINFOFOR
                       INTO V_CDALMOXINFO, V_CDLOCALINFO
                       FROM AGENTETERCEFOR
                      WHERE CDFILIAL = V_CDFILIEMIT
                        AND CDFORNECED = P_CLIENTE;
                  EXCEPTION
                     WHEN NO_DATA_FOUND THEN
                        V_CDALMOXINFO := ' ';
                        V_CDLOCALINFO := ' ';
                  END;
                  
                  BEGIN
                     SELECT CDFILIAL
                       INTO V_CDFILIAGENT
                       FROM FILIAL
                      WHERE CDFORNAGETERC = P_CLIENTE;
                  EXCEPTION
                     WHEN NO_DATA_FOUND THEN
                        V_CDFILIAGENT := NULL;
                  END;

                  IF NOT V_CDFILIAGENT IS NULL THEN
                     BEGIN
                        SELECT NVL(NVL(P.CDALMOXARIFE, F.CDALMOXARIFE), ' ') AS CDALMOXARIFE, NVL(NVL(P.CDLOCALESTOQ, F.CDLOCALESTOQ), ' ') AS CDLOCALESTOQ,
                               NVL(F.IDUTILLOTE, 'N') AS IDUTILLOTE
                          INTO V_CDALMOXARIFEAG, V_CDLOCALESTOQAG, V_IDUTILLOTEAG
                          FROM PARAMFILIAL F, PRODFILI P
                         WHERE F.CDFILIAL  = V_CDFILIAGENT
                           AND P.CDFILIAL  = V_CDFILIAGENT
                           AND P.CDPRODUTO = C_ITLANCTOEST.CDPRODESTO;
                     EXCEPTION
                        WHEN NO_DATA_FOUND THEN
                           V_CDALMOXARIFEAG := ' ';
                           V_CDLOCALESTOQAG := ' ';
                           V_IDUTILLOTEAG   := 'N';
                     END;

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

                     IF V_IDUTILLOTEAG = 'S' THEN
                        IF (V_NRLOTEESTQAG IS NULL) OR (V_NRLOTEESTQAG = ' ') THEN
                           PRXLOTEPRODEST(V_CDFILIAGENT, P_INIVALID, C_ITLANCTOEST.CDPRODESTO, V_NRLOTEESTQAG);
                           V_NRSUBLOTEAG := ' ';
                        END IF;
                     ELSE
                        V_NRLOTEESTQAG := ' ';
                        V_NRSUBLOTEAG  := ' ';
                     END IF;
                  END IF;
               END IF;

               IF (V_CDALMOXINFO IS NOT NULL) AND (V_CDALMOXINFO <> ' ') AND (V_CDFILIAGENT IS NULL) THEN

                  IF V_BOLANESTENTR THEN
                     --GERANDO O REGISTRO NA TABELA LANCTOESTOQ PARA A ENTRADA NO ALMOXAXARIFADO
                     IF (V_NRLANESTENTR IS NULL) OR (V_NRLANESTENTR = '') THEN
                        NOVO_CODIGO_NT('LANCTOEST'||P_FILIAL, V_NRLANESTENTR);
                        V_NRLANESTENTR := SUBSTR(V_NRLANESTENTR, 11, 10);
                     END IF;
                     
                     INSERT INTO LANCTOESTOQ
                        (CDFILIAL,
                         NRLANCESTQ,
                         IDTPLANCTO,
                         DTLANCESTQ,
                         DSLANCESTQ,
                         CDFILIMOVI,
                         CDOPERADOR)
                     VALUES
                        (P_FILIAL,
                         V_NRLANESTENTR,
                         W_2,
                         P_INIVALID,
                         'Transferencia de Estoque ' || V_NRLANESTENTR,
                         V_CDFILIEMIT,
                         P_CDOPERADOR);

                     --GERANDO O REGISTRO NA TABELA CTRLMOVIESTQ
                     IF (V_NRCTRLMOVEST IS NULL) OR (V_NRCTRLMOVEST = '') THEN
                        NOVO_CODIGO_NT('NRTRANSESTQ'||V_CDFILIEMIT, V_NRCTRLMOVEST);
                        V_NRCTRLMOVEST := SUBSTR(V_NRCTRLMOVEST, 11, 10);
                     END IF;

                     INSERT INTO CTRLMOVIESTQ
                        (CDFILIAL,
                         NRCTRLMOVEST,
                         CDFILIALENTR,
                         NRLANESTENTR,
                         CDFILIALSAID,
                         NRLANESTSAID,
                         CDALMOXENTR,
                         CDALMOXSAID,
                         CDLCESTENTR,
                         CDLCESTSAID,
                         DTMOVIESTQ,
                         NRREQUESTO)
                     VALUES
                        (V_CDFILIEMIT,
                         V_NRCTRLMOVEST,
                         P_FILIAL,
                         V_NRLANESTENTR,
                         P_FILIAL,
                         P_LANCESTQ,
                         V_CDALMOXINFO,
                         C_ITLANCTOEST.CDALMOXARIFE,
                         V_CDLOCALINFO,
                         C_ITLANCTOEST.CDLOCALESTOQ,
                         P_INIVALID,
                         '');

                     V_BOLANESTENTR := FALSE;
                  END IF;

                  --GERANDO O REGISTRO NA TABELA ITLANCTOEST
                  INSERT INTO ITLANCTOEST
                     (CDFILIAL,
                      NRLANCESTQ,
                      NRSEQUITEM,
                      CDPRODUTO,
                      DSLANCESTIT,
                      CDALMOXARIFE,
                      CDLOCALESTOQ,
                      NRLOTEESTQ,
                      NRSUBLOTE,
                      CDFILIMOVI,
                      CDPRODMOVI,
                      IDORDEMCLC,
                      DTLANCMOVI,
                      IDEVOLESTOQ,
                      QTTOTLANCTO,
                      IDTIPOMOVI,
                      QTLANCTOEST,
                      VRUNILANCTO,
                      VRTOTLANCTO,
                      VRLANCTOEST,
                      VRLANCTOBRUT,
                      IDORIGEMPROD)
                  VALUES
                     (P_FILIAL,
                     V_NRLANESTENTR,
                     C_ITLANCTOEST.NRSEQITPROD,
                     C_ITLANCTOEST.CDPRODUTO,
                     '',
                     V_CDALMOXINFO,
                     V_CDLOCALINFO,
                     C_ITLANCTOEST.NRLOTEESTQ,
                     C_ITLANCTOEST.NRSUBLOTE,
                     V_CDFILIEMIT,
                     C_ITLANCTOEST.CDPRODESTO,
                     W_2,
                     P_INIVALID,
                     W_S,
                     V_QTDELANCTO,
                     W_2,
                     V_QTDELANCTO * V_FATOCONV,
                     V_VRUNITLANCTO,
                     V_VRTOTALANCTO,
                     V_TOTACONTAB,
                     V_TOTABRUT,
                     C_ITLANCTOEST.IDORIGEMPROD);
               ELSE
                  /* Se o fornecedor da nota fiscal for agente de terceirizacao */
                  IF NOT V_CDFILIAGENT IS NULL THEN
                     IF V_CDFILIORIG IS NULL THEN
                        IF V_BOLANESTENTRAG THEN
                           /* Gerando o registro na tabela LANCTOESTOQ para a entrada na filial relacionada ao agente de terceirizacao */
                           NOVO_CODIGO_NT('LANCNF/FILIAL' || V_CDFILIAGENT, V_NRLANCTONFAG);
                           V_NRLANCTONFAG := SUBSTR(V_NRLANCTONFAG, 11, 10);

                           NOVO_CODIGO_NT('LANCTOEST'||V_CDFILIAGENT, V_NRLANESTENTRAG);
                           V_NRLANESTENTRAG := SUBSTR(V_NRLANESTENTRAG, 11, 10);

                           V_TPOPERRETORNO := NULL;
                           BEGIN
                              SELECT CDTPOOPRETORNO
                                INTO V_TPOPERRETORNO
                                FROM PARAMGERAL
                               WHERE CDPARGERAL = '0001';
                           EXCEPTION
                           WHEN NO_DATA_FOUND THEN
                              V_TPOPERRETORNO := NULL;
                           END;

                           IF (V_TPOPERRETORNO IS NULL) THEN
                              RAISE_APPLICATION_ERROR(-20501, 'Tipo de operacao para geracao de lancamento de estoque deve ser informado - (Parametros para Documentos Fiscais de Saida - Operador Logistico)', TRUE);
                           END IF;

                           INSERT INTO NOTAFISCAL
                              (CDFILIAL, NRLANCTONF, CDFILIRECE, CDEMPRESA, CDINSCESTA, CDSERIE, CDINSCMUNI,
                               IDTPIJURNF, NRINSJURNF, CDFORNECED, IDBLOQUEADO, IDDOCFISCAL, IDDOCFINANC,
                               NRNOTAFISC, DTEMISSAO, DTENTRSAID, VRPRODUTOS, VRNOTAFISC, IDENTRSAIDOP,
                               CDTIPOOPER, CDSERIEENTR, CDCLIENTE, CDFILIEMIT, IDORIGDESTNF)
                           VALUES
                              (V_CDFILIAGENT, V_NRLANCTONFAG, V_CDFILIAGENT, V_CDEMPRESAAG, V_CDINSCESTAAG, NULL, V_CDINSCMUNIAG,
                               V_IDTPIJURNF, V_NRINSJURNF, P_CLIENTE, 'N', 'N', 'S',
                               NULL, P_INIVALID, P_INIVALID, NVL(V_LIQUIDO,0), NVL(V_TOTALNOTA,0), 'E',
                               V_TPOPERRETORNO, NULL, NULL, NULL, V_IDORIGDESTNF);

                           INSERT INTO ITEMNOTAFISC
                              (CDFILIAL, NRLANCTONF, NRSEQUITNOTA, CDFILIALIT, NRLANCTONFIT)
                           VALUES
                              (V_CDFILIAGENT, V_NRLANCTONFAG, '001', P_FILIAL, P_LANCTONF);

                           INSERT INTO LANCTOESTOQ
                              (CDFILIAL,
                               NRLANCESTQ,
                               NRLANCTONF,
                               IDTPLANCTO,
                               DTLANCESTQ,
                               DSLANCESTQ,
                               CDFILIMOVI,
                               CDOPERADOR)
                           VALUES
                              (V_CDFILIAGENT,
                               V_NRLANESTENTRAG,
                               V_NRLANCTONFAG,
                               'E',
                               P_INIVALID,
                               'NF Remessa Armazenagem - lanc. ' || V_CDFILIEMIT || ' ' || P_LANCTONF,
                               V_CDFILIAGENT,
                               P_CDOPERADOR);

                           V_BOLANESTENTRAG := FALSE;
                        END IF;

                        INSERT INTO ITEMPRODUTO
                           (CDFILIAL, NRLANCTONF, NRSEQITPROD, CDPRODUTO,
                            CDPRODEMIS, DSPRODEMIS, IDATUVRESTOQ, QTITEMPROD,
                            VRUNITITEM, VRDESCITEM, VRTOTAITEM, VRCONTITEM,
                            VRBRUTITEM, IDCONFORITEM, CDFILIMOVI,
                            CDALMOXARIFE, CDLOCALESTOQ, NRLOTEESTQ, NRSUBLOTE,
                            CDPRODMOVI)
                        VALUES
                           (V_CDFILIAGENT, V_NRLANCTONFAG, C_ITLANCTOEST.NRSEQITPROD, C_ITLANCTOEST.CDPRODUTO,
                            C_ITLANCTOEST.CDARVPROD, C_ITLANCTOEST.NMPRODUTO, 'S', V_QTDELANCTO,
                            V_VRUNITLANCTO, C_ITLANCTOEST.VRDESCITEM, V_VRTOTALANCTO, V_VRTOTALANCTO,
                            V_VRTOTALANCTO, 'S', V_CDFILIAGENT,
                            V_CDALMOXARIFEAG, V_CDLOCALESTOQAG, V_NRLOTEESTQAG, V_NRSUBLOTEAG,
                            C_ITLANCTOEST.CDPRODESTO);

                        INSERT INTO ITLANCTOEST
                           (CDFILIAL,
                            NRLANCESTQ,
                            NRSEQUITEM,
                            CDPRODUTO,
                            DSLANCESTIT,
                            CDALMOXARIFE,
                            CDLOCALESTOQ,
                            NRLOTEESTQ,
                            NRSUBLOTE,
                            CDFILIMOVI,
                            CDPRODMOVI,
                            IDORDEMCLC,
                            DTLANCMOVI,
                            IDEVOLESTOQ,
                            QTTOTLANCTO,
                            IDTIPOMOVI,
                            QTLANCTOEST,
                            VRUNILANCTO,
                            VRTOTLANCTO,
                            VRLANCTOEST,
                            VRLANCTOBRUT,
                            IDORIGEMPROD)
                        VALUES
                           (V_CDFILIAGENT,
                            V_NRLANESTENTRAG,
                            C_ITLANCTOEST.NRSEQITPROD,
                            C_ITLANCTOEST.CDPRODUTO,
                            '',
                            V_CDALMOXARIFEAG,
                            V_CDLOCALESTOQAG,
                            V_NRLOTEESTQAG,
                            V_NRSUBLOTEAG,
                            V_CDFILIAGENT,
                            C_ITLANCTOEST.CDPRODESTO,
                            W_2,
                            P_INIVALID,
                            W_S,
                            V_QTDELANCTO,
                            W_2,
                            V_QTDELANCTO * V_FATOCONV,
                            V_VRUNITLANCTO,
                            V_VRTOTALANCTO,
                            V_TOTACONTAB,
                            V_TOTABRUT,
                            C_ITLANCTOEST.IDORIGEMPROD);
                     END IF;
                  END IF;
               END IF;
            END IF;
         END LOOP;
      END IF;
   END IF;
   IF (V_CDSITUCRT <> '3') THEN
      SELECT COUNT(*)
         INTO V_EXISTDSDADOSADIC
         FROM ITEMPRODUTO
      WHERE CDFILIAL   = P_FILIAL
        AND NRLANCTONF = P_LANCTONF
        AND (CDFISCOPERSN IN ('101', '201') OR SUBSTR(CDFISCOPERSN,2, 3) IN ('101', '201'));
      IF V_EXISTDSDADOSADIC > 0 THEN
         V_CDIMPOSICMS  := null;
         FOR C_ICMS IN (SELECT CDIMPOSTO
                          FROM IMPOSTO
                         WHERE CDIMPOSTONFE = '00')
         LOOP
            V_CDIMPOSICMS := V_CDIMPOSICMS||C_ICMS.CDIMPOSTO||'_';
         END LOOP;
         IF V_CDIMPOSICMS IS NOT NULL THEN
            SELECT SUM(VRIMPOSTOIT) VRIMPOSTOICMS, MAX(VRALIQITEM) VRALIQUOTAICMS
              INTO V_APROVICMS, V_ALIQAPROVICMS
              FROM ITEMPROIMPOS I
             WHERE I.CDFILIAL   = P_FILIAL
               AND I.NRLANCTONF   = P_LANCTONF
               AND I.NRITPROIMPOS = '1'
               AND (INSTR(V_CDIMPOSICMS,I.CDIMPOSTO||'_') > 0)
               AND I.NRSEQITPROD IN (SELECT NRSEQITPROD
                                       FROM ITEMPRODUTO IP
                                      WHERE IP.CDFILIAL = P_FILIAL
                                        AND IP.NRLANCTONF = P_LANCTONF
                                        AND (IP.CDFISCOPERSN IN ('101', '201') OR SUBSTR(IP.CDFISCOPERSN,2, 3) IN ('101', '201')));

            SELECT COUNT(*)
              INTO V_EXISTDSDADOSADIC
              FROM DADOSADIC
             WHERE CDFILIAL = P_FILIAL
               AND NRLANCTONF = P_LANCTONF
               AND DSDADOADIC LIKE 'Permite o aproveitamento do credito do ICMS no valor de R$ %';

            IF V_EXISTDSDADOSADIC = 0 THEN
               INSERT INTO DADOSADIC(CDFILIAL, NRLANCTONF, NRDADOADIC, DSDADOADIC)
                              VALUES(P_FILIAL, P_LANCTONF, V_DADOADIC, 'Permite o aproveitamento do credito do ICMS no valor de R$ '||DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(V_APROVICMS, 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(V_APROVICMS, 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(V_APROVICMS, 2), '9999999999999.99')))|| ' corresp. a aliquota de '|| DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(V_ALIQAPROVICMS, 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(V_ALIQAPROVICMS, 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(V_ALIQAPROVICMS, 2), '9999999999999.99'))) || '% conf. Art.23 da LC 123/06.');

               V_DADOADIC := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_DADOADIC) + 1)),3,0);
            ELSE
               UPDATE DADOSADIC
                  SET DSDADOADIC = 'Permite o aproveitamento do credito do ICMS no valor de R$ '||DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(V_APROVICMS, 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(V_APROVICMS, 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(V_APROVICMS, 2), '9999999999999.99')))|| ' corresp. a aliquota de '|| DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(V_ALIQAPROVICMS, 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(V_ALIQAPROVICMS, 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(V_ALIQAPROVICMS, 2), '9999999999999.99'))) || '% conf. Art.23 da LC 123/06.'
                 WHERE CDFILIAL = P_FILIAL
                   AND NRLANCTONF = P_LANCTONF
                   AND DSDADOADIC LIKE 'Permite o aproveitamento do credito do ICMS no valor de R$ %';
            END IF;
         END IF;
      END IF;
   END IF;
   /*Portaria CAT 37/2002*/
	IF (V_IDNTRANSCREICMS = 'S') THEN
		SELECT COUNT(*)
          INTO V_EXISTDSDADOSADIC
          FROM DADOSADIC
         WHERE CDFILIAL = P_FILIAL
           AND NRLANCTONF = P_LANCTONF
           AND DSDADOADIC LIKE 'NF emitida de acordo com o Regime Especial - Portaria CAT 37/2002';

		IF V_EXISTDSDADOSADIC = 0 THEN
			INSERT INTO DADOSADIC(CDFILIAL, NRLANCTONF, NRDADOADIC, DSDADOADIC)
					  VALUES (P_FILIAL, P_LANCTONF, V_DADOADIC, 'NF emitida de acordo com o Regime Especial - Portaria CAT 37/2002');
			      V_DADOADIC := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_DADOADIC) + 1)),3,0);
			ELSE
				UPDATE DADOSADIC
				SET DSDADOADIC = 'NF emitida de acordo com o Regime Especial - Portaria CAT 37/2002'
				WHERE CDFILIAL = P_FILIAL
				AND NRLANCTONF = P_LANCTONF
				AND DSDADOADIC LIKE 'NF emitida de acordo com o Regime Especial - Portaria CAT 37/2002';
		END IF;
	ELSE
		DELETE FROM DADOSADIC
		WHERE CDFILIAL = P_FILIAL
        AND NRLANCTONF = P_LANCTONF
        AND DSDADOADIC LIKE 'NF emitida de acordo com o Regime Especial - Portaria CAT 37/2002';		
	END IF;
   /*Mensagem referente ao ICMS 60 - calculo realizado na CALCULA_ICMS60*/
   DELETE FROM DADOSADIC
    WHERE CDFILIAL = P_FILIAL
      AND NRLANCTONF = P_LANCTONF
      AND DSDADOADIC LIKE 'ICMS cobrado anteriormente por substituicao tributaria: BC %';
    
     SELECT SUM(VRBCITENTR), SUM(VRIMPITENTR)
       INTO V_VRBCITENTR, V_VRIMPITENTR
       FROM ITEMPRODUTO IP, ITEMPROIMPOS II
      WHERE IP.CDFILIAL = II.CDFILIAL
        AND IP.NRLANCTONF = II.NRLANCTONF
        AND IP.NRSEQITPROD = II.NRSEQITPROD
        AND IP.CDFILIAL = P_FILIAL
        AND IP.NRLANCTONF = P_LANCTONF
        AND SUBSTR(IP.CDSITUTRIBPR, 2, 2) = '60';
      
      IF V_VRIMPITENTR <> 0 THEN
           SELECT COUNT(*)
             INTO V_EXISTDSDADOSADIC
             FROM DADOSADIC
            WHERE CDFILIAL = P_FILIAL
              AND NRLANCTONF = P_LANCTONF
              AND DSDADOADIC LIKE 'ICMS cobrado anteriormente por substituicao tributaria: BC %';

          IF V_EXISTDSDADOSADIC = 0 THEN
             INSERT INTO DADOSADIC(CDFILIAL, NRLANCTONF, NRDADOADIC, DSDADOADIC)
                            VALUES(P_FILIAL, P_LANCTONF, V_DADOADIC, 'ICMS cobrado anteriormente por substituicao tributaria: BC '||DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(V_VRBCITENTR, 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(V_VRBCITENTR, 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(V_VRBCITENTR, 2), '9999999999999.99')))|| ' - Valor '|| DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(V_VRIMPITENTR, 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(V_VRIMPITENTR, 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(V_VRIMPITENTR, 2), '9999999999999.99'))));
             V_DADOADIC := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_DADOADIC) + 1)),3,0);
          END IF;
      END IF;
   /*Grava o numero do pedido nos dados adicionais da nota*/	  
   IF V_IDADICNRPEDIDO = 'S' THEN
      DELETE FROM DADOSADIC
       WHERE CDFILIAL = P_FILIAL
         AND NRLANCTONF = P_LANCTONF
         AND DSDADOADIC LIKE 'Numero do Pedido:%';
		 
         FOR C_NRPEDIDO IN (SELECT DISTINCT I.NRPEDIDO 
                              FROM ITEMPRODUTO I LEFT JOIN PEDIDO P ON (I.CDFILIALPED = P.CDFILIAL)
                                                                   AND (I.NRPEDIDO = P.NRPEDIDO)
                             WHERE I.NRLANCTONF = P_LANCTONF
                               AND I.CDFILIAL = P_FILIAL)
         LOOP
            IF C_NRPEDIDO.NRPEDIDO IS NOT NULL THEN
               V_DESCNRPEDIDO := C_NRPEDIDO.NRPEDIDO||' - '||V_DESCNRPEDIDO;
            END IF; 
            
            IF (V_DESCNRPEDIDO IS NOT NULL) OR (TRIM(V_DESCNRPEDIDO) <> '') THEN
               IF (TRIM(SUBSTR(V_DESCNRPEDIDO, LENGTH(V_DESCNRPEDIDO) - 2, 3)) = '-') THEN
                  V_DESCNRPEDIDO := TRIM(SUBSTR(V_DESCNRPEDIDO, 1, LENGTH(V_DESCNRPEDIDO) - 3));
               END IF;
            END IF;
         END LOOP;
		 
		 IF (V_DESCNRPEDIDO IS NOT NULL) OR (TRIM(V_DESCNRPEDIDO) <> '') THEN
            INSERT INTO DADOSADIC(CDFILIAL, NRLANCTONF, NRDADOADIC, DSDADOADIC)
                  VALUES(P_FILIAL, P_LANCTONF, V_DADOADIC, 'Numero do Pedido: '||V_DESCNRPEDIDO);
            V_DADOADIC := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_DADOADIC) + 1)),3,0);
		 END IF;
   END IF; 
END;
/