----------------------------
fCategoria
----------------------------


WITH PERIODOS AS (
    SELECT
        LEVEL AS ID_PERIODO,
        ADD_MONTHS(TRUNC(SYSDATE,'MM'), -(LEVEL-1)) AS MES_REF,
        ADD_MONTHS(TRUNC(SYSDATE,'MM'), -LEVEL) AS MES_ANALISE,
        ADD_MONTHS(
            TRUNC(ADD_MONTHS(TRUNC(SYSDATE,'MM'), -LEVEL), 'MM'),
            -11
        ) AS DATA_INICIO,
        LAST_DAY(
            ADD_MONTHS(TRUNC(SYSDATE,'MM'), -LEVEL)
        ) AS DATA_FIM
    FROM DUAL
    CONNECT BY LEVEL <= 12
),
PARAMETROS AS (
    SELECT 
        MAX(CASE WHEN NOME = 'CON_FREQUENCIACLIENTE' 
                 THEN VALOR END) AS CON_FREQUENCIACLIENTE,
        MAX(CASE WHEN NOME = 'CON_FATURAMENTOCATCLIENTE' 
                 THEN VALOR END) AS CON_FATURAMENTOCATCLIENTE
    FROM PCPARAMFILIAL
),
PARAM_CATEGORIA_TICKET AS (
    SELECT
        500 AS LIM_TICKET_VALOR,
        3   AS LIM_TICKET_FREQUENCIA
    FROM DUAL
),
FATURAMENTO AS (
    SELECT
        P.ID_PERIODO,
        NF.CODCLI,
        SUM(NF.VLATEND)    AS FATURAMENTO_BRUTO,
        SUM(NF.VLCUSTOFIN) AS CUSTO_BRUTO
    FROM VIEW_VENDAS_RESUMO_FATURAMENTO NF
    JOIN PERIODOS P
      ON NF.DTSAIDA BETWEEN P.DATA_INICIO AND P.DATA_FIM
    WHERE NF.CONDVENDA IN (1,7)
      AND NF.DTCANCEL IS NULL
    GROUP BY
        P.ID_PERIODO,
        NF.CODCLI
),
DEVOLUCAO AS (
    SELECT
        P.ID_PERIODO,
        DV.CODCLI,
        SUM(DV.VLDEVOLUCAO) AS DEVOLUCAO,
        SUM(DV.VLCMVDEVOL)  AS CUSTO_DEVOL
    FROM VIEW_DEVOL_RESUMO_FATURAMENTO DV
    JOIN PERIODOS P
      ON DV.DTENT BETWEEN P.DATA_INICIO AND P.DATA_FIM
    WHERE DV.DTCANCEL IS NULL
      AND DV.CONDVENDA IN (1,7)
    GROUP BY
        P.ID_PERIODO,
        DV.CODCLI
),
FREQUENCIA AS (
    SELECT
        P.ID_PERIODO,
        NF.CODCLI,
        COUNT(DISTINCT NF.NUMTRANSVENDA) AS FREQUENCIA
    FROM VIEW_VENDAS_RESUMO_FATURAMENTO NF
    JOIN PERIODOS P
      ON NF.DTSAIDA BETWEEN P.DATA_INICIO AND P.DATA_FIM
    WHERE NF.CONDVENDA IN (1,7)
      AND NF.DTCANCEL IS NULL
    GROUP BY
        P.ID_PERIODO,
        NF.CODCLI
),
FREQ_VENDEDOR AS (
    SELECT
        P.ID_PERIODO,
        NF.CODCLI,
        NF.CODUSUR AS CODVEND,
        COUNT(DISTINCT NF.NUMTRANSVENDA) AS FREQUENCIA_VENDEDOR
    FROM PCNFSAID NF
    JOIN PERIODOS P
      ON NF.DTSAIDA BETWEEN P.DATA_INICIO AND P.DATA_FIM
    WHERE NF.CONDVENDA IN (1,7)
      AND NF.DTCANCEL IS NULL
    GROUP BY
        P.ID_PERIODO,
        NF.CODCLI,
        NF.CODUSUR
),
VENDEDOR_PRINCIPAL AS (
    SELECT
        V.ID_PERIODO,
        V.CODCLI,
        V.CODVEND,
        U.NOME AS NOME_VENDEDOR,
        V.FREQUENCIA_VENDEDOR,
        ROW_NUMBER() OVER (
            PARTITION BY V.ID_PERIODO, V.CODCLI
            ORDER BY V.FREQUENCIA_VENDEDOR DESC
        ) AS RN
    FROM FREQ_VENDEDOR V
    LEFT JOIN PCUSUARI U
           ON U.CODUSUR = V.CODVEND
),
BASE AS (
    SELECT
        P.ID_PERIODO,
        TO_CHAR(P.MES_REF,'MM/YYYY') AS PERIODO_REFERENCIA,
        F.CODCLI,
        CLI.CLIENTE,
        CASE 
            WHEN CLI.TIPOFJ = 'F' THEN 'Física'
            WHEN CLI.TIPOFJ = 'J' THEN 'Jurídica'
            ELSE 'Não informado'
        END AS TIPO_PESSOA,
        NVL(FR.FREQUENCIA,0) AS FREQUENCIA,
        NVL(F.FATURAMENTO_BRUTO,0) AS FATURAMENTO_BRUTO,
        NVL(D.DEVOLUCAO,0) AS DEVOLUCAO,
        NVL(F.FATURAMENTO_BRUTO,0) - NVL(D.DEVOLUCAO,0) AS FATURAMENTO_LIQUIDO,
        NVL(F.CUSTO_BRUTO,0) - NVL(D.CUSTO_DEVOL,0)     AS CUSTO_LIQUIDO,
        ROUND(
            (
              (NVL(F.FATURAMENTO_BRUTO,0))
            - (NVL(F.CUSTO_BRUTO,0))
            )
            /
            NULLIF((NVL(F.FATURAMENTO_BRUTO,0)),0),
        4) AS PERCENT_MARGEM,
        ROUND(
            NVL(F.FATURAMENTO_BRUTO,0)
            /
            NULLIF(FR.FREQUENCIA,0),
        2) AS TICKET_MEDIO,
        VP.CODVEND              AS CODVEND_PRINCIPAL,
        VP.NOME_VENDEDOR        AS VENDEDOR_PRINCIPAL,
        VP.FREQUENCIA_VENDEDOR,
        ROUND(
            VP.FREQUENCIA_VENDEDOR
            /
            NULLIF(FR.FREQUENCIA,0),
        4) AS PERC_COMPRAS_VENDEDOR_PRINCIPAL,
        P2.CON_FATURAMENTOCATCLIENTE,
        P2.CON_FREQUENCIACLIENTE,
        PC.LIM_TICKET_VALOR,
        PC.LIM_TICKET_FREQUENCIA
    FROM PERIODOS P
    JOIN FATURAMENTO F       ON F.ID_PERIODO = P.ID_PERIODO
    JOIN PCCLIENT CLI        ON CLI.CODCLI = F.CODCLI
    LEFT JOIN DEVOLUCAO D    ON D.ID_PERIODO = F.ID_PERIODO AND D.CODCLI = F.CODCLI
    LEFT JOIN FREQUENCIA FR  ON FR.ID_PERIODO = F.ID_PERIODO AND FR.CODCLI = F.CODCLI
    LEFT JOIN VENDEDOR_PRINCIPAL VP
           ON VP.ID_PERIODO = F.ID_PERIODO
          AND VP.CODCLI     = F.CODCLI
          AND VP.RN = 1
    CROSS JOIN PARAMETROS P2
    CROSS JOIN PARAM_CATEGORIA_TICKET PC
)
SELECT
    ID_PERIODO,
    PERIODO_REFERENCIA,
    CODCLI,
    CLIENTE,
    TIPO_PESSOA,
    FREQUENCIA,
    FATURAMENTO_BRUTO,
    DEVOLUCAO,
    FATURAMENTO_LIQUIDO,
    CUSTO_LIQUIDO,
    TICKET_MEDIO,
    CODVEND_PRINCIPAL,
    VENDEDOR_PRINCIPAL,
    FREQUENCIA_VENDEDOR,
    PERC_COMPRAS_VENDEDOR_PRINCIPAL,
    CASE
        WHEN FATURAMENTO_LIQUIDO > CON_FATURAMENTOCATCLIENTE
         AND FREQUENCIA          > CON_FREQUENCIACLIENTE
        THEN 'DIAMANTE'
        WHEN FATURAMENTO_LIQUIDO > CON_FATURAMENTOCATCLIENTE
         AND FREQUENCIA          <=  CON_FREQUENCIACLIENTE
        THEN 'OURO'
        WHEN FATURAMENTO_LIQUIDO <=  CON_FATURAMENTOCATCLIENTE
         AND FREQUENCIA          > CON_FREQUENCIACLIENTE
        THEN 'PRATA'
        ELSE 'BRONZE'
    END AS CATEGORIA_FATURAMENTO,
    CASE
        WHEN TICKET_MEDIO > LIM_TICKET_VALOR
         AND FREQUENCIA   > LIM_TICKET_FREQUENCIA
        THEN 'DIAMANTE'
        WHEN TICKET_MEDIO > LIM_TICKET_VALOR
         AND FREQUENCIA   <=  LIM_TICKET_FREQUENCIA
        THEN 'OURO'
        WHEN TICKET_MEDIO <=  LIM_TICKET_VALOR
         AND FREQUENCIA   > LIM_TICKET_FREQUENCIA
        THEN 'PRATA'
        ELSE 'BRONZE'
    END AS CATEGORIA_TICKET,
    PERCENT_MARGEM
