IF  EXISTS( SELECT  * FROM  SYS.OBJECTS 
	WHERE  NAME LIKE 'P_RC_CRED_CANCEL_BAIXA' AND TYPE = 'P' )
BEGIN
	DROP PROCEDURE P_RC_CRED_CANCEL_BAIXA
END
GO
GO
--EXEC P_RC_CRED_CANCEL_BAIXA 1,90,5910,1
CREATE PROCEDURE P_RC_CRED_CANCEL_BAIXA(@CD_EMP INT, 
									    @CD_FILIAL INT, 
										@CD_RC_DEB INT, 
										@CD_DP_LANC INT)
AS
begin
DECLARE @CD_NF_ENT INT
DECLARE @VLR_BAIXA MONEY
DECLARE @CD_FND_VERBA INT
DECLARE @CD_FND_VERBA_RECB INT
DECLARE @CD_FILIAL_VERBA INT
DECLARE @CD_FILIAL_NF_ENT INT 

SELECT
	@CD_FND_VERBA=CD_FND_VERBA,
	@CD_FND_VERBA_RECB=CD_FND_VERBA_RECB,
	@CD_FILIAL_VERBA=CD_FILIAL_VERBA
FROM
	CG_FND_VERBA_RC_CRED
WHERE
	CD_EMP=@CD_EMP
	AND CD_FILIAL = @CD_FILIAL
	AND CD_RC_DEB = @CD_RC_DEB
	AND CD_DP_LANC = @CD_DP_LANC

PRINT 'Delete recebimento duplicata com o  contrato'
DELETE 
FROM 
	CG_FND_VERBA_RC_CRED
WHERE
	CD_EMP=@CD_EMP
	AND CD_FILIAL = @CD_FILIAL
	AND CD_RC_DEB = @CD_RC_DEB
	AND CD_DP_LANC = @CD_DP_LANC

SELECT
	@CD_NF_ENT=CD_NF_ENT,
	@CD_FILIAL_NF_ENT=CD_FILIAL_NF_ENT
FROM
	CG_FND_VERBA_RECB
WHERE
	CD_FND_VERBA = @CD_FND_VERBA
	AND CD_FND_VERBA_RECB=@CD_FND_VERBA_RECB

PRINT 'Delete recebimento contrato'
DELETE 
FROM
	CG_FND_VERBA_RECB
WHERE
	CD_FND_VERBA = @CD_FND_VERBA
	AND CD_FND_VERBA_RECB=@CD_FND_VERBA_RECB

SELECT
	@VLR_BAIXA=VLR_LANC
FROM
	CG_FND_VERBA_EST_NF_ENT
WHERE
	CD_EMP =@CD_EMP 
	AND CD_FILIAL = @CD_FILIAL
	AND CD_FND_VERBA = @CD_FND_VERBA
	AND CD_NF = @CD_NF_ENT
	
PRINT 'Delete relacionamento duplicata com o  contrato'
DELETE
FROM
	CG_FND_VERBA_EST_NF_ENT
WHERE
	CD_EMP =@CD_EMP 
	AND CD_FILIAL = @CD_FILIAL_NF_ENT
	AND CD_FND_VERBA = @CD_FND_VERBA
	AND CD_NF = @CD_NF_ENT
	
PRINT 'Delete baixa duplicata'
DELETE
FROM
	RC_CRED
WHERE
	CD_EMP=@CD_EMP
	AND CD_FILIAL = @CD_FILIAL
	AND CD_RC_DEB = @CD_RC_DEB
	AND CD_DP_LANC = @CD_DP_LANC

PRINT 'Alteracao saldo de recebimento'
UPDATE
	CG_FND_VERBA
SET 
	 VLR_RECB =VLR_RECB-@VLR_BAIXA
WHERE
	CD_FND_VERBA = @CD_FND_VERBA

PRINT 'Alteracao saldo da duplicata'
UPDATE
	RC_DEB
SET 
	 SLD_DP=SLD_DP+@VLR_BAIXA
WHERE
	CD_EMP=@CD_EMP
	AND CD_FILIAL = @CD_FILIAL
	AND CD_RC_DEB = @CD_RC_DEB
end
