IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[P_GERA_LOTE_NFE]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[P_GERA_LOTE_NFE]
GO

CREATE PROCEDURE [dbo].[P_GERA_LOTE_NFE]         
AS 
CREATE TABLE #RsLote (ORDEM INT IDENTITY (1, 1),
					  CD_EMP INT,
					  CD_FILIAL INT,
					  CD_NF INT,
					  CD_CTR_CARTA_CORRECAO INT,
					  CD_INU INT,
					  TIPO_LOTE INT,
					  TIPO_NF INT,
					  DS_TIPO VARCHAR(100),
					  CONTIGENCIA INT)

CREATE TABLE #TipoDocumentoPendente (CD_EMP INT, 
							 CD_FILIAL INT,
							 CD_NF INT,
							 CD_CTR_CARTA_CORRECAO INT,
							 CD_INU INT,
							 TIPO_LOTE INT, 
							 TIPO_NF INT,
							 DS_TIPO VARCHAR(100))

DECLARE @CD_LOTE BIGINT
DECLARE @CD_EMP_CANCEL INT
DECLARE @CD_FILIAL_CANCEL INT
DECLARE @CD_NF_CANCEL INT
Declare @hoje date
	set @hoje=getdate()-1;


set nocount on;
CREATE TABLE #FiliaisSemChaveNFeAtivada (CD_EMP INT, CD_FILIAL INT)

	--VALIDA FILIAIS HABILITADAS PARA USO DO NFE  
	PRINT '> VALIDA FILIAIS HABILITADAS PARA USO DO NFE...';        
	INSERT INTO #FiliaisSemChaveNFeAtivada
		SELECT   
			F.CD_EMP,
			F.CD_FILIAL  
		FROM 
			PRC_FILIAL F LEFT JOIN EST_NF_NFE_LICENCAS L ON  
			L.CD_FILIAL = F.CD_FILIAL  
		WHERE  
			F.FLAG_NFE_HABILITADA = 1   
			AND ((L.CHAVE IS NULL) OR (L.UF IS NULL) OR (L.CNPJ IS NULL));  

	IF EXISTS(SELECT 1 FROM #FiliaisSemChaveNFeAtivada)  
	BEGIN  
		PRINT '  < *** ATENCAO - DESABILITANDO FILIAIS SEM LICENCA CADASTRADA! ***';  
		UPDATE 
			PRC_FILIAL 
		SET 
			FLAG_NFE_HABILITADA = 0   
		WHERE   
			CD_FILIAL IN (SELECT CD_FILIAL FROM #FiliaisSemChaveNFeAtivada)  
	END  
	ELSE  
		PRINT '  < OK - SEM FILIAIS HABILITADAS INDEVIDAMENTE';  
--...FIM VALIDACAO FILIAIS.

PRINT '> VERIFICANDO PENDENCIAS...';    
--Deletando pendencias desnecessarias
	PRINT '  - REMOVER LOTES DE ENTRADA DA PENDENCIA QUE SEJAM DE FILIAIS DESABILITADAS PARA NFE';
	DELETE	
		NFE_LOTE_PENDENTE 
	FROM       
		NFE_LOTE_PENDENTE INNER JOIN EST_NFE_LOTE_ENT NF ON
		NF.CD_NFE_LOTE = NFE_LOTE_PENDENTE.CD_NFE_LOTE
		INNER JOIN PRC_FILIAL FL ON
		FL.CD_EMP = NF.CD_EMP AND
		FL.CD_FILIAL = NF.CD_FILIAL AND
		FL.FLAG_NFE_HABILITADA = 0

	PRINT '  - REMOVER LOTES DE ENTRADA DA PENDENCIA QUE JÁ FORAM REGISTRADOS';      
	DELETE 
		NFE_LOTE_PENDENTE 
	FROM 
		NFE_LOTE_PENDENTE INNER JOIN EST_NFE_LOTE_ENT ON      
		EST_NFE_LOTE_ENT.CD_NFE_LOTE = NFE_LOTE_PENDENTE.CD_NFE_LOTE      
		INNER JOIN EST_NF_ENT_ARQ_DANFE ON      
		EST_NF_ENT_ARQ_DANFE.CD_EMP = EST_NFE_LOTE_ENT.CD_EMP AND
		EST_NF_ENT_ARQ_DANFE.CD_FILIAL = EST_NFE_LOTE_ENT.CD_FILIAL AND
		EST_NF_ENT_ARQ_DANFE.CD_NF = EST_NFE_LOTE_ENT.CD_NF;

	PRINT '  - REMOVER LOTES DE SAIDA DA PENDENCIA QUE JÁ FORAM REGISTRADOS';      
	DELETE 
		NFE_LOTE_PENDENTE 
	FROM        
		NFE_LOTE_PENDENTE INNER JOIN EST_NFE_LOTE_SAI ON      
		EST_NFE_LOTE_SAI.CD_NFE_LOTE = NFE_LOTE_PENDENTE.CD_NFE_LOTE      
		INNER JOIN EST_NF_SAI_ARQ_DANFE ON      
		EST_NF_SAI_ARQ_DANFE.CD_EMP = EST_NFE_LOTE_SAI.CD_EMP AND
		EST_NF_SAI_ARQ_DANFE.CD_FILIAL = EST_NFE_LOTE_SAI.CD_FILIAL AND      
		EST_NF_SAI_ARQ_DANFE.CD_NF = EST_NFE_LOTE_SAI.CD_NF;      
--Fim

	INSERT INTO #TipoDocumentoPendente
	SELECT                 
		TOP 500 A.CD_EMP,        
		A.CD_FILIAL, 
		A.CD_NF,
		A.CD_CTR_CARTA_CORRECAO, 
		A.CD_INU,
		(CASE        
			WHEN A.TIPO_NF IN (0, 1) THEN 0 -- Notas de entrada e saida       
			WHEN A.TIPO_NF IN (2, 3) THEN 1 -- Cancelamento
			WHEN A.TIPO_NF IN (4, 5) THEN 2 -- Carta correcao 
			WHEN A.TIPO_NF IN (6) THEN 3        
			WHEN A.TIPO_NF IN (7) THEN 4    -- Manifesto   
			WHEN A.TIPO_NF IN (8) THEN 5    --Inutilizacao   
			WHEN A.TIPO_NF IN (9) THEN 6			
		END) TIPO_LOTE,        
		A.TIPO_NF, 
		DS_TIPO
	FROM        
		V_EST_NF_NFE_PENDENTE_EMISSAO A 
	WHERE        
		A.CD_EMP = 1         
		AND A.PEND_SOLUC = 0        
		AND A.TIPO_NF in (0, 1, 2, 3, 4, 5, 7, 8, 9);

/***********************************************************************************************/
--NOTAS FICAIS SOMENTE CABEÇALHO	
/***********************************************************************************************/
   insert into #TipoDocumentoPendente
   select  
	   s.CD_EMP 
	   ,s.CD_FILIAL
	   ,s.CD_NF 
	   ,0 CD_CTR_CARTA_CORRECAO 
	   ,0 CD_INU 
	   ,0 TIPO_LOTE 
	   ,0 TIPO_NF 
	   ,'NF sem itens' DS_TIPO 
    From 
	   est_nf_sai s
	   join est_nf_serie f on 
	   s.cd_emp		= f.cd_emp and
	   s.cd_nf_serie	= f.cd_nf_serie
	   left join est_nf_sai_it i on 
	   s.cd_emp	 = i.cd_emp and
	   s.cd_nf	 = i.cd_nf and
	   s.cd_filial = i.cd_filial 
	   left join EST_NF_SAI_EST_NF_SAI_CPL c on 
	   s.cd_emp	 = c.cd_emp and
	   s.cd_nf	 = c.cd_nf and
	   s.cd_filial = c.cd_filial 
    where
	   i.cd_emp is null
	   and c.cd_emp is null
	   and f.tp_sr_serv=0
	   and f.tp_sr_nfe	=1
	   and s.dt_emi_nf > getdate()-2
	   AND S.DT_EMI_NF < CONVERT(DATE, GETDATE()) --Nao cancela as de hoje
	   and s.cd_emp	=1
	   and s.sts_nf	=0



     


/***********************************************************************************************/
	INSERT INTO #TipoDocumentoPendente
	SELECT                 
		TOP 500 A.CD_EMP,        
		A.CD_FILIAL, 
		A.CD_NF,
		A.CD_CTR_CARTA_CORRECAO, 
		A.CD_INU,
		(CASE        
			WHEN A.TIPO_NF IN (0, 1) THEN 0 -- Notas de entrada e saida       
			WHEN A.TIPO_NF IN (2, 3) THEN 1 -- Cancelamento
			WHEN A.TIPO_NF IN (4, 5) THEN 2 -- Carta correcao 
			WHEN A.TIPO_NF IN (6) THEN 3        
			WHEN A.TIPO_NF IN (7) THEN 4    -- Manifesto   
			WHEN A.TIPO_NF IN (8) THEN 5    --Inutilizacao 
			
		END) TIPO_LOTE,        
		A.TIPO_NF, 
		DS_TIPO
	FROM 
		V_EST_NF_NFE_PENDENTE_EMISSAO a
		left join est_nf_sai_it i on 
		a.cd_emp	= i.cd_emp and
		a.cd_nf		= i.cd_nf and
		a.cd_filial = i.cd_filial
	WHERE
		a.PEND_SOLUC = 0
		and a.cd_emp =1
		AND a.TIPO_NF in (0, 1)
		and i.cd_emp is null;


--Cancelando notas fiscais de entrada sem itens
IF EXISTS(SELECT
				p.CD_NF
		  FROM
				#TipoDocumentoPendente P LEFT OUTER JOIN EST_NF_ENT_IT i ON
				p.CD_EMP = i.CD_EMP AND
				p.CD_FILIAL = i.CD_FILIAL AND
				p.CD_NF = i.CD_NF
		   WHERE
			    i.CD_NF IS NULL
			   AND p.TIPO_NF=0)
begin
	SET @CD_EMP_CANCEL=0
	SET @CD_FILIAL_CANCEL=0
	SET @CD_NF_CANCEL=0
	PRINT '  - CANCELANDO NOTAS FISCAIS DE ENTRADA SEM ITENS';    
	
    BEGIN
	  
	   CREATE TABLE #tmpDeleteSemItem(cd_emp int, cd_Filial int, cd_nf int  );

	   insert into #tmpDeleteSemItem
	   select distinct 
		  p.cd_emp,
		  p.cd_filial,
		  p.cd_nf
	   FROM EST_NF_ENT_EST_NF_SAI_TRANSF a
		   INNER JOIN EST_NF_ENT b ON A.CD_EMP = B.CD_EMP
								AND A.CD_FIL_DEST = B.CD_FILIAL
								AND A.CD_NF_ENT = B.CD_NF
		   INNER JOIN #TipoDocumentoPendente P ON 
		   P.CD_EMP    = B.CD_EMP AND 
		   P.CD_FILIAL = B.CD_FILIAL AND 
		   P.CD_NF     = B.CD_NF

		   LEFT OUTER JOIN EST_NF_ENT_IT i ON B.CD_EMP = i.CD_EMP
									   AND B.CD_FILIAL = i.CD_FILIAL
									   AND B.CD_NF = i.CD_NF
	   WHERE 
		  b.cd_emp=1
		  and i.CD_NF IS NULL;

	INSERT INTO #tmpDeleteSemItem
	   SELECT DISTINCT
				P.CD_EMP,
				P.CD_FILIAL,
				P.CD_NF
		  FROM
				#TIPODOCUMENTOPENDENTE P INNER JOIN EST_NF_ENT E 	ON  
				P.CD_EMP    = E.CD_EMP AND 
				P.CD_FILIAL = E.CD_FILIAL AND 
				P.CD_NF     = E.CD_NF
				INNER JOIN GLB_MOV_OP OP ON
				E.CD_NT_MOV =OP.CD_MOV_OP 
				LEFT OUTER JOIN EST_NF_ENT_IT I ON
				P.CD_EMP = I.CD_EMP AND
				P.CD_FILIAL = I.CD_FILIAL AND
				P.CD_NF = I.CD_NF
		   WHERE
			   E.CD_EMP = 1 
			   AND E.DT_ENT = GETDATE()
			   AND I.CD_NF IS NULL
			   AND P.TIPO_NF=0
			   AND OP.TP_MOV_OP_TRANSA =0
			   AND OP.TP_MOV =0;


	   IF EXISTS (SELECT * fROM #tmpDeleteSemItem )
	   BEGIN 
		  BEGIN TRY
		  DELETE FROM a
		  FROM EST_NF_ENT_EST_NF_SAI_TRANSF_MANIFESTO_PENDENTE a
			  INNER JOIN #tmpDeleteSemItem b ON A.CD_EMP = B.CD_EMP
								    AND A.CD_FIL_DEST = B.CD_FILIAL
								    AND A.CD_NF_ENT = B.CD_NF;
		  DELETE FROM a
		  FROM EST_NF_ENT_EST_NF_SAI_TRANSF a
			  INNER JOIN #tmpDeleteSemItem b ON A.CD_EMP = B.CD_EMP
								    AND A.CD_FIL_DEST = B.CD_FILIAL
								    AND A.CD_NF_ENT = B.CD_NF;
								
		  DELETE FROM c
		  FROM 
			  EST_NFE_LOTE_ENT a
			  INNER JOIN #tmpDeleteSemItem b ON 
			  A.CD_EMP    = B.CD_EMP AND 
			  A.CD_FILIAL = B.CD_FILIAL AND 
			  A.CD_NF     = B.CD_NF
				   
			  join EST_NFE_LOTE_ENT_ERR c on 
			  A.CD_NFE_LOTE    = c.CD_NFE_LOTE AND 
			  A.CD_NFE_LOTE_ENT = c.CD_NFE_LOTE_ENT 
			   ;
			       
		  DELETE FROM a
		  FROM #TipoDocumentoPendente a
			  INNER JOIN #tmpDeleteSemItem b ON 
			  A.CD_EMP    = B.CD_EMP AND 
			  A.CD_FILIAL = B.CD_FILIAL AND 
			  A.CD_NF     = B.CD_NF;		    
		  DELETE FROM a
		  FROM EST_NFE_LOTE_ENT a
			  INNER JOIN #tmpDeleteSemItem b ON 
			  A.CD_EMP    = B.CD_EMP AND 
			  A.CD_FILIAL = B.CD_FILIAL AND 
			  A.CD_NF     = B.CD_NF;

		  DELETE FROM a
		  FROM EST_NF_ENT_NFE_PEND a
			  INNER JOIN #tmpDeleteSemItem b ON 
			  A.CD_EMP    = B.CD_EMP AND 
			  A.CD_FILIAL = B.CD_FILIAL AND 
			  A.CD_NF     = B.CD_NF

		  DELETE FROM a 
		  FROM EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT_CONFIRMACAO_OPERACAO_PENDENTE a 
			  INNER JOIN #tmpDeleteSemItem b ON 
			  A.CD_EMP    = B.CD_EMP AND 
			  A.CD_FILIAL = B.CD_FILIAL AND 
			  A.CD_NF     = B.CD_NF


		  DELETE FROM a
		  FROM EST_NF_ENT a
			  INNER JOIN #tmpDeleteSemItem b ON 
			  A.CD_EMP    = B.CD_EMP AND 
			  A.CD_FILIAL = B.CD_FILIAL AND 
			  A.CD_NF     = B.CD_NF
		  END TRY 
		  BEGIN CATCH

			 Declare @Msg varchar(300)
			 set @Msg= Error_MEssage() ;
			 print 'Falha remover notas sem itens' + char(13) + @Msg;

		  END CATCH
	   END
    END;

	--Cancelando itens da nota fiscal e voltando o estoque se necessario
	DECLARE CnotasEntradaSemItensCancel CURSOR FAST_FORWARD FOR 
		  SELECT
				p.CD_EMP,
				p.CD_FILIAL,
				p.CD_NF
		  FROM
				#TipoDocumentoPendente P LEFT OUTER JOIN EST_NF_ENT_IT i ON
				p.CD_EMP = i.CD_EMP AND
				p.CD_FILIAL = i.CD_FILIAL AND
				p.CD_NF = i.CD_NF
				LEFT OUTER JOIN EST_NF_ENT_CANCEL_SOLIC C ON
				p.CD_EMP = C.CD_EMP AND
				p.CD_FILIAL = C.CD_FILIAL AND
				p.CD_NF = C.CD_NF 
		   WHERE
			   i.CD_NF IS NULL
			   AND p.TIPO_NF=0
			   AND C.CD_NF IS NULL

	OPEN CnotasEntradaSemItensCancel
	FETCH NEXT FROM CnotasEntradaSemItensCancel INTO @CD_EMP_CANCEL, @CD_FILIAL_CANCEL,@CD_NF_CANCEL
		WHILE @@FETCH_STATUS=0
		  begin
		  --Inserindo solicitacao de cancelamento
		  INSERT INTO EST_NF_ENT_CANCEL_SOLIC
			(CD_EMP,
			CD_FILIAL,
			CD_NF,
			CD_USU,
			CD_MT_CANCEL,
			ST_DENEGADA,
			DT_CANCEL,
			DT_CAD,
			HISTORICO)
		SELECT
			@CD_EMP_CANCEL, 
			@CD_FILIAL_CANCEL,
			@CD_NF_CANCEL,
			1,
			0,
			0,
			CONVERT(CHAR(10),GETDATE(),112),
			GETDATE(),
			'NOTA FISCAL SEM ITENS'
			
			EXEC P_EST_NF_ENT_CANCELAMENTO @CD_EMP_CANCEL, @CD_FILIAL_CANCEL,@CD_NF_CANCEL

		  FETCH NEXT FROM CnotasEntradaSemItensCancel INTO  @CD_EMP_CANCEL, @CD_FILIAL_CANCEL,@CD_NF_CANCEL
		end
	PRINT 'Concluido.'
	CLOSE CnotasEntradaSemItensCancel;
	DEALLOCATE CnotasEntradaSemItensCancel;
end	

--Cancelando notas fiscais de saidas sem itens
IF EXISTS(SELECT
				p.CD_NF
		  FROM
				#TipoDocumentoPendente P LEFT OUTER JOIN EST_NF_SAI_IT i ON
				p.CD_EMP = i.CD_EMP AND
				p.CD_FILIAL = i.CD_FILIAL AND
				p.CD_NF = i.CD_NF
		   WHERE
			   i.CD_NF	IS NULL
			   AND p.TIPO_NF=1)

begin
	SET @CD_EMP_CANCEL=0
	SET @CD_FILIAL_CANCEL=0
	SET @CD_NF_CANCEL=0
	PRINT '  - CANCELANDO NOTAS FISCAIS DE SAIDAS SEM ITENS'; 

	
	--Cancelando itens da nota fiscal e voltando o estoque se necessario
	DECLARE CnotasSaidasSemItensCancel CURSOR FAST_FORWARD FOR 
		  SELECT
				p.CD_EMP,
				p.CD_FILIAL,
				p.CD_NF
		  FROM
				#TipoDocumentoPendente P 
				LEFT OUTER JOIN EST_NF_SAI_IT i ON
				p.CD_EMP = i.CD_EMP AND
				p.CD_FILIAL = i.CD_FILIAL AND
				p.CD_NF = i.CD_NF
		   WHERE
			   i.CD_NF	IS NULL	
			   AND p.TIPO_NF=1
		  UNION 
			 SELECT
				p.CD_EMP,
				p.CD_FILIAL,
				p.CD_NF
		  FROM
				EST_NF_SAI P 
				JOIN EST_NF_SERIE R ON 
				P.CD_NF_SERIE = R.CD_NF_SERIE
				LEFT OUTER JOIN EST_NF_SAI_IT i ON
				p.CD_EMP = i.CD_EMP AND
				p.CD_FILIAL = i.CD_FILIAL AND
				p.CD_NF = i.CD_NF
		   WHERE
			   i.CD_NF	IS NULL	 
			   AND P.STS_NF=0
			   AND P.DT_EMI_NF > @hoje
			   AND R.TP_SR_NFE=1
			   AND R.TP_SR_SERV=0

	OPEN CnotasSaidasSemItensCancel
	FETCH NEXT FROM CnotasSaidasSemItensCancel INTO @CD_EMP_CANCEL, @CD_FILIAL_CANCEL,@CD_NF_CANCEL
		WHILE @@FETCH_STATUS=0
		  begin
	   
			EXEC P_EST_NF_SAI_CANCELAMENTO @CD_EMP_CANCEL, @CD_FILIAL_CANCEL,@CD_NF_CANCEL

		  FETCH NEXT FROM CnotasSaidasSemItensCancel INTO  @CD_EMP_CANCEL, @CD_FILIAL_CANCEL,@CD_NF_CANCEL
		end
	PRINT 'Concluido.'
	CLOSE CnotasSaidasSemItensCancel;
	DEALLOCATE CnotasSaidasSemItensCancel;
end	


--Cancelando notas fiscais de saidas nao canceladas no sistema
IF EXISTS(SELECT
				ens.CD_NF
		  FROM
				EST_NF_SAI_CANCEL_SOLIC canc INNER JOIN EST_NF_SAI ens ON
				canc.CD_EMP = ens.CD_EMP AND
				canc.CD_FILIAL = ens.CD_FILIAL AND
				canc.CD_NF = ens.CD_NF
		   WHERE
			    ens.STS_NF=0)

begin
	SET @CD_EMP_CANCEL=0
	SET @CD_FILIAL_CANCEL=0
	SET @CD_NF_CANCEL=0
	PRINT '  - CANCELANDO NOTAS FISCAIS DE SAIDAS NAO CANCELADAS NO SISTEMA'; 

	
	--Cancelando notas fiscais com requisicao de cancelamento mas nao canceladas no sistema
	DECLARE CnotasSaidasNaoCancel CURSOR FAST_FORWARD FOR 
		  SELECT
				ens.CD_EMP,
				ens.CD_FILIAL,
				ens.CD_NF
		  FROM
				EST_NF_SAI_CANCEL_SOLIC canc 
				INNER JOIN EST_NF_SAI ens ON
				canc.CD_EMP = ens.CD_EMP AND
				canc.CD_FILIAL = ens.CD_FILIAL AND
				canc.CD_NF = ens.CD_NF
		   WHERE
			    ens.STS_NF=0

	OPEN CnotasSaidasNaoCancel
	FETCH NEXT FROM CnotasSaidasNaoCancel INTO @CD_EMP_CANCEL, @CD_FILIAL_CANCEL,@CD_NF_CANCEL
		WHILE @@FETCH_STATUS=0
		  begin
	   
			begin try
			 EXEC P_EST_NF_SAI_CANCELAMENTO @CD_EMP_CANCEL, @CD_FILIAL_CANCEL, @CD_NF_CANCEL
			 end try
			 begin catch 
				Print 'Falhas ao tentar cancelar a cd_nf ' + convert(varchar, @CD_NF_CANCEL) + ' Filial ' + convert(varchar,@CD_FILIAL_CANCEL)
			 end catch

		  FETCH NEXT FROM CnotasSaidasNaoCancel INTO  @CD_EMP_CANCEL, @CD_FILIAL_CANCEL,@CD_NF_CANCEL
		end
	PRINT 'Concluido.'
	CLOSE CnotasSaidasNaoCancel;
	DEALLOCATE CnotasSaidasNaoCancel;
end	




SET  @CD_LOTE = (SELECT ISNULL(MAX(CD_NFE_LOTE), 0) + 1 FROM EST_NFE_LOTE);     
PRINT 'Gerando dados para o lote'
INSERT INTO #RsLote		
	SELECT    
		d.CD_EMP
		, d.CD_FILIAL
		, d.CD_NF
		, d.CD_CTR_CARTA_CORRECAO
		, d.CD_INU
		, d.TIPO_LOTE
		, d.TIPO_NF
		, d.DS_TIPO,
		0 AS CONTIGENCIA
	FROM
		#TipoDocumentoPendente d
ORDER BY
	CD_EMP,
	CD_FILIAL,
	CD_NF,
	CD_CTR_CARTA_CORRECAO; 

--Alterando para contingencia se estiver liberado
UPDATE
	l
SET 
	l.CONTIGENCIA=1
FROM
	#RsLote l INNER JOIN EST_CONTINGENCIA c ON
	l.CD_EMP = c.CD_EMP AND
	l.CD_FILIAL = c.CD_FILIAL
WHERE
	CONVERT(DATETIME, CONVERT(CHAR(10), DT_CONTINGENCIA, 112)) = CONVERT(CHAR(10),GETDATE(),112)
	AND STATUS_CONTINGENCIA=1

		
INSERT INTO EST_NFE_LOTE (CD_NFE_LOTE, CD_EMP, CD_FILIAL, TP_LOTE, DT_CAD, HR_CAD, CD_USU, REG_CONTG)
SELECT
	@CD_LOTE + ORDEM, 
	CD_EMP, 
	CD_FILIAL, 
	TIPO_LOTE,
	GETDATE(), 
	GETDATE() , 
	1, 
	CONTIGENCIA
FROM
	#RsLote
ORDER BY
	ORDEM; 

PRINT '  - INSERIU EST_NFE_LOTE...';        
INSERT INTO NFE_LOTE_PENDENTE 
SELECT
	@CD_LOTE + ORDEM, 
	TIPO_LOTE,
	TIPO_NF
FROM
	#RsLote
ORDER BY
	ORDEM; 

PRINT '  - INSERIU NFE_LOTE_SAI...';        
INSERT INTO EST_NFE_LOTE_SAI (CD_NFE_LOTE, CD_NFE_LOTE_SAI, CD_EMP, CD_FILIAL, CD_NF, NR_AUTORIZADOR) 
 SELECT
	@CD_LOTE + ORDEM, 
	ORDEM, 
	CD_EMP, 
	CD_FILIAL,
	CD_NF,
	0
FROM
	#RsLote
WHERE
	TIPO_NF IN (1,2)
ORDER BY
	ORDEM;           

PRINT '  - INSERIU EST_NFE_LOTE_ENT...';        
INSERT INTO EST_NFE_LOTE_ENT (CD_NFE_LOTE, CD_NFE_LOTE_ENT, CD_EMP, CD_FILIAL, CD_NF, NR_AUTORIZADOR) 
 SELECT
	@CD_LOTE + ORDEM, 
	ORDEM, 
	CD_EMP, 
	CD_FILIAL,
	CD_NF,
	0
FROM
	#RsLote
WHERE
	TIPO_NF  IN (0,3,7)
ORDER BY
	ORDEM;     

PRINT '  - INSERIU EST_NFE_CARTA_CORRECAO_EST_NFE_LOTE...';        
INSERT INTO EST_NFE_CARTA_CORRECAO_EST_NFE_LOTE (CD_NFE_LOTE, CD_CTR_CARTA_CORRECAO, CD_USU) 
 SELECT
	@CD_LOTE + ORDEM, 
	CD_CTR_CARTA_CORRECAO, 
	1
FROM
	#RsLote
WHERE
	TIPO_NF IN (4,5)
ORDER BY
	ORDEM;  

PRINT '  - INSERIU EST_NFE_LOTE_EST_NF_NFE_INU...';        
INSERT INTO EST_NFE_LOTE_EST_NF_NFE_INU (CD_NFE_LOTE, CD_INU, CD_USU) 
 SELECT
	@CD_LOTE + ORDEM, 
	CD_INU,
	1
FROM
	#RsLote
WHERE
	TIPO_NF=8
ORDER BY
	ORDEM; 
	
	
PRINT '  - INSERIU EST_NFE_INF_EFET_PGTO_INTEG_EST_NFE_LOTE...';        
INSERT INTO EST_NFE_INF_EFET_PGTO_INTEG_EST_NFE_LOTE (CD_NFE_LOTE, CD_CTR_INF_EFET_PGTO_INTEG, CD_USU, DT_CAD, HR_CAD) 
 SELECT
	@CD_LOTE + ORDEM, 
	CD_CTR_CARTA_CORRECAO, 
	1,
	GETDATE(),
	GETDATE()
FROM
	#RsLote
WHERE
	TIPO_NF IN (9)
ORDER BY
	ORDEM;  

DROP TABLE #FiliaisSemChaveNFeAtivada;
DROP TABLE #TipoDocumentoPendente;
DROP TABLE 	#RsLote;