Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Address measurements by metric type and external id

Roland Geiderffd780cdccf9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 809955f9c..9469d787d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,7 +9,10 @@
Progression requirements can now reference the top of the prescribed range via the new rules `max_repetitions` and `max_weight`, and the new `all_sets` flag requires every prescribed set to qualify. Together they enable classic double progression schemes ("work from 8 to 12 reps at a fixed weight, add weight only once all sets reach 12"), e.g. `{"rules": ["max_repetitions"], "all_sets": true}`.
### Others
-* ...
+* `/api/v2/measurement/` accepts a `metric_type` instead of a `category` id when
+ writing, and can be filtered by `metric_type` and `external_id`. Integrations
+ such as scale apps no longer have to look up their category first or keep
+ track of the ids of the entries they wrote.
### Bug fixes
diff --git a/settings/settings_global.py b/settings/settings_global.py
index b523f9c9b..6b871fa2a 100644
--- a/settings/settings_global.py
+++ b/settings/settings_global.py
@@ -589,6 +589,7 @@ SPECTACULAR_SETTINGS = {
'POSTPROCESSING_HOOKS': [
'drf_spectacular.hooks.postprocess_schema_enums',
'wger.utils.api_schema.strip_patch_defaults',
+ 'wger.utils.api_schema.require_measurement_category',
],
# Both are exposed as a plain "type" field on more than one component, which
# spectacular would otherwise name with a hash suffix (e.g. Type947Enum).
diff --git a/wger/core/tests/api/test_schema.py b/wger/core/tests/api/test_schema.py
index a4f1047a6..3d383181c 100644
--- a/wger/core/tests/api/test_schema.py
+++ b/wger/core/tests/api/test_schema.py
@@ -73,6 +73,22 @@ class SchemaPaginationTestCase(SimpleTestCase):
self.assertEqual(paginated, [])
+class SchemaMeasurementCategoryTestCase(SimpleTestCase):
+ """
+ The category of a measurement in the generated schema
+ """
+
+ def test_category_is_required_in_the_response_only(self):
+ """
+ A create may name the metric_type instead, a stored entry always has one
+ """
+ schemas = SchemaGenerator().get_schema(request=None, public=True)['components']['schemas']
+
+ self.assertIn('category', schemas['Measurement']['required'])
+ self.assertNotIn('category', schemas['MeasurementRequest']['required'])
+ self.assertIn('metric_type', schemas['MeasurementRequest']['properties'])
+
+
class SchemaCacheTestCase(SimpleTestCase):
"""
The caching of the generated schema
diff --git a/wger/measurements/api/filtersets.py b/wger/measurements/api/filtersets.py
index 0b54cf3fe..9df7a25b6 100644
--- a/wger/measurements/api/filtersets.py
+++ b/wger/measurements/api/filtersets.py
@@ -18,9 +18,15 @@ from django_filters import rest_framework as filters
# wger
from wger.measurements.models import Measurement
+from wger.measurements.models.category import MetricType
class MeasurementEntryFilterSet(filters.FilterSet):
+ metric_type = filters.ChoiceFilter(
+ field_name='category__metric_type',
+ choices=MetricType.choices,
+ )
+
class Meta:
model = Measurement
fields = {
@@ -31,4 +37,5 @@ class MeasurementEntryFilterSet(filters.FilterSet):
],
'date': ['exact', 'gt', 'gte', 'lt', 'lte'],
'source': ['exact'],
+ 'external_id': ['exact', 'in'],
}
diff --git a/wger/measurements/api/serializers.py b/wger/measurements/api/serializers.py
index 9115edc97..ec139321a 100644
--- a/wger/measurements/api/serializers.py
+++ b/wger/measurements/api/serializers.py
@@ -57,6 +57,22 @@ def validate_json_object(value, field: str, max_bytes: int):
return value
+def context_user_id(context: dict) -> int | None:
+ """
+ Returns the id of the user a serializer writes for.
+
+ The owner is not part of the payload, it is passed to save() by the
+ viewset (as a request) or by the PowerSync handler (as a context value).
+ """
+ user_id = context.get('user_id')
+ if user_id is not None:
+ return user_id
+
+ request = context.get('request')
+ user = getattr(request, 'user', None) if request else None
+ return user.pk if user is not None and user.is_authenticated else None
+
+
class CategorySerializer(serializers.ModelSerializer):
"""
Measurement category serializer
@@ -249,17 +265,8 @@ class CategorySerializer(serializers.ModelSerializer):
def _get_user_id(self):
"""
Returns the id of the user the category belongs to.
-
- The owner is not part of the payload, it is passed to save() by the
- viewset (as a request) or by the PowerSync handler (as a context value).
"""
- user_id = self.context.get('user_id')
- if user_id is not None:
- return user_id
-
- request = self.context.get('request')
- user = getattr(request, 'user', None) if request else None
- return user.pk if user is not None and user.is_authenticated else None
+ return context_user_id(self.context)
def create(self, validated_data):
"""
@@ -303,11 +310,22 @@ class MeasurementSerializer(serializers.ModelSerializer):
coerce_to_string=False,
)
+ # Addresses the category by its type instead of its id, so that an
+ # integration does not have to look it up first
+ metric_type = serializers.ChoiceField(
+ choices=MetricType.choices,
+ write_only=True,
+ required=False,
+ help_text='Alternative to category when writing: the category of this type of the '
+ 'user. It has to exist, custom and group types are not accepted.',
+ )
+
class Meta:
model = Measurement
fields = (
'id',
'category',
+ 'metric_type',
'date',
'value',
'notes',
@@ -315,6 +333,51 @@ class MeasurementSerializer(serializers.ModelSerializer):
'external_id',
'extra_data',
)
+ # Either this or metric_type, see to_internal_value()
+ extra_kwargs = {
+ 'category': {
+ 'required': False,
+ 'help_text': 'When writing, either this or metric_type is required.',
+ },
+ }
+
+ def to_internal_value(self, data):
+ """
+ Resolves metric_type to the user's category of that type.
+
+ Done here and not in validate(): the validator of the external_id
+ constraint runs in between and needs the category. It also reports a
+ create that names neither.
+ """
+ attrs = super().to_internal_value(data)
+ metric_type = attrs.pop('metric_type', None)
+ if metric_type is None:
+ return attrs
+
+ # Free-form categories share the type, it does not identify one
+ if metric_type == MetricType.CUSTOM:
+ raise serializers.ValidationError(
+ {'metric_type': 'Free-form categories can only be addressed by their id'}
+ )
+
+ category = Category.objects.filter(
+ user_id=context_user_id(self.context),
+ metric_type=metric_type,
+ ).first()
+ if category is None:
+ raise serializers.ValidationError(
+ {'metric_type': f'You have no {metric_type} category'}
+ )
+ if attrs.get('category', category) != category:
+ raise serializers.ValidationError(
+ {'metric_type': 'Does not match the metric type of the category'}
+ )
+
+ try:
+ attrs['category'] = self.validate_category(category)
+ except serializers.ValidationError as e:
+ raise serializers.ValidationError({'metric_type': e.detail})
+ return attrs
def validate_category(self, category):
"""
diff --git a/wger/measurements/tests/test_measurements.py b/wger/measurements/tests/test_measurements.py
index 33cdde0fc..f3a87b82c 100644
--- a/wger/measurements/tests/test_measurements.py
+++ b/wger/measurements/tests/test_measurements.py
@@ -597,3 +597,82 @@ class AggregateBoundValidationTestCase(WgerTestCase):
def test_extra_data_without_bounds_is_untouched(self):
self.assertEqual(self.post({'unit': 'kg', 'source_name': 'Withings'}).status_code, 201)
+
+
+class MeasurementMetricTypeApiTestCase(WgerTestCase):
+ """
+ Writing a measurement with metric_type instead of a category id
+ """
+
+ body_weight_id = 'cccccccc-cccc-cccc-cccc-0000000000b0'
+ custom_id = 'cccccccc-cccc-cccc-cccc-000000000002'
+
+ def setUp(self):
+ super().setUp()
+ self.user_login('test')
+ self.url = reverse('measurement-list')
+
+ def post(self, **fields):
+ payload = {'date': '2026-10-08T07:30:00Z', 'value': 80, **fields}
+ return self.client.post(self.url, payload, content_type='application/json')
+
+ def test_metric_type_resolves_to_the_category_of_that_type(self):
+ response = self.post(metric_type='body_weight')
+
+ self.assertEqual(response.status_code, 201, response.data)
+ self.assertEqual(str(response.data['category']), self.body_weight_id)
+ self.assertEqual(response.data['extra_data'], {'unit': 'kg'})
+ self.assertNotIn('metric_type', response.data)
+
+ def test_matching_category_and_metric_type_are_accepted(self):
+ response = self.post(category=self.body_weight_id, metric_type='body_weight')
+
+ self.assertEqual(response.status_code, 201, response.data)
+
+ def test_neither_category_nor_metric_type_is_refused(self):
+ response = self.post()
+
+ self.assertEqual(response.status_code, 400)
+ self.assertIn('category', response.data)
+
+ def test_metric_type_without_a_usable_category_is_refused(self):
+ """
+ Nothing is written, and no category is created on the fly: name and
+ unit are the user's choice
+ """
+ Category.objects.filter(pk='cccccccc-cccc-cccc-cccc-000000000003').update(
+ metric_type=MetricType.BLOOD_PRESSURE,
+ )
+ before = (Measurement.objects.count(), Category.objects.count())
+
+ for fields in (
+ {'category': self.custom_id, 'metric_type': 'body_weight'},
+ {'metric_type': 'body_fat'},
+ {'metric_type': 'custom'},
+ {'metric_type': 'blood_pressure'},
+ ):
+ with self.subTest(**fields):
+ response = self.post(**fields)
+
+ self.assertEqual(response.status_code, 400)
+ self.assertIn('metric_type', response.data)
+
+ self.assertEqual((Measurement.objects.count(), Category.objects.count()), before)
+
+ def test_category_of_another_user_is_not_used(self):
+ self.user_login('admin')
+
+ response = self.post(metric_type='body_weight')
+
+ self.assertEqual(response.status_code, 400)
+ self.assertIn('metric_type', response.data)
+
+ def test_duplicate_external_id_is_refused(self):
+ external_id = 'eeeeeeee-eeee-eeee-eeee-000000000001'
+ first = self.post(metric_type='body_weight', external_id=external_id)
+ self.assertEqual(first.status_code, 201)
+
+ response = self.post(metric_type='body_weight', external_id=external_id)
+
+ self.assertEqual(response.status_code, 400)
+ self.assertIn('non_field_errors', response.data)
diff --git a/wger/utils/api_schema.py b/wger/utils/api_schema.py
index 909b948ba..fa1d2c584 100644
--- a/wger/utils/api_schema.py
+++ b/wger/utils/api_schema.py
@@ -82,6 +82,22 @@ def strip_patch_defaults(result, generator, **kwargs):
return result
+def require_measurement_category(result, generator, **kwargs):
+ """
+ Lists ``category`` as required in the ``Measurement`` response.
+
+ A create may name the ``metric_type`` instead, so the field is optional in
+ the serializer, and spectacular derives the required fields of a response
+ from there as well. Every stored entry has a category.
+ """
+ component = result.get('components', {}).get('schemas', {}).get('Measurement')
+ if component is not None:
+ required = {*component.get('required', []), 'category'}
+ component['required'] = [name for name in component['properties'] if name in required]
+
+ return result
+
+
class CachedSchemaGenerator(SchemaGenerator):
"""
Serves the generated schema out of the cache.
diff --git a/wger/version.py b/wger/version.py
index 93a4f1d2a..6bc604c51 100644
--- a/wger/version.py
+++ b/wger/version.py
@@ -35,7 +35,7 @@ Always use versions in the x.y.z format, without any suffixes like "beta1" or su
MIN_SERVER_VERSION = Version('2.5.0')
"""Minimum version of the server required to run sync commands on this server"""
-VERSION_STRING = '2.8.0-dev.1'
+VERSION_STRING = '2.8.0-dev.2'
"""
Current version of the app.