FROM BASE
WHERE CODCLI NOT IN (1,2)
ORDER BY
    ID_PERIODO,
    FATURAMENTO_LIQUIDO DESC;


--------------------------
fTopProdCli
--------------------------

WITH PERIODOS AS (
    SELECT
        LEVEL AS ID_PERIODO,
        ADD_MONTHS(TRUNC(SYSDATE,'MM'), -(LEVEL-1))              AS MES_REF,
        ADD_MONTHS(TRUNC(SYSDATE,'MM'), -(LEVEL+10))             AS DATA_INICIO,
        LAST_DAY(ADD_MONTHS(TRUNC(SYSDATE,'MM'), -(LEVEL-1)))    AS DATA_FIM
    FROM DUAL
    CONNECT BY LEVEL <= 12
),
ITENS_CLIENTE AS (
    SELECT
        P.ID_PERIODO,
        P.MES_REF,
        NF.CODCLI,
        M.CODPROD,
        PR.DESCRICAO AS PRODUTO,
        SUM(M.QT) AS QTD_VENDIDA,
        SUM(M.QT * M.PUNIT) AS FATURAMENTO_PRODUTO,
        SUM(M.QT * M.CUSTOFIN) AS CUSTO_PRODUTO
    FROM PCNFSAID NF
    JOIN PCMOV M
      ON M.NUMTRANSVENDA = NF.NUMTRANSVENDA
    JOIN PCPRODUT PR
      ON PR.CODPROD = M.CODPROD
    JOIN PERIODOS P
      ON NF.DTSAIDA BETWEEN P.DATA_INICIO AND P.DATA_FIM
    WHERE NF.CONDVENDA IN (1,7)
      AND NF.DTCANCEL IS NULL
      AND NF.CODCLI NOT IN (1,2)
    GROUP BY
        P.ID_PERIODO,
        P.MES_REF,
        NF.CODCLI,
        M.CODPROD,
        PR.DESCRICAO
),
DEVOLUCAO AS (
    SELECT 
        P.ID_PERIODO,
        DV.CODCLI,
        DV.CODPROD,
        SUM(DV.VLDEVOLUCAO) AS VLR_DEVOLUCAO
    FROM VIEW_DEVOL_RESUMO_FATURAMENTO DV
    JOIN PERIODOS P
      ON DV.DTENT BETWEEN P.DATA_INICIO AND P.DATA_FIM
    GROUP BY
        P.ID_PERIODO,
        DV.CODCLI,
        DV.CODPROD
),
BASE AS (
    SELECT 
        I.ID_PERIODO,
        I.MES_REF,
        I.CODCLI,
        I.CODPROD,
        I.PRODUTO,
        I.QTD_VENDIDA,
        I.FATURAMENTO_PRODUTO,
        I.CUSTO_PRODUTO,
        (I.FATURAMENTO_PRODUTO - NVL(D.VLR_DEVOLUCAO,0)) AS FATURAMENTO_LIQUIDO
    FROM ITENS_CLIENTE I
    LEFT JOIN DEVOLUCAO D
           ON D.ID_PERIODO = I.ID_PERIODO
          AND D.CODCLI    = I.CODCLI
          AND D.CODPROD   = I.CODPROD
),
BASE_FILTRADA AS (
    SELECT *
    FROM BASE
    WHERE FATURAMENTO_LIQUIDO > 0
),
RANKED AS (
    SELECT
        ID_PERIODO,
        MES_REF,
        CODCLI,
        CODPROD,
        PRODUTO,
        QTD_VENDIDA,
        FATURAMENTO_LIQUIDO,
        CUSTO_PRODUTO,
        (FATURAMENTO_LIQUIDO - CUSTO_PRODUTO) AS LUCRO_PRODUTO,
        ROUND(
            (FATURAMENTO_LIQUIDO - CUSTO_PRODUTO)
            / FATURAMENTO_LIQUIDO,
        4) AS MARGEM_PERC,
        ROW_NUMBER() OVER (
            PARTITION BY ID_PERIODO, CODCLI
            ORDER BY FATURAMENTO_LIQUIDO DESC
        ) AS POSICAO
    FROM BASE_FILTRADA
)
SELECT
    ID_PERIODO,
    TO_CHAR(MES_REF, 'MM/YYYY') AS PERIODO_REFERENCIA,
    CODCLI,
    CODPROD,
    PRODUTO,
    QTD_VENDIDA,
    FATURAMENTO_LIQUIDO,
    CUSTO_PRODUTO,
    LUCRO_PRODUTO,
    MARGEM_PERC,
    POSICAO
