Self hosted FLOSS fitness/workout, nutrition and weight tracker
Materialize dynamic measurement categories
Roland Geider0fcca9270d07
diff --git a/wger/measurements/api/serializers.py b/wger/measurements/api/serializers.pyindex 4315e5da1..f1fb0b3e2 100644--- a/wger/measurements/api/serializers.py+++ b/wger/measurements/api/serializers.py@@ -22,6 +22,7 @@ import jsonschemafrom rest_framework import serializers# wger+from wger.measurements import dynamicfrom wger.measurements.limits import (CHART_CONFIG_MAX_BYTES,EXTRA_DATA_MAX_BYTES,@@ -178,17 +179,10 @@ class CategorySerializer(serializers.ModelSerializer):data['dynamic_params'] = {}return- schemas = {- Category.DynamicType.BMI: {- 'type': 'object',- 'additionalProperties': False,- },- }-- schema = schemas.get(dynamic_type)- if schema:+ calc = dynamic.get_type(dynamic_type)+ if calc is not None:try:- jsonschema.validate(instance=dynamic_params, schema=schema)+ jsonschema.validate(instance=dynamic_params, schema=calc.params_schema)except jsonschema.exceptions.ValidationError as e:raise serializers.ValidationError({'dynamic_params': e.message})@@ -297,6 +291,12 @@ class MeasurementSerializer(serializers.ModelSerializer):f'Measurements cannot be added to a {category.metric_type} category, 'f'they belong in its components')+ # The entries of a calculated category are written by the server; the+ # engine itself saves through the model layer and never gets here+ if category.dynamic_type != Category.DynamicType.NONE:+ raise serializers.ValidationError(+ 'The entries of a calculated category are maintained by the server'+ )return categorydef validate_extra_data(self, extra_data):@@ -327,6 +327,15 @@ 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'+ )+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 {})unit = extra_data.get('unit')@@ -383,6 +392,17 @@ class MeasurementSerializer(serializers.ModelSerializer):return limits_for(category.metric_type, unit or category.unit)+class DynamicTypeSerializer(serializers.Serializer):+ """+ One calculated category type of the registry. Read-only: the registry is+ code, there is nothing to write back.+ """++ value = serializers.CharField(read_only=True)+ label = serializers.CharField(read_only=True)+ params_schema = serializers.JSONField(read_only=True)++class BucketSerializer(serializers.Serializer):"""One calendar bucket of a category's entries, see `api.aggregates`.diff --git a/wger/measurements/api/views.py b/wger/measurements/api/views.pyindex 3e66289f5..348f05121 100644--- a/wger/measurements/api/views.py+++ b/wger/measurements/api/views.py@@ -40,9 +40,11 @@ from wger.measurements.api.aggregates import (value_count_rows,)from wger.measurements.api.filtersets import MeasurementEntryFilterSet+from wger.measurements import dynamicfrom wger.measurements.api.serializers import (BucketSerializer,CategorySerializer,+ DynamicTypeSerializer,MeasurementSerializer,ValueCountSerializer,)@@ -99,17 +101,26 @@ class CategoryViewSet(WgerOwnerObjectModelViewSet):"""return [(User, 'user'), (Category, 'parent')]- @action(detail=False, methods=['get'], url_path='dynamic-types')+ @extend_schema(+ summary='Read the available calculated category types',+ responses={200: DynamicTypeSerializer(many=True)},+ )+ @action(+ detail=False,+ methods=['get'],+ url_path='dynamic-types',+ serializer_class=DynamicTypeSerializer,+ )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/+ The calculated types a category can be switched to, with the schema+ their dynamic_params have to match"""- choices = [- {'value': choice.value, 'label': choice.label} for choice in Category.DynamicType+ rows = [+ {'value': calc.slug, 'label': calc.label, 'params_schema': calc.params_schema}+ for calc in dynamic.all_types()]- return Response(choices)+ return Response(DynamicTypeSerializer(rows, many=True).data)class MeasurementViewSet(WgerOwnerObjectModelViewSet):@@ -140,6 +151,17 @@ class MeasurementViewSet(WgerOwnerObjectModelViewSet):return Measurement.objects.filter(category__user=self.request.user)+ 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+ """+ if instance.category.dynamic_type != Category.DynamicType.NONE:+ raise PermissionDenied(+ 'The entries of a calculated category are maintained by the server'+ )+ instance.delete()+def _read_max_points(self) -> int:try:return max(1, int(self.request.query_params.get('max_points', DEFAULT_MAX_POINTS)))diff --git a/wger/measurements/apps.py b/wger/measurements/apps.pyindex 991c5c9a3..d6d6f3196 100644--- a/wger/measurements/apps.py+++ b/wger/measurements/apps.py@@ -5,3 +5,7 @@ class MeasurementsConfig(AppConfig):default_auto_field = 'django.db.models.BigAutoField'name = 'wger.measurements'verbose_name = 'Measurements'++ def ready(self):+ # wger+ import wger.measurements.signals # noqa: F401diff --git a/wger/measurements/dynamic/__init__.py b/wger/measurements/dynamic/__init__.pynew file mode 100644index 000000000..501756dde--- /dev/null+++ b/wger/measurements/dynamic/__init__.py@@ -0,0 +1,36 @@+# 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/>.++# Local+from .base import (+ Dependency,+ DesiredRow,+ DynamicMeasurementType,+ all_types,+ get_type,+ register,+ source_models,+)+++__all__ = [+ 'Dependency',+ 'DesiredRow',+ 'DynamicMeasurementType',+ 'all_types',+ 'get_type',+ 'register',+ 'source_models',+]diff --git a/wger/measurements/dynamic/base.py b/wger/measurements/dynamic/base.pynew file mode 100644index 000000000..7a410c099--- /dev/null+++ b/wger/measurements/dynamic/base.py@@ -0,0 +1,103 @@+# 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+import datetime+import uuid+from collections.abc import Callable+from dataclasses import (+ dataclass,+ field,+)+from decimal import Decimal++# Django+from django.db import models+++@dataclass(frozen=True)+class Dependency:+ """+ One source model a calculated type derives its values from.++ ``user_id`` resolves a changed instance to the owner whose calculated+ categories need a recompute, ``when`` filters out instances the type does+ not care about.+ """++ model: type[models.Model]+ user_id: Callable[[models.Model], int | None]+ when: Callable[[models.Model], bool] = lambda instance: True+++@dataclass(frozen=True)+class DesiredRow:+ """+ One entry a calculated category should hold. The external_id is the+ idempotency key the engine diffs on, see the unique constraint on+ (category, source, external_id).+ """++ external_id: uuid.UUID+ date: datetime.datetime+ value: Decimal+ extra_data: dict = field(default_factory=dict)+++class DynamicMeasurementType:+ """+ A calculated category type.++ Subclasses provide the math (``compute``), the models it depends on+ (``depends_on``) and the schema of its configuration+ (``params_schema``). Everything else, the triggers, the backfill and the+ reconciliation, is engine code shared by all types.+ """++ slug: str+ label: str+ params_schema: dict = {'type': 'object', 'additionalProperties': False}+ depends_on: list[Dependency] = []++ def compute(self, category) -> list[DesiredRow]:+ """+ Returns the full desired state of the category; the engine diffs it+ against the stored rows+ """+ raise NotImplementedError+++_registry: dict[str, DynamicMeasurementType] = {}+++def register(cls: type[DynamicMeasurementType]) -> type[DynamicMeasurementType]:+ _registry[cls.slug] = cls()+ return cls+++def get_type(slug: str) -> DynamicMeasurementType | None:+ return _registry.get(slug)+++def all_types() -> list[DynamicMeasurementType]:+ return list(_registry.values())+++def source_models() -> set[type[models.Model]]:+ """+ Every model at least one registered type depends on; the signal wiring+ connects one receiver per entry+ """+ return {dep.model for calc in _registry.values() for dep in calc.depends_on}diff --git a/wger/measurements/dynamic/engine.py b/wger/measurements/dynamic/engine.pynew file mode 100644index 000000000..5cccca571--- /dev/null+++ b/wger/measurements/dynamic/engine.py@@ -0,0 +1,118 @@+# 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+import logging+import threading++# Django+from django.conf import settings+from django.db import transaction++# wger+from wger.measurements.dynamic.base import get_type+from wger.measurements.models import (+ Category,+ Measurement,+)+from wger.measurements.models.measurement import MeasurementSource+++logger = logging.getLogger(__name__)++_pending = threading.local()+++def reconcile(category: Category) -> None:+ """+ Brings the stored calculated rows of a category to the state its type+ computes: missing rows are created, changed ones updated, orphans deleted.++ Backfill, live updates and repair are all this one operation. For a+ category that is not (or no longer) dynamic it degrades to deleting+ whatever calculated rows are left.+ """+ calc = get_type(category.dynamic_type)+ existing = Measurement.objects.filter(+ category=category,+ source=MeasurementSource.CALCULATED,+ )++ if calc is None:+ existing.delete()+ return++ existing_rows = {row.external_id: row for row in existing}++ for row in calc.compute(category):+ current = existing_rows.pop(row.external_id, None)+ if current is None:+ # get_or_create so a concurrent reconcile cannot trip over the+ # (category, source, external_id) constraint+ Measurement.objects.get_or_create(+ category=category,+ source=MeasurementSource.CALCULATED,+ external_id=row.external_id,+ defaults={+ 'date': row.date,+ 'value': row.value,+ 'extra_data': row.extra_data,+ },+ )+ elif (current.date, current.value, current.extra_data) != (+ row.date,+ row.value,+ row.extra_data,+ ):+ current.date = row.date+ current.value = row.value+ current.extra_data = row.extra_data+ current.save()++ for stale in existing_rows.values():+ stale.delete()+++def reconcile_by_id(category_id) -> None:+ try:+ category = Category.objects.get(pk=category_id)+ except Category.DoesNotExist:+ return+ reconcile(category)+++def schedule_reconcile(category_id) -> None:+ """+ Queues a reconcile for after the current transaction, deduplicated so a+ batch of source writes triggers one recompute rather than one per row+ """+ ids = getattr(_pending, 'ids', None)+ if ids is None:+ ids = _pending.ids = set()+ if category_id in ids:+ return+ ids.add(category_id)+ transaction.on_commit(lambda: _run_scheduled(category_id))+++def _run_scheduled(category_id) -> None:+ getattr(_pending, 'ids', set()).discard(category_id)+ if settings.WGER_SETTINGS['USE_CELERY']:+ # wger+ from wger.measurements.tasks import reconcile_dynamic_category_task++ reconcile_dynamic_category_task.delay(str(category_id))+ else:+ reconcile_by_id(category_id)diff --git a/wger/measurements/dynamic/types.py b/wger/measurements/dynamic/types.pynew file mode 100644index 000000000..387788dae--- /dev/null+++ b/wger/measurements/dynamic/types.py@@ -0,0 +1,60 @@+# 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.core.models import UserProfile+from wger.measurements.dynamic.base import (+ Dependency,+ DesiredRow,+ DynamicMeasurementType,+ register,+)+from wger.measurements.models import (+ Category,+ Measurement,+)+from wger.measurements.models.category import MetricType+from wger.measurements.utils.bmi import calculate_bmi+++@register+class Bmi(DynamicMeasurementType):+ """+ One BMI entry per body weight entry, from the official body weight+ category and the height of the profile+ """++ slug = Category.DynamicType.BMI+ label = 'BMI'+ params_schema = {'type': 'object', 'additionalProperties': False}+ depends_on = [+ Dependency(+ Measurement,+ user_id=lambda entry: entry.category.user_id,+ when=lambda entry: entry.category.metric_type == MetricType.BODY_WEIGHT,+ ),+ # The height lives on the profile+ Dependency(UserProfile, user_id=lambda profile: profile.user_id),+ ]++ def compute(self, category: Category) -> list[DesiredRow]:+ return [+ DesiredRow(+ external_id=row['source_id'],+ date=row['date'],+ value=row['value'],+ )+ for row in calculate_bmi(category.user)+ ]diff --git a/wger/measurements/migrations/0009_calculated_source.py b/wger/measurements/migrations/0009_calculated_source.pynew file mode 100644index 000000000..60b1ca509--- /dev/null+++ b/wger/measurements/migrations/0009_calculated_source.py@@ -0,0 +1,27 @@+# Generated by Django 6.0.8 on 2026-08-15 11:43++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ('measurements', '0008_dynamic_type'),+ ]++ operations = [+ migrations.AlterField(+ model_name='measurement',+ name='source',+ field=models.CharField(+ choices=[+ ('user', 'User'),+ ('google', 'Google'),+ ('apple', 'Apple'),+ ('calculated', 'Calculated'),+ ],+ default='user',+ max_length=10,+ verbose_name='Source',+ ),+ ),+ ]diff --git a/wger/measurements/models/measurement.py b/wger/measurements/models/measurement.pyindex 469cc3ca1..3378bea81 100644--- a/wger/measurements/models/measurement.py+++ b/wger/measurements/models/measurement.py@@ -41,6 +41,8 @@ class MeasurementSource(models.TextChoices):USER = 'user'GOOGLE = 'google'APPLE = 'apple'+ # Written by the server for calculated categories, see measurements.dynamic+ CALCULATED = 'calculated'class Measurement(models.Model):diff --git a/wger/measurements/powersync.py b/wger/measurements/powersync.pyindex 426cf3d21..3b881c411 100644--- a/wger/measurements/powersync.py+++ b/wger/measurements/powersync.py@@ -72,3 +72,12 @@ class MeasurementHandler(PowerSyncHandler):# Ownership is enforced through the category FK, not via a direct# user_id on the Measurement row.return {}++ 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:+ return {+ 'error': 'Forbidden',+ 'details': 'The entries of a calculated category are maintained by the server',+ }+ return super().handle_delete(payload, user_id)diff --git a/wger/measurements/signals.py b/wger/measurements/signals.pynew file mode 100644index 000000000..a7a011afd--- /dev/null+++ b/wger/measurements/signals.py@@ -0,0 +1,111 @@+# 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+import logging++# Django+from django.contrib.auth.models import User+from django.core.exceptions import ObjectDoesNotExist+from django.db.models.signals import (+ post_delete,+ post_save,+)+from django.dispatch import receiver++# wger+# The types have to be imported before the receivers are wired up below,+# source_models() only knows what is registered+import wger.measurements.dynamic.types # noqa: F401+from wger.measurements.dynamic.base import (+ all_types,+ source_models,+)+from wger.measurements.dynamic.engine import schedule_reconcile+from wger.measurements.models import (+ Category,+ Measurement,+)+from wger.measurements.models.measurement import MeasurementSource+from wger.utils.helpers import disable_for_loaddata+++logger = logging.getLogger(__name__)+++def _deletion_originates_from_user(origin) -> bool:+ """+ True if this delete is part of removing a User account: everything the+ reconcile would look at is going away in the same cascade+ """+ return isinstance(origin, User) or getattr(origin, 'model', None) is User+++def _dispatch_source_change(sender, instance):+ """+ Schedules a reconcile for every dynamic category that depends on the+ changed instance+ """+ # The engine's own writes must not trigger another round+ if isinstance(instance, Measurement) and instance.source == MeasurementSource.CALCULATED:+ return++ for calc in all_types():+ for dep in calc.depends_on:+ if dep.model is not sender:+ continue+ try:+ if not dep.when(instance):+ continue+ user_id = dep.user_id(instance)+ except ObjectDoesNotExist:+ # A related row vanished in the same cascade+ continue+ if user_id is None:+ continue++ categories = Category.objects.filter(+ user_id=user_id,+ dynamic_type=calc.slug,+ ).values_list('pk', flat=True)+ for category_id in categories:+ schedule_reconcile(category_id)+++@disable_for_loaddata+def _source_saved(sender, instance, **kwargs):+ _dispatch_source_change(sender, instance)+++def _source_deleted(sender, instance, origin=None, **kwargs):+ if _deletion_originates_from_user(origin):+ return+ _dispatch_source_change(sender, instance)+++for model in source_models():+ uid = f'measurements_dynamic_{model._meta.label_lower}'+ post_save.connect(_source_saved, sender=model, dispatch_uid=f'{uid}_save')+ post_delete.connect(_source_deleted, sender=model, dispatch_uid=f'{uid}_delete')+++@receiver(post_save, sender=Category, dispatch_uid='measurements_dynamic_category')+@disable_for_loaddata+def _category_saved(sender, instance, **kwargs):+ """+ Enabling, reconfiguring or disabling a dynamic type on a category: the+ reconcile backfills or clears its calculated rows+ """+ schedule_reconcile(instance.pk)diff --git a/wger/measurements/tasks.py b/wger/measurements/tasks.pynew file mode 100644index 000000000..412d5400c--- /dev/null+++ b/wger/measurements/tasks.py@@ -0,0 +1,49 @@+# 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+import logging++# wger+from wger.celery_configuration import app+from wger.measurements.dynamic.engine import (+ reconcile,+ reconcile_by_id,+)+from wger.measurements.models import Category+++logger = logging.getLogger(__name__)+++def reconcile_dynamic_category_task(category_id: str):+ """+ Recomputes the calculated rows of one dynamic category+ """+ reconcile_by_id(category_id)+++def reconcile_all_dynamic_categories_task():+ """+ Recomputes every dynamic category, the safety net for source writes that+ bypass the signals (bulk operations, data migrations)+ """+ count = 0+ for category in Category.objects.exclude(dynamic_type=Category.DynamicType.NONE).iterator():+ reconcile(category)+ count += 1+ logger.info(f'Reconciled {count} dynamic measurement categories')diff --git a/wger/measurements/tests/test_dynamic.py b/wger/measurements/tests/test_dynamic.pynew file mode 100644index 000000000..1f25be87a--- /dev/null+++ b/wger/measurements/tests/test_dynamic.py@@ -0,0 +1,388 @@+# 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+import datetime+from decimal import Decimal++# Django+from django.contrib.auth.models import User+from django.urls import reverse+from django.utils import timezone++# Third Party+from rest_framework import status++# wger+from wger.core.tests.base_testcase import WgerTestCase+from wger.measurements.models import (+ Category,+ Measurement,+)+from wger.measurements.models.measurement import MeasurementSource+from wger.measurements.powersync import MeasurementHandler+++# Pinned in test-measurement-categories.json, the official body weight+# category of user 'test' (height 180 in test-user-data.json)+BODY_WEIGHT_CATEGORY = 'cccccccc-cccc-cccc-cccc-0000000000b0'+++class DynamicMeasurementTestCase(WgerTestCase):+ """+ Base with helpers to write body weight entries and read the calculated+ rows with the engine's triggers firing (they run on transaction commit)+ """++ def setUp(self):+ super().setUp()+ self.user = User.objects.get(username='test')+ self.weight_category = Category.objects.get(pk=BODY_WEIGHT_CATEGORY)+ # The fixtures ship weight entries; the tests build their own history+ Measurement.objects.filter(category=self.weight_category).delete()++ def create_weight(self, value, days_ago: int = 0, unit: str = None) -> Measurement:+ with self.captureOnCommitCallbacks(execute=True):+ entry = Measurement.objects.create(+ category=self.weight_category,+ date=timezone.now() - datetime.timedelta(days=days_ago),+ value=Decimal(value),+ extra_data={'unit': unit} if unit else {},+ )+ return entry++ def enable_bmi(self) -> Category:+ with self.captureOnCommitCallbacks(execute=True):+ category = Category.objects.create(+ user=self.user,+ name='BMI',+ unit='',+ dynamic_type=Category.DynamicType.BMI,+ )+ return category++ def calculated_rows(self, category):+ return Measurement.objects.filter(+ category=category,+ source=MeasurementSource.CALCULATED,+ ).order_by('date')+++class EngineTestCase(DynamicMeasurementTestCase):+ """+ The reconcile engine keeps the calculated rows in step with their sources+ """++ def test_enabling_backfills(self):+ """+ Switching a category to BMI computes one row per existing weight entry+ """+ entry_old = self.create_weight('72.90', days_ago=10)+ entry_new = self.create_weight('81.00')++ category = self.enable_bmi()+ rows = self.calculated_rows(category)++ self.assertEqual(rows.count(), 2)+ # height 180: 72.9 / 1.8^2 = 22.5, 81 / 1.8^2 = 25+ self.assertEqual(rows[0].value, Decimal('22.50'))+ self.assertEqual(rows[0].external_id, entry_old.pk)+ self.assertEqual(rows[0].date, entry_old.date)+ self.assertEqual(rows[1].value, Decimal('25.00'))+ self.assertEqual(rows[1].external_id, entry_new.pk)++ def test_new_weight_entry_adds_row(self):+ """+ A weight entry written after the category exists gets its BMI row+ """+ category = self.enable_bmi()+ self.assertEqual(self.calculated_rows(category).count(), 0)++ self.create_weight('81.00')++ rows = self.calculated_rows(category)+ self.assertEqual(rows.count(), 1)+ self.assertEqual(rows[0].value, Decimal('25.00'))++ def test_updated_weight_entry_recomputes_row(self):+ """+ Editing a weight entry updates its BMI row in place+ """+ entry = self.create_weight('81.00')+ category = self.enable_bmi()++ with self.captureOnCommitCallbacks(execute=True):+ entry.value = Decimal('72.90')+ entry.save()++ rows = self.calculated_rows(category)+ self.assertEqual(rows.count(), 1)+ self.assertEqual(rows[0].value, Decimal('22.50'))+ self.assertEqual(rows[0].external_id, entry.pk)++ def test_deleted_weight_entry_removes_row(self):+ """+ Deleting a weight entry deletes the BMI row derived from it+ """+ entry = self.create_weight('81.00')+ keeper = self.create_weight('72.90', days_ago=5)+ category = self.enable_bmi()++ with self.captureOnCommitCallbacks(execute=True):+ entry.delete()++ rows = self.calculated_rows(category)+ self.assertEqual(rows.count(), 1)+ self.assertEqual(rows[0].external_id, keeper.pk)++ def test_pound_entries_are_converted(self):+ """+ A weight entry stored in lb is converted to kg before the formula+ """+ self.create_weight('180', unit='lb')+ category = self.enable_bmi()++ rows = self.calculated_rows(category)+ # 180 lb = 81.65 kg, / 1.8^2 = 25.20 (and not the naive 55.56)+ self.assertEqual(rows[0].value, Decimal('25.20'))++ def test_height_change_recomputes(self):+ """+ Changing the profile height recomputes every BMI row+ """+ self.create_weight('81.00')+ category = self.enable_bmi()++ profile = self.user.userprofile+ with self.captureOnCommitCallbacks(execute=True):+ profile.height = 200+ profile.save()++ rows = self.calculated_rows(category)+ # 81 / 2.0^2+ self.assertEqual(rows[0].value, Decimal('20.25'))++ def test_missing_height_clears_rows(self):+ """+ Without a height there is no BMI, the rows are removed+ """+ self.create_weight('81.00')+ category = self.enable_bmi()+ self.assertEqual(self.calculated_rows(category).count(), 1)++ profile = self.user.userprofile+ with self.captureOnCommitCallbacks(execute=True):+ profile.height = None+ profile.save()++ self.assertEqual(self.calculated_rows(category).count(), 0)++ def test_disabling_clears_rows(self):+ """+ Switching the category back to NONE deletes its calculated rows+ """+ self.create_weight('81.00')+ category = self.enable_bmi()+ self.assertEqual(self.calculated_rows(category).count(), 1)++ with self.captureOnCommitCallbacks(execute=True):+ category.dynamic_type = Category.DynamicType.NONE+ category.save()++ self.assertEqual(self.calculated_rows(category).count(), 0)++ def test_other_users_weight_does_not_leak(self):+ """+ Weight entries of another user do not end up in this user's BMI+ """+ category = self.enable_bmi()++ admin = User.objects.get(username='admin')+ admin_weight = Category.get_or_create_body_weight(admin, unit='kg')+ with self.captureOnCommitCallbacks(execute=True):+ Measurement.objects.create(+ category=admin_weight,+ date=timezone.now(),+ value=Decimal('90.00'),+ )++ self.assertEqual(self.calculated_rows(category).count(), 0)+++class ApiWriteBlockTestCase(DynamicMeasurementTestCase):+ """+ The entries of a calculated category cannot be written through the API+ """++ def setUp(self):+ super().setUp()+ self.create_weight('81.00')+ self.category = self.enable_bmi()+ self.row = self.calculated_rows(self.category).first()+ self.user_login('test')++ def test_create_is_refused(self):+ """+ POSTing an entry into a calculated category returns a 400+ """+ response = self.client.post(+ reverse('measurement-list'),+ {+ 'category': str(self.category.pk),+ 'date': timezone.now().isoformat(),+ 'value': 42,+ },+ content_type='application/json',+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ def test_update_is_refused(self):+ """+ PATCHing a calculated row returns a 400 also without a category field+ """+ response = self.client.patch(+ reverse('measurement-detail', kwargs={'pk': self.row.pk}),+ {'value': 42},+ content_type='application/json',+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ def test_delete_is_refused(self):+ """+ DELETing a calculated row returns a 403+ """+ response = self.client.delete(+ reverse('measurement-detail', kwargs={'pk': self.row.pk}),+ )+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)++ def test_read_stays_open(self):+ """+ Calculated rows read like any other measurement+ """+ response = self.client.get(+ reverse('measurement-list'),+ {'category': str(self.category.pk)},+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.data['count'], 1)+++class PowerSyncWriteBlockTestCase(DynamicMeasurementTestCase):+ """+ The PowerSync upload path refuses writes to calculated rows as well+ """++ def setUp(self):+ super().setUp()+ self.create_weight('81.00')+ self.category = self.enable_bmi()+ self.row = self.calculated_rows(self.category).first()++ def test_create_is_refused(self):+ """+ A synced insert into a calculated category is rejected+ """+ result = MeasurementHandler().handle_create(+ {+ 'id': 'dddddddd-dddd-dddd-dddd-0000000000ff',+ 'category': str(self.category.pk),+ 'date': timezone.now().isoformat(),+ 'value': '42',+ },+ self.user.pk,+ )+ self.assertIsNotNone(result)+ self.assertIn('error', result)++ def test_delete_is_refused(self):+ """+ A synced delete of a calculated row is rejected+ """+ result = MeasurementHandler().handle_delete({'id': str(self.row.pk)}, self.user.pk)+ self.assertEqual(result['error'], 'Forbidden')+ self.assertTrue(Measurement.objects.filter(pk=self.row.pk).exists())+++class DynamicCategoryApiTestCase(DynamicMeasurementTestCase):+ """+ The category endpoint validates the dynamic fields and lists the types+ """++ def setUp(self):+ super().setUp()+ self.user_login('test')++ def test_params_must_match_schema(self):+ """+ BMI takes no parameters, a payload with any is refused+ """+ response = self.client.post(+ reverse('measurement-category-list'),+ {+ 'name': 'BMI',+ 'unit': '',+ 'dynamic_type': 'BMI',+ 'dynamic_params': {'exercise_id': 1},+ },+ content_type='application/json',+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertIn('dynamic_params', response.data)++ def test_params_cleared_without_type(self):+ """+ Params of a category without a dynamic type are stored empty+ """+ response = self.client.post(+ reverse('measurement-category-list'),+ {+ 'name': 'Plain',+ 'unit': 'cm',+ 'dynamic_params': {'stale': True},+ },+ content_type='application/json',+ )+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ self.assertEqual(response.data['dynamic_params'], {})++ def test_dynamic_types_endpoint(self):+ """+ The endpoint lists the registered types with their params schema+ """+ response = self.client.get(reverse('measurement-category-dynamic-types'))++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ bmi = next(row for row in response.data if row['value'] == 'BMI')+ self.assertEqual(bmi['label'], 'BMI')+ self.assertIn('params_schema', bmi)++ def test_create_via_api_backfills(self):+ """+ A BMI category created through the API is filled on commit+ """+ self.create_weight('81.00')++ with self.captureOnCommitCallbacks(execute=True):+ response = self.client.post(+ reverse('measurement-category-list'),+ {'name': 'BMI', 'unit': '', 'dynamic_type': 'BMI'},+ content_type='application/json',+ )+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)++ rows = self.calculated_rows(Category.objects.get(pk=response.data['id']))+ self.assertEqual(rows.count(), 1)+ self.assertEqual(rows[0].value, Decimal('25.00'))