Self hosted FLOSS fitness/workout, nutrition and weight tracker
Backport schedule improvements to master
Roland Geider616e3a442d73
diff --git a/wger/manager/helpers.py b/wger/manager/helpers.pyindex f8f9447a1..c44c1dc61 100644--- a/wger/manager/helpers.py+++ b/wger/manager/helpers.py@@ -15,6 +15,109 @@# You should have received a copy of the GNU Affero General Public License# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.+from reportlab.lib import colors+from reportlab.lib.units import cm+from reportlab.platypus import Paragraph+from reportlab.platypus import Table+from reportlab.platypus import KeepTogether++from django.utils.translation import ugettext as _++from wger.utils.pdf import styleSheet+++def render_workout_day(day, nr_of_weeks):+ '''+ Render a table with reportlab with the contents of the training day+ '''++ data = []++ # Init some counters and markers, this will be used after the iteration to+ # set different borders and colours+ day_markers = []+ group_exercise_marker = {}++ # Background colour for days+ # Reportlab doesn't use the HTML hexadecimal format, but has a range of+ # 0 till 1, so we have to convert here.+ header_colour = colors.Color(int('73', 16) / 255.0,+ int('8a', 16) / 255.0,+ int('5f', 16) / 255.0)++ set_count = 1+ day_markers.append(len(data))++ p = Paragraph('<para align="center">%(days)s: %(description)s</para>' %+ {'days': day['days_of_week']['text'],+ 'description': day['obj'].description},+ styleSheet["Bold"])++ data.append([p])++ # Note: the _('Date') will be on the 3rd cell, but since we make a span+ # over 3 cells, the value has to be on the 1st one+ data.append([_('Date') + ' ', '', ''] + [''] * nr_of_weeks)+ data.append([_('Nr.'), _('Exercise'), _('Reps')] + [_('Weight')] * nr_of_weeks)++ # Sets+ exercise_start = len(data)+ for set in day['set_list']:+ group_exercise_marker[set['obj'].id] = {'start': len(data), 'end': len(data)}++ # Exercises+ for exercise in set['exercise_list']:+ group_exercise_marker[set['obj'].id]['end'] = len(data)++ data.append([set_count,+ Paragraph(exercise['obj'].name, styleSheet["Small"]),+ exercise['setting_text']]+ + [''] * nr_of_weeks)+ set_count += 1++ table_style = [('FONT', (0, 0), (-1, -1), 'OpenSans'),+ ('FONTSIZE', (0, 0), (-1, -1), 8),+ ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),+ ('LEFTPADDING', (0, 0), (-1, -1), 2),+ ('RIGHTPADDING', (0, 0), (-1, -1), 0),+ ('TOPPADDING', (0, 0), (-1, -1), 3),+ ('BOTTOMPADDING', (0, 0), (-1, -1), 2),+ ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),++ # Header+ ('BACKGROUND', (0, 0), (-1, 0), header_colour),+ ('BOX', (0, 0), (-1, -1), 1.25, colors.black),+ ('BOX', (0, 1), (-1, -1), 1.25, colors.black),+ ('SPAN', (0, 0), (-1, 0)),++ # Cell with 'date'+ ('SPAN', (0, 1), (2, 1)),+ ('ALIGN', (0, 1), (2, 1), 'RIGHT')]++ # Combine the cells for exercises on the same superset+ for marker in group_exercise_marker:+ start_marker = group_exercise_marker[marker]['start']+ end_marker = group_exercise_marker[marker]['end']++ table_style.append(('VALIGN', (0, start_marker), (0, end_marker), 'MIDDLE'))+ table_style.append(('SPAN', (0, start_marker), (0, end_marker)))++ # Set an alternating background colour for rows with exercises.+ # The rows with exercises range from exercise_start till the end of the data+ # list+ for i in range(exercise_start, len(data) + 1):+ if not i % 2:+ table_style.append(('BACKGROUND', (1, i - 1), (-1, i - 1), colors.lavender))++ # Put everything together and manually set some of the widths+ t = Table(data, style=table_style)+ if len(t._argW) > 1:+ t._argW[0] = 0.6 * cm # Numbering+ t._argW[1] = 4 * cm # Exercise+ t._argW[2] = 2 * cm # Repetitions++ return KeepTogether(t)+def reps_smart_text(settings, set_obj):'''diff --git a/wger/manager/models.py b/wger/manager/models.pyindex ca941f739..2e24429cf 100644--- a/wger/manager/models.py+++ b/wger/manager/models.py@@ -326,6 +326,26 @@ class ScheduleStep(models.Model):'''return self.workout.comment+ def get_dates(self):+ '''+ Calculate the start and end date for this step+ '''++ steps = self.schedule.schedulestep_set.all()+ start_date = end_date = self.schedule.start_date+ previous = 0++ if not steps:+ return False++ for step in steps:+ start_date += datetime.timedelta(weeks=previous)+ end_date += datetime.timedelta(weeks=step.duration)+ previous = step.duration++ if step == self:+ return start_date, end_date+class Day(models.Model):'''diff --git a/wger/manager/pdf.py b/wger/manager/pdf.pyindex 862f81df0..c750970d7 100644--- a/wger/manager/pdf.py+++ b/wger/manager/pdf.py@@ -25,8 +25,10 @@ from django.contrib.auth.decorators import login_requiredfrom django.utils.translation import ugettext as _from wger.manager.models import Workout+from wger.manager.helpers import render_workout_dayfrom wger.utils.helpers import check_tokenfrom wger.utils.pdf import styleSheet+from wger.utils.pdf import render_footerfrom reportlab.lib.pagesizes import A4, cmfrom reportlab.platypus import Paragraph@@ -78,195 +80,22 @@ def workout_log(request, id, uidb64=None, token=None):# container for the 'Flowable' objectselements = []- # table data, here we will put the workout info- data = []-- # Init several counters and markers, this will be used after the iteration to- # set different borders and colours- day_markers = []- exercise_markers = {}- group_exercise_marker = {}- group_day_marker = {}-- # Set the number of weeks for this workout- # (sets number of columns for the weight/date log)- nr_of_weeks = 7-- # Set the first column of the weight log, depends on design- first_weight_column = 3-- # Background colour for days- # Reportlab doesn't use the HTML hexadecimal format, but has a range of- # 0 till 1, so we have to convert here.- header_colour = colors.Color(int('73', 16) / 255.0,- int('8a', 16) / 255.0,- int('5f', 16) / 255.0)-- #- # Iterate through the Workout- #+ # Set the title+ p = Paragraph('<para align="center"><strong>%(description)s</strong></para>' %+ {'description': workout},+ styleSheet["HeaderBold"])+ elements.append(p)+ elements.append(Spacer(10*cm, 0.5*cm))- # Days+ # Iterate through the Workout and render the training daysfor day in workout.canonical_representation['day_list']:- set_count = 1- day_markers.append(len(data))- group_day_marker[day['obj'].id] = {'start': len(data), 'end': len(data)}-- if not exercise_markers.get(day['obj'].id):- exercise_markers[day['obj'].id] = []-- P = Paragraph('<para align="center">%(days)s: %(description)s</para>' %- {'days': day['days_of_week']['text'],- 'description': day['obj'].description},- styleSheet["Bold"])-- data.append([P])-- # Note: the _('Date') will be on the 3rd cell, but since we make a span- # over 3 cells, the value has to be on the 1st one- data.append([_('Date') + ' ', '', ''] + [''] * nr_of_weeks)- data.append([_('Nr.'), _('Exercise'), _('Reps')] + [_('Weight')] * nr_of_weeks)-- # Sets- for set in day['set_list']:- group_exercise_marker[set['obj'].id] = {'start': len(data), 'end': len(data)}-- # Exercises- for exercise in set['exercise_list']:- group_exercise_marker[set['obj'].id]['end'] = len(data)-- # Note: '+1' here because there's an emtpy cell between days- exercise_markers[day['obj'].id].append(len(data) + 1)-- data.append([set_count,- Paragraph(exercise['obj'].name, styleSheet["Small"]),- exercise['setting_text']]- + [''] * nr_of_weeks)- set_count += 1-- data.append([''])- group_day_marker[day['obj'].id]['end'] = len(data)-- # Set the widths and heights of rows and columns- # Note: 'None' is treated as 'automatic'. Either there is only one value for the whole list- # or exactly one for every row/column- colwidths = None- rowheights = [None] * len(data)-- # Set general table styles- table_style = [('FONT', (0, 0), (-1, -1), 'OpenSans'),- ('FONTSIZE', (0, 0), (-1, -1), 8),- ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),-- # Note: a padding of 3 seems to be the default- ('LEFTPADDING', (0, 0), (-1, -1), 2),- ('RIGHTPADDING', (0, 0), (-1, -1), 0),- ('TOPPADDING', (0, 0), (-1, -1), 3),- ('BOTTOMPADDING', (0, 0), (-1, -1), 2), ]-- # Set specific styles, e.g. background for title cells- for marker in day_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))- table_style.append(('BOX', (0, marker), (-1, marker + 2), 1.25, colors.black))-- # Make the headings span the whole width- table_style.append(('SPAN', (0, marker), (-1, marker)))-- # Make the space between days span the whole width- table_style.append(('SPAN', (0, marker - 1), (-1, marker - 1)))-- # Manually set- rowheights[marker - 1] = 5-- # Make the date span 3 cells and align it to the right- table_style.append(('ALIGN', (0, marker + 1), (2, marker + 1), 'RIGHT'))- table_style.append(('SPAN', (0, marker + 1), (2, marker + 1)))-- # Combine the cells for exercises on the same set- for marker in group_exercise_marker:- start_marker = group_exercise_marker[marker]['start']- end_marker = group_exercise_marker[marker]['end']-- table_style.append(('VALIGN', (0, start_marker), (0, end_marker), 'MIDDLE'))- table_style.append(('SPAN', (0, start_marker), (0, end_marker)))-- # Set an alternating background colour for rows- for i in exercise_markers:- counter = 1- for j in exercise_markers[i]:- if not j % 2:- table_style.append(('BACKGROUND', (1, j - 1), (-1, j - 1), colors.lavender))- counter += 1-- # Make the 'impression' span 3 cells and align it to the right- for marker in group_day_marker:- start_marker = group_day_marker[marker]['start']- end_marker = group_day_marker[marker]['end']-- # There is an empty cell between the day blocks, set a border around them- table_style.append(('INNERGRID',- (0, start_marker),- (- 1, end_marker - 2),- 0.25,- colors.black))- table_style.append(('BOX',- (0, start_marker),- (-1, end_marker - 2),- 1.25,- colors.black))-- # Set the table data- if data:- t = Table(data, colwidths, rowheights, style=table_style)-- # Manually set the width of the columns- for i in range(first_weight_column, nr_of_weeks + first_weight_column):- t._argW[i] = 1.8 * cm # Columns for entering the log-- t._argW[0] = 0.6 * cm # Exercise numbering- t._argW[1] = 3.5 * cm # Name of exercise- t._argW[2] = 2 * cm # Repetitions-- # There is nothing to output- else:- t = Paragraph(_('<i>This is an empty workout, what did you expect on the PDF?</i>'),- styleSheet["Normal"])-- #- # Add all elements to the document- #-- # Set the title (if available)- if workout.comment:- P = Paragraph('<para align="center"><strong>%(description)s</strong></para>' %- {'description': workout.comment},- styleSheet["Bold"])- elements.append(P)-- # Filler+ elements.append(render_workout_day(day, nr_of_weeks=7))elements.append(Spacer(10*cm, 0.5*cm))- # Append the table- elements.append(t)-# Footer, date and infoelements.append(Spacer(10*cm, 0.5*cm))- created = datetime.date.today().strftime("%d.%m.%Y")url = reverse('manager:workout:view', kwargs={'id': workout.id})- P = Paragraph('''<para align="left">- %(date)s -- <a href="%(url)s">%(url)s</a> -- %(created)s- %(version)s- </para>''' %- {'date': _("Created on the <b>%s</b>") % created,- 'created': "wger Workout Manager",- 'version': get_version(),- 'url': request.build_absolute_uri(url), },- styleSheet["Normal"])- elements.append(P)+ elements.append(render_footer(request.build_absolute_uri(url)))# write the document and send the response to the browserdoc.build(elements)diff --git a/wger/manager/templates/mobile/schedule/view.html b/wger/manager/templates/mobile/schedule/view.htmlindex fed34dd2b..31e8ffe71 100644--- a/wger/manager/templates/mobile/schedule/view.html+++ b/wger/manager/templates/mobile/schedule/view.html@@ -42,6 +42,45 @@</div>{% endfor %}++<table class="table">+ <tr>+ <th style="width: 30%;">{% trans "Start date" %}</th>+ <td>{{schedule.start_date}}</td>+ </tr>+ <tr>+ <th>{% trans "Schedule active" %}</th>+ <td>+ {% if schedule.is_active %}+ <span class="glyphicon glyphicon-ok"></span>+ {% else %}+ <span class="glyphicon glyphicon-remove"></span>+ {% endif %}+ </td>+ </tr>+ <tr>+ <th>{% trans "Is loop" %}</th>+ <td>+ {% if schedule.is_loop %}+ <span class="glyphicon glyphicon-ok"></span>+ <em>{% trans "This schedule is a loop and will go through the workouts above till you deactivate it" %}</em>+ {% else %}+ <span class="glyphicon glyphicon-remove"></span>+ {% endif %}+ </td>+ </tr>+ {% if not schedule.is_active %}+ <tr>+ <td colspan="2">+ <a href="{% url 'schedule-start' schedule.pk %}" class="btn btn-success btn-sm">+ <span class="glyphicon glyphicon-play"></span>+ {% trans "Start schedule" %}+ </a>+ </td>+ </tr>+ {% endif %}+</table>+<div class="list-group">{% for step in schedule.schedulestep_set.select_related %}<a href="#step-{{step.id}}" data-toggle="modal" class="list-group-item wger-list-group-item">@@ -67,13 +106,6 @@{% trans "Add workout" %}</a></div>-{% if schedule.is_loop %}- <div class="alert alert-info" style="margin-bottom:0px;">- {% trans "This schedule is a loop and will go through the workouts above till you deactivate it" %}- </div>-{% endif %}--{% endblock %}@@ -85,6 +117,17 @@ edit the order per drag-and-drop. It's also possible to add one workout morethan once.{% endblocktrans %}</p><h3>{% trans "Options" %}</h3>++<p>+<a href="{% url 'manager:schedule:pdf' schedule.id uid token %}" class="btn btn-default btn-block">+<img src="{% static 'images/icons/save.svg' %}"+ width="32"+ height="32"+ alt="{% trans 'Download as PDF' %}"+ title="{% trans 'Download as PDF' %}">+{% trans "Download as PDF" %}</a>+</p>+<p><a href="#export-ical-link"class="btn btn-default btn-block"diff --git a/wger/manager/templates/mobile/tags/render_day.html b/wger/manager/templates/mobile/tags/render_day.htmlindex fd35758d2..c8bcd0ad9 100644--- a/wger/manager/templates/mobile/tags/render_day.html+++ b/wger/manager/templates/mobile/tags/render_day.html@@ -1,7 +1,7 @@{% load i18n %}{% load staticfiles wger_extras thumbnail %}-+{% if not compact %}<div class="modal fade" id="editoptions-day-{{ day.obj.id }}"><div class="modal-dialog"><div class="modal-content">@@ -52,10 +52,10 @@</div></div></div>+{% endif %}--+{% if not compact %}{% for set in day.set_list %}<div class="modal fade" id="editoptions-set-{{ set.obj.id }}"><div class="modal-dialog">@@ -100,6 +100,7 @@</div></div>{% endfor %}+{% endif %}<div class="list-group"@@ -110,7 +111,9 @@{# Day #}{# #}<a href="#editoptions-day-{{ day.obj.id }}" class="list-group-item active" data-toggle="modal">+ {% if not compact %}<span class="glyphicon glyphicon-cog pull-right"></span>+ {% endif %}<h4>{{ day.obj.description }}</h4>{{ day.days_of_week.text }}@@ -132,62 +135,76 @@class="list-group-item wger-list-group-item">{% endif %}+ {% if not compact %}<span class="glyphicon glyphicon-cog pull-right"></span>+ {% endif %}{% for exercise in set.exercise_list %}<div id="exercise-{{ exercise.obj.id }}" class="ajax-manager:set:edit-target"><div class="media">- <span class="pull-left" style="width:64px;height:64px;">- {% if exercise.obj.main_image %}- <img class="media-object"- src="{{ exercise.obj.main_image.image|thumbnail_url:'small' }}"- alt="{{exercise.obj}}"- style="max-width:100%; max-height:100%;">- {% else %}- <img class="media-object"- src="{% static 'images/icons/image-placeholder.svg' %}"- alt=""- style="opacity: 0.3; max-width:100%; max-height:100%;">- {% endif %}- </span>- <div class="media-body">- <h4 class="media-heading">- {{ exercise.obj.name }}- </h4>- <p><strong>{{exercise.setting_text}}</strong></p>-- {% if not exercise.setting_list %}- <p>- {% trans "This exercise has no repetitions." %}<br>- {% trans "Edit them now."%}- </p>- {% endif %}-- <p class="text-muted">- {% for comment in exercise.comment_list %}- {{comment}}<br>- {% endfor %}- </p>+ <div style="width:60px;height:60px;" class="media-left">+ <a href="{{exercise.obj.get_absolute_url}}" >+ {% if exercise.obj.main_image %}+ <img class="media-object"+ src="{{ exercise.obj.main_image.image|thumbnail_url:'small' }}"+ alt="{{exercise.obj}}"+ style="max-width:100%; max-height:100%;">+ {% else %}+ <img class="media-object"+ src="{% static 'images/icons/image-placeholder.svg' %}"+ alt="{% trans 'Placeholder image for exercise' %}"+ style="opacity: 0.4;max-width:100%; max-height:100%;">+ {% endif %}+ </a>+ </div>+ <div class="media-body" style="position: relative; top: 10px; left: 100px;">+ <h4 class="media-heading">+ {{ exercise.obj.name }}+ </h4>+ <p>{{exercise.setting_text}}</p>++ {% if not exercise.setting_list %}+ <p>+ {% trans "This exercise has no repetitions." %}<br>+ <a href="{% url 'manager:set:edit' set.obj.id %}" class="wger-modal-dialog">+ {% trans "Edit them now."%}+ </a>+ </p>+ {% endif %}++ {% if not compact %}+ {% if exercise.comment_list %}+ <p class="text-muted">+ {% for comment in exercise.comment_list %}+ {{comment}}<br>+ {% endfor %}+ </p>+ {% endif %}+ {% endif %}+ </div></div>- </div></div>{% endfor %} <!--for exercise in set--></a>{% empty %}+ {% if not compact %}<a href="{% url 'manager:set:add' day.obj.id %}"class="list-group-item list-group-item-success wger-modal-dialog">{% trans "No exercises selected for this day." %}<br>{% trans "Add one now." %}</a>+ {% endif %}{% endfor %} <!--for set in day-->{% if day.set_list %}+ {% if not compact %}<a href="{% url 'manager:set:add' day.obj.id %}" class="list-group-item list-group-item-success wger-modal-dialog"><span class="glyphicon glyphicon-plus"></span>{% trans "Add exercises to this workout day" %}</a>{% endif %}+ {% endif %}</div>diff --git a/wger/manager/templates/schedule/view.html b/wger/manager/templates/schedule/view.htmlindex 90f85ea3d..030d9cdb0 100644--- a/wger/manager/templates/schedule/view.html+++ b/wger/manager/templates/schedule/view.html@@ -1,6 +1,6 @@{% extends "base.html" %}{% load i18n %}-{% load staticfiles %}+{% load staticfiles wger_extras %}{% block title %}{{schedule.name}}{% endblock %}@@ -52,6 +52,35 @@ $(function() {{% endblock %}{% block content %}+<table class="table">+ <tr>+ <th style="width: 30%;">{% trans "Start date" %}</th>+ <td>{{schedule.start_date}}</td>+ </tr>+ <tr>+ <th>{% trans "Schedule active" %}</th>+ <td>+ {% if schedule.is_active %}+ <span class="glyphicon glyphicon-ok"></span>+ {% else %}+ <span class="glyphicon glyphicon-remove"></span>+ {% endif %}+ </td>+ </tr>+ <tr>+ <th>{% trans "Is loop" %}</th>+ <td>+ {% if schedule.is_loop %}+ <span class="glyphicon glyphicon-ok"></span>+ <em>{% trans "This schedule is a loop and will go through the workouts above till you deactivate it" %}</em>+ {% else %}+ <span class="glyphicon glyphicon-remove"></span>+ {% endif %}+ </td>+ </tr>+</table>++<div id="schedule-table-container"><table id="schedule-table" class="table"><thead>@@ -79,19 +108,17 @@ $(function() {<a href="{% url 'manager:step:edit' step.id %}"title="{% trans 'Edit' %}"class="wger-modal-dialog">- <img src="{% static 'images/icons/edit.svg' %}"+ <img src="{% static 'images/icons/edit.svg' %}"width="22"height="22"- alt="{% trans 'Edit' %}">- </a>- <a href="{% url 'manager:step:delete' step.id %}"- title="{% trans 'Delete' %}"- class="wger-modal-dialog">+ alt="{% trans 'Edit' %}"></a>+ <a href="{% url 'manager:step:delete' step.id %}"+ title="{% trans 'Delete' %}"+ class="wger-modal-dialog"><img src="{% static 'images/icons/trash.svg' %}"width="22"height="22"- alt="{% trans 'Delete' %}">- </a>+ alt="{% trans 'Delete' %}"></a></span></td><td>@@ -113,29 +140,67 @@ $(function() {</td></tr>{% endfor %}- {% if schedule.is_loop %}<tr><td colspan="4">- <div class="alert alert-info" style="margin-bottom:0px;">- {% trans "This schedule is a loop and will go through the workouts above till you deactivate it" %}- </div>+ {% if not schedule.is_active %}+ <a href="{% url 'manager:schedule:start' schedule.pk %}" class="btn btn-success btn-sm">+ <span class="glyphicon glyphicon-play"></span>+ {% trans "Start schedule" %}+ </a>+ {% endif %}++ <a href="{% url 'manager:step:add' schedule.id %}" class="wger-modal-dialog btn btn-default btn-sm">+ <span class="glyphicon glyphicon-plus"></span>+ {% trans "Add workout" %}+ </a>+ </td>+ <td colspan="2"></td></tr>- {% endif %}</tbody></table></div>-<p>-<a href="{% url 'manager:step:add' schedule.id %}"- class="wger-modal-dialog">-<img src="{% static 'images/icons/new.svg' %}"- width="32"- height="32"- alt="{% trans 'Add workout' %}"- title="{% trans 'Add workout' %}">-{% trans "Add workout" %}</a>-</p>++{% for step in schedule.schedulestep_set.select_related %}+{% with step_dates=step.get_dates %}+ <div class="row">+ <div class="col-md-3">+ <div class="panel panel-default">+ <div class="panel-heading">+ <h3 class="panel-title">+ {% blocktrans count weeks=step.duration %}{{ weeks }} Week+ {% plural %}{{ weeks }} Weeks+ {% endblocktrans %}+ </h3>++ {% if active_workout == step %}+ <span class="label label-info">{% trans "active" %}</span>+ {% endif %}+ </div>+ <div class="panel-body">+ <span>{{step_dates.0}} <br> {{step_dates.1}}</span>+ </div>+ <div class="panel-footer">+ <a href="{% url 'manager:workout:view' step.workout.id %}"+ class="btn btn-default btn-block btn-sm"+ style="white-space: normal;">+ <span class="glyphicon glyphicon-chevron-right pull-right"></span>+ {{ step.workout }}+ </a>+ </div>+ </div>+ </div>+ <div class="col-md-9">+ {% for day in step.workout.canonical_representation.day_list %}+ <div id="div-day-{{ day.obj.id }}">+ {% render_day day.obj flavour True %}+ </div>+ {% endfor %}+ </div>+ </div>+{% endwith %}+{% endfor %}{% endblock %}@@ -148,7 +213,6 @@ than once.{% endblocktrans %}</p><h3>{% trans "Options" %}</h3><p>-<a href="#" data-toggle="modal" data-target="#export-ical-popup"><img src="{% static 'images/icons/calendar.svg' %}"width="32"@@ -158,6 +222,16 @@ than once.{% endblocktrans %}</p>{% trans "Export calendar file" %}</a></p>+<p>+<a href="{% url 'manager:schedule:pdf' schedule.id uid token %}">+<img src="{% static 'images/icons/save.svg' %}"+ width="32"+ height="32"+ alt="{% trans 'Download as PDF' %}"+ title="{% trans 'Download as PDF' %}">+{% trans "Download as PDF" %}</a>+</p>+<p><a href="{% url 'manager:schedule:edit' schedule.id %}"class="wger-modal-dialog">@@ -180,6 +254,7 @@ than once.{% endblocktrans %}</p>{% trans "Delete schedule" %}</a></p>+<div class="modal fade" id="export-ical-popup"><div class="modal-dialog"><div class="modal-content">diff --git a/wger/manager/templates/tags/render_day.html b/wger/manager/templates/tags/render_day.htmlindex a0b6ee319..a6d07ceb4 100644--- a/wger/manager/templates/tags/render_day.html+++ b/wger/manager/templates/tags/render_day.html@@ -17,10 +17,10 @@ $(document).ready(function() {<table class="table table-bordered workout-table" id="table-day-{{ day.obj.id }}"><thead><tr id="day-{{ day.obj.id }}">- <th colspan="2" style="background: none repeat scroll 0% 0% #E0E0E0;">+ <th colspan="2" style="background: none repeat scroll 0% 0% #F5F5F5;">{{ day.days_of_week.text }} – {{ day.obj.description }}-+ {% if not compact %}<span class="editoptions" style="float: right;"><a href="{% url 'manager:day:delete' day.obj.id %}"title="{% trans 'Delete' %}">@@ -45,6 +45,7 @@ $(document).ready(function() {alt="{% trans 'Add weight log to this day' %}"></a></span>+ {% endif %}</th></tr></thead>@@ -53,6 +54,8 @@ $(document).ready(function() {<tr id="set-{{ set.obj.id }}"><td style="width: 15%;border-right-width: 0px;"><h5><strong>{{ forloop.counter }}</strong></h5>++ {% if not compact %}<span class="editoptions">{% if day.set_list|length > 1 %}<img src="{% static 'images/icons/move.svg' %}"@@ -80,13 +83,14 @@ $(document).ready(function() {alt="{% trans 'Delete' %}"></a></span>+ {% endif %}</td><td style="border-left-width: 0px;"><div class="exercise-list">{% for exercise in set.exercise_list %}<div id="exercise-{{ exercise.obj.id }}" class="ajax-set-edit-target"><div class="media">- <span class="pull-left" style="width:64px;height:64px;">+ <div style="width:60px;height:60px;" class="media-left"><a href="{{exercise.obj.get_absolute_url}}" >{% if exercise.obj.main_image %}<img class="media-object img-responsive"@@ -96,12 +100,12 @@ $(document).ready(function() {{% else %}<img class="media-object img-responsive"src="{% static 'images/icons/image-placeholder.svg' %}"- alt=""- style="opacity: 0.4;max-width:100%; max-height:100%;">+ alt="{% trans 'Placeholder image for exercise' %}"+ style="opacity: 0.4; max-width:100%; max-height:100%;">{% endif %}</a>- </span>- <div class="media-body">+ </div>+ <div class="media-body" style="position: relative; top: 10px; left: 100px;"><h4 class="media-heading">{{ exercise.obj.name }}</h4>@@ -116,6 +120,7 @@ $(document).ready(function() {</p>{% endif %}+ {% if not compact %}{% if exercise.comment_list %}<p class="text-muted">{% for comment in exercise.comment_list %}@@ -123,6 +128,7 @@ $(document).ready(function() {{% endfor %}</p>{% endif %}+ {% endif %}</div></div></div>@@ -131,6 +137,7 @@ $(document).ready(function() {</td></tr>{% empty %}+ {% if not compact %}<tr><td colspan="2"><a href="{% url 'manager:set:add' day.obj.id %}"@@ -140,12 +147,15 @@ $(document).ready(function() {</a></td></tr>+ {% endif %}{% endfor %} <!--for set in day-->+ {% if not compact %}<tr><td colspan="2"><a href="{% url 'manager:set:add' day.obj.id %}"class="wger-modal-dialog">{% trans "Add exercises to this workout day" %}</a></td></tr>+ {% endif %}</tbody></table>diff --git a/wger/manager/templatetags/wger_extras.py b/wger/manager/templatetags/wger_extras.pyindex 8aef95c4c..3f0a8d20c 100644--- a/wger/manager/templatetags/wger_extras.py+++ b/wger/manager/templatetags/wger_extras.py@@ -36,13 +36,14 @@ def get_current_settings(exercise, set_id):@register.inclusion_tag('tags/render_day.html')-def render_day(day, flavour):+def render_day(day, flavour, compact=False):'''Renders a day as it will be displayed in the workout overview'''- return {'day': day.canonical_representation,+ return {'day': day.canonical_representation,'workout': day.training,- 'flavour': flavour}+ 'flavour': flavour,+ 'compact': compact}@register.inclusion_tag('tags/pagination.html')diff --git a/wger/manager/tests/test_schedule.py b/wger/manager/tests/test_schedule.pyindex 7524bf1f3..e9c3f2eb9 100644--- a/wger/manager/tests/test_schedule.py+++ b/wger/manager/tests/test_schedule.py@@ -28,6 +28,7 @@ from wger.manager.tests.testcase import WorkoutManagerTestCasefrom wger.manager.tests.testcase import WorkoutManagerDeleteTestCasefrom wger.manager.tests.testcase import WorkoutManagerEditTestCasefrom wger.manager.tests.testcase import WorkoutManagerAddTestCase+from wger.utils.helpers import make_tokenlogger = logging.getLogger('wger.custom')@@ -171,6 +172,49 @@ class ScheduleTestCase(WorkoutManagerTestCase):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(WorkoutManagerTestCase):'''@@ -375,6 +419,77 @@ class ScheduleModelTestCase(WorkoutManagerTestCase):self.assertTrue(schedule.get_current_scheduled_workout().workout, workout)+class SchedulePdfLogExportTestCase(WorkoutManagerTestCase):+ '''+ Test exporting a schedule 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:schedule:pdf', 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'],+ 'attachment; filename=Schedule-1-log.pdf')++ # Approximate size only+ self.assertGreater(int(response['Content-Length']), 31000)+ self.assertLess(int(response['Content-Length']), 35000)++ def export_pdf(self, fail=False):+ '''+ Helper function to test exporting a workout as a pdf+ '''++ response = self.client.get(reverse('manager:schedule:pdf', kwargs={'pk': 1}))++ if fail:+ self.assertIn(response.status_code, (404, 302))+ else:+ self.assertEqual(response.status_code, 200)+ self.assertEqual(response['Content-Type'], 'application/pdf')+ self.assertEqual(response['Content-Disposition'],+ 'attachment; filename=Schedule-1-log.pdf')++ # Approximate size only+ self.assertGreater(int(response['Content-Length']), 31000)+ self.assertLess(int(response['Content-Length']), 35000)++ 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()++ 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()++ 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()++class ScheduleApiTestCase(api_base_test.ApiBaseResourceTestCase):'''Tests the schedule overview resourcediff --git a/wger/manager/tests/test_schedule_step.py b/wger/manager/tests/test_schedule_step.pyindex a279b898d..4ca073fb9 100644--- a/wger/manager/tests/test_schedule_step.py+++ b/wger/manager/tests/test_schedule_step.py@@ -11,16 +11,36 @@# GNU General Public License for more details.## You should have received a copy of the GNU Affero General Public License+import datetimefrom django.core.urlresolvers import reverse_lazyfrom wger.core.tests import api_base_testfrom wger.manager.models import ScheduleStep+from wger.manager.tests.testcase import WorkoutManagerTestCasefrom wger.manager.tests.testcase import WorkoutManagerDeleteTestCasefrom wger.manager.tests.testcase import WorkoutManagerEditTestCasefrom wger.manager.tests.testcase import WorkoutManagerAddTestCase+class ScheduleStepTestCase(WorkoutManagerTestCase):+ '''+ 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(WorkoutManagerAddTestCase):'''Tests adding a schedulediff --git a/wger/manager/urls.py b/wger/manager/urls.pyindex c0735173f..e81324a00 100644--- a/wger/manager/urls.py+++ b/wger/manager/urls.py@@ -154,6 +154,9 @@ patterns_schedule = patterns('',url(r'^(?P<pk>\d+)/view/$',schedule.view,name='view'),+ url(r'^(?P<pk>\d+)/start$',+ schedule.start,+ name='start'),url(r'^(?P<pk>\d+)/edit/$',schedule.ScheduleEditView.as_view(),name='edit'),@@ -166,6 +169,12 @@ patterns_schedule = patterns('',url(r'^(?P<pk>\d+)/ical$',ical.export_schedule,name='ical'),+ url(r'^(?P<pk>\d+)/pdf/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})$',+ schedule.export_pdf,+ name='pdf'),+ url(r'^(?P<pk>\d+)/pdf$',+ schedule.export_pdf,+ name='pdf'),)diff --git a/wger/manager/views/schedule.py b/wger/manager/views/schedule.pyindex 299b59144..8052ffe4c 100644--- a/wger/manager/views/schedule.py+++ b/wger/manager/views/schedule.py@@ -15,10 +15,15 @@# You should have received a copy of the GNU Affero General Public Licenseimport logging+import datetimefrom django.shortcuts import renderfrom django.shortcuts import get_object_or_404-from django.core.urlresolvers import reverse_lazy, reverse+from django.http import HttpResponseRedirect+from django.http import HttpResponseForbidden+from django.http import HttpResponse+from django.core.urlresolvers import reverse_lazy+from django.core.urlresolvers import reversefrom django.utils.translation import ugettext_lazyfrom django.utils.translation import ugettext as _from django.contrib.auth.decorators import login_required@@ -26,11 +31,21 @@ from django.views.generic import CreateViewfrom django.views.generic import DeleteViewfrom django.views.generic import UpdateView+from reportlab.lib.pagesizes import A4+from reportlab.lib.units import cm+from reportlab.platypus import SimpleDocTemplate+from reportlab.platypus import Paragraph+from reportlab.platypus import Spacer+from wger.manager.models import Schedule+from wger.manager.helpers import render_workout_dayfrom wger.utils.generic_views import WgerFormMixinfrom wger.utils.generic_views import WgerDeleteMixinfrom wger.utils.generic_views import WgerPermissionMixinfrom wger.utils.helpers import make_token+from wger.utils.helpers import check_token+from wger.utils.pdf import styleSheet+from wger.utils.pdf import render_footerlogger = logging.getLogger('wger.custom')@@ -73,6 +88,84 @@ def view(request, pk):return render(request, 'schedule/view.html', template_data)+@login_required+def export_pdf(request, pk, uidb64=None, token=None):+ '''+ Show the workout schedule+ '''+ user = request.user++ # 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='Schedule for {0}'.format(request.user.username))++ # container for the 'Flowable' objects+ elements = []++ # Set the title+ p = Paragraph('<para align="center">{0}</para>'.format(schedule), 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('<para>{0} {1}</para>'.format(step.duration, _('Weeks')),+ styleSheet["HeaderBold"])+ elements.append(p)+ elements.append(Spacer(10*cm, 0.5*cm))++ for day in step.workout.canonical_representation['day_list']:+ elements.append(render_workout_day(day, 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'] = 'attachment; filename=Schedule-{0}-log.pdf'.format(pk)+ 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, WgerPermissionMixin):'''Creates a new workout schedulediff --git a/wger/utils/pdf.py b/wger/utils/pdf.pyindex 04876cc7d..b2ad57d65 100644--- a/wger/utils/pdf.py+++ b/wger/utils/pdf.py@@ -13,6 +13,7 @@# You should have received a copy of the GNU Affero General Public Licensefrom os.path import join as path_join+import datetimefrom django.conf import settingsfrom django.utils import translation@@ -22,8 +23,11 @@ from reportlab.lib.styles import ParagraphStylefrom reportlab.lib.styles import StyleSheet1from reportlab.pdfbase.ttfonts import TTFontfrom reportlab.pdfbase import pdfmetrics+from reportlab.platypus import Paragraph+from wger import get_versionfrom wger.core.models import Language+# ************************# Language functions# ************************@@ -75,6 +79,25 @@ def load_ingredient_languages(request):return languages+def render_footer(url, date=None):+ '''+ Renders the footer used in the different PDFs+ :return: a Paragraph object+ '''+ if not date:+ date = datetime.date.today().strftime("%d.%m.%Y")+ p = Paragraph('''<para>+ {date} -+ <a href="{url}">{url}</a> -+ wger Workout Manager+ {version}+ </para>'''.format(date=date,+ url=url,+ version=get_version()),+ styleSheet["Normal"])+ return p++# register new truetype fonts for reportlabpdfmetrics.registerFont(TTFont('OpenSans', path_join(settings.SITE_ROOT, 'core/static/fonts/OpenSans-Light.ttf')))@@ -95,6 +118,18 @@ styleSheet.add(ParagraphStyle(fontSize=8,name='Small',))+styleSheet.add(ParagraphStyle(+ parent=styleSheet['Normal'],+ name='HeaderBold',+ fontSize=14,+ fontName='OpenSans-Bold',+ ))+styleSheet.add(ParagraphStyle(+ parent=styleSheet['Normal'],+ name='SubHeader',+ fontSize=12,+ fontName='OpenSans',+ ))styleSheet.add(ParagraphStyle(parent=styleSheet['Normal'],name='Bold',