IF EXISTS ( SELECT NAME FROM SYS.OBJECTS WHERE NAME = 'V_CUPOMFISCAL_ITEM')
BEGIN
	DROP VIEW V_CUPOMFISCAL_ITEM
END
GO

CREATE VIEW V_CUPOMFISCAL_ITEM
AS
SELECT  VD.CD_EMP,VD.CD_FILIAL,VD.DT_VD,VD.CD_CX,VD.CD_VD,VD.NR_ECF, VD.ST_VD
        ,IT.CD_IT,IT.CD_PROD,PROD.DS_PROD,EAN.CD_BARRA,NR_NCM
        ,IT.QT_IT,IT.VLR_IT,IT.TOT_IT,IT.ST_IT,IT.TIPO_DESCONTO
        ,COALESCE(IT.TX_DESC,0) AS TX_DESC
        ,COALESCE(IT.VLR_DESC_VERBA,0) AS VLR_DESC_VERBA
        ,COALESCE(IT.VLR_DESC_TOT_RAT,0) AS VLR_DESC_RATEIO
	,IT.CD_TRIB_FC,IT.TX_ICMS_IT,IT.TX_RED_IT
        ,IT.CD_VEND,VENDEDOR.NM_FUN AS NM_VEND
        ,IT.CD_VEND_VERBA,AUTR_VERBA.NM_FUN AS NM_VEND_VERBA
        ,IT.CD_USU_CANCEL,USU_CANCEL.NM_USU AS NM_USU_CANCEL
        ,PONTOS.QTDE_PONTO_FIDEL AS QT_PONTOS_FIDEL
        ,IT.CD_GRP_COMIS AS CD_GRUPO_COMISSAO,NULLIF(IT.ST_IT,1) AS IS_CANCELADO
        ,COALESCE(REC.CD_MEDICO_REC, 0) AS CD_MEDICO_REC, COALESCE(LOTE.CD_LOTE, 0) AS CD_LOTE, 0 AS NUMERO_LOTE
        ,COALESCE(LOTE.QTDE_PROD, 0) AS QTDE_PROD_LOTE, 0 AS REGISTROALTERADOITEM
        ,COALESCE(IT.TIPO_IMPOSTO,0) AS TIPO_IMPOSTO
        ,COALESCE(IT.VALOR_IBPT, 0) AS VALOR_IBPT_ITEM, COALESCE(IT.PERC_IBPT, 0) AS PERCENTUAL_IBPT_ITEM
        ,IT.PIS_COFINS,IT.TIPO_TRIBUTACAO_PIS_COFINS
        ,IT.CST_PIS,IT.VLR_BASE_PIS,IT.PERC_ALIQ_PIS,IT.VLR_PIS
        ,IT.VLR_COFINS,IT.PERC_ALIQ_COFINS,IT.VLR_BASE_COFINS,IT.CST_COFINS
        ,IT.NR_PROTOCOLO_MANIPULADO
FROM    PDV_VD VD
INNER   JOIN PDV_VD_IT IT ON IT.CD_EMP = VD.CD_EMP AND IT.CD_FILIAL = VD.CD_FILIAL AND IT.CD_VD = VD.CD_VD AND VD.DT_VD = IT.DT_VD
LEFT    JOIN EST_PROD PROD ON PROD.CD_EMP = IT.CD_EMP AND PROD.CD_PROD = IT.CD_PROD
LEFT    JOIN EST_PROD_CD_BARRA EAN ON PROD.CD_EMP = EAN.CD_EMP AND PROD.CD_PROD = EAN.CD_PROD
LEFT	JOIN FP_FUNC VENDEDOR ON  IT.CD_EMP = VENDEDOR.CD_EMP AND IT.CD_VEND = VENDEDOR.CD_FUN
LEFT	JOIN FP_FUNC AUTR_VERBA ON  IT.CD_EMP = AUTR_VERBA.CD_EMP AND IT.CD_VEND_VERBA = AUTR_VERBA.CD_FUN
LEFT 	JOIN GLB_USU USU_CANCEL ON  IT.CD_USU_CANCEL = USU_CANCEL.CD_USU
LEFT    JOIN PDV_VD_IT_FIDELI_CARTAO PONTOS ON IT.CD_EMP = PONTOS.CD_EMP AND IT.CD_FILIAL = PONTOS.CD_FILIAL AND IT.CD_VD = PONTOS.CD_VD AND IT.CD_IT = PONTOS.CD_IT
LEFT	JOIN EST_ORC_GLB_MEDICO REC ON VD.NR_ORC = REC.NR_ORC AND PROD.CD_PROD = REC.CD_PROD AND VD.CD_EMP = REC.CD_EMP AND VD.CD_FILIAL = REC.CD_FILIAL
LEFT    JOIN PDV_VD_IT_LOTE LOTE ON IT.CD_EMP = LOTE.CD_EMP AND IT.CD_FILIAL = LOTE.CD_FILIAL AND VD.CD_VD = LOTE.CD_VD AND IT.CD_IT = LOTE.CD_IT