Self hosted FLOSS fitness/workout, nutrition and weight tracker
Add Phase 4: Trophy Evaluation Engine with Celery tasks
HairyCrabW5b84e46c80b1
diff --git a/wger/trophies/services/__init__.py b/wger/trophies/services/__init__.pyindex 8cc2be4e1..9418bfd88 100644--- a/wger/trophies/services/__init__.py+++ b/wger/trophies/services/__init__.py@@ -15,5 +15,6 @@# along with this program. If not, see <http://www.gnu.org/licenses/>.from .statistics import UserStatisticsService+from .trophy import TrophyService-__all__ = ['UserStatisticsService']+__all__ = ['UserStatisticsService', 'TrophyService']diff --git a/wger/trophies/services/trophy.py b/wger/trophies/services/trophy.pynew file mode 100644index 000000000..fbffd180c--- /dev/null+++ b/wger/trophies/services/trophy.py@@ -0,0 +1,309 @@+# This file is part of wger Workout Manager <https://github.com/wger-project>.+# Copyright (C) 2013 - 2021 wger Team+#+# wger Workout Manager is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published by+# the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# wger Workout Manager is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU Affero General Public License for more details.+#+# 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/>.++# Standard Library+import logging+from datetime import timedelta+from typing import (+ Dict,+ List,+ Optional,+)++# Django+from django.conf import settings+from django.contrib.auth.models import User+from django.db.models import Q+from django.utils import timezone++# wger+from wger.trophies.checkers.registry import CheckerRegistry+from wger.trophies.models import (+ Trophy,+ UserTrophy,+)+++logger = logging.getLogger(__name__)++# Default days of inactivity before skipping user for trophy evaluation+TROPHIES_INACTIVE_USER_DAYS = getattr(settings, 'TROPHIES_INACTIVE_USER_DAYS', 30)+++class TrophyService:+ """+ Service class for trophy evaluation and management.++ This service handles:+ - Evaluating whether users have earned trophies+ - Awarding trophies to users+ - Retrieving trophy progress and status+ """++ @classmethod+ def evaluate_all_trophies(cls, user: User) -> List[UserTrophy]:+ """+ Evaluate all unearned trophies for a user.++ Checks each active trophy the user hasn't earned yet using the+ appropriate checker class. Awards trophies where criteria are met.++ Args:+ user: The user to evaluate trophies for++ Returns:+ List of newly awarded UserTrophy instances+ """+ if cls.should_skip_user(user):+ return []++ # Get all active trophies the user hasn't earned+ earned_trophy_ids = UserTrophy.objects.filter(user=user).values_list('trophy_id', flat=True)+ unevaluated_trophies = Trophy.objects.filter(is_active=True).exclude(id__in=earned_trophy_ids)++ awarded = []+ for trophy in unevaluated_trophies:+ user_trophy = cls.evaluate_trophy(user, trophy)+ if user_trophy:+ awarded.append(user_trophy)++ return awarded++ @classmethod+ def evaluate_trophy(cls, user: User, trophy: Trophy) -> Optional[UserTrophy]:+ """+ Evaluate a single trophy for a user.++ Creates a checker instance and checks if the user has met the+ trophy criteria. Awards the trophy if earned.++ Args:+ user: The user to evaluate the trophy for+ trophy: The trophy to evaluate++ Returns:+ UserTrophy if earned, None otherwise+ """+ if not trophy.is_active:+ return None++ # Check if already earned+ if UserTrophy.objects.filter(user=user, trophy=trophy).exists():+ return None++ # Get the checker for this trophy+ checker = CheckerRegistry.create_checker(user, trophy)+ if checker is None:+ logger.warning(f'No checker found for trophy: {trophy.name}')+ return None++ try:+ if checker.check():+ return cls.award_trophy(user, trophy, progress=100.0)+ except Exception as e:+ logger.error(f'Error checking trophy {trophy.name} for user {user.id}: {e}', exc_info=True)++ return None++ @classmethod+ def award_trophy(cls, user: User, trophy: Trophy, progress: float = 100.0) -> UserTrophy:+ """+ Award a trophy to a user.++ Creates a UserTrophy record marking the trophy as earned.++ Args:+ user: The user to award the trophy to+ trophy: The trophy to award+ progress: The progress value (default 100 for earned)++ Returns:+ The created UserTrophy instance+ """+ user_trophy, created = UserTrophy.objects.get_or_create(+ user=user,+ trophy=trophy,+ defaults={'progress': progress},+ )++ if created:+ logger.info(f'Awarded trophy "{trophy.name}" to user {user.username}')++ return user_trophy++ @classmethod+ def get_user_trophies(cls, user: User) -> List[UserTrophy]:+ """+ Get all earned trophies for a user.++ Args:+ user: The user to get trophies for++ Returns:+ List of UserTrophy instances+ """+ return list(+ UserTrophy.objects.filter(user=user)+ .select_related('trophy')+ .order_by('-earned_at')+ )++ @classmethod+ def get_all_trophy_progress(cls, user: User, include_hidden: bool = False) -> List[Dict]:+ """+ Get all trophies with progress information for a user.++ Returns both earned and unearned trophies with their current progress.+ For progressive trophies, calculates progress on-the-fly.++ Args:+ user: The user to get trophy progress for+ include_hidden: If True, include hidden trophies even if not earned++ Returns:+ List of dicts with trophy info and progress+ """+ result = []++ # Get all active trophies+ trophies = Trophy.objects.filter(is_active=True).order_by('order', 'name')++ # Get user's earned trophies+ earned = {+ ut.trophy_id: ut+ for ut in UserTrophy.objects.filter(user=user).select_related('trophy')+ }++ for trophy in trophies:+ user_trophy = earned.get(trophy.id)+ is_earned = user_trophy is not None++ # Skip hidden trophies unless earned or explicitly included+ if trophy.is_hidden and not is_earned and not include_hidden:+ continue++ progress_data = {+ 'trophy': trophy,+ 'is_earned': is_earned,+ 'earned_at': user_trophy.earned_at if is_earned else None,+ 'progress': 100.0 if is_earned else 0.0,+ 'current_value': None,+ 'target_value': None,+ 'progress_display': None,+ }++ # Calculate progress for progressive trophies that aren't earned+ if trophy.is_progressive and not is_earned:+ checker = CheckerRegistry.create_checker(user, trophy)+ if checker:+ try:+ progress_data['progress'] = checker.get_progress()+ progress_data['current_value'] = checker.get_current_value()+ progress_data['target_value'] = checker.get_target_value()++ # Create display string (e.g., "5000/100000 kg")+ current = progress_data['current_value']+ target = progress_data['target_value']+ if current is not None and target is not None:+ progress_data['progress_display'] = f'{current}/{target}'+ except Exception as e:+ logger.error(f'Error getting progress for trophy {trophy.name}: {e}')++ result.append(progress_data)++ return result++ @classmethod+ def should_skip_user(cls, user: User) -> bool:+ """+ Check if a user should be skipped for trophy evaluation.++ Users are skipped if:+ - They have disabled trophies in their profile+ - They haven't logged in for more than TROPHIES_INACTIVE_USER_DAYS++ Args:+ user: The user to check++ Returns:+ True if user should be skipped+ """+ # Check if user has disabled trophies (if profile has this field)+ if hasattr(user, 'userprofile'):+ profile = user.userprofile+ if hasattr(profile, 'trophies_enabled') and not profile.trophies_enabled:+ return True++ # Check for inactivity+ if user.last_login:+ inactive_threshold = timezone.now() - timedelta(days=TROPHIES_INACTIVE_USER_DAYS)+ if user.last_login < inactive_threshold:+ return True++ return False++ @classmethod+ def reevaluate_trophies(+ cls,+ trophy_ids: Optional[List[int]] = None,+ user_ids: Optional[List[int]] = None,+ ) -> Dict[str, int]:+ """+ Re-evaluate trophies for users (admin function).++ Can be used when trophy criteria change or to fix data inconsistencies.+ This will check if any users now qualify for trophies they didn't before.++ Args:+ trophy_ids: List of trophy IDs to re-evaluate (None = all)+ user_ids: List of user IDs to re-evaluate (None = all active)++ Returns:+ Dict with counts: {'users_checked': N, 'trophies_awarded': M}+ """+ # Get trophies to evaluate+ trophy_qs = Trophy.objects.filter(is_active=True)+ if trophy_ids:+ trophy_qs = trophy_qs.filter(id__in=trophy_ids)+ trophies = list(trophy_qs)++ # Get users to evaluate+ if user_ids:+ users = User.objects.filter(id__in=user_ids)+ else:+ # Get active users only+ inactive_threshold = timezone.now() - timedelta(days=TROPHIES_INACTIVE_USER_DAYS)+ users = User.objects.filter(last_login__gte=inactive_threshold)++ users_checked = 0+ trophies_awarded = 0++ for user in users:+ if cls.should_skip_user(user):+ continue++ users_checked += 1++ for trophy in trophies:+ # Don't skip already earned - this is a re-evaluation+ user_trophy = cls.evaluate_trophy(user, trophy)+ if user_trophy:+ trophies_awarded += 1++ return {+ 'users_checked': users_checked,+ 'trophies_awarded': trophies_awarded,+ }diff --git a/wger/trophies/signals.py b/wger/trophies/signals.pyindex 6014ef27f..5309d5ff9 100644--- a/wger/trophies/signals.py+++ b/wger/trophies/signals.py@@ -37,11 +37,34 @@ from wger.manager.models import (WorkoutSession,)from wger.trophies.services import UserStatisticsService+from wger.trophies.tasks import evaluate_user_trophies_tasklogger = logging.getLogger(__name__)+def _trigger_trophy_evaluation(user_id: int):+ """+ Trigger async trophy evaluation for a user.++ Uses Celery if available, otherwise evaluates synchronously.+ """+ try:+ evaluate_user_trophies_task.delay(user_id)+ except Exception:+ # Celery not available - evaluate synchronously+ from wger.trophies.services import TrophyService+ from django.contrib.auth.models import User++ try:+ user = User.objects.get(id=user_id)+ TrophyService.evaluate_all_trophies(user)+ except User.DoesNotExist:+ pass+ except Exception as e:+ logger.error(f'Error evaluating trophies for user {user_id}: {e}')++@receiver(post_save, sender=WorkoutLog)def workout_log_saved(sender, instance, created, **kwargs):"""@@ -49,6 +72,7 @@ def workout_log_saved(sender, instance, created, **kwargs):Updates user statistics when a new workout log is created.For edits, triggers a full recalculation to ensure accuracy.+ Then triggers trophy evaluation."""if not instance.user_id:return@@ -63,6 +87,9 @@ def workout_log_saved(sender, instance, created, **kwargs):else:# Edited log - full recalculation for accuracyUserStatisticsService.update_statistics(instance.user)++ # Trigger trophy evaluation+ _trigger_trophy_evaluation(instance.user_id)except Exception as e:logger.error(f'Error updating statistics for user {instance.user_id}: {e}', exc_info=True)@@ -90,6 +117,7 @@ def workout_session_saved(sender, instance, created, **kwargs):Updates user statistics when a workout session is created or updated.This captures session-level data like start/end times.+ Then triggers trophy evaluation."""if not instance.user_id:return@@ -107,6 +135,9 @@ def workout_session_saved(sender, instance, created, **kwargs):user=instance.user,session=instance,)++ # Trigger trophy evaluation+ _trigger_trophy_evaluation(instance.user_id)except Exception as e:logger.error(f'Error updating statistics for session {instance.id}: {e}', exc_info=True)diff --git a/wger/trophies/tasks.py b/wger/trophies/tasks.pynew file mode 100644index 000000000..5ae592772--- /dev/null+++ b/wger/trophies/tasks.py@@ -0,0 +1,139 @@+# This file is part of wger Workout Manager <https://github.com/wger-project>.+# Copyright (C) 2013 - 2021 wger Team+#+# wger Workout Manager is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published by+# the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# wger Workout Manager is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU Affero General Public License for more details.+#+# 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/>.++"""+Celery tasks for trophy evaluation and statistics updates.+"""++# Standard Library+import logging+from datetime import timedelta++# Django+from django.conf import settings+from django.contrib.auth.models import User+from django.utils import timezone++# wger+from wger.celery_configuration import app+from wger.trophies.services import (+ TrophyService,+ UserStatisticsService,+)+++logger = logging.getLogger(__name__)++# Default days of inactivity before skipping user+TROPHIES_INACTIVE_USER_DAYS = getattr(settings, 'TROPHIES_INACTIVE_USER_DAYS', 30)+++def evaluate_user_trophies_task(user_id: int):+ """+ Evaluate all trophies for a single user.++ This task is typically called after a workout is logged.++ Args:+ user_id: The ID of the user to evaluate+ """+ try:+ user = User.objects.get(id=user_id)+ awarded = TrophyService.evaluate_all_trophies(user)+ if awarded:+ logger.info(f'Awarded {len(awarded)} trophies to user {user.username}')+ except User.DoesNotExist:+ logger.warning(f'User {user_id} not found for trophy evaluation')+ except Exception as e:+ logger.error(f'Error evaluating trophies for user {user_id}: {e}', exc_info=True)+++def evaluate_all_users_trophies_task():+ """+ Evaluate trophies for all active users.++ This task can be run periodically (e.g., daily) to catch any+ missed trophy awards or re-evaluate after criteria changes.++ Only processes users who have logged in within TROPHIES_INACTIVE_USER_DAYS.+ """+ inactive_threshold = timezone.now() - timedelta(days=TROPHIES_INACTIVE_USER_DAYS)+ users = User.objects.filter(last_login__gte=inactive_threshold)++ total_awarded = 0+ users_processed = 0++ for user in users.iterator():+ try:+ awarded = TrophyService.evaluate_all_trophies(user)+ if awarded:+ total_awarded += len(awarded)+ users_processed += 1+ except Exception as e:+ logger.error(f'Error evaluating trophies for user {user.id}: {e}', exc_info=True)++ logger.info(+ f'Trophy evaluation complete: processed {users_processed} users, '+ f'awarded {total_awarded} trophies'+ )+++def update_user_statistics_task(user_id: int):+ """+ Perform a full statistics recalculation for a user.++ This task is useful for:+ - Initial statistics population+ - Recovery from data inconsistencies+ - After bulk data imports++ Args:+ user_id: The ID of the user to update+ """+ try:+ user = User.objects.get(id=user_id)+ UserStatisticsService.update_statistics(user)+ logger.info(f'Updated statistics for user {user.username}')+ except User.DoesNotExist:+ logger.warning(f'User {user_id} not found for statistics update')+ except Exception as e:+ logger.error(f'Error updating statistics for user {user_id}: {e}', exc_info=True)+++def recalculate_all_statistics_task():+ """+ Recalculate statistics for all active users.++ This task can be used for data recovery or after major changes.+ Only processes users who have logged in recently.+ """+ inactive_threshold = timezone.now() - timedelta(days=TROPHIES_INACTIVE_USER_DAYS)+ users = User.objects.filter(last_login__gte=inactive_threshold)++ users_processed = 0++ for user in users.iterator():+ try:+ UserStatisticsService.update_statistics(user)+ users_processed += 1+ except Exception as e:+ logger.error(f'Error updating statistics for user {user.id}: {e}', exc_info=True)++ logger.info(f'Statistics recalculation complete: processed {users_processed} users')