Self hosted FLOSS fitness/workout, nutrition and weight tracker
Use canonical form to render the weight logs
Roland Geider6f1402deaeb8
diff --git a/wger/exercises/views/exercises.py b/wger/exercises/views/exercises.pyindex c3bc9732b..922fea2a8 100644--- a/wger/exercises/views/exercises.py+++ b/wger/exercises/views/exercises.py@@ -57,6 +57,7 @@ from wger.utils.cache import cache_mapperfrom wger.utils.widgets import TranslatedSelectfrom wger.utils.widgets import TranslatedSelectMultiplefrom wger.config.models import LanguageConfig+from wger.weight.helpers import process_log_entrieslogger = logging.getLogger('wger.custom')@@ -135,7 +136,7 @@ def view(request, id, slug=None):if request.user.is_authenticated():entry = WorkoutLog()logs = WorkoutLog.objects.filter(user=request.user, exercise=exercise)- entry_log, chart_data = entry.process_log_entries(logs)+ entry_log, chart_data = process_log_entries(logs)template_data['logs'] = entry_logtemplate_data['json'] = chart_datadiff --git a/wger/manager/models.py b/wger/manager/models.pyindex 04aac8015..0c0201334 100644--- a/wger/manager/models.py+++ b/wger/manager/models.py@@ -17,13 +17,11 @@import datetimeimport logging-import jsonimport decimalfrom django.db import modelsfrom django.db.models.signals import post_savefrom django.utils.translation import ugettext_lazy as _-from django.utils.datastructures import SortedDictfrom django.contrib.auth.models import Userfrom django.core.validators import MaxValueValidatorfrom django.core.urlresolvers import reverse@@ -35,7 +33,6 @@ from django.core.validators import MinValueValidatorfrom wger.exercises.models import Exercisefrom wger.exercises.models import Language-from wger.utils.helpers import DecimalJsonEncoderfrom wger.utils.helpers import disable_for_loaddatafrom wger.utils.cache import cache_mapper, reset_workout_canonical_formfrom wger.weight.models import WeightEntry@@ -641,56 +638,6 @@ class WorkoutLog(models.Model):'''return self- def process_log_entries(self, logs):- '''- Processes and regroups a list of log entries so they can be rendered- and passed to the D3 library to render a chart- '''-- reps = []- entry_log = SortedDict()- chart_data = []- max_weight = {}-- # Group by date- for entry in logs:- if entry.reps not in reps:- reps.append(entry.reps)-- if not entry_log.get(entry.date):- entry_log[entry.date] = []- entry_log[entry.date].append(entry)-- # Find the maximum weight per date per repetition.- # 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- if not max_weight.get(entry.date):- max_weight[entry.date] = {entry.reps: entry.weight}-- if not max_weight[entry.date].get(entry.reps):- max_weight[entry.date][entry.reps] = entry.weight-- if entry.weight > max_weight[entry.date][entry.reps]:- max_weight[entry.date][entry.reps] = entry.weight-- # Group by repetitions- for entry in logs:- temp = {'date': '%s' % entry.date,- 'id': 'workout-log-%s' % entry.id}-- for rep in reps:- if entry.reps == rep:-- # Only add if entry is the maximum for the day- if entry.weight == max_weight[entry.date][entry.reps]:- temp[rep] = entry.weight- else:- temp[rep] = 0- chart_data.append(temp)-- return (entry_log, json.dumps(chart_data, cls=DecimalJsonEncoder))-class UserProfile(models.Model):GENDER_MALE = '1'diff --git a/wger/manager/templates/mobile/workout/log.html b/wger/manager/templates/mobile/workout/log.htmlindex 1c0d5265b..6395deb17 100644--- a/wger/manager/templates/mobile/workout/log.html+++ b/wger/manager/templates/mobile/workout/log.html@@ -28,30 +28,28 @@ $(document).on('pageinit', function(){{% endif %}-{% for day in workout.day_set.select_related|dictsort:"get_first_day_id" %}--+{% for day in workout.canonical_representation.day_list %}<ul data-role="listview"style="margin-top: 3em;"data-icon="add"><li data-theme="b">- <a href="{% url 'day-log' day.id %}">+ <a href="{% url 'day-log' day.obj.id %}"><h3>{{ day.description }}</h3></a></li></ul>- {% for set in day.set_set.select_related %}- {% for exercise in set.exercises.select_related %}+ {% for set in day.set_list %}+ {% for exercise in set.exercise_list %}- {% with day_list=workout_log|get_item:day.id %}- {% with exercise_list=day_list|get_item:exercise.id %}+ {% with day_list=workout_log|get_item:day.obj.id %}+ {% with exercise_list=day_list|get_item:exercise.obj.id %}<ul data-role="listview"style="margin-top: 3em;"><li>- <a href="{{ exercise.get_absolute_url }}">{{ exercise.name }}</a>+ <a href="{{ exercise.get_absolute_url }}">{{ exercise.obj.name }}</a></li></ul>diff --git a/wger/manager/templates/workout/log.html b/wger/manager/templates/workout/log.htmlindex 165a5e74f..ddc0f15a5 100644--- a/wger/manager/templates/workout/log.html+++ b/wger/manager/templates/workout/log.html@@ -24,12 +24,11 @@ function custom_modal_init()</p>{% endif %}--{% for day in workout.day_set.select_related|dictsort:"get_first_day_id" %}- <h3>{{ day.description }}</h3>+{% for day in workout.canonical_representation.day_list %}+ <h3>{{ day.obj.description }}</h3><p>- <a href="{% url 'day-log' day.id %}"+ <a href="{% url 'day-log' day.obj.id %}"title="{% trans 'Add weight log to this day' %}"><img src="{% static 'images/icons/statistics.svg' %}"width="32"@@ -39,14 +38,14 @@ function custom_modal_init()</a></p>- {% for set in day.set_set.select_related %}- {% for exercise in set.exercises.select_related %}+ {% for set in day.set_list %}+ {% for exercise in set.exercise_list %}- {% with day_list=workout_log|get_item:day.id %}- {% with exercise_list=day_list|get_item:exercise.id %}+ {% with day_list=workout_log|get_item:day.obj.id %}+ {% with exercise_list=day_list|get_item:exercise.obj.id %}<div class="alert alert-info" style="text-align: center;margin-top:1em;">- <a href="{{ exercise.get_absolute_url }}">{{ exercise.name }}</a>+ <a href="{{ exercise.get_absolute_url }}">{{ exercise.obj.name }}</a></div>{% if exercise_list.log_by_date %}diff --git a/wger/manager/templates/workout/view.html b/wger/manager/templates/workout/view.htmlindex 7628e75cf..1fc20caeb 100644--- a/wger/manager/templates/workout/view.html+++ b/wger/manager/templates/workout/view.html@@ -65,16 +65,9 @@ $(document).ready(function() {<p>-<a href="{% url 'day-add' workout.id %}" class="modal-dialog">- {% trans "Add training day" %}-</a>--|-<a id="exercise-comments-toggle" href="{% url 'preferences' %}">- {% trans "Show/Hide exercise comments" %}-</a>--+ <a href="{% url 'day-add' workout.id %}" class="modal-dialog">{% trans "Add training day" %}</a>+ |+ <a id="exercise-comments-toggle" href="{% url 'preferences' %}">{% trans "Show/Hide exercise comments" %}</a></p>{% endblock %}diff --git a/wger/manager/views/log.py b/wger/manager/views/log.pyindex 042470aa7..9dffbedaf 100644--- a/wger/manager/views/log.py+++ b/wger/manager/views/log.py@@ -45,6 +45,7 @@ from wger.manager.forms import WorkoutLogFormfrom wger.utils.generic_views import WgerFormMixinfrom wger.utils.generic_views import WgerPermissionMixin+from wger.weight.helpers import process_log_entrieslogger = logging.getLogger('wger.custom')@@ -236,25 +237,26 @@ class WorkoutLogDetailView(DetailView, WgerPermissionMixin):workout_log = {}entry = WorkoutLog()- for day in self.object.day_set.select_related():- workout_log[day.id] = {}-- for set in day.set_set.select_related():+ for day_list in self.object.canonical_representation['day_list']:+ day_id = day_list['obj'].id+ workout_log[day_id] = {}+ for set_list in day_list['set_list']:exercise_log = {}+ for exercise_list in set_list['exercise_list']:+ exercise_id = exercise_list['obj'].id+ exercise_log[exercise_id] = []- for exercise in set.exercises.select_related():- exercise_log[exercise.id] = []- logs = exercise.workoutlog_set.filter(user=self.request.user,- workout=self.object)- entry_log, chart_data = entry.process_log_entries(logs)+ logs = exercise_list['obj'].workoutlog_set.filter(user=self.request.user,+ workout=self.object)+ entry_log, chart_data = process_log_entries(logs)if entry_log:- exercise_log[exercise.id].append(entry_log)+ exercise_log[exercise_list['obj'].id].append(entry_log)if exercise_log:- workout_log[day.id][exercise.id] = {}- workout_log[day.id][exercise.id]['log_by_date'] = entry_log- workout_log[day.id][exercise.id]['div_uuid'] = 'div-' + str(uuid.uuid4())- workout_log[day.id][exercise.id]['chart_data'] = chart_data+ workout_log[day_id][exercise_id] = {}+ workout_log[day_id][exercise_id]['log_by_date'] = entry_log+ workout_log[day_id][exercise_id]['div_uuid'] = 'div-' + str(uuid.uuid4())+ workout_log[day_id][exercise_id]['chart_data'] = chart_datacontext['workout_log'] = workout_logcontext['reps'] = _("Reps")@@ -294,7 +296,7 @@ class WorkoutCalendar(HTMLCalendar):body = []for log in self.workout_logs[day]:- url = reverse('workout-log', kwargs={'pk': log.workout.pk})+ url = reverse('workout-log', kwargs={'pk': log.workout_id})formatted_date = date_obj.strftime('%Y-%m-%d')body.append('<a href="{0}" data-log="log-{1}">'.format(url, formatted_date))body.append(unicode(day))@@ -337,21 +339,23 @@ def calendar(request, year=None, month=None):month = datetime.date.today().monthelse:month = int(month)+context = {}+ logs_filtered = []+ temp_date_list = []logs = WorkoutLog.objects.filter(user=request.user,date__year=year,date__month=month).order_by('exercise')- logs_filtered = []- temp = []+ # Process the logs, 'overview' list for the calendarfor log in logs:- if not log.date in temp:- temp.append(log.date)+ if not log.date in temp_date_list:+ temp_date_list.append(log.date)logs_filtered.append(log)(current_workout, schedule) = Schedule.objects.get_current_workout(request.user)context['calendar'] = WorkoutCalendar(logs_filtered).formatmonth(year, month)- context['logs'] = WorkoutLog().process_log_entries(logs)[0]+ context['logs'] = process_log_entries(logs)[0]context['current_year'] = yearcontext['current_month'] = monthcontext['current_workout'] = current_workoutdiff --git a/wger/weight/helpers.py b/wger/weight/helpers.pyindex 467d23ce1..f48a2c7cb 100644--- a/wger/weight/helpers.py+++ b/wger/weight/helpers.py@@ -19,7 +19,11 @@ import StringIOimport datetimeimport decimalimport csv+import json+from django.utils.datastructures import SortedDict++from wger.utils.helpers import DecimalJsonEncoderfrom wger.weight.models import WeightEntrylogger = logging.getLogger('wger.custom')@@ -54,3 +58,62 @@ def parse_weight_csv(request, cleaned_data):#logger.debug(e)return (weight_list, error_list)+++def process_log_entries(logs):+ '''+ Processes and regroups a list of log entries so they can be rendered+ and passed to the D3 library to render a chart+ '''++ reps = []+ entry_log = SortedDict()+ chart_data = []+ max_weight = {}++ # Group by date+ for entry in logs:+ if entry.reps not in reps:+ reps.append(entry.reps)++ if not entry_log.get(entry.date):+ entry_log[entry.date] = []+ entry_log[entry.date].append(entry)++ # Find the maximum weight per date per repetition.+ # 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+ if not max_weight.get(entry.date):+ max_weight[entry.date] = {entry.reps: entry.weight}++ if not max_weight[entry.date].get(entry.reps):+ max_weight[entry.date][entry.reps] = entry.weight++ if entry.weight > max_weight[entry.date][entry.reps]:+ max_weight[entry.date][entry.reps] = entry.weight++ # Group by repetitions+ reps_list = {}+ for entry in logs:+ temp = {'date': '%s' % entry.date,+ 'id': 'workout-log-%s' % entry.id}++ # Only unique date, rep and weight combinations+ if reps_list.get('{0}-{1}-{2}'.format(entry.date, entry.reps, entry.weight)):+ continue+ else:+ reps_list['{0}-{1}-{2}'.format(entry.date, entry.reps, entry.weight)] = True++ # Only add if weight is the maximum for the day+ if entry.weight != max_weight[entry.date][entry.reps]:+ continue++ for rep in reps:+ if entry.reps == rep:+ temp[rep] = entry.weight+ else:+ temp[rep] = 0+ chart_data.append(temp)++ return entry_log, json.dumps(chart_data, cls=DecimalJsonEncoder)