From af3f2008bb8ee816283613ad96c3daeae3d42e16 Mon Sep 17 00:00:00 2001 From: matteotolloso Date: Sun, 14 Jan 2024 15:55:20 +0100 Subject: [PATCH] kpi mail & chat storage --- smartreport_app/email.py | 26 +++++++++++++++++++++++++- smartreport_app/models.py | 12 ++++++++++++ smartreport_app/serializers.py | 5 +++++ smartreport_app/urls.py | 2 ++ smartreport_app/views.py | 33 +++++++++++++++++++++++++++++++-- 5 files changed, 75 insertions(+), 3 deletions(-) diff --git a/smartreport_app/email.py b/smartreport_app/email.py index 3ec6514..63b45f0 100644 --- a/smartreport_app/email.py +++ b/smartreport_app/email.py @@ -1,7 +1,7 @@ from django.core.mail import EmailMessage from django.conf import settings from django.forms import ValidationError -from .models import UserType, ArchivedReport, Email, Alarm +from .models import UserType, ArchivedReport, Email, Alarm, Kpi from .sync_db_kb import get_kpi_value from base64 import b64decode from django.template.loader import render_to_string @@ -104,6 +104,30 @@ def send_emails_for_alarms(): # Send the email print(f'Success: {email.send()== 1}') +def send_kpi_mail(address, kpi_id): + + kpi = Kpi.objects.get(id=kpi_id) + subject = f'SmartReports KPI Notification' + message = f'Dear user,\nYou requested an update about the {kpi.kb_name} from the chatbot, the current value is: {get_kpi_value(kpi.kb_uid)["value"][-1]}.\n' + + print(f'DEBUG {address}') + print(f'DEBUG {kpi.kb_name}') + + email = EmailMessage( + subject = subject, + body = message, + from_email = settings.DEFAULT_FROM_EMAIL, + to = [address], + reply_to = [settings.DEFAULT_FROM_EMAIL], + ) + email.content_subtype = 'html' + + print(f'sending mail for {kpi.kb_uid} to {address}') + # Send the email + print(f'Success: {email.send()== 1}') + + return email.send() == 1 # Return True if the email was sent successfully, False otherwise. + def mail_final_presentation(): from email.mime.image import MIMEImage diff --git a/smartreport_app/models.py b/smartreport_app/models.py index 8d2bc0d..ddb639a 100644 --- a/smartreport_app/models.py +++ b/smartreport_app/models.py @@ -214,3 +214,15 @@ class Email(models.Model): def clean(self): if not isinstance(self.emails, list): raise ValidationError("Emails must be a list") + +class Chat(models.Model): + + chat_id = models.IntegerField() + + user_type = models.CharField( + max_length=128, + choices=UserType.choices, + ) + + content = models.JSONField() + diff --git a/smartreport_app/serializers.py b/smartreport_app/serializers.py index 8ae9c76..5e5e909 100644 --- a/smartreport_app/serializers.py +++ b/smartreport_app/serializers.py @@ -9,6 +9,7 @@ DashboardLayout, ArchivedReport, SmartReportTemplate, + Chat, ) @@ -119,3 +120,7 @@ class Meta: model = ArchivedReport fields = "__all__" +class ChatSerializer(serializers.ModelSerializer): + class Meta: + model = Chat + fields = "__all__" \ No newline at end of file diff --git a/smartreport_app/urls.py b/smartreport_app/urls.py index af8f37a..36125d3 100644 --- a/smartreport_app/urls.py +++ b/smartreport_app/urls.py @@ -17,6 +17,8 @@ router.register(r'smart-reports', views.SmartReportTemplateViewSet, basename='smart-reports') router.register(r'send-reports', views.SendReportEmailsViewSet, basename='send-emails') router.register(r'send-alarms', views.SendAlarmEmailsViewSet, basename='send-alarms') +router.register(r'chat', views.ChatViewSet) +router.register(r"send-mail", views.SendMailViewSet, basename="send-mail") # The API URLs are now determined automatically by the router. urlpatterns = [path("", include(router.urls))] diff --git a/smartreport_app/views.py b/smartreport_app/views.py index 8b3ab96..8375c7d 100644 --- a/smartreport_app/views.py +++ b/smartreport_app/views.py @@ -2,7 +2,7 @@ from typing import Any import django_filters from .sync_db_kb import sync_kpi_lits -from .email import send_emails_for_unsent_reports, send_emails_for_alarms, mail_final_presentation +from .email import send_emails_for_unsent_reports, send_emails_for_alarms, mail_final_presentation, send_kpi_mail from .models import ( KpiReportElement, @@ -14,6 +14,7 @@ DashboardLayout, ArchivedReport, SmartReportTemplate, + Chat, ) from .serializers import ( ReportTemplatePageSerializer, @@ -25,6 +26,7 @@ DashboardLayoutSerializer, ArchivedReportSerializer, SmartTemplateSerializer, + ChatSerializer, ) from rest_framework.response import Response from rest_framework import status @@ -154,6 +156,25 @@ def list(self, request): data = kb_interface(params = kb_interface_params) return Response({"data": data}) +class SendMailViewSet(viewsets.GenericViewSet): + def __init__(self, **kwargs: Any) -> None: + if (os.environ.get("DEBUG").lower() == "false"): + self.permission_classes = [IsAuthenticated] + super().__init__(**kwargs) + + def list(self, request): + params = request.query_params.copy() + + if 'mail' not in params: + return Response({"message": "The required parameter 'mail' is missing"}, status=status.HTTP_400_BAD_REQUEST) + + if 'kpi' not in params: + return Response({"message": "The required parameter 'kpi' is missing"}, status=status.HTTP_400_BAD_REQUEST) + + ret = send_kpi_mail(params['mail'], params['kpi']) + + return Response({"Mail send success?": ret}) + class ArchivedReportViewSet(viewsets.ModelViewSet): queryset = ArchivedReport.objects.all() @@ -192,4 +213,12 @@ def __init__(self, **kwargs: Any) -> None: def list(self, request): mail_final_presentation() # send_emails_for_alarms() - return Response({"message": "Sending emails"}) \ No newline at end of file + return Response({"message": "Sending emails"}) + +class ChatViewSet(viewsets.ModelViewSet): + queryset = Chat.objects.all() + serializer_class = ChatSerializer + filterset_fields = ["chat_id"] + + +