Self hosted FLOSS fitness/workout, nutrition and weight tracker
Store the entry unit in a new extra_data field on measurements
Roland Geiderf3b6aa1dde3f
diff --git a/wger/core/models/profile.py b/wger/core/models/profile.pyindex cef39553e..f96be2bb8 100644--- a/wger/core/models/profile.py+++ b/wger/core/models/profile.py@@ -393,7 +393,8 @@ class UserProfile(models.Model):more consistent with the other settings (age, height, etc.)"""try:- weight = Measurement.body_weight_for(self.user).latest('date').value+ entry = Measurement.body_weight_for(self.user).latest('date')+ weight = entry.value_in(self.weight_unit)except Measurement.DoesNotExist:weight = 0return weight@@ -533,7 +534,12 @@ class UserProfile(models.Model):name='Body weight',unit=self.weight_unit,)- entry = Measurement(category=category, value=weight, date=timezone.now())+ entry = Measurement(+ category=category,+ value=weight,+ date=timezone.now(),+ extra_data={'unit': self.weight_unit},+ )entry.save()return entrydiff --git a/wger/core/views/user.py b/wger/core/views/user.pyindex 04c2dcd86..f97427d59 100644--- a/wger/core/views/user.py+++ b/wger/core/views/user.py@@ -660,7 +660,11 @@ class UserDetailView(LoginRequiredMixin, WgerMultiplePermissionRequiredMixin, De})context['routine_data'] = out- context['weight_entries'] = Measurement.body_weight_for(self.object).order_by('-date')[:5]+ profile_unit = self.object.userprofile.weight_unit+ context['weight_entries'] = [+ {'date': entry.date, 'value': entry.value_in(profile_unit)}+ for entry in Measurement.body_weight_for(self.object).order_by('-date')[:5]+ ]context['nutrition_plans'] = NutritionPlan.objects.filter(user=self.object).order_by('-creation_date')[:5]diff --git a/wger/measurements/api/serializers.py b/wger/measurements/api/serializers.pyindex 98f6e277a..f480f57e8 100644--- a/wger/measurements/api/serializers.py+++ b/wger/measurements/api/serializers.py@@ -24,6 +24,7 @@ from wger.measurements.models import (Category,Measurement,)+from wger.measurements.models.category import MetricTypeclass CategorySerializer(serializers.ModelSerializer):@@ -100,6 +101,7 @@ class MeasurementSerializer(serializers.ModelSerializer):'notes','source','external_id',+ 'extra_data',)def validate_category(self, category):@@ -111,3 +113,26 @@ class MeasurementSerializer(serializers.ModelSerializer):'Measurements cannot be added to a category with subcategories')return category++ def validate_extra_data(self, extra_data):+ """+ The unit key holds the unit the value was entered in+ """+ if not isinstance(extra_data, dict):+ raise serializers.ValidationError('extra_data must be an object')+ return extra_data++ def validate(self, data):+ """+ Body weight entries only support the weight units of the user profile+ """+ 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')++ if unit is not None and category is not None:+ if category.metric_type == MetricType.BODY_WEIGHT and unit not in ('kg', 'lb'):+ raise serializers.ValidationError(+ {'extra_data': 'Body weight entries only support kg and lb as unit'}+ )+ return datadiff --git a/wger/measurements/migrations/0007_official_categories.py b/wger/measurements/migrations/0007_official_categories.pyindex bf2a5d753..f1a2a6f2b 100644--- a/wger/measurements/migrations/0007_official_categories.py+++ b/wger/measurements/migrations/0007_official_categories.py@@ -10,8 +10,9 @@ def migrate_weight_to_measurements(apps, schema_editor):The WeightEntry uuid is carried over as the Measurement id so thatclients that already synchronise weight entries by uuid keep a stable- identity. The category unit follows the user's preferred weight unit,- since WeightEntry values are stored in that unit.+ identity. WeightEntry values are stored in the user's preferred weight+ unit, so that unit becomes the category unit and is stamped on every+ migrated entry."""WeightEntry = apps.get_model('weight', 'WeightEntry')Category = apps.get_model('measurements', 'Category')@@ -55,6 +56,7 @@ def migrate_weight_to_measurements(apps, schema_editor):date=entry.date,value=entry.weight,source='user',+ extra_data={'unit': unit_by_user.get(entry.user_id, 'kg')},))if len(batch) >= BATCH_SIZE:@@ -84,6 +86,11 @@ class Migration(migrations.Migration):name='is_official',field=models.BooleanField(default=False, verbose_name='Official category'),),+ migrations.AddField(+ model_name='measurement',+ name='extra_data',+ field=models.JSONField(blank=True, default=dict, verbose_name='Extra data'),+ ),migrations.AddConstraint(model_name='category',constraint=models.UniqueConstraint(diff --git a/wger/measurements/models/measurement.py b/wger/measurements/models/measurement.pyindex 504724921..0dd603928 100644--- a/wger/measurements/models/measurement.py+++ b/wger/measurements/models/measurement.py@@ -13,6 +13,9 @@# 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+# Djangofrom django.contrib.auth.models import Userfrom django.core.validators import (@@ -25,6 +28,8 @@ from django.utils import timezone# wgerfrom wger.measurements.models import Categoryfrom wger.measurements.models.category import MetricType+from wger.utils.constants import TWOPLACES+from wger.utils.units import AbstractWeightfrom wger.utils.uuid import uuid7@@ -92,12 +97,39 @@ class Measurement(models.Model):null=True,)+ extra_data = models.JSONField(+ verbose_name='Extra data',+ default=dict,+ blank=True,+ )+ """+ Per-entry metadata. ``unit`` holds the unit the value was entered in+ (falls back to the category unit when absent), external syncs store+ their provenance (source unit, original value, device) here as well.+ """+def get_owner_object(self):"""Returns the object that has owner information"""return self.category+ @property+ def unit(self) -> str:+ """+ Returns the unit the value is stored in+ """+ return self.extra_data.get('unit') or self.category.unit++ def value_in(self, unit: str) -> Decimal:+ """+ Returns the value converted to the given weight unit ('kg' or 'lb')+ """+ if self.unit == unit:+ return self.value+ weight = AbstractWeight(self.value, self.unit)+ return (weight.kg if unit == 'kg' else weight.lb).quantize(TWOPLACES)+@classmethoddef body_weight_for(cls, user: User) -> models.QuerySet:"""diff --git a/wger/measurements/tests/test_measurements.py b/wger/measurements/tests/test_measurements.pyindex abb551878..33ca7a928 100644--- a/wger/measurements/tests/test_measurements.py+++ b/wger/measurements/tests/test_measurements.py@@ -13,6 +13,9 @@# 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+# Djangofrom django.db import (IntegrityError,@@ -104,3 +107,114 @@ class MeasurementLeafOnlyTestCase(WgerTestCase):self.assertEqual(response.status_code, 400)self.assertIn('category', response.data)+++class MeasurementUnitTestCase(WgerTestCase):+ """+ Per-entry units in extra_data+ """++ # kg entry in the official body weight category of user 'test'+ entry_pk = '11111111-1111-1111-1111-000000000001' # 77 kg++ def test_unit_falls_back_to_category(self):+ """+ Test that entries without a stamped unit use the category unit+ """+ entry = Measurement.objects.get(pk=self.entry_pk)++ self.assertEqual(entry.extra_data, {})+ self.assertEqual(entry.unit, 'kg')++ def test_unit_from_extra_data(self):+ """+ Test that a stamped unit wins over the category unit+ """+ entry = Measurement.objects.get(pk=self.entry_pk)+ entry.extra_data = {'unit': 'lb'}++ self.assertEqual(entry.unit, 'lb')++ def test_value_in_same_unit(self):+ """+ Test that no conversion happens for the entry's own unit+ """+ entry = Measurement.objects.get(pk=self.entry_pk)++ self.assertEqual(entry.value_in('kg'), Decimal('77.00'))++ def test_value_in_converts(self):+ """+ Test the conversion between kg and lb+ """+ entry = Measurement.objects.get(pk=self.entry_pk)++ self.assertEqual(entry.value_in('lb'), Decimal('169.76'))++ entry.extra_data = {'unit': 'lb'}+ self.assertEqual(entry.value_in('kg'), Decimal('34.93'))+++class MeasurementExtraDataApiTestCase(WgerTestCase):+ """+ extra_data over the measurement API+ """++ def setUp(self):+ super().setUp()+ self.user_login('test')+ self.url = reverse('measurement-list')++ def test_extra_data_roundtrip(self):+ """+ Test that extra_data can be set and read over the API+ """+ response = self.client.post(+ self.url,+ {+ 'category': 'cccccccc-cccc-cccc-cccc-0000000000b0',+ 'date': '2023-05-01T12:00:00Z',+ 'value': 180,+ 'extra_data': {'unit': 'lb'},+ },+ content_type='application/json',+ )++ self.assertEqual(response.status_code, 201)+ self.assertEqual(response.data['extra_data'], {'unit': 'lb'})+ self.assertEqual(Measurement.objects.get(pk=response.data['id']).unit, 'lb')++ def test_invalid_body_weight_unit(self):+ """+ Test that body weight entries only accept kg and lb as unit+ """+ response = self.client.post(+ self.url,+ {+ 'category': 'cccccccc-cccc-cccc-cccc-0000000000b0',+ 'date': '2023-05-01T12:00:00Z',+ 'value': 180,+ 'extra_data': {'unit': 'stone'},+ },+ 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+ """+ response = 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',+ )++ self.assertEqual(response.status_code, 201)diff --git a/wger/nutrition/models/plan.py b/wger/nutrition/models/plan.pyindex 12bc97ced..d994de2ff 100644--- a/wger/nutrition/models/plan.py+++ b/wger/nutrition/models/plan.py@@ -166,11 +166,10 @@ class NutritionPlan(models.Model):# Per body weightweight_entry = self.get_closest_weight_entry()if weight_entry and weight_entry.value:- result['per_kg']['protein'] = nutritional_values.protein / weight_entry.value- result['per_kg']['carbohydrates'] = (- nutritional_values.carbohydrates / weight_entry.value- )- result['per_kg']['fat'] = nutritional_values.fat / weight_entry.value+ weight_kg = weight_entry.value_in('kg')+ result['per_kg']['protein'] = nutritional_values.protein / weight_kg+ result['per_kg']['carbohydrates'] = nutritional_values.carbohydrates / weight_kg+ result['per_kg']['fat'] = nutritional_values.fat / weight_kgnutritional_representation = resultcache.set(cache_mapper.get_nutrition_cache_by_key(self.pk), nutritional_representation)diff --git a/wger/nutrition/tests/test_nutritional_calculations.py b/wger/nutrition/tests/test_nutritional_calculations.pyindex 1c83afde8..b110bbbc5 100644--- a/wger/nutrition/tests/test_nutritional_calculations.py+++ b/wger/nutrition/tests/test_nutritional_calculations.py@@ -19,9 +19,11 @@ from decimal import Decimal# Djangofrom django.urls import reverse+from django.utils import timezone# wgerfrom wger.core.tests.base_testcase import WgerTestCase+from wger.measurements.models import Measurementfrom wger.nutrition import models@@ -249,3 +251,38 @@ class NutritionalValuesApiTestCase(WgerTestCase):)self.assertEqual(response.status_code, 404)+++class PerBodyWeightCalculationTestCase(WgerTestCase):+ """+ Tests the per-body-weight values with weight entries in imperial units+ """++ def test_per_kg_converts_units(self):+ """+ Test that the per-kg values convert lb entries to kg+ """+ plan = models.NutritionPlan(user_id=2)+ plan.save()++ meal = models.Meal(order=1, plan=plan)+ meal.save()++ item = models.MealItem(meal=meal, ingredient_id=1, weight_unit_id=None, amount=100, order=1)+ item.save()++ Measurement.objects.create(+ category_id='cccccccc-cccc-cccc-cccc-0000000000b0',+ date=timezone.now(),+ value=180,+ extra_data={'unit': 'lb'},+ )++ values = plan.get_nutritional_values()++ # 180 lb are 81.65 kg+ self.assertAlmostEqual(+ float(values['per_kg']['protein']),+ float(values['total'].protein / Decimal('81.65')),+ 2,+ )diff --git a/wger/weight/api/serializers.py b/wger/weight/api/serializers.pyindex 14ab6c231..f00299a36 100644--- a/wger/weight/api/serializers.py+++ b/wger/weight/api/serializers.py@@ -47,3 +47,13 @@ class WeightEntrySerializer(serializers.ModelSerializer):'weight','user',)++ def to_representation(self, instance):+ """+ Weight values are returned in the user's preferred weight unit,+ entries themselves may be stored in other units+ """+ data = super().to_representation(instance)+ unit = self.context['request'].user.userprofile.weight_unit+ data['weight'] = self.fields['weight'].to_representation(instance.value_in(unit))+ return datadiff --git a/wger/weight/api/views.py b/wger/weight/api/views.pyindex 144afb8b2..de87f92c1 100644--- a/wger/weight/api/views.py+++ b/wger/weight/api/views.py@@ -52,12 +52,25 @@ class WeightEntryViewSet(viewsets.ModelViewSet):def perform_create(self, serializer):"""- Route the new entry into the user's official body-weight category+ Route the new entry into the user's official body-weight category.+ The value is interpreted in the user's preferred weight unit."""+ profile = self.request.user.userprofilecategory = Category.get_or_create_official(self.request.user,MetricType.BODY_WEIGHT,name='Body weight',- unit=self.request.user.userprofile.weight_unit,+ unit=profile.weight_unit,)- serializer.save(category=category)+ serializer.save(category=category, extra_data={'unit': profile.weight_unit})++ def perform_update(self, serializer):+ """+ A new value is interpreted in the user's current weight unit, updates+ without a value keep the stored unit+ """+ if 'value' in serializer.validated_data:+ unit = self.request.user.userprofile.weight_unit+ serializer.save(extra_data={'unit': unit})+ else:+ serializer.save()diff --git a/wger/weight/helpers.py b/wger/weight/helpers.pyindex 9f7c3d694..14ed178ba 100644--- a/wger/weight/helpers.py+++ b/wger/weight/helpers.py@@ -80,13 +80,21 @@ def parse_weight_csv(request, cleaned_data):# Create the valid weight entriesif distinct_weight_entries:+ profile_unit = request.user.userprofile.weight_unitcategory = Category.get_or_create_official(request.user,MetricType.BODY_WEIGHT,name='Body weight',- unit=request.user.userprofile.weight_unit,+ unit=profile_unit,)for date, weight in distinct_weight_entries:- weight_list.append(Measurement(date=date, value=weight, category=category))+ weight_list.append(+ Measurement(+ date=date,+ value=weight,+ category=category,+ extra_data={'unit': profile_unit},+ )+ )return weight_list, error_listdiff --git a/wger/weight/tests/test_entry.py b/wger/weight/tests/test_entry.pyindex 64a5e19d0..0ac25ce35 100644--- a/wger/weight/tests/test_entry.py+++ b/wger/weight/tests/test_entry.py@@ -12,6 +12,9 @@## You should have received a copy of the GNU Affero General Public License+# Standard Library+from decimal import Decimal+# Djangofrom django.contrib.auth.models import Userfrom django.utils import timezone@@ -98,3 +101,74 @@ class WeightEntryOfficialCategoryTestCase(api_base_test.ApiBaseTestCase, WgerTesCategory.objects.filter(user__username='test').count(),count_before,)+++class WeightEntryUnitTestCase(api_base_test.ApiBaseTestCase, WgerTestCase):+ """+ Per-entry units on the legacy weight endpoint+ """++ url = '/api/v2/weightentry/'+ entry_pk = '11111111-1111-1111-1111-000000000001' # 77, stored in kg++ def test_get_converts_to_profile_unit(self):+ """+ Test that entries in other units are converted to the profile unit+ """+ entry = Measurement.objects.get(pk=self.entry_pk)+ entry.extra_data = {'unit': 'lb'}+ entry.save()++ self.authenticate('test')+ response = self.client.get(f'{self.url}{self.entry_pk}/')++ self.assertEqual(response.status_code, 200)+ # 77 lb converted to the kg profile of user 'test'+ self.assertEqual(response.data['weight'], '34.93')++ def test_post_stamps_profile_unit(self):+ """+ Test that new entries are stamped with the user's weight unit+ """+ user = User.objects.get(username='test')+ user.userprofile.weight_unit = 'lb'+ user.userprofile.save()++ self.authenticate('test')+ response = self.client.post(self.url, {'weight': 180, 'date': timezone.now()})++ self.assertEqual(response.status_code, 201)+ entry = Measurement.objects.get(pk=response.data['id'])+ self.assertEqual(entry.value, Decimal('180.00'))+ self.assertEqual(entry.extra_data, {'unit': 'lb'})++ def test_patch_weight_restamps_unit(self):+ """+ Test that updating the weight re-stamps the current profile unit+ """+ user = User.objects.get(username='test')+ user.userprofile.weight_unit = 'lb'+ user.userprofile.save()++ self.authenticate('test')+ response = self.client.patch(f'{self.url}{self.entry_pk}/', {'weight': 170})++ self.assertEqual(response.status_code, 200)+ entry = Measurement.objects.get(pk=self.entry_pk)+ self.assertEqual(entry.value, Decimal('170.00'))+ self.assertEqual(entry.extra_data, {'unit': 'lb'})++ def test_patch_date_keeps_unit(self):+ """+ Test that updates without a weight keep the stored unit+ """+ entry = Measurement.objects.get(pk=self.entry_pk)+ entry.extra_data = {'unit': 'lb'}+ entry.save()++ self.authenticate('test')+ response = self.client.patch(f'{self.url}{self.entry_pk}/', {'date': timezone.now()})++ self.assertEqual(response.status_code, 200)+ entry.refresh_from_db()+ self.assertEqual(entry.extra_data, {'unit': 'lb'})diff --git a/wger/weight/views.py b/wger/weight/views.pyindex 540f25af5..86ea50443 100644--- a/wger/weight/views.py+++ b/wger/weight/views.py@@ -51,10 +51,11 @@ def export_csv(request):writer = csv.writer(response)weights = Measurement.body_weight_for(request.user).order_by('date')+ profile_unit = request.user.userprofile.weight_unitwriter.writerow([_('Date'), _('Weight')])for entry in weights:- writer.writerow([entry.date, entry.value])+ writer.writerow([entry.date, entry.value_in(profile_unit)])# Send the data to the browserresponse['Content-Disposition'] = 'attachment; filename=Weightdata.csv'