FROM RANKED
WHERE POSICAO <= 5
ORDER BY
    CODCLI,
    POSICAO;


----------------------
fTopProdCateg
----------------------

WITH PERIODOS AS (
    SELECT
        LEVEL AS ID_PERIODO,
        ADD_MONTHS(TRUNC(SYSDATE,'MM'), -(LEVEL-1))              AS MES_REF,
        ADD_MONTHS(TRUNC(SYSDATE,'MM'), -(LEVEL+10))             AS DATA_INICIO,
        LAST_DAY(ADD_MONTHS(TRUNC(SYSDATE,'MM'), -(LEVEL-1)))    AS DATA_FIM
    FROM DUAL
    CONNECT BY LEVEL <= 12
),
PARAMETROS AS (
    SELECT 
        MAX(CASE WHEN NOME = 'CON_FREQUENCIACLIENTE' 
                 THEN VALOR END) AS CON_FREQUENCIACLIENTE,
        MAX(CASE WHEN NOME = 'CON_FATURAMENTOCATCLIENTE' 
                 THEN VALOR END) AS CON_FATURAMENTOCATCLIENTE
    FROM PCPARAMFILIAL
),
FATURAMENTO_CLIENTE AS (
    SELECT
        P.ID_PERIODO,
        P.MES_REF,
        NF.CODCLI,
        SUM(NF.VLATEND) AS FATURAMENTO_BRUTO
    FROM VIEW_VENDAS_RESUMO_FATURAMENTO NF
    JOIN PERIODOS P
      ON NF.DTSAIDA BETWEEN P.DATA_INICIO AND P.DATA_FIM
    WHERE NF.CONDVENDA IN (1,7)
      AND NF.DTCANCEL IS NULL
    GROUP BY
        P.ID_PERIODO,
        P.MES_REF,
        NF.CODCLI
),
DEVOLUCAO_CLIENTE AS (
    SELECT
        P.ID_PERIODO,
        DV.CODCLI,
        SUM(DV.VLVENDA) * -1 AS DEVOLUCAO
    FROM VB_DEVOLUCAO DV
    JOIN PERIODOS P
      ON DV.DTVENDA BETWEEN P.DATA_INICIO AND P.DATA_FIM
    GROUP BY
        P.ID_PERIODO,
        DV.CODCLI
),
FREQUENCIA_CLIENTE AS (
    SELECT
        P.ID_PERIODO,
        NF.CODCLI,
        COUNT(NF.NUMNOTA) AS FREQUENCIA
    FROM PCNFSAID NF
    JOIN PERIODOS P
      ON NF.DTSAIDA BETWEEN P.DATA_INICIO AND P.DATA_FIM
    WHERE NF.CONDVENDA IN (1,7)
      AND NF.DTCANCEL IS NULL
    GROUP BY
        P.ID_PERIODO,
        NF.CODCLI
),
CLIENTES_CATEGORIZADOS AS (
    SELECT
        F.ID_PERIODO,
        F.MES_REF,
        F.CODCLI,
        (NVL(F.FATURAMENTO_BRUTO,0) - NVL(D.DEVOLUCAO,0)) AS FATURAMENTO_LIQUIDO,
        NVL(FR.FREQUENCIA,0) AS FREQUENCIA,
        CASE
            WHEN (NVL(F.FATURAMENTO_BRUTO,0) - NVL(D.DEVOLUCAO,0)) > P.CON_FATURAMENTOCATCLIENTE
             AND NVL(FR.FREQUENCIA,0) > P.CON_FREQUENCIACLIENTE
            THEN 'DIAMANTE'
            WHEN (NVL(F.FATURAMENTO_BRUTO,0) - NVL(D.DEVOLUCAO,0)) > P.CON_FATURAMENTOCATCLIENTE
             AND NVL(FR.FREQUENCIA,0) <= P.CON_FREQUENCIACLIENTE
            THEN 'OURO'
            WHEN (NVL(F.FATURAMENTO_BRUTO,0) - NVL(D.DEVOLUCAO,0)) <= P.CON_FATURAMENTOCATCLIENTE
             AND NVL(FR.FREQUENCIA,0) > P.CON_FREQUENCIACLIENTE
            THEN 'PRATA'
            ELSE 'BRONZE'
        END AS CATEGORIA_CLIENTE
    FROM FATURAMENTO_CLIENTE F
    LEFT JOIN DEVOLUCAO_CLIENTE D
           ON D.ID_PERIODO = F.ID_PERIODO
          AND D.CODCLI = F.CODCLI
    LEFT JOIN FREQUENCIA_CLIENTE FR
           ON FR.ID_PERIODO = F.ID_PERIODO
          AND FR.CODCLI = F.CODCLI
    CROSS JOIN PARAMETROS P
),
ITENS_CLIENTE AS (
    SELECT
        P.ID_PERIODO,
        P.MES_REF,
        NF.CODCLI,
        M.CODPROD,
        PR.DESCRICAO AS PRODUTO,
        SUM(M.QT) AS QTD_VENDIDA,
        SUM(M.QT * M.PUNIT) AS FATURAMENTO_PRODUTO,
        SUM(M.QT * M.CUSTOFIN) AS CUSTO_PRODUTO
    FROM PCNFSAID NF
    JOIN PCMOV M      ON M.NUMTRANSVENDA = NF.NUMTRANSVENDA
    JOIN PCPRODUT PR  ON PR.CODPROD = M.CODPROD
    JOIN PERIODOS P   ON NF.DTSAIDA BETWEEN P.DATA_INICIO AND P.DATA_FIM
    WHERE NF.CONDVENDA IN (1,7)
      AND NF.DTCANCEL IS NULL
      AND PR.CODPROD NOT IN (48500)
      AND PR.DESCRICAO NOT LIKE '++%'
      AND PR.DESCRICAO NOT LIKE '$%'
    GROUP BY
        P.ID_PERIODO,
        P.MES_REF,
        NF.CODCLI,
        M.CODPROD,
        PR.DESCRICAO
),
PRODUTOS_POR_CATEGORIA AS (
    SELECT
        C.ID_PERIODO,
        C.MES_REF,
        C.CATEGORIA_CLIENTE,
        I.CODPROD,
        I.PRODUTO,
        SUM(I.QTD_VENDIDA) AS QTD_TOTAL,
        SUM(I.FATURAMENTO_PRODUTO) AS FAT_TOTAL,
        SUM(I.CUSTO_PRODUTO) AS CUSTO_TOTAL
    FROM ITENS_CLIENTE I
    JOIN CLIENTES_CATEGORIZADOS C
      ON C.ID_PERIODO = I.ID_PERIODO
     AND C.CODCLI = I.CODCLI
    GROUP BY
        C.ID_PERIODO,
        C.MES_REF,
        C.CATEGORIA_CLIENTE,
        I.CODPROD,
        I.PRODUTO
),
RANKED AS (
    SELECT
        ID_PERIODO,
        MES_REF,
        CATEGORIA_CLIENTE,
        CODPROD,
        PRODUTO,
        QTD_TOTAL,
        FAT_TOTAL,
        CUSTO_TOTAL,
        ROUND(
            CASE
                WHEN FAT_TOTAL > 0
                THEN (FAT_TOTAL - CUSTO_TOTAL) / FAT_TOTAL
                ELSE 0
            END
        , 4) AS MARGEM_PERC,
        RANK() OVER (
            PARTITION BY ID_PERIODO, CATEGORIA_CLIENTE
            ORDER BY FAT_TOTAL DESC
        ) AS POSICAO
    FROM PRODUTOS_POR_CATEGORIA
)
SELECT 
    ID_PERIODO,
    TO_CHAR(MES_REF, 'MM/YYYY') AS PERIODO_REFERENCIA,
    CATEGORIA_CLIENTE,
    POSICAO,
    CODPROD,
    PRODUTO,
    QTD_TOTAL,
    FAT_TOTAL,
    CUSTO_TOTAL,
    MARGEM_PERC
