/****** Object:  View [dbo].[V_EST_NF_ENT_DANFE_PROVISORIO_ETAPAS]    Script Date: 07/04/2013 16:57:47 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[V_EST_NF_ENT_DANFE_PROVISORIO_ETAPAS]'))
DROP VIEW [dbo].[V_EST_NF_ENT_DANFE_PROVISORIO_ETAPAS]
GO
GO
GO
GO

--SELECT TOP 100 * FROM V_EST_NF_ENT_DANFE_PROVISORIO_ETAPAS WHERE (PENDENTE > 0 AND CHECKIN > 0 AND LIB > 0 AND ERROS = 0) OR FLAG_LIBERA_ENTRADA_SEM_PEDIDO > 1

CREATE VIEW [dbo].[V_EST_NF_ENT_DANFE_PROVISORIO_ETAPAS] AS
SELECT 
	E.CD_CTR,
	E.CD_EMP,
	E.CD_FILIAL,
	E.CD_FORN,
	E.NR_NF,
	E.VLR_NF,
	E.DT_EMIS_NF,
	E.DT_CAD,
	E.CD_PED_FORN,
    ISNULL(D_PROV_CHK.CD_CTR,0) AS CHECKIN,
	ISNULL(D_PROV_BLQ.CD_CTR,0) AS BLQ,
	CASE WHEN ISNULL(D_PROV_BLQ.CD_CTR,0) = 0 THEN
		 ISNULL(D_PROV_LIB.CD_CTR,1) 
	ELSE
		e.FLAG_LIBERA_ENTRADA_SEM_PEDIDO
	END AS LIB,
	ISNULL(D_PROV_PEND.CD_CTR,0) AS PENDENTE,
	ISNULL(D_PROV_ENTRADA.CD_CTR,0) AS ENTRADA,
	ISNULL(D_PROV_ERROS.CD_CTR,0) AS ERROS,
	ISNULL(GLB_MOV_OP.FLAG_NAO_REALIZAR_PROC_AUTOMATICO,0) AS FLAG_NAO_REALIZAR_PROC_AUTOMATICO,
	ISNULL(e.FLAG_LIBERA_ENTRADA_SEM_PEDIDO,0) FLAG_LIBERA_ENTRADA_SEM_PEDIDO
FROM 
    EST_NF_ENT_DANFE_PROVISORIO e
	LEFT OUTER JOIN EST_NF_ENT_DANFE_PROVISORIO_CHECKIN_ENTRADA D_PROV_CHK ON
	E.CD_CTR = D_PROV_CHK.CD_CTR 
	AND  D_PROV_CHK.DT_CAD > '20180901'
	LEFT OUTER JOIN V_EST_NF_ENT_DANFE_PROVISORIO_BLOQUEIO_PENDENTE D_PROV_BLQ ON
	E.CD_CTR = D_PROV_BLQ.CD_CTR 
	LEFT OUTER JOIN EST_NF_ENT_DANFE_PROVISORIO_LIBERACAO D_PROV_LIB ON
	E.CD_CTR = D_PROV_LIB.CD_CTR 
	LEFT OUTER JOIN EST_NF_ENT_DANFE_PROVISORIO_PENDENTE D_PROV_PEND ON
    E.CD_CTR = D_PROV_PEND.CD_CTR 
	LEFT OUTER JOIN EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT D_PROV_ENTRADA ON
    E.CD_CTR = D_PROV_ENTRADA.CD_CTR 
	LEFT OUTER JOIN EST_NF_ENT_DANFE_PROVISORIO_ERROS_VALIDACAO D_PROV_ERROS ON
    E.CD_CTR = D_PROV_ERROS.CD_CTR AND
	0 = D_PROV_ERROS.STS_ERRO
	INNER JOIN PRC_FILIAL ON
	E.CD_EMP = PRC_FILIAL.CD_EMP AND
	E.CD_FILIAL = PRC_FILIAL.CD_FILIAL
	LEFT OUTER JOIN GLB_MOV_OP ON
	E.CD_MOV_OP = GLB_MOV_OP.CD_MOV_OP
WHERE
	PRC_FILIAL.FLAG_NOTA_FISCAL_ENTRADA_AUTOMATICA = 1
	AND E.DT_CAD > '20180901'
	AND E.CD_EMP= 1
	AND E.CD_FILIAL > 0 
GO


