Self hosted FLOSS fitness/workout, nutrition and weight tracker
Add helper view to log all entries from a planned meal
Roland Geider8784ae7a764e
diff --git a/wger/nutrition/models.py b/wger/nutrition/models.pyindex fd0c34048..8bd20c0ac 100644--- a/wger/nutrition/models.py+++ b/wger/nutrition/models.py@@ -210,9 +210,9 @@ class NutritionPlan(models.Model):return 4def get_log_overview(self):- '''+ """Returns an overview for all logs available for this plan- '''+ """result = []for date in self.logitem_set.datetimes('datetime', 'day', order='DESC'):# TODO: in python 3.5 this can be simplified as z = {**x, **y}@@ -223,16 +223,13 @@ class NutritionPlan(models.Model):return resultdef get_log_entries(self, date=None):- '''+ """Convenience function that returns the log entries for a given date- '''+ """if not date:date = datetime.date.today()- # TODO: in django 1.9 use __date=date here- return self.logitem_set.filter(datetime__year=date.year,- datetime__month=date.month,- datetime__day=date.day).select_related()+ return self.logitem_set.filter(datetime__date=date).select_related()def get_log_summary(self, date=None):'''diff --git a/wger/nutrition/static/js/nutrition.js b/wger/nutrition/static/js/nutrition.jsindex 723961a5e..f854184bb 100644--- a/wger/nutrition/static/js/nutrition.js+++ b/wger/nutrition/static/js/nutrition.js@@ -106,6 +106,7 @@ function wgerDrawNutritionDiaryChart(planPk) {function (nutritionalValues) {MG.data_graphic({data: dataConverted,+ //chart_type: 'bar',y_accessor: 'energy',x_accessor: 'date',decimals: 0,diff --git a/wger/nutrition/templates/log/detail.html b/wger/nutrition/templates/log/detail.htmlindex 366168da3..25708f5bd 100644--- a/wger/nutrition/templates/log/detail.html+++ b/wger/nutrition/templates/log/detail.html@@ -88,10 +88,9 @@<tr><th>{% trans "Time" %}</th><th>{% trans "Ingredient" %}</th>- <th class="align-right">{% trans "Amount" %}</th><th class="align-right">{% trans "Energy" %}</th>{% if is_owner %}- <th class="align-right"></th>+ <th></th>{% endif %}</tr></thead>@@ -99,15 +98,15 @@{% for entry in log_entries %}<tr><td>{{ entry.datetime|time }}</td>- <td>{{ entry.ingredient }}</td>- <td class="align-right">- {{ entry.amount }}+ <td>{% if entry.weight_unit %}- {{ entry.weight_unit }}+ {{ entry.amount|floatformat:"0" }} × {{ entry.weight_unit.unit.name }}{% else %}- {% trans "g" %}+ {{ entry.amount|floatformat:"0" }}{% trans "g" %}{% endif %}+ {{ entry.ingredient }}</td>+<td class="align-right">{{ entry.get_nutritional_values.energy }} {% trans "kcal" %}</td>diff --git a/wger/nutrition/templates/plan/view.html b/wger/nutrition/templates/plan/view.htmlindex eabcdfac6..31278d25a 100644--- a/wger/nutrition/templates/plan/view.html+++ b/wger/nutrition/templates/plan/view.html@@ -87,6 +87,10 @@ function wgerCustomModalInit()title="{% trans 'Add' %}"class="wger-modal-dialog edit-meal"><span class="{% fa_class 'plus' %}"></span></a>+ <a href="{% url 'nutrition:log:log_meal' meal.id %}"+ title="{% trans 'Log this meal' %}"+ class="">+ <span class="{% fa_class 'chart-line' %}"></span></a></div>{% endif %}</td>diff --git a/wger/nutrition/tests/test_nutrition_diary.py b/wger/nutrition/tests/test_nutrition_diary.pyindex d7a5b61f1..64fde94cc 100644--- a/wger/nutrition/tests/test_nutrition_diary.py+++ b/wger/nutrition/tests/test_nutrition_diary.py@@ -19,13 +19,13 @@ import loggingfrom decimal import Decimal# Django-from django.core.urlresolvers import reverse+from django.urls import reverse# wgerfrom wger.core.tests.base_testcase import (- WorkoutManagerAccessTestCase,- WorkoutManagerDeleteTestCase,- WorkoutManagerTestCase+ WgerAccessTestCase,+ WgerDeleteTestCase,+ WgerTestCase)from wger.nutrition.models import (LogItem,@@ -36,10 +36,10 @@ from wger.nutrition.models import (logger = logging.getLogger(__name__)-class DiaryOverviewAccessTest(WorkoutManagerAccessTestCase):- '''+class DiaryOverviewAccessTest(WgerAccessTestCase):+ """Tests accessing a nutrition overview page- '''+ """url = reverse('nutrition:log:overview', kwargs={'pk': 1})user_success = 'test'user_fail = ('admin',@@ -53,10 +53,10 @@ class DiaryOverviewAccessTest(WorkoutManagerAccessTestCase):'general_manager2')-class DiaryOverview2AccessTest(WorkoutManagerAccessTestCase):- '''+class DiaryOverview2AccessTest(WgerAccessTestCase):+ """Tests accessing a nutrition overview page (read access activated)- '''+ """url = reverse('nutrition:log:overview', kwargs={'pk': 2})user_fail = Noneanonymous_fail = False@@ -72,10 +72,10 @@ class DiaryOverview2AccessTest(WorkoutManagerAccessTestCase):'general_manager2')-class DiaryDetailAccessTest(WorkoutManagerAccessTestCase):- '''+class DiaryDetailAccessTest(WgerAccessTestCase):+ """Tests accessing a nutrition overview page- '''+ """url = reverse('nutrition:log:detail', kwargs={'pk': 1,'year': 2016,'month': 5,@@ -92,10 +92,10 @@ class DiaryDetailAccessTest(WorkoutManagerAccessTestCase):'general_manager2')-class DiaryDetail2AccessTest(WorkoutManagerAccessTestCase):- '''+class DiaryDetail2AccessTest(WgerAccessTestCase):+ """Tests accessing a nutrition overview page (read access activated)- '''+ """url = reverse('nutrition:log:detail', kwargs={'pk': 2,'year': 2016,'month': 5,@@ -114,10 +114,10 @@ class DiaryDetail2AccessTest(WorkoutManagerAccessTestCase):'general_manager2')-class NutritionDiaryTestCase(WorkoutManagerTestCase):- '''+class NutritionDiaryTestCase(WgerTestCase):+ """Tests the different nutrition diary functions- '''+ """def test_calculations(self):plan = NutritionPlan.objects.get(pk=1)@@ -144,23 +144,58 @@ class NutritionDiaryTestCase(WorkoutManagerTestCase):'fibres': Decimal('0.00'),'sodium': Decimal('5.09')})+ def test_log_meal(self):+ """+ Tests that logging a meal creates log entries for all meals+ """+ plan = NutritionPlan.objects.get(pk=1)++ LogItem.objects.all().delete()+ self.assertFalse(LogItem.objects.filter(plan=plan))+ self.user_login('test')+ response = self.client.get(reverse('nutrition:log:log_meal', kwargs={"meal_pk": 1}))+ self.assertEqual(response.status_code, 302)+ self.assertEqual(LogItem.objects.filter(plan=plan).count(), 3)++ def test_log_meal_logged_out(self):+ """+ Tests that logging a meal doesn't work for a logged out user+ """+ plan = NutritionPlan.objects.get(pk=1)+ LogItem.objects.all().delete()+ self.assertFalse(LogItem.objects.filter(plan=plan))+ response = self.client.get(reverse('nutrition:log:log_meal', kwargs={"meal_pk": 1}))+ self.assertEqual(response.status_code, 403)+ self.assertEqual(LogItem.objects.filter(plan=plan).count(), 0)++ def test_log_meal_other_user(self):+ """+ Tests that logging a meal doesn't work for a logged out user+ """+ plan = NutritionPlan.objects.get(pk=1)+ LogItem.objects.all().delete()+ self.assertFalse(LogItem.objects.filter(plan=plan))+ self.user_login('admin')+ response = self.client.get(reverse('nutrition:log:log_meal', kwargs={"meal_pk": 1}))+ self.assertEqual(response.status_code, 403)+ self.assertEqual(LogItem.objects.filter(plan=plan).count(), 0)+-class DeleteLogEntryTestCase(WorkoutManagerDeleteTestCase):- '''+class DeleteLogEntryTestCase(WgerDeleteTestCase):+ """Tests deleting an entry from a nutritional diary- '''+ """object_class = LogItemurl = 'nutrition:log:delete'pk = 2user_success = 'test'- user_success = ('admin',- 'test',- 'member1',- 'member2',- 'trainer2',- 'trainer3',- 'trainer4',- 'manager3',- 'general_manager1',- 'general_manager2')+ user_fail = ('admin',+ 'member1',+ 'member2',+ 'trainer2',+ 'trainer3',+ 'trainer4',+ 'manager3',+ 'general_manager1',+ 'general_manager2')diff --git a/wger/nutrition/tests/test_plan.py.orig b/wger/nutrition/tests/test_plan.py.origdeleted file mode 100644index d02604eb7..000000000--- a/wger/nutrition/tests/test_plan.py.orig+++ /dev/null@@ -1,108 +0,0 @@-# 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/>.--from django.urls import reverse-from wger.core.tests import api_base_test--from wger.nutrition.models import NutritionPlan-from wger.manager.tests.testcase import WorkoutManagerDeleteTestCase-from wger.manager.tests.testcase import WorkoutManagerEditTestCase-from wger.manager.tests.testcase import WorkoutManagerTestCase---class PlanRepresentationTestCase(WorkoutManagerTestCase):- '''- Test the representation of a model- '''-- def test_representation(self):- '''- Test that the representation of an object is correct- '''- p = NutritionPlan.objects.get(pk=5)- self.assertEqual("{0}".format(p), 'Description 1')-- p.description = ''- p.save()- self.assertEqual("{0}".format(p), 'Nutrition plan')---class DeletePlanTestCase(WorkoutManagerDeleteTestCase):- '''- Tests deleting a nutritional plan- '''-- object_class = NutritionPlan- url = 'nutrition:plan:delete'- pk = 2---class EditPlanTestCase(WorkoutManagerEditTestCase):- '''- Tests editing an ingredient- '''-- object_class = NutritionPlan- url = 'nutrition:plan:edit'- pk = 2- data = {'description': 'My new description'}---class PlanDailyCaloriesTestCase(WorkoutManagerTestCase):- '''- Tests the handling of the daily calories in the plan page- '''- def test_overview_no_calories(self):- '''- Tests the overview page with no daily calories set- '''-- self.user_login('test')-- # Can't find goal calories text- response = self.client.get(reverse('nutrition:plan:view', kwargs={'id': 1}))- self.assertFalse(response.context['plan'].has_goal_calories)-- self.assertEqual(response.status_code, 200)- self.assertNotContains(response, 'goal amount of calories')-- def test_overview_calories(self):- '''- Tests the overview page with no daily calories set- '''-- # Plan has daily calories goal- self.user_login('test')- plan = NutritionPlan.objects.get(pk=1)- plan.has_goal_calories = True- plan.save()-- # Can find goal calories text- response = self.client.get(reverse('nutrition:plan:view', kwargs={'id': 1}))- self.assertTrue(response.context['plan'].has_goal_calories)- self.assertEqual(response.status_code, 200)- self.assertContains(response, 'goal amount of calories')---class PlanApiTestCase(api_base_test.ApiBaseResourceTestCase):- '''- Tests the nutritional plan overview resource- '''- pk = 4- resource = NutritionPlan- private_resource = True- special_endpoints = ('nutritional_values',)- data = {'description': 'The description',- 'language': 1}diff --git a/wger/nutrition/urls.py b/wger/nutrition/urls.pyindex 1074b6baa..26edc750c 100644--- a/wger/nutrition/urls.py+++ b/wger/nutrition/urls.py@@ -194,6 +194,9 @@ patterns_diary = [url(r'^entry/(?P<pk>\d+)/delete$',log.LogDeleteView.as_view(),name='delete'),+ url(r'^log-meal/(?P<meal_pk>\d+)$',+ log.log_meal,+ name='log_meal'),]diff --git a/wger/nutrition/views/log.py b/wger/nutrition/views/log.pyindex 559114fd1..85335c63d 100644--- a/wger/nutrition/views/log.py+++ b/wger/nutrition/views/log.py@@ -34,6 +34,7 @@ from django.views.generic import DeleteView# wgerfrom wger.nutrition.models import (LogItem,+ Meal,NutritionPlan)from wger.utils.generic_views import (@@ -108,6 +109,35 @@ def detail(request, pk, year, month, day):return render(request, 'log/detail.html', context)+def log_meal(request, meal_pk):+ """+ Copy the requested meal item and logs its nutritional values+ """++ # Check read permission+ meal = get_object_or_404(Meal, pk=meal_pk)+ user = meal.plan.user+ is_owner = request.user == user+ date = datetime.date.today()++ if not is_owner and not user.userprofile.ro_access:+ return HttpResponseForbidden()++ for item in meal.mealitem_set.select_related():+ log_item = LogItem(plan=item.meal.plan,+ ingredient=item.ingredient,+ weight_unit=item.weight_unit,+ amount=item.amount)+ log_item.save()++ return HttpResponseRedirect(reverse('nutrition:log:detail',+ kwargs={'pk': meal.plan.pk,+ 'year': date.year,+ 'month': date.month,+ 'day': date.day+ }))++class LogDeleteView(WgerDeleteMixin, DeleteView, WgerPermissionMixin):"""Delete a nutrition diary entry@@ -116,6 +146,7 @@ class LogDeleteView(WgerDeleteMixin, DeleteView, WgerPermissionMixin):title = ugettext_lazy('Delete?')form_action_urlname = 'nutrition:log:delete'login_required = True+ fields = ["comment", ]def get_success_url(self):"""