FROM RANKED
WHERE POSICAO <= 20
ORDER BY
    ID_PERIODO,
    CATEGORIA_CLIENTE,
    POSICAO;



----------------------------
fTopProdCategTicket
----------------------------

WITH PERIODOS AS (
    SELECT
        LEVEL AS ID_PERIODO,
        ADD_MONTHS(TRUNC(SYSDATE,'MM'), -(LEVEL-1))              AS MES_REF,
        ADD_MONTHS(TRUNC(SYSDATE,'MM'), -(LEVEL+10))             AS DATA_INICIO,
        LAST_DAY(ADD_MONTHS(TRUNC(SYSDATE,'MM'), -(LEVEL-1)))    AS DATA_FIM
    FROM DUAL
    CONNECT BY LEVEL <= 12
),
PARAM_CATEGORIA_TICKET AS (
    SELECT
        500 AS LIM_TICKET_VALOR,
        3   AS LIM_TICKET_FREQUENCIA
    FROM DUAL
),
FATURAMENTO AS (
    SELECT
        P.ID_PERIODO,
        NF.CODCLI,
        SUM(NF.VLATEND)     AS FATURAMENTO_BRUTO
    FROM VIEW_VENDAS_RESUMO_FATURAMENTO NF
    JOIN PERIODOS P
      ON NF.DTSAIDA BETWEEN P.DATA_INICIO AND P.DATA_FIM
    WHERE NF.CONDVENDA IN (1,7)
      AND NF.DTCANCEL IS NULL
    GROUP BY
        P.ID_PERIODO,
        NF.CODCLI
),
DEVOLUCAO AS (
    SELECT
        P.ID_PERIODO,
        DV.CODCLI,
        SUM(DV.VLDEVOLUCAO) AS DEVOLUCAO
    FROM VIEW_DEVOL_RESUMO_FATURAMENTO DV
    JOIN PERIODOS P
      ON DV.DTENT BETWEEN P.DATA_INICIO AND P.DATA_FIM
    WHERE DV.DTCANCEL IS NULL
      AND DV.CONDVENDA IN (1,7)
    GROUP BY
        P.ID_PERIODO,
        DV.CODCLI
),
FREQUENCIA AS (
    SELECT
        P.ID_PERIODO,
        NF.CODCLI,
        COUNT(DISTINCT NF.NUMTRANSVENDA) AS FREQUENCIA
    FROM VIEW_VENDAS_RESUMO_FATURAMENTO NF
    JOIN PERIODOS P
      ON NF.DTSAIDA BETWEEN P.DATA_INICIO AND P.DATA_FIM
    WHERE NF.CONDVENDA IN (1,7)
      AND NF.DTCANCEL IS NULL
    GROUP BY
        P.ID_PERIODO,
        NF.CODCLI
),
CLIENTE_TICKET AS (
    SELECT
        F.ID_PERIODO,
        F.CODCLI,
        (NVL(F.FATURAMENTO_BRUTO,0) - NVL(D.DEVOLUCAO,0)) AS FATURAMENTO_LIQUIDO,
        FR.FREQUENCIA,
        ROUND(
            (NVL(F.FATURAMENTO_BRUTO,0) - NVL(D.DEVOLUCAO,0))
            / NULLIF(FR.FREQUENCIA,0),
        2) AS TICKET_MEDIO,
        CASE
            WHEN ROUND(
                    (NVL(F.FATURAMENTO_BRUTO,0) - NVL(D.DEVOLUCAO,0))
                    / NULLIF(FR.FREQUENCIA,0),2
                 ) >= PT.LIM_TICKET_VALOR
             AND FR.FREQUENCIA >= PT.LIM_TICKET_FREQUENCIA
            THEN 'DIAMANTE'
            WHEN ROUND(
                    (NVL(F.FATURAMENTO_BRUTO,0) - NVL(D.DEVOLUCAO,0))
                    / NULLIF(FR.FREQUENCIA,0),2
                 ) <  PT.LIM_TICKET_VALOR
             AND FR.FREQUENCIA >= PT.LIM_TICKET_FREQUENCIA
            THEN 'PRATA'
            WHEN ROUND(
                    (NVL(F.FATURAMENTO_BRUTO,0) - NVL(D.DEVOLUCAO,0))
                    / NULLIF(FR.FREQUENCIA,0),2
                 ) >= PT.LIM_TICKET_VALOR
             AND FR.FREQUENCIA <  PT.LIM_TICKET_FREQUENCIA
            THEN 'OURO'
            ELSE 'BRONZE'
        END AS CATEGORIA_TICKET
    FROM FATURAMENTO F
    LEFT JOIN DEVOLUCAO D
           ON D.ID_PERIODO = F.ID_PERIODO
          AND D.CODCLI    = F.CODCLI
    LEFT JOIN FREQUENCIA FR
           ON FR.ID_PERIODO = F.ID_PERIODO
          AND FR.CODCLI    = F.CODCLI
    CROSS JOIN PARAM_CATEGORIA_TICKET PT
),
ITENS_CLIENTE AS (
    SELECT
        P.ID_PERIODO,
        P.MES_REF,
        NF.CODCLI,
        M.CODPROD,
        PR.DESCRICAO AS PRODUTO,
        SUM(M.QT * M.PUNIT) AS FATURAMENTO_PRODUTO,
        SUM(M.QT * M.CUSTOFIN) AS CUSTO_PRODUTO
    FROM PCNFSAID NF
    JOIN PCMOV M      ON M.NUMTRANSVENDA = NF.NUMTRANSVENDA
    JOIN PCPRODUT PR  ON PR.CODPROD = M.CODPROD
    JOIN PERIODOS P   ON NF.DTSAIDA BETWEEN P.DATA_INICIO AND P.DATA_FIM
    WHERE NF.CONDVENDA IN (1,7)
      AND NF.DTCANCEL IS NULL
      AND PR.CODPROD NOT IN (48500)
      AND PR.DESCRICAO NOT LIKE '++%'
      AND PR.DESCRICAO NOT LIKE '$%'
    GROUP BY
        P.ID_PERIODO,
        P.MES_REF,
        NF.CODCLI,
        M.CODPROD,
        PR.DESCRICAO
),
PRODUTO_CATEGORIA AS (
    SELECT
        I.ID_PERIODO,
        I.MES_REF,
        C.CATEGORIA_TICKET,
        I.CODPROD,
        I.PRODUTO,
        SUM(I.FATURAMENTO_PRODUTO) AS FAT_TOTAL,
        SUM(I.CUSTO_PRODUTO) AS CUSTO_TOTAL
    FROM ITENS_CLIENTE I
    JOIN CLIENTE_TICKET C
      ON C.ID_PERIODO = I.ID_PERIODO
     AND C.CODCLI    = I.CODCLI
    GROUP BY
        I.ID_PERIODO,
        I.MES_REF,
        C.CATEGORIA_TICKET,
        I.CODPROD,
        I.PRODUTO
),
RANKED AS (
    SELECT
        ID_PERIODO,
        TO_CHAR(MES_REF,'MM/YYYY') AS PERIODO_REFERENCIA,
        CATEGORIA_TICKET,
        CODPROD,
        PRODUTO,
        FAT_TOTAL,
        ROUND(
            CASE
                WHEN FAT_TOTAL > 0
                THEN (FAT_TOTAL - CUSTO_TOTAL) / FAT_TOTAL
                ELSE 0
            END,
        4) AS MARGEM_PERC,
        RANK() OVER (
            PARTITION BY ID_PERIODO, CATEGORIA_TICKET
            ORDER BY FAT_TOTAL DESC
        ) AS POSICAO
    FROM PRODUTO_CATEGORIA
)
SELECT *
FROM RANKED
WHERE POSICAO <= 20
ORDER BY
    ID_PERIODO,
    CATEGORIA_TICKET,
    POSICAO;


