<jupyter_start><jupyter_text><jupyter_code>import pandas as pd
import requests
import json
import uuid
import sys
#sys.path.append(r'C:\Users\breno.santos\Desktop\Projetos\Campanhas')<jupyter_output><empty_output><jupyter_text>Coleta Base .csv<jupyter_code>from google.colab import drive
drive.mount('/content/drive')

#último código de autorização drive -> 4/1AY0e-g5t8YQdnBNylI4Y-iiMq2Zp8MX6xgxQ4DebNFrW8rMc2reCg-gvj2o
'''
To-do:
- Alterar path para drive compartilhado
- Verificar compartilhamento de dados via GitHub para ter histórico de modificação de códigos

REGRAS:
- Sempre colocar os arquivos em uma pasta única chamada dados
- Criar um padrão de arquivos para mantermos o histórico, ex: dados_push_20210618
'''

file_name = r'teste.csv'
players_df = pd.read_csv(f'/content/drive/MyDrive/dados/{file_name}')
players_df.head()
#Aplica uma formula lambda que atualiza o dict e seus valores para o valor original -> https://stackoverflow.com/questions/66834210/pd-json-normalize-occurs-an-str-object-has-no-attribute-values
players_df['tags']=players_df['tags'].apply(lambda x:eval(x))

#Retira a antiga coluna do app_version
players_df = players_df.drop('app_version', axis=1)

#Normaliza as linhas do dict em colunas e dropa a coluna tags
players_df = players_df.join(pd.json_normalize(players_df.tags)).drop('tags', axis=1)

#Transforma as colunas de datas em datetime
players_df['last_active'] = pd.to_datetime(players_df['last_active'])
players_df['first_session'] = pd.to_datetime(players_df['first_session'])
players_df.head()
'''
players_df['last_active'] = pd.to_datetime(players_df['last_active'])
players_df['first_session'] = pd.to_datetime(players_df['first_session'])
players_df['tags'] = players_df['tags'].str.replace('\"','')
players_df[['identification', 'cblc']] = players_df['tags'].str.split(',', expand=True)[0].str.split(' ', expand=True)
players_df['identification'] = players_df['identification'].str.replace('{', '').str.replace(':', '')
players_df['cblc'] = players_df['cblc'].str.replace('}', '').str.replace(':', '')
'''
#Seleciona apenas os clientes que possuem cblc
user_df = players_df[ players_df['cblc'].notna() ]

#Retira valores duplicados considerando apenas dados do ultimo login do usuário
user_df = user_df.sort_values('last_active', ascending=True).drop_duplicates('cblc', keep='last')

#Filtra apenas clientes que estão subescritos e o cblc é diferente de nulo
user_df = user_df[ (players_df['subscribed'] == 'Yes') & (user_df['cblc'] != 'null') ]

#Muda o tipo de dado da coluna cblc para int (numerico)
user_df['cblc'] = user_df['cblc'].astype('int64')
'''
user_df = players_df[players_df['identification'] == 'cblc'].copy()
user_df = user_df.sort_values('last_active', ascending=True).drop_duplicates('cblc', keep='last')
user_df = user_df[(user_df['subscribed'] == 'Yes') & (user_df['cblc'] != 'null')].copy()
user_df['cblc'] = user_df['cblc'].astype(int)
'''
duplicados_mask = players_df[ ( (players_df['cblc'] != 'null') | (players_df['cblc'].notna()) ) & (players_df.duplicated(subset=['cblc'])) ]

print('Total na lista:', players_df.shape[0])
print('Sem CBLC:', players_df[ (players_df['cblc'] == 'null') | (players_df['cblc'].isna()) ].shape[0]) #qual a diferença entre estar nulo e vazio?
print('Total Subscribed:', players_df[players_df['subscribed'] == 'Yes'].shape[0])
print('Quantidade de CBLC duplicado:', players_df['cblc'].duplicated().sum()) #o que fazia antes?
print('CBLC subscribed e únicos:', user_df.shape[0])
#valores breno
duplicados_mask = (players_df['identification'] == 'cblc') & (players_df.duplicated(subset=['cblc']))

