Skip to content

Commit

Permalink
alarms (to test)
Browse files Browse the repository at this point in the history
  • Loading branch information
matteotolloso committed Nov 26, 2023
1 parent c61c00e commit 671a10b
Show file tree
Hide file tree
Showing 5 changed files with 66 additions and 9 deletions.
11 changes: 9 additions & 2 deletions smartreport_app/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
ReportTemplateImage,
KpiReportElement,
Alarm,
DashboardLayout
DashboardLayout,
Email
)


Expand Down Expand Up @@ -69,4 +70,10 @@ class DashboardLayoutAdmin(admin.ModelAdmin):
class ReportTemplateImageAdmin(admin.ModelAdmin):
list_display = ('id', 'user_type', 'report_id', 'img')
list_filter = ('report_id', 'user_type')
search_fields = ('report_id', 'user_type')
search_fields = ('report_id', 'user_type')

@admin.register(Email)
class EmailAdmin(admin.ModelAdmin):
list_display = ('id', 'user_type', 'emails')
list_filter = ('user_type', )
search_fields = ('user_type', )
35 changes: 34 additions & 1 deletion smartreport_app/email.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from django.core.mail import EmailMessage
from django.conf import settings
from django.forms import ValidationError
from .models import UserType, ArchivedReport, Email
from .models import UserType, ArchivedReport, Email, Alarm
from .sync_db_kb import get_kpi_value

def send_emails_for_unsent_reports():
# Get distinct user types from UserType enumeration
Expand Down Expand Up @@ -54,3 +55,35 @@ def send_emails_for_unsent_reports():
except Exception as e:
print(f"An error occurred: {e}")


def send_emails_for_alarms():

alarms = Alarm.objects.all().order_by('kpi', 'user_type')

current_kpi_uid = None
current_kpi_value = None

for alarm in alarms:

if alarm.kpi.kb_uid != current_kpi_uid: # update for the new kpi
current_kpi_uid = alarm.kpi.kb_uid
current_kpi_value = get_kpi_value(current_kpi_uid)


if current_kpi_value <= alarm.min_value or current_kpi_value >= alarm.max_value:
# Create an EmailMessage object
subject = 'SmartReports Alarm'
message = f'The value of {alarm.kpi.kb_name} is {current_kpi_value}.'
email = EmailMessage(
subject = subject,
body = message,
from_email = settings.DEFAULT_FROM_EMAIL,
to = Email.objects.get(user_type=alarm.user_type).emails,
reply_to = [settings.DEFAULT_FROM_EMAIL],
)

print(f'sending mail for {current_kpi_uid} to {Email.objects.get(user_type=alarm.user_type).emails}')

# Send the email
print(f'Success: {email.send()== 1}')

12 changes: 9 additions & 3 deletions smartreport_app/sync_db_kb.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,18 @@
from .models import Kpi


URL = 'https://vornao.dev:8888/kpis'
BASE_URL = 'https://vornao.dev:8888'
USERNAME = 'smartapp'
PASSWORD = 'api'


def sync_kpi_lits():

print("start sync_kpi_lits")
url = BASE_URL+'/kpis/'

kpi_list = requests.get(URL, auth=(USERNAME, PASSWORD))
print(f"start sync_kpi_lits, URL={url}")

kpi_list = requests.get(url, auth=(USERNAME, PASSWORD))

for kpi in kpi_list.json()['data']:

Expand Down Expand Up @@ -51,6 +53,10 @@ def sync_kpi_lits():
kpi_instance.save()
print(f"KPI {kpi['uid']} created")


def get_kpi_value(kpi_uid):
kpi_value = requests.get(f'{BASE_URL}/kpi/{kpi_uid}', auth=(USERNAME, PASSWORD))
return kpi_value.json()['data']['value']

if __name__ == '__main__':
sync_kpi_lits()
Expand Down
3 changes: 2 additions & 1 deletion smartreport_app/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
router.register(r"dashboard-layout", views.DashboardLayoutViewSet)
router.register(r"kpi-data", views.KpiDataViewSet, basename="kpi-data")
router.register(r'sync-kb', views.SyncKBViewSet, basename='sync-kb')
router.register(r'send-emails', views.SendEmailsViewSet, basename='send-emails')
router.register(r'send-reports', views.SendReportEmailsViewSet, basename='send-emails')
router.register(r'send-alarms', views.SendAlarmEmailsViewSet, basename='send-alarms')

# The API URLs are now determined automatically by the router.
urlpatterns = [path("", include(router.urls))]
14 changes: 12 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
from .email import send_emails_for_unsent_reports, send_emails_for_alarms

from .models import (
KpiReportElement,
Expand Down Expand Up @@ -154,12 +154,22 @@ def list(self, request):
return Response({"message": "Syncing KB"})


class SendEmailsViewSet(viewsets.GenericViewSet):
class SendReportEmailsViewSet(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):
send_emails_for_unsent_reports()
return Response({"message": "Sending emails"})

class SendAlarmEmailsViewSet(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):
send_emails_for_alarms()
return Response({"message": "Sending emails"})

0 comments on commit 671a10b

Please sign in to comment.