IF OBJECT_ID('dbo.V_RECBTOS_DIV_PIX', 'V') IS NOT NULL
    DROP VIEW dbo.V_RECBTOS_DIV_PIX
GO

CREATE VIEW dbo.V_RECBTOS_DIV_PIX
AS
SELECT 
    T.CD_EMP,
    T.CD_FILIAL,
    C.CD_CTR,
    C.DT_CUPOM,
    CASE 
        WHEN C.TP_CUPOM_NAO_FISCAL = 1 THEN 0
        WHEN C.TP_CUPOM_NAO_FISCAL = 10 
            THEN T.VL_CARTAO - ISNULL(C.VLR_TOT_CUPOM, 0)
        ELSE T.VL_CARTAO
    END AS VL_CARTAO,
    A.TP_ADM,
    C.ST_CUPOM,
    C.CD_CX,
	ISNULL(C.CD_USU,0) AS CD_USU 
FROM DBO.PDV_RECBTO_TEF T WITH (NOLOCK)
INNER JOIN DBO.PDV_CUPOM_NAO_FISCAL_TEF CT WITH (NOLOCK)
    ON T.CD_EMP = CT.CD_EMP
    AND T.CD_FILIAL = CT.CD_FILIAL
    AND T.CD_RECTO_TEF = CT.CD_RECTO_TEF
INNER JOIN DBO.PDV_CUPOM_NAO_FISCAL C WITH (NOLOCK)
    ON CT.CD_EMP = C.CD_EMP
    AND CT.CD_FILIAL = C.CD_FILIAL
    AND CT.CD_CTR = C.CD_CTR
INNER JOIN DBO.RC_ADM_CARTAO A WITH (NOLOCK)
    ON T.CD_EMP = A.CD_EMP
    AND T.CD_ADM_CARTAO = A.CD_ADM_CARTAO
LEFT JOIN DBO.RC_ADM_CARTAO_RC_CLI AC WITH (NOLOCK)
    ON A.CD_EMP = AC.CD_EMP
    AND A.CD_ADM_CARTAO = AC.CD_ADM_CARTAO
LEFT JOIN DBO.RC_CLI CLI WITH (NOLOCK)
    ON AC.CD_EMP = CLI.CD_EMP
    AND AC.CD_CLI = CLI.CD_CLI
WHERE 
    T.VL_CARTAO > 0
    AND C.ST_CUPOM = 0
    AND A.TP_ADM = 7
    AND T.CD_ADM_CARTAO > 0
    AND T.ST_TRN = 0
GO