print('Total na lista:', players_df.shape[0])
print('Sem CBLC:', players_df[players_df['identification'] != 'cblc'].shape[0])
print('Total Subscribed:', players_df[players_df['subscribed'] == 'Yes'].shape[0])
print('Quantidade de CBLC duplicado:', players_df[duplicados_mask].shape[0])
print('CBLC subscribed e únicos:', user_df.shape[0])
#Checa usuário (breno)
user_df[user_df.cblc == 100072]
#Checa usuário (marcela)
user_df[user_df.cblc == 597958]<jupyter_output><empty_output><jupyter_text>Combina Base com lista de CBLC<jupyter_code>#Incluir a base de disparo 
base_file = r'cashback.csv'
base_df = pd.read_csv(f'/content/drive/MyDrive/dados/{base_file}') #Se salvar pelo excel, incluir -> ,sep=';', engine='python'
base_df.head()
base_df.dtypes
base_df.describe()
#base_df['Classificação do cliente'].value_counts()
#base_df['Sub classificação do cliente'].value_counts()
#cblc_list = base_df.iloc[:, 1].str.replace('_Canceled', '').astype(int).tolist() 
cblc_list = base_df['cblc'].tolist()
print('Quantidade de clientes na lista:', len(cblc_list))<jupyter_output>Quantidade de clientes na lista: 2129<jupyter_text>Clientes da base que tem o aplicativo:<jupyter_code>#Verifica quais usuários da base de disparo estão dentro da base de usuários
base_push = user_df[user_df.cblc.isin(cblc_list)].copy()

print('Quantidade de clientes da base com aplicativo:', base_push.shape[0])
base_push.head()<jupyter_output><empty_output><jupyter_text>Send Push<jupyter_code>push_list = base_push.player_id.tolist()

#push_list = ["9871a349-edf0-4a21-9b71-67ac9df6bcc8"]
#push_list = push_list * 3000


len(push_list)
# Breno player ID: 9871a349-edf0-4a21-9b71-67ac9df6bcc8
# Paulo Mota player ID: c9cf4cef-5ae2-4cdd-bab9-cd572f056dfc
# Marcela ID: 352140f0-eb40-40a4-beaf-01407ef72f60 
# Adiciona meu player ID a lista de disparo
push_list.append('9871a349-edf0-4a21-9b71-67ac9df6bcc8')
#push_list.append('c9cf4cef-5ae2-4cdd-bab9-cd572f056dfc')


#push_list = ['9871a349-edf0-4a21-9b71-67ac9df6bcc8', '352140f0-eb40-40a4-beaf-01407ef72f60']

len(push_list)
url_notifications = "https://onesignal.com/api/v1/notifications"

headers = {
    'Content-Type': 'application/json; charset=utf-8;', 
    'Authorization':'Basic N<KEY>'
}

template_id = 'b2a4ff3f-1e31-4393-86d7-8013de5b0496'
template_id_no_icon = '8090726a-3759-4f54-9ff3-d043d696e793'


heading = 'Uhull! Já depositamos o seu cashback 🎉'
contents = 'O dinheiro já está na sua conta e você pode fazer com ele o que você quiser. Bora investir?'
#link = 'http://bit.ly/38Zdhn3'
def define_body_push(heading_text, content_text, template, player_id_list, push_link=False):
    
    if push_link:
        body  = \
        {
            "app_id": "1f783bd4-225f-43c5-9bf4-f74b94e656f4",
            "headings": {"en": heading_text},
            "contents": {"en": content_text},
            "template_id": template,
            "url":f"{push_link}",
            "include_player_ids": player_id_list
        }
        
    else:
        body  = \
        {
            "app_id": "1f783bd4-225f-43c5-9bf4-f74b94e656f4",
            "headings": {"en": heading},
            "contents": {"en": contents},
            "template_id": template,
            "include_player_ids": player_id_list
        }
        
    return body


def send_push(url, body, header):
    push = requests.post(url, json=body, headers=header)
    
    return push


# Trava para envio de Push

enviar_push = False

if enviar_push:
    print('Envio de push habilitado')
else:
    print('Envio de push desabilitado!')


if enviar_push:
    
    
    if len(push_list) > 2000:
        n = 2000
        chunks = [push_list[i:i + n] for i in range(0, len(push_list), n)]
        
        print('Tamanho da lista:', len(push_list))
        print('Quantidade de chunks:', len(chunks))
        print('-------------------\n')
              
        for i, chunk in enumerate(chunks):
            body_push = define_body_push(heading, contents, template_id_no_icon, chunk, push_link=False)
            push_notification = send_push(url_notifications, body_push, headers)
            print('Enviando chunk {}'.format(i))
            print(push_notification)
            print('-------------------\n')
        
    else:
        print('Tamanho da lista:', len(push_list))
        
        body_push = define_body_push(heading, contents, template_id_no_icon, push_list, push_link=False)
        push_notification = send_push(url_notifications, body_push, headers)
        print(push_notification)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1508482911236784, 'fraction_numerical': 0.038111630194246376, 'mean_word_length': 4.848310567936736, 'pattern_counts': {'":': 15, '<': 21, '<?xml version=': 0, '>': 25, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '599740', 'license': 'CNRI-Python', 'n_tokens_mistral': 3255, 'n_tokens_neox': 3093, 'n_words': 573, 'path': 'Push.ipynb', 'repo_name': 'matsuch/project1---seattle', 'size': '8176'}