mudaças pré formatação do pc

This commit is contained in:
João Herculano
2025-10-24 15:54:54 -03:00
parent 15fa59651c
commit 7221f41ebb
133 changed files with 5195259 additions and 9891 deletions
+77
View File
@@ -0,0 +1,77 @@
import requests
import datas as d
def PEF_LOJA(token):
infomes = d.inteiro_mes_atual()
# Definir a URL da requisição
url = "https://backend-metas.prd.franqueado.grupoboticario.digital/goal-pef-performance"
# Definir os parâmetros da requisição
params = {
"numPage": 1,
"numRows": 7,
"order": "ASC",
"orderBy": "revenueCurrentValue",
"years": 2025,
"pillars": "Todos",
"startCurrentCycle": "202503",
"endCurrentCycle": "202503",
"startPreviousCycle": "202403",
"endPreviousCycle": "202403",
"startCurrentDate": f"{infomes[0]}",
"endCurrentDate": f"{infomes[1]}",
"startPreviousDate": "2024-01-03",
"endPreviousDate": "2024-02-02",
"channels": "LOJ",
"calendarType": "calendar",
"previousPeriodCycleType": "retail-year",
"previousPeriodCalendarType": "retail-year",
"hour": "00:00 - 23:00",
"separationType": "businessDays",
"download": "true",
}
# Definir os headers da requisição
headers = {
"accept": "*/*",
"accept-encoding": "gzip, deflate, br, zstd",
"accept-language": "pt-BR,pt;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
"authorization": f"Bearer {token}",
"content-security-policy": "default-src https:",
"Cp-Code": "10269",
"origin": "https://extranet.grupoboticario.com.br",
"referer": "https://extranet.grupoboticario.com.br/",
"revenue-type": "gmv-revenue",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "cross-site",
"strict-transport-security": "max-age=31536000;",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36 Edg/133.0.0.0",
"x-api-key": "rCHOc2AJzo5zVMKcDrdtS9HvdUjzEFNM30IPLidz",
"x-content-type-options": "nosniff;",
"x-xss-protection": "1; mode=block;",
}
# Fazendo a requisição GET
response = requests.get(url, headers=headers, params=params)
# Verificando se a resposta foi bem-sucedida
if response.status_code == 200:
json_response = response.json()
print("Requisição bem-sucedida!")
# Verificando se há um link de download no JSON
if "data" in json_response and "downloadUrl" in json_response["data"]:
download_url = json_response["data"]["downloadUrl"]
print("Download disponível em:", download_url)
return download_url
else:
print("Nenhuma URL de download encontrada na resposta.")
return None
else:
print(f"Erro na requisição: {response.status_code}")
print(response.text)
return None
+65
View File
@@ -0,0 +1,65 @@
import requests
import datas as d
def PEF_VD(token):
infomes = d.inteiro_mes_atual()
url = "https://backend-metas.prd.franqueado.grupoboticario.digital/goal-pef-performance"
params = {
"numPage": 1,
"numRows": 7,
"order": "ASC",
"orderBy": "revenueCurrentValue",
"years": 2025,
"pillars": "Todos",
"startCurrentCycle": "202503",
"endCurrentCycle": "202503",
"startPreviousCycle": "202403",
"endPreviousCycle": "202403",
"startCurrentDate": f"{infomes[0]}",
"endCurrentDate": f"{infomes[1]}",
"startPreviousDate": "2024-02-03",
"endPreviousDate": "2024-03-01",
"channels": "VD",
"calendarType": "calendar",
"previousPeriodCycleType": "retail-year",
"previousPeriodCalendarType": "retail-year",
"hour": "00:00 - 17:00",
"separationType": "businessDays",
"download": "true"
}
headers = {
"accept": "*/*",
"accept-encoding": "gzip, deflate, br, zstd",
"accept-language": "pt-BR,pt;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
"authorization": f"Bearer {token}",
"content-security-policy": "default-src https:",
"cp-code": "10269",
"dash-view-name": "revenue-view/direct-sales",
"origin": "https://extranet.grupoboticario.com.br",
"referer": "https://extranet.grupoboticario.com.br/",
"revenue-type": "gmv-revenue",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "cross-site",
"strict-transport-security": "max-age=31536000",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36 Edg/133.0.0.0",
"x-api-key": "rCHOc2AJzo5zVMKcDrdtS9HvdUjzEFNM30IPLidz",
"x-content-type-options": "nosniff",
"x-xss-protection": "1; mode=block"
}
response = requests.get(url, params=params, headers=headers)
if response.status_code == 200:
json_response = response.json()
print("Requisição bem-sucedida!")
if "data" in json_response:
download_url = json_response["data"]["downloadUrl"]
print(download_url)
return download_url
else:
print("Nenhuma URL de download encontrada na resposta.")
else:
print(f"Erro na requisição: {response.status_code}")
print(response.text)
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+55
View File
@@ -0,0 +1,55 @@
#teste
from datetime import datetime, timedelta
import pandas as pd
#Fazer as funções de calendário varejo
#Funções de Datas
def acumulado_mes_atual():
hoje = datetime.today()
primeiro_dia_mes = hoje.replace(day=1)
# Se hoje for dia 1, 'ontem' também será o primeiro dia do mês
if hoje.day == 1:
ontem = primeiro_dia_mes
else:
ontem = hoje - timedelta(days=1)
return primeiro_dia_mes.strftime('%Y-%m-%d'), ontem.strftime('%Y-%m-%d')
def inteiro_mes_atual():
hoje = datetime.today()
primeiro_dia_mes = hoje.replace(day=1)
proximo_mes = (primeiro_dia_mes.replace(day=28) + timedelta(days=4)).replace(day=1)
ultimo_dia_mes = proximo_mes - timedelta(days=1)
primeiro_dia_formatado = primeiro_dia_mes.strftime('%Y-%m-%d')
ultimo_dia_formatado = ultimo_dia_mes.strftime('%Y-%m-%d')
return primeiro_dia_formatado, ultimo_dia_formatado
def acumulado_ano_atual():
hoje = datetime.today()
primeiro_dia_mes = hoje.replace(day=1, month=1)
hoje_formatado = hoje.strftime('%Y-%m-%d')
primeiro_dia_formatado = primeiro_dia_mes.strftime('%Y-%m-%d')
return primeiro_dia_formatado, hoje_formatado
def acumulado_do_dia_atual():
hoje = datetime.today()
hoje_formatado = hoje.strftime('%Y-%m-%d')
return hoje_formatado, hoje_formatado
def data_hora_atual():
data_hora_atual = datetime.now()
data_hora_formatada = data_hora_atual.strftime("%Y-%m-%d_%H-%M-%S")
return data_hora_formatada
# Funções para retonar os ciclos:
'''
1º Identificar a data de hoje em qual ciclo estamos
2º Depois identificar no ciclo em que está a data de começo do ciclo e fazer do começo do ciclo até agora.
'''
+81
View File
@@ -0,0 +1,81 @@
import requests
import datas as d
from datetime import datetime
import PEF_VD as pef
import PEF_Loja as pef_loja
from csv import DictReader
from datetime import datetime, timedelta
from token_GI import main
dir = r'database'
hoje_coluna = datetime.today() # Pegando a Data e Hora de hoje
hoje_formatado = hoje_coluna.strftime('%Y-%m-%d')
mes_atual = hoje_coluna.strftime('%Y-%B')
current = datetime.now()
# Processo principal
def download():
session = requests.Session() # Iniciar uma sessão persistente
with open(r"token.csv", 'r') as f:
try:
dict_reader = DictReader(f)
lista = list(dict_reader)
data = lista[0]['data']
data = datetime.strptime(data, "%Y-%m-%d %H:%M:%S")
delta = current - data - timedelta(hours=3)
print(delta)
if delta > timedelta(minutes=30):
print('token venceu, reinicie')
token =[]
main()
else:
print('Token não venceu')
tokens = lista[0]['token']
except ValueError as e:
print(e)
# Carrega
if len(tokens) > 0:
Access = tokens
#print("ID Token:", tokens["id_token"])
#print("Refresh Token:", tokens["refresh_token"])
# PEF_VD
url = pef.PEF_VD(Access)
baixarPEF = requests.get(url)
arquivo = fr"database/PEFVD_{mes_atual}.xlsx"
if baixarPEF.status_code==200:
with open(arquivo,"wb") as file:
file.write(baixarPEF.content)
print(f"Arquivo salvo com sucesso como {arquivo}.")
# x=pd.read_excel(arquivo)
# x['data'] = mes_atual
# x.to_excel(arquivo)
else:
print(f"Erro ao acessar o arquivo. Código de status: {baixarPEF.status_code}")
#PEC_VD
url = pef_loja.PEF_LOJA(Access)
baixarPEF_Loja = requests.get(url)
arquivoPEC = fr"database/PEFLOJA_{mes_atual}.xlsx"
if baixarPEF_Loja.status_code==200:
with open(arquivoPEC,"wb") as file:
file.write(baixarPEF_Loja.content)
print(f"Arquivo salvo com sucesso como {arquivoPEC}.")
else:
print(f"Erro ao acessar o arquivo. Código de status: {baixarPEF_Loja.status_code}")
else:
print("Falha ao carregar o token.")
if __name__ == "__main__":
download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R0VTVEFPX0NBTkFMX1ZEIiwiUEdJX1JFU1VMVEFET19QRFYiXSwiY3AiOiIxMDI2OSIsImxpbnhvbXMiOiJjb2xhYm9yYWRvciIsImVtYWlsX3ZlcmlmaWVkIjoidHJ1ZSIsInNjcCI6ImV4dHJhbmV0LmFwaSIsImF6cCI6ImIzMDAxZTYwLWE4ZTAtNGRhOC04MmJhLWMzYTcwMTQwNWYwOCIsInZlciI6IjEuMCIsImlhdCI6MTc0MzU5Njg4NH0.gzjXtWff-U8GYuDRugTZF5ev4-Fce41WTIvIi5BD30z4G-NkzlXwNfD-hIP7a7UKvjQoYSMAaUne5JYKViE7VIOsWSfrRc8hEMCWlVpzD3f7IBaWAhxfocyUjiyXnMtqR6b7k0Gpfvhh8p4uBMV2f_IG9ndy6E7eDiQ1D0FabTZQzayEwcDdTKG7u8nIUNTg6d1wHU1KjD7LNuiYHu79rz9cwbqduEdrE08CxluTCkoHote7qGnVmmKtlG-MHvLaR_NG26oBizrMX8kEvzVjuCxdHyVqvCqrJ5eMlEH14D6peyHB87TYhAnPanoRLT6VOo1Q2PwGoJqdtwuGX0mNoQ 2025-04-02 09:28:01
+257
View File
@@ -0,0 +1,257 @@
import os
import hashlib
import base64
import requests
import re
import json
from datetime import datetime
import csv
dir = fr"C:\Users\caique.pereira\Downloads\PEF"
# Seu diretório
hoje_coluna = datetime.today() # Pegando a Data e Hora de hoje
hoje_formatado = hoje_coluna.strftime('%Y-%m-%d')
data_atual = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
def generate_code_verifier():
"""Gera um code_verifier aleatório."""
return base64.urlsafe_b64encode(os.urandom(32)).decode('utf-8').rstrip("=")
def generate_code_challenge(code_verifier):
"""Gera o code_challenge usando SHA-256."""
sha256_hash = hashlib.sha256(code_verifier.encode('utf-8')).digest()
return base64.urlsafe_b64encode(sha256_hash).decode('utf-8').rstrip("=")
def send_authorization_request(session, code_challenge):
"""Envia uma requisição GET para a página de login usando a sessão."""
url = "https://login.extranet.grupoboticario.com.br/1e6392bd-5377-48f0-9a8e-467f5b381b18/oauth2/v2.0/authorize"
params = {
"p": "B2C_1A_JIT_SIGNUPORSIGNIN_FEDCORP_APIGEE_PRD",
"client_id": "b3001e60-a8e0-4da8-82ba-c3a701405f08",
"redirect_uri": "https://extranet.grupoboticario.com.br/auth/callback",
"response_type": "code",
"scope": "openid email https://gboticariob2c.onmicrosoft.com/a6cd4fe6-3d71-455a-b99d-f458a07cc0d1/extranet.api offline_access",
"state": "15d9d7f95f8648d1941426f4665aa383",
"code_challenge": code_challenge,
"code_challenge_method": "S256",
"response_mode": "query"
}
response = session.get(url, params=params)
if response.status_code == 200:
print("Página de login carregada com sucesso.")
return response.text # Retorna o HTML
else:
print(f"Erro ao acessar a página de login: {response.status_code}")
print("Resposta de erro:", response.text)
return None
def extract_tokens(html_content):
"""Extrai o CSRF Token e StateProperties do conteúdo HTML."""
csrf_token = None
state_properties = None
if html_content:
csrf_match = re.search(r'"csrf":"(.*?)"', html_content)
csrf_token = csrf_match.group(1) if csrf_match else None
state_properties_match = re.search(r'"transId":"StateProperties=(.*?)"', html_content)
state_properties = state_properties_match.group(1) if state_properties_match else None
return csrf_token, state_properties
def send_login_request(session, csrf_token, state_properties, username, password):
"""Envia uma requisição POST para realizar o login usando a sessão."""
url = "https://login.extranet.grupoboticario.com.br/1e6392bd-5377-48f0-9a8e-467f5b381b18/B2C_1A_JIT_SignUpOrSignin_FedCorp_APIGEE_PRD/SelfAsserted"
params = {
"tx": f"StateProperties={state_properties}",
"p": "B2C_1A_JIT_SignUpOrSignin_FEDCorp_APIGEE_PRD"
}
headers = {
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"X-CSRF-TOKEN": csrf_token,
"X-Requested-With": "XMLHttpRequest",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36 Edg/132.0.0.0",
"Accept": "application/json, text/javascript, */*; q=0.01",
"Origin": "https://login.extranet.grupoboticario.com.br",
"Referer": "https://login.extranet.grupoboticario.com.br/1e6392bd-5377-48f0-9a8e-467f5b381b18/oauth2/v2.0/authorize"
}
data = {
"request_type": "RESPONSE",
"signInName": username,
"password": password
}
response = session.post(url, params=params, headers=headers, data=data)
if response.status_code == 200:
print("Login realizado com sucesso!")
return response.text
else:
print(f"Erro ao realizar login: {response.status_code}")
return None
def send_final_request(session, csrf_token, state_properties):
"""
Envia a última requisição GET para obter a página HTML.
"""
url = "https://login.extranet.grupoboticario.com.br/1e6392bd-5377-48f0-9a8e-467f5b381b18/B2C_1A_JIT_SignUpOrSignin_FedCorp_APIGEE_PRD/api/CombinedSigninAndSignup/confirmed"
params = {
"rememberMe": "false",
"csrf_token": csrf_token,
"tx": f"StateProperties={state_properties}",
"p": "B2C_1A_JIT_SignUpOrSignin_FedCorp_APIGEE_PRD"
}
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36 Edg/132.0.0.0",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
"Referer": "https://login.extranet.grupoboticario.com.br/1e6392bd-5377-48f0-9a8e-467f5b381b18/oauth2/v2.0/authorize"
}
response = session.get(url, headers=headers, params=params, allow_redirects=False)
if response.status_code == 200:
print("Requisição final bem-sucedida!")
return response.text # Retorna o HTML
else:
print(f"Erro na requisição final: {response.status_code}")
return response.text
def extract_code_from_html(html_content):
"""
Extrai o valor do parâmetro `code` da URL no HTML fornecido.
:param html_content: O conteúdo HTML como string.
:return: O valor do código ou None, se não encontrado.
"""
# Regex para encontrar o parâmetro `code` na URL do atributo `href`
match = re.search(r'href="[^"]*?code=([^&"]+)', html_content)
if match:
return match.group(1) # Captura o valor do parâmetro `code`
return match
def send_token_request(code, code_verifier):
"""
Envia uma requisição POST para obter o token usando o código e o code_verifier.
:param code: O código extraído da etapa anterior.
:param code_verifier: O code_verifier usado no início do fluxo.
:return: A resposta do servidor.
"""
url = "https://login.extranet.grupoboticario.com.br/1e6392bd-5377-48f0-9a8e-467f5b381b18/oauth2/v2.0/token"
params = {
"p": "B2C_1A_JIT_SIGNUPORSIGNIN_FEDCORP_APIGEE_PRD"
}
headers = {
"Host": "login.extranet.grupoboticario.com.br",
"Connection": "keep-alive",
"Content-Type": "application/x-www-form-urlencoded",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36 Edg/132.0.0.0",
"Accept": "*/*",
"Origin": "https://extranet.grupoboticario.com.br",
"Sec-Fetch-Site": "same-site",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Dest": "empty",
"Referer": "https://extranet.grupoboticario.com.br/",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "pt-BR,pt;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
}
data = {
"client_id": "b3001e60-a8e0-4da8-82ba-c3a701405f08",
"code": code,
"redirect_uri": "https://extranet.grupoboticario.com.br/auth/callback",
"code_verifier": code_verifier,
"grant_type": "authorization_code"
}
response = requests.post(url, params=params, headers=headers, data=data)
return response.text
def extract_tokens_2(response_1):
response = json.loads(response_1)
try:
access_token = response.get("access_token")
id_token = response.get("id_token")
refresh_token = response.get("refresh_token")
return {
"access_token": access_token,
"id_token": id_token,
"refresh_token": refresh_token
}
except Exception as e:
print(f"Erro ao extrair tokens: {e}")
return None
# Processo principal
def main():
session = requests.Session() # Iniciar uma sessão persistente
code_verifier = generate_code_verifier()
code_challenge = generate_code_challenge(code_verifier)
print(f"Code Verifier: {code_verifier}")
print(f"Code Challenge: {code_challenge}")
# Enviar requisição GET para obter tokens
html_content = send_authorization_request(session, code_challenge)
csrf_token, state_properties = extract_tokens(html_content)
if not csrf_token or not state_properties:
print("Falha ao extrair CSRF Token ou StateProperties.")
else:
print("CSRF Token:", csrf_token)
print("StateProperties:", state_properties)
# Dados de login
username = "caique.santos1" # Colocar sua conta
password = "Peopleshit@55"
# Enviar requisição POST para login
login_response = send_login_request(session, csrf_token, state_properties, username, password)
if login_response:
print("Resposta do servidor:", login_response)
# Enviar requisição final
final_page_html = send_final_request(session, csrf_token, state_properties)
code = extract_code_from_html(final_page_html)
token = send_token_request(code, code_verifier)
# Carregar o JSON do arquivo texto
tokens = extract_tokens_2(token)
if tokens:
Access = tokens["access_token"]
csv_filename =fr"{dir}\token.csv"
# Escrever no arquivo CSV (criando se não existir)
with open(csv_filename,'r+') as file:
file.truncate(0)
with open(csv_filename, mode="a", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
print('baixei o arquivo')
# Se o arquivo estiver vazio, escrever o cabeçalho
if file.tell() == 0:
writer.writerow(["token", "data"])
# Escrever os dados
writer.writerow([Access, data_atual])
#print("ID Token:", tokens["id_token"])
#print("Refresh Token:", tokens["refresh_token"])
else:
print("Falha ao carregar ou processar o JSON.")
if __name__ == "__main__":
main()