
/*****************************************************************************************************************************/
--Filiais deposito
/*****************************************************************************************************************************/

IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME= 'EST_FECHA_PROC_MOV_RsFilialCD')
BEGIN
	DROP TABLE EST_FECHA_PROC_MOV_RsFilialCD
END

GO
CREATE TABLE EST_FECHA_PROC_MOV_RsFilialCD (CD_EMP    Tinyint
											 ,CD_FILIAL INT
											 CONSTRAINT [PK_EST_FECHA_PROC_MOV_RsFilialCD] PRIMARY KEY CLUSTERED (CD_FILIAL, CD_EMP)
											);

GO						
/*****************************************************************************************************************************/
--Relacao produtos
/*****************************************************************************************************************************/
IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME= 'EST_FECHA_PROC_MOV_RsProdutos')
BEGIN
	DROP TABLE EST_FECHA_PROC_MOV_RsProdutos
END

GO
CREATE TABLE EST_FECHA_PROC_MOV_RsProdutos (CD_EMP Tinyint,
											CD_FILIAL		 INT,
											CD_PROD			 INT,
											VLR_CUSTO_MD	 MONEY,
											VLR_CUSTO_GER	 MONEY,
											DT_PROC			 smalldatetime,
											DT_ULT_PROC 	 smalldatetime NULL
											CONSTRAINT [PK_EST_FECHA_PROC_MOV_RsProdutos] 
												PRIMARY KEY CLUSTERED (CD_PROD, CD_FILIAL, CD_EMP))  
GO
/*****************************************************************************************************************************/
--DARE de devolucao para fornecedor	
/*****************************************************************************************************************************/
IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME= 'EST_FECHA_PROC_MOV_RsDareDevolucao')
BEGIN
	DROP TABLE EST_FECHA_PROC_MOV_RsDareDevolucao
END

GO 
CREATE TABLE EST_FECHA_PROC_MOV_RsDareDevolucao (CD_EMP				Tinyint,
													CD_FILIAL		INT,
													CD_NF_SAI		INT,
													CD_PROD			INT,
													VLR_DEV_DARE	MONEY,
												 CONSTRAINT [PK_EST_FECHA_PROC_MOV_RsDareDevolucao] 
														PRIMARY KEY CLUSTERED (CD_NF_SAI, CD_PROD, CD_FILIAL, CD_EMP) )
GO
/*****************************************************************************************************************************/
--Fechamento realizado	
/*****************************************************************************************************************************/

IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME= 'EST_FECHA_PROC_MOV_RsFechaProcMov')
BEGIN
	DROP TABLE EST_FECHA_PROC_MOV_RsFechaProcMov
END

GO 
CREATE TABLE EST_FECHA_PROC_MOV_RsFechaProcMov (CD_EMP			Tinyint,   
												CD_FILIAL		INT,   
												CD_PROD			INT,   
												QT_EST_FINAL			MONEY,   
												VLR_CUSTO_MD_NOVO		MONEY,
												VLR_CUSTO_GER_NOVO		MONEY,
												VLR_SALDO_CUSTO		MONEY,
												QT_FINAL_FLUT		MONEY,
												QT_FINAL_COM		MONEY,
												VLR_AJUSTE			MONEY
												CONSTRAINT [PK_EST_FECHA_PROC_MOV_RsFechaProcMov] 
														PRIMARY KEY CLUSTERED (CD_PROD, CD_FILIAL, CD_EMP))  	
														  
GO 
/*****************************************************************************************************************************/
--Fechamento realizado	
/*****************************************************************************************************************************/

IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME= 'EST_FECHA_PROC_MOV_RsFechaRealizado')
BEGIN
	DROP TABLE EST_FECHA_PROC_MOV_RsFechaRealizado
END

GO 
CREATE TABLE EST_FECHA_PROC_MOV_RsFechaRealizado (CD_EMP			Tinyint,   
													CD_FILIAL		INT,   
													CD_PROD			INT,   
													QT_EST			MONEY,   
													VLR_CUSTO_MD		MONEY,
													VLR_CUSTO			MONEY,
													VLR_CUSTO_GER		MONEY,
													VLR_SALDO_CUSTO		MONEY,
													QT_EST_COM			MONEY,
													QT_EST_FLUT			MONEY
													CONSTRAINT [PK_EST_FECHA_PROC_MOV_RsFechaRealizado] 
																		PRIMARY KEY CLUSTERED (CD_PROD, CD_FILIAL, CD_EMP))  
GO 
/*****************************************************************************************************************************/
--Fechamento final
/*****************************************************************************************************************************/

IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME= 'EST_FECHA_PROC_MOV_RsFecha')
BEGIN
	DROP TABLE EST_FECHA_PROC_MOV_RsFecha
END

GO 
CREATE TABLE EST_FECHA_PROC_MOV_RsFecha (CD_EMP		Tinyint,   
										   CD_FILIAL	INT,   
										   CD_PROD		INT,   
										   QT_INI				MONEY,   
										   QT_INI_CALC			MONEY,   
										   VLR_CUSTO_MD_INI		MONEY,
										   VLR_CUSTO_GER_INI	MONEY,
										   INICIO				Tinyint,
										   QT_EST_ATUAL			MONEY,
										   QT_AJUSTE_MOV		MONEY,
										   VLR_SALDO_CUSTO		MONEY,
										   VLR_CUSTO_AJUSTE		MONEY, 
										   VLR_TABELA			MONEY,
										   QT_INI_COM			MONEY,
										   QT_INI_FLUT			MONEY
					CONSTRAINT [PK_EST_FECHA_PROC_MOV_RsFecha] 
							PRIMARY KEY CLUSTERED (CD_PROD, CD_FILIAL, CD_EMP)) ;
GO 

/*****************************************************************************************************************************/ 
--Ultimo processamento de custo  
/*****************************************************************************************************************************/

IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME= 'EST_FECHA_PROC_MOV_RsUltProc')
BEGIN
	DROP TABLE EST_FECHA_PROC_MOV_RsUltProc
END

GO 
CREATE TABLE EST_FECHA_PROC_MOV_RsUltProc(CD_EMP		Tinyint,   
											CD_FILIAL	INT ,   
											CD_PROD		INT ,  
											DT_PROC		Smalldatetime null
											CONSTRAINT [PK_EST_FECHA_PROC_MOV_RsUltProc] 
							PRIMARY KEY CLUSTERED ( CD_PROD, CD_FILIAL, CD_EMP));   	
	
/*****************************************************************************************************************************/	 
--Ajuste de estoque
/*****************************************************************************************************************************/

IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME= 'EST_FECHA_PROC_MOV_RsAjuste')
BEGIN
	DROP TABLE EST_FECHA_PROC_MOV_RsAjuste
END

GO 
CREATE TABLE EST_FECHA_PROC_MOV_RsAjuste(CD_EMP		Tinyint,   
							CD_FILIAL	INT,   
							CD_PROD		INT,   
							VLR_AJUSTE   MONEY 
							CONSTRAINT [PK_EST_FECHA_PROC_MOV_RsAjuste] 
								PRIMARY KEY CLUSTERED (CD_PROD, CD_FILIAL, CD_EMP));  

/*****************************************************************************************************************************/	 
--Ajuste de estoque implantados na entrada
/*****************************************************************************************************************************/
GO
IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME= 'EST_FECHA_PROC_MOV_RsImpEnt')
BEGIN
	DROP TABLE EST_FECHA_PROC_MOV_RsImpEnt
END

GO 
CREATE TABLE EST_FECHA_PROC_MOV_RsImpEnt(CD_EMP			Tinyint,   
															   CD_FILIAL	INT,   
															   CD_PROD		INT,
															   QT_IMP_ENT	INT,   
															   VLR_IMP_ENT  MONEY
															   CONSTRAINT [PK_EST_FECHA_PROC_MOV_RsImpEnt] 
																PRIMARY KEY CLUSTERED (CD_PROD, CD_FILIAL, CD_EMP) );  
GO

/*****************************************************************************************************************************/	 
--Ajuste de estoque implantados na entrada
/*****************************************************************************************************************************/

GO
IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME= 'EST_FECHA_PROC_MOV_RsEstNF')
BEGIN
	DROP TABLE EST_FECHA_PROC_MOV_RsEstNF
END

GO 
CREATE TABLE EST_FECHA_PROC_MOV_RsEstNF (CD_EMP			Tinyint,   
										   CD_FILIAL	INT,   
										   CD_PROD		INT,
										   QT_EST_ENT	INT,   
										   VLR_EST_TRANSF  MONEY 
										  CONSTRAINT [PK_EST_FECHA_PROC_MOV_RsEstNF] 
											PRIMARY KEY CLUSTERED (CD_PROD, CD_FILIAL, CD_EMP));  
GO
/*****************************************************************************************************************************/	 
--Ajuste de estoque oriundos de ajutes na origem
/*****************************************************************************************************************************/

GO
IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME= 'EST_FECHA_PROC_MOV_RsAjusteTransf')
BEGIN
	DROP TABLE EST_FECHA_PROC_MOV_RsAjusteTransf
END

GO 
CREATE TABLE EST_FECHA_PROC_MOV_RsAjusteTransf(CD_EMP			Tinyint,   
												   CD_FILIAL	INT,   
												   CD_PROD		INT,   
												   VLR_AJUSTE_TRANSF   MONEY 
												CONSTRAINT [PK_EST_FECHA_PROC_MOV_RsAjusteTransf] 
													PRIMARY KEY CLUSTERED (CD_PROD, CD_FILIAL, CD_EMP));  
							   
/*****************************************************************************************************************************/	 
-- Saidas Vendas 
/*****************************************************************************************************************************/

GO
IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME= 'EST_FECHA_PROC_MOV_RsSaidas')
BEGIN
	DROP TABLE EST_FECHA_PROC_MOV_RsSaidas
END

GO 
CREATE TABLE EST_FECHA_PROC_MOV_RsSaidas(CD_EMP			Tinyint,   
										   CD_FILIAL	INT,   
										   CD_PROD		INT,   
										   QT_SAI		MONEY,
										   QT_SAI_VD_COM			MONEY,
										   QT_SAI_VD_FLUT			MONEY 
										   CONSTRAINT [PK_EST_FECHA_PROC_MOV_RsSaidas] 
													PRIMARY KEY CLUSTERED (CD_PROD, CD_FILIAL, CD_EMP));
							     				
/*****************************************************************************************************************************/	 
-- Ajuste balanço
/*****************************************************************************************************************************/

GO
IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME= 'EST_FECHA_PROC_MOV_RsBalanco')
BEGIN
	DROP TABLE EST_FECHA_PROC_MOV_RsBalanco
END

GO 
CREATE TABLE EST_FECHA_PROC_MOV_RsBalanco(CD_EMP		Tinyint,   
										   CD_FILIAL	INT,   
										   CD_PROD		INT,   
										   QT_IMP		MONEY,
										   QT_IMP_COM			MONEY,
										   QT_IMP_FLUT			MONEY
										   CONSTRAINT [PK_EST_FECHA_PROC_MOV_RsBalanco] 
													PRIMARY KEY CLUSTERED (CD_PROD, CD_FILIAL, CD_EMP)) ;  				
go
		
/*****************************************************************************************************************************/
--Saidas Transferencias	
/*****************************************************************************************************************************/

GO
IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME= 'EST_FECHA_PROC_MOV_RsSaiTransf')
BEGIN
	DROP TABLE EST_FECHA_PROC_MOV_RsSaiTransf
END

GO 
CREATE TABLE EST_FECHA_PROC_MOV_RsSaiTransf (CD_EMP		Tinyint,
												CD_FILIAL	INT, 
												CD_PROD			INT,
												QT_SAI_TRANSF	MONEY,
												VLR_SAI_TRANSF	MONEY,
												QT_SAI_TRANSF_COM	MONEY,
												VLR_SAI_TRANSF_COM	MONEY,
												QT_SAI_TRANSF_FLUT	MONEY,
												VLR_SAI_TRANSF_FLUT	MONEY
												CONSTRAINT [PK_EST_FECHA_PROC_MOV_RsSaiTransf] 
													PRIMARY KEY CLUSTERED (CD_PROD, CD_FILIAL, CD_EMP))
go

/*****************************************************************************************************************************/
--Tabela de entrada
/*****************************************************************************************************************************/


GO
IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME= 'EST_FECHA_PROC_MOV_RsEntradas')
BEGIN
	DROP TABLE EST_FECHA_PROC_MOV_RsEntradas
END

GO 
CREATE TABLE EST_FECHA_PROC_MOV_RsEntradas  (CD_EMP		Tinyint,   
											CD_FILIAL	INT,   
											CD_PROD		INT,   
											QT_ENT		MONEY,  
											VLR_ENT		MONEY,
											VLR_DESC_FINAN		MONEY, 
											VLR_ENT_CUSTO_GER	MONEY, 
											VLR_PRC_CUSTO_REAL	MONEY, 
											QT_ENT_COM		MONEY,  
											VLR_ENT_COM		MONEY,
											QT_ENT_FLUT		MONEY,  
											VLR_ENT_FLUT	MONEY
											CONSTRAINT [PK_EST_FECHA_PROC_MOV_RsEntradas] 
													PRIMARY KEY CLUSTERED (CD_PROD, CD_FILIAL, CD_EMP))

/*****************************************************************************************************************************/
--Tabela de entrada notas de saida canceladas  
/*****************************************************************************************************************************/

GO
IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME= 'EST_FECHA_PROC_MOV_RsEntNfSaiCanc')
BEGIN
	DROP TABLE EST_FECHA_PROC_MOV_RsEntNfSaiCanc
END

GO 
CREATE TABLE EST_FECHA_PROC_MOV_RsEntNfSaiCanc (CD_EMP		Tinyint,   
										CD_FILIAL			INT,   
										CD_PROD				INT,   
										QT_ENT				MONEY,  
										VLR_ENT				MONEY,
										VLR_DESC_FINAN		MONEY, 
										VLR_ENT_CUSTO_GER	MONEY, 
										VLR_PRC_CUSTO_REAL	MONEY, 
										QT_ENT_COM		MONEY,  
										VLR_ENT_COM		MONEY,
										QT_ENT_FLUT		MONEY,  
										VLR_ENT_FLUT	MONEY
										CONSTRAINT [PK_EST_FECHA_PROC_MOV_RsEntNfSaiCanc] 
													PRIMARY KEY CLUSTERED (CD_PROD, CD_FILIAL, CD_EMP)) 

/*****************************************************************************************************************************/
--Tabela de entrada requisicao transferencia
/*****************************************************************************************************************************/
	
GO
IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME= 'EST_FECHA_PROC_MOV_RsEntradasRequisicaoTransf')
BEGIN
	DROP TABLE EST_FECHA_PROC_MOV_RsEntradasRequisicaoTransf
END

GO 
CREATE TABLE EST_FECHA_PROC_MOV_RsEntradasRequisicaoTransf (CD_EMP		Tinyint,   
															CD_FILIAL	INT,   
															CD_PROD		INT,   
															QT_ENT		MONEY,  
															VLR_ENT		MONEY,
															VLR_DESC_FINAN		MONEY, 
															VLR_ENT_CUSTO_GER	MONEY, 
															QT_ENT_COM		MONEY,  
															VLR_ENT_COM		MONEY,
															QT_ENT_FLUT		MONEY,  
															VLR_ENT_FLUT	MONEY
															CONSTRAINT [PK_EST_FECHA_PROC_MOV_RsEntradasRequisicaoTransf]
																PRIMARY KEY CLUSTERED (CD_PROD, CD_FILIAL, CD_EMP)) 

/*****************************************************************************************************************************/
--Tabela de entrada excluida
/*****************************************************************************************************************************/

GO
IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME= 'EST_FECHA_PROC_MOV_RsEntExcl')
BEGIN
	DROP TABLE EST_FECHA_PROC_MOV_RsEntExcl
END

GO 
CREATE TABLE EST_FECHA_PROC_MOV_RsEntExcl  (CD_EMP			Tinyint,   
												CD_FILIAL	INT,   
												CD_PROD		INT,   
												QT_ENT		MONEY,  
												VLR_ENT		MONEY,
												VLR_DESC_FINAN		MONEY, 
												VLR_ENT_CUSTO_GER	MONEY, 
												VLR_PRC_CUSTO_REAL	MONEY,
												QT_ENT_COM		MONEY,  
												VLR_ENT_COM		MONEY,
												QT_ENT_FLUT		MONEY,  
												VLR_ENT_FLUT	MONEY
												CONSTRAINT [PK_EST_FECHA_PROC_MOV_RsEntExcl] 
																PRIMARY KEY CLUSTERED (CD_PROD,  CD_FILIAL, CD_EMP));
					
/*****************************************************************************************************************************/
	--Devolucoes	
/*****************************************************************************************************************************/
	
GO
IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME= 'EST_FECHA_PROC_MOV_RsDevolucoes')
BEGIN
	DROP TABLE EST_FECHA_PROC_MOV_RsDevolucoes
END

GO 
CREATE TABLE EST_FECHA_PROC_MOV_RsDevolucoes(CD_EMP		Tinyint,   
								CD_FILIAL	INT,   
								CD_PROD		INT,   
								QT_DEV      MONEY,  
								VLR_DEV		MONEY,
								VLR_DEV_GER MONEY,
								QT_DEV_COM      MONEY,  
								VLR_DEV_COM		MONEY,
								QT_DEV_FLUT     MONEY,  
								VLR_DEV_FLUT	MONEY
								CONSTRAINT [PK_EST_FECHA_PROC_MOV_RsDevolucoes] 
									PRIMARY KEY CLUSTERED (CD_PROD, CD_FILIAL, CD_EMP));
	
/*****************************************************************************************************************************/
	--Estorno - Notas excluidas
/*****************************************************************************************************************************/

GO
IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME= 'EST_FECHA_PROC_MOV_RsDevEst')
BEGIN
	DROP TABLE EST_FECHA_PROC_MOV_RsDevEst
END

GO 
CREATE TABLE EST_FECHA_PROC_MOV_RsDevEst(CD_EMP			Tinyint,   
											CD_FILIAL	INT,   
											CD_PROD		INT,   
											QT_EST      MONEY,  
											VLR_EST		MONEY,
											VLR_EST_GER MONEY,
											QT_EST_COM      MONEY,  
											VLR_EST_COM		MONEY,
											QT_EST_FLUT     MONEY,  
											VLR_EST_FLUT	MONEY
											CONSTRAINT [PK_EST_FECHA_PROC_MOV_RsDevEst] 
													PRIMARY KEY CLUSTERED (CD_PROD, CD_FILIAL, CD_EMP));
								
/*****************************************************************************************************************************/
-- Tabela de resultados
/*****************************************************************************************************************************/	

GO
IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME= 'EST_FECHA_PROC_MOV_RsResultado')
BEGIN
	DROP TABLE EST_FECHA_PROC_MOV_RsResultado
END

GO 
CREATE TABLE EST_FECHA_PROC_MOV_RsResultado (CD_EMP			Tinyint,  
								CD_FILIAL		INT,  
								DT_PROC			SmallDatetime,  
								CD_PROD			INT,  
								QT_INI				MONEY,  
								VLR_CUSTO_MD_INI	MONEY,  
								QT_ENT				MONEY,  
								VLR_ENT			MONEY,  
								QT_SAI			MONEY,   
								QT_IMP			MONEY,  
								QT_EST_FINAL	MONEY,  
								VLR_CUSTO_MEDIO_NOVO		MONEY,
								VLR_DESC_FINAN				MONEY,
								VLR_ENT_CUSTO_GER			MONEY,
								VLR_CUSTO_GERENCIAL_INI		MONEY,
								VLR_CUSTO_GERENCIAL_NOVO	MONEY,
								QT_AJUSTE_MOV				MONEY,
								VLR_SALDO_CUSTO				MONEY,
								VLR_AJUSTE_CUSTO			MONEY,
								QT_SAI_VD					MONEY,
								VLR_TABELA					MONEY,
								VLR_AJUSTE_TRANSF			MONEY,
								QT_IMP_ENT					MONEY,
								VLR_IMP_ENT					MONEY,
								VLR_EST_TRANSF				MONEY,
								QT_SAI_TRANSF				MONEY,
								VLR_SAI_TRANSF				MONEY,
								
								QT_INI_COM					MONEY,  
								QT_ENT_COM					MONEY,  
								VLR_ENT_COM					MONEY,  
								QT_SAI_COM					MONEY,   
								QT_IMP_COM					MONEY,  
								QT_EST_FINAL_COM			MONEY,    
								QT_SAI_VD_COM				MONEY,
							 	QT_SAI_TRANSF_COM			MONEY,
								VLR_SAI_TRANSF_COM			MONEY,
								 
								QT_INI_FLUT					MONEY,  
								QT_ENT_FLUT					MONEY,  
								VLR_ENT_FLUT				MONEY,  
								QT_SAI_FLUT					MONEY,   
								QT_IMP_FLUT					MONEY,  
								QT_EST_FINAL_FLUT			MONEY,    
								QT_SAI_VD_FLUT				MONEY,
							 	QT_SAI_TRANSF_FLUT			MONEY,
								VLR_SAI_TRANSF_FLUT			MONEY
								CONSTRAINT [PK_EST_FECHA_PROC_MOV_RsResultado] 
									PRIMARY KEY CLUSTERED (CD_PROD, DT_PROC, CD_FILIAL, CD_EMP)); 

/*****************************************************************************************************************************************************************/
/*****************************************************************************************************************************************************************/
/*****************************************************************************************************************************************************************/

	
	CREATE NONCLUSTERED			INDEX IX_RsProdutos_Emp		ON EST_FECHA_PROC_MOV_RsProdutos ([CD_EMP],[CD_FILIAL])INCLUDE ([CD_PROD]);
	CREATE UNIQUE NONCLUSTERED	INDEX IX_RsProdutos_Prod	ON EST_FECHA_PROC_MOV_RsProdutos ([CD_EMP],[CD_FILIAL],[CD_PROD]);
	CREATE NONCLUSTERED			INDEX IX_RsUltProcCdFilial	ON EST_FECHA_PROC_MOV_RsUltProc  (CD_FILIAL,CD_EMP) INCLUDE (CD_PROD,DT_PROC);										
	 
	GO
	CREATE NONCLUSTERED INDEX IX_EST_FECHA_PROC_MOV_RsFecha_CD_EMP_CD_FILIAL ON [dbo].[EST_FECHA_PROC_MOV_RsFecha] ([CD_EMP],[CD_FILIAL])
		INCLUDE ([CD_PROD],[QT_INI],[QT_INI_CALC],[VLR_CUSTO_MD_INI],
					[VLR_CUSTO_GER_INI],[QT_AJUSTE_MOV],[VLR_TABELA],[QT_INI_COM],[QT_INI_FLUT])
	GO
	GO
	CREATE NONCLUSTERED INDEX IX_EST_FECHA_PROC_MOV_RsEntradas_CD_EMP_CD_FILIAL ON [dbo].[EST_FECHA_PROC_MOV_RsEntradas] ([CD_EMP],[CD_FILIAL])
	INCLUDE ([CD_PROD],[QT_ENT],[VLR_ENT],[VLR_DESC_FINAN],[VLR_ENT_CUSTO_GER],
				[VLR_PRC_CUSTO_REAL],[QT_ENT_COM],[VLR_ENT_COM],[QT_ENT_FLUT],[VLR_ENT_FLUT])
	GO 

