id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
22,500
schedule.py
wger-project_wger/wger/manager/views/schedule.py
# -*- coding: utf-8 -*- # 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 # Standard Library import datetime import logging # Django from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import PermissionRequiredMixin from django.http import ( HttpResponse, HttpResponseForbidden, HttpResponseRedirect, ) from django.shortcuts import ( get_object_or_404, render, ) from django.urls import ( reverse, reverse_lazy, ) from django.utils.translation import ( gettext as _, gettext_lazy, ) from django.views.generic import ( CreateView, DeleteView, UpdateView, ) # Third Party from reportlab.lib.pagesizes import A4 from reportlab.lib.units import cm from reportlab.platypus import ( Paragraph, SimpleDocTemplate, Spacer, ) # wger from wger.manager.forms import WorkoutScheduleDownloadForm from wger.manager.helpers import render_workout_day from wger.manager.models import Schedule from wger.utils.generic_views import ( WgerDeleteMixin, WgerFormMixin, ) from wger.utils.helpers import ( check_token, make_token, ) from wger.utils.pdf import ( render_footer, styleSheet, ) logger = logging.getLogger(__name__) @login_required def overview(request): """ An overview of all the user's schedules """ template_data = {} template_data['schedules'] = Schedule.objects.filter(user=request.user).order_by( '-is_active', '-start_date' ) return render(request, 'schedule/overview.html', template_data) def view(request, pk): """ Show the workout schedule """ template_data = {} schedule = get_object_or_404(Schedule, pk=pk) user = schedule.user is_owner = request.user == user if not is_owner and not user.userprofile.ro_access: return HttpResponseForbidden() uid, token = make_token(user) template_data['schedule'] = schedule if schedule.is_active: template_data['active_workout'] = schedule.get_current_scheduled_workout() else: template_data['active_workout'] = False schedule.get_current_scheduled_workout() template_data['uid'] = uid template_data['token'] = token template_data['is_owner'] = is_owner template_data['owner_user'] = user template_data['download_form'] = WorkoutScheduleDownloadForm() return render(request, 'schedule/view.html', template_data) def export_pdf_log(request, pk, images=False, comments=False, uidb64=None, token=None): """ Show the workout schedule """ user = request.user comments = bool(int(comments)) images = bool(int(images)) # Load the workout if uidb64 is not None and token is not None: if check_token(uidb64, token): schedule = get_object_or_404(Schedule, pk=pk) else: return HttpResponseForbidden() else: if request.user.is_anonymous: return HttpResponseForbidden() schedule = get_object_or_404(Schedule, pk=pk, user=user) # Create the HttpResponse object with the appropriate PDF headers. # and use it to the create the PDF using it as a file like object response = HttpResponse(content_type='application/pdf') doc = SimpleDocTemplate( response, pagesize=A4, leftMargin=cm, rightMargin=cm, topMargin=0.5 * cm, bottomMargin=0.5 * cm, title=_('Workout'), author='wger Workout Manager', subject=f'Schedule for {request.user.username}', ) # container for the 'Flowable' objects elements = [] # Set the title p = Paragraph(f'<para align="center">{schedule}</para>', styleSheet['HeaderBold']) elements.append(p) elements.append(Spacer(10 * cm, 0.5 * cm)) # Iterate through the Workout and render the training days for step in schedule.schedulestep_set.all(): p = Paragraph( f'<para>{step.duration} {_("Weeks")}</para>', styleSheet['HeaderBold'], ) elements.append(p) elements.append(Spacer(10 * cm, 0.5 * cm)) for day in step.workout.day_set.all(): elements.append( render_workout_day(day, images=images, comments=comments, nr_of_weeks=7) ) elements.append(Spacer(10 * cm, 0.5 * cm)) # Footer, date and info elements.append(Spacer(10 * cm, 0.5 * cm)) url = reverse('manager:schedule:view', kwargs={'pk': schedule.id}) elements.append(render_footer(request.build_absolute_uri(url))) # write the document and send the response to the browser doc.build(elements) response['Content-Disposition'] = f'attachment; filename=Schedule-{pk}-log.pdf' response['Content-Length'] = len(response.content) return response def export_pdf_table(request, pk, images=False, comments=False, uidb64=None, token=None): """ Show the workout schedule """ user = request.user comments = bool(int(comments)) images = bool(int(images)) # Load the workout if uidb64 is not None and token is not None: if check_token(uidb64, token): schedule = get_object_or_404(Schedule, pk=pk) else: return HttpResponseForbidden() else: if request.user.is_anonymous: return HttpResponseForbidden() schedule = get_object_or_404(Schedule, pk=pk, user=user) # Create the HttpResponse object with the appropriate PDF headers. # and use it to the create the PDF using it as a file like object response = HttpResponse(content_type='application/pdf') doc = SimpleDocTemplate( response, pagesize=A4, leftMargin=cm, rightMargin=cm, topMargin=0.5 * cm, bottomMargin=0.5 * cm, title=_('Workout'), author='wger Workout Manager', subject=f'Schedule for {request.user.username}', ) # container for the 'Flowable' objects elements = [] # Set the title p = Paragraph(f'<para align="center">{schedule}</para>', styleSheet['HeaderBold']) elements.append(p) elements.append(Spacer(10 * cm, 0.5 * cm)) # Iterate through the Workout and render the training days for step in schedule.schedulestep_set.all(): p = Paragraph( f'<para>{step.duration} {_("Weeks")}</para>', styleSheet['HeaderBold'], ) elements.append(p) elements.append(Spacer(10 * cm, 0.5 * cm)) for day in step.workout.day_set.all(): elements.append( render_workout_day( day, images=images, comments=comments, nr_of_weeks=7, only_table=True, ) ) elements.append(Spacer(10 * cm, 0.5 * cm)) # Footer, date and info elements.append(Spacer(10 * cm, 0.5 * cm)) url = reverse('manager:schedule:view', kwargs={'pk': schedule.id}) elements.append(render_footer(request.build_absolute_uri(url))) # write the document and send the response to the browser doc.build(elements) response['Content-Disposition'] = f'attachment; filename=Schedule-{pk}-table.pdf' response['Content-Length'] = len(response.content) return response @login_required def start(request, pk): """ Starts a schedule This simply sets the start date to today and the schedule is marked as being active. """ schedule = get_object_or_404(Schedule, pk=pk, user=request.user) schedule.is_active = True schedule.start_date = datetime.date.today() schedule.save() return HttpResponseRedirect(reverse('manager:schedule:view', kwargs={'pk': schedule.id})) class ScheduleCreateView(WgerFormMixin, CreateView, PermissionRequiredMixin): """ Creates a new workout schedule """ model = Schedule fields = ('name', 'start_date', 'is_active', 'is_loop') success_url = reverse_lazy('manager:schedule:overview') title = gettext_lazy('Create schedule') def form_valid(self, form): """set the submitter""" form.instance.user = self.request.user return super(ScheduleCreateView, self).form_valid(form) def get_success_url(self): return reverse_lazy('manager:schedule:view', kwargs={'pk': self.object.id}) class ScheduleDeleteView(WgerDeleteMixin, DeleteView, PermissionRequiredMixin): """ Generic view to delete a schedule """ model = Schedule success_url = reverse_lazy('manager:schedule:overview') messages = gettext_lazy('Successfully deleted') def get_context_data(self, **kwargs): """ Send some additional data to the template """ context = super(ScheduleDeleteView, self).get_context_data(**kwargs) context['title'] = _('Delete {0}?').format(self.object) return context class ScheduleEditView(WgerFormMixin, UpdateView, PermissionRequiredMixin): """ Generic view to update an existing workout routine """ model = Schedule fields = ('name', 'start_date', 'is_active', 'is_loop') def get_context_data(self, **kwargs): """ Send some additional data to the template """ context = super(ScheduleEditView, self).get_context_data(**kwargs) context['title'] = _('Edit {0}').format(self.object) return context
10,001
Python
.py
277
30.018051
93
0.670942
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,501
log.py
wger-project_wger/wger/manager/views/log.py
# -*- coding: utf-8 -*- # 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 # Standard Library import datetime import logging import uuid # Django from django.contrib.auth.mixins import LoginRequiredMixin from django.forms.models import modelformset_factory from django.http import ( HttpResponseForbidden, HttpResponseRedirect, ) from django.shortcuts import ( get_object_or_404, render, ) from django.urls import ( reverse, reverse_lazy, ) from django.utils.translation import ( gettext as _, gettext_lazy, ) from django.views.generic import ( DeleteView, DetailView, UpdateView, ) # wger from wger.core.models import ( RepetitionUnit, WeightUnit, ) from wger.manager.forms import ( HelperWorkoutSessionForm, WorkoutLogForm, WorkoutLogFormHelper, ) from wger.manager.helpers import WorkoutCalendar from wger.manager.models import ( Day, Schedule, Workout, WorkoutLog, WorkoutSession, ) from wger.utils.generic_views import ( WgerDeleteMixin, WgerFormMixin, ) from wger.utils.helpers import check_access from wger.weight.helpers import ( group_log_entries, process_log_entries, ) logger = logging.getLogger(__name__) # ************************ # Log functions # ************************ class WorkoutLogUpdateView(WgerFormMixin, UpdateView, LoginRequiredMixin): """ Generic view to edit an existing workout log weight entry """ model = WorkoutLog form_class = WorkoutLogForm def get_success_url(self): return reverse('manager:workout:view', kwargs={'pk': self.object.workout_id}) class WorkoutLogDeleteView(WgerDeleteMixin, DeleteView, LoginRequiredMixin): """ Delete a workout log """ model = WorkoutLog title = gettext_lazy('Delete workout log') def get_success_url(self): return reverse('manager:workout:view', kwargs={'pk': self.object.workout_id}) def add(request, pk): """ Add a new workout log """ # NOTE: This function is waaaay too complex and convoluted. While updating # to crispy forms, the template logic could be reduced a lot, but # there is still a lot of optimisations that could happen here. # Load the day and check ownership day = get_object_or_404(Day, pk=pk) if day.get_owner_object().user != request.user: return HttpResponseForbidden() # We need several lists here because we need to assign specific form to each # exercise: the entries for weight and repetitions have no indicator to which # exercise they belong besides the form-ID, from Django's formset counter = 0 total_sets = 0 exercise_list = {} form_to_exercise_base = {} for set_set in day.set_set.all(): for exercise in set_set.exercise_bases: # Maximum possible values total_sets += int(set_set.sets) counter_before = counter counter = counter + int(set_set.sets) - 1 form_id_range = range(counter_before, counter + 1) # Add to list exercise_list[exercise.id] = { 'obj': exercise, 'sets': int(set_set.sets), 'form_ids': form_id_range, } counter += 1 # Helper mapping form-ID <--> Exercise base for id in form_id_range: form_to_exercise_base[id] = exercise # Define the formset here because now we know the value to pass to 'extra' WorkoutLogFormSet = modelformset_factory( WorkoutLog, form=WorkoutLogForm, exclude=('date', 'workout'), extra=total_sets, ) # Process the request if request.method == 'POST': # Make a copy of the POST data and go through it. The reason for this is # that the form expects a value for the exercise which is not present in # the form (for space and usability reasons) post_copy = request.POST.copy() for form_id in form_to_exercise_base: if post_copy.get('form-%s-weight' % form_id) or post_copy.get('form-%s-reps' % form_id): post_copy['form-%s-exercise_base' % form_id] = form_to_exercise_base[form_id].id # Pass the new data to the forms formset = WorkoutLogFormSet(data=post_copy) session_form = HelperWorkoutSessionForm(data=post_copy) # If all the data is valid, save and redirect to log overview page if session_form.is_valid() and formset.is_valid(): log_date = session_form.cleaned_data['date'] if WorkoutSession.objects.filter(user=request.user, date=log_date).exists(): session = WorkoutSession.objects.get(user=request.user, date=log_date) session_form = HelperWorkoutSessionForm(data=post_copy, instance=session) # Save the Workout Session only if there is not already one for this date log_instance = session_form.save(commit=False) if not WorkoutSession.objects.filter(user=request.user, date=log_date).exists(): log_instance.date = log_date log_instance.user = request.user log_instance.workout = day.training else: session = WorkoutSession.objects.get(user=request.user, date=log_date) log_instance.instance = session log_instance.save() # Log entries (only the ones with actual content) log_instances = [i for i in formset.save(commit=False) if i.reps] for log_instance in log_instances: # Set the weight unit in kg if not hasattr(log_instance, 'weight_unit'): log_instance.weight_unit = WeightUnit.objects.get(pk=1) # Set the unit in reps if not hasattr(log_instance, 'repetition_unit'): log_instance.repetition_unit = RepetitionUnit.objects.get(pk=1) if not log_instance.weight: log_instance.weight = 0 log_instance.user = request.user log_instance.workout = day.training log_instance.date = log_date log_instance.save() return HttpResponseRedirect(reverse('manager:log:log', kwargs={'pk': day.training_id})) else: # Initialise the formset with a queryset that won't return any objects # (we only add new logs here and that seems to be the fastest way) user_weight_unit = 1 if request.user.userprofile.use_metric else 2 formset = WorkoutLogFormSet( queryset=WorkoutLog.objects.none(), initial=[ {'weight_unit': user_weight_unit, 'repetition_unit': 1} for x in range(0, total_sets) ], ) # Depending on whether there is already a workout session for today, update # the current one or create a new one (this will be the most usual case) if WorkoutSession.objects.filter(user=request.user, date=datetime.date.today()).exists(): session = WorkoutSession.objects.get(user=request.user, date=datetime.date.today()) session_form = HelperWorkoutSessionForm(instance=session) else: session_form = HelperWorkoutSessionForm() # Pass the correct forms to the exercise list for exercise in exercise_list: form_id_from = min(exercise_list[exercise]['form_ids']) form_id_to = max(exercise_list[exercise]['form_ids']) exercise_list[exercise]['forms'] = formset[form_id_from : form_id_to + 1] context = { 'day': day, 'exercise_list': exercise_list, 'formset': formset, 'helper': WorkoutLogFormHelper(), 'session_form': session_form, 'form': session_form, 'form_action': request.path, } return render(request, 'log/add.html', context) class WorkoutLogDetailView(DetailView, LoginRequiredMixin): """ An overview of the workout's log """ model = Workout template_name = 'workout/log.html' context_object_name = 'workout' owner_user = None def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super(WorkoutLogDetailView, self).get_context_data(**kwargs) is_owner = self.owner_user == self.request.user # Prepare the entries for rendering and the D3 chart workout_log = {} for day_obj in self.object.day_set.all(): day_id = day_obj.id workout_log[day_id] = {} for set_obj in day_obj.set_set.all(): exercise_log = {} for base_obj in set_obj.exercise_bases: exercise_base_id = base_obj.id exercise_log[exercise_base_id] = [] # Filter the logs for user and exclude all units that are not weight logs = base_obj.workoutlog_set.filter( user=self.owner_user, weight_unit__in=(1, 2), repetition_unit=1, workout=self.object, ) entry_log, chart_data = process_log_entries(logs) if entry_log: exercise_log[base_obj.id].append(entry_log) if exercise_log: workout_log[day_id][exercise_base_id] = {} workout_log[day_id][exercise_base_id]['log_by_date'] = entry_log workout_log[day_id][exercise_base_id]['div_uuid'] = 'div-' + str( uuid.uuid4() ) workout_log[day_id][exercise_base_id]['chart_data'] = chart_data context['workout_log'] = workout_log context['owner_user'] = self.owner_user context['is_owner'] = is_owner return context def dispatch(self, request, *args, **kwargs): """ Check for ownership """ workout = get_object_or_404(Workout, pk=kwargs['pk']) self.owner_user = workout.user is_owner = request.user == self.owner_user if not is_owner and not self.owner_user.userprofile.ro_access: return HttpResponseForbidden() # Dispatch normally return super(WorkoutLogDetailView, self).dispatch(request, *args, **kwargs) def calendar(request, username=None, year=None, month=None): """ Show a calendar with all the workout logs """ context = {} is_owner, user = check_access(request.user, username) year = int(year) if year else datetime.date.today().year month = int(month) if month else datetime.date.today().month (current_workout, schedule) = Schedule.objects.get_current_workout(user) grouped_log_entries = group_log_entries(user, year, month) context['calendar'] = WorkoutCalendar(grouped_log_entries).formatmonth(year, month) context['logs'] = grouped_log_entries context['current_year'] = year context['current_month'] = month context['current_workout'] = current_workout context['owner_user'] = user context['is_owner'] = is_owner context['impressions'] = WorkoutSession.IMPRESSION context['month_list'] = WorkoutLog.objects.filter(user=user).dates('date', 'month') return render(request, 'calendar/month.html', context) def day(request, username, year, month, day): """ Show the logs for a single day """ context = {} is_owner, user = check_access(request.user, username) try: date = datetime.date(int(year), int(month), int(day)) except ValueError as e: logger.error(f'Error on date: {e}') return HttpResponseForbidden() context['logs'] = group_log_entries(user, date.year, date.month, date.day) context['date'] = date context['owner_user'] = user context['is_owner'] = is_owner return render(request, 'calendar/day.html', context)
12,631
Python
.py
298
33.885906
100
0.636141
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,502
schedule_step.py
wger-project_wger/wger/manager/views/schedule_step.py
# -*- coding: utf-8 -*- # 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 # Standard Library import logging # Django from django.contrib.auth.mixins import PermissionRequiredMixin from django.db import models from django.forms import ( ModelChoiceField, ModelForm, ) from django.urls import reverse from django.utils.translation import ( gettext as _, gettext_lazy, ) from django.views.generic import ( CreateView, DeleteView, UpdateView, ) # wger from wger.manager.models import ( Schedule, ScheduleStep, Workout, ) from wger.utils.generic_views import ( WgerDeleteMixin, WgerFormMixin, ) logger = logging.getLogger(__name__) class StepCreateView(WgerFormMixin, CreateView, PermissionRequiredMixin): """ Creates a new workout schedule """ model = ScheduleStep fields = ('schedule', 'workout', 'duration', 'order') title = gettext_lazy('Add workout') def get_form_class(self): """ The form can only show the workouts belonging to the user. This is defined here because only at this point during the request have we access to the current user """ class StepForm(ModelForm): workout = ModelChoiceField(queryset=Workout.objects.filter(user=self.request.user)) class Meta: model = ScheduleStep exclude = ('order', 'schedule') return StepForm def get_success_url(self): return reverse('manager:schedule:view', kwargs={'pk': self.kwargs['schedule_pk']}) def form_valid(self, form): """Set the schedule and the order""" schedule = Schedule.objects.get(pk=self.kwargs['schedule_pk']) max_order = schedule.schedulestep_set.all().aggregate(models.Max('order')) form.instance.schedule = schedule form.instance.order = (max_order['order__max'] or 0) + 1 return super(StepCreateView, self).form_valid(form) class StepEditView(WgerFormMixin, UpdateView, PermissionRequiredMixin): """ Generic view to update an existing schedule step """ model = ScheduleStep title = gettext_lazy('Edit workout') def get_form_class(self): """ The form can only show the workouts belonging to the user. This is defined here because only at this point during the request have we access to the current user """ class StepForm(ModelForm): workout = ModelChoiceField(queryset=Workout.objects.filter(user=self.request.user)) class Meta: model = ScheduleStep exclude = ('order', 'schedule') return StepForm def get_success_url(self): return reverse('manager:schedule:view', kwargs={'pk': self.object.schedule_id}) class StepDeleteView(WgerDeleteMixin, DeleteView, PermissionRequiredMixin): """ Generic view to delete a schedule step """ model = ScheduleStep messages = gettext_lazy('Successfully deleted') def get_success_url(self): return reverse('manager:schedule:view', kwargs={'pk': self.object.schedule.id}) def get_context_data(self, **kwargs): """ Send some additional data to the template """ context = super(StepDeleteView, self).get_context_data(**kwargs) context['title'] = _('Delete {0}?').format(self.object) return context
4,003
Python
.py
107
31.588785
95
0.692547
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,503
day.py
wger-project_wger/wger/manager/views/day.py
# -*- coding: utf-8 -*- # 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 # Standard Library import logging # Django from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.http import HttpResponseRedirect from django.shortcuts import ( get_object_or_404, render, ) from django.urls import reverse from django.utils.translation import ( gettext as _, gettext_lazy, ) from django.views.generic import ( CreateView, UpdateView, ) # wger from wger.core.models import DaysOfWeek from wger.manager.forms import DayForm from wger.manager.models import ( Day, Workout, ) from wger.utils.generic_views import WgerFormMixin logger = logging.getLogger(__name__) # ************************ # Day functions # ************************ class DayView(WgerFormMixin, LoginRequiredMixin): """ Base generic view for exercise day """ model = Day fields = ('description', 'day') def get_success_url(self): return reverse('manager:workout:view', kwargs={'pk': self.object.training_id}) def get_form(self, form_class=DayForm): """ Filter the days of the week that are already used by other days """ # Get the form form = super(DayView, self).get_form(form_class) # Calculate the used days ('used' by other days in the same workout) if self.object: workout = self.object.training else: workout = Workout.objects.get(pk=self.kwargs['workout_pk']) used_days = [] for day in workout.day_set.all(): for weekday in day.day.all(): if not self.object or day.id != self.object.id: used_days.append(weekday.id) used_days.sort() # Set the queryset for day form.fields['day'].queryset = DaysOfWeek.objects.exclude(id__in=used_days) return form class DayEditView(DayView, UpdateView): """ Generic view to update an existing exercise day """ # Send some additional data to the template def get_context_data(self, **kwargs): context = super(DayEditView, self).get_context_data(**kwargs) context['title'] = _('Edit {0}').format(self.object) return context class DayCreateView(DayView, CreateView): """ Generic view to add a new exercise day """ title = gettext_lazy('Add workout day') owner_object = {'pk': 'workout_pk', 'class': Workout} def form_valid(self, form): """ Set the workout this day belongs to """ form.instance.training = Workout.objects.get(pk=self.kwargs['workout_pk']) return super(DayCreateView, self).form_valid(form) @login_required def delete(request, pk): """ Deletes the given day """ day = get_object_or_404(Day, training__user=request.user, pk=pk) day.delete() return HttpResponseRedirect(reverse('manager:workout:view', kwargs={'pk': day.training_id})) @login_required def view(request, id): """ Renders a day as shown in the workout overview. This function is to be used with AJAX calls. """ template_data = {} # Load day and check if its workout belongs to the user day = get_object_or_404(Day, pk=id, training__user=request.user) template_data['day'] = day return render(request, 'day/view.html', template_data)
4,015
Python
.py
113
30.539823
96
0.682511
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,504
serializers.py
wger-project_wger/wger/manager/api/serializers.py
# -*- coding: utf-8 -*- # 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/>. # Third Party from rest_framework import serializers # wger from wger.core.api.serializers import DaysOfWeekSerializer from wger.core.models import DaysOfWeek from wger.exercises.api.serializers import ( ExerciseBaseInfoSerializer, ExerciseSerializer, MuscleSerializer, ) from wger.manager.models import ( Day, Schedule, ScheduleStep, Set, Setting, Workout, WorkoutLog, WorkoutSession, ) class WorkoutSerializer(serializers.ModelSerializer): """ Workout serializer """ class Meta: model = Workout fields = ('id', 'name', 'creation_date', 'description') class WorkoutTemplateSerializer(serializers.ModelSerializer): """ Workout template serializer """ class Meta: model = Workout fields = ('id', 'name', 'creation_date', 'description', 'is_public') class WorkoutSessionSerializer(serializers.ModelSerializer): """ Workout session serializer """ user = serializers.PrimaryKeyRelatedField( read_only=True, default=serializers.CurrentUserDefault() ) class Meta: model = WorkoutSession fields = ['id', 'user', 'workout', 'date', 'notes', 'impression', 'time_start', 'time_end'] class WorkoutLogSerializer(serializers.ModelSerializer): """ Workout session serializer """ class Meta: model = WorkoutLog exclude = ('user',) class ScheduleStepSerializer(serializers.ModelSerializer): """ ScheduleStep serializer """ class Meta: model = ScheduleStep fields = ['id', 'schedule', 'workout', 'duration'] class ScheduleSerializer(serializers.ModelSerializer): """ Schedule serializer """ class Meta: model = Schedule exclude = ('user',) class DaySerializer(serializers.ModelSerializer): """ Workout day serializer """ training = serializers.PrimaryKeyRelatedField(queryset=Workout.objects.all()) day = serializers.PrimaryKeyRelatedField(queryset=DaysOfWeek.objects.all(), many=True) class Meta: model = Day fields = ['id', 'training', 'description', 'day'] class SetSerializer(serializers.ModelSerializer): """ Workout setting serializer """ exerciseday = serializers.PrimaryKeyRelatedField(queryset=Day.objects.all()) class Meta: model = Set fields = ['id', 'exerciseday', 'sets', 'order', 'comment'] class SettingSerializer(serializers.ModelSerializer): """ Workout setting serializer """ class Meta: model = Setting fields = [ 'id', 'set', 'exercise_base', 'repetition_unit', 'reps', 'weight', 'weight_unit', 'rir', 'order', 'comment', ] # # Custom helper serializers for the canonical form of a workout # class MusclesCanonicalFormSerializer(serializers.Serializer): """ Serializer for the muscles in the canonical form of a day/workout """ front = serializers.ListField(child=MuscleSerializer()) back = serializers.ListField(child=MuscleSerializer()) frontsecondary = serializers.ListField(child=MuscleSerializer()) backsecondary = serializers.ListField(child=MuscleSerializer()) class WorkoutCanonicalFormExerciseImagesListSerializer(serializers.Serializer): """ Serializer for settings in the canonical form of a workout """ image = serializers.ReadOnlyField() is_main = serializers.ReadOnlyField() class WorkoutCanonicalFormExerciseListSerializer(serializers.Serializer): """ Serializer for settings in the canonical form of a workout """ setting_obj_list = SettingSerializer(many=True) setting_list = serializers.ReadOnlyField() setting_text = serializers.ReadOnlyField() reps_list = serializers.ReadOnlyField() has_weight = serializers.ReadOnlyField() weight_list = serializers.ReadOnlyField() comment_list = serializers.ReadOnlyField() image_list = WorkoutCanonicalFormExerciseImagesListSerializer(many=True) obj = ExerciseBaseInfoSerializer() class WorkoutCanonicalFormExerciseSerializer(serializers.Serializer): """ Serializer for an exercise in the canonical form of a workout """ obj = SetSerializer() exercise_list = WorkoutCanonicalFormExerciseListSerializer(many=True) is_superset = serializers.BooleanField() settings_computed = SettingSerializer(many=True) muscles = MusclesCanonicalFormSerializer() class DaysOfWeekCanonicalFormSerializer(serializers.Serializer): """ Serializer for a days of week in the canonical form of a workout """ text = serializers.ReadOnlyField() day_list = serializers.ListField(child=DaysOfWeekSerializer()) class DayCanonicalFormSerializer(serializers.Serializer): """ Serializer for a day in the canonical form of a workout """ obj = DaySerializer() set_list = WorkoutCanonicalFormExerciseSerializer(many=True) days_of_week = DaysOfWeekCanonicalFormSerializer() muscles = MusclesCanonicalFormSerializer() class WorkoutCanonicalFormSerializer(serializers.Serializer): """ Serializer for the canonical form of a workout """ obj = WorkoutSerializer() day_list = DayCanonicalFormSerializer(many=True) muscles = MusclesCanonicalFormSerializer()
6,156
Python
.py
175
29.937143
99
0.719757
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,505
views.py
wger-project_wger/wger/manager/api/views.py
# -*- coding: utf-8 -*- # 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 json # Django from django.http import HttpResponseNotFound from django.shortcuts import get_object_or_404 # Third Party from rest_framework import viewsets from rest_framework.decorators import action from rest_framework.response import Response # wger from wger.exercises.models import ( Exercise, ExerciseBase, ) from wger.manager.api.serializers import ( DaySerializer, ScheduleSerializer, ScheduleStepSerializer, SetSerializer, SettingSerializer, WorkoutCanonicalFormSerializer, WorkoutLogSerializer, WorkoutSerializer, WorkoutSessionSerializer, WorkoutTemplateSerializer, ) from wger.manager.models import ( Day, Schedule, ScheduleStep, Set, Setting, Workout, WorkoutLog, WorkoutSession, ) from wger.utils.viewsets import WgerOwnerObjectModelViewSet from wger.weight.helpers import process_log_entries class WorkoutViewSet(viewsets.ModelViewSet): """ API endpoint for routine objects """ serializer_class = WorkoutSerializer is_private = True ordering_fields = '__all__' filterset_fields = ('name', 'description', 'creation_date') def get_queryset(self): """ Only allow access to appropriate objects """ # REST API generation if getattr(self, 'swagger_fake_view', False): return Workout.objects.none() return Workout.objects.filter(user=self.request.user) def perform_create(self, serializer): """ Set the owner """ serializer.save(user=self.request.user) @action(detail=True) def canonical_representation(self, request, pk): """ Output the canonical representation of a workout This is basically the same form as used in the application """ out = WorkoutCanonicalFormSerializer(self.get_object().canonical_representation).data return Response(out) @action(detail=True) def log_data(self, request, pk): """ Returns processed log data for graphing Basically, these are the logs for the workout and for a specific exercise base. If on a day there are several entries with the same number of repetitions, but different weights, only the entry with the higher weight is shown in the chart """ base_id = request.GET.get('id') if not base_id: return Response("Please provide an base ID in the 'id' GET parameter") base = get_object_or_404(ExerciseBase, pk=base_id) logs = base.workoutlog_set.filter( user=self.request.user, weight_unit__in=(1, 2), repetition_unit=1, workout=self.get_object(), ) entry_logs, chart_data = process_log_entries(logs) serialized_logs = {} for key, values in entry_logs.items(): serialized_logs[str(key)] = [WorkoutLogSerializer(entry).data for entry in values] return Response({'chart_data': json.loads(chart_data), 'logs': serialized_logs}) class UserWorkoutTemplateViewSet(viewsets.ReadOnlyModelViewSet): """ API endpoint for routine template objects """ serializer_class = WorkoutTemplateSerializer is_private = True ordering_fields = '__all__' filterset_fields = ('name', 'description', 'creation_date') def get_queryset(self): """ Only allow access to appropriate objects """ # REST API generation if getattr(self, 'swagger_fake_view', False): return Workout.objects.none() return Workout.templates.filter(user=self.request.user) def perform_create(self, serializer): """ Set the owner """ serializer.save(user=self.request.user) class PublicWorkoutTemplateViewSet(viewsets.ModelViewSet): """ API endpoint for public workout templates objects """ serializer_class = WorkoutSerializer is_private = True ordering_fields = '__all__' filterset_fields = ('name', 'description', 'creation_date') def get_queryset(self): """ Only allow access to appropriate objects """ return Workout.templates.filter(is_public=True) def perform_create(self, serializer): """ Set the owner """ serializer.save(user=self.request.user) class WorkoutSessionViewSet(WgerOwnerObjectModelViewSet): """ API endpoint for workout sessions objects """ serializer_class = WorkoutSessionSerializer is_private = True ordering_fields = '__all__' filterset_fields = ( 'date', 'workout', 'notes', 'impression', 'time_start', 'time_end', ) def get_queryset(self): """ Only allow access to appropriate objects """ # REST API generation if getattr(self, 'swagger_fake_view', False): return WorkoutSession.objects.none() return WorkoutSession.objects.filter(user=self.request.user) def perform_create(self, serializer): """ Set the owner """ serializer.save(user=self.request.user) def get_owner_objects(self): """ Return objects to check for ownership permission """ return [(Workout, 'workout')] class ScheduleStepViewSet(WgerOwnerObjectModelViewSet): """ API endpoint for schedule step objects """ serializer_class = ScheduleStepSerializer is_private = True ordering_fields = '__all__' filterset_fields = ( 'schedule', 'workout', 'duration', 'order', ) def get_queryset(self): """ Only allow access to appropriate objects """ # REST API generation if getattr(self, 'swagger_fake_view', False): return ScheduleStep.objects.none() return ScheduleStep.objects.filter(schedule__user=self.request.user) def get_owner_objects(self): """ Return objects to check for ownership permission """ return [(Workout, 'workout'), (Schedule, 'schedule')] class ScheduleViewSet(viewsets.ModelViewSet): """ API endpoint for schedule objects """ serializer_class = ScheduleSerializer is_private = True ordering_fields = '__all__' filterset_fields = ( 'is_active', 'is_loop', 'start_date', 'name', ) def get_queryset(self): """ Only allow access to appropriate objects """ # REST API generation if getattr(self, 'swagger_fake_view', False): return Schedule.objects.none() return Schedule.objects.filter(user=self.request.user) def perform_create(self, serializer): """ Set the owner """ serializer.save(user=self.request.user) class DayViewSet(WgerOwnerObjectModelViewSet): """ API endpoint for routine day objects """ serializer_class = DaySerializer is_private = True ordering_fields = '__all__' filterset_fields = ( 'description', 'training', 'day', ) def get_queryset(self): """ Only allow access to appropriate objects """ # REST API generation if getattr(self, 'swagger_fake_view', False): return Day.objects.none() return Day.objects.filter(training__user=self.request.user) def get_owner_objects(self): """ Return objects to check for ownership permission """ return [(Workout, 'training')] class SetViewSet(WgerOwnerObjectModelViewSet): """ API endpoint for workout set objects """ serializer_class = SetSerializer is_private = True ordering_fields = '__all__' filterset_fields = ( 'exerciseday', 'order', 'sets', ) def get_queryset(self): """ Only allow access to appropriate objects """ # REST API generation if getattr(self, 'swagger_fake_view', False): return Set.objects.none() return Set.objects.filter(exerciseday__training__user=self.request.user) def get_owner_objects(self): """ Return objects to check for ownership permission """ return [(Day, 'exerciseday')] @action(detail=True) def computed_settings(self, request, pk): """Returns the synthetic settings for this set""" out = SettingSerializer(self.get_object().compute_settings, many=True).data return Response({'results': out}) class SettingViewSet(WgerOwnerObjectModelViewSet): """ API endpoint for repetition setting objects """ serializer_class = SettingSerializer is_private = True ordering_fields = '__all__' filterset_fields = ( 'exercise_base', 'order', 'reps', 'weight', 'set', 'order', ) def get_queryset(self): """ Only allow access to appropriate objects """ # REST API generation if getattr(self, 'swagger_fake_view', False): return Setting.objects.none() return Setting.objects.filter(set__exerciseday__training__user=self.request.user) def perform_create(self, serializer): """ Set the order """ serializer.save(order=1) def get_owner_objects(self): """ Return objects to check for ownership permission """ return [(Set, 'set')] class WorkoutLogViewSet(WgerOwnerObjectModelViewSet): """ API endpoint for workout log objects """ serializer_class = WorkoutLogSerializer is_private = True ordering_fields = '__all__' filterset_fields = ( 'date', 'exercise_base', 'reps', 'weight', 'workout', 'repetition_unit', 'weight_unit', ) def get_queryset(self): """ Only allow access to appropriate objects """ # REST API generation if getattr(self, 'swagger_fake_view', False): return WorkoutLog.objects.none() return WorkoutLog.objects.filter(user=self.request.user) def perform_create(self, serializer): """ Set the owner """ serializer.save(user=self.request.user) def get_owner_objects(self): """ Return objects to check for ownership permission """ return [(Workout, 'workout')]
11,295
Python
.py
351
25.205128
94
0.643968
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,506
test_email_reminder.py
wger-project_wger/wger/manager/tests/test_email_reminder.py
# 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 # Standard Library import datetime # Django from django.contrib.auth.models import User from django.core import mail from django.core.management import call_command # wger from wger.core.models import UserProfile from wger.core.tests.base_testcase import WgerTestCase from wger.manager.models import ( Schedule, Workout, ) class EmailReminderTestCase(WgerTestCase): """ Tests the email reminder command. User 2 has setting in profile active """ def test_reminder_no_workouts(self): """ Test with no schedules or workouts """ Schedule.objects.all().delete() Workout.objects.all().delete() call_command('email-reminders') self.assertEqual(len(mail.outbox), 0) def test_reminder_one_workout(self): """ Test user with no schedules but one workout User 2, workout created 2012-11-20 """ Schedule.objects.all().delete() Workout.objects.exclude(user=User.objects.get(pk=2)).delete() call_command('email-reminders') self.assertEqual(len(mail.outbox), 1) def test_reminder_skip_if_no_email(self): """ Tests that no emails are sent if the user has provided no email User 2, workout created 2012-11-20 """ user = User.objects.get(pk=2) user.email = '' user.save() Schedule.objects.all().delete() Workout.objects.exclude(user=User.objects.get(pk=2)).delete() call_command('email-reminders') self.assertEqual(len(mail.outbox), 0) def test_reminder_last_notification(self): """ Test that no emails are sent if the last notification field is more recent than one week. User 2, workout created 2012-11-20 """ profile = UserProfile.objects.get(user=2) profile.last_workout_notification = datetime.date.today() - datetime.timedelta(days=3) profile.save() Schedule.objects.all().delete() Workout.objects.exclude(user=User.objects.get(pk=2)).delete() call_command('email-reminders') self.assertEqual(len(mail.outbox), 0) def test_reminder_last_notification_2(self): """ Test that no emails are sent if the last notification field is more than one week away. User 2, workout created 2012-11-20 """ profile = UserProfile.objects.get(user=2) profile.last_workout_notification = datetime.date.today() - datetime.timedelta(days=10) profile.save() Schedule.objects.all().delete() Workout.objects.exclude(user=User.objects.get(pk=2)).delete() call_command('email-reminders') self.assertEqual(len(mail.outbox), 1) def test_reminder_last_notification_3(self): """ Test that no emails are sent if the last notification field is null User 2, workout created 2012-11-20 """ profile = UserProfile.objects.get(user=2) profile.last_workout_notification = None profile.save() Schedule.objects.all().delete() Workout.objects.exclude(user=User.objects.get(pk=2)).delete() call_command('email-reminders') self.assertEqual(len(mail.outbox), 1) def test_reminder_setting_off(self): """ Test user with no schedules, one workout but setting in profile off """ user = User.objects.get(pk=2) user.userprofile.workout_reminder_active = False user.userprofile.save() Schedule.objects.all().delete() Workout.objects.exclude(user=user).delete() call_command('email-reminders') self.assertEqual(len(mail.outbox), 0) def test_reminder_empty_schedule(self): """ Test user with emtpy schedules and no workouts """ user = User.objects.get(pk=2) user.userprofile.workout_reminder_active = False user.userprofile.save() Schedule.objects.all().delete() Workout.objects.all().delete() schedule = Schedule() schedule.user = user schedule.is_active = True schedule.is_loop = False schedule.name = 'test schedule' schedule.start_date = datetime.date(2013, 1, 10) call_command('email-reminders') self.assertEqual(len(mail.outbox), 0) def test_reminder_schedule(self): """ Test user with a schedule and a workout """ user = User.objects.get(pk=2) Workout.objects.exclude(user=user).delete() Schedule.objects.exclude(user=user).delete() call_command('email-reminders') self.assertEqual(len(mail.outbox), 1) def test_reminder_schedule_recent(self): """ Test user with a schedule that has not finished """ user = User.objects.get(pk=1) user.userprofile.workout_reminder_active = True user.userprofile.save() Workout.objects.exclude(user=user).delete() Schedule.objects.exclude(user=user).delete() schedule = Schedule.objects.get(pk=2) schedule.start_date = datetime.date.today() - datetime.timedelta(weeks=4) schedule.is_active = True schedule.is_loop = False schedule.save() call_command('email-reminders') self.assertEqual(len(mail.outbox), 0) def test_reminder_schedule_recent_2(self): """ Test user with a schedule that is about to finish """ user = User.objects.get(pk=1) user.userprofile.workout_reminder_active = True user.userprofile.save() Workout.objects.exclude(user=user).delete() Schedule.objects.exclude(user=user).delete() # Schedule: 3, 5 and 2 weeks schedule = Schedule.objects.get(pk=2) schedule.start_date = datetime.date.today() - datetime.timedelta(weeks=9) schedule.is_active = True schedule.is_loop = False schedule.save() call_command('email-reminders') self.assertEqual(len(mail.outbox), 1) def test_reminder_schedule_recent_3(self): """ Test user with a schedule that is about to finish """ user = User.objects.get(pk=1) user.userprofile.workout_reminder_active = True user.userprofile.workout_reminder = 5 user.userprofile.save() Workout.objects.exclude(user=user).delete() Schedule.objects.exclude(user=user).delete() # Schedule: 3, 5 and 2 weeks schedule = Schedule.objects.get(pk=2) schedule.start_date = datetime.date.today() - datetime.timedelta(weeks=9) schedule.is_active = True schedule.is_loop = False schedule.save() call_command('email-reminders') self.assertEqual(len(mail.outbox), 0)
7,466
Python
.py
186
32.317204
95
0.658503
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,507
test_pdf.py
wger-project_wger/wger/manager/tests/test_pdf.py
# 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 # Django from django.contrib.auth.models import User from django.urls import reverse # wger from wger.core.tests.base_testcase import WgerTestCase from wger.utils.helpers import make_token class WorkoutPdfLogExportTestCase(WgerTestCase): """ Tests exporting a workout as a pdf """ def export_pdf_token(self): """ Helper function to test exporting a workout as a pdf using tokens """ user = User.objects.get(username='test') uid, token = make_token(user) response = self.client.get( reverse('manager:workout:pdf-log', kwargs={'id': 3, 'uidb64': uid, 'token': token}) ) self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/pdf') self.assertEqual(response['Content-Disposition'], 'attachment; filename=Workout-3-log.pdf') # Approximate size only self.assertGreater(int(response['Content-Length']), 38000) self.assertLess(int(response['Content-Length']), 42000) def export_pdf_token_wrong(self): """ Helper function to test exporting a workout as a pdf using a wrong token """ uid = 'AB' token = 'abc-11223344556677889900' response = self.client.get( reverse('manager:workout:pdf-log', kwargs={'id': 3, 'uidb64': uid, 'token': token}) ) self.assertEqual(response.status_code, 403) def export_pdf(self, fail=False): """ Helper function to test exporting a workout as a pdf """ response = self.client.get(reverse('manager:workout:pdf-log', kwargs={'id': 3})) if fail: self.assertIn(response.status_code, (403, 404, 302)) else: self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/pdf') self.assertEqual( response['Content-Disposition'], 'attachment; filename=Workout-3-log.pdf', ) # Approximate size only self.assertGreater(int(response['Content-Length']), 38000) self.assertLess(int(response['Content-Length']), 42000) def export_pdf_with_comments(self, fail=False): """ Helper function to test exporting a workout as a pdf, with exercise coments """ response = self.client.get( reverse('manager:workout:pdf-log', kwargs={'id': 3, 'comments': 0}) ) if fail: self.assertIn(response.status_code, (403, 404, 302)) else: self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/pdf') self.assertEqual( response['Content-Disposition'], 'attachment; filename=Workout-3-log.pdf', ) # Approximate size only self.assertGreater(int(response['Content-Length']), 38000) self.assertLess(int(response['Content-Length']), 42000) def export_pdf_with_images(self, fail=False): """ Helper function to test exporting a workout as a pdf, with exercise images """ response = self.client.get( reverse('manager:workout:pdf-log', kwargs={'id': 3, 'images': 1}) ) if fail: self.assertIn(response.status_code, (403, 404, 302)) else: self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/pdf') self.assertEqual( response['Content-Disposition'], 'attachment; filename=Workout-3-log.pdf', ) # Approximate size only self.assertGreater(int(response['Content-Length']), 38000) self.assertLess(int(response['Content-Length']), 42000) def export_pdf_with_images_and_comments(self, fail=False): """ Helper function to test exporting a workout as a pdf, with images and comments """ response = self.client.get( reverse('manager:workout:pdf-log', kwargs={'id': 3, 'images': 1, 'comments': 1}) ) if fail: self.assertIn(response.status_code, (403, 404, 302)) else: self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/pdf') self.assertEqual( response['Content-Disposition'], 'attachment; filename=Workout-3-log.pdf' ) # Approximate size only self.assertGreater(int(response['Content-Length']), 38000) self.assertLess(int(response['Content-Length']), 42000) def test_export_pdf_anonymous(self): """ Tests exporting a workout as a pdf as an anonymous user """ self.export_pdf(fail=True) self.export_pdf_token() self.export_pdf_token_wrong() def test_export_pdf_owner(self): """ Tests exporting a workout as a pdf as the owner user """ self.user_login('test') self.export_pdf(fail=False) self.export_pdf_token() self.export_pdf_token_wrong() def test_export_pdf_other(self): """ Tests exporting a workout as a pdf as a logged user not owning the data """ self.user_login('admin') self.export_pdf(fail=True) self.export_pdf_token() self.export_pdf_token_wrong() class WorkoutPdfTableExportTestCase(WgerTestCase): """ Tests exporting a workout as a pdf """ def export_pdf_token(self): """ Helper function to test exporting a workout as a pdf using tokens """ user = User.objects.get(username='test') uid, token = make_token(user) response = self.client.get( reverse('manager:workout:pdf-table', kwargs={'id': 3, 'uidb64': uid, 'token': token}) ) self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/pdf') self.assertEqual( response['Content-Disposition'], 'attachment; filename=Workout-3-table.pdf', ) # Approximate size only self.assertGreater(int(response['Content-Length']), 38000) self.assertLess(int(response['Content-Length']), 42000) def export_pdf_token_wrong(self): """ Helper function to test exporting a workout as a pdf using a wrong token """ uid = 'AB' token = 'abc-11223344556677889900' response = self.client.get( reverse('manager:workout:pdf-table', kwargs={'id': 3, 'uidb64': uid, 'token': token}) ) self.assertEqual(response.status_code, 403) def export_pdf(self, fail=False): """ Helper function to test exporting a workout as a pdf """ # Create a workout response = self.client.get(reverse('manager:workout:pdf-table', kwargs={'id': 3})) if fail: self.assertIn(response.status_code, (403, 404, 302)) else: self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/pdf') self.assertEqual( response['Content-Disposition'], 'attachment; filename=Workout-3-table.pdf', ) # Approximate size only self.assertGreater(int(response['Content-Length']), 38000) self.assertLess(int(response['Content-Length']), 42000) def test_export_pdf_anonymous(self): """ Tests exporting a workout as a pdf as an anonymous user """ self.export_pdf(fail=True) self.export_pdf_token() self.export_pdf_token_wrong() def test_export_pdf_owner(self): """ Tests exporting a workout as a pdf as the owner user """ self.user_login('test') self.export_pdf(fail=False) self.export_pdf_token() self.export_pdf_token_wrong() def test_export_pdf_other(self): """ Tests exporting a workout as a pdf as a logged user not owning the data """ self.user_login('admin') self.export_pdf(fail=True) self.export_pdf_token() self.export_pdf_token_wrong()
9,041
Python
.py
217
32.35023
99
0.619585
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,508
test_schedule_step.py
wger-project_wger/wger/manager/tests/test_schedule_step.py
# 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 # Standard Library import datetime # Django from django.urls import reverse_lazy # wger from wger.core.tests import api_base_test from wger.core.tests.base_testcase import ( WgerAddTestCase, WgerDeleteTestCase, WgerEditTestCase, WgerTestCase, ) from wger.manager.models import ScheduleStep class ScheduleStepRepresentationTestCase(WgerTestCase): """ Test the representation of a model """ def test_representation(self): """ Test that the representation of an object is correct """ self.assertEqual(str(ScheduleStep.objects.get(pk=1)), 'A test workout') class ScheduleStepTestCase(WgerTestCase): """ Other tests """ def test_schedule_dates_util(self, fail=False): """ Test the get_dates() method """ s1 = ScheduleStep.objects.get(pk=1) s2 = ScheduleStep.objects.get(pk=2) s3 = ScheduleStep.objects.get(pk=3) self.assertEqual(s1.get_dates(), (datetime.date(2013, 4, 21), datetime.date(2013, 5, 12))) self.assertEqual(s2.get_dates(), (datetime.date(2013, 5, 12), datetime.date(2013, 6, 16))) self.assertEqual(s3.get_dates(), (datetime.date(2013, 6, 16), datetime.date(2013, 6, 30))) class CreateScheduleStepTestCase(WgerAddTestCase): """ Tests adding a schedule """ object_class = ScheduleStep url = reverse_lazy('manager:step:add', kwargs={'schedule_pk': 1}) user_success = 'test' user_fail = False data = {'workout': 3, 'duration': 4} class EditScheduleStepTestCase(WgerEditTestCase): """ Tests editing a schedule """ object_class = ScheduleStep url = 'manager:step:edit' pk = 2 data = {'workout': 1, 'duration': 8} class DeleteScheduleStepTestCase(WgerDeleteTestCase): """ Tests editing a schedule """ object_class = ScheduleStep url = 'manager:step:delete' pk = 2 class ScheduleStepApiTestCase(api_base_test.ApiBaseResourceTestCase): """ Tests the schedule step overview resource """ pk = 4 resource = ScheduleStep private_resource = True data = { 'workout': '3', 'schedule': '1', 'duration': '8', }
2,854
Python
.py
85
28.882353
98
0.697124
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,509
test_schedule.py
wger-project_wger/wger/manager/tests/test_schedule.py
# 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 # Standard Library import datetime import logging # Django from django.contrib.auth.models import User from django.urls import reverse # wger from wger.core.tests import api_base_test from wger.core.tests.base_testcase import ( STATUS_CODES_FAIL, WgerAddTestCase, WgerDeleteTestCase, WgerEditTestCase, WgerTestCase, ) from wger.manager.models import ( Schedule, ScheduleStep, Workout, ) from wger.utils.helpers import make_token logger = logging.getLogger(__name__) class ScheduleAccessTestCase(WgerTestCase): """ Test accessing the workout page """ def test_access_shared(self): """ Test accessing the URL of a shared workout """ workout = Schedule.objects.get(pk=2) self.user_login('admin') response = self.client.get(workout.get_absolute_url()) self.assertEqual(response.status_code, 200) self.user_login('test') response = self.client.get(workout.get_absolute_url()) self.assertEqual(response.status_code, 200) self.user_logout() response = self.client.get(workout.get_absolute_url()) self.assertEqual(response.status_code, 200) def test_access_not_shared(self): """ Test accessing the URL of a private workout """ workout = Schedule.objects.get(pk=1) self.user_login('admin') response = self.client.get(workout.get_absolute_url()) self.assertEqual(response.status_code, 403) self.user_login('test') response = self.client.get(workout.get_absolute_url()) self.assertEqual(response.status_code, 200) self.user_logout() response = self.client.get(workout.get_absolute_url()) self.assertEqual(response.status_code, 403) class ScheduleRepresentationTestCase(WgerTestCase): """ Test the representation of a model """ def test_representation(self): """ Test that the representation of an object is correct """ self.assertEqual( str(Schedule.objects.get(pk=1)), 'my cool schedule that i found on the internet', ) class CreateScheduleTestCase(WgerAddTestCase): """ Tests adding a schedule """ object_class = Schedule url = 'manager:schedule:add' user_success = 'test' user_fail = False data = { 'name': 'My cool schedule', 'start_date': datetime.date.today(), 'is_active': True, 'is_loop': True, } class DeleteScheduleTestCase(WgerDeleteTestCase): """ Tests deleting a schedule """ object_class = Schedule url = 'manager:schedule:delete' pk = 1 user_success = 'test' user_fail = 'admin' class EditScheduleTestCase(WgerEditTestCase): """ Tests editing a schedule """ object_class = Schedule url = 'manager:schedule:edit' pk = 3 data = { 'name': 'An updated name', 'start_date': datetime.date.today(), 'is_active': True, 'is_loop': True, } class ScheduleTestCase(WgerTestCase): """ Other tests """ def schedule_detail_page(self): """ Helper function """ response = self.client.get(reverse('manager:schedule:view', kwargs={'pk': 2})) self.assertEqual(response.status_code, 200) self.assertContains(response, 'This schedule is a loop') schedule = Schedule.objects.get(pk=2) schedule.is_loop = False schedule.save() response = self.client.get(reverse('manager:schedule:view', kwargs={'pk': 2})) self.assertEqual(response.status_code, 200) self.assertNotContains(response, 'This schedule is a loop') def test_schedule_detail_page_owner(self): """ Tests the schedule detail page as the owning user """ self.user_login() self.schedule_detail_page() def test_schedule_overview(self): """ Tests the schedule overview """ self.user_login() response = self.client.get(reverse('manager:schedule:overview')) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.context['schedules']), 3) self.assertTrue(response.context['schedules'][0].is_active) schedule = Schedule.objects.get(pk=4) schedule.is_active = False schedule.save() response = self.client.get(reverse('manager:schedule:overview')) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.context['schedules']), 3) for i in range(0, 3): self.assertFalse(response.context['schedules'][i].is_active) def test_schedule_active(self): """ Tests that only one schedule can be active at a time (per user) """ def get_schedules(): schedule1 = Schedule.objects.get(pk=2) schedule2 = Schedule.objects.get(pk=3) schedule3 = Schedule.objects.get(pk=4) return (schedule1, schedule2, schedule3) self.user_login() (schedule1, schedule2, schedule3) = get_schedules() self.assertTrue(schedule3.is_active) schedule1.is_active = True schedule1.save() (schedule1, schedule2, schedule3) = get_schedules() self.assertTrue(schedule1.is_active) self.assertFalse(schedule2.is_active) self.assertFalse(schedule3.is_active) schedule2.is_active = True schedule2.save() (schedule1, schedule2, schedule3) = get_schedules() self.assertFalse(schedule1.is_active) self.assertTrue(schedule2.is_active) self.assertFalse(schedule3.is_active) def start_schedule(self, fail=False): """ Helper function """ schedule = Schedule.objects.get(pk=2) self.assertFalse(schedule.is_active) self.assertNotEqual(schedule.start_date, datetime.date.today()) response = self.client.get(reverse('manager:schedule:start', kwargs={'pk': 2})) schedule = Schedule.objects.get(pk=2) if fail: self.assertIn(response.status_code, STATUS_CODES_FAIL) self.assertFalse(schedule.is_active) self.assertNotEqual(schedule.start_date, datetime.date.today()) else: self.assertEqual(response.status_code, 302) self.assertTrue(schedule.is_active) self.assertEqual(schedule.start_date, datetime.date.today()) def test_start_schedule_owner(self): """ Tests starting a schedule as the owning user """ self.user_login() self.start_schedule() def test_start_schedule_other(self): """ Tests starting a schedule as a different user """ self.user_login('test') self.start_schedule(fail=True) def test_start_schedule_anonymous(self): """ Tests starting a schedule as a logged out user """ self.start_schedule(fail=True) class ScheduleEndDateTestCase(WgerTestCase): """ Test the schedule's get_end_date method """ def test_loop_schedule(self): """ Loop schedules have no end date """ schedule = Schedule.objects.get(pk=2) self.assertTrue(schedule.is_loop) self.assertFalse(schedule.get_end_date()) def test_calculate(self): """ Test the actual calculation Steps: 3, 5 and 2 weeks, starting on the 2013-04-21 """ schedule = Schedule.objects.get(pk=2) schedule.is_loop = False schedule.save() self.assertEqual(schedule.get_end_date(), datetime.date(2013, 6, 30)) def test_empty_schedule(self): """ Test the end date with an empty schedule """ schedule = Schedule.objects.get(pk=3) self.assertEqual(schedule.get_end_date(), schedule.start_date) class ScheduleModelTestCase(WgerTestCase): """ Tests the model methods """ def delete_objects(self, user): """ Helper function """ Workout.objects.filter(user=user).delete() Schedule.objects.filter(user=user).delete() def create_schedule(self, user, start_date=datetime.date.today(), is_loop=False): """ Helper function """ schedule = Schedule() schedule.user = user schedule.name = 'temp' schedule.is_active = True schedule.start_date = start_date schedule.is_loop = is_loop schedule.save() return schedule def create_workout(self, user): """ Helper function """ workout = Workout() workout.user = user workout.save() return workout def test_get_workout_steps_test_1(self): """ Test with no workouts and no schedule steps """ self.user_login('test') user = User.objects.get(pk=2) self.delete_objects(user) schedule = self.create_schedule(user) self.assertFalse(schedule.get_current_scheduled_workout()) def test_get_workout_steps_test_2(self): """ Test with one schedule step """ self.user_login('test') user = User.objects.get(pk=2) self.delete_objects(user) schedule = self.create_schedule(user) workout = self.create_workout(user) step = ScheduleStep() step.schedule = schedule step.workout = workout step.duration = 3 step.save() self.assertEqual(schedule.get_current_scheduled_workout().workout, workout) def test_get_workout_steps_test_3(self): """ Test with 3 steps """ self.user_login('test') user = User.objects.get(pk=2) self.delete_objects(user) start_date = datetime.date.today() - datetime.timedelta(weeks=4) schedule = self.create_schedule(user, start_date=start_date) workout = self.create_workout(user) step = ScheduleStep() step.schedule = schedule step.workout = workout step.duration = 3 step.order = 1 step.save() workout2 = self.create_workout(user) step2 = ScheduleStep() step2.schedule = schedule step2.workout = workout2 step2.duration = 1 step2.order = 2 step2.save() workout3 = self.create_workout(user) step3 = ScheduleStep() step3.schedule = schedule step3.workout = workout3 step3.duration = 2 step3.order = 3 step3.save() self.assertEqual(schedule.get_current_scheduled_workout().workout, workout2) def test_get_workout_steps_test_4(self): """ Test with 3 steps. Start is too far in the past, schedule ist not a loop """ self.user_login('test') user = User.objects.get(pk=2) self.delete_objects(user) start_date = datetime.date.today() - datetime.timedelta(weeks=7) schedule = self.create_schedule(user, start_date=start_date) workout = self.create_workout(user) step = ScheduleStep() step.schedule = schedule step.workout = workout step.duration = 3 step.order = 1 step.save() workout2 = self.create_workout(user) step2 = ScheduleStep() step2.schedule = schedule step2.workout = workout2 step2.duration = 1 step2.order = 2 step2.save() workout3 = self.create_workout(user) step3 = ScheduleStep() step3.schedule = schedule step3.workout = workout3 step3.duration = 2 step3.order = 3 step3.save() self.assertFalse(schedule.get_current_scheduled_workout()) def test_get_workout_steps_test_5(self): """ Test with 3 steps. Start is too far in the past but schedule is a loop """ self.user_login('test') user = User.objects.get(pk=2) self.delete_objects(user) start_date = datetime.date.today() - datetime.timedelta(weeks=7) schedule = self.create_schedule(user, start_date=start_date, is_loop=True) workout = self.create_workout(user) step = ScheduleStep() step.schedule = schedule step.workout = workout step.duration = 3 step.order = 1 step.save() workout2 = self.create_workout(user) step2 = ScheduleStep() step2.schedule = schedule step2.workout = workout2 step2.duration = 1 step2.order = 2 step2.save() workout3 = self.create_workout(user) step3 = ScheduleStep() step3.schedule = schedule step3.workout = workout3 step3.duration = 2 step3.order = 3 step3.save() self.assertTrue(schedule.get_current_scheduled_workout().workout, workout) class SchedulePdfExportTestCase(WgerTestCase): """ Test exporting a schedule as a pdf """ def export_pdf_token(self, pdf_type='log'): """ Helper function to test exporting a workout as a pdf using tokens """ user = User.objects.get(username='test') uid, token = make_token(user) response = self.client.get( reverse( f'manager:schedule:pdf-{pdf_type}', kwargs={'pk': 1, 'uidb64': uid, 'token': token}, ) ) self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/pdf') self.assertEqual( response['Content-Disposition'], f'attachment; filename=Schedule-1-{pdf_type}.pdf', ) # Approximate size only self.assertGreater(int(response['Content-Length']), 29000) self.assertLess(int(response['Content-Length']), 35000) # Wrong or expired token uid = 'MQ' token = '3xv-57ef74923091fe7f186e' response = self.client.get( reverse( f'manager:schedule:pdf-{pdf_type}', kwargs={'pk': 1, 'uidb64': uid, 'token': token}, ) ) self.assertEqual(response.status_code, 403) def export_pdf(self, fail=False, pdf_type='log'): """ Helper function to test exporting a workout as a pdf """ response = self.client.get(reverse(f'manager:schedule:pdf-{pdf_type}', kwargs={'pk': 1})) if fail: self.assertIn(response.status_code, (403, 404, 302)) else: self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/pdf') self.assertEqual( response['Content-Disposition'], f'attachment; filename=Schedule-1-{pdf_type}.pdf', ) # Approximate size only self.assertGreater(int(response['Content-Length']), 29000) self.assertLess(int(response['Content-Length']), 35000) def export_pdf_with_comments(self, fail=False, pdf_type='log'): """ Helper function to test exporting a workout as a pdf, with exercise coments """ user = User.objects.get(username='test') uid, token = make_token(user) response = self.client.get( reverse( f'manager:schedule:pdf-{pdf_type}', kwargs={'pk': 3, 'images': 0, 'comments': 1, 'uidb64': uid, 'token': token}, ) ) if fail: self.assertIn(response.status_code, (403, 404, 302)) else: self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/pdf') self.assertEqual( response['Content-Disposition'], f'attachment; filename=Schedule-3-{pdf_type}.pdf', ) # Approximate size only self.assertGreater(int(response['Content-Length']), 29000) self.assertLess(int(response['Content-Length']), 35000) def export_pdf_with_images(self, fail=False, pdf_type='log'): """ Helper function to test exporting a workout as a pdf, with exercise images """ user = User.objects.get(username='test') uid, token = make_token(user) response = self.client.get( reverse( f'manager:schedule:pdf-{pdf_type}', kwargs={'pk': 3, 'images': 1, 'comments': 0, 'uidb64': uid, 'token': token}, ) ) if fail: self.assertIn(response.status_code, (403, 404, 302)) else: self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/pdf') self.assertEqual( response['Content-Disposition'], f'attachment; filename=Schedule-3-{pdf_type}.pdf', ) # Approximate size only self.assertGreater(int(response['Content-Length']), 29000) self.assertLess(int(response['Content-Length']), 35000) def export_pdf_with_images_and_comments(self, fail=False, pdf_type='log'): """ Helper function to test exporting a workout as a pdf, with images and comments """ user = User.objects.get(username='test') uid, token = make_token(user) response = self.client.get( reverse( f'manager:schedule:pdf-{pdf_type}', kwargs={'pk': 3, 'images': 1, 'comments': 1, 'uidb64': uid, 'token': token}, ) ) if fail: self.assertIn(response.status_code, (403, 404, 302)) else: self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/pdf') self.assertEqual( response['Content-Disposition'], f'attachment; filename=Schedule-3-{pdf_type}.pdf', ) # Approximate size only self.assertGreater(int(response['Content-Length']), 29000) self.assertLess(int(response['Content-Length']), 35000) def test_export_pdf_log_anonymous(self): """ Tests exporting a workout as a pdf as an anonymous user """ self.export_pdf(fail=True) self.export_pdf_token() def test_export_pdf_log_owner(self): """ Tests exporting a workout as a pdf as the owner user """ self.user_login('test') self.export_pdf(fail=False) self.export_pdf_token() def test_export_pdf_log_other(self): """ Tests exporting a workout as a pdf as a logged user not owning the data """ self.user_login('admin') self.export_pdf(fail=True) self.export_pdf_token() def test_export_pdf_log_with_comments(self, fail=False): """ Tests exporting a workout as a pdf as the owner user with comments """ self.user_login('test') self.export_pdf_with_comments(fail=False) self.export_pdf_token() def test_export_pdf_log_with_images(self, fail=False): """ Tests exporting a workout as a pdf as the owner user with images """ self.user_login('test') self.export_pdf_with_images(fail=False) self.export_pdf_token() def test_export_pdf_log_with_images_and_comments(self, fail=False): """ Tests exporting a workout as a pdf as the owner user with images andcomments """ self.user_login('test') self.export_pdf_with_images_and_comments(fail=False) self.export_pdf_token() # #####TABLE##### def test_export_pdf_table_anonymous(self): """ Tests exporting a workout as a pdf as an anonymous user """ self.export_pdf(fail=True, pdf_type='table') self.export_pdf_token(pdf_type='table') def test_export_pdf_table_owner(self): """ Tests exporting a workout as a pdf as the owner user """ self.user_login('test') self.export_pdf(fail=False, pdf_type='table') self.export_pdf_token(pdf_type='table') def test_export_pdf_table_other(self): """ Tests exporting a workout as a pdf as a logged user not owning the data """ self.user_login('admin') self.export_pdf(fail=True, pdf_type='table') self.export_pdf_token(pdf_type='table') def test_export_pdf_table_with_comments(self, fail=False): """ Tests exporting a workout as a pdf as the owner user with comments """ self.user_login('test') self.export_pdf_with_comments(fail=False, pdf_type='table') self.export_pdf_token(pdf_type='table') def test_export_pdf_table_with_images(self, fail=False): """ Tests exporting a workout as a pdf as the owner user with images """ self.user_login('test') self.export_pdf_with_images(fail=False, pdf_type='table') self.export_pdf_token(pdf_type='table') def test_export_pdf_table_with_images_and_comments(self, fail=False): """ Tests exporting a workout as a pdf as the owner user with images andcomments """ self.user_login('test') self.export_pdf_with_images_and_comments(fail=False, pdf_type='table') self.export_pdf_token(pdf_type='table') class ScheduleApiTestCase(api_base_test.ApiBaseResourceTestCase): """ Tests the schedule overview resource """ pk = 1 resource = Schedule private_resource = True data = { 'name': 'An updated name', 'start_date': datetime.date.today(), 'is_active': True, 'is_loop': True, }
22,538
Python
.py
606
28.511551
97
0.615931
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,510
test_workout.py
wger-project_wger/wger/manager/tests/test_workout.py
# 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 # Standard Library import datetime # Django from django.urls import reverse # wger from wger.core.tests import api_base_test from wger.core.tests.base_testcase import ( WgerDeleteTestCase, WgerEditTestCase, WgerTestCase, ) from wger.manager.models import Workout class AddWorkoutTestCase(WgerTestCase): """ Tests adding a Workout """ def create_workout(self): """ Helper function to test creating workouts """ # Create a workout count_before = Workout.objects.count() response = self.client.get(reverse('manager:workout:add')) count_after = Workout.objects.count() # There is always a redirect self.assertEqual(response.status_code, 302) # Test creating workout self.assertGreater(count_after, count_before) # Test accessing workout response = self.client.get(reverse('manager:workout:view', kwargs={'pk': 1})) self.assertEqual(response.status_code, 200) def test_create_workout_logged_in(self): """ Test creating a workout a logged in user """ self.user_login() self.create_workout() self.user_logout() class DeleteTestWorkoutTestCase(WgerDeleteTestCase): """ Tests deleting a Workout """ object_class = Workout url = 'manager:workout:delete' pk = 3 user_success = 'test' user_fail = 'admin' class EditWorkoutTestCase(WgerEditTestCase): """ Tests editing a Workout """ object_class = Workout url = 'manager:workout:edit' pk = 3 user_success = 'test' user_fail = 'admin' data = {'name': 'A new comment'} class WorkoutOverviewTestCase(WgerTestCase): """ Tests the workout overview """ def get_workout_overview(self): """ Helper function to test the workout overview """ response = self.client.get(reverse('manager:workout:overview')) # Page exists self.assertEqual(response.status_code, 200) class WorkoutModelTestCase(WgerTestCase): """ Tests other functionality from the model """ def test_unicode(self): """ Test the unicode representation """ workout = Workout() workout.creation_date = datetime.date.today() self.assertEqual( str(workout), f'Workout ({datetime.date.today()})', ) workout.name = 'my description' self.assertEqual(str(workout), 'my description') class WorkoutApiTestCase(api_base_test.ApiBaseResourceTestCase): """ Tests the workout overview resource """ pk = 3 resource = Workout private_resource = True special_endpoints = ('canonical_representation',) data = {'name': 'A new comment'}
3,445
Python
.py
106
26.792453
85
0.680169
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,511
test_copy_workout.py
wger-project_wger/wger/manager/tests/test_copy_workout.py
# 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 # Standard Library import logging # Django from django.urls import reverse # wger from wger.core.models import UserProfile from wger.core.tests.base_testcase import WgerTestCase from wger.manager.models import Workout logger = logging.getLogger(__name__) class CopyWorkoutTestCase(WgerTestCase): """ Tests copying a workout or template """ def copy_workout(self): """ Helper function to test copying workouts """ # Open the copy workout form response = self.client.get(reverse('manager:workout:copy', kwargs={'pk': '3'})) self.assertEqual(response.status_code, 200) # Copy the workout count_before = Workout.objects.count() self.client.post( reverse('manager:workout:copy', kwargs={'pk': '3'}), {'name': 'A copied workout'}, ) count_after = Workout.objects.count() self.assertGreater(count_after, count_before) self.assertEqual(count_after, 4) self.assertTemplateUsed('workout/view.html') # Test accessing the copied workout response = self.client.get(reverse('manager:workout:view', kwargs={'pk': 4})) self.assertEqual(response.status_code, 200) workout_original = Workout.objects.get(pk=3) workout_copy = Workout.objects.get(pk=4) days_original = workout_original.day_set.all() days_copy = workout_copy.day_set.all() # Test that the different attributes and objects are correctly copied over for i in range(0, workout_original.day_set.count()): self.assertEqual(days_original[i].description, days_copy[i].description) for j in range(0, days_original[i].day.count()): self.assertEqual(days_original[i].day.all()[j], days_copy[i].day.all()[j]) sets_original = days_original[i].set_set.all() sets_copy = days_copy[i].set_set.all() for j in range(days_original[i].set_set.count()): self.assertEqual(sets_original[j].sets, sets_copy[j].sets) self.assertEqual(sets_original[j].order, sets_copy[j].order) self.assertEqual(sets_original[j].comment, sets_copy[j].comment) bases_original = sets_original[j].exercise_bases bases_copy = sets_copy[j].exercise_bases for k in range(len(sets_original[j].exercise_bases)): self.assertEqual(bases_original[k], bases_copy[k]) settings_original = sets_original[j].setting_set.all() settings_copy = sets_copy[j].setting_set.all() for l in range(settings_original.count()): setting_copy = settings_copy[l] setting_orig = settings_original[l] self.assertEqual(setting_orig.repetition_unit, setting_copy.repetition_unit) self.assertEqual(setting_orig.weight_unit, setting_copy.weight_unit) self.assertEqual(setting_orig.reps, setting_copy.reps) self.assertEqual(setting_orig.weight, setting_copy.weight) self.assertEqual(setting_orig.rir, setting_copy.rir) def test_copy_workout_owner(self): """ Test copying a workout as the owner user """ self.user_login('test') self.copy_workout() def test_copy_workout(self): """ Test copying a workout (not template) """ self.user_login('test') response = self.client.get(reverse('manager:workout:copy', kwargs={'pk': '3'})) self.assertEqual(response.status_code, 200) def test_copy_workout_other(self): """ Test copying a workout (not template) from another user """ self.user_login('admin') response = self.client.get(reverse('manager:workout:copy', kwargs={'pk': '3'})) self.assertEqual(response.status_code, 403) def test_copy_template_no_public_other_user(self): """ Test copying a workout template that is not marked as public and belongs to another user """ workout = Workout.objects.get(pk=3) workout.is_template = True workout.save() self.user_login('admin') response = self.client.get(reverse('manager:workout:copy', kwargs={'pk': '3'})) self.assertEqual(response.status_code, 403) def test_copy_template_no_public_owner_user(self): """ Test copying a workout template that is not marked as public and belongs to the current user """ workout = Workout.objects.get(pk=3) workout.is_template = True workout.save() self.user_login('test') response = self.client.get(reverse('manager:workout:copy', kwargs={'pk': '3'})) self.assertEqual(response.status_code, 200) def test_copy_template_public_other_user(self): """ Test copying a workout template that is marked as public and belongs to another user """ workout = Workout.objects.get(pk=3) workout.is_template = True workout.is_public = True workout.save() self.user_login('admin') response = self.client.get(reverse('manager:workout:copy', kwargs={'pk': '3'})) self.assertEqual(response.status_code, 200)
5,991
Python
.py
126
38.444444
100
0.645919
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,512
test_weight_log.py
wger-project_wger/wger/manager/tests/test_weight_log.py
# 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 # Standard Library import datetime import logging # Django from django.contrib.auth.models import User from django.core.cache import cache from django.urls import ( reverse, reverse_lazy, ) # wger from wger.core.tests import api_base_test from wger.core.tests.base_testcase import ( WgerDeleteTestCase, WgerTestCase, ) from wger.exercises.models import ExerciseBase from wger.manager.models import ( Workout, WorkoutLog, WorkoutSession, ) from wger.utils.cache import cache_mapper from wger.utils.constants import WORKOUT_TAB logger = logging.getLogger(__name__) class WeightLogAccessTestCase(WgerTestCase): """ Test accessing the weight log page """ def test_access(self): """ Test accessing the URL of a weight log """ url = reverse('manager:log:log', kwargs={'pk': 1}) self.user_login('admin') response = self.client.get(url) self.assertEqual(response.status_code, 200) self.user_login('test') response = self.client.get(url) self.assertEqual(response.status_code, 200) self.user_logout() response = self.client.get(url) self.assertEqual(response.status_code, 403) class CalendarAccessTestCase(WgerTestCase): """ Test accessing the calendar page """ def test_access_shared(self): """ Test accessing the URL of a shared calendar page """ url = reverse('manager:workout:calendar', kwargs={'username': 'admin'}) self.user_login('admin') response = self.client.get(url) self.assertEqual(response.status_code, 200) self.user_login('test') response = self.client.get(url) self.assertEqual(response.status_code, 200) self.user_logout() response = self.client.get(url) self.assertEqual(response.status_code, 200) def test_access_not_shared(self): """ Test accessing the URL of a unshared calendar page """ url = reverse('manager:workout:calendar', kwargs={'username': 'test'}) self.user_login('admin') response = self.client.get(url) self.assertEqual(response.status_code, 404) self.user_login('test') response = self.client.get(url) self.assertEqual(response.status_code, 200) self.user_logout() response = self.client.get(url) self.assertEqual(response.status_code, 404) class WeightLogOverviewAddTestCase(WgerTestCase): """ Tests the weight log functionality """ def add_weight_log(self, fail=True): """ Helper function to test adding weight log entries """ # Open the log entry page response = self.client.get(reverse('manager:day:log', kwargs={'pk': 1})) if fail: self.assertIn(response.status_code, (302, 403)) else: self.assertEqual(response.status_code, 200) # Add new log entries count_before = WorkoutLog.objects.count() form_data = { 'date': '2012-01-01', 'notes': 'My cool impression', 'impression': '3', 'time_start': datetime.time(10, 0), 'time_end': datetime.time(12, 0), 'form-0-reps': 10, 'form-0-repetition_unit': 1, 'form-0-weight': 10, 'form-0-weight_unit': 1, 'form-0-rir': '1', 'form-1-reps': 10, 'form-1-repetition_unit': 1, 'form-1-weight': 10, 'form-1-weight_unit': 1, 'form-1-rir': '2', 'form-TOTAL_FORMS': 3, 'form-INITIAL_FORMS': 0, 'form-MAX-NUM_FORMS': 3, } response = self.client.post(reverse('manager:day:log', kwargs={'pk': 1}), form_data) count_after = WorkoutLog.objects.count() # Logged out users get a 302 redirect to login page # Users not owning the workout, a 403, forbidden if fail: self.assertIn(response.status_code, (302, 403)) self.assertEqual(count_before, count_after) else: self.assertEqual(response.status_code, 302) self.assertGreater(count_after, count_before) # # Post log without RiR # form_data['form-0-rir'] = '' form_data['form-1-rir'] = '' count_before = WorkoutLog.objects.count() response = self.client.post(reverse('manager:day:log', kwargs={'pk': 1}), form_data) count_after = WorkoutLog.objects.count() if fail: self.assertIn(response.status_code, (302, 403)) self.assertEqual(count_before, count_after) else: self.assertEqual(response.status_code, 302) self.assertGreater(count_after, count_before) def test_add_weight_log_anonymous(self): """ Tests adding weight log entries as an anonymous user """ self.add_weight_log(fail=True) def test_add_weight_log_owner(self): """ Tests adding weight log entries as the owner user """ self.user_login('admin') self.add_weight_log(fail=False) def test_add_weight_log_other(self): """ Tests adding weight log entries as a logged user not owning the data """ self.user_login('test') self.add_weight_log(fail=True) class WeightlogTestCase(WgerTestCase): """ Tests other model methods """ def test_get_workout_session(self): """ Test the wgerGetWorkoutSession method """ user1 = User.objects.get(pk=1) user2 = User.objects.get(pk=2) workout1 = Workout.objects.get(pk=2) workout2 = Workout.objects.get(pk=2) WorkoutLog.objects.all().delete() log = WorkoutLog() log.user = user1 log.date = datetime.date(2014, 1, 5) log.exercise_base = ExerciseBase.objects.get(pk=1) log.workout = workout1 log.weight = 10 log.reps = 10 log.save() session1 = WorkoutSession() session1.user = user1 session1.workout = workout1 session1.notes = 'Something here' session1.impression = '3' session1.date = datetime.date(2014, 1, 5) session1.save() session2 = WorkoutSession() session2.user = user1 session2.workout = workout1 session2.notes = 'Something else here' session2.impression = '1' session2.date = datetime.date(2014, 1, 1) session2.save() session3 = WorkoutSession() session3.user = user2 session3.workout = workout2 session3.notes = 'The notes here' session3.impression = '2' session3.date = datetime.date(2014, 1, 5) session3.save() self.assertEqual(log.get_workout_session(), session1) class WeightLogDeleteTestCase(WgerDeleteTestCase): """ Tests deleting a WorkoutLog """ object_class = WorkoutLog url = reverse_lazy('manager:log:delete', kwargs={'pk': 1}) pk = 1 class WeightLogEntryEditTestCase(WgerTestCase): """ Tests editing individual weight log entries """ def edit_log_entry(self, fail=True): """ Helper function to test edit log entries """ response = self.client.get(reverse('manager:log:edit', kwargs={'pk': 1})) if fail: self.assertTrue(response.status_code in (302, 403)) else: self.assertEqual(response.status_code, 200) date_before = WorkoutLog.objects.get(pk=1).date response = self.client.post( reverse('manager:log:edit', kwargs={'pk': 1}), { 'date': '2012-01-01', 'reps': 10, 'repetition_unit': 2, 'weight_unit': 3, 'weight': 10, 'exercise_base': 1, 'rir': 2, }, ) date_after = WorkoutLog.objects.get(pk=1).date if fail: # Logged out users get a 302 redirect to login page # Users not owning the workout, a 403, forbidden self.assertTrue(response.status_code in (302, 403)) self.assertEqual(date_before, date_after) else: self.assertEqual(response.status_code, 302) self.assertEqual(date_after, datetime.date(2012, 1, 1)) def test_edit_log_entry_anonymous(self): """ Tests editing a weight log entries as an anonymous user """ self.edit_log_entry(fail=True) def test_edit_log_entry_owner(self): """ Tests editing a weight log entries as the owner user """ self.user_login('admin') self.edit_log_entry(fail=False) def test_edit_log_entry_other(self): """ Tests editing a weight log entries as a logged user not owning the data """ self.user_login('test') self.edit_log_entry(fail=True) class WorkoutLogCacheTestCase(WgerTestCase): """ Workout log cache test case """ def test_calendar(self): """ Test the log cache is correctly generated on visit """ log_hash = hash((1, 2012, 10)) self.user_login('admin') self.assertFalse(cache.get(cache_mapper.get_workout_log_list(log_hash))) self.client.get(reverse('manager:workout:calendar', kwargs={'year': 2012, 'month': 10})) self.assertTrue(cache.get(cache_mapper.get_workout_log_list(log_hash))) def test_calendar_day(self): """ Test the log cache on the calendar day view is correctly generated on visit """ log_hash = hash((1, 2012, 10, 1)) self.user_login('admin') self.assertFalse(cache.get(cache_mapper.get_workout_log_list(log_hash))) self.client.get( reverse( 'manager:workout:calendar-day', kwargs={'username': 'admin', 'year': 2012, 'month': 10, 'day': 1}, ) ) self.assertTrue(cache.get(cache_mapper.get_workout_log_list(log_hash))) def test_calendar_anonymous(self): """ Test the log cache is correctly generated on visit by anonymous users """ log_hash = hash((1, 2012, 10)) self.user_logout() self.assertFalse(cache.get(cache_mapper.get_workout_log_list(log_hash))) self.client.get( reverse( 'manager:workout:calendar', kwargs={'username': 'admin', 'year': 2012, 'month': 10} ) ) self.assertTrue(cache.get(cache_mapper.get_workout_log_list(log_hash))) def test_calendar_day_anonymous(self): """ Test the log cache is correctly generated on visit by anonymous users """ log_hash = hash((1, 2012, 10, 1)) self.user_logout() self.assertFalse(cache.get(cache_mapper.get_workout_log_list(log_hash))) self.client.get( reverse( 'manager:workout:calendar-day', kwargs={'username': 'admin', 'year': 2012, 'month': 10, 'day': 1}, ) ) self.assertTrue(cache.get(cache_mapper.get_workout_log_list(log_hash))) def test_cache_update_log(self): """ Test that the caches are cleared when saving a log """ log_hash = hash((1, 2012, 10)) log_hash_day = hash((1, 2012, 10, 1)) self.user_login('admin') self.client.get(reverse('manager:workout:calendar', kwargs={'year': 2012, 'month': 10})) self.client.get( reverse( 'manager:workout:calendar-day', kwargs={'username': 'admin', 'year': 2012, 'month': 10, 'day': 1}, ) ) log = WorkoutLog.objects.get(pk=1) log.weight = 35 log.save() self.assertFalse(cache.get(cache_mapper.get_workout_log_list(log_hash))) self.assertFalse(cache.get(cache_mapper.get_workout_log_list(log_hash_day))) def test_cache_update_log_2(self): """ Test that the caches are only cleared for a the log's month """ log_hash = hash((1, 2012, 10)) log_hash_day = hash((1, 2012, 10, 1)) self.user_login('admin') self.client.get(reverse('manager:workout:calendar', kwargs={'year': 2012, 'month': 10})) self.client.get( reverse( 'manager:workout:calendar-day', kwargs={'username': 'admin', 'year': 2012, 'month': 10, 'day': 1}, ) ) log = WorkoutLog.objects.get(pk=3) log.weight = 35 log.save() self.assertTrue(cache.get(cache_mapper.get_workout_log_list(log_hash))) self.assertTrue(cache.get(cache_mapper.get_workout_log_list(log_hash_day))) def test_cache_delete_log(self): """ Test that the caches are cleared when deleting a log """ log_hash = hash((1, 2012, 10)) log_hash_day = hash((1, 2012, 10, 1)) self.user_login('admin') self.client.get(reverse('manager:workout:calendar', kwargs={'year': 2012, 'month': 10})) self.client.get( reverse( 'manager:workout:calendar-day', kwargs={'username': 'admin', 'year': 2012, 'month': 10, 'day': 1}, ) ) log = WorkoutLog.objects.get(pk=1) log.delete() self.assertFalse(cache.get(cache_mapper.get_workout_log_list(log_hash))) self.assertFalse(cache.get(cache_mapper.get_workout_log_list(log_hash_day))) def test_cache_delete_log_2(self): """ Test that the caches are only cleared for a the log's month """ log_hash = hash((1, 2012, 10)) log_hash_day = hash((1, 2012, 10, 1)) self.user_login('admin') self.client.get(reverse('manager:workout:calendar', kwargs={'year': 2012, 'month': 10})) self.client.get( reverse( 'manager:workout:calendar-day', kwargs={'username': 'admin', 'year': 2012, 'month': 10, 'day': 1}, ) ) log = WorkoutLog.objects.get(pk=3) log.delete() self.assertTrue(cache.get(cache_mapper.get_workout_log_list(log_hash))) self.assertTrue(cache.get(cache_mapper.get_workout_log_list(log_hash_day))) class WorkoutLogApiTestCase(api_base_test.ApiBaseResourceTestCase): """ Tests the workout log overview resource """ pk = 5 resource = WorkoutLog private_resource = True data = { 'exercise_base': 1, 'workout': 3, 'reps': 3, 'repetition_unit': 1, 'weight_unit': 2, 'weight': 2, 'date': datetime.date.today(), }
15,461
Python
.py
411
28.832117
99
0.601123
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,513
__init__.py
wger-project_wger/wger/manager/tests/__init__.py
# -*- coding: utf-8 -*- # 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 import get_version VERSION = get_version()
802
Python
.py
18
43.333333
78
0.774359
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,514
test_workout_session.py
wger-project_wger/wger/manager/tests/test_workout_session.py
# 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 # Standard Library import datetime # Django from django.contrib.auth.models import User from django.core.cache import cache from django.core.exceptions import ValidationError from django.urls import ( reverse, reverse_lazy, ) # wger from wger.core.tests import api_base_test from wger.core.tests.base_testcase import ( WgerAddTestCase, WgerDeleteTestCase, WgerEditTestCase, WgerTestCase, ) from wger.manager.models import ( Workout, WorkoutLog, WorkoutSession, ) from wger.utils.cache import cache_mapper """ Tests for workout sessions """ class AddWorkoutSessionTestCase(WgerAddTestCase): """ Tests adding a workout session """ object_class = WorkoutSession url = reverse_lazy( 'manager:session:add', kwargs={ 'workout_pk': 1, 'year': datetime.date.today().year, 'month': datetime.date.today().month, 'day': datetime.date.today().day, }, ) data = { 'user': 1, 'workout': 1, 'date': datetime.date.today(), 'notes': 'Some interesting and deep insights', 'impression': '3', 'time_start': datetime.time(10, 0), 'time_end': datetime.time(13, 0), } class EditWorkoutSessionTestCase(WgerEditTestCase): """ Tests editing a workout session """ object_class = WorkoutSession url = 'manager:session:edit' pk = 3 data = { 'user': 1, 'workout': 2, 'date': datetime.date(2014, 1, 30), 'notes': 'My new insights', 'impression': '3', 'time_start': datetime.time(10, 0), 'time_end': datetime.time(13, 0), } class WorkoutSessionModelTestCase(WgerTestCase): """ Tests other functionality from the model """ def test_unicode(self): """ Test the unicode representation """ session = WorkoutSession() session.workout = Workout.objects.get(pk=1) session.date = datetime.date.today() self.assertEqual( str(session), f'{Workout.objects.get(pk=1)} - {datetime.date.today()}', ) class DeleteTestWorkoutTestCase(WgerDeleteTestCase): """ Tests deleting a Workout """ object_class = WorkoutSession url = 'manager:session:delete' pk = 3 class WorkoutSessionDeleteLogsTestCase(WgerTestCase): """ Tests that deleting a session can also delete all weight logs """ def test_delete_logs(self): self.user_login('admin') session = WorkoutSession.objects.get(pk=1) self.assertEqual(WorkoutSession.objects.all().count(), 4) count_before = WorkoutLog.objects.filter( user__username=session.user.username, date=session.date, ).count() self.assertEqual(count_before, 1) response = self.client.post( reverse('manager:session:delete', kwargs={'pk': 1, 'logs': 'logs'}) ) self.assertEqual(response.status_code, 302) self.assertEqual(WorkoutSession.objects.all().count(), 3) count_after = WorkoutLog.objects.filter( user__username=session.user.username, date=session.date, ).count() self.assertEqual(count_after, 0) class WorkoutSessionTestCase(WgerTestCase): """ Tests other workout session methods """ def test_model_validation(self): """ Tests the custom clean() method """ self.user_login('admin') # Values OK session = WorkoutSession() session.workout = Workout.objects.get(pk=2) session.user = User.objects.get(pk=1) session.date = datetime.date.today() session.time_start = datetime.time(12, 0) session.time_end = datetime.time(13, 0) session.impression = '3' session.notes = 'Some notes here' self.assertFalse(session.full_clean()) # No start or end times, also OK session.time_start = None session.time_end = None self.assertFalse(session.full_clean()) # Start time but not end time session.time_start = datetime.time(17, 0) session.time_end = None self.assertRaises(ValidationError, session.full_clean) # No start time but end time session.time_start = None session.time_end = datetime.time(17, 0) self.assertRaises(ValidationError, session.full_clean) # Start time after end time session.time_start = datetime.time(17, 0) session.time_end = datetime.time(13, 0) self.assertRaises(ValidationError, session.full_clean) class WorkoutLogCacheTestCase(WgerTestCase): """ Workout log cache test case """ def test_cache_update_session(self): """ Test that the caches are cleared when updating a workout session """ log_hash = hash((1, 2012, 10)) self.user_login('admin') self.client.get(reverse('manager:workout:calendar', kwargs={'year': 2012, 'month': 10})) session = WorkoutSession.objects.get(pk=1) session.notes = 'Lorem ipsum' session.save() self.assertFalse(cache.get(cache_mapper.get_workout_log_list(log_hash))) def test_cache_update_session_2(self): """ Test that the caches are only cleared for a the session's month """ log_hash = hash((1, 2012, 10)) self.user_login('admin') self.client.get(reverse('manager:workout:calendar', kwargs={'year': 2012, 'month': 10})) # Session is from 2014 session = WorkoutSession.objects.get(pk=2) session.notes = 'Lorem ipsum' session.save() self.assertTrue(cache.get(cache_mapper.get_workout_log_list(log_hash))) def test_cache_delete_session(self): """ Test that the caches are cleared when deleting a workout session """ log_hash = hash((1, 2012, 10)) self.user_login('admin') self.client.get(reverse('manager:workout:calendar', kwargs={'year': 2012, 'month': 10})) session = WorkoutSession.objects.get(pk=1) session.delete() self.assertFalse(cache.get(cache_mapper.get_workout_log_list(log_hash))) def test_cache_delete_session_2(self): """ Test that the caches are only cleared for a the session's month """ log_hash = hash((1, 2012, 10)) self.user_login('admin') self.client.get(reverse('manager:workout:calendar', kwargs={'year': 2012, 'month': 10})) session = WorkoutSession.objects.get(pk=2) session.delete() self.assertTrue(cache.get(cache_mapper.get_workout_log_list(log_hash))) class WorkoutSessionApiTestCase(api_base_test.ApiBaseResourceTestCase): """ Tests the workout overview resource """ pk = 4 resource = WorkoutSession private_resource = True data = { 'workout': 3, 'date': datetime.date(2014, 1, 25), 'notes': 'My new insights', 'impression': '3', 'time_start': datetime.time(10, 0), 'time_end': datetime.time(13, 0), }
7,801
Python
.py
221
28.339367
96
0.644536
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,515
test_day.py
wger-project_wger/wger/manager/tests/test_day.py
# 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 # Django from django.core.cache import cache from django.urls import reverse # wger from wger.core.tests.base_testcase import ( WgerAddTestCase, WgerEditTestCase, WgerTestCase, ) from wger.manager.models import Day from wger.utils.cache import cache_mapper class DayRepresentationTestCase(WgerTestCase): """ Test the representation of a model """ def test_representation(self): """ Test that the representation of an object is correct """ self.assertEqual(str(Day.objects.get(pk=1)), 'A day') class AddWorkoutDayTestCase(WgerAddTestCase): """ Tests adding a day to a workout """ object_class = Day url = reverse('manager:day:add', kwargs={'workout_pk': 3}) user_success = 'test' user_fail = 'admin' data = {'description': 'a new day', 'day': [1, 4]} class DeleteWorkoutDayTestCase(WgerTestCase): """ Tests deleting a day """ def delete_day(self, fail=False): """ Helper function to test deleting a day """ # Fetch the day edit page count_before = Day.objects.count() response = self.client.get(reverse('manager:day:delete', kwargs={'pk': 5})) count_after = Day.objects.count() if fail: self.assertIn(response.status_code, (302, 404)) self.assertTemplateUsed('login.html') self.assertEqual(count_before, count_after) else: self.assertRaises(Day.DoesNotExist, Day.objects.get, pk=5) self.assertEqual(response.status_code, 302) self.assertEqual(count_before - 1, count_after) def test_delete_day_anonymous(self): """ Test deleting a day as an anonymous user """ self.delete_day(fail=True) def test_delete_workout_owner(self): """ Test deleting a day as the owner user """ self.user_login('test') self.delete_day(fail=False) def test_delete_workout_other(self): """ Test deleting a day as a different logged in user """ self.user_login('admin') self.delete_day(fail=True) class EditWorkoutDayTestCase(WgerEditTestCase): """ Tests editing the day of a Workout """ object_class = Day url = 'manager:day:edit' pk = 5 user_success = 'test' user_fail = 'admin' data = {'description': 'a different description', 'day': [1, 4]} class RenderWorkoutDayTestCase(WgerTestCase): """ Tests rendering a single workout day """ def render_day(self, fail=False): """ Helper function to test rendering a single workout day """ # Fetch the day edit page response = self.client.get(reverse('manager:day:view', kwargs={'id': 5})) if fail: self.assertIn(response.status_code, (302, 404)) self.assertTemplateUsed('login.html') else: self.assertEqual(response.status_code, 200) self.assertTemplateUsed('day/view.html') def test_render_day_anonymous(self): """ Test rendering a single workout day as an anonymous user """ self.render_day(fail=True) def test_render_workout_owner(self): """ Test rendering a single workout day as the owner user """ self.user_login('test') self.render_day(fail=False) def test_render_workout_other(self): """ Test rendering a single workout day as a different logged in user """ self.user_login('admin') self.render_day(fail=True) class WorkoutCacheTestCase(WgerTestCase): """ Workout cache test case """ def test_canonical_form_cache_save(self): """ Tests the workout cache when saving """ day = Day.objects.get(pk=1) day.canonical_representation self.assertTrue(cache.get(cache_mapper.get_workout_canonical(day.training_id))) day.save() self.assertFalse(cache.get(cache_mapper.get_workout_canonical(day.training_id))) def test_canonical_form_cache_delete(self): """ Tests the workout cache when deleting """ day = Day.objects.get(pk=1) day.canonical_representation self.assertTrue(cache.get(cache_mapper.get_workout_canonical(day.training_id))) day.delete() self.assertFalse(cache.get(cache_mapper.get_workout_canonical(day.training_id))) class DayTestCase(WgerTestCase): """ Other tests """ def test_day_id_property(self): """ Test that the attribute get_first_day_id works correctly """ day = Day.objects.get(pk=5) self.assertEqual(day.get_first_day_id, 3) day = Day.objects.get(pk=3) self.assertEqual(day.get_first_day_id, 1) # class DayApiTestCase(api_base_test.ApiBaseResourceTestCase): # """ # Tests the day API resource # """ # pk = 5 # resource = Day # private_resource = True # data = {"training": 3, # "description": "API update", # "day": [1, 4] # }
5,793
Python
.py
167
28.155689
88
0.644496
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,516
test_workout_canonical.py
wger-project_wger/wger/manager/tests/test_workout_canonical.py
# 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 # Django from django.core.cache import cache # wger from wger.core.models import DaysOfWeek from wger.core.tests.base_testcase import WgerTestCase from wger.exercises.models import ( ExerciseBase, Muscle, ) from wger.manager.models import ( Day, Set, Setting, Workout, ) from wger.utils.cache import cache_mapper class WorkoutCanonicalFormTestCase(WgerTestCase): """ Tests the canonical form for a workout """ maxDiff = None def test_canonical_form(self): """ Tests the canonical form for a workout """ workout = Workout.objects.get(pk=1) setting_1 = Setting.objects.get(pk=1) setting_2 = Setting.objects.get(pk=2) muscle1 = Muscle.objects.get(pk=1) muscle2 = Muscle.objects.get(pk=2) setting1 = Setting.objects.get(pk=1) setting2 = Setting.objects.get(pk=2) image1 = '/media/exercise-images/1/protestschwein.jpg' image2 = '/media/exercise-images/1/wildschwein.jpg' self.assertEqual( workout.canonical_representation['muscles'], { 'back': [muscle2], 'frontsecondary': [muscle1], 'backsecondary': [muscle1], 'front': [muscle1], }, ) self.assertEqual(workout.canonical_representation['obj'], workout) canonical_form = { 'days_of_week': {'day_list': [DaysOfWeek.objects.get(pk=2)], 'text': 'Tuesday'}, 'muscles': { 'back': [muscle2], 'frontsecondary': [], 'backsecondary': [], 'front': [muscle1], }, 'obj': Day.objects.get(pk=1), 'set_list': [ { 'exercise_list': [ { 'obj': ExerciseBase.objects.get(pk=1), 'image_list': [ {'image': image1, 'is_main': True}, {'image': image2, 'is_main': False}, ], 'comment_list': [], 'has_weight': False, 'setting_obj_list': [setting_1], 'setting_text': '2 \xd7 8 (3 RiR)', } ], 'is_superset': False, 'muscles': { 'back': [muscle2], 'frontsecondary': [], 'backsecondary': [], 'front': [muscle1], }, 'obj': Set.objects.get(pk=1), 'settings_computed': [setting1] * 2, } ], } days_test_data = workout.canonical_representation['day_list'][0] self.assertEqual(days_test_data['days_of_week'], canonical_form['days_of_week']) self.assertEqual(days_test_data['muscles'], canonical_form['muscles']) self.assertEqual(days_test_data['obj'], canonical_form['obj']) # Check that the content is the same for key in days_test_data['set_list'][0].keys(): self.assertEqual(days_test_data['set_list'][0][key], canonical_form['set_list'][0][key]) canonical_form = { 'days_of_week': {'day_list': [DaysOfWeek.objects.get(pk=4)], 'text': 'Thursday'}, 'obj': Day.objects.get(pk=2), 'muscles': { 'back': [muscle2], 'frontsecondary': [muscle1], 'backsecondary': [muscle1], 'front': [], }, 'set_list': [ { 'exercise_list': [ { 'obj': ExerciseBase.objects.get(pk=2), 'image_list': [{'image': image2, 'is_main': False}], 'comment_list': [], 'has_weight': True, 'setting_obj_list': [setting_2], 'setting_text': '4 \xd7 10 (15 kg)', } ], 'is_superset': False, 'muscles': { 'back': [muscle2], 'frontsecondary': [muscle1], 'backsecondary': [muscle1], 'front': [], }, 'obj': Set.objects.get(pk=2), 'settings_computed': [setting2] * 4, } ], } days_test_data = workout.canonical_representation['day_list'][1] self.assertEqual(days_test_data['days_of_week'], canonical_form['days_of_week']) self.assertEqual(days_test_data['muscles'], canonical_form['muscles']) self.assertEqual(days_test_data['obj'], canonical_form['obj']) for key in days_test_data['set_list'][0].keys(): self.assertEqual(days_test_data['set_list'][0][key], canonical_form['set_list'][0][key]) # Check that the content is the same canonical_form = { 'days_of_week': {'day_list': [DaysOfWeek.objects.get(pk=5)], 'text': 'Friday'}, 'obj': Day.objects.get(pk=4), 'muscles': {'back': [], 'front': [], 'frontsecondary': [], 'backsecondary': []}, 'set_list': [], } self.assertEqual(workout.canonical_representation['day_list'][2], canonical_form) def test_canonical_form_day(self): """ Tests the canonical form for a day """ day = Day.objects.get(pk=5) weekday1 = DaysOfWeek.objects.get(pk=3) weekday2 = DaysOfWeek.objects.get(pk=5) muscle1 = Muscle.objects.get(pk=1) muscle2 = Muscle.objects.get(pk=2) setting = Setting.objects.get(pk=3) image2 = '/media/exercise-images/1/wildschwein.jpg' self.assertEqual( day.canonical_representation['days_of_week'], {'day_list': [weekday1, weekday2], 'text': 'Wednesday, Friday'}, ) self.assertEqual( day.canonical_representation['muscles'], { 'back': [muscle2], 'frontsecondary': [muscle1], 'backsecondary': [muscle1], 'front': [], }, ) self.assertEqual(day.canonical_representation['obj'], day) canonical_form = [ { 'exercise_list': [ { 'obj': ExerciseBase.objects.get(pk=2), 'image_list': [{'image': image2, 'is_main': False}], 'comment_list': [], 'has_weight': False, 'setting_obj_list': [Setting.objects.get(pk=3)], 'setting_text': '4 \xd7 10', } ], 'is_superset': False, 'muscles': { 'back': [muscle2], 'frontsecondary': [muscle1], 'backsecondary': [muscle1], 'front': [], }, 'obj': Set.objects.get(pk=3), 'settings_computed': [setting] * 4, } ] self.assertEqual(day.canonical_representation['set_list'], canonical_form) class WorkoutCacheTestCase(WgerTestCase): """ Test case for the workout canonical representation """ def test_canonical_form_cache(self): """ Tests that the workout cache of the canonical form is correctly generated """ self.assertFalse(cache.get(cache_mapper.get_workout_canonical(1))) workout = Workout.objects.get(pk=1) workout.canonical_representation self.assertTrue(cache.get(cache_mapper.get_workout_canonical(1))) def test_canonical_form_cache_save(self): """ Tests the workout cache when saving """ workout = Workout.objects.get(pk=1) workout.canonical_representation self.assertTrue(cache.get(cache_mapper.get_workout_canonical(1))) workout.save() self.assertFalse(cache.get(cache_mapper.get_workout_canonical(1))) def test_canonical_form_cache_delete(self): """ Tests the workout cache when deleting """ workout = Workout.objects.get(pk=1) workout.canonical_representation self.assertTrue(cache.get(cache_mapper.get_workout_canonical(1))) workout.delete() self.assertFalse(cache.get(cache_mapper.get_workout_canonical(1)))
9,322
Python
.py
226
28.190265
100
0.517804
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,517
test_set.py
wger-project_wger/wger/manager/tests/test_set.py
# 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 # Standard Library import logging from decimal import Decimal from typing import List from unittest import skip # Django from django.core.cache import cache from django.urls import ( reverse, reverse_lazy, ) # wger from wger.core.tests import api_base_test from wger.core.tests.base_testcase import ( STATUS_CODES_FAIL, WgerAddTestCase, WgerTestCase, ) from wger.exercises.models import ExerciseBase from wger.manager.models import ( Day, Set, Setting, ) from wger.utils.cache import cache_mapper logger = logging.getLogger(__name__) class SetAddTestCase(WgerAddTestCase): """ Test adding a set to a day """ object_class = Set url = reverse_lazy('manager:set:add', kwargs={'day_pk': 5}) user_success = 'test' user_fail = 'admin' data = { 'exercise_list': 1, # Only for mobile version 'sets': 4, 'exercise1-TOTAL_FORMS': 4, 'exercise1-INITIAL_FORMS': 0, 'exercise1-MAX_NUM_FORMS': 1000, 'exercise1-0-reps': 10, 'exercise1-0-repetition_unit': 1, 'exercise1-0-weight_unit': 1, 'exercise1-1-reps': 12, 'exercise1-1-repetition_unit': 1, 'exercise1-1-weight_unit': 1, 'exercise1-2-reps': 10, 'exercise1-2-repetition_unit': 1, 'exercise1-2-weight_unit': 1, 'exercise1-3-reps': 12, 'exercise1-3-repetition_unit': 1, 'exercise1-3-weight_unit': 1, } data_ignore = ( 'exercise1-TOTAL_FORMS', 'exercise1-INITIAL_FORMS', 'exercise1-MAX_NUM_FORMS', 'exercise_list', 'exercise1-0-reps', 'exercise1-0-repetition_unit', 'exercise1-0-weight_unit', 'exercise1-1-reps', 'exercise1-1-repetition_unit', 'exercise1-1-weight_unit', 'exercise1-2-reps', 'exercise1-2-repetition_unit', 'exercise1-2-weight_unit', 'exercise1-3-reps', 'exercise1-3-repetition_unit', 'exercise1-3-weight_unit', ) def test_add_set(self, fail=False): """ Tests adding a set and corresponding settings at the same time """ # POST the data self.user_login('test') base_ids = [1, 2] post_data = { 'exercise_list': 1, # Only for mobile version 'sets': 4, 'exercise1-TOTAL_FORMS': 4, 'exercise1-INITIAL_FORMS': 0, 'exercise1-MAX_NUM_FORMS': 1000, 'exercise1-0-reps': 10, 'exercise1-0-repetition_unit': 1, 'exercise1-0-weight_unit': 1, 'exercise1-1-reps': 12, 'exercise1-1-repetition_unit': 1, 'exercise1-1-weight_unit': 1, 'exercise1-2-reps': 10, 'exercise1-2-repetition_unit': 1, 'exercise1-2-weight_unit': 1, 'exercise1-3-reps': 12, 'exercise1-3-repetition_unit': 1, 'exercise1-3-weight_unit': 1, 'exercise2-TOTAL_FORMS': 4, 'exercise2-INITIAL_FORMS': 0, 'exercise2-MAX_NUM_FORMS': 1000, 'exercise2-0-reps': 8, 'exercise2-0-repetition_unit': 1, 'exercise2-0-weight_unit': 1, 'exercise2-1-reps': 10, 'exercise2-1-repetition_unit': 2, 'exercise2-1-weight_unit': 2, 'exercise2-2-reps': 8, 'exercise2-2-repetition_unit': 1, 'exercise2-2-weight_unit': 1, 'exercise2-3-reps': 10, 'exercise2-3-repetition_unit': 2, 'exercise2-3-weight_unit': 2, } response = self.client.post(reverse('manager:set:add', kwargs={'day_pk': 5}), post_data) self.assertEqual(response.status_code, 302) set_obj = Set.objects.get(pk=Set.objects.latest('id').id) base1 = ExerciseBase.objects.get(pk=1) # Check that everything got where it's supposed to for bases in set_obj.exercise_bases: self.assertIn(bases.id, base_ids) settings = Setting.objects.filter(set=set_obj) for setting in settings: if setting.exercise_base == base1: self.assertIn(setting.reps, (10, 12)) else: self.assertIn(setting.reps, (8, 10)) class SetDeleteTestCase(WgerTestCase): """ Tests deleting a set from a workout """ def delete_set(self, fail=True): """ Helper function to test deleting a set from a workout """ # Fetch the overview page count_before = Set.objects.count() response = self.client.get(reverse('manager:set:delete', kwargs={'pk': 3})) count_after = Set.objects.count() if fail: self.assertIn(response.status_code, (302, 403)) self.assertEqual(count_before, count_after) else: self.assertEqual(response.status_code, 302) self.assertEqual(count_before - 1, count_after) self.assertRaises(Set.DoesNotExist, Set.objects.get, pk=3) def test_delete_set_anonymous(self): """ Tests deleting a set from a workout as an anonymous user """ self.delete_set(fail=True) def test_delete_set_owner(self): """ Tests deleting a set from a workout as the owner user """ self.user_login('admin') self.delete_set(fail=True) def test_delete_set_other(self): """ Tests deleting a set from a workout as a logged user not owning the data """ self.user_login('test') self.delete_set(fail=False) class TestSetOrderTestCase(WgerTestCase): """ Tests that the order of the (existing) sets in a workout is preservead when adding new ones """ def add_set(self, exercises_id): """ Helper function that adds a set to a day """ nr_sets = 4 post_data = { 'exercises': exercises_id, 'exercise_list': exercises_id[0], # Only for mobile version, 'sets': nr_sets, } for exercise_id in exercises_id: post_data[f'exercise{exercise_id}-TOTAL_FORMS'] = nr_sets post_data[f'exercise{exercise_id}-INITIAL_FORMS'] = 0 post_data[f'exercise{exercise_id}-MAX_NUM_FORMS'] = 1000 for set_nr in range(0, nr_sets): post_data[f'exercise{exercise_id}-{set_nr}-repetition_unit'] = 1 post_data[f'exercise{exercise_id}-{set_nr}-weight_unit'] = 1 post_data[f'exercise{exercise_id}-{set_nr}-reps'] = 8 response = self.client.post(reverse('manager:set:add', kwargs={'day_pk': 5}), post_data) return response def get_order(self): """ Helper function that reads the order of the the sets in a day """ day = Day.objects.get(pk=5) order = () for day_set in day.set_set.select_related(): order += (day_set.id,) return order @skip('Fix later') def test_set_order(self, logged_in=False): """ Helper function that add some sets and checks the order """ self.user_login('test') orig = self.get_order() exercises = (1, 2, 3, 81, 84, 91, 111) for i in range(0, 7): self.add_set([exercises[i]]) prev = self.get_order() orig += (i + 4,) self.assertEqual(orig, prev) class TestSetAddFormset(WgerTestCase): """ Tests the functionality of the formset mini-view that is used in the add set page """ def get_formset(self): """ Helper function """ exercise = ExerciseBase.objects.get(pk=1) response = self.client.get( reverse('manager:set:get-formset', kwargs={'base_pk': 1, 'reps': 4}) ) self.assertEqual(response.status_code, 200) self.assertEqual(response.context['exercise'], exercise) self.assertTrue(response.context['formset']) def test_get_formset_logged_in(self): """ Tests the formset view as an authorized user """ self.user_login('test') self.get_formset() class SetEditEditTestCase(WgerTestCase): """ Tests editing a set """ def edit_set(self, fail=False): """ Helper function """ # Fetch the edit page response = self.client.get(reverse('manager:set:edit', kwargs={'pk': 3})) entry_before = Set.objects.get(pk=3) if fail: self.assertIn(response.status_code, STATUS_CODES_FAIL) else: self.assertEqual(response.status_code, 200) # Try to edit the object response = self.client.post( reverse('manager:set:edit', kwargs={'pk': 3}), { 'exercise2-TOTAL_FORMS': 1, 'exercise2-INITIAL_FORMS': 1, 'exercise2-MAX_NUM_FORMS': 1, 'exercise2-MIN_NUM_FORMS': 1, 'exercise2-0-reps': 5, 'exercise2-0-id': 3, 'exercise2-0-repetition_unit': 2, 'exercise2-0-weight_unit': 3, 'exercise2-0-rir': '1.5', }, ) entry_after = Set.objects.get(pk=3) # Check the results if fail: self.assertIn(response.status_code, STATUS_CODES_FAIL) self.assertEqual(entry_before, entry_after) else: self.assertEqual(response.status_code, 302) # The page we are redirected to doesn't trigger an error response = self.client.get(response['Location']) self.assertEqual(response.status_code, 200) # Setting was updated setting = Setting.objects.get(pk=3) self.assertEqual(setting.reps, 5) self.assertEqual(setting.repetition_unit_id, 2) self.assertEqual(setting.weight_unit_id, 3) self.assertEqual(setting.rir, '1.5') self.post_test_hook() def test_edit_set_authorized(self): """ Tests editing the object as an authorized user """ self.user_login('admin') self.edit_set(fail=True) def test_edit_set_other(self): """ Tests editing the object as an unauthorized, logged in user """ self.user_login('test') self.edit_set(fail=False) class SetWorkoutCacheTestCase(WgerTestCase): """ Workout cache test case """ def test_canonical_form_cache_save(self): """ Tests the workout cache when saving """ set = Set.objects.get(pk=1) set.exerciseday.training.canonical_representation self.assertTrue(cache.get(cache_mapper.get_workout_canonical(set.exerciseday.training_id))) set.save() self.assertFalse(cache.get(cache_mapper.get_workout_canonical(set.exerciseday.training_id))) def test_canonical_form_cache_delete(self): """ Tests the workout cache when deleting """ set = Set.objects.get(pk=1) set.exerciseday.training.canonical_representation self.assertTrue(cache.get(cache_mapper.get_workout_canonical(set.exerciseday.training_id))) set.delete() self.assertFalse(cache.get(cache_mapper.get_workout_canonical(set.exerciseday.training_id))) class SettingWorkoutCacheTestCase(WgerTestCase): """ Workout cache test case """ def test_canonical_form_cache_save(self): """ Tests the workout cache when saving """ setting = Setting.objects.get(pk=1) workout_id = setting.set.exerciseday.training_id setting.set.exerciseday.training.canonical_representation self.assertTrue(cache.get(cache_mapper.get_workout_canonical(workout_id))) setting.save() self.assertFalse(cache.get(cache_mapper.get_workout_canonical(workout_id))) def test_canonical_form_cache_delete(self): """ Tests the workout cache when deleting """ setting = Setting.objects.get(pk=1) workout_id = setting.set.exerciseday.training_id setting.set.exerciseday.training.canonical_representation self.assertTrue(cache.get(cache_mapper.get_workout_canonical(workout_id))) setting.delete() self.assertFalse(cache.get(cache_mapper.get_workout_canonical(workout_id))) class SetSmartReprTestCase(WgerTestCase): """Tests the "smart text representation" for sets""" def test_smart_repr_one_setting(self): """ Tests the representation with one setting """ set_obj = Set.objects.get(pk=1) setting_text = set_obj.reps_smart_text(set_obj.exercise_bases[0]) self.assertEqual(setting_text, '2 × 8 (3 RiR)') def test_smart_repr_custom_setting(self): """ Tests the representation with several settings """ set_obj = Set(exerciseday_id=1, order=1, sets=4) set_obj.save() setting1 = Setting( set=set_obj, exercise_base_id=1, repetition_unit_id=1, reps=8, weight=Decimal(90), weight_unit_id=1, rir='3', order=1, ) setting1.save() setting2 = Setting( set=set_obj, exercise_base_id=1, repetition_unit_id=1, reps=10, weight=Decimal(80), weight_unit_id=1, rir='2.5', order=2, ) setting2.save() setting3 = Setting( set=set_obj, exercise_base_id=1, repetition_unit_id=1, reps=10, weight=Decimal(80), weight_unit_id=1, rir='2', order=3, ) setting3.save() setting4 = Setting( set=set_obj, exercise_base_id=1, repetition_unit_id=1, reps=12, weight=Decimal(80), weight_unit_id=1, rir='1', order=4, ) setting4.save() setting_text = set_obj.reps_smart_text(ExerciseBase.objects.get(pk=1)) self.assertEqual( setting_text, '8 (90 kg, 3 RiR) – 10 (80 kg, 2.5 RiR) – ' '10 (80 kg, 2 RiR) – 12 (80 kg, 1 RiR)', ) def test_synthetic_settings(self): set_obj = Set(exerciseday_id=1, order=1, sets=4) set_obj.save() setting1 = Setting( set=set_obj, exercise_base_id=1, repetition_unit_id=1, reps=8, weight=Decimal(90), weight_unit_id=1, rir='3', order=1, ) setting1.save() setting2 = Setting( set=set_obj, exercise_base_id=3, repetition_unit_id=1, reps=10, weight=Decimal(80), weight_unit_id=1, rir='2.5', order=2, ) setting2.save() settings: List[Setting] = set_obj.compute_settings # Check that there are 2 x 4 entries (2 Exercises x 4 Sets) self.assertEqual(len(settings), 8) # Check interleaved settings for i in range(0, len(settings)): if (i % 2) == 0: self.assertEqual(settings[i].exercise_base_id, 1) self.assertEqual(settings[i].reps, 8) self.assertEqual(settings[i].weight, Decimal(90)) self.assertEqual(settings[i].rir, '3') else: self.assertEqual(settings[i].exercise_base_id, 3) self.assertEqual(settings[i].reps, 10) self.assertEqual(settings[i].weight, Decimal(80)) self.assertEqual(settings[i].rir, '2.5') class SetApiTestCase(api_base_test.ApiBaseResourceTestCase): """ Tests the set overview resource """ pk = 3 resource = Set private_resource = True data = {'exerciseday': 5, 'sets': 4}
16,690
Python
.py
460
26.934783
100
0.587783
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,518
test_generator.py
wger-project_wger/wger/manager/tests/test_generator.py
# 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 # Django from django.core.management import call_command # wger from wger.core.tests.base_testcase import WgerTestCase from wger.manager.models import ( Workout, WorkoutLog, ) class RoutineGeneratorTestCase(WgerTestCase): def test_generator_routines(self): # Arrange Workout.objects.all().delete() # Act call_command('dummy-generator-workout-plans', '--plans', 10) # Assert self.assertEqual(Workout.objects.filter(user_id=1).count(), 10) def test_generator_diary_entries(self): # Arrange Workout.objects.all().delete() # Act call_command('dummy-generator-workout-plans', '--plans', 1) call_command('dummy-generator-workout-diary', '--diary-entries', 10) # Assert # Things like nr of training days or exercises are random min_entries = 1 * 1 * 3 * 3 * 10 max_entries = 1 * 5 * 3 * 10 * 10 self.assertGreaterEqual(WorkoutLog.objects.filter(workout__user_id=1).count(), min_entries) self.assertLessEqual(WorkoutLog.objects.filter(workout__user_id=1).count(), max_entries)
1,769
Python
.py
41
38.219512
99
0.714951
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,519
test_workout_template.py
wger-project_wger/wger/manager/tests/test_workout_template.py
# 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 # Django from django.urls import reverse # wger from wger.core.tests.base_testcase import WgerTestCase from wger.manager.models import Workout class WorkoutTemplateManagerTestCase(WgerTestCase): """ Test accessing the workout template DB manager """ def test_managers(self): """ Test that the DB managers correctly filter the workouts """ self.assertEqual(Workout.objects.all().count(), 3) self.assertEqual(Workout.templates.all().count(), 0) self.assertEqual(Workout.both.all().count(), 3) workout = Workout.objects.get(pk=3) workout.is_template = True workout.save() self.assertEqual(Workout.objects.all().count(), 2) self.assertEqual(Workout.templates.all().count(), 1) self.assertEqual(Workout.both.all().count(), 3) workout.is_public = True workout.save() self.assertEqual(Workout.objects.all().count(), 2) self.assertEqual(Workout.templates.all().count(), 1) self.assertEqual(Workout.both.all().count(), 3) class SwitchViewsTestCase(WgerTestCase): """ Test the views that convert a workout to a template and viceversa """ def test_make_template(self): """ Test accessing the template view for a regular workout """ response = self.client.get(reverse('manager:workout:make-template', kwargs={'pk': 3})) self.assertEqual(response.status_code, 403) self.user_login('test') response = self.client.get(reverse('manager:workout:make-template', kwargs={'pk': 3})) self.assertEqual(response.status_code, 200) self.user_login('admin') response = self.client.get(reverse('manager:workout:make-template', kwargs={'pk': 3})) self.assertEqual(response.status_code, 403) def test_make_workout(self): """ Test marking a template a workout again """ response = self.client.get(reverse('manager:template:make-workout', kwargs={'pk': 3})) self.assertEqual(response.status_code, 403) self.user_login('test') response = self.client.get(reverse('manager:template:make-workout', kwargs={'pk': 3})) self.assertEqual(response.status_code, 302) self.user_login('admin') response = self.client.get(reverse('manager:template:make-workout', kwargs={'pk': 3})) self.assertEqual(response.status_code, 403)
3,084
Python
.py
68
39.014706
94
0.691103
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,520
test_ical.py
wger-project_wger/wger/manager/tests/test_ical.py
# 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 # Standard Library import datetime # Django from django.contrib.auth.models import User from django.urls import reverse # wger from wger.core.tests.base_testcase import WgerTestCase from wger.utils.helpers import ( make_token, next_weekday, ) # TODO: parse the generated calendar files with the icalendar library class IcalToolsTestCase(WgerTestCase): """ Tests some tools used for iCal generation """ def test_next_weekday(self): """ Test the next weekday function """ start_date = datetime.date(2013, 12, 5) # Find next monday self.assertEqual(next_weekday(start_date, 0), datetime.date(2013, 12, 9)) # Find next wednesday self.assertEqual(next_weekday(start_date, 2), datetime.date(2013, 12, 11)) # Find next saturday self.assertEqual(next_weekday(start_date, 5), datetime.date(2013, 12, 7)) class WorkoutICalExportTestCase(WgerTestCase): """ Tests exporting the ical file for a workout """ def export_ical_token(self): """ Helper function that checks exporing an ical file using tokens for access """ user = User.objects.get(username='test') uid, token = make_token(user) response = self.client.get( reverse('manager:workout:ical', kwargs={'pk': 3, 'uidb64': uid, 'token': token}) ) self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'text/calendar') self.assertEqual( response['Content-Disposition'], 'attachment; filename=Calendar-workout-3.ics' ) # Approximate size self.assertGreater(len(response.content), 540) self.assertLess(len(response.content), 620) def export_ical_token_wrong(self): """ Helper function that checks exporing an ical file using a wrong token """ uid = 'AB' token = 'abc-11223344556677889900' response = self.client.get( reverse('manager:workout:ical', kwargs={'pk': 3, 'uidb64': uid, 'token': token}) ) self.assertEqual(response.status_code, 403) def export_ical(self, fail=False): """ Helper function """ response = self.client.get(reverse('manager:workout:ical', kwargs={'pk': 3})) if fail: self.assertIn(response.status_code, (403, 404, 302)) else: self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'text/calendar') self.assertEqual( response['Content-Disposition'], 'attachment; filename=Calendar-workout-3.ics' ) # Approximate size self.assertGreater(len(response.content), 540) self.assertLess(len(response.content), 620) def test_export_ical_anonymous(self): """ Tests exporting a workout as an ical file as an anonymous user """ self.export_ical(fail=True) self.export_ical_token() self.export_ical_token_wrong() def test_export_ical_owner(self): """ Tests exporting a workout as an ical file as the owner user """ self.user_login('test') self.export_ical(fail=False) self.export_ical_token() self.export_ical_token_wrong() def test_export_ical_other(self): """ Tests exporting a workout as an ical file as a logged user not owning the data """ self.user_login('admin') self.export_ical(fail=True) self.export_ical_token() self.export_ical_token_wrong() class ScheduleICalExportTestCase(WgerTestCase): """ Tests exporting the ical file for a schedule """ def export_ical_token(self): """ Helper function that checks exporing an ical file using tokens for access """ user = User.objects.get(username='test') uid, token = make_token(user) response = self.client.get( reverse('manager:schedule:ical', kwargs={'pk': 2, 'uidb64': uid, 'token': token}) ) self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'text/calendar') self.assertEqual( response['Content-Disposition'], 'attachment; filename=Calendar-schedule-2.ics' ) # Approximate size self.assertGreater(len(response.content), 1650) self.assertLess(len(response.content), 1800) def export_ical_token_wrong(self): """ Helper function that checks exporing an ical file using a wrong token """ uid = 'AB' token = 'abc-11223344556677889900' response = self.client.get( reverse('manager:schedule:ical', kwargs={'pk': 2, 'uidb64': uid, 'token': token}) ) self.assertEqual(response.status_code, 403) def export_ical(self, fail=False): """ Helper function """ response = self.client.get(reverse('manager:schedule:ical', kwargs={'pk': 2})) if fail: self.assertIn(response.status_code, (403, 404, 302)) else: self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'text/calendar') self.assertEqual( response['Content-Disposition'], 'attachment; filename=Calendar-schedule-2.ics' ) # Approximate size self.assertGreater(len(response.content), 1650) self.assertLess(len(response.content), 1800) def test_export_ical_anonymous(self): """ Tests exporting a schedule as an ical file as an anonymous user """ self.export_ical(fail=True) self.export_ical_token() self.export_ical_token_wrong() def test_export_ical_owner(self): """ Tests exporting a schedule as an ical file as the owner user """ self.user_login('admin') self.export_ical(fail=False) self.export_ical_token() self.export_ical_token_wrong() def test_export_ical_other(self): """ Tests exporting a schedule as an ical file as a logged user not owning the data """ self.user_login('test') self.export_ical(fail=True) self.export_ical_token() self.export_ical_token_wrong()
7,079
Python
.py
180
31.166667
95
0.639708
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,521
email-reminders.py
wger-project_wger/wger/manager/management/commands/email-reminders.py
# 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 # Standard Library import datetime # Django from django.conf import settings from django.contrib.sites.models import Site from django.core import mail from django.core.management.base import BaseCommand from django.template import loader from django.utils import translation from django.utils.translation import gettext_lazy as _ # wger from wger.core.models import UserProfile from wger.manager.models import Schedule class Command(BaseCommand): """ Helper admin command to send out email reminders """ help = 'Send out automatic email reminders for workouts' def handle(self, **options): """ Find if the currently active workout is overdue """ profile_list = UserProfile.objects.filter(workout_reminder_active=True) counter = 0 for profile in profile_list: # Only continue if the user has provided an email address. # Checking it here so we check for NULL values and emtpy strings if not profile.user.email: continue # Check if we already notified the user and update the profile otherwise if profile.last_workout_notification and ( datetime.date.today() - profile.last_workout_notification < datetime.timedelta(weeks=1) ): continue (current_workout, schedule) = Schedule.objects.get_current_workout(profile.user) # No schedules, use the default workout length in user profile if not schedule and current_workout: delta = ( current_workout.creation_date + datetime.timedelta(weeks=profile.workout_duration) - datetime.date.today() ) if datetime.timedelta(days=profile.workout_reminder) > delta: if int(options['verbosity']) >= 3: self.stdout.write(f"* Workout '{current_workout}' overdue") counter += 1 self.send_email( profile.user, current_workout, delta, ) # non-loop schedule, take the step's duration elif schedule and not schedule.is_loop: schedule_step = schedule.get_current_scheduled_workout() # Only notify if the step is the last one in the schedule if schedule_step == schedule.schedulestep_set.last(): delta = schedule.get_end_date() - datetime.date.today() if datetime.timedelta(days=profile.workout_reminder) > delta: if int(options['verbosity']) >= 3: self.stdout.write( f"* Workout '{schedule_step.workout}' overdue - schedule" ) counter += 1 self.send_email(profile.user, current_workout, delta) if counter and int(options['verbosity']) >= 2: self.stdout.write(f'Sent {counter} email reminders') @staticmethod def send_email(user, workout, delta): """ Notify a user that a workout is about to expire :type user User :type workout Workout :type delta datetime.timedelta """ # Update the last notification date field user.userprofile.last_workout_notification = datetime.date.today() user.userprofile.save() # Compose and send the email translation.activate(user.userprofile.notification_language.short_name) context = { 'site': Site.objects.get_current(), 'workout': workout, 'expired': True if delta.days < 0 else False, 'days': abs(delta.days), } subject = _('Workout will expire soon') message = loader.render_to_string('workout/email_reminder.tpl', context) mail.send_mail( subject, message, settings.WGER_SETTINGS['EMAIL_FROM'], [user.email], fail_silently=True )
4,768
Python
.py
104
34.836538
100
0.621796
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,522
dummy-generator-workout-diary.py
wger-project_wger/wger/manager/management/commands/dummy-generator-workout-diary.py
# 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 # Standard Library import datetime import logging import random import uuid from random import ( choice, randint, ) from uuid import uuid4 # Django from django.contrib.auth.models import User from django.core.management.base import BaseCommand from django.utils import timezone # wger from wger.core.models import ( DaysOfWeek, Language, ) from wger.exercises.models import Exercise from wger.manager.models import ( Day, Set, Setting, Workout, WorkoutLog, ) from wger.nutrition.models import ( Ingredient, LogItem, Meal, MealItem, NutritionPlan, ) logger = logging.getLogger(__name__) class Command(BaseCommand): """ Dummy generator for workout diary entries """ help = 'Dummy generator for workout diary entries' def add_arguments(self, parser): parser.add_argument( '--diary-entries', action='store', default=30, dest='nr_diary_entries', type=int, help='The number of workout logs to create per day (default: 30)', ) parser.add_argument( '--user-id', action='store', dest='user_id', type=int, help='Add only to the specified user-ID (default: all users)', ) def handle(self, **options): self.stdout.write(f"** Generating {options['nr_diary_entries']} dummy diary entries") users = ( [User.objects.get(pk=options['user_id'])] if options['user_id'] else User.objects.all() ) weight_log = [] for user in users: self.stdout.write(f'- processing user {user.username}') # Create a log for each workout day, set, setting, reps, weight, date for workout in Workout.objects.filter(user=user): for day in workout.day_set.all(): for workout_set in day.set_set.all(): for setting in workout_set.setting_set.all(): for reps in (8, 10, 12): for i in range(options['nr_diary_entries']): date = datetime.date.today() - datetime.timedelta(weeks=i) log = WorkoutLog( user=user, exercise_base=setting.exercise_base, workout=workout, reps=reps, weight=50 - reps + random.randint(1, 10), date=date, ) weight_log.append(log) # Bulk-create the logs WorkoutLog.objects.bulk_create(weight_log)
3,477
Python
.py
96
26.197917
99
0.585388
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,523
dummy-generator-workout-plans.py
wger-project_wger/wger/manager/management/commands/dummy-generator-workout-plans.py
# 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 # Standard Library import datetime import logging import random import uuid # Django from django.contrib.auth.models import User from django.core.management.base import BaseCommand # wger from wger.core.models import DaysOfWeek from wger.exercises.models import Exercise from wger.manager.models import ( Day, Set, Setting, Workout, ) logger = logging.getLogger(__name__) class Command(BaseCommand): """ Dummy generator for workout plans """ help = 'Dummy generator for workout plans' def add_arguments(self, parser): parser.add_argument( '--plans', action='store', default=10, dest='nr_plans', type=int, help='The number of workout plans to create per user (default: 10)', ) parser.add_argument( '--user-id', action='store', dest='user_id', type=int, help='Add only to the specified user-ID (default: all users)', ) def handle(self, **options): self.stdout.write(f"** Generating {options['nr_plans']} dummy workout plan(s) per user") users = ( [User.objects.get(pk=options['user_id'])] if options['user_id'] else User.objects.all() ) for user in users: self.stdout.write(f'- processing user {user.username}') # Add plan for _ in range(options['nr_plans']): uid = str(uuid.uuid4()).split('-') start_date = datetime.date.today() - datetime.timedelta(days=random.randint(0, 100)) workout = Workout( user=user, name=f'Dummy workout - {uid[1]}', creation_date=start_date, ) workout.save() # Select a random number of workout days nr_of_days = random.randint(1, 5) day_list = [i for i in range(1, 8)] random.shuffle(day_list) # Load all exercises to a list exercise_list = [i for i in Exercise.objects.filter(language_id=2)] for day in day_list[0:nr_of_days]: uid = str(uuid.uuid4()).split('-') weekday = DaysOfWeek.objects.get(pk=day) day = Day( training=workout, description=f'Dummy day - {uid[0]}', ) day.save() day.day.add(weekday) # Select a random number of exercises nr_of_exercises = random.randint(3, 10) random.shuffle(exercise_list) day_exercises = exercise_list[0:nr_of_exercises] order = 1 for exercise in day_exercises: reps = random.choice([1, 3, 5, 8, 10, 12, 15]) sets = random.randint(2, 4) day_set = Set( exerciseday=day, sets=sets, order=order, ) day_set.save() setting = Setting( set=day_set, exercise_base=exercise.exercise_base, reps=reps, order=order, ) setting.save() order += 1
4,194
Python
.py
106
26.716981
100
0.532203
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,524
signals.py
wger-project_wger/wger/nutrition/signals.py
# -*- coding: utf-8 -*- # 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 # Django from django.core.cache import cache from django.db.models.signals import ( post_delete, post_save, ) # wger from wger.nutrition.models import ( Meal, MealItem, NutritionPlan, ) from wger.utils.cache import cache_mapper def reset_nutritional_values_canonical_form(sender, instance, **kwargs): """ Reset the nutrition values canonical form in cache """ cache.delete(cache_mapper.get_nutrition_cache_by_key(instance.get_owner_object().id)) post_save.connect(reset_nutritional_values_canonical_form, sender=NutritionPlan) post_delete.connect(reset_nutritional_values_canonical_form, sender=NutritionPlan) post_save.connect(reset_nutritional_values_canonical_form, sender=Meal) post_delete.connect(reset_nutritional_values_canonical_form, sender=Meal) post_save.connect(reset_nutritional_values_canonical_form, sender=MealItem) post_delete.connect(reset_nutritional_values_canonical_form, sender=MealItem)
1,616
Python
.py
38
40.394737
89
0.793125
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,525
sync.py
wger-project_wger/wger/nutrition/sync.py
# 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 # Standard Library import logging import os from typing import Optional # Django from django.conf import settings from django.db import IntegrityError # Third Party import requests from openfoodfacts.images import ( AWS_S3_BASE_URL, generate_image_path, ) # wger from wger.nutrition.api.endpoints import ( IMAGE_ENDPOINT, INGREDIENTS_ENDPOINT, ) from wger.nutrition.models import ( Image, Ingredient, Source, ) from wger.utils.constants import ( API_MAX_ITEMS, CC_BY_SA_3_LICENSE_ID, DOWNLOAD_INGREDIENT_OFF, DOWNLOAD_INGREDIENT_WGER, ) from wger.utils.requests import ( get_paginated, wger_headers, ) from wger.utils.url import make_uri logger = logging.getLogger(__name__) def fetch_ingredient_image(pk: int): # wger from wger.nutrition.models import Ingredient try: ingredient = Ingredient.objects.get(pk=pk) except Ingredient.DoesNotExist: logger.info(f'Ingredient with ID {pk} does not exist') return if hasattr(ingredient, 'image'): return if ingredient.source_name != Source.OPEN_FOOD_FACTS.value: return if not ingredient.source_url: return if settings.TESTING: return logger.info(f'Fetching image for ingredient {pk}') if settings.WGER_SETTINGS['DOWNLOAD_INGREDIENTS_FROM'] == DOWNLOAD_INGREDIENT_OFF: fetch_image_from_off(ingredient) elif settings.WGER_SETTINGS['DOWNLOAD_INGREDIENTS_FROM'] == DOWNLOAD_INGREDIENT_WGER: fetch_image_from_wger_instance(ingredient) def fetch_image_from_wger_instance(ingredient): url = make_uri(IMAGE_ENDPOINT, query={'ingredient__uuid': ingredient.uuid}) logger.info(f'Trying to fetch image from WGER for {ingredient.name} (UUID: {ingredient.uuid})') result = requests.get(url, headers=wger_headers()).json() if result['count'] == 0: logger.info('No ingredient matches UUID in the remote server') image_data = result['results'][0] image_uuid = image_data['uuid'] try: Image.objects.get(uuid=image_uuid) logger.info('image already present locally, skipping...') return except Image.DoesNotExist: retrieved_image = requests.get(image_data['image'], headers=wger_headers()) Image.from_json(ingredient, retrieved_image, image_data) def fetch_image_from_off(ingredient: Ingredient): """ See - https://openfoodfacts.github.io/openfoodfacts-server/api/how-to-download-images/ - https://openfoodfacts.github.io/openfoodfacts-server/api/ref-v2/ """ logger.info(f'Trying to fetch image from OFF for {ingredient.name} (UUID: {ingredient.uuid})') url = ingredient.source_url + '?fields=images,image_front_url' headers = wger_headers() try: product_data = requests.get(url, headers=headers, timeout=3).json() except requests.JSONDecodeError: logger.warning(f'Could not decode JSON response from {url}') return except requests.ConnectTimeout as e: logger.warning(f'Connection timeout while trying to fetch {url}: {e}') return except requests.ReadTimeout as e: logger.warning(f'Read timeout while trying to fetch {url}: {e}') return try: image_url: Optional[str] = product_data['product'].get('image_front_url') except KeyError: logger.info('No "product" key found, exiting...') return if not image_url: logger.info('Product data has no "image_front_url" key') return image_data = product_data['product']['images'] # Extract the image key from the url: # https://images.openfoodfacts.org/images/products/00975957/front_en.5.400.jpg -> "front_en" image_id: str = image_url.rpartition('/')[2].partition('.')[0] # Extract the uploader name try: image_id: str = image_data[image_id]['imgid'] uploader_name: str = image_data[image_id]['uploader'] except KeyError as e: logger.info('could not load all image information, skipping...', e) return # Download image from amazon image_s3_url = f'{AWS_S3_BASE_URL}{generate_image_path(ingredient.code, image_id)}' response = requests.get(image_s3_url, headers=headers) if not response.ok: logger.info(f'Could not locate image on AWS! Status code: {response.status_code}') return # Save to DB url = ( f'https://world.openfoodfacts.org/cgi/product_image.pl?code={ingredient.code}&id={image_id}' ) uploader_url = f'https://world.openfoodfacts.org/photographer/{uploader_name}' image_data = { 'image': os.path.basename(image_url), 'license': CC_BY_SA_3_LICENSE_ID, 'license_title': 'Photo', 'license_author': uploader_name, 'license_author_url': uploader_url, 'license_object_url': url, 'license_derivative_source_url': '', 'size': len(response.content), } try: Image.from_json(ingredient, response, image_data, generate_uuid=True) # Due to a race condition (e.g. when adding tasks over the search), we might # try to save an image to an ingredient that already has one. In that case, # just ignore the error except IntegrityError: logger.info('Ingredient has already an image, skipping...') return logger.info('Image successfully saved') def download_ingredient_images( print_fn, remote_url=settings.WGER_SETTINGS['WGER_INSTANCE'], style_fn=lambda x: x, ): headers = wger_headers() url = make_uri(IMAGE_ENDPOINT, server_url=remote_url, query={'limit': 100}) print_fn('*** Processing ingredient images ***') for image_data in get_paginated(url, headers=headers): image_uuid = image_data['uuid'] print_fn(f'Processing image {image_uuid}') try: ingredient = Ingredient.objects.get(uuid=image_data['ingredient_uuid']) except Ingredient.DoesNotExist: print_fn(' Remote ingredient not found in local DB, skipping...') continue if hasattr(ingredient, 'image'): continue try: Image.objects.get(uuid=image_uuid) print_fn(' Image already present locally, skipping...') continue except Image.DoesNotExist: print_fn(' Image not found in local DB, creating now...') retrieved_image = requests.get(image_data['image'], headers=headers) Image.from_json(ingredient, retrieved_image, image_data) print_fn(style_fn(' successfully saved')) def sync_ingredients( print_fn, remote_url=settings.WGER_SETTINGS['WGER_INSTANCE'], style_fn=lambda x: x, ): """Synchronize the ingredients from the remote server""" print_fn('*** Synchronizing ingredients...') url = make_uri(INGREDIENTS_ENDPOINT, server_url=remote_url, query={'limit': API_MAX_ITEMS}) for data in get_paginated(url, headers=wger_headers()): uuid = data['uuid'] name = data['name'] ingredient, created = Ingredient.objects.update_or_create( uuid=uuid, defaults={ 'name': name, 'code': data['code'], 'language_id': data['language'], 'created': data['created'], 'license_id': data['license'], 'license_object_url': data['license_object_url'], 'license_author': data['license_author_url'], 'license_author_url': data['license_author_url'], 'license_title': data['license_title'], 'license_derivative_source_url': data['license_derivative_source_url'], 'energy': data['energy'], 'carbohydrates': data['carbohydrates'], 'carbohydrates_sugar': data['carbohydrates_sugar'], 'fat': data['fat'], 'fat_saturated': data['fat_saturated'], 'protein': data['protein'], 'fiber': data['fiber'], 'sodium': data['sodium'], }, ) print_fn(f"{'created' if created else 'updated'} ingredient {uuid} - {name}") print_fn(style_fn('done!\n'))
8,856
Python
.py
216
34.041667
100
0.659807
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,526
urls.py
wger-project_wger/wger/nutrition/urls.py
# -*- coding: utf-8 -*- # 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/>. # Django from django.conf.urls import include from django.contrib.auth.decorators import login_required from django.urls import ( path, re_path, ) # wger from wger.core.views.react import ReactView from wger.nutrition.views import ( bmi, calculator, ingredient, plan, unit, unit_ingredient, ) # sub patterns for nutritional plans patterns_plan = [ path( 'overview/', ReactView.as_view(login_required=True), name='overview', ), path( '<int:id>/view/', ReactView.as_view(login_required=True), name='view', ), path( '<int:pk>/copy', plan.copy, name='copy', ), path( '<int:id>/pdf', plan.export_pdf, name='export-pdf', ), ] # sub patterns for ingredient patterns_ingredient = [ path( '<int:pk>/delete/', ingredient.IngredientDeleteView.as_view(), name='delete', ), path( '<int:pk>/edit/', ingredient.IngredientEditView.as_view(), name='edit', ), path( 'add/', login_required(ingredient.IngredientCreateView.as_view()), name='add', ), path( 'overview/', ingredient.IngredientListView.as_view(), name='list', ), path( '<int:pk>/view/', ingredient.view, name='view', ), path( '<int:pk>/view/<slug:slug>/', ingredient.view, name='view', ), ] # sub patterns for weight units patterns_weight_unit = [ path( 'list/', unit.WeightUnitListView.as_view(), name='list', ), path( 'add/', unit.WeightUnitCreateView.as_view(), name='add', ), path( '<int:pk>/delete/', unit.WeightUnitDeleteView.as_view(), name='delete', ), path( '<int:pk>/edit/', unit.WeightUnitUpdateView.as_view(), name='edit', ), ] # sub patterns for weight units / ingredient cross table patterns_unit_ingredient = [ path( 'add/<int:ingredient_pk>/', unit_ingredient.WeightUnitIngredientCreateView.as_view(), name='add', ), path( '<int:pk>/edit/', unit_ingredient.WeightUnitIngredientUpdateView.as_view(), name='edit', ), path( '<int:pk>/delete/', unit_ingredient.WeightUnitIngredientDeleteView.as_view(), name='delete', ), ] # sub patterns for BMI calculator patterns_bmi = [ path( '', bmi.view, name='view', ), path( 'calculate', bmi.calculate, name='calculate', ), path( 'chart-data', bmi.chart_data, name='chart-data', ), # JS ] # sub patterns for calories calculator patterns_calories = [ path( '', calculator.view, name='view', ), path( 'bmr', calculator.calculate_bmr, name='bmr', ), path( 'activities', calculator.calculate_activities, name='activities', ), # JS ] urlpatterns = [ path( '', include( (patterns_plan, 'plan'), namespace='plan', ), ), path( 'ingredient/', include( (patterns_ingredient, 'ingredient'), namespace='ingredient', ), ), path( 'unit/', include( (patterns_weight_unit, 'weight_unit'), namespace='weight_unit', ), ), path( 'unit-to-ingredient/', include( (patterns_unit_ingredient, 'unit_ingredient'), namespace='unit_ingredient', ), ), path( 'calculator/bmi/', include( (patterns_bmi, 'bmi'), namespace='bmi', ), ), path( 'calculator/calories/', include( (patterns_calories, 'calories'), namespace='calories', ), ), ]
4,757
Python
.py
209
16.425837
78
0.568878
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,527
tasks.py
wger-project_wger/wger/nutrition/tasks.py
# 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 # Standard Library import logging from random import ( choice, randint, ) # Django from django.conf import settings from django.core.management import call_command # Third Party from celery.schedules import crontab # wger from wger.celery_configuration import app from wger.nutrition.sync import ( download_ingredient_images, fetch_ingredient_image, sync_ingredients, ) logger = logging.getLogger(__name__) @app.task def fetch_ingredient_image_task(pk: int): """ Fetches the ingredient image from Open Food Facts servers if it is not available locally Returns the image if it is already present in the DB """ fetch_ingredient_image(pk) @app.task def fetch_all_ingredient_images_task(): """ Fetches the ingredient image from Open Food Facts servers if it is not available locally Returns the image if it is already present in the DB """ download_ingredient_images(logger.info) @app.task def sync_all_ingredients_task(): """ Fetches the current ingredients from the default wger instance """ sync_ingredients(logger.info) @app.task def sync_off_daily_delta(): """ Fetches OFF's daily delta product updates """ call_command('import-off-products', '--delta-updates') @app.on_after_finalize.connect def setup_periodic_tasks(sender, **kwargs): if settings.WGER_SETTINGS['SYNC_INGREDIENTS_CELERY']: sender.add_periodic_task( crontab( hour=str(randint(0, 23)), minute=str(randint(0, 59)), day_of_month=str(randint(1, 28)), month_of_year=choice(['1, 4, 7, 10', '2, 5, 8, 11', '3, 6, 9, 12']), ), sync_all_ingredients_task.s(), name='Sync ingredients', ) if settings.WGER_SETTINGS['SYNC_OFF_DAILY_DELTA_CELERY']: sender.add_periodic_task( crontab( hour=str(randint(0, 23)), minute=str(randint(0, 59)), ), sync_off_daily_delta.s(), name='Sync OFF daily delta updates', )
2,742
Python
.py
80
28.9875
92
0.687855
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,528
apps.py
wger-project_wger/wger/nutrition/apps.py
# -*- coding: utf-8 -*- # 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 # Django from django.apps import AppConfig class NutritionConfig(AppConfig): name = 'wger.nutrition' verbose_name = 'Nutrition' def ready(self): import wger.nutrition.signals
863
Python
.py
21
38.904762
78
0.771804
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,529
sitemap.py
wger-project_wger/wger/nutrition/sitemap.py
# -*- coding: utf-8 -*- # 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 # Django from django.contrib.sitemaps import Sitemap # wger from wger.nutrition.models import Ingredient class NutritionSitemap(Sitemap): changefreq = 'monthly' priority = 0.5 def items(self): return Ingredient.objects.all() def lastmod(self, obj): return obj.last_update
974
Python
.py
25
36.4
78
0.767516
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,530
__init__.py
wger-project_wger/wger/nutrition/__init__.py
# -*- coding: utf-8 -*- # 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 import get_version VERSION = get_version() default_app_config = 'wger.nutrition.apps.NutritionConfig'
861
Python
.py
19
44.105263
78
0.778043
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,531
consts.py
wger-project_wger/wger/nutrition/consts.py
# This file is part of wger Workout Manager <https://github.com/wger-project>. # Copyright (C) 2013 - 2021 wger Team # # 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. MEALITEM_WEIGHT_GRAM = '1' MEALITEM_WEIGHT_UNIT = '2' ENERGY_FACTOR = { 'protein': {'kg': 4, 'lb': 113}, 'carbohydrates': {'kg': 4, 'lb': 113}, 'fat': {'kg': 9, 'lb': 225}, } """ Simple approximation of energy (kcal) provided per gram or ounce """ KJ_PER_KCAL = 4.184
1,085
Python
.py
26
40.153846
79
0.725379
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,532
dataclasses.py
wger-project_wger/wger/nutrition/dataclasses.py
# 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 # Standard Library from dataclasses import ( asdict, dataclass, ) from typing import Optional @dataclass class IngredientData: name: str remote_id: str language_id: int energy: float protein: float carbohydrates: float carbohydrates_sugar: Optional[float] fat: float fat_saturated: Optional[float] fiber: Optional[float] sodium: Optional[float] code: Optional[str] source_name: str source_url: str common_name: str brand: str license_id: int license_author: str license_title: str license_object_url: str def sanity_checks(self): if not self.name: raise ValueError(f'Name is empty!') self.name = self.name[:200] self.brand = self.brand[:200] self.common_name = self.common_name[:200] macros = [ 'protein', 'fat', 'fat_saturated', 'carbohydrates', 'carbohydrates_sugar', 'sodium', 'fiber', ] for macro in macros: value = getattr(self, macro) if value and value > 100: raise ValueError(f'Value for {macro} is greater than 100: {value}') if self.carbohydrates + self.protein + self.fat > 100: raise ValueError(f'Total of carbohydrates, protein and fat is greater than 100!') def dict(self): return asdict(self)
2,070
Python
.py
64
26.296875
93
0.666833
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,533
helpers.py
wger-project_wger/wger/nutrition/helpers.py
# This file is part of wger Workout Manager <https://github.com/wger-project>. # Copyright (C) 2013 - 2021 wger Team # # 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Standard Library from dataclasses import ( asdict, dataclass, ) from decimal import Decimal from typing import Union # wger from wger.nutrition.consts import ( KJ_PER_KCAL, MEALITEM_WEIGHT_GRAM, MEALITEM_WEIGHT_UNIT, ) class BaseMealItem: """ Base class for an item (component) of a meal or log This just provides some common helper functions """ def get_unit_type(self): """ Returns the type of unit used: - a value in grams - a 'human' unit like 'a cup' or 'a slice' """ if self.weight_unit: return MEALITEM_WEIGHT_UNIT else: return MEALITEM_WEIGHT_GRAM def get_nutritional_values(self, use_metric=True): """ Sums the nutritional info for the ingredient in the MealItem :param use_metric Flag that controls the units used """ values = NutritionalValues() # Calculate the base weight of the item if self.get_unit_type() == MEALITEM_WEIGHT_GRAM: item_weight = self.amount else: item_weight = self.amount * self.weight_unit.amount * self.weight_unit.gram values.energy = self.ingredient.energy * item_weight / 100 values.protein = self.ingredient.protein * item_weight / 100 values.carbohydrates = self.ingredient.carbohydrates * item_weight / 100 values.fat = self.ingredient.fat * item_weight / 100 if self.ingredient.carbohydrates_sugar: values.carbohydrates_sugar = self.ingredient.carbohydrates_sugar * item_weight / 100 if self.ingredient.fat_saturated: values.fat_saturated = self.ingredient.fat_saturated * item_weight / 100 if self.ingredient.fiber: values.fiber = self.ingredient.fiber * item_weight / 100 if self.ingredient.sodium: values.sodium = self.ingredient.sodium * item_weight / 100 # # If necessary, convert weight units # if not use_metric: # for key, value in nutritional_info.items(): # # # Energy is not a weight! # if key == 'energy': # continue # # # Everything else, to ounces # nutritional_info[key] = AbstractWeight(value, 'g').oz # # nutritional_info['energy_kilojoule'] = Decimal(nutritional_info['energy']) * Decimal(4.184) # Only 2 decimal places, anything else doesn't make sense # for i in nutritional_info: # nutritional_info[i] = Decimal(nutritional_info[i]).quantize(TWOPLACES) return values @dataclass class NutritionalValues: # TODO: replace the Union with | when we drop support for python 3.9 energy: Union[Decimal, int, float] = 0 protein: Union[Decimal, int, float] = 0 carbohydrates: Union[Decimal, int, float] = 0 carbohydrates_sugar: Union[Decimal, int, float, None] = None fat: Union[Decimal, int, float] = 0 fat_saturated: Union[Decimal, int, float, None] = None fiber: Union[Decimal, int, float, None] = None sodium: Union[Decimal, int, float, None] = None @property def energy_kilojoule(self): return self.energy * KJ_PER_KCAL def __add__(self, other: 'NutritionalValues'): """ Allow adding nutritional values """ return NutritionalValues( energy=self.energy + other.energy, protein=self.protein + other.protein, carbohydrates=self.carbohydrates + other.carbohydrates, carbohydrates_sugar=self.carbohydrates_sugar + other.carbohydrates_sugar if self.carbohydrates_sugar and other.carbohydrates_sugar else self.carbohydrates_sugar or other.carbohydrates_sugar, fat=self.fat + other.fat, fat_saturated=self.fat_saturated + other.fat_saturated if self.fat_saturated and other.fat_saturated else self.fat_saturated or other.fat_saturated, fiber=self.fiber + other.fiber if self.fiber and other.fiber else self.fiber or other.fiber, sodium=self.sodium + other.sodium if self.sodium and other.sodium else self.sodium or other.sodium, ) @property def to_dict(self): return asdict(self)
5,165
Python
.py
121
35.239669
101
0.657171
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,534
forms.py
wger-project_wger/wger/nutrition/forms.py
# -*- coding: utf-8 -*- # 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 # Standard Library import logging from datetime import datetime from decimal import Decimal # Django from django import forms from django.forms import BooleanField from django.urls import reverse from django.utils.translation import ( gettext as _, gettext_lazy, ) # Third Party from crispy_forms.helper import FormHelper from crispy_forms.layout import ( HTML, ButtonHolder, Column, Layout, Row, Submit, ) # wger from wger.core.models import UserProfile from wger.nutrition.models import ( Ingredient, IngredientWeightUnit, LogItem, Meal, MealItem, ) from wger.utils.widgets import Html5NumberInput logger = logging.getLogger(__name__) class UnitChooserForm(forms.Form): """ A small form to select an amount and a unit for an ingredient """ amount = forms.DecimalField( decimal_places=2, label=gettext_lazy('Amount'), max_digits=5, localize=True ) unit = forms.ModelChoiceField( queryset=IngredientWeightUnit.objects.none(), label=gettext_lazy('Unit'), empty_label='g', required=False, ) def __init__(self, *args, **kwargs): super(UnitChooserForm, self).__init__(*args, **kwargs) if len(args) and args[0].get('ingredient'): ingredient_id = args[0]['ingredient'] elif kwargs.get('data'): ingredient_id = kwargs['data']['ingredient_id'] else: ingredient_id = -1 self.fields['unit'].queryset = IngredientWeightUnit.objects.filter( ingredient_id=ingredient_id ).select_related() self.helper = FormHelper() self.helper.layout = Layout( Row( Column('amount', css_class='col-6'), Column('unit', css_class='col-6'), css_class='form-row', ) ) self.helper.form_tag = False class BmiForm(forms.ModelForm): height = forms.DecimalField( widget=Html5NumberInput(), max_value=Decimal(999), ) weight = forms.DecimalField( widget=Html5NumberInput(), max_value=Decimal(999), ) class Meta: model = UserProfile fields = ('height',) def __init__(self, *args, **kwargs): super(BmiForm, self).__init__(*args, **kwargs) if 'initial' in kwargs: # if the form is rendering for the first time self['height'].label = ( _('Height (cm)') if kwargs['initial']['use_metric'] else _('Height (in)') ) self['weight'].label = ( _('Weight (kg)') if kwargs['initial']['use_metric'] else _('Weight (lbs)') ) self.helper = FormHelper() self.helper.form_action = reverse('nutrition:bmi:calculate') self.helper.form_class = 'wger-form' self.helper.form_id = 'bmi-form' self.helper.layout = Layout( Row( Column('height', css_class='col-6'), Column('weight', css_class='col-6'), css_class='form-row', ), ButtonHolder(Submit('submit', _('Calculate'), css_class='btn-success')), ) class BmrForm(forms.ModelForm): """ Form for the basal metabolic rate """ weight = forms.DecimalField(widget=Html5NumberInput()) class Meta: model = UserProfile fields = ('age', 'height', 'gender') def __init__(self, *args, **kwargs): super(BmrForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( 'age', 'height', 'gender', 'weight', ) self.helper.form_tag = False class PhysicalActivitiesForm(forms.ModelForm): """ Form for the additional physical activities """ class Meta: model = UserProfile fields = ( 'sleep_hours', 'work_hours', 'work_intensity', 'sport_hours', 'sport_intensity', 'freetime_hours', 'freetime_intensity', ) def __init__(self, *args, **kwargs): super(PhysicalActivitiesForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( 'sleep_hours', Row( Column('work_hours', css_class='col-6'), Column('work_intensity', css_class='col-6'), css_class='form-row', ), Row( Column('sport_hours', css_class='col-6'), Column('sport_intensity', css_class='col-6'), css_class='form-row', ), Row( Column('freetime_hours', css_class='col-6'), Column('freetime_intensity', css_class='col-6'), css_class='form-row', ), ) self.helper.form_tag = False class DailyCaloriesForm(forms.ModelForm): """ Form for the total daily calories needed """ base_calories = forms.IntegerField( label=_('Basic caloric intake'), help_text=_('Your basic caloric intake as calculated for ' 'your data'), required=False, widget=Html5NumberInput(), ) additional_calories = forms.IntegerField( label=_('Additional calories'), help_text=_( 'Additional calories to add to the base ' 'rate (to substract, enter a negative ' 'number)' ), initial=0, required=False, widget=Html5NumberInput(), ) class Meta: model = UserProfile fields = ('calories',) def __init__(self, *args, **kwargs): super(DailyCaloriesForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False class MealItemForm(forms.ModelForm): weight_unit = forms.ModelChoiceField( queryset=IngredientWeightUnit.objects.none(), empty_label='g', required=False, ) ingredient = forms.ModelChoiceField( queryset=Ingredient.objects.all(), widget=forms.HiddenInput, ) ingredient_searchfield = forms.CharField( required=False, label=gettext_lazy('Ingredient'), ) english_results = BooleanField( label=gettext_lazy('Also search for names in English'), initial=True, required=False, ) class Meta: model = MealItem fields = [ 'ingredient', 'english_results', 'weight_unit', 'amount', ] def __init__(self, *args, **kwargs): super(MealItemForm, self).__init__(*args, **kwargs) # Get the ingredient_id ingredient_id = None if kwargs.get('instance'): ingredient_id = kwargs['instance'].ingredient_id if kwargs.get('data'): ingredient_id = kwargs['data']['ingredient'] # Filter the available ingredients if ingredient_id: self.fields['weight_unit'].queryset = IngredientWeightUnit.objects.filter( ingredient_id=ingredient_id ) self.helper = FormHelper() self.helper.layout = Layout( 'ingredient', 'ingredient_searchfield', 'english_results', HTML('<div id="ingredient_name"></div>'), Row( Column('amount', css_class='col-6'), Column('weight_unit', css_class='col-6'), css_class='form-row', ), ) class MealLogItemForm(MealItemForm): datetime_format = '%Y-%m-%dT%H:%M' now = datetime.now().strftime(datetime_format) datetime = forms.DateTimeField( input_formats=[datetime_format], widget=forms.DateTimeInput( attrs={'type': 'datetime-local', 'class': 'form-control', 'value': now}, format=datetime_format, ), ) class Meta: model = LogItem fields = [ 'ingredient', 'weight_unit', 'amount', 'datetime', ] def __init__(self, *args, **kwargs): super(MealLogItemForm, self).__init__(*args, **kwargs) self.helper.layout = Layout( 'ingredient', 'ingredient_searchfield', 'english_results', Row( Column('amount', css_class='col-6'), Column('weight_unit', css_class='col-6'), ), Row(Column('datetime', css_class='col-6'), css_class='form-row'), ) class IngredientForm(forms.ModelForm): class Meta: model = Ingredient fields = [ 'name', 'brand', 'energy', 'protein', 'carbohydrates', 'carbohydrates_sugar', 'fat', 'fat_saturated', 'fiber', 'sodium', 'license', 'license_author', ] widgets = {'category': forms.TextInput} def __init__(self, *args, **kwargs): super(IngredientForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Row( Column('name', css_class='col-6'), Column('brand', css_class='col-6'), css_class='form-row', ), 'energy', 'protein', Row( Column('carbohydrates', css_class='col-6'), Column('carbohydrates_sugar', css_class='col-6'), css_class='form-row', ), Row( Column('fat', css_class='col-6'), Column('fat_saturated', css_class='col-6'), css_class='form-row', ), 'fiber', 'sodium', Row( Column('license', css_class='col-6'), Column('license_author', css_class='col-6'), css_class='form-row', ), )
10,751
Python
.py
325
23.843077
90
0.560324
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,535
off.py
wger-project_wger/wger/nutrition/off.py
# This file is part of wger Workout Manager <https://github.com/wger-project>. # # 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # wger from wger.nutrition.consts import KJ_PER_KCAL from wger.nutrition.dataclasses import IngredientData from wger.nutrition.models import Source from wger.utils.constants import ODBL_LICENSE_ID OFF_REQUIRED_TOP_LEVEL = [ 'product_name', 'code', 'nutriments', ] OFF_REQUIRED_NUTRIMENTS = [ 'proteins_100g', 'carbohydrates_100g', 'fat_100g', ] def extract_info_from_off(product_data: dict, language: int) -> IngredientData: if not all(req in product_data for req in OFF_REQUIRED_TOP_LEVEL): raise KeyError('Missing required top-level key') if not all(req in product_data['nutriments'] for req in OFF_REQUIRED_NUTRIMENTS): raise KeyError('Missing required nutrition key') # Basics name = product_data.get('product_name') common_name = product_data.get('generic_name', '') # If the energy is not available in kcal, convert from kJ if 'energy-kcal_100g' in product_data['nutriments']: energy = product_data['nutriments']['energy-kcal_100g'] elif 'energy-kj_100g' in product_data['nutriments']: energy = product_data['nutriments']['energy-kj_100g'] / KJ_PER_KCAL else: raise KeyError('Energy is not available') code = product_data['code'] protein = product_data['nutriments']['proteins_100g'] carbs = product_data['nutriments']['carbohydrates_100g'] fat = product_data['nutriments']['fat_100g'] # these are optional saturated = product_data['nutriments'].get('saturated-fat_100g', None) sodium = product_data['nutriments'].get('sodium_100g', None) sugars = product_data['nutriments'].get('sugars_100g', None) fiber = product_data['nutriments'].get('fiber_100g', None) brand = product_data.get('brands', '') # License and author info source_name = Source.OPEN_FOOD_FACTS.value source_url = f'https://world.openfoodfacts.org/api/v2/product/{code}.json' authors = ', '.join(product_data.get('editors_tags', ['open food facts'])) object_url = f'https://world.openfoodfacts.org/product/{code}/' ingredient_data = IngredientData( remote_id=code, name=name, language_id=language, energy=energy, protein=protein, carbohydrates=carbs, carbohydrates_sugar=sugars, fat=fat, fat_saturated=saturated, fiber=fiber, sodium=sodium, code=code, source_name=source_name, source_url=source_url, common_name=common_name, brand=brand, license_id=ODBL_LICENSE_ID, license_author=authors, license_title=name, license_object_url=object_url, ) ingredient_data.sanity_checks() return ingredient_data
3,481
Python
.py
83
36.746988
85
0.699055
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,536
usda.py
wger-project_wger/wger/nutrition/usda.py
# This file is part of wger Workout Manager <https://github.com/wger-project>. # # 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # wger from wger.nutrition.dataclasses import IngredientData from wger.nutrition.models import Source from wger.utils.constants import CC_0_LICENSE_ID def convert_to_grams(entry: dict) -> float: """ Convert a nutrient entry to grams """ nutrient = entry['nutrient'] amount = float(entry['amount']) if nutrient['unitName'] == 'g': return amount elif nutrient['unitName'] == 'mg': return amount / 1000 else: raise ValueError(f'Unknown unit: {nutrient["unitName"]}') def extract_info_from_usda(product_data: dict, language: int) -> IngredientData: if not product_data.get('foodNutrients'): raise KeyError('Missing key "foodNutrients"') remote_id = str(product_data['fdcId']) barcode = None energy = None protein = None carbs = None carbs_sugars = None fats = None fats_saturated = None sodium = None fiber = None brand = product_data.get('brandName', '') for nutrient in product_data['foodNutrients']: if not nutrient.get('nutrient'): raise KeyError('Missing key "nutrient"') nutrient_id = nutrient['nutrient']['id'] match nutrient_id: # in kcal case 1008: energy = float(nutrient.get('amount')) case 1003: protein = convert_to_grams(nutrient) case 1005: carbs = convert_to_grams(nutrient) # Total lipid (fat) | Total fat (NLEA) case 1004 | 1085: fats = convert_to_grams(nutrient) case 1093: sodium = convert_to_grams(nutrient) case 1079: fiber = convert_to_grams(nutrient) macros = [energy, protein, carbs, fats] for value in macros: if value is None: raise KeyError(f'Could not extract all basic macros: {macros=} {remote_id=}') name = product_data['description'].title() # License and author info source_name = Source.USDA.value source_url = f'https://fdc.nal.usda.gov/' author = ( 'U.S. Department of Agriculture, Agricultural Research Service, ' 'Beltsville Human Nutrition Research Center. FoodData Central.' ) object_url = f'https://fdc.nal.usda.gov/fdc-app.html#/food-details/{remote_id}/nutrients' ingredient_data = IngredientData( code=barcode, remote_id=remote_id, name=name, common_name=name, language_id=language, energy=energy, protein=protein, carbohydrates=carbs, carbohydrates_sugar=carbs_sugars, fat=fats, fat_saturated=fats_saturated, fiber=fiber, sodium=sodium, source_name=source_name, source_url=source_url, brand=brand, license_id=CC_0_LICENSE_ID, license_author=author, license_title=name, license_object_url=object_url, ) ingredient_data.sanity_checks() return ingredient_data
3,778
Python
.py
100
30.62
93
0.651888
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,537
managers.py
wger-project_wger/wger/nutrition/managers.py
# This file is part of wger Workout Manager <https://github.com/wger-project>. # Copyright (C) wger Team # # 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Django from django.conf import settings from django.db import connections from django.db.models import ( Manager, QuerySet, ) # wger from wger.utils.db import is_postgres_db class ApproximateCountQuerySet(QuerySet): """ Approximate count query set, postgreSQL only While this doesn't return an exact count, it does return an approximate in a much shorter amount of time, which is specially important for the ingredients https://testdriven.io/blog/django-approximate-counting/ """ def count(self): if self.query.where: return super(ApproximateCountQuerySet, self).count() if is_postgres_db() and not settings.TESTING: cursor = connections[self.db].cursor() cursor.execute( "SELECT reltuples FROM pg_class WHERE relname = '%s';" % self.model._meta.db_table ) return int(cursor.fetchone()[0]) return super(ApproximateCountQuerySet, self).count() ApproximateCountManager = Manager.from_queryset(ApproximateCountQuerySet)
1,861
Python
.py
43
38.744186
98
0.732558
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,538
sources.py
wger-project_wger/wger/nutrition/models/sources.py
# This file is part of wger Workout Manager <https://github.com/wger-project>. # # 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Standard Library from enum import Enum class Source(Enum): WGER = 'wger' OPEN_FOOD_FACTS = 'Open Food Facts' USDA = 'USDA'
903
Python
.py
20
43.4
79
0.757955
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,539
weight_unit.py
wger-project_wger/wger/nutrition/models/weight_unit.py
# This file is part of wger Workout Manager <https://github.com/wger-project>. # Copyright (C) 2013 - 2021 wger Team # # 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Django from django.db import models from django.utils.translation import gettext_lazy as _ # wger from wger.core.models import Language class WeightUnit(models.Model): """ A more human usable weight unit (spoon, table, slice...) """ language = models.ForeignKey( Language, verbose_name=_('Language'), editable=False, on_delete=models.CASCADE, ) name = models.CharField( max_length=200, verbose_name=_('Name'), ) # Metaclass to set some other properties class Meta: ordering = [ 'name', ] def __str__(self): """ Return a more human-readable representation """ return self.name def get_owner_object(self): """ Weight unit has no owner information """ return None
1,657
Python
.py
49
28.897959
79
0.68125
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,540
ingredient.py
wger-project_wger/wger/nutrition/models/ingredient.py
# This file is part of wger Workout Manager <https://github.com/wger-project>. # Copyright (C) 2013 - 2021 wger Team # # 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Standard Library import logging import uuid as uuid from decimal import Decimal from json import JSONDecodeError # Django from django.conf import settings from django.contrib.postgres.indexes import GinIndex from django.core.cache import cache from django.core.exceptions import ValidationError from django.core.validators import ( MaxValueValidator, MinLengthValidator, MinValueValidator, ) from django.db import models from django.http import HttpRequest from django.urls import reverse from django.utils.text import slugify from django.utils.translation import gettext_lazy as _ # Third Party from openfoodfacts import API from requests import ( ConnectTimeout, HTTPError, ReadTimeout, ) # wger from wger.core.models import Language from wger.nutrition.consts import ( ENERGY_FACTOR, KJ_PER_KCAL, ) from wger.nutrition.managers import ApproximateCountManager from wger.nutrition.models.ingredient_category import IngredientCategory from wger.nutrition.models.sources import Source from wger.utils.cache import cache_mapper from wger.utils.constants import TWOPLACES from wger.utils.language import load_language from wger.utils.models import AbstractLicenseModel from wger.utils.requests import wger_user_agent logger = logging.getLogger(__name__) class Ingredient(AbstractLicenseModel, models.Model): """ An ingredient, with some approximate nutrition values """ ENERGY_APPROXIMATION = 15 """ How much the calculated energy from protein, etc. can deviate from the energy amount given (in percent). """ objects = ApproximateCountManager() language = models.ForeignKey( Language, verbose_name=_('Language'), editable=False, on_delete=models.CASCADE, ) created = models.DateTimeField( _('Date'), auto_now_add=True, ) """Date when the ingredient was created""" last_update = models.DateTimeField( _('Date'), auto_now=True, blank=True, editable=False, ) """Last update time""" uuid = models.UUIDField( default=uuid.uuid4, unique=True, editable=False, verbose_name='UUID', ) """Globally unique ID, to identify the ingredient across installations""" # Product infos name = models.CharField( max_length=200, verbose_name=_('Name'), validators=[MinLengthValidator(3)], ) energy = models.IntegerField( verbose_name=_('Energy'), help_text=_('In kcal per 100g'), ) protein = models.DecimalField( decimal_places=3, max_digits=6, verbose_name=_('Protein'), help_text=_('In g per 100g of product'), validators=[MinValueValidator(Decimal(0)), MaxValueValidator(Decimal(100))], ) carbohydrates = models.DecimalField( decimal_places=3, max_digits=6, verbose_name=_('Carbohydrates'), help_text=_('In g per 100g of product'), validators=[MinValueValidator(Decimal(0)), MaxValueValidator(Decimal(100))], ) carbohydrates_sugar = models.DecimalField( decimal_places=3, max_digits=6, blank=True, null=True, verbose_name=_('Sugar content in carbohydrates'), help_text=_('In g per 100g of product'), validators=[MinValueValidator(Decimal(0)), MaxValueValidator(Decimal(100))], ) fat = models.DecimalField( decimal_places=3, max_digits=6, verbose_name=_('Fat'), help_text=_('In g per 100g of product'), validators=[MinValueValidator(Decimal(0)), MaxValueValidator(Decimal(100))], ) fat_saturated = models.DecimalField( decimal_places=3, max_digits=6, blank=True, null=True, verbose_name=_('Saturated fat content in fats'), help_text=_('In g per 100g of product'), validators=[MinValueValidator(Decimal(0)), MaxValueValidator(Decimal(100))], ) fiber = models.DecimalField( decimal_places=3, max_digits=6, blank=True, null=True, verbose_name=_('Fiber'), help_text=_('In g per 100g of product'), validators=[MinValueValidator(Decimal(0)), MaxValueValidator(Decimal(100))], ) sodium = models.DecimalField( decimal_places=3, max_digits=6, blank=True, null=True, verbose_name=_('Sodium'), help_text=_('In g per 100g of product'), validators=[MinValueValidator(Decimal(0)), MaxValueValidator(Decimal(100))], ) code = models.CharField( max_length=200, null=True, blank=True, db_index=True, ) """The product's barcode""" remote_id = models.CharField( max_length=200, null=True, blank=True, db_index=True, ) """ID of the product in the external source database. Used for updated during imports.""" source_name = models.CharField( max_length=200, null=True, blank=True, ) """Name of the source, such as Open Food Facts""" source_url = models.URLField( verbose_name=_('Link'), help_text=_('Link to product'), blank=True, null=True, ) """URL of the product at the source""" last_imported = models.DateTimeField( _('Date'), auto_now_add=True, null=True, blank=True, ) common_name = models.CharField( max_length=200, null=True, blank=True, ) category = models.ForeignKey( IngredientCategory, verbose_name=_('Category'), on_delete=models.CASCADE, null=True, blank=True, ) brand = models.CharField( max_length=200, verbose_name=_('Brand name of product'), null=True, blank=True, ) # Metaclass to set some other properties class Meta: ordering = [ 'name', ] indexes = (GinIndex(fields=['name']),) # # Django methods # def get_absolute_url(self): """ Returns the canonical URL to view this object. Since some names consist of only non-ascii characters (e.g. 감자깡), the resulting slug would be empty and no URL would match. In that case, use the regular URL with only the ID. """ slug = slugify(self.name) if not slug: return reverse('nutrition:ingredient:view', kwargs={'pk': self.id}) else: return reverse('nutrition:ingredient:view', kwargs={'pk': self.id, 'slug': slug}) def clean(self): """ Do a very broad sanity check on the nutritional values according to the following rules: - 1g of protein: 4kcal - 1g of carbohydrates: 4kcal - 1g of fat: 9kcal The sum is then compared to the given total energy, with ENERGY_APPROXIMATION percent tolerance. """ # Note: calculations in 100 grams, to save us the '/100' everywhere energy_protein = 0 if self.protein: energy_protein = self.protein * ENERGY_FACTOR['protein']['kg'] energy_carbohydrates = 0 if self.carbohydrates: energy_carbohydrates = self.carbohydrates * ENERGY_FACTOR['carbohydrates']['kg'] energy_fat = 0 if self.fat: # TODO: for some reason, during the tests the fat value is not # converted to decimal (django 1.9) energy_fat = Decimal(self.fat * ENERGY_FACTOR['fat']['kg']) energy_calculated = energy_protein + energy_carbohydrates + energy_fat # Compare the values, but be generous if self.energy: energy_upper = self.energy * (1 + (self.ENERGY_APPROXIMATION / Decimal(100.0))) energy_lower = self.energy * (1 - (self.ENERGY_APPROXIMATION / Decimal(100.0))) if not ((energy_upper > energy_calculated) and (energy_calculated > energy_lower)): raise ValidationError( _( f'The total energy ({self.energy}kcal) is not the approximate sum of the ' f'energy provided by protein, carbohydrates and fat ({energy_calculated}kcal' f' +/-{self.ENERGY_APPROXIMATION}%)' ) ) def save(self, *args, **kwargs): """ Reset the cache """ super(Ingredient, self).save(*args, **kwargs) cache.delete(cache_mapper.get_ingredient_key(self.id)) def __str__(self): """ Return a more human-readable representation """ return self.name def __eq__(self, other): """ Compare ingredients based on their values, not like django on their PKs """ logger.debug('Overwritten behaviour: comparing ingredients on values, not PK.') equal = True if isinstance(other, self.__class__): for i in ( 'carbohydrates', 'carbohydrates_sugar', 'creation_date', 'energy', 'fat', 'fat_saturated', 'fiber', 'name', 'protein', 'sodium', ): if ( hasattr(self, i) and hasattr(other, i) and (getattr(self, i, None) != getattr(other, i, None)) ): equal = False else: equal = False return equal def __hash__(self): """ Define a hash function This is rather unnecessary, but it seems that newer versions of django have a problem when the __eq__ function is implemented, but not the __hash__ one. Returning hash(pk) is also django's default. :return: hash(pk) """ return hash(self.pk) # # Own methods # def set_author(self, request): if not self.license_author: self.license_author = request.get_host().split(':')[0] def get_owner_object(self): """ Ingredient has no owner information """ return False @property def energy_kilojoule(self): """ returns kilojoules for current ingredient, 0 if energy is uninitialized """ if self.energy: return Decimal(self.energy * KJ_PER_KCAL).quantize(TWOPLACES) else: return 0 @property def off_link(self): if self.source_name == Source.OPEN_FOOD_FACTS.value: return f'https://world.openfoodfacts.org/product/{self.code}/' def get_image(self, request: HttpRequest): """ Returns the ingredient image If it is not available locally, it is fetched from Open Food Facts servers """ if hasattr(self, 'image'): return self.image if not request.user.is_authenticated: return if not settings.WGER_SETTINGS['USE_CELERY']: logger.info('Celery deactivated, skipping retrieving ingredient image') return # Let celery fetch the image # wger from wger.nutrition.tasks import fetch_ingredient_image_task fetch_ingredient_image_task.delay(self.pk) @classmethod def fetch_ingredient_from_off(cls, code: str): """ Searches OFF by barcode and creates a local ingredient from the result """ # wger from wger.nutrition.off import extract_info_from_off logger.info(f'Searching for ingredient {code} in OFF') try: api = API(user_agent=wger_user_agent(), timeout=3) result = api.product.get(code) except JSONDecodeError as e: logger.info(f'Got JSONDecodeError from OFF: {e}') return None except (ReadTimeout, ConnectTimeout): logger.info('Timeout from OFF') return None except HTTPError as e: logger.info(f'Got HTTPError from OFF: {e}') return None if not result: logger.info('Product not found') return None try: ingredient_data = extract_info_from_off(result, load_language(result['lang']).pk) except (KeyError, ValueError) as e: logger.debug(f'Error extracting data from OFF: {e}') return None if not ingredient_data.name: return if not ingredient_data.common_name: return ingredient = cls(**ingredient_data.dict()) ingredient.save() logger.info(f'Ingredient found and saved to local database: {ingredient.uuid}') return ingredient
13,635
Python
.py
390
26.74359
101
0.618147
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,541
__init__.py
wger-project_wger/wger/nutrition/models/__init__.py
# This file is part of wger Workout Manager <https://github.com/wger-project>. # Copyright (C) 2013 - 2021 wger Team # # 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Local from .image import Image from .ingredient import Ingredient from .ingredient_category import IngredientCategory from .ingredient_weight_unit import IngredientWeightUnit from .log import LogItem from .meal import Meal from .meal_item import MealItem from .plan import NutritionPlan from .sources import Source from .weight_unit import WeightUnit
1,156
Python
.py
26
43.423077
79
0.795394
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,542
log.py
wger-project_wger/wger/nutrition/models/log.py
# This file is part of wger Workout Manager <https://github.com/wger-project>. # Copyright (C) 2013 - 2021 wger Team # # 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Standard Library from decimal import Decimal # Django from django.core.validators import ( MaxValueValidator, MinValueValidator, ) from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ # wger from wger.nutrition.helpers import BaseMealItem # Local from .ingredient import Ingredient from .ingredient_weight_unit import IngredientWeightUnit from .meal import Meal from .plan import NutritionPlan class LogItem(BaseMealItem, models.Model): """ An item (component) of a log """ # Metaclass to set some other properties class Meta: ordering = [ '-datetime', ] plan = models.ForeignKey( NutritionPlan, verbose_name=_('Nutrition plan'), on_delete=models.CASCADE, ) """ The plan this log belongs to """ meal = models.ForeignKey( Meal, verbose_name=_('Meal'), on_delete=models.SET_NULL, related_name='log_items', blank=True, null=True, ) """ The meal this log belongs to (optional) """ datetime = models.DateTimeField(verbose_name=_('Date and Time (Approx.)'), default=timezone.now) """ Time and date when the log was added """ comment = models.TextField( verbose_name=_('Comment'), blank=True, null=True, ) """ Comment field, for additional information """ ingredient = models.ForeignKey( Ingredient, verbose_name=_('Ingredient'), on_delete=models.CASCADE, ) """ Ingredient """ weight_unit = models.ForeignKey( IngredientWeightUnit, verbose_name=_('Weight unit'), null=True, blank=True, on_delete=models.CASCADE, ) """ Weight unit used (grams, slices, etc.) """ amount = models.DecimalField( decimal_places=2, max_digits=6, verbose_name=_('Amount'), validators=[MinValueValidator(Decimal(1)), MaxValueValidator(Decimal(1000))], ) """ The amount of units """ def __str__(self): """ Return a more human-readable representation """ return f'Diary entry for {self.datetime}, plan {self.plan.pk}' def get_owner_object(self): """ Returns the object that has owner information """ return self.plan
3,224
Python
.py
109
24.247706
100
0.66344
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,543
ingredient_weight_unit.py
wger-project_wger/wger/nutrition/models/ingredient_weight_unit.py
# This file is part of wger Workout Manager <https://github.com/wger-project>. # Copyright (C) 2013 - 2021 wger Team # # 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Standard Library import logging # Django from django.db import models from django.utils.translation import gettext_lazy as _ # Local from .ingredient import Ingredient from .weight_unit import WeightUnit logger = logging.getLogger(__name__) class IngredientWeightUnit(models.Model): """ A specific human usable weight unit for an ingredient """ ingredient = models.ForeignKey( Ingredient, verbose_name=_('Ingredient'), editable=False, on_delete=models.CASCADE, ) unit = models.ForeignKey( WeightUnit, verbose_name=_('Weight unit'), on_delete=models.CASCADE, ) gram = models.IntegerField(verbose_name=_('Amount in grams')) amount = models.DecimalField( decimal_places=2, max_digits=5, default=1, verbose_name=_('Amount'), help_text=_('Unit amount, e.g. "1 Cup" or "1/2 spoon"'), ) def get_owner_object(self): """ Weight unit has no owner information """ return None def __str__(self): """ Return a more human-readable representation """ return f'{self.amount if self.amount > 1 else ""}{self.unit.name} ({self.gram}g)'
2,042
Python
.py
57
30.964912
89
0.688292
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,544
meal.py
wger-project_wger/wger/nutrition/models/meal.py
# This file is part of wger Workout Manager <https://github.com/wger-project>. # Copyright (C) 2013 - 2021 wger Team # # 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Standard Library import logging # Django from django.db import models from django.utils.translation import gettext_lazy as _ # wger from wger.utils.fields import Html5TimeField # Local from ..helpers import NutritionalValues from .plan import NutritionPlan logger = logging.getLogger(__name__) class Meal(models.Model): """ A meal """ # Metaclass to set some other properties class Meta: ordering = [ 'time', ] plan = models.ForeignKey( NutritionPlan, verbose_name=_('Nutrition plan'), editable=False, on_delete=models.CASCADE, ) order = models.IntegerField( verbose_name=_('Order'), blank=True, editable=False, ) time = Html5TimeField( null=True, blank=True, verbose_name=_('Time (approx)'), ) name = models.CharField( max_length=25, blank=True, verbose_name=_('Name'), help_text=_( 'Give meals a textual description / name such as "Breakfast" or "after workout"' ), ) def __str__(self): """ Return a more human-readable representation """ return f'{self.order} Meal' def get_owner_object(self): """ Returns the object that has owner information """ return self.plan def get_nutritional_values(self, use_metric=True): """ Sums the nutritional info of all items in the meal :param: use_metric Flag that controls the units used """ nutritional_values = NutritionalValues() for item in self.mealitem_set.select_related(): nutritional_values += item.get_nutritional_values(use_metric=use_metric) return nutritional_values
2,595
Python
.py
78
27.5
92
0.667333
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,545
plan.py
wger-project_wger/wger/nutrition/models/plan.py
# This file is part of wger Workout Manager <https://github.com/wger-project>. # Copyright (C) 2013 - 2021 wger Team # # 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Standard Library import datetime import logging from decimal import Decimal # Django from django.contrib.auth.models import User from django.core.cache import cache from django.db import models from django.urls import reverse from django.utils.translation import gettext_lazy as _ # wger from wger.nutrition.consts import ENERGY_FACTOR from wger.nutrition.helpers import NutritionalValues from wger.utils.cache import cache_mapper from wger.utils.constants import TWOPLACES from wger.weight.models import WeightEntry logger = logging.getLogger(__name__) class NutritionPlan(models.Model): """ A nutrition plan """ # Metaclass to set some other properties class Meta: # Order by creation_date, descending (oldest first) ordering = [ '-creation_date', ] user = models.ForeignKey( User, verbose_name=_('User'), editable=False, on_delete=models.CASCADE, ) creation_date = models.DateField( _('Creation date'), auto_now_add=True, ) description = models.CharField( max_length=80, blank=True, verbose_name=_('Description'), help_text=_( 'A description of the goal of the plan, e.g. ' '"Gain mass" or "Prepare for summer"' ), ) only_logging = models.BooleanField( verbose_name='Only logging', default=False, ) """Flag to indicate that the nutritional plan will only used for logging""" goal_energy = models.IntegerField(null=True, default=None) goal_protein = models.IntegerField(null=True, default=None) goal_carbohydrates = models.IntegerField(null=True, default=None) goal_fiber = models.IntegerField(null=True, default=None) goal_fat = models.IntegerField(null=True, default=None) has_goal_calories = models.BooleanField( verbose_name=_('Use daily calories'), default=False, help_text=_( 'Tick the box if you want to mark this ' 'plan as having a goal amount of calories. ' 'You can use the calculator or enter the ' 'value yourself.' ), ) """A flag indicating whether the plan has a goal amount of calories""" def __str__(self): """ Return a more human-readable representation """ if self.description: return self.description else: return str(_('Nutrition plan')) def get_absolute_url(self): """ Returns the canonical URL to view this object """ return reverse('nutrition:plan:view', kwargs={'id': self.id}) def get_nutritional_values(self): """ Sums the nutritional info of all items in the plan """ nutritional_representation = cache.get(cache_mapper.get_nutrition_cache_by_key(self.pk)) 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}, 'per_kg': {'protein': 0, 'carbohydrates': 0, 'fat': 0}, } # Energy for meal in self.meal_set.select_related(): nutritional_values += meal.get_nutritional_values(use_metric=use_metric) result['total'] = nutritional_values energy = nutritional_values.energy # In percent if energy: result['percent']['protein'] = ( nutritional_values.protein * ENERGY_FACTOR['protein'][unit] / energy * 100 ) result['percent']['carbohydrates'] = ( nutritional_values.carbohydrates * ENERGY_FACTOR['carbohydrates'][unit] / energy * 100 ) result['percent']['fat'] = ( nutritional_values.fat * ENERGY_FACTOR['fat'][unit] / energy * 100 ) # Per body weight weight_entry = self.get_closest_weight_entry() if weight_entry and weight_entry.weight: result['per_kg']['protein'] = nutritional_values.protein / weight_entry.weight result['per_kg']['carbohydrates'] = ( nutritional_values.carbohydrates / weight_entry.weight ) result['per_kg']['fat'] = nutritional_values.fat / weight_entry.weight nutritional_representation = result cache.set(cache_mapper.get_nutrition_cache_by_key(self.pk), nutritional_representation) return nutritional_representation def get_closest_weight_entry(self): """ Returns the closest weight entry for the nutrition plan. Returns None if there are no entries. """ target = self.creation_date closest_entry_gte = ( WeightEntry.objects.filter(user=self.user) .filter(date__gte=target) .order_by('date') .first() ) closest_entry_lte = ( WeightEntry.objects.filter(user=self.user) .filter(date__lte=target) .order_by('-date') .first() ) if closest_entry_gte is None or closest_entry_lte is None: return closest_entry_gte or closest_entry_lte if abs(closest_entry_gte.date - target) < abs(closest_entry_lte.date - target): return closest_entry_gte else: return closest_entry_lte def get_owner_object(self): """ Returns the object that has owner information """ return self def get_calories_approximation(self): """ Calculates the deviation from the goal calories and the actual amount of the current plan """ goal_calories = self.user.userprofile.calories actual_calories = self.get_nutritional_values()['total']['energy'] # Within 3% if (actual_calories < goal_calories * 1.03) and (actual_calories > goal_calories * 0.97): return 1 # within 7% elif (actual_calories < goal_calories * 1.07) and (actual_calories > goal_calories * 0.93): return 2 # within 10% elif (actual_calories < goal_calories * 1.10) and (actual_calories > goal_calories * 0.9): return 3 # even more else: return 4 def get_log_entries(self, date=None): """ Convenience function that returns the log entries for a given date """ if not date: date = datetime.date.today() return self.logitem_set.filter(datetime__date=date).select_related()
7,706
Python
.py
193
30.880829
99
0.61738
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,546
meal_item.py
wger-project_wger/wger/nutrition/models/meal_item.py
# This file is part of wger Workout Manager <https://github.com/wger-project>. # Copyright (C) 2013 - 2021 wger Team # # 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Standard Library import logging from decimal import Decimal # Django from django.core.validators import ( MaxValueValidator, MinValueValidator, ) from django.db import models from django.utils.translation import gettext_lazy as _ # wger from wger.nutrition.helpers import BaseMealItem # Local from .ingredient import Ingredient from .ingredient_weight_unit import IngredientWeightUnit from .meal import Meal logger = logging.getLogger(__name__) class MealItem(BaseMealItem, models.Model): """ An item (component) of a meal """ meal = models.ForeignKey( Meal, verbose_name=_('Nutrition plan'), editable=False, on_delete=models.CASCADE, ) ingredient = models.ForeignKey( Ingredient, verbose_name=_('Ingredient'), on_delete=models.CASCADE, ) weight_unit = models.ForeignKey( IngredientWeightUnit, verbose_name=_('Weight unit'), null=True, blank=True, on_delete=models.CASCADE, ) order = models.IntegerField( verbose_name=_('Order'), blank=True, editable=False, ) amount = models.DecimalField( decimal_places=2, max_digits=6, verbose_name=_('Amount'), validators=[MinValueValidator(Decimal(1)), MaxValueValidator(Decimal(1000))], ) def __str__(self): """ Return a more human-readable representation """ return f'{self.amount}g ingredient {self.ingredient_id}' def get_owner_object(self): """ Returns the object that has owner information """ return self.meal.plan
2,460
Python
.py
75
27.853333
85
0.695744
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,547
ingredient_category.py
wger-project_wger/wger/nutrition/models/ingredient_category.py
# This file is part of wger Workout Manager <https://github.com/wger-project>. # Copyright (C) 2013 - 2021 wger Team # # 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Django from django.db import models from django.utils.translation import gettext_lazy as _ class IngredientCategory(models.Model): """ Model for an Ingredient category """ name = models.CharField(max_length=100, verbose_name=_('Name')) # Metaclass to set some other properties class Meta: verbose_name_plural = _('Ingredient Categories') ordering = [ 'name', ] def __str__(self): """ Return a more human-readable representation """ return self.name def get_owner_object(self): """ Category has no owner information """ return False
1,475
Python
.py
39
33.25641
79
0.69979
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,548
image.py
wger-project_wger/wger/nutrition/models/image.py
# This file is part of wger Workout Manager <https://github.com/wger-project>. # Copyright (C) 2013 - 2021 wger Team # # 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Standard Library import pathlib import uuid # Django from django.db import models from django.utils.translation import gettext_lazy as _ # wger from wger.core.models import License from wger.utils.helpers import BaseImage from wger.utils.models import AbstractLicenseModel def ingredient_image_upload_dir(instance, filename): """ Returns the upload target for exercise images """ ext = pathlib.Path(filename).suffix return f'ingredients/{instance.ingredient.pk}/{instance.uuid}{ext}' class Image(AbstractLicenseModel, models.Model, BaseImage): """ Model for an ingredient image """ uuid = models.UUIDField( default=uuid.uuid4, unique=True, editable=False, verbose_name='UUID', ) """Globally unique ID, to identify the image across installations""" ingredient = models.OneToOneField( 'Ingredient', null=True, on_delete=models.CASCADE, ) """Image for this ingredient""" image = models.ImageField( verbose_name=_('Image'), help_text=_('Only PNG and JPEG formats are supported'), upload_to=ingredient_image_upload_dir, height_field='height', width_field='width', ) """Uploaded image""" created = models.DateTimeField(auto_now_add=True) """The date when this image was first created """ last_update = models.DateTimeField(auto_now=True) """The date when this image was last synchronized """ size = models.IntegerField() """The size of the image in bytes""" height = models.IntegerField(editable=False) """Height of the image""" width = models.IntegerField(editable=False) """Width of the image""" @classmethod def from_json( cls, connect_to, retrieved_image, json_data: dict, generate_uuid: bool = False, ): image: cls = super().from_json(connect_to, retrieved_image, json_data, generate_uuid) image.ingredient = connect_to image.license_id = json_data['license'] image.license_title = json_data['license_title'] image.license_object_url = json_data['license_object_url'] image.license_author = json_data['license_author'] image.license_author_url = json_data['license_author_url'] image.license_derivative_source_url = json_data['license_derivative_source_url'] image.size = json_data['size'] image.save_image(retrieved_image, json_data) image.save() connect_to.image = image connect_to.save() return image
3,395
Python
.py
88
33.170455
93
0.69425
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,549
0013_ingredient_image.py
wger-project_wger/wger/nutrition/migrations/0013_ingredient_image.py
# Generated by Django 3.2.14 on 2022-08-09 12:33 from django.db import migrations, models import django.db.models.deletion import uuid import wger.nutrition.models.image import wger.utils.helpers def noop(apps, schema_editor): pass def generate_uuids(apps, schema_editor): """ Generate new UUIDs for each exercise :param apps: :param schema_editor: :return: """ Ingredient = apps.get_model('nutrition', 'Ingredient') for ingredient in Ingredient.objects.all(): ingredient.uuid = uuid.uuid4() ingredient.save(update_fields=['uuid']) class Migration(migrations.Migration): dependencies = [ ('core', '0013_auto_20210726_1729'), ('nutrition', '0012_alter_ingredient_license_author'), ] operations = [ migrations.AddField( model_name='ingredient', name='uuid', field=models.UUIDField( default=uuid.uuid4, editable=False, verbose_name='UUID', ), ), migrations.CreateModel( name='Image', fields=[ ( 'id', models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name='ID', ), ), ( 'license_author', models.CharField( blank=True, help_text='If you are not the author, enter the name or source here. This ' 'is needed for some licenses e.g. the CC-BY-SA.', max_length=60, null=True, verbose_name='Author', ), ), ( 'uuid', models.UUIDField( default=uuid.uuid4, editable=False, unique=True, verbose_name='UUID', ), ), ( 'image', models.ImageField( help_text='Only PNG and JPEG formats are supported', upload_to=wger.nutrition.models.image.ingredient_image_upload_dir, verbose_name='Image', height_field='height', width_field='width', ), ), ('created', models.DateTimeField(auto_now_add=True)), ('last_update', models.DateTimeField(auto_now=True)), ('size', models.IntegerField()), ('height', models.IntegerField(editable=False)), ('width', models.IntegerField(editable=False)), ( 'ingredient', models.OneToOneField( null=True, on_delete=django.db.models.deletion.CASCADE, to='nutrition.ingredient', ), ), ( 'license', models.ForeignKey( default=2, on_delete=django.db.models.deletion.CASCADE, to='core.license', verbose_name='License', ), ), ], options={ 'abstract': False, }, bases=(models.Model, wger.utils.helpers.BaseImage), ), migrations.RunPython(generate_uuids, reverse_code=noop), migrations.AlterField( model_name='ingredient', name='uuid', field=models.UUIDField( default=uuid.uuid4, editable=False, unique=True, verbose_name='UUID', ), ), ]
4,064
Python
.py
116
19.37931
99
0.443655
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,550
0005_logitem.py
wger-project_wger/wger/nutrition/migrations/0005_logitem.py
# Generated by Django 3.1 on 2020-08-25 10:29 import django.core.validators from django.db import migrations, models import django.db.models.deletion import wger.nutrition.models class Migration(migrations.Migration): dependencies = [ ('nutrition', '0004_auto_20200819_2310'), ] operations = [ migrations.CreateModel( name='LogItem', fields=[ ( 'id', models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name='ID' ), ), ('datetime', models.DateTimeField(auto_now=True)), ('comment', models.TextField(blank=True, null=True, verbose_name='Comment')), ( 'amount', models.DecimalField( decimal_places=2, max_digits=6, validators=[ django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(1000), ], verbose_name='Amount', ), ), ( 'ingredient', models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, to='nutrition.ingredient', verbose_name='Ingredient', ), ), ( 'plan', models.ForeignKey( editable=False, on_delete=django.db.models.deletion.CASCADE, to='nutrition.nutritionplan', verbose_name='Nutrition plan', ), ), ( 'weight_unit', models.ForeignKey( blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='nutrition.ingredientweightunit', verbose_name='Weight unit', ), ), ], options={ 'ordering': ['datetime'], }, bases=(wger.nutrition.helpers.BaseMealItem, models.Model), ), ]
2,469
Python
.py
67
19.253731
95
0.423686
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,551
0003_auto_20170118_2308.py
wger-project_wger/wger/nutrition/migrations/0003_auto_20170118_2308.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.11 on 2017-01-18 22:08 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('nutrition', '0002_auto_20170101_1538'), ] operations = [ migrations.RemoveField( model_name='ingredient', name='user', ), ]
356
Python
.py
13
21.153846
49
0.60472
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,552
0023_fiber_spelling.py
wger-project_wger/wger/nutrition/migrations/0023_fiber_spelling.py
# Generated by Django 4.2.6 on 2024-05-21 19:32 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('nutrition', '0022_add_remote_id_increase_author_field_length'), ] operations = [ migrations.RenameField( model_name='ingredient', old_name='fibres', new_name='fiber', ), migrations.RenameField( model_name='nutritionplan', old_name='goal_fibers', new_name='goal_fiber', ), ]
545
Python
.py
18
21.944444
73
0.586998
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,553
0017_remove_nutritionplan_language_alter_logitem_meal.py
wger-project_wger/wger/nutrition/migrations/0017_remove_nutritionplan_language_alter_logitem_meal.py
# Generated by Django 4.1.9 on 2023-09-27 20:13 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('nutrition', '0016_alter_logitem_options_and_more'), ] operations = [ migrations.RemoveField( model_name='nutritionplan', name='language', ), migrations.AlterField( model_name='logitem', name='meal', field=models.ForeignKey( blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='log_items', to='nutrition.meal', verbose_name='Meal', ), ), migrations.AddField( model_name='nutritionplan', name='only_logging', field=models.BooleanField(default=False, verbose_name='Only logging'), ), ]
973
Python
.py
30
22.1
82
0.559105
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,554
0006_auto_20201201_0653.py
wger-project_wger/wger/nutrition/migrations/0006_auto_20201201_0653.py
# Generated by Django 3.1.3 on 2020-12-01 05:53 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('nutrition', '0005_logitem'), ] operations = [ migrations.AlterField( model_name='logitem', name='datetime', field=models.DateTimeField(default=django.utils.timezone.now), ), ]
432
Python
.py
14
24.142857
74
0.649758
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,555
0016_alter_logitem_options_and_more.py
wger-project_wger/wger/nutrition/migrations/0016_alter_logitem_options_and_more.py
# Generated by Django 4.1.9 on 2023-07-27 07:43 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('nutrition', '0015_alter_ingredient_creation_date_and_more'), ] operations = [ migrations.AlterModelOptions( name='logitem', options={'ordering': ['-datetime']}, ), migrations.RenameField( model_name='ingredient', old_name='creation_date', new_name='created', ), migrations.RenameField( model_name='ingredient', old_name='update_date', new_name='last_update', ), ]
675
Python
.py
22
21.863636
70
0.57319
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,556
0015_alter_ingredient_creation_date_and_more.py
wger-project_wger/wger/nutrition/migrations/0015_alter_ingredient_creation_date_and_more.py
# Generated by Django 4.1.7 on 2023-06-08 11:20 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('nutrition', '0014_license_information'), ] operations = [ migrations.AlterField( model_name='ingredient', name='creation_date', field=models.DateTimeField(auto_now_add=True, verbose_name='Date'), ), migrations.AlterField( model_name='ingredient', name='update_date', field=models.DateTimeField(auto_now=True, verbose_name='Date'), ), ]
615
Python
.py
18
25.833333
79
0.615514
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,557
0024_remove_ingredient_status.py
wger-project_wger/wger/nutrition/migrations/0024_remove_ingredient_status.py
# Generated by Django 4.2.13 on 2024-05-24 17:28 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('nutrition', '0023_fiber_spelling'), ] operations = [ migrations.RemoveField( model_name='ingredient', name='status', ), migrations.AlterField( model_name='image', name='license_author', field=models.TextField( blank=True, help_text='If you are not the author, enter the name or source here.', max_length=3500, null=True, verbose_name='Author(s)', ), ), migrations.AlterField( model_name='ingredient', name='fiber', field=models.DecimalField( blank=True, decimal_places=3, help_text='In g per 100g of product', max_digits=6, null=True, validators=[ django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(100), ], verbose_name='Fiber', ), ), migrations.AlterField( model_name='ingredient', name='license_author', field=models.TextField( blank=True, help_text='If you are not the author, enter the name or source here.', max_length=3500, null=True, verbose_name='Author(s)', ), ), ]
1,677
Python
.py
51
20.352941
86
0.503083
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,558
0010_logitem_meal.py
wger-project_wger/wger/nutrition/migrations/0010_logitem_meal.py
# Generated by Django 3.2.7 on 2021-10-03 19:00 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('nutrition', '0009_meal_name'), ] operations = [ migrations.AddField( model_name='logitem', name='meal', field=models.ForeignKey( blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='log_items', to='nutrition.meal', verbose_name='Meal', ), ), ]
641
Python
.py
21
20.571429
60
0.548701
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,559
0018_nutritionplan_goal_carbs_nutritionplan_goal_energy_and_more.py
wger-project_wger/wger/nutrition/migrations/0018_nutritionplan_goal_carbs_nutritionplan_goal_energy_and_more.py
# Generated by Django 4.1.9 on 2023-09-29 21:05 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('nutrition', '0017_remove_nutritionplan_language_alter_logitem_meal'), ] operations = [ migrations.AddField( model_name='nutritionplan', name='goal_carbohydrates', field=models.IntegerField(default=None, null=True), ), migrations.AddField( model_name='nutritionplan', name='goal_energy', field=models.IntegerField(default=None, null=True), ), migrations.AddField( model_name='nutritionplan', name='goal_fat', field=models.IntegerField(default=None, null=True), ), migrations.AddField( model_name='nutritionplan', name='goal_protein', field=models.IntegerField(default=None, null=True), ), ]
973
Python
.py
28
25.321429
79
0.603613
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,560
0001_initial.py
wger-project_wger/wger/nutrition/migrations/0001_initial.py
# -*- coding: utf-8 -*- from django.db import models, migrations import wger.utils.fields from django.conf import settings import django.core.validators class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('core', '0001_initial'), ] operations = [ migrations.CreateModel( name='Ingredient', fields=[ ( 'id', models.AutoField( verbose_name='ID', serialize=False, auto_created=True, primary_key=True ), ), ( 'license_author', models.CharField( help_text='If you are not the author, enter the name or source here. This is needed for some licenses e.g. the CC-BY-SA.', max_length=50, null=True, verbose_name='Author', blank=True, ), ), ( 'status', models.CharField( default=b'1', max_length=2, editable=False, choices=[ (b'1', 'Pending'), (b'2', 'Accepted'), (b'3', 'Declined'), (b'4', 'Submitted by administrator'), (b'5', 'System ingredient'), ], ), ), ('creation_date', models.DateField(auto_now_add=True, verbose_name='Date')), ('update_date', models.DateField(auto_now=True, verbose_name='Date')), ('name', models.CharField(max_length=200, verbose_name='Name')), ( 'energy', models.IntegerField(help_text='In kcal per 100g', verbose_name='Energy'), ), ( 'protein', models.DecimalField( help_text='In g per 100g of product', verbose_name='Protein', max_digits=6, decimal_places=3, validators=[ django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(100), ], ), ), ( 'carbohydrates', models.DecimalField( help_text='In g per 100g of product', verbose_name='Carbohydrates', max_digits=6, decimal_places=3, validators=[ django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(100), ], ), ), ( 'carbohydrates_sugar', models.DecimalField( decimal_places=3, validators=[ django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(100), ], max_digits=6, blank=True, help_text='In g per 100g of product', null=True, verbose_name='Sugar content in carbohydrates', ), ), ( 'fat', models.DecimalField( help_text='In g per 100g of product', verbose_name='Fat', max_digits=6, decimal_places=3, validators=[ django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(100), ], ), ), ( 'fat_saturated', models.DecimalField( decimal_places=3, validators=[ django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(100), ], max_digits=6, blank=True, help_text='In g per 100g of product', null=True, verbose_name='Saturated fat content in fats', ), ), ( 'fibres', models.DecimalField( decimal_places=3, validators=[ django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(100), ], max_digits=6, blank=True, help_text='In g per 100g of product', null=True, verbose_name='Fibres', ), ), ( 'sodium', models.DecimalField( decimal_places=3, validators=[ django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(100), ], max_digits=6, blank=True, help_text='In g per 100g of product', null=True, verbose_name='Sodium', ), ), ( 'language', models.ForeignKey( editable=False, to='core.Language', verbose_name='Language', on_delete=models.CASCADE, ), ), ( 'license', models.ForeignKey( default=2, verbose_name='License', to='core.License', on_delete=models.CASCADE, ), ), ( 'user', models.ForeignKey( blank=True, editable=False, to=settings.AUTH_USER_MODEL, null=True, verbose_name='User', on_delete=models.CASCADE, ), ), ], options={ 'ordering': ['name'], }, bases=(models.Model,), ), migrations.CreateModel( name='IngredientWeightUnit', fields=[ ( 'id', models.AutoField( verbose_name='ID', serialize=False, auto_created=True, primary_key=True ), ), ('gram', models.IntegerField(verbose_name='Amount in grams')), ( 'amount', models.DecimalField( default=1, help_text='Unit amount, e.g. "1 Cup" or "1/2 spoon"', verbose_name='Amount', max_digits=5, decimal_places=2, ), ), ( 'ingredient', models.ForeignKey( editable=False, to='nutrition.Ingredient', verbose_name='Ingredient', on_delete=models.CASCADE, ), ), ], options={}, bases=(models.Model,), ), migrations.CreateModel( name='Meal', fields=[ ( 'id', models.AutoField( verbose_name='ID', serialize=False, auto_created=True, primary_key=True ), ), ( 'order', models.IntegerField( verbose_name='Order', max_length=1, editable=False, blank=True ), ), ( 'time', wger.utils.fields.Html5TimeField( null=True, verbose_name='Time (approx)', blank=True ), ), ], options={ 'ordering': ['time'], }, bases=(models.Model,), ), migrations.CreateModel( name='MealItem', fields=[ ( 'id', models.AutoField( verbose_name='ID', serialize=False, auto_created=True, primary_key=True ), ), ( 'order', models.IntegerField( verbose_name='Order', max_length=1, editable=False, blank=True ), ), ( 'amount', models.DecimalField( verbose_name='Amount', max_digits=6, decimal_places=2, validators=[ django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(1000), ], ), ), ( 'ingredient', models.ForeignKey( verbose_name='Ingredient', to='nutrition.Ingredient', on_delete=models.CASCADE, ), ), ( 'meal', models.ForeignKey( editable=False, to='nutrition.Meal', verbose_name='Nutrition plan', on_delete=models.CASCADE, ), ), ( 'weight_unit', models.ForeignKey( verbose_name='Weight unit', blank=True, to='nutrition.IngredientWeightUnit', null=True, on_delete=models.CASCADE, ), ), ], options={}, bases=(models.Model,), ), migrations.CreateModel( name='NutritionPlan', fields=[ ( 'id', models.AutoField( verbose_name='ID', serialize=False, auto_created=True, primary_key=True ), ), ( 'creation_date', models.DateField(auto_now_add=True, verbose_name='Creation date'), ), ( 'description', models.TextField( help_text='A description of the goal of the plan, e.g. "Gain mass" or "Prepare for summer"', max_length=2000, verbose_name='Description', blank=True, ), ), ( 'has_goal_calories', models.BooleanField( default=False, help_text='Tick the box if you want to mark this plan as having a goal amount of calories. You can use the calculator or enter the value yourself.', verbose_name='Use daily calories', ), ), ( 'language', models.ForeignKey( editable=False, to='core.Language', verbose_name='Language', on_delete=models.CASCADE, ), ), ( 'user', models.ForeignKey( editable=False, to=settings.AUTH_USER_MODEL, verbose_name='User', on_delete=models.CASCADE, ), ), ], options={ 'ordering': ['-creation_date'], }, bases=(models.Model,), ), migrations.CreateModel( name='WeightUnit', fields=[ ( 'id', models.AutoField( verbose_name='ID', serialize=False, auto_created=True, primary_key=True ), ), ('name', models.CharField(max_length=200, verbose_name='Name')), ( 'language', models.ForeignKey( editable=False, to='core.Language', verbose_name='Language', on_delete=models.CASCADE, ), ), ], options={ 'ordering': ['name'], }, bases=(models.Model,), ), migrations.AddField( model_name='meal', name='plan', field=models.ForeignKey( editable=False, to='nutrition.NutritionPlan', verbose_name='Nutrition plan', on_delete=models.CASCADE, ), preserve_default=True, ), migrations.AddField( model_name='ingredientweightunit', name='unit', field=models.ForeignKey( verbose_name='Weight unit', to='nutrition.WeightUnit', on_delete=models.CASCADE ), preserve_default=True, ), ]
14,916
Python
.py
403
16.995037
172
0.362327
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,561
0004_auto_20200819_2310.py
wger-project_wger/wger/nutrition/migrations/0004_auto_20200819_2310.py
# Generated by Django 3.1 on 2020-08-19 21:10 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('nutrition', '0003_auto_20170118_2308'), ] operations = [ migrations.AlterField( model_name='nutritionplan', name='description', field=models.CharField( blank=True, help_text='A description of the goal of the plan, e.g. "Gain mass" or "Prepare for summer"', max_length=80, verbose_name='Description', ), ), ]
609
Python
.py
18
24.166667
108
0.572402
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,562
0011_alter_logitem_datetime.py
wger-project_wger/wger/nutrition/migrations/0011_alter_logitem_datetime.py
# Generated by Django 3.2.13 on 2022-05-16 09:27 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('nutrition', '0010_logitem_meal'), ] operations = [ migrations.AlterField( model_name='logitem', name='datetime', field=models.DateTimeField( default=django.utils.timezone.now, verbose_name='Date and Time (Approx.)' ), ), ]
508
Python
.py
16
24
89
0.618852
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,563
0014_license_information.py
wger-project_wger/wger/nutrition/migrations/0014_license_information.py
# Generated by Django 4.2 on 2023-04-07 15:11 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('nutrition', '0013_ingredient_image'), ] operations = [ migrations.AddField( model_name='image', name='license_author_url', field=models.URLField( blank=True, max_length=100, verbose_name='Link to author profile, if available', ), ), migrations.AddField( model_name='image', name='license_derivative_source_url', field=models.URLField( blank=True, help_text='Note that a derivative work is one which is not only based on a ' 'previous work, but which also contains sufficient new, creative ' 'content to entitle it to its own copyright.', max_length=100, verbose_name='Link to the original source, if this is a derivative work', ), ), migrations.AddField( model_name='image', name='license_object_url', field=models.URLField( blank=True, max_length=100, verbose_name='Link to original object, if available', ), ), migrations.AddField( model_name='image', name='license_title', field=models.CharField( blank=True, max_length=200, verbose_name='The original title of this object, if available', ), ), migrations.AddField( model_name='ingredient', name='license_author_url', field=models.URLField( blank=True, max_length=100, verbose_name='Link to author profile, if available', ), ), migrations.AddField( model_name='ingredient', name='license_derivative_source_url', field=models.URLField( blank=True, help_text='Note that a derivative work is one which is not only based on a ' 'previous work, but which also contains sufficient new, creative ' 'content to entitle it to its own copyright.', max_length=100, verbose_name='Link to the original source, if this is a derivative work', ), ), migrations.AddField( model_name='ingredient', name='license_object_url', field=models.URLField( blank=True, max_length=100, verbose_name='Link to original object, if available', ), ), migrations.AddField( model_name='ingredient', name='license_title', field=models.CharField( blank=True, max_length=200, verbose_name='The original title of this object, if available', ), ), migrations.AlterField( model_name='image', name='license_author', field=models.CharField( blank=True, help_text='If you are not the author, enter the name or source here.', max_length=200, null=True, verbose_name='Author(s)', ), ), migrations.AlterField( model_name='ingredient', name='license_author', field=models.CharField( blank=True, help_text='If you are not the author, enter the name or source here.', max_length=200, null=True, verbose_name='Author(s)', ), ), ]
3,885
Python
.py
108
22.861111
92
0.513385
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,564
0019_alter_image_license_author_and_more.py
wger-project_wger/wger/nutrition/migrations/0019_alter_image_license_author_and_more.py
# Generated by Django 4.2.6 on 2023-11-23 19:46 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('nutrition', '0018_nutritionplan_goal_carbs_nutritionplan_goal_energy_and_more'), ] operations = [ migrations.AlterField( model_name='image', name='license_author', field=models.CharField( blank=True, help_text='If you are not the author, enter the name or source here.', max_length=600, null=True, verbose_name='Author(s)', ), ), migrations.AlterField( model_name='image', name='license_author_url', field=models.URLField(blank=True, verbose_name='Link to author profile, if available'), ), migrations.AlterField( model_name='image', name='license_derivative_source_url', field=models.URLField( blank=True, help_text='Note that a derivative work is one which is not only based on a previous work, but which also contains sufficient new, creative content to entitle it to its own copyright.', verbose_name='Link to the original source, if this is a derivative work', ), ), migrations.AlterField( model_name='image', name='license_object_url', field=models.URLField(blank=True, verbose_name='Link to original object, if available'), ), migrations.AlterField( model_name='image', name='license_title', field=models.CharField( blank=True, max_length=300, verbose_name='The original title of this object, if available', ), ), migrations.AlterField( model_name='ingredient', name='license_author', field=models.CharField( blank=True, help_text='If you are not the author, enter the name or source here.', max_length=600, null=True, verbose_name='Author(s)', ), ), migrations.AlterField( model_name='ingredient', name='license_author_url', field=models.URLField(blank=True, verbose_name='Link to author profile, if available'), ), migrations.AlterField( model_name='ingredient', name='license_derivative_source_url', field=models.URLField( blank=True, help_text='Note that a derivative work is one which is not only based on a previous work, but which also contains sufficient new, creative content to entitle it to its own copyright.', verbose_name='Link to the original source, if this is a derivative work', ), ), migrations.AlterField( model_name='ingredient', name='license_object_url', field=models.URLField(blank=True, verbose_name='Link to original object, if available'), ), migrations.AlterField( model_name='ingredient', name='license_title', field=models.CharField( blank=True, max_length=300, verbose_name='The original title of this object, if available', ), ), ]
3,490
Python
.py
86
28.27907
200
0.564412
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,565
0008_auto_20210102_1446.py
wger-project_wger/wger/nutrition/migrations/0008_auto_20210102_1446.py
# Generated by Django 3.1.3 on 2021-01-02 13:46 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('nutrition', '0007_auto_20201214_0013'), ] operations = [ migrations.AlterField( model_name='ingredient', name='code', field=models.CharField(blank=True, db_index=True, max_length=200, null=True), ), migrations.AlterField( model_name='ingredient', name='common_name', field=models.CharField(blank=True, max_length=200, null=True), ), migrations.AlterField( model_name='ingredient', name='source_name', field=models.CharField(blank=True, max_length=200, null=True), ), migrations.AlterField( model_name='logitem', name='plan', field=models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, to='nutrition.nutritionplan', verbose_name='Nutrition plan', ), ), ]
1,140
Python
.py
33
24.575758
89
0.581142
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,566
0020_full_text_search.py
wger-project_wger/wger/nutrition/migrations/0020_full_text_search.py
# Generated by Django 3.2.15 on 2022-12-07 19:31 import django.contrib.postgres.indexes import django.contrib.postgres.search from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('nutrition', '0019_alter_image_license_author_and_more'), ] operations = [ migrations.AddIndex( model_name='ingredient', index=django.contrib.postgres.indexes.GinIndex( fields=['name'], name='nutrition_i_search__f274b7_gin' ), ), ]
552
Python
.py
16
27.5
70
0.659774
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,567
0009_meal_name.py
wger-project_wger/wger/nutrition/migrations/0009_meal_name.py
# Generated by Django 3.2.6 on 2021-08-22 20:45 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('nutrition', '0008_auto_20210102_1446'), ] operations = [ migrations.AddField( model_name='meal', name='name', field=models.CharField( blank=True, help_text='Give meals a textual description / name such as "Breakfast" or "after workout"', max_length=25, verbose_name='Name', ), ), ]
585
Python
.py
18
22.833333
107
0.559503
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,568
0007_auto_20201214_0013.py
wger-project_wger/wger/nutrition/migrations/0007_auto_20201214_0013.py
# Generated by Django 3.1.4 on 2020-12-13 23:13 import django.core.validators from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('nutrition', '0006_auto_20201201_0653'), ] operations = [ migrations.CreateModel( name='IngredientCategory', fields=[ ( 'id', models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name='ID' ), ), ('name', models.CharField(max_length=100, verbose_name='Name')), ], options={ 'verbose_name_plural': 'Ingredient Categories', 'ordering': ['name'], }, ), migrations.AddField( model_name='ingredient', name='brand', field=models.CharField( blank=True, max_length=200, null=True, verbose_name='Brand name of product' ), ), migrations.AddField( model_name='ingredient', name='code', field=models.CharField(blank=True, max_length=200, null=True, verbose_name='Name'), ), migrations.AddField( model_name='ingredient', name='common_name', field=models.CharField( blank=True, max_length=200, null=True, verbose_name='Common name of product' ), ), migrations.AddField( model_name='ingredient', name='last_imported', field=models.DateTimeField(auto_now_add=True, null=True, verbose_name='Date'), ), migrations.AddField( model_name='ingredient', name='source_name', field=models.CharField( blank=True, max_length=200, null=True, verbose_name='Source Name' ), ), migrations.AddField( model_name='ingredient', name='source_url', field=models.URLField( blank=True, help_text='Link to product', null=True, verbose_name='Link' ), ), migrations.AlterField( model_name='ingredient', name='name', field=models.CharField( max_length=200, validators=[django.core.validators.MinLengthValidator(3)], verbose_name='Name', ), ), migrations.AddField( model_name='ingredient', name='category', field=models.ForeignKey( blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='nutrition.ingredientcategory', verbose_name='Category', ), ), ]
2,907
Python
.py
84
22.321429
95
0.519688
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,569
0002_auto_20170101_1538.py
wger-project_wger/wger/nutrition/migrations/0002_auto_20170101_1538.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.12 on 2017-01-01 14:38 from django.db import migrations, models def copy_username(apps, schema_editor): """ Copies the exercise name to the original name field """ Ingredient = apps.get_model('nutrition', 'Ingredient') for ingredient in Ingredient.objects.all(): if ingredient.user: ingredient.license_author = ingredient.user.username else: ingredient.license_author = 'wger.de' ingredient.save() def update_status(apps, schema_editor): """ Updates the status of the ingredients """ Ingredient = apps.get_model('nutrition', 'Ingredient') Ingredient.objects.filter(status__in=('5', '4')).update(status=2) class Migration(migrations.Migration): dependencies = [ ('nutrition', '0001_initial'), ] operations = [ migrations.AlterField( model_name='meal', name='order', field=models.IntegerField(blank=True, editable=False, verbose_name='Order'), ), migrations.AlterField( model_name='mealitem', name='order', field=models.IntegerField(blank=True, editable=False, verbose_name='Order'), ), migrations.RunPython(copy_username, reverse_code=migrations.RunPython.noop), migrations.RunPython(update_status, reverse_code=migrations.RunPython.noop), migrations.AlterField( model_name='ingredient', name='status', field=models.CharField( choices=[('1', 'Pending'), ('2', 'Accepted'), ('3', 'Declined')], default='1', editable=False, max_length=2, ), ), ]
1,761
Python
.py
48
28.020833
88
0.607038
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,570
0012_alter_ingredient_license_author.py
wger-project_wger/wger/nutrition/migrations/0012_alter_ingredient_license_author.py
# Generated by Django 4.1.5 on 2023-02-05 11:17 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('nutrition', '0011_alter_logitem_datetime'), ] operations = [ migrations.AlterField( model_name='ingredient', name='license_author', field=models.CharField( blank=True, help_text='If you are not the author, enter the name or source here. This is needed for some licenses e.g. the CC-BY-SA.', max_length=60, null=True, verbose_name='Author', ), ), ]
667
Python
.py
19
25.052632
138
0.569876
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,571
0022_add_remote_id_increase_author_field_length.py
wger-project_wger/wger/nutrition/migrations/0022_add_remote_id_increase_author_field_length.py
# Generated by Django 4.2.6 on 2024-05-18 07:31 from django.db import migrations, models from wger.nutrition.models import Source def set_external_id(apps, schema_editor): """Set remote_id, used by imported ingredients (OFF, etc.)""" Ingredient = apps.get_model('nutrition', 'Ingredient') Ingredient.objects.filter(source_name=Source.OPEN_FOOD_FACTS.value).update( remote_id=models.F('code') ) class Migration(migrations.Migration): dependencies = [ ('nutrition', '0021_add_fibers_field'), ] operations = [ migrations.AddField( model_name='ingredient', name='remote_id', field=models.CharField(blank=True, db_index=True, max_length=200, null=True), ), migrations.RunPython( set_external_id, reverse_code=migrations.RunPython.noop, ), migrations.AlterField( model_name='image', name='license_author', field=models.CharField( blank=True, help_text='If you are not the author, enter the name or source here.', max_length=3500, null=True, verbose_name='Author(s)', ), ), migrations.AlterField( model_name='ingredient', name='license_author', field=models.CharField( blank=True, help_text='If you are not the author, enter the name or source here.', max_length=3500, null=True, verbose_name='Author(s)', ), ), ]
1,643
Python
.py
46
25.23913
89
0.568911
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,572
0021_add_fibers_field.py
wger-project_wger/wger/nutrition/migrations/0021_add_fibers_field.py
# Generated by Django 4.2.6 on 2024-05-18 09:33 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('nutrition', '0020_full_text_search'), ] operations = [ migrations.AddField( model_name='nutritionplan', name='goal_fibers', field=models.IntegerField(default=None, null=True), ), ]
408
Python
.py
13
24.230769
63
0.629156
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,573
calculator.py
wger-project_wger/wger/nutrition/views/calculator.py
# -*- coding: utf-8 -*- # 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 json import logging # Django from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.shortcuts import render # wger from wger.nutrition.forms import ( BmrForm, DailyCaloriesForm, PhysicalActivitiesForm, ) logger = logging.getLogger(__name__) """ Protein calculator views """ @login_required def view(request): """ The basal metabolic rate detail page """ form_data = { 'age': request.user.userprofile.age, 'height': request.user.userprofile.height, 'gender': request.user.userprofile.gender, 'weight': request.user.userprofile.weight, } context = { 'form': BmrForm(initial=form_data), 'form_activities': PhysicalActivitiesForm(instance=request.user.userprofile), 'form_calories': DailyCaloriesForm(instance=request.user.userprofile), } return render(request, 'rate/form.html', context) @login_required def calculate_bmr(request): """ Calculates the basal metabolic rate. Currently only the Mifflin-St.Jeor-Formel is supported """ data = {} form = BmrForm(data=request.POST, instance=request.user.userprofile) if form.is_valid(): form.save() # Create a new weight entry as needed request.user.userprofile.user_bodyweight(form.cleaned_data['weight']) bmr = request.user.userprofile.calculate_basal_metabolic_rate() result = {'bmr': '{0:.0f}'.format(bmr)} data = json.dumps(result) else: logger.debug(form.errors) data['bmr'] = str(form.errors) data = json.dumps(data) # print(form.errors) # print(form.is_valid()) # Return the results to the client return HttpResponse(data, 'application/json') @login_required def calculate_activities(request): """ Calculates the calories needed by additional physical activities """ data = {} form = PhysicalActivitiesForm(data=request.POST, instance=request.user.userprofile) if form.is_valid(): form.save() # Calculate the activities factor and the total calories factor = request.user.userprofile.calculate_activities() total = request.user.userprofile.calculate_basal_metabolic_rate() * factor result = {'activities': '{0:.0f}'.format(total), 'factor': '{0:.2f}'.format(factor)} data = json.dumps(result) else: logger.debug(form.errors) data['activities'] = str(form.errors) data = json.dumps(data) # Return the results to the client return HttpResponse(data, 'application/json')
3,395
Python
.py
92
31.967391
92
0.706134
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,574
ingredient.py
wger-project_wger/wger/nutrition/views/ingredient.py
# -*- coding: utf-8 -*- # 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 # Standard Library import logging # Django from django.conf import settings from django.contrib.auth.mixins import ( LoginRequiredMixin, PermissionRequiredMixin, ) from django.core.cache import cache from django.http import HttpResponseForbidden from django.shortcuts import ( get_object_or_404, render, ) from django.urls import reverse_lazy from django.utils.decorators import method_decorator from django.utils.translation import ( gettext as _, gettext_lazy, ) from django.views.decorators.cache import cache_page from django.views.generic import ( CreateView, DeleteView, ListView, UpdateView, ) # wger from wger.nutrition.forms import ( IngredientForm, UnitChooserForm, ) from wger.nutrition.models import Ingredient from wger.utils.cache import cache_mapper from wger.utils.constants import PAGINATION_OBJECTS_PER_PAGE from wger.utils.generic_views import ( WgerDeleteMixin, WgerFormMixin, ) from wger.utils.language import load_language logger = logging.getLogger(__name__) # ************************ # Ingredient functions # ************************ @method_decorator(cache_page(settings.WGER_SETTINGS['INGREDIENT_CACHE_TTL']), name='dispatch') class IngredientListView(ListView): """ Show an overview of all ingredients """ model = Ingredient template_name = 'ingredient/overview.html' context_object_name = 'ingredients_list' paginate_by = PAGINATION_OBJECTS_PER_PAGE def get_queryset(self): """ Filter the ingredients the user will see by its language """ language = load_language() return Ingredient.objects.filter(language=language) def view(request, pk, slug=None): context = {} ingredient = cache.get(cache_mapper.get_ingredient_key(int(pk))) if not ingredient: ingredient = get_object_or_404(Ingredient, pk=pk) cache.set( cache_mapper.get_ingredient_key(ingredient), ingredient, settings.WGER_SETTINGS['INGREDIENT_CACHE_TTL'], ) context['ingredient'] = ingredient context['image'] = ingredient.get_image(request) context['form'] = UnitChooserForm( data={'ingredient_id': ingredient.id, 'amount': 100, 'unit': None} ) return render(request, 'ingredient/view.html', context) class IngredientDeleteView( WgerDeleteMixin, LoginRequiredMixin, PermissionRequiredMixin, DeleteView, ): """ Generic view to delete an existing ingredient """ model = Ingredient template_name = 'delete.html' success_url = reverse_lazy('nutrition:ingredient:list') messages = gettext_lazy('Successfully deleted') permission_required = 'nutrition.delete_ingredient' # Send some additional data to the template def get_context_data(self, **kwargs): context = super(IngredientDeleteView, self).get_context_data(**kwargs) context['title'] = _('Delete {0}?').format(self.object) return context class IngredientEditView(WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, UpdateView): """ Generic view to update an existing ingredient """ template_name = 'form.html' model = Ingredient form_class = IngredientForm permission_required = 'nutrition.change_ingredient' def get_context_data(self, **kwargs): """ Send some additional data to the template """ context = super(IngredientEditView, self).get_context_data(**kwargs) context['title'] = _('Edit {0}').format(self.object) return context class IngredientCreateView(WgerFormMixin, CreateView): """ Generic view to add a new ingredient """ template_name = 'form.html' model = Ingredient form_class = IngredientForm title = gettext_lazy('Add a new ingredient') def form_valid(self, form): form.instance.language = load_language() form.instance.set_author(self.request) return super(IngredientCreateView, self).form_valid(form) def dispatch(self, request, *args, **kwargs): """ Demo users can't submit ingredients """ if request.user.userprofile.is_temporary: return HttpResponseForbidden() return super(IngredientCreateView, self).dispatch(request, *args, **kwargs)
4,998
Python
.py
142
30.478873
97
0.71396
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,575
bmi.py
wger-project_wger/wger/nutrition/views/bmi.py
# -*- coding: utf-8 -*- # 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 json import logging # Django from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.shortcuts import render from django.utils.translation import gettext as _ # wger from wger.nutrition.forms import BmiForm from wger.utils import helpers from wger.utils.units import AbstractHeight logger = logging.getLogger(__name__) """ BMI views """ @login_required def view(request): """ The BMI calculator detail page """ context = {} form_data = { 'height': request.user.userprofile.height, 'weight': request.user.userprofile.weight, 'use_metric': request.user.userprofile.use_metric, } context['form'] = BmiForm(initial=form_data) return render(request, 'bmi/form.html', context) @login_required def calculate(request): """ Calculates the BMI """ data = [] form = BmiForm(request.POST, instance=request.user.userprofile) output_height = request.POST['height'] if not request.user.userprofile.use_metric: request_copy = request.POST.copy() output_height = request_copy['height'] request_copy['height'] = AbstractHeight(request_copy['height'], mode='inches').cm form = BmiForm(request_copy, instance=request.user.userprofile) if form.is_valid(): form.save() # Create a new weight entry as needed request.user.userprofile.user_bodyweight(form.cleaned_data['weight']) bmi = request.user.userprofile.calculate_bmi() result = { 'bmi': '{0:.2f}'.format(bmi), 'weight': form.cleaned_data['weight'], 'height': output_height, } data = json.dumps(result, cls=helpers.DecimalJsonEncoder) response = HttpResponse(data, 'application/json') else: help_message = { ('error'): _('Please make sure your height is within the appropriate range.'), } if request.user.userprofile.use_metric: help_message['cm_range'] = _('140 to 230') else: help_message['in_range'] = _('56 to 90') data = json.dumps(help_message) response = HttpResponse(data, 'application/json') response.status_code = 406 # Return the results to the client return response def chart_data(request): """ Returns the data to render the BMI chart The individual values taken from * http://apps.who.int/bmi/index.jsp?introPage=intro_3.html * https://de.wikipedia.org/wiki/Body-Mass-Index """ if request.user.userprofile.use_metric: data = json.dumps( [ {'key': 'filler', 'height': 150, 'weight': 30}, {'key': 'filler', 'height': 200, 'weight': 30}, {'key': 'severe_thinness', 'height': 150, 'weight': 35.978}, {'key': 'severe_thinness', 'height': 200, 'weight': 63.960}, {'key': 'moderate_thinness', 'height': 150, 'weight': 38.228}, {'key': 'moderate_thinness', 'height': 200, 'weight': 67.960}, {'key': 'mild_thinness', 'height': 150, 'weight': 41.603}, {'key': 'mild_thinness', 'height': 200, 'weight': 73.960}, {'key': 'normal_range', 'height': 150, 'weight': 56.228}, {'key': 'normal_range', 'height': 200, 'weight': 99.960}, {'key': 'pre_obese', 'height': 150, 'weight': 67.478}, {'key': 'pre_obese', 'height': 200, 'weight': 119.960}, {'key': 'obese_class_1', 'height': 150, 'weight': 78.728}, {'key': 'obese_class_1', 'height': 200, 'weight': 139.960}, {'key': 'obese_class_2', 'height': 150, 'weight': 89.978}, {'key': 'obese_class_2', 'height': 200, 'weight': 159.960}, {'key': 'obese_class_3', 'height': 150, 'weight': 90}, {'key': 'obese_class_3', 'height': 200, 'weight': 190}, ] ) else: data = json.dumps( [ {'key': 'filler', 'height': 150, 'weight': 66.139}, {'key': 'filler', 'height': 200, 'weight': 66.139}, {'key': 'severe_thinness', 'height': 150, 'weight': 79.317}, {'key': 'severe_thinness', 'height': 200, 'weight': 141.008}, {'key': 'moderate_thinness', 'height': 150, 'weight': 84.277}, {'key': 'moderate_thinness', 'height': 200, 'weight': 149.826}, {'key': 'mild_thinness', 'height': 150, 'weight': 91.718}, {'key': 'mild_thinness', 'height': 200, 'weight': 163.054}, {'key': 'normal_range', 'height': 150, 'weight': 123.960}, {'key': 'normal_range', 'height': 200, 'weight': 220.374}, {'key': 'pre_obese', 'height': 150, 'weight': 148.762}, {'key': 'pre_obese', 'height': 200, 'weight': 264.467}, {'key': 'obese_class_1', 'height': 150, 'weight': 173.564}, {'key': 'obese_class_1', 'height': 200, 'weight': 308.559}, {'key': 'obese_class_2', 'height': 150, 'weight': 198.366}, {'key': 'obese_class_2', 'height': 200, 'weight': 352.651}, {'key': 'obese_class_3', 'height': 150, 'weight': 198.416}, {'key': 'obese_class_3', 'height': 200, 'weight': 352.740}, ] ) # Return the results to the client return HttpResponse(data, 'application/json')
6,260
Python
.py
137
37.087591
90
0.58597
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,576
plan.py
wger-project_wger/wger/nutrition/views/plan.py
# -*- coding: utf-8 -*- # 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 # Standard Library import logging # Django from django.contrib.auth.decorators import login_required from django.http import ( HttpResponse, HttpResponseForbidden, HttpResponseRedirect, ) from django.shortcuts import get_object_or_404 from django.urls import reverse from django.utils.translation import gettext as _ # Third Party from reportlab.lib import colors from reportlab.lib.pagesizes import A4 from reportlab.lib.units import cm from reportlab.platypus import ( Paragraph, SimpleDocTemplate, Spacer, Table, ) # wger from wger.nutrition.consts import MEALITEM_WEIGHT_GRAM from wger.nutrition.models import NutritionPlan from wger.utils.helpers import check_token from wger.utils.pdf import ( get_logo, header_colour, render_footer, row_color, styleSheet, ) logger = logging.getLogger(__name__) # ************************ # Plan functions # ************************ @login_required def copy(request, pk): """ Copy the nutrition plan """ plan = get_object_or_404(NutritionPlan, pk=pk, user=request.user) # Copy plan meals = plan.meal_set.select_related() plan_copy = plan plan_copy.pk = None plan_copy.save() # Copy the meals for meal in meals: meal_items = meal.mealitem_set.select_related() meal_copy = meal meal_copy.pk = None meal_copy.plan = plan_copy meal_copy.save() # Copy the individual meal entries for item in meal_items: item_copy = item item_copy.pk = None item_copy.meal = meal_copy item_copy.save() # Redirect return HttpResponseRedirect(reverse('nutrition:plan:view', kwargs={'id': plan.id})) def export_pdf(request, id: int): """ Generates a PDF with the contents of a nutrition plan See also * http://www.blog.pythonlibrary.org/2010/09/21/reportlab * http://www.reportlab.com/apis/reportlab/dev/platypus.html """ # Load the plan if request.user.is_anonymous: return HttpResponseForbidden() plan = get_object_or_404(NutritionPlan, pk=id, user=request.user) plan_data = plan.get_nutritional_values() # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf') # Create the PDF object, using the response object as its "file." doc = SimpleDocTemplate( response, pagesize=A4, title=_('Nutritional plan'), author='wger Workout Manager', subject=_('Nutritional plan for %s') % request.user.username, topMargin=1 * cm, ) # container for the 'Flowable' objects elements = [] data = [] # Iterate through the Plan meal_markers = [] ingredient_markers = [] # Meals i = 0 for meal in plan.meal_set.select_related(): i += 1 meal_markers.append(len(data)) if not meal.time: p = Paragraph( f'<para align="center"><strong>{_("Nr.")} {i}</strong></para>', styleSheet['SubHeader'], ) else: p = Paragraph( f'<para align="center"><strong>' f'{_("Nr.")} {i} - {meal.time.strftime("%H:%M")}' f'</strong></para>', styleSheet['SubHeader'], ) data.append([p]) # Ingredients for item in meal.mealitem_set.select_related(): ingredient_markers.append(len(data)) p = Paragraph(f'<para>{item.ingredient.name}</para>', styleSheet['Normal']) if item.get_unit_type() == MEALITEM_WEIGHT_GRAM: unit_name = 'g' else: unit_name = ' × ' + item.weight_unit.unit.name data.append( [Paragraph('{0:.0f}{1}'.format(item.amount, unit_name), styleSheet['Normal']), p] ) # Add filler data.append([Spacer(1 * cm, 0.6 * cm)]) # Set general table styles table_style = [] # Set specific styles, e.g. background for title cells for marker in meal_markers: # Set background colour for headings table_style.append(('BACKGROUND', (0, marker), (-1, marker), header_colour)) table_style.append(('BOX', (0, marker), (-1, marker), 1.25, colors.black)) # Make the headings span the whole width table_style.append(('SPAN', (0, marker), (-1, marker))) # has the plan any data? if data: t = Table(data, style=table_style) # Manually set the width of the columns t._argW[0] = 3.5 * cm # There is nothing to output else: t = Paragraph( _('<i>This is an empty plan, what did you expect on the PDF?</i>'), styleSheet['Normal'] ) # Add site logo elements.append(get_logo()) elements.append(Spacer(10 * cm, 0.5 * cm)) # Set the title (if available) if plan.description: p = Paragraph( '<para align="center"><strong>%(description)s</strong></para>' % {'description': plan.description}, styleSheet['HeaderBold'], ) elements.append(p) # Filler elements.append(Spacer(10 * cm, 1.5 * cm)) # append the table to the document elements.append(t) elements.append(Paragraph('<para>&nbsp;</para>', styleSheet['Normal'])) # Create table with nutritional calculations data = [] data.append( [ Paragraph( f'<para align="center">{_("Nutritional data")}</para>', styleSheet['SubHeaderBlack'], ) ] ) data.append( [ Paragraph(_('Macronutrients'), styleSheet['Normal']), Paragraph(_('Total'), styleSheet['Normal']), Paragraph(_('Percent of energy'), styleSheet['Normal']), Paragraph(_('g per body kg'), styleSheet['Normal']), ] ) data.append( [ Paragraph(_('Energy'), styleSheet['Normal']), Paragraph(str(plan_data['total'].energy), styleSheet['Normal']), ] ) data.append( [ Paragraph(_('Protein'), styleSheet['Normal']), Paragraph(str(plan_data['total'].protein), styleSheet['Normal']), Paragraph(str(plan_data['percent']['protein']), styleSheet['Normal']), Paragraph(str(plan_data['per_kg']['protein']), styleSheet['Normal']), ] ) data.append( [ Paragraph(_('Carbohydrates'), styleSheet['Normal']), Paragraph(str(plan_data['total'].carbohydrates), styleSheet['Normal']), Paragraph(str(plan_data['percent']['carbohydrates']), styleSheet['Normal']), Paragraph(str(plan_data['per_kg']['carbohydrates']), styleSheet['Normal']), ] ) data.append( [ Paragraph(' ' + _('Sugar content in carbohydrates'), styleSheet['Normal']), Paragraph(str(plan_data['total'].carbohydrates_sugar), styleSheet['Normal']), ] ) data.append( [ Paragraph(_('Fat'), styleSheet['Normal']), Paragraph(str(plan_data['total'].fat), styleSheet['Normal']), Paragraph(str(plan_data['percent']['fat']), styleSheet['Normal']), Paragraph(str(plan_data['per_kg']['fat']), styleSheet['Normal']), ] ) data.append( [ Paragraph(_('Saturated fat content in fats'), styleSheet['Normal']), Paragraph(str(plan_data['total'].fat_saturated), styleSheet['Normal']), ] ) data.append( [ Paragraph(_('Fiber'), styleSheet['Normal']), Paragraph(str(plan_data['total'].fiber), styleSheet['Normal']), ] ) data.append( [ Paragraph(_('Sodium'), styleSheet['Normal']), Paragraph(str(plan_data['total'].sodium), styleSheet['Normal']), ] ) table_style = [] table_style.append(('BOX', (0, 0), (-1, -1), 1.25, colors.black)) table_style.append(('GRID', (0, 0), (-1, -1), 0.40, colors.black)) table_style.append(('SPAN', (0, 0), (-1, 0))) # Title table_style.append(('SPAN', (1, 2), (-1, 2))) # Energy table_style.append(('BACKGROUND', (0, 3), (-1, 3), row_color)) # Protein table_style.append(('BACKGROUND', (0, 4), (-1, 4), row_color)) # Carbohydrates table_style.append(('SPAN', (1, 5), (-1, 5))) # Sugar table_style.append(('LEFTPADDING', (0, 5), (0, 5), 15)) table_style.append(('BACKGROUND', (0, 6), (-1, 6), row_color)) # Fats table_style.append(('SPAN', (1, 7), (-1, 7))) # Saturated fats table_style.append(('LEFTPADDING', (0, 7), (0, 7), 15)) table_style.append(('SPAN', (1, 8), (-1, 8))) # Fiber table_style.append(('SPAN', (1, 9), (-1, 9))) # Sodium t = Table(data, style=table_style) t._argW[0] = 6 * cm elements.append(t) # Footer, date and info elements.append(Spacer(10 * cm, 0.5 * cm)) elements.append(render_footer(request.build_absolute_uri(plan.get_absolute_url()))) doc.build(elements) response['Content-Disposition'] = 'attachment; filename=nutritional-plan.pdf' response['Content-Length'] = len(response.content) return response
9,946
Python
.py
268
29.83209
100
0.602533
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,577
unit.py
wger-project_wger/wger/nutrition/views/unit.py
# -*- coding: utf-8 -*- # 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 # Standard Library import logging # Django from django.contrib.auth.mixins import ( LoginRequiredMixin, PermissionRequiredMixin, ) from django.urls import ( reverse, reverse_lazy, ) from django.utils.translation import ( gettext as _, gettext_lazy, ) from django.views.generic import ( CreateView, DeleteView, ListView, UpdateView, ) # wger from wger.nutrition.models import WeightUnit from wger.utils.constants import PAGINATION_OBJECTS_PER_PAGE from wger.utils.generic_views import ( WgerDeleteMixin, WgerFormMixin, ) from wger.utils.language import load_language logger = logging.getLogger(__name__) # ************************ # Weight units functions # ************************ class WeightUnitListView(PermissionRequiredMixin, ListView): """ Generic view to list all weight units """ model = WeightUnit template_name = 'units/list.html' context_object_name = 'unit_list' paginate_by = PAGINATION_OBJECTS_PER_PAGE permission_required = 'nutrition.add_ingredientweightunit' def get_queryset(self): """ Only show ingredient units in the current user's language """ return WeightUnit.objects.filter(language=load_language()) class WeightUnitCreateView( WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, CreateView, ): """ Generic view to add a new weight unit for ingredients """ model = WeightUnit fields = ['name'] title = gettext_lazy('Add new weight unit') permission_required = 'nutrition.add_ingredientweightunit' def get_success_url(self): return reverse('nutrition:weight_unit:list') def form_valid(self, form): form.instance.language = load_language() return super(WeightUnitCreateView, self).form_valid(form) class WeightUnitDeleteView( WgerDeleteMixin, LoginRequiredMixin, PermissionRequiredMixin, DeleteView, ): """ Generic view to delete a weight unit """ model = WeightUnit success_url = reverse_lazy('nutrition:weight_unit:list') permission_required = 'nutrition.delete_ingredientweightunit' messages = gettext_lazy('Successfully deleted') def get_context_data(self, **kwargs): """ Send some additional data to the template """ context = super(WeightUnitDeleteView, self).get_context_data(**kwargs) context['title'] = _('Delete {0}?').format(self.object) return context class WeightUnitUpdateView( WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, UpdateView, ): """ Generic view to update an weight unit """ model = WeightUnit fields = ['name'] permission_required = 'nutrition.change_ingredientweightunit' def get_success_url(self): return reverse('nutrition:weight_unit:list') def get_context_data(self, **kwargs): """ Send some additional data to the template """ context = super(WeightUnitUpdateView, self).get_context_data(**kwargs) context['title'] = _('Edit {0}').format(self.object) return context
3,822
Python
.py
120
27.383333
78
0.709625
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,578
unit_ingredient.py
wger-project_wger/wger/nutrition/views/unit_ingredient.py
# -*- coding: utf-8 -*- # 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 # Standard Library import logging # Django from django.contrib.auth.mixins import ( LoginRequiredMixin, PermissionRequiredMixin, ) from django.forms import ( ModelChoiceField, ModelForm, ) from django.shortcuts import get_object_or_404 from django.urls import reverse from django.utils.translation import gettext_lazy from django.views.generic import ( CreateView, DeleteView, UpdateView, ) # wger from wger.nutrition.models import ( Ingredient, IngredientWeightUnit, WeightUnit, ) from wger.utils.generic_views import ( WgerDeleteMixin, WgerFormMixin, ) from wger.utils.language import load_language logger = logging.getLogger(__name__) # ************************ # Weight units to ingredient functions # ************************ class WeightUnitIngredientCreateView( WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, CreateView, ): """ Generic view to add a new weight unit to ingredient entry """ model = IngredientWeightUnit title = gettext_lazy('Add a new weight unit') permission_required = 'nutrition.add_ingredientweightunit' def get_success_url(self): return reverse('nutrition:ingredient:view', kwargs={'pk': self.kwargs['ingredient_pk']}) def form_valid(self, form): ingredient = get_object_or_404(Ingredient, pk=self.kwargs['ingredient_pk']) form.instance.ingredient = ingredient return super(WeightUnitIngredientCreateView, self).form_valid(form) def get_form_class(self): """ The form can only show units in the user's language """ class IngredientWeightUnitForm(ModelForm): unit = ModelChoiceField(queryset=WeightUnit.objects.filter(language=load_language())) class Meta: model = IngredientWeightUnit fields = ['unit', 'gram', 'amount'] return IngredientWeightUnitForm class WeightUnitIngredientUpdateView( WgerFormMixin, LoginRequiredMixin, PermissionRequiredMixin, UpdateView, ): """ Generic view to update an weight unit to ingredient entry """ model = IngredientWeightUnit title = gettext_lazy('Edit a weight unit to ingredient connection') permission_required = 'nutrition.add_ingredientweightunit' def get_success_url(self): return reverse('nutrition:ingredient:view', kwargs={'pk': self.object.ingredient.id}) def get_form_class(self): """ The form can only show units in the user's language """ class IngredientWeightUnitForm(ModelForm): unit = ModelChoiceField(queryset=WeightUnit.objects.filter(language=load_language())) class Meta: model = IngredientWeightUnit fields = ['unit', 'gram', 'amount'] return IngredientWeightUnitForm class WeightUnitIngredientDeleteView( WgerDeleteMixin, LoginRequiredMixin, PermissionRequiredMixin, DeleteView, ): """ Generic view to delete a weight unit to ingredient entry """ model = IngredientWeightUnit title = gettext_lazy('Delete?') permission_required = 'nutrition.add_ingredientweightunit' def get_success_url(self): return reverse('nutrition:ingredient:view', kwargs={'pk': self.object.ingredient.id})
4,002
Python
.py
114
30.070175
97
0.715803
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,579
serializers.py
wger-project_wger/wger/nutrition/api/serializers.py
# 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/>. # Third Party from rest_framework import serializers # wger from wger.nutrition.models import ( Image, Ingredient, IngredientWeightUnit, LogItem, Meal, MealItem, NutritionPlan, WeightUnit, ) class IngredientWeightUnitSerializer(serializers.ModelSerializer): """ IngredientWeightUnit serializer """ class Meta: model = IngredientWeightUnit fields = [ 'id', 'amount', 'gram', 'ingredient', 'unit', ] class IngredientWeightUnitInfoSerializer(serializers.ModelSerializer): """ IngredientWeightUnit info serializer """ class Meta: model = IngredientWeightUnit depth = 1 fields = [ 'gram', 'amount', 'unit', ] class WeightUnitSerializer(serializers.ModelSerializer): """ WeightUnit serializer """ class Meta: model = WeightUnit fields = [ 'id', 'language', 'name', ] class IngredientImageSerializer(serializers.ModelSerializer): """ Image serializer """ ingredient_uuid = serializers.CharField(source='ingredient.uuid', read_only=True) ingredient_id = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = Image fields = [ 'id', 'uuid', 'ingredient_id', 'ingredient_uuid', 'image', 'created', 'last_update', 'size', 'width', 'height', 'license', 'license_title', 'license_object_url', 'license_author', 'license_author_url', 'license_derivative_source_url', ] class IngredientSerializer(serializers.ModelSerializer): """ Ingredient serializer """ class Meta: model = Ingredient fields = [ 'id', 'uuid', 'remote_id', 'source_name', 'source_url', 'code', 'name', 'created', 'last_update', 'last_imported', 'energy', 'protein', 'carbohydrates', 'carbohydrates_sugar', 'fat', 'fat_saturated', 'fiber', 'sodium', 'license', 'license_title', 'license_object_url', 'license_author', 'license_author_url', 'license_derivative_source_url', 'language', ] class IngredientInfoSerializer(serializers.ModelSerializer): """ Ingredient info serializer """ weight_units = IngredientWeightUnitInfoSerializer(source='ingredientweightunit_set', many=True) image = IngredientImageSerializer(read_only=True) class Meta: model = Ingredient depth = 1 fields = [ 'id', 'uuid', 'remote_id', 'source_name', 'source_url', 'code', 'name', 'created', 'last_update', 'last_imported', 'energy', 'protein', 'carbohydrates', 'carbohydrates_sugar', 'fat', 'fat_saturated', 'fiber', 'sodium', 'weight_units', 'language', 'image', 'license', 'license_title', 'license_object_url', 'license_author', 'license_author_url', 'license_derivative_source_url', ] class MealItemSerializer(serializers.ModelSerializer): """ MealItem serializer """ meal = serializers.PrimaryKeyRelatedField(label='Nutrition plan', queryset=Meal.objects.all()) class Meta: model = MealItem fields = [ 'id', 'meal', 'ingredient', 'weight_unit', 'order', 'amount', ] class LogItemSerializer(serializers.ModelSerializer): """ LogItem serializer """ class Meta: model = LogItem fields = [ 'id', 'plan', 'meal', 'ingredient', 'weight_unit', 'datetime', 'amount', ] class MealItemInfoSerializer(serializers.ModelSerializer): """ Meal Item info serializer """ meal = serializers.PrimaryKeyRelatedField(read_only=True) ingredient = serializers.PrimaryKeyRelatedField(read_only=True) ingredient_obj = IngredientInfoSerializer(source='ingredient', read_only=True) weight_unit = serializers.PrimaryKeyRelatedField(read_only=True) weight_unit_obj = IngredientWeightUnitSerializer(source='weight_unit', read_only=True) image = IngredientImageSerializer(source='ingredient.image', read_only=True) class Meta: model = MealItem depth = 1 fields = [ 'id', 'meal', 'ingredient', 'ingredient_obj', 'weight_unit', 'weight_unit_obj', 'image', 'order', 'amount', ] class MealSerializer(serializers.ModelSerializer): """ Meal serializer """ plan = serializers.PrimaryKeyRelatedField( label='Nutrition plan', queryset=NutritionPlan.objects.all(), ) class Meta: model = Meal fields = ['id', 'plan', 'order', 'time', 'name'] class NutritionalValuesSerializer(serializers.Serializer): """ Nutritional values serializer """ energy = serializers.FloatField() protein = serializers.FloatField() carbohydrates = serializers.FloatField() carbohydrates_sugar = serializers.FloatField() fat = serializers.FloatField() fat_saturated = serializers.FloatField() fiber = serializers.FloatField() sodium = serializers.FloatField() class MealInfoSerializer(serializers.ModelSerializer): """ Meal info serializer """ meal_items = MealItemInfoSerializer(source='mealitem_set', many=True) plan = serializers.PrimaryKeyRelatedField(read_only=True) nutritional_values = NutritionalValuesSerializer( source='get_nutritional_values', read_only=True, ) class Meta: model = Meal fields = [ 'id', 'plan', 'order', 'time', 'name', 'meal_items', 'nutritional_values', ] class NutritionPlanSerializer(serializers.ModelSerializer): """ Nutritional plan serializer """ # nutritional_values = NutritionalValuesSerializer(source='get_nutritional_values.total') class Meta: model = NutritionPlan fields = [ 'id', 'creation_date', 'description', 'only_logging', 'goal_energy', 'goal_protein', 'goal_carbohydrates', 'goal_fat', 'goal_fiber', # 'nutritional_values', ] class NutritionPlanInfoSerializer(serializers.ModelSerializer): """ Nutritional plan info serializer """ meals = MealInfoSerializer(source='meal_set', many=True) class Meta: model = NutritionPlan depth = 1 fields = [ 'id', 'creation_date', 'description', 'only_logging', 'goal_energy', 'goal_protein', 'goal_carbohydrates', 'goal_fat', 'goal_fiber', 'meals', ]
8,447
Python
.py
297
19.643098
99
0.569523
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,580
filtersets.py
wger-project_wger/wger/nutrition/api/filtersets.py
# Third Party from django_filters import rest_framework as filters # wger from wger.nutrition.models import ( Ingredient, LogItem, ) class LogItemFilterSet(filters.FilterSet): class Meta: model = LogItem fields = { 'datetime': ['exact', 'date'], 'amount': ['exact'], 'ingredient': ['exact'], 'plan': ['exact'], 'weight_unit': ['exact'], } class IngredientFilterSet(filters.FilterSet): class Meta: model = Ingredient fields = { 'id': ['exact', 'in'], 'uuid': ['exact'], 'code': ['exact'], 'source_name': ['exact'], 'name': ['exact'], 'energy': ['exact'], 'protein': ['exact'], 'carbohydrates': ['exact'], 'carbohydrates_sugar': ['exact'], 'fat': ['exact'], 'fat_saturated': ['exact'], 'fiber': ['exact'], 'sodium': ['exact'], 'created': ['exact', 'gt', 'lt'], 'last_update': ['exact', 'gt', 'lt'], 'last_imported': ['exact', 'gt', 'lt'], 'language': ['exact'], 'license': ['exact'], 'license_author': ['exact'], }
1,270
Python
.py
41
21.268293
52
0.462418
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,581
views.py
wger-project_wger/wger/nutrition/api/views.py
# -*- coding: utf-8 -*- # 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.conf import settings from django.contrib.postgres.search import TrigramSimilarity from django.utils.decorators import method_decorator from django.views.decorators.cache import cache_page # Third Party from drf_spectacular.types import OpenApiTypes from drf_spectacular.utils import ( OpenApiParameter, extend_schema, inline_serializer, ) from easy_thumbnails.alias import aliases from easy_thumbnails.files import get_thumbnailer from rest_framework import viewsets from rest_framework.decorators import ( action, api_view, ) from rest_framework.fields import ( CharField, IntegerField, ) from rest_framework.response import Response # wger from wger.nutrition.api.filtersets import ( IngredientFilterSet, LogItemFilterSet, ) from wger.nutrition.api.serializers import ( IngredientImageSerializer, IngredientInfoSerializer, IngredientSerializer, IngredientWeightUnitSerializer, LogItemSerializer, MealItemSerializer, MealSerializer, NutritionalValuesSerializer, NutritionPlanInfoSerializer, NutritionPlanSerializer, WeightUnitSerializer, ) from wger.nutrition.forms import UnitChooserForm from wger.nutrition.models import ( Image, Ingredient, IngredientWeightUnit, LogItem, Meal, MealItem, NutritionPlan, WeightUnit, ) from wger.utils.constants import ( ENGLISH_SHORT_NAME, SEARCH_ALL_LANGUAGES, ) from wger.utils.db import is_postgres_db from wger.utils.language import load_language from wger.utils.viewsets import WgerOwnerObjectModelViewSet logger = logging.getLogger(__name__) class IngredientViewSet(viewsets.ReadOnlyModelViewSet): """ API endpoint for ingredient objects. For a read-only endpoint with all the information of an ingredient, see /api/v2/ingredientinfo/ """ serializer_class = IngredientSerializer ordering_fields = '__all__' filterset_class = IngredientFilterSet @method_decorator(cache_page(settings.WGER_SETTINGS['INGREDIENT_CACHE_TTL'])) def list(self, request, *args, **kwargs): return super().list(request, *args, **kwargs) def get_queryset(self): """H""" qs = Ingredient.objects.all() code = self.request.query_params.get('code') if not code: return qs qs = qs.filter(code=code) if qs.count() == 0: logger.debug('code not found locally, fetching code from off') Ingredient.fetch_ingredient_from_off(code) return qs @action(detail=True) def get_values(self, request, pk): """ Calculates the nutritional values for current ingredient and the given amount and unit. This function basically just performs a multiplication (in the model), and is a candidate to be moved to pure AJAX calls, however doing it like this keeps the logic nicely hidden and respects the DRY principle. """ result = { 'energy': 0, 'protein': 0, 'carbohydrates': 0, 'carbohydrates_sugar': 0, 'fat': 0, 'fat_saturated': 0, 'fiber': 0, 'sodium': 0, 'errors': [], } ingredient = self.get_object() form = UnitChooserForm(request.GET) if form.is_valid(): # Create a temporary MealItem object if form.cleaned_data['unit']: unit_id = form.cleaned_data['unit'].id else: unit_id = None item = MealItem() item.ingredient = ingredient item.weight_unit_id = unit_id item.amount = form.cleaned_data['amount'] result = item.get_nutritional_values().to_dict else: result['errors'] = form.errors return Response(result) class IngredientInfoViewSet(IngredientViewSet): """ Read-only info API endpoint for ingredient objects. Returns nested data structures for more easy parsing. """ serializer_class = IngredientInfoSerializer @extend_schema( parameters=[ OpenApiParameter( 'term', OpenApiTypes.STR, OpenApiParameter.QUERY, description='The name of the ingredient to search"', required=True, ), OpenApiParameter( 'language', OpenApiTypes.STR, OpenApiParameter.QUERY, description='Comma separated list of language codes to search', required=True, ), ], responses={ 200: inline_serializer( name='IngredientSearchResponse', fields={ 'value': CharField(), 'data': inline_serializer( name='IngredientSearchItemResponse', fields={ 'id': IntegerField(), 'name': CharField(), 'category': CharField(), 'image': CharField(), 'image_thumbnail': CharField(), }, ), }, ) }, ) @api_view(['GET']) def search(request): """ Searches for ingredients. This format is currently used by the ingredient search autocompleter """ term = request.GET.get('term', None) language_codes = request.GET.get('language', ENGLISH_SHORT_NAME) results = [] response = {} if not term: return Response(response) query = Ingredient.objects.all() # Filter the appropriate languages languages = [load_language(l) for l in language_codes.split(',')] if language_codes != SEARCH_ALL_LANGUAGES: query = query.filter( language__in=languages, ) query = query.only('name') # Postgres uses a full-text search if is_postgres_db(): query = ( query.annotate(similarity=TrigramSimilarity('name', term)) .filter(similarity__gt=0.15) .order_by('-similarity', 'name') ) else: query = query.filter(name__icontains=term) for ingredient in query[:150]: if hasattr(ingredient, 'image'): image_obj = ingredient.image image = image_obj.image.url t = get_thumbnailer(image_obj.image) thumbnail = t.get_thumbnail(aliases.get('micro_cropped')).url else: ingredient.get_image(request) image = None thumbnail = None ingredient_json = { 'value': ingredient.name, 'data': { 'id': ingredient.id, 'name': ingredient.name, 'image': image, 'image_thumbnail': thumbnail, }, } results.append(ingredient_json) response['suggestions'] = results return Response(response) class ImageViewSet(viewsets.ReadOnlyModelViewSet): """ API endpoint for ingredient images """ queryset = Image.objects.all() serializer_class = IngredientImageSerializer ordering_fields = '__all__' filterset_fields = ('uuid', 'ingredient_id', 'ingredient__uuid') @method_decorator(cache_page(settings.WGER_SETTINGS['INGREDIENT_CACHE_TTL'])) def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) class WeightUnitViewSet(viewsets.ReadOnlyModelViewSet): """ API endpoint for weight unit objects """ queryset = WeightUnit.objects.all() serializer_class = WeightUnitSerializer ordering_fields = '__all__' filterset_fields = ('language', 'name') class IngredientWeightUnitViewSet(viewsets.ReadOnlyModelViewSet): """ API endpoint for many-to-many table ingredient-weight unit objects """ queryset = IngredientWeightUnit.objects.all() serializer_class = IngredientWeightUnitSerializer ordering_fields = '__all__' filterset_fields = ( 'amount', 'gram', 'ingredient', 'unit', ) class NutritionPlanViewSet(viewsets.ModelViewSet): """ API endpoint for nutrition plan objects. For a read-only endpoint with all the information of nutritional plan(s), see /api/v2/nutritionplaninfo/ """ serializer_class = NutritionPlanSerializer is_private = True ordering_fields = '__all__' filterset_fields = ( 'creation_date', 'description', 'has_goal_calories', ) def get_queryset(self): """ Only allow access to appropriate objects """ # REST API generation if getattr(self, 'swagger_fake_view', False): return NutritionPlan.objects.none() return NutritionPlan.objects.filter(user=self.request.user) def perform_create(self, serializer): """ Set the owner """ serializer.save(user=self.request.user) @action(detail=True) def nutritional_values(self, request, pk): """ Return an overview of the nutritional plan's values """ serializer = NutritionalValuesSerializer( NutritionPlan.objects.get(pk=pk).get_nutritional_values()['total'], ) return Response(serializer.data) class NutritionPlanInfoViewSet(NutritionPlanViewSet): """ Read-only info API endpoint for nutrition plan objects. Returns nested data structures for more easy parsing. """ serializer_class = NutritionPlanInfoSerializer class MealViewSet(WgerOwnerObjectModelViewSet): """ API endpoint for meal objects """ serializer_class = MealSerializer is_private = True ordering_fields = '__all__' filterset_fields = ( 'order', 'plan', 'time', ) def get_queryset(self): """ Only allow access to appropriate objects """ # REST API generation if getattr(self, 'swagger_fake_view', False): return Meal.objects.none() return Meal.objects.filter(plan__user=self.request.user) def perform_create(self, serializer): """ Set the order """ serializer.save(order=1) def get_owner_objects(self): """ Return objects to check for ownership permission """ return [(NutritionPlan, 'plan')] @action(detail=True) def nutritional_values(self, request, pk): """ Return an overview of the nutritional plan's values """ serializer = NutritionalValuesSerializer(Meal.objects.get(pk=pk).get_nutritional_values()) return Response(serializer.data) class MealItemViewSet(WgerOwnerObjectModelViewSet): """ API endpoint for meal item objects """ serializer_class = MealItemSerializer is_private = True ordering_fields = '__all__' filterset_fields = ( 'amount', 'ingredient', 'meal', 'order', 'weight_unit', ) def get_queryset(self): """ Only allow access to appropriate objects """ # REST API generation if getattr(self, 'swagger_fake_view', False): return MealItem.objects.none() return MealItem.objects.filter(meal__plan__user=self.request.user) def perform_create(self, serializer): """ Set the order """ serializer.save(order=1) def get_owner_objects(self): """ Return objects to check for ownership permission """ return [(Meal, 'meal')] @action(detail=True) def nutritional_values(self, request, pk): """ Return an overview of the nutritional plan's values """ return Response(MealItem.objects.get(pk=pk).get_nutritional_values()) class LogItemViewSet(WgerOwnerObjectModelViewSet): """ API endpoint for a meal log item """ serializer_class = LogItemSerializer is_private = True ordering_fields = '__all__' filterset_class = LogItemFilterSet def get_queryset(self): """ Only allow access to appropriate objects """ # REST API generation if getattr(self, 'swagger_fake_view', False): return LogItem.objects.none() return LogItem.objects.select_related('plan').filter(plan__user=self.request.user) def get_owner_objects(self): """ Return objects to check for ownership permission """ return [(NutritionPlan, 'plan'), (Meal, 'meal')] @action(detail=True) def nutritional_values(self, request, pk): """ Return an overview of the nutritional plan's values """ return Response( LogItem.objects.get(pk=pk, plan__user=self.request.user).get_nutritional_values() )
13,613
Python
.py
406
26.036946
98
0.640664
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,582
test_calories_calculator.py
wger-project_wger/wger/nutrition/tests/test_calories_calculator.py
# 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 # Standard Library import datetime import decimal import json # Django from django.contrib.auth.models import User from django.urls import reverse # wger from wger.core.tests.base_testcase import WgerTestCase from wger.utils.constants import TWOPLACES from wger.weight.models import WeightEntry class CaloriesCalculatorTestCase(WgerTestCase): """ Tests the calories calculator methods and views """ def test_page(self): """ Access the page """ response = self.client.get(reverse('nutrition:calories:view')) self.assertEqual(response.status_code, 302) self.user_login('test') response = self.client.get(reverse('nutrition:calories:view')) self.assertEqual(response.status_code, 200) def test_calculator(self): """ Tests the calculator itself """ self.user_login('test') response = self.client.post( reverse('nutrition:calories:activities'), { 'sleep_hours': 7, 'work_hours': 8, 'work_intensity': 1, 'sport_hours': 6, 'sport_intensity': 3, 'freetime_hours': 8, 'freetime_intensity': 1, }, ) self.assertEqual(response.status_code, 200) result = json.loads(response.content.decode('utf8')) self.assertEqual( decimal.Decimal(result['factor']), decimal.Decimal(1.57).quantize(TWOPLACES) ) self.assertEqual(decimal.Decimal(result['activities']), decimal.Decimal(2920)) def test_automatic_weight_entry_bmi(self): """ Tests that weight entries are automatically created or updated """ self.user_login('test') user = User.objects.get(username=self.current_user) # Existing weight entry is old, a new one is created entry1 = WeightEntry.objects.filter(user=user).latest() response = self.client.post( reverse('nutrition:bmi:calculate'), {'height': 180, 'weight': 80} ) self.assertEqual(response.status_code, 200) entry2 = WeightEntry.objects.filter(user=user).latest() self.assertEqual(entry1.weight, 83) self.assertEqual(entry2.weight, 80) # Existing weight entry is from today, is updated entry2.delete() entry1.date = datetime.date.today() entry1.save() response = self.client.post( reverse('nutrition:bmi:calculate'), {'height': 180, 'weight': 80} ) self.assertEqual(response.status_code, 200) entry2 = WeightEntry.objects.filter(user=user).latest() self.assertEqual(entry1.pk, entry2.pk) self.assertEqual(entry2.weight, 80) # No existing entries WeightEntry.objects.filter(user=user).delete() response = self.client.post( reverse('nutrition:bmi:calculate'), {'height': 180, 'weight': 80} ) self.assertEqual(response.status_code, 200) entry = WeightEntry.objects.filter(user=user).latest() self.assertEqual(entry.weight, 80) self.assertEqual(entry.date, datetime.date.today()) def test_bmr(self): """ Tests the BMR view """ self.user_login('test') response = self.client.post( reverse('nutrition:calories:bmr'), {'age': 30, 'height': 180, 'gender': 1, 'weight': 80} ) self.assertEqual(response.status_code, 200) result = json.loads(response.content.decode('utf8')) self.assertEqual(result, {'bmr': '1780'}) def test_automatic_weight_entry_bmr(self): """ Tests that weight entries are automatically created or updated """ self.user_login('test') user = User.objects.get(username=self.current_user) # Existing weight entry is old, a new one is created entry1 = WeightEntry.objects.filter(user=user).latest() response = self.client.post( reverse('nutrition:calories:bmr'), {'age': 30, 'height': 180, 'gender': 1, 'weight': 80} ) self.assertEqual(response.status_code, 200) entry2 = WeightEntry.objects.filter(user=user).latest() self.assertEqual(entry1.weight, 83) self.assertEqual(entry2.weight, 80) # Existing weight entry is from today, is updated entry2.delete() entry1.date = datetime.date.today() entry1.save() response = self.client.post( reverse('nutrition:calories:bmr'), {'age': 30, 'height': 180, 'gender': 1, 'weight': 80} ) self.assertEqual(response.status_code, 200) entry2 = WeightEntry.objects.filter(user=user).latest() self.assertEqual(entry1.pk, entry2.pk) self.assertEqual(entry2.weight, 80) # No existing entries WeightEntry.objects.filter(user=user).delete() response = self.client.post( reverse('nutrition:calories:bmr'), {'age': 30, 'height': 180, 'gender': 1, 'weight': 80} ) self.assertEqual(response.status_code, 200) entry = WeightEntry.objects.filter(user=user).latest() self.assertEqual(entry.weight, 80) self.assertEqual(entry.date, datetime.date.today())
5,934
Python
.py
141
33.865248
100
0.646162
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,583
test_pdf.py
wger-project_wger/wger/nutrition/tests/test_pdf.py
# 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 # Django from django.contrib.auth.models import User from django.urls import reverse # wger from wger.core.models import Language from wger.core.tests.base_testcase import WgerTestCase from wger.nutrition.models import NutritionPlan from wger.utils.helpers import make_token class NutritionalPlanPdfExportTestCase(WgerTestCase): """ Tests exporting a nutritional plan as a pdf """ def export_pdf(self, fail=False): """ Helper function to test exporting a nutritional plan as a pdf """ # Get a plan response = self.client.get(reverse('nutrition:plan:export-pdf', kwargs={'id': 4})) if fail: self.assertIn(response.status_code, (404, 403)) else: self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/pdf') self.assertEqual( response['Content-Disposition'], 'attachment; filename=nutritional-plan.pdf' ) # Approximate size self.assertGreater(int(response['Content-Length']), 38000) self.assertLess(int(response['Content-Length']), 42000) # Create an empty plan user = User.objects.get(pk=2) language = Language.objects.get(pk=1) plan = NutritionPlan() plan.user = user plan.language = language plan.save() response = self.client.get(reverse('nutrition:plan:export-pdf', kwargs={'id': plan.id})) if fail: self.assertIn(response.status_code, (404, 403)) else: self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/pdf') self.assertEqual( response['Content-Disposition'], 'attachment; filename=nutritional-plan.pdf' ) # Approximate size self.assertGreater(int(response['Content-Length']), 38000) self.assertLess(int(response['Content-Length']), 42000) def test_export_pdf_anonymous(self): """ Tests exporting a nutritional plan as a pdf as an anonymous user """ self.export_pdf(fail=True) def test_export_pdf_owner(self): """ Tests exporting a nutritional plan as a pdf as the owner user """ self.user_login('test') self.export_pdf(fail=False) def test_export_pdf_other(self): """ Tests exporting a nutritional plan as a pdf as a logged user not owning the data """ self.user_login('admin') self.export_pdf(fail=True)
3,260
Python
.py
78
34.166667
96
0.666983
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,584
test_meal_item.py
wger-project_wger/wger/nutrition/tests/test_meal_item.py
# 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.tests import api_base_test from wger.nutrition.models import MealItem class MealItemApiTestCase(api_base_test.ApiBaseResourceTestCase): """ Tests the meal overview resource """ pk = 10 resource = MealItem private_resource = True data = { 'meal': 2, 'amount': 100, 'ingredient': 1, }
1,079
Python
.py
29
34.137931
78
0.743786
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,585
test_search_api.py
wger-project_wger/wger/nutrition/tests/test_search_api.py
# 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/>. # Third Party from rest_framework import status # wger from wger.core.tests.api_base_test import ApiBaseTestCase from wger.core.tests.base_testcase import BaseTestCase class SearchIngredientApiTestCase(BaseTestCase, ApiBaseTestCase): url = '/api/v2/ingredient/search/' def setUp(self): super().setUp() self.init_media_root() def test_basic_search_logged_out(self): """ Logged-out users are also allowed to use the search """ response = self.client.get(self.url + '?term=test') result1 = response.data['suggestions'][0] self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data['suggestions']), 2) self.assertEqual(result1['value'], 'Ingredient, test, 2, organic, raw') self.assertEqual(result1['data']['id'], 2) def test_basic_search_logged_in(self): """ Logged-in users get the same results """ self.authenticate('test') response = self.client.get(self.url + '?term=test') result1 = response.data['suggestions'][0] self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data['suggestions']), 2) self.assertEqual(result1['value'], 'Ingredient, test, 2, organic, raw') self.assertEqual(result1['data']['id'], 2) def test_search_language_code_en(self): """ Explicitly passing the en language code (same as no code) """ response = self.client.get(self.url + '?term=test&language=en') result1 = response.data['suggestions'][0] self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data['suggestions']), 2) self.assertEqual(result1['value'], 'Ingredient, test, 2, organic, raw') self.assertEqual(result1['data']['id'], 2) def test_search_language_code_en_no_results(self): """ The "Testzutat" ingredient should not be found when searching in English """ response = self.client.get(self.url + '?term=Testzutat&language=en') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data['suggestions']), 0) def test_search_language_code_de(self): """ The "Testübung" exercise should be only found when searching in German """ response = self.client.get(self.url + '?term=Testzutat&language=de') result1 = response.data['suggestions'][0] self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data['suggestions']), 1) self.assertEqual(result1['value'], 'Testzutat 123') self.assertEqual(result1['data']['id'], 6) def test_search_several_language_codes(self): """ Passing different language codes works correctly """ response = self.client.get(self.url + '?term=guest&language=en,de') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data['suggestions']), 5) def test_search_unknown_language_codes(self): """ Unknown language codes are ignored """ response = self.client.get(self.url + '?term=guest&language=en,de,kg') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data['suggestions']), 5) def test_search_all_languages(self): """ Disable all language filters """ response = self.client.get(self.url + '?term=guest&language=*') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data['suggestions']), 7)
4,467
Python
.py
93
40.956989
80
0.677694
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,586
test_tasks.py
wger-project_wger/wger/nutrition/tests/test_tasks.py
# 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 # Standard Library from unittest.mock import ( ANY, patch, ) # wger from wger.core.tests.base_testcase import WgerTestCase from wger.nutrition.models import Ingredient from wger.nutrition.sync import ( fetch_ingredient_image, logger, ) from wger.utils.constants import ( DOWNLOAD_INGREDIENT_OFF, DOWNLOAD_INGREDIENT_WGER, ) from wger.utils.requests import wger_headers class MockOffResponse: def __init__(self): self.status_code = 200 self.ok = True self.content = b'2000' # yapf: disable @staticmethod def json(): return { "product": { 'image_front_url': 'https://images.openfoodfacts.org/images/products/00975957/front_en.5.400.jpg', 'images': { 'front_en': { 'imgid': '12345', }, '12345': { 'uploader': 'Mr Foobar' } } }, } # yapf: disable class MockWgerApiResponse: def __init__(self): self.status_code = 200 self.content = b'2000' # yapf: disable @staticmethod def json(): return { "count": 1, "next": None, "previous": None, "results": [ { "id": 1, "uuid": "188324b5-587f-42d7-9abc-d2ca64c73d45", "ingredient_id": "12345", "ingredient_uuid": "e9baa8bd-84fc-4756-8d90-5b9739b06cf8", "image": "http://localhost:8000/media/ingredients/1/188324b5-587f-42d7-9abc-d2ca64c73d45.jpg", "created": "2023-03-15T23:20:10.969369+01:00", "last_update": "2023-03-15T23:20:10.969369+01:00", "size": 20179, "width": 400, "height": 166, "license": 1, "license_author": "Tester McTest", "license_author_url": "https://example.com/editors/mcLovin", "license_title": "", "license_object_url": "", "license_derivative_source_url": "" } ] } # yapf: enable class FetchIngredientImageTestCase(WgerTestCase): """ Test fetching an ingredient image """ @patch('requests.get') @patch.object(logger, 'info') def test_source(self, mock_logger, mock_request): """ Test that sources other than OFF are ignored """ ingredient = Ingredient.objects.get(pk=1) ingredient.source_name = 'blabla' ingredient.save() with self.settings(WGER_SETTINGS={'DOWNLOAD_INGREDIENTS_FROM': True}): result = fetch_ingredient_image(1) mock_logger.assert_not_called() mock_request.assert_not_called() self.assertEqual(result, None) @patch('requests.get') @patch.object(logger, 'info') def test_download_off_setting(self, mock_logger, mock_request): """ Test that no images are fetched if the appropriate setting is not set """ ingredient = Ingredient.objects.get(pk=1) ingredient.source_name = 'blabla' ingredient.save() with self.settings(WGER_SETTINGS={'DOWNLOAD_INGREDIENTS_FROM': False}): result = fetch_ingredient_image(1) mock_logger.assert_not_called() mock_request.assert_not_called() self.assertEqual(result, None) @patch('requests.get', return_value=MockOffResponse()) @patch('wger.nutrition.models.Image.from_json') @patch.object(logger, 'info') def test_download_ingredient_off(self, mock_logger, mock_from_json, mock_request): """ Test that the image is correctly downloaded While this way of testing is fragile and depends on what exactly (and when) things are logged, it seems to work. Also, directly mocking the logger object could probably be done better """ with self.settings( WGER_SETTINGS={'DOWNLOAD_INGREDIENTS_FROM': DOWNLOAD_INGREDIENT_OFF}, TESTING=False, ): result = fetch_ingredient_image(1) # log1 = mock_logger.mock_calls[0] # print(log1) mock_logger.assert_any_call('Fetching image for ingredient 1') mock_logger.assert_any_call( 'Trying to fetch image from OFF for Test ingredient 1 (UUID: ' '7908c204-907f-4b1e-ad4e-f482e9769ade)' ) mock_logger.assert_any_call('Image successfully saved') mock_request.assert_any_call( 'https://world.openfoodfacts.org/api/v2/product/5055365635003.json?fields=images,image_front_url', headers=wger_headers(), timeout=ANY, ) mock_request.assert_any_call( 'https://openfoodfacts-images.s3.eu-west-3.amazonaws.com/data/123/456/789/0987/654321/12345.jpg', headers=wger_headers(), ) mock_from_json.assert_called() self.assertEqual(result, None) @patch('requests.get', return_value=MockWgerApiResponse()) @patch('wger.nutrition.models.Image.from_json') @patch.object(logger, 'info') def test_download_ingredient_wger(self, mock_logger, mock_from_json, mock_request): """ Test that the image is correctly downloaded While this way of testing is fragile and depends on what exactly (and when) things are logged, it seems to work. Also, directly mocking the logger object could probably be done better """ with self.settings( WGER_SETTINGS={'DOWNLOAD_INGREDIENTS_FROM': DOWNLOAD_INGREDIENT_WGER}, TESTING=False ): result = fetch_ingredient_image(1) mock_logger.assert_any_call('Fetching image for ingredient 1') mock_logger.assert_any_call( 'Trying to fetch image from WGER for Test ingredient 1 (UUID: ' '7908c204-907f-4b1e-ad4e-f482e9769ade)' ) mock_request.assert_any_call( 'https://wger.de/api/v2/ingredient-image/?ingredient__uuid=7908c204-907f-4b1e-ad4e-f482e9769ade', headers=wger_headers(), ) mock_request.assert_any_call( 'http://localhost:8000/media/ingredients/1/188324b5-587f-42d7-9abc-d2ca64c73d45.jpg', headers=wger_headers(), ) mock_from_json.assert_called() self.assertEqual(result, None)
7,463
Python
.py
183
30.393443
114
0.597877
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,587
test_weight_unit.py
wger-project_wger/wger/nutrition/tests/test_weight_unit.py
# 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/>. # Django from django.urls import reverse # wger from wger.core.tests import api_base_test from wger.core.tests.base_testcase import ( WgerAddTestCase, WgerDeleteTestCase, WgerEditTestCase, WgerTestCase, ) from wger.nutrition.models import WeightUnit from wger.utils.constants import PAGINATION_OBJECTS_PER_PAGE class WeightUnitRepresentationTestCase(WgerTestCase): """ Test the representation of a model """ def test_representation(self): """ Test that the representation of an object is correct """ self.assertEqual(str(WeightUnit.objects.get(pk=1)), 'Scheibe') class AddWeightUnitTestCase(WgerAddTestCase): """ Tests adding a new weight unit """ object_class = WeightUnit url = 'nutrition:weight_unit:add' data = {'name': 'A new weight unit'} class DeleteWeightUnitTestCase(WgerDeleteTestCase): """ Tests deleting a weight unit """ object_class = WeightUnit url = 'nutrition:weight_unit:delete' pk = 1 class EditWeightUnitTestCase(WgerEditTestCase): """ Tests editing a weight unit """ object_class = WeightUnit url = 'nutrition:weight_unit:edit' pk = 1 data = {'name': 'A new name'} class WeightUnitOverviewTestCase(WgerTestCase): """ Tests the ingredient unit overview page """ def test_overview(self): # Add more ingredient units so we can test the pagination self.user_login('admin') data = {'name': 'A new, cool unit', 'language': 2} for i in range(0, 50): self.client.post(reverse('nutrition:weight_unit:add'), data) # Page exists and the pagination works response = self.client.get(reverse('nutrition:weight_unit:list')) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.context['unit_list']), PAGINATION_OBJECTS_PER_PAGE) response = self.client.get(reverse('nutrition:weight_unit:list'), {'page': 2}) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.context['unit_list']), PAGINATION_OBJECTS_PER_PAGE) response = self.client.get(reverse('nutrition:weight_unit:list'), {'page': 3}) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.context['unit_list']), 3) # 'last' is a special case response = self.client.get(reverse('nutrition:weight_unit:list'), {'page': 'last'}) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.context['unit_list']), 3) # Page does not exist response = self.client.get(reverse('nutrition:weight_unit:list'), {'page': 100}) self.assertEqual(response.status_code, 404) response = self.client.get(reverse('nutrition:weight_unit:list'), {'page': 'foobar'}) self.assertEqual(response.status_code, 404) class WeightUnitApiTestCase(api_base_test.ApiBaseResourceTestCase): """ Tests the weight unit overview resource """ pk = 1 resource = WeightUnit private_resource = False data = {'name': 'The weight unit name'}
3,858
Python
.py
94
35.723404
93
0.705457
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,588
test_usda.py
wger-project_wger/wger/nutrition/tests/test_usda.py
# 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/>. # Django from django.test import SimpleTestCase # wger from wger.nutrition.dataclasses import IngredientData from wger.nutrition.usda import ( convert_to_grams, extract_info_from_usda, ) from wger.utils.constants import CC_0_LICENSE_ID class ExtractInfoFromUSDATestCase(SimpleTestCase): """ Test the extract_info_from_usda function """ usda_data1 = {} def setUp(self): self.usda_data1 = { 'foodClass': 'FinalFood', 'description': 'FOO WITH CHOCOLATE', 'foodNutrients': [ { 'type': 'FoodNutrient', 'id': 2259514, 'nutrient': { 'id': 1170, 'number': '410', 'name': 'Pantothenic acid', 'rank': 6700, 'unitName': 'mg', }, 'dataPoints': 2, 'foodNutrientDerivation': { 'code': 'A', 'description': 'Analytical', 'foodNutrientSource': { 'id': 1, 'code': '1', 'description': 'Analytical or derived from analytical', }, }, 'max': 1.64, 'min': 1.53, 'median': 1.58, 'amount': 1.58, }, { 'type': 'FoodNutrient', 'id': 2259524, 'nutrient': { 'id': 1004, 'number': '204', 'name': 'Total lipid (fat)', 'rank': 800, 'unitName': 'g', }, 'dataPoints': 6, 'foodNutrientDerivation': { 'code': 'A', 'description': 'Analytical', 'foodNutrientSource': { 'id': 1, 'code': '1', 'description': 'Analytical or derived from analytical', }, }, 'max': 3.99, 'min': 2.17, 'median': 3.26, 'amount': 3.24, }, { 'type': 'FoodNutrient', 'id': 2259525, 'nutrient': { 'id': 1005, 'number': '205', 'name': 'Carbohydrate, by difference', 'rank': 1110, 'unitName': 'g', }, 'foodNutrientDerivation': { 'code': 'NC', 'description': 'Calculated', 'foodNutrientSource': { 'id': 2, 'code': '4', 'description': 'Calculated or imputed', }, }, 'amount': 0.000, }, { 'type': 'FoodNutrient', 'id': 2259526, 'nutrient': { 'id': 1008, 'number': '208', 'name': 'Energy', 'rank': 300, 'unitName': 'kcal', }, 'foodNutrientDerivation': { 'code': 'NC', 'description': 'Calculated', 'foodNutrientSource': { 'id': 2, 'code': '4', 'description': 'Calculated or imputed', }, }, 'amount': 166, }, { 'type': 'FoodNutrient', 'id': 2259565, 'nutrient': { 'id': 1003, 'number': '203', 'name': 'Protein', 'rank': 600, 'unitName': 'g', }, 'foodNutrientDerivation': { 'code': 'NC', 'description': 'Calculated', 'foodNutrientSource': { 'id': 2, 'code': '4', 'description': 'Calculated or imputed', }, }, 'max': 32.9, 'min': 31.3, 'median': 32.1, 'amount': 32.1, }, ], 'foodAttributes': [], 'nutrientConversionFactors': [ { 'type': '.CalorieConversionFactor', 'proteinValue': 4.27, 'fatValue': 9.02, 'carbohydrateValue': 3.87, }, {'type': '.ProteinConversionFactor', 'value': 6.25}, ], 'isHistoricalReference': False, 'ndbNumber': 5746, 'foodPortions': [ { 'id': 121343, 'value': 1.0, 'measureUnit': {'id': 1043, 'name': 'piece', 'abbreviation': 'piece'}, 'gramWeight': 174.0, 'sequenceNumber': 1, 'minYearAcquired': 2012, 'amount': 1.0, } ], 'publicationDate': '4/1/2019', 'inputFoods': [ { 'id': 11213, 'foodDescription': 'Lorem ipsum', 'inputFood': { 'foodClass': 'Composite', 'description': '......', 'publicationDate': '4/1/2019', 'foodCategory': { 'id': 5, 'code': '0500', 'description': 'Poultry Products', }, 'fdcId': 331904, 'dataType': 'Sample', }, }, ], 'foodCategory': {'description': 'Poultry Products'}, 'fdcId': 1234567, 'dataType': 'Foundation', } def test_regular_response(self): """ Test that the function can read the regular case """ result = extract_info_from_usda(self.usda_data1, 1) data = IngredientData( name='Foo With Chocolate', remote_id='1234567', language_id=1, energy=166.0, protein=32.1, carbohydrates=0.0, carbohydrates_sugar=None, fat=3.24, fat_saturated=None, fiber=None, sodium=None, code=None, source_name='USDA', source_url='https://fdc.nal.usda.gov/', common_name='Foo With Chocolate', brand='', license_id=CC_0_LICENSE_ID, license_author='U.S. Department of Agriculture, Agricultural Research Service, ' 'Beltsville Human Nutrition Research Center. FoodData Central.', license_title='Foo With Chocolate', license_object_url='https://fdc.nal.usda.gov/fdc-app.html#/food-details/1234567/nutrients', ) self.assertEqual(result, data) def test_no_energy(self): """ No energy available """ del self.usda_data1['foodNutrients'][3] self.assertRaises(KeyError, extract_info_from_usda, self.usda_data1, 1) def test_no_nutrients(self): """ No nutrients available """ del self.usda_data1['foodNutrients'] self.assertRaises(KeyError, extract_info_from_usda, self.usda_data1, 1) def test_converting_grams(self): """ Convert from grams (nothing changes) """ entry = {'nutrient': {'unitName': 'g'}, 'amount': '5.0'} self.assertEqual(convert_to_grams(entry), 5.0) def test_converting_milligrams(self): """ Convert from milligrams """ entry = {'nutrient': {'unitName': 'mg'}, 'amount': '5000'} self.assertEqual(convert_to_grams(entry), 5.0) def test_converting_unknown_unit(self): """ Convert from unknown unit """ entry = {'nutrient': {'unitName': 'kg'}, 'amount': '5.0'} self.assertRaises(ValueError, convert_to_grams, entry) def test_converting_invalid_amount(self): """ Convert from invalid amount """ entry = {'nutrient': {'unitName': 'g'}, 'amount': 'invalid'} self.assertRaises(ValueError, convert_to_grams, entry)
9,874
Python
.py
261
21.172414
103
0.412133
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,589
test_weight_unit_ingredient.py
wger-project_wger/wger/nutrition/tests/test_weight_unit_ingredient.py
# 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/>. # Django from django.urls import ( reverse, reverse_lazy, ) # wger from wger.core.tests import api_base_test from wger.core.tests.base_testcase import ( WgerAddTestCase, WgerDeleteTestCase, WgerEditTestCase, WgerTestCase, ) from wger.nutrition.models import ( IngredientWeightUnit, WeightUnit, ) class WeightUnitIngredientRepresentationTestCase(WgerTestCase): """ Test the representation of a model """ def test_representation(self): """ Test that the representation of an object is correct """ self.assertEqual(str(IngredientWeightUnit.objects.get(pk=1)), 'Spoon (109g)') class AddWeightUnitIngredientTestCase(WgerAddTestCase): """ Tests adding a new weight unit to an ingredient """ object_class = IngredientWeightUnit url = reverse_lazy('nutrition:unit_ingredient:add', kwargs={'ingredient_pk': 1}) data = { 'unit': 5, 'gram': 123, 'amount': 1, } class DeleteWeightUnitIngredientTestCase(WgerDeleteTestCase): """ Tests deleting a weight unit from an ingredient """ object_class = IngredientWeightUnit url = 'nutrition:unit_ingredient:delete' pk = 1 class EditWeightUnitTestCase(WgerEditTestCase): """ Tests editing a weight unit from an ingredient """ object_class = IngredientWeightUnit url = 'nutrition:unit_ingredient:edit' pk = 1 data = { 'unit': 5, 'gram': 10, 'amount': 0.3, } class WeightUnitFormTestCase(WgerTestCase): """ Tests the form for the weight units """ def test_add_weight_unit(self): """ Tests the form in the add view """ self.user_login('admin') response = self.client.get( reverse('nutrition:unit_ingredient:add', kwargs={'ingredient_pk': 1}) ) choices = [text for value, text in response.context['form']['unit'].field.choices] for unit in WeightUnit.objects.all(): if unit.language_id == 1: self.assertNotIn(unit.name, choices) else: self.assertIn(unit.name, choices) def test_edit_weight_unit(self): """ Tests that the form in the edit view only shows weight units in the user's language """ self.user_login('admin') response = self.client.get(reverse('nutrition:unit_ingredient:edit', kwargs={'pk': 1})) choices = [text for value, text in response.context['form']['unit'].field.choices] for unit in WeightUnit.objects.all(): if unit.language_id == 1: self.assertNotIn(unit.name, choices) else: self.assertIn(unit.name, choices) class WeightUnitToIngredientApiTestCase(api_base_test.ApiBaseResourceTestCase): """ Tests the weight unit to ingredient API resource """ pk = 1 resource = IngredientWeightUnit private_resource = False data = { 'amount': '1', 'gram': 240, 'id': 1, 'ingredient': '1', 'unit': '1', }
3,822
Python
.py
114
27.517544
95
0.665943
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,590
test_nutritional_values.py
wger-project_wger/wger/nutrition/tests/test_nutritional_values.py
# 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 # Django from django.test import SimpleTestCase # wger from wger.nutrition.helpers import NutritionalValues class NutritionalValuesTestCase(SimpleTestCase): """ Tests the Nutritional Values dataclass methods """ def test_kj_property(self): """ Test that the KJ conversion is correct """ values = NutritionalValues(energy=100) self.assertAlmostEqual(values.energy_kilojoule, 418.4, places=3) def test_addition(self): """Test that the addition works correctly""" values1 = NutritionalValues( energy=100, protein=90, carbohydrates=80, carbohydrates_sugar=70, fat=60, fat_saturated=50, fiber=40, sodium=30, ) values2 = NutritionalValues( energy=10, protein=9, carbohydrates=8, carbohydrates_sugar=7, fat=6, fat_saturated=5, fiber=4, sodium=3, ) values3 = values1 + values2 self.assertEqual( values3, NutritionalValues( energy=110, protein=99, carbohydrates=88, carbohydrates_sugar=77, fat=66, fat_saturated=55, fiber=44, sodium=33, ), ) def test_addition_nullable_values(self): """Test that the addition works correctly for the nullable values""" values1 = NutritionalValues() values2 = NutritionalValues(carbohydrates_sugar=10, fat_saturated=20, fiber=30, sodium=40) values3 = values1 + values2 self.assertEqual( values3, NutritionalValues( energy=0, protein=0, carbohydrates=0, carbohydrates_sugar=10, fat=0, fat_saturated=20, fiber=30, sodium=40, ), )
2,696
Python
.py
81
23.567901
98
0.594626
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,591
test_ingredient.py
wger-project_wger/wger/nutrition/tests/test_ingredient.py
# 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 json from decimal import Decimal from unittest.mock import patch # Django from django.core.exceptions import ValidationError from django.urls import reverse # Third Party from rest_framework import status # wger from wger.core.models import Language from wger.core.tests import api_base_test from wger.core.tests.api_base_test import ApiBaseTestCase from wger.core.tests.base_testcase import ( BaseTestCase, WgerAddTestCase, WgerDeleteTestCase, WgerEditTestCase, WgerTestCase, ) from wger.nutrition.models import ( Ingredient, Meal, ) from wger.utils.constants import NUTRITION_TAB class IngredientRepresentationTestCase(WgerTestCase): """ Test the representation of a model """ def test_representation(self): """ Test that the representation of an object is correct """ self.assertEqual(str(Ingredient.objects.get(pk=1)), 'Test ingredient 1') class DeleteIngredientTestCase(WgerDeleteTestCase): """ Tests deleting an ingredient """ object_class = Ingredient url = 'nutrition:ingredient:delete' pk = 1 class EditIngredientTestCase(WgerEditTestCase): """ Tests editing an ingredient """ object_class = Ingredient url = 'nutrition:ingredient:edit' pk = 1 data = { 'name': 'A new name', 'sodium': 2, 'energy': 200, 'fat': 10, 'carbohydrates_sugar': 5, 'fat_saturated': 3.14, 'fiber': 2.1, 'protein': 20, 'carbohydrates': 10, 'license': 2, 'license_author': 'me!', } def post_test_hook(self): """ Test that the update date is correctly set """ if self.current_user == 'admin': ingredient = Ingredient.objects.get(pk=1) self.assertEqual( ingredient.last_update.replace(microsecond=0), datetime.datetime.now(tz=datetime.timezone.utc).replace(microsecond=0), ) class AddIngredientTestCase(WgerAddTestCase): """ Tests adding an ingredient """ object_class = Ingredient url = 'nutrition:ingredient:add' user_fail = False data = { 'name': 'A new ingredient', 'sodium': 2, 'energy': 200, 'fat': 10, 'carbohydrates_sugar': 5, 'fat_saturated': 3.14, 'fiber': 2.1, 'protein': 20, 'carbohydrates': 10, 'license': 2, 'license_author': 'me!', } def post_test_hook(self): """ Test that the creation date and the status are correctly set """ if self.current_user == 'admin': ingredient = Ingredient.objects.get(pk=self.pk_after) self.assertEqual( ingredient.created.replace(microsecond=0), datetime.datetime.now(tz=datetime.timezone.utc).replace(microsecond=0), ) elif self.current_user == 'test': ingredient = Ingredient.objects.get(pk=self.pk_after) class IngredientNameShortTestCase(WgerTestCase): """ Tests that ingredient cannot have name with length less than 3 """ data = { 'name': 'Ui', 'sodium': 2, 'energy': 200, 'fat': 10, 'carbohydrates_sugar': 5, 'fat_saturated': 3.14, 'fiber': 2.1, 'protein': 20, 'carbohydrates': 10, 'license': 2, 'license_author': 'me!', } def test_add_ingredient_short_name(self): """ Test that ingredient cannot be added with name of length less than 3 """ self.user_login('admin') count_before = Ingredient.objects.count() response = self.client.post(reverse('nutrition:ingredient:add'), self.data) count_after = Ingredient.objects.count() self.assertEqual(response.status_code, 200) # Ingredient was not added self.assertEqual(count_before, count_after) def test_edit_ingredient_short_name(self): """ Test that ingredient cannot be edited to name of length less than 3 """ self.user_login('admin') response = self.client.post( reverse('nutrition:ingredient:edit', kwargs={'pk': '1'}), self.data ) self.assertEqual(response.status_code, 200) ingredient = Ingredient.objects.get(pk=1) # Ingredient was not edited self.assertNotEqual(ingredient.last_update.date(), datetime.date.today()) class IngredientDetailTestCase(WgerTestCase): """ Tests the ingredient details page """ def ingredient_detail(self, editor=False): """ Tests the ingredient details page """ response = self.client.get(reverse('nutrition:ingredient:view', kwargs={'pk': 6})) self.assertEqual(response.status_code, 200) # Correct tab is selected self.assertEqual(response.context['active_tab'], NUTRITION_TAB) self.assertTrue(response.context['ingredient']) # Only authorized users see the edit links if editor: self.assertContains(response, 'Edit ingredient') self.assertContains(response, 'Delete ingredient') else: self.assertNotContains(response, 'Edit ingredient') self.assertNotContains(response, 'Delete ingredient') # Non-existent ingredients throw a 404. response = self.client.get(reverse('nutrition:ingredient:view', kwargs={'pk': 42})) self.assertEqual(response.status_code, 404) def test_ingredient_detail_editor(self): """ Tests the ingredient details page as a logged-in user with editor rights """ self.user_login('admin') self.ingredient_detail(editor=True) def test_ingredient_detail_non_editor(self): """ Tests the ingredient details page as a logged-in user without editor rights """ self.user_login('test') self.ingredient_detail(editor=False) def test_ingredient_detail_logged_out(self): """ Tests the ingredient details page as an anonymous (logged out) user """ self.ingredient_detail(editor=False) class IngredientSearchTestCase(WgerTestCase): """ Tests the ingredient search functions """ def search_ingredient(self, fail=True): """ Helper function """ kwargs = {'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'} response = self.client.get(reverse('ingredient-search'), {'term': 'test'}, **kwargs) self.assertEqual(response.status_code, 200) result = json.loads(response.content.decode('utf8')) self.assertEqual(len(result['suggestions']), 2) self.assertEqual(result['suggestions'][0]['value'], 'Ingredient, test, 2, organic, raw') self.assertEqual(result['suggestions'][0]['data']['id'], 2) suggestion_0_name = 'Ingredient, test, 2, organic, raw' self.assertEqual(result['suggestions'][0]['data']['name'], suggestion_0_name) self.assertEqual(result['suggestions'][0]['data']['image'], None) self.assertEqual(result['suggestions'][0]['data']['image_thumbnail'], None) self.assertEqual(result['suggestions'][1]['value'], 'Test ingredient 1') self.assertEqual(result['suggestions'][1]['data']['id'], 1) self.assertEqual(result['suggestions'][1]['data']['name'], 'Test ingredient 1') self.assertEqual(result['suggestions'][1]['data']['image'], None) self.assertEqual(result['suggestions'][1]['data']['image_thumbnail'], None) def test_search_ingredient_anonymous(self): """ Test searching for an ingredient by an anonymous user """ self.search_ingredient() def test_search_ingredient_logged_in(self): """ Test searching for an ingredient by a logged-in user """ self.user_login('test') self.search_ingredient() class IngredientValuesTestCase(WgerTestCase): """ Tests the nutritional value calculator for an ingredient """ def calculate_value(self): """ Helper function """ # Get the nutritional values in 1 gram of product response = self.client.get( reverse('api-ingredient-get-values', kwargs={'pk': 1}), {'amount': 1, 'ingredient': 1, 'unit': ''}, ) self.assertEqual(response.status_code, 200) result = json.loads(response.content.decode('utf8')) self.assertEqual(len(result), 8) self.assertEqual( result, { 'sodium': 0.00549, 'energy': 1.76, # 'energy_kilojoule': '7.36', 'fat': 0.0819, 'carbohydrates_sugar': None, 'fat_saturated': 0.03244, 'fiber': None, 'protein': 0.2563, 'carbohydrates': 0.00125, }, ) # Get the nutritional values in 1 unit of product response = self.client.get( reverse('api-ingredient-get-values', kwargs={'pk': 1}), {'amount': 1, 'ingredient': 1, 'unit': 2}, ) self.assertEqual(response.status_code, 200) result = json.loads(response.content.decode('utf8')) self.assertEqual(len(result), 8) self.assertEqual( result, { 'sodium': 0.612135, 'energy': 196.24, # 'energy_kilojoule': '821.07', 'fat': 9.13185, 'carbohydrates_sugar': None, 'fat_saturated': 3.61706, 'fiber': None, 'protein': 28.57745, 'carbohydrates': 0.139375, }, ) def test_calculate_value_anonymous(self): """ Calculate the nutritional values as an anonymous user """ self.calculate_value() def test_calculate_value_logged_in(self): """ Calculate the nutritional values as a logged-in user """ self.user_login('test') self.calculate_value() class IngredientTestCase(WgerTestCase): """ Tests other ingredient functions """ def test_compare(self): """ Tests the custom compare method based on values """ language = Language.objects.get(pk=1) ingredient1 = Ingredient.objects.get(pk=1) ingredient2 = Ingredient.objects.get(pk=1) ingredient2.name = 'A different name altogether' self.assertFalse(ingredient1 == ingredient2) ingredient1 = Ingredient() ingredient1.name = 'ingredient name' ingredient1.energy = 150 ingredient1.protein = 30 ingredient1.language = language ingredient2 = Ingredient() ingredient2.name = 'ingredient name' ingredient2.energy = 150 ingredient2.language = language self.assertFalse(ingredient1 == ingredient2) ingredient2.protein = 31 self.assertFalse(ingredient1 == ingredient2) ingredient2.protein = None self.assertFalse(ingredient1 == ingredient2) ingredient2.protein = 30 self.assertEqual(ingredient1, ingredient2) meal = Meal.objects.get(pk=1) self.assertFalse(ingredient1 == meal) def test_total_energy(self): """ Tests the custom clean() method """ self.user_login('admin') # Values OK ingredient = Ingredient() ingredient.name = 'FooBar, cooked, with salt' ingredient.energy = 50 ingredient.protein = 0.5 ingredient.carbohydrates = 12 ingredient.fat = Decimal('0.1') ingredient.language_id = 1 self.assertFalse(ingredient.full_clean()) # Values wrong ingredient.protein = 20 self.assertRaises(ValidationError, ingredient.full_clean) ingredient.protein = 0.5 ingredient.fat = 5 self.assertRaises(ValidationError, ingredient.full_clean) ingredient.fat = 0.1 ingredient.carbohydrates = 20 self.assertRaises(ValidationError, ingredient.full_clean) ingredient.fat = 5 ingredient.carbohydrates = 20 self.assertRaises(ValidationError, ingredient.full_clean) class IngredientApiTestCase(api_base_test.ApiBaseResourceTestCase): """ Tests the ingredient API resource """ pk = 4 resource = Ingredient private_resource = False overview_cached = True data = {'language': 1, 'license': 2} class IngredientModelTestCase(WgerTestCase): """ Tests the ingredient model functions """ def setUp(self): super().setUp() self.off_response = { 'code': '1234', 'lang': 'de', 'product_name': 'Foo with chocolate', 'generic_name': 'Foo with chocolate, 250g package', 'brands': 'The bar company', 'editors_tags': ['open food facts', 'MrX'], 'nutriments': { 'energy-kcal_100g': 120, 'proteins_100g': 10, 'carbohydrates_100g': 20, 'sugars_100g': 30, 'fat_100g': 40, 'saturated-fat_100g': 11, 'sodium_100g': 5, 'fiber_100g': None, }, } self.off_response_no_results = None @patch('openfoodfacts.api.ProductResource.get') def test_fetch_from_off_success(self, mock_api): """ Tests creating an ingredient from OFF """ mock_api.return_value = self.off_response ingredient = Ingredient.fetch_ingredient_from_off('1234') self.assertEqual(ingredient.name, 'Foo with chocolate') self.assertEqual(ingredient.code, '1234') self.assertEqual(ingredient.energy, 120) self.assertEqual(ingredient.protein, 10) self.assertEqual(ingredient.carbohydrates, 20) self.assertEqual(ingredient.fat, 40) self.assertEqual(ingredient.fat_saturated, 11) self.assertEqual(ingredient.sodium, 5) self.assertEqual(ingredient.fiber, None) self.assertEqual(ingredient.brand, 'The bar company') self.assertEqual(ingredient.license_author, 'open food facts, MrX') @patch('openfoodfacts.api.ProductResource.get') def test_fetch_from_off_success_long_name(self, mock_api): """ Tests creating an ingredient from OFF - name gets truncated """ self.off_response['product_name'] = """ The Shiba Inu (柴犬, Japanese: [ɕiba inɯ]) is a breed of hunting dog from Japan. A small-to-medium breed, it is the smallest of the six original and distinct spitz breeds of dog native to Japan.[1] Its name literally translates to "brushwood dog", as it is used to flush game.""" mock_api.return_value = self.off_response ingredient = Ingredient.fetch_ingredient_from_off('1234') self.assertEqual(len(ingredient.name), 200) @patch('openfoodfacts.api.ProductResource.get') def test_fetch_from_off_key_missing_1(self, mock_api): """ Tests creating an ingredient from OFF - missing key in nutriments """ del self.off_response['nutriments']['energy-kcal_100g'] mock_api.return_value = self.off_response ingredient = Ingredient.fetch_ingredient_from_off('1234') self.assertIsNone(ingredient) @patch('openfoodfacts.api.ProductResource.get') def test_fetch_from_off_key_missing_2(self, mock_api): """ Tests creating an ingredient from OFF - missing name """ del self.off_response['product_name'] mock_api.return_value = self.off_response ingredient = Ingredient.fetch_ingredient_from_off('1234') self.assertIsNone(ingredient) @patch('openfoodfacts.api.ProductResource.get') def test_fetch_from_off_no_results(self, mock_api): """ Tests creating an ingredient from OFF """ mock_api.return_value = self.off_response_no_results ingredient = Ingredient.fetch_ingredient_from_off('1234') self.assertIsNone(ingredient) class IngredientApiCodeSearch(BaseTestCase, ApiBaseTestCase): url = '/api/v2/ingredient/' @patch('wger.nutrition.models.Ingredient.fetch_ingredient_from_off') def test_search_existing_code(self, mock_fetch_from_off): """ Test that when a code already exists, no off sync happens """ response = self.client.get(self.url + '?code=1234567890987654321') mock_fetch_from_off.assert_not_called() self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data['count'], 1) @patch('wger.nutrition.models.Ingredient.fetch_ingredient_from_off') def test_search_new_code(self, mock_fetch_from_off): """ Test that when a code isn't present, it will be fetched """ response = self.client.get(self.url + '?code=122333444455555666666') mock_fetch_from_off.assert_called_with('122333444455555666666') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data['count'], 0)
18,057
Python
.py
464
30.489224
96
0.631612
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,592
test_meal.py
wger-project_wger/wger/nutrition/tests/test_meal.py
# 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 # wger from wger.core.tests import api_base_test from wger.nutrition.models import Meal class MealApiTestCase(api_base_test.ApiBaseResourceTestCase): """ Tests the meal overview resource """ pk = 2 resource = Meal private_resource = True special_endpoints = ('nutritional_values',) data = { 'time': datetime.time(9, 2), 'plan': 4, 'order': 1, }
1,159
Python
.py
32
33.1875
78
0.740642
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,593
test_nutritional_cache.py
wger-project_wger/wger/nutrition/tests/test_nutritional_cache.py
# Django from django.contrib.auth.models import User from django.core.cache import cache # wger from wger.core.models import Language from wger.core.tests.base_testcase import WgerTestCase from wger.nutrition.models import ( Meal, MealItem, NutritionPlan, ) from wger.utils.cache import cache_mapper class NutritionalPlanCacheTestCase(WgerTestCase): def create_nutrition_plan(self): """ Create a nutrition plan and set dummy attributes that are required Create meal and set dummy attributes that are required Create meal item and set dummy attributes that are required """ plan = NutritionPlan() plan.user = User.objects.create_user(username='example_user_1') plan.language = Language.objects.get(short_name='en') plan.save() meal = Meal() meal.plan = plan meal.order = 1 meal.save() meal_item = MealItem() meal_item.id = 1 meal_item.meal = meal meal_item.amount = 1 meal_item.ingredient_id = 1 meal_item.order = 1 test_objects = [plan, meal, meal_item] return test_objects def test_cache_setting(self): """ Test that a cache is set once the nutritional instance is created """ plan = self.create_nutrition_plan()[0] self.assertFalse(cache.get(cache_mapper.get_nutrition_cache_by_key(plan))) plan.get_nutritional_values() self.assertTrue(cache.get(cache_mapper.get_nutrition_cache_by_key(plan))) def test_nutrition_save_and_delete(self): """ Test that cache is deleted when a nutrition is created or deleted. """ plan = self.create_nutrition_plan()[0] plan.get_nutritional_values() self.assertTrue(cache.get(cache_mapper.get_nutrition_cache_by_key(plan))) plan.save() self.assertFalse(cache.get(cache_mapper.get_nutrition_cache_by_key(plan))) plan.get_nutritional_values() self.assertTrue(cache.get(cache_mapper.get_nutrition_cache_by_key(plan))) plan.delete() self.assertFalse(cache.get(cache_mapper.get_nutrition_cache_by_key(plan))) def test_meal_save_delete(self): """ Test that the cache is deleted once a meal undergoes a save or delete operation """ test_object_list = self.create_nutrition_plan() plan = test_object_list[0] meal = test_object_list[1] plan.get_nutritional_values() self.assertTrue(cache.get(cache_mapper.get_nutrition_cache_by_key(plan))) meal.save() self.assertFalse(cache.get(cache_mapper.get_nutrition_cache_by_key(plan.pk))) plan.get_nutritional_values() self.assertTrue(cache.get(cache_mapper.get_nutrition_cache_by_key(plan))) meal.delete() self.assertFalse(cache.get(cache_mapper.get_nutrition_cache_by_key(plan))) def test_meal_item_save_delete(self): """ Test that the cache is deleted once a meal undergoes a save or delete operation """ test_object_list = self.create_nutrition_plan() plan = test_object_list[0] meal_item = test_object_list[2] plan.get_nutritional_values() self.assertTrue(cache.get(cache_mapper.get_nutrition_cache_by_key(plan))) meal_item.save() self.assertFalse(cache.get(cache_mapper.get_nutrition_cache_by_key(plan.pk))) plan.get_nutritional_values() self.assertTrue(cache.get(cache_mapper.get_nutrition_cache_by_key(plan))) meal_item.delete() self.assertFalse(cache.get(cache_mapper.get_nutrition_cache_by_key(meal_item)))
3,664
Python
.py
86
34.825581
87
0.66844
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,594
test_ingredient_overview.py
wger-project_wger/wger/nutrition/tests/test_ingredient_overview.py
# 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/>. # Django from django.urls import reverse # wger from wger.core.tests.base_testcase import WgerTestCase from wger.utils.constants import PAGINATION_OBJECTS_PER_PAGE class IngredientOverviewTestCase(WgerTestCase): """ Tests the ingredient overview """ def test_overview(self): # Add more ingredients so we can test the pagination self.user_login('admin') data = { 'name': 'Test ingredient', 'language': 2, 'sodium': 10.54, 'energy': 176, 'fat': 8.19, 'carbohydrates_sugar': 0.0, 'fat_saturated': 3.24, 'fiber': 0.0, 'protein': 25.63, 'carbohydrates': 0.0, 'license': 1, 'license_author': 'internet', } for i in range(0, 50): self.client.post(reverse('nutrition:ingredient:add'), data) # Page exists self.user_logout() response = self.client.get(reverse('nutrition:ingredient:list')) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.context['ingredients_list']), PAGINATION_OBJECTS_PER_PAGE) response = self.client.get(reverse('nutrition:ingredient:list'), {'page': 2}) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.context['ingredients_list']), PAGINATION_OBJECTS_PER_PAGE) rest_ingredients = 11 response = self.client.get(reverse('nutrition:ingredient:list'), {'page': 3}) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.context['ingredients_list']), rest_ingredients) # 'last' is a special case response = self.client.get(reverse('nutrition:ingredient:list'), {'page': 'last'}) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.context['ingredients_list']), rest_ingredients) # Page does not exist response = self.client.get(reverse('nutrition:ingredient:list'), {'page': 100}) self.assertEqual(response.status_code, 404) response = self.client.get(reverse('nutrition:ingredient:list'), {'page': 'foobar'}) self.assertEqual(response.status_code, 404) def ingredient_overview(self): """ Helper function to test the ingredient overview page """ # Page exists response = self.client.get(reverse('nutrition:ingredient:list')) self.assertEqual(response.status_code, 200) def test_ingredient_index_editor(self): """ Tests the ingredient overview page as a logged-in user with editor rights """ self.user_login('admin') self.ingredient_overview() def test_ingredient_index_non_editor(self): """ Tests the overview page as a logged-in user without editor rights """ self.user_login('test') self.ingredient_overview() def test_ingredient_index_demo_user(self): """ Tests the overview page as a logged in demo user """ self.user_login('demo') self.ingredient_overview() def test_ingredient_index_logged_out(self): """ Tests the overview page as an anonymous (logged out) user """ self.ingredient_overview()
4,035
Python
.py
93
35.709677
96
0.661056
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,595
test_copy_plan.py
wger-project_wger/wger/nutrition/tests/test_copy_plan.py
# 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 # Django from django.urls import reverse # wger from wger.core.tests.base_testcase import WgerTestCase from wger.nutrition.models import NutritionPlan class CopyPlanTestCase(WgerTestCase): """ Tests copying a nutritional plan """ def copy_plan(self, fail=False): """ Helper function to test copying nutrition plans """ # Open the copy nutritional plan form response = self.client.get(reverse('nutrition:plan:copy', kwargs={'pk': 4})) if fail: self.assertIn(response.status_code, (302, 403, 404)) else: self.assertEqual(response.status_code, 302) # Copy the plan count_before = NutritionPlan.objects.count() response = self.client.post( reverse('nutrition:plan:copy', kwargs={'pk': 4}), {'comment': 'A copied plan'}, ) count_after = NutritionPlan.objects.count() if fail: self.assertEqual(count_before, count_after) else: self.assertGreater(count_after, count_before) self.assertEqual(count_after, 7) def test_copy_plan_anonymous(self): """ Test copying a nutritional plan as an anonymous user """ self.copy_plan(fail=True) def test_copy_plan_owner(self): """ Test copying a nutritional plan as the owner user """ self.user_login('test') self.copy_plan(fail=False) def test_copy_plan_other(self): """ Test copying a nutritional plan as a logged in user not owning the plan """ self.user_login('admin') self.copy_plan(fail=True)
2,316
Python
.py
61
31.229508
84
0.668452
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,596
test_bmi.py
wger-project_wger/wger/nutrition/tests/test_bmi.py
# 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 # Standard Library import datetime import json from decimal import Decimal # Django from django.contrib.auth.models import User from django.urls import reverse # wger from wger.core.models import UserProfile from wger.core.tests.base_testcase import WgerTestCase from wger.utils.constants import TWOPLACES from wger.weight.models import WeightEntry class BmiTestCase(WgerTestCase): """ Tests the BMI methods and views """ def test_page(self): """ Access the BMI page """ response = self.client.get(reverse('nutrition:bmi:view')) self.assertEqual(response.status_code, 302) self.user_login('test') response = self.client.get(reverse('nutrition:bmi:view')) self.assertEqual(response.status_code, 200) def test_calculator_metric(self): """ Tests the calculator itself """ self.user_login('test') response = self.client.post( reverse('nutrition:bmi:calculate'), {'height': 180, 'weight': 80} ) self.assertEqual(response.status_code, 200) bmi = json.loads(response.content.decode('utf8')) self.assertEqual(Decimal(bmi['bmi']), Decimal(24.69).quantize(TWOPLACES)) self.assertEqual(Decimal(bmi['weight']), Decimal(80)) self.assertEqual(Decimal(bmi['height']), Decimal(180)) def test_calculator_metric_low_height(self): """ Tests the calculator when the height is too low. Should trigger an error message. """ self.user_login('test') profile = UserProfile.objects.get(user__username='test') profile.save() response = self.client.post( reverse('nutrition:bmi:calculate'), {'height': 115, 'weight': 76} ) self.assertEqual(response.status_code, 406) response = json.loads(response.content.decode('utf8')) self.assertTrue('error' in response) def test_calculator_metric_high_height(self): """ Tests the calculator when the height is too low. Should trigger an error message. """ self.user_login('test') profile = UserProfile.objects.get(user__username='test') profile.save() response = self.client.post( reverse('nutrition:bmi:calculate'), {'height': 250, 'weight': 82} ) self.assertEqual(response.status_code, 406) response = json.loads(response.content.decode('utf8')) self.assertTrue('error' in response) def test_calculator_imperial(self): """ Tests the calculator using imperial units """ self.user_login('test') profile = UserProfile.objects.get(user__username='test') profile.weight_unit = 'lb' profile.save() response = self.client.post( reverse('nutrition:bmi:calculate'), {'height': 73, 'weight': 176} ) self.assertEqual(response.status_code, 200) bmi = json.loads(response.content.decode('utf8')) self.assertEqual(Decimal(bmi['bmi']), Decimal(23.33).quantize(TWOPLACES)) self.assertEqual(Decimal(bmi['weight']), Decimal(176).quantize(TWOPLACES)) self.assertEqual(Decimal(bmi['height']), Decimal(73)) def test_calculator_imperial_low_height(self): """ Tests the calculator when the height is too low. Should trigger an error message. """ self.user_login('test') profile = UserProfile.objects.get(user__username='test') profile.weight_unit = 'lb' profile.save() response = self.client.post( reverse('nutrition:bmi:calculate'), {'height': 48, 'weight': 145} ) self.assertEqual(response.status_code, 406) response = json.loads(response.content.decode('utf8')) self.assertTrue('error' in response) def test_calculator_imperial_high_height(self): """ Tests the calculator when the height is too low. Should trigger an error message. """ self.user_login('test') profile = UserProfile.objects.get(user__username='test') profile.weight_unit = 'lb' profile.save() response = self.client.post( reverse('nutrition:bmi:calculate'), {'height': 98, 'weight': 145} ) self.assertEqual(response.status_code, 406) response = json.loads(response.content.decode('utf8')) self.assertTrue('error' in response) def test_automatic_weight_entry(self): """ Tests that weight entries are automatically created or updated """ self.user_login('test') user = User.objects.get(username=self.current_user) # Existing weight entry is old, a new one is created entry1 = WeightEntry.objects.filter(user=user).latest() response = self.client.post( reverse('nutrition:bmi:calculate'), {'height': 180, 'weight': 80} ) self.assertEqual(response.status_code, 200) entry2 = WeightEntry.objects.filter(user=user).latest() self.assertEqual(entry1.weight, 83) self.assertEqual(entry2.weight, 80) # Existing weight entry is from today, is updated entry2.delete() entry1.date = datetime.date.today() entry1.save() response = self.client.post( reverse('nutrition:bmi:calculate'), {'height': 180, 'weight': 80} ) self.assertEqual(response.status_code, 200) entry2 = WeightEntry.objects.filter(user=user).latest() self.assertEqual(entry1.pk, entry2.pk) self.assertEqual(entry2.weight, 80) # No existing entries WeightEntry.objects.filter(user=user).delete() response = self.client.post( reverse('nutrition:bmi:calculate'), {'height': 180, 'weight': 80} ) self.assertEqual(response.status_code, 200) entry = WeightEntry.objects.filter(user=user).latest() self.assertEqual(entry.weight, 80) self.assertEqual(entry.date, datetime.date.today())
6,686
Python
.py
156
35.083333
89
0.657955
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,597
test_off.py
wger-project_wger/wger/nutrition/tests/test_off.py
# 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/>. # Django from django.test import SimpleTestCase # wger from wger.nutrition.dataclasses import IngredientData from wger.nutrition.off import extract_info_from_off from wger.utils.constants import ODBL_LICENSE_ID class ExtractInfoFromOffTestCase(SimpleTestCase): """ Test the extract_info_from_off function """ off_data1 = {} def setUp(self): self.off_data1 = { 'code': '1234', 'lang': 'de', 'product_name': 'Foo with chocolate', 'generic_name': 'Foo with chocolate, 250g package', 'brands': 'The bar company', 'editors_tags': ['open food facts', 'MrX'], 'nutriments': { 'energy-kcal_100g': 120, 'proteins_100g': 10, 'carbohydrates_100g': 20, 'sugars_100g': 30, 'fat_100g': 40, 'saturated-fat_100g': 11, 'sodium_100g': 5, 'fiber_100g': None, 'other_stuff': 'is ignored', }, } def test_regular_response(self): """ Test that the function can read the regular case """ result = extract_info_from_off(self.off_data1, 1) data = IngredientData( name='Foo with chocolate', remote_id='1234', language_id=1, energy=120, protein=10, carbohydrates=20, carbohydrates_sugar=30, fat=40, fat_saturated=11, fiber=None, sodium=5, code='1234', source_name='Open Food Facts', source_url='https://world.openfoodfacts.org/api/v2/product/1234.json', common_name='Foo with chocolate, 250g package', brand='The bar company', license_id=ODBL_LICENSE_ID, license_author='open food facts, MrX', license_title='Foo with chocolate', license_object_url='https://world.openfoodfacts.org/product/1234/', ) self.assertEqual(result, data) def test_convert_kj(self): """ If the energy is not available in kcal per 100 g, but is in kj per 100 g, we convert it to kcal per 100 g """ del self.off_data1['nutriments']['energy-kcal_100g'] self.off_data1['nutriments']['energy-kj_100g'] = 120 result = extract_info_from_off(self.off_data1, 1) # 120 / KJ_PER_KCAL self.assertAlmostEqual(result.energy, 28.6806, 3) def test_no_energy(self): """ No energy available """ del self.off_data1['nutriments']['energy-kcal_100g'] self.assertRaises(KeyError, extract_info_from_off, self.off_data1, 1) def test_no_sugar_or_saturated_fat(self): """ No sugar or saturated fat available """ del self.off_data1['nutriments']['sugars_100g'] del self.off_data1['nutriments']['saturated-fat_100g'] result = extract_info_from_off(self.off_data1, 1) self.assertEqual(result.carbohydrates_sugar, None) self.assertEqual(result.fat_saturated, None)
3,875
Python
.py
98
30.591837
82
0.611643
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,598
test_generator.py
wger-project_wger/wger/nutrition/tests/test_generator.py
# 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 # Django from django.core.management import call_command # wger from wger.core.tests.base_testcase import WgerTestCase from wger.nutrition.models import NutritionPlan class NutritionalPlansGeneratorTestCase(WgerTestCase): def test_generator(self): # Arrange NutritionPlan.objects.all().delete() # Act call_command('dummy-generator-nutrition', '--plans', 10) # Assert self.assertEqual(NutritionPlan.objects.filter(user_id=1).count(), 10)
1,134
Python
.py
26
40.384615
78
0.76951
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)
22,599
test_plan.py
wger-project_wger/wger/nutrition/tests/test_plan.py
# 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.tests import api_base_test from wger.nutrition.models import NutritionPlan class PlanApiTestCase(api_base_test.ApiBaseResourceTestCase): """ Tests the nutritional plan overview resource TODO: setting overview_cached to true since get_nutritional_values is cached, but we don't really use it. This should be removed """ pk = 4 resource = NutritionPlan private_resource = True overview_cached = False special_endpoints = ('nutritional_values',) data = {'description': 'The description'}
1,276
Python
.py
29
41.103448
78
0.76409
wger-project/wger
3,065
570
221
AGPL-3.0
9/5/2024, 5:13:18 PM (Europe/Amsterdam)