Self hosted FLOSS fitness/workout, nutrition and weight tracker
Add the aggregate reads behind the measurement charts
Roland Geider739fdbd706a6
diff --git a/wger/measurements/api/aggregates.py b/wger/measurements/api/aggregates.pynew file mode 100644index 000000000..13afe253f--- /dev/null+++ b/wger/measurements/api/aggregates.py@@ -0,0 +1,216 @@+# 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/>.++"""+Condensing measurements into what a chart draws.++A chart shows a few hundred points and a watch-fed metric holds tens of+thousands a year, so the condensing belongs in the query rather than in the+client. The flutter app does the same thing against its local SQLite; this is+the same ladder and the same bucket semantics for the clients without one.+"""++# Standard Library+from zoneinfo import (+ ZoneInfo,+ ZoneInfoNotFoundError,+)++# Django+from django.db.models import (+ Count,+ DecimalField,+ F,+ Max,+ Min,+ Sum,+)+from django.db.models.functions import (+ Cast,+ Coalesce,+ TruncDay,+ TruncHour,+ TruncMonth,+ TruncWeek,+)+++#: Points a chart is condensed to. Mirrors `measurementChartMaxPoints` in the+#: flutter app, and both clients may pass their own.+DEFAULT_MAX_POINTS = 200++#: Calendar units entries are condensed into, finest first. Not equal slices of+#: the span: these metrics have a daily rhythm, so slices that do not line up+#: with a day each catch a different phase of it and the chart oscillates at+#: the slice frequency.+BUCKET_UNITS = {+ 'hour': TruncHour,+ 'day': TruncDay,+ 'week': TruncWeek,+ 'month': TruncMonth,+}+++class InvalidBucket(ValueError):+ """The client asked for a unit or a timezone that does not exist"""+++def parse_timezone(name: str | None):+ """+ The zone the calendar buckets are cut in, the server's own when the client+ names none.++ Buckets follow the user's calendar, not UTC: a reading half an hour after+ midnight belongs to the day the user had it.+ """+ if not name:+ return None++ try:+ return ZoneInfo(name)+ except (ZoneInfoNotFoundError, ValueError):+ raise InvalidBucket(f'Unknown timezone: {name}')+++def _bounds_expression(key: str, aggregate):+ """+ The stored bound of a daily aggregate, falling back to the value itself.++ An entry that already summarises a day (heart rate) carries the range it+ stands for in `extra_data`, and contributes that rather than its mean, so+ condensing an aggregate keeps the true extremes.+ """+ return aggregate(+ Coalesce(+ Cast(F(f'extra_data__{key}'), DecimalField(max_digits=8, decimal_places=2)),+ F('value'),+ )+ )+++def ladder_unit(queryset, tz, max_points: int) -> str:+ """+ The finest unit that keeps the series under [max_points], counting what+ each one would produce in a single pass.++ Mirrors the ladder the flutter repository walks. There is no unit below+ the hour: an entry-level read is the plain list endpoint.+ """+ counts = queryset.aggregate(+ **{+ name: Count(trunc('date', tzinfo=tz), distinct=True)+ for name, trunc in BUCKET_UNITS.items()+ }+ )++ for name in BUCKET_UNITS:+ if counts[name] <= max_points:+ return name+ return 'month'+++def bucket_rows(queryset, unit: str, tz, max_points: int = DEFAULT_MAX_POINTS) -> list[dict]:+ """+ One row per category, calendar bucket and stored unit, oldest first.++ Grouped by the unit the values were entered in as well, because a mean over+ kg and lb values is a number in neither: the client converts each row+ through its own helper and merges them afterwards (see `Measurement.unit`).+ """+ if unit == 'auto':+ unit = ladder_unit(queryset, tz, max_points)+ if unit not in BUCKET_UNITS:+ raise InvalidBucket(f'Unknown bucket: {unit}')++ rows = (+ queryset.annotate(+ start=BUCKET_UNITS[unit]('date', tzinfo=tz),+ stored_unit=F('extra_data__unit'),+ )+ .values('category', 'start', 'stored_unit')+ .annotate(+ count=Count('id'),+ total=Sum('value'),+ low=_bounds_expression('min', Min),+ high=_bounds_expression('max', Max),+ )+ .order_by('start')+ )++ return [+ {+ 'category': row['category'],+ 'start': row['start'],+ 'unit': row['stored_unit'],+ 'count': row['count'],+ 'sum': row['total'],+ 'min': row['low'],+ 'max': row['high'],+ }+ for row in rows+ ]+++def value_count_rows(queryset, tz, summed_per_day: bool = False) -> list[dict]:+ """+ How often each value occurred, for the histogram.++ Not bucketed by time but by value, which is the granularity a histogram+ bins at anyway: a year of heart rate is tens of thousands of readings over+ some two hundred distinct bpm. Counting instead of binning keeps the+ conversion of a mixed-unit category exact, since the values still go+ through the client's helper. [summed_per_day] counts daily totals rather+ than single readings, for the metrics whose samples mean nothing alone.+ """+ if summed_per_day:+ daily = (+ queryset.annotate(day=TruncDay('date', tzinfo=tz), stored_unit=F('extra_data__unit'))+ .values('category', 'day', 'stored_unit')+ .annotate(value=Sum('value'), newest=Max('date'))+ )+ counted: dict[tuple, dict] = {}+ for row in daily:+ key = (row['category'], row['stored_unit'], row['value'])+ entry = counted.setdefault(+ key,+ {+ 'category': row['category'],+ 'unit': row['stored_unit'],+ 'value': row['value'],+ 'count': 0,+ 'newest': row['newest'],+ },+ )+ entry['count'] += 1+ entry['newest'] = max(entry['newest'], row['newest'])+ return sorted(counted.values(), key=lambda r: (str(r['category']), r['value']))++ rows = (+ queryset.annotate(stored_unit=F('extra_data__unit'))+ .values('category', 'stored_unit', 'value')+ .annotate(count=Count('id'), newest=Max('date'))+ .order_by('value')+ )++ return [+ {+ 'category': row['category'],+ 'unit': row['stored_unit'],+ 'value': row['value'],+ 'count': row['count'],+ 'newest': row['newest'],+ }+ for row in rows+ ]diff --git a/wger/measurements/api/serializers.py b/wger/measurements/api/serializers.pyindex bf454ea2b..dac06486d 100644--- a/wger/measurements/api/serializers.py+++ b/wger/measurements/api/serializers.py@@ -315,3 +315,32 @@ class MeasurementSerializer(serializers.ModelSerializer):raise serializers.ValidationError({'value': f'Value must be between {limits.min} and {limits.max}'})+++class BucketSerializer(serializers.Serializer):+ """+ One calendar bucket of a category's entries, see `api.aggregates`.++ Read-only: buckets are derived, there is nothing to write back.+ """++ category = serializers.UUIDField(read_only=True)+ start = serializers.DateTimeField(read_only=True)+ unit = serializers.CharField(read_only=True, allow_null=True)+ count = serializers.IntegerField(read_only=True)+ sum = serializers.DecimalField(read_only=True, max_digits=10, decimal_places=2)+ min = serializers.DecimalField(read_only=True, max_digits=10, decimal_places=2)+ max = serializers.DecimalField(read_only=True, max_digits=10, decimal_places=2)+++class ValueCountSerializer(serializers.Serializer):+ """+ How often one value occurred, and when it was measured last. Read-only for+ the same reason as `BucketSerializer`.+ """++ category = serializers.UUIDField(read_only=True)+ value = serializers.DecimalField(read_only=True, max_digits=8, decimal_places=2)+ unit = serializers.CharField(read_only=True, allow_null=True)+ count = serializers.IntegerField(read_only=True)+ newest = serializers.DateTimeField(read_only=True)diff --git a/wger/measurements/api/views.py b/wger/measurements/api/views.pyindex bace2c50a..2d081f1cf 100644--- a/wger/measurements/api/views.py+++ b/wger/measurements/api/views.py@@ -23,13 +23,24 @@ from django.contrib.auth.models import Userfrom django.core.exceptions import PermissionDenied# Third Party+from rest_framework.decorators import actionfrom rest_framework.permissions import IsAuthenticated+from rest_framework.response import Response# wger+from wger.measurements.api.aggregates import (+ DEFAULT_MAX_POINTS,+ InvalidBucket,+ bucket_rows,+ parse_timezone,+ value_count_rows,+)from wger.measurements.api.filtersets import MeasurementEntryFilterSetfrom wger.measurements.api.serializers import (+ BucketSerializer,CategorySerializer,MeasurementSerializer,+ ValueCountSerializer,)from wger.measurements.models import (Category,@@ -112,3 +123,58 @@ class MeasurementViewSet(WgerOwnerObjectModelViewSet):return Measurement.objects.none()return Measurement.objects.filter(category__user=self.request.user)++ def _read_max_points(self) -> int:+ try:+ return max(1, int(self.request.query_params.get('max_points', DEFAULT_MAX_POINTS)))+ except ValueError:+ raise InvalidBucket('max_points must be a number')++ @action(detail=False, methods=['get'], serializer_class=BucketSerializer)+ def aggregate(self, request):+ """+ The entries condensed into what a chart draws: one row per category,+ calendar bucket and stored unit.++ Takes the filters of the list endpoint (`category`, `category__in`,+ `date__gte`, ...) plus `bucket` (`auto`, the default, or one of hour,+ day, week, month), `tz` and `max_points`. A separate route rather than+ a mode of the list, because a bucket is not a measurement: it has no+ id, and nothing that reads measurements should have to tell them apart.+ """+ try:+ rows = bucket_rows(+ self.filter_queryset(self.get_queryset()),+ request.query_params.get('bucket', 'auto'),+ parse_timezone(request.query_params.get('tz')),+ self._read_max_points(),+ )+ except InvalidBucket as e:+ return Response({'detail': str(e)}, status=400)++ return Response(BucketSerializer(rows, many=True).data)++ @action(+ detail=False,+ url_path='value-counts',+ methods=['get'],+ serializer_class=ValueCountSerializer,+ )+ def value_counts(self, request):+ """+ How often each value occurred, which is what a histogram bins.++ Takes the same filters, plus `tz` and `summed_per_day` for the metrics+ whose samples mean nothing on their own (steps, sleep), which are+ counted as daily totals instead.+ """+ try:+ rows = value_count_rows(+ self.filter_queryset(self.get_queryset()),+ parse_timezone(request.query_params.get('tz')),+ request.query_params.get('summed_per_day') in ('1', 'true', 'True'),+ )+ except InvalidBucket as e:+ return Response({'detail': str(e)}, status=400)++ return Response(ValueCountSerializer(rows, many=True).data)diff --git a/wger/measurements/management/commands/dummy-generator-health-measurements.py b/wger/measurements/management/commands/dummy-generator-health-measurements.pyindex e78cea57f..9f7c937fa 100644--- a/wger/measurements/management/commands/dummy-generator-health-measurements.py+++ b/wger/measurements/management/commands/dummy-generator-health-measurements.py@@ -85,8 +85,8 @@ class Command(BaseCommand):help = ('Dummy generator for measurements as the Apple Health / Health Connect importer ''writes them (source, external_id and provenance in extra_data). By default only '- 'a handful of entries per metric, --realistic generates the data volume the '- 'platforms actually deliver.'+ 'a handful of entries per metric, --realistic the amount someone syncing every '+ 'day accumulates.')def add_arguments(self, parser):@@ -102,9 +102,18 @@ class Command(BaseCommand):'--realistic',action='store_true',dest='realistic',- help='Generate the raw sample volume the platforms deliver (heart rate samples, '- 'hourly step/distance/energy buckets, sleep segments) instead of the daily '- 'aggregates the importer writes today',+ help='Generate the entries someone syncing every day accumulates (a weigh-in '+ 'every morning, blood pressure twice a day) instead of a handful per metric',+ )+ parser.add_argument(+ '--raw-samples',+ action='store_true',+ dest='raw_samples',+ help='Generate the raw sample volume the platforms deliver (a heart rate reading '+ 'every few minutes, hourly step/distance/energy buckets, one entry per sleep '+ 'segment) instead of the daily aggregates. This is for load tests: the importer '+ 'aggregates these metrics and never writes this volume, so a client reading it '+ 'sees an amount of data it cannot produce itself. Implies --realistic',)parser.add_argument('--metrics',@@ -144,7 +153,9 @@ class Command(BaseCommand):metrics = self.parse_metrics(options['metrics'])self.days = days- self.realistic = options['realistic']+ self.raw_samples = options['raw_samples']+ # The raw volume is only meaningful on top of the daily entries+ self.realistic = options['realistic'] or self.raw_samplesself.source = MeasurementSource(options['source']).valueself.seed = options['seed']self.clamped = 0@@ -159,10 +170,22 @@ class Command(BaseCommand):[User.objects.get(pk=options['user_id'])] if options['user_id'] else User.objects.all())- volume = 'realistic' if self.realistic else 'sparse'+ if self.raw_samples:+ volume = 'raw sample'+ elif self.realistic:+ volume = 'realistic'+ else:+ volume = 'sparse'self.stdout.write(f'** Generating {volume} health data ({self.source}) for the last {days} days')+ if self.raw_samples:+ self.stdout.write(+ self.style.WARNING(+ ' --raw-samples writes the platform volume, not what the importer '+ 'stores: expect a few hundred entries per day and metric'+ )+ )for user in users:self.stdout.write(f'- processing user {user.username}')@@ -500,7 +523,7 @@ class Command(BaseCommand):day = self.day_start(offset)samples = self.heart_rate_samples(rng, day, rng.uniform(48, 64))- if self.realistic:+ if self.raw_samples:entries += [self.entry(category,@@ -591,15 +614,16 @@ class Command(BaseCommand):"""Generates a cumulative metric (steps, distance, energy).- Sparse mode imports the daily total the platform aggregates itself,- realistic mode the raw interval records, one per active hour.+ Writes the daily total the platform aggregates itself, which is what+ the importer stores; --raw-samples writes the raw interval records+ instead, one per active hour."""entries = []for offset in self.day_range():day = self.day_start(offset)total = rng.uniform(daily_min, daily_max) * (1.25 if day.weekday() >= 5 else 1)- if not self.realistic:+ if not self.raw_samples:entries.append(self.entry(category,@@ -676,7 +700,7 @@ class Command(BaseCommand):if not of_stage:continue- if self.realistic:+ if self.raw_samples:entries += [self.entry(category,diff --git a/wger/measurements/tests/test_aggregates.py b/wger/measurements/tests/test_aggregates.pynew file mode 100644index 000000000..091054a55--- /dev/null+++ b/wger/measurements/tests/test_aggregates.py@@ -0,0 +1,192 @@+# 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.urls import reverse+from django.utils import timezone++# wger+from wger.core.tests.base_testcase import WgerTestCase+from wger.measurements.models import (+ Category,+ Measurement,+)+++class AggregateApiTestCase(WgerTestCase):+ """+ The condensed reads behind the charts+ """++ category_id = 'cccccccc-cccc-cccc-cccc-000000000002'++ def setUp(self):+ super().setUp()+ self.user_login('test')+ self.category = Category.objects.get(pk=self.category_id)+ Measurement.objects.filter(category=self.category).delete()++ def add(self, date, value, unit=None, extra=None):+ data = dict(extra or {})+ if unit:+ data['unit'] = unit+ return Measurement.objects.create(+ category=self.category,+ date=date,+ value=Decimal(str(value)),+ notes='',+ extra_data=data,+ )++ def aggregate(self, **params):+ response = self.client.get(+ reverse('measurement-aggregate'),+ {'category': self.category_id, **params},+ )+ self.assertEqual(response.status_code, 200)+ return response.data++ def value_counts(self, **params):+ response = self.client.get(+ reverse('measurement-value-counts'),+ {'category': self.category_id, **params},+ )+ self.assertEqual(response.status_code, 200)+ return response.data++ def test_a_day_bucket_holds_the_readings_of_that_day(self):+ day = timezone.make_aware(datetime.datetime(2026, 5, 4, 8))+ self.add(day, 60)+ self.add(day + datetime.timedelta(hours=12), 80)++ rows = self.aggregate(bucket='day', tz='UTC')++ self.assertEqual(len(rows), 1)+ self.assertEqual(rows[0]['count'], 2)+ self.assertEqual(rows[0]['sum'], '140.00')+ self.assertEqual(rows[0]['min'], '60.00')+ self.assertEqual(rows[0]['max'], '80.00')++ def test_the_ladder_picks_the_finest_unit_that_fits(self):+ # Two readings a day over four days: the hour level is eight points,+ # the day level four, so the day is the first one under the limit+ for day in range(4, 8):+ base = timezone.make_aware(datetime.datetime(2026, 5, day, 8))+ self.add(base, 60)+ self.add(base + datetime.timedelta(hours=12), 80)++ rows = self.aggregate(max_points=5, tz='UTC')++ self.assertEqual(len(rows), 4)+ self.assertEqual(rows[0]['count'], 2)++ def test_a_fixed_bucket_ignores_the_point_limit(self):+ for day in range(1, 15):+ self.add(timezone.make_aware(datetime.datetime(2026, 5, day, 8)), 60)++ self.assertEqual(len(self.aggregate(bucket='day', max_points=2, tz='UTC')), 14)++ def test_buckets_are_cut_in_the_given_zone(self):+ # 23:30 UTC is the next day in Berlin, so the two readings share a day+ # there and not in UTC+ self.add(datetime.datetime(2026, 5, 4, 23, 30, tzinfo=datetime.UTC), 60)+ self.add(datetime.datetime(2026, 5, 5, 6, 0, tzinfo=datetime.UTC), 80)++ self.assertEqual(len(self.aggregate(bucket='day', tz='UTC')), 2)+ self.assertEqual(len(self.aggregate(bucket='day', tz='Europe/Berlin')), 1)++ def test_mixed_units_are_kept_apart(self):+ # A mean over kg and lb values is a number in neither, so the client+ # converts each row before merging them+ day = timezone.make_aware(datetime.datetime(2026, 5, 4, 8))+ self.add(day, 80, unit='kg')+ self.add(day + datetime.timedelta(hours=1), 180, unit='lb')++ rows = self.aggregate(bucket='day', tz='UTC')++ self.assertEqual(len(rows), 2)+ self.assertEqual({row['unit'] for row in rows}, {'kg', 'lb'})++ def test_a_stored_aggregate_contributes_its_bounds(self):+ # What the health sync writes for heart rate: one row a day holding+ # the day's average with the range it summarises+ self.add(+ timezone.make_aware(datetime.datetime(2026, 5, 4, 8)),+ 70,+ extra={'min': 48, 'max': 165},+ )++ rows = self.aggregate(bucket='day', tz='UTC')++ self.assertEqual(rows[0]['min'], '48.00')+ self.assertEqual(rows[0]['max'], '165.00')++ def test_the_date_filters_of_the_list_apply(self):+ self.add(timezone.make_aware(datetime.datetime(2026, 1, 1, 8)), 60)+ self.add(timezone.make_aware(datetime.datetime(2026, 5, 4, 8)), 80)++ rows = self.aggregate(bucket='day', tz='UTC', date__gte='2026-03-01')++ self.assertEqual(len(rows), 1)+ self.assertEqual(rows[0]['sum'], '80.00')++ def test_an_unknown_bucket_or_zone_is_refused(self):+ for params in ({'bucket': 'fortnight'}, {'tz': 'Middle/Earth'}):+ response = self.client.get(+ reverse('measurement-aggregate'),+ {'category': self.category_id, **params},+ )+ self.assertEqual(response.status_code, 400)++ def test_another_users_category_is_not_aggregated(self):+ self.user_login('admin')++ self.assertEqual(self.aggregate(bucket='day'), [])++ def test_value_counts_count_how_often_a_value_occurred(self):+ # A year of readings comes back as the distinct values it covers+ for hour, value in ((8, 60), (9, 60), (10, 75)):+ self.add(timezone.make_aware(datetime.datetime(2026, 5, 4, hour)), value)++ rows = self.value_counts()++ self.assertEqual(+ [(row['value'], row['count']) for row in rows],+ [('60.00', 2), ('75.00', 1)],+ )++ def test_value_counts_carry_the_newest_date_of_a_value(self):+ self.add(datetime.datetime(2026, 5, 4, 8, tzinfo=datetime.UTC), 60)+ self.add(datetime.datetime(2026, 5, 6, 8, tzinfo=datetime.UTC), 60)++ rows = self.value_counts()++ self.assertEqual(len(rows), 1)+ self.assertTrue(rows[0]['newest'].startswith('2026-05-06'))++ def test_value_counts_of_a_summed_metric_are_daily_totals(self):+ for day, hour, value in ((4, 8, 3000), (4, 20, 2000), (5, 8, 5000)):+ self.add(timezone.make_aware(datetime.datetime(2026, 5, day, hour)), value)++ rows = self.value_counts(summed_per_day='true', tz='UTC')++ # Both days total 5000, so the histogram sees one value twice+ self.assertEqual(len(rows), 1)+ self.assertEqual(rows[0]['value'], '5000.00')+ self.assertEqual(rows[0]['count'], 2)diff --git a/wger/measurements/tests/test_generator.py b/wger/measurements/tests/test_generator.pyindex 96925cb65..fe66da354 100644--- a/wger/measurements/tests/test_generator.py+++ b/wger/measurements/tests/test_generator.py@@ -81,6 +81,49 @@ class MeasurementGeneratorTestCase(WgerTestCase):self.assertFalse(group.measurement_set.exists())self.assertTrue(all(c.measurement_set.exists() for c in components))+ def test_generator_health_heart_rate_is_a_daily_aggregate(self):+ """+ The default and --realistic write what the importer stores, one entry+ per day, rather than the raw samples the platform delivers+ """+ for options in ([], ['--realistic']):+ with self.subTest(options=options):+ Measurement.objects.all().delete()++ call_command(+ 'dummy-generator-health-measurements',+ '--days',+ 5,+ '--metrics',+ 'heart_rate',+ *options,+ )++ category = Category.objects.get(user_id=1, metric_type=MetricType.HEART_RATE)+ self.assertEqual(category.measurement_set.count(), 6)++ def test_generator_health_raw_samples(self):+ """+ --raw-samples writes the platform volume, which is what the load tests+ need and what the importer never stores+ """+ # Arrange+ Measurement.objects.all().delete()++ # Act+ call_command(+ 'dummy-generator-health-measurements',+ '--days',+ 5,+ '--metrics',+ 'heart_rate',+ '--raw-samples',+ )++ # Assert+ category = Category.objects.get(user_id=1, metric_type=MetricType.HEART_RATE)+ self.assertGreater(category.measurement_set.count(), 100)+class BodyWeightGeneratorTestCase(WgerTestCase):def test_generator(self):