---------------------------------
DIM_PERIODO
---------------------------------

SELECT
    LEVEL AS ID_PERIODO,
    ADD_MONTHS(TRUNC(SYSDATE,'MM'), -(LEVEL-1)) AS MES_REF,
    ADD_MONTHS(TRUNC(ADD_MONTHS(TRUNC(SYSDATE,'MM'), -(LEVEL-1)),'MM'), -11) AS DATA_INICIO,
    LAST_DAY(ADD_MONTHS(TRUNC(SYSDATE,'MM'), -(LEVEL-1)))                     AS DATA_FIM,
    TO_CHAR(
        ADD_MONTHS(TRUNC(SYSDATE,'MM'), -(LEVEL-1)),
        'MM/YYYY'
    ) AS PERIODO_REFERENCIA,
    EXTRACT(YEAR  FROM ADD_MONTHS(TRUNC(SYSDATE,'MM'), -(LEVEL-1))) AS ANO,
    EXTRACT(MONTH FROM ADD_MONTHS(TRUNC(SYSDATE,'MM'), -(LEVEL-1))) AS MES,
    TO_CHAR(
        ADD_MONTHS(TRUNC(SYSDATE,'MM'), -(LEVEL-1)),
        'Month',
        'NLS_DATE_LANGUAGE=PORTUGUESE'
    ) AS NOME_MES,
    TO_CHAR(
        ADD_MONTHS(TRUNC(SYSDATE,'MM'), -(LEVEL-1)),
        'YYYY/MM'
    ) AS ANO_MES,
    CASE
        WHEN EXTRACT(MONTH FROM ADD_MONTHS(TRUNC(SYSDATE,'MM'), -(LEVEL-1))) BETWEEN 1 AND 3 THEN 'Q1'
        WHEN EXTRACT(MONTH FROM ADD_MONTHS(TRUNC(SYSDATE,'MM'), -(LEVEL-1))) BETWEEN 4 AND 6 THEN 'Q2'
        WHEN EXTRACT(MONTH FROM ADD_MONTHS(TRUNC(SYSDATE,'MM'), -(LEVEL-1))) BETWEEN 7 AND 9 THEN 'Q3'
        ELSE 'Q4'
    END AS TRIMESTRE,
    CASE
        WHEN EXTRACT(MONTH FROM ADD_MONTHS(TRUNC(SYSDATE,'MM'), -(LEVEL-1))) BETWEEN 1 AND 6 THEN '1º Sem'
        ELSE '2º Sem'
    END AS SEMESTRE
