Skip to content

Commit 1d35230

Browse files
committed
Add yesterday stats when day totals are not yet available
Fixes dsmrreader#1811
1 parent 5da612b commit 1d35230

File tree

1 file changed

+14
-5
lines changed

1 file changed

+14
-5
lines changed

dsmr_stats/services.py

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -260,10 +260,7 @@ def clear_statistics() -> None:
260260

261261
def electricity_tariff_percentage(start: date, end: date) -> Optional[Dict]:
262262
"""Returns the total electricity consumption percentage by tariff (high/low tariff)."""
263-
totals = DayStatistics.objects.filter(
264-
day__gte=start,
265-
day__lte=end,
266-
).aggregate(
263+
totals = DayStatistics.objects.filter(day__gte=start, day__lte=end,).aggregate(
267264
electricity1=Sum("electricity1"),
268265
electricity2=Sum("electricity2"),
269266
)
@@ -419,7 +416,6 @@ def year_statistics(target_date: datetime.date):
419416
return range_statistics(start=start_of_year, end=end_of_year)
420417

421418

422-
# @TODO: Consider reworking this to meter positions in favor of https://github.com/dsmrreader/dsmr-reader/issues/1811
423419
def period_totals() -> Dict:
424420
"""Retrieves year/month period totals and merges them with today's consumption."""
425421
today = timezone.localtime(timezone.now())
@@ -429,6 +425,17 @@ def period_totals() -> Dict:
429425
except LookupError:
430426
today_stats = {}
431427

428+
# also add yesterday stats if today totals are not available yet
429+
# see https://github.com/dsmrreader/dsmr-reader/issues/1811
430+
if not day_statistics(target_date=today):
431+
try:
432+
yesterday = today - timezone.timedelta(days=1)
433+
yesterday_stats = dsmr_consumption.services.day_consumption(day=yesterday)
434+
except LookupError:
435+
yesterday_stats = {}
436+
else:
437+
yesterday_stats = {}
438+
432439
month_stats = month_statistics(target_date=today)
433440
year_stats = year_statistics(target_date=today)
434441
excluded_keys = (
@@ -443,13 +450,15 @@ def period_totals() -> Dict:
443450
continue
444451

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

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

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

455464
return dict(

0 commit comments

Comments
 (0)