                     UPDATE NOTAFISCAL
                        SET DSCDFISOPENF = V_DSCDFISOPEITREGRA
                      WHERE CDFILIAL   = P_FILIAL   AND
                            NRLANCTONF = P_LANCTONF;
                  ELSE
                     UPDATE NOTAFISCAL
                        SET DSCDFISOPENF = (SELECT MAX(DSCFOPTMP)
                                              FROM CFOPTEMP
                                             WHERE NRCFOPTEMP = V_CFOPTEMP)
                      WHERE CDFILIAL   = P_FILIAL
                        AND NRLANCTONF = P_LANCTONF
                        AND DSCDFISOPENF IS NULL;

                  END IF;

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

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

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

                  DELETE CFOPTEMP
                   WHERE NRCFOPTEMP = V_CFOPTEMP;


                  SELECT MAX(IDORDPRIMDFENT)
                    INTO V_IDORDPRIMDFENT
                    FROM PARAMGERAL;


                  IF (C_ITEMPROD.IDPRODBONIF = 'N') OR (V_CDTIPOOPERBONIF = 'N') THEN
                     CONSULTA_CSOSN(P_ENTRSAID, P_EMPRESA, C_ITEMPROD.CDARVPROD, P_INSCESTA, P_TIPOOPER, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC, V_IDINTEREST, V_CDFISCOPERSN);
                  ELSE
                     CONSULTA_CSOSN(P_ENTRSAID, P_EMPRESA, C_ITEMPROD.CDARVPROD, P_INSCESTA, V_CDTIPOOPERBONIF, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC, V_IDINTEREST, V_CDFISCOPERSN);
                  END IF;

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

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

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

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

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

                  DELETE CFOPTEMP
                  WHERE NRCFOPTEMP = V_CFOPTEMP;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

         DELETE TRABIMPOSNFTOT WHERE CDFILIMPTOT = P_FILIAL AND NRLANCIMPTOT = P_LANCTONF;

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

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

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

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

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

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

      END LOOP;
   END IF;

   V_DIFERENCA := 0;
   /* RATEIO DOS ENCARGOS PARA OS PRODUTOS DA NOTA. ESTE RATEIO 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

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

            FOR C_ITEMPRODUTO IN (SELECT NRSEQITPROD, VRTOTAITEM
                                    FROM ITEMPRODUTO
                                   WHERE CDFILIAL = P_FILIAL
                                     AND NRLANCTONF = P_LANCTONF
                                     AND (NVL(IDPRODBONIF, 'N') = 'N')) 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
                                       AND (NVL(IDPRODBONIF, 'N') = 'N')
                                     GROUP BY CDFILIAL, NRLANCTONF) TOTAL
                WHERE ITEMPRODUTO.CDFILIAL = TOTAL.CDFILIAL
                  AND ITEMPRODUTO.NRLANCTONF = TOTAL.NRLANCTONF
                  AND ITEMPRODUTO.NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;

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

            V_DIFERENCA := C_ITEMENCARGO.VRITEMENCA - V_VRFRETEITEM;

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

            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 NRSEQITPROD, VRTOTAITEM
                                    FROM ITEMPRODUTO
                                   WHERE CDFILIAL = P_FILIAL
                                     AND NRLANCTONF = P_LANCTONF
                                     AND (NVL(IDPRODBONIF, 'N') = 'N')) 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
                                       AND (NVL(IDPRODBONIF, 'N') = 'N')
                                     GROUP BY CDFILIAL, NRLANCTONF) TOTAL
                WHERE ITEMPRODUTO.CDFILIAL = TOTAL.CDFILIAL
                  AND ITEMPRODUTO.NRLANCTONF = TOTAL.NRLANCTONF
                  AND ITEMPRODUTO.NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;

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

            V_DIFERENCA := C_ITEMENCARGO.VRITEMENCA - V_VRSEGURITEM;

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

            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 NRSEQITPROD, VRTOTAITEM
                                    FROM ITEMPRODUTO
                                   WHERE CDFILIAL = P_FILIAL
                                     AND NRLANCTONF = P_LANCTONF
                                     AND (NVL(IDPRODBONIF, 'N') = 'N')) 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
                                       AND (NVL(IDPRODBONIF, 'N') = 'N')
                                     GROUP BY CDFILIAL, NRLANCTONF) TOTAL
                WHERE ITEMPRODUTO.CDFILIAL = TOTAL.CDFILIAL
                  AND ITEMPRODUTO.NRLANCTONF = TOTAL.NRLANCTONF
                  AND ITEMPRODUTO.NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;

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

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

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

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

            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;

            FOR C_ITEMPRODUTO IN (SELECT NRSEQITPROD, VRTOTAITEM
                                    FROM ITEMPRODUTO
                                   WHERE CDFILIAL = P_FILIAL
                                     AND NRLANCTONF = P_LANCTONF
                                     AND (NVL(IDPRODBONIF, 'N') = 'N')) 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
                                       AND (NVL(IDPRODBONIF, 'N') = 'N')
                                     GROUP BY CDFILIAL, NRLANCTONF) TOTAL
                WHERE ITEMPRODUTO.CDFILIAL = TOTAL.CDFILIAL
                  AND ITEMPRODUTO.NRLANCTONF = TOTAL.NRLANCTONF
                  AND ITEMPRODUTO.NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;

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

            V_DIFERENCA := C_ITEMENCARGO.VRITEMENCA - V_VROUTRASDESPITEM;

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

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

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

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

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

            V_DIFERENCA := C_ITEMENCARGO.VRITEMENCA - V_VRDESPADUANEIRA;

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

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

   /*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(IP.IDPRODBONIF, 'N') = 'N')
                                        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)
                                          AND (NVL(IP.IDPRODBONIF, 'N') = 'N')
                                        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') 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 (NVL(IP.IDPRODBONIF, 'N') = 'N')
                                           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)
                                                               AND (NVL(I.IDPRODBONIF, 'N') = 'N')));

               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(IP.IDPRODBONIF, 'N') = 'N')
                                        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)
                                          AND (NVL(IP.IDPRODBONIF, 'N') = 'N')
                                        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') 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 (NVL(IP.IDPRODBONIF, 'N') = 'N')
                                           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)
                                                               AND (NVL(I.IDPRODBONIF, 'N') = 'N')));

               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)
                                        AND (NVL(IP.IDPRODBONIF, 'N') = 'N')) 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)
                                          AND (NVL(IP.IDPRODBONIF, 'N') = 'N')
                                        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') 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 (NVL(IP.IDPRODBONIF, 'N') = 'N')
                                           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)
                                                               AND (NVL(I.IDPRODBONIF, 'N') = 'N')));

               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;
               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)
                                        AND (NVL(IP.IDPRODBONIF, 'N') = 'N')) 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)
                                          AND (NVL(IP.IDPRODBONIF, 'N') = 'N')
                                        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') THEN
                     UPDATE ITEMPRODUTO
                        SET VROUTRASDESPITEM = TRUNC((C_ITEMENCARGO.VRITEMENCA * (V_PERCENTITEM / 100)), 2)
                      WHERE CDFILIAL  = P_FILIAL
                        AND NRLANCTONF = P_LANCTONF
                        AND NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;
                  ELSE
                     UPDATE ITEMPRODUTO
                        SET VROUTRASDESPITEM = ROUND((C_ITEMENCARGO.VRITEMENCA * (V_PERCENTITEM / 100)), 2)
                      WHERE CDFILIAL  = P_FILIAL
                        AND NRLANCTONF = P_LANCTONF
                        AND NRSEQITPROD = C_ITEMPRODUTO.NRSEQITPROD;
                  END IF;
               END LOOP;
               /*AJUSTE DE VALORES*/
               SELECT SUM(VROUTRASDESPITEM)
                 INTO V_VROUTRASDESPITEM
                 FROM ITEMPRODUTO
                WHERE CDFILIAL = P_FILIAL
                  AND NRLANCTONF = P_LANCTONF;

               V_DIFERENCA := C_ITEMENCARGO.VRITEMENCA - V_VROUTRASDESPITEM;

               IF V_DIFERENCA <> 0 THEN
                  UPDATE ITEMPRODUTO
                     SET VROUTRASDESPITEM = VROUTRASDESPITEM + V_DIFERENCA
                   WHERE CDFILIAL = P_FILIAL
                     AND NRLANCTONF = P_LANCTONF
                     AND NRSEQITPROD = (SELECT MAX(NRSEQITPROD)
                                         FROM ITEMPRODUTO 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 (NVL(IP.IDPRODBONIF, 'N') = 'N')
                                           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)
                                                               AND (NVL(I.IDPRODBONIF, 'N') = 'N')));

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

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

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

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

               V_DIFERENCA := C_ITEMENCARGO.VRITEMENCA - V_VRDESPADUANEIRA;

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

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


   --CALCULO DO VALOR TOTAL DA NOTA FISCAL

   V_TOTALNOTA := 0;

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

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

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

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

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

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



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

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

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

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

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

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

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

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

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

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

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

   /* Calculo do valor total da nf de importacao*/
   IF (V_IDNFIMPORTACAO = 'S') THEN
      UPDATE NOTAFISCAL
         SET VRNOTAFISC = ROUND(V_TOTALNOTA, 2)
       WHERE CDFILIAL   = P_FILIAL    AND
             NRLANCTONF = P_LANCTONF;

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

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

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

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

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

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

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

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

         V_VRDIFERENCA := V_VRTOTIMPONF - C_VRIMPOSTO.VRIMPOSIT;

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

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

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

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

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


      V_VRDIFERENCA := V_VRNOTAFISC - V_VRBRUTO;

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

         UPDATE ITEMPRODUTO
         SET VRBRUTITEM = VRBRUTITEM + V_VRDIFERENCA
         WHERE CDFILIAL    = P_FILIAL   AND
               NRLANCTONF  = P_LANCTONF AND
               NRSEQITPROD = V_NRSEQITPROD;
      END IF;

   -- RECALCULO DO VALOR CONTABIL DO ITEM

      IF (P_TIPOOPER <> '03') THEN

         UPDATE ITEMPRODUTO
            SET VRBRUTITEM = ROUND(VRBRUTITEM, 2)
          WHERE CDFILIAL   = P_FILIAL
            AND NRLANCTONF = P_LANCTONF;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

   ARREDONDA_BASECALC(W_E, P_FILIAL, P_LANCTONF);

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

   IF V_SEQUIMPOSTNF = '01' THEN
      DELETE IMPOSTONF
      WHERE (CDFILIAL = P_FILIAL) AND
            (NRLANCTONF = P_LANCTONF);
   END IF;
   
   UPDATE TRABITPROIMPOS
      SET CDFISCIMPOIT = CASE WHEN VRIMPOSIT > 0 THEN 1 ELSE 2 END
    WHERE CDFISCIMPOIT IS NULL
      AND CDFILIMPOIT  = P_FILIAL
      AND NRLANCIMPOIT = P_LANCTONF
      AND NRSEQITPRO = '1';

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

      V_CDFILIREDU := NULL;

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

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

         V_VRCONTITIMP := 0;

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

         IF (V_IDCALCDIFENTFISC = 'N') THEN

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

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

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

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

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

         V_VRCONTITIMP := 0;

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

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

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

      END IF;
   END LOOP;

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

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

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

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

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


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

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

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

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

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

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

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

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

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

   END LOOP;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

   END IF;

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

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

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

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

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

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

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


   /* ESTA ROTINA ABAIXO SERVE PARA ATUALIZAR O VALOR 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 THEN
      FOR C_ATUAVRCONT IN (SELECT T.CDIMPOSTOIT, SUM(T.VRIMPOSIT) AS VRIMPOSIT, T.CDFISCIMPOIT,
                                  I.IDIMPORECUP, I.CDCCTBLATIV, I.CDCCTBLPASS, I.IDTRATIMPO
                           FROM TRABITPROIMPOS T, IMPOSTO I
                           WHERE T.CDFILIMPOIT  = P_FILIAL      AND
                                 T.NRLANCIMPOIT = P_LANCTONF    AND
                                 T.NRSEQITPRO   = W_1           AND
                                 I.CDIMPOSTO    = T.CDIMPOSTOIT AND
                                 I.IDTIPCONTAB  = W_D
                           GROUP BY T.CDIMPOSTOIT, T.CDFISCIMPOIT, I.IDIMPORECUP,
                                    I.CDCCTBLATIV, I.CDCCTBLPASS, I.IDTRATIMPO) LOOP

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

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

         IF V_VRDIFERENCA <> 0 THEN
            V_IMPOCONTAB := 0;

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

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

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

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

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

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

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

            V_DTSAIDNFORIG := NULL;

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

            IF (V_EXISTE_ROT) > 0 THEN

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

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

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

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

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

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

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

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

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

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

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

               V_VRCUSTOLOG := 0;
               V_VRCUSTOSEG := 0;

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

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

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

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

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

            --Alteracao para verificar se o CFOP atualiza estoque

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

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

            IF(V_CFOPTPOPER > 0) THEN

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

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

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

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

         END LOOP;
      END IF;
   END IF;

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

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

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

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

   IF V_IDOPERDEVONF = 'S' THEN

      V_TOTALNOTA := ROUND(V_TOTALNOTA, 2);

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

   -- Recalcula diferencial de aliquota considerando valor contabil quando nao possuir reducao de base de calculo

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

      V_CDFILIREDU := NULL;

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

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

         V_VRCONTITIMP := 0;

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

         IF (V_IDCALCDIFENTFISC = 'N') THEN

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

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

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

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

         V_VRCONTITIMP := 0;

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

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

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

      END IF;
   END LOOP;

   /*Excluir/Incluir mensagens da tabela intg_dadosadic*/
   IF V_NRACESSONFE IS NOT NULL THEN

      V_TAMMENSADICXML := 0;
      V_CONTMENS := 1;
      BEGIN
         SELECT LENGTH(DSDADOADICXML)
           INTO V_TAMMENSADICXML
           FROM INTG_DADOSADIC
          WHERE NRACESSONFE = V_NRACESSONFE;
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_TAMMENSADICXML := 0;
      END;

      IF V_TAMMENSADICXML > 0 THEN
         WHILE (V_CONTMENS < V_TAMMENSADICXML) LOOP

            IF (V_CONTMENS + 120) > V_TAMMENSADICXML THEN
               SELECT SUBSTR(DSDADOADICXML, V_CONTMENS, (V_TAMMENSADICXML - V_CONTMENS))
                 INTO V_MENSXML
                 FROM INTG_DADOSADIC
                WHERE NRACESSONFE = V_NRACESSONFE;

               V_CONTMENS := V_TAMMENSADICXML;
            ELSE
               SELECT SUBSTR(DSDADOADICXML, V_CONTMENS, 120)
                 INTO V_MENSXML
                 FROM INTG_DADOSADIC
                WHERE NRACESSONFE = V_NRACESSONFE;

               V_CONTMENS := V_CONTMENS + 120;
            END IF;

            DELETE
              FROM DADOSADIC
             WHERE CDFILIAL   = P_FILIAL
               AND NRLANCTONF = P_LANCTONF
               AND TRIM(DSDADOADIC) = TRIM(V_MENSXML);
         END LOOP;
      END IF;

      SELECT MAX(NRDADOADIC)
        INTO V_DADOADIC
        FROM DADOSADIC
       WHERE (CDFILIAL   = P_FILIAL) AND
             (NRLANCTONF = P_LANCTONF);

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

      V_TAMMENSADICXML := 0;
      V_CONTMENS := 1;
      BEGIN
         SELECT LENGTH(DSDADOADICXML)
           INTO V_TAMMENSADICXML
           FROM INTG_DADOSADIC
          WHERE NRACESSONFE = V_NRACESSONFE;
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_TAMMENSADICXML := 0;
      END;

      IF V_TAMMENSADICXML > 0 THEN

         WHILE (V_CONTMENS < V_TAMMENSADICXML) LOOP

            IF (V_CONTMENS + 120) > V_TAMMENSADICXML THEN
               SELECT SUBSTR(DSDADOADICXML, V_CONTMENS, (V_TAMMENSADICXML - V_CONTMENS))
                 INTO V_MENSXML
                 FROM INTG_DADOSADIC
                WHERE NRACESSONFE = V_NRACESSONFE;

               V_CONTMENS := V_TAMMENSADICXML;
            ELSE
               SELECT SUBSTR(DSDADOADICXML, V_CONTMENS, 120)
                 INTO V_MENSXML
                 FROM INTG_DADOSADIC
                WHERE NRACESSONFE = V_NRACESSONFE;

               V_CONTMENS := V_CONTMENS + 120;
            END IF;

            INSERT INTO DADOSADIC(CDFILIAL, NRLANCTONF, NRDADOADIC, CDMENSAGEM, DSDADOADIC)
                        VALUES(P_FILIAL, P_LANCTONF, V_DADOADIC, NULL, TRIM(V_MENSXML));


            V_DADOADIC := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_DADOADIC) + 1)),3,0);
         END LOOP;
      END IF;
   END IF;
   /*Excluir/Incluir mensagens da tabela intg_dadosadic*/

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

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

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

      V_VRIMPDIFALIQ := 0;

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

      IF V_VRIMPDIFALIQ > 0 THEN

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

   -- Caso utiliza atualizacao de estoque na aprovacao da nota fiscal
      IF (NVL(P_AUDIT, 'N') <> 'S')  THEN
         IF (V_IDPERLANESTAPNF = 'S') AND (P_TIPOOPER <> '10') THEN
            UPDATE ITLANCTOEST
               SET IDEVOLESTOQ  = 'N'
             WHERE CDFILIAL     = P_FILIAL
               AND NRLANCESTQ   = P_LANCESTQ;
         END IF;
      END IF;   

      IF (NVL(P_AUDIT, 'N') = 'S')  AND (NVL(V_IDSTATUS, 'P') = 'P') THEN
         IF (V_IDPERLANESTAPNF = 'S') AND (P_TIPOOPER <> '10') THEN
            UPDATE ITLANCTOEST
               SET IDEVOLESTOQ  = 'N'
             WHERE CDFILIAL     = P_FILIAL
               AND NRLANCESTQ   = P_LANCESTQ;
         END IF;
      END IF;

   IF (V_IDORIGDESTNF = 'F') AND (P_TIPOOPER <> '03') AND (NVL(V_ESTORNOCANC, 'N') = 'N')THEN
      CONHECIMENTO_TRANSPORTE(P_FILIAL, P_LANCTONF, P_LANCESTQ);
   END IF;

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

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

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

      END IF;
   END LOOP;

   DELETE ALIQTEMP
   WHERE  NRALIQTEMP = P_FILIAL||P_LANCTONF;

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

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

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

         IF NOT V_CDFILIAGENT IS NULL THEN

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

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

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

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

                  IF V_BOLANESTSAIDAG THEN
                     /* Gerando o registro na tabela LANCTOESTOQ para a entrada na filial relacionada ao agente de 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_TPOPERREMESSA := NULL;
                     BEGIN
                        SELECT CDTPOOPREMESSA
                          INTO V_TPOPERREMESSA
                          FROM PARAMGERAL
                         WHERE CDPARGERAL = '0001';
                     EXCEPTION
                     WHEN NO_DATA_FOUND THEN
                        V_TPOPERREMESSA := NULL;
                     END;

                     IF (V_TPOPERREMESSA IS NULL) THEN
                        RAISE_APPLICATION_ERROR(-20501, 'Tipo de 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, CDEMPRESA, CDINSCESTA, CDINSCMUNI, NRLANCTONF, NRINSJURNF,
                         IDTPIJURNF, DTEMISSAO, NRNOTAFISC, CDSERIE, IDBLOQUEADO, IDDOCFISCAL,
                         IDDOCFINANC, VRPRODUTOS, VRNOTAFISC, IDENTRSAIDOP, CDTIPOOPER, CDCLIENTE,
                         DTENTRSAID, CDFILIEMIT, IDORIGDESTNF, CDFORNECED, CDFILIRECE, NRAPURACFAT)

                     VALUES
                        (V_CDFILIAGENT, V_CDEMPRESAAG, V_CDINSCESTAAG, V_CDINSCMUNIAG, V_NRLANCTONFAG, V_NRINSJURNF,
                         V_IDTPIJURNF, P_INIVALID, NULL, NULL, 'N', 'N',
                         'S', V_VRPRODUTOS, V_VRNOTAFISC, 'S', V_TPOPERREMESSA, P_FORNECED,
                         P_INIVALID, V_CDFILIAGENT, 'C', NULL, NULL, NULL);

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

                     INSERT INTO LANCTOESTOQ
                        (CDFILIAL, CDFILIMOVI, NRLANCESTQ, IDTPLANCTO,
                         DTLANCESTQ, DSLANCESTQ,
                         NRLANCTONF, CDOPERADOR, CDALMOXARIFE, CDLOCALESTOQ)
                     VALUES
                        (V_CDFILIAGENT, V_CDFILIAGENT, V_NRLANESTENTRAG, '4',
                         P_INIVALID, 'NF Retorno Armazenagem - lanc. ' || V_CDFILIRECE || ' ' || P_LANCTONF,
                         V_NRLANCTONFAG, P_CDOPERADOR, NULL, NULL);

                     V_BOLANESTSAIDAG := FALSE;
                  END IF;

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

                  INSERT INTO ITLANCTOEST
                     (CDFILIAL, NRLANCESTQ, NRSEQUITEM, CDPRODUTO,
                      CDPRODMOVI, VRUNILANCTO, VRTOTLANCTO, QTTOTLANCTO,
                      QTLANCTOEST, IDTIPOMOVI, DTLANCMOVI, IDORDEMCLC,
                      VRLANCTOBRUT, VRLANCTOEST, CDFILIMOVI, CDALMOXARIFE,
                      CDLOCALESTOQ, NRLOTEESTQ, NRSUBLOTE, IDORIGEMPROD)
                  VALUES
                     (V_CDFILIAGENT, V_NRLANESTENTRAG, C_ITLANCTOEST.NRSEQITPROD, C_ITLANCTOEST.CDPRODUTO,
                       C_ITLANCTOEST.CDPRODESTO, C_ITLANCTOEST.VRUNITITEM, C_ITLANCTOEST.VRTOTAITEM, C_ITLANCTOEST.QTITEMPROD,
                      C_ITLANCTOEST.QTITEMPROD * C_ITLANCTOEST.VRFATOCONV, '4', P_INIVALID, '9',
                      C_ITLANCTOEST.VRBRUTITEM, C_ITLANCTOEST.VRTOTAITEM, V_CDFILIAGENT, V_CDALMOXARIFEAG,
                      V_CDLOCALESTOQAG, V_NRLOTEESTQAG, V_NRSUBLOTEAG, C_ITLANCTOEST.IDORIGEMPROD);
               END LOOP;
            END IF;
            -- se possuir agente de terceirizacao e filial OL sera efetuada alteracao no pedido OL e na reserva do pedido
            IF NOT V_CDFILIOLAGETERC IS NULL THEN

               FOR C_INTG_ITENS IN (SELECT I.NRAUTOFORN, P.CDPRODUTO, SUM(I.QTITEMPROD) AS QTITEMPROD
                                      FROM INTG_NOTAFISCAL N, INTG_ITEMPRODUTO I, PRODFORNXML P
                                     WHERE N.NRACESSONFE = V_NRACESSONFE
                                       AND I.NRACESSONFE = N.NRACESSONFE
                                       AND P.CDFORNECED   = N.CDFORNECED
                                       AND P.CDPRODUTOXML = I.CDPRODUTO
                                     GROUP BY I.NRAUTOFORN, P.CDPRODUTO)
               LOOP
                  FOR C_ITEM_PED IN (SELECT IT.CDFILDEST, IT.CDFILLANC, IT.NRPEDEXOL, IT.CDMARCA, IT.CDPRODUTO, IT.DTPROGENPEOL
                                       FROM PEDIDOEXOL P, ITEMPEDEXOL IT, RELACPRODOL R
                                      WHERE P.USR_NRPEDIDO = C_INTG_ITENS.NRAUTOFORN
                                        AND IT.CDFILDEST = P.CDFILDEST
                                        AND IT.CDFILLANC = P.CDFILLANC
                                        AND IT.NRPEDEXOL = P.NRPEDEXOL
                                        AND IT.IDBAIXENPEOL IS NULL
                                        AND R.CDPRARVORIG = C_INTG_ITENS.CDPRODUTO
                                        AND IT.CDPRODUTO  = R.CDPRARVORIG
                                        AND IT.CDMARCA    = R.CDMARCA
                                      ORDER BY IT.CDPRODUTO, IT.DTPROGENPEOL)
                  LOOP
                     -- altera a qtde atendida do pedido OL com a qtde. da nota fiscal somente para a primeira data de entrega
                     UPDATE ITEMPEDEXOL
                        SET QTATENDPEDOL = C_INTG_ITENS.QTITEMPROD
                      WHERE CDFILDEST    = C_ITEM_PED.CDFILDEST
                        AND CDFILLANC    = C_ITEM_PED.CDFILLANC
                        AND NRPEDEXOL    = C_ITEM_PED.NRPEDEXOL
                        AND CDMARCA      = C_ITEM_PED.CDMARCA
                        AND CDPRODUTO    = C_ITEM_PED.CDPRODUTO
                        AND DTPROGENPEOL = C_ITEM_PED.DTPROGENPEOL;

                     -- altera a qtde reservada do pedido OL e a filial da reserva do pedido para a filial OL
                     UPDATE RESERVAPEDEXOL
                        SET CDFILRESOL    = V_CDFILIOLAGETERC,
                            QTRESERVESTOL = C_INTG_ITENS.QTITEMPROD,
                            CDFILIAL      = P_FILIAL,
                            NRLANCTONF    = P_LANCTONF
                      WHERE CDFILDEST    = C_ITEM_PED.CDFILDEST
                        AND CDFILLANC    = C_ITEM_PED.CDFILLANC
                        AND NRPEDEXOL    = C_ITEM_PED.NRPEDEXOL
                        AND CDMARCA      = C_ITEM_PED.CDMARCA
                        AND CDPRODUTO    = C_ITEM_PED.CDPRODUTO
                        AND DTPROGENPEOL = C_ITEM_PED.DTPROGENPEOL;

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

         -- Atualiza valor contabil do produto considerando o custo medio do produto em estoque caso o parametro esteja marcado
         IF (V_IDOPERDEVONF = W_S AND V_IDUTCUSORIGEST = W_S) THEN
            FOR C_ITLANCTOEST IN (SELECT CDFILIMOVI, NRSEQITPROD,IP.CDPRODUTO,VRUNITITEM,VRTOTAITEM,
                                         QTITEMPROD,CDPRODESTO,VRBRUTITEM,VRDESCITEM,VRCONTITEM,
                                         NVL(IP.CDALMOXARIFE, ' ') CDALMOXARIFE,
                                         NVL(IP.CDLOCALESTOQ, ' ') CDLOCALESTOQ,
                                         NVL(NRLOTEESTQ, ' ') NRLOTEESTQ,
                                         NVL(NRSUBLOTE, ' ') NRSUBLOTE,
                                         P.VRFATOCONV
                                   FROM ITEMPRODUTO IP, PRODUTO P
                                  WHERE IP.CDFILIAL    = P_FILIAL     AND
                                        IP.NRLANCTONF  = P_LANCTONF   AND
                                        P.CDPRODUTO    = IP.CDPRODUTO) LOOP


               V_VRCUSTENTR := ROUND(CUSTO_PRODUTO_LCEST(C_ITLANCTOEST.CDFILIMOVI, C_ITLANCTOEST.CDPRODESTO, V_CDTIPCUSTEST, P_INIVALID,
                                                         V_DTATUAL, C_ITLANCTOEST.CDALMOXARIFE, C_ITLANCTOEST.CDLOCALESTOQ,
                                                         C_ITLANCTOEST.NRLOTEESTQ, C_ITLANCTOEST.NRSUBLOTE), 5);

               UPDATE ITEMPRODUTO
                  SET VRCONTITEM = ((C_ITLANCTOEST.QTITEMPROD * C_ITLANCTOEST.VRFATOCONV) * V_VRCUSTENTR)
                WHERE CDFILIAL =  P_FILIAL
                  AND NRLANCTONF = P_LANCTONF
                  AND NRSEQITPROD = C_ITLANCTOEST.NRSEQITPROD;
            END LOOP;
         END IF;
      END IF;
   END IF;
  -- Mensagem Dados Adicionais ICMS Interestadual - DIFAL
   DELETE
     FROM DADOSADIC
    WHERE CDFILIAL = P_FILIAL
      AND NRLANCTONF = P_LANCTONF
      AND DSDADOADIC LIKE 'Valores totais do ICMS Interestadual%';

   SELECT MAX(NRDADOADIC)
     INTO V_DADOADIC
     FROM DADOSADIC
    WHERE CDFILIAL = P_FILIAL
      AND NRLANCTONF = P_LANCTONF;
   IF V_DADOADIC IS NULL THEN
      V_DADOADIC := '001';
   ELSE
      V_DADOADIC := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_DADOADIC) + 1)), 3, 0);
   END IF;
   FOR C_VRIMPOPARTDEST IN (SELECT VRALIQINTEDEST,
                                   VRALIQFCP,
                                   SUM(VRIMPOPARTDEST) AS VRIMPOPARTDEST,
                                   SUM(VRIMPOPARTREME) AS VRIMPOPARTREME,
                                   SUM(VRIMPOFCP) AS VRIMPOFCP
                              FROM TRABITPROIMPOS IT, IMPOSTO I
                             WHERE IT.CDIMPOSTOIT = I.CDIMPOSTO
                               AND I.CDIMPOSTONFE = '00'
                               AND CDFILIMPOIT  = P_FILIAL
                               AND NRLANCIMPOIT = P_LANCTONF
                             GROUP BY VRALIQINTEDEST,
                                   VRALIQFCP
                            HAVING SUM(VRIMPOPARTDEST) > 0
                             ORDER BY VRALIQINTEDEST)
   LOOP
      SELECT DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(C_VRIMPOPARTDEST.VRIMPOPARTDEST, 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(C_VRIMPOPARTDEST.VRIMPOPARTDEST, 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(C_VRIMPOPARTDEST.VRIMPOPARTDEST, 2), '9999999999999.99'))),
             DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(C_VRIMPOPARTDEST.VRALIQINTEDEST, 2), '999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(C_VRIMPOPARTDEST.VRALIQINTEDEST, 2), '999.99')), LTRIM(TO_CHAR(ROUND(C_VRIMPOPARTDEST.VRALIQINTEDEST, 2), '999.99'))),
             DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(C_VRIMPOPARTDEST.VRIMPOPARTREME, 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(C_VRIMPOPARTDEST.VRIMPOPARTREME, 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(C_VRIMPOPARTDEST.VRIMPOPARTREME, 2), '9999999999999.99'))),
             DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(C_VRIMPOPARTDEST.VRIMPOFCP, 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(C_VRIMPOPARTDEST.VRIMPOFCP, 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(C_VRIMPOPARTDEST.VRIMPOFCP, 2), '9999999999999.99'))),
             DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(C_VRIMPOPARTDEST.VRALIQFCP, 2), '999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(C_VRIMPOPARTDEST.VRALIQFCP, 2), '999.99')), LTRIM(TO_CHAR(ROUND(C_VRIMPOPARTDEST.VRALIQFCP, 2), '999.99')))
        INTO V_VRIMPOPARTDESTINO,
             V_VRALIQPARTDESTINO,
             V_VRIMPOPARTORIGEM,
             V_VRIMPOFCPDESTINO,
             V_VRALIQFCPDESTINO
        FROM DUAL;

      V_MSGDADOSADIC := 'Valores totais do ICMS Interestadual: DIFAL da UF destino R$' || V_VRIMPOPARTDESTINO || ' (Aliquota interna do destinatario ' || V_VRALIQPARTDESTINO || '%)';
      IF C_VRIMPOPARTDEST.VRIMPOFCP > 0 THEN
         V_MSGDADOSADIC := V_MSGDADOSADIC || ' + ' || V_VRALIQFCPDESTINO || '% de FECP totalizando R$' || V_VRIMPOFCPDESTINO;
      END IF;
      V_MSGDADOSADIC := V_MSGDADOSADIC || '; DIFAL da UF Origem R$' || V_VRIMPOPARTORIGEM ;
      V_MSGDADOSADIC := V_MSGDADOSADIC || '. Atendendo ao disposto na Emenda Constitucional n 87 de 2015';

      INSERT INTO DADOSADIC
         (CDFILIAL,
          NRLANCTONF,
          NRDADOADIC,
          CDMENSAGEM,
          DSDADOADIC)
      VALUES
         (P_FILIAL,
          P_LANCTONF,
          V_DADOADIC,
          '',
          V_MSGDADOSADIC);
      V_DADOADIC := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_DADOADIC) + 1)), 3, 0);
   END LOOP;
  /*Colocando nos dados adicionais da nota base de calculo e valor do imposto quando o ICMS ST importar do XML como encargo
    e o CST for 60*/ 
   DELETE FROM DADOSADIC
    WHERE CDFILIAL = P_FILIAL
      AND NRLANCTONF = P_LANCTONF
      AND DSDADOADIC LIKE 'Valores ICMS ST (CST 60): BC%';	  
   IF (V_IDNFGERADAVIAXML = 'S') THEN     
      BEGIN
         SELECT SUM(IT.VRBASECALCIT), SUM(IT.VRIMPOSTOIT)
           INTO V_VRBCITENTR, V_VRIMPITENTR
           FROM INTG_TRABITPROIMPOS IT, IMPOSTO I
          WHERE IT.NRACESSONFE = V_NRACESSONFE
            AND IT.CDIMPOSTOIT = I.CDIMPOSTO
            AND I.CDENCARGOIMPXML IS NOT NULL
            AND I.CDIMPOSTONFE = '80'
            AND I.IDIMPORTAIMPXML = 'S'
            AND SUBSTR(IT.CDSITUTRIBIT,2,2) = '60';
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_VRBCITENTR := 0;
            V_VRIMPITENTR := 0;
      END;     
      IF (V_VRIMPITENTR > 0) THEN
          INSERT INTO DADOSADIC(CDFILIAL, NRLANCTONF, NRDADOADIC, DSDADOADIC)
                         VALUES(P_FILIAL, P_LANCTONF, V_DADOADIC, 'Valores ICMS ST (CST 60): 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;
END;
/