/*****************************************************************************************************************************************************************/
/*****************************************************************************************************************************************************************/

go
/****** Object:  StoredProcedure [dbo].[P_EST_FECHA_PROC_MOV]    Script Date: 02/11/2014 18:34:05 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[P_EST_FECHA_PROC_MOV]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[P_EST_FECHA_PROC_MOV]
GO
GO 

GO

/*

=======================================================================================
'Job.................: Itec - Manutencao custo medio
'Função..............: 
'Objetivo............: Calcular o custo do produto 
'Tabelas.............: EST_FECHA | EST_FECHA_PROC_MOV
'Dt Modificação......: 20/05/2021
'Modificação.........: Tag #A001 - Ao atualiza a informa nas tabelas de relatorios, foi adicionado o CD_EMP no where.
					   Tag #I001 - 
'=======================================================================================
Tag #A001 - Alteração do codigo  
Tag #I001 - Inclusão de novo codigo 

*/
 
CREATE PROCEDURE [dbo].[P_EST_FECHA_PROC_MOV] (@CD_EMP			int,   
												 @CD_FILIAL		int,   
												 @DT_BASE		datetime,
												 @FORCA_FECHA_ESTOQUE int=0,
												 @CD_PROD		INT=0,
												 @ATU_CPL		int=0,
												 @IGNORA_ATU	int=0,
												 @Debug			Tinyint=0) 
	--WITH RECOMPILE,			ENCRYPTION 
		AS  
BEGIN  

SET NOCOUNT ON  
SET DEADLOCK_PRIORITY HIGH;
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
SET CONTEXT_INFO 0x66666;


if @Debug=1
begin
	PRINT	'****** Inicio - P_EST_FECHA_PROC_MOV ******' + CONVERT(VARCHAR(8), GETDATE(), 108);
end

DECLARE @ANO INT, @MES INT; 
DECLARE @ANO_CUSTO INT, @MES_CUSTO INT;   
DECLARE @DT_INI_FILIAL  AS DATETIME
declare @SqlExec varchar(MAx)
DECLARE @NaoUtilizaCustoGerTransf Tinyint=0;
DECLARE @DT_INI_DEL AS DATETIME;
DECLARE @DT_FIM_DEL AS DATETIME;

DECLARE @INICIO				  int,
		@BLQ_REG_INVENT		  int,
		@TP_CUSTO_TRANSF	  int,
		@CUSTO_SAI_INICIO_DIA int,
		@CUSTO_GER_VLR_ORIGEM tinyint,
		@Inicial			  tinyint,
		@AdicionaSubsTribCustoGer tinyint;

if @Debug=1
begin
	print '*'
	print '*'
	print 'Inicio da rotina de calculo de custo - Time : ' + convert(varchar,getdate(),108)				  
	print 'FILIAL ' + convert(varchar, @CD_FILIAL) + ' Dia ' + convert(varchar,@DT_BASE,112)
	print '*'
	print '*'
	print 'Validando o fechamento de estoque  - Time : ' +convert(varchar,getdate(),108) 
end
/*************************************************************************************************************************/
	SET @ANO = YEAR(DATEADD( MONTH,-1,(@DT_BASE)));  
	SET @MES = MONTH(DATEADD( MONTH,-1,(@DT_BASE)));  

	if not exists(select * from prc_filial_est_fecha f
					where
						f.cd_emp = @cd_emp
						and f.cd_filial = @cd_filial
						and f.ano_fecha = @ano
						and f.mes_fecha = @mes)
		begin
			print 'Nao foi possivel encontrar o fechamento estoque realizado - Time : ' +convert(varchar,getdate(),108) 
			print '**********' 
			print '* Abortando a rotina -' +convert(varchar,getdate(),108)
			print '**********' 
			return;
		end;
/*************************************************************************************************************************/
DECLARE @UltDia INT
SET @UltDia=  DATEPART(DAY,DATEADD(MONTH,1,DATEADD(DAY,(DATEPART(DAY, @DT_BASE)-1)*-1,@DT_BASE))-1)
--set  @UltDia=0

SET @BLQ_REG_INVENT =ISNULL((SELECT VALOR FROM PRC_EMP_CONFIG 
								WHERE CD_EMP=1 
									AND CD_CHAVE = 'BLOQ_PROC_CUSTO_REG_INVENTARIO'),0); 


SET @CUSTO_SAI_INICIO_DIA  =ISNULL((SELECT VALOR FROM PRC_EMP_CONFIG 
												WHERE CD_EMP=1 
												AND CD_CHAVE = 'CUSTO_MEDIO_INICIO_DIA_VENDAS'),0);
												
--Verifca se o valor de custo gerencial é calculado pelo valor de custo da filial de origem  - transf.
SET @CUSTO_GER_VLR_ORIGEM =ISNULL((SELECT VALOR FROM PRC_FILIAL_CONFIG 
										WHERE CD_EMP=1 
												AND CD_CHAVE = 'CUSTO_GERENCIAL_VLR_CUSTO_PROD_ORIG'
												AND CD_FILIAL=@CD_FILIAL),0);

SET @AdicionaSubsTribCustoGer =ISNULL((SELECT VALOR FROM PRC_EMP_CONFIG 
										WHERE CD_EMP=1 
												AND CD_CHAVE = 'ADD_SUBS_TRIB_CUSTO_GERENCIAL'
												),0);

Set @NaoUtilizaCustoGerTransf = ISNULL ((SELECT VALOR FROM PRC_EMP_CONFIG WHERE CD_CHAVE = 'NAO_CONTROLA_CUSTO_GERENCIAL_TRANSF'),0)
		
		 
if not @CD_PROD<> 0
BEGIN
	IF @BLQ_REG_INVENT =1 BEGIN
		--Verifica bloqueio contábil 
		IF EXISTS(SELECT  CD_EMP
					FROM 
						EST_PROD_INVENTARIO  
					WHERE
						DT_REF >= @DT_BASE
						AND CD_EMP=@CD_EMP
						AND CD_FILIAL=@CD_FILIAL)
		begin
			print 'Data de processamento com bloqueio. Inventario já registrado para o periodo solicitado. - Time : ' +convert(varchar,getdate(),108);
 			RETURN; 
		end
		
		IF EXISTS(Select 1
				    From CTB_EXP_CTR  Where 
					   CD_EMP =@CD_EMP		  
					   AND CD_FILIAL =@CD_FILIAL
					   AND DT_EXP >=@DT_BASE
					   AND LIBERADO='N' 
					   AND TP_EXP =0)
		  begin
			 print 'Data com exportação fiscal já realizada. - Time : ' +convert(varchar,getdate(),108);
			 RETURN; 
		  end
	END
END

IF EXISTS(SELECT    CD_EMP
			FROM 
				PRC_FILIAL  
			WHERE
				DT_INI_SISTEMA > @DT_BASE
				AND CD_EMP=@CD_EMP
				AND CD_FILIAL=@CD_FILIAL)
begin
	print 'Data de processamento menor que a data de inicio da filial. - Time : ' +convert(varchar,getdate(),108);
 	RETURN; 
end 

SET @TP_CUSTO_TRANSF=ISNULL((SELECT VALOR FROM PRC_EMP_CONFIG 
								WHERE 
									CD_EMP=1 
									AND CD_CHAVE = 'CALCULA_CUSTO_MD_APENAS_TRANSF_DEPOSITO'),0); 
									 

/*****************************************************************************************************************************/
	/*	
	DELETE FROM EST_FECHA_PROC_MOV_RsFilialCD		WHERE CD_EMP=@CD_EMP ;
	DELETE FROM EST_FECHA_PROC_MOV_RsProdutos		WHERE CD_EMP=@CD_EMP AND CD_FILIAL =@CD_FILIAL; 
	DELETE FROM EST_FECHA_PROC_MOV_RsDareDevolucao	WHERE CD_EMP=@CD_EMP AND CD_FILIAL =@CD_FILIAL;
	DELETE FROM EST_FECHA_PROC_MOV_RsFechaProcMov	WHERE CD_EMP=@CD_EMP AND CD_FILIAL =@CD_FILIAL;
	DELETE FROM EST_FECHA_PROC_MOV_RsFechaRealizado WHERE CD_EMP=@CD_EMP AND CD_FILIAL =@CD_FILIAL;
	DELETE FROM EST_FECHA_PROC_MOV_RsFecha			WHERE CD_EMP=@CD_EMP AND CD_FILIAL =@CD_FILIAL;
	DELETE FROM EST_FECHA_PROC_MOV_RsUltProc		WHERE CD_EMP=@CD_EMP AND CD_FILIAL =@CD_FILIAL;
	DELETE FROM EST_FECHA_PROC_MOV_RsAjuste			WHERE CD_EMP=@CD_EMP AND CD_FILIAL =@CD_FILIAL;
	DELETE FROM EST_FECHA_PROC_MOV_RsImpEnt			WHERE CD_EMP=@CD_EMP AND CD_FILIAL =@CD_FILIAL;
	DELETE FROM EST_FECHA_PROC_MOV_RsEstNF			WHERE CD_EMP=@CD_EMP AND CD_FILIAL =@CD_FILIAL;
	DELETE FROM EST_FECHA_PROC_MOV_RsAjusteTransf	WHERE CD_EMP=@CD_EMP AND CD_FILIAL =@CD_FILIAL;
	DELETE FROM EST_FECHA_PROC_MOV_RsSaidas			WHERE CD_EMP=@CD_EMP AND CD_FILIAL =@CD_FILIAL;
	DELETE FROM EST_FECHA_PROC_MOV_RsBalanco		WHERE CD_EMP=@CD_EMP AND CD_FILIAL =@CD_FILIAL;
	DELETE FROM EST_FECHA_PROC_MOV_RsSaiTransf		WHERE CD_EMP=@CD_EMP AND CD_FILIAL =@CD_FILIAL;
	DELETE FROM EST_FECHA_PROC_MOV_RsEntradas		WHERE CD_EMP=@CD_EMP AND CD_FILIAL =@CD_FILIAL;
	DELETE FROM EST_FECHA_PROC_MOV_RsEntNfSaiCanc	WHERE CD_EMP=@CD_EMP AND CD_FILIAL =@CD_FILIAL;
	DELETE FROM EST_FECHA_PROC_MOV_RsEntradasRequisicaoTransf WHERE CD_EMP=@CD_EMP AND CD_FILIAL =@CD_FILIAL;
	DELETE FROM EST_FECHA_PROC_MOV_RsDevEst			WHERE CD_EMP=@CD_EMP AND CD_FILIAL =@CD_FILIAL;
	DELETE FROM EST_FECHA_PROC_MOV_RsDevolucoes		WHERE CD_EMP=@CD_EMP AND CD_FILIAL =@CD_FILIAL;
	DELETE FROM EST_FECHA_PROC_MOV_RsResultado		WHERE CD_EMP=@CD_EMP AND CD_FILIAL =@CD_FILIAL;
	*/

	truncate table EST_FECHA_PROC_MOV_RsFilialCD		;
	truncate table EST_FECHA_PROC_MOV_RsProdutos		; 
	truncate table EST_FECHA_PROC_MOV_RsDareDevolucao	;
	truncate table EST_FECHA_PROC_MOV_RsFechaProcMov	;
	truncate table EST_FECHA_PROC_MOV_RsFechaRealizado ;
	truncate table EST_FECHA_PROC_MOV_RsFecha			;
	truncate table EST_FECHA_PROC_MOV_RsUltProc		;
	truncate table EST_FECHA_PROC_MOV_RsAjuste			;
	truncate table EST_FECHA_PROC_MOV_RsImpEnt			;
	truncate table EST_FECHA_PROC_MOV_RsEstNF			;
	truncate table EST_FECHA_PROC_MOV_RsAjusteTransf	;
	truncate table EST_FECHA_PROC_MOV_RsSaidas			;
	truncate table EST_FECHA_PROC_MOV_RsBalanco		;
	truncate table EST_FECHA_PROC_MOV_RsSaiTransf		;
	truncate table EST_FECHA_PROC_MOV_RsEntradas		;
	truncate table EST_FECHA_PROC_MOV_RsEntNfSaiCanc	;
	truncate table EST_FECHA_PROC_MOV_RsEntradasRequisicaoTransf;
	truncate table EST_FECHA_PROC_MOV_RsDevEst			;
	truncate table EST_FECHA_PROC_MOV_RsDevolucoes		;
	truncate table EST_FECHA_PROC_MOV_RsResultado		;
	truncate table EST_FECHA_PROC_MOV_RsEntExcl			;
if @Debug=1
begin
	print 'Limpou tabelas auxiliares - Time : ' +convert(varchar,getdate(),108)		
