IF  EXISTS (SELECT * FROM SYS.VIEWS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[V_PAINEL_NFE_EST_NF_SAI_CANCEL_PENDENCIA_ANALITICO]'))
DROP VIEW [DBO].[V_PAINEL_NFE_EST_NF_SAI_CANCEL_PENDENCIA_ANALITICO]    
GO
  
--SELECT * FROM V_PAINEL_NFE_EST_NF_SAI_CANCEL_PENDENCIA_ANALITICO
CREATE VIEW V_PAINEL_NFE_EST_NF_SAI_CANCEL_PENDENCIA_ANALITICO
AS
SELECT
    V_EST_NF_SAI_CAB.CD_FILIAL,
	V_EST_NF_SAI_CAB.NF_NF,
	V_EST_NF_SAI_CAB.NM_DEST,
	V_EST_NF_SAI_CAB.NR_AUTORIZADOR,
	V_EST_NF_SAI_CAB.NR_PROTOCOLO,
	EST_NF_SAI_CANCEL.DT_CANCEL,
	'CANCELAMENTO TRANSACAO' AS TIPO_TRANSACAO
FROM
	V_EST_NF_SAI_CAB INNER JOIN EST_NF_SAI_CANCEL ON
	V_EST_NF_SAI_CAB.CD_EMP = EST_NF_SAI_CANCEL.CD_EMP AND
	V_EST_NF_SAI_CAB.CD_FILIAL = EST_NF_SAI_CANCEL.CD_FILIAL AND
	V_EST_NF_SAI_CAB.CD_NF = EST_NF_SAI_CANCEL.CD_NF 
	INNER JOIN EST_NF_SAI_NFE_CANCEL_PEND ON
	V_EST_NF_SAI_CAB.CD_EMP = EST_NF_SAI_NFE_CANCEL_PEND.CD_EMP AND
	V_EST_NF_SAI_CAB.CD_FILIAL = EST_NF_SAI_NFE_CANCEL_PEND.CD_FILIAL AND
	V_EST_NF_SAI_CAB.CD_NF = EST_NF_SAI_NFE_CANCEL_PEND.CD_NF
	LEFT OUTER JOIN EST_NF_SAI_NFE_CANCEL_ERR ON
	V_EST_NF_SAI_CAB.CD_EMP = EST_NF_SAI_NFE_CANCEL_ERR.CD_EMP AND
	V_EST_NF_SAI_CAB.CD_FILIAL = EST_NF_SAI_NFE_CANCEL_ERR.CD_FILIAL AND
	V_EST_NF_SAI_CAB.CD_NF = EST_NF_SAI_NFE_CANCEL_ERR.CD_NF 
WHERE
	EST_NF_SAI_NFE_CANCEL_ERR.CD_NF IS NULL 
	AND EST_NF_SAI_NFE_CANCEL_PEND.PEND_SOLUC=1   
UNION ALL
SELECT
    EST_NF_NFE_INU.CD_FILIAL,
	EST_NF_NFE_INU.NR_NF,
	ISNULL(V_EST_NF_SAI_CAB.NM_DEST,'') AS NM_DEST,
	'',
	'',
	EST_NF_NFE_INU.DT_CAD,
	'INUTILIZACAO' AS TIPO_TRANSACAO
FROM
	EST_NF_NFE_INU INNER JOIN EST_NF_NFE_INU_PEND ON
	EST_NF_NFE_INU.CD_INU = EST_NF_NFE_INU_PEND.CD_INU
	LEFT OUTER JOIN EST_NF_SAI_EST_NF_NFE_INU ON
	EST_NF_NFE_INU.CD_INU = EST_NF_SAI_EST_NF_NFE_INU.CD_INU
	LEFT OUTER JOIN V_EST_NF_SAI_CAB ON
	EST_NF_SAI_EST_NF_NFE_INU.CD_EMP = V_EST_NF_SAI_CAB.CD_EMP AND
	EST_NF_SAI_EST_NF_NFE_INU.CD_FILIAL = V_EST_NF_SAI_CAB.CD_FILIAL AND
	EST_NF_SAI_EST_NF_NFE_INU.CD_NF = V_EST_NF_SAI_CAB.CD_NF 
WHERE
	EST_NF_NFE_INU_PEND.PEND_SOLUC=1
