IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[V_EST_NF_ENT_DANFE_PROVISORIO_ITENS_VALIDACAO_IMPOSTO_ETAPAS]'))
DROP VIEW V_EST_NF_ENT_DANFE_PROVISORIO_ITENS_VALIDACAO_IMPOSTO_ETAPAS
GO
GO
--SELECT * FROM V_EST_NF_ENT_DANFE_PROVISORIO_ITENS_VALIDACAO_IMPOSTO_ETAPAS WHERE CD_CTR = 851
CREATE VIEW V_EST_NF_ENT_DANFE_PROVISORIO_ITENS_VALIDACAO_IMPOSTO_ETAPAS AS
SELECT
	I.CD_CTR,
	I.CD_CTR_IT,
	CASE WHEN IVP.CD_CTR IS NULL THEN
		CASE WHEN IV.CD_CTR IS NULL THEN
			'SIM'
		ELSE
			'NAO'
		END 
	ELSE
		'PENDENTE'
	END AS ERRO_VALORES_XML_VERSUS_CADASTRO,
	CASE WHEN ISNULL((SELECT 
		TOP 1 ERR.CD_CTR 
     FROM 
		EST_NF_ENT_DANFE_PROVISORIO_ITENS_VALIDACAO_IMPOSTO_ERROS_VALIDACAO ERR 
     WHERE 
		ERR.CD_CTR=I.CD_CTR),0) > 0 THEN
	    'SIM'
	 ELSE
	    'NAO'
	 END AS ERRO_PARAMETRO_XML_VERSUS_CADASTRO,

	CASE WHEN IVP.CD_CTR IS NULL THEN
		'NAO'
	ELSE
		'SIM'
	END AS PENDENTE_XML_VERSUS_CADASTRO
FROM 
	EST_NF_ENT_DANFE_PROVISORIO_ITENS I LEFT OUTER JOIN EST_NF_ENT_DANFE_PROVISORIO_ITENS_VALIDACAO_IMPOSTO_PENDENTE IVP ON
	I.CD_CTR=IVP.CD_CTR AND
	I.CD_CTR_IT=IVP.CD_CTR_IT 
	LEFT OUTER JOIN  EST_NF_ENT_DANFE_PROVISORIO_ITENS_VALIDACAO_IMPOSTO IV ON
	I.CD_CTR=IV.CD_CTR AND
	I.CD_CTR_IT=IV.CD_CTR_IT AND
	I.VLR_PROD_UNIT=IV.VLR_PROD_UNIT AND 
	I.PERC_PROD_DESC = ROUND(IV.PERC_PROD_DESC,2) AND
	I.VLR_PROD_TOTAL = ROUND(IV.VLR_PROD_TOTAL,2) AND
	I.VLR_PROD_BASE_ICMS = ROUND(IV.VLR_PROD_BASE_ICMS,2) AND 
	I.VLR_PROD_ICMS = ROUND(IV.VLR_PROD_ICMS,2) AND
	I.VLR_PROD_BASE_IPI = ROUND(IV.VLR_PROD_BASE_IPI,2) AND 
	I.VLR_PROD_IPI = ROUND(IV.VLR_PROD_IPI,2) AND  
	I.PERC_PROD_IPI = ROUND(IV.PERC_PROD_IPI,2) AND 
	I.PERC_PROD_ICMS= ROUND(I.PERC_PROD_ICMS,2) AND
	I.VLR_PROD_PMC = ROUND(IV.VLR_PROD_PMC,2) AND
	I.VLR_PROD_BASE_ST = ROUND(IV.VLR_PROD_BASE_ST,2) AND 
	I.VLR_PROD_ICMS_ST = ROUND(IV.VLR_PROD_ICMS_ST,2) AND 
	
	
	I.PERC_PROD_RED_BASE_ICMS = CASE WHEN ROUND(IV.PERC_PROD_RED_BASE_ICMS,2)>0 THEN
									(100.00 - ROUND(IV.PERC_PROD_RED_BASE_ICMS,2)) 
								ELSE
									0 
								END AND

	I.PERC_PROD_RED_BASE_ST = CASE WHEN ROUND(IV.PERC_PROD_RED_BASE_ST,2)>0 THEN
									(100.00 - ROUND(IV.PERC_PROD_RED_BASE_ST,2)) 
							   ELSE
									0 
								END AND	
	I.PERC_PROD_ICMS_ST = ROUND(IV.PERC_PROD_ICMS_ST,2) AND
	I.VLR_PROD_FRETE = ROUND(IV.VLR_PROD_FRETE,2) AND
	I.QTDE_PROD = IV.QTDE_PROD AND
	I.VLR_PROD_DESC = ROUND(IV.VLR_PROD_DESC,2) AND
	I.VLR_CRED_BASE_SN = ROUND(IV.VLR_CRED_BASE_SN,2) AND
	I.VLR_CRED_ICMS_SN = ROUND(IV.VLR_CRED_ICMS_SN,2) AND
	I.PERC_CRED_ICMS_SIMPLES = ROUND(IV.PERC_CRED_ICMS_SIMPLES,2) AND
	I.VLR_CRED_ICMS_SIMPLES = ROUND(IV.VLR_CRED_ICMS_SIMPLES,2) AND
	I.VLR_OUTRAS_DESPESAS = ROUND(IV.VLR_OUTRAS_DESPESAS,2) AND
	ISNULL(I.PERC_DESC_FINAN,0) = ROUND(IV.PERC_DESC_FINAN,2) AND
	ISNULL(I.VLR_DESC_FINAN,0) = ROUND(IV.VLR_DESC_FINAN,2)
