CREATE OR REPLACE
PROCEDURE REPLICACAO_DOCUMENTOS
(P_CDFILIAL    IN NOTAFISCAL.CDFILIAL%TYPE,
 P_NRLANCTONF  IN NOTAFISCAL.NRLANCTONF%TYPE,
 P_CDFILIPROC  IN NOTAFISCAL.CDFILIAL%TYPE,
 P_PRXNOTAFISC IN NOTAFISCAL.NRLANCTONF%TYPE,
 P_PRXLANCETSQ IN LANCTOESTOQ.NRLANCESTQ%TYPE,
 P_IDSISTEMA   IN VARCHAR2 DEFAULT 'DF',
 P_IDDOCFATUR  IN NOTAFISCAL.IDDOCFATUR%TYPE DEFAULT NULL)

AS

/* VARIAVEIS DA TABELA DE NOTA FISCAL */
   V_CDEMPRESA      VARCHAR2(02);
   V_CDEMPRAUX      VARCHAR2(02);
   V_CDINSCESTA     VARCHAR2(16);
   V_CDINSCMUNI     VARCHAR2(16);
   V_CDFORNECED     VARCHAR2(21);
   V_CDFORNECEDFIL  VARCHAR2(30);
   V_CDCLIENTE      VARCHAR2(21);
   V_NRNOTAFISC     VARCHAR2(20);
   V_DTEMISSAO      DATE;
   V_DTENTRSAID     DATE;
   V_VRPRODUTOS     NUMBER;
   V_VRNOTAFISC     NUMBER;
   V_NRPLACAVEIC    VARCHAR2(07);
   V_SGUFVEIC       VARCHAR2(02);
   V_IDPGTOFRETE    VARCHAR2(01);
   V_DSQTDEVOLU     VARCHAR2(10);
   V_DSESPECVOLU    VARCHAR2(10);
   V_DSMARCAVOLU    VARCHAR2(10);
   V_DSNUMEVOLU     VARCHAR2(15);
   V_VRPBRUTOVOLU   NUMBER;
   V_VRPLIQUVOLU    NUMBER;
   V_IDENTRSAIDOP   VARCHAR2(01);
   V_CDTIPOOPER     VARCHAR2(02);
   V_CDSERIE        VARCHAR2(05);
   V_CDSERIEAUX     VARCHAR2(05);
   V_IDTPIJURTRAN   VARCHAR2(01);
   V_NRINSJURTRAN   VARCHAR2(20);
   V_CDSERIEENTR    VARCHAR2(05);
   V_CDSERIEENTRAUX VARCHAR2(05);
   V_CDFILIRECE     VARCHAR2(04);
   V_CDMODDOCFISC   VARCHAR2(02);
   V_SGESTADO       VARCHAR2(02);
   V_CDMUNICIPIO    VARCHAR2(04);   

/* VARIAVEIS DA TABELA DE ITEMS DA NOTA FISCAL */
   V_NRSEQITPROD    VARCHAR2(04);
   V_CDPRODUTO      VARCHAR2(20);
   V_CDPRODESTO     PRODUTO.CDPRODESTO%TYPE;
   V_CDPRODEMIS     VARCHAR2(20);
   V_DSPRODEMIS     VARCHAR2(200);
   V_CDPRODRELAC    VARCHAR2(20);
   V_CDPRODEMISREL  VARCHAR2(20);
   V_DSPRODEMISREL  VARCHAR2(200);
   V_CDARVPROD      VARCHAR2(20);
   V_QTITEMPROD     NUMBER;
   V_VRUNITITEM     NUMBER;
   V_VRDESCITEM     NUMBER;
   V_VRTOTAITEM     NUMBER;
   V_VRCONTITEM     NUMBER;
   V_VRBRUTITEM     NUMBER;
   V_VRLIQUITEM     NUMBER;

/* VARIAVEIS DA TABELA DE IMPOSTOS DOS ITENS */
   V_CDIMPOSTO      VARCHAR2(02);
   V_VRALIQITEM     NUMBER;
   V_VRIMPOSTOIT    NUMBER;
   V_VRPERREDBCIT   NUMBER;
   V_CDIMPOSTONFE   VARCHAR2(02);

/* VARIAVEIS DA TABELA DE TOTALIZACAO DE IMPOSTOS */
   V_VRTOTIMPONF    NUMBER;

/* VARIAVEIS DA TABELA DE ENCARGOS */
   V_CDENCARGO      VARCHAR2(02);
   V_VRITEMENCA     NUMBER;
   V_NRDADOADIC     VARCHAR2(03);
   V_CDMENSAGEM     VARCHAR2(03);
   V_DSDADOADIC     VARCHAR2(255);