FROM DUAL
CONNECT BY LEVEL <= 12;



-------------------------
Valores_Categ_Fatu
-------------------------

WITH PERIODOS AS (
    SELECT
        LEVEL AS ID_PERIODO,
        ADD_MONTHS(TRUNC(SYSDATE,'MM'), -(LEVEL-1))              AS MES_REF,
        ADD_MONTHS(TRUNC(SYSDATE,'MM'), -(LEVEL+10))             AS DATA_INICIO,
        LAST_DAY(ADD_MONTHS(TRUNC(SYSDATE,'MM'), -(LEVEL-1)))    AS DATA_FIM
    FROM DUAL
    CONNECT BY LEVEL <= 12
),
PARAMETROS AS (
    SELECT 
        MAX(CASE WHEN NOME = 'CON_FREQUENCIACLIENTE' 
                 THEN VALOR END) AS CON_FREQUENCIACLIENTE,
        MAX(CASE WHEN NOME = 'CON_FATURAMENTOCATCLIENTE' 
                 THEN VALOR END) AS CON_FATURAMENTOCATCLIENTE
    FROM PCPARAMFILIAL
),
FATURAMENTO AS (
    SELECT
        P.ID_PERIODO,
        NF.CODCLI,
        SUM(NF.VLATEND)     AS FATURAMENTO_BRUTO,
        SUM(NF.VLCUSTOFIN)  AS CUSTO_BRUTO
    FROM VIEW_VENDAS_RESUMO_FATURAMENTO NF
    JOIN PERIODOS P
      ON NF.DTSAIDA BETWEEN P.DATA_INICIO AND P.DATA_FIM
    WHERE NF.CONDVENDA IN (1,7)
      AND NF.DTCANCEL IS NULL
    GROUP BY
        P.ID_PERIODO,
        NF.CODCLI
),
DEVOLUCAO AS (
    SELECT
        P.ID_PERIODO,
        DV.CODCLI,
        SUM(DV.VLDEVOLUCAO) AS DEVOLUCAO
    FROM VIEW_DEVOL_RESUMO_FATURAMENTO DV
    JOIN PERIODOS P
      ON DV.DTENT BETWEEN P.DATA_INICIO AND P.DATA_FIM
    WHERE DV.DTCANCEL IS NULL
      AND DV.CONDVENDA IN (1,7)
    GROUP BY
        P.ID_PERIODO,
        DV.CODCLI
),
FREQUENCIA AS (
    SELECT
        P.ID_PERIODO,
        NF.CODCLI,
        COUNT(DISTINCT NF.NUMTRANSVENDA) AS FREQUENCIA
    FROM VIEW_VENDAS_RESUMO_FATURAMENTO NF
    JOIN PERIODOS P
      ON NF.DTSAIDA BETWEEN P.DATA_INICIO AND P.DATA_FIM
    WHERE NF.CONDVENDA IN (1,7)
      AND NF.DTCANCEL IS NULL
    GROUP BY
        P.ID_PERIODO,
        NF.CODCLI
),
BASE_CLIENTE AS (
    SELECT
        P.ID_PERIODO,
        P.MES_REF,
        F.CODCLI,
        NVL(F.FATURAMENTO_BRUTO,0) AS FATURAMENTO_BRUTO,
        NVL(D.DEVOLUCAO,0)         AS DEVOLUCAO,
        NVL(FR.FREQUENCIA,0)       AS FREQUENCIA,
        NVL(F.FATURAMENTO_BRUTO,0) - NVL(D.DEVOLUCAO,0) AS FATURAMENTO_LIQUIDO,
        NVL(F.CUSTO_BRUTO,0)        AS CUSTO_LIQUIDO
    FROM PERIODOS P
    JOIN FATURAMENTO F ON F.ID_PERIODO = P.ID_PERIODO
    LEFT JOIN DEVOLUCAO D 
           ON D.ID_PERIODO = F.ID_PERIODO 
          AND D.CODCLI = F.CODCLI
    LEFT JOIN FREQUENCIA FR 
           ON FR.ID_PERIODO = F.ID_PERIODO 
          AND FR.CODCLI = F.CODCLI
),
CLIENTE_CATEGORIA AS (
    SELECT
        B.*,
        CASE
        WHEN FATURAMENTO_LIQUIDO >= CON_FATURAMENTOCATCLIENTE
         AND FREQUENCIA          >= CON_FREQUENCIACLIENTE
        THEN 'DIAMANTE'
        WHEN FATURAMENTO_LIQUIDO <  CON_FATURAMENTOCATCLIENTE
         AND FREQUENCIA          >= CON_FREQUENCIACLIENTE
        THEN 'PRATA'
        WHEN FATURAMENTO_LIQUIDO >= CON_FATURAMENTOCATCLIENTE
         AND FREQUENCIA          <  CON_FREQUENCIACLIENTE
        THEN 'OURO'
        ELSE 'BRONZE'
    END AS CATEGORIA
    FROM BASE_CLIENTE B
    CROSS JOIN PARAMETROS P
)
SELECT
    ID_PERIODO,
    TO_CHAR(MES_REF,'MM/YYYY') AS PERIODO_REFERENCIA,
    CATEGORIA,
    COUNT(DISTINCT CODCLI) AS QTD_CLIENTES,
    SUM(FREQUENCIA)        AS FREQUENCIA_TOTAL,
    SUM(FATURAMENTO_BRUTO) AS FATURAMENTO_BRUTO,
    SUM(DEVOLUCAO)         AS DEVOLUCAO,
    ROUND(SUM(FATURAMENTO_LIQUIDO),2) AS FATURAMENTO_LIQUIDO,
    ROUND(
        SUM(FATURAMENTO_BRUTO )
        /
        NULLIF(SUM(FREQUENCIA),0),
    2) AS TICKET_MEDIO,
    ROUND(
        (SUM(FATURAMENTO_LIQUIDO) - SUM(CUSTO_LIQUIDO))
        /
        NULLIF(SUM(FATURAMENTO_LIQUIDO),0),
    4) AS MARGEMa
