Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Fix macro percentages for users with imperial units

Roland Geider8a026b8bfb93
diff --git a/wger/nutrition/models/plan.py b/wger/nutrition/models/plan.py
index 9c20524f4..a0df5c26b 100644
--- a/wger/nutrition/models/plan.py
+++ b/wger/nutrition/models/plan.py
@@ -134,7 +134,6 @@ class NutritionPlan(models.Model):
if not nutritional_representation:
nutritional_values = NutritionalValues()
use_metric = self.user.userprofile.use_metric
- unit = 'kg' if use_metric else 'lb'
result = {
'total': NutritionalValues(),
'percent': {'protein': 0, 'carbohydrates': 0, 'fat': 0},
@@ -148,19 +147,20 @@ class NutritionPlan(models.Model):
energy = nutritional_values.energy
- # In percent
+ # In percent. The macros are always in grams, regardless of the
+ # unit the user prefers, so the energy factor per gram applies.
if energy:
result['percent']['protein'] = (
- nutritional_values.protein * ENERGY_FACTOR['protein'][unit] / energy * 100
+ nutritional_values.protein * ENERGY_FACTOR['protein']['kg'] / energy * 100
)
result['percent']['carbohydrates'] = (
nutritional_values.carbohydrates
- * ENERGY_FACTOR['carbohydrates'][unit]
+ * ENERGY_FACTOR['carbohydrates']['kg']
/ energy
* 100
)
result['percent']['fat'] = (
- nutritional_values.fat * ENERGY_FACTOR['fat'][unit] / energy * 100
+ nutritional_values.fat * ENERGY_FACTOR['fat']['kg'] / energy * 100
)
# Per body weight
diff --git a/wger/nutrition/tests/test_nutritional_calculations.py b/wger/nutrition/tests/test_nutritional_calculations.py
index 1c83afde8..28646b48b 100644
--- a/wger/nutrition/tests/test_nutritional_calculations.py
+++ b/wger/nutrition/tests/test_nutritional_calculations.py
@@ -18,6 +18,7 @@ import logging
from decimal import Decimal
# Django
+from django.core.cache import cache
from django.urls import reverse
# wger
@@ -235,6 +236,24 @@ class NutritionalValuesCalculationsTestCase(WgerTestCase):
self.assertAlmostEqual(values['per_kg']['fat'], Decimal(1.51), 2)
self.assertAlmostEqual(values['per_kg']['protein'], Decimal(4.33), 2)
+ def test_calculations_user_imperial(self):
+ """
+ Tests that the macro percentages don't depend on the user's weight unit
+ """
+ self.user_login('test')
+ plan = models.NutritionPlan.objects.get(pk='11111111-1111-1111-1111-000000000004')
+
+ profile = plan.user.userprofile
+ profile.weight_unit = 'lb'
+ profile.save()
+ cache.clear()
+
+ values = plan.get_nutritional_values()
+
+ self.assertAlmostEqual(values['percent']['carbohydrates'], Decimal(29.79), 2)
+ self.assertAlmostEqual(values['percent']['fat'], Decimal(20.36), 2)
+ self.assertAlmostEqual(values['percent']['protein'], Decimal(26.06), 2)
+
class NutritionalValuesApiTestCase(WgerTestCase):
"""