/* VARIAVEIS DA TABELA DE REPLICACAO DE DOCUMENTOS */
   V_CDFILIORIGTRD  VARCHAR2(04);
   V_CDFILIDESTTRD  VARCHAR2(04);
   V_IDENTRSAIDTRD  VARCHAR2(01);
   V_CDTIPOOPERTRD  VARCHAR2(02);
   V_CDSERIETRD     VARCHAR2(05);
   V_CDALMOXARTRD   VARCHAR2(06);
   V_CDLOCESTQTRD   VARCHAR2(06);
   V_CDFILIALREPLIC VARCHAR2(04);
   V_NRREPLICDOC    VARCHAR2(04);
   
   V_NRLOTEESTQ     VARCHAR2(20);
   V_NRSUBLOTE      VARCHAR2(04);

   V_ALMOXARIFE     VARCHAR2(06);
   V_LOCALESTOQ     VARCHAR2(06);
   V_IDCTRLESTQ     VARCHAR2(01);
   V_IDUTILLOTE     VARCHAR2(01);
   V_DSNUMELOTE     PARAMFILIAL.DSNUMELOTE%TYPE;

   V_IDATUESTTPOP   TIPOOPERAC.IDATUESTTPOP%TYPE;

   V_PRXNRLANCNF    VARCHAR2(10);
   V_PRXNRLANCEST   VARCHAR2(10);
   V_IDTPIJURFILI   VARCHAR2(01);
   V_NRINSJURFILI   VARCHAR2(20);
   V_VRLANCAMENTO   NUMBER;
   V_IDEMPDESTREPAUT VARCHAR2(01);
   V_IDCNTRESTOQ    VARCHAR2(01);
   V_IDFUNCAOFILI   VARCHAR2(01);
   V_REPLICACAOOK   NUMBER;
   V_SUGREGSTENTR   VARCHAR2(01);
   V_CDENCARGOST    VARCHAR2(02);
   V_T_VRIMPICMSST  NUMBER;
   V_IDPERREPLICNFOL VARCHAR2(01);
   V_IDPERREPLICNFOLAUX BOOLEAN;

   V_CDALMOXARIFE ALMOXARIFADO.CDALMOXARIFE%TYPE;
   V_CDLOCALESTOQ LOCALESTOQUE.CDLOCALESTOQ%TYPE;

   V_IDENTREPALMEXP VARCHAR2(01);
   V_CDALMOXCESTEXP VARCHAR2(06);
   V_CDLOCESTEXP    VARCHAR2(06);         

   V_DTVALILOTE     DATE;
   V_DTFABRPROD     DATE;
   V_NRLOTEFORN     VARCHAR2(20);
   V_IDORIGDESTOP   VARCHAR2(02);
   V_CDGRUPOFISC    VARCHAR2(05);
   V_IDINTEREST     VARCHAR2(01);
   V_PAISDEST       VARCHAR2(04);
   V_ESTADEST       VARCHAR2(02);
   V_MUNIDEST       VARCHAR2(04);
   V_PAISORIG       VARCHAR2(04);
   V_ESTAORIG       VARCHAR2(02);
   V_MUNIORIG       VARCHAR2(04);
   /*Gerar Vencimentos ao replicar nf origem fornecedor*/
   P_RESULTADO      VARCHAR2(50);
   V_IDUTILVENC     VARCHAR2(01);

   CURSOR C_NOTAFISCAL IS
      SELECT CDEMPRESA,   CDINSCESTA, CDINSCMUNI,   CDFORNECED,   CDCLIENTE,
             NRNOTAFISC,  DTEMISSAO,  DTENTRSAID,   VRPRODUTOS,   VRNOTAFISC,
             NRPLACAVEIC, SGUFVEIC,   IDPGTOFRETE,  DSQTDEVOLU,   DSESPECVOLU,
             DSMARCAVOLU, DSNUMEVOLU, VRPBRUTOVOLU, VRPLIQUVOLU,  IDENTRSAIDOP,
             CDTIPOOPER,  CDSERIE,    IDTPIJURTRAN, NRINSJURTRAN, CDSERIEENTR,
             CDFILIRECE, CDMODDOCFISC
      FROM NOTAFISCAL
      WHERE CDFILIAL   = P_CDFILIAL AND
            NRLANCTONF = P_NRLANCTONF;

   CURSOR C_ITEMPRODUTO IS
      SELECT I.NRSEQITPROD, I.CDPRODUTO,  I.CDPRODEMIS, I.DSPRODEMIS, I.QTITEMPROD,
             I.VRUNITITEM,  I.VRDESCITEM, I.VRTOTAITEM, I.VRCONTITEM, I.VRBRUTITEM,
             (I.VRTOTAITEM - I.VRDESCITEM) AS VRLIQUITEM, NVL(I.NRLOTEESTQ, ' ') NRLOTEESTQ, NVL(I.NRSUBLOTE, ' ') NRSUBLOTE,
             L.DTVALILOTE, L.DTFABRPROD, L.NRLOTEFORN
        FROM ITEMPRODUTO I, LOTE L
       WHERE I.CDFILIAL   = P_CDFILIAL
         AND I.NRLANCTONF = P_NRLANCTONF
         AND I.CDFILIMOVI = L.CDFILIAL   (+)
         AND I.NRLOTEESTQ = L.NRLOTEESTQ (+)
         AND I.NRSUBLOTE  = L.NRSUBLOTE  (+)
         AND I.CDPRODMOVI = L.CDPRODUTO  (+)
      ORDER BY NRSEQITPROD;

   CURSOR C_ITEMPROIMPOS IS
      SELECT DISTINCT I.NRSEQITPROD, I.CDIMPOSTO, I.VRALIQITEM, I.VRIMPOSTOIT, I.VRPERREDBCIT, II.CDIMPOSTONFE
      FROM ITEMPROIMPOS I INNER JOIN IMPOSTO II ON I.CDIMPOSTO = II.CDIMPOSTO
      WHERE I.CDFILIAL     = P_CDFILIAL      AND
            I.NRLANCTONF   = P_NRLANCTONF    AND
            I.NRITPROIMPOS = '1'
      ORDER BY I.NRSEQITPROD, I.CDIMPOSTO;

   CURSOR C_IMPOSNFTOT IS
      SELECT DISTINCT I.CDIMPOSTO, I.VRTOTIMPONF, II.CDIMPOSTONFE
      FROM IMPOSNFTOT I INNER JOIN IMPOSTO II ON I.CDIMPOSTO = II.CDIMPOSTO
      WHERE I.CDFILIAL     = P_CDFILIAL      AND
            I.NRLANCTONF   = P_NRLANCTONF

      ORDER BY I.CDIMPOSTO;

   CURSOR C_ITEMENCARGO IS
      SELECT CDENCARGO, VRITEMENCA
      FROM ITEMENCARGO
      WHERE CDFILIAL    = P_CDFILIAL AND
            NRLANCTONF  = P_NRLANCTONF
      ORDER BY CDENCARGO;

   CURSOR C_DADOSADIC IS
      SELECT NRDADOADIC, CDMENSAGEM, DSDADOADIC
      FROM DADOSADIC
      WHERE CDFILIAL    = P_CDFILIAL AND
            NRLANCTONF  = P_NRLANCTONF
      ORDER BY NRDADOADIC;

   CURSOR C_TRABREPLICDOC IS
      SELECT CDFILIORIGTRD, CDFILIDESTTRD, IDENTRSAIDTRD,
             CDTIPOOPERTRD, CDSERIETRD,    CDALMOXARTRD,
             CDLOCESTQTRD, CDFILIALREPLIC, NRREPLICDOC
      FROM TRABREPLICDOC
      WHERE CDFILIALTRD   = P_CDFILIAL AND
            NRLANCTONFTRD = P_NRLANCTONF
      ORDER BY IDENTRSAIDTRD DESC;
