From 8c47d07845857199afe7c59c03765ea951b25248 Mon Sep 17 00:00:00 2001 From: Chris Hill-Scott Date: Thu, 5 Mar 2020 10:00:30 +0000 Subject: [PATCH] Optimise method to prevent redundant counting If we know that the most recently returned letter was reported more than 7 days ago then we know, without having to go to the database again, that the count of returned letters in the last 7 days is 0. --- app/service/rest.py | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/app/service/rest.py b/app/service/rest.py index 2ea5a0e53..9e2bef9fc 100644 --- a/app/service/rest.py +++ b/app/service/rest.py @@ -122,7 +122,7 @@ from app.schemas import ( email_data_request_schema ) from app.user.users_schema import post_set_permissions_schema -from app.utils import pagination_links +from app.utils import midnight_n_days_ago, pagination_links service_blueprint = Blueprint('service', __name__) @@ -959,6 +959,16 @@ def returned_letter_statistics(service_id): 'most_recent_report': None, }) + most_recent_reported_at = datetime.combine( + most_recent.reported_at, datetime.min.time() + ) + + if most_recent_reported_at < midnight_n_days_ago(7): + return jsonify({ + 'returned_letter_count': 0, + 'most_recent_report': most_recent.reported_at.strftime(DATETIME_FORMAT_NO_TIMEZONE), + }) + count = fetch_returned_letter_count(service_id) return jsonify({