/****** Object:  StoredProcedure [dbo].[P_EST_PROD_CPL_CUSTO_NOVO_LANCAMENTO]    Script Date: 02/15/2013 19:10:14 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[P_EST_PROD_CPL_CUSTO_NOVO_LANCAMENTO]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[P_EST_PROD_CPL_CUSTO_NOVO_LANCAMENTO]
GO
--EXEC P_EST_PROD_CPL_CUSTO_NOVO_LANCAMENTO 1,001,79922,'05/23/2015', 38.8,1

CREATE PROCEDURE P_EST_PROD_CPL_CUSTO_NOVO_LANCAMENTO(@CD_EMP INT,
													  @CD_FILIAL INT,
													  @CD_PROD INT,
													  @DT_PROC DATETIME,
													  @VLR_CUSTO_MD MONEY,
													  @CD_USU INT)
AS
DECLARE @CD_CTR INT
SET NOCOUNT ON 
SET @CD_CTR=0
--Realizar exclusao de dados ja existente					
DELETE 
FROM 
	EST_FECHA_PROC_MOV
WHERE
	CD_EMP=@CD_EMP
	AND CD_FILIAL=@CD_FILIAL
	AND CD_PROD=@CD_PROD
	AND DT_PROC=@DT_PROC

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)
SELECT
	@CD_EMP, 
	@CD_FILIAL, 
	@CD_PROD, 
	@DT_PROC, 
	0,
	0, 
	0, 
	0, 
	0, 
	0, 
	@VLR_CUSTO_MD, 
	0, 
	0, 
	@VLR_CUSTO_MD, 
	0, 
	@VLR_CUSTO_MD, 
	@VLR_CUSTO_MD, 
	GETDATE(), 
	0, 
	0, 
	0, 
	0, 
	0

--Gerando acerto de custo                    
SET @CD_CTR = ISNULL((SELECT
						MAX(CD_CTR)+1
					FROM
						EST_PROD_CPL_ACERTO_CUSTO),1)

INSERT INTO  EST_PROD_CPL_ACERTO_CUSTO
	(CD_CTR, 
	CD_EMP, 
	CD_FILIAL, 
	CD_PROD, 
	VLR_CUSTO_ACERTO, 
	CD_USU, 
	DT_MOV, 
	DT_CAD)
SELECT
	@CD_CTR,
	@CD_EMP,
	@CD_FILIAL,
	@CD_PROD,
	@VLR_CUSTO_MD,
	@CD_USU,
	@DT_PROC,
	GETDATE()

 UPDATE
	EST_PROD_CPL
 SET                   
	VLR_CUSTO_MD=@VLR_CUSTO_MD, 
	VLR_CUSTO=@VLR_CUSTO_MD, 
	VLR_COMPRA=@VLR_CUSTO_MD,
	VLR_CUSTO_GER=@VLR_CUSTO_MD       
WHERE
	CD_EMP =@CD_EMP
	AND CD_FILIAL=@CD_FILIAL 
	AND CD_PROD =@CD_PROD
 