IF  EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[P_LOCALIZA_BAIXA_CLIENTE]') AND TYPE IN (N'P', N'PC'))
DROP PROCEDURE [DBO].[P_LOCALIZA_BAIXA_CLIENTE]
GO
 
--- PARÂMETRO CÓDIGO DE CLIENTE, DOS ÚLTIMOS 30 DIAS
--- RC_PGTO_PDV


CREATE PROCEDURE [DBO].[P_LOCALIZA_BAIXA_CLIENTE](
	@CD_CLI   INT,
    @IS_PROTOCOLO   TINYINT = 0)	

AS 

DECLARE @DATA DATE
SET @DATA = (SELECT CONVERT(VARCHAR(10), DATEADD(DD, -31, GETDATE()),120))

IF @IS_PROTOCOLO = 1
BEGIN
	SET @CD_CLI = ISNULL ((SELECT DISTINCT CD_CLI FROM RC_DEB WHERE CD_CLI =(@CD_CLI)), 0)
END
    
SELECT 
	RCFP.CD_CTR_PGTO ,
	RD.CD_CLI, RCL.RZ_CLI, RD.NR_DP, RCFP.DT_PGTO AS DT_PAG, 
	(RC.VL_PGTO + RC.VL_JUR) AS VL_PGTO, 
	GD.TP_DOC AS CD_DOC,
	RCFP.PROT_ATEND_NO_CRYPT
FROM RC_CRED RC INNER JOIN 	RC_PGTO_PDV_RC_CRED RCFPRC ON 
	RCFPRC.CD_EMP = RC.CD_EMP AND
	RCFPRC.CD_FILIAL = RC.CD_FILIAL AND
	RCFPRC.CD_RC_DEB = RC.CD_RC_DEB AND
	RCFPRC.CD_DP_LANC = RC.CD_DP_LANC 
	
	INNER JOIN 	RC_PGTO_PDV RCFP ON
	RCFP.CD_CTR_PGTO = RCFPRC.CD_CTR_PGTO 
	
	INNER JOIN 	RC_DEB RD ON 
	RD.CD_EMP = RC.CD_EMP AND
	RD.CD_FILIAL = RC.CD_FILIAL AND
	RD.CD_RC_DEB = RC.CD_RC_DEB  
	
	INNER JOIN 	RC_CLI RCL ON
	RCL.CD_CLI = RD.CD_CLI 
	
	INNER JOIN 	GLB_DOC GD ON
	RC.CD_DOC = GD.CD_DOC AND
	RC.CD_EMP = GD.CD_EMP

WHERE RD.CD_CLI = @CD_CLI 
	AND RC.DT_PAG > @DATA

UNION ALL

SELECT 
	RCFP.CD_CTR_PGTO ,RD.CD_CLI, RCL.RZ_CLI, RD.CD_CTR AS NR_DP, 
	RCFP.DT_PGTO, RC.VLR_CRED AS VL_PGTO, ISNULL(RC.CD_DOC, 1) AS CD_DOC,
	RCFP.PROT_ATEND_NO_CRYPT 
FROM RC_CREDIARIO_PARC_CRED RC INNER JOIN RC_PGTO_PDV_RC_CREDIARIO_PARC_CRED RCFPRC ON 
	RCFPRC.CD_CTR = RC.CD_CTR AND
	RCFPRC.CD_CTR_CRED = RC.CD_CTR_CRED 
	
	INNER JOIN 	RC_PGTO_PDV RCFP ON
	RCFP.CD_CTR_PGTO = RCFPRC.CD_CTR_PGTO 
	
	INNER JOIN RC_CREDIARIO_PARC RD ON 
	RD.CD_EMP = 1 AND
	RD.CD_CTR = RC.CD_CTR 
	
	INNER JOIN RC_CLI RCL ON
	RCL.CD_CLI = RD.CD_CLI 

WHERE RD.CD_CLI = @CD_CLI 
	AND RCFP.DT_PGTO > @DATA
