                           SELECT NVL(SUM(VRICMSST),0), NVL(SUM(VRBASECALC),0)
                             INTO V_VRICMSST, V_VRBASECALC
                             FROM INFICMSST
                            WHERE CDFILIAL = P_FILIAL
                              AND NRLANCTONF = P_LANCTONF;

                           IF V_VRICMSST > 0 THEN

                              UPDATE ITEMENCARGO
                                 SET VRITEMENCA = ROUND(VRITEMENCA + V_VRICMSST,2)
                               WHERE CDFILIAL = P_FILIAL
                                 AND NRLANCTONF = P_LANCTONF
                                 AND CDENCARGO = V_CDENCARGOOD;

                              IF V_VRBASECALC > 0 THEN
                                 SELECT COUNT(*)
                                   INTO V_EXISTDSDADOSADIC
                                   FROM DADOSADIC
                                  WHERE CDFILIAL = P_FILIAL
                                    AND NRLANCTONF = P_LANCTONF
                                    AND DSDADOADIC LIKE 'Base de Cálculo do ICMS ST%';

                                 IF V_EXISTDSDADOSADIC = 0 THEN

                                    INSERT INTO DADOSADIC(CDFILIAL, NRLANCTONF, NRDADOADIC, DSDADOADIC)
                                                   VALUES(P_FILIAL, P_LANCTONF, V_DADOADIC, 'Base de Cálculo do ICMS ST: R$'||DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(V_VRBASECALC , 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(V_VRBASECALC , 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(V_VRBASECALC , 2), '9999999999999.99')))|| ' ICMS ST: R$'|| DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(V_VRICMSST, 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(V_VRICMSST, 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(V_VRICMSST, 2), '9999999999999.99'))));

                                    V_DADOADIC := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_DADOADIC) + 1)),3,0);
                                 ELSE
                                    UPDATE DADOSADIC
                                       SET DSDADOADIC = 'Base de Cálculo do ICMS ST: R$'||DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(V_VRBASECALC, 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(V_VRBASECALC, 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(V_VRBASECALC, 2), '9999999999999.99')))|| ' ICMS ST: R$'|| DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(V_VRICMSST, 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(V_VRICMSST, 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(V_VRICMSST, 2), '9999999999999.99')))
                                      WHERE CDFILIAL = P_FILIAL
                                        AND NRLANCTONF = P_LANCTONF
                                        AND DSDADOADIC LIKE 'Base de Cálculo do ICMS ST%';
                                 END IF;
                              ELSE
                                 SELECT COUNT(*)
                                   INTO V_EXISTDSDADOSADIC
                                   FROM DADOSADIC
                                  WHERE CDFILIAL = P_FILIAL
                                    AND NRLANCTONF = P_LANCTONF
                                    AND DSDADOADIC LIKE 'ICMS ST: R$%';

                                 IF V_EXISTDSDADOSADIC = 0 THEN
                                    INSERT INTO DADOSADIC(CDFILIAL, NRLANCTONF, NRDADOADIC, DSDADOADIC)
                                                   VALUES(P_FILIAL, P_LANCTONF, V_DADOADIC, 'ICMS ST: R$ '||DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(V_VRICMSST, 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(V_VRICMSST, 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(V_VRICMSST, 2), '9999999999999.99'))));

                                    V_DADOADIC := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_DADOADIC) + 1)),3,0);
                                 ELSE
                                    UPDATE DADOSADIC
                                       SET DSDADOADIC = 'ICMS ST: R$ '||DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(V_VRICMSST, 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(V_VRICMSST, 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(V_VRICMSST, 2), '9999999999999.99')))
                                      WHERE CDFILIAL = P_FILIAL
                                        AND NRLANCTONF = P_LANCTONF
                                        AND DSDADOADIC LIKE 'ICMS ST: R$%';
                                 END IF;
                              END IF;
                           END IF;
                        ELSE
                           UPDATE ITEMENCARGO
                              SET VRITEMENCA = ROUND(VRITEMENCA + (V_VRENCAICMSSTIT * V_VRFATOCONV) + V_VRTOTALICMSST,2)
                            WHERE CDFILIAL = P_FILIAL
                              AND NRLANCTONF = P_LANCTONF
                              AND CDENCARGO = V_CDENCARGOOD;

                           SELECT COUNT(*)
                             INTO V_EXISTDSDADOSADIC
                             FROM DADOSADIC
                            WHERE CDFILIAL = P_FILIAL
                              AND NRLANCTONF = P_LANCTONF
                              AND DSDADOADIC LIKE 'ICMS ST: R$%';

                           IF V_EXISTDSDADOSADIC = 0 THEN
                              INSERT INTO DADOSADIC(CDFILIAL, NRLANCTONF, NRDADOADIC, DSDADOADIC)
                                             VALUES(P_FILIAL, P_LANCTONF, V_DADOADIC, 'ICMS ST: R$ '||DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(V_VRTOTALICMSST + (V_VRENCAICMSSTIT * V_VRFATOCONV), 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(V_VRTOTALICMSST + (V_VRENCAICMSSTIT * V_VRFATOCONV), 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(V_VRTOTALICMSST + (V_VRENCAICMSSTIT * V_VRFATOCONV), 2), '9999999999999.99'))));

                              V_DADOADIC := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_DADOADIC) + 1)),3,0);
                           ELSE
                              UPDATE DADOSADIC
                                 SET DSDADOADIC = 'ICMS ST: R$ '||DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(V_VRTOTALICMSST + (V_VRENCAICMSSTIT * V_VRFATOCONV), 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(V_VRTOTALICMSST + (V_VRENCAICMSSTIT * V_VRFATOCONV), 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(V_VRTOTALICMSST + (V_VRENCAICMSSTIT * V_VRFATOCONV), 2), '9999999999999.99')))
                                WHERE CDFILIAL = P_FILIAL
                                  AND NRLANCTONF = P_LANCTONF
                                  AND DSDADOADIC LIKE 'ICMS ST: R$%';
                           END IF;
                        END IF;
                     END IF;
                  END IF;
               END IF;
            END IF;
         END IF;
         IF (V_IDGERIPIDESPA = 'S') THEN
            SELECT MAX(CDENCARGO)
              INTO V_CDENCARGOOD
              FROM ENCARGO
             WHERE CDENCARGONFE = '04';

            IF V_CDENCARGOOD IS NOT NULL THEN
               SELECT NVL(MAX(IDALTERADO), 'N')
                 INTO V_IDALTERADO_ENCA
                 FROM ITEMENCARGO
                WHERE CDFILIAL   = P_FILIAL
                  AND NRLANCTONF = P_LANCTONF
                  AND CDENCARGO  = V_CDENCARGOOD;
               IF V_IDALTERADO_ENCA = 'N' THEN
                  IF (V_VRTOTALIPI > 0) THEN
                     UPDATE ITEMENCARGO
                        SET VRITEMENCA = ROUND(VRITEMENCA + V_VRTOTALIPI, 2)
                      WHERE CDFILIAL = P_FILIAL
                        AND NRLANCTONF = P_LANCTONF
                        AND CDENCARGO = V_CDENCARGOOD;

                     SELECT COUNT(*)
                       INTO V_EXISTDSDADOSADIC
                       FROM DADOSADIC
                      WHERE CDFILIAL = P_FILIAL
                        AND NRLANCTONF = P_LANCTONF
                        AND DSDADOADIC LIKE 'Valor de IPI: R$%';

                     IF (V_EXISTDSDADOSADIC = 0) THEN

                        INSERT INTO DADOSADIC(CDFILIAL, NRLANCTONF, NRDADOADIC, DSDADOADIC)
                                       VALUES(P_FILIAL, P_LANCTONF, V_DADOADIC, 'Valor de IPI: R$ '||DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(V_VRTOTALIPI, 2),'9999999999999.99')),1, 1),'.','0'||LTRIM(TO_CHAR(ROUND(V_VRTOTALIPI, 2),'9999999999999.99')),LTRIM(TO_CHAR(ROUND(V_VRTOTALIPI, 2),'9999999999999.99'))));

                        V_DADOADIC := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_DADOADIC) + 1)),3,0);
                     ELSE
                        UPDATE DADOSADIC
                           SET DSDADOADIC = 'Valor de IPI: R$ '||DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(V_VRTOTALIPI, 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(V_VRTOTALIPI, 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(V_VRTOTALIPI, 2), '9999999999999.99')))
                          WHERE CDFILIAL = P_FILIAL
                            AND NRLANCTONF = P_LANCTONF
                            AND DSDADOADIC LIKE 'Valor de IPI: R$%';
                     END IF;
                  END IF;
               END IF;
            END IF;
         END IF;
      END IF;

      --RATEIO DOS ENCARGOS--------------------------------------------------------------------------------------------------------
      FOR C_ITEMENCARGO IN (SELECT IE.CDENCARGO AS CDENCARGO, VRITEMENCA, IDENCARGO,
                                   EN.CDCTBLENTREN, EN.CDCTBLSAIDEN
                            FROM ITEMENCARGO IE, ENCARGO EN
                            WHERE (IE.CDFILIAL   = P_FILIAL)     AND
                                  (IE.NRLANCTONF = P_LANCTONF)   AND
                                  (IE.VRITEMENCA > 0)            AND
                                  (EN.CDENCARGO  = IE.CDENCARGO)) LOOP
         V_TOTAPRODENCA := 0;
         FOR C_VRLIQRATEIO IN (SELECT DISTINCT(IP.NRSEQITPROD) AS NRSEQITPROD, (VRTOTAITEM - VRDESCITEM) AS VRLIQUIDO
                               FROM ITEMPRODUTO IP, ITEMPROIMPOS II
                               WHERE (IP.CDFILIAL    = P_FILIAL)       AND
                                     (IP.NRLANCTONF  = P_LANCTONF)     AND
                                     (II.CDFILIAL    = IP.CDFILIAL)    AND
                                     (II.NRLANCTONF  = IP.NRLANCTONF)  AND
                                     (II.NRSEQITPROD = IP.NRSEQITPROD) AND
                                     (EXISTS(SELECT BC.CDIMPOSTO
                                             FROM BASECALC BC
                                             WHERE (BC.CDENCARGO = C_ITEMENCARGO.CDENCARGO) AND
                                                   (BC.CDIMPOSTO = II.CDIMPOSTO)            AND
                                                   (BC.CDIMPOSTO IN (SELECT B.CDIMPOSTO
                                                                    FROM BASECALC B
                                                                    WHERE B.CDENCARGO = C_ITEMENCARGO.CDENCARGO))))) LOOP

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

         IF V_TOTAPRODENCA = 0 THEN
            IF (V_IDCONTCONFORIG = 'N') THEN
               SELECT SUM(VRTOTAITEM - VRDESCITEM)
               INTO   V_TOTAPRODENCA
               FROM ITEMPRODUTO IP
               WHERE (IP.CDFILIAL   = P_FILIAL)   AND
                     (IP.NRLANCTONF = P_LANCTONF);

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

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

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

                     IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (NVL(V_IDORIGDESTNF, 'C') <> 'L') THEN
                        UPDATE ITEMPRODUTO
                        SET VRBRUTITEM = TRUNC(VRBRUTITEM + (V_VRBRUTO  * (VRTOTAITEM - VRDESCITEM)),2),
                            VRCONTITEM = TRUNC(VRCONTITEM + (V_VRCONTAB * (VRTOTAITEM - VRDESCITEM)),2)
                        WHERE CDFILIAL    = P_FILIAL   AND
                              NRLANCTONF  = P_LANCTONF AND
                              NRSEQITPROD = C_ATUAVRCONT.NRSEQITPROD;
                     ELSE
                        UPDATE ITEMPRODUTO
                        SET VRBRUTITEM = ROUND(VRBRUTITEM + (V_VRBRUTO  * (VRTOTAITEM - VRDESCITEM)),5),
                            VRCONTITEM = ROUND(VRCONTITEM + (V_VRCONTAB * (VRTOTAITEM - VRDESCITEM)),5)
                        WHERE CDFILIAL    = P_FILIAL   AND
                              NRLANCTONF  = P_LANCTONF AND
                              NRSEQITPROD = C_ATUAVRCONT.NRSEQITPROD;
                     END IF;
                  END LOOP;
               END IF;
            END IF;
         ELSE
            IF (V_IDCONTCONFORIG = 'N') THEN
               FOR C_ATUAVRCONT IN (SELECT DISTINCT(IP.NRSEQITPROD) AS NRSEQITPROD, (VRTOTAITEM - VRDESCITEM) AS VRLIQUIDO
                                    FROM ITEMPRODUTO IP, ITEMPROIMPOS II
                                    WHERE (IP.CDFILIAL    = P_FILIAL)       AND
                                          (IP.NRLANCTONF  = P_LANCTONF)     AND
                                          (II.CDFILIAL    = IP.CDFILIAL)    AND
                                          (II.NRLANCTONF  = IP.NRLANCTONF)  AND
                                          (II.NRSEQITPROD = IP.NRSEQITPROD) AND
                                          (EXISTS(SELECT BC.CDIMPOSTO
                                                  FROM BASECALC BC
                                                  WHERE (BC.CDENCARGO = C_ITEMENCARGO.CDENCARGO) AND
                                                        (BC.CDIMPOSTO = II.CDIMPOSTO)            AND
                                                        (BC.CDIMPOSTO IN (SELECT B.CDIMPOSTO
                                                                          FROM BASECALC B
                                                                          WHERE B.CDENCARGO = C_ITEMENCARGO.CDENCARGO))))) LOOP

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

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

                  IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (NVL(V_IDORIGDESTNF, 'C') <> 'L') THEN
                     UPDATE ITEMPRODUTO
                     SET VRBRUTITEM = TRUNC(VRBRUTITEM + (V_VRBRUTO  * (VRTOTAITEM - VRDESCITEM)),2),
                         VRCONTITEM = TRUNC(VRCONTITEM + (V_VRCONTAB * (VRTOTAITEM - VRDESCITEM)),2)
                     WHERE CDFILIAL    = P_FILIAL   AND
                           NRLANCTONF  = P_LANCTONF AND
                           NRSEQITPROD = C_ATUAVRCONT.NRSEQITPROD;
                  ELSE
                     UPDATE ITEMPRODUTO
                     SET VRBRUTITEM = ROUND(VRBRUTITEM + (V_VRBRUTO  * (VRTOTAITEM - VRDESCITEM)),5),
                         VRCONTITEM = ROUND(VRCONTITEM + (V_VRCONTAB * (VRTOTAITEM - VRDESCITEM)),5)
                     WHERE CDFILIAL    = P_FILIAL   AND
                           NRLANCTONF  = P_LANCTONF AND
                           NRSEQITPROD = C_ATUAVRCONT.NRSEQITPROD;
                  END IF;
               END LOOP;
            END IF;

            FOR C_ITEMPROIMPOS IN (SELECT II.NRSEQITPROD, II.NRITPROIMPOS, II.CDIMPOSTO, II.VRPERREDBCIT, II.VRALIQITEM,
                                          II.VRPARDEDIT, II.IDTRIMPSTII, (VRTOTAITEM - VRDESCITEM) AS VRLIQUIDO,
                                          NVL(II.VRALIQINTEDEST, 0) AS VRALIQINTEDEST, NVL(II.VRALIQFCP, 0) AS VRALIQFCP,
                                          NVL(IP.IDUTILBCPMC, 'N') AS IDUTILBCPMC, I.CDIMPOSTONFE
                                   FROM ITEMPROIMPOS II, ITEMPRODUTO IP, BASECALC BC, IMPOSTO I
                                   WHERE (II.CDFILIAL     = P_FILIAL)                AND
                                         (II.NRLANCTONF   = P_LANCTONF)              AND
                                         (IP.CDFILIAL     = P_FILIAL)                AND
                                         (IP.NRLANCTONF   = P_LANCTONF)              AND
                                         (IP.NRSEQITPROD  = II.NRSEQITPROD)          AND
                                         (BC.CDIMPOSTO    = II.CDIMPOSTO)            AND
                                         (II.CDIMPOSTO    = I.CDIMPOSTO)             AND
                                         (BC.CDENCARGO    = C_ITEMENCARGO.CDENCARGO)
                                   ORDER BY 1, 2, 3) LOOP

               IF NOT((C_ITEMPROIMPOS.IDUTILBCPMC = W_S) AND (C_ITEMPROIMPOS.CDIMPOSTONFE = '80')) OR (C_ITEMPROIMPOS.IDUTILBCPMC <> W_S) THEN

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

                  IF (V_TOTAPRODENCA <> 0) THEN
                     IF (C_ITEMENCARGO.IDENCARGO = w_A) THEN
                        V_PRODUENCARGO := +(C_ITEMENCARGO.VRITEMENCA/V_TOTAPRENIMPO)*C_ITEMPROIMPOS.VRLIQUIDO;
                     ELSIF (C_ITEMENCARGO.IDENCARGO = w_D) THEN
                        V_PRODUENCARGO := -(C_ITEMENCARGO.VRITEMENCA/V_TOTAPRENIMPO)*C_ITEMPROIMPOS.VRLIQUIDO;
                     ELSE
                        V_PRODUENCARGO := 0;
                     END IF;
                  END IF;

                  V_IDVRIMPSTRIB := null;
                  BEGIN
                     SELECT CASE COUNT(*) WHEN 0 THEN 'M' ELSE 'R' END
                       INTO V_MAJORAOUREDUZ
                       FROM ITEMPROIMPOS
                      WHERE CDFILIAL = P_FILIAL 
                        AND NRLANCTONF = P_LANCTONF
                        AND NRSEQITPROD = C_ITEMPROIMPOS.NRSEQITPROD
                        AND CDIMPOSTO = C_ITEMPROIMPOS.CDIMPOSTO
                        AND NRITPROIMPOS = w_2;
                  EXCEPTION
                     WHEN NO_DATA_FOUND THEN
                        V_MAJORAOUREDUZ := 'M';
                  END;

                  V_VRIMPOSTOST := 0;
                  IF V_MAJORAOUREDUZ = 'R' THEN
                     V_TAXABASECALC := (100 - C_ITEMPROIMPOS.VRPERREDBCIT)/100;
                     V_TAXAALIQUOTA := (C_ITEMPROIMPOS.VRALIQITEM/100);
                  ELSE
                     V_TAXABASECALC := 1 + (C_ITEMPROIMPOS.VRPERREDBCIT)/100;
                     V_TAXAALIQUOTA := (C_ITEMPROIMPOS.VRALIQITEM/100);

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

                     IF (C_ITEMPROIMPOS.IDTRIMPSTII <> w_1) AND (NVL(V_IDVRIMPSTRIB,w_N) = w_S) THEN
                        Begin
                           SELECT NVL(MAX(VRIMPOSTOIT),0)
                           INTO   V_VRIMPOSTOST
                           FROM ITEMPROIMPOS I
                           WHERE (CDFILIAL     = P_FILIAL)                   AND
                                 (NRLANCTONF   = P_LANCTONF)                 AND
                                 (INSTR(V_CDIMPOSTRIB,CDIMPOSTO||'_') > 0)   AND
                                 (NRITPROIMPOS = C_ITEMPROIMPOS.NRITPROIMPOS);
                        Exception
                           When No_Data_Found Then
                              V_VRIMPOSTOST := 0;
                        End;
                     END IF;
                  END IF;

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

                  SELECT NVL(MAX(IDPERVISIMPSCRE), 'S')
                    INTO V_IDPERVISIMPSCRE
                    FROM PARAMGERAL;

                  UPDATE ITEMPROIMPOS
                     SET VRCONTITIMP  = VRCONTITIMP  + (V_PRODUENCARGO * V_TAXABASECALC),
                         VRBASECALCIT = VRBASECALCIT + ((V_PRODUENCARGO * V_TAXABASECALC) / (1 - ((C_ITEMPROIMPOS.VRALIQINTEDEST + C_ITEMPROIMPOS.VRALIQFCP) / 100))),
                         VRIMPOSTOIT  = (VRIMPOSTOIT  + (((V_PRODUENCARGO * V_TAXABASECALC) / (1 - ((C_ITEMPROIMPOS.VRALIQINTEDEST + C_ITEMPROIMPOS.VRALIQFCP) / 100))) * V_TAXAALIQUOTA)) - (((V_VRIMPOSTOST * V_TAXABASECALC) / (1 - ((C_ITEMPROIMPOS.VRALIQINTEDEST + C_ITEMPROIMPOS.VRALIQFCP) / 100))) * V_TAXAALIQUOTA),
                         VRIMPOSTOVISUIT = DECODE(V_IDPERVISIMPSCRE, 'S', (VRIMPOSTOIT  + ((V_PRODUENCARGO * V_TAXABASECALC) * V_TAXAALIQUOTA)) - ((V_VRIMPOSTOST * V_TAXABASECALC) * V_TAXAALIQUOTA),  DECODE(CDFISCALIT , '1', (VRIMPOSTOIT  + ((V_PRODUENCARGO * V_TAXABASECALC) * V_TAXAALIQUOTA)) - ((V_VRIMPOSTOST * V_TAXABASECALC) * V_TAXAALIQUOTA),0)),
                         VRADICFECP  = VRADICFECP  + ROUND((V_PRODUENCARGO * (VRADICALIQFECP / 100) * V_TAXABASECALC),2)
                   WHERE (CDFILIAL     = P_FILIAL)                   AND
                         (NRLANCTONF   = P_LANCTONF)                 AND
                         (NRSEQITPROD  = C_ITEMPROIMPOS.NRSEQITPROD) AND
                         (CDIMPOSTO    = C_ITEMPROIMPOS.CDIMPOSTO)   AND
                         (NRITPROIMPOS = C_ITEMPROIMPOS.NRITPROIMPOS);
               END IF;

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

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

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

      FOR C_PRODUTO IN (SELECT IP.NRSEQITPROD AS NRSEQITPROD, II.CDIMPOSTO, VRPERREDBCIT,
                               VRALIQITEM, VRPARDEDIT, CDFISCALIT, VRIMPOSTOIT, IDTRATIMPO,
                               IM.IDIMPORECUP, IM.CDCCTBLPASS, IM.CDCCTBLATIV, NRITPROIMPOS,
                               IDTRIMPSTII, IM.IDTIPCONTAB, II.VRBASECALCIT, IP.IDUTILBCPMC,
                               IM.CDIMPOSTONFE
                        FROM ITEMPRODUTO IP, ITEMPROIMPOS II, IMPOSTO IM
                        WHERE (IP.CDFILIAL     = P_FILIAL)      AND
                              (IP.NRLANCTONF   = P_LANCTONF)    AND
                              (II.CDFILIAL     = IP.CDFILIAL)   AND
                              (II.NRLANCTONF   = IP.NRLANCTONF) AND
                              (IM.CDIMPOSTO    = II.CDIMPOSTO)  AND
                              --(INSTR(V_CDIMPOSRECALC,II.CDIMPOSTO||'_') > 0) AND
                              (II.NRITPROIMPOS = w_1)           AND
                              (II.NRSEQITPROD  = IP.NRSEQITPROD)
                        ORDER BY NRSEQITPROD, CDIMPOSTO) LOOP

         IF NOT((C_PRODUTO.IDUTILBCPMC = W_S) AND (C_PRODUTO.CDIMPOSTONFE = '80')) OR (C_PRODUTO.IDUTILBCPMC <> W_S) THEN
            V_IDIMPOBCALTPOP := NULL;
   
            SELECT TO_CHAR(MAX('S')) , NVL(SUM(VRIMPOSTOIT),0) AS VRIMPOBCALC
              INTO   V_IDIMPOBCALTPOP, V_TOTAIMPBCALC
              FROM ITEMPRODUTO IP, ITEMPROIMPOS II, BASECALCTPOPER BC , IMPOSTO I
             WHERE (BC.CDIMPOSTO    = C_PRODUTO.CDIMPOSTO)
               AND (IP.CDFILIAL     = P_FILIAL)
               AND (IP.NRLANCTONF   = P_LANCTONF)
               AND (II.NRLANCTONF   = IP.NRLANCTONF)
               AND (II.CDFILIAL     = IP.CDFILIAL)
               AND (IP.NRSEQITPROD  = C_PRODUTO.NRSEQITPROD)
               AND (II.NRSEQITPROD  = C_PRODUTO.NRSEQITPROD)
               AND (II.NRITPROIMPOS = C_PRODUTO.NRITPROIMPOS)
               AND ((SUBSTR(IP.CDSITUTRIBPR,2,2) = BC.CDCSTIMPOTPOP)  OR (BC.CDCSTIMPOTPOP  IS NULL))
               AND ((SUBSTR(IP.CDFISOPEITEM,2,4) = BC.CDCFOPIMPOTPOP) OR (BC.CDCFOPIMPOTPOP IS NULL))
               AND ((C_PRODUTO.CDFISCALIT        = BC.CDFISCIMPOTPOP) OR (BC.CDFISCIMPOTPOP IS NULL))
               AND (BC.IDENTRSAIDOP = 'S')
               AND (BC.CDTIPOOPER = P_TIPOOPER)
               AND (II.CDIMPOSTO = BC.CDIMPOBCALC)
               AND (BC.CDIMPOBCALC = I.CDIMPOSTO)
               AND (NVL(BC.IDTRATIMPOBCTPOP, I.IDTRATIMPO) <> 'D');
   
            IF V_IDIMPOBCALTPOP IS NULL THEN
               SELECT NVL(SUM(VRIMPOSTOIT),0) AS VRIMPOBCALC
                 INTO   V_TOTAIMPBCALC
                 FROM ITEMPRODUTO IP, ITEMPROIMPOS II, BASECALC BC, IMPOSTO I
                WHERE (BC.CDIMPOSTO    = C_PRODUTO.CDIMPOSTO)    AND
                      (IP.CDFILIAL     = P_FILIAL)               AND
                      (IP.NRLANCTONF   = P_LANCTONF)             AND
                      (II.NRLANCTONF   = IP.NRLANCTONF)          AND
                      (II.CDFILIAL     = IP.CDFILIAL)            AND
                      (IP.NRSEQITPROD  = C_PRODUTO.NRSEQITPROD)  AND
                      (II.NRSEQITPROD  = C_PRODUTO.NRSEQITPROD)  AND
                      (II.NRITPROIMPOS = C_PRODUTO.NRITPROIMPOS) AND
                      ((SUBSTR(IP.CDSITUTRIBPR,2,2) = BC.CDCSTIMPO)  OR (BC.CDCSTIMPO  IS NULL)) AND
                      ((SUBSTR(IP.CDFISOPEITEM,2,4) = BC.CDCFOPIMPO) OR (BC.CDCFOPIMPO IS NULL)) AND
                      ((C_PRODUTO.CDFISCALIT        = BC.CDFISCIMPO) OR (BC.CDFISCIMPO IS NULL)) AND
                      (II.CDIMPOSTO = BC.CDIMPOBCALC) AND
                      (BC.IDTIPOBCALC   = w_I)AND
                      (BC.CDIMPOBCALC = I.CDIMPOSTO)  AND
                      (NVL(BC.IDTRATIMPOBC, I.IDTRATIMPO) <> 'D');
            END IF;
   
            V_IDIMBCALTPOPDE := NULL;
   
            SELECT TO_CHAR(MAX('S')), (NVL(SUM(VRIMPOSTOIT),0)*-1) AS VRIMPOBCALC
              INTO V_IDIMBCALTPOPDE, V_TOTAIMPBCDES
              FROM ITEMPRODUTO IP, ITEMPROIMPOS II, BASECALCTPOPER BC, IMPOSTO I
             WHERE (BC.CDIMPOSTO    = C_PRODUTO.CDIMPOSTO)
               AND (IP.CDFILIAL     = P_FILIAL)
               AND (IP.NRLANCTONF   = P_LANCTONF)
               AND (II.NRLANCTONF   = IP.NRLANCTONF)
               AND (II.CDFILIAL     = IP.CDFILIAL)
               AND (IP.NRSEQITPROD  = C_PRODUTO.NRSEQITPROD)
               AND (II.NRSEQITPROD  = C_PRODUTO.NRSEQITPROD)
               AND (II.NRITPROIMPOS = C_PRODUTO.NRITPROIMPOS)
               AND ((SUBSTR(IP.CDSITUTRIBPR,2,2) = BC.CDCSTIMPOTPOP)  OR (BC.CDCSTIMPOTPOP  IS NULL))
               AND ((SUBSTR(IP.CDFISOPEITEM,2,4) = BC.CDCFOPIMPOTPOP) OR (BC.CDCFOPIMPOTPOP IS NULL))
               AND ((C_PRODUTO.CDFISCALIT        = BC.CDFISCIMPOTPOP) OR (BC.CDFISCIMPOTPOP IS NULL))
               AND (BC.IDENTRSAIDOP = 'S')
               AND (BC.CDTIPOOPER = P_TIPOOPER)
               AND (II.CDIMPOSTO = BC.CDIMPOBCALC)
               AND (BC.CDIMPOBCALC = I.CDIMPOSTO)
               AND (NVL(BC.IDTRATIMPOBCTPOP, I.IDTRATIMPO) = 'D');
   
            IF V_IDIMBCALTPOPDE IS NULL THEN
   
               SELECT (NVL(SUM(VRIMPOSTOIT),0)*-1) AS VRIMPOBCALC INTO V_TOTAIMPBCDES
                 FROM ITEMPRODUTO IP, ITEMPROIMPOS II, BASECALC BC, IMPOSTO I
                WHERE (BC.CDIMPOSTO    = C_PRODUTO.CDIMPOSTO)    AND
                      (IP.CDFILIAL     = P_FILIAL)               AND
                      (IP.NRLANCTONF   = P_LANCTONF)             AND
                      (II.NRLANCTONF   = IP.NRLANCTONF)          AND
                      (II.CDFILIAL     = IP.CDFILIAL)            AND
                      (IP.NRSEQITPROD  = C_PRODUTO.NRSEQITPROD)  AND
                      (II.NRSEQITPROD  = C_PRODUTO.NRSEQITPROD)  AND
                      (II.NRITPROIMPOS = C_PRODUTO.NRITPROIMPOS) AND
                      ((SUBSTR(IP.CDSITUTRIBPR,2,2) = BC.CDCSTIMPO)  OR (BC.CDCSTIMPO  IS NULL)) AND
                      ((SUBSTR(IP.CDFISOPEITEM,2,4) = BC.CDCFOPIMPO) OR (BC.CDCFOPIMPO IS NULL)) AND
                      ((C_PRODUTO.CDFISCALIT        = BC.CDFISCIMPO) OR (BC.CDFISCIMPO IS NULL)) AND
                      (II.CDIMPOSTO = BC.CDIMPOBCALC) AND
                      (BC.IDTIPOBCALC   = 'I')        AND
                      (BC.CDIMPOBCALC = I.CDIMPOSTO)  AND
                      (NVL(BC.IDTRATIMPOBC, I.IDTRATIMPO) = 'D');
            END IF;
   
            V_VRIMPOSTO := C_PRODUTO.VRIMPOSTOIT;
   
            /*IMPOSTO PARA SUBSTITUIÇÃO TRIBUTARIA*/
            V_CDIMPOSTRIB  := null;
            V_IDVRIMPSTRIB := null;
            FOR C_ICMSST IN (SELECT CDIMPOSTO
                               FROM IMPOSTO
                              WHERE CDIMPOSTRIB = C_PRODUTO.CDIMPOSTO)
            LOOP
               V_CDIMPOSTRIB := V_CDIMPOSTRIB||C_ICMSST.CDIMPOSTO||'_';
            END LOOP;
   
            V_VRIMPOSTOST := 0;
            /*Só irá fazer o cálculo de outro imposto compondo a base de cálculo,
              se o valor do mesmo não estiver zerado OU
              se for o imposto de st, pois o icms pode ter sido recalculado(por ter alguem compondo sua bc)
              e o imposto st precisa retirar o valor final do st*/
   
            IF (NOT(V_TOTAIMPBCALC IS NULL) OR (V_TOTAIMPBCALC <> 0)) OR
               (NOT(V_TOTAIMPBCDES IS NULL) OR (V_TOTAIMPBCDES <> 0)) OR
               (V_CDIMPOSTRIB IS NOT NULL) THEN
   
               SELECT NVL(MAX(IDPERVISIMPSCRE),'S')
                 INTO V_IDPERVISIMPSCRE
                 FROM PARAMGERAL;
   
               IF V_CDIMPOSTRIB IS NULL THEN
                  V_TAXABASECALC := (100 - C_PRODUTO.VRPERREDBCIT)/100;
                  V_TAXAALIQUOTA := (C_PRODUTO.VRALIQITEM/100);
                  V_VRIMPOSTO    := V_VRIMPOSTO + (((V_TOTAIMPBCALC+V_TOTAIMPBCDES) * V_TAXABASECALC) * V_TAXAALIQUOTA);
   
                  UPDATE ITEMPROIMPOS
                     SET VRBASECALCIT = VRBASECALCIT + ((V_TOTAIMPBCALC+V_TOTAIMPBCDES) * V_TAXABASECALC),
                         VRIMPOSTOIT  = VRIMPOSTOIT  + (((V_TOTAIMPBCALC+V_TOTAIMPBCDES) * V_TAXABASECALC) * V_TAXAALIQUOTA),
                         VRIMPOSTOVISUIT = DECODE(V_IDPERVISIMPSCRE, 'S', VRIMPOSTOIT  + (((V_TOTAIMPBCALC+V_TOTAIMPBCDES) * V_TAXABASECALC) * V_TAXAALIQUOTA), DECODE(CDFISCALIT, '1', VRIMPOSTOIT  + (((V_TOTAIMPBCALC+V_TOTAIMPBCDES) * V_TAXABASECALC) * V_TAXAALIQUOTA), 0))
                   WHERE (CDFILIAL     = P_FILIAL)              AND
                         (NRLANCTONF   = P_LANCTONF)            AND
                         (NRSEQITPROD  = C_PRODUTO.NRSEQITPROD) AND
                         (CDIMPOSTO    = C_PRODUTO.CDIMPOSTO)   AND
                         (NRITPROIMPOS = C_PRODUTO.NRITPROIMPOS);
   
                  /* ROTINA PARA RECALCULAR O DIFERIMENTO DO IMPOSTO */
                  BEGIN
                     SELECT MAX(VRIMPOSTOOPERAIT), MAX(VRPERDIFEREIT)
                       INTO V_VRIMPOSTOOPERAIT, V_VRPERDIFEREIT
                       FROM ITEMPROIMPOS
                      WHERE (CDFILIAL     = P_FILIAL)               AND
                            (NRLANCTONF   = P_LANCTONF)             AND
                            (NRSEQITPROD  = C_PRODUTO.NRSEQITPROD)  AND
                            (CDIMPOSTO    = C_PRODUTO.CDIMPOSTO)    AND
                            (NRITPROIMPOS = C_PRODUTO.NRITPROIMPOS) AND
                            (VRPERDIFEREIT <> 0);
                  EXCEPTION
                     When No_Data_Found Then
                        V_VRIMPOSTOOPERAIT := 0; V_VRPERDIFEREIT := 0;
                  END;
   
                  IF V_VRPERDIFEREIT <> 0 THEN
                     V_VRIMPOSTOOPERAIT := ROUND((V_VRIMPOSTOOPERAIT + ((ROUND((V_TOTAIMPBCALC+V_TOTAIMPBCDES), 2) * V_TAXABASECALC) * V_TAXAALIQUOTA)),2);
                     V_VRIMPOSTODIFERIT := ROUND((V_VRIMPOSTOOPERAIT * V_VRPERDIFEREIT/100), 2);
   
                     UPDATE ITEMPROIMPOS
                        SET VRIMPOSTOOPERAIT = V_VRIMPOSTOOPERAIT,
                            VRIMPOSTODIFERIT = V_VRIMPOSTODIFERIT,
                            VRIMPOSTOIT = (V_VRIMPOSTOOPERAIT - V_VRIMPOSTODIFERIT),
                            VRIMPOSTOVISUIT = (V_VRIMPOSTOOPERAIT - V_VRIMPOSTODIFERIT)
                      WHERE (CDFILIAL     = P_FILIAL)               AND
                            (NRLANCTONF   = P_LANCTONF)             AND
                            (NRSEQITPROD  = C_PRODUTO.NRSEQITPROD)  AND
                            (CDIMPOSTO    = C_PRODUTO.CDIMPOSTO)    AND
                            (NRITPROIMPOS = C_PRODUTO.NRITPROIMPOS) AND
                            (VRPERDIFEREIT <> 0);
                  END IF;
               ELSE
                  V_VRIMPOSST   := 0;
                  V_VRIMPOSTOST := 0;
                  FOR C_SUBSTRIB IN (SELECT NVL(IDVRIMPSTRIB, 'N') IDVRIMPSTRIB, I.CDIMPOSTO
                                       FROM ITEMPROIMPOS I, IMPOSTO II
                                      WHERE (CDFILIAL     = P_FILIAL)
                                        AND (NRLANCTONF   = P_LANCTONF)
                                        AND (NRSEQITPROD  = C_PRODUTO.NRSEQITPROD)
                                        AND (NRITPROIMPOS = '1')
                                        AND (INSTR(V_CDIMPOSTRIB,II.CDIMPOSTO||'_') > 0)
                                        AND (I.CDIMPOSTO = II.CDIMPOSTO))
                  LOOP
                     IF (C_SUBSTRIB.IDVRIMPSTRIB = w_S) THEN
                        Begin
                           SELECT NVL(ROUND(MAX(VRIMPOSTOIT), 2),0)
                           INTO   V_VRIMPOSST
                           FROM ITEMPROIMPOS I
                           WHERE (CDFILIAL     = P_FILIAL)                   AND
                                 (NRLANCTONF   = P_LANCTONF)                 AND
                                 (NRSEQITPROD  = C_PRODUTO.NRSEQITPROD)  AND
                                 (CDIMPOSTO    = C_SUBSTRIB.CDIMPOSTO)       AND
                                 (INSTR(V_CDIMPOSTRIB,CDIMPOSTO||'_') > 0)   AND
                                 (NRITPROIMPOS = w_1);
                        Exception
                           When No_Data_Found Then
                              V_VRIMPOSST := 0;
                        End;
                     ELSE
                        V_VRIMPOSST := 0;
                     END IF;
                     V_VRIMPOSTOST := V_VRIMPOSTOST + V_VRIMPOSST;
                  END LOOP;
   
                  V_TAXABASECALC := 1 + (C_PRODUTO.VRPERREDBCIT)/100;
                  V_TAXAALIQUOTA := (C_PRODUTO.VRALIQITEM/100);
                  V_VRIMPOSTO := ((C_PRODUTO.VRBASECALCIT+ ((V_TOTAIMPBCALC+V_TOTAIMPBCDES) * V_TAXABASECALC)) * V_TAXAALIQUOTA);
   
                  SELECT NVL(MAX(IDPERVISIMPSCRE), 'S')
                    INTO V_IDPERVISIMPSCRE
                    FROM PARAMGERAL;
   
                  IF V_VRIMPOSTOST > V_VRIMPOSTO THEN
                     UPDATE ITEMPROIMPOS
                     SET VRBASECALCIT = VRBASECALCIT + ((V_TOTAIMPBCALC+V_TOTAIMPBCDES) * V_TAXABASECALC),
                         VRIMPOSTOIT  = 0,
                         VRIMPOSTOVISUIT = 0
                     WHERE (CDFILIAL     = P_FILIAL)              AND
                           (NRLANCTONF   = P_LANCTONF)            AND
                           (NRSEQITPROD  = C_PRODUTO.NRSEQITPROD) AND
                           (CDIMPOSTO    = C_PRODUTO.CDIMPOSTO)   AND
                           (NRITPROIMPOS = C_PRODUTO.NRITPROIMPOS);
                     V_VRIMPOSTO := 0;
                  ELSE
                     UPDATE ITEMPROIMPOS
                        SET VRBASECALCIT = VRBASECALCIT + ((V_TOTAIMPBCALC+V_TOTAIMPBCDES) * V_TAXABASECALC),
                            VRIMPOSTOIT  = V_VRIMPOSTO - V_VRIMPOSTOST,
                            VRIMPOSTOVISUIT = DECODE(V_IDPERVISIMPSCRE, 'S', V_VRIMPOSTO - V_VRIMPOSTOST, DECODE(CDFISCALIT, '1', V_VRIMPOSTO - V_VRIMPOSTOST, 0))
                      WHERE (CDFILIAL     = P_FILIAL)              AND
                            (NRLANCTONF   = P_LANCTONF)            AND
                            (NRSEQITPROD  = C_PRODUTO.NRSEQITPROD) AND
                            (CDIMPOSTO    = C_PRODUTO.CDIMPOSTO)   AND
                            (NRITPROIMPOS = C_PRODUTO.NRITPROIMPOS);
                     V_VRIMPOSTO := V_VRIMPOSTO - V_VRIMPOSTOST;
   
                     IF (V_IDCONTCONFORIG = 'N') THEN
                        UPDATE ITEMPRODUTO
                           SET VRBRUTITEM = VRBRUTITEM + V_VRIMPOSTO,
                               VRCONTITEM = VRCONTITEM + V_VRIMPOSTO
                         WHERE CDFILIAL = P_FILIAL
                           AND NRLANCTONF = P_LANCTONF
                           AND NRSEQITPROD = C_PRODUTO.NRSEQITPROD;
                     END IF;
   
                  END IF;
               END IF;
            END IF;
         END IF;
      END LOOP;

      IF V_IDOPERDEVONF = w_S THEN
         V_SEQUIMPOSTNF := w_01;

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

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

         --TOTALIZAÇÃO DOS IMPOSTOS
         FOR C_IMPOSNFTOT IN (SELECT IT.CDIMPOSTO
                              FROM ITEMPROIMPOS IT
                              WHERE (IT.CDFILIAL   = P_FILIAL) AND
                                    (IT.NRLANCTONF = P_LANCTONF)
                              GROUP BY IT.CDIMPOSTO) LOOP

            V_IMPOSTOIT  := 0;
            V_BASECALCIT := 0;

            SELECT NVL(SUM(IT.VRIMPOSTOIT),0), 
                   NVL(SUM(IT.VRBASECALCIT),0),
                   NVL(SUM(IT.VRADICFECP),0)
            INTO   V_IMPOSTOIT,
                   V_BASECALCIT,
                   V_VRADICFECPNFTOT
            FROM ITEMPROIMPOS IT, IMPOSTO I
            WHERE (IT.CDFILIAL   = P_FILIAL)               AND
                  (IT.NRLANCTONF = P_LANCTONF)             AND
                  (IT.CDIMPOSTO  = C_IMPOSNFTOT.CDIMPOSTO) AND
                  (IT.CDIMPOSTO  = I.CDIMPOSTO);

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

            IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (V_ICMS = 'S') THEN
               INSERT INTO IMPOSNFTOT
                  (CDFILIAL, NRLANCTONF, CDIMPOSTO, VRTOTIMPONF, VRTOTBCALCNF,
                   VRADICFECP)
               VALUES 
                  (P_FILIAL, P_LANCTONF, C_IMPOSNFTOT.CDIMPOSTO, TRUNC(V_IMPOSTOIT ,V_NRDECITOTANF), TRUNC(V_BASECALCIT,V_NRDECITOTANF),
                   V_VRADICFECPNFTOT);
            ELSE
               INSERT INTO IMPOSNFTOT
                  (CDFILIAL, NRLANCTONF, CDIMPOSTO, VRTOTIMPONF, VRTOTBCALCNF,
                   VRADICFECP)
               VALUES
                  (P_FILIAL, P_LANCTONF, C_IMPOSNFTOT.CDIMPOSTO, ROUND(V_IMPOSTOIT ,V_NRDECITOTANF), ROUND(V_BASECALCIT,V_NRDECITOTANF),
                   V_VRADICFECPNFTOT);
            END IF;

         END LOOP;

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

         FOR C_ITEMNOTAFISC IN (SELECT CDFILIALIT, NRLANCTONFIT
                                FROM ITEMNOTAFISC
                                WHERE CDFILIAL   = P_FILIAL AND
                                      NRLANCTONF = P_LANCTONF) LOOP

            SELECT SUM(VRTOTAITEM - VRDESCITEM) AS VRLIQUORIG
            INTO   V_VRLIQUORIG
            FROM ITEMPRODUTO I
            WHERE CDFILIAL    = C_ITEMNOTAFISC.CDFILIALIT AND
                  NRLANCTONF  = C_ITEMNOTAFISC.NRLANCTONFIT;

            IF V_VRLIQUORIG = 0 THEN
               V_VRFATOCONV := 0;
            ELSE
               V_VRFATOCONV := V_LIQUIDO / V_VRLIQUORIG;
            END IF;

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

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

               IF ((V_IDUTMUNIORIG = 'O') OR (V_IDUTMUNIORIG = 'N')) THEN
                  CONSULTA_ALIQUOTA(C_IMPOSNFTOT.CDIMPOSTO, w_S, P_EMPRESA, '', P_INSCESTA, V_PAISORIG,
                                    V_ESTAORIG, V_PAISDEST, V_ESTADEST, V_MUNIORIG, V_LIQUIITEM, P_INIVALID, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC, P_TIPOOPER);
               ELSE
                  CONSULTA_ALIQUOTA(C_IMPOSNFTOT.CDIMPOSTO, w_S, P_EMPRESA, '', P_INSCESTA, V_PAISORIG,
                                    V_ESTAORIG, V_PAISDEST, V_ESTADEST, V_MUNIDEST, V_LIQUIITEM, P_INIVALID, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC, P_TIPOOPER);
               END IF;

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

               IF ((V_NRALIQTEMP IS NOT NULL) AND (V_CDTIPOOPER IS NOT NULL) AND (V_ESTORNOCANC <> w_S)) THEN
                  IF (V_ALIQUTMP IS NULL) THEN
                     V_ALIQUTMP := 0;
                  END IF;
                  V_PRODUENCARGO := 0;

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

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

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

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

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

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

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

                  V_PRODUENCARGO := V_SOMAITEM - V_DESCITEM;

                  V_TAXABASECALC := (100 - V_PREDBCTMP)/100;
                  V_TAXAALIQUOTA := (V_ALIQUTMP/100);
                  V_BASECALCIT   := (V_LIQUIDO + V_PRODUENCARGO) * V_TAXABASECALC;

                  V_CONTIMPO     := V_BASECALCIT;
                  V_IMPOSTOIT    := (V_BASECALCIT * V_TAXAALIQUOTA) - V_PARDEDTMP;

                  IF V_BASECALCIT < 0 THEN
                     V_BASECALCIT := 0;
                  END IF;

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

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

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

                  IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (V_ICMS = 'S') THEN
                     INSERT INTO IMPOSNFTOT(CDFILIAL, NRLANCTONF, CDIMPOSTO, VRTOTIMPONF, VRTOTBCALCNF)
                                       VALUES (P_FILIAL, P_LANCTONF, C_IMPOSNFTOT.CDIMPOSTO, TRUNC(V_IMPOSTOIT ,V_NRDECITOTANF), TRUNC(V_BASECALCIT,V_NRDECITOTANF));
                  ELSE
                     INSERT INTO IMPOSNFTOT(CDFILIAL, NRLANCTONF, CDIMPOSTO, VRTOTIMPONF, VRTOTBCALCNF)
                                       VALUES (P_FILIAL, P_LANCTONF, C_IMPOSNFTOT.CDIMPOSTO, ROUND(V_IMPOSTOIT ,V_NRDECITOTANF), ROUND(V_BASECALCIT,V_NRDECITOTANF));
                  END IF;

               ELSE
                  V_IMPOSTOIT  := (C_IMPOSNFTOT.VRTOTIMPONF * V_VRFATOCONV);
                  V_BASECALCIT := (C_IMPOSNFTOT.VRTOTBCALCNF * V_VRFATOCONV);
                  V_ALIQUTMP   := NULL;
                  V_UTIBB      := 'N';

                  --integração fiscal especifica com Compass_Argentina atraves da importação de aliquota do imposto IBB
                  --A aliquota de imposto 03(ibb) sera cadastrada na tabela paramintegraibb e tera prioridade sobre o
                  -- cadastro de aliquota realizado em sistema
                  /*IF C_IMPOSNFTOT.CDIMPOSTO = '03' THEN
                     IF V_IDORIGDESTNF = 'C' THEN

                        V_DTVINGENTE := NVL(V_DTINIREFEFAT, P_INIVALID);

                        SELECT NVL(MAX(VRALIQUOTAIBB),NULL)
                        INTO   V_ALIQUTMP
                        FROM PARAMINTEGRAIBB
                        WHERE CDCLIENTE = P_CLIENTE AND
                              V_DTVINGENTE BETWEEN DTVIGINICIALIBB AND DTVIGFINALIBB;

                        IF V_ALIQUTMP IS NOT NULL THEN
                           V_UTIBB := 'S';
                        END IF;
                     END IF;
                  END IF;

                  IF V_UTIBB = 'S' THEN
                     INSERT INTO IMPOSNFTOT(CDFILIAL, NRLANCTONF, CDIMPOSTO, VRTOTIMPONF, VRTOTBCALCNF)
                                    VALUES (P_FILIAL, P_LANCTONF, C_IMPOSNFTOT.CDIMPOSTO, ROUND((V_LIQUIDO * (V_ALIQUTMP/100))  ,V_NRDECITOTANF), ROUND(V_LIQUIDO,V_NRDECITOTANF));
                  ELSE*/
                     V_ICMS := 'N';
                     FOR C_ICMS IN (SELECT CDIMPOSTO
                                      FROM IMPOSTONFE N, IMPOSTO I
                                     WHERE N.CDIMPOSTONFE = I.CDIMPOSTONFE
                                       AND N.CDIMPOSTONFE = '00'
                                       AND I.CDIMPOSTO = C_IMPOSNFTOT.CDIMPOSTO)
                      LOOP
                         V_ICMS := 'S';
                      END LOOP;

                     IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (V_ICMS = 'S') THEN
                        INSERT INTO IMPOSNFTOT(CDFILIAL, NRLANCTONF, CDIMPOSTO, VRTOTIMPONF, VRTOTBCALCNF)
                                       VALUES (P_FILIAL, P_LANCTONF, C_IMPOSNFTOT.CDIMPOSTO, TRUNC(V_IMPOSTOIT ,V_NRDECITOTANF), TRUNC(V_BASECALCIT,V_NRDECITOTANF));
                     ELSE
                        INSERT INTO IMPOSNFTOT(CDFILIAL, NRLANCTONF, CDIMPOSTO, VRTOTIMPONF, VRTOTBCALCNF)
                                       VALUES (P_FILIAL, P_LANCTONF, C_IMPOSNFTOT.CDIMPOSTO, ROUND(V_IMPOSTOIT ,V_NRDECITOTANF), ROUND(V_BASECALCIT,V_NRDECITOTANF));
                     END IF;

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

            FOR C_IMPOSTONF IN (SELECT IT.CDIMPOSTO, IT.NRIMPOSNF, IT.VRCONTABILNF, IT.VRPERREDBCNF, IT.VRBASECALCNF,
                                       IT.VRALIQNF, IT.VRPARDEDNF, IT.VRIMPOSTONF, IT.CDFISCALNF, IT.CDSITUTRIBNF,
                                       IT.CDFISCOPERNF, IT.CDSUFXCFOPNF, IDTRIMPOSTNF, IT.CDSITUTRIBIMNFE, IP.IDIMPORECUP,
									                     IT.CDTPCREDPICONF, IT.CDNATUBCALPCNF, IT.IDMOTDESONERANF
                                FROM IMPOSTONF IT, IMPOSTO IP
                                WHERE IT.CDFILIAL   = C_ITEMNOTAFISC.CDFILIALIT   AND
                                      IT.NRLANCTONF = C_ITEMNOTAFISC.NRLANCTONFIT AND
                                      IT.CDIMPOSTO  = IP.CDIMPOSTO                AND
                                      IP.IDPRODNOTA = w_C) LOOP
               /*VERIFICA CST POR IMPOSTO*/
               V_IMPOICMS := NULL;
               V_CDGRUPOFISCAUX := NULL;

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

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

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

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

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

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


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

               IF ((V_IDUTMUNIORIG = 'O') OR (V_IDUTMUNIORIG = 'N')) THEN
                  CONSULTA_ALIQUOTA(C_IMPOSTONF.CDIMPOSTO, w_S, P_EMPRESA, '', P_INSCESTA, V_PAISORIG,
                                    V_ESTAORIG, V_PAISDEST, V_ESTADEST, V_MUNIORIG, V_LIQUIITEM, P_INIVALID, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC,P_TIPOOPER);
               ELSE
                  CONSULTA_ALIQUOTA(C_IMPOSTONF.CDIMPOSTO, w_S, P_EMPRESA, '', P_INSCESTA, V_PAISORIG,
                                    V_ESTAORIG, V_PAISDEST, V_ESTADEST, V_MUNIDEST, V_LIQUIITEM, P_INIVALID, P_FILIAL, P_LANCTONF, V_CDGRUPOFISC, P_TIPOOPER);
               END IF;

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

               IF ((V_NRALIQTEMP IS NOT NULL) AND (V_CDTIPOOPER IS NOT NULL)) THEN
                  IF (V_ALIQUTMP IS NULL) THEN
                     V_ALIQUTMP := 0;
                  END IF;
                  V_PRODUENCARGO := 0;

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

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

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

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

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

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

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

                  V_PRODUENCARGO := V_SOMAITEM - V_DESCITEM;

                  V_TAXABASECALC := (100 - V_PREDBCTMP)/100;
                  V_TAXAALIQUOTA := (V_ALIQUTMP/100);
                  V_BASECALCIT   := (V_LIQUIDO + V_PRODUENCARGO) * V_TAXABASECALC;

                  V_CONTIMPO     := V_BASECALCIT;
                  V_IMPOSTOIT    := (V_BASECALCIT * V_TAXAALIQUOTA) - V_PARDEDTMP;

                  IF V_BASECALCIT < 0 THEN
                     V_BASECALCIT := 0;
                  END IF;

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

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

                  IF (C_IMPOSTONF.IDIMPORECUP = w_S) OR (C_IMPOSTONF.IDIMPORECUP <> w_S AND V_ALIQUTMP <> 0) THEN
                     IF ((C_IMPOSTONF.IDIMPORECUP = w_S) AND (C_IMPOSTONF.CDFISCALNF <> w_1)) THEN
                        V_BASECALCIT := 0;
                        V_ALIQUTMP   := 0;
                        V_IMPOSTOIT  := 0;
                        V_PREDBCTMP  := 0;
                        V_PARDEDTMP  := 0;
                     END IF;

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

                     IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (V_ICMS = 'S') THEN
                        INSERT INTO IMPOSTONF(
                           CDFILIAL, NRLANCTONF, CDIMPOSTO, NRIMPOSNF, VRCONTABILNF, VRPERREDBCNF, VRBASECALCNF,
                           VRALIQNF, VRPARDEDNF, VRIMPOSTONF, CDFISCALNF, IDTRIMPOSTNF, CDSITUTRIBIMNFE, CDTPCREDPICONF, CDNATUBCALPCNF, IDMOTDESONERANF)
                        VALUES(
                           P_FILIAL, P_LANCTONF, C_IMPOSTONF.CDIMPOSTO, C_IMPOSTONF.NRIMPOSNF, TRUNC(V_CONTIMPO,2), V_PREDBCTMP,
                           TRUNC(V_BASECALCIT,2), V_ALIQUTMP, TRUNC(V_PARDEDTMP,2), TRUNC(V_IMPOSTOIT,2), C_IMPOSTONF.CDSUFXCFOPNF, C_IMPOSTONF.IDTRIMPOSTNF, V_CDSITTRIBTMP, V_CDTPCRPICOSTNFEIT, V_CDNATUBCPCSTNFEIT, V_IDMOTIDESSTNFE);
                     ELSE
                        INSERT INTO IMPOSTONF(
                           CDFILIAL, NRLANCTONF, CDIMPOSTO, NRIMPOSNF, VRCONTABILNF, VRPERREDBCNF, VRBASECALCNF,
                           VRALIQNF, VRPARDEDNF, VRIMPOSTONF, CDFISCALNF, IDTRIMPOSTNF, CDSITUTRIBIMNFE, CDTPCREDPICONF, CDNATUBCALPCNF, IDMOTDESONERANF)
                        VALUES(
                           P_FILIAL, P_LANCTONF, C_IMPOSTONF.CDIMPOSTO, C_IMPOSTONF.NRIMPOSNF, ROUND(V_CONTIMPO,2), V_PREDBCTMP,
                           V_BASECALCIT, V_ALIQUTMP, V_PARDEDTMP, V_IMPOSTOIT, C_IMPOSTONF.CDSUFXCFOPNF, C_IMPOSTONF.IDTRIMPOSTNF, V_CDSITTRIBTMP, V_CDTPCRPICOSTNFEIT, V_CDNATUBCPCSTNFEIT, V_IDMOTIDESSTNFE);
                     END IF;

                     IF ((C_IMPOSTONF.IDIMPORECUP = w_S) AND (V_PREDBCTMP > 0) AND (C_IMPOSTONF.CDFISCALNF = w_1)) THEN
                        INSERT INTO IMPOSTONF(
                           CDFILIAL, NRLANCTONF, CDIMPOSTO, NRIMPOSNF, VRCONTABILNF, VRPERREDBCNF, VRBASECALCNF,
                           VRALIQNF, VRPARDEDNF, VRIMPOSTONF, CDFISCALNF, CDSITUTRIBIMNFE, CDTPCREDPICONF, CDNATUBCALPCNF, IDMOTDESONERANF)
                        VALUES(
                           P_FILIAL, P_LANCTONF, C_IMPOSTONF.CDIMPOSTO, C_IMPOSTONF.NRIMPOSNF, V_CONTABCALC, V_PERDBCALC,
                           0, 0, V_PARDEDTMP, 0, w_2, V_CDSITTRIBTMP, V_CDTPCRPICOSTNFEIT, V_CDNATUBCPCSTNFEIT, V_IDMOTIDESSTNFE);
                     END IF;
                  END IF;

                  DELETE ALIQTEMP
                  WHERE NRALIQTEMP = V_ALIQTEMP;
               ELSE
                  V_ALIQUTMP   := NULL;
                  V_UTIBB      := 'N';
                  --integração fiscal especifica com Compass_Argentina atraves da importação de aliquota do imposto IBB
                  --A aliquota de imposto 03(ibb) sera cadastrada na tabela paramintegraibb e tera prioridade sobre o
                  -- cadastro de aliquota realizado em sistema
                  /*IF C_IMPOSTONF.CDIMPOSTO = '03' THEN
                     IF V_IDORIGDESTNF = 'C' THEN
                        V_DTVINGENTE := NVL(V_DTINIREFEFAT, P_INIVALID);

                        SELECT NVL(MAX(VRALIQUOTAIBB),NULL)
                        INTO   V_ALIQUTMP
                        FROM PARAMINTEGRAIBB
                        WHERE CDCLIENTE = P_CLIENTE AND
                              V_DTVINGENTE BETWEEN DTVIGINICIALIBB AND DTVIGFINALIBB;

                        IF V_ALIQUTMP IS NOT NULL THEN
                           V_UTIBB := 'S';
                        END IF;
                     END IF;
                  END IF;*/

                  IF V_UTIBB = 'S' THEN
                     V_ICMS := 'N';
                     FOR C_ICMS IN (SELECT CDIMPOSTO
                                      FROM IMPOSTONFE N, IMPOSTO I
                                     WHERE N.CDIMPOSTONFE = I.CDIMPOSTONFE
                                       AND N.CDIMPOSTONFE = '00'
                                       AND I.CDIMPOSTO = C_IMPOSTONF.CDIMPOSTO)
                     LOOP
                        V_ICMS := 'S';
                     END LOOP;

                     IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (V_ICMS = 'S') THEN
                        INSERT INTO IMPOSTONF(
                           CDFILIAL, NRLANCTONF, CDIMPOSTO, NRIMPOSNF, VRCONTABILNF, VRPERREDBCNF, VRBASECALCNF,
                           VRALIQNF, VRPARDEDNF, VRIMPOSTONF, CDFISCALNF, CDSITUTRIBNF, CDFISCOPERNF, CDSUFXCFOPNF, IDTRIMPOSTNF, CDSITUTRIBIMNFE, CDTPCREDPICONF, CDNATUBCALPCNF, IDMOTDESONERANF)
                        VALUES(P_FILIAL, P_LANCTONF, C_IMPOSTONF.CDIMPOSTO, C_IMPOSTONF.NRIMPOSNF,
                               V_LIQUIDO, 0, V_LIQUIDO,
                               V_ALIQUTMP, 0, TRUNC((V_LIQUIDO * (V_ALIQUTMP/100)),2), C_IMPOSTONF.CDFISCALNF,
                               C_IMPOSTONF.CDSITUTRIBNF, C_IMPOSTONF.CDFISCOPERNF, C_IMPOSTONF.CDSUFXCFOPNF, C_IMPOSTONF.IDTRIMPOSTNF, C_IMPOSTONF.CDSITUTRIBIMNFE, V_CDTPCRPICOSTNFEIT, V_CDNATUBCPCSTNFEIT, V_IDMOTIDESSTNFE);
                     ELSE
                        INSERT INTO IMPOSTONF(
                           CDFILIAL, NRLANCTONF, CDIMPOSTO, NRIMPOSNF, VRCONTABILNF, VRPERREDBCNF, VRBASECALCNF,
                           VRALIQNF, VRPARDEDNF, VRIMPOSTONF, CDFISCALNF, CDSITUTRIBNF, CDFISCOPERNF, CDSUFXCFOPNF, IDTRIMPOSTNF, CDSITUTRIBIMNFE, CDTPCREDPICONF, CDNATUBCALPCNF, IDMOTDESONERANF)
                        VALUES(P_FILIAL, P_LANCTONF, C_IMPOSTONF.CDIMPOSTO, C_IMPOSTONF.NRIMPOSNF,
                               V_LIQUIDO, 0, V_LIQUIDO,
                               V_ALIQUTMP, 0, (V_LIQUIDO * (V_ALIQUTMP/100)), C_IMPOSTONF.CDFISCALNF,
                               C_IMPOSTONF.CDSITUTRIBNF, C_IMPOSTONF.CDFISCOPERNF, C_IMPOSTONF.CDSUFXCFOPNF, C_IMPOSTONF.IDTRIMPOSTNF, C_IMPOSTONF.CDSITUTRIBIMNFE, V_CDTPCRPICOSTNFEIT, V_CDNATUBCPCSTNFEIT, V_IDMOTIDESSTNFE);
                     END IF;
                  ELSE
                     V_ICMS := 'N';
                     FOR C_ICMS IN (SELECT CDIMPOSTO
                                      FROM IMPOSTONFE N, IMPOSTO I
                                     WHERE N.CDIMPOSTONFE = I.CDIMPOSTONFE
                                       AND N.CDIMPOSTONFE = '00'
                                       AND I.CDIMPOSTO = C_IMPOSTONF.CDIMPOSTO)
                     LOOP
                        V_ICMS := 'S';
                     END LOOP;

                     IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (V_ICMS = 'S') THEN
                        INSERT INTO IMPOSTONF(
                           CDFILIAL, NRLANCTONF, CDIMPOSTO, NRIMPOSNF, VRCONTABILNF, VRPERREDBCNF, VRBASECALCNF,
                           VRALIQNF, VRPARDEDNF, VRIMPOSTONF, CDFISCALNF, CDSITUTRIBNF, CDFISCOPERNF, CDSUFXCFOPNF, IDTRIMPOSTNF, CDSITUTRIBIMNFE, CDTPCREDPICONF, CDNATUBCALPCNF, IDMOTDESONERANF)
                        VALUES(P_FILIAL, P_LANCTONF, C_IMPOSTONF.CDIMPOSTO, C_IMPOSTONF.NRIMPOSNF,
                               TRUNC((C_IMPOSTONF.VRCONTABILNF * V_VRFATOCONV),2), C_IMPOSTONF.VRPERREDBCNF, TRUNC((C_IMPOSTONF.VRBASECALCNF * V_VRFATOCONV),2),
                               C_IMPOSTONF.VRALIQNF, TRUNC((C_IMPOSTONF.VRPARDEDNF * V_VRFATOCONV),2), TRUNC((C_IMPOSTONF.VRIMPOSTONF * V_VRFATOCONV),2), C_IMPOSTONF.CDFISCALNF,
                               C_IMPOSTONF.CDSITUTRIBNF, C_IMPOSTONF.CDFISCOPERNF, C_IMPOSTONF.CDSUFXCFOPNF, C_IMPOSTONF.IDTRIMPOSTNF, C_IMPOSTONF.CDSITUTRIBIMNFE, V_CDTPCRPICOSTNFEIT, V_CDNATUBCPCSTNFEIT, V_IDMOTIDESSTNFE);
                     ELSE
                        INSERT INTO IMPOSTONF(
                           CDFILIAL, NRLANCTONF, CDIMPOSTO, NRIMPOSNF, VRCONTABILNF, VRPERREDBCNF, VRBASECALCNF,
                           VRALIQNF, VRPARDEDNF, VRIMPOSTONF, CDFISCALNF, CDSITUTRIBNF, CDFISCOPERNF, CDSUFXCFOPNF, IDTRIMPOSTNF, CDSITUTRIBIMNFE, CDTPCREDPICONF, CDNATUBCALPCNF, IDMOTDESONERANF)
                        VALUES(P_FILIAL, P_LANCTONF, C_IMPOSTONF.CDIMPOSTO, C_IMPOSTONF.NRIMPOSNF,
                               ROUND((C_IMPOSTONF.VRCONTABILNF * V_VRFATOCONV),2), C_IMPOSTONF.VRPERREDBCNF, (C_IMPOSTONF.VRBASECALCNF * V_VRFATOCONV),
                               C_IMPOSTONF.VRALIQNF, (C_IMPOSTONF.VRPARDEDNF * V_VRFATOCONV), (C_IMPOSTONF.VRIMPOSTONF * V_VRFATOCONV), C_IMPOSTONF.CDFISCALNF,
                               C_IMPOSTONF.CDSITUTRIBNF, C_IMPOSTONF.CDFISCOPERNF, C_IMPOSTONF.CDSUFXCFOPNF, C_IMPOSTONF.IDTRIMPOSTNF, C_IMPOSTONF.CDSITUTRIBIMNFE,  V_CDTPCRPICOSTNFEIT, V_CDNATUBCPCSTNFEIT, V_IDMOTIDESSTNFE);
                     END IF;

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

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

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

            FOR C_IMPOSTOITENS IN (SELECT CDFILIAL,     NRLANCTONF,     NRSEQITPROD,     CDIMPOSTO,      NRITPROIMPOS,    CDFISCALIT,
                                          CDSITUTRIBIT, CDFISCOPERIT,   CDSUFXCFOPIT,    VRALIQITEM,     VRPERREDBCIT,    VRPARDEDIT,
                                          VRCONTITIMP,  VRBASECALCIT,   VRIMPOSTOIT,     IDERROSIMPIT,   IDAVISIMPIT,     CDSITUTRIBITNFE,
                                          IDMODBCITNFE, IDMODBCSTITNFE, CDTPCREDPICOITE, CDNATUBCALPCIT, IDMOTDESONERAIT, IDTRIMPSTII,
                                          CDDETALHEPROD, CDENQLEGALIPI, CDCEST,          CDBENEFFISCAL
                                     FROM ITEMPROIMPOS
                                    WHERE CDFILIAL   = P_FILIAL
                                      AND NRLANCTONF = P_LANCTONF) LOOP

               INSERT INTO ITEMPROIMPOSORIG(CDFILIAL,      NRLANCTONF,     NRSEQITPROD,     CDIMPOSTO,      NRITPROIMPOS,    CDFISCALIT,
                                            CDSITUTRIBIT,  CDFISCOPERIT,   CDSUFXCFOPIT,    VRALIQITEM,     VRPERREDBCIT,    VRPARDEDIT,
                                            VRCONTITIMP,   VRBASECALCIT,   VRIMPOSTOIT,     IDERROSIMPIT,   IDAVISIMPIT,     CDSITUTRIBITNFE,
                                            IDMODBCITNFE,  IDMODBCSTITNFE, CDTPCREDPICOITE, CDNATUBCALPCIT, IDMOTDESONERAIT, IDTRIMPSTII,
                                            CDDETALHEPROD, CDENQLEGALIPI,  CDCEST,          CDBENEFFISCAL)
                    VALUES (C_IMPOSTOITENS.CDFILIAL,      C_IMPOSTOITENS.NRLANCTONF,     C_IMPOSTOITENS.NRSEQITPROD,     C_IMPOSTOITENS.CDIMPOSTO,      C_IMPOSTOITENS.NRITPROIMPOS,    C_IMPOSTOITENS.CDFISCALIT,
                            C_IMPOSTOITENS.CDSITUTRIBIT,  C_IMPOSTOITENS.CDFISCOPERIT,   C_IMPOSTOITENS.CDSUFXCFOPIT,    C_IMPOSTOITENS.VRALIQITEM,     C_IMPOSTOITENS.VRPERREDBCIT,    C_IMPOSTOITENS.VRPARDEDIT,
                            C_IMPOSTOITENS.VRCONTITIMP,   C_IMPOSTOITENS.VRBASECALCIT,   C_IMPOSTOITENS.VRIMPOSTOIT,     C_IMPOSTOITENS.IDERROSIMPIT,   C_IMPOSTOITENS.IDAVISIMPIT,     C_IMPOSTOITENS.CDSITUTRIBITNFE,
                            C_IMPOSTOITENS.IDMODBCITNFE,  C_IMPOSTOITENS.IDMODBCSTITNFE, C_IMPOSTOITENS.CDTPCREDPICOITE, C_IMPOSTOITENS.CDNATUBCALPCIT, C_IMPOSTOITENS.IDMOTDESONERAIT, C_IMPOSTOITENS.IDTRIMPSTII,
                            C_IMPOSTOITENS.CDDETALHEPROD, C_IMPOSTOITENS.CDENQLEGALIPI,  C_IMPOSTOITENS.CDCEST,          C_IMPOSTOITENS.CDBENEFFISCAL);
            END LOOP;
         END IF;

         FOR C_ITEMNOTAFISC IN (SELECT IT.CDFILIALIT, IT.NRLANCTONFIT, NVL(N.NRNOTAFISCALELE, N.NRNOTAFISC) AS NRNOTA,
                                       TO_CHAR(N.DTEMISSAO,  'DD/MM/YYYY') AS DTEMISSAO, N.VRNOTAFISC
                             FROM ITEMNOTAFISC IT, NOTAFISCAL N
                             WHERE IT.CDFILIAL   = P_FILIAL
                               AND IT.NRLANCTONF = P_LANCTONF
                               AND IT.CDFILIALIT   = N.CDFILIAL
                               AND IT.NRLANCTONFIT = N.NRLANCTONF) LOOP

            INSERT INTO DADOSADIC(CDFILIAL, NRLANCTONF, NRDADOADIC, DSDADOADIC)
                           VALUES(P_FILIAL, P_LANCTONF, V_DADOADIC, 'Nota de Origem: '|| C_ITEMNOTAFISC.NRNOTA||' (Emissão: '|| C_ITEMNOTAFISC.DTEMISSAO||' Total: '||DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(C_ITEMNOTAFISC.VRNOTAFISC, 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(C_ITEMNOTAFISC.VRNOTAFISC, 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(C_ITEMNOTAFISC.VRNOTAFISC, 2), '9999999999999.99')))|| ' )');
            V_DADOADIC := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_DADOADIC) + 1)),3,0);
         END LOOP;
      END IF;
