Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Evaluate the day-based statistics in the owner's timezone

Roland Geider4840d0bca17a
diff --git a/wger/gym/helpers.py b/wger/gym/helpers.py
index db1ee6e8b..2fa3f30ff 100644
--- a/wger/gym/helpers.py
+++ b/wger/gym/helpers.py
@@ -34,16 +34,20 @@ def get_user_last_activity(user):
dates = []
+ # The day is derived in the member's zone, not in the one of the trainer
+ # looking at the list
+ tz = user.userprofile.zone_info
+
# Check workout logs. They use datetimes, the sessions and the user cache
# only dates
last_log = WorkoutLog.objects.filter(user=user).order_by('date').last()
if last_log:
- dates.append(timezone.localdate(last_log.date))
+ dates.append(timezone.localdate(last_log.date, timezone=tz))
# Check workout sessions
last_session = WorkoutSession.objects.filter(user=user).order_by('datetime_start').last()
if last_session:
- dates.append(timezone.localdate(last_session.datetime_start))
+ dates.append(timezone.localdate(last_session.datetime_start, timezone=tz))
return max(dates) if dates else None
diff --git a/wger/manager/models/routine.py b/wger/manager/models/routine.py
index 79697e716..3b6659a48 100644
--- a/wger/manager/models/routine.py
+++ b/wger/manager/models/routine.py
@@ -233,11 +233,13 @@ class Routine(models.Model):
if not days:
return []
- # Precompute session dates from prefetched logs
+ # Precompute session dates from prefetched logs. The zone is the same
+ # for every session of this routine's user, fetch it once
+ tz = self.user.userprofile.zone_info
workout_session_map = defaultdict(set)
for day in days:
for session in day.workoutsession_set.all():
- workout_session_map[day.id].add(session.local_day)
+ workout_session_map[day.id].add(session.local_day_in(tz))
# Main sequence generation logic
labels = self.label_dict
@@ -454,8 +456,9 @@ class Routine(models.Model):
avg_log_data(res_group[key], cnt_group[key])
# Iterate over each workout session associated with the routine
+ tz = self.user.userprofile.zone_info
for session in self.sessions.all():
- session_date = session.local_day
+ session_date = session.local_day_in(tz)
week_number = session_date.isocalendar().week
# TODO: filter for lb
diff --git a/wger/manager/models/session.py b/wger/manager/models/session.py
index 6f52f9ce5..7b3bf702f 100644
--- a/wger/manager/models/session.py
+++ b/wger/manager/models/session.py
@@ -137,13 +137,20 @@ class WorkoutSession(models.Model):
the timezone of the user it belongs to and not in the one of whoever is
asking. An ORM lookup such as ``datetime_start__date`` resolves in the
active timezone instead and is not an equivalent.
+
+ Loads the owner's profile. Anything iterating over sessions of one user
+ should fetch the zone once and use ``local_day_in`` instead.
+ """
+ return self.local_day_in(self.user.userprofile.zone_info)
+
+ def local_day_in(self, tz: datetime.tzinfo) -> datetime.date | None:
+ """
+ The calendar day this session counts for, in the given timezone
"""
if not self.datetime_start:
return None
- return timezone.localtime(
- self.datetime_start, timezone=self.user.userprofile.zone_info
- ).date()
+ return timezone.localtime(self.datetime_start, timezone=tz).date()
class Meta:
"""
diff --git a/wger/trophies/checkers/date_based.py b/wger/trophies/checkers/date_based.py
index 12b86c7f0..d30b3dc0b 100644
--- a/wger/trophies/checkers/date_based.py
+++ b/wger/trophies/checkers/date_based.py
@@ -14,6 +14,12 @@
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
+# Django
+from django.db.models.functions import (
+ ExtractDay,
+ ExtractMonth,
+)
+
# Local
from .base import BaseTrophyChecker
@@ -68,11 +74,18 @@ class DateBasedChecker(BaseTrophyChecker):
# wger
from wger.manager.models import WorkoutSession
- return WorkoutSession.objects.filter(
- user=self.user,
- datetime_start__month=month,
- datetime_start__day=day,
- ).exists()
+ # Extract with an explicit tzinfo: bare __month/__day resolve in the
+ # active timezone, which in a celery task is the instance one
+ tz = self.user.userprofile.zone_info
+ return (
+ WorkoutSession.objects.filter(user=self.user)
+ .annotate(
+ local_month=ExtractMonth('datetime_start', tzinfo=tz),
+ local_dom=ExtractDay('datetime_start', tzinfo=tz),
+ )
+ .filter(local_month=month, local_dom=day)
+ .exists()
+ )
def get_progress(self) -> float:
"""
diff --git a/wger/trophies/services/statistics.py b/wger/trophies/services/statistics.py
index e58a6091d..2af4c37f9 100644
--- a/wger/trophies/services/statistics.py
+++ b/wger/trophies/services/statistics.py
@@ -22,6 +22,7 @@ from typing import Optional
# Django
from django.contrib.auth.models import User
+from django.db.models.functions import TruncDate
from django.utils import timezone
# wger
@@ -91,9 +92,13 @@ class UserStatisticsService:
sessions = WorkoutSession.objects.filter(user=user).order_by('datetime_start')
stats.total_workouts = sessions.count()
+ # The zone of the user the sessions belong to, fetched once for the
+ # whole recalculation: local_day would load the profile per session
+ tz = user.userprofile.zone_info
+
# Calculate streaks and other date-based stats
- workout_dates = sorted({session.local_day for session in sessions if session.local_day})
- current_streak, longest_streak = cls._calculate_streaks(workout_dates)
+ workout_dates = sorted({day for session in sessions if (day := session.local_day_in(tz))})
+ current_streak, longest_streak = cls._calculate_streaks(workout_dates, tz)
stats.current_streak = current_streak
stats.longest_streak = longest_streak
@@ -102,12 +107,12 @@ class UserStatisticsService:
stats.last_workout_date = workout_dates[-1]
# Calculate earliest and latest workout times
- earliest, latest = cls._calculate_workout_times(sessions)
+ earliest, latest = cls._calculate_workout_times(sessions, tz)
stats.earliest_workout_time = earliest
stats.latest_workout_time = latest
# Calculate weekend workout streak
- weekend_streak, last_complete_weekend = cls._calculate_weekend_streak(workout_dates)
+ weekend_streak, last_complete_weekend = cls._calculate_weekend_streak(workout_dates, tz)
stats.weekend_workout_streak = weekend_streak
stats.last_complete_weekend_date = last_complete_weekend
@@ -152,12 +157,14 @@ class UserStatisticsService:
volume = weight_kg * reps
stats.total_weight_lifted += volume
+ tz = user.userprofile.zone_info
+
# Get the session date
session_date = None
if session:
- session_date = session.local_day
+ session_date = session.local_day_in(tz)
elif workout_log and workout_log.session:
- session_date = workout_log.session.local_day
+ session_date = workout_log.session.local_day_in(tz)
if session_date:
# Check if this is a new workout day
@@ -192,11 +199,11 @@ class UserStatisticsService:
stats.worked_out_jan_1 = True
# Update weekend streak
- cls._update_weekend_streak_incremental(stats, session_date)
+ cls._update_weekend_streak_incremental(stats, session_date, tz)
# Update workout times if session has time info
if session and session.datetime_end:
- session_time = timezone.localtime(session.datetime_start).time()
+ session_time = timezone.localtime(session.datetime_start, timezone=tz).time()
if stats.earliest_workout_time is None or session_time < stats.earliest_workout_time:
stats.earliest_workout_time = session_time
if stats.latest_workout_time is None or session_time > stats.latest_workout_time:
@@ -258,14 +265,17 @@ class UserStatisticsService:
return total
@classmethod
- def _calculate_streaks(cls, workout_dates: list) -> tuple:
+ def _calculate_streaks(cls, workout_dates: list, tz: datetime.tzinfo) -> tuple:
"""
Calculate current and longest workout streaks.
- A streak is consecutive days with at least one workout.
+ A streak is consecutive days with at least one workout. Whether it is
+ still alive depends on what "today" is, which is a day in the user's
+ timezone like the workout dates themselves.
Args:
workout_dates: List of dates with workouts, sorted ascending
+ tz: the timezone of the user the dates belong to
Returns:
Tuple of (current_streak, longest_streak)
@@ -280,7 +290,7 @@ class UserStatisticsService:
longest_streak = 1
streak = 1
- today = timezone.localdate()
+ today = timezone.localdate(timezone=tz)
for i in range(1, len(unique_dates)):
if (unique_dates[i] - unique_dates[i - 1]).days == 1:
@@ -303,30 +313,36 @@ class UserStatisticsService:
return current_streak, longest_streak
@classmethod
- def _calculate_workout_times(cls, sessions) -> tuple:
+ def _calculate_workout_times(cls, sessions, tz: datetime.tzinfo) -> tuple:
"""
- Find earliest and latest workout start times.
+ Find earliest and latest workout start times, in the user's timezone.
Args:
sessions: QuerySet of WorkoutSession
+ tz: the timezone of the user the sessions belong to
Returns:
Tuple of (earliest_time, latest_time)
"""
# 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]
+ times = [
+ timezone.localtime(s.datetime_start, timezone=tz).time()
+ for s in sessions
+ if s.datetime_end
+ ]
if not times:
return None, None
return min(times), max(times)
@classmethod
- def _calculate_weekend_streak(cls, workout_dates: list) -> tuple:
+ def _calculate_weekend_streak(cls, workout_dates: list, tz: datetime.tzinfo) -> tuple:
"""
Calculate consecutive weekends with workouts on both Saturday and Sunday.
Args:
workout_dates: List of workout dates
+ tz: the timezone of the user the dates belong to, decides "today"
Returns:
Tuple of (weekend_streak, last_complete_weekend_date)
@@ -373,7 +389,7 @@ class UserStatisticsService:
streak = 1
# Determine current streak
- today = timezone.localdate()
+ today = timezone.localdate(timezone=tz)
last_complete = complete_weekends[-1]
# Find the most recent Saturday
@@ -390,13 +406,19 @@ class UserStatisticsService:
return current_streak, last_complete
@classmethod
- def _update_weekend_streak_incremental(cls, stats: UserStatistics, workout_date: datetime.date):
+ def _update_weekend_streak_incremental(
+ cls,
+ stats: UserStatistics,
+ workout_date: datetime.date,
+ tz: datetime.tzinfo,
+ ):
"""
Incrementally update weekend streak when a workout is logged.
Args:
stats: The UserStatistics to update
workout_date: The date of the workout
+ tz: the timezone of the user, decides which day a session falls on
"""
# Only process weekend days
weekday = workout_date.weekday()
@@ -411,13 +433,14 @@ class UserStatisticsService:
sunday = saturday + datetime.timedelta(days=1)
- # Check if both days have workouts
- has_saturday = WorkoutSession.objects.filter(
- user=stats.user, datetime_start__date=saturday
- ).exists()
- has_sunday = WorkoutSession.objects.filter(
- user=stats.user, datetime_start__date=sunday
- ).exists()
+ # Check if both days have workouts. TruncDate with an explicit tzinfo:
+ # a bare __date resolves in the active timezone, which in a celery task
+ # is the instance one
+ sessions = WorkoutSession.objects.filter(user=stats.user).annotate(
+ local_date=TruncDate('datetime_start', tzinfo=tz)
+ )
+ has_saturday = sessions.filter(local_date=saturday).exists()
+ has_sunday = sessions.filter(local_date=sunday).exists()
if has_saturday and has_sunday:
# This weekend is complete
diff --git a/wger/trophies/tests/test_statistics_streaks.py b/wger/trophies/tests/test_statistics_streaks.py
index 9658cfd3b..e0d2b599b 100644
--- a/wger/trophies/tests/test_statistics_streaks.py
+++ b/wger/trophies/tests/test_statistics_streaks.py
@@ -55,7 +55,7 @@ class CalculateStreaksTestCase(SimpleTestCase):
def calculate(self, dates):
with frozen_today():
- return UserStatisticsService._calculate_streaks(dates)
+ return UserStatisticsService._calculate_streaks(dates, timezone.get_default_timezone())
def test_no_workouts(self):
self.assertEqual(self.calculate([]), (0, 0))
@@ -113,7 +113,9 @@ class CalculateWorkoutTimesTestCase(SimpleTestCase):
)
]
- earliest, latest = UserStatisticsService._calculate_workout_times(sessions)
+ earliest, latest = UserStatisticsService._calculate_workout_times(
+ sessions, timezone.get_default_timezone()
+ )
self.assertEqual(earliest, datetime.time(7, 30))
self.assertEqual(latest, datetime.time(7, 30))
@@ -128,7 +130,9 @@ class CalculateWorkoutTimesTestCase(SimpleTestCase):
),
]
- earliest, latest = UserStatisticsService._calculate_workout_times(sessions)
+ earliest, latest = UserStatisticsService._calculate_workout_times(
+ sessions, timezone.get_default_timezone()
+ )
self.assertEqual(earliest, datetime.time(18, 0))
self.assertEqual(latest, datetime.time(18, 0))
@@ -136,7 +140,12 @@ class CalculateWorkoutTimesTestCase(SimpleTestCase):
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))
+ self.assertEqual(
+ UserStatisticsService._calculate_workout_times(
+ sessions, timezone.get_default_timezone()
+ ),
+ (None, None),
+ )
class CalculateWeekendStreakTestCase(SimpleTestCase):
@@ -149,7 +158,9 @@ class CalculateWeekendStreakTestCase(SimpleTestCase):
def calculate(self, dates):
with frozen_today():
- return UserStatisticsService._calculate_weekend_streak(dates)
+ return UserStatisticsService._calculate_weekend_streak(
+ dates, timezone.get_default_timezone()
+ )
def test_no_workouts(self):
self.assertEqual(self.calculate([]), (0, None))