Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dev #76

Merged
merged 5 commits into from
Jan 6, 2024
Merged

Dev #76

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions smartreport_app/email.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from .sync_db_kb import get_kpi_value
from base64 import b64decode
from django.template.loader import render_to_string
from django.core.mail import send_mail

def send_emails_for_unsent_reports():
# Get distinct user types from UserType enumeration
Expand Down Expand Up @@ -103,3 +104,43 @@ def send_emails_for_alarms():
# Send the email
print(f'Success: {email.send()== 1}')


def mail_final_presentation():
from email.mime.image import MIMEImage
from django.core.mail import EmailMultiAlternatives


subject = 'Reporting on wearable device'
body_html = '''
<html>
<body>
<p>Dear Sandra,</p>
<p>We regret to inform you that there seems to be an issue with the wearable device n°1234. </p>
<p>We encourage you to contact the doctor and to check the functioning of the device through your dashboard or the virtual assistant. </p>
<p>Kind regards,<br>The Smartreports team</p>
<img src="cid:yellow.png" width="300" />
</body>
</html>
'''

from_email = settings.DEFAULT_FROM_EMAIL

msg = EmailMultiAlternatives(
subject,
body_html,
from_email=from_email,
to=['[email protected]', '[email protected]'],
# to=['[email protected]'],
# to=['[email protected]']

)

msg.mixed_subtype = 'related'
msg.attach_alternative(body_html, "text/html")
image = 'yellow.png'
with open('/home/matteo/smartreports-backend/smartreport_app/yellow.png', 'rb') as f:
img = MIMEImage(f.read())
img.add_header('Content-ID', '<{name}>'.format(name=image))
img.add_header('Content-Disposition', 'inline', filename=image)
msg.attach(img)
print(msg.send(fail_silently=False))
70 changes: 55 additions & 15 deletions smartreport_app/kb_interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ def kb_interface(params):
start_time = params['start_time']
end_time = params['end_time']
frequency = params['kpi_frequency_list']
predict = params['predict']

