PRINT '> NFE - SCRIPT #0017';

IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[V_NFE_PENDENTE_AUTENTICACAO]'))
DROP VIEW [dbo].[V_NFE_PENDENTE_AUTENTICACAO]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE VIEW [dbo].[V_NFE_PENDENTE_AUTENTICACAO]
AS
	SELECT 
		TOP 20 
		FILIAL.CD_FILIAL
		, REPLACE(REPLACE(REPLACE(FILIAL.CGC, '/', ''), '-', ''), '.', '') AS CNPJ 
		, VLD.NR_AUTORIZADOR 
		, VLD.CD_CTR 
		, VLD.CD_FORN AS PROV 
		, OP.DEST_ORIG 
		, ENT.NR_NF ENT_NR_NF
		, VLD.NR_NF VALID_NR_NF
		, (CASE OP.DEST_ORIG 
				WHEN 0 THEN (SELECT CID.UF FROM RC_CLI REME INNER JOIN GLB_CID CID ON REME.CD_CID = CID.CD_CID WHERE REME.CD_CLI = VLD.CD_FORN) 
				WHEN 1 THEN (SELECT CID.UF FROM PG_FORN	REME INNER JOIN GLB_CID CID ON REME.CD_CID = CID.CD_CID WHERE REME.CD_FORN = VLD.CD_FORN) 
				WHEN 2 THEN (SELECT CID.UF FROM PRC_FILIAL REME INNER JOIN GLB_CID CID ON REME.CD_CID = CID.CD_CID WHERE REME.CD_FILIAL = VLD.CD_FORN) 
				ELSE (SELECT CID.UF FROM PG_FORN REME INNER JOIN GLB_CID CID ON REME.CD_CID = CID.CD_CID WHERE REME.CD_FORN = VLD.CD_FORN) 
			END) UF
	FROM
		EST_NF_ENT_NFE_FORN_VALID_PENDENTE PEND 
	INNER JOIN EST_NF_ENT_NFE_FORN_VALID VLD ON
		VLD.CD_CTR = PEND.CD_CTR
	INNER JOIN PRC_FILIAL FILIAL ON
			FILIAL.CD_EMP = VLD.CD_EMP
		AND FILIAL.CD_FILIAL = VLD.CD_FILIAL
		AND FILIAL.FLAG_VALIDAR_NOTA_ENTRADA_FORN = 1
	LEFT JOIN EST_NF_ENT_DANFE_PROVISORIO PRO ON
		PRO.CD_CTR = VLD.CD_CTR
	LEFT JOIN EST_NF_ENT ENT ON
			ENT.CD_EMP = PRO.CD_EMP
		AND ENT.CD_FILIAL = PRO.CD_FILIAL
		AND ENT.NR_NF = PRO.NR_NF
	LEFT JOIN GLB_MOV_OP OP ON
		OP.CD_MOV_OP = ENT.CD_NT_MOV

GO

PRINT '    < [OK]';

	