/****** Object:  View [dbo].[V_EST_NF_SAI_IT]    Script Date: 22/01/2015 18:08:26 ******/
IF EXISTS(SELECT * FROM SYS.OBJECTS WHERE NAME ='V_EST_NF_SAI_IT' AND TYPE = 'V')
BEGIN
	DROP VIEW [dbo].[V_EST_NF_SAI_IT]
END
GO
GO
CREATE VIEW [dbo].[V_EST_NF_SAI_IT]
AS
SELECT     
	EST_NF_SAI.CD_EMP, 
	EST_NF_SAI.CD_FILIAL, 
	EST_NF_SAI.CD_NF, 
	EST_NF_SAI.DT_EMI_NF, 
	EST_NF_SAI_IT.CD_PROD, 
    EST_NF_SAI_IT.QT_IT, 
	EST_NF_SAI_IT.VLR_IT,
	EST_NF_SAI_IT.VLR_TOT_IT,
	EST_NF_SAI.STS_NF,
	GLB_MOV_OP.TP_MOV_OP_TRANSA, 
	GLB_MOV_OP.TP_MOV, 
	GLB_MOV_OP.ATU_EST, 
	GLB_MOV_OP.ATU_EST_FLUT,
	EST_TRIB.CD_TRIB_FC,
	CASE WHEN ISNULL(PDV_VD_EST_NF_SAI.CD_NF,0) =0 THEN 0 ELSE 1 END AS FLAG_NF_CUPOM,
	EST_NF_SAI_IT.UN,
	GLB_NT_OP.CD_NT_OP_FC,
EST_NF_SAI_IT.PERC_IPI,
	EST_PROD.NR_NCM,
	EST_NF_SAI_IT.PERC_REDU_BASE_ICMS,
	EST_NF_SAI_IT.ALIQ_ICMS_INTERNO,
	ISNULL(EST_NF_SAI_IT.VLR_BASE_PIS, 0) AS VLR_BASE_PIS,     
	ISNULL(EST_NF_SAI_IT.VLR_PIS, 0) AS VLR_PIS,     
	ISNULL(EST_NF_SAI_IT.PERC_ALIQ_PIS, 0) AS PERC_ALIQ_PIS,     
	ISNULL(EST_NF_SAI_IT.VLR_BASE_COFINS, 0) AS VLR_BASE_COFINS,     
	ISNULL(EST_NF_SAI_IT.VLR_COFINS, 0) AS VLR_COFINS,     
	ISNULL(EST_NF_SAI_IT.PERC_ALIQ_COFINS, 0) AS PERC_ALIQ_COFINS,
	ISNULL(EST_NF_SAI_IT.CST_PIS, 0) AS CST_PIS,      
	ISNULL(EST_NF_SAI_IT.CST_COFINS, 0) AS CST_COFINS,
	ISNULL(EST_NF_SAI_IT.VLR_PROD_FRETE,0) AS VLR_FRETE_IT,
	ISNULL(EST_NF_SAI_IT.VLR_OUTROS_DESPESAS,0) AS  VLR_OUTRAS_DESPESAS,
	0 AS VLR_DESC_FINAN,
	ISNULL(EST_NF_SAI_IT.VLR_DESC_IT,0) AS  VLR_DESC,
	ISNULL(EST_NF_SAI_IT.VLR_BASE_ICMS_IT,0) AS  VLR_BASE_ICMS,
	ISNULL(EST_NF_SAI_IT.ALIQ_ICMS,0) AS  ALIQ_ICMS,
	ROUND(ISNULL((EST_NF_SAI_IT.VLR_TOT_IT - dbo.EST_NF_SAI_IT.VLR_DESC_IT) * EST_NF_SAI_IT.PERC_IPI, 0)/100,2) AS VLR_IPI,
	EST_NF_SAI_IT.PERC_IVA,
	EST_NF_SAI_IT.VLR_ICMS_IT,
	EST_NF_SAI_IT.VLR_ICMS_SUBS,
	EST_NF_SAI_IT.VLR_CUSTO_MD AS VLR_CUSTO_IT
FROM         
	EST_NF_SAI INNER JOIN EST_NF_SAI_IT ON 
	EST_NF_SAI.CD_EMP = EST_NF_SAI_IT.CD_EMP AND 
    EST_NF_SAI.CD_FILIAL = EST_NF_SAI_IT.CD_FILIAL AND 
	EST_NF_SAI.CD_NF = EST_NF_SAI_IT.CD_NF
	INNER JOIN GLB_MOV_OP ON 
	EST_NF_SAI.CD_NT_MOV = GLB_MOV_OP.CD_MOV_OP
	INNER JOIN EST_TRIB ON
	EST_NF_SAI_IT.CD_TRIB = EST_TRIB.CD_TRIB
	LEFT OUTER JOIN PDV_VD_EST_NF_SAI ON
	EST_NF_SAI_IT.CD_EMP = PDV_VD_EST_NF_SAI.CD_EMP AND
	EST_NF_SAI_IT.CD_FILIAL = PDV_VD_EST_NF_SAI.CD_FILIAL AND
	EST_NF_SAI_IT.CD_NF = PDV_VD_EST_NF_SAI.CD_NF 
	INNER JOIN GLB_NT_OP ON 
	EST_NF_SAI_IT.CD_NT_OP = GLB_NT_OP.CD_NT_OP 
    INNER JOIN DBO.EST_PROD ON 
    EST_PROD.CD_EMP = EST_NF_SAI_IT.CD_EMP AND 
    EST_PROD.CD_PROD = EST_NF_SAI_IT.CD_PROD