FROM CLIENTE_CATEGORIA
GROUP BY
    ID_PERIODO,
    MES_REF,
    CATEGORIA
ORDER BY
    ID_PERIODO,
    CATEGORIA


----------------------------------------------
Valores_Categ_Ticket
----------------------------------------------

WITH PERIODOS AS (
    SELECT
        LEVEL AS ID_PERIODO,
        ADD_MONTHS(TRUNC(SYSDATE,'MM'), -(LEVEL-1))              AS MES_REF,
        ADD_MONTHS(TRUNC(SYSDATE,'MM'), -(LEVEL+10))             AS DATA_INICIO,
        LAST_DAY(ADD_MONTHS(TRUNC(SYSDATE,'MM'), -(LEVEL-1)))    AS DATA_FIM
    FROM DUAL
    CONNECT BY LEVEL <= 12
),
PARAM_CATEGORIA_TICKET AS (
    SELECT
        500 AS LIM_TICKET_VALOR,
        3   AS LIM_TICKET_FREQUENCIA
    FROM DUAL
),
FATURAMENTO AS (
    SELECT
        P.ID_PERIODO,
        NF.CODCLI,
        SUM(NF.VLATEND)     AS FATURAMENTO_BRUTO,
        SUM(NF.VLCUSTOFIN)  AS CUSTO_BRUTO
    FROM VIEW_VENDAS_RESUMO_FATURAMENTO NF
    JOIN PERIODOS P
      ON NF.DTSAIDA BETWEEN P.DATA_INICIO AND P.DATA_FIM
    WHERE NF.CONDVENDA IN (1,7)
      AND NF.DTCANCEL IS NULL
    GROUP BY
        P.ID_PERIODO,
        NF.CODCLI
),
DEVOLUCAO AS (
    SELECT
        P.ID_PERIODO,
        DV.CODCLI,
        SUM(DV.VLDEVOLUCAO) AS DEVOLUCAO
    FROM VIEW_DEVOL_RESUMO_FATURAMENTO DV
    JOIN PERIODOS P
      ON DV.DTENT BETWEEN P.DATA_INICIO AND P.DATA_FIM
    WHERE DV.DTCANCEL IS NULL
      AND DV.CONDVENDA IN (1,7)
    GROUP BY
        P.ID_PERIODO,
        DV.CODCLI
),
FREQUENCIA AS (
    SELECT
        P.ID_PERIODO,
        NF.CODCLI,
        COUNT(DISTINCT NF.NUMTRANSVENDA) AS FREQUENCIA
    FROM VIEW_VENDAS_RESUMO_FATURAMENTO NF
    JOIN PERIODOS P
      ON NF.DTSAIDA BETWEEN P.DATA_INICIO AND P.DATA_FIM
    WHERE NF.CONDVENDA IN (1,7)
      AND NF.DTCANCEL IS NULL
    GROUP BY
        P.ID_PERIODO,
        NF.CODCLI
),
BASE_CLIENTE AS (
    SELECT
        P.ID_PERIODO,
        P.MES_REF,
        F.CODCLI,
        NVL(F.FATURAMENTO_BRUTO,0) AS FATURAMENTO_BRUTO,
        NVL(D.DEVOLUCAO,0)         AS DEVOLUCAO,
        NVL(FR.FREQUENCIA,0)       AS FREQUENCIA,
        NVL(F.FATURAMENTO_BRUTO,0) - NVL(D.DEVOLUCAO,0) AS FATURAMENTO_LIQUIDO,
        NVL(F.CUSTO_BRUTO,0)        AS CUSTO_LIQUIDO
    FROM PERIODOS P
    JOIN FATURAMENTO F ON F.ID_PERIODO = P.ID_PERIODO
    LEFT JOIN DEVOLUCAO D 
           ON D.ID_PERIODO = F.ID_PERIODO 
          AND D.CODCLI = F.CODCLI
    LEFT JOIN FREQUENCIA FR 
           ON FR.ID_PERIODO = F.ID_PERIODO 
          AND FR.CODCLI = F.CODCLI
),
CLIENTE_TICKET AS (
    SELECT
        B.*,
        ROUND(
            B.FATURAMENTO_LIQUIDO / NULLIF(B.FREQUENCIA,0),
        2) AS TICKET_MEDIO_CLI,
        CASE
            WHEN ROUND(B.FATURAMENTO_LIQUIDO / NULLIF(B.FREQUENCIA,0),2) >= PT.LIM_TICKET_VALOR
             AND B.FREQUENCIA >= PT.LIM_TICKET_FREQUENCIA
            THEN 'DIAMANTE'
            WHEN ROUND(B.FATURAMENTO_LIQUIDO / NULLIF(B.FREQUENCIA,0),2) <  PT.LIM_TICKET_VALOR
             AND B.FREQUENCIA >= PT.LIM_TICKET_FREQUENCIA
            THEN 'PRATA'
            WHEN ROUND(B.FATURAMENTO_LIQUIDO / NULLIF(B.FREQUENCIA,0),2) >= PT.LIM_TICKET_VALOR
             AND B.FREQUENCIA <  PT.LIM_TICKET_FREQUENCIA
            THEN 'OURO'
            ELSE 'BRONZE'
        END AS CATEGORIA_TICKET
    FROM BASE_CLIENTE B
    CROSS JOIN PARAM_CATEGORIA_TICKET PT
)
SELECT
    ID_PERIODO,
    TO_CHAR(MES_REF,'MM/YYYY') AS PERIODO_REFERENCIA,
    CATEGORIA_TICKET,
    COUNT(DISTINCT CODCLI) AS QTD_CLIENTES,
    SUM(FREQUENCIA)        AS FREQUENCIA_TOTAL,
    ROUND(SUM(FATURAMENTO_BRUTO),2) AS FATURAMENTO_BRUTO,
    ROUND(SUM(DEVOLUCAO),2)         AS DEVOLUCAO,
    ROUND(SUM(FATURAMENTO_LIQUIDO),2) AS FATURAMENTO_LIQUIDO,
    ROUND(
        SUM(FATURAMENTO_BRUTO)
        /
        NULLIF(SUM(FREQUENCIA),0),
    2) AS TICKET_MEDIO,
    ROUND(
        (SUM(FATURAMENTO_LIQUIDO) - SUM(CUSTO_LIQUIDO))
        /
        NULLIF(SUM(FATURAMENTO_LIQUIDO),0),
    4) AS MARGEM
