Self hosted FLOSS fitness/workout, nutrition and weight tracker
Create the official body weight category for every user
Roland Geiderd203ef70cc22
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 878cbaf02..7efcaea8d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1 +1,5 @@# Changelog for the next release++- Body weight entries are now stored as measurements in a weight category+ that every user gets automatically, existing entries are+ migrated. Official categories cannot be deleted.diff --git a/wger/core/signals.py b/wger/core/signals.pyindex 1e2ff31d1..9a83be4cd 100644--- a/wger/core/signals.py+++ b/wger/core/signals.py@@ -31,16 +31,24 @@ from wger.core.models import (UserCache,UserProfile,)+from wger.measurements.models import Category+from wger.measurements.models.category import MetricTypefrom wger.utils.helpers import disable_for_loaddata@disable_for_loaddatadef create_user_profile(sender, instance, created, **kwargs):"""- Every new user gets a profile+ Every new user gets a profile and the official body weight category"""if created:- UserProfile.objects.create(user=instance)+ profile = UserProfile.objects.create(user=instance)+ Category.get_or_create_official(+ instance,+ MetricType.BODY_WEIGHT,+ name='Body weight',+ unit=profile.weight_unit,+ )@disable_for_loaddatadiff --git a/wger/measurements/api/serializers.py b/wger/measurements/api/serializers.pyindex 6273499a5..98f6e277a 100644--- a/wger/measurements/api/serializers.py+++ b/wger/measurements/api/serializers.py@@ -33,7 +33,20 @@ class CategorySerializer(serializers.ModelSerializer):class Meta:model = Category- fields = ('id', 'name', 'unit', 'metric_type', 'parent', 'order')+ fields = ('id', 'name', 'unit', 'metric_type', 'parent', 'order', 'is_official')+ read_only_fields = ('is_official',)++ def validate_metric_type(self, metric_type):+ """+ The metric type of an official category is fixed: the legacy weight+ endpoint and the health sync rely on it+ """+ if self.instance and self.instance.is_official:+ if metric_type != self.instance.metric_type:+ raise serializers.ValidationError(+ 'The metric type of an official category cannot be changed'+ )+ return metric_typedef validate_parent(self, parent):"""diff --git a/wger/measurements/api/views.py b/wger/measurements/api/views.pyindex 61965ef3b..bace2c50a 100644--- a/wger/measurements/api/views.py+++ b/wger/measurements/api/views.py@@ -50,7 +50,7 @@ class CategoryViewSet(WgerOwnerObjectModelViewSet):serializer_class = CategorySerializeris_private = Trueordering_fields = '__all__'- filterset_fields = ('id', 'name', 'unit', 'metric_type', 'parent')+ filterset_fields = ('id', 'name', 'unit', 'metric_type', 'parent', 'is_official')def get_queryset(self):"""@@ -68,6 +68,15 @@ class CategoryViewSet(WgerOwnerObjectModelViewSet):"""serializer.save(user=self.request.user)+ def perform_destroy(self, instance):+ """+ Official categories hold the data of the legacy weight endpoint and+ must not be deleted+ """+ if instance.is_official:+ raise PermissionDenied('Official categories cannot be deleted')+ instance.delete()+@staticmethoddef get_owner_objects():"""diff --git a/wger/measurements/migrations/0007_official_categories.py b/wger/measurements/migrations/0007_official_categories.pyindex 902be8212..bf2a5d753 100644--- a/wger/measurements/migrations/0007_official_categories.py+++ b/wger/measurements/migrations/0007_official_categories.py@@ -5,8 +5,8 @@ BATCH_SIZE = 2000def migrate_weight_to_measurements(apps, schema_editor):"""- For every existing WeightEntry, ensure the owning user has an official- 'body_weight' Category and create a matching Measurement row.+ Give every user an official 'body_weight' Category and create a+ Measurement row for every existing WeightEntry.The WeightEntry uuid is carried over as the Measurement id so thatclients that already synchronise weight entries by uuid keep a stable@@ -31,6 +31,21 @@ def migrate_weight_to_measurements(apps, schema_editor):)category_by_user[user_id] = category+ # Users without weight entries get the official category as well, new+ # users get it via the post_save signal on registration+ remaining = [+ Category(+ user_id=user_id,+ metric_type='body_weight',+ is_official=True,+ name='Body weight',+ unit=unit or 'kg',+ )+ for user_id, unit in unit_by_user.items()+ if user_id not in category_by_user+ ]+ Category.objects.bulk_create(remaining, batch_size=BATCH_SIZE)+batch = []for entry in WeightEntry.objects.all().iterator():batch.append(diff --git a/wger/measurements/powersync.py b/wger/measurements/powersync.pyindex 8968a402e..d0f2d7988 100644--- a/wger/measurements/powersync.py+++ b/wger/measurements/powersync.py@@ -43,6 +43,15 @@ class CategoryHandler(PowerSyncHandler):serializer_class = CategorySerializerviewset_class = CategoryViewSet+ def handle_delete(self, payload, user_id):+ entry = self._get_or_none(payload, user_id)+ if entry is not None and entry.is_official:+ return {+ 'error': 'Forbidden',+ 'details': 'Official categories cannot be deleted',+ }+ return super().handle_delete(payload, user_id)+@register_handlerclass MeasurementHandler(PowerSyncHandler):diff --git a/wger/measurements/tests/test_categories.py b/wger/measurements/tests/test_categories.pyindex 28424ee2d..82082bb57 100644--- a/wger/measurements/tests/test_categories.py+++ b/wger/measurements/tests/test_categories.py@@ -13,12 +13,14 @@# You should have received a copy of the GNU Affero General Public License# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.# Django+from django.contrib.auth.models import Userfrom django.urls import reverse# wgerfrom wger.core.tests import api_base_testfrom wger.core.tests.base_testcase import WgerTestCasefrom wger.measurements.models import Category+from wger.measurements.models.category import MetricTypeclass UnitApiTestCase(api_base_test.ApiBaseResourceTestCase):@@ -116,3 +118,95 @@ class CategoryGroupApiTestCase(WgerTestCase):self.assertEqual(response.status_code, 204)self.assertFalse(Category.objects.filter(pk=child.data['id']).exists())+++class OfficialCategoryTestCase(WgerTestCase):+ """+ Automatic creation and protection of official categories+ """++ # Pinned in test-measurement-categories.json+ official = 'cccccccc-cccc-cccc-cccc-0000000000b0' # user 'test'+ custom = 'cccccccc-cccc-cccc-cccc-000000000003' # user 'test'++ def setUp(self):+ super().setUp()+ self.user_login('test')++ def detail_url(self, pk):+ return reverse('measurement-category-detail', kwargs={'pk': pk})++ def test_new_user_gets_official_category(self):+ """+ Test that creating a user creates the official body weight category+ """+ user = User.objects.create_user('fresh-user', password='123')++ category = Category.objects.get(user=user, is_official=True)+ self.assertEqual(category.metric_type, MetricType.BODY_WEIGHT)+ self.assertEqual(category.unit, user.userprofile.weight_unit)++ def test_delete_official_forbidden(self):+ """+ Test that the official category cannot be deleted over the API+ """+ response = self.client.delete(self.detail_url(self.official))++ self.assertEqual(response.status_code, 403)+ self.assertTrue(Category.objects.filter(pk=self.official).exists())++ def test_delete_custom_allowed(self):+ """+ Test that custom categories can still be deleted+ """+ response = self.client.delete(self.detail_url(self.custom))++ self.assertEqual(response.status_code, 204)++ def test_metric_type_of_official_fixed(self):+ """+ Test that the metric type of an official category cannot be changed+ """+ response = self.client.patch(+ self.detail_url(self.official),+ {'metric_type': 'custom'},+ content_type='application/json',+ )++ self.assertEqual(response.status_code, 400)+ self.assertIn('metric_type', response.data)++ def test_rename_official_allowed(self):+ """+ Test that the official category can still be renamed+ """+ response = self.client.patch(+ self.detail_url(self.official),+ {'name': 'Körpergewicht'},+ content_type='application/json',+ )++ self.assertEqual(response.status_code, 200)++ def test_is_official_read_only(self):+ """+ Test that the official flag cannot be set over the API+ """+ response = self.client.patch(+ self.detail_url(self.custom),+ {'is_official': True},+ content_type='application/json',+ )++ self.assertEqual(response.status_code, 200)+ self.assertFalse(Category.objects.get(pk=self.custom).is_official)++ def test_filter_by_is_official(self):+ """+ Test that the category list can be filtered by the official flag+ """+ response = self.client.get(reverse('measurement-category-list'), {'is_official': True})++ self.assertEqual(response.status_code, 200)+ self.assertEqual(len(response.data['results']), 1)+ self.assertEqual(response.data['results'][0]['id'], self.official)