import os
from datetime import datetime
import pytz
import streamlit as st
from apscheduler.schedulers.background import BackgroundScheduler
from monitor_logic import diagnose_n8n_webhook, run_monitor_check
# Timezone configuravel via variavel de ambiente (padrao: America/Sao_Paulo)
TIMEZONE = os.getenv("TIMEZONE", "America/Sao_Paulo")
tz = pytz.timezone(TIMEZONE)
st.set_page_config(
page_title="Monitor Evolution API",
page_icon="đ¤",
layout="wide",
)
def gerar_tabela_html(logs):
"""Gera tabela HTML com estilos inline para garantir funcionamento."""
if not logs:
return ""
estilo_tabela = "width: 100%; border-collapse: collapse; margin-top: 10px;"
estilo_header = (
"background-color: #f0f2f6; padding: 12px 15px; text-align: center; "
"font-weight: bold; font-size: 16px; border-bottom: 2px solid #ddd;"
)
estilo_celula = (
"padding: 10px 15px; text-align: center; font-size: 14px; "
"border-bottom: 1px solid #eee;"
)
estilo_celula_detalhes = (
"padding: 10px 15px; text-align: left; font-size: 14px; "
"border-bottom: 1px solid #eee;"
)
html = f'
'
html += ""
html += f'| Hora | '
html += f'Status | '
html += f'WhatsApp | '
html += f'Email | '
html += f'Detalhes | '
html += "
"
html += ""
for log in logs:
html += ""
html += f'| {log["Hora"]} | '
html += f'{log["Status"]} | '
html += f'{log["WhatsApp"]} | '
html += f'{log["Email"]} | '
html += f'{log["Detalhes"]} | '
html += "
"
html += "
"
return html
if "logs" not in st.session_state:
st.session_state["logs"] = []
if "last_run" not in st.session_state:
st.session_state["last_run"] = "Nunca"
def scheduled_job():
"""Executa verificacao agendada (background thread)."""
now = datetime.now(tz)
print(f"[{now}] Executando verificacao agendada...")
status, messages, whatsapp_status, email_status = run_monitor_check()
print(f"Status: {status} | WhatsApp: {whatsapp_status} | Email: {email_status}")
print("\n".join(messages))
@st.cache_resource
def init_scheduler():
scheduler = BackgroundScheduler(timezone=TIMEZONE)
scheduler.add_job(
scheduled_job,
"cron",
hour=8,
minute=0,
second=0,
id="daily_080000_check",
replace_existing=True,
)
scheduler.start()
return scheduler
scheduler = init_scheduler()
st.title("đ¤ Monitor Evolution API + Webhook")
st.markdown("---")
col1, col2 = st.columns(2)
with col1:
st.metric(label="Ultima Verificacao", value=st.session_state["last_run"])
with col2:
st.write("### Status Agendador")
st.success("â
Ativo (diariamente as 08:00:00 | intervalo 24h)")
st.markdown("### Acoes")
if st.button("đ Executar Verificacao Agora", type="primary"):
with st.spinner("Verificando status dos servicos..."):
status, messages, whatsapp_status, email_status = run_monitor_check()
now = datetime.now(tz)
st.session_state["last_run"] = now.strftime("%H:%M:%S")
entry = {
"Hora": now.strftime("%H:%M:%S"),
"Status": "â
Sucesso" if status else "â Erro",
"WhatsApp": whatsapp_status,
"Email": email_status,
"Detalhes": " | ".join(messages),
}
st.session_state["logs"].insert(0, entry)
if status:
st.success("â
Todos os servicos estao operacionais!")
else:
st.error("â Falha detectada em um ou mais servicos. Verifique os logs.")
st.markdown("---")
st.markdown("### Historico de Execucoes (Sessao Atual)")
if st.session_state["logs"]:
tabela_html = gerar_tabela_html(st.session_state["logs"])
st.markdown(tabela_html, unsafe_allow_html=True)
else:
st.info("âšī¸ Nenhuma verificacao executada nesta sessao ainda.")
st.sidebar.title("âšī¸ Sobre")
st.sidebar.info(
"""
Este aplicativo monitora:
1. **Evolution API**: Verifica se a instancia esta online.
2. **N8N Webhook**: Verifica se o endpoint responde.
**Notificacoes:**
- â
**Sucesso**: Envia WhatsApp.
- â **Erro**: Envia Email.
"""
)
st.sidebar.markdown("---")
with st.sidebar.expander("đ ī¸ Diagnostico N8N"):
st.write("Teste isolado do Webhook N8N")
if st.button("Testar Webhook N8N", key="btn_diag"):
with st.spinner("Enviando POST de teste..."):
success, log_data = diagnose_n8n_webhook()
if success:
st.success(f"â
Status: {log_data['status_code']}")
else:
st.error(f"â Erro: {log_data.get('status_code') or log_data.get('error')}")
st.json(log_data)
st.sidebar.markdown("---")
st.sidebar.caption("Disparador automatico: diariamente as 08:00:00 (24h)")