/****** Object:  View [dbo].[V_EST_PROD]    Script Date: 04/11/2013 10:05:53 ******/
IF EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[V_RC_DEB_CONV_BLOQUEIO]'))
	DROP VIEW [dbo].[V_RC_DEB_CONV_BLOQUEIO]
GO
--select * from V_RC_DEB_CONV_BLOQUEIO WHERE CD_CLI = 435
CREATE VIEW [dbo].[V_RC_DEB_CONV_BLOQUEIO]
AS
SELECT 
	RC_DEB.CD_CLI, 
	-- ACHO QUE DEVE SER AQUI, SE  DIAS_CAREN_ATRASO MAIOR QUE 0 
	CASE WHEN ISNULL(RC_MDL_VENDA.DIAS_CAREN_ATRASO,0) > 0 THEN
		DATEADD(DAY, RC_MDL_VENDA.DIAS_CAREN_ATRASO, (dateadd(day,DIAS_BLOQ_ATRASO,RC_DEB.DT_VENCTO)))
	 ELSE
		dateadd(day,DIAS_BLOQ_ATRASO,RC_DEB.DT_VENCTO )
	END AS DT_LIMITE,
	RC_DEB.DT_VENCTO,
	CONVERT(DATE,GETDATE()) AS DT_ATUAL,
	datediff(day,RC_DEB.DT_VENCTO,CONVERT(DATE,GETDATE()) ) as DIAS_ATRASO,
	CONV.CD_CONV,
	RC_DEB.CD_FILIAL,
	RC_DEB.NR_DP,
	RC_DEB.CD_RC_DEB,
	ISNULL(RC_MDL_VENDA.DIAS_BLOQ_ATRASO,0) DIAS_BLOQ_ATRASO,
	ISNULL(DIAS_CAREN_ATRASO,0) AS DIAS_CAREN_ATRASO
	
FROM RC_DEB INNER JOIN RC_DEB_RC_CLI_CONV ON 
	RC_DEB.CD_EMP = RC_DEB_RC_CLI_CONV.CD_EMP AND 
	RC_DEB.CD_FILIAL = RC_DEB_RC_CLI_CONV.CD_FILIAL AND
	RC_DEB.CD_RC_DEB = RC_DEB_RC_CLI_CONV.CD_RC_DEB
	
	INNER JOIN RC_CLI_CONV CONV ON
	CONV.CD_EMP=RC_DEB.CD_EMP AND
	CONV.CD_CLI=RC_DEB.CD_CLI

	INNER JOIN RC_MDL_VENDA ON 
	RC_MDL_VENDA.CD_EMP = CONV.CD_EMP AND 
    RC_MDL_VENDA.CD_MDL_VD = CONV.CD_MDL_VD

WHERE 
	(RC_DEB.CD_EMP = 1) 
	AND (RC_DEB.STS_DP IN (0, 2)) 
	AND (RC_DEB.SLD_DP > 0) 
