Merge pull request #3267 from alphagov/fix-daily-totals-query

Improve the query to get today's totals for a service.
This commit is contained in:
Rebecca Law
2021-06-16 07:34:01 +01:00
committed by GitHub
2 changed files with 18 additions and 5 deletions

View File

@@ -437,15 +437,13 @@ def dao_fetch_todays_stats_for_service(service_id):
def fetch_todays_total_message_count(service_id): def fetch_todays_total_message_count(service_id):
start_date = get_london_midnight_in_utc(date.today())
result = db.session.query( result = db.session.query(
func.count(Notification.id).label('count') func.count(Notification.id).label('count')
).filter( ).filter(
Notification.service_id == service_id, Notification.service_id == service_id,
Notification.key_type != KEY_TYPE_TEST, Notification.key_type != KEY_TYPE_TEST,
func.date(Notification.created_at) == date.today() Notification.created_at >= start_date
).group_by(
Notification.notification_type,
Notification.status,
).first() ).first()
return 0 if result is None else result.count return 0 if result is None else result.count

View File

@@ -985,10 +985,25 @@ def test_fetch_stats_should_not_gather_notifications_older_than_7_days(
def test_dao_fetch_todays_total_message_count_returns_count_for_today(notify_db_session): def test_dao_fetch_todays_total_message_count_returns_count_for_today(notify_db_session):
notification = create_notification(template=create_template(service=create_service())) template = create_template(service=create_service())
notification = create_notification(template=template)
# don't include notifications earlier than today
create_notification(template=template, created_at=datetime.utcnow()-timedelta(days=2))
assert fetch_todays_total_message_count(notification.service.id) == 1 assert fetch_todays_total_message_count(notification.service.id) == 1
def test_dao_fetch_todays_total_message_count_returns_count_for_all_notification_type_and_selected_service(
notify_db_session
):
service = create_service()
different_service = create_service(service_name='different service')
create_notification(template=create_template(service=service))
create_notification(template=create_template(service=service, template_type='email'))
create_notification(template=create_template(service=service, template_type='letter'))
create_notification(template=create_template(service=different_service))
assert fetch_todays_total_message_count(service.id) == 3
def test_dao_fetch_todays_total_message_count_returns_0_when_no_messages_for_today(notify_db, def test_dao_fetch_todays_total_message_count_returns_0_when_no_messages_for_today(notify_db,
notify_db_session): notify_db_session):
assert fetch_todays_total_message_count(uuid.uuid4()) == 0 assert fetch_todays_total_message_count(uuid.uuid4()) == 0