Self hosted FLOSS fitness/workout, nutrition and weight tracker
Restrict which categories can be calculated
Roland Geiderfdd41e7e9066
diff --git a/wger/measurements/api/serializers.py b/wger/measurements/api/serializers.pyindex 5cfcdefee..324c2369b 100644--- a/wger/measurements/api/serializers.py+++ b/wger/measurements/api/serializers.py@@ -38,6 +38,7 @@ from wger.measurements.models.category import (BODY_WEIGHT_UNITS,MetricType,)+from wger.measurements.models.measurement import MeasurementSourcedef validate_json_object(value, field: str, max_bytes: int):@@ -162,13 +163,13 @@ class CategorySerializer(serializers.ModelSerializer):)self._validate_unique_metric_type(metric_type)- self._validate_dynamic(data)+ self._validate_dynamic(data, metric_type)return data- def _validate_dynamic(self, data):+ def _validate_dynamic(self, data, metric_type):"""- The dynamic_params JSON has to match the schema of the selected- dynamic_type+ What a category may be calculated from, and whether its parameters fit+ the type it selects"""dynamic_type = data.get('dynamic_type', getattr(self.instance, 'dynamic_type', Category.DynamicType.NONE)@@ -179,6 +180,29 @@ class CategorySerializer(serializers.ModelSerializer):data['dynamic_params'] = {}return+ # A stored configuration is only re-checked when the payload moves it.+ # What it points at can be deleted afterwards, and that must not block+ # renaming or reordering the category (see _validate_value_range)+ if 'dynamic_type' not in data and 'dynamic_params' not in data:+ return++ # A typed category has a writer already, the health import or the+ # server itself. Two of them would fight over the same rows, and for+ # body weight the calculated entries would even end up as the input of+ # their own computation+ if metric_type != MetricType.CUSTOM:+ raise serializers.ValidationError(+ {'dynamic_type': f'A {metric_type} category cannot be calculated'}+ )++ if self.instance is not None and self._has_own_entries():+ raise serializers.ValidationError(+ {+ 'dynamic_type': 'The category holds entries of its own, move or delete '+ 'them before calculating it'+ }+ )+calc = dynamic.get_type(dynamic_type)if calc is not None:try:@@ -191,6 +215,14 @@ class CategorySerializer(serializers.ModelSerializer):except ValueError as e:raise serializers.ValidationError({'dynamic_params': str(e)})+ def _has_own_entries(self) -> bool:+ """+ Whether the category holds entries that are not the output of a+ calculation. The engine only ever replaces its own rows, so these+ would stay in the series without anything maintaining them.+ """+ return self.instance.measurement_set.exclude(source=MeasurementSource.CALCULATED).exists()+def _validate_unique_metric_type(self, metric_type):"""Only one category per metric type and user.@@ -332,14 +364,11 @@ class MeasurementSerializer(serializers.ModelSerializer):"""The unit and the range of the value both depend on the metric type"""- # Also blocks updates that leave the category field untouched- if (- self.instance is not None- and self.instance.category.dynamic_type != Category.DynamicType.NONE- ):- raise serializers.ValidationError(- 'The entries of a calculated category are maintained by the server'- )+ # Being maintained by the server is a property of the entry, not of+ # its category: rows the user wrote before the category was switched+ # over stay editable+ if self.instance is not None and self.instance.source == MeasurementSource.CALCULATED:+ raise serializers.ValidationError('A calculated entry is maintained by the server')category = data.get('category') or (self.instance.category if self.instance else None)extra_data = data.get('extra_data', self.instance.extra_data if self.instance else {})diff --git a/wger/measurements/api/views.py b/wger/measurements/api/views.pyindex 348f05121..db9bb5645 100644--- a/wger/measurements/api/views.py+++ b/wger/measurements/api/views.py@@ -52,6 +52,7 @@ from wger.measurements.models import (Category,Measurement,)+from wger.measurements.models.measurement import MeasurementSourcefrom wger.utils.viewsets import WgerOwnerObjectModelViewSet@@ -153,13 +154,11 @@ class MeasurementViewSet(WgerOwnerObjectModelViewSet):def perform_destroy(self, instance):"""- The entries of a calculated category are maintained by the server;- deleting one would only have the next reconcile recreate it+ A calculated entry is maintained by the server; deleting one would+ only have the next reconcile recreate it"""- if instance.category.dynamic_type != Category.DynamicType.NONE:- raise PermissionDenied(- 'The entries of a calculated category are maintained by the server'- )+ if instance.source == MeasurementSource.CALCULATED:+ raise PermissionDenied('A calculated entry is maintained by the server')instance.delete()def _read_max_points(self) -> int:diff --git a/wger/measurements/powersync.py b/wger/measurements/powersync.pyindex 3b881c411..866ad33e5 100644--- a/wger/measurements/powersync.py+++ b/wger/measurements/powersync.py@@ -26,6 +26,7 @@ from wger.measurements.models import (Category,Measurement,)+from wger.measurements.models.measurement import MeasurementSourcefrom wger.utils.powersync import (PowerSyncHandler,register_handler,@@ -75,9 +76,9 @@ class MeasurementHandler(PowerSyncHandler):def handle_delete(self, payload, user_id):entry = self._get_or_none(payload, user_id)- if entry is not None and entry.category.dynamic_type != Category.DynamicType.NONE:+ if entry is not None and entry.source == MeasurementSource.CALCULATED:return {'error': 'Forbidden',- 'details': 'The entries of a calculated category are maintained by the server',+ 'details': 'A calculated entry is maintained by the server',}return super().handle_delete(payload, user_id)diff --git a/wger/measurements/tests/test_dynamic.py b/wger/measurements/tests/test_dynamic.pyindex 81fda75a2..99df8516c 100644--- a/wger/measurements/tests/test_dynamic.py+++ b/wger/measurements/tests/test_dynamic.py@@ -29,6 +29,7 @@ from rest_framework import statusfrom wger.core.tests.base_testcase import WgerTestCasefrom wger.manager.consts import WEIGHT_UNIT_LBfrom wger.manager.models import WorkoutLog+from wger.measurements.dynamic.engine import reconcilefrom wger.measurements.models import (Category,Measurement,@@ -243,6 +244,120 @@ class EngineTestCase(DynamicMeasurementTestCase):self.assertEqual(self.calculated_rows(category).count(), 0)+class TypedCategoryTestCase(DynamicMeasurementTestCase):+ """+ Calculated types belong on custom categories, not on the typed ones the+ server and the health importer maintain themselves+ """++ def setUp(self):+ super().setUp()+ self.user_login('test')++ def test_official_category_refuses_dynamic_type(self):+ """+ The official body weight category cannot be turned into a BMI one+ """+ response = self.client.patch(+ reverse('measurement-category-detail', kwargs={'pk': self.weight_category.pk}),+ {'dynamic_type': 'BMI'},+ content_type='application/json',+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.weight_category.refresh_from_db()+ self.assertEqual(self.weight_category.dynamic_type, Category.DynamicType.NONE)++ def test_calculated_rows_never_feed_themselves(self):+ """+ A BMI computation ignores calculated entries, so a category that ends+ up as the source of its own type does not grow with every run+ """+ self.create_weight('81.00')++ # Past the check above this is only reachable through a bulk write+ with self.captureOnCommitCallbacks(execute=True):+ self.weight_category.dynamic_type = Category.DynamicType.BMI+ self.weight_category.save()+ first_run = self.calculated_rows(self.weight_category).count()++ reconcile(self.weight_category)++ self.assertEqual(self.calculated_rows(self.weight_category).count(), first_run)+++class ExistingEntriesTestCase(DynamicMeasurementTestCase):+ """+ Entries a user wrote themselves stay theirs, also in a category that was+ switched to a calculated type afterwards+ """++ def setUp(self):+ super().setUp()+ self.category = Category.objects.create(user=self.user, name='Waist', unit='cm')+ self.entry = Measurement.objects.create(+ category=self.category,+ date=timezone.now(),+ value=Decimal('90.00'),+ )+ self.user_login('test')++ def test_activation_refused_with_own_entries(self):+ """+ A category holding entries of its own cannot be switched over+ """+ response = self.client.patch(+ reverse('measurement-category-detail', kwargs={'pk': self.category.pk}),+ {'dynamic_type': 'BMI'},+ content_type='application/json',+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ def test_own_entries_stay_editable(self):+ """+ An entry of the user's own remains editable, the block is about the+ calculated rows and not about the category+ """+ with self.captureOnCommitCallbacks(execute=True):+ self.category.dynamic_type = Category.DynamicType.BMI+ self.category.save()++ response = self.client.patch(+ reverse('measurement-detail', kwargs={'pk': self.entry.pk}),+ {'value': 95},+ content_type='application/json',+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)++ def test_own_entries_stay_deletable(self):+ """+ The same for deleting, on the REST and the PowerSync path+ """+ with self.captureOnCommitCallbacks(execute=True):+ self.category.dynamic_type = Category.DynamicType.BMI+ self.category.save()++ response = self.client.delete(+ reverse('measurement-detail', kwargs={'pk': self.entry.pk}),+ )++ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)++ def test_own_entries_stay_deletable_over_powersync(self):+ """+ The synced delete of an own entry is not refused either+ """+ with self.captureOnCommitCallbacks(execute=True):+ self.category.dynamic_type = Category.DynamicType.BMI+ self.category.save()++ MeasurementHandler().handle_delete({'id': str(self.entry.pk)}, self.user.pk)++ self.assertFalse(Measurement.objects.filter(pk=self.entry.pk).exists())++class ApiWriteBlockTestCase(DynamicMeasurementTestCase):"""The entries of a calculated category cannot be written through the API@@ -523,6 +638,24 @@ class WhtrTestCase(DynamicMeasurementTestCase):)self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ def test_unrelated_patch_survives_a_deleted_source(self):+ """+ Renaming the category still works once its source is gone; only a+ payload that moves the configuration is checked against the data+ """+ self.create_waist('90.00')+ category = self.enable_whtr()+ self.waist.delete()++ self.user_login('test')+ response = self.client.patch(+ reverse('measurement-category-detail', kwargs={'pk': category.pk}),+ {'name': 'Ratio'},+ content_type='application/json',+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+def test_api_requires_source(self):"""The category_id param is mandatorydiff --git a/wger/measurements/utils/bmi.py b/wger/measurements/utils/bmi.pyindex 9c32d2e41..6650156c0 100644--- a/wger/measurements/utils/bmi.py+++ b/wger/measurements/utils/bmi.py@@ -26,6 +26,7 @@ def calculate_bmi(user) -> list[dict]:"""# wgerfrom wger.measurements.models import Measurement+ from wger.measurements.models.measurement import MeasurementSourceprofile = user.userprofileif not profile.height or profile.height <= 0:@@ -33,11 +34,15 @@ def calculate_bmi(user) -> list[dict]:height_sq = (Decimal(profile.height) / 100) ** 2+ # Calculated entries are never an input, otherwise a body weight category+ # that calculates itself would grow with every run+ entries = Measurement.body_weight_for(user).exclude(source=MeasurementSource.CALCULATED)+return [{'source_id': entry.id,'date': entry.date,'value': round(entry.value_in('kg') / height_sq, 2),}- for entry in Measurement.body_weight_for(user).order_by('date')+ for entry in entries.order_by('date')]