Add dao method to get template stats per month in financial year for service

This commit is contained in:
Imdad Ahad
2017-02-14 17:59:18 +00:00
parent b0d5def289
commit 8272a4388d
5 changed files with 162 additions and 9 deletions

View File

@@ -29,6 +29,7 @@ from app.models import (
NOTIFICATION_STATUS_TYPES,
TEMPLATE_TYPES,
)
from app.service.statistics import format_monthly_template_notification_stats
from app.statsd_decorators import statsd
from app.utils import get_london_month_from_utc_column
@@ -224,6 +225,38 @@ def _stats_for_service_query(service_id):
)
@statsd(namespace="dao")
def dao_fetch_monthly_historical_stats_by_template_for_service(service_id, year):
month = get_london_month_from_utc_column(NotificationHistory.created_at)
sq = db.session.query(
NotificationHistory.template_id,
NotificationHistory.status,
month.label('month'),
func.count().label('count')
).filter(
NotificationHistory.service_id == service_id,
NotificationHistory.created_at.between(*get_financial_year(year))
).group_by(
month,
NotificationHistory.template_id,
NotificationHistory.status
).subquery()
rows = db.session.query(
Template.id.label('template_id'),
Template.name,
sq.c.status,
sq.c.count.label('count'),
sq.c.month
).join(
sq,
sq.c.template_id == Template.id
).all()
return format_monthly_template_notification_stats(year, rows)
@statsd(namespace="dao")
def dao_fetch_monthly_historical_stats_for_service(service_id, year):
month = get_london_month_from_utc_column(NotificationHistory.created_at)

View File

@@ -1,7 +1,7 @@
import itertools
from datetime import datetime, timedelta
from app.models import TEMPLATE_TYPES
from app.models import NOTIFICATION_STATUS_TYPES, TEMPLATE_TYPES
def format_statistics(statistics):
@@ -15,6 +15,28 @@ def format_statistics(statistics):
return counts
def format_monthly_template_notification_stats(year, rows):
dict = {
datetime.strftime(date, '%Y-%m'): {}
for date in [
datetime(year, month, 1) for month in range(4, 13)
] + [
datetime(year + 1, month, 1) for month in range(1, 4)
]
}
for row in rows:
formatted_month = row.month.strftime('%Y-%m')
if str(row.template_id) not in dict[formatted_month]:
dict[formatted_month][str(row.template_id)] = {
"name": row.name,
"counts": dict.fromkeys(NOTIFICATION_STATUS_TYPES, 0)
}
dict[formatted_month][str(row.template_id)]["counts"][row.status] += row.count
return dict
def create_zeroed_stats_dicts():
return {
template_type: {