Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Created Django App + Databases and their Models + Migrations

Yousefa6bd3ddd5db6
diff --git a/wger/Implement.txt b/wger/Implement.txt
new file mode 100644
index 000000000..ef98e2740
--- /dev/null
+++ b/wger/Implement.txt
@@ -0,0 +1,265 @@
+Use case
+Allow the user to earn trophies
+
+Proposal
+Create a trophy system so the user can earn them while working out.
+
+The system should be able to accommodate trophies based on different parameters like
+
+time ("worked out before x:yz")
+volume ("lifted xyz kg")
+count ("finished xyz nr of workouts", "most trained exercise")
+sequence ("30 day streak")
+other
+For this we will need to create new tables in the database, at the very least a Trophy table and an m2n table linking it to the user. We will have to implement some python classes that can check if a user has earned a certain trophy (should also accept parameters so one class can be used for "lifted 1000 kg", "lifted 10000 kg", etc.). Some trophies can display a progression. While most trophies will be shown to the user, some should be invisible till earned. It's also probably better to make this a new django app, since it will fetch data from other places.
+
+Since there's potentially a lot of data to handle, we need to consider the performance of the calculations, we probably need to add a statistics table that can be updated as the user uses the app and be quickly read when needed. Also note that we already have a celery queue, we can use that if we need to run periodic or long-running tasks. If a user already has a trophy, we should obviously not check again if it can be earned, but the system should be able to re-evaluate some or all trophies (e.g. if the criteria has changed in the meanwhile). Also, we should only process users that have logged in in the last 30 (?) days.
+
+There is code in the routine model (calculate_log_statistics) that calculates some statistics from a routine, we might be able to reuse some of that.
+
+The trophies and their status should be available over an API endpoint, so that clients can check the progress (how and when the user will receive any notifications is not part of this issue).
+
+New trophies are added directly to the db via either an app update (if python), db migration, fixtures, etc., no need for any upload functionality or similar. However, administrators should be able to disable the trophies in the config, as well as users in their preferences.
+
+Also, ✨tests✨
+
+Possible trophies
+To start we could implement these, others can be added later once the system is in place
+
+Beginner: did one workout
+Unstoppable: 30-day workout streak
+Weekend Warrior: worked out on Saturday and Sunday for 4 weekends in a row
+Lifter: lifted a cumulative total of 5000kg
+Atlas: lifted a cumulative total of 100000kg
+Early Bird: worked out before 6:00
+Night Owl: worked out after 21:00
+New Year, New Me: worked out the 1st of January
+Phoenix: Returned to training after being inactive for 30 days
+
+================================================================================
+STEPS TO IMPLEMENT (Backend Only)
+================================================================================
+
+PHASE 1: Foundation - Django App & Database Models
+--------------------------------------------------
+1.1 Create new Django app "trophies"
+ - Run: python manage.py startapp trophies
+ - Add to INSTALLED_APPS in settings_global.py
+ - Create app structure (models/, api/, tests/, management/commands/)
+
+1.2 Create database models
+ - Trophy model:
+ * id, uuid
+ * name (CharField)
+ * description (TextField)
+ * image (ImageField, optional)
+ * trophy_type (CharField: time, volume, count, sequence, other)
+ * checker_class (CharField - Python path to checker class)
+ * checker_params (JSONField - parameters for the checker)
+ * is_hidden (BooleanField - hidden until earned)
+ * is_progressive (BooleanField - shows progress)
+ * is_active (BooleanField - admin can disable)
+ * order (PositiveIntegerField)
+ * created, updated timestamps
+
+ - UserTrophy model (M2M through table):
+ * user (ForeignKey to User)
+ * trophy (ForeignKey to Trophy)
+ * earned_at (DateTimeField)
+ * progress (FloatField, 0-100, for progressive trophies)
+ * is_notified (BooleanField - for future notification system)
+
+ - UserStatistics model (denormalized stats for performance):
+ * user (OneToOneField to User)
+ * total_weight_lifted (DecimalField)
+ * total_workouts (PositiveIntegerField)
+ * current_streak (PositiveIntegerField)
+ * longest_streak (PositiveIntegerField)
+ * last_workout_date (DateField)
+ * earliest_workout_time (TimeField, nullable)
+ * latest_workout_time (TimeField, nullable)
+ * weekend_workout_streak (PositiveIntegerField)
+ * last_updated (DateTimeField)
+
+1.3 Create and run migrations
+ - python manage.py makemigrations trophies
+ - python manage.py migrate
+
+1.4 Add user preference for trophies
+ - Add "trophies_enabled" (BooleanField, default=True) to UserProfile model
+ - Create migration for core app
+
+1.5 Add site-wide config option
+ - Add trophy system toggle to config app or WGER_SETTINGS
+
+
+PHASE 2: Trophy Checker System
+------------------------------
+2.1 Create base checker class
+ - Abstract base class: BaseTrophyChecker
+ - Methods:
+ * __init__(self, user, trophy, params)
+ * check(self) -> bool (is trophy earned?)
+ * get_progress(self) -> float (0-100, for progressive)
+ * get_target_value(self) -> any (what user needs to achieve)
+ * get_current_value(self) -> any (user's current progress)
+
+2.2 Implement trophy checker classes
+ - CountBasedChecker (for workout count trophies)
+ * Beginner: params={'count': 1}
+
+ - StreakChecker (for consecutive day streaks)
+ * Unstoppable: params={'days': 30}
+
+ - WeekendWarriorChecker (Saturday + Sunday streaks)
+ * Weekend Warrior: params={'weekends': 4}
+
+ - VolumeChecker (cumulative weight lifted)
+ * Lifter: params={'kg': 5000}
+ * Atlas: params={'kg': 100000}
+
+ - TimeBasedChecker (workout time of day)
+ * Early Bird: params={'before': '06:00'}
+ * Night Owl: params={'after': '21:00'}
+
+ - DateBasedChecker (specific dates)
+ * New Year, New Me: params={'month': 1, 'day': 1}
+
+ - InactivityReturnChecker (return after gap)
+ * Phoenix: params={'inactive_days': 30}
+
+2.3 Create checker registry
+ - Dictionary mapping checker_class strings to actual classes
+ - Factory function to instantiate checkers
+
+
+PHASE 3: Statistics Service
+---------------------------
+3.1 Create UserStatisticsService class
+ - Methods:
+ * update_statistics(user) - full recalculation
+ * increment_workout(user, workout_log) - incremental update
+ * get_or_create_statistics(user)
+
+3.2 Implement statistics calculations
+ - Reuse/adapt code from routine model (calculate_log_statistics)
+ - Calculate: total volume, workout count, streaks, times
+
+3.3 Add Django signals
+ - Post-save signal on WorkoutLog/WorkoutSession
+ - Trigger incremental statistics update
+ - Trigger trophy evaluation
+
+
+PHASE 4: Trophy Evaluation Engine
+---------------------------------
+4.1 Create TrophyService class
+ - Methods:
+ * evaluate_all_trophies(user) - check all unearthed trophies
+ * evaluate_trophy(user, trophy) - check single trophy
+ * award_trophy(user, trophy) - create UserTrophy record
+ * get_user_trophies(user) - list earned trophies
+ * get_trophy_progress(user) - list all with progress
+ * reevaluate_trophies(trophy_ids=None) - admin re-evaluation
+
+4.2 Implement evaluation logic
+ - Skip already earned trophies (unless re-evaluating)
+ - Skip users with trophies_enabled=False
+ - Skip inactive users (no login in 30 days)
+ - Use checker classes to determine eligibility
+ - Update progress for progressive trophies
+
+4.3 Add Celery tasks
+ - evaluate_user_trophies_task(user_id) - async single user
+ - evaluate_all_users_trophies_task() - periodic batch job
+ - update_user_statistics_task(user_id) - async stats update
+
+
+PHASE 5: API Endpoints
+----------------------
+5.1 Create serializers
+ - TrophySerializer (id, name, description, image, type, is_hidden, is_progressive)
+ - UserTrophySerializer (trophy, earned_at, progress)
+ - TrophyProgressSerializer (trophy, progress, current_value, target_value, is_earned)
+
+5.2 Create API ViewSets
+ - TrophyViewSet (read-only list of all active trophies)
+ * GET /api/v2/trophy/ - list all visible trophies
+ * GET /api/v2/trophy/{id}/ - trophy detail
+
+ - UserTrophyViewSet (user's earned trophies)
+ * GET /api/v2/user-trophy/ - list user's earned trophies
+ * GET /api/v2/user-trophy/progress/ - all trophies with progress
+
+5.3 Register URLs
+ - Add routes to wger/urls.py under API v2 router
+
+
+PHASE 6: Management Commands & Data Loading
+-------------------------------------------
+6.1 Create management command: load_trophies
+ - Load initial trophy definitions from fixtures or code
+ - Idempotent (can run multiple times safely)
+
+6.2 Create management command: evaluate_trophies
+ - Manual trigger for trophy evaluation
+ - Options: --user, --trophy, --all, --force-reevaluate
+
+6.3 Create management command: recalculate_statistics
+ - Rebuild UserStatistics for all/specific users
+
+6.4 Create fixtures
+ - Initial trophy definitions (the 9 proposed trophies)
+
+
+PHASE 7: Testing
+----------------
+7.1 Model tests
+ - Trophy model CRUD
+ - UserTrophy model constraints
+ - UserStatistics calculations
+
+7.2 Checker tests
+ - Test each checker class with mock data
+ - Edge cases (boundary conditions, empty data)
+
+7.3 Service tests
+ - UserStatisticsService accuracy
+ - TrophyService evaluation logic
+ - Award/skip logic
+
+7.4 API tests
+ - Authentication required
+ - Correct filtering (user's own trophies only)
+ - Hidden trophy visibility rules
+ - Progress endpoint accuracy
+
+7.5 Integration tests
+ - End-to-end: create workout → stats update → trophy earned
+ - Celery task execution (if applicable)
+
+
+PHASE 8: Documentation & Finalization
+-------------------------------------
+8.1 Add OpenAPI documentation
+ - Document new endpoints in drf-spectacular schema
+
+8.2 Update README/docs
+ - Document trophy system configuration
+ - Document how to add new trophies
+
+8.3 Create database migration for initial trophies
+ - Or use fixture loading in deployment
+
+
+================================================================================
+IMPLEMENTATION ORDER SUMMARY
+================================================================================
+1. Phase 1: Foundation (models, migrations, config)
+2. Phase 2: Checker classes
+3. Phase 3: Statistics service
+4. Phase 4: Trophy evaluation engine
+5. Phase 5: API endpoints
+6. Phase 6: Management commands & data
+7. Phase 7: Tests (can be done alongside each phase)
+8. Phase 8: Documentation
\ No newline at end of file
diff --git a/wger/core/migrations/0020_add_trophies_enabled_to_userprofile.py b/wger/core/migrations/0020_add_trophies_enabled_to_userprofile.py
new file mode 100644
index 000000000..a70f23647
--- /dev/null
+++ b/wger/core/migrations/0020_add_trophies_enabled_to_userprofile.py
@@ -0,0 +1,18 @@
+# Generated by Django 5.2.8 on 2025-11-25 10:56
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('core', '0019_delete_daysofweek'),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name='userprofile',
+ name='trophies_enabled',
+ field=models.BooleanField(default=True, help_text='Enable or disable the trophy system for this user', verbose_name='Enable trophies'),
+ ),
+ ]
diff --git a/wger/core/models/profile.py b/wger/core/models/profile.py
index a1c642437..0428def89 100644
--- a/wger/core/models/profile.py
+++ b/wger/core/models/profile.py
@@ -374,6 +374,13 @@ by the US Department of Agriculture. It is extremely complete, with around
behalf over the REST API
"""
+ trophies_enabled = models.BooleanField(
+ default=True,
+ verbose_name=_('Enable trophies'),
+ help_text=_('Enable or disable the trophy system for this user'),
+ )
+ """Flag to enable or disable trophies for this user"""
+
@property
def is_trustworthy(self) -> bool:
"""
diff --git a/wger/settings_global.py b/wger/settings_global.py
index a3ed09b78..2414af271 100644
--- a/wger/settings_global.py
+++ b/wger/settings_global.py
@@ -65,6 +65,7 @@ INSTALLED_APPS = [
'wger.weight',
'wger.gallery',
'wger.measurements',
+ 'wger.trophies',
# reCaptcha support, see https://github.com/praekelt/django-recaptcha
'django_recaptcha',
@@ -568,6 +569,10 @@ WGER_SETTINGS = {
'USE_CELERY': False,
'USE_RECAPTCHA': False,
'WGER_INSTANCE': 'https://wger.de',
+
+ # Trophy system settings
+ 'TROPHIES_ENABLED': True, # Global toggle to enable/disable trophy system
+ 'TROPHIES_INACTIVE_USER_DAYS': 30, # Days of inactivity before skipping trophy evaluation
}
#
diff --git a/wger/trophies/__init__.py b/wger/trophies/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/wger/trophies/api/__init__.py b/wger/trophies/api/__init__.py
new file mode 100644
index 000000000..1292caeab
--- /dev/null
+++ b/wger/trophies/api/__init__.py
@@ -0,0 +1,15 @@
+# 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/>.
diff --git a/wger/trophies/apps.py b/wger/trophies/apps.py
new file mode 100644
index 000000000..227c13b86
--- /dev/null
+++ b/wger/trophies/apps.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/>.
+
+# Django
+from django.apps import AppConfig
+
+
+class TrophiesConfig(AppConfig):
+ name = 'wger.trophies'
+ verbose_name = 'Trophies'
+
+ def ready(self):
+ import wger.trophies.signals
diff --git a/wger/trophies/management/__init__.py b/wger/trophies/management/__init__.py
new file mode 100644
index 000000000..1292caeab
--- /dev/null
+++ b/wger/trophies/management/__init__.py
@@ -0,0 +1,15 @@
+# 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/>.
diff --git a/wger/trophies/management/commands/__init__.py b/wger/trophies/management/commands/__init__.py
new file mode 100644
index 000000000..1292caeab
--- /dev/null
+++ b/wger/trophies/management/commands/__init__.py
@@ -0,0 +1,15 @@
+# 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/>.
diff --git a/wger/trophies/migrations/0001_initial.py b/wger/trophies/migrations/0001_initial.py
new file mode 100644
index 000000000..7551c3fa3
--- /dev/null
+++ b/wger/trophies/migrations/0001_initial.py
@@ -0,0 +1,83 @@
+# Generated by Django 5.2.8 on 2025-11-25 10:54
+
+import django.core.validators
+import django.db.models.deletion
+import uuid
+import wger.trophies.models.trophy
+from django.conf import settings
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ initial = True
+
+ dependencies = [
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name='Trophy',
+ fields=[
+ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
+ ('uuid', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
+ ('name', models.CharField(help_text='The name of the trophy', max_length=100, verbose_name='Name')),
+ ('description', models.TextField(blank=True, default='', help_text='A description of how to earn this trophy', verbose_name='Description')),
+ ('image', models.ImageField(blank=True, null=True, upload_to=wger.trophies.models.trophy.trophy_image_upload_path, verbose_name='Image')),
+ ('trophy_type', models.CharField(choices=[('time', 'Time-based'), ('volume', 'Volume-based'), ('count', 'Count-based'), ('sequence', 'Sequence-based'), ('date', 'Date-based'), ('other', 'Other')], default='other', help_text='The type of criteria used to evaluate this trophy', max_length=20, verbose_name='Trophy type')),
+ ('checker_class', models.CharField(help_text='The Python class path used to check if this trophy is earned', max_length=255, verbose_name='Checker class')),
+ ('checker_params', models.JSONField(blank=True, default=dict, help_text='JSON parameters passed to the checker class', verbose_name='Checker parameters')),
+ ('is_hidden', models.BooleanField(default=False, help_text='If true, this trophy is hidden until earned', verbose_name='Hidden')),
+ ('is_progressive', models.BooleanField(default=False, help_text='If true, this trophy shows progress towards completion', verbose_name='Progressive')),
+ ('is_active', models.BooleanField(default=True, help_text='If false, this trophy cannot be earned', verbose_name='Active')),
+ ('order', models.PositiveIntegerField(default=0, help_text='Display order of the trophy', verbose_name='Order')),
+ ('created', models.DateTimeField(auto_now_add=True)),
+ ('updated', models.DateTimeField(auto_now=True)),
+ ],
+ options={
+ 'verbose_name': 'Trophy',
+ 'verbose_name_plural': 'Trophies',
+ 'ordering': ['order', 'name'],
+ },
+ ),
+ migrations.CreateModel(
+ name='UserStatistics',
+ fields=[
+ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
+ ('total_weight_lifted', models.DecimalField(decimal_places=2, default=0, help_text='Cumulative weight lifted in kg', max_digits=12, verbose_name='Total weight lifted')),
+ ('total_workouts', models.PositiveIntegerField(default=0, help_text='Total number of workout sessions completed', verbose_name='Total workouts')),
+ ('current_streak', models.PositiveIntegerField(default=0, help_text='Current consecutive days with workouts', verbose_name='Current streak')),
+ ('longest_streak', models.PositiveIntegerField(default=0, help_text='Longest consecutive days with workouts', verbose_name='Longest streak')),
+ ('last_workout_date', models.DateField(blank=True, help_text='Date of the most recent workout', null=True, verbose_name='Last workout date')),
+ ('earliest_workout_time', models.TimeField(blank=True, help_text='Earliest time a workout was started', null=True, verbose_name='Earliest workout time')),
+ ('latest_workout_time', models.TimeField(blank=True, help_text='Latest time a workout was started', null=True, verbose_name='Latest workout time')),
+ ('weekend_workout_streak', models.PositiveIntegerField(default=0, help_text='Consecutive weekends with workouts on both Saturday and Sunday', verbose_name='Weekend workout streak')),
+ ('last_inactive_date', models.DateField(blank=True, help_text='Last date before the current activity period began', null=True, verbose_name='Last inactive date')),
+ ('worked_out_jan_1', models.BooleanField(default=False, help_text='Whether user has ever worked out on January 1st', verbose_name='Worked out on January 1st')),
+ ('last_updated', models.DateTimeField(auto_now=True, verbose_name='Last updated')),
+ ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='trophy_statistics', to=settings.AUTH_USER_MODEL, verbose_name='User')),
+ ],
+ options={
+ 'verbose_name': 'User statistics',
+ 'verbose_name_plural': 'User statistics',
+ },
+ ),
+ migrations.CreateModel(
+ name='UserTrophy',
+ fields=[
+ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
+ ('earned_at', models.DateTimeField(auto_now_add=True, help_text='When the trophy was earned', verbose_name='Earned at')),
+ ('progress', models.FloatField(default=0.0, help_text='Progress towards earning the trophy (0-100)', validators=[django.core.validators.MinValueValidator(0.0), django.core.validators.MaxValueValidator(100.0)], verbose_name='Progress')),
+ ('is_notified', models.BooleanField(default=False, help_text='Whether the user has been notified about earning this trophy', verbose_name='Notified')),
+ ('trophy', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user_trophies', to='trophies.trophy', verbose_name='Trophy')),
+ ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='earned_trophies', to=settings.AUTH_USER_MODEL, verbose_name='User')),
+ ],
+ options={
+ 'verbose_name': 'User trophy',
+ 'verbose_name_plural': 'User trophies',
+ 'ordering': ['-earned_at'],
+ 'unique_together': {('user', 'trophy')},
+ },
+ ),
+ ]
diff --git a/wger/trophies/migrations/__init__.py b/wger/trophies/migrations/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/wger/trophies/models/__init__.py b/wger/trophies/models/__init__.py
new file mode 100644
index 000000000..8dd94bf23
--- /dev/null
+++ b/wger/trophies/models/__init__.py
@@ -0,0 +1,20 @@
+# 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 .trophy import Trophy
+from .user_statistics import UserStatistics
+from .user_trophy import UserTrophy
diff --git a/wger/trophies/models/trophy.py b/wger/trophies/models/trophy.py
new file mode 100644
index 000000000..a7463ab92
--- /dev/null
+++ b/wger/trophies/models/trophy.py
@@ -0,0 +1,160 @@
+# 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 uuid
+
+# Django
+from django.db import models
+from django.utils.translation import gettext_lazy as _
+
+
+def trophy_image_upload_path(instance, filename):
+ """
+ Returns the upload path for trophy images
+ """
+ ext = filename.split('.')[-1]
+ return f'trophies/{instance.uuid}.{ext}'
+
+
+class Trophy(models.Model):
+ """
+ Model representing a trophy/achievement that users can earn
+ """
+
+ TYPE_TIME = 'time'
+ TYPE_VOLUME = 'volume'
+ TYPE_COUNT = 'count'
+ TYPE_SEQUENCE = 'sequence'
+ TYPE_DATE = 'date'
+ TYPE_OTHER = 'other'
+
+ TROPHY_TYPES = (
+ (TYPE_TIME, _('Time-based')),
+ (TYPE_VOLUME, _('Volume-based')),
+ (TYPE_COUNT, _('Count-based')),
+ (TYPE_SEQUENCE, _('Sequence-based')),
+ (TYPE_DATE, _('Date-based')),
+ (TYPE_OTHER, _('Other')),
+ )
+
+ uuid = models.UUIDField(
+ default=uuid.uuid4,
+ editable=False,
+ unique=True,
+ )
+ """Unique identifier for the trophy"""
+
+ name = models.CharField(
+ max_length=100,
+ verbose_name=_('Name'),
+ help_text=_('The name of the trophy'),
+ )
+ """The name of the trophy"""
+
+ description = models.TextField(
+ verbose_name=_('Description'),
+ help_text=_('A description of how to earn this trophy'),
+ blank=True,
+ default='',
+ )
+ """Description of the trophy and how to earn it"""
+
+ image = models.ImageField(
+ verbose_name=_('Image'),
+ upload_to=trophy_image_upload_path,
+ blank=True,
+ null=True,
+ )
+ """Optional image for the trophy"""
+
+ trophy_type = models.CharField(
+ max_length=20,
+ choices=TROPHY_TYPES,
+ default=TYPE_OTHER,
+ verbose_name=_('Trophy type'),
+ help_text=_('The type of criteria used to evaluate this trophy'),
+ )
+ """The type of trophy (time, volume, count, sequence, date, other)"""
+
+ checker_class = models.CharField(
+ max_length=255,
+ verbose_name=_('Checker class'),
+ help_text=_('The Python class path used to check if this trophy is earned'),
+ )
+ """Python path to the checker class (e.g., 'wger.trophies.checkers.CountBasedChecker')"""
+
+ checker_params = models.JSONField(
+ default=dict,
+ blank=True,
+ verbose_name=_('Checker parameters'),
+ help_text=_('JSON parameters passed to the checker class'),
+ )
+ """Parameters for the checker class (e.g., {'count': 1} for workout count)"""
+
+ is_hidden = models.BooleanField(
+ default=False,
+ verbose_name=_('Hidden'),
+ help_text=_('If true, this trophy is hidden until earned'),
+ )
+ """Whether the trophy is hidden until earned"""
+
+ is_progressive = models.BooleanField(
+ default=False,
+ verbose_name=_('Progressive'),
+ help_text=_('If true, this trophy shows progress towards completion'),
+ )
+ """Whether to show progress towards earning the trophy"""
+
+ is_active = models.BooleanField(
+ default=True,
+ verbose_name=_('Active'),
+ help_text=_('If false, this trophy cannot be earned'),
+ )
+ """Whether the trophy is active and can be earned"""
+
+ order = models.PositiveIntegerField(
+ default=0,
+ verbose_name=_('Order'),
+ help_text=_('Display order of the trophy'),
+ )
+ """Display order for the trophy"""
+
+ created = models.DateTimeField(
+ auto_now_add=True,
+ editable=False,
+ )
+ """When the trophy was created"""
+
+ updated = models.DateTimeField(
+ auto_now=True,
+ editable=False,
+ )
+ """When the trophy was last updated"""
+
+ class Meta:
+ ordering = ['order', 'name']
+ verbose_name = _('Trophy')
+ verbose_name_plural = _('Trophies')
+
+ def __str__(self):
+ return self.name
+
+ def get_owner_object(self):
+ """
+ Trophies don't have an owner - they are global
+ """
+ return None
diff --git a/wger/trophies/models/user_statistics.py b/wger/trophies/models/user_statistics.py
new file mode 100644
index 000000000..66b852db4
--- /dev/null
+++ b/wger/trophies/models/user_statistics.py
@@ -0,0 +1,131 @@
+# 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/>.
+
+# Django
+from django.contrib.auth.models import User
+from django.db import models
+from django.utils.translation import gettext_lazy as _
+
+
+class UserStatistics(models.Model):
+ """
+ Denormalized statistics table for trophy calculations.
+ This table is updated incrementally as users log workouts to avoid
+ expensive recalculations every time a trophy is evaluated.
+ """
+
+ user = models.OneToOneField(
+ User,
+ on_delete=models.CASCADE,
+ related_name='trophy_statistics',
+ verbose_name=_('User'),
+ )
+ """The user these statistics belong to"""
+
+ total_weight_lifted = models.DecimalField(
+ max_digits=12,
+ decimal_places=2,
+ default=0,
+ verbose_name=_('Total weight lifted'),
+ help_text=_('Cumulative weight lifted in kg'),
+ )
+ """Total cumulative weight lifted in kg"""
+
+ total_workouts = models.PositiveIntegerField(
+ default=0,
+ verbose_name=_('Total workouts'),
+ help_text=_('Total number of workout sessions completed'),
+ )
+ """Total number of workout sessions completed"""
+
+ current_streak = models.PositiveIntegerField(
+ default=0,
+ verbose_name=_('Current streak'),
+ help_text=_('Current consecutive days with workouts'),
+ )
+ """Current consecutive workout streak in days"""
+
+ longest_streak = models.PositiveIntegerField(
+ default=0,
+ verbose_name=_('Longest streak'),
+ help_text=_('Longest consecutive days with workouts'),
+ )
+ """Longest consecutive workout streak ever achieved"""
+
+ last_workout_date = models.DateField(
+ null=True,
+ blank=True,
+ verbose_name=_('Last workout date'),
+ help_text=_('Date of the most recent workout'),
+ )
+ """Date of the most recent workout"""
+
+ earliest_workout_time = models.TimeField(
+ null=True,
+ blank=True,
+ verbose_name=_('Earliest workout time'),
+ help_text=_('Earliest time a workout was started'),
+ )
+ """Earliest time a workout was ever started"""
+
+ latest_workout_time = models.TimeField(
+ null=True,
+ blank=True,
+ verbose_name=_('Latest workout time'),
+ help_text=_('Latest time a workout was started'),
+ )
+ """Latest time a workout was ever started"""
+
+ weekend_workout_streak = models.PositiveIntegerField(
+ default=0,
+ verbose_name=_('Weekend workout streak'),
+ help_text=_('Consecutive weekends with workouts on both Saturday and Sunday'),
+ )
+ """Consecutive weekends with workouts on both Saturday and Sunday"""
+
+ last_inactive_date = models.DateField(
+ null=True,
+ blank=True,
+ verbose_name=_('Last inactive date'),
+ help_text=_('Last date before the current activity period began'),
+ )
+ """Used for Phoenix trophy - tracks when user was last inactive"""
+
+ worked_out_jan_1 = models.BooleanField(
+ default=False,
+ verbose_name=_('Worked out on January 1st'),
+ help_text=_('Whether user has ever worked out on January 1st'),
+ )
+ """Flag for New Year, New Me trophy"""
+
+ last_updated = models.DateTimeField(
+ auto_now=True,
+ verbose_name=_('Last updated'),
+ )
+ """When these statistics were last updated"""
+
+ class Meta:
+ verbose_name = _('User statistics')
+ verbose_name_plural = _('User statistics')
+
+ def __str__(self):
+ return f'Statistics for {self.user.username}'
+
+ def get_owner_object(self):
+ """
+ Returns the object that has owner information
+ """
+ return self
diff --git a/wger/trophies/models/user_trophy.py b/wger/trophies/models/user_trophy.py
new file mode 100644
index 000000000..3a8a4e353
--- /dev/null
+++ b/wger/trophies/models/user_trophy.py
@@ -0,0 +1,86 @@
+# 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/>.
+
+# Django
+from django.contrib.auth.models import User
+from django.core.validators import (
+ MaxValueValidator,
+ MinValueValidator,
+)
+from django.db import models
+from django.utils.translation import gettext_lazy as _
+
+# Local
+from .trophy import Trophy
+
+
+class UserTrophy(models.Model):
+ """
+ Model representing a trophy earned by a user (M2M through table)
+ """
+
+ user = models.ForeignKey(
+ User,
+ on_delete=models.CASCADE,
+ related_name='earned_trophies',
+ verbose_name=_('User'),
+ )
+ """The user who earned the trophy"""
+
+ trophy = models.ForeignKey(
+ Trophy,
+ on_delete=models.CASCADE,
+ related_name='user_trophies',
+ verbose_name=_('Trophy'),
+ )
+ """The trophy that was earned"""
+
+ earned_at = models.DateTimeField(
+ auto_now_add=True,
+ verbose_name=_('Earned at'),
+ help_text=_('When the trophy was earned'),
+ )
+ """When the trophy was earned"""
+
+ progress = models.FloatField(
+ default=0.0,
+ validators=[MinValueValidator(0.0), MaxValueValidator(100.0)],
+ verbose_name=_('Progress'),
+ help_text=_('Progress towards earning the trophy (0-100)'),
+ )
+ """Progress towards earning the trophy (0-100%)"""
+
+ is_notified = models.BooleanField(
+ default=False,
+ verbose_name=_('Notified'),
+ help_text=_('Whether the user has been notified about earning this trophy'),
+ )
+ """Whether the user has been notified about this trophy (for future notification system)"""
+
+ 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}'
+
+ def get_owner_object(self):
+ """
+ Returns the object that has owner information
+ """
+ return self
diff --git a/wger/trophies/signals.py b/wger/trophies/signals.py
new file mode 100644
index 000000000..0321700bd
--- /dev/null
+++ b/wger/trophies/signals.py
@@ -0,0 +1,22 @@
+# 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/>.
+
+"""
+Signal handlers for the trophies app.
+
+Signals will be implemented in Phase 3 to trigger statistics updates
+and trophy evaluations when workouts are logged.
+"""
diff --git a/wger/trophies/tests/__init__.py b/wger/trophies/tests/__init__.py
new file mode 100644
index 000000000..1292caeab
--- /dev/null
+++ b/wger/trophies/tests/__init__.py
@@ -0,0 +1,15 @@
+# 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/>.