-------------------
   ELSIF (P_TIPOOPER = w_03) THEN /*NOTA DE COMPLEMENTO*/

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

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

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

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

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

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

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

               V_PERDBCALC := 100 - C_IMPOSITEMCOM.VRPERREDBCIT;

               V_CONTABCALC  := V_VRTOTAITEM - (V_VRTOTAITEM * V_TAXABASECALC);

               IF C_IMPOSITEMCOM.VRPERMAJBCIT > 0 THEN

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

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

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

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

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

                  IF (NVL(V_IDVRIMPSTRIB,w_N) = w_N) THEN
                     V_VRIMPOSTOST := 0;
                  ELSE
                     Begin
                        SELECT NVL(MAX(VRIMPOSTOIT),0)
                        INTO   V_VRIMPOSTOST
                        FROM ITEMPROIMPOS I
                        WHERE (CDFILIAL     = P_FILIAL)                   AND
                              (NRLANCTONF   = P_LANCTONF)                 AND
                              (NRSEQITPROD  = C_IMPOSITEMCOM.NRSEQITPROD) AND
                              (INSTR(V_CDIMPOSTRIB,CDIMPOSTO||'_') > 0)  AND
                              (NRITPROIMPOS = w_1);
                     Exception
                        When No_Data_Found Then
                           V_VRIMPOSTOST := 0;
                     End;
                  END IF;
               END IF;
               /* ICMS-ST para nota fiscal de complento */


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

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

               SELECT NVL(MAX(IDPERVISIMPSCRE),'S')
                 INTO V_IDPERVISIMPSCRE
                 FROM PARAMGERAL;

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

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

               IF (C_IMPOSITEMCOM.VRPERREDBCIT > 0)  THEN

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

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

            END IF;
         END IF;
      END LOOP;

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

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

      END LOOP;

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

      FOR C_IMPOSNFTOT IN (SELECT CDIMPOSTO, 
                                  NVL(SUM(ROUND(VRIMPOSTOIT,2)),0) AS VRIMPOSTOIT, 
                                  NVL(SUM(ROUND(VRBASECALCIT,2)),0) AS VRBASECALCIT,
                                  NVL(SUM(ROUND(VRADICFECP,2)),0) AS VRADICFECP
                           FROM ITEMPROIMPOS
                           WHERE (CDFILIAL   = P_FILIAL)   AND
                                 (NRLANCTONF = P_LANCTONF)
                           GROUP BY CDIMPOSTO) LOOP

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

         IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (V_ICMS = 'S') THEN
            INSERT INTO IMPOSNFTOT(CDFILIAL, NRLANCTONF, CDIMPOSTO, VRTOTIMPONF, VRTOTBCALCNF,
                                   VRADICFECP)
                           VALUES (P_FILIAL, P_LANCTONF, C_IMPOSNFTOT.CDIMPOSTO, TRUNC(C_IMPOSNFTOT.VRIMPOSTOIT,V_NRDECITOTANF), TRUNC(C_IMPOSNFTOT.VRBASECALCIT,V_NRDECITOTANF),
                                   C_IMPOSNFTOT.VRADICFECP);
         ELSE
            INSERT INTO IMPOSNFTOT(CDFILIAL, NRLANCTONF, CDIMPOSTO, VRTOTIMPONF, VRTOTBCALCNF,
                                   VRADICFECP)
                           VALUES (P_FILIAL, P_LANCTONF, C_IMPOSNFTOT.CDIMPOSTO, ROUND(C_IMPOSNFTOT.VRIMPOSTOIT,V_NRDECITOTANF), ROUND(C_IMPOSNFTOT.VRBASECALCIT,V_NRDECITOTANF),
                                   C_IMPOSNFTOT.VRADICFECP);
         END IF;
      END LOOP;

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

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

      IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (NVL(V_IDORIGDESTNF, 'C') <> 'L') THEN
         UPDATE ITEMPRODUTO
         SET VRBRUTITEM   = TRUNC((VRTOTAITEM - VRDESCITEM),2),
             VRCONTITEM   = TRUNC((VRTOTAITEM - VRDESCITEM),2)
         WHERE CDFILIAL   = P_FILIAL   AND
               NRLANCTONF = P_LANCTONF;
      ELSE
         UPDATE ITEMPRODUTO
         SET VRBRUTITEM   = ROUND((VRTOTAITEM - VRDESCITEM),5),
             VRCONTITEM   = ROUND((VRTOTAITEM - VRDESCITEM),5)
         WHERE CDFILIAL   = P_FILIAL   AND
               NRLANCTONF = P_LANCTONF;
      END IF;

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

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

         FOR C_CSTTEMP IN (SELECT DSMENSCSTTMP
                           FROM CSTTEMP
                           WHERE (NRCSTTEMP = V_CSTTEMP)    AND
                                 (DSMENSCSTTMP IS NOT NULL) AND
                                 (NOT EXISTS(SELECT DSDADOADIC
                                             FROM DADOSADIC
                                             WHERE (CDFILIAL   = P_FILIAL)   AND
                                                   (NRLANCTONF = P_LANCTONF) AND
                                                   (DSDADOADIC LIKE CSTTEMP.DSMENSCSTTMP || '%')))) LOOP

            IF NOT (C_CSTTEMP.DSMENSCSTTMP IS NULL) THEN
               INSERT INTO DADOSADIC(CDFILIAL, NRLANCTONF, NRDADOADIC, DSDADOADIC)
               VALUES(P_FILIAL, P_LANCTONF, V_DADOADIC, C_CSTTEMP.DSMENSCSTTMP);

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

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

         FOR C_CFOPTEMP IN (SELECT DSMENSCFOTMP
                            FROM CFOPTEMP
                            WHERE (NRCFOPTEMP = V_CFOPTEMP)  AND
                                  (DSMENSCFOTMP IS NOT NULL) AND
                                  (NOT EXISTS(SELECT DSDADOADIC
                                              FROM DADOSADIC
                                              WHERE (CDFILIAL   = P_FILIAL)   AND
                                                    (NRLANCTONF = P_LANCTONF) AND
                                                    (DSDADOADIC LIKE CFOPTEMP.DSMENSCFOTMP || '%')))) LOOP

            IF NOT (C_CFOPTEMP.DSMENSCFOTMP IS NULL) THEN
               INSERT INTO DADOSADIC(CDFILIAL, NRLANCTONF, NRDADOADIC, DSDADOADIC)
               VALUES(P_FILIAL, P_LANCTONF, V_DADOADIC, C_CFOPTEMP.DSMENSCFOTMP);

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

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

            SELECT MAX(CDFISOPETMP), MAX(CDSUFCFOPTMP), SUBSTR(MAX(DSCFOPTMP),1,50)
            INTO   V_FISOPEITEM    , V_SUFXCFOPPR, V_DSCDFISOPEIT
            FROM CFOPTEMP
            WHERE NRCFOPTEMP = V_CFOPTEMP;

            SELECT MAX(CDSITTRIBTMP)
            INTO   V_SITUTRIBPR
            FROM CSTTEMP
            WHERE NRCSTTEMP = V_CSTTEMP;
         ELSE
            V_CFOPINFUSU := 'S';
            V_FISOPEITEM := C_ITPROD.CDCFOPINFUSU;
            V_SUFXCFOPPR := C_ITPROD.CDSUFXINFUSU;
            V_SITUTRIBPR := C_ITPROD.CDCSTINFUSU;
         END IF;

         IF V_IDDOCREPLIC IS NOT NULL THEN
            IF LENGTH(V_SITUTRIBPR) = 3 THEN
               V_SITUTRIBPR := SUBSTR(V_SITUTRIBPR,1,1) || w_90;
            ELSE
               V_SITUTRIBPR := w_90;
            END IF;
         END IF;

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

         UPDATE ITEMPRODUTO
         SET CDFISOPEITEM  = V_FISOPEITEM,
             CDSUFXCFOPPR  = V_SUFXCFOPPR,
             CDSITUTRIBPR  = V_SITUTRIBPR,
             DSCDFISOPEIT  = V_DSCDFISOPEIT,
             CDFISCOPERSN  = V_CDFISCOPERSN
         WHERE CDFILIAL    = P_FILIAL   AND
               NRLANCTONF  = P_LANCTONF AND
               NRSEQITPROD = C_ITPROD.NRSEQITPROD;

         DELETE CFOPTEMP
         WHERE NRCFOPTEMP = V_CFOPTEMP;

         DELETE CSTTEMP
         WHERE NRCSTTEMP = V_CSTTEMP;

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

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

             V_IMPOICMS := NULL;
             V_CDGRUPOFISCAUX := NULL;

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

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

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

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

         END LOOP;
      END LOOP;
   END IF;

   V_DIFERENCA := 0;
   /* RATEIO DOS ENCARGOS PARA OS PRODUTOS DA NOTA. ESTE RATEIO É NECESSÁRIO PARA A NOTA FISCAL ELETRÔNICA */
   FOR C_ITEMENCARGO IN (SELECT ENCARGO.CDENCARGONFE, SUM(ITEMENCARGO.VRITEMENCA) AS VRITEMENCA
                           FROM ITEMENCARGO, ENCARGO
                          WHERE ITEMENCARGO.CDENCARGO = ENCARGO.CDENCARGO
                            AND ENCARGO.CDENCARGONFE IN ('01', '02', '03', '04', '05')
                            AND NVL(ITEMENCARGO.VRITEMENCA, 0) >= 0
                            AND CDFILIAL = P_FILIAL
                            AND NRLANCTONF = P_LANCTONF
                          GROUP BY ENCARGO.CDENCARGONFE) LOOP
      /* ENCARGO FRETE */
      IF (C_ITEMENCARGO.CDENCARGONFE = '01') THEN
         IF (C_ITEMENCARGO.VRITEMENCA > 0) THEN
            FOR C_ITEMPRODUTO IN (SELECT NRSEQITPROD, VRTOTAITEM
                                    FROM ITEMPRODUTO
                                   WHERE CDFILIAL = P_FILIAL
                                     AND NRLANCTONF = P_LANCTONF) LOOP

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

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

            V_DIFERENCA := C_ITEMENCARGO.VRITEMENCA - V_VRFRETEITEM;

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

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

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

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

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

            V_DIFERENCA := C_ITEMENCARGO.VRITEMENCA - V_VRSEGURITEM;

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

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

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

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

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

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

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

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

            END IF;
         ELSE
            UPDATE ITEMPRODUTO
               SET VRENCARGODESC = VRDESCITEM + 0
             WHERE CDFILIAL  = P_FILIAL
               AND NRLANCTONF = P_LANCTONF;
         END IF;
      END IF;
           /*ENCARGO OUTRAS DESPESAS*/
      IF (C_ITEMENCARGO.CDENCARGONFE = '04') THEN
         IF (C_ITEMENCARGO.VRITEMENCA > 0) THEN
            IF (V_IDNFORIGVIAXML = 'S') THEN
               FOR C_ITEMPRODUTO IN (SELECT NRSEQITPROD, VRTOTAITEM, VRENCARGOIMPXML
                                       FROM ITEMPRODUTO
                                      WHERE CDFILIAL = P_FILIAL
                                        AND NRLANCTONF = P_LANCTONF
                                        AND VRENCARGOIMPXML > 0) LOOP

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

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

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

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

            V_DIFERENCA := C_ITEMENCARGO.VRITEMENCA - V_VROUTRASDESPITEM;

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

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

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

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

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

            V_DIFERENCA := C_ITEMENCARGO.VRITEMENCA - V_VRDESPADUANEIRA;

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

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

