Self hosted FLOSS fitness/workout, nutrition and weight tracker
Use one definition of the day a session counts for
Roland Geider311aeb4d3d2c
diff --git a/wger/manager/models/session.py b/wger/manager/models/session.pyindex 13d4c3c3b..b9da2f5b9 100644--- a/wger/manager/models/session.py+++ b/wger/manager/models/session.py@@ -120,7 +120,21 @@ class WorkoutSession(models.Model):"""Return a more human-readable representation"""- return f'{self.routine} - {self.datetime_start.date() if self.datetime_start else ""}'+ return f'{self.routine} - {self.local_day}'++ @property+ def local_day(self) -> datetime.date | None:+ """+ The calendar day this session counts for, e.g. for streaks++ A session that runs over midnight counts for the day it started on. The+ day is derived in the instance timezone; there is no per-user timezone+ yet, see the ORM equivalent ``datetime_start__date``.+ """+ if not self.datetime_start:+ return None++ return timezone.localtime(self.datetime_start).date()class Meta:"""diff --git a/wger/trophies/services/statistics.py b/wger/trophies/services/statistics.pyindex afd97a0d6..e58a6091d 100644--- a/wger/trophies/services/statistics.py+++ b/wger/trophies/services/statistics.py@@ -22,6 +22,7 @@ from typing import Optional# Djangofrom django.contrib.auth.models import User+from django.utils import timezone# wgerfrom wger.manager.consts import WEIGHT_UNIT_LB@@ -91,11 +92,7 @@ class UserStatisticsService:stats.total_workouts = sessions.count()# Calculate streaks and other date-based stats- workout_dates = list(- sessions.values_list('datetime_start__date', flat=True)- .distinct()- .order_by('datetime_start__date')- )+ workout_dates = sorted({session.local_day for session in sessions if session.local_day})current_streak, longest_streak = cls._calculate_streaks(workout_dates)stats.current_streak = current_streakstats.longest_streak = longest_streak@@ -158,15 +155,11 @@ class UserStatisticsService:# Get the session datesession_date = Noneif session:- session_date = session.datetime_start+ session_date = session.local_dayelif workout_log and workout_log.session:- session_date = workout_log.session.datetime_start+ session_date = workout_log.session.local_dayif session_date:- # Convert datetime to date if needed for comparison- if hasattr(session_date, 'date'):- session_date = session_date.date()-# Check if this is a new workout dayis_new_day = stats.last_workout_date is None or session_date > stats.last_workout_date@@ -202,8 +195,8 @@ class UserStatisticsService:cls._update_weekend_streak_incremental(stats, session_date)# Update workout times if session has time info- if session and session.datetime_start:- session_time = session.datetime_start.time()+ if session and session.datetime_end:+ session_time = timezone.localtime(session.datetime_start).time()if stats.earliest_workout_time is None or session_time < stats.earliest_workout_time:stats.earliest_workout_time = session_timeif stats.latest_workout_time is None or session_time > stats.latest_workout_time:@@ -287,7 +280,7 @@ class UserStatisticsService:longest_streak = 1streak = 1- today = datetime.date.today()+ today = timezone.localdate()for i in range(1, len(unique_dates)):if (unique_dates[i] - unique_dates[i - 1]).days == 1:@@ -320,7 +313,9 @@ class UserStatisticsService:Returns:Tuple of (earliest_time, latest_time)"""- times = [s.datetime_start.time() for s in sessions if s.datetime_start is not None]+ # Only sessions with an end carry a time the user actually recorded. The+ # rest are migrated rows that only ever had a date.+ times = [timezone.localtime(s.datetime_start).time() for s in sessions if s.datetime_end]if not times:return None, Nonereturn min(times), max(times)@@ -378,7 +373,7 @@ class UserStatisticsService:streak = 1# Determine current streak- today = datetime.date.today()+ today = timezone.localdate()last_complete = complete_weekends[-1]# Find the most recent Saturdaydiff --git a/wger/trophies/tests/test_statistics_streaks.py b/wger/trophies/tests/test_statistics_streaks.pyindex a1c74fa71..9658cfd3b 100644--- a/wger/trophies/tests/test_statistics_streaks.py+++ b/wger/trophies/tests/test_statistics_streaks.py@@ -35,15 +35,13 @@ FROZEN_TODAY = datetime.date(2024, 6, 19)def frozen_today():"""- Freezes datetime.date.today() so the streak calculations are deterministic+ Freezes the current day so the streak calculations are deterministic"""- class FrozenDate(datetime.date):- @classmethod- def today(cls):- return FROZEN_TODAY-- return mock.patch('datetime.date', FrozenDate)+ return mock.patch(+ 'wger.trophies.services.statistics.timezone.localdate',+ return_value=FROZEN_TODAY,+ )def days_ago(days: int) -> datetime.date:@@ -94,6 +92,53 @@ class CalculateStreaksTestCase(SimpleTestCase):self.assertEqual(self.calculate(dates), (0, 3))+class CalculateWorkoutTimesTestCase(SimpleTestCase):+ """+ Test which sessions contribute to the earliest and latest workout time+ """++ @staticmethod+ def session(start, end=None):+ return WorkoutSession(+ datetime_start=timezone.make_aware(start),+ datetime_end=timezone.make_aware(end) if end else None,+ )++ def test_times_are_taken_in_the_local_timezone(self):+ """The stored value is UTC, the reported time is the one the user saw"""++ sessions = [+ self.session(+ datetime.datetime(2024, 6, 19, 7, 30), datetime.datetime(2024, 6, 19, 9, 0)+ )+ ]++ earliest, latest = UserStatisticsService._calculate_workout_times(sessions)++ self.assertEqual(earliest, datetime.time(7, 30))+ self.assertEqual(latest, datetime.time(7, 30))++ def test_sessions_without_an_end_are_ignored(self):+ """Migrated sessions that only ever had a date must not count as a time"""++ sessions = [+ self.session(datetime.datetime(2024, 6, 19, 0, 0)),+ self.session(+ datetime.datetime(2024, 6, 20, 18, 0), datetime.datetime(2024, 6, 20, 19, 0)+ ),+ ]++ earliest, latest = UserStatisticsService._calculate_workout_times(sessions)++ self.assertEqual(earliest, datetime.time(18, 0))+ self.assertEqual(latest, datetime.time(18, 0))++ def test_no_session_with_an_end_yields_nothing(self):+ sessions = [self.session(datetime.datetime(2024, 6, 19, 0, 0))]++ self.assertEqual(UserStatisticsService._calculate_workout_times(sessions), (None, None))++class CalculateWeekendStreakTestCase(SimpleTestCase):"""Tests the weekend streak calculation over real date sequences