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

create view V_EQUALS_AUDTI_PGTO
as
select
    pdv_Vd_tef.CD_EMP, 
    pdv_Vd_tef.CD_FILIAL, 
    pdv_Vd_tef.CD_VD, 
    pdv_Vd_tef.CD_CTR,
    pdv_vd.nr_ecf,
    pdv_vd.cd_cx,
    pdv_vd.dt_vd,
    pdv_Vd_tef.NR_AUTORIZACAO,
    pdv_Vd_tef.NSU_SITEF,
    pdv_Vd_tef.VL_CARTAO,
    (CASE WHEN ISNULL(V_EQUALS_FINAL.CD_CTR_PDV_VD_TEF,0)=0 THEN
	   'NÃO'
    ELSE
	   'SIM'
    END) AS VENDA_CONCILIADA,
    ISNULL(V_EQUALS_FINAL.IDT_LOTE_REDE,0) AS IDT_LOTE_REDE
    ,'CUPOM FISCAL'  AS TP_DOCUMENTO
from 
    pdv_vd inner join pdv_Vd_tef on 
    pdv_vd.cd_emp = pdv_Vd_tef.cd_emp
    and pdv_vd.cd_filial = pdv_Vd_tef.cd_filial
    and pdv_vd.cd_vd = pdv_Vd_tef.cd_vd LEFT JOIN V_EQUALS_FINAL ON
    pdv_Vd_tef.CD_EMP= V_EQUALS_FINAL.CD_EMP
    AND pdv_Vd_tef.CD_FILIAL=V_EQUALS_FINAL.CD_FILIAL
    AND pdv_Vd_tef.CD_VD=V_EQUALS_FINAL.CD_VD
    AND pdv_Vd_tef.CD_CTR=V_EQUALS_FINAL.CD_CTR_PDV_VD_TEF

union all
select
    PDV_CUPOM_NAO_FISCAL.CD_EMP, 
    PDV_CUPOM_NAO_FISCAL.CD_FILIAL, 
    PDV_CUPOM_NAO_FISCAL_TEF.CD_CTR as CD_VD, 
    pdv_Vd_tef.CD_RECTO_TEF AS CD_CTR,
    PDV_CUPOM_NAO_FISCAL.NR_COO as nr_ecf,
    PDV_CUPOM_NAO_FISCAL.cd_cx,
    PDV_CUPOM_NAO_FISCAL.DT_CUPOM as dt_vd,
    pdv_Vd_tef.NR_AUTORIZACAO ,
    CAST(PDV_VD_TEF.NSU_SITEF AS BIGINT) AS NSU_SITEF,
    pdv_Vd_tef.VL_CARTAO,
    (CASE WHEN ISNULL(V_EQUALS_FINAL.CD_RECTO_TEF,0)=0 THEN
	   'NÃO'
    ELSE
	   'SIM'
    END) AS VENDA_CONCILIADA,
    ISNULL(V_EQUALS_FINAL.IDT_LOTE_REDE,0) AS IDT_LOTE_REDE 
    ,'CUPOM NÃO FISCAL'  AS TP_DOCUMENTO
from 


PDV_CUPOM_NAO_FISCAL
     INNER JOIN PDV_CUPOM_NAO_FISCAL_TEF ON PDV_CUPOM_NAO_FISCAL.CD_EMP = PDV_CUPOM_NAO_FISCAL_TEF.CD_EMP
                                            AND PDV_CUPOM_NAO_FISCAL.CD_FILIAL = PDV_CUPOM_NAO_FISCAL_TEF.CD_FILIAL
                                            AND PDV_CUPOM_NAO_FISCAL.CD_CTR = PDV_CUPOM_NAO_FISCAL_TEF.CD_CTR
     INNER JOIN PDV_RECBTO_TEF AS PDV_VD_TEF ON PDV_VD_TEF.CD_EMP = PDV_CUPOM_NAO_FISCAL_TEF.CD_EMP
                                                AND PDV_VD_TEF.CD_FILIAL = PDV_CUPOM_NAO_FISCAL_TEF.CD_FILIAL
                                                AND PDV_VD_TEF.CD_RECTO_TEF = PDV_CUPOM_NAO_FISCAL_TEF.CD_RECTO_TEF
												AND PDV_VD_TEF.VL_CARTAO > 0

    LEFT JOIN V_EQUALS_FINAL ON
	   pdv_Vd_tef.CD_EMP= V_EQUALS_FINAL.CD_EMP
	   AND pdv_Vd_tef.CD_FILIAL=V_EQUALS_FINAL.CD_FILIAL
	   AND pdv_Vd_tef.CD_RECTO_TEF=V_EQUALS_FINAL.CD_RECTO_TEF
