Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Remove schedule models and logic

Roland Geider122afcf78150
diff --git a/.gitignore b/.gitignore
index 3f2ebf49d..5bb40e0a0 100644
--- a/.gitignore
+++ b/.gitignore
@@ -76,5 +76,6 @@ venv-wger
/coverage.lcov
/media/
/static/
+/db/
/extras/docker/open-food-facts/dump/*.tar.gz
/extras/docker/open-food-facts/dump/off/*
diff --git a/wger/core/views/misc.py b/wger/core/views/misc.py
index 54c73f56a..2ae8669f8 100644
--- a/wger/core/views/misc.py
+++ b/wger/core/views/misc.py
@@ -47,8 +47,6 @@ from wger.core.forms import (
FeedbackAnonymousForm,
FeedbackRegisteredForm,
)
-from wger.core.models import DaysOfWeek
-from wger.manager.models import Schedule
logger = logging.getLogger(__name__)
diff --git a/wger/manager/api/serializers.py b/wger/manager/api/serializers.py
index 79398db88..13a87c203 100644
--- a/wger/manager/api/serializers.py
+++ b/wger/manager/api/serializers.py
@@ -34,8 +34,6 @@ from wger.manager.models import (
RestConfig,
RiRConfig,
Routine,
- Schedule,
- ScheduleStep,
SetsConfig,
Slot,
SlotEntry,
@@ -502,26 +500,5 @@ class LogStatsDataSerializer(serializers.Serializer):
"""
intensity = GroupedLogDataSerializer()
- # tonnage = GroupedLogDataSerializer()
sets = GroupedLogDataSerializer()
volume = GroupedLogDataSerializer()
-
-
-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',)
diff --git a/wger/manager/api/views.py b/wger/manager/api/views.py
index 7dc0b2106..33f21ad38 100644
--- a/wger/manager/api/views.py
+++ b/wger/manager/api/views.py
@@ -47,8 +47,6 @@ from wger.manager.api.serializers import (
RiRConfigSerializer,
RoutineSerializer,
RoutineStructureSerializer,
- ScheduleSerializer,
- ScheduleStepSerializer,
SetNrConfigSerializer,
SlotEntrySerializer,
SlotSerializer,
@@ -71,8 +69,6 @@ from wger.manager.models import (
RestConfig,
RiRConfig,
Routine,
- Schedule,
- ScheduleStep,
SetsConfig,
Slot,
SlotEntry,
@@ -382,70 +378,6 @@ class WorkoutSessionViewSet(WgerOwnerObjectModelViewSet):
return [(Routine, '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 [(Routine, '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 WorkoutLogViewSet(WgerOwnerObjectModelViewSet):
"""
API endpoint for workout log objects
diff --git a/wger/manager/management/commands/email-reminders.py b/wger/manager/management/commands/email-reminders.py
index 70ae709b5..28b3e3cce 100644
--- a/wger/manager/management/commands/email-reminders.py
+++ b/wger/manager/management/commands/email-reminders.py
@@ -26,7 +26,7 @@ from django.utils.translation import gettext_lazy as _
# wger
from wger.core.models import UserProfile
-from wger.manager.models import Schedule
+from wger.manager.models import Routine
class Command(BaseCommand):
@@ -55,12 +55,12 @@ class Command(BaseCommand):
):
continue
- (current_workout, schedule) = Schedule.objects.get_current_workout(profile.user)
+ current_workout = Routine.objects.last()
# No schedules, use the default workout length in user profile
- if not schedule and current_workout:
+ if current_workout:
delta = (
- current_workout.creation_date
+ current_workout.created
+ datetime.timedelta(weeks=profile.workout_duration)
- datetime.date.today()
)
@@ -76,22 +76,6 @@ class Command(BaseCommand):
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')
diff --git a/wger/manager/managers.py b/wger/manager/managers.py
index 04f93051a..90f50be79 100644
--- a/wger/manager/managers.py
+++ b/wger/manager/managers.py
@@ -15,7 +15,6 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Django
-from django.core.exceptions import ObjectDoesNotExist
from django.db import models
# wger
@@ -26,51 +25,6 @@ from wger.manager.consts import (
)
-class ScheduleManager(models.Manager):
- """
- Custom manager for workout schedules
- """
-
- def get_current_workout(self, user):
- """
- Finds the currently active workout for the user, by checking the schedules
- and the workouts
- :rtype : list
- """
- # wger
- from wger.manager.models import (
- Schedule,
- Workout,
- )
-
- # Try first to find an active schedule that has steps
- try:
- schedule = Schedule.objects.filter(user=user).get(is_active=True)
- if schedule.schedulestep_set.count():
- # The schedule might exist and have steps, but if it's too far in
- # the past and is not a loop, we won't use it. Doing it like this
- # is kind of wrong, but lets us continue to the correct place
- if not schedule.get_current_scheduled_workout():
- raise ObjectDoesNotExist
-
- active_workout = schedule.get_current_scheduled_workout().workout
- else:
- # same as above
- raise ObjectDoesNotExist
-
- # there are no active schedules, just return the last workout
- except ObjectDoesNotExist:
- schedule = False
- try:
- active_workout = Workout.objects.filter(user=user).latest('creation_date')
-
- # no luck, there aren't even workouts for the user
- except ObjectDoesNotExist:
- active_workout = False
-
- return active_workout, schedule
-
-
class WorkoutLogQuerySet(models.QuerySet):
def kg(self):
"""Return all entries with kg as weight"""
diff --git a/wger/manager/migrations/0021_flexible_routines_cleanup.py b/wger/manager/migrations/0021_flexible_routines_cleanup.py
index 88b1aa344..f3f6bd7ad 100644
--- a/wger/manager/migrations/0021_flexible_routines_cleanup.py
+++ b/wger/manager/migrations/0021_flexible_routines_cleanup.py
@@ -31,9 +31,15 @@ class Migration(migrations.Migration):
migrations.DeleteModel(
name='Day',
),
- # migrations.DeleteModel(
- # name='Workout',
- # ),
+ migrations.DeleteModel(
+ name='Workout',
+ ),
+ migrations.DeleteModel(
+ name='Schedule',
+ ),
+ migrations.DeleteModel(
+ name='ScheduleStep',
+ ),
migrations.RenameModel(
old_name='DayNg',
new_name='Day',
diff --git a/wger/manager/models/__init__.py b/wger/manager/models/__init__.py
index d72a5ff96..ca7a980ff 100644
--- a/wger/manager/models/__init__.py
+++ b/wger/manager/models/__init__.py
@@ -32,8 +32,6 @@ from .rir_config import (
RiRConfig,
)
from .routine import Routine
-from .schedule import Schedule
-from .schedule_step import ScheduleStep
from .session import WorkoutSession
from .sets_config import (
MaxSetsConfig,
diff --git a/wger/manager/models/schedule.py b/wger/manager/models/schedule.py
deleted file mode 100644
index 896b32835..000000000
--- a/wger/manager/models/schedule.py
+++ /dev/null
@@ -1,143 +0,0 @@
-# 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
-
-# Django
-from django.contrib.auth.models import User
-from django.db import models
-from django.urls import reverse
-from django.utils.translation import gettext_lazy as _
-
-# wger
-from wger.manager.managers import ScheduleManager
-from wger.utils.fields import Html5DateField
-
-
-class Schedule(models.Model):
- """
- Model for a workout schedule.
-
- A schedule is a collection of workous that are done for a certain time.
- E.g. workouts A, B, C, A, B, C, and so on.
- """
-
- objects = ScheduleManager()
- """Custom manager"""
-
- user = models.ForeignKey(
- User,
- verbose_name=_('User'),
- editable=False,
- on_delete=models.CASCADE,
- )
- """
- The user this schedule belongs to. This could be accessed through a step
- that points to a workout, that points to a user, but this is more straight
- forward and performant
- """
-
- name = models.CharField(
- verbose_name=_('Name'),
- max_length=100,
- help_text=_('Name or short description of the schedule. ' "For example 'Program XYZ'."),
- )
- """Name or short description of the schedule."""
-
- start_date = Html5DateField(verbose_name=_('Start date'), default=datetime.date.today)
- """The start date of this schedule"""
-
- is_active = models.BooleanField(
- verbose_name=_('Schedule active'),
- default=True,
- help_text=_(
- 'Tick the box if you want to mark this schedule '
- 'as your active one (will be shown e.g. on your '
- 'dashboard). All other schedules will then be '
- 'marked as inactive'
- ),
- )
- """A flag indicating whether the schedule is active (needed for dashboard)"""
-
- is_loop = models.BooleanField(
- verbose_name=_('Is a loop'),
- default=False,
- help_text=_(
- 'Tick the box if you want to repeat the schedules '
- 'in a loop (i.e. A, B, C, A, B, C, and so on)'
- ),
- )
- """A flag indicating whether the schedule should act as a loop"""
-
- def __str__(self):
- """
- Return a more human-readable representation
- """
- return self.name
-
- def get_absolute_url(self):
- return reverse('manager:schedule:view', kwargs={'pk': self.id})
-
- def get_owner_object(self):
- """
- Returns the object that has owner information
- """
- return self
-
- def save(self, *args, **kwargs):
- """
- Only one schedule can be marked as active at a time
- """
- if self.is_active:
- Schedule.objects.filter(user=self.user).update(is_active=False)
- self.is_active = True
-
- super(Schedule, self).save(*args, **kwargs)
-
- def get_current_scheduled_workout(self):
- """
- Returns the currently active schedule step for a user
- """
- steps = self.schedulestep_set.all()
- start_date = self.start_date
- found = False
- if not steps:
- return False
- while not found:
- for step in steps:
- current_limit = start_date + datetime.timedelta(weeks=step.duration)
- if current_limit >= datetime.date.today():
- found = True
- return step
- start_date = current_limit
-
- # If it's not a loop, there's no workout that matches, return
- if not self.is_loop:
- return False
-
- def get_end_date(self):
- """
- Calculates the date when the schedule is over or None is the schedule
- is a loop.
- """
- if self.is_loop:
- return None
-
- end_date = self.start_date
- for step in self.schedulestep_set.all():
- end_date = end_date + datetime.timedelta(weeks=step.duration)
- return end_date
diff --git a/wger/manager/models/schedule_step.py b/wger/manager/models/schedule_step.py
deleted file mode 100644
index 0f540d0f0..000000000
--- a/wger/manager/models/schedule_step.py
+++ /dev/null
@@ -1,96 +0,0 @@
-# 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
-
-# Django
-from django.core.validators import (
- MaxValueValidator,
- MinValueValidator,
-)
-from django.db import models
-from django.utils.translation import gettext_lazy as _
-
-# Local
-from .schedule import Schedule
-from .workout import Workout
-
-
-class ScheduleStep(models.Model):
- """
- Model for a step in a workout schedule.
-
- A step is basically a workout a with a bit of metadata (next and previous
- steps, duration, etc.)
- """
-
- class Meta:
- """
- Set default ordering
- """
-
- ordering = [
- 'order',
- ]
-
- schedule = models.ForeignKey(Schedule, verbose_name=_('schedule'), on_delete=models.CASCADE)
- """The schedule is step belongs to"""
-
- workout = models.ForeignKey(Workout, on_delete=models.CASCADE)
- """The workout this step manages"""
-
- duration = models.IntegerField(
- verbose_name=_('Duration'),
- help_text=_('The duration in weeks'),
- default=4,
- validators=[MinValueValidator(1), MaxValueValidator(25)],
- )
- """The duration in weeks"""
-
- order = models.IntegerField(verbose_name=_('Order'), default=1)
-
- def get_owner_object(self):
- """
- Returns the object that has owner information
- """
- return self.workout
-
- def __str__(self):
- """
- Return a more human-readable representation
- """
- return self.workout.name
-
- 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
diff --git a/wger/manager/templates/schedule/overview.html b/wger/manager/templates/schedule/overview.html
deleted file mode 100644
index 321c695e4..000000000
--- a/wger/manager/templates/schedule/overview.html
+++ /dev/null
@@ -1,53 +0,0 @@
-{% extends "base.html" %}
-{% load i18n static wger_extras %}
-
-{% block title %}{% translate "Your schedules" %}{% endblock %}
-
-
-{% block header %}
-{% endblock %}
-
-{% block content %}
- <div class="list-group">
- {% for schedule in schedules %}
- <a href="{% url 'manager:schedule:view' schedule.id %}"
- class="list-group-item list-group-item-action">
- <span class="glyphicon glyphicon-chevron-right float-end"></span>
-
- {% if schedule.is_active %}
- <span class="badge rounded-pill text-bg-secondary float-end">
- {% translate "active" %}
- </span>
- {% endif %}
-
- <p class="list-group-item-heading h5">{{ schedule }}</p>
- <p class="list-group-item-text">{{ schedule.start_date }}</p>
- </a>
- {% empty %}
- {% translate "No schedules found." %}
- {% translate 'Add one now' as text %}
- {% modal_link url='manager:schedule:add' text=text css_class='dropdown-item' %}
- {% endfor %}
- </div>
-{% endblock %}
-
-
-{% block sidebar %}
- <p>{% blocktranslate %}Schedules are collections of workouts that you do in
- succession.{% endblocktranslate %}</p>
-
- <p>{% blocktranslate %}You can indicate how long you want to do each workout
- before jumping to the next. It is also possible to create a loop, so you
- always do the same workouts in succession, e.g. A > B > C > A > B > C and so
- on.{% endblocktranslate %}</p>
-
- <p>{% blocktranslate %}The currently active schedule will remain active (and be
- shown e.g. in your dashboard) till it reaches the last workout or till you
- deactivate it, if it is a loop.{% endblocktranslate %}</p>
-{% endblock %}
-
-
-{% block options %}
- {% translate 'Add schedule' as text %}
- {% modal_link url='manager:schedule:add' text=text %}
-{% endblock %}
diff --git a/wger/manager/templates/schedule/view.html b/wger/manager/templates/schedule/view.html
deleted file mode 100644
index ce80e30e2..000000000
--- a/wger/manager/templates/schedule/view.html
+++ /dev/null
@@ -1,284 +0,0 @@
-{% extends "base.html" %}
-{% load i18n static wger_extras crispy_forms_tags l10n %}
-
-{# #}
-{# Opengraph #}
-{# #}
-{% block opengraph %}
- {{ block.super }}
- <meta property="og:title" content="{% translate 'Schedule' %}">
- <meta property="og:description" content="{{ schedule }} / {{ owner_user.username }}">
-{% endblock %}
-
-{% block title %}{{ schedule.name }}{% endblock %}
-
-{% block header %}
-{% endblock %}
-
-{% block content %}
- <table class="table">
- <tr>
- <th style="width: 30%;">{% translate "Start date" %}</th>
- <td>{{ schedule.start_date }}</td>
- </tr>
- <tr>
- <th>{% translate "Schedule active" %}</th>
- <td>
- {% if schedule.is_active %}
- <span class="{% fa_class 'check' %}"></span>
- {% else %}
- <span class="{% fa_class 'times' %}"></span>
- {% endif %}
- </td>
- </tr>
- <tr>
- <th>{% translate "Is a loop" %}</th>
- <td>
- {% if schedule.is_loop %}
- <span class="{% fa_class 'check' %}"></span>
- <small>{% translate "This schedule is a loop and will go through the workouts above till you deactivate it" %}</small>
- {% else %}
- <span class="{% fa_class 'times' %}"></span>
- {% endif %}
- </td>
- </tr>
- </table>
-
-
- <div id="schedule-table-container">
- <table id="schedule-table" class="table" data-schedule="{{ schedule.id }}">
- <thead>
- <tr>
- <th>{% translate "Nr." %}</th>
- {% if is_owner %}
- <th>{% translate "Actions" %}</th>
- {% endif %}
- <th>{% translate "Workout" %}</th>
- <th>{% translate "Weeks" %}</th>
- </tr>
- </thead>
- <tbody>
- {% for step in schedule.schedulestep_set.select_related %}
- <tr data-id="{{ step.id }}">
- <td>
- {{ forloop.counter }}
- </td>
- {% if is_owner %}
- <td style="min-width: 6em;">
- <span class="editoptions">
- <a
- href="{% url 'manager:step:edit' step.id %}"
- class="{{ css_class }}"
- hx-get="{% url 'manager:step:edit' step.id %}"
- hx-target="#ajax-info-content"
- data-bs-toggle="modal"
- data-bs-target="#wger-ajax-info"
- >
- <span class="{% fa_class 'edit' %}"></span>
- </a>
-
- <a
- href="{% url 'manager:step:delete' step.id %}"
- class="{{ css_class }}"
- hx-get="{% url 'manager:step:delete' step.id %}"
- hx-target="#ajax-info-content"
- data-bs-toggle="modal"
- data-bs-target="#wger-ajax-info"
- >
- <span class="{% fa_class 'trash' %}"></span>
- </a>
- </span>
- </td>
- {% endif %}
- <td>
- <a href="{{ step.workout.get_absolute_url }}">{{ step.workout }}</a>
- {% if active_workout == step %}
- &nbsp;<span class="badge badge-info">{% translate "active" %}</span>
- {% endif %}
- </td>
- <td>
- {{ step.duration }}
- </td>
- </tr>
- {% empty %}
- {% if is_owner %}
- <tr>
- <td colspan="4">
- {% translate 'Add one now.' as text %}
- {% url 'manager:step:add' schedule.id as url %}
- {% modal_link url=url text=text css_class='dropdown-item' %}
- </td>
- </tr>
- {% endif %}
- {% endfor %}
- {% if is_owner %}
- <tr>
- <td colspan="4">
- {% if not schedule.is_active %}
- <a href="{% url 'manager:schedule:start' schedule.pk %}"
- class="btn btn-success btn-sm">
- <span class="{% fa_class 'play' %}"></span>
- {% translate "Start schedule" %}
- </a>
- {% endif %}
-
- {% translate 'Add workout' as text %}
- {% url 'manager:step:add' schedule.id as url %}
- {% modal_link url=url text=text css_class='btn btn-light btn-sm' %}
- </td>
- <td colspan="2">
- </td>
- </tr>
- {% endif %}
- </tbody>
- </table>
- </div>
-
-
- {% for step in schedule.schedulestep_set.select_related %}
- {% with step_dates=step.get_dates %}
- <div class="row">
- <div class="col-md-3">
- <div class="card">
- <div class="card-body">
- {% if active_workout == step %}
- <span class="badge rounded-pill text-bg-secondary float-end">
- {% translate "active" %}
- </span>
- {% endif %}
- <h4 class="card-title">
- {% blocktranslate count weeks=step.duration %}{{ weeks }} Week
- {% plural %}{{ weeks }} Weeks
- {% endblocktranslate %}
- </h4>
-
- <span class="card-text">
- <span>{{ step_dates.0 }} <br> {{ step_dates.1 }}</span>
- </span>
- </div>
- <div class="card-footer">
- <a href="{{ step.workout.get_absolute_url }}"
- class="btn btn-dark btn-block btn-sm"
- style="white-space: normal;">
- <span class="glyphicon glyphicon-chevron-right float-end"></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 False %}
- </div>
- {% endfor %}
- </div>
- </div>
- {% endwith %}
- {% endfor %}
-{% endblock %}
-
-
-{% block sidebar %}
- {% if is_owner %}
- <h4>{% translate "Adding workouts" %}</h4>
-
- <p>{% blocktranslate %}Add as many workouts to the schedule as you want. You can
- edit the order by dragging and dropping them. It's also possible to add one workout more
- than once.{% endblocktranslate %}</p>
- {% endif %}
-
- <div class="modal fade" id="export-ical-popup">
- <div class="modal-dialog">
- <div class="modal-content">
- <div class="modal-header">
- <h4 class="modal-title">{% translate "Export calendar file" %}</h4>
- <button type="button" class="close" data-bs-dismiss="modal" aria-hidden="true">
- &times;
- </button>
- </div>
- <div class="modal-body">
- <p>{% translate "Export this schedule as a calendar file." %}</p>
- <p>{% blocktranslate %}You can then import the file it into your calendar
- application for example google calendar, outlook or iCal. This will create
- an appointment for each training day with the appropriate
- exercises.{% endblocktranslate %}</p>
- <p>
- <a href="{% url 'manager:schedule:ical' schedule.id uid token %}"
- class="btn btn-block btn-light">
- {% translate "Export calendar file" %}
- </a>
- </p>
- </div>
- <div class="modal-footer">
- <button type="button" class="btn btn-light"
- data-bs-dismiss="modal">{% translate "Close" %}</button>
- </div>
- </div>
- </div>
- </div>
-
- <div class="modal fade" id="download-pdf-popup">
- <div class="modal-dialog">
- <div class="modal-content">
- <div class="modal-header">
- <h4 class="modal-title">{% translate "Download as PDF" %}</h4>
- <button type="button" class="close" data-bs-dismiss="modal" aria-hidden="true">
- &times;
- </button>
- </div>
- <div class="modal-body">
- <form class="wger-form">
- {% crispy download_form %}
- <div id="pdf-download-info" data-schedule-id="{{ schedule.id|unlocalize }}"
- data-uid="{{ uid }}"
- data-token="{{ token }}"></div>
- </form>
- </div>
- <div class="modal-footer">
- <button type="button" class="btn btn-light"
- data-bs-dismiss="modal">{% translate "Close" %}</button>
- </div>
- </div>
- </div>
- </div>
-{% endblock %}
-
-{# #}
-{# Options #}
-{# #}
-{% block options %}
- <div class="btn-group">
- <div class="btn-group">
- <button type="button" class="btn btn-primary btn-sm dropdown-toggle"
- data-bs-toggle="dropdown"
- aria-haspopup="true" aria-expanded="false">
- <span class="{% fa_class 'cog' %}"></span>
- {% translate "Options" %}
- </button>
- <div class="dropdown-menu">
- <a href="#" data-bs-toggle="modal" data-bs-target="#export-ical-popup"
- class="dropdown-item">
- <span class="{% fa_class 'calendar' %}"></span>
- {% translate "Export calendar file" %}
- </a>
- <a data-bs-toggle="modal" data-bs-target="#download-pdf-popup"
- class="dropdown-item">
- <span class="{% fa_class 'download' %}"></span>
- {% translate "Download as PDF" %}
- </a>
- {% if is_owner %}
- {% translate 'Edit' as text %}
- {% url 'manager:schedule:edit' schedule.id as url %}
- {% modal_link url=url text=text css_class='dropdown-item' %}
-
- <div role="separator" class="dropdown-divider"></div>
-
- {% translate 'Delete' as text %}
- {% url 'manager:schedule:delete' schedule.id as url %}
- {% modal_link url=url text=text css_class='dropdown-item' %}
- {% endif %}
- </div>
- </div>
- </div>
-{% endblock %}
diff --git a/wger/manager/tests/test_email_reminder.py b/wger/manager/tests/test_email_reminder.py
index c80f9689e..b79b8c3ac 100644
--- a/wger/manager/tests/test_email_reminder.py
+++ b/wger/manager/tests/test_email_reminder.py
@@ -23,10 +23,7 @@ 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,
-)
+from wger.manager.models import Workout
class EmailReminderTestCase(WgerTestCase):
@@ -40,7 +37,6 @@ class EmailReminderTestCase(WgerTestCase):
"""
Test with no schedules or workouts
"""
- Schedule.objects.all().delete()
Workout.objects.all().delete()
call_command('email-reminders')
@@ -53,7 +49,6 @@ class EmailReminderTestCase(WgerTestCase):
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')
@@ -70,7 +65,6 @@ class EmailReminderTestCase(WgerTestCase):
user.email = ''
user.save()
- Schedule.objects.all().delete()
Workout.objects.exclude(user=User.objects.get(pk=2)).delete()
call_command('email-reminders')
@@ -88,7 +82,6 @@ class EmailReminderTestCase(WgerTestCase):
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')
@@ -106,7 +99,6 @@ class EmailReminderTestCase(WgerTestCase):
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')
@@ -123,7 +115,6 @@ class EmailReminderTestCase(WgerTestCase):
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')
@@ -137,103 +128,7 @@ class EmailReminderTestCase(WgerTestCase):
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)
diff --git a/wger/manager/tests/test_generator.py b/wger/manager/tests/test_generator.py
index 06c5b1a3a..9f9898e86 100644
--- a/wger/manager/tests/test_generator.py
+++ b/wger/manager/tests/test_generator.py
@@ -29,7 +29,7 @@ class RoutineGeneratorTestCase(WgerTestCase):
Workout.objects.all().delete()
# Act
- call_command('dummy-generator-routines', '--plans', 10)
+ call_command('dummy-generator-routines', '--routines', 10)
# Assert
self.assertEqual(Workout.objects.filter(user_id=1).count(), 10)
@@ -39,7 +39,7 @@ class RoutineGeneratorTestCase(WgerTestCase):
Workout.objects.all().delete()
# Act
- call_command('dummy-generator-routines', '--plans', 1)
+ call_command('dummy-generator-routines', '--routines', 1)
call_command('dummy-generator-workout-diary', '--diary-entries', 10)
# Assert
diff --git a/wger/manager/tests/test_ical.py b/wger/manager/tests/test_ical.py
index 6feceb594..4f9356a8f 100644
--- a/wger/manager/tests/test_ical.py
+++ b/wger/manager/tests/test_ical.py
@@ -138,92 +138,3 @@ class WorkoutICalExportTestCase(WgerTestCase):
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()
diff --git a/wger/manager/urls.py b/wger/manager/urls.py
index 0ed44c513..a62c92c4f 100644
--- a/wger/manager/urls.py
+++ b/wger/manager/urls.py
@@ -28,8 +28,6 @@ from wger.manager.views import (
ical,
pdf,
routine,
- schedule,
- schedule_step,
workout,
)
@@ -134,115 +132,10 @@ patterns_routine = [
),
]
-# sub patterns for schedules
-patterns_schedule = [
- path(
- 'overview',
- schedule.overview,
- name='overview',
- ),
- path(
- 'add',
- schedule.ScheduleCreateView.as_view(),
- name='add',
- ),
- path(
- '<int:pk>/view',
- schedule.view,
- name='view',
- ),
- path(
- '<int:pk>/start',
- schedule.start,
- name='start',
- ),
- path(
- '<int:pk>/edit',
- schedule.ScheduleEditView.as_view(),
- name='edit',
- ),
- path(
- '<int:pk>/delete',
- schedule.ScheduleDeleteView.as_view(),
- name='delete',
- ),
- re_path(
- r'^(?P<pk>\d+)/ical/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,33})$',
- ical.export_schedule,
- name='ical',
- ),
- path(
- '<int:pk>/ical',
- ical.export_schedule,
- name='ical',
- ),
- re_path(
- r'^(?P<pk>\d+)/pdf/log/(?P<images>[01]+)/(?P<comments>[01]+)/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,33})$',
- schedule.export_pdf_log,
- name='pdf-log',
- ), # JS!
- re_path(
- r'^(?P<pk>\d+)/pdf/log/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,33})$',
- schedule.export_pdf_log,
- name='pdf-log',
- ),
- re_path(
- r'^(?P<pk>\d+)/pdf/log/(?P<images>[01]+)/(?P<comments>[01]+)$',
- schedule.export_pdf_log,
- name='pdf-log',
- ),
- path(
- '<int:pk>/pdf/log',
- schedule.export_pdf_log,
- name='pdf-log',
- ),
- re_path(
- r'^(?P<pk>\d+)/pdf/table/(?P<images>[01]+)/(?P<comments>[01]+)/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,33})$',
- schedule.export_pdf_table,
- name='pdf-table',
- ), # JS!
- re_path(
- r'^(?P<pk>\d+)/pdf/table/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,33})$',
- schedule.export_pdf_table,
- name='pdf-table',
- ),
- re_path(
- r'^(?P<pk>\d+)/pdf/table/(?P<images>[01]+)/(?P<comments>[01]+)$',
- schedule.export_pdf_table,
- name='pdf-table',
- ),
- path(
- '<int:pk>/pdf/table',
- schedule.export_pdf_table,
- name='pdf-table',
- ),
-]
-
-# sub patterns for schedule steps
-patterns_step = [
- path(
- '<int:schedule_pk>/step/add',
- schedule_step.StepCreateView.as_view(),
- name='add',
- ),
- path(
- '<int:pk>/edit',
- schedule_step.StepEditView.as_view(),
- name='edit',
- ),
- path(
- '<int:pk>/delete',
- schedule_step.StepDeleteView.as_view(),
- name='delete',
- ),
-]
-
urlpatterns = [
path('', include((patterns_workout, 'workout'), namespace='workout')),
path('', include((patterns_routine, 'routine'), namespace='routine')),
path('template/', include((patterns_templates, 'template'), namespace='template')),
path('<int:routine_pk>/day/', include((patterns_days, 'day'), namespace='day')),
path('log/', include((patterns_log, 'log'), namespace='log')),
- path('schedule/', include((patterns_schedule, 'schedule'), namespace='schedule')),
- path('schedule/step/', include((patterns_step, 'step'), namespace='step')),
]
diff --git a/wger/manager/views/ical.py b/wger/manager/views/ical.py
index 893d3af35..4802826b4 100644
--- a/wger/manager/views/ical.py
+++ b/wger/manager/views/ical.py
@@ -35,10 +35,7 @@ from icalendar.tools import UIDGenerator
# wger
from wger import get_version
-from wger.manager.models import (
- Schedule,
- Workout,
-)
+from wger.manager.models import Workout
from wger.utils.helpers import (
check_token,
next_weekday,
@@ -140,36 +137,3 @@ def export(request, pk, uidb64=None, token=None):
response.write(calendar.to_ical())
response['Content-Length'] = len(response.content)
return response
-
-
-def export_schedule(request, pk, uidb64=None, token=None):
- """
- Export the current schedule as an iCal file
- """
-
- # Load the schedule
- 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=request.user)
-
- # Create the calendar
- calendar = get_calendar()
-
- # Create the events and add them to the calendar
- start_date = datetime.date.today()
- for step in schedule.schedulestep_set.all():
- get_events_workout(calendar, step.workout, step.duration, start_date)
- start_date = start_date + datetime.timedelta(weeks=step.duration)
-
- # Send the file to the user
- response = HttpResponse(content_type='text/calendar')
- response['Content-Disposition'] = f'attachment; filename=Calendar-schedule-{schedule.pk}.ics'
- response.write(calendar.to_ical())
- response['Content-Length'] = len(response.content)
- return response
diff --git a/wger/manager/views/schedule.py b/wger/manager/views/schedule.py
deleted file mode 100644
index fe7b0e526..000000000
--- a/wger/manager/views/schedule.py
+++ /dev/null
@@ -1,326 +0,0 @@
-# -*- 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
-
- # 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, 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
-
- 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,
- 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
diff --git a/wger/manager/views/schedule_step.py b/wger/manager/views/schedule_step.py
deleted file mode 100644
index eb5be6e3f..000000000
--- a/wger/manager/views/schedule_step.py
+++ /dev/null
@@ -1,139 +0,0 @@
-# -*- 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
diff --git a/wger/urls.py b/wger/urls.py
index 8252c9f5c..f6ebf759f 100644
--- a/wger/urls.py
+++ b/wger/urls.py
@@ -133,8 +133,6 @@ router.register(
router.register(r'rir-config', manager_api_views.RiRConfigViewSet, basename='rir-config')
router.register(r'max-rir-config', manager_api_views.MaxRiRConfigViewSet, basename='max-rir-config')
router.register(r'workoutlog', manager_api_views.WorkoutLogViewSet, basename='workoutlog')
-router.register(r'schedulestep', manager_api_views.ScheduleStepViewSet, basename='schedulestep')
-router.register(r'schedule', manager_api_views.ScheduleViewSet, basename='schedule')
# Core app
router.register(r'daysofweek', core_api_views.DaysOfWeekViewSet, basename='daysofweek')