Self hosted FLOSS fitness/workout, nutrition and weight tracker
Add repeatable trophies and context data to user trophies
Justincd3b7b0960fd
diff --git a/wger/trophies/README.md b/wger/trophies/README.mdindex f86b42b13..2d8b7dbac 100644--- a/wger/trophies/README.md+++ b/wger/trophies/README.md@@ -54,6 +54,7 @@ Defines an achievement that users can earn.- `is_hidden`: Hidden until earned- `is_progressive`: Shows progress percentage- `is_active`: Can be earned (admins can disable)+- `is_repeatable`: Can be earned multiple times- `order`: Display order### UserTrophy@@ -66,6 +67,7 @@ Links users to their earned trophies.- `earned_at`: Timestamp when earned- `progress`: Progress percentage (0-100)- `is_notified`: For future notification system+- `context_data`: Additionnal information on the trophy### UserStatisticsdiff --git a/wger/trophies/migrations/0001_initial.py b/wger/trophies/migrations/0001_initial.pyindex 8388d0ee9..e4c99b050 100644--- a/wger/trophies/migrations/0001_initial.py+++ b/wger/trophies/migrations/0001_initial.py@@ -293,8 +293,7 @@ class Migration(migrations.Migration):options={'verbose_name': 'User trophy','verbose_name_plural': 'User trophies',- 'ordering': ['-earned_at'],- 'unique_together': {('user', 'trophy')},+ 'ordering': ['-earned_at']},),]diff --git a/wger/trophies/migrations/0004_trophy_is_repeatable_usertrophy_context_data.py b/wger/trophies/migrations/0004_trophy_is_repeatable_usertrophy_context_data.pynew file mode 100644index 000000000..1ab30018a--- /dev/null+++ b/wger/trophies/migrations/0004_trophy_is_repeatable_usertrophy_context_data.py@@ -0,0 +1,23 @@+# Generated by Django 5.2.9 on 2025-12-16 16:14++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ('trophies', '0003_load_initial_trophies'),+ ]++ operations = [+ migrations.AddField(+ model_name='trophy',+ name='is_repeatable',+ field=models.BooleanField(default=False, help_text='If true, this trophy can be earned multiple times', verbose_name='Repeatable'),+ ),+ migrations.AddField(+ model_name='usertrophy',+ name='context_data',+ field=models.JSONField(blank=True, default=None, help_text='Additional information concerning this trophy', null=True, verbose_name='Context data'),+ ),+ ]diff --git a/wger/trophies/models/trophy.py b/wger/trophies/models/trophy.pyindex a7463ab92..c12d5c91a 100644--- a/wger/trophies/models/trophy.py+++ b/wger/trophies/models/trophy.py@@ -126,6 +126,13 @@ class Trophy(models.Model):)"""Whether the trophy is active and can be earned"""+ is_repeatable = models.BooleanField(+ default=False,+ verbose_name=_('Repeatable'),+ help_text=_('If true, this trophy can be earned multiple times'),+ )+ """Whether the trophy can be earned multiple times"""+order = models.PositiveIntegerField(default=0,verbose_name=_('Order'),diff --git a/wger/trophies/models/user_trophy.py b/wger/trophies/models/user_trophy.pyindex 3a8a4e353..53001b53e 100644--- a/wger/trophies/models/user_trophy.py+++ b/wger/trophies/models/user_trophy.py@@ -20,7 +20,7 @@ from django.core.validators import (MaxValueValidator,MinValueValidator,)-from django.db import models+from django.db import IntegrityError, modelsfrom django.utils.translation import gettext_lazy as _# Local@@ -70,11 +70,19 @@ class UserTrophy(models.Model):)"""Whether the user has been notified about this trophy (for future notification system)"""+ context_data = models.JSONField(+ blank=True,+ null=True,+ default=None,+ verbose_name=_('Context data'),+ help_text=_('Additional information concerning this trophy'),+ )+ """Additional information concerning this trophy (useful for repeatable trophies)"""+class Meta:ordering = ['-earned_at']verbose_name = _('User trophy')verbose_name_plural = _('User trophies')- unique_together = [['user', 'trophy']]def __str__(self):return f'{self.user.username} - {self.trophy.name}'@@ -84,3 +92,11 @@ class UserTrophy(models.Model):Returns the object that has owner information"""return self++ def save(self, *args, **kwargs):+ # Prevent duplicate non-repeatable trophies (allow more than one if trophy.is_repeatable)+ if not self.trophy.is_repeatable and UserTrophy.objects.filter(+ user=self.user, trophy=self.trophy+ ).exclude(pk=self.pk).exists():+ raise IntegrityError('User already has this non-repeatable trophy')+ super().save(*args, **kwargs)\ No newline at end of filediff --git a/wger/trophies/services/trophy.py b/wger/trophies/services/trophy.pyindex 69d220c99..91242733b 100644--- a/wger/trophies/services/trophy.py+++ b/wger/trophies/services/trophy.py@@ -61,6 +61,7 @@ class TrophyService:Checks each active trophy the user hasn't earned yet using theappropriate checker class. Awards trophies where criteria are met.+ Always re-evaluates repeatable trophies.Args:user: The user to evaluate trophies for@@ -73,7 +74,7 @@ class TrophyService:# Get all active trophies the user hasn't earnedearned_trophy_ids = UserTrophy.objects.filter(user=user).values_list('trophy_id', flat=True)- unevaluated_trophies = Trophy.objects.filter(is_active=True).exclude(+ unevaluated_trophies = Trophy.objects.filter(is_active=True, is_repeatable=False).exclude(id__in=earned_trophy_ids)@@ -104,7 +105,7 @@ class TrophyService:return None# Check if already earned- if UserTrophy.objects.filter(user=user, trophy=trophy).exists():+ if not trophy.is_repeatable and UserTrophy.objects.filter(user=user, trophy=trophy).exists():return None# Get the checker for this trophy@@ -138,11 +139,14 @@ class TrophyService:Returns:The created UserTrophy instance"""- user_trophy, created = UserTrophy.objects.get_or_create(- user=user,- trophy=trophy,- defaults={'progress': progress},- )+ if trophy.is_repeatable:+ user_trophy, created = UserTrophy.objects.create(user=user, trophy=trophy, progress=progress)+ else:+ 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}')diff --git a/wger/trophies/tests/test_models.py b/wger/trophies/tests/test_models.pyindex 23f24a614..d62a7d69e 100644--- a/wger/trophies/tests/test_models.py+++ b/wger/trophies/tests/test_models.py@@ -63,6 +63,16 @@ class TrophyModelTestCase(WgerTestCase):self.assertEqual(trophy.order, 0)self.assertEqual(trophy.description, '')+ def test_is_repeatable_defaults_to_false(self):+ """Test the is_repeatable field defaults to False"""+ trophy = Trophy.objects.create(+ name='Repeatable Test Trophy',+ trophy_type=Trophy.TYPE_OTHER,+ checker_class='personal_record',+ )++ self.assertFalse(trophy.is_repeatable)+def test_trophy_str(self):"""Test trophy string representation"""trophy = Trophy.objects.create(@@ -193,6 +203,53 @@ class UserTrophyModelTestCase(WgerTestCase):trophy=self.trophy,)+ def test_repeatable_trophy_earned_twice(self):+ """Test a user can earn the same repeatable trophy twice"""+ repeatable_trophy = Trophy.objects.create(+ name='Repeatable Test',+ trophy_type=Trophy.TYPE_OTHER,+ checker_class='personal_record',+ is_repeatable=True+ )++ user_trophy_1 = UserTrophy.objects.create(+ user=self.user,+ trophy=repeatable_trophy,+ context_data={"weight":100, "unit":"kg"}+ )++ user_trophy_2 = UserTrophy.objects.create(+ user=self.user,+ trophy=repeatable_trophy,+ context_data={"weight":110, "unit":"kg"}+ )++ self.assertNotEquals(user_trophy_1, user_trophy_2)+ self.assertEqual(UserTrophy.objects.filter(trophy=repeatable_trophy).count(), 2)+++ def test_context_data_default_should_be_none(self):+ """Test context_data default is None"""+ user_trophy = UserTrophy.objects.create(+ user=self.user,+ trophy=self.trophy,+ )++ self.assertIsNone(user_trophy.context_data)++ def test_context_data(self):+ """JSON data should be stored and retrieved correctly"""+ data = {'pr_weight': 200, 'units': 'kg'}+ user_trophy2 = UserTrophy.objects.create(+ user=self.user,+ trophy=Trophy.objects.create(+ name='PR Test', trophy_type=Trophy.TYPE_OTHER, checker_class='personal_record'+ ),+ context_data=data,+ )++ self.assertEqual(user_trophy2.context_data, data)+def test_progress_field(self):"""Test progress field for progressive trophies"""user_trophy = UserTrophy.objects.create(