Self hosted FLOSS fitness/workout, nutrition and weight tracker
Base Checker Class + Checker Registry Fully Implemented
Yousefa5bb40cad1d6
diff --git a/wger/trophies/checkers/__init__.py b/wger/trophies/checkers/__init__.pynew file mode 100644index 000000000..86c5fadb6--- /dev/null+++ b/wger/trophies/checkers/__init__.py@@ -0,0 +1,26 @@+# 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/>.++# Local+from .base import BaseTrophyChecker+from .count_based import CountBasedChecker+from .date_based import DateBasedChecker+from .inactivity_return import InactivityReturnChecker+from .registry import CheckerRegistry+from .streak import StreakChecker+from .time_based import TimeBasedChecker+from .volume import VolumeChecker+from .weekend_warrior import WeekendWarriorCheckerdiff --git a/wger/trophies/checkers/base.py b/wger/trophies/checkers/base.pynew file mode 100644index 000000000..f952c8044--- /dev/null+++ b/wger/trophies/checkers/base.py@@ -0,0 +1,126 @@+# 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+from abc import (+ ABC,+ abstractmethod,+)+from typing import (+ Any,+ Optional,+)++# Django+from django.contrib.auth.models import User+++class BaseTrophyChecker(ABC):+ """+ Abstract base class for all trophy checkers.++ Each trophy type has a corresponding checker class that knows how to+ evaluate whether a user has earned that trophy.+ """++ def __init__(self, user: User, trophy: 'Trophy', params: dict):+ """+ Initialize the checker.++ Args:+ user: The user to check the trophy for+ trophy: The trophy being checked+ params: Parameters from the trophy's checker_params field+ """+ self.user = user+ self.trophy = trophy+ self.params = params+ self._statistics = None++ @property+ def statistics(self):+ """+ Lazy-load the user's statistics.+ """+ if self._statistics is None:+ from wger.trophies.models import UserStatistics+ self._statistics, _ = UserStatistics.objects.get_or_create(user=self.user)+ return self._statistics++ @abstractmethod+ def check(self) -> bool:+ """+ Check if the user has earned the trophy.++ Returns:+ True if the trophy has been earned, False otherwise+ """+ pass++ @abstractmethod+ def get_progress(self) -> float:+ """+ Get the user's progress towards earning the trophy.++ Returns:+ A float between 0 and 100 representing percentage progress+ """+ pass++ @abstractmethod+ def get_target_value(self) -> Any:+ """+ Get the target value the user needs to achieve.++ Returns:+ The target value (type depends on trophy type)+ """+ pass++ @abstractmethod+ def get_current_value(self) -> Any:+ """+ Get the user's current value towards the target.++ Returns:+ The current value (type depends on trophy type)+ """+ pass++ def get_progress_display(self) -> str:+ """+ Get a human-readable string describing the progress.++ Returns:+ A formatted string showing current/target progress+ """+ current = self.get_current_value()+ target = self.get_target_value()+ return f'{current} / {target}'++ def validate_params(self) -> bool:+ """+ Validate that the required parameters are present.++ Override this method in subclasses to add specific validation.++ Returns:+ True if parameters are valid, False otherwise+ """+ return True++ def __repr__(self) -> str:+ return f'<{self.__class__.__name__}(user={self.user.username}, trophy={self.trophy.name})>'diff --git a/wger/trophies/checkers/count_based.py b/wger/trophies/checkers/count_based.pynew file mode 100644index 000000000..fed68b068--- /dev/null+++ b/wger/trophies/checkers/count_based.py@@ -0,0 +1,72 @@+# 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+from typing import Any++# Local+from .base import BaseTrophyChecker+++class CountBasedChecker(BaseTrophyChecker):+ """+ Checker for count-based trophies.++ Used for trophies that require completing a certain number of workouts.++ Expected params:+ count (int): The number of workouts required to earn the trophy++ Example:+ Beginner trophy: params={'count': 1}+ Dedicated trophy: params={'count': 100}+ """++ def validate_params(self) -> bool:+ """Validate that count parameter is present and valid."""+ count = self.params.get('count')+ return count is not None and isinstance(count, int) and count > 0++ def check(self) -> bool:+ """Check if user has completed required number of workouts."""+ if not self.validate_params():+ return False+ return self.get_current_value() >= self.get_target_value()++ def get_progress(self) -> float:+ """Get progress as percentage of workouts completed."""+ if not self.validate_params():+ return 0.0+ target = self.get_target_value()+ if target <= 0:+ return 0.0+ current = self.get_current_value()+ progress = (current / target) * 100+ return min(progress, 100.0)++ def get_target_value(self) -> int:+ """Get the target number of workouts."""+ return self.params.get('count', 0)++ def get_current_value(self) -> int:+ """Get the user's current workout count."""+ return self.statistics.total_workouts++ def get_progress_display(self) -> str:+ """Get human-readable progress string."""+ current = self.get_current_value()+ target = self.get_target_value()+ return f'{current} / {target} workouts'diff --git a/wger/trophies/checkers/date_based.py b/wger/trophies/checkers/date_based.pynew file mode 100644index 000000000..84e68d77d--- /dev/null+++ b/wger/trophies/checkers/date_based.py@@ -0,0 +1,109 @@+# 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+from typing import Any++# Local+from .base import BaseTrophyChecker+++class DateBasedChecker(BaseTrophyChecker):+ """+ Checker for date-based trophies.++ Used for trophies that require working out on a specific date (month/day).++ Expected params:+ month (int): The month (1-12) when the workout must occur+ day (int): The day of the month (1-31) when the workout must occur++ Example:+ New Year, New Me trophy: params={'month': 1, 'day': 1}+ """++ def validate_params(self) -> bool:+ """Validate that month and day parameters are present and valid."""+ month = self.params.get('month')+ day = self.params.get('day')++ if month is None or day is None:+ return False++ if not isinstance(month, int) or not isinstance(day, int):+ return False++ if month < 1 or month > 12:+ return False++ if day < 1 or day > 31:+ return False++ return True++ def check(self) -> bool:+ """Check if user has worked out on the specified date."""+ if not self.validate_params():+ return False++ month = self.params.get('month')+ day = self.params.get('day')++ # Special case for January 1st - we store this flag directly+ if month == 1 and day == 1:+ return self.statistics.worked_out_jan_1++ # For other dates, we need to query the workout sessions+ # This is done in the statistics service when updating+ from wger.manager.models import WorkoutSession+ return WorkoutSession.objects.filter(+ user=self.user,+ date__month=month,+ date__day=day,+ ).exists()++ def get_progress(self) -> float:+ """+ Get progress towards the trophy.++ For date-based trophies, progress is binary - either achieved (100%) or not (0%).+ """+ return 100.0 if self.check() else 0.0++ def get_target_value(self) -> str:+ """Get the target date as a string."""+ month = self.params.get('month')+ day = self.params.get('day')++ if month is None or day is None:+ return 'N/A'++ # Convert to month name+ import calendar+ month_name = calendar.month_name[month]+ return f'{month_name} {day}'++ def get_current_value(self) -> str:+ """Get whether the user has achieved this."""+ if self.check():+ return 'Achieved'+ return 'Not yet'++ def get_progress_display(self) -> str:+ """Get human-readable progress string."""+ if self.check():+ return 'Achieved!'+ return f'Work out on {self.get_target_value()}'diff --git a/wger/trophies/checkers/inactivity_return.py b/wger/trophies/checkers/inactivity_return.pynew file mode 100644index 000000000..2533d3b01--- /dev/null+++ b/wger/trophies/checkers/inactivity_return.py@@ -0,0 +1,118 @@+# 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 datetime+from typing import Any++# Local+from .base import BaseTrophyChecker+++class InactivityReturnChecker(BaseTrophyChecker):+ """+ Checker for inactivity return trophies (Phoenix trophy).++ Used for trophies that reward users for returning to training after+ being inactive for a certain period.++ Expected params:+ inactive_days (int): The minimum number of inactive days before returning++ Example:+ Phoenix trophy: params={'inactive_days': 30}+ """++ def validate_params(self) -> bool:+ """Validate that inactive_days parameter is present and valid."""+ inactive_days = self.params.get('inactive_days')+ return inactive_days is not None and isinstance(inactive_days, int) and inactive_days > 0++ def check(self) -> bool:+ """+ Check if user has returned to training after being inactive.++ The user earns this trophy if:+ 1. They have a last_inactive_date recorded (meaning they were inactive)+ 2. They have a last_workout_date after the inactive period+ 3. The gap between last_inactive_date and the workout before that was >= inactive_days+ """+ if not self.validate_params():+ return False++ last_inactive_date = self.statistics.last_inactive_date+ last_workout_date = self.statistics.last_workout_date++ # If no inactive date recorded, user hasn't had a qualifying gap yet+ if last_inactive_date is None:+ return False++ # If no workout after the inactive period, haven't returned yet+ if last_workout_date is None:+ return False++ # Check if they've worked out after the inactive date+ # The statistics service sets last_inactive_date when it detects+ # a gap of >= inactive_days before a new workout+ return last_workout_date > last_inactive_date++ def get_progress(self) -> float:+ """+ Get progress towards the trophy.++ This is a special trophy - progress shows how close to earning it after returning.+ If they haven't been inactive long enough, shows 0.+ If they've returned after inactivity, shows 100.+ """+ return 100.0 if self.check() else 0.0++ def get_target_value(self) -> int:+ """Get the required number of inactive days."""+ return self.params.get('inactive_days', 0)++ def get_current_value(self) -> str:+ """Get the current status."""+ if self.check():+ return 'Returned after inactivity'++ last_workout = self.statistics.last_workout_date+ if last_workout is None:+ return 'No workouts yet'++ # Calculate days since last workout+ today = datetime.date.today()+ days_inactive = (today - last_workout).days++ return f'{days_inactive} days since last workout'++ def get_progress_display(self) -> str:+ """Get human-readable progress string."""+ if self.check():+ return 'Achieved! Welcome back!'++ target_days = self.get_target_value()+ last_workout = self.statistics.last_workout_date++ if last_workout is None:+ return f'Complete a workout, then return after {target_days}+ days of rest'++ today = datetime.date.today()+ days_inactive = (today - last_workout).days++ if days_inactive >= target_days:+ return 'Return to training to earn this trophy!'++ return f'{days_inactive} / {target_days} days inactive'diff --git a/wger/trophies/checkers/registry.py b/wger/trophies/checkers/registry.pynew file mode 100644index 000000000..2d0b0726e--- /dev/null+++ b/wger/trophies/checkers/registry.py@@ -0,0 +1,158 @@+# 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 typing import (+ Dict,+ Optional,+ Type,+)++# Django+from django.contrib.auth.models import User++# Local+from .base import BaseTrophyChecker+from .count_based import CountBasedChecker+from .date_based import DateBasedChecker+from .inactivity_return import InactivityReturnChecker+from .streak import StreakChecker+from .time_based import TimeBasedChecker+from .volume import VolumeChecker+from .weekend_warrior import WeekendWarriorChecker+++logger = logging.getLogger(__name__)+++class CheckerRegistry:+ """+ Registry for trophy checker classes.++ Maps checker class names (as stored in Trophy.checker_class) to their+ actual Python classes.+ """++ # Registry mapping checker class paths to actual classes+ _registry: Dict[str, Type[BaseTrophyChecker]] = {+ 'wger.trophies.checkers.CountBasedChecker': CountBasedChecker,+ 'wger.trophies.checkers.StreakChecker': StreakChecker,+ 'wger.trophies.checkers.WeekendWarriorChecker': WeekendWarriorChecker,+ 'wger.trophies.checkers.VolumeChecker': VolumeChecker,+ 'wger.trophies.checkers.TimeBasedChecker': TimeBasedChecker,+ 'wger.trophies.checkers.DateBasedChecker': DateBasedChecker,+ 'wger.trophies.checkers.InactivityReturnChecker': InactivityReturnChecker,+ }++ @classmethod+ def register(cls, class_path: str, checker_class: Type[BaseTrophyChecker]) -> None:+ """+ Register a new checker class.++ Args:+ class_path: The path string to use in Trophy.checker_class+ checker_class: The checker class to register+ """+ if not issubclass(checker_class, BaseTrophyChecker):+ raise ValueError(f'{checker_class} must be a subclass of BaseTrophyChecker')+ cls._registry[class_path] = checker_class++ @classmethod+ def unregister(cls, class_path: str) -> None:+ """+ Unregister a checker class.++ Args:+ class_path: The path string to remove+ """+ cls._registry.pop(class_path, None)++ @classmethod+ def get_checker_class(cls, class_path: str) -> Optional[Type[BaseTrophyChecker]]:+ """+ Get a checker class by its path.++ Args:+ class_path: The path string from Trophy.checker_class++ Returns:+ The checker class, or None if not found+ """+ return cls._registry.get(class_path)++ @classmethod+ def get_all_checkers(cls) -> Dict[str, Type[BaseTrophyChecker]]:+ """+ Get all registered checker classes.++ Returns:+ A copy of the registry dictionary+ """+ return cls._registry.copy()++ @classmethod+ def create_checker(+ cls,+ user: User,+ trophy: 'Trophy',+ ) -> Optional[BaseTrophyChecker]:+ """+ Factory method to create a checker instance for a trophy.++ Args:+ user: The user to check the trophy for+ trophy: The trophy to check++ Returns:+ An instance of the appropriate checker class, or None if the+ checker class is not found in the registry+ """+ checker_class = cls.get_checker_class(trophy.checker_class)++ if checker_class is None:+ logger.warning(+ f'Checker class not found in registry: {trophy.checker_class} '+ f'for trophy: {trophy.name}'+ )+ return None++ try:+ return checker_class(+ user=user,+ trophy=trophy,+ params=trophy.checker_params or {},+ )+ except Exception as e:+ logger.error(+ f'Error creating checker for trophy {trophy.name}: {e}',+ exc_info=True,+ )+ return None+++def get_checker_for_trophy(user: User, trophy: 'Trophy') -> Optional[BaseTrophyChecker]:+ """+ Convenience function to get a checker instance for a trophy.++ Args:+ user: The user to check the trophy for+ trophy: The trophy to check++ Returns:+ An instance of the appropriate checker class, or None if not found+ """+ return CheckerRegistry.create_checker(user, trophy)diff --git a/wger/trophies/checkers/streak.py b/wger/trophies/checkers/streak.pynew file mode 100644index 000000000..d6de7a5fa--- /dev/null+++ b/wger/trophies/checkers/streak.py@@ -0,0 +1,77 @@+# 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+from typing import Any++# Local+from .base import BaseTrophyChecker+++class StreakChecker(BaseTrophyChecker):+ """+ Checker for streak-based trophies.++ Used for trophies that require working out for consecutive days.++ Expected params:+ days (int): The number of consecutive days required++ Example:+ Unstoppable trophy: params={'days': 30}+ """++ def validate_params(self) -> bool:+ """Validate that days parameter is present and valid."""+ days = self.params.get('days')+ return days is not None and isinstance(days, int) and days > 0++ def check(self) -> bool:+ """Check if user has achieved the required streak."""+ if not self.validate_params():+ return False+ # Check both current streak and longest streak (in case they achieved it before)+ target = self.get_target_value()+ return (+ self.statistics.current_streak >= target+ or self.statistics.longest_streak >= target+ )++ def get_progress(self) -> float:+ """Get progress as percentage of streak achieved."""+ if not self.validate_params():+ return 0.0+ target = self.get_target_value()+ if target <= 0:+ return 0.0+ # Use the maximum of current or longest streak for progress+ current = self.get_current_value()+ progress = (current / target) * 100+ return min(progress, 100.0)++ def get_target_value(self) -> int:+ """Get the target streak length in days."""+ return self.params.get('days', 0)++ def get_current_value(self) -> int:+ """Get the user's best streak (max of current and longest)."""+ return max(self.statistics.current_streak, self.statistics.longest_streak)++ def get_progress_display(self) -> str:+ """Get human-readable progress string."""+ current = self.get_current_value()+ target = self.get_target_value()+ return f'{current} / {target} days'diff --git a/wger/trophies/checkers/time_based.py b/wger/trophies/checkers/time_based.pynew file mode 100644index 000000000..8781f255f--- /dev/null+++ b/wger/trophies/checkers/time_based.py@@ -0,0 +1,149 @@+# 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 datetime+from typing import (+ Any,+ Optional,+)++# Local+from .base import BaseTrophyChecker+++class TimeBasedChecker(BaseTrophyChecker):+ """+ Checker for time-based trophies.++ Used for trophies that require working out before or after a certain time.++ Expected params:+ before (str, optional): Time string in HH:MM format - workout must be before this time+ after (str, optional): Time string in HH:MM format - workout must be after this time++ At least one of 'before' or 'after' must be provided.++ Example:+ Early Bird trophy: params={'before': '06:00'}+ Night Owl trophy: params={'after': '21:00'}+ """++ def _parse_time(self, time_str: str) -> Optional[datetime.time]:+ """Parse a time string in HH:MM format."""+ try:+ parts = time_str.split(':')+ hour = int(parts[0])+ minute = int(parts[1]) if len(parts) > 1 else 0+ return datetime.time(hour=hour, minute=minute)+ except (ValueError, IndexError, AttributeError):+ return None++ def validate_params(self) -> bool:+ """Validate that at least one of before/after is present and valid."""+ before = self.params.get('before')+ after = self.params.get('after')++ if before is None and after is None:+ return False++ if before is not None and self._parse_time(before) is None:+ return False++ if after is not None and self._parse_time(after) is None:+ return False++ return True++ def check(self) -> bool:+ """Check if user has worked out at the required time."""+ if not self.validate_params():+ return False++ before = self.params.get('before')+ after = self.params.get('after')++ if before is not None:+ # Check if user has ever worked out before the specified time+ target_time = self._parse_time(before)+ earliest = self.statistics.earliest_workout_time+ if earliest is not None and earliest < target_time:+ return True++ if after is not None:+ # Check if user has ever worked out after the specified time+ target_time = self._parse_time(after)+ latest = self.statistics.latest_workout_time+ if latest is not None and latest > target_time:+ return True++ return False++ def get_progress(self) -> float:+ """+ Get progress towards the trophy.++ For time-based trophies, progress is binary - either achieved (100%) or not (0%).+ """+ return 100.0 if self.check() else 0.0++ def get_target_value(self) -> str:+ """Get the target time as a string."""+ before = self.params.get('before')+ after = self.params.get('after')++ if before is not None:+ return f'Before {before}'+ if after is not None:+ return f'After {after}'+ return 'N/A'++ def get_current_value(self) -> str:+ """Get the user's relevant workout time."""+ before = self.params.get('before')++ if before is not None:+ earliest = self.statistics.earliest_workout_time+ if earliest is not None:+ return earliest.strftime('%H:%M')+ return 'No workouts yet'++ # For 'after' condition+ latest = self.statistics.latest_workout_time+ if latest is not None:+ return latest.strftime('%H:%M')+ return 'No workouts yet'++ def get_progress_display(self) -> str:+ """Get human-readable progress string."""+ if self.check():+ return 'Achieved!'++ before = self.params.get('before')+ if before is not None:+ earliest = self.statistics.earliest_workout_time+ if earliest is not None:+ return f'Earliest: {earliest.strftime("%H:%M")} (need before {before})'+ return f'Work out before {before}'++ after = self.params.get('after')+ if after is not None:+ latest = self.statistics.latest_workout_time+ if latest is not None:+ return f'Latest: {latest.strftime("%H:%M")} (need after {after})'+ return f'Work out after {after}'++ return 'N/A'diff --git a/wger/trophies/checkers/volume.py b/wger/trophies/checkers/volume.pynew file mode 100644index 000000000..0a7649ed5--- /dev/null+++ b/wger/trophies/checkers/volume.py@@ -0,0 +1,88 @@+# 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+from decimal import Decimal+from typing import (+ Any,+ Union,+)++# Local+from .base import BaseTrophyChecker+++class VolumeChecker(BaseTrophyChecker):+ """+ Checker for volume-based trophies.++ Used for trophies that require lifting a cumulative amount of weight.++ Expected params:+ kg (int|float): The total weight in kg required to earn the trophy++ Example:+ Lifter trophy: params={'kg': 5000}+ Atlas trophy: params={'kg': 100000}+ """++ def validate_params(self) -> bool:+ """Validate that kg parameter is present and valid."""+ kg = self.params.get('kg')+ return kg is not None and isinstance(kg, (int, float)) and kg > 0++ def check(self) -> bool:+ """Check if user has lifted the required total weight."""+ if not self.validate_params():+ return False+ return self.get_current_value() >= self.get_target_value()++ def get_progress(self) -> float:+ """Get progress as percentage of weight lifted."""+ if not self.validate_params():+ return 0.0+ target = self.get_target_value()+ if target <= 0:+ return 0.0+ current = float(self.get_current_value())+ progress = (current / target) * 100+ return min(progress, 100.0)++ def get_target_value(self) -> float:+ """Get the target weight in kg."""+ return float(self.params.get('kg', 0))++ def get_current_value(self) -> Decimal:+ """Get the user's total weight lifted in kg."""+ return self.statistics.total_weight_lifted++ def get_progress_display(self) -> str:+ """Get human-readable progress string."""+ current = self.get_current_value()+ target = self.get_target_value()++ # Format large numbers with commas for readability+ if current >= 1000:+ current_str = f'{current:,.0f}'+ else:+ current_str = f'{current:.1f}'++ if target >= 1000:+ target_str = f'{target:,.0f}'+ else:+ target_str = f'{target:.1f}'++ return f'{current_str} / {target_str} kg'diff --git a/wger/trophies/checkers/weekend_warrior.py b/wger/trophies/checkers/weekend_warrior.pynew file mode 100644index 000000000..5325d5081--- /dev/null+++ b/wger/trophies/checkers/weekend_warrior.py@@ -0,0 +1,72 @@+# 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+from typing import Any++# Local+from .base import BaseTrophyChecker+++class WeekendWarriorChecker(BaseTrophyChecker):+ """+ Checker for Weekend Warrior trophy.++ Used for trophies that require working out on both Saturday and Sunday+ for consecutive weekends.++ Expected params:+ weekends (int): The number of consecutive complete weekends required++ Example:+ Weekend Warrior trophy: params={'weekends': 4}+ """++ def validate_params(self) -> bool:+ """Validate that weekends parameter is present and valid."""+ weekends = self.params.get('weekends')+ return weekends is not None and isinstance(weekends, int) and weekends > 0++ def check(self) -> bool:+ """Check if user has completed workouts on required consecutive weekends."""+ if not self.validate_params():+ return False+ return self.get_current_value() >= self.get_target_value()++ def get_progress(self) -> float:+ """Get progress as percentage of weekend streak achieved."""+ if not self.validate_params():+ return 0.0+ target = self.get_target_value()+ if target <= 0:+ return 0.0+ current = self.get_current_value()+ progress = (current / target) * 100+ return min(progress, 100.0)++ def get_target_value(self) -> int:+ """Get the target number of consecutive complete weekends."""+ return self.params.get('weekends', 0)++ def get_current_value(self) -> int:+ """Get the user's current weekend workout streak."""+ return self.statistics.weekend_workout_streak++ def get_progress_display(self) -> str:+ """Get human-readable progress string."""+ current = self.get_current_value()+ target = self.get_target_value()+ return f'{current} / {target} weekends'