Skip to content

Commit

Permalink
Add yesterday stats when day totals are not yet available
Browse files Browse the repository at this point in the history
  • Loading branch information
RichieB2B committed Feb 23, 2023
1 parent 5da612b commit d9bd4dd
Showing 1 changed file with 14 additions and 1 deletion.
15 changes: 14 additions & 1 deletion dsmr_stats/services.py
Original file line number Diff line number Diff line change
Expand Up @@ -419,16 +419,27 @@ def year_statistics(target_date: datetime.date):
return range_statistics(start=start_of_year, end=end_of_year)


# @TODO: Consider reworking this to meter positions in favor of https://github.com/dsmrreader/dsmr-reader/issues/1811
def period_totals() -> Dict:
"""Retrieves year/month period totals and merges them with today's consumption."""
today = timezone.localtime(timezone.now())
yesterday = today - timezone.timedelta(days=1)

try:
today_stats = dsmr_consumption.services.day_consumption(day=today)
except LookupError:
today_stats = {}

# also add yesterday stats if day totals are not available yet
# see https://github.com/dsmrreader/dsmr-reader/issues/1811
yesterday_totals = day_statistics(target_date=yesterday)
if not any(x for x in yesterday_totals.values()):
try:
yesterday_stats = dsmr_consumption.services.day_consumption(day=yesterday)
except LookupError:
yesterday_stats = {}
else:
yesterday_stats = {}

month_stats = month_statistics(target_date=today)
year_stats = year_statistics(target_date=today)
excluded_keys = (
Expand All @@ -443,13 +454,15 @@ def period_totals() -> Dict:
continue

# Assumes same keys, zero value fallback.
month_stats[k] += yesterday_stats.get(k, 0)
month_stats[k] += today_stats.get(k, 0)

for k in year_stats.keys():
if k in excluded_keys or year_stats[k] is None:
continue

# Assumes same keys, zero value fallback.
year_stats[k] += yesterday_stats.get(k, 0)
year_stats[k] += today_stats.get(k, 0)

return dict(
Expand Down

0 comments on commit d9bd4dd

Please sign in to comment.