From 89c48757c68a9fc9f275a789117209fd90d751e8 Mon Sep 17 00:00:00 2001 From: Baptiste Jonglez Date: Wed, 20 Oct 2021 22:44:52 +0200 Subject: [PATCH] Display monthly statistics for the range of months where the project was active instead of the currently hard-coded "one year" range in the past starting from today. --- ihatemoney/models.py | 8 ++++++++ ihatemoney/web.py | 16 ++++++++++++++-- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/ihatemoney/models.py b/ihatemoney/models.py index e0ca07040..f14c20784 100644 --- a/ihatemoney/models.py +++ b/ihatemoney/models.py @@ -257,6 +257,14 @@ def get_member_bills(self, member_id): .order_by(Bill.id.desc()) ) + def get_most_recent_bill(self): + """Returns the most recent bill (according to bill date) or None if there are no bills""" + return self.get_bills_unordered().order_by(Bill.date.desc()).first() + + def get_least_recent_bill(self): + """Returns the least recent bill (according to bill date) or None if there are no bills""" + return self.get_bills_unordered().order_by(Bill.date.asc()).first() + def get_pretty_bills(self, export_format="json"): """Return a list of project's bills with pretty formatting""" bills = self.get_bills() diff --git a/ihatemoney/web.py b/ihatemoney/web.py index f783cd865..3bcc9eb73 100644 --- a/ihatemoney/web.py +++ b/ihatemoney/web.py @@ -10,6 +10,7 @@ """ from datetime import datetime from functools import wraps +import itertools import json import os @@ -895,12 +896,23 @@ def strip_ip_addresses(): @main.route("//statistics") def statistics(): """Compute what each member has paid and spent and display it""" - today = datetime.now() + if g.project.has_bills(): + first_date = g.project.get_least_recent_bill().date + last_date = g.project.get_most_recent_bill().date + else: + first_date = datetime.now() - relativedelta(months=12) + last_date = datetime.now() + # Infinite iterator towards the past + all_months = (last_date - relativedelta(months=i) for i in itertools.count()) + # Stop when reaching one month before the first date + months = itertools.takewhile( + lambda x: x > first_date - relativedelta(months=1), all_months + ) return render_template( "statistics.html", members_stats=g.project.members_stats, monthly_stats=g.project.monthly_stats, - months=[today - relativedelta(months=i) for i in range(12)], + months=months, current_view="statistics", )