FROM CLIENTE_TICKET
GROUP BY
    ID_PERIODO,
    MES_REF,
    CATEGORIA_TICKET
ORDER BY
    ID_PERIODO,
    CATEGORIA_TICKET;


--------------------------
Valores_Periodo
--------------------------

WITH PERIODOS AS (
    SELECT
        LEVEL AS ID_PERIODO,
        ADD_MONTHS(TRUNC(SYSDATE,'MM'), -(LEVEL-1))              AS MES_REF,
        ADD_MONTHS(TRUNC(SYSDATE,'MM'), -(LEVEL+10))             AS DATA_INICIO,
        LAST_DAY(ADD_MONTHS(TRUNC(SYSDATE,'MM'), -(LEVEL-1)))    AS DATA_FIM
    FROM DUAL
    CONNECT BY LEVEL <= 12
),
FATURAMENTO AS (
    SELECT
        P.ID_PERIODO,
        NF.CODCLI,
        SUM(NF.VLATEND)    AS FATURAMENTO_BRUTO,
        SUM(NF.VLCUSTOFIN) AS CUSTO_BRUTO
    FROM VIEW_VENDAS_RESUMO_FATURAMENTO NF
    JOIN PERIODOS P
      ON NF.DTSAIDA BETWEEN P.DATA_INICIO AND P.DATA_FIM
    WHERE NF.CONDVENDA IN (1,7)
      AND NF.DTCANCEL IS NULL
    GROUP BY
        P.ID_PERIODO,
        NF.CODCLI
),
DEVOLUCAO AS (
    SELECT
        P.ID_PERIODO,
        DV.CODCLI,
        SUM(DV.VLDEVOLUCAO) AS DEVOLUCAO
    FROM VIEW_DEVOL_RESUMO_FATURAMENTO DV
    JOIN PERIODOS P
      ON DV.DTENT BETWEEN P.DATA_INICIO AND P.DATA_FIM
    WHERE DV.DTCANCEL IS NULL
      AND DV.CONDVENDA IN (1,7)
    GROUP BY
        P.ID_PERIODO,
        DV.CODCLI
),
FREQUENCIA AS (
    SELECT
        P.ID_PERIODO,
        NF.CODCLI,
        COUNT(DISTINCT NF.NUMTRANSVENDA) AS FREQUENCIA
    FROM VIEW_VENDAS_RESUMO_FATURAMENTO NF
    JOIN PERIODOS P
      ON NF.DTSAIDA BETWEEN P.DATA_INICIO AND P.DATA_FIM
    WHERE NF.CONDVENDA IN (1,7)
      AND NF.DTCANCEL IS NULL
    GROUP BY
        P.ID_PERIODO,
        NF.CODCLI
),
BASE AS (
    SELECT
        P.ID_PERIODO,
        P.MES_REF,
        F.CODCLI,
        NVL(F.FATURAMENTO_BRUTO,0) AS FATURAMENTO_BRUTO,
        NVL(F.CUSTO_BRUTO,0)       AS CUSTO_BRUTO,
        NVL(D.DEVOLUCAO,0)         AS DEVOLUCAO,
        NVL(FR.FREQUENCIA,0)       AS FREQUENCIA
    FROM PERIODOS P
    JOIN FATURAMENTO F ON F.ID_PERIODO = P.ID_PERIODO
    LEFT JOIN DEVOLUCAO D 
           ON D.ID_PERIODO = F.ID_PERIODO 
          AND D.CODCLI = F.CODCLI
    LEFT JOIN FREQUENCIA FR 
           ON FR.ID_PERIODO = F.ID_PERIODO 
          AND FR.CODCLI = F.CODCLI
)
SELECT
    ID_PERIODO,
    TO_CHAR(MES_REF,'MM/YYYY') AS PERIODO_REFERENCIA,
    COUNT(DISTINCT CODCLI) AS QTD_CLIENTES,
    SUM(FREQUENCIA)       AS FREQUENCIA_TOTAL,
    ROUND(SUM(FATURAMENTO_BRUTO),2) AS FATURAMENTO_BRUTO,
    ROUND(SUM(DEVOLUCAO),2)         AS DEVOLUCAO,
    ROUND(SUM(FATURAMENTO_BRUTO - DEVOLUCAO),2) AS FATURAMENTO_LIQUIDO,
    ROUND(SUM(CUSTO_BRUTO),2)                   AS CUSTO_BRUTO,
    ROUND(
        (SUM(FATURAMENTO_BRUTO - DEVOLUCAO) - SUM(CUSTO_BRUTO))
        /
        NULLIF(SUM(FATURAMENTO_BRUTO - DEVOLUCAO),0),
    4) AS MARGEM,
    ROUND(
        SUM(FATURAMENTO_BRUTO)
        /
        NULLIF(SUM(FREQUENCIA), 0),
    2) AS TICKET_MEDIO
FROM BASE
GROUP BY
    ID_PERIODO,
    MES_REF
ORDER BY
    ID_PERIODO