FEAT: Adiciona funções para identificar dispositivos físicos, atualiza geração de relatório semanal com consolidado
This commit is contained in:
parent
cc7fa5e7dd
commit
01ffd019f8
@ -279,11 +279,21 @@ def save_daily_csv(all_users_with_status, domain_mapping, trunks_by_domain, dest
|
||||
return output_dir
|
||||
|
||||
|
||||
DEVICE_WHITELIST = ["yealink", "fanvil"]
|
||||
|
||||
|
||||
def is_physical_phone(agent):
|
||||
"""Retorna True se o dispositivo for Yealink ou Fanvil (telefone físico)."""
|
||||
agent_lower = agent.lower()
|
||||
return any(w in agent_lower for w in DEVICE_WHITELIST)
|
||||
|
||||
|
||||
def generate_weekly_report():
|
||||
"""
|
||||
Gera relatório semanal consolidado.
|
||||
Lê os CSVs dos últimos 7 dias e consolida por ramal/domínio.
|
||||
Um ramal é contado como 'Presente' se apareceu registrado em ao menos 1 dia.
|
||||
Gera relatório semanal consolidado todo dia, baseado nos últimos 7 dias.
|
||||
Substitui os arquivos anteriores.
|
||||
- semanal_<dominio>.csv — detalhe por ramal
|
||||
- consolidado_semanal.csv — resumo com contagem de telefones físicos por domínio
|
||||
"""
|
||||
today = datetime.now()
|
||||
script_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
@ -291,13 +301,11 @@ def generate_weekly_report():
|
||||
weekly_dir = os.path.join(script_dir, "csv_semanal")
|
||||
os.makedirs(weekly_dir, exist_ok=True)
|
||||
|
||||
# Coleta os últimos 7 dias
|
||||
# Últimos 7 dias (do mais antigo ao mais recente)
|
||||
days = [(today - timedelta(days=i)).strftime("%Y%m%d") for i in range(6, -1, -1)]
|
||||
week_label = f"{days[0]}_a_{days[-1]}"
|
||||
log(f"Gerando relatório semanal — período {days[0]} a {days[-1]}")
|
||||
|
||||
log(f"Gerando relatório semanal para o período {days[0]} a {days[-1]}")
|
||||
|
||||
# Estrutura: { domain_description: { ramal: { dias_presente, agent_mais_recente, domain_label } } }
|
||||
# Estrutura: { domain_key: { ramal: { dias_presente, agent_mais_recente, domain_label } } }
|
||||
weekly_data = {}
|
||||
|
||||
for day in days:
|
||||
@ -324,21 +332,17 @@ def generate_weekly_report():
|
||||
if not ramal:
|
||||
continue
|
||||
|
||||
if domain_key not in weekly_data:
|
||||
weekly_data[domain_key] = {}
|
||||
|
||||
if ramal not in weekly_data[domain_key]:
|
||||
weekly_data[domain_key][ramal] = {
|
||||
weekly_data.setdefault(domain_key, {})
|
||||
weekly_data[domain_key].setdefault(ramal, {
|
||||
"dias_presente": 0,
|
||||
"agent_mais_recente": "",
|
||||
"domain_label": domain_label
|
||||
}
|
||||
})
|
||||
|
||||
# Conta como presente se tiver qualquer status de registro
|
||||
if status and status != "Sem registro":
|
||||
weekly_data[domain_key][ramal]["dias_presente"] += 1
|
||||
# Atualiza o agent para o mais recente (último dia processado)
|
||||
if agent:
|
||||
# Sempre sobrescreve — último dia processado = mais recente
|
||||
weekly_data[domain_key][ramal]["agent_mais_recente"] = agent
|
||||
|
||||
if domain_label:
|
||||
@ -351,9 +355,15 @@ def generate_weekly_report():
|
||||
log("Nenhum dado encontrado para gerar relatório semanal.")
|
||||
return
|
||||
|
||||
# Gera um CSV por domínio
|
||||
# Consolidado: { domain_label: contagem de telefones físicos presentes }
|
||||
consolidado = {}
|
||||
|
||||
# Gera um CSV por domínio — substitui o anterior sem timestamp no nome
|
||||
for domain_key, ramais in weekly_data.items():
|
||||
filename = os.path.join(weekly_dir, f"semanal_{domain_key}_{week_label}.csv")
|
||||
filename = os.path.join(weekly_dir, f"semanal_{domain_key}.csv")
|
||||
|
||||
domain_label_geral = ""
|
||||
telefones_fisicos = 0
|
||||
|
||||
with open(filename, "w", newline="", encoding="utf-8-sig") as csvfile:
|
||||
writer = csv.writer(csvfile, delimiter=";")
|
||||
@ -365,25 +375,38 @@ def generate_weekly_report():
|
||||
"Dispositivo (mais recente)"
|
||||
])
|
||||
for ramal, info in sorted(ramais.items()):
|
||||
status_semanal = "Presente" if info["dias_presente"] >= 1 else "Ausente"
|
||||
presente = info["dias_presente"] >= 1
|
||||
status_semanal = "Presente" if presente else "Ausente"
|
||||
agent = info["agent_mais_recente"]
|
||||
domain_label_geral = info["domain_label"] or domain_key
|
||||
|
||||
writer.writerow([
|
||||
ramal,
|
||||
info["domain_label"],
|
||||
domain_label_geral,
|
||||
status_semanal,
|
||||
info["dias_presente"],
|
||||
info["agent_mais_recente"]
|
||||
agent
|
||||
])
|
||||
|
||||
# Conta para o consolidado: presente + dispositivo físico
|
||||
if presente and is_physical_phone(agent):
|
||||
telefones_fisicos += 1
|
||||
|
||||
consolidado[domain_label_geral or domain_key] = telefones_fisicos
|
||||
log(f"Relatório semanal gerado: {filename}")
|
||||
|
||||
# Gera o consolidado geral — substitui o anterior
|
||||
consolidado_path = os.path.join(weekly_dir, "consolidado_semanal.csv")
|
||||
with open(consolidado_path, "w", newline="", encoding="utf-8-sig") as csvfile:
|
||||
writer = csv.writer(csvfile, delimiter=";")
|
||||
writer.writerow(["Domínio", "Telefones Físicos Presentes (Yealink/Fanvil)"])
|
||||
for domain_label, qtd in sorted(consolidado.items()):
|
||||
writer.writerow([domain_label, qtd])
|
||||
|
||||
log(f"Consolidado semanal gerado: {consolidado_path}")
|
||||
log(f"Relatório semanal concluído. {len(weekly_data)} domínios processados.")
|
||||
|
||||
|
||||
def is_sunday():
|
||||
"""Retorna True se hoje for domingo."""
|
||||
return datetime.now().weekday() == 6
|
||||
|
||||
|
||||
def main():
|
||||
load_env()
|
||||
|
||||
@ -407,9 +430,7 @@ def main():
|
||||
|
||||
log("=== Coleta diária concluída ===")
|
||||
|
||||
# Se for domingo, gera o relatório semanal consolidado
|
||||
if is_sunday():
|
||||
log("=== Domingo detectado — gerando relatório semanal ===")
|
||||
log("=== Gerando relatório semanal ===")
|
||||
generate_weekly_report()
|
||||
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user