From 0b8c403e5598666797993215c00c9f8efaa32937 Mon Sep 17 00:00:00 2001 From: Ekaropolus Date: Mon, 19 May 2025 23:49:29 -0600 Subject: [PATCH] whatsaap Bot statistics and activity --- pxy_dashboard/apps/views.py | 69 ++++++++++- .../pxy_dashboard/apps/apps-whatsapp-bot.html | 115 +++++++++++++++--- pxy_whatsapp/urls.py | 1 + 3 files changed, 165 insertions(+), 20 deletions(-) diff --git a/pxy_dashboard/apps/views.py b/pxy_dashboard/apps/views.py index 7c50d22..838ab24 100644 --- a/pxy_dashboard/apps/views.py +++ b/pxy_dashboard/apps/views.py @@ -1,5 +1,17 @@ from django.views.generic.base import TemplateView from django.contrib.auth.mixins import LoginRequiredMixin +from pxy_whatsapp.views import whatsapp_stats +import json +import logging +from django.contrib.auth.decorators import login_required +from pxy_whatsapp.models import WhatsAppBot +from django.shortcuts import render +from django.utils import timezone +from datetime import timedelta +import json +from pxy_whatsapp.models import Message, WhatsAppBot + +logger = logging.getLogger(__name__) class AppsView(LoginRequiredMixin, TemplateView): @@ -270,12 +282,57 @@ def dispatch_plan_view(request): }) -from django.contrib.auth.decorators import login_required -from django.shortcuts import render -import requests + + + + @login_required def apps_whatsapp_bot(request): - stats = request.user.has_perm("pxy_whatsapp.view_whatsappstats") and \ - requests.get(request.build_absolute_uri("/whatsapp/stats/"), cookies=request.COOKIES).json() - return render(request, "pxy_dashboard/apps/apps-whatsapp-bot.html", {"stats": stats}) + stats = {} + bots_info = [] + + # — 1) Cargar métricas — + try: + resp = whatsapp_stats(request) + if resp.status_code == 200: + stats = resp.json() + except Exception as e: + logger.error(f"Error loading WhatsApp stats: {e}") + + # — 2) Cargar información de los bots — + try: + for bot in WhatsAppBot.objects.all(): + bots_info.append({ + "name": bot.name, + "phone_number_id": bot.phone_number_id, + "is_active": bot.is_active, + "assistant": bot.assistant.name, + }) + except Exception as e: + logger.error(f"Error loading WhatsApp bots: {e}") + + # — 3) Prepare weekly data for scatter — + today = timezone.now().date() + start_date = today - timedelta(days=6) + weekly_data = {} + for bot in WhatsAppBot.objects.all(): + points = [] + for i in range(7): + day = start_date + timedelta(days=i) + count = Message.objects.filter( + conversation__bot=bot, + timestamp__date=day + ).count() + points.append({"x": day.strftime("%Y-%m-%d"), "y": count}) + weekly_data[bot.name] = points + + # pass it as JSON + context = { + "stats": stats, + "bots_info": bots_info, + "weekly_data_json": json.dumps(weekly_data), + } + + return render(request, "pxy_dashboard/apps/apps-whatsapp-bot.html", context) + diff --git a/pxy_dashboard/templates/pxy_dashboard/apps/apps-whatsapp-bot.html b/pxy_dashboard/templates/pxy_dashboard/apps/apps-whatsapp-bot.html index b61d09d..9e88c8e 100644 --- a/pxy_dashboard/templates/pxy_dashboard/apps/apps-whatsapp-bot.html +++ b/pxy_dashboard/templates/pxy_dashboard/apps/apps-whatsapp-bot.html @@ -1,12 +1,21 @@ {% extends "pxy_dashboard/partials/base.html" %} +{% load static %} + +{% block title %}Zone Definition{% endblock %} + +{% block extra_css %} + +{% endblock %} + {% block content %} {% include "pxy_dashboard/partials/dashboard/kpi_row.html" %} +
-

{{ stats.total_conversations }}

+

{{ stats.total_conversations|default:"–" }}

Conversaciones totales

@@ -14,7 +23,7 @@
-

{{ stats.messages_in }}

+

{{ stats.messages_in|default:"–" }}

Mensajes recibidos (24h)

@@ -22,7 +31,7 @@
-

{{ stats.messages_out }}

+

{{ stats.messages_out|default:"–" }}

Mensajes enviados (24h)

@@ -30,26 +39,104 @@
-

{{ stats.avg_response_time|floatformat:0 }} ms

+

{{ stats.avg_response_time|default:"–" }} ms

Tiempo de respuesta promedio

-
-
Actividad por hora
+ +
+
+
Bots Configurados
+
-
+
+ + + + + + + + + + + {% for bot in bots_info %} + + + + + + + {% empty %} + + + + {% endfor %} + +
NombrePhone Number IDEstadoAsistente AI
{{ bot.name }}{{ bot.phone_number_id }} + {% if bot.is_active %} + Activo + {% else %} + Inactivo + {% endif %} + {{ bot.assistant }}
+ No hay bots configurados +
+
-{% block extra_js %} - - -{% endblock %} + +
+
+
Actividad Semanal de Mensajes por Bot
+
+
+
+
+
+ + {% endblock %} + +{% block extra_js %} + + + + +{% endblock %} \ No newline at end of file diff --git a/pxy_whatsapp/urls.py b/pxy_whatsapp/urls.py index be3ef61..86508c9 100644 --- a/pxy_whatsapp/urls.py +++ b/pxy_whatsapp/urls.py @@ -4,4 +4,5 @@ from . import views urlpatterns = [ path('webhook/', views.webhook, name='webhook'), path('webhook/verify/', views.webhook_verification, name='webhook_verification'), + path('stats/', views.whatsapp_stats, name='whatsapp_stats'), ]