/****** Object:  StoredProcedure [dbo].[P_EST_NF_ENT_ANALISE_ENTRADA_VALORES]    Script Date: 11/28/2013 09:35:25 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[P_EST_NF_ENT_ANALISE_ENTRADA_VALORES]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[P_EST_NF_ENT_ANALISE_ENTRADA_VALORES]
GO
GO
--EXEC P_EST_NF_ENT_ANALISE_ENTRADA_VALORES 1,6,0,0,'2018-01-01','2018-06-07'
CREATE PROCEDURE P_EST_NF_ENT_ANALISE_ENTRADA_VALORES @CD_EMP INT,
												       @CD_FILIAL INT,
													  @MES INT, 
													  @ANO INT, 
													  @DT_INI DATETIME=NULL,
												      @DT_FIM DATETIME=NULL AS
DECLARE @CD_CTR INT
DECLARE @CD_NF INT
DECLARE @NR_NF INT
SET NOCOUNT ON;
	DECLARE @DTINI AS DATETIME, @DTFIM AS DATETIME, @DTATUAL AS DATETIME;
	SET @DTATUAL= CONVERT(CHAR(10),GETDATE(),112)	
	IF @MES > 0 
	begin
		SET @DTINI  =  CONVERT(VARCHAR, @ANO*100+@MES ) + '01';
		SET @DTFIM  =  dbo.F_FINAL_MES(@DTINI);
	end

	IF @MES = 0 
	begin
		SET @DTINI  =  @DT_INI;
		SET @DTFIM  =  @DT_FIM;
	end

DECLARE CEstNFEntAnalise CURSOR FAST_FORWARD
FOR SELECT
	EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT.CD_CTR,
	EST_NF_ENT.CD_NF,
	EST_NF_ENT.NR_NF 
FROM
EST_NF_ENT INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT ON
EST_NF_ENT.CD_EMP = EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT.CD_EMP AND
EST_NF_ENT.CD_FILIAL = EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT.CD_FILIAL AND
EST_NF_ENT.CD_NF = EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT.CD_NF 
INNER JOIN 
(SELECT
	CD_EMP,
	CD_FILIAL,
	CD_NF,
	SUM(VLR_ICMS_SUBS) AS VLR_ICMS_SUBS_IT
FROM
	EST_NF_ENT_IT
WHERE
	CD_EMP =@CD_EMP
	AND CD_FILIAL=@CD_FILIAL
	AND DT_ENT BETWEEN @DTINI AND @DTFIM
GROUP BY
	CD_EMP,
	CD_FILIAL,
	CD_NF) RS ON
EST_NF_ENT.CD_EMP = RS.CD_EMP AND
EST_NF_ENT.CD_FILIAL = RS.CD_FILIAL AND
EST_NF_ENT.CD_NF = RS.CD_NF 
WHERE
	EST_NF_ENT.CD_EMP =@CD_EMP
	AND EST_NF_ENT.CD_FILIAL=@CD_FILIAL
	AND EST_NF_ENT.DT_ENT BETWEEN @DTINI AND @DTFIM
	AND VLR_ICMS_SUBS <> VLR_ICMS_SUBS_IT

	OPEN CEstNFEntAnalise;
	FETCH NEXT FROM CEstNFEntAnalise INTO @CD_CTR,
										  @CD_NF,
										  @NR_NF

	WHILE @@FETCH_STATUS = 0
		BEGIN
		PRINT 'Filial '+CONVERT(VARCHAR,@CD_FILIAL) + ' Codigo nota fiscal ' +CONVERT(VARCHAR,@CD_NF)+ ' nota fiscal ' +CONVERT(VARCHAR,@NR_NF)+  ' ' +CONVERT(VARCHAR, GETDATE(), 108);
		exec P_EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT_COMPARACAO @CD_CTR
		exec P_EST_NF_ENT_IT_RECALCULO_CUSTO @CD_EMP,@CD_FILIAL,0,0,1,'','',0,@CD_NF

	FETCH NEXT FROM CEstNFEntAnalise INTO @CD_CTR,
										  @CD_NF,
										  @NR_NF
    END
--FECHANDO CURSOS    
CLOSE CEstNFEntAnalise;    
    
--DESALOCANDO CURSOS DA MEMORIA    
DEALLOCATE CEstNFEntAnalise;