--CÁLCULO DO VALOR TOTAL DA NOTA FISCAL

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

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

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

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

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

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

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

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

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

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

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

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

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

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

   IF P_TIPOOPER = w_12 THEN

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

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

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

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

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

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

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

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

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

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

   CONSULTA_DESONERACAO(P_FILIAL, P_LANCTONF, V_IMPOSDESONERA);

   V_TOTALNOTA := V_TOTALNOTA - V_IMPOSDESONERA;

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

   IF (V_IDCONTCONFORIG = 'N') OR (V_IDOPERDEVONF <> w_S) THEN
      SELECT NVL(V_TOTALNOTA,0) - SUM(ROUND(NVL(VRBRUTITEM,0), 5))
        INTO V_DIFEVRBRUTO
        FROM ITEMPRODUTO
       WHERE CDFILIAL = P_FILIAL
         AND NRLANCTONF = P_LANCTONF;

      IF V_DIFEVRBRUTO <> 0 THEN
         UPDATE ITEMPRODUTO
            SET VRBRUTITEM = ROUND(VRBRUTITEM + V_DIFEVRBRUTO,5)
          WHERE CDFILIAL = P_FILIAL
            AND NRLANCTONF = P_LANCTONF
            AND NRSEQITPROD = (SELECT MAX(I.NRSEQITPROD)
                                 FROM ITEMPRODUTO I
                                WHERE I.CDFILIAL     = P_FILIAL
                                  AND I.NRLANCTONF   = P_LANCTONF
                                  AND VRTOTAITEM = (SELECT MAX(VRTOTAITEM)
                                                      FROM ITEMPRODUTO I
                                                     WHERE I.CDFILIAL     = P_FILIAL
                                                       AND I.NRLANCTONF   = P_LANCTONF));

      END IF;
   END IF;

-- RECALCULO DO VALOR CONTABIL DO ITEM

   FOR C_ITEM IN (SELECT II.CDIMPOSTO, I.VRBRUTITEM, I.NRSEQITPROD, I.VRCONTITEM
                  FROM ITEMPRODUTO I, ITEMPROIMPOS II
                  WHERE I.CDFILIAL    = P_FILIAL       AND
                        I.NRLANCTONF  = P_LANCTONF     AND
                        I.CDFILIAL    = II.CDFILIAL    AND
                        I.NRLANCTONF  = II.NRLANCTONF  AND
                        I.NRSEQITPROD = II.NRSEQITPROD ) LOOP
      V_ICMS := 'N';
      FOR C_ICMS IN (SELECT CDIMPOSTO
                       FROM IMPOSTONFE N, IMPOSTO I
                      WHERE N.CDIMPOSTONFE = I.CDIMPOSTONFE
                        AND N.CDIMPOSTONFE = '00'
                        AND I.CDIMPOSTO = C_ITEM.CDIMPOSTO)
      LOOP
         V_ICMS := 'S';
      END LOOP;

      IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (V_ICMS = 'S') THEN
         UPDATE ITEMPROIMPOS
         SET VRCONTITIMP = TRUNC(VRCONTITIMP,2)
         WHERE (NRLANCTONF   = P_LANCTONF)         AND
               (CDFILIAL     = P_FILIAL)           AND
               (NRSEQITPROD  = C_ITEM.NRSEQITPROD) AND
               (CDIMPOSTO    = C_ITEM.CDIMPOSTO)   AND
               (NRITPROIMPOS = w_2);
      ELSE
         UPDATE ITEMPROIMPOS
         SET VRCONTITIMP = ROUND(VRCONTITIMP,5)    
         WHERE (NRLANCTONF   = P_LANCTONF)         AND
               (CDFILIAL     = P_FILIAL)           AND
               (NRSEQITPROD  = C_ITEM.NRSEQITPROD) AND
               (CDIMPOSTO    = C_ITEM.CDIMPOSTO)   AND
               (NRITPROIMPOS = w_2);
      END IF;

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

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

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

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

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

   END LOOP;

   ARREDONDA_BASECALC(w_S, P_FILIAL, P_LANCTONF);

   V_SEQUIMPOSTNF := w_01;

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

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

   /* GERANDO INFORMAÇÕES NA TABELA IMPOSTONF */
   IF V_NRDECITOTANF = 0 THEN
      IF V_IDOPERDEVONF = W_S THEN
         FOR C_IMPOSTONF IN (SELECT IT.CDIMPOSTO, 
                                    VRALIQITEM, 
                                    VRPERREDBCIT, 
                                    VRPARDEDIT, 
                                    CDFISCALIT,
                                    CDSITUTRIBIT, 
                                    CDFISCOPERIT, 
                                    CDSUFXCFOPIT, 
                                    IDTRIMPSTII,
                                    IT.VRADICALIQFECP,
                                    SUM(VRCONTITIMP) AS VRCONTITIMP,
                                    SUM(VRBASECALCIT) AS VRBASECALCIT, 
                                    SUM(VRIMPOSTOIT) AS VRIMPOSTOIT,
                                    MAX(NRITPROIMPOS) AS NRITPROIMPOS,
                                    SUM(VRBCICMSSTRETIDO) AS VRBCICMSSTRETIDO, 
                                    SUM(VRICMSSTRETIDO) VRICMSSTRETIDO,
                                    SUM(IT.VRADICFECP) AS VRADICFECP,
                                    NVL(IDDIFALIQCUSPRI, 'N') AS IDDIFALIQCUSPRI
                               FROM ITEMPROIMPOS IT, IMPOSTO I
                              WHERE (CDFILIAL = P_FILIAL)
                                AND (NRLANCTONF = P_LANCTONF)
                                AND (IT.CDIMPOSTO = I.CDIMPOSTO) 
                                AND (((CDFISCALIT = w_1) AND (IDIMPORECUP = w_S)) OR ((IDIMPORECUP <> w_S) AND (VRALIQITEM <> 0)))
                              GROUP BY IT.CDIMPOSTO, 
                                    VRALIQITEM, 
                                    VRPERREDBCIT, 
                                    VRPARDEDIT, 
                                    CDFISCALIT,
                                    CDSITUTRIBIT, 
                                    CDFISCOPERIT, 
                                    CDSUFXCFOPIT, 
                                    IDTRIMPSTII, 
                                    IT.VRADICALIQFECP,
                                    IDDIFALIQCUSPRI
                              UNION
                             SELECT IT.CDIMPOSTO, 
                                    0 AS VRALIQITEM, 
                                    0 AS VRPERREDBCIT, 
                                    0 AS VRPARDEDIT, 
                                    CDFISCALIT,
                                    CDSITUTRIBIT, 
                                    CDFISCOPERIT, 
                                    CDSUFXCFOPIT, 
                                    IDTRIMPSTII, 
                                    IT.VRADICALIQFECP,
                                    SUM(VRCONTITIMP) AS VRCONTITIMP,
                                    0 AS VRBASECALCIT, 
                                    0 AS VRIMPOSTOIT,
                                    MAX(NRITPROIMPOS) AS NRITPROIMPOS,
                                    SUM(VRBCICMSSTRETIDO) AS VRBCICMSSTRETIDO, 
                                    SUM(VRICMSSTRETIDO) AS VRICMSSTRETIDO,
                                    SUM(IT.VRADICFECP) AS VRADICFECP,
                                    NVL(IDDIFALIQCUSPRI, 'N') AS IDDIFALIQCUSPRI
                               FROM ITEMPROIMPOS IT, IMPOSTO I
                              WHERE (CDFILIAL = P_FILIAL)
                                AND (NRLANCTONF = P_LANCTONF)
                                AND (IT.CDIMPOSTO = I.CDIMPOSTO) 
                                AND (NRITPROIMPOS <> w_3)
                                AND (((CDFISCALIT <> w_1) AND (IDIMPORECUP = w_S)) OR ((IDIMPORECUP <> w_S) AND (VRALIQITEM = 0))) 
                              GROUP BY IT.CDIMPOSTO, 
                                    CDFISCALIT, 
                                    CDSITUTRIBIT,
                                    CDFISCOPERIT, 
                                    CDSUFXCFOPIT, 
                                    IDTRIMPSTII, 
                                    IT.VRADICALIQFECP,
                                    IDDIFALIQCUSPRI
                              UNION
                             SELECT IT.CDIMPOSTO, 
                                    VRALIQITEM, 
                                    VRPERREDBCIT, 
                                    VRPARDEDIT, 
                                    CDFISCALIT,
                                    CDSITUTRIBIT, 
                                    CDFISCOPERIT, 
                                    CDSUFXCFOPIT, 
                                    IDTRIMPSTII, 
                                    IT.VRADICALIQFECP,
                                    SUM(VRCONTITIMP) AS VRCONTITIMP,
                                    SUM(VRBASECALCIT) AS VRBASECALCIT, 
                                    SUM(VRIMPOSTOIT) AS VRIMPOSTOIT,
                                    MAX(NRITPROIMPOS) AS NRITPROIMPOS,
                                    SUM(VRBCICMSSTRETIDO) VRBCICMSSTRETIDO, 
                                    SUM(VRICMSSTRETIDO) VRICMSSTRETIDO,
                                    SUM(IT.VRADICFECP) AS VRADICFECP,
                                    NVL(IDDIFALIQCUSPRI, 'N') AS IDDIFALIQCUSPRI
                               FROM ITEMPROIMPOS IT, IMPOSTO I
                              WHERE (CDFILIAL = P_FILIAL)
                                AND (NRLANCTONF = P_LANCTONF)
                                AND (IT.CDIMPOSTO = I.CDIMPOSTO)
                                AND (NRITPROIMPOS = w_3)
                              GROUP BY 
                                    IT.CDIMPOSTO, 
                                    VRALIQITEM, 
                                    VRPERREDBCIT, 
                                    VRPARDEDIT, 
                                    CDFISCALIT,
                                    CDSITUTRIBIT, 
                                    CDFISCOPERIT, 
                                    CDSUFXCFOPIT, 
                                    IDTRIMPSTII, 
                                    IT.VRADICALIQFECP,
                                    IDDIFALIQCUSPRI) 
         LOOP
            V_ICMS := 'N';
            FOR C_ICMS IN (SELECT CDIMPOSTO
                             FROM IMPOSTONFE N, IMPOSTO I
                            WHERE N.CDIMPOSTONFE = I.CDIMPOSTONFE
                              AND N.CDIMPOSTONFE = '00'
                              AND I.CDIMPOSTO = C_IMPOSTONF.CDIMPOSTO)
            LOOP
               V_ICMS := 'S';
            END LOOP;
            
            IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (V_ICMS = 'S') THEN
               INSERT INTO IMPOSTONF(
                  CDFILIAL, NRLANCTONF, CDIMPOSTO, NRIMPOSNF, 
                  VRCONTABILNF, VRPERREDBCNF, VRBASECALCNF, VRALIQNF, 
                  VRPARDEDNF, VRIMPOSTONF, CDFISCALNF, CDSITUTRIBNF,
                  CDFISCOPERNF, CDSUFXCFOPNF, IDIMPOSTONF, VRBCICMSSTRETIDO, 
                  VRICMSSTRETIDO, IDTRIMPOSTNF, IDDIFALIQCUSPRN, VRADICALIQFECP, 
                  VRADICFECP)
               VALUES(
                  P_FILIAL, P_LANCTONF, C_IMPOSTONF.CDIMPOSTO, V_SEQUIMPOSTNF, 
                  C_IMPOSTONF.VRCONTITIMP, C_IMPOSTONF.VRPERREDBCIT, C_IMPOSTONF.VRBASECALCIT, C_IMPOSTONF.VRALIQITEM, 
                  C_IMPOSTONF.VRPARDEDIT, TRUNC(C_IMPOSTONF.VRIMPOSTOIT,0), C_IMPOSTONF.CDFISCALIT, C_IMPOSTONF.CDSITUTRIBIT,
                  C_IMPOSTONF.CDFISCOPERIT, C_IMPOSTONF.CDSUFXCFOPIT, C_IMPOSTONF.NRITPROIMPOS, C_IMPOSTONF.VRBCICMSSTRETIDO, 
                  C_IMPOSTONF.VRICMSSTRETIDO, C_IMPOSTONF.IDTRIMPSTII, C_IMPOSTONF.IDDIFALIQCUSPRI, C_IMPOSTONF.VRADICALIQFECP, 
                  C_IMPOSTONF.VRADICFECP);
            ELSE
               INSERT INTO IMPOSTONF(
                  CDFILIAL, NRLANCTONF, CDIMPOSTO, NRIMPOSNF, 
                  VRCONTABILNF, VRPERREDBCNF, VRBASECALCNF, VRALIQNF, 
                  VRPARDEDNF, VRIMPOSTONF, CDFISCALNF, CDSITUTRIBNF,
                  CDFISCOPERNF, CDSUFXCFOPNF, IDIMPOSTONF, VRBCICMSSTRETIDO, 
                  VRICMSSTRETIDO, IDTRIMPOSTNF, IDDIFALIQCUSPRN, VRADICALIQFECP, 
                  VRADICFECP)
               VALUES(
                  P_FILIAL, P_LANCTONF, C_IMPOSTONF.CDIMPOSTO, V_SEQUIMPOSTNF, 
                  C_IMPOSTONF.VRCONTITIMP, C_IMPOSTONF.VRPERREDBCIT, C_IMPOSTONF.VRBASECALCIT, C_IMPOSTONF.VRALIQITEM, 
                  C_IMPOSTONF.VRPARDEDIT, ROUND(C_IMPOSTONF.VRIMPOSTOIT,0), C_IMPOSTONF.CDFISCALIT, C_IMPOSTONF.CDSITUTRIBIT,
                  C_IMPOSTONF.CDFISCOPERIT, C_IMPOSTONF.CDSUFXCFOPIT, C_IMPOSTONF.NRITPROIMPOS, C_IMPOSTONF.VRBCICMSSTRETIDO, 
                  C_IMPOSTONF.VRICMSSTRETIDO, C_IMPOSTONF.IDTRIMPSTII, C_IMPOSTONF.IDDIFALIQCUSPRI, C_IMPOSTONF.VRADICALIQFECP, 
                  C_IMPOSTONF.VRADICFECP);
            END IF;

            V_SEQUIMPOSTNF := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_SEQUIMPOSTNF) + 1)),2,0);
         END LOOP;
      ELSE
         FOR C_IMPOSTONF IN (SELECT IT.CDIMPOSTO, 
                                    VRALIQITEM, 
                                    VRPERREDBCIT, 
                                    VRPARDEDIT, 
                                    CDFISCALIT, 
                                    CDSITUTRIBIT,
                                    CDFISCOPERIT, 
                                    CDSUFXCFOPIT, 
                                    IDTRIMPSTII, 
                                    IT.VRADICALIQFECP,
                                    SUM(ROUND(VRCONTITIMP,5)) AS VRCONTITIMP, 
                                    SUM(VRBASECALCIT) AS VRBASECALCIT, 
                                    SUM(VRIMPOSTOIT) AS VRIMPOSTOIT, 
                                    NRITPROIMPOS, 
                                    SUM(VRBCICMSSTRETIDO) AS VRBCICMSSTRETIDO, 
                                    SUM(IT.VRADICFECP) AS VRADICFECP,
                                    SUM(VRICMSSTRETIDO) VRICMSSTRETIDO
                             FROM ITEMPROIMPOS IT, IMPOSTO I
                             WHERE (CDFILIAL = P_FILIAL)
                               AND (NRLANCTONF = P_LANCTONF)
                               AND (IT.CDIMPOSTO = I.CDIMPOSTO)
                               AND (((CDFISCALIT = w_1) AND (IDIMPORECUP = w_S)) OR ((IDIMPORECUP <> w_S) AND (VRALIQITEM <> 0)))
                             GROUP BY IT.CDIMPOSTO, 
                                   VRALIQITEM, 
                                   VRPERREDBCIT, 
                                   VRPARDEDIT, 
                                   CDFISCALIT,
                                   CDSITUTRIBIT,
                                   CDFISCOPERIT,
                                   CDSUFXCFOPIT,
                                   IDTRIMPSTII,
                                   IT.VRADICALIQFECP,
                                   NRITPROIMPOS
                             UNION
                            SELECT IT.CDIMPOSTO, 
                                   0 AS VRALIQITEM, 
                                   0 AS VRPERREDBCIT, 
                                   0 AS VRPARDEDIT, 
                                   CDFISCALIT, 
                                   CDSITUTRIBIT,
                                   CDFISCOPERIT, 
                                   CDSUFXCFOPIT, 
                                   IDTRIMPSTII, 
                                   IT.VRADICALIQFECP,
                                   SUM(ROUND(VRCONTITIMP,5)) AS VRCONTITIMP, 
                                   0 AS VRBASECALCIT, 
                                   0 AS VRIMPOSTOIT,  
                                   NRITPROIMPOS, 
                                   SUM(VRBCICMSSTRETIDO) AS VRBCICMSSTRETIDO, 
                                   SUM(IT.VRADICFECP) AS VRADICFECP,
                                   SUM(VRICMSSTRETIDO) AS VRICMSSTRETIDO
                              FROM ITEMPROIMPOS IT, IMPOSTO I
                             WHERE (CDFILIAL = P_FILIAL)
                               AND (NRLANCTONF = P_LANCTONF)
                               AND (IT.CDIMPOSTO = I.CDIMPOSTO)
                               AND (((IT.CDFISCALIT <> w_1) AND (IDIMPORECUP = w_S)) OR ((I.IDIMPORECUP  <> w_S) AND (VRALIQITEM = 0)))
                             GROUP BY IT.CDIMPOSTO, 
                                   CDFISCALIT, 
                                   CDSITUTRIBIT,
                                   CDFISCOPERIT, 
                                   CDSUFXCFOPIT, 
                                   IDTRIMPSTII, 
                                   IT.VRADICALIQFECP,
                                   NRITPROIMPOS) 
         LOOP
            V_ICMS := 'N';
            FOR C_ICMS IN (SELECT CDIMPOSTO
                             FROM IMPOSTONFE N, IMPOSTO I
                            WHERE N.CDIMPOSTONFE = I.CDIMPOSTONFE
                              AND N.CDIMPOSTONFE = '00'
                              AND I.CDIMPOSTO = C_IMPOSTONF.CDIMPOSTO)
            LOOP
               V_ICMS := 'S';
            END LOOP;

            IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (V_ICMS = 'S') THEN
               INSERT INTO IMPOSTONF(
                  CDFILIAL, NRLANCTONF, CDIMPOSTO, NRIMPOSNF, 
                  VRCONTABILNF, VRPERREDBCNF, VRBASECALCNF, VRALIQNF, 
                  VRPARDEDNF, VRIMPOSTONF, CDFISCALNF, CDSITUTRIBNF,
                  CDFISCOPERNF, CDSUFXCFOPNF, IDIMPOSTONF, VRBCICMSSTRETIDO, 
                  VRICMSSTRETIDO, IDTRIMPOSTNF, VRADICALIQFECP, VRADICFECP)
               VALUES(
                  P_FILIAL, P_LANCTONF, C_IMPOSTONF.CDIMPOSTO, V_SEQUIMPOSTNF, 
                  C_IMPOSTONF.VRCONTITIMP, C_IMPOSTONF.VRPERREDBCIT, C_IMPOSTONF.VRBASECALCIT, C_IMPOSTONF.VRALIQITEM, 
                  C_IMPOSTONF.VRPARDEDIT, TRUNC(C_IMPOSTONF.VRIMPOSTOIT,0), C_IMPOSTONF.CDFISCALIT, C_IMPOSTONF.CDSITUTRIBIT,
                  C_IMPOSTONF.CDFISCOPERIT, C_IMPOSTONF.CDSUFXCFOPIT, C_IMPOSTONF.NRITPROIMPOS, C_IMPOSTONF.VRBCICMSSTRETIDO, 
                  C_IMPOSTONF.VRICMSSTRETIDO, C_IMPOSTONF.IDTRIMPSTII, C_IMPOSTONF.VRADICALIQFECP, C_IMPOSTONF.VRADICFECP);
            ELSE
               INSERT INTO IMPOSTONF(
                  CDFILIAL, NRLANCTONF, CDIMPOSTO, NRIMPOSNF, 
                  VRCONTABILNF, VRPERREDBCNF, VRBASECALCNF, VRALIQNF, 
                  VRPARDEDNF, VRIMPOSTONF, CDFISCALNF, CDSITUTRIBNF,
                  CDFISCOPERNF, CDSUFXCFOPNF, IDIMPOSTONF, VRBCICMSSTRETIDO, 
                  VRICMSSTRETIDO, IDTRIMPOSTNF, VRADICALIQFECP, VRADICFECP)
               VALUES(
                  P_FILIAL, P_LANCTONF, C_IMPOSTONF.CDIMPOSTO, V_SEQUIMPOSTNF, 
                  C_IMPOSTONF.VRCONTITIMP, C_IMPOSTONF.VRPERREDBCIT, C_IMPOSTONF.VRBASECALCIT, C_IMPOSTONF.VRALIQITEM, 
                  C_IMPOSTONF.VRPARDEDIT, ROUND(C_IMPOSTONF.VRIMPOSTOIT,0), C_IMPOSTONF.CDFISCALIT, C_IMPOSTONF.CDSITUTRIBIT,
                  C_IMPOSTONF.CDFISCOPERIT, C_IMPOSTONF.CDSUFXCFOPIT, C_IMPOSTONF.NRITPROIMPOS, C_IMPOSTONF.VRBCICMSSTRETIDO, 
                  C_IMPOSTONF.VRICMSSTRETIDO, C_IMPOSTONF.IDTRIMPSTII, C_IMPOSTONF.VRADICALIQFECP, C_IMPOSTONF.VRADICFECP);
            END IF;

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

   ELSE
      IF V_IDOPERDEVONF = w_S THEN
         FOR C_IMPOSTONF IN (SELECT IT.CDIMPOSTO, 
                                    VRALIQITEM, 
                                    VRPERREDBCIT, 
                                    VRPARDEDIT, 
                                    CDFISCALIT, 
                                    CDSITUTRIBIT,
                                    CDFISCOPERIT, 
                                    CDSUFXCFOPIT, 
                                    IDTRIMPSTII, 
                                    IT.VRADICALIQFECP,
                                    SUM(VRCONTITIMP) AS VRCONTITIMP, 
                                    SUM(VRBASECALCIT) AS VRBASECALCIT, 
                                    SUM(VRIMPOSTOIT) AS VRIMPOSTOIT,
                                    MAX(NRITPROIMPOS) AS NRITPROIMPOS, 
                                    SUM(VRBCICMSSTRETIDO) AS VRBCICMSSTRETIDO, 
                                    SUM(VRICMSSTRETIDO) AS VRICMSSTRETIDO,
                                    SUM(IT.VRADICFECP) AS VRADICFECP,
                                    NVL(IDDIFALIQCUSPRI, 'N') AS IDDIFALIQCUSPRI
                               FROM ITEMPROIMPOS IT, IMPOSTO I
                              WHERE (CDFILIAL = P_FILIAL)
                                AND (NRLANCTONF = P_LANCTONF)
                                AND (IT.CDIMPOSTO = I.CDIMPOSTO)
                                AND (((CDFISCALIT = w_1) AND (IDIMPORECUP = w_S)) OR ((IDIMPORECUP <> w_S) AND (VRALIQITEM <> 0)))
                              GROUP BY IT.CDIMPOSTO, 
                                    VRALIQITEM, 
                                    VRPERREDBCIT, 
                                    VRPARDEDIT, 
                                    CDFISCALIT,
                                    CDSITUTRIBIT, 
                                    CDFISCOPERIT, 
                                    CDSUFXCFOPIT, 
                                    IDTRIMPSTII, 
                                    IT.VRADICALIQFECP,
                                    IDDIFALIQCUSPRI
                              UNION
                             SELECT IT.CDIMPOSTO, 
                                    0 AS VRALIQITEM, 
                                    0 AS VRPERREDBCIT, 
                                    0 AS VRPARDEDIT, 
                                    CDFISCALIT, 
                                    CDSITUTRIBIT,
                                    CDFISCOPERIT, 
                                    CDSUFXCFOPIT, 
                                    IDTRIMPSTII, 
                                    IT.VRADICALIQFECP,
                                    SUM(VRCONTITIMP) AS VRCONTITIMP, 
                                    0 AS VRBASECALCIT, 
                                    0 AS VRIMPOSTOIT,
                                    MAX(NRITPROIMPOS) AS NRITPROIMPOS, 
                                    SUM(VRBCICMSSTRETIDO) AS VRBCICMSSTRETIDO, 
                                    SUM(VRICMSSTRETIDO) AS VRICMSSTRETIDO,
                                    SUM(IT.VRADICFECP) AS VRADICFECP,
                                    NVL(IDDIFALIQCUSPRI, 'N') AS IDDIFALIQCUSPRI
                               FROM ITEMPROIMPOS IT, IMPOSTO I
                              WHERE (CDFILIAL = P_FILIAL)
                                AND (NRLANCTONF = P_LANCTONF)
                                AND (IT.CDIMPOSTO = I.CDIMPOSTO)
                                AND (NRITPROIMPOS <> w_3)
                                AND (((CDFISCALIT <> w_1) AND (IDIMPORECUP = w_S)) OR ((IDIMPORECUP <> w_S) AND (VRALIQITEM = 0)))
                              GROUP BY IT.CDIMPOSTO, 
                                    CDFISCALIT, 
                                    CDSITUTRIBIT,
                                    CDFISCOPERIT, 
                                    CDSUFXCFOPIT, 
                                    IDTRIMPSTII, 
                                    IT.VRADICALIQFECP,
                                    IDDIFALIQCUSPRI
                              UNION
                             SELECT IT.CDIMPOSTO, 
                                    VRALIQITEM, 
                                    VRPERREDBCIT, 
                                    VRPARDEDIT, 
                                    CDFISCALIT, 
                                    CDSITUTRIBIT,
                                    CDFISCOPERIT, 
                                    CDSUFXCFOPIT, 
                                    IDTRIMPSTII, 
                                    IT.VRADICALIQFECP,
                                    SUM(VRCONTITIMP) AS VRCONTITIMP, 
                                    SUM(VRBASECALCIT) AS VRBASECALCIT, 
                                    SUM(VRIMPOSTOIT) AS VRIMPOSTOIT,
                                    MAX(NRITPROIMPOS) AS NRITPROIMPOS, 
                                    SUM(VRBCICMSSTRETIDO) AS VRBCICMSSTRETIDO, 
                                    SUM(VRICMSSTRETIDO) AS VRICMSSTRETIDO,
                                    SUM(IT.VRADICFECP) AS VRADICFECP,
                                    NVL(IDDIFALIQCUSPRI, 'N') AS IDDIFALIQCUSPRI
                               FROM ITEMPROIMPOS IT, IMPOSTO I
                              WHERE (CDFILIAL = P_FILIAL)
                                AND (NRLANCTONF = P_LANCTONF)
                                AND (IT.CDIMPOSTO = I.CDIMPOSTO) 
                                AND (NRITPROIMPOS = w_3)
                              GROUP BY IT.CDIMPOSTO, 
                                    VRALIQITEM, 
                                    VRPERREDBCIT, 
                                    VRPARDEDIT, 
                                    CDFISCALIT,
                                    CDSITUTRIBIT,
                                    CDFISCOPERIT,
                                    CDSUFXCFOPIT,
                                    IDTRIMPSTII,
                                    IT.VRADICALIQFECP,
                                    IDDIFALIQCUSPRI) 
         LOOP
            V_ICMS := 'N';
            FOR C_ICMS IN (SELECT CDIMPOSTO
                             FROM IMPOSTONFE N, IMPOSTO I
                            WHERE N.CDIMPOSTONFE = I.CDIMPOSTONFE
                              AND N.CDIMPOSTONFE = '00'
                              AND I.CDIMPOSTO = C_IMPOSTONF.CDIMPOSTO)
            LOOP
               V_ICMS := 'S';
            END LOOP;

            IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (V_ICMS = 'S') THEN
               INSERT INTO IMPOSTONF(
                  CDFILIAL, NRLANCTONF, CDIMPOSTO, NRIMPOSNF, 
                  VRCONTABILNF, VRPERREDBCNF, VRBASECALCNF, VRALIQNF, 
                  VRPARDEDNF, VRIMPOSTONF, CDFISCALNF, CDSITUTRIBNF,
                  CDFISCOPERNF, CDSUFXCFOPNF, IDIMPOSTONF, VRBCICMSSTRETIDO, 
                  VRICMSSTRETIDO, IDTRIMPOSTNF, IDDIFALIQCUSPRN, VRADICALIQFECP, 
                  VRADICFECP)
               VALUES(
                  P_FILIAL, P_LANCTONF, C_IMPOSTONF.CDIMPOSTO, V_SEQUIMPOSTNF, 
                  TRUNC(C_IMPOSTONF.VRCONTITIMP,V_NRDECITOTANF), C_IMPOSTONF.VRPERREDBCIT, C_IMPOSTONF.VRBASECALCIT, C_IMPOSTONF.VRALIQITEM, 
                  C_IMPOSTONF.VRPARDEDIT, TRUNC(C_IMPOSTONF.VRIMPOSTOIT,V_NRDECITOTANF), C_IMPOSTONF.CDFISCALIT, C_IMPOSTONF.CDSITUTRIBIT,
                  C_IMPOSTONF.CDFISCOPERIT, C_IMPOSTONF.CDSUFXCFOPIT, C_IMPOSTONF.NRITPROIMPOS, C_IMPOSTONF.VRBCICMSSTRETIDO, 
                  C_IMPOSTONF.VRICMSSTRETIDO, C_IMPOSTONF.IDTRIMPSTII, C_IMPOSTONF.IDDIFALIQCUSPRI, C_IMPOSTONF.VRADICALIQFECP, 
                  C_IMPOSTONF.VRADICFECP);
            ELSE
               INSERT INTO IMPOSTONF(
                  CDFILIAL, NRLANCTONF, CDIMPOSTO, NRIMPOSNF, 
                  VRCONTABILNF, VRPERREDBCNF, VRBASECALCNF, VRALIQNF, 
                  VRPARDEDNF, VRIMPOSTONF, CDFISCALNF, CDSITUTRIBNF,
                  CDFISCOPERNF, CDSUFXCFOPNF, IDIMPOSTONF, VRBCICMSSTRETIDO, 
                  VRICMSSTRETIDO, IDTRIMPOSTNF, IDDIFALIQCUSPRN, VRADICALIQFECP, 
                  VRADICFECP)
               VALUES(
                  P_FILIAL, P_LANCTONF, C_IMPOSTONF.CDIMPOSTO, V_SEQUIMPOSTNF, 
                  ROUND(C_IMPOSTONF.VRCONTITIMP,5), C_IMPOSTONF.VRPERREDBCIT, C_IMPOSTONF.VRBASECALCIT, C_IMPOSTONF.VRALIQITEM, 
                  C_IMPOSTONF.VRPARDEDIT, ROUND(C_IMPOSTONF.VRIMPOSTOIT,V_NRDECITOTANF), C_IMPOSTONF.CDFISCALIT, C_IMPOSTONF.CDSITUTRIBIT,
                  C_IMPOSTONF.CDFISCOPERIT, C_IMPOSTONF.CDSUFXCFOPIT, C_IMPOSTONF.NRITPROIMPOS, C_IMPOSTONF.VRBCICMSSTRETIDO, 
                  C_IMPOSTONF.VRICMSSTRETIDO, C_IMPOSTONF.IDTRIMPSTII, C_IMPOSTONF.IDDIFALIQCUSPRI, C_IMPOSTONF.VRADICALIQFECP, 
                  C_IMPOSTONF.VRADICFECP);
            END IF;

            V_SEQUIMPOSTNF := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_SEQUIMPOSTNF) + 1)),2,0);
         END LOOP;
      ELSE
         FOR C_IMPOSTONF IN (SELECT IT.CDIMPOSTO, 
                                    VRALIQITEM, 
                                    VRPERREDBCIT, 
                                    VRPARDEDIT, 
                                    CDFISCALIT, 
                                    CDSITUTRIBIT,
                                    CDFISCOPERIT, 
                                    CDSUFXCFOPIT, 
                                    IDTRIMPSTII, 
                                    IT.VRADICALIQFECP,
                                    SUM(ROUND(VRCONTITIMP,5)) AS VRCONTITIMP,
                                    SUM(VRBASECALCIT) AS VRBASECALCIT, 
                                    SUM(VRIMPOSTOIT) AS VRIMPOSTOIT,  
                                    NRITPROIMPOS, 
                                    SUM(VRBCICMSSTRETIDO) AS VRBCICMSSTRETIDO, 
                                    SUM(IT.VRADICFECP) AS VRADICFECP,
                                    SUM(VRICMSSTRETIDO) AS VRICMSSTRETIDO
                               FROM ITEMPROIMPOS IT, IMPOSTO I
                              WHERE (CDFILIAL = P_FILIAL)
                                AND (NRLANCTONF = P_LANCTONF) 
                                AND (IT.CDIMPOSTO = I.CDIMPOSTO) 
                                AND (((CDFISCALIT  = w_1) AND (IDIMPORECUP = w_S)) OR ((IDIMPORECUP <> w_S) AND (VRALIQITEM <> 0)))
                              GROUP BY IT.CDIMPOSTO, 
                                    VRALIQITEM, 
                                    VRPERREDBCIT, 
                                    VRPARDEDIT, 
                                    CDFISCALIT,
                                    CDSITUTRIBIT, 
                                    CDFISCOPERIT, 
                                    CDSUFXCFOPIT, 
                                    IDTRIMPSTII, 
                                    IT.VRADICALIQFECP,
                                    NRITPROIMPOS
                              UNION
                             SELECT IT.CDIMPOSTO, 
                                    0 AS VRALIQITEM, 
                                    0 AS VRPERREDBCIT, 
                                    0 AS VRPARDEDIT, 
                                    CDFISCALIT, 
                                    CDSITUTRIBIT,
                                    CDFISCOPERIT, 
                                    CDSUFXCFOPIT, 
                                    IDTRIMPSTII, 
                                    IT.VRADICALIQFECP,
                                    SUM(ROUND(VRCONTITIMP,5)) AS VRCONTITIMP, 
                                    0 AS VRBASECALCIT, 
                                    0 AS VRIMPOSTOIT,
                                    NRITPROIMPOS, 
                                    SUM(VRBCICMSSTRETIDO) AS VRBCICMSSTRETIDO, 
                                    SUM(IT.VRADICFECP) AS VRADICFECP,
                                    SUM(VRICMSSTRETIDO) AS VRICMSSTRETIDO
                               FROM ITEMPROIMPOS IT, IMPOSTO I
                              WHERE (CDFILIAL      = P_FILIAL)
                                AND (NRLANCTONF    = P_LANCTONF)
                                AND (IT.CDIMPOSTO  = I.CDIMPOSTO)
                                AND (((IT.CDFISCALIT <> w_1) AND (IDIMPORECUP = w_S)) OR ((I.IDIMPORECUP  <> w_S) AND (VRALIQITEM = 0)))
                              GROUP BY 
                                    IT.CDIMPOSTO,
                                    CDFISCALIT,
                                    CDSITUTRIBIT,
                                    CDFISCOPERIT, 
                                    CDSUFXCFOPIT, 
                                    IDTRIMPSTII, 
                                    IT.VRADICALIQFECP,
                                    NRITPROIMPOS) 
         LOOP
            V_ICMS := 'N';
            FOR C_ICMS IN (SELECT CDIMPOSTO
                             FROM IMPOSTONFE N, IMPOSTO I
                            WHERE N.CDIMPOSTONFE = I.CDIMPOSTONFE
                              AND N.CDIMPOSTONFE = '00'
                              AND I.CDIMPOSTO = C_IMPOSTONF.CDIMPOSTO)
            LOOP
               V_ICMS := 'S';
            END LOOP;

            IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (V_ICMS = 'S') THEN
               INSERT INTO IMPOSTONF(
                  CDFILIAL, NRLANCTONF, CDIMPOSTO, NRIMPOSNF, 
                  VRCONTABILNF, VRPERREDBCNF, VRBASECALCNF, VRALIQNF, 
                  VRPARDEDNF, VRIMPOSTONF, CDFISCALNF, CDSITUTRIBNF,
                  CDFISCOPERNF, CDSUFXCFOPNF, IDIMPOSTONF, VRBCICMSSTRETIDO, 
                  VRICMSSTRETIDO, IDTRIMPOSTNF, VRADICALIQFECP, VRADICFECP)
               VALUES(
                  P_FILIAL, P_LANCTONF, C_IMPOSTONF.CDIMPOSTO, V_SEQUIMPOSTNF, 
                  C_IMPOSTONF.VRCONTITIMP, C_IMPOSTONF.VRPERREDBCIT, C_IMPOSTONF.VRBASECALCIT, C_IMPOSTONF.VRALIQITEM, 
                  C_IMPOSTONF.VRPARDEDIT, TRUNC(C_IMPOSTONF.VRIMPOSTOIT, V_NRDECITOTANF), C_IMPOSTONF.CDFISCALIT, C_IMPOSTONF.CDSITUTRIBIT,
                  C_IMPOSTONF.CDFISCOPERIT, C_IMPOSTONF.CDSUFXCFOPIT, C_IMPOSTONF.NRITPROIMPOS, C_IMPOSTONF.VRBCICMSSTRETIDO, 
                  C_IMPOSTONF.VRICMSSTRETIDO, C_IMPOSTONF.IDTRIMPSTII, C_IMPOSTONF.VRADICALIQFECP, C_IMPOSTONF.VRADICFECP);
            ELSE
               INSERT INTO IMPOSTONF(
                  CDFILIAL, NRLANCTONF, CDIMPOSTO, NRIMPOSNF, 
                  VRCONTABILNF, VRPERREDBCNF, VRBASECALCNF, VRALIQNF, 
                  VRPARDEDNF, VRIMPOSTONF, CDFISCALNF, CDSITUTRIBNF,
                  CDFISCOPERNF, CDSUFXCFOPNF, IDIMPOSTONF, VRBCICMSSTRETIDO, 
                  VRICMSSTRETIDO, IDTRIMPOSTNF, VRADICALIQFECP, VRADICFECP)
               VALUES(
                  P_FILIAL, P_LANCTONF, C_IMPOSTONF.CDIMPOSTO, V_SEQUIMPOSTNF, 
                  C_IMPOSTONF.VRCONTITIMP, C_IMPOSTONF.VRPERREDBCIT, C_IMPOSTONF.VRBASECALCIT, C_IMPOSTONF.VRALIQITEM, 
                  C_IMPOSTONF.VRPARDEDIT, ROUND(C_IMPOSTONF.VRIMPOSTOIT, V_NRDECITOTANF), C_IMPOSTONF.CDFISCALIT, C_IMPOSTONF.CDSITUTRIBIT,
                  C_IMPOSTONF.CDFISCOPERIT, C_IMPOSTONF.CDSUFXCFOPIT, C_IMPOSTONF.NRITPROIMPOS, C_IMPOSTONF.VRBCICMSSTRETIDO, 
                  C_IMPOSTONF.VRICMSSTRETIDO, C_IMPOSTONF.IDTRIMPSTII, C_IMPOSTONF.VRADICALIQFECP, C_IMPOSTONF.VRADICFECP);
            END IF;
            V_SEQUIMPOSTNF := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_SEQUIMPOSTNF) + 1)),2,0);
         END LOOP;
      END IF;
   END IF;
   
   FOR C_CARGA IN (SELECT DISTINCT CDIMPOSTO
                     FROM IMPOSTONF
                     WHERE CDFILIAL = P_FILIAL
                       AND NRLANCTONF = P_LANCTONF) LOOP

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

      END IF;
   END LOOP;

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