end
/*****************************************************************************************************************************/
-- Carrega os produtos para calculo do custo.
/*****************************************************************************************************************************/	
 	
	DECLARE @NMTBL VARCHAR(100), @CMD VARCHAR(max), @QTDE_PROD int;
	SET @NMTBL = 'EST_FECHA_PROC_MOV_PEND_TBL_PROC_' +CONVERT(VARCHAR,@CD_FILIAL);
	
	IF NOT OBJECT_ID(@NMTBL) IS NULL
		BEGIN

			SET @CMD = 'INSERT INTO EST_FECHA_PROC_MOV_RsProdutos(CD_EMP, CD_FILIAL, CD_PROD, VLR_CUSTO_MD,VLR_CUSTO_GER, DT_PROC, DT_ULT_PROC)
						SELECT 
							DISTINCT CD_EMP, CD_FILIAL, CD_PROD, 0,0, DT_PROC, NULL
						FROM ' + @NMTBL + ' WHERE CD_EMP= ' + convert(varchar,@CD_EMP)
			SET @CMD = @CMD + ' AND CD_FILIAL =' + convert(varchar,@CD_FILIAL)
			SET @CMD = @CMD + ' AND DT_PROC= ''' + convert(varchar, @DT_BASE,112) + '''';

			--PRINT @CMD;
			EXEC (@CMD);
			
			SELECT @QTDE_PROD=ISNULL(COUNT(CD_PROD),'0') 
				FROM EST_FECHA_PROC_MOV_RsProdutos
				where 
					cd_emp=@cd_emp 
					and cd_filial =@cd_filial;
			if @Debug=1
			begin
				print 'Todos os produtos pendentes de geracao de custo da data: ' + convert(varchar,@DT_BASE,112) + ' qtde: ' + convert(varchar, @QTDE_PROD )+ '  - Time : ' + convert(varchar,getdate(),108)		
			end	
		END

	if @cd_prod >0
	begin

		INSERT INTO EST_FECHA_PROC_MOV_RsProdutos(CD_EMP, CD_FILIAL, CD_PROD,VLR_CUSTO_MD, VLR_CUSTO_GER, DT_PROC, DT_ULT_PROC)
		SELECT @CD_EMP, @CD_FILIAL, @CD_PROD,0,0, @DT_BASE,NULL;
		set @QTDE_PROD=1;
	end

	if isnull(@QTDE_PROD,0) =0 
	begin
		print 'Nenhum produto para atualizacao'
		return;
	end
	  

	SET @CMD = 'Update a
	set
		DT_ULT_PROC	= b.DT_ULT_PROC 
	From 
		EST_FECHA_PROC_MOV_RsProdutos a
		CROSS APPLY (SELECT  MAX(DT_PROC) DT_ULT_PROC
					FROM
						EST_FECHA_PROC_MOV  WITH (nolock) 			   
					WHERE 
						CD_PROD		=  a.CD_PROD  AND 
						CD_EMP		=  1 AND
						CD_FILIAL	=  ' + CONVERT(VARCHAR(6), @CD_FILIAL) + ' AND
						DT_PROC		< '''+CONVERT(VARCHAR(12), @DT_BASE, 112)+''') B'
	Exec (@CMD);

	SET @CMD = 'UPDATE a
				  SET
					  VLR_CUSTO_MD = m.VLR_CUSTO_MD_NOVO
					, VLR_CUSTO_GER = m.VLR_CUSTO_GER_NOVO 
				FROM   EST_FECHA_PROC_MOV_RsProdutos a
					   JOIN EST_FECHA_PROC_MOV M ON A.CD_EMP = M.CD_EMP
													AND A.CD_PROD = M.CD_PROD
													AND A.CD_FILIAL = M.CD_FILIAL
													AND a.DT_ULT_PROC = M.DT_PROC
				WHERE
					  A.CD_EMP = 1
					  AND A.CD_FILIAL =  '+CONVERT(VARCHAR(6), @CD_FILIAL); 

    EXECUTE (@cmd)
/*****************************************************************************************************************************/
-- Atualizacao de datas dos itens nas tabelas de movimentacao
/*****************************************************************************************************************************/	
if @Debug=1
begin
	print 'Carregou tabelas auxiliares EST_FECHA_PROC_MOV_RsProdutos - Time : ' +convert(varchar,getdate(),108);
end
	
	DECLARE @DTINICIOMES DATETIME
		  
/*****************************************************************************************************************************/
-- Inicio do processo de exclusao de registros
/*****************************************************************************************************************************/	

	SET @INICIO = 0;
	IF @DT_INI_FILIAL >= @DT_BASE
	BEGIN
		SET @DT_BASE = @DT_INI_FILIAL
		SET @INICIO = 1;	
		SET @FORCA_FECHA_ESTOQUE =1;
		if @Debug=1
		begin
			print 'Alterada a data base para data de inicio da filial - Time : ' +convert(varchar,getdate(),108)
		end	

		DELETE FROM   F
		FROM
			EST_FECHA_PROC_MOV  F
			INNER JOIN EST_FECHA_PROC_MOV_RsProdutos P ON   
			F.CD_EMP	 = P.CD_EMP AND
			F.CD_FILIAL  = P.CD_FILIAL AND
			F.CD_PROD	 = P.CD_PROD
		WHERE   
			F.CD_EMP   = @CD_EMP   
			AND F.CD_FILIAL = @CD_FILIAL  
			AND F.DT_PROC  < @DT_BASE;

		if @Debug=1
		begin
			print 'Excluiu registros anteriores - Time : ' +convert(varchar,getdate(),108)
		end
	END
  
	iF @TP_CUSTO_TRANSF=1 --Carrega as filiais CD
	BEGIN
		INSERT INTO EST_FECHA_PROC_MOV_RsFilialCD
		SELECT 
			CD_EMP,
			CD_FILIAL 
		FROM 
			PRC_FILIAL
		WHERE
			ESPECIE_FILIAL=0
			AND CD_EMP=1 
		UNION SELECT 
			1 CD_EMP,
			CD_FILIAL 
		FROM 
			V_PRC_FILIAL_RELACAO_DEPOSITOS 
	 END
 
 	--Inicio da rotina de exclusao..
	SET @DT_INI_DEL = @DT_BASE;  
	
	--Diminui um dia na data base para usar > ao inves de >=
	SET @DT_BASE = @DT_BASE-1; 
  
	WHILE EXISTS(SELECT  f.CD_EMP  FROM
						EST_FECHA_PROC_MOV F
						INNER JOIN EST_FECHA_PROC_MOV_RsProdutos P ON   
						F.CD_EMP	 = P.CD_EMP AND
						F.CD_FILIAL  = P.CD_FILIAL AND
						F.CD_PROD	 = P.CD_PROD
					WHERE
						f.CD_EMP   = @CD_EMP   
						AND f.CD_FILIAL = @CD_FILIAL  
						AND f.DT_PROC  > @DT_BASE )
	BEGIN
	
		SET @DT_FIM_DEL = dbo.F_FINAL_MES(@DT_INI_DEL);
		if @Debug=1
		begin
			print 'Inicia a exclusao de registros entre ' + convert(varchar,@DT_INI_DEL,112) + '  e  ' + convert(varchar,@DT_FIM_DEL,112)  + '  - Time : ' +convert(varchar,getdate(),108);
		END

		DELETE FROM f FROM
			EST_FECHA_PROC_MOV   f
			INNER JOIN EST_FECHA_PROC_MOV_RsProdutos P ON   
			F.CD_EMP	 = P.CD_EMP AND
			F.CD_FILIAL  = P.CD_FILIAL AND
			F.CD_PROD	 = P.CD_PROD 
		WHERE   
			P.CD_EMP   = @CD_EMP   
			AND F.CD_FILIAL = @CD_FILIAL  
			AND F.DT_PROC  BETWEEN @DT_INI_DEL AND @DT_FIM_DEL;
		if @Debug=1
		begin
			print 'Excluiu registros entre ' + convert(varchar,@DT_INI_DEL,112) + '  e  ' + convert(varchar,@DT_FIM_DEL,112)  + '  - Time : ' +convert(varchar,getdate(),108);
		end

		SET @DT_INI_DEL =(SELECT MIN(F.DT_PROC) 
							FROM 
								EST_FECHA_PROC_MOV   F
								INNER JOIN EST_FECHA_PROC_MOV_RsProdutos P ON   
								F.CD_EMP	 = P.CD_EMP AND
								F.CD_FILIAL  = P.CD_FILIAL AND
								F.CD_PROD	 = P.CD_PROD
							WHERE   
								P.CD_EMP   = @CD_EMP   
								AND F.CD_FILIAL = @CD_FILIAL  
								AND F.DT_PROC  >  @DT_BASE);
		
	END
	 
	--Devolve a data base original;
 	SET @DT_BASE = @DT_BASE + 1;   

	
	 
/*****************************************************************************************************************************/
--	Busca o ultimo processamento de custo
/*****************************************************************************************************************************/	
 	--Funcao de usuario deixa lento - high cpu..
	--SET @DTINICIOMES =  DBO.F_INICIO_MES(@DT_BASE)
	SET @DTINICIOMES =  dateadd(day, (datepart(day,@dt_base)-1)*-1, @dt_base)
	IF @DTINICIOMES <> @DT_BASE AND @INICIO=0
	begin
		SET @FORCA_FECHA_ESTOQUE = 0
	end


	INSERT INTO EST_FECHA_PROC_MOV_RsUltProc  
	SELECT   
		A.CD_EMP,   
		A.CD_FILIAL,   
		A.CD_PROD,   
		MAX(B.DT_PROC) DT_PROC
	FROM   
		EST_FECHA_PROC_MOV_RsProdutos A  
		INNER JOIN  EST_FECHA_PROC_MOV  B ON   
		A.CD_EMP = B.CD_EMP AND   
		A.CD_FILIAL = B.CD_FILIAL AND  
		A.CD_PROD = B.CD_PROD  
	WHERE  
		b.CD_EMP  = @CD_EMP  
		AND b.CD_FILIAL = @CD_FILIAL
		AND B.DT_PROC < @DT_BASE
	GROUP BY   
		A.CD_EMP,   
		A.CD_FILIAL,   
		A.CD_PROD option (recompile);
		   

	INSERT INTO EST_FECHA_PROC_MOV_RsUltProc  
	SELECT   
		A.CD_EMP,   
		A.CD_FILIAL,   
		A.CD_PROD,   
		NULL DT_PROC 
	FROM   
		EST_FECHA_PROC_MOV_RsProdutos A  
		LEFT OUTER JOIN  EST_FECHA_PROC_MOV_RsUltProc  B ON   
		A.CD_EMP = B.CD_EMP AND   
		A.CD_FILIAL = B.CD_FILIAL AND  
		A.CD_PROD = B.CD_PROD  
	WHERE  
		b.cd_emp is null  
		and a.CD_EMP  = @cd_emp  
		AND a.CD_FILIAL = @cd_filial;
	 
	if @Debug=1
	begin
		PRINT 'Carregou produtos sem proc custo EST_FECHA_PROC_MOV_RsUltProc - Time : ' +convert(varchar,getdate(),108)
	end

	IF @FORCA_FECHA_ESTOQUE = 0 
	begin 
		IF NOT EXISTS(SELECT * FROM EST_FECHA_PROC_MOV_RsUltProc WHERE NOT DT_PROC IS NULL)   
		BEGIN    
			 set @FORCA_FECHA_ESTOQUE = 1 
		END
	end   
	 
		 
/*****************************************************************************************************************************/
--	Carrega o fechamento de estoque
/*****************************************************************************************************************************/	

	if @FORCA_FECHA_ESTOQUE = 1 
	begin
		--Tabela de fechamento de estoque
		INSERT INTO EST_FECHA_PROC_MOV_RsFechaRealizado (CD_EMP, CD_FILIAL,  CD_PROD,  QT_EST,   
										VLR_CUSTO_MD, VLR_CUSTO, VLR_CUSTO_GER,
										VLR_SALDO_CUSTO, QT_EST_COM, QT_EST_FLUT)
		SELECT 
			F.CD_EMP,
			F.CD_FILIAL,
			F.CD_PROD,
			F.QT_EST+F.QT_EST_FLUT QT_EST,
			isnull(F.VLR_CUSTO_MD,0)	VLR_CUSTO_MD,
			isnull(F.VLR_CUSTO,0)		VLR_CUSTO,
			isnull(F.VLR_CUSTO_GER,0)	VLR_CUSTO_GER,
			--Nao passa saldo de um mes para o outro...
			0 VLR_SALDO_CUSTO,
			F.QT_EST,
			F.QT_EST_FLUT 
		FROM
			EST_FECHA F
			INNER JOIN EST_FECHA_PROC_MOV_RsProdutos P ON   
			F.CD_EMP	 = P.CD_EMP AND
			F.CD_FILIAL  = P.CD_FILIAL AND
			F.CD_PROD	 = P.CD_PROD
		WHERE
			F.CD_EMP = @CD_EMP
			AND F.CD_FILIAL = @CD_FILIAL
			AND F.ANO_FECHA = @ANO 
			AND F.MES_FECHA = @MES;

 		if @Debug=1
		begin
			print 'Carregou fechamento estoque EST_FECHA_PROC_MOV_RsFechaRealizado ' + convert(varchar,@MES) + convert(varchar,@ANO) +  ' - Time : ' +convert(varchar,getdate(),108) 
		end
	end 

/*****************************************************************************************************************************/

	 insert into EST_FECHA_PROC_MOV_RsFechaProcMov (CD_EMP, CD_FILIAL, CD_PROD, QT_EST_FINAL,
									VLR_CUSTO_MD_NOVO,VLR_CUSTO_GER_NOVO,
									VLR_SALDO_CUSTO,QT_FINAL_FLUT,QT_FINAL_COM, VLR_AJUSTE)
	 SELECT 
		a.CD_EMP, 
		a.CD_FILIAL, 
		a.CD_PROD,
		ISNULL(B.QT_EST_FINAL,0)		QT_EST_FINAL,
		ISNULL(B.VLR_CUSTO_MD_NOVO,0)	VLR_CUSTO_MD_NOVO,
		ISNULL(B.VLR_CUSTO_GER_NOVO,0)	VLR_CUSTO_GER_NOVO,
		ISNULL(B.VLR_SALDO_CUSTO,0)		VLR_SALDO_CUSTO,
		ISNULL(B.QT_FINAL_FLUT,0)		QT_FINAL_FLUT,
		ISNULL(B.QT_FINAL_COM,0)		QT_FINAL_COM,
		ISNULL(B.VLR_AJUSTE,0)		VLR_AJUSTE
	FROM 
		EST_FECHA_PROC_MOV_RsUltProc A
		JOIN EST_FECHA_PROC_MOV B ON  
		a.CD_EMP	= b.CD_EMP AND  
		a.CD_FILIAL = b.CD_FILIAL AND  
		a.CD_PROD	= b.CD_PROD 
		AND a.DT_PROC = b.DT_PROC  ; 
	 
	if @Debug=1
	begin
		PRINT 'Carregou produtos sem proc custo EST_FECHA_PROC_MOV_RsFechaProcMov - Time : ' +convert(varchar,getdate(),108)
	end
/*****************************************************************************************************************************/
--	Monta a base de saldo inicial do custo
/*****************************************************************************************************************************/	
 
	INSERT INTO EST_FECHA_PROC_MOV_RsFecha  (CD_EMP , CD_FILIAL,  CD_PROD, QT_INI,   
						   QT_INI_CALC, VLR_CUSTO_MD_INI,VLR_CUSTO_GER_INI,
						   INICIO, QT_EST_ATUAL, QT_AJUSTE_MOV, VLR_SALDO_CUSTO,
						   VLR_CUSTO_AJUSTE, VLR_TABELA, QT_INI_COM, QT_INI_FLUT)   
	SELECT  
		A.CD_EMP,  
		A.CD_FILIAL,  
		A.CD_PROD,  

		CASE WHEN @FORCA_FECHA_ESTOQUE = 0 THEN
			CASE WHEN A.DT_PROC IS NULL THEN  
				ISNULL(c.QT_EST,0)  + ISNULL(C.QT_EST_FLUT,0)
			ELSE  
				ISNULL(b.QT_EST_FINAL,0) 
			END 
		ELSE
			ISNULL(c.QT_EST,0)+ ISNULL(C.QT_EST_FLUT,0)
		END AS QT_INI,   
	
		CASE WHEN @FORCA_FECHA_ESTOQUE = 0 THEN
			CASE WHEN A.DT_PROC IS NULL THEN  
				ISNULL(c.QT_EST,0)   + ISNULL(C.QT_EST_FLUT,0)
			ELSE  
				ISNULL(b.QT_EST_FINAL,0)
			END 
		ELSE
			ISNULL(c.QT_EST,0)+ ISNULL(C.QT_EST_FLUT,0)
		END  AS QT_INI_CALC,  


		CASE WHEN @FORCA_FECHA_ESTOQUE = 0 THEN
			CASE WHEN A.DT_PROC IS NULL THEN  
				CASE WHEN ISNULL(c.VLR_CUSTO_MD,0) = 0 THEN 
						ISNULL(c.VLR_CUSTO,0)
					ELSE  ISNULL(c.VLR_CUSTO_MD,0) END   -- EST_FECHA  
			ELSE  
				CASE WHEN ISNULL(b.VLR_CUSTO_MD_NOVO,0) = 0 THEN 
						CASE WHEN  ISNULL(c.VLR_CUSTO_MD,0) = 0 THEN 
							ISNULL(c.VLR_CUSTO,0)
						ELSE ISNULL(c.VLR_CUSTO_MD,0) END
					ELSE ISNULL(b.VLR_CUSTO_MD_NOVO,0)  END   
			END 
		ELSE
			CASE WHEN ISNULL(c.VLR_CUSTO_MD,0) = 0 THEN
					ISNULL(c.VLR_CUSTO,0)
				ELSE  ISNULL(c.VLR_CUSTO_MD,0) END
		END AS VLR_CUSTO_MD,  
		 
		CASE WHEN @FORCA_FECHA_ESTOQUE = 0 THEN
			CASE WHEN A.DT_PROC IS NULL THEN  
				case when ISNULL(c.VLR_CUSTO_GER,0) = 0 then
					ISNULL(c.VLR_CUSTO_MD,0)
				else
					ISNULL(c.VLR_CUSTO_GER,0)  
				end
			ELSE  
				CASE WHEN ISNULL(B.VLR_CUSTO_GER_NOVO,0) = 0 THEN
					ISNULL(B.VLR_CUSTO_MD_NOVO,0)
				ELSE
					ISNULL(B.VLR_CUSTO_GER_NOVO,0)
				END
			END
		ELSE 
			isnull( ISNULL(c.VLR_CUSTO_GER, c.VLR_CUSTO_MD),0 ) 
		END AS VLR_CUSTO_GER ,
		
		CASE WHEN @FORCA_FECHA_ESTOQUE = 0 THEN
			CASE WHEN A.DT_PROC IS NULL THEN  
				1
			ELSE  
				0   
			END 
		ELSE
			1
		END AS INICIO,   

		0 QT_EST_ATUAL,
		0 QT_AJUSTE_MOV, 

		(CASE WHEN @FORCA_FECHA_ESTOQUE = 0 THEN
				ISNULL(B.VLR_SALDO_CUSTO,0) 
				ELSE ISNULL(C.VLR_SALDO_CUSTO,0) END)  VLR_SALDO_CUSTO,
		B.VLR_AJUSTE,

		isnull(d.VLR_TABELA,0) VLR_TABELA,

		CASE WHEN @FORCA_FECHA_ESTOQUE = 0 THEN
			CASE WHEN A.DT_PROC IS NULL THEN  
				ISNULL(c.QT_EST,0)  
			ELSE  
				ISNULL(b.QT_FINAL_COM,0) 
			END 
		ELSE
			ISNULL(c.QT_EST,0)
		ENd QT_EST_COM,
		ISNULL(b.QT_FINAL_FLUT,0) QT_EST_FLUT
	FROM  
		EST_FECHA_PROC_MOV_RsUltProc A 
		LEFT OUTER JOIN EST_FECHA_PROC_MOV_RsFechaRealizado C    ON
		A.CD_EMP	= C.CD_EMP AND  
		A.CD_FILIAL = C.CD_FILIAL AND  
		A.CD_PROD	= C.CD_PROD    

		LEFT OUTER JOIN EST_FECHA_PROC_MOV_RsFechaProcMov b ON
		A.CD_EMP	= b.CD_EMP AND  
		A.CD_FILIAL = b.CD_FILIAL AND  
		A.CD_PROD	= b.CD_PROD     

		LEFT JOIN EST_PROD_PRECO D WITH(NOLOCK) ON  
		a.CD_EMP	= D.CD_EMP AND  
		a.CD_FILIAL = D.CD_FILIAL AND  
		a.CD_PROD	= D.CD_PROD 
		AND D.CD_EMP = @CD_EMP  
		AND D.CD_FILIAL = @CD_FILIAL
	WHERE  
		A.CD_EMP = @CD_EMP  
		AND A.CD_FILIAL = @CD_FILIAL ; 
	
	if @Debug=1
	begin  
		print 'Carregou EST_FECHA_PROC_MOV_RsFecha - Time : ' +convert(varchar,getdate(),108)   
	end
	
	
-- Tag #I001
  UPDATE R
		   SET R.VLR_CUSTO_MEDIO_NOVO	  = a.VLR_AJUSTE,
		       R.VLR_CUSTO_GERENCIAL_NOVO = a.VLR_AJUSTE
	FROM  
		EST_FECHA_PROC_MOV_RsResultado r  with(nolock)
	    JOIN EST_FECHA_PROC_MOV_RsAjuste a with(nolock) ON  
		r.CD_EMP	= a.CD_EMP  AND  
		r.CD_FILIAL	= a.CD_FILIAL AND  
		r.CD_PROD	= a.CD_PROD  
   WHERE  
		r.CD_EMP        = @CD_EMP   
		AND r.CD_FILIAL = @CD_FILIAL  
		AND r.DT_PROC   = @DT_BASE	
			 
/*****************************************************************************************************************************/
--	Atualiza o saldo inicial de estoque
/*****************************************************************************************************************************/	
 
	--Se for dia 1 força atualizacao no saldo de estoque atual do produto
	IF datepart(day,@DT_BASE)=1
	BEGIN 
		--Pega estoque inicial...
		update a
		set 
			a.QT_EST_ATUAL		= isnull(f.QT_EST,0) + isnull(f.QT_EST_FLUT,0), 
			a.VLR_CUSTO_MD_INI 	= isnull(f.VLR_CUSTO_MD,0),
			a.VLR_SALDO_CUSTO 	= 0, -- Nao passa saldo de um mes p outro.
			a.QT_INI_COM		= isnull(f.QT_EST,0) ,
			a.QT_INI_FLUT		= isnull(f.QT_EST_FLUT,0)
		from
			EST_FECHA_PROC_MOV_RsFecha a
			INNER JOIN EST_FECHA F ON  
			A.CD_EMP	= F.CD_EMP AND
			A.CD_FILIAL = F.CD_FILIAL AND
			A.CD_PROD	= F.CD_PROD 
		WHERE
			f.CD_EMP=@CD_EMP
			AND f.CD_FILIAL  =@CD_FILIAL 
			AND f.ANO_FECHA  =DATEPART(YEAR, @DT_BASE-1)
			AND f.MES_FECHA  =DATEPART(MONTH, @DT_BASE-1);
			 
		UPDATE F
		SET
			QT_INI = F.QT_EST_ATUAL,
			QT_INI_CALC = F.QT_EST_ATUAL,
			QT_AJUSTE_MOV = QT_INI - F.QT_EST_ATUAL
		FROM EST_FECHA_PROC_MOV_RsFecha F
		WHERE
			F.QT_EST_ATUAL <> F.QT_INI 
			and f.CD_EMP = @CD_EMP   
			AND f.CD_FILIAL= @CD_FILIAL   ;

		if @Debug=1
		begin
			print 'Atualizou saldo de estoque EST_FECHA_PROC_MOV_RsFecha - Time : ' +convert(varchar,getdate(),108)
		end
	END
	 	
/*****************************************************************************************************************************/
-- Carrega as entradas
/*****************************************************************************************************************************/	
	IF @CUSTO_GER_VLR_ORIGEM=1
	BEGIN
		UPDATE I
		SET
			VLR_CUSTO_PROD_ORIG =S.VLR_CUSTO_PROD_ORIG
		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 = I.DT_ENT   
			JOIN  EST_NF_ENT_EST_NF_SAI_TRANSF T ON  
			E.CD_EMP	= T.CD_EMP AND   
			E.CD_FILIAL = T.CD_FIL_DEST AND   
			E.CD_NF		= T.CD_NF_ENT  
			INNER JOIN (SELECT CD_EMP, CD_FILIAL, CD_NF, CD_PROD, AVG(VLR_CUSTO_PROD_ORIG) VLR_CUSTO_PROD_ORIG FROM	EST_NF_SAI_IT S GROUP BY CD_EMP, CD_FILIAL, CD_NF, CD_PROD ) S ON   
			T.CD_EMP	  = S.CD_EMP AND   
			T.CD_FIL_ORIG = S.CD_FILIAL AND   
			T.CD_NF_SAI	  = S.CD_NF AND	 
			I.CD_PROD	  = S.CD_PROD 
		WHERE       
			I.CD_EMP = @CD_EMP   
			AND I.CD_FILIAL = @CD_FILIAL
			AND I.DT_ENT   = @DT_BASE
			AND E.STS_NF = 0   ;

	END

	INSERT INTO EST_FECHA_PROC_MOV_RsEntradas (CD_EMP, CD_FILIAL, CD_PROD,   QT_ENT,  
								VLR_ENT,VLR_DESC_FINAN, VLR_ENT_CUSTO_GER, 
								VLR_PRC_CUSTO_REAL, QT_ENT_COM,VLR_ENT_COM,
								QT_ENT_FLUT, VLR_ENT_FLUT)
	SELECT       
		E.CD_EMP,   
		E.CD_FILIAL,   
		I.CD_PROD,   
		SUM(I.QT_IT) QT_IT,    
		SUM( 
			(CASE WHEN O.CALC_CUSTO_MEDIO = 1 THEN  
					CASE WHEN @TP_CUSTO_TRANSF=0 THEN
						CASE WHEN O.FLAG_CUSTO_ZERO_ENT = 1 THEN
							0
						ELSE
							CASE WHEN ISNULL(I.VLR_CUSTO_ACERTO,0)=0 THEN
								CASE WHEN ISNULL(dev.CD_NF_ENT,0)> 0 and o.DEST_ORIG = 0 THEN 
										  case when ISNULL(I.VLR_CUSTO_MD,0) > 0 then I.VLR_CUSTO_MD
												else ISNULL(I.VLR_PRC_CUSTO,0) end --Devolucao de vendas  
								ELSE
									ISNULL(I.VLR_PRC_CUSTO,0)
								END
							ELSE
								ISNULL(I.VLR_CUSTO_ACERTO,0) 								
							END
						END
					ELSE --Calcular custo medio apenas transf. do cd
						CASE WHEN O.TP_MOV=10 THEN --Se for transf.
							CASE WHEN ISNULL(I.VLR_CUSTO_ACERTO,0)=0 THEN
								CASE WHEN  not ISNULL(CD.CD_EMP,0)=0  then --Se o Forn. for CD pega o custo no CD no dia da Emissao da NF
									ISNULL(dbo.F_VLR_CUSTO_EST_FECHA_PROC_MOV (E.CD_EMP,E.CD_FORN,I.CD_PROD,E.DT_EMI_NF,0),0) 
								else 
									H.VLR_CUSTO_MD
								end
							ELSE
								ISNULL(I.VLR_CUSTO_ACERTO,0)							
							END
						ELSE --Nao e transferencia.
							CASE WHEN ISNULL(I.VLR_CUSTO_ACERTO,0)=0 THEN
								CASE WHEN ISNULL(dev.CD_NF_ENT,0)> 0 and o.DEST_ORIG = 0 THEN 
									ISNULL(I.VLR_CUSTO_MD,0) --Devolucao de vendas
								ELSE
									ISNULL(I.VLR_PRC_CUSTO,0)
								END
							ELSE
								ISNULL(I.VLR_CUSTO_ACERTO,0)								
							END
						END
					END
				ELSE 
					 H.VLR_CUSTO_MD
				END)  
				
				* I.QT_IT) / SUM(I.QT_IT) VLR_PRC_CUSTO, 
		 
		SUM(ROUND(ISNULL((CASE WHEN ISNULL(E.FLAG_NF_PROD_TOTAL_BRUTO, 0) = 0 THEN 
				(ISNULL(I.VLR_TOT_IT,0) + ISNULL(I.VLR_ICMS_SUBS,0) + ISNULL(I.VLR_IPI,0) + ISNULL(I.VLR_FRETE_IT,0))  
			ELSE 
				(ISNULL(I.VLR_TOT_IT,0) + ISNULL(I.VLR_ICMS_SUBS,0) + ISNULL(I.VLR_IPI,0) + ISNULL(I.VLR_FRETE_IT,0)) - ISNULL( I.VLR_DESC,0)
			END)* (ISNULL(I.PERC_DESC_FINAN,0) / 100.0000),0),2)) / SUM(I.QT_IT) AS VLR_DESC_FINAN_PROD, 
		
		SUM((CASE WHEN ISNULL(O.CALC_CUSTO_MEDIO,0) = 1 THEN 
				CASE WHEN ISNULL(O.FLAG_CUSTO_ZERO_ENT,0) = 1 THEN
						0
					when @CUSTO_GER_VLR_ORIGEM = 1 and ISNULL(I.VLR_CUSTO_PROD_ORIG,0) > 0  then
						CASE WHEN ISNULL(I.VLR_CUSTO_ACERTO,0)=0 THEN
							ISNULL(I.VLR_CUSTO_PROD_ORIG,0) + Case When @AdicionaSubsTribCustoGer=1 then (ISNULL(I.VLR_ICMS_SUBS,0)/I.QT_IT) else 0 end
						ELSE
							ISNULL(I.VLR_CUSTO_ACERTO,0)								
						END
					ELSE
					    --Transferindo o custo gerencial
						CASE WHEN ISNULL(I.VLR_CUSTO_GERENCIAL_TRANSF,0) > 0 THEN
							CASE WHEN ISNULL(I.VLR_CUSTO_ACERTO,0)=0 THEN
								ISNULL(I.VLR_CUSTO_GERENCIAL_TRANSF,0)
							ELSE
								ISNULL(I.VLR_CUSTO_ACERTO,0)								
							END
						ELSE
							(CASE WHEN ISNULL(I.VLR_CUSTO_ACERTO,0)=0 THEN
								CASE WHEN ISNULL(dev.CD_NF_ENT,0)> 0 and o.DEST_ORIG = 0 THEN 
									ISNULL(I.VLR_CUSTO_MD,0) --Devolucao de vendas
								ELSE
									ISNULL(I.VLR_PRC_CUSTO,0)
								END
							ELSE
								ISNULL(I.VLR_CUSTO_ACERTO,0)								
							END ) -
							--Menos o desconto financeiro
							(ISNULL((CASE WHEN ISNULL(E.FLAG_NF_PROD_TOTAL_BRUTO, 0) = 0 THEN 
										(ISNULL(I.VLR_TOT_IT,0) + ISNULL(I.VLR_ICMS_SUBS,0) + ISNULL(I.VLR_IPI,0) + ISNULL(I.VLR_FRETE_IT,0))  
									ELSE 
										(ISNULL(I.VLR_TOT_IT,0) + ISNULL(I.VLR_ICMS_SUBS,0) + ISNULL(I.VLR_IPI,0) + ISNULL(I.VLR_FRETE_IT,0)) - ISNULL( I.VLR_DESC,0)
									END)* (ISNULL(I.PERC_DESC_FINAN,0) / 100.0000),0) / I.QT_IT)							 
						END
					END
				ELSE 
					H.VLR_CUSTO_GER					
				END ) * I.QT_IT)/ SUM(I.QT_IT) 
				AS VLR_CUSTO_GER,		

		SUM( 
			(CASE WHEN O.CALC_CUSTO_MEDIO = 1 THEN  
					CASE WHEN @TP_CUSTO_TRANSF=0 THEN
						CASE WHEN O.FLAG_CUSTO_ZERO_ENT = 1 THEN
							0
						ELSE ISNULL(I.VLR_PRC_CUSTO,0) 
						END
					ELSE --Calcular custo medio apenas transf. do cd
						CASE WHEN O.TP_MOV=10 THEN --Se for transf.
							CASE WHEN  NOT ISNULL(CD.CD_EMP,0)=0  THEN --Se o forn. for cd pega o custo no cd no dia da emissao da nf
								ISNULL(DBO.F_VLR_CUSTO_EST_FECHA_PROC_MOV (E.CD_EMP,E.CD_FORN,I.CD_PROD,E.DT_EMI_NF,0),0) 
							ELSE 
								H.VLR_CUSTO_MD
							END
						ELSE --Nao e transferencia.
							ISNULL(I.VLR_PRC_CUSTO,0)
						END
					END
				ELSE 
					 H.VLR_CUSTO_MD  
				END)  
				* I.QT_IT) / SUM(I.QT_IT) VLR_PRC_CUSTO_REAL ,

		SUM(CASE WHEN O.TP_ESTQ =0 THEN I.QT_IT ELSE 0 END) QT_ENT_COM,    
		SUM(CASE WHEN O.TP_ESTQ =0 THEN
				(CASE WHEN O.CALC_CUSTO_MEDIO = 1 THEN  
						CASE WHEN @TP_CUSTO_TRANSF=0 THEN
							CASE WHEN O.FLAG_CUSTO_ZERO_ENT = 1 THEN
								0
							ELSE
								CASE WHEN ISNULL(I.VLR_CUSTO_ACERTO,0)=0 THEN
									   CASE WHEN ISNULL(dev.CD_NF_ENT,0)> 0 and o.DEST_ORIG = 0 THEN 
										  case when ISNULL(I.VLR_CUSTO_MD,0) > 0 then I.VLR_CUSTO_MD
												else ISNULL(I.VLR_PRC_CUSTO,0) end --Devolucao de vendas
									   ELSE
										   ISNULL(I.VLR_PRC_CUSTO,0)
									   END
								ELSE
									ISNULL(I.VLR_CUSTO_ACERTO,0)								
								END
							END
						ELSE --Calcular custo medio apenas transf. do cd
							CASE WHEN O.TP_MOV=10 THEN --Se for transf.
								CASE WHEN ISNULL(I.VLR_CUSTO_ACERTO,0)=0 THEN
									CASE WHEN  not ISNULL(CD.CD_EMP,0)=0  then --Se o Forn. for CD pega o custo no CD no dia da Emissao da NF
										ISNULL(dbo.F_VLR_CUSTO_EST_FECHA_PROC_MOV (E.CD_EMP,E.CD_FORN,I.CD_PROD,E.DT_EMI_NF,0),0) 
									else 
										H.VLR_CUSTO_MD
									end
								ELSE
									ISNULL(I.VLR_CUSTO_ACERTO,0)							
								END
							ELSE --Nao e transferencia.
								CASE WHEN ISNULL(I.VLR_CUSTO_ACERTO,0)=0 THEN
								    CASE WHEN ISNULL(dev.CD_NF_ENT,0)> 0 and o.DEST_ORIG = 0 THEN 
										  ISNULL(I.VLR_CUSTO_MD,0) --Devolucao de vendas
								    ELSE
										  ISNULL(I.VLR_PRC_CUSTO,0)
								    END
								ELSE
									ISNULL(I.VLR_CUSTO_ACERTO,0)								
								END
							END
						END
					ELSE 
						H.VLR_CUSTO_MD
					END)   
					* I.QT_IT ELSE 0 END )  / SUM(I.QT_IT)    VLR_ENT_COM, 
		SUM(CASE WHEN O.TP_ESTQ =1 THEN I.QT_IT ELSE 0 END) QT_ENT_FLUT,    
		SUM(CASE WHEN O.TP_ESTQ =1 THEN
				(CASE WHEN O.CALC_CUSTO_MEDIO = 1 THEN  
						CASE WHEN @TP_CUSTO_TRANSF=0 THEN
							CASE WHEN O.FLAG_CUSTO_ZERO_ENT = 1 THEN
								0
							ELSE
								CASE WHEN ISNULL(I.VLR_CUSTO_ACERTO,0)=0 THEN
								    CASE WHEN ISNULL(dev.CD_NF_ENT,0)> 0 and o.DEST_ORIG = 0 THEN 
									   ISNULL(I.VLR_CUSTO_MD,0) --Devolucao de vendas
								    ELSE
									   ISNULL(I.VLR_PRC_CUSTO,0)
								    END
								ELSE
									ISNULL(I.VLR_CUSTO_ACERTO,0)								
								END
							END
						ELSE --Calcular custo medio apenas transf. do cd
							CASE WHEN O.TP_MOV=10 THEN --Se for transf.
								CASE WHEN ISNULL(I.VLR_CUSTO_ACERTO,0)=0 THEN
									CASE WHEN  not ISNULL(CD.CD_EMP,0)=0  then --Se o Forn. for CD pega o custo no CD no dia da Emissao da NF
										ISNULL(dbo.F_VLR_CUSTO_EST_FECHA_PROC_MOV (E.CD_EMP,E.CD_FORN,I.CD_PROD,E.DT_EMI_NF,0),0) 
									else 
										H.VLR_CUSTO_MD
									end
								ELSE
									ISNULL(I.VLR_CUSTO_ACERTO,0)							
								END
							ELSE --Nao e transferencia.
								CASE WHEN ISNULL(I.VLR_CUSTO_ACERTO,0)=0 THEN
								    CASE WHEN ISNULL(dev.CD_NF_ENT,0)> 0 and o.DEST_ORIG = 0 THEN 
									    ISNULL(I.VLR_CUSTO_MD,0) --Devolucao de vendas
								    ELSE
									   ISNULL(I.VLR_PRC_CUSTO,0)
								    END
								ELSE
									ISNULL(I.VLR_CUSTO_ACERTO,0)								
								END
							END
						END
					ELSE 
						H.VLR_CUSTO_MD
					END)   
					* I.QT_IT ELSE 0 END )  / SUM(I.QT_IT)   VLR_ENT_FLUT
	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 = I.DT_ENT
		
		INNER JOIN EST_FECHA_PROC_MOV_RsProdutos H ON   
		I.CD_EMP	 = H.CD_EMP AND
		I.CD_FILIAL  = H.CD_FILIAL AND
		I.CD_PROD	 = H.CD_PROD

		INNER JOIN  GLB_MOV_OP O ON   
		E.CD_NT_MOV = O.CD_MOV_OP  
		 
		LEFT JOIN  EST_FECHA_PROC_MOV_RsFilialCD Cd ON --Entradas do CD  
		E.CD_EMP  = cd.CD_EMP AND   
		e.CD_FORN = cd.CD_FILIAL  

		LEFT JOIN  PDV_VD_EST_NF_ENT  p ON  
		E.CD_EMP = P.CD_EMP AND   
		E.CD_FILIAL = P.CD_FILIAL AND   
		E.CD_NF  = P.CD_NF  
		
		LEFT JOIN  EST_NF_SAI_NF_ENT  dev ON  
		E.CD_EMP = dev.CD_EMP AND   
		E.CD_FILIAL = dev.CD_FILIAL AND   
		E.CD_NF  = dev.CD_NF_ENT      
	WHERE       
		I.CD_EMP = @CD_EMP   
		AND I.CD_FILIAL = @CD_FILIAL  
		AND I.DT_ENT = @DT_BASE  
		AND O.ATU_EST = 1    
		AND P.CD_EMP IS NULL  
		AND E.STS_NF = 0   
		AND I.QT_IT > 0   
		AND O.TP_ESTQ IN(0,1)
	GROUP BY  
		E.CD_EMP,   
		E.CD_FILIAL,   
		I.CD_PROD;


	if @Debug=1
	begin
		print 'Carregou EST_FECHA_PROC_MOV_RsEntradas Est. comercial  - Time : ' +convert(varchar,getdate(),108); 
	end
/*****************************************************************************************************************************/
-- Carrega as entradas por requisicao de transferencias
/*****************************************************************************************************************************/	
	INSERT INTO EST_FECHA_PROC_MOV_RsEntradasRequisicaoTransf(CD_EMP,   CD_FILIAL, CD_PROD,   
											QT_ENT,  VLR_ENT,	VLR_DESC_FINAN, VLR_ENT_CUSTO_GER,
											QT_ENT_COM,  VLR_ENT_COM,
											QT_ENT_FLUT, VLR_ENT_FLUT)
	SELECT   
		EST_PROD_IMP.CD_EMP,
		EST_PROD_IMP.CD_FILIAL,        
		EST_PROD_IMP.CD_PROD,
		SUM(EST_PROD_IMP.QT_IMP) AS QT_IMP,   
		AVG(EST_PROD_REQ_TRANSF_LIB_ITENS.VLR_CUSTO) AS VLR_CUSTO,
		0 AS VLR_DESC_FINAN,  
		AVG(EST_PROD_REQ_TRANSF_LIB_ITENS.VLR_CUSTO) AS VLR_ENT_CUSTO_GER,
		SUM(EST_PROD_IMP.QT_IMP) AS QT_ENT_COM,   
		AVG(EST_PROD_REQ_TRANSF_LIB_ITENS.VLR_CUSTO) AS VLR_ENT_COM,
		0 QT_ENT_FLUT, 
		0 VLR_ENT_FLUT 
	FROM   
		EST_PROD_IMP INNER JOIN EST_PROD_REQ_TRANSF_LIB_ITENS_ENT_EST_PROD_IMP ON   
		EST_PROD_IMP.CD_EMP = EST_PROD_REQ_TRANSF_LIB_ITENS_ENT_EST_PROD_IMP.CD_EMP AND   
		EST_PROD_IMP.CD_FILIAL = EST_PROD_REQ_TRANSF_LIB_ITENS_ENT_EST_PROD_IMP.CD_FILIAL_DEST AND   
		EST_PROD_IMP.CD_IMP = EST_PROD_REQ_TRANSF_LIB_ITENS_ENT_EST_PROD_IMP.CD_IMP AND   
		EST_PROD_IMP.CD_PROD = EST_PROD_REQ_TRANSF_LIB_ITENS_ENT_EST_PROD_IMP.CD_PROD  
		INNER JOIN EST_PROD_REQ_TRANSF_LIB_ITENS ON 
		EST_PROD_REQ_TRANSF_LIB_ITENS_ENT_EST_PROD_IMP.CD_EMP  = EST_PROD_REQ_TRANSF_LIB_ITENS.CD_EMP AND
		EST_PROD_REQ_TRANSF_LIB_ITENS_ENT_EST_PROD_IMP.CD_FILIAL_ORIG = EST_PROD_REQ_TRANSF_LIB_ITENS.CD_FILIAL AND
		EST_PROD_REQ_TRANSF_LIB_ITENS_ENT_EST_PROD_IMP.CD_REQ = EST_PROD_REQ_TRANSF_LIB_ITENS.CD_REQ AND
		EST_PROD_REQ_TRANSF_LIB_ITENS_ENT_EST_PROD_IMP.CD_PROD = EST_PROD_REQ_TRANSF_LIB_ITENS.CD_PROD
		INNER JOIN EST_FECHA_PROC_MOV_RsProdutos H ON   
		EST_PROD_IMP.CD_EMP	 = H.CD_EMP AND
		EST_PROD_IMP.CD_FILIAL  = H.CD_FILIAL AND
		EST_PROD_IMP.CD_PROD	 = H.CD_PROD
	WHERE       
		EST_PROD_REQ_TRANSF_LIB_ITENS_ENT_EST_PROD_IMP.CD_EMP = @CD_EMP   
		AND EST_PROD_REQ_TRANSF_LIB_ITENS_ENT_EST_PROD_IMP.CD_FILIAL_DEST = @CD_FILIAL   
		AND EST_PROD_IMP.DT_CAD  = @DT_BASE  
		AND EST_PROD_IMP.TP_EST = 0 
	GROUP BY  
		EST_PROD_IMP.CD_EMP,
		EST_PROD_IMP.CD_FILIAL,        
		EST_PROD_IMP.CD_PROD;  


	--Soma a quantidade de entrada e assume o custo da nota fiscal
	UPDATE
		e
	SET
		e.QT_ENT=e.QT_ENT + r.QT_ENT,
		e.QT_ENT_COM=e.QT_ENT_COM+ r.QT_ENT
	FROM
		EST_FECHA_PROC_MOV_RsEntradasRequisicaoTransf r 
		INNER JOIN EST_FECHA_PROC_MOV_RsEntradas e ON
		r.CD_EMP = e.CD_EMP AND
		r.CD_FILIAL = e.CD_FILIAL AND
		r.CD_PROD = e.CD_PROD 
	where
			R.CD_EMP = @CD_EMP   
		AND r.CD_FILIAL= @CD_FILIAL   ;
	 
	--Insere itens na entrada
	INSERT INTO EST_FECHA_PROC_MOV_RsEntradas(CD_EMP, CD_FILIAL, CD_PROD,   QT_ENT,  
								VLR_ENT,VLR_DESC_FINAN, VLR_ENT_CUSTO_GER, 
								VLR_PRC_CUSTO_REAL, QT_ENT_COM,VLR_ENT_COM,
								QT_ENT_FLUT, VLR_ENT_FLUT)
	SELECT
		r.CD_EMP,   
		r.CD_FILIAL,   
		r.CD_PROD,   
		r.QT_ENT,  
		r.VLR_ENT,
		r.VLR_DESC_FINAN, 
		r.VLR_ENT_CUSTO_GER,
		r.VLR_ENT,
		r.QT_ENT,  
		r.VLR_ENT,
		0 QT_ENT_FLUT,
		0 VLR_ENT_FLUT 
	FROM
		EST_FECHA_PROC_MOV_RsEntradasRequisicaoTransf r 
		LEFT OUTER JOIN EST_FECHA_PROC_MOV_RsEntradas e ON
		r.CD_EMP = e.CD_EMP AND
		r.CD_FILIAL = e.CD_FILIAL AND
		r.CD_PROD = e.CD_PROD 
	WHERE
		e.CD_PROD IS NULL
		and r.CD_EMP = @CD_EMP   
		AND r.CD_FILIAL= @CD_FILIAL   ;

	if @Debug=1
	begin
		print 'Carregou EST_FECHA_PROC_MOV_RsEntradas requisicao transferencia  - Time : ' +convert(varchar,getdate(),108);
	end

	insert into EST_FECHA_PROC_MOV_RsEntExcl (CD_EMP, CD_FILIAL, CD_PROD ,
								QT_ENT,VLR_ENT,
								VLR_DESC_FINAN,VLR_ENT_CUSTO_GER, VLR_PRC_CUSTO_REAL,
								QT_ENT_COM,VLR_ENT_COM,
								QT_ENT_FLUT,VLR_ENT_FLUT)
	SELECT       
		i.CD_EMP,   
		i.CD_FILIAL,   
		I.CD_PROD,   
		SUM(I.QT_IT) QT_IT,    
		SUM( 
			(CASE WHEN O.CALC_CUSTO_MEDIO = 1 THEN  
					CASE WHEN @TP_CUSTO_TRANSF=0 THEN
						CASE WHEN O.FLAG_CUSTO_ZERO_ENT = 1 THEN
							0
						ELSE
							CASE WHEN ISNULL(I.VLR_CUSTO_ACERTO,0)=0 THEN
								ISNULL(I.VLR_PRC_CUSTO,0)
							ELSE
								ISNULL(I.VLR_CUSTO_ACERTO,0)								
							END
						END
					ELSE --Calcular custo medio apenas transf. do cd
						CASE WHEN O.TP_MOV=10 THEN --Se for transf.
							CASE WHEN ISNULL(I.VLR_CUSTO_ACERTO,0)=0 THEN
								CASE WHEN  not ISNULL(CD.CD_EMP,0)=0  then --Se o Forn. for CD pega o custo no CD no dia da Emissao da NF
									ISNULL(dbo.F_VLR_CUSTO_EST_FECHA_PROC_MOV (i.CD_EMP,i.CD_FORN,I.CD_PROD,i.DT_EMI_NF,0),0) 
								else 
									H.VLR_CUSTO_MD
								end
							ELSE
								ISNULL(I.VLR_CUSTO_ACERTO,0)								
							END
						ELSE --Nao e transferencia.
							CASE WHEN ISNULL(I.VLR_CUSTO_ACERTO,0)=0 THEN
								ISNULL(I.VLR_PRC_CUSTO,0)
							ELSE
								ISNULL(I.VLR_CUSTO_ACERTO,0)								
							END
						END
					END
				ELSE 
						H.VLR_CUSTO_MD
				END)  
				
				* I.QT_IT) / SUM(I.QT_IT) VLR_PRC_CUSTO, 
		 
		SUM(ROUND(ISNULL((CASE WHEN 0 = 0 THEN --ISNULL(i.FLAG_NF_PROD_TOTAL_BRUTO, 0)
				(ISNULL(I.VLR_TOT_IT,0) + ISNULL(I.VLR_ICMS_SUBS,0) + ISNULL(I.VLR_IPI,0) + ISNULL(I.VLR_FRETE_IT,0))  
			ELSE 
				(ISNULL(I.VLR_TOT_IT,0) + ISNULL(I.VLR_ICMS_SUBS,0) + ISNULL(I.VLR_IPI,0) + ISNULL(I.VLR_FRETE_IT,0)) - ISNULL( I.VLR_DESC,0)
			END)* (ISNULL(I.PERC_DESC_FINAN,0) / 100.0000),0),2)) / SUM(I.QT_IT) AS VLR_DESC_FINAN_PROD, 
		
		SUM((CASE WHEN ISNULL(O.CALC_CUSTO_MEDIO,0) = 1 THEN 
					CASE WHEN ISNULL(O.FLAG_CUSTO_ZERO_ENT,0) = 1 THEN
						0
					ELSE
						--Transferindo o custo gerencial
						CASE WHEN ISNULL(I.VLR_CUSTO_GERENCIAL_TRANSF,0) > 0 THEN
							CASE WHEN ISNULL(I.VLR_CUSTO_ACERTO,0)=0 THEN
								ISNULL(I.VLR_CUSTO_GERENCIAL_TRANSF,0)
							ELSE
								ISNULL(I.VLR_CUSTO_ACERTO,0)								
							END
						ELSE
							CASE WHEN ISNULL(I.VLR_CUSTO_ACERTO,0)=0 THEN
								ISNULL(I.VLR_PRC_CUSTO,0)
							ELSE
								ISNULL(I.VLR_CUSTO_ACERTO,0)								
							END
						END
					END
				ELSE 
					H.VLR_CUSTO_GER
					END) * I.QT_IT)/ SUM(I.QT_IT) 
		AS VLR_CUSTO_GER,
		
		SUM( 
			(CASE WHEN O.CALC_CUSTO_MEDIO = 1 THEN  
					CASE WHEN @TP_CUSTO_TRANSF=0 THEN
						CASE WHEN O.FLAG_CUSTO_ZERO_ENT = 1 THEN
							0
						ELSE ISNULL(I.VLR_PRC_CUSTO,0) 
						END
					ELSE --Calcular custo medio apenas transf. do cd
						CASE WHEN O.TP_MOV=10 THEN --Se for transf.
							CASE WHEN  NOT ISNULL(CD.CD_EMP,0)=0  THEN --SE O FORN. FOR CD PEGA O CUSTO NO CD NO DIA DA EMISSAO DA NF
								ISNULL(dbo.F_VLR_CUSTO_EST_FECHA_PROC_MOV (i.CD_EMP,i.CD_FORN,i.CD_PROD,i.DT_EMI_NF,0),0) 
							ELSE 
								H.VLR_CUSTO_MD
							END
						ELSE --Nao e transferencia.
							ISNULL(I.VLR_PRC_CUSTO,0)
						END
					END
				ELSE 
					H.VLR_CUSTO_MD 
				END)  
				
				* I.QT_IT) / SUM(I.QT_IT) VLR_PRC_CUSTO_REAL, 

		SUM(case when O.TP_ESTQ =0 then I.QT_IT else 0 end) QT_ENT_COM,    
		SUM(case when O.TP_ESTQ =0 then
			(CASE WHEN O.CALC_CUSTO_MEDIO = 1 THEN  
					CASE WHEN @TP_CUSTO_TRANSF=0 THEN
						CASE WHEN O.FLAG_CUSTO_ZERO_ENT = 1 THEN
							0
						ELSE
							CASE WHEN ISNULL(I.VLR_CUSTO_ACERTO,0)=0 THEN
								ISNULL(I.VLR_PRC_CUSTO,0)
							ELSE
								ISNULL(I.VLR_CUSTO_ACERTO,0)								
							END
						END
					ELSE --Calcular custo medio apenas transf. do cd
						CASE WHEN O.TP_MOV=10 THEN --Se for transf.
							CASE WHEN ISNULL(I.VLR_CUSTO_ACERTO,0)=0 THEN
								CASE WHEN  not ISNULL(CD.CD_EMP,0)=0  then --Se o Forn. for CD pega o custo no CD no dia da Emissao da NF
									ISNULL(dbo.F_VLR_CUSTO_EST_FECHA_PROC_MOV (i.CD_EMP,i.CD_FORN,I.CD_PROD,i.DT_EMI_NF,0),0) 
								else 
									H.VLR_CUSTO_MD
								end
							ELSE
								ISNULL(I.VLR_CUSTO_ACERTO,0)								
							END
						ELSE --Nao e transferencia.
							CASE WHEN ISNULL(I.VLR_CUSTO_ACERTO,0)=0 THEN
								ISNULL(I.VLR_PRC_CUSTO,0)
							ELSE
								ISNULL(I.VLR_CUSTO_ACERTO,0)								
							END
						END
					END
				ELSE 
						H.VLR_CUSTO_MD
				END)  
				
				* I.QT_IT ELSE 0 END) / SUM(I.QT_IT)   VLR_ENT_COM,

		SUM(case when O.TP_ESTQ =1 then I.QT_IT else 0 end) QT_ENT_FLUT,    
		SUM(case when O.TP_ESTQ =1 then
			(CASE WHEN O.CALC_CUSTO_MEDIO = 1 THEN  
					CASE WHEN @TP_CUSTO_TRANSF=0 THEN
						CASE WHEN O.FLAG_CUSTO_ZERO_ENT = 1 THEN
							0
						ELSE
							CASE WHEN ISNULL(I.VLR_CUSTO_ACERTO,0)=0 THEN
								ISNULL(I.VLR_PRC_CUSTO,0)
							ELSE
								ISNULL(I.VLR_CUSTO_ACERTO,0)								
							END
						END
					ELSE --Calcular custo medio apenas transf. do cd
						CASE WHEN O.TP_MOV=10 THEN --Se for transf.
							CASE WHEN ISNULL(I.VLR_CUSTO_ACERTO,0)=0 THEN
								CASE WHEN  not ISNULL(CD.CD_EMP,0)=0  then --Se o Forn. for CD pega o custo no CD no dia da Emissao da NF
									ISNULL(dbo.F_VLR_CUSTO_EST_FECHA_PROC_MOV (i.CD_EMP,i.CD_FORN,I.CD_PROD,i.DT_EMI_NF,0),0) 
								else 
									H.VLR_CUSTO_MD
								end
							ELSE
								ISNULL(I.VLR_CUSTO_ACERTO,0)								
							END
						ELSE --Nao e transferencia.
							CASE WHEN ISNULL(I.VLR_CUSTO_ACERTO,0)=0 THEN
								ISNULL(I.VLR_PRC_CUSTO,0)
							ELSE
								ISNULL(I.VLR_CUSTO_ACERTO,0)								
							END
						END
					END
				ELSE 
						H.VLR_CUSTO_MD 
				END)  
				
				* I.QT_IT ELSE 0 END) / SUM(I.QT_IT) VLR_ENT_FLUT  
	FROM           
		EST_NF_ENT_IT_ESTORNO i
		
		INNER JOIN EST_FECHA_PROC_MOV_RsProdutos H ON   
		I.CD_EMP	 = H.CD_EMP AND
		I.CD_FILIAL  = H.CD_FILIAL AND
		I.CD_PROD	 = H.CD_PROD

		INNER JOIN  GLB_MOV_OP O ON   
		i.CD_MOV_OP = O.CD_MOV_OP  
		 
		LEFT JOIN  EST_FECHA_PROC_MOV_RsFilialCD Cd ON --Entradas do CD  
		i.CD_EMP  = cd.CD_EMP AND   
		i.CD_FORN = cd.CD_FILIAL    
	WHERE       
		i.CD_EMP = @CD_EMP   
		AND i.CD_FILIAL = @CD_FILIAL  
		AND i.DT_ENT = @DT_BASE  
		AND O.ATU_EST = 1   
		AND I.QT_IT > 0   
	GROUP BY  
		i.CD_EMP,   
		i.CD_FILIAL,   
		i.CD_PROD ;
	
	if @Debug=1
	begin
		print 'Carregou EST_FECHA_PROC_MOV_RsEntExcl  - Time : ' +convert(varchar,getdate(),108);
	end

	INSERT INTO EST_FECHA_PROC_MOV_RsEntNfSaiCanc (CD_EMP,CD_FILIAL,CD_PROD, QT_ENT,VLR_ENT,
									VLR_DESC_FINAN,VLR_ENT_CUSTO_GER,VLR_PRC_CUSTO_REAL, 
									QT_ENT_COM, VLR_ENT_COM,QT_ENT_FLUT,VLR_ENT_FLUT)
	SELECT       
		i.CD_EMP,   
		i.CD_FILIAL,   
		I.CD_PROD,   
		SUM(I.QT_IT) QT_IT,    
		SUM( 
			(CASE WHEN O.CALC_CUSTO_MEDIO = 1 THEN  
					CASE WHEN @TP_CUSTO_TRANSF=0 THEN
						CASE WHEN O.FLAG_CUSTO_ZERO_ENT = 1 THEN
							0
						ELSE
							CASE WHEN ISNULL(I.VLR_CUSTO_ACERTO,0)=0 THEN
								ISNULL(I.VLR_CUSTO,0)
							ELSE
								ISNULL(I.VLR_CUSTO_ACERTO,0)								
							END
						END
					ELSE --Calcular custo medio apenas transf. do cd
						CASE WHEN O.TP_MOV=10 THEN --Se for transf.
							CASE WHEN ISNULL(I.VLR_CUSTO_ACERTO,0)=0 THEN
								H.VLR_CUSTO_MD
							ELSE
								ISNULL(I.VLR_CUSTO_ACERTO,0)								
							END
						ELSE --Nao e transferencia.
							CASE WHEN ISNULL(I.VLR_CUSTO_ACERTO,0)=0 THEN
								ISNULL(I.VLR_CUSTO,0)
							ELSE
								ISNULL(I.VLR_CUSTO_ACERTO,0)								
							END
						END
					END
				ELSE 
						H.VLR_CUSTO_MD
				END)  
				* I.QT_IT) / SUM(I.QT_IT) VLR_PRC_CUSTO,  
		0 AS VLR_DESC_FINAN_PROD, 
		
		SUM((CASE WHEN ISNULL(O.CALC_CUSTO_MEDIO,0) = 1 THEN 
					CASE WHEN ISNULL(O.FLAG_CUSTO_ZERO_ENT,0) = 1 THEN
						0
					ELSE
						--Transferindo o custo gerencial
						CASE WHEN ISNULL(I.VLR_CUSTO_GERENCIAL_TRANSF,0) > 0 THEN
							CASE WHEN ISNULL(I.VLR_CUSTO_ACERTO,0)=0 THEN
								ISNULL(I.VLR_CUSTO_GERENCIAL_TRANSF,0)
							ELSE
								ISNULL(I.VLR_CUSTO_ACERTO,0)								
							END
						ELSE
							CASE WHEN ISNULL(I.VLR_CUSTO_ACERTO,0)=0 THEN
								ISNULL(I.VLR_CUSTO,0)
							ELSE
								ISNULL(I.VLR_CUSTO_ACERTO,0)								
							END
						END
					END
				ELSE 
					H.VLR_CUSTO_GER
				END) * I.QT_IT)/ SUM(I.QT_IT) 
		AS VLR_CUSTO_GER,
		SUM( 
			(CASE WHEN O.CALC_CUSTO_MEDIO = 1 THEN  
					CASE WHEN @TP_CUSTO_TRANSF=0 THEN
						CASE WHEN O.FLAG_CUSTO_ZERO_ENT = 1 THEN
							0
						ELSE ISNULL(I.VLR_CUSTO,0) 
						END
					ELSE --Calcular custo medio apenas transf. do cd
						CASE WHEN O.TP_MOV=10 THEN --Se for transf.
							H.VLR_CUSTO_MD
						ELSE --Nao e transferencia.
							ISNULL(I.VLR_CUSTO,0)
						END
					END
				ELSE 
					H.VLR_CUSTO_MD
				END)  
				
				* I.QT_IT) / SUM(I.QT_IT) VLR_PRC_CUSTO_REAL, 
				
		SUM(case when O.TP_ESTQ =0 then I.QT_IT else 0 end) QT_ENT_COM,    
		SUM(case when O.TP_ESTQ =0 then 
			(CASE WHEN O.CALC_CUSTO_MEDIO = 1 THEN  
					CASE WHEN @TP_CUSTO_TRANSF=0 THEN
						CASE WHEN O.FLAG_CUSTO_ZERO_ENT = 1 THEN
							0
						ELSE
							CASE WHEN ISNULL(I.VLR_CUSTO_ACERTO,0)=0 THEN
								ISNULL(I.VLR_CUSTO,0)
							ELSE
								ISNULL(I.VLR_CUSTO_ACERTO,0)								
							END
						END
					ELSE --Calcular custo medio apenas transf. do cd
						CASE WHEN O.TP_MOV=10 THEN --Se for transf.
							CASE WHEN ISNULL(I.VLR_CUSTO_ACERTO,0)=0 THEN
								H.VLR_CUSTO_MD
							ELSE
								ISNULL(I.VLR_CUSTO_ACERTO,0)								
							END
						ELSE --Nao e transferencia.
							CASE WHEN ISNULL(I.VLR_CUSTO_ACERTO,0)=0 THEN
								ISNULL(I.VLR_CUSTO,0)
							ELSE
								ISNULL(I.VLR_CUSTO_ACERTO,0)								
							END
						END
					END
				ELSE 
						H.VLR_CUSTO_MD
				END) * I.QT_IT  ELSE 0 END) / SUM(I.QT_IT)   VLR_ENT_COM,

		SUM(case when O.TP_ESTQ =1 then I.QT_IT else 0 end) QT_ENT_FLUT,    
		SUM(case when O.TP_ESTQ =1 then 
			(CASE WHEN O.CALC_CUSTO_MEDIO = 1 THEN  
					CASE WHEN @TP_CUSTO_TRANSF=0 THEN
						CASE WHEN O.FLAG_CUSTO_ZERO_ENT = 1 THEN
							0
						ELSE
							CASE WHEN ISNULL(I.VLR_CUSTO_ACERTO,0)=0 THEN
								ISNULL(I.VLR_CUSTO,0)
							ELSE
								ISNULL(I.VLR_CUSTO_ACERTO,0)								
							END
						END
					ELSE --Calcular custo medio apenas transf. do cd
						CASE WHEN O.TP_MOV=10 THEN --Se for transf.
							CASE WHEN ISNULL(I.VLR_CUSTO_ACERTO,0)=0 THEN
								H.VLR_CUSTO_MD
							ELSE
								ISNULL(I.VLR_CUSTO_ACERTO,0)								
							END
						ELSE --Nao e transferencia.
							CASE WHEN ISNULL(I.VLR_CUSTO_ACERTO,0)=0 THEN
								ISNULL(I.VLR_CUSTO,0)
							ELSE
								ISNULL(I.VLR_CUSTO_ACERTO,0)								
							END
						END
					END
				ELSE 
						H.VLR_CUSTO_MD 
				END) * I.QT_IT  ELSE 0 END) / SUM(I.QT_IT) VLR_ENT_FLUT  
	FROM           
		EST_NF_SAI_IT i
		INNER JOIN EST_NF_SAI S ON 
		I.CD_EMP	    = S.CD_EMP AND
		I.CD_FILIAL   = S.CD_FILIAL AND
		I.CD_NF	    = S.CD_NF and 
		I.DT_EMI_NF   = S.DT_EMI_NF

		INNER JOIN EST_NF_SAI_CANCEL C ON 
		S.CD_EMP	  =C.CD_EMP AND
		S.CD_FILIAL =C.CD_FILIAL AND
		S.CD_NF	  =C.CD_NF

 		INNER JOIN EST_FECHA_PROC_MOV_RsProdutos H ON   
		I.CD_EMP	 = H.CD_EMP AND
		I.CD_FILIAL  = H.CD_FILIAL AND
		I.CD_PROD	 = H.CD_PROD

		INNER JOIN  GLB_MOV_OP O ON   
		S.CD_NT_MOV = O.CD_MOV_OP   
	WHERE       
		c.CD_EMP = @CD_EMP
		--AND NOT S.STS_NF=0 
		AND c.CD_FILIAL = @CD_FILIAL  
		AND c.DT_CANCEL  = @DT_BASE  
		AND O.BX_EST = 1   
		AND O.TP_ESTQ IN(0,1) 
		AND I.QT_IT > 0   
	GROUP BY  
		i.CD_EMP,   
		i.CD_FILIAL,   
		i.CD_PROD ;



    -- select * from EST_FECHA_PROC_MOV_RsEntradas
	--Junta as entradas com os estornos de nf..
	update e
	set
		QT_ENT				= e.QT_ENT	+ r.QT_ENT,  
		VLR_ENT				= case when (e.QT_ENT + r.QT_ENT) >0 then	    
								    ((e.QT_ENT*e.VLR_ENT) + (r.QT_ENT*r.VLR_ENT)) / (e.QT_ENT	+ r.QT_ENT)
								    else (e.VLR_ENT + r.VLR_ENT)/2.0000  end, 

		  
		VLR_DESC_FINAN		= (e.VLR_DESC_FINAN +  r.VLR_DESC_FINAN) /2.0000, 

		VLR_ENT_CUSTO_GER	= case when (e.QT_ENT + r.QT_ENT) >0 then	    
							 ((e.QT_ENT*e.VLR_ENT_CUSTO_GER) + (r.QT_ENT*r.VLR_ENT_CUSTO_GER)) / (e.QT_ENT	+ r.QT_ENT)
							else  (e.VLR_ENT_CUSTO_GER + r.VLR_ENT_CUSTO_GER) /2.0000 end, 


		QT_ENT_COM		= e.QT_ENT_COM	+ r.QT_ENT_COM,   

		VLR_ENT_COM		= case when (e.QT_ENT_COM	+ r.QT_ENT_COM) > 0 then
							((e.QT_ENT_COM*e.VLR_ENT_COM) + (r.QT_ENT_COM*r.VLR_ENT_COM)) / (e.QT_ENT_COM	+ r.QT_ENT_COM)
							 else (e.VLR_ENT_COM + r.VLR_ENT_COM)/2.0000 end,
							  
		QT_ENT_FLUT		= e.QT_ENT_FLUT	+ r.QT_ENT_FLUT,  
		VLR_ENT_FLUT		= case when (e.QT_ENT_FLUT+ r.QT_ENT_FLUT) > 0 then 
							 ((e.QT_ENT_FLUT*e.VLR_ENT_FLUT) + (r.QT_ENT_FLUT*r.VLR_ENT_FLUT))/(e.QT_ENT_FLUT+ r.QT_ENT_FLUT)
							 else (e.VLR_ENT_FLUT + r.VLR_ENT_FLUT)/2.0000   end
	from
		EST_FECHA_PROC_MOV_RsEntradas e
		inner join EST_FECHA_PROC_MOV_RsEntExcl r on 
		e.CD_EMP	= r.CD_EMP AND   
		e.CD_FILIAL = r.CD_FILIAL AND   
		e.CD_PROD	= r.CD_PROD  ;
		 

	if @Debug=1
	begin	
		print 'Atualiza EST_FECHA_PROC_MOV_RsEntradas  - Time : ' +convert(varchar,getdate(),108);
	end

	INSERT INTO EST_FECHA_PROC_MOV_RsEntradas (CD_EMP, CD_FILIAL, CD_PROD,   QT_ENT,  
								VLR_ENT,VLR_DESC_FINAN, VLR_ENT_CUSTO_GER, 
								VLR_PRC_CUSTO_REAL, QT_ENT_COM,VLR_ENT_COM,
								QT_ENT_FLUT, VLR_ENT_FLUT)
	SELECT
		e.CD_EMP, 
		e.CD_FILIAL, 
		e.CD_PROD,   
		e.QT_ENT,  
		e.VLR_ENT,
		e.VLR_DESC_FINAN, 
		e.VLR_ENT_CUSTO_GER, 
		e.VLR_PRC_CUSTO_REAL, 
		e.QT_ENT_COM,
		e.VLR_ENT_COM,
		e.QT_ENT_FLUT, 
		e.VLR_ENT_FLUT
	FROM
		EST_FECHA_PROC_MOV_RsEntExcl E
		LEFT JOIN EST_FECHA_PROC_MOV_RsEntradas EN ON 
		E.CD_EMP	= EN.CD_EMP AND   
		E.CD_FILIAL = EN.CD_FILIAL AND   
		E.CD_PROD	= EN.CD_PROD 
	WHERE 
		EN.CD_EMP IS NULL ;
	  
 
	--Junta as entradas com os cancelamentos de nf..
	update e
	set
		QT_ENT				= e.QT_ENT	+ r.QT_ENT,  
		VLR_ENT				= case when (e.QT_ENT + r.QT_ENT) >0 then	    
								    ((e.QT_ENT*e.VLR_ENT) + (r.QT_ENT*r.VLR_ENT)) / (e.QT_ENT	+ r.QT_ENT)
								    else (e.VLR_ENT + r.VLR_ENT)/2.0000  end, 

		  
		VLR_DESC_FINAN		= (e.VLR_DESC_FINAN +  r.VLR_DESC_FINAN) /2.0000, 

		VLR_ENT_CUSTO_GER	= case when (e.QT_ENT + r.QT_ENT) >0 then	    
							 ((e.QT_ENT*e.VLR_ENT_CUSTO_GER) + (r.QT_ENT*r.VLR_ENT_CUSTO_GER)) / (e.QT_ENT	+ r.QT_ENT)
							else  (e.VLR_ENT_CUSTO_GER + r.VLR_ENT_CUSTO_GER) /2.0000 end, 


		QT_ENT_COM		= e.QT_ENT_COM	+ r.QT_ENT_COM,   

		VLR_ENT_COM		= case when (e.QT_ENT_COM	+ r.QT_ENT_COM) > 0 then
							((e.QT_ENT_COM*e.VLR_ENT_COM) + (r.QT_ENT_COM*r.VLR_ENT_COM)) / (e.QT_ENT_COM	+ r.QT_ENT_COM)
							 else (e.VLR_ENT_COM + r.VLR_ENT_COM)/2.0000 end,
							  
		QT_ENT_FLUT		= e.QT_ENT_FLUT	+ r.QT_ENT_FLUT,  
		VLR_ENT_FLUT		= case when (e.QT_ENT_FLUT+ r.QT_ENT_FLUT) > 0 then 
							 ((e.QT_ENT_FLUT*e.VLR_ENT_FLUT) + (r.QT_ENT_FLUT*r.VLR_ENT_FLUT))/(e.QT_ENT_FLUT+ r.QT_ENT_FLUT)
							 else (e.VLR_ENT_FLUT + r.VLR_ENT_FLUT)/2.0000   end
	from
		EST_FECHA_PROC_MOV_RsEntradas e
		inner join EST_FECHA_PROC_MOV_RsEntNfSaiCanc r on 
		e.CD_EMP	= r.CD_EMP AND   
		e.CD_FILIAL = r.CD_FILIAL AND   
		e.CD_PROD	= r.CD_PROD ;  
		
	--   select * from EST_FECHA_PROC_MOV_RsEntradas
	INSERT INTO EST_FECHA_PROC_MOV_RsEntradas (CD_EMP, CD_FILIAL, CD_PROD,   QT_ENT,  
								VLR_ENT,VLR_DESC_FINAN, VLR_ENT_CUSTO_GER, 
								VLR_PRC_CUSTO_REAL, QT_ENT_COM,VLR_ENT_COM,
								QT_ENT_FLUT, VLR_ENT_FLUT)
	SELECT
		e.CD_EMP, 
		e.CD_FILIAL, 
		e.CD_PROD,   
		e.QT_ENT,  
		e.VLR_ENT,
		e.VLR_DESC_FINAN, 
		e.VLR_ENT_CUSTO_GER, 
		e.VLR_PRC_CUSTO_REAL, 
		e.QT_ENT_COM,
		e.VLR_ENT_COM,
		e.QT_ENT_FLUT, 
		e.VLR_ENT_FLUT
	FROM
		EST_FECHA_PROC_MOV_RsEntNfSaiCanc E
		LEFT JOIN EST_FECHA_PROC_MOV_RsEntradas EN ON 
		e.CD_EMP	= EN.CD_EMP AND   
		e.CD_FILIAL = EN.CD_FILIAL AND   
		e.CD_PROD	= EN.CD_PROD  
	WHERE EN.CD_EMP IS NULL  ;
  
	if @Debug=1
	begin	
		print 'Carregou EST_FECHA_PROC_MOV_RsEntradas  - Time : ' +convert(varchar,getdate(),108);
	end
	
/**************************************************************************************************************************/
-- Saidas Transferencias
/**************************************************************************************************************************/
     
	set @SqlExec = 'INSERT INTO EST_FECHA_PROC_MOV_RsSaiTransf(CD_EMP, CD_FILIAL , CD_PROD,
								QT_SAI_TRANSF, VLR_SAI_TRANSF , 
								QT_SAI_TRANSF_COM , VLR_SAI_TRANSF_COM,
								QT_SAI_TRANSF_FLUT, VLR_SAI_TRANSF_FLUT)
	SELECT      
		S.CD_EMP,   
		S.CD_FILIAL,   
		I.CD_PROD,    
		SUM(I.QT_IT) as QT_SAI_TRANSF,
		(SUM(I.QT_IT * (CASE WHEN O.CALC_CUSTO_MEDIO =0 THEN 
								H.VLR_CUSTO_MD
							ELSE i.VLR_CUSTO END)) /SUM(I.QT_IT) )  as VLR_SAI_TRANSF , 

		SUM(case when O.TP_ESTQ=0 then I.QT_IT else 0 end) as QT_SAI_TRANSF_COM,		
		SUM(case when O.TP_ESTQ=0 then I.QT_IT ELSE 0 END * (CASE WHEN O.CALC_CUSTO_MEDIO =0 THEN 
													 H.VLR_CUSTO_MD
													 ELSE i.VLR_CUSTO END)) /SUM(I.QT_IT) as VLR_SAI_TRANSF_COM ,
		SUM(case when O.TP_ESTQ=1 then I.QT_IT else 0 end) as QT_SAI_TRANSF_FLUT,
		SUM(case when O.TP_ESTQ=1 then I.QT_IT ELSE 0 END * (CASE WHEN O.CALC_CUSTO_MEDIO =0 THEN 
													  H.VLR_CUSTO_MD
													   ELSE i.VLR_CUSTO END)) /SUM(I.QT_IT) as VLR_SAI_TRANSF_FLUT  
	FROM           
		EST_NF_SAI S  with(nolock)
		INNER JOIN  GLB_MOV_OP O ON   
		S.CD_NT_MOV = O.CD_MOV_OP  
		INNER JOIN  EST_NF_SAI_IT I with(nolock) 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  = I.DT_EMI_NF
		
		INNER JOIN EST_FECHA_PROC_MOV_RsProdutos h with(nolock)  ON   
		I.CD_EMP	 = H.CD_EMP AND
		I.CD_FILIAL  = H.CD_FILIAL AND
		I.CD_PROD	 = H.CD_PROD 
	WHERE     
		i.CD_EMP = ' + convert(varchar, @CD_EMP ) + ' AND i.CD_FILIAL =' +  convert(varchar, @CD_FILIAL ) 
		+ ' AND i.DT_EMI_NF = ''' + convert(varchar, @DT_BASE ,112) 
		+ ''' AND O.BX_EST = 1   
		AND O.TP_ESTQ IN (0,1)  AND I.QT_IT > 0   AND	O.DEST_ORIG = 2
		AND	O.TP_TRANSA = 0
	GROUP BY
		S.CD_EMP,   
		S.CD_FILIAL,   
		I.CD_PROD;' 
		  
	exec(@SqlExec);

	--select * from EST_FECHA_PROC_MOV_RsSaiTransf
	if @Debug=1
	begin	
		print 'Carregou EST_FECHA_PROC_MOV_RsSaiTransf - Time : ' +convert(varchar,getdate(),108);
	end

/*************************************************************************************************************************/
 -- Ajustes Custo Medio Inicial
/*************************************************************************************************************************/
	INSERT INTO EST_FECHA_PROC_MOV_RsBalanco (CD_EMP, CD_FILIAL , CD_PROD	,   
							   QT_IMP, QT_IMP_COM , QT_IMP_FLUT)
	SELECT       
		I.CD_EMP,   
		I.CD_FILIAL,   
		I.CD_PROD,  
		ISNULL(SUM(I.QT_IMP),0) AS QT_IMP ,
		SUM(CASE WHEN I.TP_EST =0 THEN I.QT_IMP ELSE 0 END) QT_IMP_COM,
		SUM(CASE WHEN I.TP_EST =1 THEN I.QT_IMP ELSE 0 END) QT_IMP_FLUT 
	FROM           
		EST_PROD_IMP I  
		INNER JOIN EST_FECHA_PROC_MOV_RsProdutos H ON   
		I.CD_EMP	 = H.CD_EMP AND
		I.CD_FILIAL  = H.CD_FILIAL AND
		I.CD_PROD	 = H.CD_PROD
	WHERE       
		I.CD_EMP = @CD_EMP   
		AND I.TP_EST IN (0,1)   
		AND I.CD_FILIAL = @CD_FILIAL  
		AND I.DT_CAD = @DT_BASE  
		AND NOT EXISTS(SELECT
							CD_PROD
					   FROM
							EST_PROD_REQ_TRANSF_LIB_ITENS_ENT_EST_PROD_IMP
						WHERE
							I.CD_EMP	= EST_PROD_REQ_TRANSF_LIB_ITENS_ENT_EST_PROD_IMP.CD_EMP AND   
							I.CD_FILIAL = EST_PROD_REQ_TRANSF_LIB_ITENS_ENT_EST_PROD_IMP.CD_FILIAL_DEST AND   
							I.CD_IMP	= EST_PROD_REQ_TRANSF_LIB_ITENS_ENT_EST_PROD_IMP.CD_IMP AND   
							I.CD_PROD	= EST_PROD_REQ_TRANSF_LIB_ITENS_ENT_EST_PROD_IMP.CD_PROD )	 
	GROUP BY   
		I.CD_PROD,   
		I.CD_EMP,   
		I.CD_FILIAL ;


	if @Debug=1
	begin	 
		print 'Carregou EST_FECHA_PROC_MOV_RsBalanco - Time : ' +convert(varchar,getdate(),108); 
	end
	
  
/*****************************************************************************************************************************/
-- Carrega os ajustes no custo
/*****************************************************************************************************************************/	

	INSERT INTO EST_FECHA_PROC_MOV_RsAjuste (CD_EMP,  CD_FILIAL,CD_PROD,VLR_AJUSTE)
	SELECT
		A.CD_EMP,
		A.CD_FILIAL,
		A.CD_PROD,
		ISNULL(A.VLR_CUSTO_ACERTO,0) 
	FROM 
		EST_PROD_CPL_ACERTO_CUSTO A  
		INNER JOIN EST_FECHA_PROC_MOV_RsProdutos P ON   
		A.CD_EMP	 = P.CD_EMP AND
		A.CD_FILIAL  = P.CD_FILIAL AND
		A.CD_PROD	 = P.CD_PROD
	WHERE       
		A.CD_EMP = @CD_EMP   
		AND A.CD_FILIAL = @CD_FILIAL  
		AND A.DT_MOV = @DT_BASE
		AND A.TP_AJUSTE =0; 

	INSERT INTO EST_FECHA_PROC_MOV_RsAjuste (CD_EMP,  CD_FILIAL,CD_PROD,VLR_AJUSTE)
	SELECT
		A.CD_EMP,
		A.CD_FILIAL,
		A.CD_PROD,
		ISNULL(A.VLR_CUSTO_ACERTO,0) 
	FROM 
		EST_PROD_CPL_ACERTO_CUSTO A  
		INNER JOIN EST_FECHA_PROC_MOV_RsProdutos P ON   
		A.CD_EMP	 = P.CD_EMP AND
		A.CD_FILIAL  = P.CD_FILIAL AND
		A.CD_PROD	 = P.CD_PROD
	WHERE       
		A.CD_EMP = @CD_EMP   
		AND A.CD_FILIAL = @CD_FILIAL  
		AND A.DT_MOV = @DT_BASE
		AND A.TP_AJUSTE =5; 

	if @Debug=1
	begin 
		print 'Carregou EST_FECHA_PROC_MOV_RsAjuste  - Time : ' +convert(varchar,getdate(),108);
	end

	INSERT INTO EST_FECHA_PROC_MOV_RsImpEnt (CD_EMP,  CD_FILIAL, CD_PROD,
							   QT_IMP_ENT,VLR_IMP_ENT)
	SELECT
		A.CD_EMP,
		A.CD_FILIAL,
		A.CD_PROD,
		ISNULL(A.QT_AJUSTE,0) QT_IMP_ENT,
		ISNULL(A.VLR_CUSTO_ACERTO,0) VLR_IMP_ENT 
	FROM 
		EST_PROD_CPL_ACERTO_CUSTO A  
		INNER JOIN EST_FECHA_PROC_MOV_RsProdutos P ON   
		A.CD_EMP	 = P.CD_EMP AND
		A.CD_FILIAL  = P.CD_FILIAL AND
		A.CD_PROD	 = P.CD_PROD
	WHERE       
		A.CD_EMP = @CD_EMP   
		AND A.CD_FILIAL = @CD_FILIAL  
		AND A.DT_MOV = @DT_BASE
		AND A.TP_AJUSTE = 1 ;
		 
	if @Debug=1
	begin 
		print 'Carregou EST_FECHA_PROC_MOV_RsImpEnt  - Time : ' +convert(varchar,getdate(),108); 
	end

	INSERT INTO EST_FECHA_PROC_MOV_RsEstNF (CD_EMP, CD_FILIAL, CD_PROD,
							   QT_EST_ENT, VLR_EST_TRANSF)
	SELECT
		A.CD_EMP,
		A.CD_FILIAL,
		A.CD_PROD,
		ISNULL(A.QT_AJUSTE,0) QT_IMP_ENT,
		ISNULL(A.VLR_CUSTO_ACERTO,0) VLR_IMP_ENT 
	FROM 
		EST_PROD_CPL_ACERTO_CUSTO A  
		INNER JOIN EST_FECHA_PROC_MOV_RsProdutos P ON   
		A.CD_EMP	 = P.CD_EMP AND
		A.CD_FILIAL  = P.CD_FILIAL AND
		A.CD_PROD	 = P.CD_PROD
	WHERE       
		A.CD_EMP = @CD_EMP   
		AND A.CD_FILIAL = @CD_FILIAL  
		AND A.DT_MOV = @DT_BASE
		AND A.TP_AJUSTE= 2 ;
	
	if @Debug=1
	begin 
		print 'Carregou EST_FECHA_PROC_MOV_RsImpEnt  - Time : ' +convert(varchar,getdate(),108); 
	end
	   
/**************************************************************************************************************************/
-- Vendas - Saidas a Custo Medio
/**************************************************************************************************************************/
	INSERT INTO EST_FECHA_PROC_MOV_RsSaidas(CD_EMP, CD_FILIAL, CD_PROD,   
						QT_SAI,QT_SAI_VD_COM,QT_SAI_VD_FLUT)
	SELECT 
		CD_EMP,  
		CD_FILIAL,  
		CD_PROD,   
		SUM(QT_SAI) QT_SAI,
		SUM(case when TP_EST=0 then QT_SAI else 0 end) QT_SAI,
		SUM(case when TP_EST=1 then QT_SAI else 0 end) QT_SAI_FLUT 
	FROM( SELECT  
				V.CD_EMP,  
				V.CD_FILIAL,  
				I.CD_PROD,   
				I.QT_IT AS QT_SAI,
				0 TP_EST
			FROM  
				PDV_VD V   with(nolock)
				INNER JOIN  PDV_VD_IT I  with(nolock) 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  = I.DT_VD   
				INNER JOIN EST_FECHA_PROC_MOV_RsProdutos P with(nolock) ON   
				i.CD_EMP	 = P.CD_EMP AND
				i.CD_FILIAL  = P.CD_FILIAL AND
				i.CD_PROD	 = P.CD_PROD 
			WHERE  
				V.CD_EMP = @CD_EMP  
				AND I.DT_VD =@DT_BASE  
				AND V.CD_FILIAL = @CD_FILIAL  
				AND V.ST_VD = 0  
				AND I.ST_IT = 1   
			UNION ALL 
			SELECT      
				S.CD_EMP,   
				S.CD_FILIAL,   
				I.CD_PROD,   
				I.QT_IT AS QT_SAI ,
				O.TP_ESTQ	 
			FROM           
				EST_NF_SAI S  with(nolock)
				INNER JOIN  GLB_MOV_OP O ON   
				S.CD_NT_MOV = O.CD_MOV_OP  
				INNER JOIN  EST_NF_SAI_IT I with(nolock) 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  = I.DT_EMI_NF
				
				INNER JOIN EST_FECHA_PROC_MOV_RsProdutos P ON   
				i.CD_EMP	 = P.CD_EMP AND
				i.CD_FILIAL  = P.CD_FILIAL AND
				i.CD_PROD	 = P.CD_PROD
			WHERE     
				S.CD_EMP = @CD_EMP       
				AND S.CD_FILIAL = @CD_FILIAL  
				AND i.DT_EMI_NF = @DT_BASE  
				AND O.BX_EST	= 1  
				AND O.TP_ESTQ	IN(0,1)  
				--AND S.STS_NF	= 0     --Notas canceladas abatendo na est_nf_Sai_canc
				AND	NOT O.TP_MOV in(11) -- Nao fazer tipo 11 -> Implementado nas devolucoes....
				AND O.DEST_ORIG <> 2 --Nao trazer trasnf
				 ) TblSai
	group by 
		CD_EMP,  
		CD_FILIAL,  
		CD_PROD;
	
	if @Debug=1
	begin 
		print 'Carregou EST_FECHA_PROC_MOV_RsSaidas - Time : ' +convert(varchar,getdate(),108); 
	end
	 
/*************************************************************************************************************************/
 --  Custo Devolucao 
/*************************************************************************************************************************/
  
  	INSERT INTO EST_FECHA_PROC_MOV_RsDareDevolucao(CD_EMP,CD_FILIAL,CD_NF_SAI,CD_PROD,VLR_DEV_DARE )
	SELECT  
		NFSAI.CD_EMP,
		NFSAI.CD_FILIAL, 
		NFSAI.CD_NF,
		NFSAI.CD_PROD,  
		SUM(
			(( 
				((NFSAI.QT_IT * NFSAI.VLR_IT) - NFSAI.VLR_DESC_IT) +
				((NFSAI.QT_IT * NFSAI.VLR_IT) - NFSAI.VLR_DESC_IT) * 
				(NFSAI.PERC_IPI /  100.00)
				) / NFSAI.QT_IT
				) + (ISNULL(DARE.VLR_ICMS_SUBS,0) /DARE.QT_IT)
				- (ISNULL(DARE.VLR_PIS_COFINS,0) /DARE.QT_IT)   
			)VLR_DEV_DARE 
	FROM 
		V_EST_NF_ENT_IT_DAR_GERADO DARE with(nolock)
		INNER JOIN EST_NF_ENT_NF_SAI ES with(nolock) 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 NFSAI ON
		ES.CD_EMP	 = NFSAI.CD_EMP AND
		ES.CD_FILIAL = NFSAI.CD_FILIAL AND
		ES.CD_NF_SAI = NFSAI.CD_NF AND 
		DARE.CD_PROD = NFSAI.CD_PROD
						
		INNER JOIN EST_FECHA_PROC_MOV_RsProdutos P ON   
		NFSAI.CD_EMP	 = P.CD_EMP AND
		NFSAI.CD_FILIAL  = P.CD_FILIAL AND
		NFSAI.CD_PROD	 = P.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		
	WHERE
		ES.CD_EMP = @CD_EMP 
		AND ES.CD_FILIAL = @CD_FILIAL
		AND nfsai.DT_EMI_NF = @DT_BASE 
		and DARE.QT_IT> 0
		and NFSAI.QT_IT >0
		AND O.BX_EST = 1  
		AND O.TP_ESTQ in (0,1)  
		AND O.DEST_ORIG <> 2 --Nao transferencia
	GROUP BY 	
			NFSAI.CD_EMP,
			NFSAI.CD_FILIAL, 
			NFSAI.CD_NF,
			NFSAI.CD_PROD   ;  
		 
	if @Debug=1
	begin 
		print 'Carregou DARE de devolucao  - Time : ' +convert(varchar,getdate(),108);
	end 

	INSERT INTO EST_FECHA_PROC_MOV_RsDevolucoes  (CD_EMP,  CD_FILIAL,  CD_PROD,   
								QT_DEV, VLR_DEV,VLR_DEV_GER,
								QT_DEV_COM, VLR_DEV_COM,
								QT_DEV_FLUT, VLR_DEV_FLUT)
	SELECT       
		S.CD_EMP,   
		S.CD_FILIAL,   
		I.CD_PROD,   
		SUM(I.QT_IT) QT_DEV,    
		SUM((CASE WHEN O.CALC_CUSTO_MEDIO = 1 THEN 
						CASE WHEN O.FLAG_CUSTO_ZERO_ENT = 1 THEN
							0
						ELSE
							isnull(darDev.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
									)
						END
					ELSE
						case when f.VLR_CUSTO_MD_INI =0 or f.QT_INI=0 then ei.VLR_PRC_CUSTO
							else f.VLR_CUSTO_MD_INI  end
					END) * I.QT_IT) / SUM(I.QT_IT) VLR_DEV, 

		(SUM( (CASE WHEN O.CALC_CUSTO_MEDIO = 1 THEN 
						CASE WHEN O.FLAG_CUSTO_ZERO_ENT = 1 THEN
							0
						ELSE
							W.VLR_CUSTO_GER
						END
					ELSE
						W.VLR_CUSTO_GER
					END) * I.QT_IT) / SUM(I.QT_IT))  VLR_DEV_GER,
		 
		SUM(CASE WHEN O.TP_ESTQ=0 THEN I.QT_IT ELSE 0 END) QT_DEV,    
		SUM(CASE WHEN O.TP_ESTQ=0 THEN
				(CASE WHEN O.CALC_CUSTO_MEDIO = 1 THEN 
						CASE WHEN O.FLAG_CUSTO_ZERO_ENT = 1 THEN
							0
						ELSE
							isnull(darDev.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
									)
						END
					ELSE
						case when f.VLR_CUSTO_MD_INI =0 OR F.QT_INI =0 then ei.VLR_PRC_CUSTO
							else f.VLR_CUSTO_MD_INI  end
					END) * I.QT_IT ELSE 0 END ) / SUM(I.QT_IT)  VLR_DEV_COM, 
		
		SUM(CASE WHEN O.TP_ESTQ=1 THEN I.QT_IT ELSE 0 END) QT_DEV_FLUT ,    
		SUM(CASE WHEN O.TP_ESTQ=1 THEN
				(CASE WHEN O.CALC_CUSTO_MEDIO = 1 THEN 
						CASE WHEN O.FLAG_CUSTO_ZERO_ENT = 1 THEN
							0
						ELSE
							isnull(darDev.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
									)
						END
					ELSE
						--Se o custo inicial for zero pega o custo da entrada
						case when f.VLR_CUSTO_MD_INI =0 or f.QT_INI=0 then ei.VLR_PRC_CUSTO
							else f.VLR_CUSTO_MD_INI  end
					END) * I.QT_IT ELSE 0 END ) / SUM(I.QT_IT) AS VLR_DEV_FLUT

	FROM           
		EST_NF_SAI S  with(nolock)
		INNER JOIN  EST_NF_SAI_IT I with(nolock) 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	= I.DT_EMI_NF 
		
		LEFT JOIN (select top 1 CD_EMP as cd_emp ,
				    CD_FILIAL as cd_filial,
				    CD_NF_ENT as cd_nf_ent,
				    CD_NF_SAI as cd_nf_sai
				 from EST_NF_ENT_NF_SAI   ) ES ON
		S.CD_EMP		= ES.CD_EMP AND
		S.CD_FILIAL		= ES.CD_FILIAL AND
		S.CD_NF			= ES.CD_NF_SAI  


		LEFT JOIN (SELECT 
						A.CD_EMP,
						A.CD_FILIAL,
						A.CD_NF_RELACIONADA CD_NF
					FROM 
						EST_NF_SAI_EST_NF_SAI A with(nolock)
						INNER JOIN EST_NF_SAI B with(nolock) 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
						) r  ON
		S.CD_EMP		= r.CD_EMP AND
		S.CD_FILIAL		= r.CD_FILIAL AND
		S.CD_NF			= r.CD_NF  

		LEFT JOIN  EST_NF_ENT_IT EI with(nolock) ON   
		ES.CD_EMP	 = EI.CD_EMP AND   
		ES.CD_FILIAL = EI.CD_FILIAL AND   
		ES.CD_NF_ENT = EI.CD_NF    
		AND I.CD_PROD  = EI.CD_PROD

		INNER JOIN EST_FECHA_PROC_MOV_RsProdutos w ON   
		i.CD_EMP	 = w.CD_EMP AND
		i.CD_FILIAL  = w.CD_FILIAL AND
		i.CD_PROD	 = w.CD_PROD

		INNER JOIN EST_TRIB ON
		I.CD_TRIB = EST_TRIB.CD_TRIB
		
		INNER JOIN  GLB_MOV_OP O ON   
		S.CD_NT_MOV = O.CD_MOV_OP  

		INNER JOIN EST_FECHA_PROC_MOV_RsFecha F ON 
		w.CD_EMP	    = F.CD_EMP	  AND
		w.CD_FILIAL   = F.CD_FILIAL AND
		w.CD_PROD	    = F.CD_PROD	   

		LEFT JOIN  PDV_VD_EST_NF_SAI  p with(nolock) ON  
		S.CD_EMP	= P.CD_EMP AND   
		S.CD_FILIAL = P.CD_FILIAL AND   
		S.CD_NF		= P.CD_NF  

		LEFT OUTER JOIN EST_FECHA_PROC_MOV_RsDareDevolucao darDev ON
		I.CD_EMP	    = darDev.CD_EMP AND   
		I.CD_FILIAL   = darDev.CD_FILIAL AND   
		I.CD_NF	    = darDev.CD_NF_SAI  AND
		I.CD_PROD	    = darDev.CD_PROD 
	WHERE       
		I.CD_EMP = @CD_EMP   
		AND I.CD_FILIAL = @CD_FILIAL  
		AND i.DT_EMI_NF = @DT_BASE  
		AND O.BX_EST	= 1   
		AND O.TP_ESTQ	in (0,1)
		AND	O.TP_MOV	= 11
		AND O.TP_MOV_OP_TRANSA= 1
   		AND P.CD_EMP IS NULL  
		AND S.STS_NF = 0   
		AND I.QT_IT > 0   
	GROUP BY  
		S.CD_EMP,   
		S.CD_FILIAL,   
		I.CD_PROD;

	--select * from EST_FECHA_PROC_MOV_RsDevolucoes
	if @Debug=1
	begin 
		print 'Carregou EST_FECHA_PROC_MOV_RsDevolucoes  - Time : ' +convert(varchar,getdate(),108);
	end

	INSERT INTO EST_FECHA_PROC_MOV_RsDevEst(CD_EMP, CD_FILIAL, CD_PROD ,
							QT_EST, VLR_EST, VLR_EST_GER,
							QT_EST_COM,	VLR_EST_COM,
							QT_EST_FLUT, VLR_EST_FLUT)
	SELECT       
		I.CD_EMP,   
		I.CD_FILIAL,   
		I.CD_PROD,   
		SUM(I.QT_IT) QT_DEV,    
		SUM((CASE WHEN O.CALC_CUSTO_MEDIO = 1 THEN 
						CASE WHEN O.FLAG_CUSTO_ZERO_ENT = 1 THEN
							0
						ELSE
							i.VLR_PRC_CUSTO
						END
					ELSE
						f.VLR_CUSTO_MD_INI
					END) * I.QT_IT) / SUM(I.QT_IT) VLR_DEV, 
		(SUM( (CASE WHEN O.CALC_CUSTO_MEDIO = 1 THEN 
						CASE WHEN O.FLAG_CUSTO_ZERO_ENT = 1 THEN
							0
						ELSE
							H.VLR_CUSTO_GER
						END
					ELSE
						H.VLR_CUSTO_GER
					END) * I.QT_IT) / SUM(I.QT_IT))  VLR_DEV_GER,
		
		SUM(case when O.TP_ESTQ =0 then I.QT_IT else 0 end) QT_DEV_COM,  
		SUM(Case when O.TP_ESTQ =0 then 
				(CASE WHEN O.CALC_CUSTO_MEDIO = 1 THEN 
						CASE WHEN O.FLAG_CUSTO_ZERO_ENT = 1 THEN
							0
						ELSE
							i.VLR_PRC_CUSTO
						END
					ELSE
						f.VLR_CUSTO_MD_INI
					END) * I.QT_IT ELSE 0 END) / SUM(I.QT_IT)  VLR_DEV_COM,
		SUM(case when O.TP_ESTQ =1 then I.QT_IT else 0 end) QT_DEV_FLUT, 
		SUM(Case when O.TP_ESTQ =1 then 
				(CASE WHEN O.CALC_CUSTO_MEDIO = 1 THEN 
						CASE WHEN O.FLAG_CUSTO_ZERO_ENT = 1 THEN
							0
						ELSE
							i.VLR_PRC_CUSTO
						END
					ELSE
						f.VLR_CUSTO_MD_INI
					END) * I.QT_IT ELSE 0 END) / SUM(I.QT_IT) VLR_DEV_FLUT
	FROM           
		 
		EST_NF_ENT_IT_ESTORNO i with(nolock)
		
		INNER JOIN EST_FECHA_PROC_MOV_RsProdutos H ON   
		I.CD_EMP	 = H.CD_EMP AND
		I.CD_FILIAL  = H.CD_FILIAL AND
		I.CD_PROD	 = H.CD_PROD
		
		INNER JOIN  GLB_MOV_OP O ON   
		i.CD_MOV_OP = O.CD_MOV_OP  

		INNER JOIN EST_FECHA_PROC_MOV_RsFecha F with(nolock) ON 
		I.CD_EMP	= F.CD_EMP	  AND
		I.CD_FILIAL = F.CD_FILIAL AND
		I.CD_PROD	= F.CD_PROD
				 
		LEFT JOIN  EST_FECHA_PROC_MOV_RsFilialCD Cd ON --Entradas do CD  
		i.CD_EMP  = cd.CD_EMP AND   
		i.CD_FORN = cd.CD_FILIAL    
	WHERE       
		i.CD_EMP = @CD_EMP   
		AND i.CD_FILIAL = @CD_FILIAL  
		AND CONVERT(DATE,i.DT_CAD)= @DT_BASE  
		AND O.ATU_EST = 1   
		AND O.TP_ESTQ IN (0,1)    
		AND I.QT_IT > 0   
	GROUP BY  
		i.CD_EMP,   
		i.CD_FILIAL,   
		i.CD_PROD ;		 
	 
	--Adiciona as notas estornadas/excluidas
	update d
	set
		QT_DEV		= QT_DEV + QT_EST,  
		VLR_DEV		= (VLR_DEV + VLR_EST) /2.0000,
		VLR_DEV_GER	= (VLR_DEV_GER +VLR_EST_GER) /2.0000,
		QT_DEV_COM	= QT_DEV_COM+ QT_EST_COM,
		VLR_DEV_COM	= (VLR_DEV_COM+ VLR_EST_COM) /2.0000,
		QT_DEV_FLUT	= QT_DEV_FLUT+ QT_EST_FLUT, 
		VLR_DEV_FLUT= (VLR_DEV_FLUT+ VLR_EST_FLUT) /2.0000
	from
		EST_FECHA_PROC_MOV_RsDevolucoes D
		INNER JOIN  EST_FECHA_PROC_MOV_RsDevEst e on
		d.CD_EMP	 = e.CD_EMP AND
		d.CD_FILIAL  = e.CD_FILIAL AND
		d.CD_PROD	 = e.CD_PROD  ;


	if @Debug=1
	begin  
		print 'Atualiza EST_FECHA_PROC_MOV_RsDevEst  - Time : ' +convert(varchar,getdate(),108);
	end

	insert into EST_FECHA_PROC_MOV_RsDevolucoes 	(CD_EMP	, CD_FILIAL, CD_PROD,	  
								QT_DEV, VLR_DEV, VLR_DEV_GER,
								QT_DEV_COM ,  VLR_DEV_COM,
								QT_DEV_FLUT  ,  VLR_DEV_FLUT)
	select 
		d.CD_EMP,
		d.CD_FILIAL,	
		d.CD_PROD,	
		d.QT_EST,	
		d.VLR_EST,	
		d.VLR_EST_GER,	
		d.QT_EST_COM,
		d.VLR_EST_COM,
		d.QT_EST_FLUT, 
		d.VLR_EST_FLUT
	from
		EST_FECHA_PROC_MOV_RsDevEst D
		LEFT JOIN  EST_FECHA_PROC_MOV_RsDevolucoes e on
		d.CD_EMP	 = e.CD_EMP AND
		d.CD_FILIAL  = e.CD_FILIAL AND
		d.CD_PROD	 = e.CD_PROD  
	where   e.cd_emp is null  ;  


	if @Debug=1
	begin 
		print 'Carregou EST_FECHA_PROC_MOV_RsDevEst  - Time : ' +convert(varchar,getdate(),108);
	end
/*****************************************************************************************************************************/
-- resultado parcial
/*****************************************************************************************************************************/	
	IF @CUSTO_SAI_INICIO_DIA=1
	BEGIN
		
		if @Debug=1
		begin 
			print 'Saida pelo custo inicial- Time : ' +convert(varchar,getdate(),108);
		end

		UPDATE F
		SET 
			F.QT_INI_CALC=QT_INI-(ISNULL(s.QT_SAI,0) + ISNULL(r.QT_SAI_TRANSF,0))

		FROM EST_FECHA_PROC_MOV_RsFecha F	 
			LEFT join EST_FECHA_PROC_MOV_RsSaidas s on
			f.CD_EMP	= s.CD_EMP AND   
			f.CD_FILIAL = s.CD_FILIAL AND   
			f.CD_PROD	= s.CD_PROD   
			left join EST_FECHA_PROC_MOV_RsSaiTransf r on
			f.CD_EMP	= r.CD_EMP AND   
			f.CD_FILIAL = r.CD_FILIAL AND   
			f.CD_PROD	= r.CD_PROD  
		WHERE 
			F.QT_INI_CALC<>0
			and f.CD_EMP = @CD_EMP   
			AND f.CD_FILIAL = @CD_FILIAL  
	END

	if @Debug=1
	begin 
		print 'Monta resultado parcial  - Time : ' +convert(varchar,getdate(),108);
	end

	INSERT INTO EST_FECHA_PROC_MOV_RsResultado  (CD_EMP,CD_FILIAL,DT_PROC, CD_PROD,
									QT_INI, VLR_CUSTO_MD_INI,QT_ENT,VLR_ENT,QT_SAI,QT_IMP,QT_EST_FINAL,VLR_CUSTO_MEDIO_NOVO,
									VLR_DESC_FINAN,VLR_ENT_CUSTO_GER,VLR_CUSTO_GERENCIAL_INI,VLR_CUSTO_GERENCIAL_NOVO,
									QT_AJUSTE_MOV,VLR_SALDO_CUSTO,VLR_AJUSTE_CUSTO,QT_SAI_VD,VLR_TABELA,VLR_AJUSTE_TRANSF,
									QT_IMP_ENT,VLR_IMP_ENT,VLR_EST_TRANSF,QT_SAI_TRANSF,VLR_SAI_TRANSF,
									QT_INI_COM,QT_ENT_COM,VLR_ENT_COM,QT_SAI_COM,QT_IMP_COM,QT_EST_FINAL_COM		,QT_SAI_VD_COM,QT_SAI_TRANSF_COM,VLR_SAI_TRANSF_COM,
									QT_INI_FLUT,QT_ENT_FLUT,VLR_ENT_FLUT,QT_SAI_FLUT,QT_IMP_FLUT,QT_EST_FINAL_FLUT	,QT_SAI_VD_FLUT,QT_SAI_TRANSF_FLUT,VLR_SAI_TRANSF_FLUT)
	SELECT   
		f.CD_EMP,  
		f.CD_FILIAL,  
		@DT_BASE AS DT_PROC ,   
		f.CD_PROD,  
		ISNULL(f.QT_INI,0) AS QT_INI,  
		ISNULL(f.VLR_CUSTO_MD_INI,0) AS VLR_CUSTO_MD_INI,  
		ISNULL(e.QT_ENT,0) AS QT_ENT,  
		ISNULL(e.VLR_ENT,0) AS VLR_ENT,  
		ISNULL(s.QT_SAI,0) + ISNULL(r.QT_SAI_TRANSF,0) + ISNULL(d.QT_DEV,0) AS QT_SAI,  
		ISNULL(b.QT_IMP,0)  AS QT_IMP,
		  
		(ISNULL(f.QT_INI,0) + ISNULL(e.QT_ENT,0) + ISNULL(b.QT_IMP,0))
			- (ISNULL(s.QT_SAI,0) + ISNULL(r.QT_SAI_TRANSF,0) + ISNULL(d.QT_DEV,0) ) AS  QT_EST_FINAL,
		
		/*********************************************************************************/   
		--Custo medio novo
		/*********************************************************************************/

		case when (Isnull(f.QT_INI_CALC,0) + Isnull(e.QT_ENT,0) + ISNULL(b.QT_IMP,0))
						- (Isnull(d.QT_DEV,0)
						) =0 then 
			case when Isnull(e.QT_ENT,0) - Isnull(d.QT_DEV,0) <> 0 then
				(
					(ISNULL(e.VLR_ENT,0) * ISNULL(e.QT_ENT,0))
					-(Isnull(d.QT_DEV,0) * Isnull(d.VLR_DEV,0))
				)
				/
				(
					Isnull(e.QT_ENT,0)- Isnull(d.QT_DEV,0)
				)
			else
				ISNULL(f.VLR_CUSTO_MD_INI,0)
			end  
		when (Isnull(f.QT_INI_CALC,0)+ ISNULL(b.QT_IMP,0)) <=0 and (Isnull(e.QT_ENT,0) - Isnull(d.QT_DEV,0) ) > 0 then 
			ISNULL(e.VLR_ENT,0) 
		else
	 		 --Entradas
			(
				( 
					 ((ISNULL(f.QT_INI_CALC,0) + ISNULL(b.QT_IMP,0)- ISNULL(i.QT_IMP_ENT,0)) 
						 * ISNULL(f.VLR_CUSTO_MD_INI,0))  

					+	(ISNULL(e.VLR_ENT,0) * ISNULL(e.QT_ENT,0))
				)	
				- --menos
				--Saidas (devolucoes)
				( 
					(Isnull(d.QT_DEV,0) * Isnull(d.VLR_DEV,0))
				)
			)		
			/ --dividido	
			(
				(Isnull(f.QT_INI_CALC,0)+ ISNULL(b.QT_IMP,0) + Isnull(e.QT_ENT,0))
				- (Isnull(d.QT_DEV,0))
			)				 
		END AS VLR_CUSTO_MD_NOVO,

		/*********************************************************************************/
				
		ISNULL(e.VLR_DESC_FINAN,0) AS VLR_DESC_FINAN,
		ISNULL(e.VLR_ENT_CUSTO_GER,0) AS VLR_ENT_CUSTO_GER,

		Case when ISNULL(f.VLR_CUSTO_GER_INI,0) = 0 THEN
			ISNULL(f.VLR_CUSTO_MD_INI,0)  
		ELSE
			ISNULL(f.VLR_CUSTO_GER_INI,0)
		END AS VLR_CUSTO_GERENCIAL_INI,

		CASE WHEN ISNULL(f.QT_INI,0) > 0 THEN  
			CASE WHEN (ISNULL(f.QT_INI,0) + ISNULL(e.QT_ENT,0)) > 0 THEN   
				(( ISNULL(e.VLR_ENT_CUSTO_GER,0) *  ISNULL(e.QT_ENT,0) ) + (ISNULL(f.QT_INI,0) * ISNULL(f.VLR_CUSTO_GER_INI,0))) 
				/ (ISNULL(f.QT_INI,0) + ISNULL(e.QT_ENT,0))
			ELSE  
				ISNULL(f.VLR_CUSTO_GER_INI,0)  
			END
		ELSE
			CASE WHEN ISNULL(e.QT_ENT,0) > 0 THEN  
				ISNULL(e.VLR_ENT_CUSTO_GER,0)
			ELSE
				ISNULL(f.VLR_CUSTO_GER_INI,0)  
			END
		END	AS VLR_CUSTO_GER_NOVO,
		 
		ISNULL(f.QT_AJUSTE_MOV,0)	QT_AJUSTE_MOV,  
				
		/*********************************************************************************/   
		--Saldo custo
		/*********************************************************************************/

		(
			( 
				(ISNULL(e.VLR_ENT,0)  * ISNULL(E.QT_ENT,0)) 
				+ (Isnull(f.QT_INI,0) * ISNULL(f.VLR_CUSTO_MD_INI,0))   
				+ ((Isnull(b.QT_IMP,0)-ISNULL(I.QT_IMP_ENT,0)) * ISNULL(f.VLR_CUSTO_MD_INI,0))
			)		
			- --menos Saidas
			( 
				(Isnull(r.QT_SAI_TRANSF,0)* Isnull(r.VLR_SAI_TRANSF,0))
				+ (Isnull(d.QT_DEV,0)	  * Isnull(d.VLR_DEV,0))
			--	+ (ISNULL(s.QT_SAI,0)	  * ISNULL(f.VLR_CUSTO_MD_INI,0))
			) 
		)	 AS VLR_SALDO_CUSTO, 


		/*********************************************************************************/  

		ISNULL(A.VLR_AJUSTE,0)  AS VLR_AJUSTE_CUSTO,
			
		ISNULL(s.QT_SAI,0) as QT_SAI_VD,
		f.VLR_TABELA,
		CASE WHEN ISNULL(AT.VLR_AJUSTE_TRANSF,0) <> 0 THEN
			ISNULL(AT.VLR_AJUSTE_TRANSF,0)  - ISNULL((E.QT_ENT*E.VLR_PRC_CUSTO_REAL),0)
		ELSE 0 END AS VLR_AJUSTE_TRANS,

		ISNULL(I.QT_IMP_ENT,0) QT_IMP_ENT,
		ISNULL(I.VLR_IMP_ENT ,0)VLR_IMP_ENT,
		ISNULL(et.VLR_EST_TRANSF ,0) VLR_EST_TRANSF, 
		ISNULL(r.QT_SAI_TRANSF,0) QT_SAI_TRANSF, 
		ISNULL(r.VLR_SAI_TRANSF,0)  VLR_SAI_TRANSF,

		ISNULL(f.QT_INI_COM,0),	
		ISNULL(e.QT_ENT_COM,0),	
		ISNULL(e.VLR_ENT_COM,0), 
		ISNULL(s.QT_SAI_VD_COM,0) + ISNULL(r.QT_SAI_TRANSF_COM,0),  
		ISNULL(b.QT_IMP_COM,0),	
		ISNULL(f.QT_INI_COM,0) + ISNULL(e.QT_ENT_COM,0) - (ISNULL(s.QT_SAI_VD_COM,0) + ISNULL(r.QT_SAI_TRANSF_COM,0)) as QT_EST_FINAL_COM,  
		ISNULL(s.QT_SAI_VD_COM,0), 
		ISNULL(r.QT_SAI_TRANSF_COM,0), 
		ISNULL(r.VLR_SAI_TRANSF_COM,0), 
		ISNULL(f.QT_INI_FLUT,0),	
		ISNULL(e.QT_ENT_FLUT,0),	
		ISNULL(e.VLR_ENT_FLUT,0), 
		ISNULL(s.QT_SAI_VD_FLUT,0)+ 	ISNULL(r.QT_SAI_TRANSF_FLUT,0),
		ISNULL(b.QT_IMP_FLUT,0),
		ISNULL(f.QT_INI_FLUT,0) + ISNULL(e.QT_ENT_FLUT,0)+ ISNULL(b.QT_IMP_FLUT,0) - (ISNULL(s.QT_SAI_VD_FLUT,0)+ ISNULL(r.QT_SAI_TRANSF_FLUT,0) ) as  QT_EST_FINAL_FLUT, 
		ISNULL(s.QT_SAI_VD_FLUT,0), 
		ISNULL(r.QT_SAI_TRANSF_FLUT,0), 
		ISNULL(r.VLR_SAI_TRANSF_FLUT,0)

	FROM  
		
		EST_FECHA_PROC_MOV_RsFecha f with(nolock)

		left join EST_FECHA_PROC_MOV_RsEntradas e with(nolock) on 
		f.CD_EMP	= e.CD_EMP AND   
		f.CD_FILIAL = e.CD_FILIAL AND   
		f.CD_PROD   = e.CD_PROD  

		left join EST_FECHA_PROC_MOV_RsAjuste a with(nolock) on 
		f.CD_EMP	= a.CD_EMP AND   
		f.CD_FILIAL = a.CD_FILIAL AND   
		f.CD_PROD	= a.CD_PROD  

		left join EST_FECHA_PROC_MOV_RsAjusteTransf aT with(nolock) on 
		f.CD_EMP	= at.CD_EMP AND   
		f.CD_FILIAL = at.CD_FILIAL AND   
		f.CD_PROD	= at.CD_PROD  

		left join EST_FECHA_PROC_MOV_RsSaidas s with(nolock) on
		f.CD_EMP	= s.CD_EMP AND   
		f.CD_FILIAL = s.CD_FILIAL AND   
		f.CD_PROD	= s.CD_PROD  

		left join EST_FECHA_PROC_MOV_RsSaiTransf r with(nolock) on
		f.CD_EMP	= r.CD_EMP AND   
		f.CD_FILIAL = r.CD_FILIAL AND   
		f.CD_PROD	= r.CD_PROD 

		left join EST_FECHA_PROC_MOV_RsBalanco b with(nolock) on
		f.CD_EMP	= b.CD_EMP AND   
		f.CD_FILIAL = b.CD_FILIAL AND   
		f.CD_PROD	= b.CD_PROD  
		left join EST_FECHA_PROC_MOV_RsDevolucoes d  with(nolock)on
		f.CD_EMP	= d.CD_EMP AND   
		f.CD_FILIAL = d.CD_FILIAL AND   
		f.CD_PROD	= d.CD_PROD 
		 
		left join EST_FECHA_PROC_MOV_RsImpEnt i with(nolock)  on 
		f.CD_EMP	= i.CD_EMP AND   
		f.CD_FILIAL = i.CD_FILIAL AND   
		f.CD_PROD	= i.CD_PROD   
		
		left join EST_FECHA_PROC_MOV_RsEstNF et with(nolock) on 
		f.CD_EMP	= et.CD_EMP AND   
		f.CD_FILIAL = et.CD_FILIAL AND   
		f.CD_PROD	= et.CD_PROD ; 
		 
/*****************************************************************************************************************************/
-- Calcula o saldo de custo gerado pela movimentacao incorreta
/*****************************************************************************************************************************/	 
	if @Debug=1
	begin 
		print 'Carregou EST_FECHA_PROC_MOV_RsResultado  - Time : ' +convert(varchar,getdate(),108);
	end
	--select * from EST_FECHA_PROC_MOV_RsResultado

	--Nao deixar o custo ficar negativo
	update r
	set r.VLR_CUSTO_MEDIO_NOVO =r.VLR_CUSTO_MD_INI 
	from EST_FECHA_PROC_MOV_RsResultado r
	where r.VLR_CUSTO_MEDIO_NOVO < 0
		and r.CD_EMP = @CD_EMP   
		AND r.CD_FILIAL = @CD_FILIAL     ; 

	update r
	set 
		--Saldo de custo diario... somar no fechamento do mes..
		VLR_SALDO_CUSTO =round((case when (r.VLR_SALDO_CUSTO -(r.QT_SAI_VD *
																CASE WHEN  @CUSTO_SAI_INICIO_DIA=1 AND r.QT_INI <>0 THEN r.VLR_CUSTO_MD_INI
																ELSE r.VLR_CUSTO_MEDIO_NOVO 
																END )
											) <> (r.VLR_CUSTO_MEDIO_NOVO*(r.QT_EST_FINAL)) then
										
										(r.VLR_SALDO_CUSTO -
													(r.QT_SAI_VD *  CASE WHEN  @CUSTO_SAI_INICIO_DIA=1 AND r.QT_INI <>0 THEN r.VLR_CUSTO_MD_INI
																			ELSE r.VLR_CUSTO_MEDIO_NOVO END)
																				
										)
										- (r.VLR_CUSTO_MEDIO_NOVO*(r.QT_EST_FINAL))  
								else 0 end),2) +ISNULL(A.VLR,0),

		VLR_AJUSTE_CUSTO = case  when r.VLR_AJUSTE_CUSTO <> 0 then
									(r.QT_EST_FINAL * r.VLR_AJUSTE_CUSTO)-(r.QT_EST_FINAL * r.VLR_CUSTO_MEDIO_NOVO)
							else 0 end,

		VLR_AJUSTE_TRANSF=r.VLR_AJUSTE_TRANSF+ r.VLR_IMP_ENT + r.VLR_EST_TRANSF,

		VLR_CUSTO_MEDIO_NOVO = CASE WHEN (r.VLR_IMP_ENT+ISNULL(A.VLR,0)) <> 0   THEN
									CASE WHEN r.QT_EST_FINAL <> 0 THEN
										r.VLR_CUSTO_MEDIO_NOVO +  (r.VLR_IMP_ENT+ISNULL(A.VLR,0))/ r.QT_EST_FINAL
									ELSE 
										CASE WHEN R.VLR_CUSTO_MEDIO_NOVO <> 0 THEN
											R.VLR_CUSTO_MEDIO_NOVO + (R.VLR_IMP_ENT) +ISNULL(A.VLR,0)
										ELSE 0	
										END
									END  
								ELSE 
									r.VLR_CUSTO_MEDIO_NOVO 
								END + 
									CASE WHEN r.VLR_EST_TRANSF  <> 0 THEN
										CASE WHEN r.QT_EST_FINAL <> 0 THEN
											((r.VLR_EST_TRANSF/ r.QT_EST_FINAL))
										ELSE 
											0
										END  
									ELSE 0
									END
	from
		EST_FECHA_PROC_MOV_RsResultado r
		inner join EST_FECHA_PROC_MOV_RsFecha f on 
		r.CD_EMP	    = f.CD_EMP AND   
		r.CD_FILIAL   = f.CD_FILIAL AND   
		r.CD_PROD	    = f.CD_PROD   
		left join  (SELECT CD_EMP, CD_FILIAL,CD_PROD, SUM(VLR_AJUSTE_TRANSF) VLR
							FROM EST_PROD_CPL_ACERTO_CUSTO
							WHERE
								DT_MOV= @DT_BASE
								AND TP_AJUSTE=1
								and CD_FILIAL =@CD_FILIAL
								and CD_EMP    =@CD_EMP
							GROUP BY CD_EMP, CD_FILIAL,CD_PROD) a on 
		r.CD_EMP	= a.CD_EMP AND   
		r.CD_FILIAL = a.CD_FILIAL AND   
		r.CD_PROD	= a.CD_PROD ;

	if @Debug=1
	begin 
		print 'Atualizou o saldo do custo EST_FECHA_PROC_MOV_RsResultado  - Time : ' +convert(varchar,getdate(),108);
	end

/*****************************************************************************************************************************/
-- Colocando o valor ult. entrada custo.
	update e
	set 
		VLR_ENT=j.VlrEnt-- ISNULL(dbo.F_VLR_CUSTO_EST_FECHA_PROC_MOV (1,999,E.CD_PROD,e.DT_PROC,6),0)
	from 
		EST_FECHA_PROC_MOV_RsResultado e
		Cross apply (SELECT CASE WHEN ISNULL(VLR_AJUSTE,0)=0 THEN VLR_ENT ELSE VLR_AJUSTE END VlrEnt
										FROM EST_FECHA_PROC_MOV with (nolock)
										WHERE 
											CD_EMP =1 
											AND CD_FILIAL	=e.CD_FILIAL
											AND CD_PROD		=E.CD_PROD
											AND VLR_ENT > 0
											AND DT_PROC		= (SELECT MAX(DT_PROC) DT_PROC
																FROM EST_FECHA_PROC_MOV
																WHERE 
																	CD_EMP =1 
																	AND CD_FILIAL	=e.CD_FILIAL
																	AND CD_PROD		=E.CD_PROD
																	AND DT_PROC		<=e.DT_PROC
																	AND VLR_ENT > 0)) j

	where 
		QT_ENT=0
		AND VLR_ENT=0;


	--select * from EST_FECHA_PROC_MOV_RsResultado
/*****************************************************************************************************************************/
-- Insere o resultado final
/*****************************************************************************************************************************/	 
	
	 INSERT INTO EST_FECHA_PROC_MOV  (CD_EMP,CD_FILIAL,CD_PROD,DT_PROC,QT_EST_INI_DIA,
										VLR_CUSTO_MD_INI,	QT_ENT,			VLR_ENT,QT_SAI,QT_IMP,
										VLR_CUSTO_MD_NOVO,	QT_EST_FINAL,	VLR_CUSTO_GER_INI,
										VLR_CUSTO_GER_NOVO,	VLR_DESC_FINAN,	VLR_CUSTO_MD_CALC, 
										VLR_AJUSTE, DT_CAD, VLR_DEVOLUCAO,	QTD_DEVOLUCAO, 
										QT_AJUSTE_MOV ,	VLR_SALDO_CUSTO,	VLR_AJUSTE_CUSTO,
										VLR_TABELA,		VLR_AJUSTE_CUSTO_TRANSF,
										QT_INI_COM,		QT_ENT_COM,		VLR_ENT_COM	,
										QT_DEV_COM,		VLR_DEV_COM,	QT_IMP_COM,		VLR_IMP_COM,	
										QT_SAI_COM,		VLR_SAI_COM,	QT_TRANSF_COM,	VLR_TRANSF_COM,	
										QT_FINAL_COM,	QT_INI_FLUT,	QT_ENT_FLUT,	VLR_ENT_FLUT,	
										QT_DEV_FLUT,	VLR_DEV_FLUT,	QT_IMP_FLUT,	VLR_IMP_FLUT,	
										QT_SAI_FLUT,	VLR_SAI_FLUT,	QT_TRANSF_FLUT,	VLR_TRANSF_FLUT, 
										QT_FINAL_FLUT) 

	SELECT  
		r.CD_EMP,  
		r.CD_FILIAL,  
		r.CD_PROD,  
		r.DT_PROC,   
		  
		SUM(r.QT_INI),  
		AVG(r.VLR_CUSTO_MD_INI),  
		SUM(r.QT_ENT),  
		SUM(R.VLR_ENT)  VLR_ENT,  
		SUM(r.QT_SAI),   
		SUM(r.QT_IMP),  
		avg(ISNULL(a.VLR_AJUSTE, r.VLR_CUSTO_MEDIO_NOVO )) VLR_CUSTO_MEDIO_NOVO,  
		SUM(r.QT_EST_FINAL), 
		avg(r.VLR_CUSTO_GERENCIAL_INI ) ,
		avg(ISNULL(a.VLR_AJUSTE, case when @NaoUtilizaCustoGerTransf =0 then r.VLR_CUSTO_GERENCIAL_NOVO ELSE  r.VLR_CUSTO_MEDIO_NOVO END) )  VLR_CUSTO_GERENCIAL_NOVO,  
		SUM(r.VLR_DESC_FINAN)		VLR_DESC_FINAN, 
		avg(r.VLR_CUSTO_MEDIO_NOVO) VLR_CUSTO_MD_CALC,  
		avg(ISNULL(a.VLR_AJUSTE,0)) VLR_AJUSTE,
		GETDATE()					DT_CAD,
		SUM(ISNULL(d.VLR_DEV,0))	VLR_DEV,
		SUM(ISNULL(d.QT_DEV,0))		QT_DEV,

		SUM(R.QT_AJUSTE_MOV), 
		AVG(ISNULL(r.VLR_SALDO_CUSTO,0) )	VLR_SALDO_CUSTO,
		AVG(ISNULL(r.VLR_AJUSTE_CUSTO,0) )	VLR_AJUSTE_CUSTO,
		AVG(ISNULL(r.VLR_TABELA,0))			VLR_TABELA,
		AVG(ISNULL(r.VLR_AJUSTE_TRANSF,0))	VLR_AJUSTE_TRANSF, 

		SUM(r.QT_INI_COM) QT_INI_COM,   
		SUM(r.QT_ENT_COM) QT_ENT_COM,     
		SUM(r.VLR_ENT_COM) VLR_ENT_COM,    
		SUM(ISNULL(d.QT_DEV_COM,0)) QT_DEV_COM,		
		SUM(ISNULL(d.VLR_DEV_COM,0)) VLR_DEV_COM, 
		SUM(r.QT_IMP_COM) QT_IMP_COM, 
		SUM(case when r.QT_IMP_COM  <> 0  then  r.VLR_CUSTO_MD_INI else 0 end )  VLR_IMP_COM, 
		SUM(r.QT_SAI_COM)  QT_SAI_COM,		 
		SUM(case when r.QT_SAI_COM  <> 0  then  r.VLR_CUSTO_MD_INI else 0 end )  VLR_SAI_COM,  
		SUM(r.QT_SAI_TRANSF_COM) QT_TRANSF_COM,	
		SUM(r.VLR_SAI_TRANSF_COM) VLR_TRANSF_COM, 
		SUM(r.QT_EST_FINAL_COM) QT_FINAL_COM,	 
		SUM(r.QT_INI_FLUT) QT_INI_FLUT,   
		SUM(r.QT_ENT_FLUT) QT_ENT_FLUT,     
		SUM(r.VLR_ENT_FLUT) VLR_ENT_FLUT,    
		SUM(ISNULL(d.QT_DEV_FLUT,0)) QT_DEV_FLUT,		
		SUM(ISNULL(d.VLR_DEV_FLUT,0)) VLR_DEV_FLUT, 
		SUM(r.QT_IMP_FLUT) QT_IMP_FLUT,		
		SUM(case when r.QT_IMP_FLUT  <> 0  then  r.VLR_CUSTO_MD_INI else 0 end ) VLR_IMP_FLUT,	 
		SUM(r.QT_SAI_FLUT) QT_SAI_FLUT,		 
		SUM(case when r.QT_SAI_FLUT <> 0 then r.VLR_CUSTO_MD_INI else 0 end  ) VLR_SAI_FLUT, 
		SUM(r.QT_SAI_TRANSF_FLUT) QT_TRANSF_FLUT,	
		SUM(r.VLR_SAI_TRANSF_FLUT) VLR_TRANSF_FLUT,	
		SUM(r.QT_EST_FINAL_FLUT) QT_FINAL_FLUT	  
		
	FROM  
		EST_FECHA_PROC_MOV_RsResultado r  with(nolock)

		LEFT JOIN EST_FECHA_PROC_MOV_RsFecha f with(nolock) ON  
		r.CD_EMP	= f.CD_EMP  AND  
		r.CD_FILIAL	= f.CD_FILIAL AND  
		r.CD_PROD	= f.CD_PROD  
		 
		LEFT JOIN EST_FECHA_PROC_MOV_RsAjuste a with(nolock) ON  
		r.CD_EMP	= a.CD_EMP  AND  
		r.CD_FILIAL	= a.CD_FILIAL AND  
		r.CD_PROD	= a.CD_PROD  
		
		LEFT join EST_FECHA_PROC_MOV_RsDevolucoes d with(nolock) on 
		r.CD_EMP	= d.CD_EMP AND
		r.CD_FILIAL = d.CD_FILIAL AND
		r.CD_PROD	= d.CD_PROD 
	WHERE  
		r.CD_EMP = @CD_EMP   
		AND r.CD_FILIAL = @CD_FILIAL  
		AND r.DT_PROC   = @DT_BASE  
		
		AND (r.QT_ENT <> 0 
				or r.QT_SAI <> 0 
				or r.QT_IMP <> 0 
				
				or (CASE WHEN ISNULL(f.INICIO,0) = 1 THEN  r.QT_INI 
						ELSE 0 END) <> 0
				or ISNULL(a.VLR_AJUSTE,0) <> 0
				or ISNULL(R.VLR_AJUSTE_TRANSF,0) <> 0 
				or ISNULL(R.VLR_SALDO_CUSTO,0) <> 0  
				or ISNULL(D.QT_DEV,0) <>0 
				or ISNULL(f.QT_AJUSTE_MOV,0) <> 0
				or  datepart(day,r.DT_PROC)=1  --Sempre inserir dia 1 por ser inicial
				or  datepart(day,r.DT_PROC)=15  --Sempre inserir dia 15 para evitar voltar demais..
				or  datepart(day,r.DT_PROC)=@UltDia  --Sempre inserir ultimo dia 
				)
	GROUP BY 
		r.CD_EMP,  
		r.CD_FILIAL,  
		r.CD_PROD,  
		r.DT_PROC;    
	
	if @Debug=1
	begin 
		print 'Carregou EST_FECHA_PROC_MOV - Time : ' +convert(varchar,getdate(),108);
	end

	
/*****************************************************************************************************************************/
-- Atualizacao do custo nas tabelas base
/*****************************************************************************************************************************/	


		update r 
		set
			VLR_CUSTO_MEDIO_NOVO =  a.VLR_AJUSTE,
			VLR_CUSTO_GERENCIAL_NOVO=  a.VLR_AJUSTE
		from 
			EST_FECHA_PROC_MOV_RsResultado r  with(nolock) 		 
			JOIN EST_FECHA_PROC_MOV_RsAjuste a with(nolock) ON  
			r.CD_EMP	= a.CD_EMP  AND  
			r.CD_FILIAL	= a.CD_FILIAL AND  
			r.CD_PROD	= a.CD_PROD   


		if @Debug=1
		begin 
			print 'Atualizando o custo medio - Time : ' +convert(varchar,getdate(),108) 
		end

		--Se for o ultimo dia do mes atualiza o fechamento de estoque... 
		IF @DT_BASE = CONVERT(DATETIME,dbo.F_FINAL_MES(@DT_BASE)) 
		BEGIN
			if @Debug=1
			begin 
				print 'Atualizando fechamento estoque - Time : ' +convert(varchar,getdate(),108) 
			end

			IF @BLQ_REG_INVENT =1 BEGIN
			
				UPDATE F 
				SET
					F.VLR_CUSTO_MD =R.VLR_CUSTO_MEDIO_NOVO,
					f.VLR_CUSTO_GER = R.VLR_CUSTO_GERENCIAL_NOVO,
					f.VLR_SALDO_CUSTO = R.VLR_SALDO_CUSTO
				FROM
					EST_FECHA F 
					INNER JOIN EST_FECHA_PROC_MOV_RsResultado R ON 
					F.CD_EMP	= R.CD_EMP  AND  
					F.CD_FILIAL = R.CD_FILIAL AND  
					F.CD_PROD	= R.CD_PROD 
					left join EST_PROD_INVENTARIO i on 
					F.CD_EMP	= i.CD_EMP  AND  
					F.CD_FILIAL = i.CD_FILIAL AND  
					F.CD_PROD	= i.CD_PROD 
					AND i.DT_REF = @DT_BASE 
				WHERE
					F.CD_EMP = @CD_EMP
					AND F.CD_FILIAL = @CD_FILIAL
					AND I.CD_EMP IS NULL --> Que nao registro de inventario gerado
					AND F.MES_FECHA = DATEPART(MONTH,@DT_BASE)
					AND F.ANO_FECHA = DATEPART(YEAR,@DT_BASE)
					and R.VLR_CUSTO_MEDIO_NOVO> 0; ;
				
			
			END
			ELSE
			BEGIN

				UPDATE F 
				SET
					F.VLR_CUSTO_MD =R.VLR_CUSTO_MEDIO_NOVO,
					f.VLR_CUSTO_GER = R.VLR_CUSTO_GERENCIAL_NOVO,
					f.VLR_SALDO_CUSTO = R.VLR_SALDO_CUSTO
				FROM
					EST_FECHA F
					INNER JOIN EST_FECHA_PROC_MOV_RsResultado R ON 
					F.CD_EMP	= R.CD_EMP  AND  
					F.CD_FILIAL = R.CD_FILIAL AND  
					F.CD_PROD	= R.CD_PROD  
				WHERE
					F.CD_EMP = @CD_EMP
					AND F.CD_FILIAL = @CD_FILIAL
					AND F.MES_FECHA = DATEPART(MONTH,@DT_BASE)
					AND F.ANO_FECHA = DATEPART(YEAR,@DT_BASE)
					and R.VLR_CUSTO_MEDIO_NOVO> 0; 
			 
			END

			if @Debug=1
			begin 
				print 'Ultimo dia do mes atualizou o fechamento de estoque - Time : ' +convert(varchar,getdate(),108) 
			end
		END
	
/*****************************************************************************************************************************/
	IF @IGNORA_ATU =0
	begin
		
		if @Debug=1
		begin
			print 'Processando custos em documentos armazenados: ' +convert(varchar,getdate(),108) 
		end

		--EXEC P_EST_PROD_REPROCESSAMENTO_CUSTO_EXEC_ALL @CD_EMP,@CD_FILIAL,0,0,0,@DT_BASE,@CD_PROD;
	 
		--Movimentos de entrada  
		UPDATE
			EST_NF_ENT_IT
		SET 
			VLR_CUSTO_MD				= e.VLR_CUSTO_MEDIO_NOVO,
			VLR_CUSTO_GERENCIAL_TRANSF	= 0
		FROM
			EST_NF_ENT_IT 
			INNER JOIN EST_FECHA_PROC_MOV_RsResultado E ON
			EST_NF_ENT_IT.CD_EMP	= E.CD_EMP AND
			EST_NF_ENT_IT.CD_FILIAL = E.CD_FILIAL AND
			EST_NF_ENT_IT.CD_PROD	= E.CD_PROD AND 
			EST_NF_ENT_IT.DT_ENT	= E.DT_PROC

		WHERE
			EST_NF_ENT_IT.CD_EMP		= 1 
			AND EST_NF_ENT_IT.CD_FILIAL = @CD_FILIAL 
			AND EST_NF_ENT_IT.DT_ENT	= @DT_BASE 	
	
		--Custo gerencial de transferencia.
		IF EXISTS(SELECT E.CD_EMP FROM 
						EST_NF_ENT  E
						JOIN EST_NF_ENT_EST_NF_SAI_TRANSF ON
						E.CD_EMP	= EST_NF_ENT_EST_NF_SAI_TRANSF.CD_EMP AND
						E.CD_FILIAL = EST_NF_ENT_EST_NF_SAI_TRANSF.CD_FIL_DEST AND
						E.CD_NF		= EST_NF_ENT_EST_NF_SAI_TRANSF.CD_NF_ENT	
					WHERE
						E.CD_EMP		= 1 
						AND E.CD_FILIAL = @CD_FILIAL 
						AND E.DT_ENT	= @DT_BASE )
		BEGIN
		
			UPDATE
				EST_NF_ENT_IT
			SET 
				VLR_CUSTO_GERENCIAL_TRANSF	= case when @NaoUtilizaCustoGerTransf =0 then 
															CASE WHEN @CUSTO_GER_VLR_ORIGEM =1 THEN E.VLR_CUSTO_GERENCIAL_NOVO
															ELSE
																dbo.F_VLR_CUSTO_EST_FECHA_PROC_MOV (EST_NF_ENT_IT.CD_EMP,ISNULL(EST_NF_ENT_EST_NF_SAI_TRANSF.CD_FIL_ORIG,-1),
																						EST_NF_ENT_IT.CD_PROD,
																						EST_NF_ENT.DT_EMI_NF,
																						1) END
												else  EST_NF_ENT_IT.VLR_CUSTO_MD END 
			FROM
				EST_NF_ENT_IT 
				INNER JOIN EST_FECHA_PROC_MOV_RsResultado E ON
				EST_NF_ENT_IT.CD_EMP	= E.CD_EMP AND
				EST_NF_ENT_IT.CD_FILIAL = E.CD_FILIAL AND
				EST_NF_ENT_IT.CD_PROD	= E.CD_PROD AND 
				EST_NF_ENT_IT.DT_ENT	= E.DT_PROC

				INNER JOIN EST_NF_ENT ON
				EST_NF_ENT_IT.CD_EMP	= EST_NF_ENT.CD_EMP AND
				EST_NF_ENT_IT.CD_FILIAL = EST_NF_ENT.CD_FILIAL AND
				EST_NF_ENT_IT.CD_NF		= EST_NF_ENT.CD_NF

				JOIN EST_NF_ENT_EST_NF_SAI_TRANSF ON
				EST_NF_ENT_IT.CD_EMP	= EST_NF_ENT_EST_NF_SAI_TRANSF.CD_EMP AND
				EST_NF_ENT_IT.CD_FILIAL = EST_NF_ENT_EST_NF_SAI_TRANSF.CD_FIL_DEST AND
				EST_NF_ENT_IT.CD_NF		= EST_NF_ENT_EST_NF_SAI_TRANSF.CD_NF_ENT	
			WHERE
				EST_NF_ENT_IT.CD_EMP		= 1 
				AND EST_NF_ENT_IT.CD_FILIAL = @CD_FILIAL 
				AND EST_NF_ENT_IT.DT_ENT	= @DT_BASE 
		END
		
		IF @CUSTO_SAI_INICIO_DIA =1
		BEGIN
			set @Inicial= 10;
		END

		--Notas de saida
		UPDATE
			I
		SET 
			VLR_CUSTO_MD			   = case when @Inicial =10 then e.VLR_CUSTO_MD_INI	
											else e.VLR_CUSTO_MEDIO_NOVO  end ,
			VLR_CUSTO_GERENCIAL_TRANSF = e.VLR_CUSTO_GERENCIAL_NOVO
		FROM 
			EST_NF_SAI_IT I 
			INNER JOIN EST_FECHA_PROC_MOV_RsResultado E ON
			i.CD_EMP	= E.CD_EMP AND
			i.CD_FILIAL = E.CD_FILIAL AND
			i.CD_PROD	= E.CD_PROD AND 
			i.DT_EMI_NF	= E.DT_PROC
		WHERE
			I.CD_EMP = 1 
			AND I.CD_FILIAL = @CD_FILIAL 
			AND I.DT_EMI_NF = @DT_BASE;

		--Cupons fiscais
		UPDATE
			i
		SET 
			VLR_CUSTO_GER	= e.VLR_CUSTO_GERENCIAL_NOVO,
			VLR_CUSTO_MEDIO = case when @Inicial =10 then e.VLR_CUSTO_MD_INI	
											else e.VLR_CUSTO_MEDIO_NOVO  end,
			VLR_CUSTO		= CASE WHEN ISNULL(e.VLR_AJUSTE_CUSTO,0)=0 THEN e.VLR_ENT 
											Else e.VLR_AJUSTE_CUSTO END
		from
			PDV_VD_IT i	
			inner join EST_FECHA_PROC_MOV_RsResultado e on 
			i.cd_emp	 = e.cd_emp and
			i.cd_filial  = e.cd_filial and
			i.cd_prod	 = e.cd_prod and
			i.DT_VD		 = e.DT_PROC  
		WHERE
				i.CD_EMP = 1 
			AND i.CD_FILIAL = @CD_FILIAL 
			AND i.DT_VD		= @DT_BASE;


		--Devolucoes Cupons fiscais
		UPDATE
			i
		SET  
			VLR_CUSTO_MEDIO = case when @Inicial =10 then e.VLR_CUSTO_MD_INI	
											else e.VLR_CUSTO_MEDIO_NOVO  end,
			VLR_CUSTO		= CASE WHEN ISNULL(e.VLR_AJUSTE_CUSTO,0)=0 THEN e.VLR_ENT 
											Else e.VLR_AJUSTE_CUSTO END
		from
			PDV_VD_DEV_EST_PROD_IMP i	
			inner join EST_FECHA_PROC_MOV_RsResultado e on 
			i.cd_emp	 = e.cd_emp and
			i.cd_filial  = e.cd_filial and
			i.cd_prod	 = e.cd_prod and
			i.DT_DEVO		 = e.DT_PROC  
		WHERE
				i.CD_EMP = 1 
			AND i.CD_FILIAL = @CD_FILIAL 
			AND i.DT_DEVO	= @DT_BASE;

			 


/*********************************************************************************************************************************************/
--Tag #A001
-- Atualiza a informa nas tabelas de relatorios 

	   declare @CD_CTR_DT_MOVIMENTO int;
	   set @CD_CTR_DT_MOVIMENTO = isnull((select CD_CTR_DT_MOVIMENTO 
									   from GLB_DT_MOVIMENTO where dt_movimento =@DT_BASE),0)

	   UPDATE 
		  PROD
	   SET
		 PROD.VLR_CUSTO_MD =  CASE WHEN CPL.TP_PROD IN(10, 11)
							 THEN Prod.VLR_VD_LIQ - (Prod.VLR_VD_LIQ  * (ISNULL(CPL.PERC_COMISSAO_SERVICO,0) / 100))
							 ELSE (case when @Inicial =10 then e.VLR_CUSTO_MD_INI	
								ELSE e.VLR_CUSTO_MEDIO_NOVO  end)  * Prod.QTDE_ITENS
						  END,
		PROD.VLR_CUSTO_GER =  CASE WHEN CPL.TP_PROD IN(10, 11)
							 THEN Prod.VLR_VD_LIQ - (Prod.VLR_VD_LIQ  * (ISNULL(CPL.PERC_COMISSAO_SERVICO,0) / 100))
								ELSE e.VLR_CUSTO_GERENCIAL_NOVO * Prod.QTDE_ITENS
						  END,
		PROD.VLR_CUSTO =	  CASE WHEN CPL.TP_PROD IN(10, 11)
						  THEN Prod.VLR_VD_LIQ - (Prod.VLR_VD_LIQ  * (ISNULL(CPL.PERC_COMISSAO_SERVICO,0) / 100))
						  ELSE (CASE WHEN ISNULL(e.VLR_AJUSTE_CUSTO,0)=0 THEN e.VLR_ENT 
								ELSE e.VLR_AJUSTE_CUSTO END) * Prod.QTDE_ITENS
						  END
	   FROM  
		  EST_MOVIMENTO_VENDAS Vendas
		  INNER JOIN EST_MOVIMENTO_VENDAS_PRODUTOS Prod ON Vendas.CD_EMP = PROD.CD_EMP
			 and Vendas.CD_CTR_VENDAS = PROD.CD_CTR_VENDAS

		  INNER JOIN EST_PROD_CPL CPL ON 
			 Vendas.CD_FILIAL = CPL.CD_FILIAL AND
			 Prod.CD_EMP	  = CPL.CD_EMP AND
			 Prod.CD_PROD	  = CPL.CD_PROD

		  inner join EST_FECHA_PROC_MOV_RsResultado e on 			 
			 Vendas.cd_filial = e.cd_filial and
			 Prod.cd_emp	   = e.cd_emp and
			 Prod.cd_prod	   = e.cd_prod and
			 e.DT_PROC	   = @DT_BASE
	   WHERE	 
		  Vendas.CD_EMP = 1
		  AND Vendas.CD_FILIAL = @CD_FILIAL
		  AND Vendas.CD_CTR_DT_MOVIMENTO = @CD_CTR_DT_MOVIMENTO;
 

/*********************************************************************************************************************************************/

		--Deteriorados
		UPDATE
			I
		SET 
			I.VLR_CUSTO_PROD = e.VLR_CUSTO_MD_INI
		FROM
			EST_PROD_DETE_IT  I
			INNER JOIN EST_PROD_DETE d ON 
			I.CD_EMP  = d.CD_EMP AND 
			I.CD_LOTE = d.CD_LOTE 
						
			inner join EST_FECHA_PROC_MOV_RsFecha e on 
			d.cd_emp	 = e.cd_emp and
			d.cd_filial  = e.cd_filial and
			i.cd_prod	 = e.cd_prod  
		WHERE
			d.CD_EMP = 1 
			AND d.CD_FILIAL = @CD_FILIAL 
			AND d.DT_CAD	= @DT_BASE ; 
		
		--Ajustes de estoque/Balanco
		UPDATE
			I
		SET 
			I.VLR_CUSTO_MD = e.VLR_CUSTO_MEDIO_NOVO
		FROM
			EST_PROD_IMP I
			inner join EST_FECHA_PROC_MOV_RsResultado e on 
			i.cd_emp	 = e.cd_emp and
			i.cd_filial  = e.cd_filial and
			i.cd_prod	 = e.cd_prod and
			i.DT_CAD	 = e.DT_PROC  
		WHERE
			I.CD_EMP = 1 
			AND I.CD_FILIAL = @CD_FILIAL 
			AND I.DT_CAD = @DT_BASE;
		
		--Custo do movimento de transferencia requisicao
		UPDATE
			i
		SET
			i.VLR_CUSTO =e.VLR_CUSTO_MEDIO_NOVO
		FROM   
			EST_PROD_REQ_TRANSF_LIB 
			INNER JOIN EST_PROD_REQ_TRANSF_LIB_ITENS i ON 
			EST_PROD_REQ_TRANSF_LIB.CD_EMP    = i.CD_EMP AND
			EST_PROD_REQ_TRANSF_LIB.CD_FILIAL = i.CD_FILIAL AND
			EST_PROD_REQ_TRANSF_LIB.CD_REQ	  = i.CD_REQ 

			INNER JOIN EST_FECHA_PROC_MOV_RsResultado e on 
			i.CD_EMP	= e.CD_EMP AND 
			i.CD_FILIAL = e.CD_FILIAL AND
			i.CD_PROD	= e.CD_PROD AND
			i.CD_EMP	= e.CD_EMP 
		WHERE       						
				EST_PROD_REQ_TRANSF_LIB.CD_EMP = 1   
			AND EST_PROD_REQ_TRANSF_LIB.CD_FILIAL = @CD_FILIAL   
			AND EST_PROD_REQ_TRANSF_LIB.DT_CAD	  = @DT_BASE
			AND EST_PROD_REQ_TRANSF_LIB.DT_CAD  = e.DT_PROC;


	end

/*****************************************************************************************************************************/
-- Limpa as tabelas temporarias
/*****************************************************************************************************************************/	
	
LimpaTabelas:
	
	if @Debug=1
	begin 
		print '*'
		print '*'
	 	print 'Filial ' + convert(varchar, @CD_FILIAL) + ' Dia ' + convert(varchar,@DT_BASE,112)
		print '*'
		print '*' 
		PRINT '**************** Fim - P_EST_FECHA_PROC_MOV ****************' + CONVERT(VARCHAR(8), GETDATE(), 108);
	end

END
