Self hosted FLOSS fitness/workout, nutrition and weight tracker
Merge branch 'feature/dynamic-measurements' (PR #2338)
Roland Geider859d95e4cf9e
diff --cc wger/measurements/api/serializers.pyindex 1ed55f83b,c07c33d71..4315e5da1--- a/wger/measurements/api/serializers.py+++ b/wger/measurements/api/serializers.py@@@ -59,167 -34,46 +60,198 @@@ class CategorySerializer(serializers.Moclass Meta:model = Category- fields = ('id', 'name', 'unit', 'dynamic_type', 'dynamic_params')+ fields = (+ 'id',+ 'name',+ 'unit',+ 'metric_type',+ 'chart_type',+ 'chart_config',+ 'parent',+ 'order',+ 'is_official',++ 'dynamic_type',++ 'dynamic_params',+ )+ read_only_fields = ('is_official',)++ def validate_chart_config(self, chart_config):+ """+ Only the shape is the server's business, the keys are the clients'+ """+ return validate_json_object(chart_config, 'chart_config', CHART_CONFIG_MAX_BYTES)++ def validate_metric_type(self, metric_type):+ """+ The metric type is fixed once the category exists: the key of a typed+ one is derived from it (Category.deterministic_id). Assigning a type to+ an existing category is a move, not a change of this field+ """+ if self.instance and metric_type != self.instance.metric_type:+ raise serializers.ValidationError('The metric type of a category cannot be changed')+ return metric_type++ def validate_parent(self, parent):+ """+ Enforce the structural rules for multi-value groups: one level of+ nesting, no cycles, and parents stay measurement-free.+ """+ if parent is None:+ return parent++ if self.instance:+ if parent.pk == self.instance.pk:+ raise serializers.ValidationError('A category cannot be its own parent')++ if self.instance.children.exists():+ raise serializers.ValidationError(+ 'A category with subcategories cannot itself have a parent'+ )++ if parent.parent_id is not None:+ raise serializers.ValidationError('Categories can only be nested one level deep')++ if parent.measurement_set.exists():+ raise serializers.ValidationError(+ 'A category with measurements cannot be used as a parent'+ )++ return parentdef validate(self, data):"""- Validate the dynamic_params JSON matches the required schema for the selected dynamic_type.+ Structural rules of the typed categories.++ Each metric type has one role: components live under the group they+ belong to, every other typed category is top-level, and there is exactly+ one category per type and user (see Category.deterministic_id).+ """+ instance = self.instance+ metric_type = data.get(+ 'metric_type',+ instance.metric_type if instance else MetricType.CUSTOM,+ )+ parent = data.get('parent', instance.parent if instance else None)++ if MetricType.is_component(metric_type):+ group = MetricType.group_of(metric_type)+ if parent is None or parent.metric_type != group:+ raise serializers.ValidationError(+ {'parent': f'A {metric_type} category must be part of a {group} group'}+ )+ elif metric_type != MetricType.CUSTOM and parent is not None:+ raise serializers.ValidationError(+ {'parent': f'A {metric_type} category cannot be nested'}+ )++ if parent is not None and MetricType.is_group(parent.metric_type):+ allowed = [c for c, _ in MetricType.components_of(parent.metric_type)]+ if metric_type not in allowed:+ raise serializers.ValidationError(+ {'metric_type': f'A {parent.metric_type} group only holds its own components'}+ )++ # 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)++ self._validate_dynamic(data)+ return data+++ def _validate_dynamic(self, data):++ """++ The dynamic_params JSON has to match the schema of the selected++ dynamic_type+ """- # get type and params+ dynamic_type = data.get(+ 'dynamic_type', getattr(self.instance, 'dynamic_type', Category.DynamicType.NONE)+ )+ dynamic_params = data.get('dynamic_params', getattr(self.instance, 'dynamic_params', {}))+- # if dynamic type is none, just clear params to avoid excessive validation+ if dynamic_type == Category.DynamicType.NONE:+ data['dynamic_params'] = {}- return super().validate(data)++ return+- # define the allowed JSON structures+ schemas = {+ Category.DynamicType.BMI: {+ 'type': 'object',+ 'additionalProperties': False,+ },- # when one rep max is added it can go here- # Category.DynamicType.ONE_REP_MAX: {- # "type": "object",- # "properties": {"exercise_id": {"type": "integer"}, "max_reps": {"type": "integer"}},- # "required": ["exercise_id"],- # "additionalProperties": False- # }+ }++ schema = schemas.get(dynamic_type)+ if schema:+ try:+ jsonschema.validate(instance=dynamic_params, schema=schema)+ except jsonschema.exceptions.ValidationError as e:+ raise serializers.ValidationError({'dynamic_params': e.message})+- return super().validate(data)+ def _validate_unique_metric_type(self, metric_type):+ """+ Only one category per metric type and user.++ DRF generates a validator for a UniqueConstraint only when the+ serializer maps every field of it. The owner is not part of the payload+ (it is passed to save() by the viewset and the PowerSync handler), so+ this constraint is skipped and a duplicate would otherwise only surface+ as an IntegrityError when saving.+ """+ user_id = self._get_user_id()+ if metric_type == MetricType.CUSTOM or user_id is None:+ return++ categories = Category.objects.filter(user_id=user_id, metric_type=metric_type)+ if self.instance is not None:+ categories = categories.exclude(pk=self.instance.pk)+ if categories.exists():+ raise serializers.ValidationError(+ {'metric_type': f'You already have a {metric_type} category'}+ )++ 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++ def create(self, validated_data):+ """+ Derives the key of a typed category and fills a group with components+ """+ metric_type = validated_data.get('metric_type', MetricType.CUSTOM)+ user_id = validated_data.get('user_id') or getattr(validated_data.get('user'), 'pk', None)++ # A client that creates the category offline derives the same key, so+ # only fill it in when the payload brought none of its own+ if 'id' not in validated_data and Category.has_deterministic_id(metric_type) and user_id:+ validated_data['id'] = Category.deterministic_id(user_id, metric_type)++ category = super().create(validated_data)+ category.create_components()+ return category++ def update(self, instance, validated_data):+ """+ Fills in the components a group is missing+ """+ category = super().update(instance, validated_data)+ category.create_components()+ return categoryclass MeasurementSerializer(serializers.ModelSerializer):diff --cc wger/measurements/api/views.pyindex 50146aba6,09d4dba97..3e66289f5--- a/wger/measurements/api/views.py+++ b/wger/measurements/api/views.py@@@ -97,8 -82,20 +97,20 @@@ class CategoryViewSet(WgerOwnerObjectMo"""Return objects to check for ownership permission"""- return [(User, 'user')]+ return [(User, 'user'), (Category, 'parent')]+ @action(detail=False, methods=['get'], url_path='dynamic-types')+ def dynamic_types(self, request):+ """+ Dedicated route for virtual/calculated categories+ Returns a list of available dynamic calculation types from the model Enum.+ URL: /api/v2/measurement-category/dynamic-types/+ """+ choices = [+ {'value': choice.value, 'label': choice.label} for choice in Category.DynamicType+ ]+ return Response(choices)+class MeasurementViewSet(WgerOwnerObjectModelViewSet):"""diff --cc wger/measurements/migrations/0008_dynamic_type.pyindex 000000000,92ecc9679..da45e0a4bmode 000000,100644..100644--- a/wger/measurements/migrations/0008_dynamic_type.py+++ b/wger/measurements/migrations/0008_dynamic_type.py@@@ -1,0 -1,31 +1,31 @@@+ # Generated by Django 5.2.14 on 2026-05-15 08:13++ from django.db import migrations, models+++ class Migration(migrations.Migration):+ dependencies = [- ('measurements', '0003_alter_measurement_unique_together_and_more'),++ ('measurements', '0007_migrate_weight'),+ ]++ operations = [+ migrations.AddField(+ model_name='category',+ name='dynamic_params',+ field=models.JSONField(+ blank=True,+ default=dict,+ help_text='Configuration parameters for dynamic calculations',+ ),+ ),+ migrations.AddField(+ model_name='category',+ name='dynamic_type',+ field=models.CharField(- choices=[('NONE', 'None'), ('BMI', 'Bmi')],++ choices=[('NONE', 'None'), ('BMI', 'BMI')],+ db_index=True,+ default='NONE',+ max_length=20,+ ),+ ),+ ]diff --cc wger/measurements/models/category.pyindex 1c32aba3e,cc6a06481..f54789bae--- a/wger/measurements/models/category.py+++ b/wger/measurements/models/category.py@@@ -189,64 -39,21 +189,76 @@@ class Category(models.Model)unit = models.CharField(verbose_name='Unit',max_length=30,+ # Not every metric has one: a step count is a bare number, and a+ # free-form category may be too+ blank=True,+ )++ metric_type = models.CharField(+ verbose_name='Metric type',+ max_length=30,+ choices=MetricType.choices,+ default=MetricType.CUSTOM,+ )++ # Null means "derive the chart from the metric type", which is what every+ # category does unless the user picked something else. Which of the values+ # are offered is a client decision (a step count is a bar or a heatmap, not+ # a line), and so is what happens to a value that does not fit the category:+ # the clients fall back to the derived default instead of showing nothing,+ # which is also what keeps an older client working when a type is added here+ chart_type = models.CharField(+ verbose_name='Chart type',+ max_length=20,+ choices=ChartType.choices,+ blank=True,+ null=True,+ )++ # Taste-level chart settings, e.g. {"trend": "sluggish"}: the keys are+ # client business, a missing one means the client's default. PATCH replaces+ # the object, so clients merge back keys they do not know (like extra_data)+ chart_config = models.JSONField(+ verbose_name='Chart config',+ default=dict,+ blank=True,+ )++ # Multi-value measurements (e.g. blood pressure) are modelled as a parent+ # category holding one child category per component. Only leaf categories+ # (no children) carry measurements; nesting is limited to one level.+ parent = models.ForeignKey(+ 'self',+ verbose_name='Parent',+ on_delete=models.CASCADE,+ related_name='children',+ blank=True,+ null=True,+ )++ # Position in the category list; for children, the position within the group+ order = models.IntegerField(+ verbose_name='Order',+ default=0,+ )++ is_official = models.BooleanField(+ verbose_name='Official category',+ default=False,)+ class DynamicType(models.TextChoices):- NONE = ('NONE',)- BMI = ('BMI',)- # ONE_REP_MAX = ('ONE_REP_MAX'), can be added in future++ NONE = 'NONE', 'None'++ BMI = 'BMI', 'BMI'++ dynamic_type = models.CharField(+ max_length=20, choices=DynamicType.choices, default=DynamicType.NONE, db_index=True+ )++ dynamic_params = models.JSONField(+ default=dict, blank=True, help_text='Configuration parameters for dynamic calculations'+ )+def get_owner_object(self):"""Returns the object that has owner informationdiff --cc wger/measurements/powersync.pyindex 5ea568a8f,000000000..426cf3d21mode 100644,000000..100644--- a/wger/measurements/powersync.py+++ b/wger/measurements/powersync.py@@@ -1,74 -1,0 +1,74 @@@+# 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+# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.++# wger+from wger.measurements.api.serializers import (+ CategorySerializer,+ MeasurementSerializer,+)+from wger.measurements.api.views import (+ CategoryViewSet,+ MeasurementViewSet,+)+from wger.measurements.models import (+ Category,+ Measurement,+)+from wger.utils.powersync import (+ PowerSyncHandler,+ register_handler,+)+++@register_handler+class CategoryHandler(PowerSyncHandler):+ """+ Measurement categories — directly owned by ``user``; the ``parent`` FK+ (multi-value groups) additionally needs an ownership check.+ """++ model = Category+ serializer_class = CategorySerializer+ viewset_class = CategoryViewSet- json_fields = frozenset({'chart_config'})++ json_fields = frozenset({'chart_config', 'dynamic_params'})++ # The serializer checks the "one category per metric type" rule, for which+ # it needs to know whose categories to look at+ pass_user_id_in_context = True++ 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_handler+class MeasurementHandler(PowerSyncHandler):+ """Measurements live under a ``Category``; ownership rides on that FK."""++ model = Measurement+ serializer_class = MeasurementSerializer+ viewset_class = MeasurementViewSet+ user_filter = 'category__user_id'+ json_fields = frozenset({'extra_data'})++ def create_save_kwargs(self, payload, user_id):+ # Ownership is enforced through the category FK, not via a direct+ # user_id on the Measurement row.+ return {}diff --cc wger/measurements/utils/bmi.pyindex 000000000,fc32181a4..9c32d2e41mode 000000,100644..100644--- a/wger/measurements/utils/bmi.py+++ b/wger/measurements/utils/bmi.py@@@ -1,0 -1,41 +1,43 @@@+ # -*- coding: utf-8 -*-++ # 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+ # along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.+++# Standard Library++from decimal import Decimal+-def calculate_bmi(user, category_id):++++def calculate_bmi(user) -> list[dict]:++ """++ Returns one row per body weight entry: its date, the BMI it works out to++ and the id of the entry it derives from++ """+ # wger- from wger.weight.models import WeightEntry++ from wger.measurements.models import Measurement++ profile = user.userprofile- if not profile or not profile.height or profile.height <= 0:++ if not profile.height or profile.height <= 0:+ return []+- # height_sq will be a float- height_sq = (profile.height / 100) ** 2-- weights = WeightEntry.objects.filter(user=user).order_by('date')++ height_sq = (Decimal(profile.height) / 100) ** 2++ return [+ {- 'id': w.id,- 'category': int(category_id), # link it to the requested category- 'date': w.date.isoformat(),- 'value': round(float(w.weight) / height_sq, 2),- 'notes': 'Auto-calculated from weight entry',++ 'source_id': entry.id,++ 'date': entry.date,++ 'value': round(entry.value_in('kg') / height_sq, 2),+ }- for w in weights++ for entry in Measurement.body_weight_for(user).order_by('date')+ ]