Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Add Phase 5: API endpoints for trophies

HairyCrabW62bb11ab34b3
diff --git a/wger/trophies/api/filtersets.py b/wger/trophies/api/filtersets.py
new file mode 100644
index 000000000..f30ff9c9f
--- /dev/null
+++ b/wger/trophies/api/filtersets.py
@@ -0,0 +1,55 @@
+# 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/>.
+
+# Third Party
+from django_filters import rest_framework as filters
+
+# wger
+from wger.trophies.models import (
+ Trophy,
+ UserTrophy,
+)
+
+
+class TrophyFilterSet(filters.FilterSet):
+ """
+ Filter set for Trophy model.
+ """
+
+ class Meta:
+ model = Trophy
+ fields = {
+ 'id': ['exact', 'in'],
+ 'trophy_type': ['exact', 'in'],
+ 'is_active': ['exact'],
+ 'is_hidden': ['exact'],
+ 'is_progressive': ['exact'],
+ }
+
+
+class UserTrophyFilterSet(filters.FilterSet):
+ """
+ Filter set for UserTrophy model.
+ """
+
+ class Meta:
+ model = UserTrophy
+ fields = {
+ 'id': ['exact', 'in'],
+ 'trophy': ['exact', 'in'],
+ 'earned_at': ['exact', 'gt', 'gte', 'lt', 'lte'],
+ 'is_notified': ['exact'],
+ }
diff --git a/wger/trophies/api/serializers.py b/wger/trophies/api/serializers.py
new file mode 100644
index 000000000..6bd3a0033
--- /dev/null
+++ b/wger/trophies/api/serializers.py
@@ -0,0 +1,112 @@
+# 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/>.
+
+# Third Party
+from rest_framework import serializers
+
+# wger
+from wger.trophies.models import (
+ Trophy,
+ UserStatistics,
+ UserTrophy,
+)
+
+
+class TrophySerializer(serializers.ModelSerializer):
+ """
+ Serializer for Trophy model.
+
+ Shows trophy information for listing active trophies.
+ """
+
+ class Meta:
+ model = Trophy
+ fields = (
+ 'id',
+ 'uuid',
+ 'name',
+ 'description',
+ 'image',
+ 'trophy_type',
+ 'is_hidden',
+ 'is_progressive',
+ 'order',
+ )
+ read_only_fields = fields
+
+
+class UserTrophySerializer(serializers.ModelSerializer):
+ """
+ Serializer for UserTrophy model.
+
+ Shows user's earned trophies with trophy details.
+ """
+
+ trophy = TrophySerializer(read_only=True)
+
+ class Meta:
+ model = UserTrophy
+ fields = (
+ 'id',
+ 'trophy',
+ 'earned_at',
+ 'progress',
+ 'is_notified',
+ )
+ read_only_fields = fields
+
+
+class UserStatisticsSerializer(serializers.ModelSerializer):
+ """
+ Serializer for UserStatistics model.
+
+ Shows user's trophy-related statistics.
+ """
+
+ class Meta:
+ model = UserStatistics
+ fields = (
+ 'id',
+ 'total_weight_lifted',
+ 'total_workouts',
+ 'current_streak',
+ 'longest_streak',
+ 'last_workout_date',
+ 'earliest_workout_time',
+ 'latest_workout_time',
+ 'weekend_workout_streak',
+ 'last_complete_weekend_date',
+ 'worked_out_jan_1',
+ 'last_updated',
+ )
+ read_only_fields = fields
+
+
+class TrophyProgressSerializer(serializers.Serializer):
+ """
+ Serializer for trophy progress information.
+
+ Used for showing progress on all trophies (earned and unearned).
+ This is not a ModelSerializer as it aggregates data from multiple sources.
+ """
+
+ trophy = TrophySerializer(read_only=True)
+ is_earned = serializers.BooleanField()
+ earned_at = serializers.DateTimeField(allow_null=True)
+ progress = serializers.FloatField()
+ current_value = serializers.CharField(allow_null=True)
+ target_value = serializers.CharField(allow_null=True)
+ progress_display = serializers.CharField(allow_null=True)
diff --git a/wger/trophies/api/views.py b/wger/trophies/api/views.py
new file mode 100644
index 000000000..7af17c1ba
--- /dev/null
+++ b/wger/trophies/api/views.py
@@ -0,0 +1,168 @@
+# 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/>.
+
+# Third Party
+from rest_framework import viewsets
+from rest_framework.decorators import action
+from rest_framework.response import Response
+
+# wger
+from wger.trophies.api.filtersets import (
+ TrophyFilterSet,
+ UserTrophyFilterSet,
+)
+from wger.trophies.api.serializers import (
+ TrophyProgressSerializer,
+ TrophySerializer,
+ UserStatisticsSerializer,
+ UserTrophySerializer,
+)
+from wger.trophies.models import (
+ Trophy,
+ UserStatistics,
+ UserTrophy,
+)
+from wger.trophies.services import TrophyService
+
+
+class TrophyViewSet(viewsets.ReadOnlyModelViewSet):
+ """
+ API endpoint for Trophy objects.
+
+ Returns active trophies. Hidden trophies are excluded unless:
+ - The user has earned them, or
+ - The user is staff
+
+ list:
+ Return a list of active trophies
+
+ retrieve:
+ Return a specific trophy by ID
+ """
+
+ serializer_class = TrophySerializer
+ filterset_class = TrophyFilterSet
+ ordering_fields = ['order', 'name', 'trophy_type']
+ ordering = ['order', 'name']
+
+ def get_queryset(self):
+ """
+ Return active trophies, filtering hidden ones appropriately.
+ """
+ # REST API generation
+ if getattr(self, 'swagger_fake_view', False):
+ return Trophy.objects.none()
+
+ user = self.request.user
+ queryset = Trophy.objects.filter(is_active=True)
+
+ # Staff can see all trophies
+ if user.is_staff:
+ return queryset
+
+ # For regular users, exclude hidden trophies unless earned
+ if user.is_authenticated:
+ earned_trophy_ids = UserTrophy.objects.filter(user=user).values_list(
+ 'trophy_id', flat=True
+ )
+ return queryset.filter(is_hidden=False) | queryset.filter(id__in=earned_trophy_ids)
+
+ # Anonymous users only see non-hidden trophies
+ return queryset.filter(is_hidden=False)
+
+ @action(detail=False, methods=['get'])
+ def progress(self, request):
+ """
+ Return all trophies with progress information for the current user.
+
+ For each trophy, returns:
+ - Trophy info
+ - Whether earned
+ - Earned timestamp (if earned)
+ - Progress percentage (0-100)
+ - Current/target values (for progressive trophies)
+ """
+ if not request.user.is_authenticated:
+ return Response([])
+
+ include_hidden = request.user.is_staff
+ progress_data = TrophyService.get_all_trophy_progress(
+ request.user,
+ include_hidden=include_hidden,
+ )
+
+ serializer = TrophyProgressSerializer(progress_data, many=True)
+ return Response(serializer.data)
+
+
+class UserTrophyViewSet(viewsets.ReadOnlyModelViewSet):
+ """
+ API endpoint for user's earned trophies.
+
+ Returns the current user's earned trophies.
+
+ list:
+ Return all earned trophies for the current user
+
+ retrieve:
+ Return a specific user trophy by ID
+ """
+
+ serializer_class = UserTrophySerializer
+ filterset_class = UserTrophyFilterSet
+ ordering_fields = ['earned_at', 'trophy__name']
+ ordering = ['-earned_at']
+
+ is_private = True
+
+ def get_queryset(self):
+ """
+ Return only the current user's trophies.
+ """
+ # REST API generation
+ if getattr(self, 'swagger_fake_view', False):
+ return UserTrophy.objects.none()
+
+ return UserTrophy.objects.filter(user=self.request.user).select_related('trophy')
+
+
+class UserStatisticsViewSet(viewsets.ReadOnlyModelViewSet):
+ """
+ API endpoint for user's trophy statistics.
+
+ Returns the current user's trophy-related statistics.
+
+ list:
+ Return the current user's statistics
+
+ retrieve:
+ Return statistics by ID
+ """
+
+ serializer_class = UserStatisticsSerializer
+ ordering_fields = '__all__'
+
+ is_private = True
+
+ def get_queryset(self):
+ """
+ Return only the current user's statistics.
+ """
+ # REST API generation
+ if getattr(self, 'swagger_fake_view', False):
+ return UserStatistics.objects.none()
+
+ return UserStatistics.objects.filter(user=self.request.user)
diff --git a/wger/trophies/services/trophy.py b/wger/trophies/services/trophy.py
index fbffd180c..783028c8c 100644
--- a/wger/trophies/services/trophy.py
+++ b/wger/trophies/services/trophy.py
@@ -39,8 +39,9 @@ from wger.trophies.models import (
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)
+# Trophy settings from WGER_SETTINGS (defined in settings_global.py)
+TROPHIES_ENABLED = settings.WGER_SETTINGS['TROPHIES_ENABLED']
+TROPHIES_INACTIVE_USER_DAYS = settings.WGER_SETTINGS['TROPHIES_INACTIVE_USER_DAYS']
class TrophyService:
@@ -232,7 +233,8 @@ class TrophyService:
Check if a user should be skipped for trophy evaluation.
Users are skipped if:
- - They have disabled trophies in their profile
+ - The trophy system is globally disabled (WGER_SETTINGS['TROPHIES_ENABLED'])
+ - They have disabled trophies in their profile (userprofile.trophies_enabled)
- They haven't logged in for more than TROPHIES_INACTIVE_USER_DAYS
Args:
@@ -241,6 +243,10 @@ class TrophyService:
Returns:
True if user should be skipped
"""
+ # Check if trophy system is globally disabled
+ if not TROPHIES_ENABLED:
+ return True
+
# Check if user has disabled trophies (if profile has this field)
if hasattr(user, 'userprofile'):
profile = user.userprofile
diff --git a/wger/trophies/tasks.py b/wger/trophies/tasks.py
index 5ae592772..118956bf7 100644
--- a/wger/trophies/tasks.py
+++ b/wger/trophies/tasks.py
@@ -37,8 +37,8 @@ from wger.trophies.services import (
logger = logging.getLogger(__name__)
-# Default days of inactivity before skipping user
-TROPHIES_INACTIVE_USER_DAYS = getattr(settings, 'TROPHIES_INACTIVE_USER_DAYS', 30)
+# Trophy settings from WGER_SETTINGS (defined in settings_global.py)
+TROPHIES_INACTIVE_USER_DAYS = settings.WGER_SETTINGS['TROPHIES_INACTIVE_USER_DAYS']
@app.task
diff --git a/wger/urls.py b/wger/urls.py
index e04ecc742..3eb8b99ee 100644
--- a/wger/urls.py
+++ b/wger/urls.py
@@ -48,6 +48,7 @@ from wger.gallery.api import views as gallery_api_views
from wger.manager.api import views as manager_api_views
from wger.measurements.api import views as measurements_api_views
from wger.nutrition.api import views as nutrition_api_views
+from wger.trophies.api import views as trophies_api_views
from wger.utils.generic_views import TextTemplateView
from wger.weight.api import views as weight_api_views
@@ -249,6 +250,15 @@ router.register(
basename='measurement-category',
)
+# Trophies app
+router.register(r'trophy', trophies_api_views.TrophyViewSet, basename='trophy')
+router.register(r'user-trophy', trophies_api_views.UserTrophyViewSet, basename='user-trophy')
+router.register(
+ r'user-statistics',
+ trophies_api_views.UserStatisticsViewSet,
+ basename='user-statistics',
+)
+
#
# Sitemaps
#