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

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 /*
=======================================================================================
'Job.................: Linx - Manutencao dia 1
'Função..............: 
'Objetivo............: Fechamento de estoque mensal
'Tabelas.............: EST_FECHA
'Dt Modificação......: 04/05/2021
'Modificação.........: Tag #A001 - Tratamento de exceção
					   Tag #A002 - Evitar key lookup 
					   Tag #I001 - Evitar Sort
'=======================================================================================
Tag #A001 - Alteração do codigo  
Tag #I001 - Inclusão de novo codigo 

*/
--EXECUTE P_EST_FECHA_FILIAL 1,1,2015,11      
CREATE PROCEDURE [dbo].[P_EST_FECHA_FILIAL_MES] @CD_EMP INT, 
												@CD_FILIAL INT, 
												@ANO INT=NULL, 
												@MES VARCHAR(2)=NULL, 
												@PARCIAL INT=0,
												@CD_PROD INT=0,
												@CD_USU INT=1
									  AS
												 
BEGIN TRY

SET DEADLOCK_PRIORITY HIGH;
SET NOCOUNT ON;
DECLARE @agora DATETIME
DECLARE @DTABERTURABALAN DATETIME
 
IF @ano IS NULL OR @mes IS NULL
	SELECT @agora=DATEADD(month, -1, GETDATE()), @ano=YEAR(@agora), @mes=MONTH(@agora)

if @parcial=1
	SELECT @agora=GETDATE(),
			 @ano=YEAR(@agora), 
			 @mes=MONTH(@agora)


IF  LEN(@mes)=1 
	SET @mes='0' + @mes

DECLARE 
	@dtInicioMes DATETIME, 
	@dtInicioMesPosterior DATETIME, 
	@dtInicioMesAnterior DATETIME, 
	@anoAnt INT, 
	@mesAnt INT,
	@ANO_INI_SIS INT,
	@MES_INI_SIS INT,
	@dtDiaFinalMesFechamento DATETIME;

	IF @PARCIAL =1
	BEGIN
		
		Print 'Recalculo custo saidas' 
		EXEC P_EST_NF_SAI_IT_RECALCULO_CUSTO_ALL @mes,@ano,@cd_filial;
		Print 'Recalculo custo entrada' 
		EXEC P_EST_NF_ENT_IT_RECALCULO_CUSTO_ALL @mes,@ano,@cd_filial ;
	END 

	
	SELECT	
			@dtInicioMes = convert(char(8),CONVERT(CHAR(4), @ano) +  @mes + '01'),
			@dtInicioMesPosterior = DATEADD(month, 1, @dtInicioMes), 
			@dtInicioMesAnterior = DATEADD(month, -1, @dtInicioMes), 
			@anoAnt = DATEPART(year, @dtInicioMesAnterior), 
			@mesAnt=DATEPART(month, @dtInicioMesAnterior),
			@dtDiaFinalMesFechamento = DATEADD(DAY, -1, @dtInicioMesPosterior)

	Print 'Fechando estoque periodo ' + convert(varchar,@dtInicioMes,10) + ' e ' + convert(varchar,@dtInicioMesPosterior,10) + ' dia final mes fechamento ' + convert(varchar,@dtDiaFinalMesFechamento,10)
	--Verifica se o mes informado e o mesmo do mes de inicio do sistema
	--Se for pega as transacoes a partir da data de virada da loja

	if exists (SELECT     
						DT_INI_SISTEMA
				   FROM         
						PRC_FILIAL
				   WHERE     
						MONTH(DT_INI_SISTEMA) = @mes
						AND YEAR(DT_INI_SISTEMA) = @ano
						AND CD_FILIAL = @cd_filial 
						AND CD_EMP = @cd_emp)
	BEGIN  
		SET @DTINICIOMES=(SELECT     
								DT_INI_SISTEMA
						   FROM         
								PRC_FILIAL
						   WHERE     
								CD_FILIAL = @CD_FILIAL 
								AND CD_EMP = @CD_EMP)
	END
	
	--Fim  
	SET @ANO_INI_SIS = (SELECT  DATEPART(YEAR, DT_INI_SISTEMA)
			   FROM         
					PRC_FILIAL
			   WHERE     
					CD_FILIAL = @CD_FILIAL 
					AND CD_EMP = @CD_EMP);
					
	SET @MES_INI_SIS = (SELECT  DATEPART(MONTH, DT_INI_SISTEMA)
			   FROM         
					PRC_FILIAL
			   WHERE     
					CD_FILIAL = @CD_FILIAL 
					AND CD_EMP = @CD_EMP)
	
	--se o mes de reprocessamento for anterior ao inicio do sistema aborta o fechamento
	if (@ANO*100+@MES) < (@ANO_INI_SIS*100+@MES_INI_SIS)
	BEGIN
		Print 'Nao e possivel refazer o fechamento de estoque anterior a virada da loja.' 
		RETURN;
	END 
	
	if @CD_USU <> 1
	begin
		--Verifica bloqueio contabil 
		IF EXISTS(SELECT  TOP 1 CD_EMP
					FROM 
						EST_PROD_INVENTARIO  
					WHERE
						DT_REF >= @dtDiaFinalMesFechamento
						AND CD_EMP=@CD_EMP
						AND CD_FILIAL=@CD_FILIAL)
		begin
			Print 'Data de processamento com bloqueio. Inventario ja registrado para o periodo solicitado. - Time : ' +convert(varchar,getdate(),108);
			RETURN; 
		end 
	end
	SELECT
		@DTABERTURABALAN = DT_ABERTURA_BALAN
	FROM
		EST_PROD_BALAN_ABERTURA_RETROATIVA
	WHERE
		CD_EMP = @CD_EMP
		AND CD_FILIAL = @CD_FILIAL
		AND STS_EVENTOS_BALAN = 0
	Print 'Data de posicao estoque.: ' + CONVERT( CHAR(10),@DTABERTURABALAN,112)
	 
	IF @DTABERTURABALAN IS NULL
	begin
		SET @DTABERTURABALAN= CONVERT(CHAR(10),GETDATE(),112)
	end

/**********************************************************************************************************************/
--Criacao tabelas auxiliares
/**********************************************************************************************************************/
  
	Print 'Cria as tabelas temporarias - Time ' + convert(varchar(20),getdate(),108);
	IF  OBJECT_ID('TEMPDB.dbo.#TABLE_AUX') IS NOT NULL
	BEGIN
		DROP TABLE #TABLE_AUX
	END 
	IF  OBJECT_ID('TEMPDB.dbo.#PROD_INI') IS NOT NULL
	BEGIN
		DROP TABLE #PROD_INI
	END 
	IF  OBJECT_ID('TEMPDB.dbo.#PROD_FECHA_ANT') IS NOT NULL
	BEGIN
		DROP TABLE #PROD_FECHA_ANT
	END 
	IF  OBJECT_ID('TEMPDB.dbo.#PROD_SAI_NF') IS NOT NULL
	BEGIN
		DROP TABLE #PROD_SAI_NF
	END 
	IF  OBJECT_ID('TEMPDB.dbo.#PROD_ENT_NF') IS NOT NULL
	BEGIN
		DROP TABLE #PROD_ENT_NF
	END  
	IF  OBJECT_ID('TEMPDB.dbo.#PROD_SAI_NF_FLUT') IS NOT NULL
	BEGIN
		DROP TABLE #PROD_SAI_NF_FLUT
	END  
	IF  OBJECT_ID('TEMPDB.dbo.#PROD_ENT_NF_FLUT') IS NOT NULL
	BEGIN
		DROP TABLE #PROD_ENT_NF_FLUT 
	END 
	
	IF  OBJECT_ID('dbo.#PROD_ENT_NF_FLUT') IS NOT NULL
	BEGIN
		DROP TABLE #PROD_ENT_NF_FLUT 
	END 
	
	 
	IF  OBJECT_ID('TEMPDB.dbo.#PROD_NF_SAI_EM_TERC') IS NOT NULL
	BEGIN
		DROP TABLE #PROD_NF_SAI_EM_TERC 
	END  
	IF  OBJECT_ID('TEMPDB.dbo.#PROD_NF_ENT_EM_TERC') IS NOT NULL
	BEGIN
		DROP TABLE #PROD_NF_ENT_EM_TERC 
	END  
	IF  OBJECT_ID('TEMPDB.dbo.#PROD_NF_ENT_DE_TERC') IS NOT NULL
	BEGIN
		DROP TABLE #PROD_NF_ENT_DE_TERC 
	END  
	
	IF  OBJECT_ID('TEMPDB.dbo.#PROD_NF_SAI_DE_TERC') IS NOT NULL
	BEGIN
		DROP TABLE #PROD_NF_SAI_DE_TERC 
	END 
	IF  OBJECT_ID('TEMPDB.dbo.#PROD_VD_PDV') IS NOT NULL
	BEGIN
		DROP TABLE #PROD_VD_PDV 
	END 
	IF  OBJECT_ID('TEMPDB.dbo.#PROD_AJUSTE') IS NOT NULL
	BEGIN
		DROP TABLE #PROD_AJUSTE 
	END 
	IF  OBJECT_ID('TEMPDB.dbo.#PROD_SAI_PED_VD') IS NOT NULL
	BEGIN
		DROP TABLE #PROD_SAI_PED_VD 
	END 
	IF  OBJECT_ID('TEMPDB.dbo.#PROD_ENT_PED_CP') IS NOT NULL
	BEGIN
		DROP TABLE #PROD_ENT_PED_CP 
	END 
	IF  OBJECT_ID('TEMPDB.dbo.#PROD_ENT_PED_CP') IS NOT NULL
	BEGIN
		DROP TABLE #PROD_ENT_PED_CP 
	END 
	IF  OBJECT_ID('TEMPDB.dbo.#PROD_AJUSTE_FLUT') IS NOT NULL
	BEGIN
		DROP TABLE #PROD_AJUSTE_FLUT 
	END  
	IF  OBJECT_ID('TEMPDB.dbo.#PROD_AJUSTE_EM_TERC') IS NOT NULL
	BEGIN
		DROP TABLE #PROD_AJUSTE_EM_TERC 
	END  
	IF  OBJECT_ID('TEMPDB.dbo.#PROD_AJUSTE_DE_TERC') IS NOT NULL
	BEGIN
		DROP TABLE #PROD_AJUSTE_DE_TERC 
	END  

	IF  OBJECT_ID('TEMPDB.dbo.#PROD_ACERTO_CUSTO') IS NOT NULL
	BEGIN
		DROP TABLE #PROD_ACERTO_CUSTO 
	END   
	
	IF  OBJECT_ID('TEMPDB.dbo.#PROD_ENT_NF_CANC') IS NOT NULL
	BEGIN
		DROP TABLE #PROD_ENT_NF_CANC 
	END   	 
	
	IF  OBJECT_ID('TEMPDB.dbo.#PROD_ENT_NF_EST') IS NOT NULL
	BEGIN
		DROP TABLE #PROD_ENT_NF_EST 
	END    
		
	IF  OBJECT_ID('TEMPDB.dbo.#PROD_SAI_NF_EST') IS NOT NULL
	BEGIN
		DROP TABLE #PROD_SAI_NF_EST 
	END    
		
	IF  OBJECT_ID('TEMPDB.dbo.#RsProdFecha') IS NOT NULL
	BEGIN
		DROP TABLE #RsProdFecha
	END   	 

	
	CREATE TABLE #PROD_INI (CD_PROD		INT,
							CD_SIGLA	INT,
							LISTA_PROD	INT,
							PIS_COFINS	INT,
							VLR_CUSTO_CAD		MONEY,
							VLR_CUSTO_MD_CAD	MONEY,
							VLR_CUSTO_MOV		MONEY,
							VLR_CUSTO_MD_MOV	MONEY,
							VLR_TABELA			MONEY,
							MEDIAF				MONEY,
							EMAX				MONEY,
							ESEG				MONEY,
							VLR_CUSTO_GER		MONEY,
							VLR_SALDO_CUSTO		MONEY);
						 
	CREATE TABLE #PROD_FECHA_ANT(CD_PROD		INT,
								QT_EST_FECHA		MONEY,
								QT_EST_EM_TERC		MONEY,
								QT_EST_DE_TERC		MONEY,
								QT_EST_FLUT			MONEY,
								VLR_EST_INICIAL_CM	MONEY,
								QT_INI_FLUT			MONEY,
								VLR_INI_FLUT		MONEY,
								VLR_SALDO_CUSTO_INI		MONEY);
								 
	CREATE TABLE #PROD_SAI_NF (CD_PROD				INT,
								QT_IT_NF_SAI		MONEY,
								QT_IT_SAI_TRANF		MONEY,
								VLR_CMV				MONEY,
								VLR_SAIDA_TRANSF_CM	MONEY,
								QT_DEV_CP			MONEY,
								VLR_DEV_CP_CM		MONEY,
								QT_SAI_VD			MONEY,
								QT_SAI_BONIFICA		MONEY,
								QT_SAI_OUTRAS		MONEY,
								VLR_SAI_VD			MONEY,
								VLR_SAI_BONIFICA	MONEY,
								VLR_SAI_OUTRAS		MONEY,
								QT_SAI_PERDA		MONEY,
								VLR_SAI_PERDA		MONEY);

	CREATE TABLE #PROD_ENT_NF (CD_PROD					INT,
								QT_IT_NF_ENT			MONEY,
								QT_IT_ENT_TRANSF		MONEY,
								VLR_ICMS_SUBS			MONEY,
								VLR_ICMS_IT				MONEY,
								VLR_CUSTO_MES_FECHA		MONEY,
								VLR_ENTRADAS_CE			MONEY,
								VLR_ENTRADA_TRANSF_CM	MONEY,
								QT_DEV_VD				MONEY,
								VLR_DEV_VD_CM			MONEY,
								QT_ENT_CP				MONEY,
								QT_ENT_BONIFICA			MONEY,
								QT_ENT_OUTRAS			MONEY,
								VLR_ENT_CP				MONEY,
								VLR_ENT_BONIFICA		MONEY,
								VLR_ENT_OUTRAS			MONEY);

	CREATE TABLE #PROD_SAI_NF_FLUT (CD_PROD				INT,
								QT_EST_FLUT				MONEY,
								QT_DEV_CP_FLUTUANTE		MONEY,
								VLR_DEV_CP_FLUTUANTE	MONEY,
								QT_SAI_PERDA_FLUTUANTE	MONEY,
								VLR_SAI_PERDA_FLUTUANTE	MONEY,
								QT_SAI_TRANSF_FLUT		MONEY,
								VLR_SAI_TRANSF_FLUT		MONEY,
								QT_SAI_OUTRAS_FLUTUANTE	MONEY,
								VLR_SAI_OUTRAS_FLUTUANTE MONEY);

	CREATE TABLE #PROD_ENT_NF_FLUT ( CD_PROD				INT,
									QT_EST_FLUT				MONEY,
									QT_ENT_TRANSF_FLUT		MONEY,
									VLR_ENT_TRANSF_FLUT		MONEY,
									QT_DEV_VD_FLUTUANTE			MONEY,
									VLR_DEV_VD_FLUTUANTE		MONEY,
									QT_ENT_OUTRAS_FLUTUANTE		MONEY,
									VLR_ENT_OUTRAS_FLUTUANTE	MONEY);

	CREATE TABLE #PROD_NF_SAI_EM_TERC (CD_PROD INT ,QT_EST_EM_TERC MONEY);
	
	CREATE TABLE #PROD_NF_ENT_EM_TERC(CD_PROD				INT,
									  VLR_ICMS_SUBS			MONEY,
									  VLR_ICMS_IT			MONEY,
									  VLR_CUSTO_MES_FECHA	MONEY,
									  QT_EST_EM_TERC		MONEY);

	CREATE TABLE #PROD_NF_ENT_DE_TERC (CD_PROD INT,
										VLR_ICMS_SUBS			MONEY,	
										VLR_ICMS_IT				MONEY,
										VLR_CUSTO_MES_FECHA		MONEY,
										QT_EST_DE_TERC			MONEY);

	CREATE TABLE #PROD_NF_SAI_DE_TERC (CD_PROD INT,QT_EST_DE_TERC MONEY);

	CREATE TABLE #PROD_VD_PDV ( CD_PROD		MONEY,
									QT_IT_PDV	MONEY,
									VLR_CMV		MONEY);
	
	CREATE TABLE #PROD_AJUSTE(CD_PROD			INT,
								QT_IT_IMP		MONEY,
								VLR_AJUSTES_CM	MONEY,
								QT_DEV_VD		MONEY,
								VLR_DEV_VD_CM	MONEY,
								QT_AJUSTE_ENT	MONEY,
								QT_AJUSTE_SAI	MONEY,
								VLR_AJUSTE_ENT_CM MONEY,
								VLR_AJUSTE_SAI_CM MONEY);
	
	CREATE TABLE #PROD_SAI_PED_VD (CD_PROD	int,
									QT_IT_PED_VD	MONEY,
									VLR_CMV		MONEY );

	CREATE TABLE #PROD_ENT_PED_CP (CD_PROD			INT,
									QT_IT_PED_CP	MONEY,
									QT_ENT_CP		MONEY,
									VLR_ENT_CP		MONEY);
	
	
	CREATE TABLE #PROD_AJUSTE_FLUT(CD_PROD					INT,
								QT_EST_FLUT					MONEY,
								QT_AJUSTE_ENT_FLUTUANTE		MONEY,
								VLR_AJUSTE_ENT_FLUTUANTE	MONEY,
								QT_AJUSTE_SAI_FLUTUANTE		MONEY,
								VLR_AJUSTE_SAI_FLUTUANTE	MONEY);
	
 	CREATE TABLE #PROD_AJUSTE_EM_TERC (CD_PROD INT,QT_EST_EM_TERC MONEY);
	CREATE TABLE #PROD_AJUSTE_DE_TERC (CD_PROD INT,QT_EST_DE_TERC MONEY);

	CREATE TABLE #PROD_ACERTO_CUSTO (CD_PROD INT, VLR_ACERTO_CUSTO MONEY);

	
	CREATE TABLE #PROD_ENT_NF_CANC (CD_PROD INT, QT_IT_ENT_CANC MONEY, VLR_ENT_CANC MONEY);
	
	CREATE TABLE #PROD_ENT_NF_EST (CD_PROD			INT,
									QT_ENT_EST		MONEY,
									VLR_ENT_EST		MONEY);
		
	CREATE TABLE #PROD_SAI_NF_EST (CD_PROD			INT,
									QT_SAI_EST		MONEY,
									VLR_SAI_EST		MONEY);
	 	
