Self hosted FLOSS fitness/workout, nutrition and weight tracker
Kategorie-Unit an den metric_type binden
Roland Geider1635236083dc
diff --git a/wger/measurements/api/serializers.py b/wger/measurements/api/serializers.pyindex e14d1a8a1..370f5d62d 100644--- a/wger/measurements/api/serializers.py+++ b/wger/measurements/api/serializers.py@@ -29,7 +29,10 @@ from wger.measurements.models import (Category,Measurement,)-from wger.measurements.models.category import MetricType+from wger.measurements.models.category import (+ BODY_WEIGHT_UNITS,+ MetricType,+)class CategorySerializer(serializers.ModelSerializer):@@ -130,6 +133,15 @@ class CategorySerializer(serializers.ModelSerializer):{'metric_type': 'A category with measurements cannot become a group'})+ # Body weight is read through Measurement.value_in(), which converts+ # between kg and lb and knows no third unit+ if metric_type == MetricType.BODY_WEIGHT:+ unit = data.get('unit', instance.unit if instance else None)+ if unit not in BODY_WEIGHT_UNITS:+ raise serializers.ValidationError(+ {'unit': 'Body weight categories only support kg and lb as unit'}+ )+self._validate_unique_metric_type(metric_type)return data@@ -256,8 +268,12 @@ class MeasurementSerializer(serializers.ModelSerializer):extra_data = data.get('extra_data', self.instance.extra_data if self.instance else {})unit = extra_data.get('unit')- if 'extra_data' in data and unit is not None and category is not None:- if category.metric_type == MetricType.BODY_WEIGHT and unit not in ('kg', 'lb'):+ # Checked whenever the payload restamps the unit or moves the entry+ # into another category; a unit already stored must not block an+ # unrelated edit+ touches_unit = 'extra_data' in data or 'category' in data+ if touches_unit and unit is not None and category is not None:+ if category.metric_type == MetricType.BODY_WEIGHT and unit not in BODY_WEIGHT_UNITS:raise serializers.ValidationError({'extra_data': 'Body weight entries only support kg and lb as unit'})diff --git a/wger/measurements/models/category.py b/wger/measurements/models/category.pyindex f16bdbf9d..4f0f3fa56 100644--- a/wger/measurements/models/category.py+++ b/wger/measurements/models/category.py@@ -129,6 +129,17 @@ COMPONENT_GROUPS: dict[str, str] = {}+BODY_WEIGHT_UNITS = ('kg', 'lb')+"""+The units a body weight is stored in, on the category as well as per entry.++Body weight is the one metric whose values are converted on read+(``Measurement.value_in``), so a category holding anything else has no reader:+the legacy weight endpoint, the BMI, the trainer view and the CSV export all+go through that conversion.+"""++CATEGORY_NAMESPACE = uuid.UUID('4c5ef6dd-97c9-5b18-9f8b-2a5c1ed70a2f')"""Namespace for the derived primary keys, see Category.deterministic_id()"""diff --git a/wger/measurements/models/measurement.py b/wger/measurements/models/measurement.pyindex 7662da93c..57cc43e37 100644--- a/wger/measurements/models/measurement.py+++ b/wger/measurements/models/measurement.py@@ -28,7 +28,10 @@ from wger.measurements.limits import (VALUE_MAX_DIGITS,)from wger.measurements.models import Category-from wger.measurements.models.category import MetricType+from wger.measurements.models.category import (+ BODY_WEIGHT_UNITS,+ MetricType,+)from wger.utils.constants import TWOPLACESfrom wger.utils.units import AbstractWeightfrom wger.utils.uuid import uuid7@@ -146,7 +149,7 @@ class Measurement(models.Model):"""if self.unit == unit:return self.value- if unit not in ('kg', 'lb') or self.unit not in ('kg', 'lb'):+ if unit not in BODY_WEIGHT_UNITS or self.unit not in BODY_WEIGHT_UNITS:raise ValueError(f'Cannot convert between {self.unit} and {unit}')weight = AbstractWeight(self.value, self.unit)return (weight.kg if unit == 'kg' else weight.lb).quantize(TWOPLACES)diff --git a/wger/measurements/tests/test_categories.py b/wger/measurements/tests/test_categories.pyindex 990385bc7..ad0512d07 100644--- a/wger/measurements/tests/test_categories.py+++ b/wger/measurements/tests/test_categories.py@@ -374,6 +374,33 @@ class OfficialCategoryTestCase(WgerTestCase):self.assertEqual(response.status_code, 200)+ def test_unit_of_body_weight_restricted(self):+ """+ Test that a body weight category only takes kg and lb as unit+ """+ response = self.client.patch(+ self.detail_url(self.official),+ {'unit': 'stone'},+ content_type='application/json',+ )++ self.assertEqual(response.status_code, 400)+ self.assertIn('unit', response.data)+ self.assertEqual(Category.objects.get(pk=self.official).unit, 'kg')++ def test_unit_of_body_weight_switchable(self):+ """+ Test that the category can still be switched between kg and lb+ """+ response = self.client.patch(+ self.detail_url(self.official),+ {'unit': 'lb'},+ content_type='application/json',+ )++ self.assertEqual(response.status_code, 200)+ self.assertEqual(Category.objects.get(pk=self.official).unit, 'lb')+def test_is_official_read_only(self):"""Test that the official flag cannot be set over the APIdiff --git a/wger/measurements/tests/test_measurements.py b/wger/measurements/tests/test_measurements.pyindex 2b874afe9..6b8645e6d 100644--- a/wger/measurements/tests/test_measurements.py+++ b/wger/measurements/tests/test_measurements.py@@ -382,6 +382,31 @@ class MeasurementExtraDataApiTestCase(WgerTestCase):self.assertEqual(response.status_code, 400)self.assertIn('extra_data', response.data)+ def test_moving_an_entry_with_a_foreign_unit(self):+ """+ Test that an entry cannot be moved into the body weight category while+ it carries a unit that category does not support+ """+ entry = self.client.post(+ self.url,+ {+ 'category': 'cccccccc-cccc-cccc-cccc-000000000003',+ 'date': '2023-05-01T12:00:00Z',+ 'value': 42,+ 'extra_data': {'unit': 'rods to the hogshead'},+ },+ content_type='application/json',+ )++ response = self.client.patch(+ reverse('measurement-detail', kwargs={'pk': entry.data['id']}),+ {'category': 'cccccccc-cccc-cccc-cccc-0000000000b0'},+ content_type='application/json',+ )++ self.assertEqual(response.status_code, 400)+ self.assertIn('extra_data', response.data)+def test_custom_category_unit_free(self):"""Test that custom categories accept any unit in extra_data