if plot_type == 'semaphore':
resp = get_kpi_value(kpi_list[0]) # is only one
Expand Down Expand Up @@ -35,12 +36,11 @@ def kb_interface(params):
'rgb(75, 193, 193)',
'rgb(255, 159, 64)',
'rgb(154, 102, 255)',
'rgb(255, 205, 86)',
'rgb(201, 203, 208)'
'rgb(255, 205, 86)'
]
transp_colors = [color[:-1]+', 0.2)' for color in colors]
frequencies_lbls = {
'monthly': [
'annual': [
'January',
'February',
'March',
Expand All @@ -54,8 +54,8 @@ def kb_interface(params):
'November',
'December'
],
'hourly': [str(i)+':00' for i in range(24)],
'daily': [
'daily': [str(i)+':00' for i in range(24)],
'weekly': [
'Monday',
'Tuesday',
'Wednesday',
Expand All @@ -66,22 +66,36 @@ def kb_interface(params):
]
}

if frequency == 'monthly':
start_freq = start_time.month # int in [0,11]
elif frequency == 'daily':
start_freq = start_time.day # int in [0,6]
elif frequency == 'hourly':
start_freq = start_time.hour # int in [0,11]
elif frequency == 'weekly':
start_freq = 0
# if frequency == 'monthly':
# start_freq = start_time.month # int in [0,11]
# elif frequency == 'daily':
# start_freq = start_time.day # int in [0,6]
# elif frequency == 'hourly':
# start_freq = start_time.hour # int in [0,11]
# elif frequency == 'weekly':
# start_freq = 0

start_freq = 0


kb_resps = []
for i, kpi_uid in enumerate(kpi_list):
kn_resp = get_kpi_value(kpi_uid, start_time, end_time) # call to group 1 api
kb_resps.append(kn_resp)

frequencies_lbls['weekly'] = [f'Week {i}' for i in range(len(kb_resps[0]['value']))] # assuming they all have the same length

if predict:
for key, value in frequencies_lbls.items():
value.append(['Monday' ,'Prediction']) # TODO start after the current date
value.append(['Tuesday' ,'Prediction'])


for kb_resp in kb_resps:
kb_resp['value'].append(random.random()) # TODO actual prediction
kb_resp['value'].append(random.random())




labels = []
datasets = []
Expand All @@ -95,7 +109,31 @@ def kb_interface(params):
dataset['fill'] = False
dataset['borderColor'] = colors[i%len(colors)]
dataset['backgroundColor'] = transp_colors[i%len(colors)]
dataset['tension'] = 0.1
dataset['tension'] = 0
if predict:
dashed_dataset = {}
dashed_dataset['fill'] = False
dashed_dataset['borderColor'] = colors[i%len(colors)]
dashed_dataset['backgroundColor'] = transp_colors[i%len(colors)]
dashed_dataset['tension'] = 0.8
dashed_dataset['label'] = kb_resp['name'] + ' ' +'Prediction'
dashed_dataset['data'] = []

# put to None all the values of the dashed dataset except the last two
for i, val in enumerate(dataset['data']):
if i == len(dataset['data'])-1 or i == len(dataset['data'])-2 or i == len(dataset['data'])-3:
dashed_dataset['data'].append(val)
else:
dashed_dataset['data'].append(None)

# remove the last two value from the original dataset
dataset['data'][-1] = None
dataset['data'][-2] = None

dashed_dataset['borderDash'] = [1, 1]

datasets.append(dashed_dataset)

elif plot_type == 'bar':
dataset['borderColor'] = colors[i%len(colors)]
dataset['backgroundColor'] = colors[i%len(colors)]
Expand All @@ -108,6 +146,8 @@ def kb_interface(params):
dataset['backgroundColor'] = colors
datasets.append(dataset)

datasets.reverse()

response = {
'labels': labels,
'datasets': datasets
Expand Down
16 changes: 12 additions & 4 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
from .email import send_emails_for_unsent_reports, send_emails_for_alarms, mail_final_presentation

from .models import (
KpiReportElement,
Expand Down Expand Up @@ -112,7 +112,7 @@ def __init__(self, **kwargs: Any) -> None:
super().__init__(**kwargs)

def list(self, request):
params = request.query_params
params = request.query_params.copy()

if 'kpis' not in params or params.getlist("kpis") == []:
return Response({"message": "The required parameter 'kpis' is missing"}, status=status.HTTP_400_BAD_REQUEST)
Expand All @@ -127,6 +127,10 @@ def list(self, request):
if 'chart_type' not in params:
return Response({"message": "The required parameter 'chart_type' is missing"}, status=status.HTTP_400_BAD_REQUEST)

# TODO remove after testing
if params["chart_type"] == 'line':
params['predict'] = True

if list_of_KB_uids == []:
return Response({"message": "No kpis found"}, status=status.HTTP_400_BAD_REQUEST)

Expand All @@ -136,8 +140,10 @@ def list(self, request):

if params["chart_type"] in ["semaphore", "value"] and len(list_of_KB_uids) > 1:
return Response({"message": "This plot only supports one kpi"}, status=status.HTTP_400_BAD_REQUEST)

if 'predict' in params and params["predict"] == "true" and params['chart_type'] != 'line':
return Response({"message": "This plot does not support prediction"}, status=status.HTTP_400_BAD_REQUEST)


# TODO implement start and end time
# TODO for now frequency is only weekly
kb_interface_params = {
Expand All @@ -146,6 +152,7 @@ def list(self, request):
'kpi_frequency_list' : 'weekly',
'start_time' : 'boh',
'end_time' : 'boh',
'predict' : params['predict'] if 'predict' in params else False,
}

data = kb_interface(params = kb_interface_params)
Expand Down Expand Up @@ -187,5 +194,6 @@ def __init__(self, **kwargs: Any) -> None:
super().__init__(**kwargs)

def list(self, request):
send_emails_for_alarms()
mail_final_presentation()
# send_emails_for_alarms()
return Response({"message": "Sending emails"})
Binary file added smartreport_app/yellow.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
8 changes: 8 additions & 0 deletions smartreport_app/yellow_semaphore.html

Large diffs are not rendered by default.

Loading