--IDENTIFICADOR DE ERROS E AVISOS
   IF NOT(P_TIPOOPER IN ('09', '10', '12')) THEN /*VALE DE TRANSFERENCIA, SAIDA SEM NOTA, NOTA DE CREDITO/DEBITO*/
      /* (AVISO) ITEM COM CÓDIGO DA SITUAÇÃO TRIBUTÁRIA INVÁLIDO */
      Begin
         SELECT IDERROAVISOFIL
         INTO   V_IDERROAVISO
         FROM ERROAVISONFFIL
         WHERE CDERROAVISOFIL = w_Av09
           AND CDFILIAL = V_CDFILIEMIT;
      Exception
         When No_Data_Found Then
            V_IDERROAVISO := Null;
      End;

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

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

      /* (AVISO) ITEM COM CÓDIGO FISCAL DE OPERAÇÃO INVÁLIDO */
      Begin
         SELECT IDERROAVISOFIL
         INTO   V_IDERROAVISO
         FROM ERROAVISONFFIL
         WHERE CDERROAVISOFIL = w_Av10
           AND CDFILIAL = V_CDFILIEMIT;
      Exception
         When No_Data_Found Then
            V_IDERROAVISO := Null;
      End;

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

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

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

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

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

         /* (AVISO) IMPOSTO DO ITEM COM SITUAÇÃO TRIBUTÁRIA(CST) INVÁLIDA */
         Begin
            SELECT IDERROAVISOFIL
            INTO   V_IDERROAVISO
            FROM ERROAVISONFFIL
            WHERE CDERROAVISOFIL = w_Av05
              AND CDFILIAL = V_CDFILIEMIT;
         Exception
            When No_Data_Found Then
               V_IDERROAVISO := Null;
         End;

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

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

         /* (AVISO) IMPOSTO DO ITEM COM CÓD. FISCAL OPERAÇÃO - CFOP INVÁLIDO */
         Begin
            SELECT IDERROAVISOFIL
            INTO   V_IDERROAVISO
            FROM ERROAVISONFFIL
            WHERE CDERROAVISOFIL = w_Av06
              AND CDFILIAL = V_CDFILIEMIT;
         Exception
            When No_Data_Found Then
               V_IDERROAVISO := Null;
         End;

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

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

      END IF;
   END IF;

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

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

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

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

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

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

   END IF;

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

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

   -- CALCULANDO PESO BRUTO DOS PRODUTOS DA NOTA FISCAL
   BEGIN

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

   EXCEPTION

      WHEN No_Data_Found THEN
         V_VRPESOBRUTO := Null;

   END;

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

      BEGIN

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

      EXCEPTION

         WHEN No_Data_Found THEN
            V_VRPESOBRUTO := Null;

      END;

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

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

         IF (V_VRPESOBRUTO <> 0) THEN

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

         END IF;

      ELSE

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

      END IF;

   END IF;

   -- CALCULANDO PESO LÍQUIDO DOS PRODUTOS DA NOTA FISCAL
   BEGIN

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

   EXCEPTION

      WHEN No_Data_Found THEN
         V_VRLIQUORIG := Null;

   END;

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

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

      IF(V_IDCALCPESONF = 'S') THEN

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

         IF V_VRLIQUORIG IS NOT NULL AND V_VRLIQUORIG <> 0 THEN

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

         END IF;

      END IF;

   END IF;

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

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

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

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

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

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

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

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

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


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

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

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

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

         IF V_VRDIFERENCA <> 0 THEN
            IF (C_ATUAVRCONT.IDTRATIMPO = w_A) THEN
               IF ((C_ATUAVRCONT.IDIMPORECUP = w_S)  AND (C_ATUAVRCONT.CDFISCALIT = w_1)) OR
                  ((C_ATUAVRCONT.IDIMPORECUP <> w_S) AND (C_ATUAVRCONT.CDCCTBLPASS IS NOT NULL)) AND
                  (C_ATUAVRCONT.IDTIPCONTAB = w_D) THEN
                  V_ICMS := 'N';
                  FOR C_ICMS IN (SELECT CDIMPOSTO
                                   FROM IMPOSTONFE N, IMPOSTO I
                                  WHERE N.CDIMPOSTONFE = I.CDIMPOSTONFE
                                    AND N.CDIMPOSTONFE = '00'
                                    AND I.CDIMPOSTO = C_ATUAVRCONT.CDIMPOSTO)
                  LOOP
                     V_ICMS := 'S';
                  END LOOP;

                  IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (V_ICMS = 'S') THEN
                     UPDATE ITEMPRODUTO
                     SET VRBRUTITEM = TRUNC(VRBRUTITEM + ((V_VRDIFERENCA / V_VRBRUTO)  * VRBRUTITEM),2)
                     WHERE EXISTS(SELECT CDFILIAL, NRLANCTONF, NRSEQITPROD
                                  FROM ITEMPROIMPOS T
                                  WHERE T.CDFILIAL    = P_FILIAL                AND
                                        T.NRLANCTONF  = P_LANCTONF              AND
                                        T.NRSEQITPROD = ITEMPRODUTO.NRSEQITPROD AND
                                        T.CDIMPOSTO   = C_ATUAVRCONT.CDIMPOSTO);
                  ELSE
                     UPDATE ITEMPRODUTO
                     SET VRBRUTITEM = ROUND(VRBRUTITEM + ((V_VRDIFERENCA / V_VRBRUTO)  * VRBRUTITEM),5)
                     WHERE EXISTS(SELECT CDFILIAL, NRLANCTONF, NRSEQITPROD
                                  FROM ITEMPROIMPOS T
                                  WHERE T.CDFILIAL    = P_FILIAL                AND
                                        T.NRLANCTONF  = P_LANCTONF              AND
                                        T.NRSEQITPROD = ITEMPRODUTO.NRSEQITPROD AND
                                        T.CDIMPOSTO   = C_ATUAVRCONT.CDIMPOSTO);
                  END IF;
               ELSE
                  V_ICMS := 'N';
                  FOR C_ICMS IN (SELECT CDIMPOSTO
                                   FROM IMPOSTONFE N, IMPOSTO I
                                  WHERE N.CDIMPOSTONFE = I.CDIMPOSTONFE
                                    AND N.CDIMPOSTONFE = '00'
                                    AND I.CDIMPOSTO = C_ATUAVRCONT.CDIMPOSTO)
                  LOOP
                     V_ICMS := 'S';
                  END LOOP;

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

               END IF;
            ELSIF (C_ATUAVRCONT.IDTRATIMPO = w_D) THEN
               IF ((C_ATUAVRCONT.IDIMPORECUP = w_S) AND (C_ATUAVRCONT.CDFISCALIT = w_1))  OR
                  ((C_ATUAVRCONT.IDIMPORECUP <> w_S) AND (C_ATUAVRCONT.CDCCTBLATIV IS NOT NULL)) AND
                  (C_ATUAVRCONT.IDTIPCONTAB = w_D) THEN

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

                  IF ((V_IDSISTEMA = 'VND') OR (V_IDSISTEMA = 'PDV')) AND (V_ICMS = 'S') THEN
                     UPDATE ITEMPRODUTO
                     SET VRBRUTITEM = TRUNC(VRBRUTITEM - ((V_VRDIFERENCA / V_VRBRUTO)  * VRBRUTITEM),2)
                     WHERE EXISTS(SELECT CDFILIAL, NRLANCTONF, NRSEQITPROD
                                  FROM ITEMPROIMPOS T
                                  WHERE T.CDFILIAL    = P_FILIAL                AND
                                        T.NRLANCTONF  = P_LANCTONF              AND
                                        T.NRSEQITPROD = ITEMPRODUTO.NRSEQITPROD AND
                                        T.CDIMPOSTO   = C_ATUAVRCONT.CDIMPOSTO);
                  ELSE
                     UPDATE ITEMPRODUTO
                     SET VRBRUTITEM = ROUND(VRBRUTITEM - ((V_VRDIFERENCA / V_VRBRUTO)  * VRBRUTITEM),5)
                     WHERE EXISTS(SELECT CDFILIAL, NRLANCTONF, NRSEQITPROD
                                  FROM ITEMPROIMPOS T
                                  WHERE T.CDFILIAL    = P_FILIAL                AND
                                        T.NRLANCTONF  = P_LANCTONF              AND
                                        T.NRSEQITPROD = ITEMPRODUTO.NRSEQITPROD AND
                                        T.CDIMPOSTO   = C_ATUAVRCONT.CDIMPOSTO);
                  END IF;
               ELSE
                  V_ICMS := 'N';
                  FOR C_ICMS IN (SELECT CDIMPOSTO
                                   FROM IMPOSTONFE N, IMPOSTO I
                                  WHERE N.CDIMPOSTONFE = I.CDIMPOSTONFE
                                    AND N.CDIMPOSTONFE = '00'
                                    AND I.CDIMPOSTO = C_ATUAVRCONT.CDIMPOSTO)
                  LOOP
                     V_ICMS := 'S';
                  END LOOP;

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

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

               IF (C_ATUAVRCONT.IDTIPCONTAB = w_D) THEN
                  V_ICMS := 'N';
                  FOR C_ICMS IN (SELECT CDIMPOSTO
                                   FROM IMPOSTONFE N, IMPOSTO I
                                  WHERE N.CDIMPOSTONFE = I.CDIMPOSTONFE
                                    AND N.CDIMPOSTONFE = '00'
                                    AND I.CDIMPOSTO = C_ATUAVRCONT.CDIMPOSTO)
                  LOOP
                     V_ICMS := 'S';
                  END LOOP;

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

   BEGIN
      SELECT CDFILIALPED, NRPEDIDO
        INTO V_CDFILIALPED, V_NRPEDIDO
        FROM ITEMPRODUTO
       WHERE CDFILIAL = P_FILIAL
         AND NRLANCTONF = P_LANCTONF
         AND ROWNUM = 1;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_CDFILIALPED := NULL;
         V_NRPEDIDO := NULL;
   END;

   IF (V_CDFILIALPED IS NOT NULL) AND (V_NRPEDIDO IS NOT NULL) THEN
      BEGIN
         SELECT DADOSADICENDPED
           INTO V_DADOSADICENDPED
           FROM (SELECT ('DADO PARA ENTREGA - CLIENTE: '||C.NRINSJURCLIE||' '||C.NMRAZSOCCLIE||
                         ' - ENDEREÇO: '|| D.DSENDEPED||
                         ' - BAIRRO: '||D.NMBAIRROPED||
                         ' - MUNICIPIO: '||D.NMMUNIPED||
                         ' - ESTADO: '||D.SGESTADOPED||
                         ' - CEP: '||NRCEPPED) AS DADOSADICENDPED
                   FROM DADOSENDPED D, CLIENTE C
                  WHERE D.CDCLIENTE = C.CDCLIENTE
                    AND C.IDENDEMISCLI <> D.IDTPENDECLIE
                    AND D.CDFILIAL = V_CDFILIALPED
                    AND NRPEDIDO = V_NRPEDIDO) DEP
          WHERE NOT EXISTS(SELECT DSDADOADIC
                             FROM DADOSADIC                                     
                            WHERE CDFILIAL   = P_FILIAL
                              AND NRLANCTONF = P_LANCTONF
                              AND DSDADOADIC = DEP.DADOSADICENDPED);
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_DADOSADICENDPED := NULL;
      END;

      IF V_DADOSADICENDPED IS NOT NULL THEN
         INSERT INTO DADOSADIC
            (CDFILIAL, NRLANCTONF, NRDADOADIC, DSDADOADIC)
         VALUES
            (P_FILIAL, P_LANCTONF, V_DADOADIC, SUBSTR(V_DADOSADICENDPED, 1, 250));

         V_DADOADIC := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_DADOADIC) + 1)),3,0);
      END IF;
   ELSE
      FOR C_ENDDADOSADIC IN (SELECT DSDADOADIC FROM (
                             SELECT '' AS NRDADOADIC,'999' AS CDMENSAGEM,('DESTINO - FILIAL: '||F.NRINSJURFILI||' '||F.NMFILIAL||' -  ENDEREÇO: '||
                                    E.DSENDEFILI||' - BAIRRO: '||E.NMBAIRFILI||' - MUNICIPIO: '||M.NMMUNICIPIO||' - ESTADO: '||M.SGESTADO) AS DSDADOADIC
                               FROM NOTAFISCAL N INNER JOIN ENDEFILI E ON (CASE WHEN N.IDENTRSAIDOP = 'S' THEN N.CDFILIRECE ELSE N.CDFILIEMIT END) = E.CDFILIAL
                                                 INNER JOIN FILIAL F    ON E.CDFILIAL   = F.CDFILIAL
                                                 INNER JOIN MUNICIPIO M ON E.CDMUNICIPIO = M.CDMUNICIPIO
                                                                       AND E.CDPAIS      = M.CDPAIS
                                                                       AND E.SGESTADO    = M.SGESTADO
                              WHERE N.CDFILIAL     = P_FILIAL
                                AND N.NRLANCTONF   = P_LANCTONF
                                AND N.IDORIGDESTNF = 'L'
                                AND E.IDTPENDEFILI = 'T'
                             UNION ALL
                             SELECT '' AS NRDADOADIC, '999' AS CDMENSAGEM,('DESTINO - CLIENTE: '||C.NRINSJURCLIE||' '||C.NMRAZSOCCLIE||' -  ENDEREÇO: '||
                                    E.DSENDECLIE||' - BAIRRO: '||E.NMBAIRCLIE||' - MUNICIPIO: '||M.NMMUNICIPIO||' - ESTADO: '||M.SGESTADO) AS DSDADOADIC
                               FROM NOTAFISCAL N INNER JOIN ENDECLIE E ON N.CDCLIENTE = E.CDCLIENTE
                                                 INNER JOIN CLIENTE  C ON E.CDCLIENTE = C.CDCLIENTE
                                                 INNER JOIN MUNICIPIO M ON E.CDMUNICIPIO = M.CDMUNICIPIO
                                                                       AND E.CDPAIS      = M.CDPAIS
                                                                       AND E.SGESTADO    = M.SGESTADO
                              WHERE N.CDFILIAL     = P_FILIAL
                                AND N.NRLANCTONF   = P_LANCTONF
                                AND E.IDTPENDECLIE = 'T'
                             UNION ALL
                             SELECT '' AS NRDADOADIC, '999' AS CDMENSAGEM,('DESTINO - FORNECEDOR: '||F.NRINSJURFORN||' '||F.NMRAZSOCFORN||' -  ENDEREÇO: '||
                                    E.DSENDEFORN||' - BAIRRO: '||E.NMBAIRFORN||' - MUNICIPIO: '||M.NMMUNICIPIO||' - ESTADO: '||M.SGESTADO) AS DSDADOADIC
                               FROM NOTAFISCAL N INNER JOIN ENDEFORN E   ON N.CDFORNECED = E.CDFORNECED
                                                 INNER JOIN FORNECEDOR F ON E.CDFORNECED = F.CDFORNECED
                                                 INNER JOIN MUNICIPIO M  ON E.CDMUNICIPIO = M.CDMUNICIPIO
                                                                        AND E.CDPAIS      = M.CDPAIS
                                                                        AND E.SGESTADO    = M.SGESTADO
                              WHERE N.CDFILIAL     = P_FILIAL
                                AND N.NRLANCTONF   = P_LANCTONF
                                AND E.IDTPENDEFORN = 'T'
                             ORDER BY CDMENSAGEM) I
                              WHERE NOT EXISTS(SELECT DSDADOADIC
                                                 FROM DADOSADIC                                     
                                                WHERE (CDFILIAL   = P_FILIAL)
                                                  AND (NRLANCTONF = P_LANCTONF)
                                                  AND (DSDADOADIC = I.DSDADOADIC))) LOOP

          INSERT INTO DADOSADIC(CDFILIAL, NRLANCTONF, NRDADOADIC, DSDADOADIC)
                         VALUES(P_FILIAL, P_LANCTONF, V_DADOADIC, SUBSTR(C_ENDDADOSADIC.DSDADOADIC,1,250));

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

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

   V_STRVRADICALIQFECP := NULL;
   V_STRVRADICFECP := NULL;

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

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

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

      /* INSERIDO POR LUCIANA CORREA PARA O SISTEMA DE PDV */
      IF (V_IDSISTEMA <> w_VMN) THEN

         BEGIN
            SELECT NRCTRLMOVEST, CDFILIALENTR, NRLANESTENTR
              INTO V_NRCTRLMOVEST, V_CDFILIALENTR, V_NRLANESTENTR
              FROM CTRLMOVIESTQ
             WHERE CDFILIALSAID = P_FILIAL
               AND NRLANESTSAID = P_LANCESTQ;
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_CDFILIALENTR := NULL;
               V_NRCTRLMOVEST := NULL;
               V_NRLANESTENTR := NULL;
         END;

         IF V_NRCTRLMOVEST IS NOT NULL THEN
            DELETE 
              FROM CTRLMOVIESTQ
             WHERE CDFILIAL = V_CDFILIEMIT
               AND NRCTRLMOVEST = V_NRCTRLMOVEST;

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

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

         END IF;

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

         IF V_COUNT > 0 THEN

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

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

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

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

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

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

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


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

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

      END IF;

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                  END IF;

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

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

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

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

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

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

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

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

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

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

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

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

            /* Se NF Remessa para Industrialização e Operação Atualiza Estoque */
            IF (V_IDREMESSAINDU = 'S') AND (V_IDATUESTTPOP = 'S') THEN

               IF V_IDORIGDESTNF = 'C' THEN
                  BEGIN
                     SELECT NVL(CDALMOXINFOCLI, ' ') AS CDALMOXINFOCLI, NVL(CDLOCALINFOCLI, ' ') AS CDLOCALINFOCLI
                       INTO V_CDALMOXINFO, V_CDLOCALINFO
                       FROM AGENTETERCECLI
                      WHERE CDFILIAL = V_CDFILIEMIT
                        AND CDCLIENTE = P_CLIENTE;
                  EXCEPTION
                     WHEN NO_DATA_FOUND THEN
                        V_CDALMOXINFO := ' ';
                        V_CDLOCALINFO := ' ';
                  END;
               END IF;
               IF V_IDORIGDESTNF = 'F' THEN
                  BEGIN
                     SELECT NVL(CDALMOXINFOFOR, ' ') AS CDALMOXINFOFOR, NVL(CDLOCALINFOFOR, ' ') AS CDLOCALINFOFOR
                       INTO V_CDALMOXINFO, V_CDLOCALINFO
                       FROM AGENTETERCEFOR
                      WHERE CDFILIAL = V_CDFILIEMIT
                        AND CDFORNECED = P_CLIENTE;
                  EXCEPTION
                     WHEN NO_DATA_FOUND THEN
                        V_CDALMOXINFO := ' ';
                        V_CDLOCALINFO := ' ';
                  END;

                  BEGIN
                     SELECT CDFILIAL
                       INTO V_CDFILIAGENT
                       FROM FILIAL
                      WHERE CDFORNAGETERC = P_CLIENTE;
                  EXCEPTION
                     WHEN NO_DATA_FOUND THEN
                        V_CDFILIAGENT := NULL;
                  END;

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

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

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

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

                  IF V_BOLANESTENTR THEN
                     --GERANDO O REGISTRO NA TABELA LANCTOESTOQ PARA A ENTRADA NO ALMOXAXARIFADO
                     IF (V_NRLANESTENTR IS NULL) OR (V_NRLANESTENTR = '') THEN
                        NOVO_CODIGO_NT('LANCTOEST'||P_FILIAL, V_NRLANESTENTR);
                        V_NRLANESTENTR := SUBSTR(V_NRLANESTENTR, 11, 10);
                     END IF;

                     INSERT INTO LANCTOESTOQ
                        (CDFILIAL,
                         NRLANCESTQ,
                         IDTPLANCTO,
                         DTLANCESTQ,
                         DSLANCESTQ,
                         CDFILIMOVI,
                         CDOPERADOR)
                     VALUES
                        (P_FILIAL,
                         V_NRLANESTENTR,
                         W_2,
                         P_INIVALID,
                         'Transferência de Estoque ' || V_NRLANESTENTR,
                         V_CDFILIEMIT,
                         P_CDOPERADOR);

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

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

                     V_BOLANESTENTR := FALSE;
                  END IF;

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

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

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

                           IF (V_TPOPERRETORNO IS NULL) THEN
                              RAISE_APPLICATION_ERROR(-20501, 'Tipo de operação para geração de lançamento de estoque deve ser informado - (Parâmetros para Documentos Fiscais de Saída - Operador Logístico)', TRUE);
                           END IF;

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

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

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

                           V_BOLANESTENTRAG := FALSE;
                        END IF;

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

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

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

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

               V_DADOADIC := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_DADOADIC) + 1)),3,0);
            ELSE
               UPDATE DADOSADIC
                  SET DSDADOADIC = 'Permite o aproveitamento do credito do ICMS no valor de R$ '||DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(V_APROVICMS, 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(V_APROVICMS, 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(V_APROVICMS, 2), '9999999999999.99')))|| ' corresp. a alíquota de '|| DECODE(SUBSTR(LTRIM(TO_CHAR(ROUND(V_ALIQAPROVICMS, 2), '9999999999999.99')), 1, 1), '.', '0'||LTRIM(TO_CHAR(ROUND(V_ALIQAPROVICMS, 2), '9999999999999.99')), LTRIM(TO_CHAR(ROUND(V_ALIQAPROVICMS, 2), '9999999999999.99'))) || '% conf. Art.23 da LC 123/06.'
                 WHERE CDFILIAL = P_FILIAL
                   AND NRLANCTONF = P_LANCTONF
                   AND DSDADOADIC LIKE 'Permite o aproveitamento do credito do ICMS no valor de R$ %';
            END IF;
         END IF;
      END IF;
   END IF;
END;
/

CREATE OR REPLACE FUNCTION SPED_BLOCOC(
   P_CDIMPOSTO    IN IMPOSTO.CDIMPOSTO%TYPE,
   P_CDEMPRESA    IN EMPRESA.CDEMPRESA%TYPE,
   P_CDINSCESTA   IN EMPRESA.CDINSCESTA%TYPE,
   P_DTINICIAL    IN NOTAFISCAL.DTENTRSAID%TYPE,
   P_DTFINAL      IN NOTAFISCAL.DTENTRSAID%TYPE,
   P_LIVROMAG     IN NOTAFISCAL.NRLANCTONF%TYPE,
   P_NRSEQARQMAG  IN ARQMAGNETICO.NRSEQARQMAG%TYPE,
   P_PERFIL       IN NOTAFISCAL.IDSTATUS%TYPE,
   P_VERSAO       IN VARCHAR2,
   P_IDDIFALIQ    IN VARCHAR2,
   P_TOTALIZA     IN NUMBER,
   P_GERAFORSALE  IN VARCHAR2 DEFAULT 'N') RETURN VARCHAR  
AS
   V_CONTREGC        NUMBER;
   V_SEQADIC         NUMBER;
   V_MOVIMENT        NUMBER;
   V_TOTFORPER_S     NUMBER;
   V_TOTFORPER_E     NUMBER;
   V_VRFORAPER       NUMBER;
   V_VRFORAPER_E     NUMBER;
   V_SEQUPROD        NUMBER;
   V_SEQUENCIAL      VARCHAR2(100);
   V_IDFRETE         VARCHAR2(01);
   V_IDSEGUR         VARCHAR2(01);
   V_IDOUTROS        VARCHAR2(01);
   V_IDDESCONTO      VARCHAR2(01);
   V_PIS             VARCHAR2(02);
   V_COFINS          VARCHAR2(02);
   V_IPI             VARCHAR2(02);
   V_CDIMPOSTRIB     VARCHAR2(02);
   V_DTPERIODO       VARCHAR2(01);
   V_DADOS_2         VARCHAR2(10);
   V_IDSTATUS        VARCHAR2(01);
   V_ICMS            VARCHAR2(02);
   TIPOOPER_COMPL_S  VARCHAR(02);
   TIPOOPER_COMPL_E  VARCHAR(02);
   V_DTEMISSAO       DATE;
   V_DTENTRSAID      DATE;
   V_NRSEQUMAPAPU    VARCHAR2(10);
   V_COD_NAT         VARCHAR2(100);
   V_COD_PAR         VARCHAR2(100);
   V_UNID            VARCHAR2(100);
   V_PRODUTO         VARCHAR2(100);
   V_VRDEBESP        NUMBER;
   V_LINHA           VARCHAR2(255);
   V_NR_TOT          VARCHAR2(02);
   V_DESCR_NR_TOT    VARCHAR2(255);
   V_REG_C197        VARCHAR2(1000);
   V_COD_OBS         VARCHAR2(1000);
   V_SGESTADO        VARCHAR2(02);
   V_CDAJUSTEC195    VARCHAR2(10);
   V_IDGERREGC197    VARCHAR2(10);
   V_CDSITUCRT       VARCHAR2(01);
   V_VENDABRUTA      FLOAT;
   V_VENDACANC       FLOAT;
   V_IDDIFEALIQUOTA  VARCHAR2(02);
   V_CFOPC195        VARCHAR2(01);
   V_IDANTICMSARROZ  VARCHAR2(01);
   V_CDTPOPANTARROZ  VARCHAR2(03);
   V_CDAJUSTEXTEMP   VARCHAR2(10);
   V_IDTPCARGATRIB   VARCHAR2(01);
   V_CODC195         VARCHAR2(06);
   V_TXTC195         VARCHAR2(500);
   V_CDFORNECED      VARCHAR2(20);
   V_GERAC113        VARCHAR2(01);
   V_C195            VARCHAR2(06);
   V_NRSEQITEM       NUMBER;
   V_IDATUESTTPOP    VARCHAR2(01);
   V_CONTCTBL        VARCHAR2(100);
   V_UNIDADE         VARCHAR2(100);
