Skip to content

Commit

Permalink
Merge pull request #79 from SmartReports/dev
Browse files Browse the repository at this point in the history
kpi mail & chat storage
  • Loading branch information
matteotolloso authored Jan 14, 2024
2 parents 6761c8f + af3f200 commit 0e15ba9
Show file tree
Hide file tree
Showing 5 changed files with 75 additions and 3 deletions.
26 changes: 25 additions & 1 deletion smartreport_app/email.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions smartreport_app/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

5 changes: 5 additions & 0 deletions smartreport_app/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
DashboardLayout,
ArchivedReport,
SmartReportTemplate,
Chat,
)


Expand Down Expand Up @@ -119,3 +120,7 @@ class Meta:
model = ArchivedReport
fields = "__all__"

class ChatSerializer(serializers.ModelSerializer):
class Meta:
model = Chat
fields = "__all__"
2 changes: 2 additions & 0 deletions smartreport_app/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))]
33 changes: 31 additions & 2 deletions smartreport_app/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -14,6 +14,7 @@
DashboardLayout,
ArchivedReport,
SmartReportTemplate,
Chat,
)
from .serializers import (
ReportTemplatePageSerializer,
Expand All @@ -25,6 +26,7 @@
DashboardLayoutSerializer,
ArchivedReportSerializer,
SmartTemplateSerializer,
ChatSerializer,
)
from rest_framework.response import Response
from rest_framework import status
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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"})
return Response({"message": "Sending emails"})

class ChatViewSet(viewsets.ModelViewSet):
queryset = Chat.objects.all()
serializer_class = ChatSerializer
filterset_fields = ["chat_id"]



0 comments on commit 0e15ba9

Please sign in to comment.