From 30b8efac2fffb2f2740cf23e9182e2f5a209a569 Mon Sep 17 00:00:00 2001 From: Ekaropolus Date: Tue, 20 May 2025 01:17:30 -0600 Subject: [PATCH] Stats on view of dashboard --- pxy_dashboard/apps/views.py | 38 ++++++++++++++++++++++++------------- 1 file changed, 25 insertions(+), 13 deletions(-) diff --git a/pxy_dashboard/apps/views.py b/pxy_dashboard/apps/views.py index 838ab24..b4f3b09 100644 --- a/pxy_dashboard/apps/views.py +++ b/pxy_dashboard/apps/views.py @@ -283,24 +283,37 @@ def dispatch_plan_view(request): +from django.db.models import Avg +from django.utils import timezone +from datetime import timedelta +import json, logging +from pxy_whatsapp.models import Conversation, Message - - +logger = logging.getLogger(__name__) @login_required def apps_whatsapp_bot(request): - stats = {} - bots_info = [] - - # — 1) Cargar métricas — + # — 1) Calcular métricas directamente — try: - resp = whatsapp_stats(request) - if resp.status_code == 200: - stats = resp.json() + total_conversations = Conversation.objects.count() + messages_in = Message.objects.filter(direction="in").count() + messages_out = Message.objects.filter(direction="out").count() + # Promedio de tiempo de respuesta (solo out con tiempo) + avg_rt = Message.objects.filter( + direction="out", response_time_ms__isnull=False + ).aggregate(Avg("response_time_ms"))["response_time_ms__avg"] or 0 + stats = { + "total_conversations": total_conversations, + "messages_in": messages_in, + "messages_out": messages_out, + "avg_response_time": int(avg_rt), + } except Exception as e: - logger.error(f"Error loading WhatsApp stats: {e}") + logger.error(f"Error calculando métricas de WhatsApp: {e}") + stats = {"total_conversations": 0, "messages_in": 0, "messages_out": 0, "avg_response_time": 0} # — 2) Cargar información de los bots — + bots_info = [] try: for bot in WhatsAppBot.objects.all(): bots_info.append({ @@ -310,7 +323,7 @@ def apps_whatsapp_bot(request): "assistant": bot.assistant.name, }) except Exception as e: - logger.error(f"Error loading WhatsApp bots: {e}") + logger.error(f"Error cargando bots de WhatsApp: {e}") # — 3) Prepare weekly data for scatter — today = timezone.now().date() @@ -327,12 +340,11 @@ def apps_whatsapp_bot(request): points.append({"x": day.strftime("%Y-%m-%d"), "y": count}) weekly_data[bot.name] = points - # pass it as JSON + # 4) Render con todo el contexto 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)