/*****************************************************************************************************************************/
--Relacao produtos
/*****************************************************************************************************************************/
CREATE TABLE #RsProdFecha (CD_EMP INT,
								CD_FILIAL INT,
								CD_PROD INT )  
								
/*****************************************************************************************************************************/
-- Carrega os produtos para fechamento do estoque
/*****************************************************************************************************************************/	
		
 		IF  OBJECT_ID('TEMPDB.DBO.##TMP_EST_FECHA_PROD') IS NOT NULL
		BEGIN

			INSERT INTO #RsProdFecha (CD_EMP, CD_FILIAL, CD_PROD)
			SELECT 
				DISTINCT CD_EMP, CD_FILIAL, CD_PROD
			FROM
				##TMP_EST_FECHA_PROD
		END

		IF @CD_PROD > 0 
		BEGIN
			INSERT INTO #RsProdFecha(CD_EMP, CD_FILIAL, CD_PROD)
			SELECT @CD_EMP, @CD_FILIAL, @CD_PROD
		END

		if not exists(select top 1 cd_emp from #RsProdFecha)
		begin
			INSERT INTO #RsProdFecha(CD_EMP, CD_FILIAL, CD_PROD)
			select CD_EMP, CD_FILIAL, CD_PROD
			from 
				est_prod_cpl
			where
				cd_emp =@CD_EMP
				and cd_filial = @CD_FILIAL
		end
		
		CREATE UNIQUE CLUSTERED INDEX IX_RsProdFecha ON #RsProdFecha (CD_PROD,CD_FILIAL,CD_EMP);	
-- Tag #I001
		CREATE INDEX IX_RSPRODFECHA_01 ON #RSPRODFECHA (CD_EMP,CD_FILIAL,CD_PROD)
/**********************************************************************************************************************/
--	Atualiza datas tabelas de movimentacao
/**********************************************************************************************************************/
		
		--Exclui ajustes de devolucao CF sem vinculo.
		DELETE FROM I 
		FROM
			EST_PROD_IMP I
			LEFT JOIN PDV_VD_DEV_EST_PROD_IMP D ON 
			I.CD_EMP    = D.CD_EMP AND
			I.CD_PROD   = D.CD_PROD AND
			I.CD_IMP    = D.CD_IMP AND
			I.CD_FILIAL = D.CD_FILIAL 
		WHERE 
			I.TP_IMP=6 
			AND D.CD_EMP IS NULL  
			AND i.CD_EMP=@CD_EMP 
			AND i.CD_FILIAL=@CD_FILIAL
			AND i.DT_CAD  BETWEEN @DTINICIOMES AND @DTINICIOMESPOSTERIOR ;

		if exists(select e.CD_EMP
									FROM 
									EST_NF_ENT E
									INNER JOIN EST_NF_ENT_IT I ON 
									E.CD_EMP = I.CD_EMP AND
									E.CD_FILIAL = I.CD_FILIAL AND
									E.CD_NF = I.CD_NF AND
									E.DT_ENT <> isnull(I.DT_ENT,'19000101') 
								WHERE
									e.CD_EMP=@CD_EMP 
									AND e.CD_FILIAL=@CD_FILIAL
									AND e.DT_ENT BETWEEN @DTINICIOMES AND @DTINICIOMESPOSTERIOR)
		begin
			UPDATE I
			SET
				I.DT_ENT=E.DT_ENT
			FROM 
				EST_NF_ENT E
				INNER JOIN EST_NF_ENT_IT I ON 
				E.CD_EMP = I.CD_EMP AND
				E.CD_FILIAL = I.CD_FILIAL AND
				E.CD_NF = I.CD_NF AND
				E.DT_ENT <> isnull(I.DT_ENT,'19000101')
				 
			
			WHERE
				e.CD_EMP=@CD_EMP 
				AND e.CD_FILIAL=@CD_FILIAL
				AND e.DT_ENT BETWEEN @DTINICIOMES AND @DTINICIOMESPOSTERIOR ;
		end
	  
	   if exists (select * from 
					EST_NF_SAI S
					INNER JOIN EST_NF_SAI_IT I ON 
					S.CD_EMP	= I.CD_EMP AND
					S.CD_FILIAL	= I.CD_FILIAL AND
					S.CD_NF		= I.CD_NF AND
					S.DT_EMI_NF	<> isnull(I.DT_EMI_NF,'19000101')
					 
				WHERE
					s.CD_EMP=@CD_EMP 
					AND s.CD_FILIAL=@CD_FILIAL 
	 				AND s.DT_EMI_NF  BETWEEN @DTINICIOMES AND @DTINICIOMESPOSTERIOR)
		begin

			UPDATE I
			SET
				I.DT_EMI_NF=S.DT_EMI_NF 
			FROM 
				EST_NF_SAI S
				INNER JOIN EST_NF_SAI_IT I ON 
				S.CD_EMP	= I.CD_EMP AND
				S.CD_FILIAL	= I.CD_FILIAL AND
				S.CD_NF		= I.CD_NF AND
				S.DT_EMI_NF	<> isnull(I.DT_EMI_NF,'19000101') 
			WHERE
				s.CD_EMP=@CD_EMP 
				AND s.CD_FILIAL=@CD_FILIAL 
	 			AND s.DT_EMI_NF  BETWEEN @DTINICIOMES AND @DTINICIOMESPOSTERIOR
		end

-- Tag #A002
		if exists (select top 1 v.CD_EMP from 
						PDV_VD V
						INNER JOIN PDV_VD_IT I ON 
						V.CD_EMP	= I.CD_EMP AND
						V.CD_FILIAL	= I.CD_FILIAL AND
						V.CD_VD		= I.CD_VD AND
						V.DT_VD		<> isnull(I.DT_VD,'19000101') 
					WHERE
						v.CD_EMP=@CD_EMP 
						AND v.CD_FILIAL=@CD_FILIAL  
						AND v.DT_VD BETWEEN @DTINICIOMES AND @DTINICIOMESPOSTERIOR)
		begin
			UPDATE I
			SET
				I.DT_VD = V.DT_VD
			FROM 
				PDV_VD V
				INNER JOIN PDV_VD_IT I ON 
				V.CD_EMP	= I.CD_EMP AND
				V.CD_FILIAL	= I.CD_FILIAL AND
				V.CD_VD		= I.CD_VD AND
				V.DT_VD		<> isnull(I.DT_VD,'19000101')
				 
			WHERE
				v.CD_EMP=@CD_EMP 
				AND v.CD_FILIAL=@CD_FILIAL  
				AND v.DT_VD  BETWEEN @DTINICIOMES AND @DTINICIOMESPOSTERIOR
		end
			 
		
/**********************************************************************************************************************/
-- Produtos iniciais		
/**********************************************************************************************************************/
	Print 'Insere tabela inicial #PROD_INI - Time ' + convert(varchar(20),getdate(),108);
	INSERT INTO #PROD_INI
	SELECT  
		EST_PROD_CPL.CD_PROD,  
		EST_PROD_CPL.CD_SIGLA,  
		EST_PROD.LISTA_PROD,	
		EST_PROD.PIS_COFINS,
		EST_PROD_CPL.VLR_CUSTO AS VLR_CUSTO_CAD, 
		EST_PROD_CPL.VLR_CUSTO_MD AS VLR_CUSTO_MD_CAD, 
		0 AS VLR_CUSTO_MOV,
		0 AS VLR_CUSTO_MD_MOV,
		ISNULL(EST_PROD_PRECO.VLR_TABELA,0) VLR_TABELA,
		EST_PROD_CPL.MEDIAF,		
		EST_PROD_CPL.EMAX, 
		EST_PROD_CPL.ESEG,
		EST_PROD_CPL.VLR_CUSTO_GER, 
		0  AS VLR_SALDO_CUSTO
	FROM 
		EST_PROD_CPL 
		INNER JOIN EST_PROD  ON
		EST_PROD_CPL.CD_EMP		= EST_PROD.CD_EMP AND
		EST_PROD_CPL.CD_PROD	= EST_PROD.CD_PROD   
		LEFT JOIN EST_PROD_PRECO ON
		EST_PROD_CPL.CD_EMP		= EST_PROD_PRECO.CD_EMP AND
		EST_PROD_CPL.CD_FILIAL	= EST_PROD_PRECO.CD_FILIAL AND
		EST_PROD_CPL.CD_PROD	= EST_PROD_PRECO.CD_PROD

		INNER JOIN #RsProdFecha wx ON 
		EST_PROD_CPL.CD_EMP		= wx.CD_EMP AND
		EST_PROD_CPL.CD_FILIAL  = wx.CD_FILIAL AND
		EST_PROD_CPL.CD_PROD	= wX.CD_PROD

	WHERE 
		EST_PROD_CPL.CD_EMP=@cd_emp
		AND EST_PROD_CPL.CD_FILIAL=@cd_filial;	 
	
	Print 'Carrega o custo medio na tabela inicial #PROD_INI - Time ' + convert(varchar(20),getdate(),108);
    
/***************************************************************************************************/

/***************************************************************************************************/
    CREATE TABLE #TABLE_AUX
	   (DT_PROC           smalldatetime,
	    VLR_CUSTO_MD_NOVO MONEY,
	    CD_PROD           INT,
	    CD_FILIAL         INT
	   );

    TRUNCATE TABLE #TABLE_AUX
    INSERT INTO #TABLE_AUX
    SELECT 
	   MAX(A.DT_PROC) DT_PROC,
	   0,
	   A.CD_PROD,
	   A.CD_FILIAL
    FROM 
	   EST_FECHA_PROC_MOV A           
    WHERE 
	   A.CD_EMP = @CD_EMP
	   AND A.CD_FILIAL = @CD_FILIAL 
	   AND A.DT_PROC <= @DTDIAFINALMESFECHAMENTO
    GROUP BY  
	   A.CD_PROD,
	   A.CD_FILIAL;

    update a
    set
	   VLR_CUSTO_MD_NOVO=P.VLR_CUSTO_MD_NOVO
    from 
	   #TABLE_AUX a
	   join EST_FECHA_PROC_MOV p on
	   a.cd_prod	= p.cd_prod and
	   a.CD_FILIAL = p.CD_FILIAL and
	   a.DT_PROC	= p.DT_PROC  
    WHERE 
	   p.CD_EMP = @CD_EMP
	   AND p.CD_FILIAL = @CD_FILIAL ;
   
    UPDATE A
    SET
	    A.VLR_CUSTO_MOV= B.VLR_CUSTO_MD_NOVO 
    FROM 
	   #PROD_INI A
	   JOIN #TABLE_AUX B ON   
	   A.CD_PROD	 = B.CD_PROD

	UPDATE #prod_ini SET VLR_CUSTO_MD_MOV=VLR_CUSTO_MOV; 
	
/***************************************************************************************************/		
	update i
	set
		VLR_SALDO_CUSTO=w.VLR_SALDO_CUSTO
	from
		#PROD_INI i
		inner join (SELECT   
						w.CD_PROD,
						sum(VLR_SALDO_CUSTO) VLR_SALDO_CUSTO
					from 
						#RsProdFecha w
						INNER JOIN EST_FECHA_PROC_MOV m on 
						w.CD_EMP	= m.CD_EMP AND
						w.CD_FILIAL = m.CD_FILIAL AND
						w.CD_PROD	= m.CD_PROD
					where
						m.CD_EMP=@CD_EMP
						AND m.CD_FILIAL=@CD_FILIAL
						AND m.DT_PROC>=@DTINICIOMES 
						AND m.DT_PROC<@DTINICIOMESPOSTERIOR
					group by	  
						w.CD_PROD) w on  
		i.CD_PROD	= w.CD_PROD;

		
		CREATE UNIQUE CLUSTERED INDEX IX_#PROD_INI ON #PROD_INI (CD_PROD);	
/**********************************************************************************************************************/
-- Fechamento anterior		
/**********************************************************************************************************************/
	Print 'Insere fechamento anterior #PROD_FECHA_ANT - Time ' + convert(varchar(20),getdate(),108);
	INSERT INTO #PROD_FECHA_ANT
	SELECT  
		F.CD_PROD, 
		SUM(F.QT_EST) AS QT_EST_FECHA, 
		SUM(F.QT_EST_EM_TERC) QT_EST_EM_TERC,
		SUM(F.QT_EST_DE_TERC)	QT_EST_DE_TERC, 
		SUM(F.QT_EST_FLUT)	QT_EST_FLUT, 
		SUM((F.QT_EST * F.VLR_CUSTO_MD)) AS VLR_EST_INICIAL_CM,	 
		SUM((F.QT_EST_FLUT))			 AS QT_INI_FLUT, 
		SUM((F.QT_EST_FLUT *  F.VLR_CUSTO_MD))   AS VLR_INI_FLUT,
		SUM(ISNULL(F.VLR_SALDO_CUSTO,0))		AS VLR_SALDO_CUSTO_INI
	FROM 
		EST_FECHA F
		
		INNER JOIN #RsProdFecha wx ON 
		F.CD_EMP	= wx.CD_EMP AND
		F.CD_FILIAL = wx.CD_FILIAL AND
		F.CD_PROD	= wX.CD_PROD
	WHERE 
		F.CD_EMP=@CD_EMP 
		AND F.CD_FILIAL=@CD_FILIAL 
		AND F.MES_FECHA=@MESANT  
		AND F.ANO_FECHA=@ANOANT 
	GROUP BY F.CD_PROD;

/**********************************************************************************************************************/
-- Exclui ajustes de devolução sem vinculo com cupom fiscal.	
/**********************************************************************************************************************/
	Print 'Rotinas auxiliares - Time ' + convert(varchar(20),getdate(),108);

	DELETE FROM A
	FROM 
		EST_PROD_IMP A
		LEFT JOIN PDV_VD_DEV_EST_PROD_IMP V ON 
		A.CD_EMP	= V.CD_EMP AND
		A.CD_IMP	= V.CD_IMP AND
		A.CD_FILIAL = V.CD_FILIAL AND 
		A.CD_PROD	= V.CD_PROD

		INNER JOIN #RsProdFecha wx ON 
		A.CD_EMP	= wx.CD_EMP AND
		A.CD_FILIAL = wx.CD_FILIAL AND
		A.CD_PROD	= wx.CD_PROD 
	WHERE 
		A.CD_EMP=1 
		AND V.CD_EMP IS NULL 
		AND A.TP_EST=0  
		AND A.TP_IMP =6 
		AND A.CD_FILIAL=@CD_FILIAL
		AND A.DT_CAD>=@DTINICIOMES 
		AND A.DT_CAD<@DTINICIOMESPOSTERIOR;

		 
/**********************************************************************************************************************/
-- Nota fiscal de saida	
/**********************************************************************************************************************/
	Print 'Insere saidas nf #PROD_SAI_NF - Time ' + convert(varchar(20),getdate(),108);

	INSERT INTO #PROD_SAI_NF 
	SELECT 
		i.CD_PROD,  
		SUM(CASE WHEN DEST_ORIG<>2 THEN 
			i.QT_IT  ELSE 0 END) AS QT_IT_NF_SAI,  

		SUM(CASE WHEN DEST_ORIG=2 THEN 
			i.QT_IT  ELSE 0 END) AS QT_IT_SAI_TRANF,  

		SUM(((CASE WHEN DEST_ORIG<>2 THEN 
			i.QT_IT ELSE 0 END) * I.VLR_CUSTO_MD
							 )) AS VLR_CMV,
		
		SUM(((CASE WHEN DEST_ORIG = 2 THEN 
			i.QT_IT ELSE 0 END) * CASE WHEN O.CALC_CUSTO_MEDIO = 1 THEN
									isnull(devDare.VLR_DEV_DARE, i.VLR_CUSTO) 									
									ELSE 
									   I.VLR_CUSTO_MD
									END
									)) AS VLR_SAIDA_TRANSF_CM, 
		--Se for devolucao
		SUM((CASE WHEN O.TP_MOV =11 AND O.TP_MOV_OP_TRANSA = 1 AND O.DEST_ORIG <> 2 THEN 
				i.QT_IT ELSE 0 END)) AS QT_DEV_CP,								
		
		SUM(((CASE WHEN O.TP_MOV =11 AND O.TP_MOV_OP_TRANSA = 1 AND O.DEST_ORIG <> 2 THEN 
				i.QT_IT ELSE 0 END) * CASE WHEN O.CALC_CUSTO_MEDIO = 1 THEN 
										isnull(devDare.VLR_DEV_DARE, ISNULL(i.VLR_CUSTO,0)	
										+ case when isnull(ei.QT_IT,0)=0 then 0
											else (CASE WHEN ISNULL(R.CD_EMP,0)=0 THEN 0 --Ressarcimento icms
												ELSE ((ISNULL(ei.VLR_ICMS_SUBS,0)+ISNULL(ei.VLR_ICMS_IT,0))/ei.QT_IT) END)
											end
										- case when isnull(ei.QT_IT,0)=0 then 0
											else ((ISNULL(ei.VLR_PIS,0)+ISNULL(ei.VLR_COFINS,0))/ei.QT_IT)  --Impostos da entrada
											end )
										ELSE 
										  case when I.VLR_CUSTO_MD = 0 THEN ei.VLR_PRC_CUSTO
										  else I.VLR_CUSTO_MD
										  end 
										END 
										)) AS VLR_DEV_CP_CM, 

		--Se for  venda
		SUM((CASE WHEN O.TP_MOV =0 AND O.TP_MOV_OP_TRANSA = 1 AND O.DEST_ORIG <> 2 THEN 
				i.QT_IT ELSE 0 END)) AS QT_SAI_VD,  
		--Se for  bonificacao
		SUM((CASE WHEN O.TP_MOV =3 AND O.TP_MOV_OP_TRANSA = 1 AND O.DEST_ORIG <> 2 THEN 
				i.QT_IT ELSE 0 END)) AS QT_SAI_BONIFICA,	 
		--Se for  outras
		SUM((CASE WHEN O.TP_MOV IN (11,0,3,24) AND O.TP_MOV_OP_TRANSA = 1 OR DEST_ORIG = 2 THEN 
				0 ELSE i.QT_IT  END)) AS QT_SAI_OUTRAS, 
		SUM(( (CASE WHEN O.TP_MOV =0 AND O.TP_MOV_OP_TRANSA = 1 AND O.DEST_ORIG <> 2 THEN 
				i.QT_IT ELSE 0 END) * I.VLR_CUSTO_MD
								    )) as VLR_SAI_VD, 
				
		SUM(( (CASE WHEN O.TP_MOV =3 AND O.TP_MOV_OP_TRANSA = 1 AND O.DEST_ORIG <> 2 THEN 
				i.QT_IT ELSE 0 END) * CASE WHEN O.CALC_CUSTO_MEDIO = 1 THEN
										  isnull(devDare.VLR_DEV_DARE, i.VLR_CUSTO)
									   ELSE  
										 I.VLR_CUSTO_MD
									   end
										))   
										AS VLR_SAI_BONIFICA, 
				
		SUM(( (CASE WHEN O.TP_MOV  IN (11,0,3,24)  AND O.TP_MOV_OP_TRANSA = 1 OR DEST_ORIG = 2 THEN 
				0 ELSE i.QT_IT   END) * CASE WHEN O.CALC_CUSTO_MEDIO = 1 THEN
										  isnull(devDare.VLR_DEV_DARE, i.VLR_CUSTO)
										ELSE 
										  I.VLR_CUSTO_MD
										end
										))  AS VLR_SAI_OUTRAS,
		--Se for Perda
		SUM((CASE WHEN O.TP_MOV =24 AND O.TP_MOV_OP_TRANSA = 1 AND O.DEST_ORIG <> 2 THEN 
				i.QT_IT ELSE 0 END)) AS QT_SAI_PERDA,	
											
		SUM(( (CASE WHEN O.TP_MOV =24 AND O.TP_MOV_OP_TRANSA = 1 AND O.DEST_ORIG <> 2  THEN 
				i.QT_IT ELSE 0 END) *	CASE WHEN O.CALC_CUSTO_MEDIO = 1 THEN
										isnull(devDare.VLR_DEV_DARE, i.VLR_CUSTO)
									ELSE  I.VLR_CUSTO_MD
										end
										)) AS VLR_SAI_PERDA 				
	FROM
		EST_NF_SAI n
		INNER JOIN EST_NF_SAI_IT i ON
			n.CD_EMP	=i.CD_EMP AND
			N.CD_FILIAL	=I.CD_FILIAL AND
			N.CD_NF		=I.CD_NF AND
			N.DT_EMI_NF =I.DT_EMI_NF
		
		INNER JOIN #RsProdFecha wx ON 
			I.CD_EMP	= wx.CD_EMP AND
			I.CD_FILIAL = wx.CD_FILIAL AND
			I.CD_PROD	= wx.CD_PROD

		LEFT JOIN (SELECT
						NF_SAI.CD_EMP,
						NF_SAI.CD_NF,
						NF_SAI.CD_FILIAL,
						NF_SAI.CD_PROD,  
						AVG(
							 ((((NF_SAI.QT_IT * NF_SAI.VLR_IT) - NF_SAI.VLR_DESC_IT) + 
							 ((NF_SAI.QT_IT * NF_SAI.VLR_IT) - NF_SAI.VLR_DESC_IT) * (NF_SAI.PERC_IPI /  100.00)) / NF_SAI.QT_IT) 
						  + (ISNULL(DARE.VLR_ICMS_SUBS,0) /DARE.QT_IT) 
						  
						  ) VLR_DEV_DARE
					FROM 
						V_EST_NF_ENT_IT_DAR_GERADO DARE 
						INNER JOIN EST_NF_ENT_NF_SAI ES ON
							DARE.CD_EMP		= ES.CD_EMP AND
							DARE.CD_FILIAL  = ES.CD_FILIAL AND
							DARE.CD_NF		= ES.CD_NF_ENT  
						INNER JOIN EST_NF_SAI_IT NF_SAI ON
							ES.CD_EMP	 = NF_SAI.CD_EMP AND
							ES.CD_FILIAL = NF_SAI.CD_FILIAL AND
							ES.CD_NF_SAI = NF_SAI.CD_NF AND 
						DARE.CD_PROD = NF_SAI.CD_PROD
						
						INNER JOIN EST_NF_SAI   T ON
							ES.CD_EMP    = T.CD_EMP AND
							ES.CD_FILIAL = T.CD_FILIAL AND
							ES.CD_NF_SAI = T.CD_NF

						INNER JOIN GLB_MOV_OP O ON
							T.CD_NT_MOV = O.CD_MOV_OP
							AND O.DEST_ORIG <> 2 --NAO TRANSFERENCIA
					WHERE
						NF_SAI.CD_EMP=@cd_emp
						AND NF_SAI.CD_FILIAL=@cd_filial
						AND NF_SAI.DT_EMI_NF>=@dtInicioMes AND NF_SAI.DT_EMI_NF<@dtInicioMesPosterior
					   GROUP BY NF_SAI.CD_EMP,
						NF_SAI.CD_NF,
						NF_SAI.CD_FILIAL,
						NF_SAI.CD_PROD
						) DevDare ON
		i.CD_EMP	= DevDare.CD_EMP AND 
		i.CD_FILIAL	= DevDare.CD_FILIAL AND 
		i.CD_NF		= DevDare.CD_NF AND
		i.CD_PROD	= DevDare.CD_PROD

		LEFT JOIN (SELECT 
						A.CD_EMP,
						A.CD_FILIAL,
						A.CD_NF_RELACIONADA CD_NF
					FROM 
						EST_NF_SAI_EST_NF_SAI A
						INNER JOIN EST_NF_SAI B ON
							A.CD_EMP=B.CD_EMP AND
							A.CD_FILIAL=B.CD_FILIAL AND
							A.CD_NF=B.CD_NF
						INNER JOIN GLB_MOV_OP O ON
							B.CD_NT_MOV=O.CD_MOV_OP 
					WHERE  
						O.TP_MOV=25--Credito ICMs
						AND b.CD_EMP=@cd_emp 
						AND b.CD_FILIAL=@cd_filial 
						AND b.DT_EMI_NF>=@dtInicioMes AND b.DT_EMI_NF<@dtInicioMesPosterior 

						) r  ON
			n.CD_EMP		= r.CD_EMP AND
			n.CD_FILIAL		= r.CD_FILIAL AND
			n.CD_NF			= r.CD_NF  

		LEFT JOIN (
			SELECT
				EI.CD_EMP,
				EI.CD_FILIAL,
				EI.CD_PROD,
				ES.CD_NF_SAI,
				MAX(EI.QT_IT) AS QT_IT,
				MAX(EI.VLR_ICMS_SUBS) AS VLR_ICMS_SUBS,
				MAX(EI.VLR_ICMS_IT) AS VLR_ICMS_IT,
				MAX(EI.VLR_PIS) AS VLR_PIS,
				MAX(EI.VLR_COFINS) AS VLR_COFINS,
				MAX(EI.VLR_PRC_CUSTO) AS VLR_PRC_CUSTO
			FROM

				EST_NF_ENT_NF_SAI ES
		
				LEFT JOIN EST_NF_ENT_IT EI ON
					ES.CD_EMP	 = EI.CD_EMP AND
					ES.CD_FILIAL = EI.CD_FILIAL AND
					ES.CD_NF_ENT = EI.CD_NF
					
			GROUP BY
				EI.CD_EMP,
				EI.CD_FILIAL,
				EI.CD_PROD,
				ES.CD_NF_SAI) EI ON
			n.CD_EMP		= EI.CD_EMP AND
			n.CD_FILIAL		= EI.CD_FILIAL AND
			n.CD_NF			= EI.CD_NF_SAI AND 
			I.CD_PROD  = EI.CD_PROD

		INNER JOIN GLB_MOV_OP o ON 
			n.CD_NT_MOV=o.CD_MOV_OP

		LEFT JOIN PDV_VD_EST_NF_SAI G ON  --Retira nota que substitui cupom fiscal
			n.CD_EMP=G.CD_EMP AND 
			n.CD_FILIAL=G.CD_FILIAL AND 
			n.CD_NF=G.CD_NF
	WHERE 
		n.CD_EMP=@cd_emp 
		AND n.CD_FILIAL=@cd_filial 
		AND n.STS_NF=0 
		AND o.BX_EST=1 
		AND o.TP_ESTQ=0
		AND i.DT_EMI_NF>=@dtInicioMes AND i.DT_EMI_NF<@dtInicioMesPosterior 
		AND G.CD_EMP  IS NULL
	GROUP BY 
		i.CD_PROD;

/**********************************************************************************************************************/
-- Cancelamento de notas fiscais fora prazo
/**********************************************************************************************************************/
	Print 'Insere entradas nf #PROD_ENT_NF_CANC - Time ' + convert(varchar(20),getdate(),108);

	INSERT INTO #PROD_ENT_NF_CANC
	SELECT  
		i.CD_PROD,  
		SUM(i.QT_IT) AS QT_IT,  
		SUM(i.QT_IT  *  i.VLR_CUSTO_MD) as VLR 
	
 	FROM      
		EST_NF_SAI n 
		INNER JOIN EST_NF_SAI_IT i ON 
		n.CD_EMP	=i.CD_EMP AND 
		N.CD_FILIAL	=I.CD_FILIAL AND 
		N.CD_NF		=I.CD_NF AND
		N.DT_EMI_NF =I.DT_EMI_NF   
		INNER JOIN GLB_MOV_OP o ON 
		n.CD_NT_MOV=o.CD_MOV_OP
		INNER JOIN EST_NF_SAI_CANCEL C  ON
		I.CD_EMP	= C.CD_EMP AND
		I.CD_FILIAL = C.CD_FILIAL AND
		I.CD_NF		= C.CD_NF  

		INNER JOIN #RsProdFecha wx ON 
		I.CD_EMP	= wx.CD_EMP AND
		I.CD_FILIAL = wx.CD_FILIAL AND
		I.CD_PROD	= wx.CD_PROD
	WHERE     
		C.CD_EMP = @CD_EMP   
		AND C.DT_CANCEL>=@dtInicioMes 
		AND C.DT_CANCEL<@dtInicioMesPosterior   
		AND C.CD_FILIAL = @CD_FILIAL   
		AND o.BX_EST = 1  
		AND o.TP_ESTQ = 0  
		AND n.STS_NF = 0  
		--AND C.CANCEL_FORA_PRAZO=1
		AND NOT EXISTS (SELECT   
							CD_NF   
						FROM   
							PDV_VD_EST_NF_SAI  
						WHERE  
							I.CD_EMP	= PDV_VD_EST_NF_SAI.CD_EMP AND  
							I.CD_FILIAL = PDV_VD_EST_NF_SAI.CD_FILIAL AND  
							I.CD_NF		= PDV_VD_EST_NF_SAI.CD_NF AND  
							I.CD_EMP	= @CD_EMP  
							AND I.CD_FILIAL = @CD_FILIAL)
		GROUP BY 		
			i.CD_PROD ;

/**********************************************************************************************************************/
-- Entrada notas fiscais	
/**********************************************************************************************************************/
	Print 'Insere entradas nf #PROD_ENT_NF - Time ' + convert(varchar(20),getdate(),108);

	INSERT INTO #PROD_ENT_NF
	SELECT  
		i.CD_PROD,  
		SUM(CASE WHEN DEST_ORIG<>2 THEN 
				i.QT_IT 
			ELSE 
				0 
			END)	AS QT_IT_NF_ENT, 
		SUM(CASE WHEN DEST_ORIG=2 THEN 
				i.QT_IT 
			ELSE 
				0 
			END) AS QT_ENT_TRANSF, 
   		SUM(CASE WHEN ISNULL(i.VLR_ICMS_SUBS,0) > 0 THEN 
				ISNULL(i.VLR_ICMS_SUBS,0) / ISNULL(i.QT_IT,0) 
				ELSE 0 END) AS VLR_ICMS_SUBS,
		
		SUM(CASE WHEN ISNULL(i.VLR_ICMS_SUBS,0) > 0 THEN 
				ISNULL(i.VLR_ICMS_IT,0) / ISNULL(i.QT_IT,0) 
			ELSE 0 END) AS VLR_ICMS_IT, 
		AVG(i.VLR_PRC_CUSTO) AS VLR_CUSTO_MES_FECHA,  
		
		SUM((CASE WHEN DEST_ORIG <> 2 THEN  i.QT_IT 
				ELSE 0 END)  *  (CASE WHEN O.CALC_CUSTO_MEDIO = 1 THEN
									i.VLR_PRC_CUSTO									
							   ELSE 
									I.VLR_CUSTO_MD
							   END)) AS VLR_ENTRADAS_CE,  
		SUM((CASE WHEN DEST_ORIG = 2 THEN  i.QT_IT 
				ELSE 0 END)*  (  i.VLR_PRC_CUSTO ))VLR_ENTRADA_TRANSF_CM, 


		--Se for devolucao de venda
		SUM(CASE WHEN O.TP_MOV =11 AND O.TP_MOV_OP_TRANSA = 0  THEN 
					CASE WHEN DEST_ORIG =1 THEN
						CASE WHEN gr.CD_FILIAL IS NULL  THEN
							0 ELSE i.QT_IT END
					WHEN DEST_ORIG IN(0,2)  THEN
						i.QT_IT 
					ELSE 0 END 
			 ELSE 0 END) AS QT_DEV_VD,

		SUM( (CASE WHEN O.TP_MOV =11 AND O.TP_MOV_OP_TRANSA = 0 THEN 
					CASE WHEN DEST_ORIG =1 THEN
						CASE WHEN ff.CD_FILIAL IS NULL  THEN
							0 ELSE i.QT_IT END
					WHEN DEST_ORIG IN(0,2) THEN
						i.QT_IT 
					ELSE 0 END
				ELSE 0 END) * I.VLR_CUSTO_MD
							 ) AS VLR_DEV_VD_CM, 
		
		SUM(CASE WHEN O.TP_MOV in (0,11) AND O.TP_MOV_OP_TRANSA = 0   THEN 
					CASE WHEN O.DEST_ORIG =1 THEN
						CASE WHEN gr.CD_FILIAL IS NULL  THEN
							i.QT_IT ELSE 0 END 
					ELSE 0 END 
			ELSE 0 END ) AS QT_ENT_CP, 
					 
		SUM(CASE WHEN O.TP_MOV =3 AND O.TP_MOV_OP_TRANSA = 0 AND DEST_ORIG <> 2 THEN 
			i.QT_IT ELSE 0 END) AS QT_ENT_BONIFICA,
			 
		SUM(CASE WHEN O.TP_MOV in (0,3,11) AND O.TP_MOV_OP_TRANSA = 0 OR DEST_ORIG = 2 THEN 
				0 ELSE i.QT_IT END) AS QT_ENT_OUTRAS, 
		
		SUM(CASE WHEN O.TP_MOV in (0,11) AND O.TP_MOV_OP_TRANSA = 0 
										AND ISNULL(O.FLAG_CUSTO_ZERO_ENT,0) = 0  THEN
					CASE WHEN DEST_ORIG =1 THEN
						CASE WHEN gr.CD_FILIAL IS NULL  THEN
							i.QT_IT * i.VLR_PRC_CUSTO  ELSE 0 END 
					ELSE 0 END 
			ELSE 0 END )  AS VLR_ENT_CP,  
		
		SUM( (CASE WHEN O.TP_MOV =3 AND O.TP_MOV_OP_TRANSA = 0 AND ISNULL(O.FLAG_CUSTO_ZERO_ENT,0) = 0 AND DEST_ORIG <> 2  THEN
					i.QT_IT *(CASE WHEN O.CALC_CUSTO_MEDIO = 1 THEN
									i.VLR_PRC_CUSTO									
								ELSE 
								    I.VLR_CUSTO_MD
								    END)
				ELSE  0 END)) AS VLR_ENT_BONIFICA, 

		SUM((CASE WHEN O.TP_MOV  in (0,3,11) AND O.TP_MOV_OP_TRANSA = 0 AND ISNULL(O.FLAG_CUSTO_ZERO_ENT,0) = 0 
				OR DEST_ORIG = 2   THEN 
					0 
				ELSE 
					i.QT_IT * (CASE WHEN O.CALC_CUSTO_MEDIO = 1 THEN
								i.VLR_PRC_CUSTO									
							   ELSE 
									I.VLR_CUSTO_MD
							   END)
				END)) AS VLR_ENT_OUTRAS   
	FROM 
		EST_NF_ENT n 
		
		INNER JOIN PRC_FILIAL FL ON 
		n.CD_EMP = FL.CD_EMP AND 
		n.CD_FILIAL = FL.CD_FILIAL 

		LEFT JOIN PRC_FILIAL_PG_FORN FF ON  
		n.CD_EMP = FF.CD_EMP AND 
		n.CD_FORN = FF.CD_FORN 
		 
		inner JOIN PRC_GRP_ECON_PRC_FILIAL grE ON  
		n.CD_EMP = grE.CD_EMP AND 
		n.CD_FILIAL = grE.CD_FILIAL 

		LEFT JOIN PRC_GRP_ECON_PRC_FILIAL gr ON  
		ff.CD_EMP = gr.CD_EMP AND 
		ff.CD_FILIAL = gr.CD_FILIAL 
		 
		and gre.CD_GRP_ECON = gr.CD_GRP_ECON

		INNER JOIN GLB_MOV_OP o ON 
		n.CD_NT_MOV=o.CD_MOV_OP 

		INNER JOIN EST_NF_ENT_IT i ON 
		n.CD_EMP=i.CD_EMP AND 
		n.CD_FILIAL=i.CD_FILIAL AND 
		n.CD_NF=i.CD_NF and
		n.DT_ENT = I.DT_ENT

		INNER JOIN #RsProdFecha wx ON 
		I.CD_EMP	= wx.CD_EMP AND
		I.CD_FILIAL = wx.CD_FILIAL AND
		I.CD_PROD	= wX.CD_PROD

	WHERE 
		n.CD_EMP=@cd_emp 
		AND n.CD_FILIAL=@cd_filial 
		AND o.TP_ESTQ = 0
		AND n.STS_NF=0 
		AND o.ATU_EST=1 
		AND I.DT_ENT>=@dtInicioMes 
		AND I.DT_ENT<@dtInicioMesPosterior 
	GROUP BY 
		i.CD_PROD;
		 
/**********************************************************************************************************************/
-- Entrada notas fiscais estorno
/**********************************************************************************************************************/
	Print 'Insere entradas estorno #PROD_ENT_NF_EST - Time ' + convert(varchar(20),getdate(),108);

	INSERT INTO #PROD_ENT_NF_EST
	SELECT  
		i.CD_PROD,  
		SUM(i.QT_IT)	AS QT_ENT,  
		SUM(i.QT_IT*i.VLR_PRC_CUSTO) AS VLR_CUSTO 
	FROM 
		EST_NF_ENT_IT_ESTORNO i 
		
		INNER JOIN PRC_FILIAL FL ON 
		i.CD_EMP = FL.CD_EMP AND 
		i.CD_FILIAL = FL.CD_FILIAL 

		LEFT JOIN PRC_FILIAL_PG_FORN FF ON  
		i.CD_EMP = FF.CD_EMP AND 
		i.CD_FORN = FF.CD_FORN 
		 
		inner JOIN PRC_GRP_ECON_PRC_FILIAL grE ON  
		i.CD_EMP = grE.CD_EMP AND 
		i.CD_FILIAL = grE.CD_FILIAL 

		LEFT JOIN PRC_GRP_ECON_PRC_FILIAL gr ON  
		ff.CD_EMP = gr.CD_EMP AND 
		ff.CD_FILIAL = gr.CD_FILIAL 
		 
		and gre.CD_GRP_ECON = gr.CD_GRP_ECON

		INNER JOIN GLB_MOV_OP o ON 
		i.CD_MOV_OP 	=o.CD_MOV_OP 

		INNER JOIN #RsProdFecha wx ON 
		I.CD_EMP	= wx.CD_EMP AND
		I.CD_FILIAL = wx.CD_FILIAL AND
		I.CD_PROD	= wX.CD_PROD

	WHERE 
		I.CD_EMP=@cd_emp 
		AND I.CD_FILIAL=@cd_filial 
		AND o.TP_ESTQ = 0
		AND o.ATU_EST=1 
		AND I.DT_ENT>=@dtInicioMes 
		AND I.DT_ENT<@dtInicioMesPosterior 
	GROUP BY 
		i.CD_PROD; 
		 
		 
	
/**********************************************************************************************************************/
-- Entrada notas fiscais estorno saida
/**********************************************************************************************************************/
	Print 'Insere entradas estorno #PROD_SAI_NF_EST - Time ' + convert(varchar(20),getdate(),108);

	INSERT INTO #PROD_SAI_NF_EST
	SELECT  
		i.CD_PROD,  
		SUM(i.QT_IT)	AS QT_SAI,  
		SUM(i.QT_IT*i.VLR_PRC_CUSTO) AS VLR_CUSTO 
	FROM 
		EST_NF_ENT_IT_ESTORNO i 
		
		INNER JOIN PRC_FILIAL FL ON 
		i.CD_EMP = FL.CD_EMP AND 
		i.CD_FILIAL = FL.CD_FILIAL 

		LEFT JOIN PRC_FILIAL_PG_FORN FF ON  
		i.CD_EMP = FF.CD_EMP AND 
		i.CD_FORN = FF.CD_FORN 
		 
		inner JOIN PRC_GRP_ECON_PRC_FILIAL grE ON  
		i.CD_EMP = grE.CD_EMP AND 
		i.CD_FILIAL = grE.CD_FILIAL 

		LEFT JOIN PRC_GRP_ECON_PRC_FILIAL gr ON  
		ff.CD_EMP = gr.CD_EMP AND 
		ff.CD_FILIAL = gr.CD_FILIAL 
		 
		and gre.CD_GRP_ECON = gr.CD_GRP_ECON

		INNER JOIN GLB_MOV_OP o ON 
		i.CD_MOV_OP 	=o.CD_MOV_OP 

		INNER JOIN #RsProdFecha wx ON 
		I.CD_EMP	= wx.CD_EMP AND
		I.CD_FILIAL = wx.CD_FILIAL AND
		I.CD_PROD	= wX.CD_PROD

	WHERE 
		I.CD_EMP=@cd_emp 
		AND I.CD_FILIAL=@cd_filial 
		AND o.TP_ESTQ = 0
		AND o.ATU_EST=1 
		AND CONVERT(DATE,I.DT_CAD)>=@dtInicioMes 
		AND CONVERT(DATE,I.DT_CAD)<@dtInicioMesPosterior 
	GROUP BY 
		i.CD_PROD; 
		 	
/**********************************************************************************************************************/
-- Saidas notas fiscais flutuante
/**********************************************************************************************************************/
	Print 'Insere saidas nf flut #PROD_SAI_NF_FLUT - Time ' + convert(varchar(20),getdate(),108); 

	INSERT INTO #PROD_SAI_NF_FLUT 
	SELECT  
		I.CD_PROD,  
		SUM(I.QT_IT )*-1 QT_EST_FLUT,  

		--Se for devolucao
		SUM((CASE WHEN O.TP_MOV =11 AND O.TP_MOV_OP_TRANSA = 1 AND O.DEST_ORIG <> 2 THEN 
				i.QT_IT ELSE 0 END)) AS QT_DEV_CP,								
		
		SUM(((CASE WHEN O.TP_MOV =11 AND O.TP_MOV_OP_TRANSA = 1 AND O.DEST_ORIG <> 2 THEN 
				i.QT_IT ELSE 0 END) * CASE WHEN O.CALC_CUSTO_MEDIO = 1 THEN
											isnull(devDare.VLR_DEV_DARE, i.VLR_CUSTO)
										ELSE 
											I.VLR_CUSTO_MD										
										  end 
										)) AS VLR_DEV_CP_CM,  

		SUM(CASE WHEN O.TP_MOV =24 AND O.TP_MOV_OP_TRANSA = 1 AND O.DEST_ORIG <> 2 THEN 
				I.QT_IT ELSE 0 END) AS QT_SAI_PERDA_FLUTUANTE,  
		SUM((CASE WHEN O.TP_MOV =24 AND O.TP_MOV_OP_TRANSA = 1 AND O.DEST_ORIG <> 2  THEN 
				I.QT_IT ELSE 0 END) *
							CASE WHEN O.CALC_CUSTO_MEDIO = 1 THEN
								i.VLR_CUSTO
							else 
								I.VLR_CUSTO_MD
							end 
							) AS VLR_SAI_PERDA_FLUTUANTE,  
		
		SUM(CASE WHEN DEST_ORIG=2 THEN 
			I.QT_IT  ELSE 0 END) AS QT_SAI_TRANSF_FLUT,  
		SUM((CASE WHEN DEST_ORIG = 2 THEN 
			I.QT_IT ELSE 0 END) * CASE WHEN O.CALC_CUSTO_MEDIO = 1 THEN
								    i.VLR_CUSTO
								else 
									I.VLR_CUSTO_MD
								end ) AS VLR_SAI_TRANSF_FLUT, 
		--SE FOR  OUTRAS
		SUM(CASE WHEN O.TP_MOV IN (11,0,3,24) AND O.TP_MOV_OP_TRANSA = 1 OR DEST_ORIG = 2 THEN 
			0 ELSE I.QT_IT  END) AS QT_SAI_OUTRAS_FLUTUANTE,		

		SUM((CASE WHEN O.TP_MOV  IN (11,0,3,24)  AND O.TP_MOV_OP_TRANSA = 1 OR DEST_ORIG = 2 THEN 
				0 ELSE I.QT_IT   END) * CASE WHEN O.CALC_CUSTO_MEDIO = 1 THEN
									   i.VLR_CUSTO
									else 
									   I.VLR_CUSTO_MD  
								     end 
								)  AS VLR_SAI_OUTRAS_FLUTUANTE 
 
	FROM 
		EST_NF_SAI N 
		INNER JOIN EST_NF_SAI_IT I ON 
		N.CD_EMP=I.CD_EMP AND 
		N.CD_FILIAL=I.CD_FILIAL AND 
		N.CD_NF=I.CD_NF AND
		n.DT_EMI_NF = I.DT_EMI_NF
		INNER JOIN #RsProdFecha wx ON 
		I.CD_EMP	= wx.CD_EMP AND
		I.CD_FILIAL = wx.CD_FILIAL AND
		I.CD_PROD	= wX.CD_PROD


		LEFT JOIN (SELECT
						NF_SAI.CD_EMP,
						NF_SAI.CD_NF,
						NF_SAI.CD_FILIAL,
						NF_SAI.CD_PROD,  
						((((NF_SAI.QT_IT * NF_SAI.VLR_IT) - NF_SAI.VLR_DESC_IT) +
						((NF_SAI.QT_IT * NF_SAI.VLR_IT) - NF_SAI.VLR_DESC_IT) * 
						(NF_SAI.PERC_IPI /  100.00)) / NF_SAI.QT_IT) + (ISNULL(DARE.VLR_ICMS_SUBS,0) /DARE.QT_IT) VLR_DEV_DARE
					FROM 
						V_EST_NF_ENT_IT_DAR_GERADO DARE 
						INNER JOIN EST_NF_ENT_NF_SAI ES ON
						DARE.CD_EMP		= ES.CD_EMP AND
						DARE.CD_FILIAL  = ES.CD_FILIAL AND
						DARE.CD_NF		= ES.CD_NF_ENT  
						INNER JOIN EST_NF_SAI_IT NF_SAI ON
						ES.CD_EMP	 = NF_SAI.CD_EMP AND
						ES.CD_FILIAL = NF_SAI.CD_FILIAL AND
						ES.CD_NF_SAI = NF_SAI.CD_NF AND 
						DARE.CD_PROD = NF_SAI.CD_PROD) DevDare ON
		i.CD_EMP	=DevDare.CD_EMP AND 
		i.CD_FILIAL	=DevDare.CD_FILIAL AND 
		i.CD_NF		=DevDare.CD_NF AND
		i.CD_PROD	=DevDare.CD_PROD

		INNER JOIN GLB_MOV_OP O ON 
		N.CD_NT_MOV=O.CD_MOV_OP
	WHERE 
		N.CD_EMP=@CD_EMP 
		AND N.CD_FILIAL=@CD_FILIAL 
		AND N.STS_NF=0 
		AND O.BX_EST=1 
		AND O.TP_ESTQ=1
		AND I.DT_EMI_NF>=@DTINICIOMES 
		AND I.DT_EMI_NF<@DTINICIOMESPOSTERIOR 
	GROUP BY     
		I.CD_PROD;

/**********************************************************************************************************************/
-- Entradas notas fiscais flutuante
/**********************************************************************************************************************/
	
	Print 'Insere entradas nf flut #PROD_ENT_NF_FLUT - Time ' + convert(varchar(20),getdate(),108); 
	 
	INSERT INTO #PROD_ENT_NF_FLUT 
			 (CD_PROD,QT_EST_FLUT,QT_ENT_TRANSF_FLUT,
				VLR_ENT_TRANSF_FLUT,QT_DEV_VD_FLUTUANTE,VLR_DEV_VD_FLUTUANTE,QT_ENT_OUTRAS_FLUTUANTE,VLR_ENT_OUTRAS_FLUTUANTE)
	SELECT 
		i.CD_PROD,  
		SUM(i.QT_IT) QT_EST_FLUT,  
		SUM(CASE WHEN DEST_ORIG=2 THEN 
				i.QT_IT  ELSE 0  END) AS QT_ENT_TRANSF_FLUT,  

		SUM((CASE WHEN DEST_ORIG = 2 THEN  i.QT_IT 
				ELSE 0 END) *  ( i.VLR_PRC_CUSTO )) VLR_ENT_TRANSF_FLUT,	
				  
		--Se for devolucao de venda
		SUM(CASE WHEN O.TP_MOV =11 AND O.TP_MOV_OP_TRANSA = 0  THEN 
					CASE WHEN DEST_ORIG =1 THEN
						CASE WHEN ff.CD_FILIAL IS NULL  THEN
							0 ELSE i.QT_IT END
					WHEN DEST_ORIG IN(0,2) THEN
						i.QT_IT 
					ELSE 0 END 
			 ELSE 0 END) AS QT_DEV_VD,

		SUM( (CASE WHEN O.TP_MOV =11 AND O.TP_MOV_OP_TRANSA = 0 THEN 
					CASE WHEN DEST_ORIG =1 THEN
						CASE WHEN ff.CD_FILIAL IS NULL  THEN
							0 ELSE i.QT_IT END
					WHEN DEST_ORIG IN(0,2) THEN
						i.QT_IT 
					ELSE 0 END
				ELSE 0 END) * 
				    I.VLR_CUSTO_MD
				) AS VLR_DEV_VD_CM, 

		SUM(CASE WHEN O.TP_MOV IN (0,3,11) AND O.TP_MOV_OP_TRANSA = 0  AND O.DEST_ORIG <> 1  OR O.DEST_ORIG =2  THEN 
			0 ELSE i.QT_IT END) AS QT_ENT_OUTRAS_FLUTUANTE, 

		SUM( (CASE WHEN O.TP_MOV IN (0,3,11) AND O.TP_MOV_OP_TRANSA = 0  AND O.DEST_ORIG <> 1  OR O.DEST_ORIG =2  THEN 
				0 
			  ELSE 
				i.QT_IT 
			  END) * I.VLR_CUSTO_MD
			 ) AS VLR_ENT_OUTRAS_FLUTUANTE 
	FROM 
		EST_NF_ENT n  
		INNER JOIN GLB_MOV_OP o ON 
		n.CD_NT_MOV=o.CD_MOV_OP 

		INNER JOIN EST_NF_ENT_IT i ON 
		n.CD_EMP=i.CD_EMP AND 
		n.CD_FILIAL=i.CD_FILIAL AND 
		n.CD_NF=i.CD_NF and 
		n.DT_ENT =I.DT_ENT 
		
		INNER JOIN #RsProdFecha wx ON 
		I.CD_EMP	= wx.CD_EMP AND
		I.CD_FILIAL = wx.CD_FILIAL AND
		I.CD_PROD	= wX.CD_PROD

		LEFT JOIN PRC_FILIAL_PG_FORN FF ON  
		n.CD_EMP = FF.CD_EMP AND 
		n.CD_FORN = FF.CD_FORN 

	WHERE 
		I.CD_EMP=@cd_emp 
		AND I.CD_FILIAL=@cd_filial 
		AND o.TP_ESTQ = 1
		AND n.STS_NF=0 
		AND o.ATU_EST=1 
		AND i.DT_ENT>=@dtInicioMes 
		AND i.DT_ENT<@dtInicioMesPosterior 
	GROUP BY 
		i.CD_PROD;
		 
		 
/**********************************************************************************************************************/
-- Saidas notas fiscais em terceiros
/**********************************************************************************************************************/
	Print 'Insere saidas em terceiros #PROD_NF_SAI_EM_TERC - Time ' + convert(varchar(20),getdate(),108); 
	 
	INSERT INTO #PROD_NF_SAI_EM_TERC
	SELECT 
		i.CD_PROD,  
		SUM(i.QT_IT) QT_EST_EM_TERC  
	FROM 
		EST_NF_SAI n 
		INNER JOIN EST_NF_SAI_IT i ON 
		n.CD_EMP	=i.CD_EMP AND 
		n.CD_FILIAL	=i.CD_FILIAL AND 
		n.CD_NF		=i.CD_NF
		
		INNER JOIN #RsProdFecha wx ON 
		I.CD_EMP	= wx.CD_EMP AND
		I.CD_FILIAL = wx.CD_FILIAL AND
		I.CD_PROD	= wX.CD_PROD

		INNER JOIN GLB_MOV_OP o ON 
		n.CD_NT_MOV=o.CD_MOV_OP
	WHERE 
		n.CD_EMP=@cd_emp 
		AND n.CD_FILIAL=@cd_filial 
		AND n.STS_NF=0 
		AND o.BX_EST=1 
		AND o.TP_ESTQ =0
		AND i.DT_EMI_NF>=@dtInicioMes 
		AND i.DT_EMI_NF<@dtInicioMesPosterior 
		AND o.ENVIO_OPERADOR_LOG =1
		AND NOT EXISTS (SELECT * FROM PDV_VD_EST_NF_SAI  --Retira nota que substitui cupom fiscal
					  WHERE n.CD_EMP=CD_EMP AND n.CD_FILIAL=CD_FILIAL AND n.CD_NF=CD_NF)
	GROUP BY i.CD_PROD;

/**********************************************************************************************************************/
-- Entrada notas fiscais em terceiros
/**********************************************************************************************************************/
	Print 'Insere entradas em terceiros #PROD_NF_ENT_EM_TERC - Time ' + convert(varchar(20),getdate(),108); 

	insert into #PROD_NF_ENT_EM_TERC
	SELECT 
		i.CD_PROD,   
   		SUM(CASE WHEN ISNULL(i.VLR_ICMS_SUBS,0) > 0 THEN 
					ISNULL(i.VLR_ICMS_SUBS,0) / ISNULL(i.QT_IT,0) 
				ELSE 0 END) AS VLR_ICMS_SUBS,
		SUM(CASE WHEN ISNULL(i.VLR_ICMS_SUBS,0) > 0 THEN 
				ISNULL(i.VLR_ICMS_IT,0) / ISNULL(i.QT_IT,0) 
			ELSE 0 END) AS VLR_ICMS_IT, 
		AVG(i.VLR_PRC_CUSTO) AS VLR_CUSTO_MES_FECHA,
		SUM(i.QT_IT) * -1 QT_EST_EM_TERC  
	FROM 
		EST_NF_ENT n 
		INNER JOIN GLB_MOV_OP o ON 
		n.CD_NT_MOV=o.CD_MOV_OP 
		INNER JOIN EST_NF_ENT_IT i ON 
		n.CD_EMP=i.CD_EMP AND 
		n.CD_FILIAL=i.CD_FILIAL AND 
		n.CD_NF=i.CD_NF
		
		INNER JOIN #RsProdFecha wx ON 
		I.CD_EMP	= wx.CD_EMP AND
		I.CD_FILIAL = wx.CD_FILIAL AND
		I.CD_PROD	= wX.CD_PROD

	WHERE 
		n.CD_EMP=@cd_emp 
		AND n.CD_FILIAL=@cd_filial 
		AND o.TP_ESTQ =0 
		AND n.STS_NF=0 
		AND o.ATU_EST=1 
		AND i.DT_ENT>=@dtInicioMes 
		AND i.DT_ENT<@dtInicioMesPosterior 
		AND o.FLAG_RETORNO_OPERADOR_LOG=1
	GROUP BY 
		i.CD_PROD;

/**********************************************************************************************************************/
-- Entrada notas fiscais de terceiros
/**********************************************************************************************************************/
	Print 'Insere entradas de terceiros #PROD_NF_ENT_DE_TERC - Time ' + convert(varchar(20),getdate(),108); 

	INSERT INTO #PROD_NF_ENT_DE_TERC
	SELECT 
		i.CD_PROD,  
   		SUM(CASE WHEN ISNULL(i.VLR_ICMS_SUBS,0) > 0 THEN 
				ISNULL(i.VLR_ICMS_SUBS,0) / ISNULL(i.QT_IT,0) 
			ELSE 0  END) AS VLR_ICMS_SUBS,
		SUM(CASE WHEN ISNULL(i.VLR_ICMS_SUBS,0) > 0 THEN 
				ISNULL(i.VLR_ICMS_IT,0) / ISNULL(i.QT_IT,0) 
			ELSE 0 END)AS VLR_ICMS_IT, 
		AVG(i.VLR_PRC_CUSTO) AS VLR_CUSTO_MES_FECHA, 
		SUM(i.QT_IT) QT_EST_DE_TERC  
	FROM 
		EST_NF_ENT n INNER JOIN GLB_MOV_OP o ON 
		n.CD_NT_MOV=o.CD_MOV_OP 
		INNER JOIN EST_NF_ENT_IT i ON 
		n.CD_EMP=i.CD_EMP AND 
		n.CD_FILIAL=i.CD_FILIAL AND 
		n.CD_NF=i.CD_NF

		
		INNER JOIN #RsProdFecha wx ON 
		I.CD_EMP	= wx.CD_EMP AND
		I.CD_FILIAL = wx.CD_FILIAL AND
		I.CD_PROD	= wX.CD_PROD

	WHERE 
		n.CD_EMP=@cd_emp 
		AND n.CD_FILIAL=@cd_filial 
		AND o.TP_ESTQ =3 
		AND n.STS_NF=0 
		AND o.ATU_EST=1 
		AND i.DT_ENT>=@dtInicioMes 
		AND i.DT_ENT<@dtInicioMesPosterior 
		AND o.FLAG_ENTRADA_OPERADOR_LOG=1
	GROUP BY 
		i.CD_PROD;

/**********************************************************************************************************************/
-- Saida notas fiscais de terceiros
/**********************************************************************************************************************/
   Print 'Insere saidas de terceiros #PROD_NF_SAI_DE_TERC - Time ' + convert(varchar(20),getdate(),108); 

   INSERT INTO #PROD_NF_SAI_DE_TERC
   SELECT 
		i.CD_PROD, 
    	SUM((i.QT_IT * -1)) QT_EST_DE_TERC 
	FROM 
		EST_NF_SAI n 
		INNER JOIN EST_NF_SAI_IT i ON 
		n.CD_EMP=i.CD_EMP AND 
		n.CD_FILIAL=i.CD_FILIAL AND 
		n.CD_NF=i.CD_NF
		INNER JOIN GLB_MOV_OP o ON 
		n.CD_NT_MOV=o.CD_MOV_OP
		
		INNER JOIN #RsProdFecha wx ON 
		I.CD_EMP	= wx.CD_EMP AND
		I.CD_FILIAL = wx.CD_FILIAL AND
		I.CD_PROD	= wX.CD_PROD
	WHERE 
		n.CD_EMP=@cd_emp 
		AND n.CD_FILIAL=@cd_filial 
		AND n.STS_NF=0 
		AND o.BX_EST=1 
		AND o.TP_ESTQ =3
		AND i.DT_EMI_NF>=@dtInicioMes 
		AND i.DT_EMI_NF<@dtInicioMesPosterior 
		AND o.FLAG_RETORNO_OPERADOR_LOG =1
		AND NOT EXISTS (SELECT * FROM PDV_VD_EST_NF_SAI  --Retira nota que substitui cupom fiscal
					  WHERE n.CD_EMP=CD_EMP AND n.CD_FILIAL=CD_FILIAL AND n.CD_NF=CD_NF)
	GROUP BY i.CD_PROD;

/**********************************************************************************************************************/
-- Saida venda cupom fiscal
/**********************************************************************************************************************/
	
	Print 'Insere saidas cupom #PROD_VD_PDV - Time ' + convert(varchar(20),getdate(),108); 
	INSERT INTO #PROD_VD_PDV
    SELECT 
		i.CD_PROD, 
		SUM(i.QT_IT) AS QT_IT_PDV,  
		SUM(i.QT_IT  * I.VLR_CUSTO_MEDIO
		) VLR_CMV  
	FROM 
		PDV_VD v 
		INNER JOIN PDV_VD_IT i ON 
		v.CD_VD=i.CD_VD AND 
		v.CD_FILIAL=i.CD_FILIAL AND 
		v.CD_EMP=i.CD_EMP
		and	v.DT_VD=i.DT_VD  

		INNER JOIN #RsProdFecha wx ON 
		I.CD_EMP	= wx.CD_EMP AND
		I.CD_FILIAL = wx.CD_FILIAL AND
		I.CD_PROD	= wX.CD_PROD
	WHERE 
		v.CD_EMP=@cd_emp 
		AND v.CD_FILIAL=@cd_filial 
		AND i.ST_IT=1 
		AND v.ST_VD=0 
		AND i.DT_VD>=@dtInicioMes 
		AND i.DT_VD<@dtInicioMesPosterior
	GROUP BY I.CD_PROD ;

/**********************************************************************************************************************/
-- Ajustes
/**********************************************************************************************************************/
 	Print 'Insere ajustes #PROD_AJUSTE - Time ' + convert(varchar(20),getdate(),108); 
	
	INSERT INTO #PROD_AJUSTE
	SELECT 
		I.CD_PROD, 
		SUM(I.QT_IMP) AS QT_IT_IMP,  
		SUM((I.QT_IMP   * I.VLR_CUSTO_MD
					   )) AS VLR_AJUSTES_CM, 

		SUM(CASE WHEN I.TP_IMP= 6 THEN 
			I.QT_IMP 	ELSE 0 END) QT_DEV_VD ,	
			 
		SUM(CASE WHEN I.TP_IMP =6 	THEN
				(I.QT_IMP   * I.VLR_CUSTO_MD
						  )
				ELSE 0 END ) AS VLR_DEV_VD_CM,		 
		SUM(CASE WHEN I.TP_IMP =6 	THEN 0 else
			case when I.QT_IMP > 0 THEN I.QT_IMP ELSE 0 END  end) AS QT_AJUSTE_ENT,  

		SUM(CASE WHEN I.TP_IMP =6 	THEN 0 else
			case when I.QT_IMP < 0 THEN I.QT_IMP ELSE 0 END end) AS QT_AJUSTE_SAI,  
		
		SUM(CASE WHEN I.TP_IMP =6 	THEN 0 
				 WHEN I.TP_IMP = 5 	THEN (I.QT_IMP * i.VLR_CUSTO_MD) --Entrada requisicao					
				else
					case when I.QT_IMP > 0 THEN 
						(I.QT_IMP   * I.VLR_CUSTO_MD
					   ) 
					ELSE 0 
					END  
				end)  AS VLR_AJUSTE_ENT_CM, 

		SUM(CASE WHEN I.TP_IMP = 6 	THEN 0 
				 WHEN I.TP_IMP = 4 	THEN (I.QT_IMP * i.VLR_CUSTO_MD) --Saida requisicao
			else
			case when I.QT_IMP < 0 THEN (I.QT_IMP   * I.VLR_CUSTO_MD
					   ) ELSE 0 END end)  AS VLR_AJUSTE_SAI_CM 
	FROM 
		EST_PROD_IMP I
		
		INNER JOIN #RsProdFecha wx ON 
		I.CD_EMP	= wx.CD_EMP AND
		I.CD_FILIAL = wx.CD_FILIAL AND
		I.CD_PROD	= wX.CD_PROD
	WHERE 
		I.CD_EMP=@cd_emp 
		AND I.CD_FILIAL=@cd_filial 
		AND I.TP_EST=0 
		AND I.DT_CAD>=@dtInicioMes 
		AND I.DT_CAD<@dtInicioMesPosterior
	GROUP BY I.CD_PROD;

/**********************************************************************************************************************/
-- Saidas
/**********************************************************************************************************************/
 	Print 'Insere saidas diversas - Time ' + convert(varchar(20),getdate(),108); 
	
	INSERT INTO #PROD_SAI_PED_VD
	SELECT 
		i.CD_PROD,  
		SUM(i.QT_IT) AS QT_IT_PED_VD, 
		SUM(i.QT_IT * I.VLR_CUSTO_MD
		) VLR_CMV  
	FROM 
		EST_PED_VD_ORC o  
		INNER JOIN EST_PED_VD_IT i ON 
		o.CD_EMP=i.CD_EMP AND 
		o.CD_FILIAL=i.CD_FILIAL AND 
		o.CD_PED=i.CD_PED

		INNER JOIN #RsProdFecha wx ON 
		I.CD_EMP	= wx.CD_EMP AND
		I.CD_FILIAL = wx.CD_FILIAL AND
		I.CD_PROD	= wX.CD_PROD

	WHERE 
		i.CD_EMP=@cd_emp 
		AND o.CD_FILIAL=@cd_filial 
		AND o.DT_CAD>=@dtInicioMes 
		AND o.DT_CAD<@dtInicioMesPosterior
	GROUP BY I.CD_PROD;

/**********************************************************************************************************************/
-- Entradas
/**********************************************************************************************************************/
 	Print 'Insere entradas diversas - Time ' + convert(varchar(20),getdate(),108); 
	INSERT INTO #PROD_ENT_PED_CP
	SELECT 
		i.CD_PROD,  
		SUM(i.QT_IT) AS QT_IT_PED_CP,  
		SUM(i.QT_IT) AS QT_ENT_CP,  
		SUM(i.QT_IT * i.VLR_CUSTO
			 ) AS VLR_ENT_CP 
	FROM 
		EST_PED_CP_IT i 
		INNER JOIN EST_PED_CP_ORC o ON 
		i.CD_EMP=o.CD_EMP AND 
		i.CD_FILIAL=o.CD_FILIAL AND 
		i.CD_PED=o.CD_PED
		
		INNER JOIN #RsProdFecha wx ON 
		I.CD_EMP	= wx.CD_EMP AND
		I.CD_FILIAL = wx.CD_FILIAL AND
		I.CD_PROD	= wX.CD_PROD
	WHERE 
		o.CD_EMP=@cd_emp 
		AND o.CD_FILIAL=@cd_filial 
		AND o.DT_CAD>=@dtInicioMes 
		AND o.DT_CAD<@dtInicioMesPosterior
	GROUP BY I.CD_PROD; 

/**********************************************************************************************************************/
-- Ajuste flutuante
/**********************************************************************************************************************/
	Print 'Insere ajustes estoque flutuante - Time ' + convert(varchar(20),getdate(),108); 
	INSERT INTO #PROD_AJUSTE_FLUT
	SELECT 
		CD_PROD,	 
		SUM(QT_IMP) AS QT_EST_FLUT,  
		SUM(CASE WHEN TP_IMP =6 	THEN 0 ELSE
				CASE WHEN QT_IMP > 0 THEN QT_IMP ELSE 0 END  END) AS QT_AJUSTE_ENT_FLUTUANTE,  
		SUM(CASE WHEN TP_IMP =6 	THEN 0 ELSE
				CASE WHEN QT_IMP > 0 THEN (QT_IMP *  VLR_CUSTO_MD
											 ) ELSE 0 END  END)  AS VLR_AJUSTE_ENT_FLUTUANTE, 
		SUM(CASE WHEN TP_IMP =6 	THEN 0 ELSE
				CASE WHEN QT_IMP < 0 THEN QT_IMP ELSE 0 END END) AS QT_AJUSTE_SAI_FLUTUANTE, 
		SUM(CASE WHEN TP_IMP =6 	THEN 0 ELSE
				CASE WHEN QT_IMP < 0 THEN (QT_IMP * VLR_CUSTO_MD
											) ELSE 0 END END)  AS VLR_AJUSTE_SAI_FLUTUANTE 
	FROM 
		EST_PROD_IMP
	WHERE 
		CD_EMP=@cd_emp 
		AND CD_FILIAL=@cd_filial 
		AND TP_EST=1 
		AND DT_CAD>=@dtInicioMes 
		AND DT_CAD<@dtInicioMesPosterior
	GROUP BY CD_PROD; 	

/**********************************************************************************************************************/
-- Ajuste em Terceiros
/**********************************************************************************************************************/
	Print 'Insere ajustes estoque em terceiros - Time ' + convert(varchar(20),getdate(),108); 
	INSERT INTO #PROD_AJUSTE_EM_TERC
	SELECT 
		I.CD_PROD,	 
		SUM(I.QT_IMP) AS QT_EST_EM_TERC  
	FROM 
		EST_PROD_IMP I
		
		INNER JOIN #RsProdFecha wx ON 
		I.CD_EMP	= wx.CD_EMP AND
		I.CD_FILIAL = wx.CD_FILIAL AND
		I.CD_PROD	= wX.CD_PROD
	WHERE 
		I.CD_EMP=@cd_emp 
		AND I.CD_FILIAL=@cd_filial 
		AND I.TP_EST=2 
		AND I.DT_CAD>=@dtInicioMes 
		AND I.DT_CAD<@dtInicioMesPosterior
	GROUP BY I.CD_PROD; 

/**********************************************************************************************************************/
-- Ajuste de terceiros
/**********************************************************************************************************************/
	
	Print 'Insere ajustes estoque de terceiros - Time ' + convert(varchar(20),getdate(),108); 
 	INSERT INTO #PROD_AJUSTE_DE_TERC
	SELECT 
		I.CD_PROD, 
		SUM(I.QT_IMP) AS QT_EST_DE_TERC 
	FROM 
		EST_PROD_IMP I
			
		INNER JOIN #RsProdFecha wx ON 
		I.CD_EMP	= wx.CD_EMP AND
		I.CD_FILIAL = wx.CD_FILIAL AND
		I.CD_PROD	= wX.CD_PROD
	WHERE 
		I.CD_EMP=@cd_emp 
		AND I.CD_FILIAL=@cd_filial 
		AND I.TP_EST=3 
		AND I.DT_CAD>=@dtInicioMes 
		AND I.DT_CAD<@dtInicioMesPosterior
	GROUP BY I.CD_PROD;
		 
/**********************************************************************************************************************/
-- Acerto de custo médio
/**********************************************************************************************************************/
	Print 'Insere ajustes no custo medio - Time ' + convert(varchar(20),getdate(),108); 
 	INSERT INTO #PROD_ACERTO_CUSTO
	SELECT 
		A.CD_PROD, 
		SUM(A.VLR_AJUSTE_CUSTO)VLR_AJUSTE_CUSTO
	FROM 
		EST_FECHA_PROC_MOV A			
		INNER JOIN #RsProdFecha wx ON 
		A.CD_EMP	= wx.CD_EMP AND
		A.CD_FILIAL = wx.CD_FILIAL AND
		A.CD_PROD	= wX.CD_PROD
	WHERE 
		A.CD_EMP=@cd_emp 
		AND A.CD_FILIAL=@cd_filial  
		AND A.DT_PROC>=@dtInicioMes 
		AND A.DT_PROC<@dtInicioMesPosterior
	GROUP BY A.CD_PROD;
		 
/**********************************************************************************************************************/
-- Exclui o movimento existente
/**********************************************************************************************************************/
  
    Print 'Limpa a tabela EST_FECHA - Time ' + convert(varchar(20),getdate(),108);  
	 
	DELETE FROM P
	FROM 
		EST_FECHA_PARCIAL P
		INNER JOIN #RsProdFecha wx ON 
		P.CD_EMP	= wx.CD_EMP AND
		P.CD_FILIAL = wx.CD_FILIAL AND
		P.CD_PROD	= wX.CD_PROD
	WHERE 
		P.CD_EMP=@CD_EMP 
		AND P.CD_FILIAL=@CD_FILIAL 
		AND P.MES_FECHA=@MES 
		AND P.ANO_FECHA=@ANO;
			 
	IF @PARCIAL =0 
	BEGIN
		DELETE FROM P
		FROM 
			EST_FECHA  P
			INNER JOIN #RsProdFecha wx ON 
			P.CD_EMP	= wx.CD_EMP AND
			P.CD_FILIAL = wx.CD_FILIAL AND
			P.CD_PROD	= wX.CD_PROD
		WHERE 
			P.CD_EMP=@CD_EMP 
			AND P.CD_FILIAL=@CD_FILIAL 
			AND P.MES_FECHA=@MES 
			AND P.ANO_FECHA=@ANO;
	END
	 

/**********************************************************************************************************************/
-- Juncao das tabelas temporarias para gerar o resultado
/**********************************************************************************************************************/
    Print 'Carrega resultado - Time ' + convert(varchar(20),getdate(),108); 
	

	INSERT INTO EST_FECHA_PARCIAL (CD_EMP,CD_FILIAL,ANO_FECHA,MES_FECHA,CD_PROD,QT_EST,
								QT_SAI,QT_ENT,QT_ME,QT_IMP,QT_TRANSF_SAI,QT_TRANSF_ENT,VLR_CUSTO,
								VLR_CUSTO_MD,VLR_VD,VLR_SUBS_PROD,VLR_ICMS_PROD,CD_SIGLA,QT_EST_EM_TERC,
								QT_EST_DE_TERC,QT_EST_FLUT,MEDIAF,EMAX,ESEG,LISTA_PROD,PIS_COFINS,VLR_CUSTO_GER,
								QT_EST_INI, DT_CAD,VLR_CMV,VLR_ENTRADAS_CE,VLR_SAIDA_TRANSF_CM,VLR_EST_INICIAL_CM,
								VLR_ENTRADA_TRANSF_CM,VLR_AJUSTES_CM, QT_DEV_VD,
								VLR_DEV_VD_CM,QT_DEV_CP, VLR_DEV_CP_CM , 
								QT_AJUSTE_ENT, QT_AJUSTE_SAI,
								QT_ENT_CP, QT_ENT_BONIFICA, QT_ENT_OUTRAS, 
								QT_SAI_VD, QT_SAI_BONIFICA, QT_SAI_OUTRAS,
								VLR_AJUSTE_ENT_CM, VLR_AJUSTE_SAI_CM,
								VLR_ENT_CP, VLR_ENT_BONIFICA, VLR_ENT_OUTRAS, 
								VLR_SAI_VD, VLR_SAI_BONIFICA, VLR_SAI_OUTRAS,
								QT_SAI_PERDA, VLR_SAI_PERDA, 
								QT_INI_FLUT, VLR_INI_FLUT, QT_ENT_TRANSF_FLUT, VLR_ENT_TRANSF_FLUT,
								QT_DEV_CP_FLUTUANTE, VLR_DEV_CP_FLUTUANTE, QT_SAI_PERDA_FLUTUANTE, VLR_SAI_PERDA_FLUTUANTE,
								QT_DEV_VD_FLUTUANTE, VLR_DEV_VD_FLUTUANTE, QT_AJUSTE_ENT_FLUTUANTE,VLR_AJUSTE_ENT_FLUTUANTE,
								QT_AJUSTE_SAI_FLUTUANTE,VLR_AJUSTE_SAI_FLUTUANTE,QT_SAI_TRANSF_FLUT, VLR_SAI_TRANSF_FLUT,
								QT_ENT_OUTRAS_FLUTUANTE, VLR_ENT_OUTRAS_FLUTUANTE, QT_SAI_OUTRAS_FLUTUANTE, 
								VLR_SAI_OUTRAS_FLUTUANTE,VLR_SALDO_CUSTO, VLR_CUSTO_MD_FLUTUANTE,
								QT_ACERTO_CUSTO,VLR_ACERTO_CUSTO, VLR_SALDO_CUSTO_INI, QT_ESTORNO_NF,VLR_ESTORNO_NF)

	SELECT 
		@cd_emp AS CD_EMP, 
		@cd_filial AS CD_FILIAL, 
		@ano AS ANO, 
		convert(int,@mes) AS MES, 
		INI.CD_PROD, 
		SUM(ISNULL(QT_EST_FECHA,0)) + SUM(ISNULL(QT_IT_NF_ENT,0)) + SUM(ISNULL(QT_IT_IMP,0)) + SUM(ISNULL(QT_IT_PED_CP,0)) 
				+ SUM(ISNULL(QT_IT_ENT_TRANSF,0)) + SUM(ISNULL(QT_IT_ENT_CANC,0)) + SUM(ISNULL(QT_ENT_EST,0)) 
				- SUM(ISNULL(QT_IT_NF_SAI,0)) - SUM(ISNULL(QT_IT_PDV,0)) 
				- SUM(ISNULL(QT_IT_PED_VD,0)) - SUM(ISNULL(QT_IT_SAI_TRANF,0)) 
				- SUM(ISNULL(QT_SAI_EST,0))AS QT_EST,	

		SUM(ISNULL(QT_IT_NF_SAI,0)) + SUM(ISNULL(QT_IT_PDV,0)) + SUM(ISNULL(QT_IT_PED_VD,0))+SUM(ISNULL(QT_SAI_EST,0)) AS QT_SAI,
		SUM(ISNULL(QT_IT_NF_ENT,0)) + SUM(ISNULL(QT_IT_PED_CP,0))  + SUM(ISNULL(QT_IT_ENT_CANC,0)) + SUM(ISNULL(QT_ENT_EST,0))  AS QT_ENT,
		0 AS QT_ME,
		SUM(ISNULL(QT_IT_IMP,0)) AS QT_IMP,
		SUM(ISNULL(QT_IT_SAI_TRANF,0)) AS QT_IT_SAI_TRANF,
		SUM(ISNULL(QT_IT_ENT_TRANSF,0)) AS QT_IT_ENT_TRANSF,
		SUM(CASE WHEN ISNULL(VLR_CUSTO_MOV,0)  > 0 THEN
				ISNULL(VLR_CUSTO_MOV,0) 
			ELSE
				CASE WHEN ISNULL(ENT_NF.VLR_CUSTO_MES_FECHA,0) +
										ISNULL(NF_ENT_EM_TERC.VLR_CUSTO_MES_FECHA,0) +
											ISNULL(NF_ENT_DE_TERC.VLR_CUSTO_MES_FECHA,0)=0 THEN 
					ISNULL(VLR_CUSTO_CAD,0)
				ELSE 
					ISNULL(ENT_NF.VLR_CUSTO_MES_FECHA,0) +
										ISNULL(NF_ENT_EM_TERC.VLR_CUSTO_MES_FECHA,0) +
											ISNULL(NF_ENT_DE_TERC.VLR_CUSTO_MES_FECHA,0) 
				END 
			END) VLR_CUSTO,
		SUM(ISNULL(INI.VLR_CUSTO_MD_MOV,0)) VLR_CUSTO_MD, -- Custo medio não pode ser alterado deve ser valor contabil, por favor respeitar esta instrução	
		
		SUM(VLR_TABELA) AS VLR_VD,	

		SUM(ISNULL(ENT_NF.VLR_ICMS_SUBS,0) +
				ISNULL(NF_ENT_EM_TERC.VLR_ICMS_SUBS,0) +
				ISNULL(NF_ENT_DE_TERC.VLR_ICMS_SUBS,0)) AS VLR_ICMS_SUBS,

		SUM(ISNULL(ENT_NF.VLR_ICMS_IT,0)+
						ISNULL(NF_ENT_EM_TERC.VLR_ICMS_IT,0)+
							ISNULL(NF_ENT_DE_TERC.VLR_ICMS_IT,0)) AS VLR_ICMS_IT,
		INI.CD_SIGLA,
		SUM(ISNULL(FECHA_ANT.QT_EST_EM_TERC,0)+
						ISNULL(NF_SAI_EM_TERC.QT_EST_EM_TERC,0)+
						ISNULL(NF_ENT_EM_TERC.QT_EST_EM_TERC,0)+
						ISNULL(AJUSTE_EM_TERC.QT_EST_EM_TERC,0)) QT_EST_EM_TERC,
		SUM(ISNULL(FECHA_ANT.QT_EST_DE_TERC,0)+
				ISNULL(NF_ENT_DE_TERC.QT_EST_DE_TERC,0)+
				ISNULL(NF_SAI_DE_TERC.QT_EST_DE_TERC,0)+
				ISNULL(AJUSTE_DE_TERC.QT_EST_DE_TERC,0)) QT_EST_DE_TERC,

		SUM(ISNULL(FECHA_ANT.QT_EST_FLUT,0 )+
					ISNULL(SAI_NF_FLUT.QT_EST_FLUT,0 )+
					ISNULL(ENT_NF_FLUT.QT_EST_FLUT,0 )+
					ISNULL(AJUSTE_FLUT.QT_EST_FLUT,0 )) QT_EST_FLUT,
		SUM(ISNULL(MEDIAF,0)) MEDIAF,
		SUM(ISNULL(EMAX,0)) EMAX,
		SUM(ISNULL(ESEG,0)) ESEG,
		INI.LISTA_PROD,	
		INI.PIS_COFINS,
		SUM(ISNULL(VLR_CUSTO_GER,0))	VLR_CUSTO_GER,
		SUM(ISNULL(QT_EST_FECHA,0))		QT_EST_INI,
		GETDATE () DT_CAD,
		SUM(CASE WHEN (ISNULL(QT_IT_NF_SAI,0) + ISNULL(QT_IT_PDV,0) + ISNULL(QT_IT_PED_VD,0)) <> 0 THEN
			(ISNULL(SAI_NF.VLR_CMV,0)+ISNULL(VD_PDV.VLR_CMV,0)+ISNULL(SAI_PED_VD.VLR_CMV,0))/ 
					(ISNULL(QT_IT_NF_SAI,0) + ISNULL(QT_IT_PDV,0) + ISNULL(QT_IT_PED_VD,0))
			 ELSE 0 END) AS VLR_CMV,
	 
		SUM(CASE WHEN ISNULL(QT_IT_NF_ENT,0) <> 0 THEN
			 ISNULL(VLR_ENTRADAS_CE,0)/ ISNULL(QT_IT_NF_ENT,0) ELSE 0 END) AS VLR_ENTRADAS_CE,
		
		SUM(CASE WHEN  ISNULL(QT_IT_SAI_TRANF,0) <> 0 THEN
				(ISNULL(VLR_SAIDA_TRANSF_CM,0))/ISNULL(QT_IT_SAI_TRANF,0)ELSE 0 END) AS VLR_SAIDA_TRANSF_CM,
		 
		SUM(CASE WHEN ISNULL(QT_EST_FECHA,0) <> 0 THEN
				(ISNULL(VLR_EST_INICIAL_CM,0)/ ISNULL(QT_EST_FECHA,0)) ELSE 0 END) AS VLR_EST_INICIAL_CM,
		
		SUM(CASE WHEN   ISNULL(QT_IT_ENT_TRANSF,0)  <> 0 THEN
				 (ISNULL(VLR_ENTRADA_TRANSF_CM,0) / ISNULL(QT_IT_ENT_TRANSF,0)) ELSE 0 END) AS VLR_ENTRADA_TRANSF_CM,
		
		SUM(CASE WHEN  ISNULL(QT_IT_IMP,0) <> 0 THEN
				(ISNULL(VLR_AJUSTES_CM,0)/ISNULL(QT_IT_IMP,0))  ELSE 0 END) AS VLR_AJUSTES_CM,
		SUM(ISNULL(ENT_NF.QT_DEV_VD,0)+ISNULL(AJUSTE.QT_DEV_VD,0))  QT_DEV_VD,	

		SUM(CASE WHEN ISNULL(ENT_NF.QT_DEV_VD,0)+ISNULL(AJUSTE.QT_DEV_VD,0) <> 0 THEN
			(ISNULL(ENT_NF.VLR_DEV_VD_CM,0)+ISNULL(AJUSTE.VLR_DEV_VD_CM,0))/ 
				(ISNULL(ENT_NF.QT_DEV_VD,0)+ISNULL(AJUSTE.QT_DEV_VD,0))
			ELSE 0 END) AS VLR_DEV_VD_CM,		
		
		SUM(ISNULL(QT_DEV_CP,0))  QT_DEV_CP,
		SUM(CASE WHEN ISNULL(QT_DEV_CP,0)   <> 0 THEN
				(ISNULL(VLR_DEV_CP_CM,0)/ ISNULL(QT_DEV_CP,0)) ELSE 0 END) AS VLR_DEV_CP_CM,
  
		SUM(ISNULL(QT_AJUSTE_ENT,0))	QT_AJUSTE_ENT,		
		SUM(ISNULL(QT_AJUSTE_SAI,0))	QT_AJUSTE_SAI,		
		SUM(ISNULL(ISNULL(ENT_NF.QT_ENT_CP,0)+ ISNULL(ENT_PED_CP.QT_ENT_CP,0),0)) QT_ENT_CP,		
		SUM(ISNULL(QT_ENT_BONIFICA,0))  QT_ENT_BONIFICA,		
		SUM(ISNULL(QT_ENT_OUTRAS,0))	+  SUM(ISNULL(QT_IT_ENT_CANC,0)) +SUM(ISNULL(QT_ENT_EST,0))  QT_ENT_OUTRAS,		
		SUM(ISNULL(SAI_NF.QT_SAI_VD,0)  +ISNULL(VD_PDV.QT_IT_PDV,0)+ISNULL(SAI_PED_VD.QT_IT_PED_VD,0))	QT_SAI_VD,		
		SUM(ISNULL(QT_SAI_BONIFICA,0))  QT_SAI_BONIFICA,		
		SUM(ISNULL(QT_SAI_OUTRAS,0))+SUM(ISNULL(QT_SAI_EST,0) )	QT_SAI_OUTRAS,   
		
		SUM(CASE WHEN ISNULL(QT_AJUSTE_ENT,0) <> 0 THEN
				ISNULL(VLR_AJUSTE_ENT_CM,0)/ ISNULL(QT_AJUSTE_ENT,0)ELSE 0 END)AS VLR_AJUSTE_ENT_CM, 
		SUM(CASE WHEN ISNULL(QT_AJUSTE_SAI,0)  <> 0 THEN
				ISNULL(VLR_AJUSTE_SAI_CM,0)/ ISNULL(QT_AJUSTE_SAI,0)ELSE 0 END) AS VLR_AJUSTE_SAI_CM, 
		SUM(CASE WHEN (ISNULL(ENT_NF.QT_ENT_CP,0)+ISNULL(ENT_PED_CP.QT_ENT_CP,0)) <> 0 THEN
				(ISNULL(ENT_NF.VLR_ENT_CP,0)+ISNULL(ENT_PED_CP.VLR_ENT_CP,0))/ 
					(ISNULL(ENT_NF.QT_ENT_CP,0)+ ISNULL(ENT_PED_CP.QT_ENT_CP,0)) ELSE 0 END) AS VLR_ENT_CP, 
		SUM(CASE WHEN ISNULL(QT_ENT_BONIFICA,0)  <> 0 THEN
				ISNULL(VLR_ENT_BONIFICA,0)/ISNULL(QT_ENT_BONIFICA,0) ELSE 0 END) AS VLR_ENT_BONIFICA,	  

		SUM((CASE WHEN ISNULL(QT_ENT_OUTRAS,0) <> 0 THEN
				ISNULL(VLR_ENT_OUTRAS,0)/ISNULL(QT_ENT_OUTRAS,0) ELSE 0 END )) 
				
				+ SUM(CASE WHEN ISNULL(QT_IT_ENT_CANC,0)  > 0 THEN
						ISNULL(VLR_ENT_CANC,0)/ISNULL(QT_IT_ENT_CANC,0) 						
						ELSE 0 END)
				+ SUM(CASE WHEN ISNULL(QT_ENT_EST,0)  > 0 THEN
						ISNULL(VLR_ENT_EST,0)/ISNULL(QT_ENT_EST,0) 			
						ELSE 0 END) AS VLR_ENT_OUTRAS,	
		
		SUM(CASE WHEN ISNULL(SAI_NF.QT_SAI_VD,0)+ISNULL(VD_PDV.QT_IT_PDV,0)+ISNULL(SAI_PED_VD.QT_IT_PED_VD,0) <> 0 THEN
				(ISNULL(SAI_NF.VLR_SAI_VD,0)+ISNULL(VD_PDV.VLR_CMV,0)+ISNULL(SAI_PED_VD.VLR_CMV,0))/ 
					(ISNULL(SAI_NF.QT_SAI_VD,0)+ISNULL(VD_PDV.QT_IT_PDV,0)+ISNULL(SAI_PED_VD.QT_IT_PED_VD,0)) 
			ELSE 0 END) AS VLR_SAI_VD,

		SUM(CASE WHEN ISNULL(QT_SAI_BONIFICA,0)<> 0 THEN
				(ISNULL(VLR_SAI_BONIFICA,0)/ISNULL(QT_SAI_BONIFICA,0)) ELSE 0 END) AS VLR_SAI_BONIFICA, 
		SUM(CASE WHEN ISNULL(QT_SAI_OUTRAS,0) <> 0 THEN
				( VLR_SAI_OUTRAS/ ISNULL(QT_SAI_OUTRAS,0)) ELSE 0 END)
			+ SUM(CASE WHEN ISNULL(QT_SAI_EST,0)  > 0 THEN
						ISNULL(VLR_SAI_EST,0)/ISNULL(QT_SAI_EST,0) 			
						ELSE 0 END),
						
 		SUM(ISNULL(QT_SAI_PERDA,0))	QT_SAI_PERDA,   
		SUM(CASE WHEN ISNULL(QT_SAI_PERDA,0) <> 0 THEN
				(ISNULL(VLR_SAI_PERDA,0)/ ISNULL(QT_SAI_PERDA,0))  ELSE 0 END) AS VLR_SAI_PERDA,
		
		SUM(ISNULL(QT_INI_FLUT,0)) QT_INI_FLUT,  
		SUM(CASE WHEN ISNULL(QT_INI_FLUT,0)  <> 0 THEN
				ISNULL(VLR_INI_FLUT,0)/ISNULL(QT_INI_FLUT,0)  
			ELSE ISNULL(VLR_INI_FLUT,0) END) AS VLR_INI_FLUT ,
			 
		SUM(ISNULL(QT_ENT_TRANSF_FLUT,0)) QT_ENT_TRANSF_FLUT, 		 
		SUM(CASE WHEN ISNULL(QT_ENT_TRANSF_FLUT,0) <> 0 THEN
				(ISNULL(VLR_ENT_TRANSF_FLUT,0)/ ISNULL(QT_ENT_TRANSF_FLUT,0)) ELSE 0 END) AS VLR_ENT_TRANSF_FLUT,  
		SUM(ISNULL(QT_DEV_CP_FLUTUANTE,0)) QT_DEV_CP_FLUTUANTE, 				
		SUM(CASE WHEN ISNULL(QT_DEV_CP_FLUTUANTE,0) <> 0 THEN
				(ISNULL(VLR_DEV_CP_FLUTUANTE,0)/ ISNULL(QT_DEV_CP_FLUTUANTE,0)) ELSE 0 END) AS VLR_DEV_CP_FLUTUANTE, 
		SUM(ISNULL(QT_SAI_PERDA_FLUTUANTE,0)) QT_SAI_PERDA_FLUTUANTE, 		
		SUM(CASE WHEN ISNULL(QT_SAI_PERDA_FLUTUANTE,0) <> 0 THEN
				(ISNULL(VLR_SAI_PERDA_FLUTUANTE,0)/ISNULL(QT_SAI_PERDA_FLUTUANTE,0))  ELSE 0 END) AS VLR_SAI_PERDA_FLUTUANTE,
		SUM(ISNULL(QT_DEV_VD_FLUTUANTE,0)) QT_DEV_VD_FLUTUANTE, 	
		SUM(CASE WHEN ISNULL(QT_DEV_VD_FLUTUANTE,0) <> 0 THEN
			(ISNULL(VLR_DEV_VD_FLUTUANTE,0)/ ISNULL(QT_DEV_VD_FLUTUANTE,0))  ELSE 0 END) AS VLR_DEV_VD_FLUTUANTE, 		
		SUM(ISNULL(QT_AJUSTE_ENT_FLUTUANTE,0)) QT_AJUSTE_ENT_FLUTUANTE, 		
		SUM(CASE WHEN ISNULL(QT_AJUSTE_ENT_FLUTUANTE,0)  <> 0 THEN
			(ISNULL(VLR_AJUSTE_ENT_FLUTUANTE,0)/ ISNULL(QT_AJUSTE_ENT_FLUTUANTE,0))  ELSE 0 END) AS VLR_AJUSTE_ENT_FLUTUANTE ,  
		SUM(ISNULL(QT_AJUSTE_SAI_FLUTUANTE,0)) QT_AJUSTE_SAI_FLUTUANTE, 				
		SUM(CASE WHEN  ISNULL(QT_AJUSTE_SAI_FLUTUANTE,0) <> 0 THEN
			( ISNULL(VLR_AJUSTE_SAI_FLUTUANTE,0)/ ISNULL(QT_AJUSTE_SAI_FLUTUANTE,0))  ELSE 0 END) AS VLR_AJUSTE_SAI_FLUTUANTE , 
		SUM(ISNULL(QT_SAI_TRANSF_FLUT,0)) QT_SAI_TRANSF_FLUT, 		
		SUM(CASE WHEN ISNULL(QT_SAI_TRANSF_FLUT,0) <> 0 THEN
			(ISNULL(VLR_SAI_TRANSF_FLUT,0)/ISNULL(QT_SAI_TRANSF_FLUT,0))  ELSE 0 END) AS VLR_SAI_TRANSF_FLUT,  
		SUM(ISNULL(QT_ENT_OUTRAS_FLUTUANTE,0)) QT_ENT_OUTRAS_FLUTUANTE, 	
		SUM(CASE WHEN ISNULL(QT_ENT_OUTRAS_FLUTUANTE,0) <> 0 THEN
			(ISNULL(VLR_ENT_OUTRAS_FLUTUANTE,0)/ISNULL(QT_ENT_OUTRAS_FLUTUANTE,0))  ELSE 0 END) AS VLR_ENT_OUTRAS_FLUTUANTE,  		
		SUM(ISNULL(QT_SAI_OUTRAS_FLUTUANTE,0)) QT_SAI_OUTRAS_FLUTUANTE, 		
		SUM(CASE WHEN ISNULL(QT_SAI_OUTRAS_FLUTUANTE,0) <> 0 THEN
			(ISNULL(VLR_SAI_OUTRAS_FLUTUANTE,0)/ISNULL(QT_SAI_OUTRAS_FLUTUANTE,0))  ELSE 0 END) AS VLR_SAI_OUTRAS_FLUTUANTE  ,
		SUM(INI.VLR_SALDO_CUSTO) AS VLR_SALDO_CUSTO,
	 
		SUM(ISNULL(INI.VLR_CUSTO_MD_MOV,0)) VLR_CUSTO_MD,
		1 QT_ACERTO_CUSTO, 
		SUM( ISNULL(ACERTO_CUSTO.VLR_ACERTO_CUSTO,0) ) AS VLR_ACERTO_CUSTO, 
		SUM(FECHA_ANT.VLR_SALDO_CUSTO_INI) AS VLR_SALDO_CUSTO_INI, 
		SUM( ISNULL(EST_ENT.QT_ENT_EST,0) ) AS QT_ENT_EST, 
		SUM( ISNULL(EST_ENT.VLR_ENT_EST,0) ) AS VLR_ENT_EST  
		
	FROM 
		#PROD_INI INI 
		
		LEFT JOIN #PROD_FECHA_ANT FECHA_ANT ON INI.CD_PROD = FECHA_ANT.CD_PROD 
		LEFT JOIN #PROD_SAI_NF SAI_NF ON INI.CD_PROD = SAI_NF.CD_PROD 
		LEFT JOIN #PROD_ENT_NF ENT_NF ON INI.CD_PROD = ENT_NF.CD_PROD 
		LEFT JOIN #PROD_SAI_NF_FLUT SAI_NF_FLUT ON INI.CD_PROD = SAI_NF_FLUT.CD_PROD 
		LEFT JOIN #PROD_ENT_NF_FLUT ENT_NF_FLUT ON INI.CD_PROD = ENT_NF_FLUT.CD_PROD 
		LEFT JOIN #PROD_NF_SAI_EM_TERC NF_SAI_EM_TERC ON INI.CD_PROD = NF_SAI_EM_TERC.CD_PROD 
		LEFT JOIN #PROD_NF_ENT_EM_TERC NF_ENT_EM_TERC ON INI.CD_PROD = NF_ENT_EM_TERC.CD_PROD 
		LEFT JOIN #PROD_NF_ENT_DE_TERC NF_ENT_DE_TERC ON INI.CD_PROD = NF_ENT_DE_TERC.CD_PROD 
		LEFT JOIN #PROD_NF_SAI_DE_TERC NF_SAI_DE_TERC ON INI.CD_PROD = NF_SAI_DE_TERC.CD_PROD 
		LEFT JOIN #PROD_VD_PDV VD_PDV ON INI.CD_PROD =  VD_PDV.CD_PROD   
		LEFT JOIN #PROD_AJUSTE AJUSTE ON INI.CD_PROD =  AJUSTE.CD_PROD   
		LEFT JOIN #PROD_SAI_PED_VD SAI_PED_VD ON INI.CD_PROD =  SAI_PED_VD.CD_PROD   
		LEFT JOIN #PROD_ENT_PED_CP ENT_PED_CP ON INI.CD_PROD =  ENT_PED_CP.CD_PROD   
		LEFT JOIN #PROD_AJUSTE_FLUT AJUSTE_FLUT ON INI.CD_PROD =  AJUSTE_FLUT.CD_PROD   
		LEFT JOIN #PROD_AJUSTE_EM_TERC AJUSTE_EM_TERC ON INI.CD_PROD =  AJUSTE_EM_TERC.CD_PROD   
		LEFT JOIN #PROD_AJUSTE_DE_TERC AJUSTE_DE_TERC ON INI.CD_PROD =  AJUSTE_DE_TERC.CD_PROD 
		LEFT JOIN #PROD_ACERTO_CUSTO ACERTO_CUSTO ON INI.CD_PROD =  ACERTO_CUSTO.CD_PROD  
		LEFT JOIN #PROD_ENT_NF_CANC CANC ON INI.CD_PROD =  CANC.CD_PROD 
		LEFT JOIN #PROD_ENT_NF_EST EST_ENT ON INI.CD_PROD =  EST_ENT.CD_PROD
		LEFT JOIN #PROD_SAI_NF_EST EST_SAI ON INI.CD_PROD =  EST_SAI.CD_PROD   
	group by 
		INI.CD_PROD, 
		INI.CD_SIGLA,	
		INI.LISTA_PROD,	
		INI.PIS_COFINS  ;
		  
	IF @PARCIAL =0 
	BEGIN
		Print 'Insere o resultado final - EST_FECHA - Time ' + convert(varchar(20),getdate(),108);  
		INSERT INTO EST_FECHA (CD_EMP,CD_FILIAL,ANO_FECHA,MES_FECHA,CD_PROD,QT_EST,
								QT_SAI,QT_ENT,QT_ME,QT_IMP,QT_TRANSF_SAI,QT_TRANSF_ENT,VLR_CUSTO,
								VLR_CUSTO_MD,VLR_VD,VLR_SUBS_PROD,VLR_ICMS_PROD,CD_SIGLA,QT_EST_EM_TERC,
								QT_EST_DE_TERC,QT_EST_FLUT,MEDIAF,EMAX,ESEG,LISTA_PROD,PIS_COFINS,VLR_CUSTO_GER,
								QT_EST_INI, DT_CAD,VLR_CMV,VLR_ENTRADAS_CE,VLR_SAIDA_TRANSF_CM,VLR_EST_INICIAL_CM,
								VLR_ENTRADA_TRANSF_CM,VLR_AJUSTES_CM, QT_DEV_VD,
								VLR_DEV_VD_CM,QT_DEV_CP, VLR_DEV_CP_CM , 
								QT_AJUSTE_ENT, QT_AJUSTE_SAI,
								QT_ENT_CP, QT_ENT_BONIFICA, QT_ENT_OUTRAS, 
								QT_SAI_VD, QT_SAI_BONIFICA, QT_SAI_OUTRAS,
								VLR_AJUSTE_ENT_CM, VLR_AJUSTE_SAI_CM,
								VLR_ENT_CP, VLR_ENT_BONIFICA, VLR_ENT_OUTRAS, 
								VLR_SAI_VD, VLR_SAI_BONIFICA, VLR_SAI_OUTRAS,
								QT_SAI_PERDA, VLR_SAI_PERDA, 
								QT_INI_FLUT, VLR_INI_FLUT, QT_ENT_TRANSF_FLUT, VLR_ENT_TRANSF_FLUT,
								QT_DEV_CP_FLUTUANTE, VLR_DEV_CP_FLUTUANTE, QT_SAI_PERDA_FLUTUANTE, VLR_SAI_PERDA_FLUTUANTE,
								QT_DEV_VD_FLUTUANTE, VLR_DEV_VD_FLUTUANTE, QT_AJUSTE_ENT_FLUTUANTE,VLR_AJUSTE_ENT_FLUTUANTE,
								QT_AJUSTE_SAI_FLUTUANTE,VLR_AJUSTE_SAI_FLUTUANTE,QT_SAI_TRANSF_FLUT, VLR_SAI_TRANSF_FLUT,
								QT_ENT_OUTRAS_FLUTUANTE, VLR_ENT_OUTRAS_FLUTUANTE, QT_SAI_OUTRAS_FLUTUANTE, 
								VLR_SAI_OUTRAS_FLUTUANTE,VLR_SALDO_CUSTO,VLR_CUSTO_MD_FLUTUANTE,
								QT_ACERTO_CUSTO,VLR_ACERTO_CUSTO, VLR_SALDO_CUSTO_INI, QT_ESTORNO_NF,VLR_ESTORNO_NF)

			SELECT 
				P.CD_EMP,	P.CD_FILIAL,	P.ANO_FECHA,	P.MES_FECHA,	P.CD_PROD,	P.QT_EST,
				P.QT_SAI,	P.QT_ENT,	P.QT_ME,	P.QT_IMP,	P.QT_TRANSF_SAI,	P.QT_TRANSF_ENT,	P.VLR_CUSTO,
				P.VLR_CUSTO_MD,	P.VLR_VD,	P.VLR_SUBS_PROD,	P.VLR_ICMS_PROD,	P.CD_SIGLA,	P.QT_EST_EM_TERC,
				P.QT_EST_DE_TERC,P.QT_EST_FLUT,P.MEDIAF,P.EMAX,P.ESEG,P.LISTA_PROD,P.PIS_COFINS,P.VLR_CUSTO_GER,
				P.QT_EST_INI, P.DT_CAD,P.VLR_CMV,P.VLR_ENTRADAS_CE,P.VLR_SAIDA_TRANSF_CM,P.VLR_EST_INICIAL_CM,
				P.VLR_ENTRADA_TRANSF_CM,P.VLR_AJUSTES_CM, P.QT_DEV_VD,
				P.VLR_DEV_VD_CM,P.QT_DEV_CP, P.VLR_DEV_CP_CM , 
				P.QT_AJUSTE_ENT, P.QT_AJUSTE_SAI,
				P.QT_ENT_CP, P.QT_ENT_BONIFICA, P.QT_ENT_OUTRAS, 
				P.QT_SAI_VD, P.QT_SAI_BONIFICA, P.QT_SAI_OUTRAS,
				P.VLR_AJUSTE_ENT_CM, P.VLR_AJUSTE_SAI_CM,
				P.VLR_ENT_CP, P.VLR_ENT_BONIFICA, P.VLR_ENT_OUTRAS, 
				P.VLR_SAI_VD, P.VLR_SAI_BONIFICA, P.VLR_SAI_OUTRAS,
				P.QT_SAI_PERDA, P.VLR_SAI_PERDA, 
				P.QT_INI_FLUT, P.VLR_INI_FLUT, P.QT_ENT_TRANSF_FLUT, P.VLR_ENT_TRANSF_FLUT,
				P.QT_DEV_CP_FLUTUANTE, P.VLR_DEV_CP_FLUTUANTE, P.QT_SAI_PERDA_FLUTUANTE, P.VLR_SAI_PERDA_FLUTUANTE,
				P.QT_DEV_VD_FLUTUANTE, P.VLR_DEV_VD_FLUTUANTE, P.QT_AJUSTE_ENT_FLUTUANTE,P.VLR_AJUSTE_ENT_FLUTUANTE,
				P.QT_AJUSTE_SAI_FLUTUANTE, P.VLR_AJUSTE_SAI_FLUTUANTE, P.QT_SAI_TRANSF_FLUT, P.VLR_SAI_TRANSF_FLUT,
				P.QT_ENT_OUTRAS_FLUTUANTE, P.VLR_ENT_OUTRAS_FLUTUANTE, 
				P.QT_SAI_OUTRAS_FLUTUANTE, P.VLR_SAI_OUTRAS_FLUTUANTE,P.VLR_SALDO_CUSTO,P.VLR_CUSTO_MD_FLUTUANTE,
				P.QT_ACERTO_CUSTO,P.VLR_ACERTO_CUSTO, P.VLR_SALDO_CUSTO_INI, P.QT_ESTORNO_NF, P.VLR_ESTORNO_NF
			FROM
				EST_FECHA_PARCIAL P
				INNER JOIN #RsProdFecha wx ON 
				P.CD_EMP	= wx.CD_EMP AND
				P.CD_FILIAL = wx.CD_FILIAL AND
				P.CD_PROD	= wX.CD_PROD
			WHERE 
				P.CD_EMP=@CD_EMP 
				AND P.CD_FILIAL=@CD_FILIAL 
				AND P.MES_FECHA=@MES 
				AND P.ANO_FECHA=@ANO;

			Print 'Atualiza a tabela controle de fechamento - Time ' + convert(varchar(20),getdate(),108);  
			delete From PRC_FILIAL_EST_FECHA
			WHERE 
				CD_EMP=@CD_EMP 
				AND CD_FILIAL=@CD_FILIAL 
				AND MES_FECHA=@MES 
				AND ANO_FECHA=@ANO;

			insert into PRC_FILIAL_EST_FECHA (CD_EMP
										  ,CD_FILIAL
										  ,ANO_FECHA
										  ,MES_FECHA
										  ,CD_USU
										  ,DT_CAD
										  ,ANO_MES_FECHA)
			 select @cd_emp,
				@cd_filial,
				@ano,
				@mes,
				1,
				Getdate(),
				@ANO*100+@MES ;
				
		     Print 'Remove tabela parcial - Time ' + convert(varchar(20),getdate(),108);  
			--Remove tabela parcial
			delete from  EST_FECHA_PARCIAL
			WHERE 
				CD_EMP=@CD_EMP 
				AND CD_FILIAL=@CD_FILIAL 
				AND MES_FECHA=@MES 
				AND ANO_FECHA=@ANO;
		end
		
    Print 'Fim da rotina - EST_FECHA - Time ' + convert(varchar(20),getdate(),108);  
/**********************************************************************************************************************/
/**********************************************************************************************************************/
/**********************************************************************************************************************/

	DROP TABLE #PROD_INI;
	DROP TABLE #PROD_FECHA_ANT;
	DROP TABLE #PROD_SAI_NF;
	DROP TABLE #PROD_ENT_NF;
	DROP TABLE #PROD_SAI_NF_FLUT;
	DROP TABLE #PROD_ENT_NF_FLUT; 
	DROP TABLE #PROD_NF_SAI_EM_TERC; 
	DROP TABLE #PROD_NF_ENT_EM_TERC;
	DROP TABLE #PROD_NF_ENT_DE_TERC; 
	DROP TABLE #PROD_NF_SAI_DE_TERC;
	DROP TABLE #PROD_VD_PDV;
	DROP TABLE #RSPRODFECHA
	DROP TABLE #PROD_ENT_NF_EST  
	DROP TABLE #PROD_SAI_NF_EST 
	DROP TABLE #PROD_ENT_NF_CANC
 
	DELETE 
	FROM 
		EST_PROD_BALAN_EVENTOS 
	WHERE 
		CD_EMP=@CD_EMP
		AND CD_FILIAL=@CD_FILIAL 
		AND DT_CAD>=@DTABERTURABALAN
		AND CD_EVENTO=1
	INSERT INTO EST_PROD_BALAN_EVENTOS
	(CD_EMP,
	CD_FILIAL,
	DT_CAD,
	CD_EVENTO,
	DS_EVENTO,
	CD_USU,
	DT_REGISTRO)
	SELECT
		@CD_EMP,
		@CD_FILIAL,
		@DTABERTURABALAN,
		1,
		'REFAZER FECHAMENTO DE ESTOQUE.',
		@CD_USU,
		GETDATE()


END TRY

-- Tag #A001
BEGIN CATCH

   DECLARE @ErrorMessage VARCHAR(4000) = ERROR_MESSAGE();
   DECLARE @ErrorSeverity INT = ERROR_SEVERITY();
   DECLARE @ErrorState INT = ERROR_STATE();

   INSERT INTO ADM_ERRO ( numero ,severidade ,estado ,rotina ,linha ,mensagem ,dtErro )
	  SELECT
		 ERROR_NUMBER()			AS numero
		 ,@ErrorSeverity		AS severidade
		 ,@ErrorState			AS estado
		 ,ERROR_PROCEDURE()		AS rotina
		 ,ERROR_LINE()			AS linha
		 ,@ErrorMessage			AS mensagem
		 ,GETDATE()				AS dtErro ;

   RAISERROR(@ErrorMessage, @ErrorSeverity, @ErrorState);
END CATCH;