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

CREATE PROCEDURE [dbo].[P_LOCALIZA_BAIXA](
	@CD_CTR_PGTO    VARCHAR(32),
    @IS_PROTOCOLO   TINYINT = 0)	

AS 

IF @IS_PROTOCOLO = 1
BEGIN
	SET @CD_CTR_PGTO = ISNULL ((SELECT CD_CTR_PGTO FROM RC_PGTO_PDV WHERE PROT_ATEND = DBO.MD5(@CD_CTR_PGTO)), 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 RCFP.CD_CTR_PGTO = @CD_CTR_PGTO 

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(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 RCFP.CD_CTR_PGTO = @CD_CTR_PGTO 