BEGIN
   V_SEQUPROD := NVL(P_TOTALIZA,0);

   /*Busca o tipo de operação de complemento */
   BEGIN
      SELECT MAX(TIPOOPER_S), MAX(TIPOOPER_E)
        INTO TIPOOPER_COMPL_S, TIPOOPER_COMPL_E
        FROM (SELECT DECODE(IDENTRSAIDOP,'S',CDTIPOOPER,NULL) AS TIPOOPER_S,
                     DECODE(IDENTRSAIDOP,'E',CDTIPOOPER,NULL) AS TIPOOPER_E
                FROM TIPOOPERAC
               WHERE UPPER(NMTIPOOPER) LIKE '%NF COMPLEMENTO%'
                 AND CDTIPOOPER <> '03');
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         TIPOOPER_COMPL_S := NULL;
         TIPOOPER_COMPL_E := NULL;
   END;

   BEGIN
      SELECT MAX(EN.IDENCARGO)
        INTO V_IDFRETE
        FROM ENCARGO EN
       WHERE EN.CDENCARGONFE = '01';
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
           V_IDFRETE     := NULL;
   END;

   BEGIN
      SELECT MAX(EN.IDENCARGO)
        INTO V_IDSEGUR
        FROM ENCARGO EN
       WHERE EN.CDENCARGONFE = '02';
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
           V_IDSEGUR     := NULL;
   END;

   BEGIN
      SELECT MAX(EN.IDENCARGO)
        INTO V_IDDESCONTO
        FROM ENCARGO EN
       WHERE EN.CDENCARGONFE = '03';
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
           V_IDDESCONTO  := NULL;
   END;

   BEGIN
      SELECT MAX(EN.IDENCARGO)
        INTO V_IDOUTROS
        FROM ENCARGO EN
       WHERE EN.CDENCARGONFE = '04';
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
           V_IDOUTROS    := NULL;
   END;

   V_IPI         := '10';
   V_PIS         := '50';
   V_COFINS      := '60';
   V_CDIMPOSTRIB := '80';

   /*VERIFICA SE A EMPRESA É DO SIMPLES NACIONAL, '3' NAO É DO SIMPLES, APENAS 1 E 2*/
   SELECT NVL(MAX(CDSITUCRT), '3') CDSITUCRT
     INTO V_CDSITUCRT
     FROM PARAMEMPRESA
    WHERE CDEMPRESA = P_CDEMPRESA;

   IF V_CDSITUCRT = '3' THEN
      BEGIN
         SELECT NRSEQUMAPAPU
           INTO V_NRSEQUMAPAPU
           FROM MAPAAPURAC M
          WHERE M.CDEMPRESA    = P_CDEMPRESA
            AND M.CDINSCESTA   = P_CDINSCESTA
            AND M.CDIMPOSTO    = P_CDIMPOSTO
            AND M.DTINIPERIODO = P_DTINICIAL
            AND M.DTFIMPERIODO = P_DTFINAL;
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_NRSEQUMAPAPU := NULL;
      END;
   END IF;

   IF V_CDSITUCRT <> '3' THEN
      BEGIN
         SELECT NRSEQUMAPAPU
           INTO V_NRSEQUMAPAPU
           FROM MAPAAPURACSN M
          WHERE M.CDEMPRESA    = P_CDEMPRESA
            AND M.DTINIPERIODO = P_DTINICIAL
            AND M.DTFIMPERIODO = P_DTFINAL;
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_NRSEQUMAPAPU := NULL;
      END;
   END IF;

   /*ESTADO DA IE*/
   SELECT MAX(SGESTADO)
     INTO V_SGESTADO
     FROM INSCRESTAD
    WHERE CDEMPRESA  = P_CDEMPRESA
      AND CDINSCESTA = P_CDINSCESTA;

   V_IDTPCARGATRIB := 'N';

   /*VERIFICA SE EXISTE CARGA TRIBUTÁRIA GERADA COMO OUTROS DÉBITOS/CRÉDITOS,
     CASO CONTRÁRIO CONSIDERA COMO SE FOSSE DÉBITO/CRÉDITO NORMAL*/
   BEGIN
      SELECT MAX('O') AS IDTPCARGATRIB
        INTO V_IDTPCARGATRIB
        FROM ITMAPARECUP
       WHERE NRSEQUMAPAPU = V_NRSEQUMAPAPU
         AND IDTIPOITMAPR IN ('OC','OD')
         AND IDCARGATRIBUTARIA = 'S';
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_IDTPCARGATRIB := 'N';
   END;

   V_SEQADIC := 000001; --Código da informação complementar, registro C110.

   IF V_CDSITUCRT = '3' THEN
      FOR C_REGC100 IN(SELECT ('|C100'                                                             || '|' ||
                              NF.CAMPO2                                                            || '|' ||
                              (CASE WHEN ((NF.CDSERIEENTR BETWEEN '890' AND '899') AND (NF.CDMODDOCFISC = '55')) THEN '1' ELSE NF.CAMPO3 END) || '|' ||
                              DECODE(NF.IDSTATUSNFE,'D','',DECODE(NF.IDSTATUS,'C','',REPLACE(REPLACE(REPLACE(REPLACE(NF.IDORIGDESTNF||DECODE(NF.IDORIGDESTNF, 'F', NF.CDFORNECED, DECODE(NF.IDORIGDESTNF, 'C', NF.CDCLIENTE , DECODE(NF.IDENTRSAIDOP, 'E', NF.CDFILIEMIT, NF.CDFILIRECE))),'.'),'-'),'/'),' '))) || '|' ||
                              NF.CDMODDOCFISC                                                      || '|' ||
                              DECODE(NF.IDSTATUSNFE, 'D', '04', DECODE(NF.IDSTATUSNFE, 'I', '05',DECODE(IDSTATUS,'C','02', DECODE(NF.IDENTRSAIDOP,'S', (CASE WHEN DTEMISSAO < P_DTINICIAL THEN DECODE(NF.CDTIPOOPER,'03','07',TIPOOPER_COMPL_S,'07','01') ELSE DECODE(NF.CDTIPOOPER,'03','06',TIPOOPER_COMPL_S,'06','00') END),(CASE WHEN ((NF.CDSERIEENTR BETWEEN '890' AND '899') AND (NF.CDMODDOCFISC = '55')) THEN '08'ELSE (CASE WHEN DTENTRSAID < P_DTINICIAL THEN DECODE(NF.CDTIPOOPER,'03','07',TIPOOPER_COMPL_E,'07','01')ELSE DECODE(NF.CDTIPOOPER,'03','06',TIPOOPER_COMPL_E,'06','00') END) END))))) ||'|'||
                              CASE WHEN LENGTH(NF.NRACESSONFE) = '44' THEN SUBSTR(NRACESSONFE,23,3) ELSE REPLACE(REPLACE(DECODE(NF.IDENTRSAIDOP, 'E', NF.CDSERIEENTR, NF.CDSERIE),'-',''),'.','') END  || '|' ||
                              DECODE(NF.IDENTRSAIDOP,'E',LTRIM(NF.NRNOTAFISC,'0'), DECODE(NF.NRACESSONFE, '', LTRIM(REPLACE(LTRIM(NF.NRNOTAFISC, '0'),' ')),DECODE(NF.IDSTATUS,'C',LTRIM(NF.NRNOTAFISC,'0'),LTRIM(NF.NRNOTAFISCALELE, '0')) )  )|| '|' ||
                              DECODE(NF.CDMODDOCFISC,'04','',NRACESSONFE)                               || '|' ||  --chave da nota fiscal eletronica
                              DECODE(NF.IDSTATUSNFE, 'D', '', DECODE(NF.IDSTATUS, 'C', '', DECODE(NF.IDSTATUSNFE,'I','',TO_CHAR(NF.DTEMISSAO,'ddmmyyyy'))) )      || '|' ) AS DADOS_1,
                              (REPLACE(LTRIM(TO_CHAR(ROUND(NF.VRCONTABILNF,2), '999999999990.00')), '.', ',') || '|' ||
                              DECODE(NF.IDSTATUSNFE, 'D', '', DECODE(NF.IDSTATUS, 'C', '', DECODE(NF.IDSTATUSNFE,'I','',DECODE(NVL(NF.QTDEPARC,0),0,'2',1,'0','1'))))    || '|' || -- campo 13
                              DECODE(NF.IDSTATUSNFE, 'D', '', DECODE(NF.IDSTATUS, 'C', '', DECODE(NF.IDSTATUSNFE,'I','',REPLACE(LTRIM(TO_CHAR((SELECT SUM(ROUND(NVL(VRENCARGODESC,0),2)) FROM ITEMPRODUTO WHERE CDFILIAL = NF.CDFILIAL AND NRLANCTONF = NF.NRLANCTONF AND NRSEQITPROD IS NOT NULL), '999999999990.00')), '.', ',')))) || '|' ||
                              REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(NF.IDSTATUSNFE, 'D', '', DECODE(NF.IDSTATUS, 'C', '', DECODE(NF.IDSTATUSNFE,'I','', NVL(NF.VRIMPDESONERADO,0)))),2), '999999999990.00')), '.', ',') || '|' ||  -- abatimento no tributado e nao comercial desconto ICMS
                              DECODE(NF.IDSTATUSNFE, 'D', '', DECODE(NF.IDSTATUS, 'C', '', DECODE(NF.IDSTATUSNFE,'I','',REPLACE(LTRIM(TO_CHAR(ROUND(NF.VRPRODUTOS,2)+NVL((SELECT SUM(ROUND(NVL(VRDESCITEM,0),2) + ROUND(NVL(VRENCARGOIMPXML,0),2)) FROM ITEMPRODUTO WHERE CDFILIAL = NF.CDFILIAL AND NRLANCTONF = NF.NRLANCTONF AND NRSEQITPROD IS NOT NULL),0), '999999999990.00')), '.', ',')))) || '|' ||
                              DECODE(NF.IDSTATUSNFE, 'D', '', DECODE(NF.IDSTATUS, 'C', '', DECODE(NF.IDSTATUSNFE,'I','',RPAD(NVL(NF.IDPGTOFRETE, '9'), 1, ' '))))                                       || '|' ||
                              REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(NF.IDSTATUSNFE, 'D', '', DECODE(NF.IDSTATUS, 'C', '', DECODE(NF.IDSTATUSNFE,'I','',VALOR_ENCARGO_NFE(NF.CDFILIAL, NF.NRLANCTONF, V_IDFRETE,  '01')))),2), '999999999990.00')), '.', ',') || '|' ||
                              REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(NF.IDSTATUSNFE, 'D', '', DECODE(NF.IDSTATUS, 'C', '', DECODE(NF.IDSTATUSNFE,'I','',VALOR_ENCARGO_NFE(NF.CDFILIAL, NF.NRLANCTONF, V_IDSEGUR,  '02')))),2), '999999999990.00')), '.', ',') || '|' ||
                              /*REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(NF.IDSTATUS, 'C', '', ABS(VALOR_IMPOSTO_NF(NF.CDFILIAL, NF.NRLANCTONF,V_CDIMPOSTRIB, 'I','1')) + ABS(VALOR_IMPOSTO_NF(NF.CDFILIAL, NF.NRLANCTONF, V_IPI, 'I','1'))),2), '999999999990.00')), '.', ',')  || '|' || --campo20*/
                              /*REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(NF.IDSTATUSNFE, 'D', '', DECODE(NF.IDSTATUS, 'C', '', DECODE(NF.IDSTATUSNFE,'I','',VALOR_ENCARGO_NFE(NF.CDFILIAL, NF.NRLANCTONF, V_IDOUTROS, '04')))),2), '999999999990.00')), '.', ',') || '|' || -- Campo 20*/
                              DECODE(NF.IDSTATUSNFE, 'D', '', DECODE(NF.IDSTATUS, 'C', '', DECODE(NF.IDSTATUSNFE,'I','',REPLACE(LTRIM(TO_CHAR(ROUND((SELECT NVL(SUM(I.VRITEMENCA),0)
                                                                                                                                                       FROM ITEMENCARGO I, ENCARGO E
                                                                                                                                                      WHERE I.CDFILIAL     = NF.CDFILIAL
                                                                                                                                                        AND I.NRLANCTONF   = NF.NRLANCTONF
                                                                                                                                                        AND E.CDENCARGO    = I.CDENCARGO
                                                                                                                                                        AND E.IDENCARGO    = 'A'
                                                                                                                                                        AND E.CDENCARGONFE = '04'
                                                                                                                                                        AND I.CDENCARGO NOT IN (SELECT CDENCARGOIMPXML
                                                                                                                                                                                  FROM IMPOSTO I
                                                                                                                                                                                 WHERE CDIMPOSTONFE IN ('80','10'))),2), '999999999990.00')), '.', ',')))) || '|' || -- Campo 20 outras obrigações acessórias
                              REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(NF.IDSTATUSNFE, 'D', '', DECODE(NF.IDSTATUS, 'C', '', DECODE(NF.IDSTATUSNFE,'I','',NF.VRBASECALCNF))),2), '999999999990.00')), '.', ',') || '|' || -- campo 21
                              REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(NF.IDSTATUSNFE, 'D', '', DECODE(NF.IDSTATUS, 'C', '', DECODE(NF.IDSTATUSNFE,'I','',NF.VRIMPOSTONF))),2), '999999999990.00')), '.', ',') || '|' || -- campo 22
                              REPLACE(LTRIM(TO_CHAR(DECODE(NF.IDSTATUSNFE, 'D', '', DECODE(NF.IDSTATUS,'C','', DECODE(NF.IDSTATUSNFE,'I','',VALOR_IMPOSTO_NFE(NF.CDFILIAL, NF.NRLANCTONF,'80','B','1')))), '999999999990.00')), '.', ',') || '|' || -- base de calc susbt. trib
                              REPLACE(LTRIM(TO_CHAR(DECODE(NF.IDSTATUSNFE, 'D', '', DECODE(NF.IDSTATUS,'C','', DECODE(NF.IDSTATUSNFE,'I','',VALOR_IMPOSTO_NFE(NF.CDFILIAL, NF.NRLANCTONF,'80','I','1') + VALOR_FECP_NFE(NF.CDFILIAL, NF.NRLANCTONF,'80','I','1')))), '999999999990.00')), '.', ',') || '|' || -- valor do icms retido susbt. trib
                              REPLACE(LTRIM(TO_CHAR(DECODE(NF.IDSTATUSNFE, 'D', '', DECODE(NF.IDSTATUS,'C','', DECODE(NF.IDSTATUSNFE,'I','',VALOR_IMPOSTO_NFE(NF.CDFILIAL, NF.NRLANCTONF,'10','I','1')))), '999999999990.00')), '.', ',') || '|' || -- valor do IPI
                              REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(NF.IDSTATUSNFE, 'D', '', DECODE(NF.IDSTATUS, 'C', '', DECODE(NF.IDSTATUSNFE,'I','',VALOR_IMPOSTO_NFE(NF.CDFILIAL, NF.NRLANCTONF, '50', 'I','1')))),2), '999999999990.00')), '.', ',') || '|' || -- valor do PIS
                              REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(NF.IDSTATUSNFE, 'D', '', DECODE(NF.IDSTATUS, 'C', '', DECODE(NF.IDSTATUSNFE,'I','',VALOR_IMPOSTO_NFE(NF.CDFILIAL, NF.NRLANCTONF, '60', 'I','1')))),2), '999999999990.00')), '.', ',') || '|' || -- valor do COFINS
                              DECODE(NF.IDSTATUSNFE, 'D', '', DECODE(NF.IDSTATUS, 'C', '', DECODE(NF.IDSTATUSNFE,'I','','0,00'))) || '|' || -- pis retido por subst. trib.
                              DECODE(NF.IDSTATUSNFE, 'D', '', DECODE(NF.IDSTATUS, 'C', '', DECODE(NF.IDSTATUSNFE,'I','','0,00'))) || '|'  ) AS DADOS_3,
                              NF.CDFILIAL AS CDFILIAL, NF.NRLANCTONF AS NRLANCTONF, '' AS CDCAIXA, NF.NRINSJURTRAN, NF.IDTPIJURTRAN, NF.VRPBRUTOVOLU, NF.VRPLIQUVOLU,
                              NF.NRPLACAVEIC, NF.DSQTDEVOLU, NF.DSESPECVOLU, NF.DSMARCAVOLU, NF.DSNUMEVOLU, NF.CDFISCOPERNF, NF.NRNOTAFISC AS NRNOTAFISC,
                              NF.DTEMISSAO, NF.DTENTRSAID, NF.IDENTRSAIDOP, NF.VRIMPOSTONF, NF.CDMODDOCFISC, NF.IDSTATUS, NF.IDORIGDESTNF,
                              NF.IDORIGDESTNF||DECODE(NF.IDORIGDESTNF, 'F', NF.CDFORNECED, DECODE(NF.IDORIGDESTNF, 'C', NF.CDCLIENTE , DECODE(NF.IDENTRSAIDOP, 'E', NF.CDFILIEMIT, NF.CDFILIRECE))) AS COD_PAR,
                              DECODE(NF.IDSTATUSNFE, 'D', '04', DECODE(NF.IDSTATUSNFE, 'I', '05',DECODE(IDSTATUS,'C','02', DECODE(NF.IDENTRSAIDOP,'S', (CASE WHEN DTEMISSAO < P_DTINICIAL THEN DECODE(NF.CDTIPOOPER,'03','07',TIPOOPER_COMPL_S,'07','01') ELSE DECODE(NF.CDTIPOOPER,'03','06',TIPOOPER_COMPL_S,'06','00') END),(CASE WHEN ((NF.CDSERIEENTR BETWEEN '890' AND '899') AND (NF.CDMODDOCFISC = '55')) THEN '08'ELSE (CASE WHEN DTENTRSAID < P_DTINICIAL THEN DECODE(NF.CDTIPOOPER,'03','07',TIPOOPER_COMPL_E,'07','01')ELSE DECODE(NF.CDTIPOOPER,'03','06',TIPOOPER_COMPL_E,'06','00') END) END))))) AS SITU_DOC,
                              NF.IDSTATUSNFE, NVL(NF.IDSIMPLESNACIONAL,'N') AS IDSIMPLESNACIONAL, NF.QTDEPARC, NF.CDTIPOOPER, DECODE(NF.IDENTRSAIDOP,'S',NF.CDFILIEMIT,NF.CDFILIRECE) AS FILIAL
                         FROM (/*NF DE SAÍDA COM E SEM CARGA TRIBUTÁRIA*/
                               SELECT N.CAMPO2, N.CAMPO3, N.NRACESSONFE, N.CDFILIAL, N.NRLANCTONF, N.IDENTRSAIDOP, N.NRNOTAFISC, N.CDSERIE, N.CDSERIEENTR,
                                      N.NRINSJURNF, N.IDSTATUS, N.DTENTRSAID, N.VRNOTAFISC, N.VRPRODUTOS, N.IDPGTOFRETE,
                                      N.NRPLACAVEIC, N.DSQTDEVOLU, N.DSESPECVOLU, N.DSMARCAVOLU, N.DSNUMEVOLU,
                                      N.CDFILIEMIT, N.CDFILIRECE, N.DTEMISSAO, N.CDFISCOPERNF, N.CDMODDOCFISC, N.CDCLIENTE, N.CDFORNECED, N.IDORIGDESTNF,
                                      N.VRCONTABILNF, N.NRINSJURTRAN, N.IDTPIJURTRAN, N.VRPBRUTOVOLU, N.VRPLIQUVOLU,
                                      TO_CHAR(NVL(VALOR_IMPOSTO_NFE_CARGA(N.CDFILIAL, N.NRLANCTONF, 'B', 'I', '1'),0) - NVL(N.VRBASEC197,0) +
                                              NVL(DECODE(V_IDTPCARGATRIB,'O',0,DECODE(V_SGESTADO,'SP',0,VALOR_IMPOSTO_NFE_CARGA(N.CDFILIAL,N.NRLANCTONF,'B','C','1'))),0)) AS VRBASECALCNF,
                                      TO_CHAR(NVL(VALOR_IMPOSTO_NFE_CARGA(N.CDFILIAL, N.NRLANCTONF, 'I', 'I', '1'),0) - NVL(N.VRIMPOSTOC197,0) +
                                              NVL(DECODE(V_IDTPCARGATRIB,'O',0,VALOR_IMPOSTO_NFE_CARGA(N.CDFILIAL,N.NRLANCTONF,'I','C','1')),0)) AS VRIMPOSTONF,
                                      N.VROUTRCRED, N.VRISENTRIB, N.NRNOTAFISCALELE, N.CDTIPOOPER, N.IDSTATUSNFE, N.IDSIMPLESNACIONAL, N.QTDEPARC,
                                      (SELECT NVL(SUM(I.VRIMPOSTOIT),0) FROM ITEMPROIMPOS I, IMPOSTO IM WHERE I.IDIMPDESONERAIT = 'S' AND I.CDFILIAL = N.CDFILIAL AND I.NRLANCTONF = N.NRLANCTONF AND I.CDIMPOSTO = IM.CDIMPOSTO AND IM.CDIMPOSTONFE = P_CDIMPOSTO) VRIMPDESONERADO
                                FROM (SELECT DECODE(N.IDENTRSAIDOP, 'E', '0','1') AS CAMPO2,
                                             DECODE(N.IDENTRSAIDOP, 'E', DECODE(IDSTATUSNFE,'A','0',DECODE(IDSTATUS,'E','0','1')), '0') AS CAMPO3, NRACESSONFE,
                                             I.CDFILIAL, I.NRLANCTONF, N.IDENTRSAIDOP, N.NRNOTAFISC, NVL(SS.CDSERIENFE,N.CDSERIE) AS CDSERIE, NVL(SE.CDSERIEENTRNFE,N.CDSERIEENTR) AS CDSERIEENTR,
                                             N.NRINSJURNF, N.IDSTATUS, N.DTENTRSAID, N.VRNOTAFISC, TO_CHAR(N.VRPRODUTOS) AS VRPRODUTOS, N.IDPGTOFRETE,
                                             N.NRPLACAVEIC, N.DSQTDEVOLU, N.DSESPECVOLU, N.DSMARCAVOLU, N.DSNUMEVOLU,
                                             N.CDFILIEMIT, N.CDFILIRECE, N.DTEMISSAO, MAX(I.CDFISCOPERNF) AS CDFISCOPERNF, N.CDMODDOCFISC, N.CDCLIENTE, N.CDFORNECED, N.IDORIGDESTNF,
                                             TO_CHAR(SUM(I.VRCONTABILNF)) AS VRCONTABILNF, N.NRINSJURTRAN, N.IDTPIJURTRAN, N.VRPBRUTOVOLU, N.VRPLIQUVOLU,
                                             NVL(C_197.VRBASEC197,0) AS VRBASEC197, NVL(C_197.VRIMPOSTOC197,0) AS VRIMPOSTOC197,
                                             TO_CHAR(SUM(DECODE(I.CDFISCALNF,'3',I.VRCONTABILNF,0)))   AS VROUTRCRED,
                                             TO_CHAR(SUM(DECODE(I.CDFISCALNF,'2',I.VRCONTABILNF,'1',DECODE(I.VRPERREDBCNF,0, 0,I.VRCONTABILNF-I.VRBASECALCNF), 0))) AS VRISENTRIB,
                                             N.NRNOTAFISCALELE, N.CDTIPOOPER, N.IDSTATUSNFE,  DECODE(N.IDORIGDESTNF,'F',PF.IDSIMPLESNACIONAL,'N') AS IDSIMPLESNACIONAL,
                                             MAX((SELECT COUNT(DISTINCT NRPARCELAREC)
                                                    FROM CONTARECEBER C
                                                   WHERE N.CDFILIAL    = C.CDFILIAL
                                                     AND N.NRLANCTONF  = C.NRLANCTONF
                                                     AND C.NRLANBOLREC IS NOT NULL)) AS QTDEPARC
                                        FROM NOTAFISCAL N, IMPOSTONF I, IMPOSTO IP, PARAMFORNE PF, SERIENF SS, SERIEENTR SE,
                                             (SELECT NVL(SUM(IT.VRBASECALCIT),0) AS VRBASEC197,
                                                     NVL(SUM(ROUND(IT.VRIMPOSTOIT,2)),0)  AS VRIMPOSTOC197,
                                                     DT.CDFILIAL, DT.NRLANCTONF
                                                FROM ITEMPROIMPOS IT, IMPOSTO IM, DETITMAPARECUP DT
                                               WHERE IT.CDFILIAL     = DT.CDFILIAL
                                                 AND IT.NRLANCTONF   = DT.NRLANCTONF
                                                 AND IT.NRSEQITPROD  = DT.NRSEQITPROD
                                                 AND IT.CDIMPOSTO    = DT.CDIMPOSTO
                                                 AND IT.NRITPROIMPOS = DT.NRITPROIMPOS
                                                 AND IT.NRITPROIMPOS = '1'
                                                 AND IT.CDFISCALIT   = '1'
                                                 AND IT.CDIMPOSTO    = IM.CDIMPOSTO
                                                 AND IM.CDIMPOSTONFE = '00'
                                                 AND DT.IDTIPOITMAPR <> 'VI'
                                               GROUP BY DT.CDFILIAL, DT.NRLANCTONF) C_197
                                       WHERE I.NRSEQUMAPAPU    = V_NRSEQUMAPAPU
                                         AND IP.CDIMPOSTONFE   = P_CDIMPOSTO
                                         AND IP.CDIMPOSTO      = I.CDIMPOSTO
                                         AND (NVL(N.IDSISTEMA,'DFS') <> 'REC'
                                         AND NVL(N.IDSISTEMA, 'DFS') <> 'PAG'
                                         AND NVL(N.IDSISTEMA, 'DFS') <> 'CMP'
                                         AND NVL(N.IDSISTEMA, 'DFS') <> 'SUP'
                                         AND NVL(N.IDSISTEMA, 'DFS') <> 'TMP'
                                         AND NVL(N.IDSISTEMA, 'DFS') <> 'FIS')
                                         AND N.IDENTRSAIDOP    = 'S'
                                         AND NVL(I.IDIMPOSTONF, '1') <> '3'
                                         AND N.CDFILIAL        = I.CDFILIAL
                                         AND SE.CDSERIEENTR(+) = N.CDSERIEENTR
                                         AND SS.CDEMPRESA(+)   = N.CDEMPRESA
                                         AND SS.CDINSCESTA(+)  = N.CDINSCESTA
                                         AND SS.CDINSCMUNI(+)  = N.CDINSCMUNI
                                         AND SS.CDSERIE(+)     = N.CDSERIE
                                         AND N.NRLANCTONF      = I.NRLANCTONF
                                         AND N.CDFORNECED      = PF.CDFORNECED(+)
                                         AND ((N.IDSTATUS = 'A') OR (N.IDSTATUS = 'E'))
                                         AND N.CDMODDOCFISC IN ('01','1B','04','55')
                                         AND NVL(P_GERAFORSALE,'N') = 'N'
                                         AND N.CDFILIAL        = C_197.CDFILIAL(+)
                                         AND N.NRLANCTONF      = C_197.NRLANCTONF(+)
                                       GROUP BY DECODE(N.IDENTRSAIDOP, 'E', '0','1'), I.CDFILIAL, I.NRLANCTONF, N.IDENTRSAIDOP, N.NRNOTAFISC, NVL(SS.CDSERIENFE,N.CDSERIE),
                                                      NVL(SE.CDSERIEENTRNFE,N.CDSERIEENTR), N.NRINSJURNF, N.IDSTATUS, N.DTENTRSAID, N.VRNOTAFISC, TO_CHAR(N.VRPRODUTOS), N.IDPGTOFRETE,
                                                      N.DTEMISSAO, N.CDMODDOCFISC, N.CDCLIENTE, N.CDFORNECED, N.IDORIGDESTNF,
                                                      N.CDFILIEMIT, N.CDFILIRECE, N.NRINSJURTRAN, N.IDTPIJURTRAN, N.VRPBRUTOVOLU, N.VRPLIQUVOLU,
                                                      N.NRPLACAVEIC, N.DSQTDEVOLU, N.DSESPECVOLU, N.DSMARCAVOLU, N.DSNUMEVOLU, NRACESSONFE, N.NRNOTAFISCALELE, N.CDTIPOOPER, N.IDSTATUSNFE,
                                                      DECODE(N.IDORIGDESTNF,'F',PF.IDSIMPLESNACIONAL,'N'), NVL(C_197.VRBASEC197,0), NVL(C_197.VRIMPOSTOC197,0))N
                                UNION ALL
                               /******** NOTA CANCELADA *******/
                               SELECT DECODE(N.IDENTRSAIDOP, 'E', '0','1') AS CAMPO2,
                                      '0' AS CAMPO3, NRACESSONFE,
                                      N.CDFILIAL, N.NRLANCTONF, N.IDENTRSAIDOP, N.NRNOTAFISC, NVL(SS.CDSERIENFE,N.CDSERIE) AS CDSERIE, NVL(SE.CDSERIEENTRNFE,N.CDSERIEENTR) AS CDSERIEENTR,
                                      '' AS NRINSJURNF, N.IDSTATUS, N.DTENTRSAID, N.VRNOTAFISC, '' AS VRPRODUTOS, N.IDPGTOFRETE,
                                      N.NRPLACAVEIC, N.DSQTDEVOLU, N.DSESPECVOLU, N.DSMARCAVOLU, N.DSNUMEVOLU,
                                      '' AS CDFILIEMIT, '' AS CDFILIRECE, N.DTEMISSAO, '' AS CDFISCOPERNF, N.CDMODDOCFISC, '' AS CDCLIENTE, '' AS CDFORNECED, N.IDORIGDESTNF,
                                      '' AS VRCONTABILNF, N.NRINSJURTRAN, N.IDTPIJURTRAN, N.VRPBRUTOVOLU, N.VRPLIQUVOLU,
                                      '' AS VRBASECALCNF,
                                      '' AS VRIMPOSTONF,
                                      '' AS VROUTRCRED,
                                      '' AS VRISENTRIB,
                                      NRNOTAFISCALELE,
                                      N.CDTIPOOPER, N.IDSTATUSNFE, 'N' AS IDSIMPLESNACIONAL,
                                      0 AS QTDEPARC, 0 AS VRIMPDESONERADO
                                 FROM NOTAFISCAL N, SERIENF SS, SERIEENTR SE
                                WHERE (NVL(N.IDSISTEMA,'DFS') <> 'REC'
                                  AND NVL(N.IDSISTEMA, 'DFS') <> 'PAG'
                                  AND NVL(N.IDSISTEMA, 'DFS') <> 'CMP'
                                  AND NVL(N.IDSISTEMA, 'DFS') <> 'SUP'
                                  AND NVL(N.IDSISTEMA, 'DFS') <> 'TMP'
                                  AND NVL(N.IDSISTEMA, 'DFS') <> 'FIS')
                                  AND SE.CDSERIEENTR(+) = N.CDSERIEENTR
                                  AND SS.CDEMPRESA(+)   = N.CDEMPRESA
                                  AND SS.CDINSCESTA(+)  = N.CDINSCESTA
                                  AND SS.CDINSCMUNI(+)  = N.CDINSCMUNI
                                  AND SS.CDSERIE(+)     = N.CDSERIE
                                  AND N.IDENTRSAIDOP = 'S'
                                  AND N.IDSTATUS = 'C'
                                  AND N.CDMODDOCFISC IN ('01','1B','04','55')
                                  AND N.DTEMISSAO BETWEEN P_DTINICIAL AND P_DTFINAL
                                  AND N.CDINSCESTA = P_CDINSCESTA
                                  AND N.CDEMPRESA = P_CDEMPRESA
                                GROUP BY DECODE(N.IDENTRSAIDOP, 'E', '0','1'), N.CDFILIAL, N.NRLANCTONF, N.IDENTRSAIDOP, N.NRNOTAFISC, NVL(SS.CDSERIENFE,N.CDSERIE), NVL(SE.CDSERIEENTRNFE,N.CDSERIEENTR),
                                         N.IDSTATUS, N.DTENTRSAID, N.VRNOTAFISC, N.IDPGTOFRETE, N.CDMODDOCFISC, N.CDCLIENTE,
                                         N.CDFORNECED, N.IDORIGDESTNF, N.CDFILIEMIT, N.CDFILIRECE, N.DTEMISSAO, N.NRINSJURTRAN, N.IDTPIJURTRAN,
                                         N.VRPBRUTOVOLU, N.VRPLIQUVOLU, N.NRPLACAVEIC, N.DSQTDEVOLU, N.DSESPECVOLU, N.DSMARCAVOLU,
                                         N.DSNUMEVOLU, N.NRACESSONFE, N.CDTIPOOPER, N.IDSTATUSNFE, N.NRNOTAFISCALELE
                                UNION ALL
                               /******** NOTA DENEGADA *******/
                               /*Não é possível escriturar nota denegada na entrada, então mesmo que seja a transmissão de uma entrada
                                 deve ser escriturada como saída para manter o controle de numeração*/
                               SELECT '1' AS CAMPO2,
                                      '0' AS CAMPO3, NRACESSONFE,
                                      '' AS CDFILIAL, '' AS NRLANCTONF, N.IDENTRSAIDOP, N.NRNOTAFISC, NVL(NVL(SS.CDSERIENFE,N.CDSERIE),NVL(SE.CDSERIEENTR,N.CDSERIEENTR)) AS CDSERIE, '' AS CDSERIEENTR,
                                      '' AS NRINSJURNF, N.IDSTATUS, N.DTENTRSAID, N.VRNOTAFISC, '' AS VRPRODUTOS, N.IDPGTOFRETE,
                                      '' AS NRPLACAVEIC, '' AS DSQTDEVOLU, '' AS DSESPECVOLU, '' AS DSMARCAVOLU, N.DSNUMEVOLU,
                                      '' CDFILIEMIT, '' CDFILIRECE, N.DTEMISSAO, '' AS CDFISCOPERNF, N.CDMODDOCFISC, '' AS CDCLIENTE, '' AS CDFORNECED, N.IDORIGDESTNF,
                                      '' AS VRCONTABILNF, N.NRINSJURTRAN, N.IDTPIJURTRAN, N.VRPBRUTOVOLU, N.VRPLIQUVOLU,
                                      '' AS VRBASECALCNF,
                                      '' AS VRIMPOSTONF,
                                      '' AS VROUTRCRED,
                                      '' AS VRISENTRIB,
                                      NRNOTAFISCALELE,
                                      N.CDTIPOOPER, N.IDSTATUSNFE, 'N' AS IDSIMPLESNACIONAL,
                                      0 AS QTDEPARC, 0 AS VRIMPDESONERADO
                                 FROM NOTAFISCAL N, SERIENF SS, SERIEENTR SE
                                WHERE (NVL(N.IDSISTEMA,'DFS') <> 'REC'
                                  AND NVL(N.IDSISTEMA, 'DFS') <> 'PAG'
                                  AND NVL(N.IDSISTEMA, 'DFS') <> 'CMP'
                                  AND NVL(N.IDSISTEMA, 'DFS') <> 'SUP'
                                  AND NVL(N.IDSISTEMA, 'DFS') <> 'TMP'
                                  AND NVL(N.IDSISTEMA, 'DFS') <> 'FIS')
                                  AND SE.CDSERIEENTR(+) = N.CDSERIEENTR
                                  AND SS.CDEMPRESA(+)   = N.CDEMPRESA
                                  AND SS.CDINSCESTA(+)  = N.CDINSCESTA
                                  AND SS.CDINSCMUNI(+)  = N.CDINSCMUNI
                                  AND SS.CDSERIE(+)     = N.CDSERIE
                                  AND N.IDSTATUSNFE     = 'D'
                                  AND N.NRACESSONFE     IS NOT NULL
                                  AND N.CDMODDOCFISC    IN ('01','1B','04','55')
                                  AND N.DTEMISSAO       BETWEEN P_DTINICIAL AND P_DTFINAL
                                  AND N.CDINSCESTA      = P_CDINSCESTA
                                  AND N.CDEMPRESA       = P_CDEMPRESA
                                GROUP BY DECODE(N.IDENTRSAIDOP, 'E', '0','1'), N.CDFILIAL, N.NRLANCTONF, N.IDENTRSAIDOP, N.NRNOTAFISC,
                                         NVL(NVL(SS.CDSERIENFE,N.CDSERIE),NVL(SE.CDSERIEENTR,N.CDSERIEENTR)),
                                         N.IDSTATUS, N.DTENTRSAID, N.VRNOTAFISC, N.IDPGTOFRETE, N.CDMODDOCFISC, N.CDCLIENTE,
                                         N.CDFORNECED, N.IDORIGDESTNF, N.CDFILIEMIT, N.CDFILIRECE, N.DTEMISSAO, N.NRINSJURTRAN, N.IDTPIJURTRAN,
                                         N.VRPBRUTOVOLU, N.VRPLIQUVOLU, N.NRPLACAVEIC, N.DSQTDEVOLU, N.DSESPECVOLU, N.DSMARCAVOLU,
                                         N.DSNUMEVOLU, N.NRACESSONFE, N.CDTIPOOPER, N.IDSTATUSNFE, N.NRNOTAFISCALELE
                                UNION ALL
                               /******** NÚMERAÇÃO INUTILIZADA *******/
                               SELECT '1' AS CAMPO2,
                                      '0' AS CAMPO3,
                                      ''  AS NRACESSONFE,
                                      ''  AS CDFILIAL, '' AS NRLANCTONF,
                                      'S' AS IDENTRSAIDOP, N.NRINUTILNFELE AS NRNOTAFISC, N.CDSERIE AS CDSERIE, '' AS CDSERIEENTR,
                                      '' AS NRINSJURNF, 'I' AS IDSTATUS, N.DTINUTNFE AS DTENTRSAID, 0 AS VRNOTAFISC, '' AS VRPRODUTOS, '' AS IDPGTOFRETE,
                                      '' AS NRPLACAVEIC, '' AS DSQTDEVOLU, '' AS DSESPECVOLU, '' AS DSMARCAVOLU, '' AS DSNUMEVOLU,
                                      '' CDFILIEMIT, '' CDFILIRECE, N.DTINUTNFE AS DTEMISSAO, '' AS CDFISCOPERNF, '55' AS CDMODDOCFISC, '' AS CDCLIENTE, '' AS CDFORNECED, '' AS IDORIGDESTNF,
                                      '' AS VRCONTABILNF, '' AS NNRINSJURTRAN, '' AS IDTPIJURTRAN, 0 AS VRPBRUTOVOLU, 0 AS VRPLIQUVOLU,
                                      '' AS VRBASECALCNF,
                                      '' AS VRIMPOSTONF,
                                      '' AS VROUTRCRED,
                                      '' AS VRISENTRIB,
                                      N.NRINUTILNFELE AS NRNOTAFISCALELE,
                                      '' AS CDTIPOOPER, 'I' AS IDSTATUSNFE, 'N' AS IDSIMPLESNACIONAL,
                                      0 AS QTDEPARC, 0 AS VRIMPDESONERADO
                                 FROM NUMINUTILNFELE N
                                WHERE TRUNC(N.DTINUTNFE)BETWEEN P_DTINICIAL AND P_DTFINAL
                                  AND N.CDEMPRESA  = P_CDEMPRESA
                                  AND N.CDINSCESTA = P_CDINSCESTA
                                  AND N.NRPROTOCINUTNFE  <> 'TEKNISA'
                                UNION ALL
                               /*NF ENTRADA COM E SEM CARGA TRIBUTÁRIA*/
                               SELECT N.CAMPO2, N.CAMPO3, N.NRACESSONFE, N.CDFILIAL, N.NRLANCTONF, N.IDENTRSAIDOP, N.NRNOTAFISC, N.CDSERIE,
                                      N.CDSERIEENTR, N.NRINSJURNF, N.IDSTATUS, N.DTENTRSAID, N.VRNOTAFISC, N.VRPRODUTOS, N.IDPGTOFRETE,
                                      N.NRPLACAVEIC, N.DSQTDEVOLU, N.DSESPECVOLU, N.DSMARCAVOLU, N.DSNUMEVOLU, N.CDFILIEMIT, N.CDFILIRECE,
                                      N.DTEMISSAO, N.CDFISCOPERNF, N.CDMODDOCFISC, N.CDCLIENTE, N.CDFORNECED, N.IDORIGDESTNF,
                                      N.VRCONTABILNF, N.NRINSJURTRAN, N.IDTPIJURTRAN, N.VRPBRUTOVOLU, N.VRPLIQUVOLU,
                                      TO_CHAR(NVL(VALOR_IMPOSTO_NFE_CARGA(N.CDFILIAL, N.NRLANCTONF, 'B', 'I', '1'),0) - NVL(N.VRBASEC197,0) +
                                              NVL(DECODE(V_IDTPCARGATRIB,'O',0,DECODE(V_SGESTADO,'SP',0,VALOR_IMPOSTO_NFE_CARGA(N.CDFILIAL,N.NRLANCTONF,'B','C','1'))),0)) AS VRBASECALCNF,
                                      TO_CHAR(NVL(VALOR_IMPOSTO_NFE_CARGA(N.CDFILIAL, N.NRLANCTONF, 'I', 'I', '1'),0) - NVL(N.VRIMPOSTOC197,0) +
                                              NVL(DECODE(V_IDTPCARGATRIB,'O',0,DECODE(V_SGESTADO,'SP',0,VALOR_IMPOSTO_NFE_CARGA(N.CDFILIAL,N.NRLANCTONF,'I','C','1'))),0)) AS VRIMPOSTONF,
                                      N.VROUTRCRED, N.VRISENTRIB, N.NRNOTAFISCALELE, N.CDTIPOOPER, N.IDSTATUSNFE, N.IDSIMPLESNACIONAL, N.QTDEPARC,
                                      (SELECT NVL(SUM(I.VRIMPOSTOIT),0) FROM ITEMPROIMPOS I, IMPOSTO IM WHERE I.IDIMPDESONERAIT = 'S' AND I.CDFILIAL = N.CDFILIAL AND I.NRLANCTONF = N.NRLANCTONF AND I.CDIMPOSTO = IM.CDIMPOSTO AND IM.CDIMPOSTONFE = P_CDIMPOSTO) VRIMPDESONERADO
                                 FROM (SELECT DECODE(N.IDENTRSAIDOP, 'E', '0','1') AS CAMPO2,
                                              DECODE(N.IDENTRSAIDOP, 'E', DECODE(IDSTATUSNFE,'A','0',DECODE(IDSTATUS,'E','0','1')), '0') AS CAMPO3, NRACESSONFE,
                                              I.CDFILIAL, I.NRLANCTONF, N.IDENTRSAIDOP, N.NRNOTAFISC, NVL(SS.CDSERIENFE,N.CDSERIE) AS CDSERIE, NVL(SE.CDSERIEENTRNFE,N.CDSERIEENTR) AS CDSERIEENTR,
                                              N.NRINSJURNF, N.IDSTATUS, N.DTENTRSAID, N.VRNOTAFISC, TO_CHAR(N.VRPRODUTOS) AS VRPRODUTOS, N.IDPGTOFRETE,
                                              N.NRPLACAVEIC, N.DSQTDEVOLU, N.DSESPECVOLU, N.DSMARCAVOLU, N.DSNUMEVOLU,
                                              N.CDFILIEMIT, N.CDFILIRECE, N.DTEMISSAO, MAX(I.CDFISCOPERNF) AS CDFISCOPERNF, N.CDMODDOCFISC, N.CDCLIENTE, N.CDFORNECED, N.IDORIGDESTNF,
                                              TO_CHAR(SUM(I.VRCONTABILNF)) AS VRCONTABILNF, N.NRINSJURTRAN, N.IDTPIJURTRAN, N.VRPBRUTOVOLU, N.VRPLIQUVOLU,
                                              NVL(C_197.VRBASEC197,0) AS VRBASEC197, NVL(C_197.VRIMPOSTOC197,0) AS VRIMPOSTOC197,
                                              TO_CHAR(SUM(DECODE(I.CDFISCALNF,'3',I.VRCONTABILNF,0)))   AS VROUTRCRED,
                                              TO_CHAR(SUM(DECODE(I.CDFISCALNF,'2',I.VRCONTABILNF,'1',DECODE(I.VRPERREDBCNF,0, 0,I.VRCONTABILNF-I.VRBASECALCNF), 0))) AS VRISENTRIB,
                                              N.NRNOTAFISCALELE, N.CDTIPOOPER, N.IDSTATUSNFE, DECODE(N.IDORIGDESTNF,'F',PF.IDSIMPLESNACIONAL,'N') AS IDSIMPLESNACIONAL,
                                              MAX((SELECT COUNT(DISTINCT NRPARCELAPAG)
                                                     FROM CONTAPAGAR C
                                                    WHERE N.CDFILIAL    = C.CDFILIAL
                                                      AND N.NRLANCTONF  = C.NRLANCTONF
                                                      AND C.NRLANBOLPAG IS NOT NULL)) AS QTDEPARC
                                         FROM NOTAFISCAL N, IMPOSTONF I, IMPOSTO IP, PARAMFORNE PF, SERIEENTR SE, SERIENF SS,
                                              (SELECT NVL(SUM(IT.VRBASECALCIT),0) AS VRBASEC197,
                                                      NVL(SUM(ROUND(IT.VRIMPOSTOIT,2)),0)  AS VRIMPOSTOC197,
                                                      DT.CDFILIAL, DT.NRLANCTONF
                                                 FROM ITEMPROIMPOS IT, IMPOSTO IM, DETITMAPARECUP DT
                                                WHERE IT.CDFILIAL     = DT.CDFILIAL
                                                  AND IT.NRLANCTONF   = DT.NRLANCTONF
                                                  AND IT.NRSEQITPROD  = DT.NRSEQITPROD
                                                  AND IT.CDIMPOSTO    = DT.CDIMPOSTO
                                                  AND IT.NRITPROIMPOS = DT.NRITPROIMPOS
                                                  AND IT.NRITPROIMPOS = '1'
                                                  AND IT.CDFISCALIT   = '1'
                                                  AND IT.CDIMPOSTO    = IM.CDIMPOSTO
                                                  AND IM.CDIMPOSTONFE = '00'
                                                  AND DT.IDTIPOITMAPR <> 'VI'
                                                GROUP BY DT.CDFILIAL, DT.NRLANCTONF) C_197
                                        WHERE I.NRSEQUMAPAPU    = V_NRSEQUMAPAPU
                                          AND IP.CDIMPOSTONFE   = P_CDIMPOSTO
                                          AND IP.CDIMPOSTO      = I.CDIMPOSTO
                                          AND (NVL(N.IDSISTEMA,'DFS')  <> 'REC'
                                          AND NVL(N.IDSISTEMA, 'DFS')  <> 'PAG'
                                          AND NVL(N.IDSISTEMA, 'DFS')  <> 'CMP'
                                          AND NVL(N.IDSISTEMA, 'DFS')  <> 'SUP'
                                          AND NVL(N.IDSISTEMA, 'DFS')  <> 'TMP'
                                          AND NVL(N.IDSISTEMA, 'DFS')  <> 'FIS' )
                                          AND N.IDENTRSAIDOP    = 'E'
                                          AND PF.CDFORNECED(+)  = N.CDFORNECED
                                          AND NVL(I.IDIMPOSTONF, '1') <> '3'
                                          AND N.CDFILIAL        = I.CDFILIAL
                                          AND N.NRLANCTONF      = I.NRLANCTONF
                                          AND SE.CDSERIEENTR(+) = N.CDSERIEENTR
                                          AND SS.CDEMPRESA(+)   = N.CDEMPRESA
                                          AND SS.CDINSCESTA(+)  = N.CDINSCESTA
                                          AND SS.CDINSCMUNI(+)  = N.CDINSCMUNI
                                          AND SS.CDSERIE(+)     = N.CDSERIE
                                          AND ((N.IDSTATUS = 'A') OR (N.IDSTATUS = 'E'))
                                          AND N.CDMODDOCFISC IN ('01','1B','04','55')
                                          AND NVL(P_GERAFORSALE,'N') = 'N'
                                          AND N.CDFILIAL        = C_197.CDFILIAL(+)
                                          AND N.NRLANCTONF      = C_197.NRLANCTONF(+)
                                        GROUP BY DECODE(N.IDENTRSAIDOP, 'E', '0','1'), I.CDFILIAL, I.NRLANCTONF, N.IDENTRSAIDOP,
                                               N.NRNOTAFISC, NVL(SS.CDSERIENFE,N.CDSERIE), NVL(SE.CDSERIEENTRNFE,N.CDSERIEENTR), N.NRINSJURNF, N.IDSTATUS, N.DTENTRSAID, NRACESSONFE,
                                               N.VRNOTAFISC, TO_CHAR(N.VRPRODUTOS), N.IDPGTOFRETE, N.DTEMISSAO , N.CDMODDOCFISC, N.CDCLIENTE,
                                               N.CDFORNECED, N.IDORIGDESTNF, N.CDFILIEMIT, N.CDFILIRECE, N.NRINSJURTRAN, N.IDTPIJURTRAN, N.VRPBRUTOVOLU, N.VRPLIQUVOLU,
                                               N.NRPLACAVEIC, N.DSQTDEVOLU, N.DSESPECVOLU, N.DSMARCAVOLU, N.DSNUMEVOLU, NRACESSONFE, N.NRNOTAFISCALELE, N.CDTIPOOPER, IDSTATUSNFE,
                                               DECODE(N.IDORIGDESTNF,'F',PF.IDSIMPLESNACIONAL,'N'), NVL(C_197.VRBASEC197,0), NVL(C_197.VRIMPOSTOC197,0))N
                                UNION
                               /*******NOTAS FISCAIS FORSALE - C100 FOS ***********/
                               SELECT DECODE(NF.IDENTRSAIDOP, 'E', '0','1') AS CAMPO2,
                                      DECODE(NF.IDENTRSAIDOP, 'E', DECODE(IDSTATUS,'E','0','1'), '0') AS CAMPO3, NRACESSONFE,
                                      NF.CDFILIAL, NF.NRLANCTONF, NF.IDENTRSAIDOP, NF.NRNOTAFISC, NF.CDSERIE, NF.CDSERIEENTR,
                                      NF.NRINSJURNF, NF.IDSTATUS, NF.DTENTRSAID, NF.VRNOTAFISC, TO_CHAR(NF.VRPRODUTOS) AS VRPRODUTOS, NF.IDPGTOFRETE,
                                      NF.NRPLACAVEIC, NF.DSQTDEVOLU, NF.DSESPECVOLU, NF.DSMARCAVOLU, NF.DSNUMEVOLU,
                                      NF.CDFILIEMIT, NF.CDFILIRECE, NF.DTEMISSAO, MAX(NF.CDFISCOPERNF) AS CDFISCOPERNF, NF.CDMODDOCFISC, NF.CDCLIENTE, NF.CDFORNECED, NF.IDORIGDESTNF,
                                      NF.VRCONTABILNF AS VRCONTABILNF,
                                      NF.NRINSJURTRAN, NF.IDTPIJURTRAN, NF.VRPBRUTOVOLU, NF.VRPLIQUVOLU,
                                      TO_CHAR(VRBASECALCNF) AS VRBASECALCNF,
                                      TO_CHAR(VRIMPOSTONF),
                                      TO_CHAR(VROUTRCRED),
                                      TO_CHAR(VRISENTRIB),
                                      NF.NRNOTAFISCALELE,
                                      NF.CDTIPOOPER, '' AS IDSTATUSNFE, NF.IDSIMPLESNACIONAL, NF.QTDEPARC,
                                      (SELECT NVL(SUM(I.VRIMPOSTOIT),0) FROM ITEMPROIMPOS I, IMPOSTO IM WHERE I.IDIMPDESONERAIT = 'S' AND I.CDFILIAL = NF.CDFILIAL AND I.NRLANCTONF = NF.NRLANCTONF AND I.CDIMPOSTO = IM.CDIMPOSTO AND IM.CDIMPOSTONFE = P_CDIMPOSTO) VRIMPDESONERADO
                                 FROM ENDECLIE EC, ENDEFORN EF, ENDEFILI EFI,
                                      (SELECT DECODE(NVL(N.IDORIGDESTNF,DECODE(N.IDENTRSAIDOP,'S','C','F')),'C',CL.NRINSJURCLIE,'F',FO.NRINSJURFORN,'L',FI.NRINSJURFILI) AS NRINSJURNF,
                                              DECODE(NVL(N.IDORIGDESTNF,DECODE(N.IDENTRSAIDOP,'S','C','F')),'C',CL.NRINSESTCLIE,'F',FO.NRINSESTFORN,'L',FI.CDINSCESTA  ) AS NRINSEST,
                                              N.IDORIGDESTNF, N.CDCLIENTE, N.CDFORNECED, N.CDFILIEMIT, N.CDFILIRECE, N.NRNOTAFISC, I.CDFISCOPERNF,
                                              N.NRLANCTONF,N.CDFILIAL, N.IDENTRSAIDOP, DECODE(N.CDMODDOCFISC,'2D','55',N.CDMODDOCFISC) AS CDMODDOCFISC,
                                              NVL(SS.CDSERIENFE,N.CDSERIE) AS CDSERIE, NVL(SE.CDSERIEENTRNFE,N.CDSERIEENTR) AS CDSERIEENTR, N.DTENTRSAID, N.DTEMISSAO,
                                              TO_CHAR(SUM(VRCONTABILNF)) AS VRCONTABILNF,
                                              DECODE(I.CDFISCALNF,'1',SUM(VRBASECALCNF),0) AS VRBASECALCNF,
                                              DECODE(I.CDFISCALNF,'2',SUM(VRCONTABILNF),'1',SUM(DECODE(I.VRPERREDBCNF,0, 0,I.VRCONTABILNF-I.VRBASECALCNF)),0) AS VRISENTRIB,
                                              DECODE(I.CDFISCALNF,'3',SUM(VRCONTABILNF),0) AS VROUTRCRED,
                                              DECODE(I.CDFISCALNF,'1',SUM(VRIMPOSTONF ),0) AS VRIMPOSTONF,
                                              SUM(N.VRPRODUTOS) AS VRPRODUTOS,
                                              N.NRINSJURTRAN,N.IDTPIJURTRAN, N.VRPBRUTOVOLU, N.VRPLIQUVOLU, N.NRNOTAFISCALELE, I.VRPERREDBCNF,N.IDSTATUS,N.IDPGTOFRETE,
                                              N.NRPLACAVEIC, N.DSQTDEVOLU, N.DSESPECVOLU, N.DSMARCAVOLU, N.DSNUMEVOLU,N.VRNOTAFISC, NRACESSONFE, N.CDTIPOOPER,
                                              DECODE(N.IDORIGDESTNF,'F',PF.IDSIMPLESNACIONAL,'N') AS IDSIMPLESNACIONAL,
                                              MAX((SELECT COUNT(DISTINCT NRPARCELAREC)
                                                     FROM CONTARECEBER C
                                                    WHERE N.CDFILIAL    = C.CDFILIAL
                                                      AND N.NRLANCTONF  = C.NRLANCTONF
                                                      AND C.NRLANBOLREC IS NOT NULL)) AS QTDEPARC
                                         FROM NOTAFISCAL N, IMPOSTONF I, IMPOSTO IMP, CLIENTE CL, FORNECEDOR FO, FILIAL FI, PARAMFORNE PF, SERIENF SS, SERIEENTR SE
                                        WHERE N.CDFILIAL     = I.CDFILIAL
                                          AND N.NRLANCTONF   = I.NRLANCTONF
                                          AND IMP.CDIMPOSTO  = I.CDIMPOSTO
                                          AND N.CDCLIENTE    = CL.CDCLIENTE(+)
                                          AND N.CDFORNECED   = FO.CDFORNECED(+)
                                          AND N.CDFORNECED   = PF.CDFORNECED(+)
                                          AND N.CDFILIRECE   = FI.CDFILIAL(+)
                                          AND N.CDFILIEMIT   = FI.CDFILIAL(+)
                                          AND DTEMISSAO BETWEEN P_DTINICIAL AND P_DTFINAL
                                          AND ((N.IDSTATUS   = 'A' OR N.IDSTATUS = 'E') OR (N.IDSTATUSNFE = 'A' OR N.IDSTATUSNFE = 'T'))
                                          AND N.CDINSCESTA   = P_CDINSCESTA
                                          AND IMP.CDIMPOSTONFE = P_CDIMPOSTO
                                          AND (I.IDIMPOSTONF <> '3' OR IDIMPOSTONF IS NULL)
                                          AND (NVL(N.IDSISTEMA, 'DFS') <> 'REC'
                                          AND NVL(N.IDSISTEMA, 'DFS')  <> 'PAG'
                                          AND NVL(N.IDSISTEMA, 'DFS')  <> 'CMP'
                                          AND NVL(N.IDSISTEMA, 'DFS')  <> 'SUP'
                                          AND NVL(N.IDSISTEMA, 'DFS')  <> 'TMP'
                                          AND NVL(N.IDSISTEMA, 'DFS')  <> 'FIS')
                                          AND SE.CDSERIEENTR(+) = N.CDSERIEENTR
                                          AND SS.CDEMPRESA(+)   = N.CDEMPRESA
                                          AND SS.CDINSCESTA(+)  = N.CDINSCESTA
                                          AND SS.CDINSCMUNI(+)  = N.CDINSCMUNI
                                          AND SS.CDSERIE(+)     = N.CDSERIE
                                          AND N.CDMODDOCFISC IN ('01','1B','04','55','2D')
                                          AND N.IDENTRSAIDOP = 'S'
                                          AND NVL(P_GERAFORSALE,'N') = 'S'
                                        GROUP BY DECODE(NVL(N.IDORIGDESTNF,DECODE(N.IDENTRSAIDOP,'S','C','F')),'C',CL.NRINSJURCLIE,'F',FO.NRINSJURFORN,'L',FI.NRINSJURFILI),
                                                 DECODE(NVL(N.IDORIGDESTNF,DECODE(N.IDENTRSAIDOP,'S','C','F')),'C',CL.NRINSESTCLIE,'F',FO.NRINSESTFORN,'L',FI.CDINSCESTA),N.IDORIGDESTNF,
                                                 N.CDCLIENTE, N.CDFORNECED, N.CDFILIEMIT, N.CDFILIRECE, N.NRNOTAFISC, I.CDFISCOPERNF, N.NRLANCTONF,
                                                 N.CDFILIAL, N.IDENTRSAIDOP, N.CDMODDOCFISC, NVL(SS.CDSERIENFE,N.CDSERIE), NVL(SE.CDSERIEENTRNFE,N.CDSERIEENTR),
                                                 N.DTENTRSAID, N.DTEMISSAO,  I.CDFISCALNF, N.NRINSJURTRAN, N.IDTPIJURTRAN, N.VRPBRUTOVOLU,
                                                 N.VRPLIQUVOLU,N.NRNOTAFISCALELE,I.VRPERREDBCNF,N.IDSTATUS,IDPGTOFRETE,
                                                 N.NRPLACAVEIC, N.DSQTDEVOLU, N.DSESPECVOLU, N.DSMARCAVOLU, N.DSNUMEVOLU,N.VRNOTAFISC,NRACESSONFE,N.CDTIPOOPER,DECODE(N.IDORIGDESTNF,'F',PF.IDSIMPLESNACIONAL,'N'))NF
                                WHERE NF.CDCLIENTE    = EC.CDCLIENTE(+)
                                  AND NF.CDFORNECED   = EF.CDFORNECED(+)
                                  AND NF.CDFILIEMIT   = EFI.CDFILIAL(+)
                                  AND NF.CDFILIRECE   = EFI.CDFILIAL(+)
                                  AND IDTPENDECLIE(+) = 'P'
                                  AND IDTPENDEFORN(+) = 'P'
                                  AND IDTPENDEFILI(+) = 'P'
                                  AND NVL(P_GERAFORSALE,'N') = 'S'
                                GROUP BY DECODE(NF.IDENTRSAIDOP, 'E', '0','1'),
                                         DECODE(NF.IDENTRSAIDOP, 'E', DECODE(IDSTATUS,'E','0','1'), '0'), NRACESSONFE,
                                         NF.CDFILIAL, NF.NRLANCTONF, NF.IDENTRSAIDOP, NF.NRNOTAFISC, NF.CDSERIE, NF.CDSERIEENTR,
                                         NF.NRINSJURNF, NF.IDSTATUS, NF.DTENTRSAID, NF.VRNOTAFISC, TO_CHAR(NF.VRPRODUTOS), NF.IDPGTOFRETE,
                                         NF.NRPLACAVEIC, NF.DSQTDEVOLU, NF.DSESPECVOLU, NF.DSMARCAVOLU, NF.DSNUMEVOLU,
                                         NF.CDFILIEMIT, NF.CDFILIRECE, NF.DTEMISSAO, NF.CDMODDOCFISC, NF.CDCLIENTE, NF.CDFORNECED, NF.IDORIGDESTNF,
                                         NF.VRCONTABILNF, NF.NRINSJURTRAN, NF.IDTPIJURTRAN, NF.VRPBRUTOVOLU, NF.VRPLIQUVOLU,
                                         TO_CHAR(VRBASECALCNF), TO_CHAR(VRIMPOSTONF), TO_CHAR(VROUTRCRED), TO_CHAR(VRISENTRIB),
                                         NF.NRNOTAFISCALELE,NF.CDTIPOOPER,NF.IDSIMPLESNACIONAL, NF.QTDEPARC, NF.CDTIPOOPER)NF
                        UNION ALL
                       /*Registro C100 para Nota Fiscal Eletrônica para Consumidor Final (NFC-e)*/
                       SELECT ('|C100'                                                                || '|' ||
                               NF.CAMPO2                                                              || '|' ||
                               NF.CAMPO3                                                              || '|' ||
                               ''                                                                     || '|' ||
                               NF.CDMODDOCFISC                                                        || '|' ||
                               DECODE(NF.IDSTATUSNFCE,'D','04','I','05','C','02','00')                || '|' ||
                               REPLACE(REPLACE(NF.CDSERIE,'-',''),'.','')                             || '|' ||
                               LTRIM(NF.NRNOTAFISC,'0')                                               || '|' ||
                               NF.NRACESSONFCE                                                        || '|' ||
                               DECODE(NF.IDSTATUSNFCE,'D','','I','','C','',TO_CHAR(NF.DTEMISSAO,'ddmmyyyy')) || '|' ) AS DADOS_1,
                               (DECODE(NF.IDSTATUSNFCE,'D','','I','','C','',REPLACE(LTRIM(TO_CHAR(ROUND(NF.VRCONTABILNF,2),'999999999990.00')),'.',','))  || '|' || -- Campo 12 - Valor total do documento fiscal
                               DECODE(NF.IDSTATUSNFCE,'D','','I','','C','','0')                                                                           || '|' || -- Campo 13 - Indicador de Pagamento
                               DECODE(NF.IDSTATUSNFCE,'D','','I','','C','',REPLACE(LTRIM(TO_CHAR(NF.VRDESITVEND,'999999999990.00')),'.',','))             || '|' || -- Campo 14 - Valor total do desconto
                               DECODE(NF.IDSTATUSNFCE,'D','','I','','C','','0,00')                                                                        || '|' || -- Campo 15 - Abatimento não tributado e não comercial - desconto ICMS
                               DECODE(NF.IDSTATUSNFCE,'D','','I','','C','',REPLACE(LTRIM(TO_CHAR(ROUND(NF.VRCONTABILNF+NF.VRDESITVEND,2),'999999999990.00')),'.',',')) || '|' || -- Campo 16 - Valor total das mercadorias e serviços
                               DECODE(NF.IDSTATUSNFCE,'D','','I','','C','','9')                                                                           || '|' || -- Campo 17 - Indicador de Frete
                               DECODE(NF.IDSTATUSNFCE,'D','','I','','C','','0,00')                                                                        || '|' || -- Campo 18 - Valor de Frete
                               DECODE(NF.IDSTATUSNFCE,'D','','I','','C','','0,00')                                                                        || '|' || -- Campo 19 - Valor do Seguro
                               DECODE(NF.IDSTATUSNFCE,'D','','I','','C','','0,00')                                                                        || '|' || -- Campo 20 - Outras despesas acessórias
                               DECODE(NF.IDSTATUSNFCE,'D','','I','','C','',REPLACE(LTRIM(TO_CHAR(ROUND(NF.VRBASECALC,2 ),'999999999990.00')), '.', ','))  || '|' || -- Campo 21 - Valor da base de cálculo do ICMS
                               DECODE(NF.IDSTATUSNFCE,'D','','I','','C','',REPLACE(LTRIM(TO_CHAR(ROUND(NF.VRIMPOSTONF,2),'999999999990.00')), '.', ','))  || '|' || -- Campo 22 - Valor do ICMS
                               '' || '|' || -- base de calc susbt. trib
                               '' || '|' || -- valor do icms retido susbt. trib
                               '' || '|' || -- valor do IPI
                               '' || '|' || -- valor do PIS
                               '' || '|' || -- valor do COFINS
                               '' || '|' || -- pis retido por subst. trib.
                               '' || '|'  ) AS DADOS_3,
                               NF.CDFILIAL, NF.NRLANCTONF, NF.CDCAIXA, '' AS NRINSJURTRAN, '' AS IDTPIJURTRAN, 0 AS VRPBRUTOVOLU, 0 AS VRPLIQUVOLU,
                               '' AS NRPLACAVEIC, '' AS DSQTDEVOLU, '' AS DSESPECVOLU, '' AS DSMARCAVOLU, '' AS DSNUMEVOLU, '' AS CDFISCOPERNF, NF.NRNOTAFISC AS NRNOTAFISC,
                               NF.DTEMISSAO, NF.DTENTRSAID, NF.IDENTRSAIDOP, TO_CHAR(NF.VRIMPOSTONF) AS VRIMPOSTONF, NF.CDMODDOCFISC, NF.IDSTATUS, NF.IDORIGDESTNF,
                               '' AS COD_PAR, DECODE(NF.IDSTATUSNFCE,'D','04','I','05','C','02','00') AS SITU_DOC, NF.IDSTATUSNFCE AS IDSTATUSNFE,
                               'N' AS IDSIMPLESNACIONAL, NF.QTDEPARC, '' AS CDTIPOOPER, NF.CDFILIAL AS FILIAL
                         FROM (SELECT '1' AS CAMPO2, '0' AS CAMPO3, '65' AS CDMODDOCFISC, VE.IDSTATUSNFCE, VE.CDSERIENFCE AS CDSERIE, VE.NRNOTAFISCALCE AS NRNOTAFISC,
                                      SUM(TRUNC(IT.QTPRODVEND*(IT.VRUNITVEND+NVL(IT.VRUNITVENDCL,0)),2)-NVL(IT.VRDESITVEND,0)+NVL(IT.VRACRITVEND,0)) AS VRCONTABILNF,
                                      SUM(VRDESITVEND) AS VRDESITVEND, VE.NRACESSONFCE, TRUNC(VE.DTEMISSAONFCE) AS DTEMISSAO, IP.VRIMPOSTONF, IP.VRBASECALC,
                                      VE.CDFILIAL AS CDFILIAL, VE.NRSEQVENDA AS NRLANCTONF, VE.CDCAIXA, VE.DTENTRVENDA AS DTENTRSAID, 'S' AS IDENTRSAIDOP,
                                      '' AS IDSTATUS, '' AS IDORIGDESTNF, 1 AS QTDEPARC
                                 FROM VENDA VE, ITEMVENDA IT, FILIAL FI,
                                      (SELECT I.CDFILIAL, I.CDCAIXA, I.NRSEQVENDA,
                                              SUM(CASE WHEN I.VRPRBCREDUICMS > 0
                                                       THEN I.VRBASECALCREDUZ
                                                       ELSE TRUNC(T.QTPRODVEND*(T.VRUNITVEND+NVL(T.VRUNITVENDCL,0)),2)-NVL(T.VRDESITVEND,0)+NVL(T.VRACRITVEND,0) END) AS VRBASECALC,
                                              SUM(CASE WHEN I.VRPRBCREDUICMS > 0
                                                       THEN I.VRIMPOPRODREDUZ
                                                       ELSE TRUNC(I.VRIMPOPRODIT,2) END) AS VRIMPOSTONF
                                         FROM ITVENDAIMPOS I,  ITEMVENDA T,  VENDA V,  IMPOSTO M, FILIAL F
                                        WHERE F.CDEMPRESA       = P_CDEMPRESA
                                          AND F.CDINSCESTA      = P_CDINSCESTA
                                          AND F.CDEMPRESA       = V.CDEMPRESA
                                          AND F.CDFILIAL        = V.CDFILIAL
                                          AND TRUNC(V.DTEMISSAONFCE) BETWEEN P_DTINICIAL AND P_DTFINAL
                                          AND V.IDSITUVENDA     = 'O'
                                          AND V.IDTPAMBNFCE     = '1'
                                          AND V.IDSTATUSNFCE    = 'A'
                                          AND V.CDFILIAL        = T.CDFILIAL
                                          AND V.NRSEQVENDA      = T.NRSEQVENDA
                                          AND V.CDCAIXA         = T.CDCAIXA
                                          AND T.CDFILIAL        = I.CDFILIAL
                                          AND T.CDCAIXA         = I.CDCAIXA
                                          AND T.NRSEQUITVEND    = I.NRSEQUITVEND
                                          AND T.NRSEQVENDA      = I.NRSEQVENDA
                                          AND I.CDIMPOSTO       = M.CDIMPOSTO
                                          AND M.CDIMPOSTONFE    = P_CDIMPOSTO
                                          AND M.IDTPIMPOSFIS    = 'T'
                                          AND V.IDAPROVACAONFCE = 'A'
                                          AND V.IDTPEMISVEND    = 'N'
                                        GROUP BY I.CDFILIAL, I.CDCAIXA, I.NRSEQVENDA) IP
                                WHERE VE.CDEMPRESA       = P_CDEMPRESA
                                  AND TRUNC(VE.DTEMISSAONFCE) BETWEEN P_DTINICIAL AND P_DTFINAL
                                  AND VE.IDSITUVENDA     = 'O'
                                  AND VE.IDTPAMBNFCE     = '1'
                                  AND VE.IDSTATUSNFCE    = 'A'
                                  AND VE.IDAPROVACAONFCE = 'A'
                                  AND VE.CDFILIAL        = IT.CDFILIAL
                                  AND VE.NRSEQVENDA      = IT.NRSEQVENDA
                                  AND VE.CDCAIXA         = IT.CDCAIXA
                                  AND IT.CDFILIAL        = IP.CDFILIAL(+)
                                  AND IT.CDCAIXA         = IP.CDCAIXA(+)
                                  AND IT.NRSEQVENDA      = IP.NRSEQVENDA(+)
                                  AND VE.IDTPEMISVEND    = 'N'
                                  AND VE.CDFILIAL        = FI.CDFILIAL
                                  AND FI.CDEMPRESA       = P_CDEMPRESA
                                  AND FI.CDINSCESTA      = P_CDINSCESTA
                                GROUP BY VE.IDSTATUSNFCE, VE.CDSERIENFCE, VE.NRNOTAFISCALCE, VE.NRACESSONFCE,
                                         TRUNC(VE.DTEMISSAONFCE), VE.CDFILIAL, VE.NRSEQVENDA, VE.CDCAIXA,
                                         VE.DTENTRVENDA, IP.VRIMPOSTONF, IP.VRBASECALC
                                UNION ALL
                               SELECT '1' AS CAMPO2, '0' AS CAMPO3, '65' AS CDMODDOCFISC, VE.IDSTATUSNFCE, VE.CDSERIENFCE AS CDSERIE, VE.NRNOTAFISCALCE AS NRNOTAFISC,
                                      0 AS VRCONTABILNF, 0 AS VRDESITVEND, VE.NRACESSONFCE, TRUNC(VE.DTEMISSAONFCE) AS DTEMISSAO, 0 AS VRIMPOSTONF, 0 AS VRBASECALC,
                                      VE.CDFILIAL AS CDFILIAL, VE.NRSEQVENDA AS NRLANCTONF, VE.CDCAIXA, VE.DTENTRVENDA AS DTENTRSAID, 'S' AS IDENTRSAIDOP,
                                      'C' AS IDSTATUS, '' AS IDORIGDESTNF, 0 AS QTDEPARC
                                 FROM VENDA VE, FILIAL FI
                                WHERE VE.CDEMPRESA       = P_CDEMPRESA
                                  AND TRUNC(VE.DTEMISSAONFCE) BETWEEN P_DTINICIAL AND P_DTFINAL
                                  AND VE.IDSITUVENDA     = 'C'
                                  AND VE.IDTPAMBNFCE     = '1'
                                  AND VE.IDSTATUSNFCE    = 'C'
                                  AND VE.IDTPEMISVEND    = 'N'
                                  AND VE.CDFILIAL        = FI.CDFILIAL
                                  AND FI.CDEMPRESA       = P_CDEMPRESA
                                  AND FI.CDINSCESTA      = P_CDINSCESTA
                                UNION ALL
                               /******** NÚMERAÇÃO INUTILIZADA *******/
                               SELECT '1' AS CAMPO2, '0' AS CAMPO3, '65' AS CDMODDOCFISC, 'I' AS IDSTATUSNFCE, I.CDSERIENFCE AS CDSERIE,
                                      I.NRNOTAFISCALCE AS NRNOTAFISC, 0 AS VRCONTABILNF, 0 AS VRDESITVEND, ''  AS NRACESSONFE,
                                      TRUNC(I.DTHRINUTNFCE) AS DTEMISSAO, 0 AS VRIMPOSTONF, 0 AS VRBASECALC, I.CDFILIAL,
                                      '' AS NRSEQVENDA, I.CDCAIXA, I.DTENTRVENDA AS DTENTRSAID, 'S' AS IDENTRSAIDOP, 'I' AS IDSTATUS,
                                      '' AS IDORIGDESTNF, 0 AS QTDEPARC
                                 FROM INUTILIZANFCE I, FILIAL F
                                WHERE I.CDFILIAL    = F.CDFILIAL
                                  AND F.CDEMPRESA   = P_CDEMPRESA
                                  AND F.CDINSCESTA  = P_CDINSCESTA
                                  AND TRUNC(I.DTHRINUTNFCE) BETWEEN P_DTINICIAL AND P_DTFINAL
                                  AND I.IDTPAMBNFCE = '1')NF)LOOP

         IF C_REGC100.IDSTATUS = 'C' OR C_REGC100.IDSTATUSNFE = 'D' OR C_REGC100.IDSTATUSNFE = 'I' THEN
            V_DADOS_2 := '|';
         ELSE
            IF C_REGC100.IDENTRSAIDOP = 'E' THEN
               V_DADOS_2 := TO_CHAR(C_REGC100.DTENTRSAID,'ddmmyyyy') || '|';
            ELSE
               V_DADOS_2 := TO_CHAR(C_REGC100.DTEMISSAO,'ddmmyyyy') || '|';
            END IF;
         END IF;

         /* verifica a situacao do documento
         IF C_REGC100.IDENTRSAIDOP = 'E' THEN
            IF C_REGC100.IDSTATUS = 'C' THEN
               /* documentos cancelados
               V_DADOS_2 := '02|';
            ELSE
               IF NOT C_REGC100.DTENTRSAID BETWEEN P_DTINICIAL AND P_DTFINAL THEN
                  /* documentos de entrada fora do periodo
                  V_DADOS_2 := '01|';
               ELSE
                  V_DADOS_2 := '00|';
               END IF;
            END IF;
         ELSE
            IF C_REGC100.IDSTATUS = 'C' THEN
               /* documentos cancelados
               V_DADOS_2 := '02|';
            ELSE
               IF NOT C_REGC100.DTENTRSAID BETWEEN P_DTINICIAL AND P_DTFINAL THEN
                  /* documentos de entrada fora do periodo
                  V_DADOS_2 := '01|';
               ELSE
                  V_DADOS_2 := '00|';
               END IF;
            END IF;
         END IF;
         /* valor utilizado para o campo valores recolhidos ou a recolher, extra apuracao - E110
         IF V_DADOS_2 = '01|' AND C_REGC100.IDENTRSAIDOP = 'S' THEN
            V_VRDEBESP := NVL(V_VRDEBESP,0)+ C_REGC100.VRIMPOSTONF;
         END IF;
         */

         V_VRDEBESP := 0;
         /* valor total de imposto fora do periodo - nf saida */
         V_VRFORAPER := 0;
         IF (C_REGC100.SITU_DOC IN ('01', '07')) AND (C_REGC100.IDENTRSAIDOP = 'S') THEN
            BEGIN
               SELECT SUM(VRIMPOSTONF)
               INTO V_VRFORAPER
               FROM IMPOSTONF IP, IMPOSTO IM
               WHERE CDFILIAL        = C_REGC100.CDFILIAL
                 AND NRLANCTONF      = C_REGC100.NRLANCTONF
                 AND CDFISCALNF      = '1'
                 AND NVL(IDIMPOSTONF,'1') <> '3'
                 AND IP.CDIMPOSTO    = IM.CDIMPOSTO
                 AND IM.CDIMPOSTONFE = P_CDIMPOSTO;
            EXCEPTION
               WHEN NO_DATA_FOUND THEN
                  V_VRFORAPER := 0;
            END;
            V_TOTFORPER_S := NVL(V_TOTFORPER_S,0)+NVL(V_VRFORAPER,0);
         END IF;

         /* valor total de imposto fora do periodo - nf entrada
         V_VRFORAPER_E := 0;
         IF (V_DADOS_2 = '01|') AND (C_REGC100.IDENTRSAIDOP = 'E') THEN
            BEGIN
               SELECT SUM(VRIMPOSTONF)
               INTO V_VRFORAPER_E
               FROM IMPOSTONF
               WHERE CDFILIAL = C_REGC100.CDFILIAL
                 AND NRLANCTONF = C_REGC100.NRLANCTONF;
            EXCEPTION
               WHEN NO_DATA_FOUND THEN
                  V_VRFORAPER_E := 0;
            END;
            V_TOTFORPER_E :=  NVL(V_TOTFORPER_E,0)+NVL(V_VRFORAPER_E,0);
         END IF;
         */

         INSERT INTO ARQMAGNETICO
            (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
         VALUES
            ('19'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_REGC100.DADOS_1||V_DADOS_2||C_REGC100.DADOS_3, P_NRSEQARQMAG);
         V_CONTREGC :=  NVL(V_CONTREGC,0) + 1;
         V_SEQUENCIAL := LPAD(RTRIM(TO_CHAR(TO_NUMBER('1'))),3,'0');

         /* CODIGO DO PARTICIPANTE */
         SELECT MAX(CDCHAVEREG)
           INTO V_COD_PAR
           FROM TMP_REGDADOSSPED
          WHERE CDCHAVEREG = C_REGC100.COD_PAR
            AND CDREGISTRO = '0150';

         IF (V_COD_PAR IS NULL) AND (C_REGC100.COD_PAR IS NOT NULL) THEN
            V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
            INSERT INTO TMP_REGDADOSSPED
              (CDREGISTRO, CDCONTREGI, CDCHAVEREG)
            VALUES
              ('0150', V_SEQUPROD, C_REGC100.COD_PAR);
         END IF;

         /*REGISTRO C101 - INFORMAÇÃO COMPLEMENTAR DOS DOCUMENTOS FISCAIS QUANDO DAS
          OPERAÇÕES INTERESTADUAIS DESTINADAS A CONSUMIDOR FINAL NÃO CONTRIBUINTE EC 87/15*/
         FOR C_REGC101 IN (SELECT '|C101'                                                           || '|' ||
                                  REPLACE(LTRIM(TO_CHAR(VRFCP,       '999999999990.00')), '.', ',') || '|' ||
                                  REPLACE(LTRIM(TO_CHAR(VRDIFALDEST, '999999999990.00')), '.', ',') || '|' ||
                                  REPLACE(LTRIM(TO_CHAR(VRDIFALORIG, '999999999990.00')), '.', ',') || '|'  AS ARQC101
                             FROM (SELECT SUM(ROUND(DECODE(C_REGC100.IDENTRSAIDOP,'S',I.VRIMPOFCP,     DECODE(C.IDTIPOCFOP,'D',I.VRIMPOFCP,     0)),2)) AS VRFCP,
                                          SUM(ROUND(DECODE(C_REGC100.IDENTRSAIDOP,'S',I.VRIMPOPARTDEST,DECODE(C.IDTIPOCFOP,'D',I.VRIMPOPARTDEST,0)),2)) AS VRDIFALDEST,
                                          SUM(ROUND(DECODE(C_REGC100.IDENTRSAIDOP,'S',I.VRIMPOPARTREME,DECODE(C.IDTIPOCFOP,'D',I.VRIMPOPARTREME,0)),2)) AS VRDIFALORIG
                                     FROM ITEMPROIMPOS I, IMPOSTO IM, CFOPPADRAO C
                                    WHERE I.CDFILIAL      = C_REGC100.CDFILIAL
                                      AND I.NRLANCTONF    = C_REGC100.NRLANCTONF
                                      AND I.CDIMPOSTO     = IM.CDIMPOSTO
                                      AND IM.CDIMPOSTONFE = P_CDIMPOSTO
                                      AND I.CDFISCOPERIT  = C.CDCFOPPADRAO
                                      AND C_REGC100.CDMODDOCFISC = '55')
                            WHERE VRFCP > 0 OR VRDIFALDEST > 0 OR VRDIFALORIG > 0) LOOP

            INSERT INTO ARQMAGNETICO
               (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
            VALUES
               ('19'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_REGC101.ARQC101 , P_NRSEQARQMAG);
            V_CONTREGC   :=  NVL(V_CONTREGC,0) + 1;
            V_SEQUENCIAL := LPAD(RTRIM(TO_CHAR(TO_NUMBER('1'))),3,'0');
         END LOOP;

         V_COD_PAR := null;

         /*REGISTRO C110 - OBSERVAÇÃO DO DOCUMENTO*/
         FOR C_REGC110 IN (SELECT '|C110'                                  ||'|'||
                                  LPAD(RTRIM(TO_CHAR(V_SEQADIC)),6,'0')    ||'|'||
                                  'CUPOM FISCAL REFERENCIADO - COO NÚMERO '||TRIM(D.NRCOOCUPOMNF)||'|'  AS DSREGC110,
                                  '|C114'                                  ||'|'||
                                  '2D'                                     ||'|'||
                                  SUBSTR(D.NRSERIEIMPNF,1,21)              ||'|'||
                                  SUBSTR(LPAD(D.NRCOOCUPOMNF,10,'0'),5,6)  ||'|'||
                                  TO_CHAR(C_REGC100.DTEMISSAO,'DDMMYYYY')  ||'|' AS DSREGC114
                             FROM DADOSNF D, NOTAFISCAL N
                            WHERE D.NRLANCTONF  = C_REGC100.NRLANCTONF
                              AND D.CDFILIAL    = C_REGC100.CDFILIAL
                              AND D.NRECFCUPOMNF IS NOT NULL
                              AND D.NRLANCTONF  = N.NRLANCTONF
                              AND D.CDFILIAL    = N.CDFILIAL
                              AND C_REGC100.CDMODDOCFISC <> '65'
                              AND NOT ((N.IDSTATUSNFE = 'A') OR (N.CDMODDOCFISC = '55')))LOOP

            INSERT INTO ARQMAGNETICO
               (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
            VALUES
               ('19'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_REGC110.DSREGC110 , P_NRSEQARQMAG);
            V_CONTREGC :=  NVL(V_CONTREGC,0) + 1;
            V_SEQUENCIAL := LPAD(RTRIM(TO_CHAR(TO_NUMBER('1'))),3,'0');

            /*REGISTRO C114 - CUPOM FISCAL REFERENCIADO*/
            INSERT INTO ARQMAGNETICO
               (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
            VALUES
               ('19'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_REGC110.DSREGC114 , P_NRSEQARQMAG);
            V_CONTREGC :=  NVL(V_CONTREGC,0) + 1;
            V_SEQUENCIAL := LPAD(RTRIM(TO_CHAR(TO_NUMBER('1'))),3,'0');
            V_SEQADIC := V_SEQADIC +1;
         END LOOP;

         /*REGISTRO C110 - OBSERVAÇÃO DO DOCUMENTO -- DADOSADIC*/
         FOR C_REGC110 IN (SELECT D.DSDADOADIC AS DSREGC110
                             FROM DADOSADIC D, NOTAFISCAL N
                            WHERE D.NRLANCTONF = C_REGC100.NRLANCTONF
                              AND D.CDFILIAL   = C_REGC100.CDFILIAL
                              AND D.NRLANCTONF = N.NRLANCTONF
                              AND D.CDFILIAL   = N.CDFILIAL
                              AND C_REGC100.CDMODDOCFISC <> '65'
                              AND NOT ((N.IDSTATUSNFE = 'A') OR (N.CDMODDOCFISC = '55')))LOOP

            INSERT INTO ARQMAGNETICO
               (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
            VALUES
               ('19'||LPAD(RTRIM(V_CONTREGC), 8, '0'), '|C110|'||LPAD(RTRIM(TO_CHAR(V_SEQADIC)),6,'0')||'|'||TRIM(SUBSTR(C_REGC110.DSREGC110, 0,499))||'|', P_NRSEQARQMAG);
            V_CONTREGC   := NVL(V_CONTREGC,0) + 1;
            V_SEQUENCIAL := LPAD(RTRIM(TO_CHAR(TO_NUMBER('1'))),3,'0');

            V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
            INSERT INTO TMP_REGDADOSSPED
               (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO1)
            VALUES
               ('0450', V_SEQUPROD, LPAD(RTRIM(TO_CHAR(V_SEQADIC)),6,'0'), TRIM(SUBSTR(C_REGC110.DSREGC110, 0, 499)));
            V_SEQUENCIAL := LPAD(RTRIM(TO_CHAR(TO_NUMBER('1'))),3,'0');
            V_SEQADIC    := V_SEQADIC +1;
         END LOOP;

         V_GERAC113 := 'N';
         /* C113 - documento fiscal referenciado */
         FOR C_REGC113 IN (SELECT REG        ||'|'||
                                  IND_OPER   ||'|'||
                                  IND_EMIT   ||'|'||
                                  REPLACE(REPLACE(REPLACE(REPLACE(COD_PART,'.'),'-'),'/'),' ') ||'|'||
                                  COD_MOD    ||'|'||
                                  SER        ||'|'||
                                  SUB        ||'|'||
                                  NUM_DOC    ||'|'||
                                  DT_DOC     ||'|'||
                                  CASE WHEN TO_NUMBER(P_VERSAO) >= 11 THEN CHV_DOCe ||'|' ELSE '' END AS DSREG_C113,
                                  COD_PART, CDFORNECED
                             FROM (SELECT '|C113' AS REG,
                                          '0' AS IND_OPER,
                                          DECODE(SUBSTR(NP.NRACESSONFE,7,14),REPLACE(REPLACE(REPLACE(I.NRINSJURIEST,'-',''),'.',''),'/',''),'0','1') AS IND_EMIT,
                                          'F'||NVL(F.CDFORNECED,NVL(NP.NRINSJURIEST,SUBSTR(NP.NRACESSONFE,7,14))) AS  COD_PART,
                                          NVL(NP.CDMODDOCFISC,SUBSTR(NP.NRACESSONFE,21,2)) AS COD_MOD,
                                          NVL(NP.CDSERIE,SUBSTR(NP.NRACESSONFE,23,3)) AS SER,
                                          '' AS SUB,
                                          NVL(NP.NRNOTAFISC,SUBSTR(NP.NRACESSONFE,26,9)) AS NUM_DOC,
                                          TO_CHAR(NP.DTEMISSAO,'ddmmyyyy') AS DT_DOC,
                                          NP.NRACESSONFE AS CHV_DOCe,
                                          'F'||F.CDFORNECED AS CDFORNECED
                                     FROM NFPRODRURAL NP, FORNECEDOR F, INSCRESTAD I
                                    WHERE NP.CDFILIAL     = C_REGC100.CDFILIAL
                                      AND NP.NRLANCTONF   = C_REGC100.NRLANCTONF
                                      AND I.CDINSCESTA    = P_CDINSCESTA
                                      AND C_REGC100.CDMODDOCFISC <> '65'
                                      AND NVL(NP.NRINSJURIEST,SUBSTR(NP.NRACESSONFE,7,14)) = REPLACE(REPLACE(REPLACE(F.NRINSJURFORN(+),'-',''),'.',''),'/','')))LOOP
            IF V_GERAC113 = 'N' THEN
               INSERT INTO ARQMAGNETICO
                  (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
               VALUES
                  ('19'||LPAD(RTRIM(V_CONTREGC), 8, '0'), '|C110|'||LPAD(RTRIM(TO_CHAR(V_SEQADIC)),6,'0')||'|'||'NOTAS FISCAIS DE PRODUTOR RURAL REFERENCIADAS A NF: '||C_REGC100.NRNOTAFISC||'|', P_NRSEQARQMAG);
               V_CONTREGC   := NVL(V_CONTREGC,0) + 1;
               V_SEQUENCIAL := LPAD(RTRIM(TO_CHAR(TO_NUMBER('1'))),3,'0');

               V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
               INSERT INTO TMP_REGDADOSSPED
                  (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO1)
               VALUES
                  ('0450', V_SEQUPROD, LPAD(RTRIM(TO_CHAR(V_SEQADIC)),6,'0'), 'NOTAS FISCAIS DE PRODUTOR RURAL REFERENCIADAS A NF: '||C_REGC100.NRNOTAFISC);
               V_SEQUENCIAL := LPAD(RTRIM(TO_CHAR(TO_NUMBER('1'))),3,'0');
               V_SEQADIC    := V_SEQADIC +1;
            END IF;
            V_GERAC113 := 'S';

            /* verifica se o cnpj está cadastrado no sistema - o registro 0150 é obrigatório */
            IF C_REGC113.CDFORNECED IS NOT NULL THEN

               /* CODIGO DO PARTICIPANTE */
               SELECT MAX(CDCHAVEREG)
                 INTO V_COD_PAR
                 FROM TMP_REGDADOSSPED
                WHERE CDCHAVEREG = C_REGC113.CDFORNECED
                  AND CDREGISTRO = '0150';

               IF (V_COD_PAR IS NULL) AND (C_REGC113.CDFORNECED IS NOT NULL) THEN
                  V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
                  INSERT INTO TMP_REGDADOSSPED
                    (CDREGISTRO, CDCONTREGI, CDCHAVEREG)
                  VALUES
                    ('0150', V_SEQUPROD, C_REGC113.CDFORNECED);
               END IF;
            END IF;
            V_CDFORNECED := '';

            INSERT INTO ARQMAGNETICO
               (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
            VALUES
               ('19'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_REGC113.DSREG_C113, P_NRSEQARQMAG);
            V_CONTREGC   := NVL(V_CONTREGC,0) + 1;
         END LOOP;

         /*QUANDO A OPERAÇÃO FOR A PRAZO PARA AS ENTRADAS NOS MODELOS 1 E 1A DEVER SER GERADOS OS REGISTROS REFERENTES A FATURA*/
         IF (C_REGC100.CDMODDOCFISC IN ('01','1A')) AND (C_REGC100.QTDEPARC > 1) THEN
            /*REGISTRO C140*/
            FOR C_REGC140 IN (SELECT '|C140'                                                               ||'|'||
                                     DECODE(N.IDENTRSAIDOP,'E','1','S','0')                                ||'|'||
                                     DECODE(F.IDTPTITULOCRED,'XX','',F.IDTPTITULOCRED)                     ||'|'||
                                     TRIM(DECODE(F.IDTPTITULOCRED,'99',F.DSTPTITULOCRED,''))               ||'|'||
                                     LTRIM(N.NRNOTAFISC,'0')                                               ||'|'||
                                     LPAD(RTRIM(TO_CHAR(C_REGC100.QTDEPARC)),2,'0')                        ||'|'||
                                     REPLACE(LTRIM(TO_CHAR(SUM(C.VRORIGPAG),'999999999990.00')), '.', ',') ||'|' AS DSREG_C140
                                FROM NOTAFISCAL N, FORNECEDOR F, CONTAPAGAR C
                               WHERE N.CDFILIAL   = C_REGC100.CDFILIAL
                                 AND N.NRLANCTONF = C_REGC100.NRLANCTONF
                                 AND N.CDFORNECED = F.CDFORNECED
                                 AND N.CDFILIAL   = C.CDFILIAL
                                 AND N.NRLANCTONF = C.NRLANCTONF
                               GROUP BY N.IDENTRSAIDOP, F.IDTPTITULOCRED, F.DSTPTITULOCRED,
                                     N.NRNOTAFISC, C_REGC100.QTDEPARC) LOOP

               INSERT INTO ARQMAGNETICO
                  (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
               VALUES
                  ('19'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_REGC140.DSREG_C140, P_NRSEQARQMAG);
               V_CONTREGC   := NVL(V_CONTREGC,0) + 1;
            END LOOP;

            /*REGISTRO C141*/
            FOR C_REGC141 IN (SELECT '|C141'                                                               ||'|'||
                                     LPAD(RTRIM(TO_CHAR(C.NRPARCELAPAG)),2,'0')                             ||'|'||
                                     TO_CHAR(C.DTORIGVENPAG,'DDMMYYYY')                                    ||'|'||
                                     REPLACE(LTRIM(TO_CHAR(SUM(C.VRORIGPAG),'999999999990.00')), '.', ',') ||'|' AS DSREG_C141
                                FROM CONTAPAGAR C
                               WHERE C.CDFILIAL   = C_REGC100.CDFILIAL
                                 AND C.NRLANCTONF = C_REGC100.NRLANCTONF
                               GROUP BY C.NRPARCELAPAG, C.DTORIGVENPAG
                               ORDER BY C.NRPARCELAPAG) LOOP

               INSERT INTO ARQMAGNETICO
                  (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
               VALUES
                  ('19'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_REGC141.DSREG_C141, P_NRSEQARQMAG);
               V_CONTREGC   := NVL(V_CONTREGC,0) + 1;
            END LOOP;
         END IF;

         BEGIN
            SELECT IDATUESTTPOP
              INTO V_IDATUESTTPOP
              FROM TIPOOPERAC
             WHERE CDTIPOOPER   = C_REGC100.CDTIPOOPER
               AND IDENTRSAIDOP = C_REGC100.IDENTRSAIDOP;
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               V_IDATUESTTPOP := 'N';
         END;

         /*REGISTRO C170*/
         FOR C_REGC170 IN (SELECT COD_ITEM       || '|' ||
                                  DESCR_COMPL    || '|' ||
                                  QTD            || '|' AS PARTE1,
                                                    '|' ||
                                  VL_ITEM        || '|' ||
                                  VL_DESC        || '|' ||
                                  IND_MOV        || '|' ||
                                  CST_ICMS       || '|' ||
                                  CFOP           || '|' ||
                                  CFOP           || '|' || -- natureza da operacao campo 12
                                  VL_BC_ICMS     || '|' ||
                                  ALIQ_ICMS      || '|' ||
                                  VL_ICMS        || '|' ||
                                  VL_BC_ICMS_ST  || '|' || --16
                                  ALIQ_ST        || '|' || --17
                                  VL_ICMS_ST     || '|' || --18
                                  ''             || '|' || -- indicador de apurao do IPI CAMPO 19
                                  CST_IPI        || '|' || -- cst ipi campo 20
                                  '' 		        || '|' || -- Cdigo enquadramento IPI campo 21
                                  VL_BC_IPI      || '|' || --22
                                  ALIQ_IPI       || '|' || --23
                                  VL_IPI         || '|' || --24
                                  CST_PIS        || '|' || -- cst pis   campo 25
                                  VL_BC_PIS      || '|' ||
                                  ALIQ_PIS       || '|' ||
                                  ''   		    || '|' || -- quantidade base de calculo
                                  ''             || '|' || -- aliquota pis quantidade
                                  VL_PIS         || '|' ||
                                  CST_COFINS     || '|' || -- cst cofins campo 31
                                  VL_BC_COFINS   || '|' ||
                                  ALIQ_COFINS    || '|' ||
                                  ''	          || '|' || -- quantidade base de calculo
                                  ''             || '|' || -- aliquota cofins quantidade
                                  VL_COFINS      || '|' ||
                                  COD_CTA        || '|' ||
                                  CASE WHEN P_VERSAO >= '013' THEN VL_ABAT_NT || '|' ELSE '' END AS ARQ_C170,  -- codigo da conta analitica contabil deb/cred
                                  CDPRODUTO, CFOP AS CDFISCOPERIT, DSCDFISOPEIT, CDCLASFISC, COD_CTA, SGUNIDADE, VRFATOCONV, CDEXPPROD, IDPRODEST
                             FROM (/* NOTAS NÃO ELETRÓNICAS COM E SEM CARGA TRIBUTÁRIA */
                                  SELECT NVL(PA.CDARVPROD,PR.CDARVPROD) AS COD_ITEM,
                                         DECODE(C_REGC100.IDENTRSAIDOP, 'E', TRIM(RETIRA_CARACTER_ESPECIAL(IT.DSPRODEMIS, 'S'))) AS DESCR_COMPL,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(IT.QTITEMPROD,3), '999999999990.000')), '.', ',') AS QTD,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(NVL(IT.VRTOTAITEM,0),2)+ROUND(NVL(VRENCARGOIMPXML,0),2), '999999999990.00')), '.', ',') AS VL_ITEM,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(NVL(IT.VRENCARGODESC,0),2), '999999999990.00')), '.', ',') AS VL_DESC,
                                         DECODE(NVL(V_IDATUESTTPOP,'N'),'N','1','0') AS IND_MOV,
                                         LPAD(NVL(IP.CDSITUTRIBIT,0),3,'0') AS CST_ICMS,
                                         IP.CDFISCOPERIT AS CFOP,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(CASE WHEN DT.NRSEQDETITMAPA IS NULL OR DT.IDTIPOITMAPR = 'VI'
                                                                          THEN NVL(VALOR_IMPOSTO_ITEM_NFE_CARGA(IP.CDFILIAL,IP.NRLANCTONF,IP.NRSEQITPROD,'B','I','1'),0)
                                                                          ELSE 0 END +
                                                                     DECODE(V_IDTPCARGATRIB,'O',0,DECODE(V_SGESTADO,'SP',0,NVL(VALOR_IMPOSTO_ITEM_NFE_CARGA(IP.CDFILIAL,IP.NRLANCTONF,IP.NRSEQITPROD,'B','C','1'),0))), 2), '999999999990.00')), '.', ',') AS VL_BC_ICMS,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(IP.CDFISCALIT, '1', DECODE(DT.NRSEQDETITMAPA,'',IP.VRALIQITEM, 0), 0) ,2), '999999999990.00')), '.', ',') AS ALIQ_ICMS,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(CASE WHEN DT.NRSEQDETITMAPA IS NULL OR DT.IDTIPOITMAPR = 'VI'
                                                                          THEN NVL(VALOR_IMPOSTO_ITEM_NFE_CARGA(IP.CDFILIAL,IP.NRLANCTONF,IP.NRSEQITPROD,'I','I','1'),0)
                                                                          ELSE 0 END +
                                                                     DECODE(V_IDTPCARGATRIB,'O',0,DECODE(C_REGC100.IDENTRSAIDOP,'S',NVL(VALOR_IMPOSTO_ITEM_NFE_CARGA(IP.CDFILIAL,IP.NRLANCTONF,IP.NRSEQITPROD,'I','C','1'),0),
                                                                                                                                    DECODE(V_SGESTADO,'SP',0,NVL(VALOR_IMPOSTO_ITEM_NFE_CARGA(IP.CDFILIAL,IP.NRLANCTONF,IP.NRSEQITPROD,'I','C','1'),0)))),2), '999999999990.00')), '.', ',') AS VL_ICMS,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_CDIMPOSTRIB, 'B','1'),2), '999999999990.00')), '.', ',') AS VL_BC_ICMS_ST,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_CDIMPOSTRIB, 'A','1') + VALOR_FECP_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_CDIMPOSTRIB, 'A','1'),2), '999999999990.00')), '.', ',') AS ALIQ_ST,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_CDIMPOSTRIB, 'I','1') + VALOR_FECP_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_CDIMPOSTRIB, 'I','1'),2), '999999999990.00')), '.', ',') AS VL_ICMS_ST,
                                         (SELECT MAX(CDSITUTRIBITNFE)
                                            FROM ITEMPROIMPOS N, IMPOSTO IM
                                           WHERE IP.CDFILIAL     = N.CDFILIAL
                                             AND IP.NRLANCTONF   = N.NRLANCTONF
                                             AND IP.NRSEQITPROD  = N.NRSEQITPROD
                                             AND IM.CDIMPOSTO    = N.CDIMPOSTO
                                             AND N.NRITPROIMPOS  = '1'
                                             AND IM.CDIMPOSTONFE = V_IPI)  AS CST_IPI,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_IPI, 'B','1'),2), '999999999990.00')), '.', ',') AS VL_BC_IPI,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_IPI, 'A','1'),2), '999999999990.00')), '.', ',') AS ALIQ_IPI,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_IPI, 'I','1'),2), '999999999990.00')), '.', ',') AS VL_IPI,
                                         (SELECT MAX(CDSITUTRIBITNFE)
                                            FROM ITEMPROIMPOS N, IMPOSTO IM
                                           WHERE IP.CDFILIAL     = N.CDFILIAL
                                             AND IP.NRLANCTONF   = N.NRLANCTONF
                                             AND IP.NRSEQITPROD  = N.NRSEQITPROD
                                             AND IM.CDIMPOSTO    = N.CDIMPOSTO
                                             AND N.NRITPROIMPOS  = '1'
                                             AND IM.CDIMPOSTONFE = V_PIS) AS CST_PIS,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_PIS, 'B','1'),2), '999999999990.00')), '.', ',') AS VL_BC_PIS,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_PIS, 'A','1'),2), '999999999990.00')), '.', ',') AS ALIQ_PIS,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_PIS, 'I','1'),2), '999999999990.00')), '.', ',') AS VL_PIS,
                                         (SELECT MAX(CDSITUTRIBITNFE)
                                            FROM ITEMPROIMPOS N, IMPOSTO IM
                                           WHERE IP.CDFILIAL     = N.CDFILIAL
                                             AND IP.NRLANCTONF   = N.NRLANCTONF
                                             AND IP.NRSEQITPROD  = N.NRSEQITPROD
                                             AND IM.CDIMPOSTO    = N.CDIMPOSTO
                                             AND N.NRITPROIMPOS  = '1'
                                             AND IM.CDIMPOSTONFE = V_COFINS) AS CST_COFINS,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_COFINS, 'B','1'),2), '999999999990.00')), '.', ',') AS VL_BC_COFINS,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_COFINS, 'A','1'),2), '999999999990.00')), '.', ',') AS ALIQ_COFINS,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_COFINS, 'I','1'),2), '999999999990.00')), '.', ',') AS VL_COFINS,
                                         CONTCTBL_SPED(C_REGC100.IDENTRSAIDOP, NVL(PA.CDPRODUTO,PR.CDPRODUTO), C_REGC100.CDTIPOOPER, C_REGC100.FILIAL) AS COD_CTA,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(IP.IDIMPDESONERAIT,'S',NVL(IP.VRIMPOSTOIT,0),0),2), '999999999990.00')), '.', ',') AS VL_ABAT_NT,
                                         NVL(PA.CDPRODUTO,PR.CDPRODUTO) AS CDPRODUTO, IT.DSCDFISOPEIT, IT.CDPRODNCMTRANS AS CDCLASFISC, PR.SGUNIDADE, PR.VRFATOCONV,
                                         '' AS CDEXPPROD, DECODE(PA.CDPRODUTO,PR.CDPRODUTO,'S','N') AS IDPRODEST
                                    FROM ITEMPRODUTO IT, PRODUTO PR, PRODUTO PA, ITEMPROIMPOS IP, IMPOSTO IM, DETITMAPARECUP DT
                                   WHERE IT.CDFILIAL      = C_REGC100.CDFILIAL
                                     AND IT.NRLANCTONF    = C_REGC100.NRLANCTONF
                                     AND IM.CDIMPOSTONFE  = P_CDIMPOSTO
                                     AND IM.CDIMPOSTO     = IP.CDIMPOSTO
                                     AND IT.CDFILIAL      = IP.CDFILIAL
                                     AND IT.NRLANCTONF    = IP.NRLANCTONF
                                     AND IT.NRSEQITPROD   = IP.NRSEQITPROD
                                     AND IT.CDPRODUTO     = PR.CDPRODUTO
                                     AND PR.CDPRODESTO    = PA.CDPRODUTO(+)
                                     AND IP.NRITPROIMPOS  =  '1'
                                     AND C_REGC100.CDMODDOCFISC NOT IN ('55','65')
                                     AND ROUND(IT.QTITEMPROD,3) > 0
                                     AND IP.CDFILIAL      = DT.CDFILIAL(+)
                                     AND IP.NRLANCTONF    = DT.NRLANCTONF(+)
                                     AND IP.CDIMPOSTO     = DT.CDIMPOSTO(+)
                                     AND IP.NRSEQITPROD   = DT.NRSEQITPROD(+)
                                     AND IP.NRITPROIMPOS  = DT.NRITPROIMPOS(+)
                                   UNION ALL
                                  /*NOTAS DE ENTRADA ELETRÓNICAS COM E SEM CARGA TRIBUTÁRIA */
                                  SELECT NVL(PA.CDARVPROD,PR.CDARVPROD) AS COD_ITEM,
                                         DECODE(C_REGC100.IDENTRSAIDOP, 'E', TRIM(RETIRA_CARACTER_ESPECIAL(IT.DSPRODEMIS, 'S'))) AS DESCR_COMPL,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(IT.QTITEMPROD,3), '999999999990.000')), '.', ',') AS QTD,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(NVL(IT.VRTOTAITEM,0),2)+ROUND(NVL(VRENCARGOIMPXML,0),2), '999999999990.00')), '.', ',') AS VL_ITEM,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(NVL(IT.VRENCARGODESC,0),2), '999999999990.00')), '.', ',') AS VL_DESC,
                                         DECODE(NVL(V_IDATUESTTPOP,'N'),'N','1','0') AS IND_MOV,
                                         LPAD(NVL(IP.CDSITUTRIBIT,0),3,'0') AS CST_ICMS,
                                         IP.CDFISCOPERIT AS CFOP,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(CASE WHEN DT.NRSEQDETITMAPA IS NULL OR DT.IDTIPOITMAPR = 'VI'
                                                                          THEN NVL(VALOR_IMPOSTO_ITEM_NFE_CARGA(IP.CDFILIAL,IP.NRLANCTONF,IP.NRSEQITPROD,'B','I','1'),0)
                                                                          ELSE 0 END +
                                                                     DECODE(V_IDTPCARGATRIB,'O',0,DECODE(V_SGESTADO,'SP',0,NVL(VALOR_IMPOSTO_ITEM_NFE_CARGA(IP.CDFILIAL,IP.NRLANCTONF,IP.NRSEQITPROD,'B','C','1'),0))),2), '999999999990.00')), '.', ',') AS VL_BC_ICMS,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(IP.CDFISCALIT, '1', DECODE(DT.NRSEQDETITMAPA,'',IP.VRALIQITEM,0), 0),2), '999999999990.00')), '.', ',') AS ALIQ_ICMS,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(CASE WHEN DT.NRSEQDETITMAPA IS NULL OR DT.IDTIPOITMAPR = 'VI'
                                                                          THEN NVL(VALOR_IMPOSTO_ITEM_NFE_CARGA(IP.CDFILIAL,IP.NRLANCTONF,IP.NRSEQITPROD,'I','I','1'),0)
                                                                          ELSE 0 END +
                                                                     DECODE(V_IDTPCARGATRIB,'O',0,DECODE(V_SGESTADO,'SP',0,NVL(VALOR_IMPOSTO_ITEM_NFE_CARGA(IP.CDFILIAL,IP.NRLANCTONF,IP.NRSEQITPROD,'I','C','1'),0))),2), '999999999990.00')), '.', ',') AS VL_ICMS,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_CDIMPOSTRIB, 'B','1'),2), '999999999990.00')), '.', ',') AS VL_BC_ICMS_ST,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_CDIMPOSTRIB, 'A','1') + VALOR_FECP_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_CDIMPOSTRIB, 'A','1'),2), '999999999990.00')), '.', ',') AS ALIQ_ST,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_CDIMPOSTRIB, 'I','1') + VALOR_FECP_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_CDIMPOSTRIB, 'I','1'),2), '999999999990.00')), '.', ',') AS VL_ICMS_ST,
                                         (SELECT MAX(CDSITUTRIBITNFE)
                                            FROM ITEMPROIMPOS N, IMPOSTO IM
                                           WHERE IP.CDFILIAL     = N.CDFILIAL
                                             AND IP.NRLANCTONF   = N.NRLANCTONF
                                             AND IP.NRSEQITPROD  = N.NRSEQITPROD
                                             AND IM.CDIMPOSTO    = N.CDIMPOSTO
                                             AND N.NRITPROIMPOS  = '1'
                                             AND IM.CDIMPOSTONFE = V_IPI) AS CST_IPI,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_IPI, 'B','1'),2), '999999999990.00')), '.', ',') AS VL_BC_IPI,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_IPI, 'A','1'),2), '999999999990.00')), '.', ',') AS ALIQ_IPI,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_IPI, 'I','1'),2), '999999999990.00')), '.', ',') AS VL_IPI,
                                         (SELECT MAX(CDSITUTRIBITNFE)
                                            FROM ITEMPROIMPOS N, IMPOSTO IM
                                           WHERE IP.CDFILIAL     = N.CDFILIAL
                                             AND IP.NRLANCTONF   = N.NRLANCTONF
                                             AND IP.NRSEQITPROD  = N.NRSEQITPROD
                                             AND IM.CDIMPOSTO    = N.CDIMPOSTO
                                             AND N.NRITPROIMPOS  = '1'
                                             AND IM.CDIMPOSTONFE = V_PIS) AS CST_PIS,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_PIS, 'B','1'),2), '999999999990.00')), '.', ',') AS VL_BC_PIS,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_PIS, 'A','1'),2), '999999999990.00')), '.', ',') AS ALIQ_PIS,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_PIS, 'I','1'),2), '999999999990.00')), '.', ',') AS VL_PIS,
                                         (SELECT MAX(CDSITUTRIBITNFE)
                                            FROM ITEMPROIMPOS N, IMPOSTO IM
                                           WHERE IP.CDFILIAL     = N.CDFILIAL
                                             AND IP.NRLANCTONF   = N.NRLANCTONF
                                             AND IP.NRSEQITPROD  = N.NRSEQITPROD
                                             AND IM.CDIMPOSTO    = N.CDIMPOSTO
                                             AND N.NRITPROIMPOS  = '1'
                                             AND IM.CDIMPOSTONFE = V_COFINS) AS CST_COFINS,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_COFINS, 'B','1'),2), '999999999990.00')), '.', ',') AS VL_BC_COFINS,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_COFINS, 'A','1'),2), '999999999990.00')), '.', ',') AS ALIQ_COFINS,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_COFINS, 'I','1'),2), '999999999990.00')), '.', ',') AS VL_COFINS,
                                         CONTCTBL_SPED(C_REGC100.IDENTRSAIDOP, NVL(PA.CDPRODUTO,PR.CDPRODUTO), C_REGC100.CDTIPOOPER, C_REGC100.FILIAL) AS COD_CTA,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(IP.IDIMPDESONERAIT,'S',NVL(IP.VRIMPOSTOIT,0),0),2), '999999999990.00')), '.', ',') AS VL_ABAT_NT,
                                         NVL(PA.CDPRODUTO,PR.CDPRODUTO) AS CDPRODUTO, IT.DSCDFISOPEIT, IT.CDPRODNCMTRANS AS CDCLASFISC, PR.SGUNIDADE, PR.VRFATOCONV,
                                         (SELECT CP.CDEXPPROD FROM CODEXPPROD CP WHERE CP.CDLIVROMAG = P_LIVROMAG AND CP.CDPRODUTO = IT.CDPRODUTO) AS CDEXPPROD,
                                         DECODE(PA.CDPRODUTO,PR.CDPRODUTO,'S','N') AS IDPRODEST
                                    FROM ITEMPRODUTO IT, PRODUTO PR, PRODUTO PA, ITEMPROIMPOS IP, IMPOSTO IM, DETITMAPARECUP DT
                                   WHERE IT.CDFILIAL      = C_REGC100.CDFILIAL
                                     AND IT.NRLANCTONF    = C_REGC100.NRLANCTONF
                                     AND IM.CDIMPOSTONFE  = P_CDIMPOSTO
                                     AND IM.CDIMPOSTO     = IP.CDIMPOSTO
                                     AND IT.CDFILIAL      = IP.CDFILIAL
                                     AND IT.NRLANCTONF    = IP.NRLANCTONF
                                     AND IT.NRSEQITPROD   = IP.NRSEQITPROD
                                     AND IT.CDPRODUTO     = PR.CDPRODUTO
                                     AND PR.CDPRODESTO    = PA.CDPRODUTO(+)
                                     AND IP.NRITPROIMPOS  =  '1'
                                     AND C_REGC100.IDENTRSAIDOP = 'E'
                                     AND C_REGC100.CDMODDOCFISC = '55'
                                     AND C_REGC100.IDSTATUSNFE <> 'A'
                                     AND ROUND(IT.QTITEMPROD,3) > 0
                                     AND IP.CDFILIAL      = DT.CDFILIAL(+)
                                     AND IP.NRLANCTONF    = DT.NRLANCTONF(+)
                                     AND IP.CDIMPOSTO     = DT.CDIMPOSTO(+)
                                     AND IP.NRSEQITPROD   = DT.NRSEQITPROD(+)
                                     AND IP.NRITPROIMPOS  = DT.NRITPROIMPOS(+)
                                   UNION ALL
                                   /*NOTAS DE SAÍDA ELETRÔNICAS COM E SEM CARGA TRIBUTÁRIA - COM CÓDIGO DE INFORMAÇÃO ADICIONAL PARA O ESTADO DE PE */
                                  SELECT NVL(PA.CDARVPROD,PR.CDARVPROD) AS COD_ITEM,
                                         ' ' AS DESCR_COMPL,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(IT.QTITEMPROD,3), '999999999990.000')), '.', ',') AS QTD,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(NVL(IT.VRTOTAITEM,0),2)+ROUND(NVL(VRENCARGOIMPXML,0),2), '999999999990.00')), '.', ',') AS VL_ITEM,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(NVL(IT.VRENCARGODESC,0),2), '999999999990.00')), '.', ',') AS VL_DESC,
                                         DECODE(NVL(V_IDATUESTTPOP,'N'),'N','1','0') AS IND_MOV,
                                         LPAD(NVL(IP.CDSITUTRIBIT,0),3,'0') AS CST_ICMS,
                                         IP.CDFISCOPERIT AS CFOP,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(CASE WHEN DT.NRSEQDETITMAPA IS NULL OR DT.IDTIPOITMAPR = 'VI'
                                                                          THEN NVL(VALOR_IMPOSTO_ITEM_NFE_CARGA(IP.CDFILIAL,IP.NRLANCTONF,IP.NRSEQITPROD,'B','I','1'),0)
                                                                          ELSE 0 END +
                                                                     DECODE(V_IDTPCARGATRIB,'O',0,DECODE(V_SGESTADO,'SP',0,NVL(VALOR_IMPOSTO_ITEM_NFE_CARGA(IP.CDFILIAL,IP.NRLANCTONF,IP.NRSEQITPROD,'B','C','1'),0))),2), '999999999990.00')), '.', ',') AS VL_BC_ICMS,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(IP.CDFISCALIT, '1', DECODE(DT.NRSEQDETITMAPA,'',IP.VRALIQITEM,0), 0),2), '999999999990.00')), '.', ',') AS ALIQ_ICMS,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(CASE WHEN DT.NRSEQDETITMAPA IS NULL OR DT.IDTIPOITMAPR = 'VI'
                                                                          THEN NVL(VALOR_IMPOSTO_ITEM_NFE_CARGA(IP.CDFILIAL,IP.NRLANCTONF,IP.NRSEQITPROD,'I','I','1'),0)
                                                                          ELSE 0 END +
                                                                     DECODE(V_IDTPCARGATRIB,'O',0,DECODE(V_SGESTADO,'SP',0,NVL(VALOR_IMPOSTO_ITEM_NFE_CARGA(IP.CDFILIAL,IP.NRLANCTONF,IP.NRSEQITPROD,'I','C','1'),0))),2), '999999999990.00')), '.', ',') AS VL_ICMS,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_CDIMPOSTRIB, 'B','1'),2), '999999999990.00')), '.', ',') AS VL_BC_ICMS_ST,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_CDIMPOSTRIB, 'A','1') + VALOR_FECP_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_CDIMPOSTRIB, 'A','1'),2), '999999999990.00')), '.', ',') AS ALIQ_ST,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_CDIMPOSTRIB, 'I','1') + VALOR_FECP_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_CDIMPOSTRIB, 'I','1'),2), '999999999990.00')), '.', ',') AS VL_ICMS_ST,
                                         (SELECT MAX(CDSITUTRIBITNFE)
                                            FROM ITEMPROIMPOS N, IMPOSTO IM
                                           WHERE IP.CDFILIAL     = N.CDFILIAL
                                             AND IP.NRLANCTONF   = N.NRLANCTONF
                                             AND IP.NRSEQITPROD  = N.NRSEQITPROD
                                             AND IM.CDIMPOSTO    = N.CDIMPOSTO
                                             AND N.NRITPROIMPOS  = '1'
                                             AND IM.CDIMPOSTONFE = V_IPI) AS CST_IPI,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_IPI, 'B','1'),2), '999999999990.00')), '.', ',') AS VL_BC_IPI,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_IPI, 'A','1'),2), '999999999990.00')), '.', ',') AS ALIQ_IPI,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_IPI, 'I','1'),2), '999999999990.00')), '.', ',') AS VL_IPI,
                                         (SELECT MAX(CDSITUTRIBITNFE)
                                            FROM ITEMPROIMPOS N, IMPOSTO IM
                                           WHERE IP.CDFILIAL     = N.CDFILIAL
                                             AND IP.NRLANCTONF   = N.NRLANCTONF
                                             AND IP.NRSEQITPROD  = N.NRSEQITPROD
                                             AND IM.CDIMPOSTO    = N.CDIMPOSTO
                                             AND N.NRITPROIMPOS  = '1'
                                             AND IM.CDIMPOSTONFE = V_PIS) AS CST_PIS,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_PIS, 'B','1'),2), '999999999990.00')), '.', ',') AS VL_BC_PIS,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_PIS, 'A','1'),2), '999999999990.00')), '.', ',') AS ALIQ_PIS,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_PIS, 'I','1'),2), '999999999990.00')), '.', ',') AS VL_PIS,
                                         (SELECT MAX(CDSITUTRIBITNFE)
                                            FROM ITEMPROIMPOS N, IMPOSTO IM
                                           WHERE IP.CDFILIAL     = N.CDFILIAL
                                             AND IP.NRLANCTONF   = N.NRLANCTONF
                                             AND IP.NRSEQITPROD  = N.NRSEQITPROD
                                             AND IM.CDIMPOSTO    = N.CDIMPOSTO
                                             AND N.NRITPROIMPOS  = '1'
                                             AND IM.CDIMPOSTONFE = V_COFINS) AS CST_COFINS,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_COFINS, 'B','1'),2), '999999999990.00')), '.', ',') AS VL_BC_COFINS,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_COFINS, 'A','1'),2), '999999999990.00')), '.', ',') AS ALIQ_COFINS,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(VALOR_IMPOSTO_ITEM_NFE(IP.CDFILIAL, IP.NRLANCTONF, IP.NRSEQITPROD, V_COFINS, 'I','1'),2), '999999999990.00')), '.', ',') AS VL_COFINS,
                                         CONTCTBL_SPED(C_REGC100.IDENTRSAIDOP, NVL(PA.CDPRODUTO,PR.CDPRODUTO), C_REGC100.CDTIPOOPER, C_REGC100.FILIAL) AS COD_CTA,
                                         REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(IP.IDIMPDESONERAIT,'S',NVL(IP.VRIMPOSTOIT,0),0),2), '999999999990.00')), '.', ',') AS VL_ABAT_NT,
                                         NVL(PA.CDPRODUTO,PR.CDPRODUTO) AS CDPRODUTO, IT.DSCDFISOPEIT, IT.CDPRODNCMTRANS AS CDCLASFISC, PR.SGUNIDADE, PR.VRFATOCONV,
                                         CP.CDEXPPROD, DECODE(PA.CDPRODUTO,PR.CDPRODUTO,'S','N') AS IDPRODEST
                                    FROM ITEMPRODUTO IT, PRODUTO PR, PRODUTO PA, ITEMPROIMPOS IP, IMPOSTO IM, DETITMAPARECUP DT, CODEXPPROD CP
                                   WHERE V_SGESTADO       = 'PE'
                                     AND IT.CDFILIAL      = C_REGC100.CDFILIAL
                                     AND IT.NRLANCTONF    = C_REGC100.NRLANCTONF
                                     AND IM.CDIMPOSTONFE  = P_CDIMPOSTO
                                     AND IM.CDIMPOSTO     = IP.CDIMPOSTO
                                     AND IT.CDFILIAL      = IP.CDFILIAL
                                     AND IT.NRLANCTONF    = IP.NRLANCTONF
                                     AND IT.NRSEQITPROD   = IP.NRSEQITPROD
                                     AND IT.CDPRODUTO     = PR.CDPRODUTO
                                     AND PR.CDPRODESTO    = PA.CDPRODUTO(+)
                                     AND IP.NRITPROIMPOS  =  '1'
                                     AND C_REGC100.IDENTRSAIDOP = 'S'
                                     AND C_REGC100.CDMODDOCFISC = '55'
                                     AND ROUND(IT.QTITEMPROD,3) > 0
                                     AND IP.CDFILIAL      = DT.CDFILIAL(+)
                                     AND IP.NRLANCTONF    = DT.NRLANCTONF(+)
                                     AND IP.CDIMPOSTO     = DT.CDIMPOSTO(+)
                                     AND IP.NRSEQITPROD   = DT.NRSEQITPROD(+)
                                     AND IP.NRITPROIMPOS  = DT.NRITPROIMPOS(+)
                                     AND CP.CDLIVROMAG    = P_LIVROMAG
                                     AND CP.CDPRODUTO     = IT.CDPRODUTO
                                     AND CP.CDEXPPROD     IS NOT NULL)) LOOP

            /* CODIGO DO CFOP */
            SELECT MAX(CDCHAVEREG)
              INTO V_COD_NAT
              FROM TMP_REGDADOSSPED
             WHERE CDCHAVEREG = C_REGC170.CDFISCOPERIT
               AND CDREGISTRO = '0400';

            IF (V_COD_NAT IS NULL) AND (C_REGC170.CDFISCOPERIT IS NOT NULL) THEN
               V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
               INSERT INTO TMP_REGDADOSSPED
                 (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO1, CDCAMPO2)
               VALUES
                 ('0400', V_SEQUPROD, C_REGC170.CDFISCOPERIT, C_REGC170.DSCDFISOPEIT, C_REGC100.IDENTRSAIDOP);
            END IF;
            V_COD_NAT := NULL;

            V_UNIDADE := C_REGC170.SGUNIDADE||CASE WHEN C_REGC170.IDPRODEST = 'N' THEN CONT_FATCONVERSAO_SPED(C_REGC170.SGUNIDADE, C_REGC170.VRFATOCONV) ELSE '' END;

            /* UNIDADE DE MEDIDA */
            SELECT MAX(CDCHAVEREG)
              INTO V_UNID
              FROM TMP_REGDADOSSPED
             WHERE CDCHAVEREG = V_UNIDADE
               AND CDREGISTRO = '0190';

            IF (V_UNID IS NULL) AND (V_UNIDADE IS NOT NULL) THEN
               V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
               INSERT INTO TMP_REGDADOSSPED
                 (CDREGISTRO, CDCONTREGI, CDCAMPO1, CDCAMPO2, CDCAMPO3, CDCHAVEREG)
               VALUES
                 ('0190', V_SEQUPROD, C_REGC170.SGUNIDADE, C_REGC170.VRFATOCONV, SUBSTR(V_UNIDADE,LENGTH(C_REGC170.SGUNIDADE)+1,LENGTH(V_UNIDADE)), V_UNIDADE);
            END IF;
            V_UNID := NULL;

            /* CODIGO DO PRODUTO */
            SELECT MAX(CDCHAVEREG)
              INTO V_PRODUTO
              FROM TMP_REGDADOSSPED
             WHERE CDCHAVEREG = C_REGC170.CDPRODUTO
               AND CDREGISTRO = '0200';
            IF (V_PRODUTO IS NULL) AND (C_REGC170.CDPRODUTO IS NOT NULL) THEN
               V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
               INSERT INTO TMP_REGDADOSSPED
                 (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO3)
               VALUES
                 ('0200', V_SEQUPROD, C_REGC170.CDPRODUTO, C_REGC170.CDCLASFISC);
            END IF;
            V_PRODUTO := NULL;

            /* PLANO DE CONTAS REFERENCIAL */
            SELECT MAX(CDCHAVEREG)
              INTO V_CONTCTBL
              FROM TMP_REGDADOSSPED
             WHERE CDCHAVEREG = C_REGC170.COD_CTA
               AND CDREGISTRO = '0500';

            IF (V_CONTCTBL IS NULL) AND (C_REGC170.COD_CTA IS NOT NULL) THEN
               V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
               INSERT INTO TMP_REGDADOSSPED
                  (CDREGISTRO, CDCONTREGI, CDCHAVEREG)
               VALUES
                  ('0500', V_SEQUPROD, C_REGC170.COD_CTA);
            END IF;
            V_CONTCTBL := NULL;

            INSERT INTO ARQMAGNETICO
               (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
            VALUES
               ('19'||LPAD(RTRIM(V_CONTREGC), 8, '0'), '|C170'|| '|' ||V_SEQUENCIAL|| '|' || C_REGC170.PARTE1 ||V_UNIDADE||C_REGC170.ARQ_C170, P_NRSEQARQMAG);
            V_SEQUENCIAL := LPAD(RTRIM(TO_CHAR(TO_NUMBER(RTRIM(V_SEQUENCIAL))+1)), 3,'0');
            V_CONTREGC :=  NVL(V_CONTREGC,0) + 1;

            IF (V_SGESTADO = 'PE') AND (C_REGC170.CDEXPPROD IS NOT NULL) AND (P_VERSAO >= '013') THEN
               INSERT INTO ARQMAGNETICO
                  (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
               VALUES
                  ('19'||LPAD(RTRIM(V_CONTREGC), 8, '0'), '|C177'|| '|' || C_REGC170.CDEXPPROD || '|', P_NRSEQARQMAG);
               V_CONTREGC :=  NVL(V_CONTREGC,0) + 1;
            END IF;
         END LOOP;

         IF P_VERSAO NOT IN ( '001', '002') THEN
            /*REGISTRO C190*/
            /*É PASSADO O CSOSN APENAS QUANDO A EMPRESA É DO SIMPLES E O FORNECEDOR TAMBÉM, CASO A EMPRESA NAO SEJA DO SIMPLES, MAIS O FORNECEDOR
            SIM, MANDA O CST MESMO. NESTE CASO A EMPRESA NAO É SIMPLES */
            FOR C_REGC190 IN(SELECT ('|C190'      || '|' ||
                                     T.CST_ICMS   || '|' ||
                                     T.CFOP       || '|' ||
                                     REPLACE(LTRIM(TO_CHAR(ROUND(NVL(T.ALIQ_ICMS,0),2), '999999999990.00')), '.', ',') || '|' ||
                                     REPLACE(LTRIM(TO_CHAR(ROUND(NVL(T.VL_OPR,0),2),    '999999999990.00')), '.', ',') || '|' ||
                                     REPLACE(LTRIM(TO_CHAR(ROUND(NVL(T.VL_BC_ICMS,0),2),'999999999990.00')), '.', ',') || '|' ||
                                     REPLACE(LTRIM(TO_CHAR(ROUND(NVL(T.VL_ICMS,0),2),   '999999999990.00')), '.', ',') || '|' ||
                                     REPLACE(LTRIM(TO_CHAR(ROUND(NVL(T.BC_ST,0),2),     '999999999990.00')), '.', ',') || '|' ||
                                     REPLACE(LTRIM(TO_CHAR(ROUND(NVL(T.IMP_ST,0),2),    '999999999990.00')), '.', ',') || '|' ||
                                     REPLACE(LTRIM(TO_CHAR(ROUND(NVL(T.VL_RED_BC,0),2), '999999999990.00')), '.', ',') || '|' ||
                                     REPLACE(LTRIM(TO_CHAR(ROUND(NVL(VL_IPI,0),2),      '999999999990.00')), '.', ',') || '|' ||
                                     '' || '|') ARQ_C190,
                                     T.VL_ICMS, T.CFOP AS COD_NAT, T.CST_ICMS, T.ALIQ_ICMS
                               FROM (/*NOTAS DE SAIDA COM E SEM CARGA TRIBUTÁRIA*/
                                     SELECT I.CDSITUTRIBIT AS CST_ICMS,
                                            I.CDFISCOPERIT AS CFOP,
                                            CASE WHEN DT.NRSEQDETITMAPA IS NULL OR DT.IDTIPOITMAPR = 'VI'
                                                 THEN DECODE(I.CDFISCALIT,'1',I.VRALIQITEM,0)
                                                 ELSE 0 END AS ALIQ_ICMS,
                                            SUM(I.VRCONTITIMP)+NVL(SUM(VALOR_REDUCAO(I.CDFILIAL, I.NRLANCTONF, I.CDSITUTRIBIT, I.NRSEQITPROD, I.CDFISCOPERIT, NULL, NULL, NULL)),0) VL_OPR,
                                            SUM(CASE WHEN DT.NRSEQDETITMAPA IS NULL OR DT.IDTIPOITMAPR = 'VI'
                                                     THEN NVL(VALOR_IMPOSTO_ITEM_NFE_CARGA(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'B','I','1'),0) +
                                                          DECODE(V_IDTPCARGATRIB,'O',0,DECODE(V_SGESTADO,'SP',0,NVL(VALOR_IMPOSTO_ITEM_NFE_CARGA(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'B','C','1'),0)))
                                                     ELSE 0 END) AS VL_BC_ICMS,
                                            SUM(CASE WHEN DT.NRSEQDETITMAPA IS NULL OR DT.IDTIPOITMAPR = 'VI'
                                                     THEN NVL(VALOR_IMPOSTO_ITEM_NFE_CARGA(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'I','I','1'),0) +
                                                          DECODE(V_IDTPCARGATRIB,'O',0,NVL(VALOR_IMPOSTO_ITEM_NFE_CARGA(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'I','C','1'),0))
                                                     ELSE 0 END) AS VL_ICMS,
                                            NVL(SUM(CASE WHEN DT.NRSEQDETITMAPA IS NULL OR DT.IDTIPOITMAPR = 'VI'
                                                         THEN DECODE(I.CDFISCALIT,'1',VALOR_REDUCAO(I.CDFILIAL, I.NRLANCTONF, I.CDSITUTRIBIT, I.NRSEQITPROD, I.CDFISCOPERIT, NULL, NULL, NULL),0)
                                                         ELSE 0 END),0) AS VL_RED_BC,
                                            SUM((SELECT NVL(SUM(VRIMPOSTOIT),0)
                                                   FROM ITEMPROIMPOS IT, IMPOSTO IM
                                                  WHERE (IT.CDFILIAL     = I.CDFILIAL           ) AND
                                                        (IT.NRLANCTONF   = I.NRLANCTONF         ) AND
                                                        (IT.CDIMPOSTO    = IM.CDIMPOSTO         ) AND
                                                        (IT.NRITPROIMPOS = '1'                  ) AND
                                                        (IT.CDFISCALIT   = '1'                  ) AND
                                                        (IM.CDIMPOSTONFE = '10'                 ) AND
                                                        I.NRSEQITPROD = IT.NRSEQITPROD         )) AS VL_IPI,
                                            '' AS COD_OBS,
                                            SUM(VALOR_IMPOSTO_ITEM_NFE(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'80','B','1')) AS BC_ST,
                                            SUM(VALOR_IMPOSTO_ITEM_NFE(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'80','I','1') + VALOR_FECP_ITEM_NFE(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'80','I','1')) AS IMP_ST
                                       FROM ITEMPROIMPOS I, ITEMPRODUTO P, IMPOSTO IM, DETITMAPARECUP DT
                                      WHERE I.CDFILIAL      = C_REGC100.CDFILIAL
                                        AND I.NRLANCTONF    = C_REGC100.NRLANCTONF
                                        AND C_REGC100.IDENTRSAIDOP = 'S'
                                        AND C_REGC100.CDMODDOCFISC <> '65'
                                        AND I.NRITPROIMPOS  = '1'
                                        AND IM.CDIMPOSTONFE = P_CDIMPOSTO
                                        AND IM.CDIMPOSTO    = I.CDIMPOSTO
                                        AND I.CDFILIAL      = DT.CDFILIAL(+)
                                        AND I.NRLANCTONF    = DT.NRLANCTONF(+)
                                        AND I.CDIMPOSTO     = DT.CDIMPOSTO(+)
                                        AND I.NRSEQITPROD   = DT.NRSEQITPROD(+)
                                        AND I.NRITPROIMPOS  = DT.NRITPROIMPOS(+)
                                        AND I.CDFILIAL      = P.CDFILIAL
                                        AND I.NRLANCTONF    = P.NRLANCTONF
                                        AND I.NRSEQITPROD   = P.NRSEQITPROD
                                        AND (ROUND(P.QTITEMPROD,3) > 0 OR C_REGC100.SITU_DOC IN ('06','07'))
                                      GROUP BY I.CDSITUTRIBIT, I.CDFISCOPERIT, CASE WHEN DT.NRSEQDETITMAPA IS NULL OR DT.IDTIPOITMAPR = 'VI'
                                                                                    THEN DECODE(I.CDFISCALIT,'1',I.VRALIQITEM,0)
                                                                                    ELSE 0 END
                                      UNION ALL
                                     /*NOTAS DE ENTRADA COM E SEM CARGA TRIBUTÁRIA*/
                                     SELECT I.CDSITUTRIBIT AS CST_ICMS,
                                            I.CDFISCOPERIT AS CFOP,
                                            CASE WHEN DT.NRSEQDETITMAPA IS NULL OR DT.IDTIPOITMAPR = 'VI'
                                                 THEN DECODE(I.CDFISCALIT,'1',I.VRALIQITEM,0)
                                                 ELSE 0 END AS ALIQ_ICMS,
                                            SUM(I.VRCONTITIMP)+NVL(SUM(VALOR_REDUCAO(I.CDFILIAL, I.NRLANCTONF, I.CDSITUTRIBIT, I.NRSEQITPROD, I.CDFISCOPERIT, NULL, NULL, NULL)),0) VL_OPR,
                                            SUM(CASE WHEN DT.NRSEQDETITMAPA IS NULL OR DT.IDTIPOITMAPR = 'VI'
                                                     THEN NVL(VALOR_IMPOSTO_ITEM_NFE_CARGA(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'B','I','1'),0) +
                                                          DECODE(V_IDTPCARGATRIB,'O',0,DECODE(V_SGESTADO,'SP',0,NVL(VALOR_IMPOSTO_ITEM_NFE_CARGA(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'B','C','1'),0)))
                                                     ELSE 0 END) AS VL_BC_ICMS,
                                            SUM(CASE WHEN DT.NRSEQDETITMAPA IS NULL OR DT.IDTIPOITMAPR = 'VI'
                                                     THEN NVL(VALOR_IMPOSTO_ITEM_NFE_CARGA(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'I','I','1'),0) +
                                                          DECODE(V_IDTPCARGATRIB,'O',0,DECODE(V_SGESTADO,'SP',0,NVL(VALOR_IMPOSTO_ITEM_NFE_CARGA(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'I','C','1'),0)))
                                                     ELSE 0 END) AS VL_ICMS,
                                            NVL(SUM(CASE WHEN DT.NRSEQDETITMAPA IS NULL OR DT.IDTIPOITMAPR = 'VI'
                                                         THEN DECODE(I.CDFISCALIT,'1',VALOR_REDUCAO(I.CDFILIAL, I.NRLANCTONF, I.CDSITUTRIBIT, I.NRSEQITPROD, I.CDFISCOPERIT, NULL, NULL, NULL),0)
                                                         ELSE 0 END),0) AS VL_RED_BC,
                                            SUM((SELECT NVL(SUM(VRIMPOSTOIT),0)
                                                   FROM ITEMPROIMPOS IT, IMPOSTO IM
                                                  WHERE (IT.CDFILIAL     = I.CDFILIAL           ) AND
                                                        (IT.NRLANCTONF   = I.NRLANCTONF         ) AND
                                                        (IT.CDIMPOSTO    = IM.CDIMPOSTO         ) AND
                                                        (IT.NRITPROIMPOS = '1'                  ) AND
                                                        (IT.CDFISCALIT   = '1'                  ) AND
                                                        (IM.CDIMPOSTONFE = '10'                 ) AND
                                                        I.NRSEQITPROD = IT.NRSEQITPROD         )) AS VL_IPI,
                                            '' AS COD_OBS,
                                            SUM(VALOR_IMPOSTO_ITEM_NFE(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'80','B','1')) AS BC_ST,
                                            SUM(VALOR_IMPOSTO_ITEM_NFE(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'80','I','1') + VALOR_FECP_ITEM_NFE(I.CDFILIAL,I.NRLANCTONF,I.NRSEQITPROD,'80','I','1')) AS IMP_ST
                                       FROM ITEMPROIMPOS I, ITEMPRODUTO P, IMPOSTO IM, DETITMAPARECUP DT
                                      WHERE I.CDFILIAL      = C_REGC100.CDFILIAL
                                        AND I.NRLANCTONF    = C_REGC100.NRLANCTONF
                                        AND C_REGC100.IDENTRSAIDOP = 'E'
                                        AND C_REGC100.CDMODDOCFISC <> '65'
                                        AND I.NRITPROIMPOS  = '1'
                                        AND IM.CDIMPOSTONFE = P_CDIMPOSTO
                                        AND IM.CDIMPOSTO    = I.CDIMPOSTO
                                        AND I.CDFILIAL      = DT.CDFILIAL(+)
                                        AND I.NRLANCTONF    = DT.NRLANCTONF(+)
                                        AND I.CDIMPOSTO     = DT.CDIMPOSTO(+)
                                        AND I.NRSEQITPROD   = DT.NRSEQITPROD(+)
                                        AND I.NRITPROIMPOS  = DT.NRITPROIMPOS(+)
                                        AND I.CDFILIAL      = P.CDFILIAL
                                        AND I.NRLANCTONF    = P.NRLANCTONF
                                        AND I.NRSEQITPROD   = P.NRSEQITPROD
                                        AND (ROUND(P.QTITEMPROD,3) > 0 OR C_REGC100.SITU_DOC IN ('06','07'))
                                      GROUP BY I.CDSITUTRIBIT, I.CDFISCOPERIT, CASE WHEN DT.NRSEQDETITMAPA IS NULL OR DT.IDTIPOITMAPR = 'VI'
                                                                                    THEN DECODE(I.CDFISCALIT,'1',I.VRALIQITEM,0)
                                                                                    ELSE 0 END
                                      UNION ALL
                                     /*NFC-e*/
                                     SELECT NVL(LPAD(CDCSTPRODI,3,'0'), (CASE WHEN IM.IDTPIMPOSFIS = 'T' THEN '000'
                                                                              WHEN IM.IDTPIMPOSFIS = 'I' THEN '040'
                                                                              WHEN IM.IDTPIMPOSFIS = 'F' THEN '060'
                                                                              WHEN IM.IDTPIMPOSFIS = 'N' THEN '041' END)) AS CST_ICMS,
                                            NVL(CDCFOPPROD, '5102') AS CFOP,
                                            ROUND(IP.VRPEALPRODIT,2) AS ALIQ_ICMS,
                                            SUM(TRUNC((IT.QTPRODVEND  * (IT.VRUNITVEND+NVL(IT.VRUNITVENDCL,0))) - NVL(IT.VRDESITVEND,0) + NVL(IT.VRACRITVEND,0),2)) AS VL_OPR,
                                            SUM(CASE WHEN IM.IDTPIMPOSFIS = 'T' AND IM.CDIMPOSTONFE = P_CDIMPOSTO
                                                     THEN CASE WHEN IP.VRPRBCREDUICMS > 0
                                                               THEN IP.VRBASECALCREDUZ
                                                               ELSE TRUNC((IT.QTPRODVEND * (IT.VRUNITVEND+NVL(IT.VRUNITVENDCL,0))) - NVL(IT.VRDESITVEND,0) + NVL(IT.VRACRITVEND,0),2) END
                                                     ELSE 0 END) AS VL_BC_ICMS,
                                            SUM(CASE WHEN IM.IDTPIMPOSFIS = 'T' AND IM.CDIMPOSTONFE = P_CDIMPOSTO
                                                     THEN CASE WHEN IP.VRPRBCREDUICMS > 0
                                                               THEN IP.VRIMPOPRODREDUZ
                                                               ELSE TRUNC(VRIMPOPRODIT,2) END
                                                     ELSE 0 END) AS VL_ICMS,
                                            SUM(DECODE(IP.VRPRBCREDUICMS,0,0,IP.VRBCREDUZICMS)) AS VL_RED_BC,
                                            0 AS VL_IPI,
                                            '' AS COD_OBS,
                                            0 AS BC_ST,
                                            0 AS IMP_ST
                                       FROM ITEMVENDA IT, ITVENDAIMPOS IP, IMPOSTO IM
                                      WHERE IT.CDFILIAL     = C_REGC100.CDFILIAL
                                        AND IT.CDCAIXA      = C_REGC100.CDCAIXA
                                        AND IT.NRSEQVENDA   = C_REGC100.NRLANCTONF
                                        AND IT.CDFILIAL     = IP.CDFILIAL
                                        AND IT.CDCAIXA      = IP.CDCAIXA
                                        AND IT.NRSEQUITVEND = IP.NRSEQUITVEND
                                        AND IT.NRSEQVENDA   = IP.NRSEQVENDA
                                        AND IP.CDIMPOSTO    = IM.CDIMPOSTO
                                        AND NVL(C_REGC100.IDSTATUS,'A') <>  'C'
                                      GROUP BY NVL(LPAD(CDCSTPRODI,3,'0'), (CASE WHEN IM.IDTPIMPOSFIS = 'T' THEN '000'
                                                                 WHEN IM.IDTPIMPOSFIS = 'I' THEN '040'
                                                                 WHEN IM.IDTPIMPOSFIS = 'F' THEN '060'
                                                                 WHEN IM.IDTPIMPOSFIS = 'N' THEN '041' END)),
                                               CDCFOPPROD, IP.VRPEALPRODIT) T) LOOP
               INSERT INTO ARQMAGNETICO
                  (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
               VALUES
                  ('19'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_REGC190.ARQ_C190, P_NRSEQARQMAG);
               V_CONTREGC := NVL(V_CONTREGC,0) + 1;

               IF P_VERSAO >= '013' THEN
                  FOR C_REGC191 IN (SELECT '|C191'         || '|' ||
                                           REPLACE(LTRIM(TO_CHAR(SUM(CASE WHEN SUBSTR(IT.CDSITUTRIBIT,2,2) IN ('00','10','20','51','70','90') AND IM.CDIMPOSTONFE = '00'
                                                THEN ROUND(IT.VRADICFECP,2)
                                                ELSE 0 END),'999999999990.00')), '.', ',') || '|' ||
                                           REPLACE(LTRIM(TO_CHAR(SUM(CASE WHEN SUBSTR(IT.CDSITUTRIBIT,2,2) IN ('10','30','70','90') AND IM.CDIMPOSTONFE = '80'
                                                THEN ROUND(IT.VRADICFECP,2)
                                                ELSE 0 END),'999999999990.00')), '.', ',') || '|' ||
                                           REPLACE(LTRIM(TO_CHAR(SUM(CASE WHEN SUBSTR(IT.CDSITUTRIBIT,2,2) IN ('60')
                                                THEN ROUND(IT.VRADICFECP,2)
                                                ELSE 0 END),'999999999990.00')), '.', ',') || '|' AS ARQ_C191, IT.CDFISCOPERIT
                                      FROM ITEMPROIMPOS IT, ITEMPROIMPOS II, IMPOSTO IM
                                     WHERE IT.CDFILIAL     = C_REGC100.CDFILIAL
                                       AND IT.NRLANCTONF   = C_REGC100.NRLANCTONF
                                       AND IT.CDFISCOPERIT = C_REGC190.COD_NAT
                                       AND IT.CDSITUTRIBIT = C_REGC190.CST_ICMS
                                       AND IT.VRALIQITEM   = C_REGC190.ALIQ_ICMS
                                       AND IT.NRITPROIMPOS = '1'
                                       AND IT.CDFILIAL     = II.CDFILIAL
                                       AND IT.NRLANCTONF   = II.NRLANCTONF
                                       AND IT.NRSEQITPROD  = II.NRSEQITPROD
                                       AND II.CDFISCOPERIT = C_REGC190.COD_NAT
                                       AND II.CDSITUTRIBIT = C_REGC190.CST_ICMS
                                       AND II.CDIMPOSTO    = IM.CDIMPOSTO
                                       AND IM.CDIMPOSTONFE IN ('00','80')
                                       AND II.VRADICFECP   > 0
                                     GROUP BY IT.CDFISCOPERIT) LOOP
                      INSERT INTO ARQMAGNETICO
                         (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
                      VALUES
                         ('19'||LPAD(RTRIM(V_CONTREGC), 8, '0'), C_REGC191.ARQ_C191, P_NRSEQARQMAG);
                      V_CONTREGC := NVL(V_CONTREGC,0) + 1;
                  END LOOP;
               END IF;
            END LOOP;
         END IF;

         V_C195 := 'N';
         /* GERACAO DOS REGISTROS COM DIFERENCIAL DE ALIQUOTA E ANTECIPAÇÃO DE ICMS DO ARROZ*/
         FOR C_REGC197 IN (SELECT COD_AJ, DESCR_COMPL_AJ, COD_ITEM, IDTIPOITMAPR,
                                  REPLACE(LTRIM(TO_CHAR(ROUND(VL_BC_ICMS,2),'999999999990.00')), '.', ',') AS VL_BC_ICMS,
                                  REPLACE(LTRIM(TO_CHAR(ROUND(ALIQ_ICMS,2), '999999999990.00')), '.', ',') AS ALIQ_ICMS,
                                  REPLACE(LTRIM(TO_CHAR(ROUND(VL_ICMS,2),   '999999999990.00')), '.', ',') AS VL_ICMS,
                                  REPLACE(LTRIM(TO_CHAR(ROUND(VL_OUTROS,2), '999999999990.00')), '.', ',') AS VL_OUTROS,
                                  CDCFOPPADRAO, CDCLASFISC, CDPRODUTO
                             FROM (SELECT IM.CDAJUSTEITMAPA AS COD_AJ, IM.DSITEMMAPR AS DESCR_COMPL_AJ, '' AS COD_ITEM,
                                          0 AS VL_BC_ICMS, 0 AS ALIQ_ICMS,
                                          IM.VRITEMMAPR AS VL_ICMS,
                                          IM.VROUTROSITMAPR AS VL_OUTROS, IM.IDTIPOITMAPR,
                                          IM.CDCFOPPADRAO AS CDCFOPPADRAO, '' AS CDCLASFISC, '' AS CDPRODUTO
                                     FROM ITMAPARECUP IM
                                    WHERE IM.CDFILIAL     = C_REGC100.CDFILIAL
                                      AND IM.NRLANCTONF   = C_REGC100.NRLANCTONF
                                      AND C_REGC100.CDMODDOCFISC <> '65'
                                      AND IM.IDCOMPOEC197 = 'D'
                                    UNION ALL
                                   SELECT IM.CDAJUSTEITMAPA AS COD_AJ, IM.DSITEMMAPR AS DESCR_COMPL_AJ,
                                          NVL(PA.CDARVPROD,PR.CDARVPROD) AS COD_ITEM,
                                          SUM(DECODE(DT.IDSUBSTSOLIDST,'S',IT.VRBASECALCIT,DECODE(IT.CDFISCALIT,'1',IT.VRBASECALCIT,0))) AS VL_BC_ICMS,
                                          DECODE(DT.IDSUBSTSOLIDST,'S',IT.VRALIQITEM,DECODE(IT.CDFISCALIT,'1',IT.VRALIQITEM,0)) AS ALIQ_ICMS,
                                          SUM(ROUND(DECODE(DT.IDSUBSTSOLIDST,'S',DT.VRIMPOSTOIT,IT.VRIMPOSTOIT),2)) AS VL_ICMS,
                                          SUM(ROUND(IM.VROUTROSITMAPR,2)) AS VL_OUTROS, IM.IDTIPOITMAPR, '' AS CDCFOPPADRAO, IP.CDPRODNCMTRANS AS CDCLASFISC,
                                          NVL(PA.CDPRODUTO,PR.CDPRODUTO) AS CDPRODUTO
                                     FROM ITMAPARECUP IM, IMPOSTO IM, ITEMPROIMPOS IT, DETITMAPARECUP DT, PRODUTO PA, PRODUTO PR, ITEMPRODUTO IP
                                    WHERE IM.CDFILIAL     = C_REGC100.CDFILIAL
                                      AND IM.NRLANCTONF   = C_REGC100.NRLANCTONF
                                      AND C_REGC100.CDMODDOCFISC <> '65'
                                      AND IM.IDCOMPOEC197 = 'I'
                                      AND IM.CDFILIAL     = IT.CDFILIAL
                                      AND IM.NRLANCTONF   = IT.NRLANCTONF
                                      AND IT.CDIMPOSTO    = IM.CDIMPOSTO
                                      AND IM.CDIMPOSTONFE IN ('00','80')
                                      AND IT.CDIMPOSTO    = DT.CDIMPOSTO
                                      AND IM.NRSEQUMAPAPU = DT.NRSEQUMAPAPU
                                      AND IM.IDTIPOITMAPR = DT.IDTIPOITMAPR
                                      AND IM.NRSEQITMAPR  = DT.NRSEQITMAPR
                                      AND IT.CDFILIAL     = DT.CDFILIAL
                                      AND IT.NRLANCTONF   = DT.NRLANCTONF
                                      AND IT.NRSEQITPROD  = DT.NRSEQITPROD
                                      AND IT.NRITPROIMPOS = DT.NRITPROIMPOS
                                      AND IT.CDFILIAL     = IP.CDFILIAL
                                      AND IT.NRLANCTONF   = IP.NRLANCTONF
                                      AND IT.NRSEQITPROD  = IP.NRSEQITPROD
                                      AND DT.CDFILIAL     = IP.CDFILIAL
                                      AND DT.NRLANCTONF   = IP.NRLANCTONF
                                      AND DT.NRSEQITPROD  = IP.NRSEQITPROD
                                      AND PR.CDPRODUTO    = IP.CDPRODUTO
                                      AND PR.CDPRODESTO   = PA.CDPRODUTO(+)
                                      AND DT.IDTIPOITMAPR <> 'VI'
                                      AND ((IT.NRITPROIMPOS = '1' AND IT.CDFISCALIT = '1') OR (IT.NRITPROIMPOS = '3') OR (DT.IDSUBSTSOLIDST = 'S'))
                                    GROUP BY IM.CDAJUSTEITMAPA, IM.DSITEMMAPR, IT.CDFISCALIT, IT.VRALIQITEM, DT.IDSUBSTSOLIDST,
                                          NVL(PA.CDARVPROD,PR.CDARVPROD), IM.IDTIPOITMAPR, IP.CDPRODNCMTRANS, NVL(PA.CDPRODUTO,PR.CDPRODUTO)
                                    UNION ALL
                                   SELECT IM.CDAJUSTEITMAPA AS COD_AJ, IM.DSITEMMAPR AS DESCR_COMPL_AJ,
                                          NVL(PA.CDARVPROD,PR.CDARVPROD) AS COD_ITEM,
                                          SUM(DT.VROUTBASE) AS VL_BC_ICMS,
                                          NVL(DT.VROUTALIQ,0) AS ALIQ_ICMS,
                                          0 AS VL_ICMS,
                                          SUM(ROUND(DT.VROUTROSIMPIT,2)) AS VL_OUTROS, IM.IDTIPOITMAPR,
                                          IM.CDCFOPPADRAO, IP.CDPRODNCMTRANS AS CDCLASFISC,
                                          NVL(PA.CDPRODUTO,PR.CDPRODUTO) AS CDPRODUTO
                                     FROM ITMAPARECUP IM, DETITMAPARECUP DT, PRODUTO PA, PRODUTO PR, ITEMPRODUTO IP
                                    WHERE IM.CDFILIAL     = C_REGC100.CDFILIAL
                                      AND IM.NRLANCTONF   = C_REGC100.NRLANCTONF
                                      AND C_REGC100.CDMODDOCFISC <> '65'
                                      AND IM.IDCOMPOEC197 = 'I'
                                      AND IM.IDTIPOITMAPR = 'VI'
                                      AND IM.NRSEQUMAPAPU = DT.NRSEQUMAPAPU
                                      AND IM.IDTIPOITMAPR = DT.IDTIPOITMAPR
                                      AND IM.NRSEQITMAPR  = DT.NRSEQITMAPR
                                      AND DT.CDFILIAL     = IP.CDFILIAL
                                      AND DT.NRLANCTONF   = IP.NRLANCTONF
                                      AND DT.NRSEQITPROD  = IP.NRSEQITPROD
                                      AND PR.CDPRODUTO    = IP.CDPRODUTO
                                      AND PR.CDPRODESTO   = PA.CDPRODUTO(+)
                                    GROUP BY IM.CDAJUSTEITMAPA, IM.DSITEMMAPR,
                                          NVL(PA.CDARVPROD,PR.CDARVPROD), DT.VROUTALIQ,
                                          IM.IDTIPOITMAPR, IM.CDCFOPPADRAO, IP.CDPRODNCMTRANS,
                                          NVL(PA.CDPRODUTO,PR.CDPRODUTO)
                                    UNION ALL
                                   SELECT IM.CDAJUSTEITMAPA AS COD_AJ, IM.DSITEMMAPR AS DESCR_COMPL_AJ,
                                          NVL(PA.CDARVPROD,PR.CDARVPROD) AS COD_ITEM,
                                          SUM(DT.VROUTBASE) AS VL_BC_ICMS,
                                          NVL(DT.VROUTALIQ,0) AS ALIQ_ICMS,
                                          0 AS VL_ICMS,
                                          SUM(ROUND(DT.VROUTROSIMPIT,2)) AS VL_OUTROS, IM.IDTIPOITMAPR,
                                          IM.CDCFOPPADRAO, IP.CDCLASFISC AS CDCLASFISC,
                                          NVL(PA.CDPRODUTO,PR.CDPRODUTO) AS CDPRODUTO
                                     FROM ITMAPARECUP IM, DETITMAPARECUP DT, PRODUTO PA, PRODUTO PR, ITEMVENDA IP
                                    WHERE DT.CDFILIALVND   = C_REGC100.CDFILIAL
                                      AND DT.NRSEQVENDA    = C_REGC100.NRLANCTONF
                                      AND DT.CDCAIXA       = C_REGC100.CDCAIXA
                                      AND C_REGC100.CDMODDOCFISC = '65'
                                      AND IM.IDCOMPOEC197  = 'I'
                                      AND IM.IDTIPOITMAPR  = 'VI'
                                      AND IM.NRSEQUMAPAPU  = DT.NRSEQUMAPAPU
                                      AND IM.IDTIPOITMAPR  = DT.IDTIPOITMAPR
                                      AND IM.NRSEQITMAPR   = DT.NRSEQITMAPR
                                      AND DT.CDFILIALVND   = IP.CDFILIAL
                                      AND DT.CDCAIXA       = IP.CDCAIXA
                                      AND DT.NRSEQVENDA    = IP.NRSEQVENDA
                                      AND DT.NRSEQUITVEND  = IP.NRSEQUITVEND
                                      AND PR.CDPRODUTO     = IP.CDPRODUTO
                                      AND PR.CDPRODESTO    = PA.CDPRODUTO(+)
                                    GROUP BY IM.CDAJUSTEITMAPA, IM.DSITEMMAPR,
                                          NVL(PA.CDARVPROD,PR.CDARVPROD), DT.VROUTALIQ,
                                          IM.IDTIPOITMAPR, IM.CDCFOPPADRAO, IP.CDCLASFISC,
                                          NVL(PA.CDPRODUTO,PR.CDPRODUTO))
                            ORDER BY SUBSTR(COD_AJ,8,3), IDTIPOITMAPR, CDCFOPPADRAO, CDCLASFISC, CDPRODUTO) LOOP

             BEGIN
                SELECT LPAD(NVL(IT.CDITEMVARIAVEL,'0')||DECODE(C_REGC197.CDCFOPPADRAO,'','',SUBSTR(C_REGC197.DESCR_COMPL_AJ,2,3)),6,'0') AS COD_OBS,
                       TRIM(IT.DSAJUSTE) AS TXT
                  INTO V_CODC195, V_TXTC195
                  FROM ITEMVARAJEFD IT
                 WHERE IT.SGESTADO       = SUBSTR(C_REGC197.COD_AJ,1,2)
                   AND IT.CDITEMVARIAVEL = SUBSTR(C_REGC197.COD_AJ,8,3);
             EXCEPTION
                WHEN NO_DATA_FOUND THEN
                   V_CODC195 := '';
                   V_TXTC195 := '';
             END;

            /* CODIGO DO PRODUTO */
            SELECT MAX(CDCHAVEREG)
              INTO V_PRODUTO
              FROM TMP_REGDADOSSPED
             WHERE CDCHAVEREG = C_REGC197.CDPRODUTO
               AND CDREGISTRO = '0200';

            IF (V_PRODUTO IS NULL) AND (C_REGC197.CDPRODUTO IS NOT NULL) THEN
               V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
               INSERT INTO TMP_REGDADOSSPED
                 (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO3)
               VALUES
                 ('0200', V_SEQUPROD, C_REGC197.CDPRODUTO, C_REGC197.CDCLASFISC);
            END IF;
            V_PRODUTO := NULL;

             V_COD_OBS := NULL;
             SELECT MAX(CDCHAVEREG)
               INTO V_COD_OBS
               FROM TMP_REGDADOSSPED
              WHERE CDCHAVEREG = V_CODC195
                AND CDREGISTRO = '0460';

             IF (V_COD_OBS IS NULL) THEN
                V_SEQUPROD := NVL(V_SEQUPROD,0) + 1;
                INSERT INTO TMP_REGDADOSSPED
                   (CDREGISTRO, CDCONTREGI, CDCHAVEREG, CDCAMPO1)
                VALUES
                   ('0460', V_SEQUPROD, NVL(V_CODC195,SUBSTR(C_REGC197.COD_AJ,8,3)), V_TXTC195);
             END IF;

             IF (V_C195 IS NULL) OR (V_C195 <> SUBSTR(C_REGC197.COD_AJ,8,3)||CASE WHEN C_REGC197.CDCFOPPADRAO IS NOT NULL THEN SUBSTR(C_REGC197.DESCR_COMPL_AJ,2,3) ELSE '' END) THEN
                INSERT INTO ARQMAGNETICO
                   (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
                VALUES
                   ('19'||LPAD(RTRIM(V_CONTREGC), 8, '0'), '|C195'  || '|' || V_CODC195 || '|' || '' || '|', P_NRSEQARQMAG);
                V_CONTREGC := NVL(V_CONTREGC,0) + 1;
             END IF;

             V_REG_C197 := '|C197'                   || '|' ||
                           C_REGC197.COD_AJ          || '|' ||
                           C_REGC197.DESCR_COMPL_AJ  || '|' ||
                           C_REGC197.COD_ITEM        || '|' ||
                           C_REGC197.VL_BC_ICMS      || '|' ||
                           C_REGC197.ALIQ_ICMS       || '|' ||
                           C_REGC197.VL_ICMS         || '|' ||
                           C_REGC197.VL_OUTROS       || '|' ;
             INSERT INTO ARQMAGNETICO
               (NRORDREGARQ, DSREGARQMAG, NRSEQARQMAG)
             VALUES
               ('19'||LPAD(RTRIM(V_CONTREGC), 8, '0'), V_REG_C197, P_NRSEQARQMAG);
             V_CONTREGC := NVL(V_CONTREGC,0) + 1;

             V_C195 := SUBSTR(C_REGC197.COD_AJ,8,3)||CASE WHEN C_REGC197.CDCFOPPADRAO IS NOT NULL THEN SUBSTR(C_REGC197.DESCR_COMPL_AJ,2,3) ELSE '' END;
         END LOOP;
      END LOOP;
   END IF;

   IF V_CDSITUCRT <> '3' THEN  /*SIMPLES NACIONAL*/
       FOR C_REGC100 IN(SELECT ('|C100'                                                              || '|' ||
                                NF.CAMPO2                                                            || '|' ||
                                (CASE WHEN ((NF.CDSERIEENTR BETWEEN '890' AND '899') AND (NF.CDMODDOCFISC = '55')) THEN '1' ELSE NF.CAMPO3 END) || '|' ||
                                DECODE(NF.IDSTATUSNFE,'D','',DECODE(NF.IDSTATUS,'C','',REPLACE(REPLACE(REPLACE(REPLACE(NF.IDORIGDESTNF||DECODE(NF.IDORIGDESTNF, 'F', NF.CDFORNECED, DECODE(NF.IDORIGDESTNF, 'C', NF.CDCLIENTE , DECODE(NF.IDENTRSAIDOP, 'E', NF.CDFILIEMIT, NF.CDFILIRECE))),'.'),'-'),'/'),' '))) || '|' ||
                                NF.CDMODDOCFISC                                                      || '|' ||
                                DECODE(NF.IDSTATUSNFE, 'D', '04', DECODE(IDSTATUS,'C','02', DECODE(NF.IDENTRSAIDOP,'S', (CASE WHEN DTEMISSAO < P_DTINICIAL THEN DECODE(NF.CDTIPOOPER,'03','07',TIPOOPER_COMPL_S,'07','01') ELSE DECODE(NF.CDTIPOOPER,'03','06',TIPOOPER_COMPL_S,'06','00') END), (CASE WHEN ((NF.CDSERIEENTR BETWEEN '890' AND '899') AND (NF.CDMODDOCFISC = '55')) THEN '08'ELSE (CASE WHEN DTENTRSAID < P_DTINICIAL THEN DECODE(NF.CDTIPOOPER,'03','07',TIPOOPER_COMPL_E,'07','01')ELSE DECODE(NF.CDTIPOOPER,'03','06',TIPOOPER_COMPL_E,'06','00') END) END)))) ||'|'||
                                CASE WHEN LENGTH(NF.NRACESSONFE) = '44' THEN SUBSTR(NRACESSONFE,23,3) ELSE REPLACE(REPLACE(DECODE(NF.IDENTRSAIDOP, 'E', NF.CDSERIEENTR, NF.CDSERIE),'-',''),'.','') END   || '|' ||
                                DECODE(NF.IDENTRSAIDOP, 'E', LTRIM(NF.NRNOTAFISC,'0'), DECODE(NF.NRACESSONFE, '', LTRIM(REPLACE(LTRIM(NF.NRNOTAFISC, '0'),' ')),DECODE(NF.IDSTATUS,'C',LTRIM(NF.NRNOTAFISC,'0'),LTRIM(NF.NRNOTAFISCALELE, '0')) )  )|| '|' ||
                                NRACESSONFE                                                                                        || '|' ||  --chave da nota fiscal eletronica
                                DECODE(NF.IDSTATUSNFE, 'D', '', DECODE(NF.IDSTATUS, 'C', '', TO_CHAR(NF.DTEMISSAO,'ddmmyyyy')) )   || '|' ) AS DADOS_1,
                                (REPLACE(LTRIM(TO_CHAR(ROUND(NF.VRCONTABILNF,2), '999999999990.00')), '.', ',')                    || '|' ||
                                DECODE(NF.IDSTATUSNFE, 'D', '', DECODE(NF.IDSTATUS, 'C', '', DECODE(NVL(NF.QTDEPARC,0),0,'2',1,'0','1'))) || '|' || -- campo 13
                                DECODE(NF.IDSTATUSNFE, 'D', '', DECODE(NF.IDSTATUS, 'C', '', REPLACE(LTRIM(TO_CHAR((SELECT SUM(ROUND(VRENCARGODESC,2)) FROM ITEMPRODUTO WHERE CDFILIAL = NF.CDFILIAL AND NRLANCTONF = NF.NRLANCTONF AND NRSEQITPROD IS NOT NULL), '999999999990.00')), '.', ','))) || '|' ||
                                REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(NF.IDSTATUSNFE, 'D', '', DECODE(NF.IDSTATUS, 'C', '', VALOR_ENCARGO_NFE(NF.CDFILIAL, NF.NRLANCTONF, V_IDDESCONTO, '03'))),2), '999999999990.00')), '.', ',') || '|' ||  -- abatimento no tributado e nao comercial desconto ICMS
                                DECODE(NF.IDSTATUSNFE, 'D', '', DECODE(NF.IDSTATUS, 'C', '', REPLACE(LTRIM(TO_CHAR(ROUND(NF.VRPRODUTOS,2), '999999999990.00')), '.', ','))) || '|' ||
                                DECODE(NF.IDSTATUSNFE, 'D', '', DECODE(NF.IDSTATUS, 'C', '', RPAD(NVL(NF.IDPGTOFRETE, '9'), 1 , ' ')))                                      || '|' ||
                                REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(NF.IDSTATUSNFE, 'D', '', DECODE(NF.IDSTATUS, 'C', '', VALOR_ENCARGO_NFE(NF.CDFILIAL, NF.NRLANCTONF, V_IDFRETE,  '01'))),2), '999999999990.00')), '.', ',') || '|' ||
                                REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(NF.IDSTATUSNFE, 'D', '', DECODE(NF.IDSTATUS, 'C', '', VALOR_ENCARGO_NFE(NF.CDFILIAL, NF.NRLANCTONF, V_IDSEGUR,  '02'))),2), '999999999990.00')), '.', ',') || '|' ||
                                /*REPLACE(LTRIM(TO_CHAR(ROUND(DECODE(NF.IDSTATUS, 'C', '', ABS(VALOR_IMPOSTO_NF(NF.CDFILIAL, NF.NRLANCTONF,V_CDIMPOSTRIB, 'I','1')) + ABS(VALOR_IMPOSTO_NF(NF.CDFILIAL, NF.NRLANCTONF, V_IPI, 'I','1'))),2), '999999999990.00')), '.', ',')  || '|' || --campo20*/