BEGIN
   V_CDSERIEAUX     := '';
   V_CDSERIEENTRAUX := ''; 
   V_T_VRIMPICMSST  := 0;

   SELECT NVL(IDEMPDESTREPAUT, 'N'),
          NVL(IDPERREPLICNFOL, 'N')
     INTO V_IDEMPDESTREPAUT,
          V_IDPERREPLICNFOL
     FROM PARAMGERAL;

   DELETE FROM ITEMPRODUTO
    WHERE (CDFILIAL,NRLANCTONF) IN (SELECT CDFILIAL, NRLANCTONF
                                      FROM NOTAFISCAL
                                     WHERE IDDOCREPLIC = P_CDFILIAL||P_NRLANCTONF 
                                       AND IDDOCREPLIC <> CDFILIAL||NRLANCTONF
                                       AND IDBLOQUEADO <> 'S');

   DELETE FROM CONTARECEBER
    WHERE (CDFILIAL,NRLANCTONF) IN (SELECT CDFILIAL, NRLANCTONF
                                      FROM NOTAFISCAL
                                     WHERE IDDOCREPLIC = P_CDFILIAL||P_NRLANCTONF 
                                       AND IDDOCREPLIC <> CDFILIAL||NRLANCTONF     
                                       AND IDBLOQUEADO <> 'S');

   DELETE FROM CONTAPAGAR
    WHERE (CDFILIAL,NRLANCTONF) IN (SELECT CDFILIAL, NRLANCTONF
                                      FROM NOTAFISCAL
                                     WHERE IDDOCREPLIC = P_CDFILIAL||P_NRLANCTONF 
                                       AND IDDOCREPLIC <> CDFILIAL||NRLANCTONF     
                                       AND IDBLOQUEADO <> 'S');

   FOR C_NOTAFISCAL IN (SELECT CDFILIAL, NRLANCTONF
                       FROM NOTAFISCAL
                       WHERE IDDOCREPLIC =  P_CDFILIAL||P_NRLANCTONF AND
                             IDDOCREPLIC <> CDFILIAL||NRLANCTONF     AND
                             IDBLOQUEADO <> 'S') LOOP
      DELETA_NF(C_NOTAFISCAL.CDFILIAL, C_NOTAFISCAL.NRLANCTONF);
   END LOOP;

   V_PRXNRLANCNF  := P_PRXNOTAFISC;
   V_PRXNRLANCEST := P_PRXLANCETSQ;
   V_REPLICACAOOK := 0;

   OPEN C_NOTAFISCAL;
   LOOP
   FETCH C_NOTAFISCAL INTO
      V_CDEMPRAUX,    V_CDINSCESTA,   V_CDINSCMUNI,   V_CDFORNECED,
      V_CDCLIENTE,    V_NRNOTAFISC,   V_DTEMISSAO,    V_DTENTRSAID,
      V_VRPRODUTOS,   V_VRNOTAFISC,   V_NRPLACAVEIC,  V_SGUFVEIC,
      V_IDPGTOFRETE,  V_DSQTDEVOLU,   V_DSESPECVOLU,  V_DSMARCAVOLU,
      V_DSNUMEVOLU,   V_VRPBRUTOVOLU, V_VRPLIQUVOLU,  V_IDENTRSAIDOP,
      V_CDTIPOOPER,   V_CDSERIE,      V_IDTPIJURTRAN, V_NRINSJURTRAN,
      V_CDSERIEENTR,  V_CDFILIRECE, V_CDMODDOCFISC;
   EXIT WHEN C_NOTAFISCAL%NOTFOUND;

      OPEN C_TRABREPLICDOC;
      LOOP
         FETCH C_TRABREPLICDOC INTO
            V_CDFILIORIGTRD, V_CDFILIDESTTRD,
            V_IDENTRSAIDTRD, V_CDTIPOOPERTRD, V_CDSERIETRD, V_CDALMOXARTRD,
            V_CDLOCESTQTRD, V_CDFILIALREPLIC, V_NRREPLICDOC;
         EXIT WHEN C_TRABREPLICDOC%NOTFOUND;

         SELECT NVL(MAX(IDFUNCAOFILI), 'X')
           INTO V_IDFUNCAOFILI
           FROM FILIAL
          WHERE CDFILIAL =  V_CDFILIDESTTRD;
          
         V_IDPERREPLICNFOLAUX := TRUE;
         IF V_IDFUNCAOFILI = 'O' THEN
            IF V_IDPERREPLICNFOL <> 'S' THEN
               V_IDPERREPLICNFOLAUX := FALSE;
            END IF;
         END IF;

         IF (((V_IDENTRSAIDTRD = 'E') AND V_IDPERREPLICNFOLAUX) OR (V_IDENTRSAIDTRD = 'S')) THEN
            SELECT MIN(MT.CDMODDOCFISC)
              INTO V_CDMODDOCFISC
              FROM MODDOCFISCTPOP MT
             WHERE MT.IDENTRSAIDOP = V_IDENTRSAIDTRD
               AND MT.CDTIPOOPER   = V_CDTIPOOPERTRD
               AND MT.CDMODDOCFISC = V_CDMODDOCFISC;

            IF (V_CDMODDOCFISC IS NULL) THEN
               SELECT MIN(MT.CDMODDOCFISC)
                 INTO V_CDMODDOCFISC
                 FROM MODDOCFISCTPOP MT
                WHERE MT.IDENTRSAIDOP = V_IDENTRSAIDTRD
                  AND MT.CDTIPOOPER   = V_CDTIPOOPERTRD;
            END IF;

            IF V_IDEMPDESTREPAUT = 'S' AND V_IDENTRSAIDTRD = 'E' THEN
               SELECT MAX(IDTPIJURFILI), MAX(NRINSJURFILI), MAX(CDEMPRESA), MAX(CDINSCESTA), MAX(CDINSCMUNI)
               INTO V_IDTPIJURFILI, V_NRINSJURFILI, V_CDEMPRESA, V_CDINSCESTA, V_CDINSCMUNI
               FROM FILIAL
               WHERE (CDFILIAL = V_CDFILIDESTTRD);
            ELSE
               SELECT MAX(IDTPIJURFILI), MAX(NRINSJURFILI)
               INTO V_IDTPIJURFILI, V_NRINSJURFILI
               FROM FILIAL
               WHERE (CDFILIAL = V_CDFILIORIGTRD AND V_IDENTRSAIDTRD = 'E') OR
                     (CDFILIAL = V_CDFILIDESTTRD AND V_IDENTRSAIDTRD = 'S');

               /*Verifica a inscricao inicialmente para a empresa do lancamento*/
               SELECT MAX(CDEMPRESA), MAX(CDINSCESTA), MAX(CDINSCMUNI)
               INTO V_CDEMPRESA, V_CDINSCESTA, V_CDINSCMUNI
               FROM FILIAL
               WHERE ((CDFILIAL  = V_CDFILIORIGTRD AND V_IDENTRSAIDTRD = 'S')  OR
                      (CDFILIAL  = V_CDFILIDESTTRD AND V_IDENTRSAIDTRD = 'E')) AND
                     (CDEMPRESA = V_CDEMPRAUX);

               /*Se a empresa da filial for diferente verifica a incricao para a empresa relacionada*/
               IF V_CDEMPRESA IS NULL THEN
                  SELECT MAX(CDEMPRESA), MAX(CDINSCESTA), MAX(CDINSCMUNI)
                  INTO V_CDEMPRESA, V_CDINSCESTA, V_CDINSCMUNI
                  FROM EMPRCNTRFIL
                  WHERE ((CDFILIAL  = V_CDFILIORIGTRD AND V_IDENTRSAIDTRD = 'S')  OR
                         (CDFILIAL  = V_CDFILIDESTTRD AND V_IDENTRSAIDTRD = 'E')) AND
                        (CDEMPRESA = V_CDEMPRAUX);
               END IF;

               /*Caso nao possua inscricao para a empresa da NF ele considera a inscricao da filial*/
               IF V_CDEMPRESA IS NULL THEN
                  SELECT MAX(CDEMPRESA), MAX(CDINSCESTA), MAX(CDINSCMUNI)
                  INTO V_CDEMPRESA, V_CDINSCESTA, V_CDINSCMUNI
                  FROM FILIAL
                  WHERE (CDFILIAL  = V_CDFILIORIGTRD AND V_IDENTRSAIDTRD = 'S') OR
                        (CDFILIAL  = V_CDFILIDESTTRD AND V_IDENTRSAIDTRD = 'E');
               END IF;
            END IF;

            IF V_IDENTRSAIDTRD = 'E' THEN
               V_VRLANCAMENTO := V_VRNOTAFISC;
               IF (V_CDSERIEENTR IS NULL) AND (V_CDSERIETRD IS NOT NULL) THEN
                  V_CDSERIEENTRAUX := V_CDSERIETRD;
               END IF;

               IF V_CDSERIEENTRAUX IS NULL THEN
                  SELECT MAX(CDSERIEENTR) INTO V_CDSERIEENTRAUX
                    FROM SERIEENTR
                   WHERE CDSERIEENTR = V_CDSERIE;
               END IF;
               V_CDSERIEAUX := NULL;
               V_DTEMISSAO  := V_DTENTRSAID;
            ELSE
               V_VRLANCAMENTO   := 0;
               V_CDSERIEAUX     := V_CDSERIETRD;
               V_DTEMISSAO      := NULL;
               V_NRNOTAFISC     := NULL;
               V_CDSERIEENTRAUX := NULL;
            END IF;
			
			BEGIN
               SELECT NVL(IDORIGDESTOP, 'L'), NVL(IDUTILVENC, 'N')
                 INTO V_IDORIGDESTOP, V_IDUTILVENC
                 FROM TIPOOPERAC
                WHERE CDTIPOOPER   = V_CDTIPOOPERTRD
                  AND IDENTRSAIDOP = V_IDENTRSAIDTRD;
            EXCEPTION
               WHEN NO_DATA_FOUND THEN BEGIN
                  V_IDORIGDESTOP := 'L'; V_IDUTILVENC := 'N';
               END;
            END;

            BEGIN
               SELECT MAX(SGESTADOPRESSERV), MAX(CDMUNICIPRESSERV)
                 INTO V_SGESTADO, V_CDMUNICIPIO
                 FROM DADOSERVPRES
                WHERE CDFILIAL   = P_CDFILIAL
                  AND NRLANCTONF = P_NRLANCTONF;
            EXCEPTION
               WHEN NO_DATA_FOUND THEN BEGIN
                  V_SGESTADO := NULL; V_CDMUNICIPIO := NULL;
               END;
            END;

            IF (V_IDORIGDESTOP = 'F') THEN
               BEGIN
                  SELECT CDFORNECED
                    INTO V_CDFORNECEDFIL
                    FROM FORNECEDOR
                   WHERE NRINSJURFORN = V_NRINSJURFILI;
               EXCEPTION
                  WHEN NO_DATA_FOUND THEN BEGIN
                     V_CDFORNECEDFIL := NULL;
                  END;
               END;   

               IF (V_CDFORNECEDFIL IS NULL) THEN
                  RAISE_APPLICATION_ERROR(-20501, 'REPLIC_BLOQ - OPERACAO BLOQUEADA! FORNECEDOR NAO CADASTRADO PARA O TIPO DE OPERACAO ' ||V_CDTIPOOPERTRD||'.', True);
               END IF;

               INSERT INTO NOTAFISCAL
                  (CDFILIAL,     NRLANCTONF,   CDEMPRESA,    CDINSCESTA,   CDINSCMUNI,
                   CDFORNECED,   CDFILIRECE,   IDTPIJURNF,   NRINSJURNF,   IDBLOQUEADO,
                   DTEMISSAO,    DTENTRSAID,   VRPRODUTOS,   VRNOTAFISC,   NRPLACAVEIC,
                   SGUFVEIC,     IDPGTOFRETE,  DSQTDEVOLU,   DSESPECVOLU,  DSMARCAVOLU,
                   DSNUMEVOLU,   VRPBRUTOVOLU, VRPLIQUVOLU,  IDENTRSAIDOP, CDTIPOOPER,
                   CDSERIE,      IDTPIJURTRAN, NRINSJURTRAN, IDSTATUS,     IDSISTEMA,
                   CDSERIEENTR,  IDDOCREPLIC,  IDORIGDESTNF, NRNOTAFISC,   CDMODDOCFISC,
                   DTLANCAMENNF, IDDOCFATUR,   IDDOCFINANC, SGESTADO, CDMUNICIPIO)
               VALUES
                  (P_CDFILIPROC,     V_PRXNRLANCNF,   V_CDEMPRESA,    V_CDINSCESTA,    V_CDINSCMUNI,
                   V_CDFORNECEDFIL,  V_CDFILIDESTTRD, V_IDTPIJURFILI, V_NRINSJURFILI,  'N',
                   V_DTEMISSAO,      V_DTENTRSAID,    V_VRPRODUTOS,   V_VRLANCAMENTO,  V_NRPLACAVEIC,
                   V_SGUFVEIC,       V_IDPGTOFRETE,   V_DSQTDEVOLU,   V_DSESPECVOLU,   V_DSMARCAVOLU,
                   V_DSNUMEVOLU,     V_VRPBRUTOVOLU,  V_VRPLIQUVOLU,  V_IDENTRSAIDTRD, V_CDTIPOOPERTRD,
                   V_CDSERIEAUX,     V_IDTPIJURTRAN,  V_NRINSJURTRAN, 'P',             'DF'||V_IDENTRSAIDTRD,
                   V_CDSERIEENTRAUX, P_CDFILIAL||P_NRLANCTONF, V_IDORIGDESTOP, V_NRNOTAFISC, V_CDMODDOCFISC,
                   V_DTENTRSAID,     P_IDDOCFATUR, 'N', V_SGESTADO, V_CDMUNICIPIO);
            ELSE
               INSERT INTO NOTAFISCAL
                  (CDFILIAL,     NRLANCTONF,   CDEMPRESA,    CDINSCESTA,   CDINSCMUNI,
                   CDFILIEMIT,   CDFILIRECE,   IDTPIJURNF,   NRINSJURNF,   IDBLOQUEADO,
                   DTEMISSAO,    DTENTRSAID,   VRPRODUTOS,   VRNOTAFISC,   NRPLACAVEIC,
                   SGUFVEIC,     IDPGTOFRETE,  DSQTDEVOLU,   DSESPECVOLU,  DSMARCAVOLU,
                   DSNUMEVOLU,   VRPBRUTOVOLU, VRPLIQUVOLU,  IDENTRSAIDOP, CDTIPOOPER,
                   CDSERIE,      IDTPIJURTRAN, NRINSJURTRAN, IDSTATUS,     IDSISTEMA,
                   CDSERIEENTR,  IDDOCREPLIC,  IDORIGDESTNF, NRNOTAFISC, CDMODDOCFISC,
                   DTLANCAMENNF, IDDOCFATUR,   IDDOCFINANC, SGESTADO, CDMUNICIPIO)
               VALUES
                  (P_CDFILIPROC, V_PRXNRLANCNF, V_CDEMPRESA, V_CDINSCESTA, V_CDINSCMUNI,
                   V_CDFILIORIGTRD, V_CDFILIDESTTRD, V_IDTPIJURFILI, V_NRINSJURFILI, 'N',
                   V_DTEMISSAO, V_DTENTRSAID, V_VRPRODUTOS, V_VRLANCAMENTO, V_NRPLACAVEIC,
                   V_SGUFVEIC, V_IDPGTOFRETE, V_DSQTDEVOLU, V_DSESPECVOLU, V_DSMARCAVOLU,
                   V_DSNUMEVOLU, V_VRPBRUTOVOLU, V_VRPLIQUVOLU, V_IDENTRSAIDTRD, V_CDTIPOOPERTRD,
                   V_CDSERIEAUX, V_IDTPIJURTRAN, V_NRINSJURTRAN, 'P', 'DF'||V_IDENTRSAIDTRD,
                   V_CDSERIEENTRAUX, P_CDFILIAL||P_NRLANCTONF, V_IDORIGDESTOP, V_NRNOTAFISC, V_CDMODDOCFISC,
                   V_DTENTRSAID, P_IDDOCFATUR, 'N', V_SGESTADO, V_CDMUNICIPIO);
            END IF;

            IF V_IDENTRSAIDTRD = 'E' THEN
               OPEN C_ITEMPRODUTO;
               LOOP
                  FETCH C_ITEMPRODUTO INTO
                     V_NRSEQITPROD, V_CDPRODUTO,  V_CDPRODEMIS, V_DSPRODEMIS,
                     V_QTITEMPROD,  V_VRUNITITEM, V_VRDESCITEM, V_VRTOTAITEM,
                     V_VRCONTITEM,  V_VRBRUTITEM, V_VRLIQUITEM, V_NRLOTEESTQ, V_NRSUBLOTE,
                     V_DTVALILOTE,  V_DTFABRPROD, V_NRLOTEFORN;
                  EXIT WHEN C_ITEMPRODUTO%NOTFOUND;

                  SELECT NVL(MAX(IDCTRLESTQ),'S'), NVL(MAX(IDUTILLOTE), 'N'), MAX(DSNUMELOTE), NVL(MAX(IDENTREPALMEXP), 'N')
                  INTO V_IDCTRLESTQ, V_IDUTILLOTE, V_DSNUMELOTE, V_IDENTREPALMEXP
                  FROM PARAMFILIAL
                  WHERE CDFILIAL = V_CDFILIDESTTRD;

                  SELECT NVL(IDATUESTTPOP, 'S')
                    INTO V_IDATUESTTPOP
                    FROM TIPOOPERAC
                   WHERE CDTIPOOPER   = V_CDTIPOOPERTRD
                     AND IDENTRSAIDOP = V_IDENTRSAIDTRD;
					 
				      V_CDPRODRELAC   := NULL;
                  V_CDPRODEMISREL := NULL;
                  V_DSPRODEMISREL := NULL;
					 
				      BEGIN
                     SELECT P.CDPRODDEST, P2.CDARVPROD, P2.NMPRODUTO
                       INTO V_CDPRODRELAC, V_CDPRODEMISREL, V_DSPRODEMISREL
                       FROM PRODREPLICDOC P, PRODUTO P2
                      WHERE P.CDFILIAL     = V_CDFILIALREPLIC
                        AND P.NRREPLICDOC  = V_NRREPLICDOC
                        AND P.CDFILIORIGRD = V_CDFILIORIGTRD
                        AND P.CDFILIDESTRD = V_CDFILIDESTTRD
                        AND P.IDENTRSAIDOP = V_IDENTRSAIDTRD
                        AND P.CDTIPOOPER   = V_CDTIPOOPERTRD
                        AND P.CDPRODORIGEM = V_CDPRODUTO
                        AND P.CDPRODDEST   = P2.CDPRODUTO;
                  EXCEPTION
                     WHEN NO_DATA_FOUND THEN BEGIN
                        V_CDPRODRELAC := NULL; V_CDPRODEMISREL := NULL; V_DSPRODEMISREL := NULL;
                     END;
                  END;

                  IF (V_CDPRODRELAC IS NOT NULL) THEN
                     V_CDPRODUTO     := V_CDPRODRELAC;
                     V_CDPRODEMIS    := V_CDPRODEMISREL;
                     V_DSPRODEMIS    := V_DSPRODEMISREL;
                  END IF;

                  IF V_IDUTILLOTE = 'S' THEN
                     SELECT NVL(MAX(IDCNTRESTOQ), 'S'), NVL(MAX(IDUTCTRLLOTE), 'S')
                       INTO V_IDCNTRESTOQ,    V_IDUTILLOTE
                       FROM PRODFILI
                      WHERE CDFILIAL  = V_CDFILIDESTTRD
                        AND CDPRODUTO = V_CDPRODUTO;
                  ELSE
                     SELECT NVL(MAX(IDCNTRESTOQ), 'S'), 'N'
                       INTO V_IDCNTRESTOQ,    V_IDUTILLOTE
                       FROM PRODFILI
                      WHERE CDFILIAL  = V_CDFILIDESTTRD
                        AND CDPRODUTO = V_CDPRODUTO;
                  END IF;

                  IF V_IDCTRLESTQ = 'S' AND V_IDATUESTTPOP = 'S' AND V_IDCNTRESTOQ = 'S' THEN

                     LOCALESTOQUE_PADRAO(V_CDFILIDESTTRD, V_CDPRODUTO, V_CDALMOXARIFE, V_CDLOCALESTOQ, P_IDSISTEMA);

                     IF V_CDALMOXARTRD = 'P' THEN
                        V_ALMOXARIFE := V_CDALMOXARIFE;
                     ELSE
                        V_ALMOXARIFE := V_CDALMOXARTRD;
                     END IF;

                     IF V_CDLOCESTQTRD = 'P' THEN
                        V_LOCALESTOQ := V_CDLOCALESTOQ;
                     ELSE
                        V_LOCALESTOQ := V_CDLOCESTQTRD;
                     END IF;

                     /* Se o parametro "Realizar Entrada de Replicacao no Almoxarifado/Localizacao Expedicao/Reservas de Pedidos" */
                     IF (V_IDENTREPALMEXP = 'S') THEN
                        SELECT MAX(CDPRODESTO)
                          INTO V_CDPRODESTO
                          FROM PRODUTO
                         WHERE CDPRODUTO = V_CDPRODUTO;

                        SELECT MAX(CDALMOXPRCLI), MAX(CDLOCALPRCLI)
                          INTO V_CDALMOXCESTEXP, V_CDLOCESTEXP
                          FROM PRODFILI
                         WHERE CDFILIAL  = V_CDFILIDESTTRD
                           AND CDPRODUTO = V_CDPRODESTO;

                        IF (V_CDALMOXCESTEXP IS NOT NULL) THEN
                           V_ALMOXARIFE := V_CDALMOXCESTEXP;
                        END IF;

                        IF (V_CDLOCESTEXP IS NOT NULL) THEN
                           V_LOCALESTOQ := V_CDLOCESTEXP;
                        END IF;                      
                     END IF;

                     IF V_IDUTILLOTE = 'S' THEN
                        IF (V_NRLOTEESTQ IS NULL) OR (V_NRLOTEESTQ = ' ') THEN
                           PRXLOTEPRODEST(V_CDFILIDESTTRD, V_DTENTRSAID, V_CDPRODUTO, V_NRLOTEESTQ);
                        END IF;

                        IF V_NRLOTEESTQ IS NULL THEN
                           RAISE_APPLICATION_ERROR(-20501, 'REPLIC_BLOQ - OPERACAO BLOQUEADA! NAO FOI POSSIVEL GERAR LOTE. FAVOR VERIFICAR OS PARAMETROS DE CONTROLE DE LOTE.', True);
                        END IF;
                     ELSE
                        V_NRLOTEESTQ := ' ';
                        V_NRSUBLOTE  := ' ';
                     END IF;

                     INSERT INTO LOTE
                     (CDFILIAL, NRLOTEESTQ, NRSUBLOTE, CDPRODUTO, IDSTATLOTE, DTENTRLOTE)
                     (SELECT V_CDFILIDESTTRD, V_NRLOTEESTQ, V_NRSUBLOTE, V_CDPRODUTO, 'L', SYSDATE
                        FROM PARAMGERAL
                       MINUS
                      SELECT CDFILIAL, NRLOTEESTQ, NRSUBLOTE, CDPRODUTO, 'L', SYSDATE
                        FROM LOTE
                       WHERE CDFILIAL   = V_CDFILIDESTTRD
                         AND NRLOTEESTQ = V_NRLOTEESTQ
                         AND NRSUBLOTE  = V_NRSUBLOTE
                         AND CDPRODUTO  = V_CDPRODUTO);

                     IF V_NRLOTEESTQ <> ' ' THEN
                        UPDATE LOTE
                           SET DTVALILOTE = V_DTVALILOTE,
                               DTFABRPROD = V_DTFABRPROD,
                               NRLOTEFORN = V_NRLOTEFORN
                         WHERE CDFILIAL   = V_CDFILIDESTTRD
                           AND NRLOTEESTQ = V_NRLOTEESTQ
                           AND NRSUBLOTE  = V_NRSUBLOTE
                           AND CDPRODUTO  = V_CDPRODUTO;
                     END IF;

                     INSERT INTO ITEMPRODUTO
                        (CDFILIAL,   NRLANCTONF,   NRSEQITPROD,  CDPRODUTO,  CDPRODEMIS,
                         DSPRODEMIS, IDATUVRESTOQ, QTITEMPROD,   VRUNITITEM, VRDESCITEM,
                         VRTOTAITEM, VRCONTITEM,   IDCONFORITEM, VRBRUTITEM, CDFILIMOVI,
                         CDALMOXARIFE, CDLOCALESTOQ, NRLOTEESTQ, NRSUBLOTE)
                     VALUES
                        (P_CDFILIPROC, V_PRXNRLANCNF, V_NRSEQITPROD, V_CDPRODUTO, V_CDPRODEMIS,
                         V_DSPRODEMIS, 'S', V_QTITEMPROD, V_VRUNITITEM, V_VRDESCITEM,
                         V_VRTOTAITEM, 0, 'S', V_VRLIQUITEM, V_CDFILIDESTTRD,
                         V_ALMOXARIFE, V_LOCALESTOQ, V_NRLOTEESTQ, V_NRSUBLOTE);
                  ELSE
                     INSERT INTO ITEMPRODUTO
                        (CDFILIAL,   NRLANCTONF,   NRSEQITPROD,  CDPRODUTO,  CDPRODEMIS,
                         DSPRODEMIS, IDATUVRESTOQ, QTITEMPROD,   VRUNITITEM, VRDESCITEM,
                         VRTOTAITEM, VRCONTITEM,   IDCONFORITEM, VRBRUTITEM, CDFILIMOVI)
                     VALUES
                        (P_CDFILIPROC, V_PRXNRLANCNF, V_NRSEQITPROD, V_CDPRODUTO, V_CDPRODEMIS,
                         V_DSPRODEMIS, 'S', V_QTITEMPROD, V_VRUNITITEM, V_VRDESCITEM,
                         V_VRTOTAITEM, 0, 'S', V_VRLIQUITEM, V_CDFILIDESTTRD);
                  END IF;
                  -- CASO A NF REPLICADA SEJA ORIGEM FORNECEDOR, BUSCA PARAMETRIZACAO DA REGRA FISCAL CENTRALIZADA
                  IF (V_IDORIGDESTOP = 'F') THEN
                     V_IDINTEREST   := 'N';
                     V_CDGRUPOFISC  := NULL;

                     --VARIAVEIS PARA CONSULTA DOS IMPOSTOS
                     BEGIN
                        SELECT CDPAIS,     SGESTADO,   CDMUNICIPIO
                          INTO V_PAISDEST, V_ESTADEST, V_MUNIDEST
                          FROM INSCRESTAD
                         WHERE (CDEMPRESA  = V_CDEMPRESA)
                           AND (CDINSCESTA = V_CDINSCESTA);
                     EXCEPTION
                        WHEN NO_DATA_FOUND THEN
                           V_PAISDEST := NULL; V_ESTADEST := NULL; V_MUNIDEST := NULL;
                     END;

                     BEGIN
                        SELECT CDPAIS, SGESTADO, CDMUNICIPIO
                          INTO V_PAISORIG, V_ESTAORIG, V_MUNIORIG
                          FROM ENDEFORN
                         WHERE (CDFORNECED   = V_CDFORNECEDFIL)
                           AND (IDTPENDEFORN = 'P');
                     EXCEPTION
                        WHEN NO_DATA_FOUND THEN
                           V_PAISORIG := NULL; V_ESTAORIG := NULL; V_MUNIORIG := NULL;
                     END;

                     IF (V_PAISORIG = V_PAISDEST) AND (V_ESTAORIG <> V_ESTADEST) THEN
                        V_IDINTEREST := 'S';
                     END IF;
                     --VARIAVEIS PARA CONSULTA DOS IMPOSTOS

                     IF (V_CDPRODEMISREL IS NOT NULL) THEN
                        V_CDARVPROD := V_CDPRODEMISREL;
                     ELSE
                        BEGIN
                           SELECT CDARVPROD
                             INTO V_CDARVPROD
                             FROM PRODUTO
                            WHERE CDPRODUTO = V_CDPRODUTO;
                        EXCEPTION
                           WHEN NO_DATA_FOUND THEN BEGIN
                              V_CDARVPROD := V_CDPRODEMIS;
                           END;
                        END;
                     END IF;

                     CONSULTA_GRUPOFISCAL('F', V_CDFORNECEDFIL, V_CDFILIDESTTRD, 'E', V_CDTIPOOPERTRD, V_CDGRUPOFISC);

                     IMPOSTO_ENTRADA_PRODUTO(V_CDEMPRESA, V_CDINSCESTA, V_CDTIPOOPERTRD, V_CDFORNECEDFIL, P_CDFILIPROC, V_PRXNRLANCNF,
                                             NVL(V_DTENTRSAID, TRUNC(SYSDATE)), 'E', '', V_CDGRUPOFISC, V_IDINTEREST, V_CDARVPROD,
                                             '', 'F', V_CDFILIDESTTRD, NULL, NULL, V_VRTOTAITEM, 'N');

                     V_VRDESCITEM := NVL(V_VRDESCITEM, 0);

                     FOR C_ALIQITEM IN(SELECT IM.CDIMPOSTO, IM.SGIMPOSTO, IM.IDTRATIMPO, IM.IDPREIMPENTR,
                                              I.CDFISCTEMP, NVL(AL.VRALIQUTMP, 0) AS VRALIQUOTA,
                                              NVL(AL.VRADICALIQFECP, 0) AS VRADICALIQFECP
                                         FROM INCITEMP I, IMPOSTO IM, ALIQTEMPPROD AL
                                        WHERE I.CDIMPOTEMP  = IM.CDIMPOSTO
                                          AND I.NRINCITEMP  = P_CDFILIPROC||V_PRXNRLANCNF
                                          AND I.NRINCITEMP  = AL.NRALIQTEMP(+)
                                          AND I.CDIMPOTEMP  = AL.CDIMPOTEMP(+)
                                          AND IM.IDPRODNOTA <> 'C') LOOP

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

                           VALUES
                              (P_CDFILIPROC,     V_PRXNRLANCNF,  V_NRSEQITPROD, C_ALIQITEM.CDIMPOSTO, (V_VRTOTAITEM - V_VRDESCITEM),
                               0, (V_VRTOTAITEM - V_VRDESCITEM),  C_ALIQITEM.VRALIQUOTA, 0, 0,
                               C_ALIQITEM.CDFISCTEMP, '1', 'N',
                               0, '0', 0, C_ALIQITEM.VRADICALIQFECP);
                     END LOOP;
                  END IF;
                  DELETE
                    FROM ALIQTEMPPROD
                   WHERE NRALIQTEMP = P_CDFILIPROC||V_PRXNRLANCNF;

                  DELETE
                    FROM INCITEMP
                   WHERE NRINCITEMP = P_CDFILIPROC||V_PRXNRLANCNF;

                  DELETE
                    FROM ALIQTEMP
                   WHERE NRALIQTEMP = P_CDFILIPROC||V_PRXNRLANCNF;

               -- CASO A NF REPLICADA SEJA ORIGEM FORNECEDOR, BUSCA PARAMETRIZACAO DA REGRA FISCAL CENTRALIZADA
               END LOOP;
               CLOSE C_ITEMPRODUTO;

               -- TOTALIZACAO DOS IMPOSTOS CASO NAO SEJA DESTINO FILIAL

               IF (V_IDORIGDESTOP = 'F') THEN
                  FOR C_TRABIMPOSNFTOT IN (SELECT SUM(T.VRIMPOSIT) VRTOTAIMPO, T.CDIMPOSTOIT
                                             FROM TRABITPROIMPOS T, IMPOSTO I
                                            WHERE CDFILIMPOIT  = P_CDFILIPROC
                                              AND NRLANCIMPOIT = V_PRXNRLANCNF
                                              AND IDPRODNOTA <> 'C'
                                              AND T.CDIMPOSTOIT = I.CDIMPOSTO
                                            GROUP BY CDIMPOSTOIT
                                            ORDER BY CDIMPOSTOIT)LOOP

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

                           VALUES(P_CDFILIPROC, V_PRXNRLANCNF, C_TRABIMPOSNFTOT.CDIMPOSTOIT, (0 + C_TRABIMPOSNFTOT.VRTOTAIMPO), 0);
                  END LOOP;
               END IF;
            ELSE
               OPEN C_ITEMPRODUTO;
               LOOP
                  FETCH C_ITEMPRODUTO INTO
                     V_NRSEQITPROD, V_CDPRODUTO,  V_CDPRODEMIS, V_DSPRODEMIS,
                     V_QTITEMPROD,  V_VRUNITITEM, V_VRDESCITEM, V_VRTOTAITEM,
                     V_VRCONTITEM,  V_VRBRUTITEM, V_VRLIQUITEM, V_NRLOTEESTQ, V_NRSUBLOTE,
                     V_DTVALILOTE,  V_DTFABRPROD, V_NRLOTEFORN;
                  EXIT WHEN C_ITEMPRODUTO%NOTFOUND;

                  SELECT NVL(MAX(IDCTRLESTQ),'S'), NVL(MAX(IDUTILLOTE), 'N'), MAX(DSNUMELOTE)
                  INTO V_IDCTRLESTQ, V_IDUTILLOTE, V_DSNUMELOTE
                  FROM PARAMFILIAL
                  WHERE CDFILIAL = V_CDFILIORIGTRD;

                  SELECT NVL(IDATUESTTPOP, 'S')
                    INTO V_IDATUESTTPOP
                    FROM TIPOOPERAC
                   WHERE CDTIPOOPER   = V_CDTIPOOPERTRD
                     AND IDENTRSAIDOP = V_IDENTRSAIDTRD;

                  IF V_IDUTILLOTE = 'S' THEN
                     SELECT NVL(MAX(IDCNTRESTOQ), 'S'), NVL(MAX(IDUTCTRLLOTE), 'S')
                       INTO V_IDCNTRESTOQ, V_IDUTILLOTE
                       FROM PRODFILI
                      WHERE CDFILIAL  = V_CDFILIORIGTRD
                        AND CDPRODUTO = V_CDPRODUTO;
                  ELSE
                     SELECT NVL(MAX(IDCNTRESTOQ), 'S'), 'N'
                       INTO V_IDCNTRESTOQ, V_IDUTILLOTE
                       FROM PRODFILI
                      WHERE CDFILIAL  = V_CDFILIORIGTRD
                        AND CDPRODUTO = V_CDPRODUTO;
                  END IF;

                  IF V_IDCTRLESTQ = 'S' AND V_IDATUESTTPOP = 'S' AND V_IDCNTRESTOQ = 'S' THEN
                     LOCALESTOQUE_PADRAO(V_CDFILIORIGTRD, V_CDPRODUTO, V_CDALMOXARIFE, V_CDLOCALESTOQ);

                     IF V_CDALMOXARTRD = 'P' THEN
                        V_ALMOXARIFE := V_CDALMOXARIFE;
                     ELSE
                        V_ALMOXARIFE := V_CDALMOXARTRD;
                     END IF;

                     IF V_CDLOCESTQTRD = 'P' THEN
                        V_LOCALESTOQ := V_CDLOCALESTOQ;
                     ELSE
                        V_LOCALESTOQ := V_CDLOCESTQTRD;
                     END IF;

                     IF V_IDUTILLOTE = 'S' THEN
                        IF (V_NRLOTEESTQ IS NULL) or (V_NRLOTEESTQ = ' ') THEN
                           CONSULTA_LOTE('S', V_CDFILIORIGTRD, V_ALMOXARIFE, V_LOCALESTOQ, V_CDPRODUTO, V_NRLOTEESTQ, V_NRSUBLOTE);
                        END IF;
                     ELSE
                        V_NRLOTEESTQ := ' ';
                        V_NRSUBLOTE  := ' ';
                     END IF;

                     INSERT INTO LOTE
                     (CDFILIAL, NRLOTEESTQ, NRSUBLOTE, CDPRODUTO, IDSTATLOTE, DTENTRLOTE)
                     (SELECT V_CDFILIORIGTRD, V_NRLOTEESTQ, V_NRSUBLOTE, V_CDPRODUTO, 'L', SYSDATE
                        FROM PARAMGERAL
                       MINUS
                      SELECT CDFILIAL, NRLOTEESTQ, NRSUBLOTE, CDPRODUTO, 'L', SYSDATE
                        FROM LOTE
                       WHERE CDFILIAL   = V_CDFILIORIGTRD
                         AND NRLOTEESTQ = V_NRLOTEESTQ
                         AND NRSUBLOTE  = V_NRSUBLOTE
                         AND CDPRODUTO  = V_CDPRODUTO);

                     IF V_NRLOTEESTQ <> ' ' THEN
                        UPDATE LOTE
                           SET DTVALILOTE = V_DTVALILOTE,
                               DTFABRPROD = V_DTFABRPROD,
                               NRLOTEFORN = V_NRLOTEFORN
                         WHERE CDFILIAL   = V_CDFILIDESTTRD
                           AND NRLOTEESTQ = V_NRLOTEESTQ
                           AND NRSUBLOTE  = V_NRSUBLOTE
                           AND CDPRODUTO  = V_CDPRODUTO;
                     END IF;

                     INSERT INTO ITEMPRODUTO
                        (CDFILIAL,   NRLANCTONF,   NRSEQITPROD,  CDPRODUTO,  CDPRODEMIS,
                         DSPRODEMIS, IDATUVRESTOQ, QTITEMPROD,   VRUNITITEM, VRDESCITEM,
                         VRTOTAITEM, VRCONTITEM,   IDCONFORITEM, VRBRUTITEM, CDFILIMOVI,
                         CDALMOXARIFE, CDLOCALESTOQ, NRLOTEESTQ, NRSUBLOTE)
                      VALUES
                        (P_CDFILIPROC, V_PRXNRLANCNF, V_NRSEQITPROD, V_CDPRODUTO, V_CDPRODEMIS,
                         V_DSPRODEMIS, 'S', V_QTITEMPROD, V_VRUNITITEM, V_VRDESCITEM,
                         V_VRTOTAITEM, 0, 'S', V_VRLIQUITEM, V_CDFILIORIGTRD,
                         V_ALMOXARIFE, V_LOCALESTOQ, V_NRLOTEESTQ, V_NRSUBLOTE);
                  ELSE
                      INSERT INTO ITEMPRODUTO
                        (CDFILIAL,   NRLANCTONF,   NRSEQITPROD,  CDPRODUTO,  CDPRODEMIS,
                         DSPRODEMIS, IDATUVRESTOQ, QTITEMPROD,   VRUNITITEM, VRDESCITEM,
                         VRTOTAITEM, VRCONTITEM,   IDCONFORITEM, VRBRUTITEM, CDFILIMOVI)
                      VALUES
                        (P_CDFILIPROC, V_PRXNRLANCNF, V_NRSEQITPROD, V_CDPRODUTO, V_CDPRODEMIS,
                         V_DSPRODEMIS, 'S', V_QTITEMPROD, V_VRUNITITEM, V_VRDESCITEM,
                         V_VRTOTAITEM, 0, 'S', V_VRLIQUITEM, V_CDFILIORIGTRD);
                  END IF;
               END LOOP;
               CLOSE C_ITEMPRODUTO;
            END IF;

            V_SUGREGSTENTR  := 'S';
            V_CDENCARGOST   := NULL;
            V_T_VRIMPICMSST := 0;

            IF V_IDENTRSAIDTRD = 'E' THEN
            -- CARREGAR IMPOSTOS DA ORIGEM SE A OPERACAO NAO TIVER COMO ORIGEM FORNECEDOR
               IF (V_IDORIGDESTOP <> 'F') THEN
                  BEGIN
                     SELECT NVL(IE.IDSUGREGSTENTR,'S'), IE.CDENCARGOST
                       INTO V_SUGREGSTENTR, V_CDENCARGOST
                       FROM NOTAFISCAL NF INNER JOIN INSCRESTAD IE ON NF.CDEMPRESA  = IE.CDEMPRESA
                                                                  AND NF.CDINSCESTA = IE.CDINSCESTA
                      WHERE NF.CDFILIAL   = P_CDFILIPROC
                        AND NF.NRLANCTONF = V_PRXNRLANCNF;
                  EXCEPTION
                     WHEN NO_DATA_FOUND THEN BEGIN
                        V_SUGREGSTENTR := 'S';
                        V_CDENCARGOST  := NULL;
                     END;
                  END;

                  OPEN C_ITEMPROIMPOS;
                  LOOP
                     FETCH C_ITEMPROIMPOS INTO
                        V_NRSEQITPROD, V_CDIMPOSTO, V_VRALIQITEM, V_VRIMPOSTOIT, V_VRPERREDBCIT, V_CDIMPOSTONFE;
                     EXIT WHEN C_ITEMPROIMPOS%NOTFOUND;

                     IF (V_CDIMPOSTONFE = '80') AND (V_SUGREGSTENTR = 'N') AND (V_CDENCARGOST IS NULL) THEN
                        UPDATE ITEMPRODUTO
                           SET VRUNITITEM = ((V_VRIMPOSTOIT/QTITEMPROD)+VRUNITITEM),
                               VRTOTAITEM = (VRTOTAITEM+V_VRIMPOSTOIT),
                               VRBRUTITEM = (VRBRUTITEM+V_VRIMPOSTOIT)
                         WHERE CDFILIAL    = P_CDFILIPROC
                           AND NRLANCTONF  = V_PRXNRLANCNF
                           AND NRSEQITPROD = V_NRSEQITPROD;
                     ELSE
                        IF (V_CDIMPOSTONFE = '80') AND (V_SUGREGSTENTR = 'N') THEN
                           V_T_VRIMPICMSST := V_T_VRIMPICMSST+V_VRIMPOSTOIT;

                           UPDATE ITEMPRODUTO
                              SET VRICMSSTITORIG = V_VRIMPOSTOIT
                            WHERE CDFILIAL    = P_CDFILIPROC
                              AND NRLANCTONF  = V_PRXNRLANCNF
                              AND NRSEQITPROD = V_NRSEQITPROD;
                        ELSE
                           INSERT INTO TRABITPROIMPOS
                              (CDFILIMPOIT,  NRLANCIMPOIT,  NRSEQIMPOIT,   CDIMPOSTOIT,
                               VRCONTIMPOIT, VRREDBCIMPOIT, VRBCALCIMPOIT, VRALIQIMPOIT,
                               VRPDEDIMPOIT, VRIMPOSIT,     NRSEQITPRO)
                           VALUES
                              (P_CDFILIPROC, V_PRXNRLANCNF, V_NRSEQITPROD, V_CDIMPOSTO,
                               0, V_VRPERREDBCIT, 0, V_VRALIQITEM,
                               0, V_VRIMPOSTOIT, '1');
                        END IF;
                     END IF;
                  END LOOP;
                  CLOSE C_ITEMPROIMPOS;

                  OPEN C_IMPOSNFTOT;
                  LOOP
                     FETCH C_IMPOSNFTOT INTO
                        V_CDIMPOSTO, V_VRTOTIMPONF, V_CDIMPOSTONFE;
                     EXIT WHEN C_IMPOSNFTOT%NOTFOUND;
                        IF NOT ((V_CDIMPOSTONFE = '80') AND (V_SUGREGSTENTR = 'N')) THEN
                           INSERT INTO TRABIMPOSNFTOT
                              (CDFILIMPTOT, NRLANCIMPTOT, CDIMPOSTOT,
                               VRIMPOSTOT,  VRBCALIMPTOT)
                           VALUES
                              (P_CDFILIPROC,  V_PRXNRLANCNF, V_CDIMPOSTO,
                               V_VRTOTIMPONF, 0);
                        END IF;
                  END LOOP;
                  CLOSE C_IMPOSNFTOT;
               END IF;
               -- CARREGAR IMPOSTOS DA ORIGEM SE A OPERACAO NAO TIVER COMO ORIGEM FORNECEDOR
            END IF;

            OPEN C_ITEMENCARGO;
            LOOP
               FETCH C_ITEMENCARGO INTO
                  V_CDENCARGO, V_VRITEMENCA;
               EXIT WHEN C_ITEMENCARGO%NOTFOUND;

               IF V_CDENCARGOST = V_CDENCARGO THEN                            
                  INSERT INTO ITEMENCARGO
                     (CDFILIAL, NRLANCTONF, CDENCARGO, VRITEMENCA)
                  VALUES
                     (P_CDFILIPROC, V_PRXNRLANCNF, V_CDENCARGO, V_VRITEMENCA+V_T_VRIMPICMSST);
               ELSE
                  INSERT INTO ITEMENCARGO
                     (CDFILIAL, NRLANCTONF, CDENCARGO, VRITEMENCA)
                  VALUES
                     (P_CDFILIPROC, V_PRXNRLANCNF, V_CDENCARGO, V_VRITEMENCA);
               END IF; 

            END LOOP;
            CLOSE C_ITEMENCARGO;

            OPEN C_DADOSADIC;
            LOOP
               FETCH C_DADOSADIC INTO
                  V_NRDADOADIC, V_CDMENSAGEM, V_DSDADOADIC;
               EXIT WHEN C_DADOSADIC%NOTFOUND;

               INSERT INTO DADOSADIC
                  (CDFILIAL, NRLANCTONF, NRDADOADIC, CDMENSAGEM, DSDADOADIC)
               VALUES
                  (P_CDFILIPROC, V_PRXNRLANCNF, V_NRDADOADIC, V_CDMENSAGEM, V_DSDADOADIC);
            END LOOP;
            CLOSE C_DADOSADIC;

            IF V_IDENTRSAIDTRD = 'E' THEN
               SELECT NVL(MAX(IDCTRLESTQ),'S')
                 INTO V_IDCTRLESTQ
                 FROM PARAMFILIAL
                WHERE CDFILIAL = V_CDFILIDESTTRD;

               SELECT NVL(IDATUESTTPOP, 'S')
                 INTO V_IDATUESTTPOP
                 FROM TIPOOPERAC
                WHERE CDTIPOOPER   = V_CDTIPOOPERTRD
                  AND IDENTRSAIDOP = V_IDENTRSAIDTRD;

               IF V_IDCTRLESTQ = 'S' AND V_IDATUESTTPOP = 'S' THEN
                  IF NVL(P_IDDOCFATUR, 'N') <> 'S' THEN
                     IF (V_IDORIGDESTOP = 'F') THEN
                        IMPOSTO_ENTRADA(V_CDEMPRESA, V_CDINSCESTA, V_CDTIPOOPERTRD, V_CDFORNECEDFIL, P_CDFILIPROC,
                                        V_PRXNRLANCNF, V_DTENTRSAID, V_VRLANCAMENTO, V_PRXNRLANCEST, 'E');

                        IF (V_IDUTILVENC = 'S') THEN
                           GERA_DADOS_FINANCEIRO(P_CDFILIPROC, V_PRXNRLANCNF, P_CDFILIPROC, 'L', P_RESULTADO);
                        END IF;

                     ELSE
                        IMPOSTO_ENTRADA(V_CDEMPRESA, V_CDINSCESTA, V_CDTIPOOPERTRD, '', P_CDFILIPROC,
                                        V_PRXNRLANCNF, V_DTENTRSAID, V_VRLANCAMENTO, V_PRXNRLANCEST, 'E');
                     END IF;
                  ELSE
                     IF (V_IDORIGDESTOP = 'F') THEN
                        IMPOSTO_ENTRADA(V_CDEMPRESA, V_CDINSCESTA, V_CDTIPOOPERTRD, V_CDFORNECEDFIL, P_CDFILIPROC,
                                        V_PRXNRLANCNF, V_DTENTRSAID, V_VRLANCAMENTO, '', 'E');
                        IF (V_IDUTILVENC = 'S') THEN
                           GERA_DADOS_FINANCEIRO(P_CDFILIPROC, V_PRXNRLANCNF, P_CDFILIPROC, 'L', P_RESULTADO);
                        END IF;
                     ELSE
                        IMPOSTO_ENTRADA(V_CDEMPRESA, V_CDINSCESTA, V_CDTIPOOPERTRD, '', P_CDFILIPROC,
                                        V_PRXNRLANCNF, V_DTENTRSAID, V_VRLANCAMENTO, '', 'E');
                     END IF;
                  END IF;
               ELSE
                  IF (V_IDORIGDESTOP = 'F') THEN
                     IMPOSTO_ENTRADA(V_CDEMPRESA, V_CDINSCESTA, V_CDTIPOOPERTRD, V_CDFORNECEDFIL, P_CDFILIPROC,
                                     V_PRXNRLANCNF, V_DTENTRSAID, V_VRLANCAMENTO, '', 'E');
                     IF (V_IDUTILVENC = 'S') THEN
                        GERA_DADOS_FINANCEIRO(P_CDFILIPROC, V_PRXNRLANCNF, P_CDFILIPROC, 'L', P_RESULTADO);
                     END IF;
				      ELSE
                     IMPOSTO_ENTRADA(V_CDEMPRESA, V_CDINSCESTA, V_CDTIPOOPERTRD, '', P_CDFILIPROC,
                                     V_PRXNRLANCNF, V_DTENTRSAID, V_VRLANCAMENTO, '', 'E');
                  END IF;
			      END IF;
            ELSE
               SELECT NVL(MAX(IDCTRLESTQ),'S')
                 INTO V_IDCTRLESTQ
                 FROM PARAMFILIAL
                WHERE CDFILIAL = V_CDFILIORIGTRD;

               SELECT NVL(IDATUESTTPOP, 'S')
                 INTO V_IDATUESTTPOP
                 FROM TIPOOPERAC
                WHERE CDTIPOOPER   = V_CDTIPOOPERTRD
                  AND IDENTRSAIDOP = V_IDENTRSAIDTRD;

               IF V_IDCTRLESTQ = 'S' AND V_IDATUESTTPOP = 'S' THEN
                  IF NVL(P_IDDOCFATUR, 'N') <> 'S' THEN
                     IMPOSTO_SAIDA(V_CDEMPRESA, V_CDINSCESTA, V_CDTIPOOPERTRD, '', P_CDFILIPROC,
                                   V_PRXNRLANCNF, V_DTENTRSAID, V_VRLANCAMENTO, V_PRXNRLANCEST);
                  ELSE
                     IMPOSTO_SAIDA(V_CDEMPRESA, V_CDINSCESTA, V_CDTIPOOPERTRD, '', P_CDFILIPROC,
                                   V_PRXNRLANCNF, V_DTENTRSAID, V_VRLANCAMENTO, '');
                  END IF;
               ELSE
                  IMPOSTO_SAIDA(V_CDEMPRESA, V_CDINSCESTA, V_CDTIPOOPERTRD, '', P_CDFILIPROC,
                                V_PRXNRLANCNF, V_DTENTRSAID, V_VRLANCAMENTO, '');
               END IF;
            END IF;

            /* ATUALIZACAO DO ULTIMO CUSTO E VALOR DOS IMPOSTOS */
            IF V_IDENTRSAIDTRD = 'E' THEN
               GRAVA_IMPOSTO(P_CDFILIPROC, V_PRXNRLANCNF);
               CUSTO_LIQUIDO(P_CDFILIPROC, V_PRXNRLANCEST, V_VRPRODUTOS);
            END IF;

            V_PRXNRLANCNF  := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_PRXNRLANCNF) + 1)),10,0);
            V_PRXNRLANCEST := LPAD(RTRIM(TO_CHAR(TO_NUMBER(V_PRXNRLANCEST) + 1)),10,0);
            V_REPLICACAOOK := 1;
         END IF;
      END LOOP;
      CLOSE C_TRABREPLICDOC;

      IF V_REPLICACAOOK = 1 THEN
         UPDATE NOTAFISCAL
            SET IDNFUTILREPLIC = 'S'
          WHERE CDFILIAL   = P_CDFILIAL
            AND NRLANCTONF = P_NRLANCTONF;
      END IF;
   END LOOP;
   CLOSE C_NOTAFISCAL;
END;
/