Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Sync exercise variations as well

Roland Geider5cb269d5cf6c
diff --git a/wger/exercises/api/serializers.py b/wger/exercises/api/serializers.py
index 87c8a6310..446d54f42 100644
--- a/wger/exercises/api/serializers.py
+++ b/wger/exercises/api/serializers.py
@@ -304,7 +304,7 @@ class ExerciseVariationSerializer(serializers.ModelSerializer):
class Meta:
model = Variation
- fields = ('id',)
+ fields = ('id', 'uuid')
class ExerciseInfoAliasSerializer(serializers.ModelSerializer):
@@ -556,7 +556,7 @@ class ExerciseInfoSerializer(serializers.ModelSerializer):
equipment = EquipmentSerializer(many=True, read_only=True)
translations = ExerciseTranslationBaseInfoSerializer(many=True, read_only=True)
videos = ExerciseVideoInfoSerializer(source='exercisevideo_set', many=True, read_only=True)
- variations = serializers.PrimaryKeyRelatedField(read_only=True)
+ variations = serializers.SlugRelatedField(slug_field='uuid', read_only=True)
author_history = serializers.ListSerializer(child=serializers.CharField())
total_authors_history = serializers.ListSerializer(child=serializers.CharField())
last_update_global = serializers.DateTimeField(read_only=True)
diff --git a/wger/exercises/fixtures/test-exercises.json b/wger/exercises/fixtures/test-exercises.json
index 8320f762b..8c87352ef 100644
--- a/wger/exercises/fixtures/test-exercises.json
+++ b/wger/exercises/fixtures/test-exercises.json
@@ -3,24 +3,28 @@
"pk": 1,
"model": "exercises.variation",
"fields": {
+ "uuid": "a1b2c3d4-0001-0000-0000-000000000001"
}
},
{
"pk": 2,
"model": "exercises.variation",
"fields": {
+ "uuid": "a1b2c3d4-0002-0000-0000-000000000002"
}
},
{
"pk": 3,
"model": "exercises.variation",
"fields": {
+ "uuid": "a1b2c3d4-0003-0000-0000-000000000003"
}
},
{
"pk": 4,
"model": "exercises.variation",
"fields": {
+ "uuid": "a1b2c3d4-0004-0000-0000-000000000004"
}
},
{
diff --git a/wger/exercises/migrations/0036_add_uuid_to_variation.py b/wger/exercises/migrations/0036_add_uuid_to_variation.py
new file mode 100644
index 000000000..06e0f91ba
--- /dev/null
+++ b/wger/exercises/migrations/0036_add_uuid_to_variation.py
@@ -0,0 +1,31 @@
+import uuid as uuid_mod
+from django.db import migrations, models
+from django.db.migrations.state import StateApps
+
+
+def generate_variation_uuids(apps: StateApps, schema_editor):
+ Variation = apps.get_model('exercises', 'Variation')
+ for variation in Variation.objects.all():
+ variation.uuid = uuid_mod.uuid4()
+ variation.save(update_fields=['uuid'])
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('exercises', '0035_add_is_ai_generated'),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name='variation',
+ name='uuid',
+ field=models.UUIDField(null=True),
+ ),
+ migrations.RunPython(generate_variation_uuids, migrations.RunPython.noop),
+ migrations.AlterField(
+ model_name='variation',
+ name='uuid',
+ field=models.UUIDField(default=uuid_mod.uuid4, editable=False, unique=True),
+ ),
+ ]
diff --git a/wger/exercises/models/variation.py b/wger/exercises/models/variation.py
index 1c302b99a..43feff743 100644
--- a/wger/exercises/models/variation.py
+++ b/wger/exercises/models/variation.py
@@ -14,6 +14,9 @@
# 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
@@ -23,6 +26,12 @@ class Variation(models.Model):
Variation ids for exercises
"""
+ uuid = models.UUIDField(
+ default=uuid.uuid4,
+ editable=False,
+ unique=True,
+ )
+
def __str__(self):
"""
Return a more human-readable representation
diff --git a/wger/exercises/signals.py b/wger/exercises/signals.py
index 9ffaaae94..369702601 100644
--- a/wger/exercises/signals.py
+++ b/wger/exercises/signals.py
@@ -17,6 +17,7 @@
# Django
from django.db.models.signals import (
post_delete,
+ post_save,
pre_delete,
pre_save,
)
@@ -30,9 +31,11 @@ from easy_thumbnails.signals import saved_file
# wger
from wger.exercises.models import (
DeletionLog,
+ Exercise,
ExerciseImage,
ExerciseVideo,
Translation,
+ Variation,
)
@@ -124,3 +127,43 @@ def add_deletion_log_video(sender, instance: ExerciseVideo, **kwargs):
model_type=DeletionLog.MODEL_VIDEO,
uuid=instance.uuid,
).save()
+
+
+@receiver(pre_save, sender=Exercise)
+def store_previous_variation(sender, instance: Exercise, **kwargs):
+ """
+ Store the previous variation ID before saving so we can clean up
+ orphaned groups afterwards.
+ """
+ if instance.pk:
+ instance._previous_variation_id = (
+ Exercise.objects.filter(pk=instance.pk)
+ .values_list('variations_id', flat=True)
+ .first()
+ )
+ else:
+ instance._previous_variation_id = None
+
+
+@receiver(post_save, sender=Exercise)
+def cleanup_orphaned_variation(sender, instance: Exercise, **kwargs):
+ """
+ Clean up the previous variation group if it now has fewer than 2 exercises.
+
+ A variation with only 1 exercise makes no sense, so we unlink the
+ remaining exercise and delete the variation.
+
+ Note: it's necessary to handle this case like this because the naive option
+ of just removing all variations with only one (or none) exercises won't work,
+ as it would prevent any variations from being created since there will always
+ be a moment where there is only one exercise in the variation.
+ """
+ previous_id = getattr(instance, '_previous_variation_id', None)
+ if previous_id is None or previous_id == instance.variations_id:
+ return
+
+ members = Exercise.objects.filter(variations_id=previous_id)
+ count = members.count()
+ if count <= 1:
+ members.update(variations=None)
+ Variation.objects.filter(pk=previous_id).delete()
diff --git a/wger/exercises/sync.py b/wger/exercises/sync.py
index 6e23432de..ec4a15365 100644
--- a/wger/exercises/sync.py
+++ b/wger/exercises/sync.py
@@ -52,6 +52,7 @@ from wger.exercises.models import (
ExerciseVideo,
Muscle,
Translation,
+ Variation,
)
from wger.manager.models import (
SlotEntry,
@@ -84,9 +85,21 @@ def sync_exercises(
muscles = [Muscle.objects.get(pk=i['id']) for i in data['muscles']]
muscles_sec = [Muscle.objects.get(pk=i['id']) for i in data['muscles_secondary']]
+ # Sync variation group by UUID
+ remote_variation_uuid = data.get('variations')
+ local_variation = None
+ if remote_variation_uuid is not None:
+ local_variation, _ = Variation.objects.get_or_create(
+ uuid=remote_variation_uuid,
+ )
+
exercise, exercise_created = Exercise.objects.update_or_create(
uuid=uuid,
- defaults={'category_id': category_id, 'created': created},
+ defaults={
+ 'category_id': category_id,
+ 'created': created,
+ 'variations': local_variation,
+ },
)
print_fn(f'{"created" if exercise_created else "updated"} exercise {uuid}')
diff --git a/wger/exercises/tests/test_exercise_signals.py b/wger/exercises/tests/test_exercise_signals.py
new file mode 100644
index 000000000..7ac1a31aa
--- /dev/null
+++ b/wger/exercises/tests/test_exercise_signals.py
@@ -0,0 +1,110 @@
+# This file is part of wger Workout Manager.
+#
+# 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 General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+
+from wger.core.tests.base_testcase import WgerTestCase
+from wger.exercises.models import (
+ Exercise,
+ Variation,
+)
+
+
+class CleanupOrphanedVariationsTestCase(WgerTestCase):
+ """
+ Test that the post_save signal on Exercise cleans up variation groups
+ that have fewer than 2 exercises.
+ """
+
+ def test_removing_exercise_from_group_of_two_cleans_up(self):
+ """
+ When a group has 2 exercises and one is removed, the remaining
+ exercise should be unlinked and the variation deleted.
+ """
+ # Variation 1 has 2 exercises in the test fixtures
+ variation = Variation.objects.get(pk=1)
+ members = Exercise.objects.filter(variations=variation)
+ self.assertEqual(members.count(), 2)
+ other_pk = members.exclude(pk=members.first().pk).first().pk
+
+ # Remove one exercise from the group
+ exercise = members.first()
+ exercise.variations = None
+ exercise.save()
+
+ # The variation should be deleted and the other exercise unlinked
+ self.assertFalse(Variation.objects.filter(pk=1).exists())
+ other = Exercise.objects.get(pk=other_pk)
+ self.assertIsNone(other.variations)
+
+ def test_removing_exercise_from_larger_group_keeps_group(self):
+ """
+ When a group has 3+ exercises and one is removed, the group
+ should remain intact.
+ """
+ # Add a third exercise to variation 1
+ variation = Variation.objects.get(pk=1)
+ ex = Exercise.objects.filter(variations__isnull=True).first()
+ ex.variations = variation
+ ex.save()
+ self.assertEqual(
+ Exercise.objects.filter(variations=variation).count(), 3
+ )
+
+ # Remove one exercise
+ first = Exercise.objects.filter(variations=variation).first()
+ first.variations = None
+ first.save()
+
+ # The group should still exist with 2 members
+ self.assertTrue(Variation.objects.filter(pk=variation.pk).exists())
+ self.assertEqual(
+ Exercise.objects.filter(variations=variation).count(), 2
+ )
+
+ def test_moving_exercise_to_different_group_cleans_up_old(self):
+ """
+ When an exercise is moved from a 2-exercise group to another group,
+ the old group should be cleaned up.
+ """
+ old_variation = Variation.objects.get(pk=1)
+ new_variation = Variation.objects.get(pk=2)
+ self.assertEqual(
+ Exercise.objects.filter(variations=old_variation).count(), 2
+ )
+
+ # Move one exercise to the other group
+ exercise = Exercise.objects.filter(variations=old_variation).first()
+ exercise.variations = new_variation
+ exercise.save()
+
+ # Old variation should be cleaned up
+ self.assertFalse(Variation.objects.filter(pk=old_variation.pk).exists())
+
+ def test_saving_without_change_does_nothing(self):
+ """
+ Saving an exercise without changing its variation should not
+ affect the group.
+ """
+ variation = Variation.objects.get(pk=2)
+ count_before = Exercise.objects.filter(variations=variation).count()
+
+ # Save without changing variation
+ exercise = Exercise.objects.filter(variations=variation).first()
+ exercise.save()
+
+ # Nothing should change
+ self.assertTrue(Variation.objects.filter(pk=variation.pk).exists())
+ self.assertEqual(
+ Exercise.objects.filter(variations=variation).count(),
+ count_before,
+ )
diff --git a/wger/exercises/tests/test_sync.py b/wger/exercises/tests/test_sync.py
index ed94b33d2..38eed88fa 100644
--- a/wger/exercises/tests/test_sync.py
+++ b/wger/exercises/tests/test_sync.py
@@ -436,7 +436,7 @@ class MockExerciseResponse:
]
}
],
- "variations": 47,
+ "variations": "4e1bb2fc-3b0e-4a1a-bd3e-3728a0e6d8a7",
"videos": [],
"author_history": [
"Mrs Winterbottom"
@@ -552,7 +552,7 @@ class MockExerciseResponse:
]
}
],
- "variations": 47,
+ "variations": "4e1bb2fc-3b0e-4a1a-bd3e-3728a0e6d8a7",
"videos": [],
"author_history": [
"Mr X"
@@ -795,6 +795,15 @@ class TestSyncMethods(WgerTestCase):
translation_fr = exercise.get_translation('fr')
self.assertEqual(str(translation_fr.uuid), '581338a1-8e52-405b-99eb-f0724c528bc8')
+ # Both exercises should be in the same variation group
+ self.assertIsNotNone(new_exercise.variations)
+ self.assertIsNotNone(exercise.variations)
+ self.assertEqual(new_exercise.variations, exercise.variations)
+ self.assertEqual(
+ str(new_exercise.variations.uuid),
+ '4e1bb2fc-3b0e-4a1a-bd3e-3728a0e6d8a7',
+ )
+
@patch('requests.get', return_value=MockImageResponse())
def test_image_sync(self, mock_request):
"""Test that download_exercise_images updates existing images and creates new ones"""