Files
notifications-admin/app/main/views/dashboard.py
T

488 lines
16 KiB
Python
Raw Normal View History

import calendar
from datetime import datetime
2017-02-16 15:08:16 +00:00
from functools import partial
from itertools import groupby
2018-02-20 11:22:17 +00:00
from flask import (
Response,
2018-02-20 11:22:17 +00:00
abort,
jsonify,
render_template,
request,
session,
url_for,
)
from flask_login import current_user
2017-11-24 16:34:45 +00:00
from werkzeug.utils import redirect
2017-06-06 12:57:55 +01:00
from app import (
billing_api_client,
2018-02-20 11:22:17 +00:00
current_service,
format_date_numeric,
format_datetime_numeric,
service_api_client,
template_statistics_client,
)
2018-02-20 11:22:17 +00:00
from app.main import main
2020-01-08 14:29:56 +00:00
from app.statistics_utils import get_formatted_percentage
2017-01-30 17:27:09 +00:00
from app.utils import (
DELIVERED_STATUSES,
2017-01-30 17:27:09 +00:00
FAILURE_STATUSES,
REQUESTED_STATUSES,
Spreadsheet,
2018-03-21 15:08:03 +00:00
generate_next_dict,
generate_previous_dict,
2018-02-20 11:22:17 +00:00
get_current_financial_year,
user_has_permissions,
2017-01-30 17:27:09 +00:00
)
2015-12-18 10:26:56 +00:00
2019-11-04 11:07:55 +00:00
@main.route("/services/<uuid:service_id>/dashboard")
2018-06-14 11:39:06 +01:00
@user_has_permissions('view_activity', 'send_messages')
2018-02-14 10:38:00 +00:00
def old_service_dashboard(service_id):
return redirect(url_for('.service_dashboard', service_id=service_id))
2019-11-04 11:07:55 +00:00
@main.route("/services/<uuid:service_id>")
@user_has_permissions()
def service_dashboard(service_id):
if session.get('invited_user'):
session.pop('invited_user', None)
session['service_id'] = service_id
if not current_user.has_permissions('view_activity'):
return redirect(url_for('main.choose_template', service_id=service_id))
2015-12-18 10:26:56 +00:00
return render_template(
2016-03-17 11:45:48 +00:00
'views/dashboard/dashboard.html',
2016-06-28 09:21:46 +01:00
updates_url=url_for(".service_dashboard_updates", service_id=service_id),
partials=get_dashboard_partials(service_id)
)
2016-03-17 11:45:48 +00:00
2019-11-04 11:07:55 +00:00
@main.route("/services/<uuid:service_id>/dashboard.json")
@user_has_permissions('view_activity')
2016-03-23 08:43:45 +00:00
def service_dashboard_updates(service_id):
return jsonify(**get_dashboard_partials(service_id))
2016-03-23 08:43:45 +00:00
2019-11-04 11:07:55 +00:00
@main.route("/services/<uuid:service_id>/template-activity")
@user_has_permissions('view_activity')
def template_history(service_id):
2017-02-16 15:08:16 +00:00
2017-11-24 16:34:45 +00:00
return redirect(url_for('main.template_usage', service_id=service_id), code=301)
2019-11-04 11:07:55 +00:00
@main.route("/services/<uuid:service_id>/template-usage")
@user_has_permissions('view_activity')
def template_usage(service_id):
year, current_financial_year = requested_and_current_financial_year(request)
stats = template_statistics_client.get_monthly_template_usage_for_service(service_id, year)
stats = sorted(stats, key=lambda x: (x['count']), reverse=True)
2017-11-22 15:50:31 +00:00
def get_monthly_template_stats(month_name, stats):
return {
'name': month_name,
'templates_used': [
{
'id': stat['template_id'],
'name': stat['name'],
'type': stat['type'],
'requested_count': stat['count']
2017-11-22 15:50:31 +00:00
}
for stat in stats
if calendar.month_name[int(stat['month'])] == month_name
],
}
months = [
get_monthly_template_stats(month, stats)
for month in get_months_for_financial_year(year, time_format='%B')
]
return render_template(
'views/dashboard/all-template-statistics.html',
months=months,
stats=stats,
most_used_template_count=max(
max((
template['requested_count']
for template in month['templates_used']
), default=0)
for month in months
),
years=get_tuples_of_financial_years(
partial(url_for, '.template_usage', service_id=service_id),
start=current_financial_year - 2,
end=current_financial_year,
),
selected_year=year
)
2019-11-04 11:07:55 +00:00
@main.route("/services/<uuid:service_id>/usage")
@user_has_permissions('manage_service', allow_org_user=True)
def usage(service_id):
year, current_financial_year = requested_and_current_financial_year(request)
free_sms_allowance = billing_api_client.get_free_sms_fragment_limit_for_year(service_id, year)
units = billing_api_client.get_billable_units(service_id, year)
yearly_usage = billing_api_client.get_service_usage(service_id, year)
2016-04-20 15:37:17 +01:00
return render_template(
2019-10-29 16:27:58 +00:00
'views/usage.html',
2017-04-26 17:09:07 +01:00
months=list(get_free_paid_breakdown_for_billable_units(
year,
free_sms_allowance,
2017-12-15 17:28:52 +00:00
units
2017-04-26 17:09:07 +01:00
)),
2017-01-25 15:59:06 +00:00
selected_year=year,
2017-02-16 15:08:16 +00:00
years=get_tuples_of_financial_years(
partial(url_for, '.usage', service_id=service_id),
start=current_financial_year - 1,
end=current_financial_year + 1,
),
2017-12-15 17:28:52 +00:00
**calculate_usage(yearly_usage,
free_sms_allowance)
2016-04-20 15:37:17 +01:00
)
2019-11-04 11:07:55 +00:00
@main.route("/services/<uuid:service_id>/monthly")
@user_has_permissions('view_activity')
2017-01-30 17:27:09 +00:00
def monthly(service_id):
year, current_financial_year = requested_and_current_financial_year(request)
return render_template(
2017-01-30 17:27:09 +00:00
'views/dashboard/monthly.html',
months=format_monthly_stats_to_list(
service_api_client.get_monthly_notification_stats(service_id, year)['data']
),
2017-02-16 15:08:16 +00:00
years=get_tuples_of_financial_years(
partial_url=partial(url_for, '.monthly', service_id=service_id),
start=current_financial_year - 2,
2017-02-16 15:08:16 +00:00
end=current_financial_year,
),
2017-01-30 17:27:09 +00:00
selected_year=year,
)
2019-11-04 11:07:55 +00:00
@main.route("/services/<uuid:service_id>/inbox")
@user_has_permissions('view_activity')
2017-05-22 17:02:03 +01:00
def inbox(service_id):
2017-07-07 15:51:59 +01:00
return render_template(
'views/dashboard/inbox.html',
partials=get_inbox_partials(service_id),
2018-03-21 15:08:03 +00:00
updates_url=url_for('.inbox_updates', service_id=service_id, page=request.args.get('page')),
2017-07-07 15:51:59 +01:00
)
2019-11-04 11:07:55 +00:00
@main.route("/services/<uuid:service_id>/inbox.json")
@user_has_permissions('view_activity')
2017-07-07 15:51:59 +01:00
def inbox_updates(service_id):
return jsonify(get_inbox_partials(service_id))
2019-11-04 11:07:55 +00:00
@main.route("/services/<uuid:service_id>/inbox.csv")
@user_has_permissions('view_activity')
def inbox_download(service_id):
return Response(
Spreadsheet.from_rows(
[[
'Phone number',
'Message',
'Received',
]] + [[
message['user_number'],
message['content'].lstrip(('=+-@')),
format_datetime_numeric(message['created_at']),
2018-03-21 15:08:03 +00:00
] for message in service_api_client.get_inbound_sms(service_id)['data']]
).as_csv_data,
mimetype='text/csv',
headers={
'Content-Disposition': 'inline; filename="Received text messages {}.csv"'.format(
format_date_numeric(datetime.utcnow().isoformat())
)
}
)
2017-07-07 15:51:59 +01:00
def get_inbox_partials(service_id):
2018-03-21 15:08:03 +00:00
page = int(request.args.get('page', 1))
if not current_service.has_permission('inbound_sms'):
abort(403)
inbound_messages_data = service_api_client.get_most_recent_inbound_sms(service_id, page=page)
2018-03-21 15:08:03 +00:00
inbound_messages = inbound_messages_data['data']
if not inbound_messages:
2019-03-29 15:16:29 +00:00
inbound_number = current_service.inbound_number
else:
inbound_number = None
2018-03-21 15:08:03 +00:00
prev_page = None
if page > 1:
prev_page = generate_previous_dict('main.inbox', service_id, page)
next_page = None
if inbound_messages_data['has_next']:
next_page = generate_next_dict('main.inbox', service_id, page)
2017-07-07 15:51:59 +01:00
return {'messages': render_template(
'views/dashboard/_inbox_messages.html',
2018-04-04 15:39:50 +01:00
messages=inbound_messages,
inbound_number=inbound_number,
2018-03-21 15:08:03 +00:00
prev_page=prev_page,
next_page=next_page
2017-07-07 15:51:59 +01:00
)}
2017-05-22 17:02:03 +01:00
def filter_out_cancelled_stats(template_statistics):
return [s for s in template_statistics if s["status"] != "cancelled"]
def aggregate_template_usage(template_statistics, sort_key='count'):
template_statistics = filter_out_cancelled_stats(template_statistics)
templates = []
for k, v in groupby(sorted(template_statistics, key=lambda x: x['template_id']), key=lambda x: x['template_id']):
template_stats = list(v)
templates.append({
"template_id": k,
"template_name": template_stats[0]['template_name'],
"template_type": template_stats[0]['template_type'],
"is_precompiled_letter": template_stats[0]['is_precompiled_letter'],
"count": sum(s['count'] for s in template_stats)
})
return sorted(templates, key=lambda x: x[sort_key], reverse=True)
2016-04-12 11:42:45 +01:00
def aggregate_notifications_stats(template_statistics):
template_statistics = filter_out_cancelled_stats(template_statistics)
notifications = {
template_type: {
status: 0 for status in ('requested', 'delivered', 'failed')
2019-01-16 10:54:52 +00:00
} for template_type in ["sms", "email", "letter"]
}
for stat in template_statistics:
notifications[stat["template_type"]]["requested"] += stat["count"]
if stat["status"] in DELIVERED_STATUSES:
notifications[stat["template_type"]]["delivered"] += stat["count"]
elif stat["status"] in FAILURE_STATUSES:
notifications[stat["template_type"]]["failed"] += stat["count"]
return notifications
def get_dashboard_partials(service_id):
all_statistics = template_statistics_client.get_template_statistics_for_service(service_id, limit_days=7)
template_statistics = aggregate_template_usage(all_statistics)
stats = aggregate_notifications_stats(all_statistics)
2019-10-25 15:34:01 +01:00
dashboard_totals = get_dashboard_totals(stats),
2019-10-25 13:27:46 +01:00
free_sms_allowance = billing_api_client.get_free_sms_fragment_limit_for_year(
current_service.id,
get_current_financial_year(),
)
yearly_usage = billing_api_client.get_service_usage(
service_id,
get_current_financial_year(),
)
return {
2016-08-09 10:39:57 +01:00
'upcoming': render_template(
'views/dashboard/_upcoming.html',
),
2017-05-22 17:02:03 +01:00
'inbox': render_template(
'views/dashboard/_inbox.html',
),
'totals': render_template(
'views/dashboard/_totals.html',
service_id=service_id,
statistics=dashboard_totals[0],
2016-04-20 15:37:17 +01:00
),
'template-statistics': render_template(
'views/dashboard/template-statistics.html',
template_statistics=template_statistics,
most_used_template_count=max(
[row['count'] for row in template_statistics] or [0]
),
),
2019-10-25 13:27:46 +01:00
'usage': render_template(
'views/dashboard/_usage.html',
**calculate_usage(yearly_usage, free_sms_allowance),
),
}
2016-07-20 14:12:03 +01:00
def get_dashboard_totals(statistics):
for msg_type in statistics.values():
msg_type['failed_percentage'] = get_formatted_percentage(msg_type['failed'], msg_type['requested'])
msg_type['show_warning'] = float(msg_type['failed_percentage']) > 3
2016-07-20 14:12:03 +01:00
return statistics
2016-07-19 13:53:27 +01:00
def calculate_usage(usage, free_sms_fragment_limit):
2018-05-17 10:31:21 +01:00
sms_breakdowns = [breakdown for breakdown in usage if breakdown['notification_type'] == 'sms']
# this relies on the assumption: only one SMS rate per financial year.
sms_rate = 0 if len(sms_breakdowns) == 0 else sms_breakdowns[0].get("rate", 0)
sms_sent = get_sum_billing_units(sms_breakdowns)
sms_free_allowance = free_sms_fragment_limit
2017-05-02 14:10:56 +01:00
emails = [breakdown["billing_units"] for breakdown in usage if breakdown['notification_type'] == 'email']
emails_sent = 0 if len(emails) == 0 else emails[0]
2017-12-19 14:35:10 +00:00
letters = [(breakdown["billing_units"], breakdown['letter_total']) for breakdown in usage if
breakdown['notification_type'] == 'letter']
letter_sent = sum(row[0] for row in letters)
letter_cost = sum(row[1] for row in letters)
2017-12-19 14:35:10 +00:00
return {
2016-04-20 15:37:17 +01:00
'emails_sent': emails_sent,
'sms_free_allowance': sms_free_allowance,
'sms_sent': sms_sent,
'sms_allowance_remaining': max(0, (sms_free_allowance - sms_sent)),
'sms_chargeable': max(0, sms_sent - sms_free_allowance),
'sms_rate': sms_rate,
2017-12-19 14:35:10 +00:00
'letter_sent': letter_sent,
'letter_cost': letter_cost
}
2017-01-30 17:27:09 +00:00
def format_monthly_stats_to_list(historical_stats):
return sorted((
dict(
date=key,
2017-10-27 10:56:03 +01:00
future=yyyy_mm_to_datetime(key) > datetime.utcnow(),
name=yyyy_mm_to_datetime(key).strftime('%B'),
2017-01-30 17:27:09 +00:00
**aggregate_status_types(value)
) for key, value in historical_stats.items()
), key=lambda x: x['date'])
2017-10-27 10:56:03 +01:00
def yyyy_mm_to_datetime(string):
2017-02-08 11:16:11 +00:00
return datetime(int(string[0:4]), int(string[5:7]), 1)
2017-01-30 17:27:09 +00:00
def aggregate_status_types(counts_dict):
return get_dashboard_totals({
'{}_counts'.format(message_type): {
'failed': sum(
stats.get(status, 0) for status in FAILURE_STATUSES
),
'requested': sum(
stats.get(status, 0) for status in REQUESTED_STATUSES
)
} for message_type, stats in counts_dict.items()
})
2016-09-29 18:44:10 +01:00
2017-02-16 15:08:16 +00:00
def get_months_for_financial_year(year, time_format='%B'):
2016-09-29 18:44:10 +01:00
return [
2017-02-16 15:08:16 +00:00
month.strftime(time_format)
2016-09-29 18:44:10 +01:00
for month in (
get_months_for_year(4, 13, year) +
get_months_for_year(1, 4, year + 1)
)
if month < datetime.now()
]
def get_months_for_year(start, end, year):
return [datetime(year, month, 1) for month in range(start, end)]
2017-04-26 17:09:07 +01:00
def get_sum_billing_units(billing_units, month=None):
if month:
return sum(b['billing_units'] for b in billing_units if b['month'] == month)
return sum(b['billing_units'] for b in billing_units)
def get_free_paid_breakdown_for_billable_units(year, free_sms_fragment_limit, billing_units):
2016-09-29 18:44:10 +01:00
cumulative = 0
2017-12-15 17:28:52 +00:00
letter_cumulative = 0
sms_units = [x for x in billing_units if x['notification_type'] == 'sms']
letter_units = [x for x in billing_units if x['notification_type'] == 'letter']
2016-09-29 18:44:10 +01:00
for month in get_months_for_financial_year(year):
previous_cumulative = cumulative
2017-12-15 17:28:52 +00:00
monthly_usage = get_sum_billing_units(sms_units, month)
2016-09-29 18:44:10 +01:00
cumulative += monthly_usage
breakdown = get_free_paid_breakdown_for_month(
free_sms_fragment_limit, cumulative, previous_cumulative,
2017-12-15 17:28:52 +00:00
[billing_month for billing_month in sms_units if billing_month['month'] == month]
2016-09-29 18:44:10 +01:00
)
2018-10-03 11:18:46 +01:00
letter_billing = [(x['billing_units'], x['rate'], (x['billing_units'] * x['rate']), x['postage'])
2017-12-19 14:35:10 +00:00
for x in letter_units if x['month'] == month]
2018-10-03 11:18:46 +01:00
if letter_billing:
letter_billing.sort(key=lambda x: (x[3], x[1]))
2017-12-19 14:35:10 +00:00
letter_total = 0
for x in letter_billing:
letter_total += x[2]
letter_cumulative += letter_total
2016-09-29 18:44:10 +01:00
yield {
'name': month,
2017-12-19 14:35:10 +00:00
'letter_total': letter_total,
'letter_cumulative': letter_cumulative,
2016-09-29 18:44:10 +01:00
'paid': breakdown['paid'],
2017-12-15 17:28:52 +00:00
'free': breakdown['free'],
'letters': letter_billing
2016-09-29 18:44:10 +01:00
}
def get_free_paid_breakdown_for_month(
free_sms_fragment_limit,
2016-09-29 18:44:10 +01:00
cumulative,
previous_cumulative,
monthly_usage
):
allowance = free_sms_fragment_limit
2016-09-29 18:44:10 +01:00
2017-04-26 17:09:07 +01:00
total_monthly_billing_units = get_sum_billing_units(monthly_usage)
2017-04-25 19:03:59 +01:00
2016-09-29 18:44:10 +01:00
if cumulative < allowance:
return {
'paid': 0,
2017-04-26 17:09:07 +01:00
'free': total_monthly_billing_units,
2016-09-29 18:44:10 +01:00
}
elif previous_cumulative < allowance:
2017-04-25 19:03:59 +01:00
remaining_allowance = allowance - previous_cumulative
2016-09-29 18:44:10 +01:00
return {
2017-04-26 17:09:07 +01:00
'paid': total_monthly_billing_units - remaining_allowance,
2017-04-25 19:03:59 +01:00
'free': remaining_allowance,
2016-09-29 18:44:10 +01:00
}
else:
return {
2017-04-26 17:09:07 +01:00
'paid': total_monthly_billing_units,
2017-04-25 19:03:59 +01:00
'free': 0,
2016-09-29 18:44:10 +01:00
}
2017-01-30 17:27:09 +00:00
def requested_and_current_financial_year(request):
try:
return (
int(request.args.get('year', get_current_financial_year())),
get_current_financial_year(),
)
except ValueError:
abort(404)
2017-02-16 15:08:16 +00:00
def get_tuples_of_financial_years(
partial_url,
start=2015,
end=None,
):
return (
(
'financial year',
year,
partial_url(year=year),
'{} to {}'.format(year, year + 1),
)
for year in range(start, end + 1)
)